]> Pileus Git - ~andy/gtk/blob - gtk/gtkfilesel.c
Support added for building using a GNU toolchain on Win32,
[~andy/gtk] / gtk / gtkfilesel.c
1 /* GTK - The GIMP Toolkit
2  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GTK+ Team and others 1997-1999.  See the AUTHORS
22  * file for a list of people on the GTK+ Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GTK+ at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 #include "config.h"
28
29 #include <glib.h>               /* To get stat->_stat redefinition
30                                  *  for mingw32
31                                  */
32
33 #include <stdio.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #ifdef HAVE_SYS_PARAM_H
37 #include <sys/param.h>
38 #endif
39 #ifdef HAVE_DIRENT_H
40 #include <dirent.h>
41 #endif
42 #include <stdlib.h>
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46 #include <string.h>
47 #include <errno.h>
48 #ifdef HAVE_PWD_H
49 #include <pwd.h>
50 #endif
51
52 #include "fnmatch.h"
53
54 #include "gdk/gdkkeysyms.h"
55 #include "gtkbutton.h"
56 #include "gtkentry.h"
57 #include "gtkfilesel.h"
58 #include "gtkhbox.h"
59 #include "gtkhbbox.h"
60 #include "gtklabel.h"
61 #include "gtklist.h"
62 #include "gtklistitem.h"
63 #include "gtkmain.h"
64 #include "gtkscrolledwindow.h"
65 #include "gtksignal.h"
66 #include "gtkvbox.h"
67 #include "gtkmenu.h"
68 #include "gtkmenuitem.h"
69 #include "gtkoptionmenu.h"
70 #include "gtkclist.h"
71 #include "gtkdialog.h"
72 #include "gtkintl.h"
73
74 #ifdef WIN32
75 #define STRICT
76 #include <windows.h>
77
78 #ifdef NATIVE_WIN32
79 #include <direct.h>
80 #include <io.h>
81 #define mkdir(p,m) _mkdir(p)
82 #ifndef S_ISDIR
83 #define S_ISDIR(mode) ((mode)&_S_IFDIR)
84 #endif
85
86 #endif /* NATIVE_WIN32 */
87
88 #endif /* WIN32 */
89
90 #define DIR_LIST_WIDTH   180
91 #define DIR_LIST_HEIGHT  180
92 #define FILE_LIST_WIDTH  180
93 #define FILE_LIST_HEIGHT 180
94
95 /* I've put this here so it doesn't get confused with the 
96  * file completion interface */
97 typedef struct _HistoryCallbackArg HistoryCallbackArg;
98
99 struct _HistoryCallbackArg
100 {
101   gchar *directory;
102   GtkWidget *menu_item;
103 };
104
105
106 typedef struct _CompletionState    CompletionState;
107 typedef struct _CompletionDir      CompletionDir;
108 typedef struct _CompletionDirSent  CompletionDirSent;
109 typedef struct _CompletionDirEntry CompletionDirEntry;
110 typedef struct _CompletionUserDir  CompletionUserDir;
111 typedef struct _PossibleCompletion PossibleCompletion;
112
113 /* Non-external file completion decls and structures */
114
115 /* A contant telling PRCS how many directories to cache.  Its actually
116  * kept in a list, so the geometry isn't important. */
117 #define CMPL_DIRECTORY_CACHE_SIZE 10
118
119 /* A constant used to determine whether a substring was an exact
120  * match by first_diff_index()
121  */
122 #define PATTERN_MATCH -1
123 /* The arguments used by all fnmatch() calls below
124  */
125 #define FNMATCH_FLAGS (FNM_PATHNAME | FNM_PERIOD)
126
127 #define CMPL_ERRNO_TOO_LONG ((1<<16)-1)
128
129 /* This structure contains all the useful information about a directory
130  * for the purposes of filename completion.  These structures are cached
131  * in the CompletionState struct.  CompletionDir's are reference counted.
132  */
133 struct _CompletionDirSent
134 {
135   ino_t inode;
136   time_t mtime;
137   dev_t device;
138
139   gint entry_count;
140   gchar *name_buffer; /* memory segment containing names of all entries */
141
142   struct _CompletionDirEntry *entries;
143 };
144
145 struct _CompletionDir
146 {
147   CompletionDirSent *sent;
148
149   gchar *fullname;
150   gint fullname_len;
151
152   struct _CompletionDir *cmpl_parent;
153   gint cmpl_index;
154   gchar *cmpl_text;
155 };
156
157 /* This structure contains pairs of directory entry names with a flag saying
158  * whether or not they are a valid directory.  NOTE: This information is used
159  * to provide the caller with information about whether to update its completions
160  * or try to open a file.  Since directories are cached by the directory mtime,
161  * a symlink which points to an invalid file (which will not be a directory),
162  * will not be reevaluated if that file is created, unless the containing
163  * directory is touched.  I consider this case to be worth ignoring (josh).
164  */
165 struct _CompletionDirEntry
166 {
167   gint is_dir;
168   gchar *entry_name;
169 };
170
171 struct _CompletionUserDir
172 {
173   gchar *login;
174   gchar *homedir;
175 };
176
177 struct _PossibleCompletion
178 {
179   /* accessible fields, all are accessed externally by functions
180    * declared above
181    */
182   gchar *text;
183   gint is_a_completion;
184   gint is_directory;
185
186   /* Private fields
187    */
188   gint text_alloc;
189 };
190
191 struct _CompletionState
192 {
193   gint last_valid_char;
194   gchar *updated_text;
195   gint updated_text_len;
196   gint updated_text_alloc;
197   gint re_complete;
198
199   gchar *user_dir_name_buffer;
200   gint user_directories_len;
201
202   gchar *last_completion_text;
203
204   gint user_completion_index; /* if >= 0, currently completing ~user */
205
206   struct _CompletionDir *completion_dir; /* directory completing from */
207   struct _CompletionDir *active_completion_dir;
208
209   struct _PossibleCompletion the_completion;
210
211   struct _CompletionDir *reference_dir; /* initial directory */
212
213   GList* directory_storage;
214   GList* directory_sent_storage;
215
216   struct _CompletionUserDir *user_directories;
217 };
218
219
220 /* File completion functions which would be external, were they used
221  * outside of this file.
222  */
223
224 static CompletionState*    cmpl_init_state        (void);
225 static void                cmpl_free_state        (CompletionState *cmpl_state);
226 static gint                cmpl_state_okay        (CompletionState* cmpl_state);
227 static gchar*              cmpl_strerror          (gint);
228
229 static PossibleCompletion* cmpl_completion_matches(gchar           *text_to_complete,
230                                                    gchar          **remaining_text,
231                                                    CompletionState *cmpl_state);
232
233 /* Returns a name for consideration, possibly a completion, this name
234  * will be invalid after the next call to cmpl_next_completion.
235  */
236 static char*               cmpl_this_completion   (PossibleCompletion*);
237
238 /* True if this completion matches the given text.  Otherwise, this
239  * output can be used to have a list of non-completions.
240  */
241 static gint                cmpl_is_a_completion   (PossibleCompletion*);
242
243 /* True if the completion is a directory
244  */
245 static gint                cmpl_is_directory      (PossibleCompletion*);
246
247 /* Obtains the next completion, or NULL
248  */
249 static PossibleCompletion* cmpl_next_completion   (CompletionState*);
250
251 /* Updating completions: the return value of cmpl_updated_text() will
252  * be text_to_complete completed as much as possible after the most
253  * recent call to cmpl_completion_matches.  For the present
254  * application, this is the suggested replacement for the user's input
255  * string.  You must CALL THIS AFTER ALL cmpl_text_completions have
256  * been received.
257  */
258 static gchar*              cmpl_updated_text       (CompletionState* cmpl_state);
259
260 /* After updating, to see if the completion was a directory, call
261  * this.  If it was, you should consider re-calling completion_matches.
262  */
263 static gint                cmpl_updated_dir        (CompletionState* cmpl_state);
264
265 /* Current location: if using file completion, return the current
266  * directory, from which file completion begins.  More specifically,
267  * the cwd concatenated with all exact completions up to the last
268  * directory delimiter('/').
269  */
270 static gchar*              cmpl_reference_position (CompletionState* cmpl_state);
271
272 /* backing up: if cmpl_completion_matches returns NULL, you may query
273  * the index of the last completable character into cmpl_updated_text.
274  */
275 static gint                cmpl_last_valid_char    (CompletionState* cmpl_state);
276
277 /* When the user selects a non-directory, call cmpl_completion_fullname
278  * to get the full name of the selected file.
279  */
280 static gchar*              cmpl_completion_fullname (gchar*, CompletionState* cmpl_state);
281
282
283 /* Directory operations. */
284 static CompletionDir* open_ref_dir         (gchar* text_to_complete,
285                                             gchar** remaining_text,
286                                             CompletionState* cmpl_state);
287 #ifndef WIN32
288 static gboolean       check_dir            (gchar *dir_name, 
289                                             struct stat *result, 
290                                             gboolean *stat_subdirs);
291 #endif
292 static CompletionDir* open_dir             (gchar* dir_name,
293                                             CompletionState* cmpl_state);
294 #ifdef HAVE_PWD_H
295 static CompletionDir* open_user_dir        (gchar* text_to_complete,
296                                             CompletionState *cmpl_state);
297 #endif
298 static CompletionDir* open_relative_dir    (gchar* dir_name, CompletionDir* dir,
299                                             CompletionState *cmpl_state);
300 static CompletionDirSent* open_new_dir     (gchar* dir_name, 
301                                             struct stat* sbuf,
302                                             gboolean stat_subdirs);
303 static gint           correct_dir_fullname (CompletionDir* cmpl_dir);
304 static gint           correct_parent       (CompletionDir* cmpl_dir,
305                                             struct stat *sbuf);
306 static gchar*         find_parent_dir_fullname    (gchar* dirname);
307 static CompletionDir* attach_dir           (CompletionDirSent* sent,
308                                             gchar* dir_name,
309                                             CompletionState *cmpl_state);
310 static void           free_dir_sent (CompletionDirSent* sent);
311 static void           free_dir      (CompletionDir  *dir);
312 static void           prune_memory_usage(CompletionState *cmpl_state);
313
314 /* Completion operations */
315 static PossibleCompletion* attempt_homedir_completion(gchar* text_to_complete,
316                                                       CompletionState *cmpl_state);
317 static PossibleCompletion* attempt_file_completion(CompletionState *cmpl_state);
318 static CompletionDir* find_completion_dir(gchar* text_to_complete,
319                                           gchar** remaining_text,
320                                           CompletionState* cmpl_state);
321 static PossibleCompletion* append_completion_text(gchar* text,
322                                                   CompletionState* cmpl_state);
323 #ifdef HAVE_PWD_H
324 static gint get_pwdb(CompletionState* cmpl_state);
325 static gint compare_user_dir(const void* a, const void* b);
326 #endif
327 static gint first_diff_index(gchar* pat, gchar* text);
328 static gint compare_cmpl_dir(const void* a, const void* b);
329 static void update_cmpl(PossibleCompletion* poss,
330                         CompletionState* cmpl_state);
331
332 static void gtk_file_selection_class_init    (GtkFileSelectionClass *klass);
333 static void gtk_file_selection_init          (GtkFileSelection      *filesel);
334 static void gtk_file_selection_destroy       (GtkObject             *object);
335 static gint gtk_file_selection_key_press     (GtkWidget             *widget,
336                                               GdkEventKey           *event,
337                                               gpointer               user_data);
338
339 static void gtk_file_selection_file_button (GtkWidget *widget,
340                                             gint row, 
341                                             gint column, 
342                                             GdkEventButton *bevent,
343                                             gpointer user_data);
344
345 static void gtk_file_selection_dir_button (GtkWidget *widget,
346                                            gint row, 
347                                            gint column, 
348                                            GdkEventButton *bevent,
349                                            gpointer data);
350
351 static void gtk_file_selection_populate      (GtkFileSelection      *fs,
352                                               gchar                 *rel_path,
353                                               gint                   try_complete);
354 static void gtk_file_selection_abort         (GtkFileSelection      *fs);
355
356 static void gtk_file_selection_update_history_menu (GtkFileSelection       *fs,
357                                                     gchar                  *current_dir);
358
359 static void gtk_file_selection_create_dir (GtkWidget *widget, gpointer data);
360 static void gtk_file_selection_delete_file (GtkWidget *widget, gpointer data);
361 static void gtk_file_selection_rename_file (GtkWidget *widget, gpointer data);
362
363
364
365 static GtkWindowClass *parent_class = NULL;
366
367 /* Saves errno when something cmpl does fails. */
368 static gint cmpl_errno;
369
370 #ifdef __CYGWIN32__
371 /*
372  * Take the path currently in the file selection
373  * entry field and translate as necessary from
374  * a WIN32 style to CYGWIN32 style path.  For
375  * instance translate:
376  * x:\somepath\file.jpg
377  * to:
378  * //x/somepath/file.jpg
379  *
380  * Replace the path in the selection text field.
381  * Return a boolean value concerning whether a
382  * translation had to be made.
383  */
384 int
385 translate_win32_path(GtkFileSelection *filesel)
386 {
387   int updated = 0;
388   gchar *path;
389
390   /*
391    * Retrieve the current path
392    */
393   path = gtk_entry_get_text (GTK_ENTRY (filesel->selection_entry));
394
395   /*
396    * Translate only if this looks like a DOS-ish
397    * path... First handle any drive letters.
398    */
399   if (isalpha(path[0]) && (path[1] == ':')) {
400     /*
401      * This part kind of stinks... It isn't possible
402      * to know if there is enough space in the current
403      * string for the extra character required in this
404      * conversion.  Assume that there isn't enough space
405      * and use the set function on the text field to
406      * set the newly created string.
407      */
408     gchar *newPath;
409
410     newPath = g_malloc(strlen(path) + 2);
411     sprintf(newPath, "//%c/%s", path[0], (path + 3));
412     gtk_entry_set_text (GTK_ENTRY (filesel->selection_entry), newPath);
413
414     path = newPath;
415     updated = 1;
416   }
417
418   /*
419    * Now, replace backslashes with forward slashes 
420    * if necessary.
421    */
422   if (strchr(path, '\\')) {
423     int index;
424     for (index = 0; path[index] != '\0'; index++)
425       if (path[index] == '\\')
426         path[index] = '/';
427
428     updated = 1;
429   }
430     
431   return updated;
432 }
433 #endif
434
435 GtkType
436 gtk_file_selection_get_type (void)
437 {
438   static GtkType file_selection_type = 0;
439
440   if (!file_selection_type)
441     {
442       static const GtkTypeInfo filesel_info =
443       {
444         "GtkFileSelection",
445         sizeof (GtkFileSelection),
446         sizeof (GtkFileSelectionClass),
447         (GtkClassInitFunc) gtk_file_selection_class_init,
448         (GtkObjectInitFunc) gtk_file_selection_init,
449         /* reserved_1 */ NULL,
450         /* reserved_2 */ NULL,
451         (GtkClassInitFunc) NULL,
452       };
453
454       file_selection_type = gtk_type_unique (GTK_TYPE_WINDOW, &filesel_info);
455     }
456
457   return file_selection_type;
458 }
459
460 static void
461 gtk_file_selection_class_init (GtkFileSelectionClass *class)
462 {
463   GtkObjectClass *object_class;
464
465   object_class = (GtkObjectClass*) class;
466
467   parent_class = gtk_type_class (GTK_TYPE_WINDOW);
468
469   object_class->destroy = gtk_file_selection_destroy;
470 }
471
472 static void
473 gtk_file_selection_init (GtkFileSelection *filesel)
474 {
475   GtkWidget *entry_vbox;
476   GtkWidget *label;
477   GtkWidget *list_hbox;
478   GtkWidget *confirm_area;
479   GtkWidget *pulldown_hbox;
480   GtkWidget *scrolled_win;
481
482   char *dir_title [2];
483   char *file_title [2];
484   
485   filesel->cmpl_state = cmpl_init_state ();
486
487   /* The dialog-sized vertical box  */
488   filesel->main_vbox = gtk_vbox_new (FALSE, 10);
489   gtk_container_set_border_width (GTK_CONTAINER (filesel), 10);
490   gtk_container_add (GTK_CONTAINER (filesel), filesel->main_vbox);
491   gtk_widget_show (filesel->main_vbox);
492
493   /* The horizontal box containing create, rename etc. buttons */
494   filesel->button_area = gtk_hbutton_box_new ();
495   gtk_button_box_set_layout(GTK_BUTTON_BOX(filesel->button_area), GTK_BUTTONBOX_START);
496   gtk_button_box_set_spacing(GTK_BUTTON_BOX(filesel->button_area), 0);
497   gtk_box_pack_start (GTK_BOX (filesel->main_vbox), filesel->button_area, 
498                       FALSE, FALSE, 0);
499   gtk_widget_show (filesel->button_area);
500   
501   gtk_file_selection_show_fileop_buttons(filesel);
502
503   /* hbox for pulldown menu */
504   pulldown_hbox = gtk_hbox_new (TRUE, 5);
505   gtk_box_pack_start (GTK_BOX (filesel->main_vbox), pulldown_hbox, FALSE, FALSE, 0);
506   gtk_widget_show (pulldown_hbox);
507   
508   /* Pulldown menu */
509   filesel->history_pulldown = gtk_option_menu_new ();
510   gtk_widget_show (filesel->history_pulldown);
511   gtk_box_pack_start (GTK_BOX (pulldown_hbox), filesel->history_pulldown, 
512                       FALSE, FALSE, 0);
513     
514   /*  The horizontal box containing the directory and file listboxes  */
515   list_hbox = gtk_hbox_new (FALSE, 5);
516   gtk_box_pack_start (GTK_BOX (filesel->main_vbox), list_hbox, TRUE, TRUE, 0);
517   gtk_widget_show (list_hbox);
518
519   /* The directories clist */
520   dir_title[0] = _("Directories");
521   dir_title[1] = NULL;
522   filesel->dir_list = gtk_clist_new_with_titles (1, (gchar**) dir_title);
523   gtk_widget_set_usize (filesel->dir_list, DIR_LIST_WIDTH, DIR_LIST_HEIGHT);
524   gtk_signal_connect (GTK_OBJECT (filesel->dir_list), "select_row",
525                       (GtkSignalFunc) gtk_file_selection_dir_button, 
526                       (gpointer) filesel);
527   gtk_clist_column_titles_passive (GTK_CLIST (filesel->dir_list));
528
529   scrolled_win = gtk_scrolled_window_new (NULL, NULL);
530   gtk_container_add (GTK_CONTAINER (scrolled_win), filesel->dir_list);
531   gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_win),
532                                   GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
533   gtk_container_set_border_width (GTK_CONTAINER (scrolled_win), 5);
534   gtk_box_pack_start (GTK_BOX (list_hbox), scrolled_win, TRUE, TRUE, 0);
535   gtk_widget_show (filesel->dir_list);
536   gtk_widget_show (scrolled_win);
537
538   /* The files clist */
539   file_title[0] = _("Files");
540   file_title[1] = NULL;
541   filesel->file_list = gtk_clist_new_with_titles (1, (gchar**) file_title);
542   gtk_widget_set_usize (filesel->file_list, FILE_LIST_WIDTH, FILE_LIST_HEIGHT);
543   gtk_signal_connect (GTK_OBJECT (filesel->file_list), "select_row",
544                       (GtkSignalFunc) gtk_file_selection_file_button, 
545                       (gpointer) filesel);
546   gtk_clist_column_titles_passive (GTK_CLIST (filesel->file_list));
547
548   scrolled_win = gtk_scrolled_window_new (NULL, NULL);
549   gtk_container_add (GTK_CONTAINER (scrolled_win), filesel->file_list);
550   gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_win),
551                                   GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
552   gtk_container_set_border_width (GTK_CONTAINER (scrolled_win), 5);
553   gtk_box_pack_start (GTK_BOX (list_hbox), scrolled_win, TRUE, TRUE, 0);
554   gtk_widget_show (filesel->file_list);
555   gtk_widget_show (scrolled_win);
556
557   /* action area for packing buttons into. */
558   filesel->action_area = gtk_hbox_new (TRUE, 0);
559   gtk_box_pack_start (GTK_BOX (filesel->main_vbox), filesel->action_area, 
560                       FALSE, FALSE, 0);
561   gtk_widget_show (filesel->action_area);
562   
563   /*  The OK/Cancel button area */
564   confirm_area = gtk_hbutton_box_new ();
565   gtk_button_box_set_layout(GTK_BUTTON_BOX(confirm_area), GTK_BUTTONBOX_END);
566   gtk_button_box_set_spacing(GTK_BUTTON_BOX(confirm_area), 5);
567   gtk_box_pack_end (GTK_BOX (filesel->main_vbox), confirm_area, FALSE, FALSE, 0);
568   gtk_widget_show (confirm_area);
569
570   /*  The OK button  */
571   filesel->ok_button = gtk_button_new_with_label (_("OK"));
572   GTK_WIDGET_SET_FLAGS (filesel->ok_button, GTK_CAN_DEFAULT);
573   gtk_box_pack_start (GTK_BOX (confirm_area), filesel->ok_button, TRUE, TRUE, 0);
574   gtk_widget_grab_default (filesel->ok_button);
575   gtk_widget_show (filesel->ok_button);
576
577   /*  The Cancel button  */
578   filesel->cancel_button = gtk_button_new_with_label (_("Cancel"));
579   GTK_WIDGET_SET_FLAGS (filesel->cancel_button, GTK_CAN_DEFAULT);
580   gtk_box_pack_start (GTK_BOX (confirm_area), filesel->cancel_button, TRUE, TRUE, 0);
581   gtk_widget_show (filesel->cancel_button);
582
583   /*  The selection entry widget  */
584   entry_vbox = gtk_vbox_new (FALSE, 2);
585   gtk_box_pack_end (GTK_BOX (filesel->main_vbox), entry_vbox, FALSE, FALSE, 0);
586   gtk_widget_show (entry_vbox);
587
588   filesel->selection_text = label = gtk_label_new ("");
589   gtk_misc_set_alignment (GTK_MISC (label), 0.0, 0.5);
590   gtk_box_pack_start (GTK_BOX (entry_vbox), label, FALSE, FALSE, 0);
591   gtk_widget_show (label);
592
593   filesel->selection_entry = gtk_entry_new ();
594   gtk_signal_connect (GTK_OBJECT (filesel->selection_entry), "key_press_event",
595                       (GtkSignalFunc) gtk_file_selection_key_press, filesel);
596   gtk_signal_connect_object (GTK_OBJECT (filesel->selection_entry), "focus_in_event",
597                              (GtkSignalFunc) gtk_widget_grab_default,
598                              GTK_OBJECT (filesel->ok_button));
599   gtk_signal_connect_object (GTK_OBJECT (filesel->selection_entry), "activate",
600                              (GtkSignalFunc) gtk_button_clicked,
601                              GTK_OBJECT (filesel->ok_button));
602   gtk_box_pack_start (GTK_BOX (entry_vbox), filesel->selection_entry, TRUE, TRUE, 0);
603   gtk_widget_show (filesel->selection_entry);
604
605   if (!cmpl_state_okay (filesel->cmpl_state))
606     {
607       gchar err_buf[256];
608
609       sprintf (err_buf, _("Directory unreadable: %s"), cmpl_strerror (cmpl_errno));
610
611       gtk_label_set_text (GTK_LABEL (filesel->selection_text), err_buf);
612     }
613   else
614     {
615       gtk_file_selection_populate (filesel, "", FALSE);
616     }
617
618   gtk_widget_grab_focus (filesel->selection_entry);
619 }
620
621 GtkWidget*
622 gtk_file_selection_new (const gchar *title)
623 {
624   GtkFileSelection *filesel;
625
626   filesel = gtk_type_new (GTK_TYPE_FILE_SELECTION);
627   gtk_window_set_title (GTK_WINDOW (filesel), title);
628
629   return GTK_WIDGET (filesel);
630 }
631
632 void
633 gtk_file_selection_show_fileop_buttons (GtkFileSelection *filesel)
634 {
635   g_return_if_fail (filesel != NULL);
636   g_return_if_fail (GTK_IS_FILE_SELECTION (filesel));
637     
638   /* delete, create directory, and rename */
639   if (!filesel->fileop_c_dir) 
640     {
641       filesel->fileop_c_dir = gtk_button_new_with_label (_("Create Dir"));
642       gtk_signal_connect (GTK_OBJECT (filesel->fileop_c_dir), "clicked",
643                           (GtkSignalFunc) gtk_file_selection_create_dir, 
644                           (gpointer) filesel);
645       gtk_box_pack_start (GTK_BOX (filesel->button_area), 
646                           filesel->fileop_c_dir, TRUE, TRUE, 0);
647       gtk_widget_show (filesel->fileop_c_dir);
648     }
649         
650   if (!filesel->fileop_del_file) 
651     {
652       filesel->fileop_del_file = gtk_button_new_with_label (_("Delete File"));
653       gtk_signal_connect (GTK_OBJECT (filesel->fileop_del_file), "clicked",
654                           (GtkSignalFunc) gtk_file_selection_delete_file, 
655                           (gpointer) filesel);
656       gtk_box_pack_start (GTK_BOX (filesel->button_area), 
657                           filesel->fileop_del_file, TRUE, TRUE, 0);
658       gtk_widget_show (filesel->fileop_del_file);
659     }
660
661   if (!filesel->fileop_ren_file)
662     {
663       filesel->fileop_ren_file = gtk_button_new_with_label (_("Rename File"));
664       gtk_signal_connect (GTK_OBJECT (filesel->fileop_ren_file), "clicked",
665                           (GtkSignalFunc) gtk_file_selection_rename_file, 
666                           (gpointer) filesel);
667       gtk_box_pack_start (GTK_BOX (filesel->button_area), 
668                           filesel->fileop_ren_file, TRUE, TRUE, 0);
669       gtk_widget_show (filesel->fileop_ren_file);
670     }
671
672   gtk_widget_queue_resize(GTK_WIDGET(filesel));
673 }
674
675 void       
676 gtk_file_selection_hide_fileop_buttons (GtkFileSelection *filesel)
677 {
678   g_return_if_fail (filesel != NULL);
679   g_return_if_fail (GTK_IS_FILE_SELECTION (filesel));
680     
681   if (filesel->fileop_ren_file) 
682     {
683       gtk_widget_destroy (filesel->fileop_ren_file);
684       filesel->fileop_ren_file = NULL;
685     }
686
687   if (filesel->fileop_del_file)
688     {
689       gtk_widget_destroy (filesel->fileop_del_file);
690       filesel->fileop_del_file = NULL;
691     }
692
693   if (filesel->fileop_c_dir)
694     {
695       gtk_widget_destroy (filesel->fileop_c_dir);
696       filesel->fileop_c_dir = NULL;
697     }
698 }
699
700
701
702 void
703 gtk_file_selection_set_filename (GtkFileSelection *filesel,
704                                  const gchar      *filename)
705 {
706   char  buf[MAXPATHLEN];
707   const char *name, *last_slash;
708
709   g_return_if_fail (filesel != NULL);
710   g_return_if_fail (GTK_IS_FILE_SELECTION (filesel));
711   g_return_if_fail (filename != NULL);
712
713   last_slash = strrchr (filename, G_DIR_SEPARATOR);
714
715   if (!last_slash)
716     {
717       buf[0] = 0;
718       name = filename;
719     }
720   else
721     {
722       gint len = MIN (MAXPATHLEN - 1, last_slash - filename + 1);
723
724       strncpy (buf, filename, len);
725       buf[len] = 0;
726
727       name = last_slash + 1;
728     }
729
730   gtk_file_selection_populate (filesel, buf, FALSE);
731
732   if (filesel->selection_entry)
733     gtk_entry_set_text (GTK_ENTRY (filesel->selection_entry), name);
734 }
735
736 gchar*
737 gtk_file_selection_get_filename (GtkFileSelection *filesel)
738 {
739   static char nothing[2] = "";
740   char *text;
741   char *filename;
742
743   g_return_val_if_fail (filesel != NULL, nothing);
744   g_return_val_if_fail (GTK_IS_FILE_SELECTION (filesel), nothing);
745
746 #ifdef __CYGWIN32__
747   translate_win32_path(filesel);
748 #endif
749   text = gtk_entry_get_text (GTK_ENTRY (filesel->selection_entry));
750   if (text)
751     {
752       filename = cmpl_completion_fullname (text, filesel->cmpl_state);
753       return filename;
754     }
755
756   return nothing;
757 }
758
759 void
760 gtk_file_selection_complete (GtkFileSelection *filesel,
761                              const gchar      *pattern)
762 {
763   g_return_if_fail (filesel != NULL);
764   g_return_if_fail (GTK_IS_FILE_SELECTION (filesel));
765   g_return_if_fail (pattern != NULL);
766
767   if (filesel->selection_entry)
768     gtk_entry_set_text (GTK_ENTRY (filesel->selection_entry), pattern);
769   gtk_file_selection_populate (filesel, (gchar*) pattern, TRUE);
770 }
771
772 static void
773 gtk_file_selection_destroy (GtkObject *object)
774 {
775   GtkFileSelection *filesel;
776   GList *list;
777   HistoryCallbackArg *callback_arg;
778
779   g_return_if_fail (object != NULL);
780   g_return_if_fail (GTK_IS_FILE_SELECTION (object));
781
782   filesel = GTK_FILE_SELECTION (object);
783   
784   if (filesel->fileop_dialog)
785           gtk_widget_destroy (filesel->fileop_dialog);
786   
787   if (filesel->history_list)
788     {
789       list = filesel->history_list;
790       while (list)
791         {
792           callback_arg = list->data;
793           g_free (callback_arg->directory);
794           g_free (callback_arg);
795           list = list->next;
796         }
797       g_list_free (filesel->history_list);
798       filesel->history_list = NULL;
799     }
800   
801   cmpl_free_state (filesel->cmpl_state);
802   filesel->cmpl_state = NULL;
803
804   if (GTK_OBJECT_CLASS (parent_class)->destroy)
805     (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
806 }
807
808 /* Begin file operations callbacks */
809
810 static void
811 gtk_file_selection_fileop_error (gchar *error_message)
812 {
813   GtkWidget *label;
814   GtkWidget *vbox;
815   GtkWidget *button;
816   GtkWidget *dialog;
817   
818   g_return_if_fail (error_message != NULL);
819   
820   /* main dialog */
821   dialog = gtk_dialog_new ();
822   /*
823   gtk_signal_connect (GTK_OBJECT (dialog), "destroy",
824                       (GtkSignalFunc) gtk_file_selection_fileop_destroy, 
825                       (gpointer) fs);
826   */
827   gtk_window_set_title (GTK_WINDOW (dialog), _("Error"));
828   gtk_window_set_position (GTK_WINDOW (dialog), GTK_WIN_POS_MOUSE);
829   
830   vbox = gtk_vbox_new(FALSE, 0);
831   gtk_container_set_border_width(GTK_CONTAINER(vbox), 8);
832   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), vbox,
833                      FALSE, FALSE, 0);
834   gtk_widget_show(vbox);
835
836   label = gtk_label_new(error_message);
837   gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
838   gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 5);
839   gtk_widget_show(label);
840
841   /* yes, we free it */
842   g_free (error_message);
843   
844   /* close button */
845   button = gtk_button_new_with_label (_("Close"));
846   gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
847                              (GtkSignalFunc) gtk_widget_destroy, 
848                              (gpointer) dialog);
849   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),
850                      button, TRUE, TRUE, 0);
851   GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
852   gtk_widget_grab_default(button);
853   gtk_widget_show (button);
854
855   gtk_widget_show (dialog);
856 }
857
858 static void
859 gtk_file_selection_fileop_destroy (GtkWidget *widget, gpointer data)
860 {
861   GtkFileSelection *fs = data;
862
863   g_return_if_fail (fs != NULL);
864   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
865   
866   fs->fileop_dialog = NULL;
867 }
868
869
870 static void
871 gtk_file_selection_create_dir_confirmed (GtkWidget *widget, gpointer data)
872 {
873   GtkFileSelection *fs = data;
874   gchar *dirname;
875   gchar *path;
876   gchar *full_path;
877   gchar *buf;
878   CompletionState *cmpl_state;
879   
880   g_return_if_fail (fs != NULL);
881   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
882
883   dirname = gtk_entry_get_text (GTK_ENTRY (fs->fileop_entry));
884   cmpl_state = (CompletionState*) fs->cmpl_state;
885   path = cmpl_reference_position (cmpl_state);
886   
887   full_path = g_strconcat (path, G_DIR_SEPARATOR_S, dirname, NULL);
888   if ( (mkdir (full_path, 0755) < 0) ) 
889     {
890       buf = g_strconcat ("Error creating directory \"", dirname, "\":  ", 
891                          g_strerror(errno), NULL);
892       gtk_file_selection_fileop_error (buf);
893     }
894   g_free (full_path);
895   
896   gtk_widget_destroy (fs->fileop_dialog);
897   gtk_file_selection_populate (fs, "", FALSE);
898 }
899   
900 static void
901 gtk_file_selection_create_dir (GtkWidget *widget, gpointer data)
902 {
903   GtkFileSelection *fs = data;
904   GtkWidget *label;
905   GtkWidget *dialog;
906   GtkWidget *vbox;
907   GtkWidget *button;
908
909   g_return_if_fail (fs != NULL);
910   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
911
912   if (fs->fileop_dialog)
913           return;
914   
915   /* main dialog */
916   fs->fileop_dialog = dialog = gtk_dialog_new ();
917   gtk_signal_connect (GTK_OBJECT (dialog), "destroy",
918                       (GtkSignalFunc) gtk_file_selection_fileop_destroy, 
919                       (gpointer) fs);
920   gtk_window_set_title (GTK_WINDOW (dialog), _("Create Directory"));
921   gtk_window_set_position (GTK_WINDOW (dialog), GTK_WIN_POS_MOUSE);
922
923   /* If file dialog is grabbed, grab option dialog */
924   /* When option dialog is closed, file dialog will be grabbed again */
925   if (GTK_WINDOW(fs)->modal)
926       gtk_window_set_modal (GTK_WINDOW(dialog), TRUE);
927
928   vbox = gtk_vbox_new(FALSE, 0);
929   gtk_container_set_border_width(GTK_CONTAINER(vbox), 8);
930   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), vbox,
931                      FALSE, FALSE, 0);
932   gtk_widget_show(vbox);
933   
934   label = gtk_label_new(_("Directory name:"));
935   gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
936   gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 5);
937   gtk_widget_show(label);
938
939   /*  The directory entry widget  */
940   fs->fileop_entry = gtk_entry_new ();
941   gtk_box_pack_start (GTK_BOX (vbox), fs->fileop_entry, 
942                       TRUE, TRUE, 5);
943   GTK_WIDGET_SET_FLAGS(fs->fileop_entry, GTK_CAN_DEFAULT);
944   gtk_widget_show (fs->fileop_entry);
945   
946   /* buttons */
947   button = gtk_button_new_with_label (_("Create"));
948   gtk_signal_connect (GTK_OBJECT (button), "clicked",
949                       (GtkSignalFunc) gtk_file_selection_create_dir_confirmed, 
950                       (gpointer) fs);
951   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),
952                      button, TRUE, TRUE, 0);
953   GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
954   gtk_widget_show(button);
955   
956   button = gtk_button_new_with_label (_("Cancel"));
957   gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
958                              (GtkSignalFunc) gtk_widget_destroy, 
959                              (gpointer) dialog);
960   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),
961                      button, TRUE, TRUE, 0);
962   GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
963   gtk_widget_grab_default(button);
964   gtk_widget_show (button);
965
966   gtk_widget_show (dialog);
967 }
968
969 static void
970 gtk_file_selection_delete_file_confirmed (GtkWidget *widget, gpointer data)
971 {
972   GtkFileSelection *fs = data;
973   CompletionState *cmpl_state;
974   gchar *path;
975   gchar *full_path;
976   gchar *buf;
977   
978   g_return_if_fail (fs != NULL);
979   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
980
981   cmpl_state = (CompletionState*) fs->cmpl_state;
982   path = cmpl_reference_position (cmpl_state);
983   
984   full_path = g_strconcat (path, G_DIR_SEPARATOR_S, fs->fileop_file, NULL);
985   if ( (unlink (full_path) < 0) ) 
986     {
987       buf = g_strconcat ("Error deleting file \"", fs->fileop_file, "\":  ", 
988                          g_strerror(errno), NULL);
989       gtk_file_selection_fileop_error (buf);
990     }
991   g_free (full_path);
992   
993   gtk_widget_destroy (fs->fileop_dialog);
994   gtk_file_selection_populate (fs, "", FALSE);
995 }
996
997 static void
998 gtk_file_selection_delete_file (GtkWidget *widget, gpointer data)
999 {
1000   GtkFileSelection *fs = data;
1001   GtkWidget *label;
1002   GtkWidget *vbox;
1003   GtkWidget *button;
1004   GtkWidget *dialog;
1005   gchar *filename;
1006   gchar *buf;
1007   
1008   g_return_if_fail (fs != NULL);
1009   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1010
1011   if (fs->fileop_dialog)
1012           return;
1013
1014 #ifdef __CYGWIN32__
1015   translate_win32_path(fs);
1016 #endif
1017
1018   filename = gtk_entry_get_text (GTK_ENTRY (fs->selection_entry));
1019   if (strlen(filename) < 1)
1020           return;
1021
1022   fs->fileop_file = filename;
1023   
1024   /* main dialog */
1025   fs->fileop_dialog = dialog = gtk_dialog_new ();
1026   gtk_signal_connect (GTK_OBJECT (dialog), "destroy",
1027                       (GtkSignalFunc) gtk_file_selection_fileop_destroy, 
1028                       (gpointer) fs);
1029   gtk_window_set_title (GTK_WINDOW (dialog), _("Delete File"));
1030   gtk_window_set_position (GTK_WINDOW (dialog), GTK_WIN_POS_MOUSE);
1031
1032   /* If file dialog is grabbed, grab option dialog */
1033   /* When option dialog is closed, file dialog will be grabbed again */
1034   if (GTK_WINDOW(fs)->modal)
1035       gtk_window_set_modal (GTK_WINDOW(dialog), TRUE);
1036   
1037   vbox = gtk_vbox_new(FALSE, 0);
1038   gtk_container_set_border_width(GTK_CONTAINER(vbox), 8);
1039   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), vbox,
1040                      FALSE, FALSE, 0);
1041   gtk_widget_show(vbox);
1042
1043   buf = g_strconcat ("Really delete file \"", filename, "\" ?", NULL);
1044   label = gtk_label_new(buf);
1045   gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
1046   gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 5);
1047   gtk_widget_show(label);
1048   g_free(buf);
1049   
1050   /* buttons */
1051   button = gtk_button_new_with_label (_("Delete"));
1052   gtk_signal_connect (GTK_OBJECT (button), "clicked",
1053                       (GtkSignalFunc) gtk_file_selection_delete_file_confirmed, 
1054                       (gpointer) fs);
1055   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),
1056                      button, TRUE, TRUE, 0);
1057   GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1058   gtk_widget_show(button);
1059   
1060   button = gtk_button_new_with_label (_("Cancel"));
1061   gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
1062                              (GtkSignalFunc) gtk_widget_destroy, 
1063                              (gpointer) dialog);
1064   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),
1065                      button, TRUE, TRUE, 0);
1066   GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1067   gtk_widget_grab_default(button);
1068   gtk_widget_show (button);
1069
1070   gtk_widget_show (dialog);
1071
1072 }
1073
1074 static void
1075 gtk_file_selection_rename_file_confirmed (GtkWidget *widget, gpointer data)
1076 {
1077   GtkFileSelection *fs = data;
1078   gchar *buf;
1079   gchar *file;
1080   gchar *path;
1081   gchar *new_filename;
1082   gchar *old_filename;
1083   CompletionState *cmpl_state;
1084   
1085   g_return_if_fail (fs != NULL);
1086   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1087
1088   file = gtk_entry_get_text (GTK_ENTRY (fs->fileop_entry));
1089   cmpl_state = (CompletionState*) fs->cmpl_state;
1090   path = cmpl_reference_position (cmpl_state);
1091   
1092   new_filename = g_strconcat (path, G_DIR_SEPARATOR_S, file, NULL);
1093   old_filename = g_strconcat (path, G_DIR_SEPARATOR_S, fs->fileop_file, NULL);
1094
1095   if ( (rename (old_filename, new_filename)) < 0) 
1096     {
1097       buf = g_strconcat ("Error renaming file \"", file, "\":  ", 
1098                          g_strerror(errno), NULL);
1099       gtk_file_selection_fileop_error (buf);
1100     }
1101   g_free (new_filename);
1102   g_free (old_filename);
1103   
1104   gtk_widget_destroy (fs->fileop_dialog);
1105   gtk_file_selection_populate (fs, "", FALSE);
1106 }
1107   
1108 static void
1109 gtk_file_selection_rename_file (GtkWidget *widget, gpointer data)
1110 {
1111   GtkFileSelection *fs = data;
1112   GtkWidget *label;
1113   GtkWidget *dialog;
1114   GtkWidget *vbox;
1115   GtkWidget *button;
1116   gchar *buf;
1117   
1118   g_return_if_fail (fs != NULL);
1119   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1120
1121   if (fs->fileop_dialog)
1122           return;
1123
1124   fs->fileop_file = gtk_entry_get_text (GTK_ENTRY (fs->selection_entry));
1125   if (strlen(fs->fileop_file) < 1)
1126           return;
1127   
1128   /* main dialog */
1129   fs->fileop_dialog = dialog = gtk_dialog_new ();
1130   gtk_signal_connect (GTK_OBJECT (dialog), "destroy",
1131                       (GtkSignalFunc) gtk_file_selection_fileop_destroy, 
1132                       (gpointer) fs);
1133   gtk_window_set_title (GTK_WINDOW (dialog), _("Rename File"));
1134   gtk_window_set_position (GTK_WINDOW (dialog), GTK_WIN_POS_MOUSE);
1135
1136   /* If file dialog is grabbed, grab option dialog */
1137   /* When option dialog  closed, file dialog will be grabbed again */
1138   if (GTK_WINDOW(fs)->modal)
1139     gtk_window_set_modal (GTK_WINDOW(dialog), TRUE);
1140   
1141   vbox = gtk_vbox_new(FALSE, 0);
1142   gtk_container_set_border_width (GTK_CONTAINER(vbox), 8);
1143   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), vbox,
1144                      FALSE, FALSE, 0);
1145   gtk_widget_show(vbox);
1146   
1147   buf = g_strconcat ("Rename file \"", fs->fileop_file, "\" to:", NULL);
1148   label = gtk_label_new(buf);
1149   gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
1150   gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 5);
1151   gtk_widget_show(label);
1152   g_free(buf);
1153
1154   /* New filename entry */
1155   fs->fileop_entry = gtk_entry_new ();
1156   gtk_box_pack_start (GTK_BOX (vbox), fs->fileop_entry, 
1157                       TRUE, TRUE, 5);
1158   GTK_WIDGET_SET_FLAGS(fs->fileop_entry, GTK_CAN_DEFAULT);
1159   gtk_widget_show (fs->fileop_entry);
1160   
1161   gtk_entry_set_text (GTK_ENTRY (fs->fileop_entry), fs->fileop_file);
1162   gtk_editable_select_region (GTK_EDITABLE (fs->fileop_entry),
1163                               0, strlen (fs->fileop_file));
1164
1165   /* buttons */
1166   button = gtk_button_new_with_label (_("Rename"));
1167   gtk_signal_connect (GTK_OBJECT (button), "clicked",
1168                       (GtkSignalFunc) gtk_file_selection_rename_file_confirmed, 
1169                       (gpointer) fs);
1170   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),
1171                      button, TRUE, TRUE, 0);
1172   GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1173   gtk_widget_show(button);
1174   
1175   button = gtk_button_new_with_label (_("Cancel"));
1176   gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
1177                              (GtkSignalFunc) gtk_widget_destroy, 
1178                              (gpointer) dialog);
1179   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),
1180                      button, TRUE, TRUE, 0);
1181   GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1182   gtk_widget_grab_default(button);
1183   gtk_widget_show (button);
1184
1185   gtk_widget_show (dialog);
1186 }
1187
1188
1189 static gint
1190 gtk_file_selection_key_press (GtkWidget   *widget,
1191                               GdkEventKey *event,
1192                               gpointer     user_data)
1193 {
1194   GtkFileSelection *fs;
1195   char *text;
1196
1197   g_return_val_if_fail (widget != NULL, FALSE);
1198   g_return_val_if_fail (event != NULL, FALSE);
1199
1200   if (event->keyval == GDK_Tab)
1201     {
1202       fs = GTK_FILE_SELECTION (user_data);
1203 #ifdef __CYGWIN32__
1204       translate_win32_path(fs);
1205 #endif
1206       text = gtk_entry_get_text (GTK_ENTRY (fs->selection_entry));
1207
1208       text = g_strdup (text);
1209
1210       gtk_file_selection_populate (fs, text, TRUE);
1211
1212       g_free (text);
1213
1214       gtk_signal_emit_stop_by_name (GTK_OBJECT (widget), "key_press_event");
1215
1216       return TRUE;
1217     }
1218
1219   return FALSE;
1220 }
1221
1222
1223 static void
1224 gtk_file_selection_history_callback (GtkWidget *widget, gpointer data)
1225 {
1226   GtkFileSelection *fs = data;
1227   HistoryCallbackArg *callback_arg;
1228   GList *list;
1229
1230   g_return_if_fail (fs != NULL);
1231   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1232
1233   list = fs->history_list;
1234   
1235   while (list) {
1236     callback_arg = list->data;
1237     
1238     if (callback_arg->menu_item == widget)
1239       {
1240         gtk_file_selection_populate (fs, callback_arg->directory, FALSE);
1241         break;
1242       }
1243     
1244     list = list->next;
1245   }
1246 }
1247
1248 static void 
1249 gtk_file_selection_update_history_menu (GtkFileSelection *fs,
1250                                         gchar *current_directory)
1251 {
1252   HistoryCallbackArg *callback_arg;
1253   GtkWidget *menu_item;
1254   GList *list;
1255   gchar *current_dir;
1256   gint dir_len;
1257   gint i;
1258   
1259   g_return_if_fail (fs != NULL);
1260   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1261   g_return_if_fail (current_directory != NULL);
1262   
1263   list = fs->history_list;
1264
1265   if (fs->history_menu) 
1266     {
1267       while (list) {
1268         callback_arg = list->data;
1269         g_free (callback_arg->directory);
1270         g_free (callback_arg);
1271         list = list->next;
1272       }
1273       g_list_free (fs->history_list);
1274       fs->history_list = NULL;
1275       
1276       gtk_widget_destroy (fs->history_menu);
1277     }
1278   
1279   fs->history_menu = gtk_menu_new();
1280
1281   current_dir = g_strdup (current_directory);
1282
1283   dir_len = strlen (current_dir);
1284
1285   for (i = dir_len; i >= 0; i--)
1286     {
1287       /* the i == dir_len is to catch the full path for the first 
1288        * entry. */
1289       if ( (current_dir[i] == G_DIR_SEPARATOR) || (i == dir_len))
1290         {
1291           /* another small hack to catch the full path */
1292           if (i != dir_len) 
1293                   current_dir[i + 1] = '\0';
1294 #ifdef __CYGWIN32__
1295           if (!strcmp(current_dir, "//"))
1296             continue;
1297 #endif
1298           menu_item = gtk_menu_item_new_with_label (current_dir);
1299           
1300           callback_arg = g_new (HistoryCallbackArg, 1);
1301           callback_arg->menu_item = menu_item;
1302           
1303           /* since the autocompletion gets confused if you don't 
1304            * supply a trailing '/' on a dir entry, set the full
1305            * (current) path to "" which just refreshes the filesel */
1306           if (dir_len == i) {
1307             callback_arg->directory = g_strdup ("");
1308           } else {
1309             callback_arg->directory = g_strdup (current_dir);
1310           }
1311           
1312           fs->history_list = g_list_append (fs->history_list, callback_arg);
1313           
1314           gtk_signal_connect (GTK_OBJECT (menu_item), "activate",
1315                               (GtkSignalFunc) gtk_file_selection_history_callback,
1316                               (gpointer) fs);
1317           gtk_menu_append (GTK_MENU (fs->history_menu), menu_item);
1318           gtk_widget_show (menu_item);
1319         }
1320     }
1321
1322   gtk_option_menu_set_menu (GTK_OPTION_MENU (fs->history_pulldown), 
1323                             fs->history_menu);
1324   g_free (current_dir);
1325 }
1326
1327 static void
1328 gtk_file_selection_file_button (GtkWidget *widget,
1329                                gint row, 
1330                                gint column, 
1331                                GdkEventButton *bevent,
1332                                gpointer user_data)
1333 {
1334   GtkFileSelection *fs = NULL;
1335   gchar *filename, *temp = NULL;
1336   
1337   g_return_if_fail (GTK_IS_CLIST (widget));
1338
1339   fs = user_data;
1340   g_return_if_fail (fs != NULL);
1341   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1342   
1343   gtk_clist_get_text (GTK_CLIST (fs->file_list), row, 0, &temp);
1344   filename = g_strdup (temp);
1345
1346 #ifdef __CYGWIN32__
1347   /* Check to see if the selection was a drive selector */
1348   if (isalpha(filename[0]) && (filename[1] == ':')) {
1349     /* It is... map it to a CYGWIN32 drive */
1350     char temp_filename[10];
1351
1352     sprintf(temp_filename, "//%c/", tolower(filename[0]));
1353     g_free(filename);
1354     filename = g_strdup(temp_filename);
1355   }
1356 #endif /* CYGWIN32 */
1357
1358   if (filename)
1359     {
1360       if (bevent)
1361         switch (bevent->type)
1362           {
1363           case GDK_2BUTTON_PRESS:
1364             gtk_button_clicked (GTK_BUTTON (fs->ok_button));
1365             break;
1366             
1367           default:
1368             gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), filename);
1369             break;
1370           }
1371       else
1372         gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), filename);
1373
1374       g_free (filename);
1375     }
1376 }
1377
1378 static void
1379 gtk_file_selection_dir_button (GtkWidget *widget,
1380                                gint row, 
1381                                gint column, 
1382                                GdkEventButton *bevent,
1383                                gpointer user_data)
1384 {
1385   GtkFileSelection *fs = NULL;
1386   gchar *filename, *temp = NULL;
1387
1388   g_return_if_fail (GTK_IS_CLIST (widget));
1389
1390   fs = GTK_FILE_SELECTION (user_data);
1391   g_return_if_fail (fs != NULL);
1392   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1393
1394   gtk_clist_get_text (GTK_CLIST (fs->dir_list), row, 0, &temp);
1395   filename = g_strdup (temp);
1396
1397   if (filename)
1398     {
1399       if (bevent)
1400         switch (bevent->type)
1401           {
1402           case GDK_2BUTTON_PRESS:
1403             gtk_file_selection_populate (fs, filename, FALSE);
1404             break;
1405           
1406           default:
1407             gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), filename);
1408             break;
1409           }
1410       else
1411         gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), filename);
1412
1413       g_free (filename);
1414     }
1415 }
1416
1417 #ifdef WIN32
1418
1419 static void
1420 win32_gtk_add_drives_to_dir_list(GtkWidget *the_dir_list)
1421 {
1422   gchar *text[2], *textPtr;
1423   gchar buffer[128];
1424   char volumeNameBuf[128];
1425   char formatBuffer[128];
1426   gint row;
1427
1428   text[1] = NULL;
1429
1430   /* Get the Drives string */
1431   GetLogicalDriveStrings(sizeof(buffer), buffer);
1432
1433   /* Add the drives as necessary */
1434   textPtr = buffer;
1435   while (*textPtr != '\0') {
1436     /* Get the volume information for this drive */
1437     if ((tolower(textPtr[0]) != 'a') && (tolower(textPtr[0]) != 'b'))
1438       {
1439         /* Ignore floppies (?) */
1440         DWORD maxComponentLength, flags;
1441
1442         GetVolumeInformation(textPtr,
1443                              volumeNameBuf, sizeof(volumeNameBuf),
1444                              NULL, &maxComponentLength,
1445                              &flags, NULL, 0);
1446         /* Build the actual displayable string */
1447
1448         sprintf(formatBuffer, "%c:\\", toupper(textPtr[0]));
1449 #if 0 /* HB: removed to allow drive change AND directory update with one click */
1450         if (strlen(volumeNameBuf) > 0)
1451           sprintf(formatBuffer, "%s (%s)", formatBuffer, volumeNameBuf);
1452 #endif
1453         /* Add to the list */
1454         text[0] = formatBuffer;
1455         row = gtk_clist_append (GTK_CLIST (the_dir_list), text);
1456       }
1457     textPtr += (strlen(textPtr) + 1);
1458   }
1459 }
1460 #endif
1461
1462 static void
1463 gtk_file_selection_populate (GtkFileSelection *fs,
1464                              gchar            *rel_path,
1465                              gint              try_complete)
1466 {
1467   CompletionState *cmpl_state;
1468   PossibleCompletion* poss;
1469   gchar* filename;
1470   gint row;
1471   gchar* rem_path = rel_path;
1472   gchar* sel_text;
1473   gchar* text[2];
1474   gint did_recurse = FALSE;
1475   gint possible_count = 0;
1476   gint selection_index = -1;
1477   gint file_list_width;
1478   gint dir_list_width;
1479   
1480   g_return_if_fail (fs != NULL);
1481   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1482   
1483   cmpl_state = (CompletionState*) fs->cmpl_state;
1484   poss = cmpl_completion_matches (rel_path, &rem_path, cmpl_state);
1485
1486   if (!cmpl_state_okay (cmpl_state))
1487     {
1488       /* Something went wrong. */
1489       gtk_file_selection_abort (fs);
1490       return;
1491     }
1492
1493   g_assert (cmpl_state->reference_dir);
1494
1495   gtk_clist_freeze (GTK_CLIST (fs->dir_list));
1496   gtk_clist_clear (GTK_CLIST (fs->dir_list));
1497   gtk_clist_freeze (GTK_CLIST (fs->file_list));
1498   gtk_clist_clear (GTK_CLIST (fs->file_list));
1499
1500   /* Set the dir_list to include ./ and ../ */
1501   text[1] = NULL;
1502   text[0] = "." G_DIR_SEPARATOR_S;
1503   row = gtk_clist_append (GTK_CLIST (fs->dir_list), text);
1504
1505   text[0] = ".." G_DIR_SEPARATOR_S;
1506   row = gtk_clist_append (GTK_CLIST (fs->dir_list), text);
1507
1508   /*reset the max widths of the lists*/
1509   dir_list_width = gdk_string_width(fs->dir_list->style->font,".." G_DIR_SEPARATOR_S);
1510   gtk_clist_set_column_width(GTK_CLIST(fs->dir_list),0,dir_list_width);
1511   file_list_width = 1;
1512   gtk_clist_set_column_width(GTK_CLIST(fs->file_list),0,file_list_width);
1513
1514   while (poss)
1515     {
1516       if (cmpl_is_a_completion (poss))
1517         {
1518           possible_count += 1;
1519
1520           filename = cmpl_this_completion (poss);
1521
1522           text[0] = filename;
1523           
1524           if (cmpl_is_directory (poss))
1525             {
1526               if (strcmp (filename, "." G_DIR_SEPARATOR_S) != 0 &&
1527                   strcmp (filename, ".." G_DIR_SEPARATOR_S) != 0)
1528                 {
1529                   int width = gdk_string_width(fs->dir_list->style->font,
1530                                                filename);
1531                   row = gtk_clist_append (GTK_CLIST (fs->dir_list), text);
1532                   if(width > dir_list_width)
1533                     {
1534                       dir_list_width = width;
1535                       gtk_clist_set_column_width(GTK_CLIST(fs->dir_list),0,
1536                                                  width);
1537                     }
1538                 }
1539             }
1540           else
1541             {
1542               int width = gdk_string_width(fs->file_list->style->font,
1543                                            filename);
1544               row = gtk_clist_append (GTK_CLIST (fs->file_list), text);
1545               if(width > file_list_width)
1546                 {
1547                   file_list_width = width;
1548                   gtk_clist_set_column_width(GTK_CLIST(fs->file_list),0,
1549                                              width);
1550                 }
1551             }
1552         }
1553
1554       poss = cmpl_next_completion (cmpl_state);
1555     }
1556
1557 #ifdef WIN32
1558   /* For Windows, add drives as potential selections */
1559   win32_gtk_add_drives_to_dir_list (fs->dir_list);
1560 #endif
1561
1562   gtk_clist_thaw (GTK_CLIST (fs->dir_list));
1563   gtk_clist_thaw (GTK_CLIST (fs->file_list));
1564
1565   /* File lists are set. */
1566
1567   g_assert (cmpl_state->reference_dir);
1568
1569   if (try_complete)
1570     {
1571
1572       /* User is trying to complete filenames, so advance the user's input
1573        * string to the updated_text, which is the common leading substring
1574        * of all possible completions, and if its a directory attempt
1575        * attempt completions in it. */
1576
1577       if (cmpl_updated_text (cmpl_state)[0])
1578         {
1579
1580           if (cmpl_updated_dir (cmpl_state))
1581             {
1582               gchar* dir_name = g_strdup (cmpl_updated_text (cmpl_state));
1583
1584               did_recurse = TRUE;
1585
1586               gtk_file_selection_populate (fs, dir_name, TRUE);
1587
1588               g_free (dir_name);
1589             }
1590           else
1591             {
1592               if (fs->selection_entry)
1593                       gtk_entry_set_text (GTK_ENTRY (fs->selection_entry),
1594                                           cmpl_updated_text (cmpl_state));
1595             }
1596         }
1597       else
1598         {
1599           selection_index = cmpl_last_valid_char (cmpl_state) -
1600                             (strlen (rel_path) - strlen (rem_path));
1601           if (fs->selection_entry)
1602             gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), rem_path);
1603         }
1604     }
1605   else
1606     {
1607       if (fs->selection_entry)
1608         gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), "");
1609     }
1610
1611   if (!did_recurse)
1612     {
1613       if (fs->selection_entry)
1614         gtk_entry_set_position (GTK_ENTRY (fs->selection_entry), selection_index);
1615
1616       if (fs->selection_entry)
1617         {
1618           sel_text = g_strconcat (_("Selection: "),
1619                                   cmpl_reference_position (cmpl_state),
1620                                   NULL);
1621
1622           gtk_label_set_text (GTK_LABEL (fs->selection_text), sel_text);
1623           g_free (sel_text);
1624         }
1625
1626       if (fs->history_pulldown) 
1627         {
1628           gtk_file_selection_update_history_menu (fs, cmpl_reference_position (cmpl_state));
1629         }
1630       
1631     }
1632 }
1633
1634 static void
1635 gtk_file_selection_abort (GtkFileSelection *fs)
1636 {
1637   gchar err_buf[256];
1638
1639   sprintf (err_buf, _("Directory unreadable: %s"), cmpl_strerror (cmpl_errno));
1640
1641   /*  BEEP gdk_beep();  */
1642
1643   if (fs->selection_entry)
1644     gtk_label_set_text (GTK_LABEL (fs->selection_text), err_buf);
1645 }
1646
1647 /**********************************************************************/
1648 /*                        External Interface                          */
1649 /**********************************************************************/
1650
1651 /* The four completion state selectors
1652  */
1653 static gchar*
1654 cmpl_updated_text (CompletionState* cmpl_state)
1655 {
1656   return cmpl_state->updated_text;
1657 }
1658
1659 static gint
1660 cmpl_updated_dir (CompletionState* cmpl_state)
1661 {
1662   return cmpl_state->re_complete;
1663 }
1664
1665 static gchar*
1666 cmpl_reference_position (CompletionState* cmpl_state)
1667 {
1668   return cmpl_state->reference_dir->fullname;
1669 }
1670
1671 static gint
1672 cmpl_last_valid_char (CompletionState* cmpl_state)
1673 {
1674   return cmpl_state->last_valid_char;
1675 }
1676
1677 static gchar*
1678 cmpl_completion_fullname (gchar* text, CompletionState* cmpl_state)
1679 {
1680   static char nothing[2] = "";
1681
1682   if (!cmpl_state_okay (cmpl_state))
1683     {
1684       return nothing;
1685     }
1686   else if (g_path_is_absolute (text))
1687     {
1688       strcpy (cmpl_state->updated_text, text);
1689     }
1690 #ifdef HAVE_PWD_H
1691   else if (text[0] == '~')
1692     {
1693       CompletionDir* dir;
1694       char* slash;
1695
1696       dir = open_user_dir (text, cmpl_state);
1697
1698       if (!dir)
1699         {
1700           /* spencer says just return ~something, so
1701            * for now just do it. */
1702           strcpy (cmpl_state->updated_text, text);
1703         }
1704       else
1705         {
1706
1707           strcpy (cmpl_state->updated_text, dir->fullname);
1708
1709           slash = strchr (text, G_DIR_SEPARATOR);
1710
1711           if (slash)
1712             strcat (cmpl_state->updated_text, slash);
1713         }
1714     }
1715 #endif
1716   else
1717     {
1718       strcpy (cmpl_state->updated_text, cmpl_state->reference_dir->fullname);
1719       if (cmpl_state->updated_text[strlen (cmpl_state->updated_text) - 1] != G_DIR_SEPARATOR)
1720         strcat (cmpl_state->updated_text, G_DIR_SEPARATOR_S);
1721       strcat (cmpl_state->updated_text, text);
1722     }
1723
1724   return cmpl_state->updated_text;
1725 }
1726
1727 /* The three completion selectors
1728  */
1729 static gchar*
1730 cmpl_this_completion (PossibleCompletion* pc)
1731 {
1732   return pc->text;
1733 }
1734
1735 static gint
1736 cmpl_is_directory (PossibleCompletion* pc)
1737 {
1738   return pc->is_directory;
1739 }
1740
1741 static gint
1742 cmpl_is_a_completion (PossibleCompletion* pc)
1743 {
1744   return pc->is_a_completion;
1745 }
1746
1747 /**********************************************************************/
1748 /*                       Construction, deletion                       */
1749 /**********************************************************************/
1750
1751 static CompletionState*
1752 cmpl_init_state (void)
1753 {
1754   gchar *getcwd_buf;
1755   CompletionState *new_state;
1756
1757   new_state = g_new (CompletionState, 1);
1758
1759   getcwd_buf = g_get_current_dir ();
1760
1761 tryagain:
1762
1763   new_state->reference_dir = NULL;
1764   new_state->completion_dir = NULL;
1765   new_state->active_completion_dir = NULL;
1766   new_state->directory_storage = NULL;
1767   new_state->directory_sent_storage = NULL;
1768   new_state->last_valid_char = 0;
1769   new_state->updated_text = g_new (gchar, MAXPATHLEN);
1770   new_state->updated_text_alloc = MAXPATHLEN;
1771   new_state->the_completion.text = g_new (gchar, MAXPATHLEN);
1772   new_state->the_completion.text_alloc = MAXPATHLEN;
1773   new_state->user_dir_name_buffer = NULL;
1774   new_state->user_directories = NULL;
1775
1776   new_state->reference_dir =  open_dir (getcwd_buf, new_state);
1777
1778   if (!new_state->reference_dir)
1779     {
1780       /* Directories changing from underneath us, grumble */
1781       strcpy (getcwd_buf, G_DIR_SEPARATOR_S);
1782       goto tryagain;
1783     }
1784
1785   g_free (getcwd_buf);
1786   return new_state;
1787 }
1788
1789 static void
1790 cmpl_free_dir_list(GList* dp0)
1791 {
1792   GList *dp = dp0;
1793
1794   while (dp) {
1795     free_dir (dp->data);
1796     dp = dp->next;
1797   }
1798
1799   g_list_free(dp0);
1800 }
1801
1802 static void
1803 cmpl_free_dir_sent_list(GList* dp0)
1804 {
1805   GList *dp = dp0;
1806
1807   while (dp) {
1808     free_dir_sent (dp->data);
1809     dp = dp->next;
1810   }
1811
1812   g_list_free(dp0);
1813 }
1814
1815 static void
1816 cmpl_free_state (CompletionState* cmpl_state)
1817 {
1818   cmpl_free_dir_list (cmpl_state->directory_storage);
1819   cmpl_free_dir_sent_list (cmpl_state->directory_sent_storage);
1820
1821   if (cmpl_state->user_dir_name_buffer)
1822     g_free (cmpl_state->user_dir_name_buffer);
1823   if (cmpl_state->user_directories)
1824     g_free (cmpl_state->user_directories);
1825   if (cmpl_state->the_completion.text)
1826     g_free (cmpl_state->the_completion.text);
1827   if (cmpl_state->updated_text)
1828     g_free (cmpl_state->updated_text);
1829
1830   g_free (cmpl_state);
1831 }
1832
1833 static void
1834 free_dir(CompletionDir* dir)
1835 {
1836   g_free(dir->fullname);
1837   g_free(dir);
1838 }
1839
1840 static void
1841 free_dir_sent(CompletionDirSent* sent)
1842 {
1843   g_free(sent->name_buffer);
1844   g_free(sent->entries);
1845   g_free(sent);
1846 }
1847
1848 static void
1849 prune_memory_usage(CompletionState *cmpl_state)
1850 {
1851   GList* cdsl = cmpl_state->directory_sent_storage;
1852   GList* cdl = cmpl_state->directory_storage;
1853   GList* cdl0 = cdl;
1854   gint len = 0;
1855
1856   for(; cdsl && len < CMPL_DIRECTORY_CACHE_SIZE; len += 1)
1857     cdsl = cdsl->next;
1858
1859   if (cdsl) {
1860     cmpl_free_dir_sent_list(cdsl->next);
1861     cdsl->next = NULL;
1862   }
1863
1864   cmpl_state->directory_storage = NULL;
1865   while (cdl) {
1866     if (cdl->data == cmpl_state->reference_dir)
1867       cmpl_state->directory_storage = g_list_prepend(NULL, cdl->data);
1868     else
1869       free_dir (cdl->data);
1870     cdl = cdl->next;
1871   }
1872
1873   g_list_free(cdl0);
1874 }
1875
1876 /**********************************************************************/
1877 /*                        The main entrances.                         */
1878 /**********************************************************************/
1879
1880 static PossibleCompletion*
1881 cmpl_completion_matches (gchar* text_to_complete,
1882                          gchar** remaining_text,
1883                          CompletionState* cmpl_state)
1884 {
1885   gchar* first_slash;
1886   PossibleCompletion *poss;
1887
1888   prune_memory_usage(cmpl_state);
1889
1890   g_assert (text_to_complete != NULL);
1891
1892   cmpl_state->user_completion_index = -1;
1893   cmpl_state->last_completion_text = text_to_complete;
1894   cmpl_state->the_completion.text[0] = 0;
1895   cmpl_state->last_valid_char = 0;
1896   cmpl_state->updated_text_len = -1;
1897   cmpl_state->updated_text[0] = 0;
1898   cmpl_state->re_complete = FALSE;
1899
1900 #ifdef HAVE_PWD_H
1901   first_slash = strchr (text_to_complete, G_DIR_SEPARATOR);
1902
1903   if (text_to_complete[0] == '~' && !first_slash)
1904     {
1905       /* Text starts with ~ and there is no slash, show all the
1906        * home directory completions.
1907        */
1908       poss = attempt_homedir_completion (text_to_complete, cmpl_state);
1909
1910       update_cmpl(poss, cmpl_state);
1911
1912       return poss;
1913     }
1914 #endif
1915   cmpl_state->reference_dir =
1916     open_ref_dir (text_to_complete, remaining_text, cmpl_state);
1917
1918   if(!cmpl_state->reference_dir)
1919     return NULL;
1920
1921   cmpl_state->completion_dir =
1922     find_completion_dir (*remaining_text, remaining_text, cmpl_state);
1923
1924   cmpl_state->last_valid_char = *remaining_text - text_to_complete;
1925
1926   if(!cmpl_state->completion_dir)
1927     return NULL;
1928
1929   cmpl_state->completion_dir->cmpl_index = -1;
1930   cmpl_state->completion_dir->cmpl_parent = NULL;
1931   cmpl_state->completion_dir->cmpl_text = *remaining_text;
1932
1933   cmpl_state->active_completion_dir = cmpl_state->completion_dir;
1934
1935   cmpl_state->reference_dir = cmpl_state->completion_dir;
1936
1937   poss = attempt_file_completion(cmpl_state);
1938
1939   update_cmpl(poss, cmpl_state);
1940
1941   return poss;
1942 }
1943
1944 static PossibleCompletion*
1945 cmpl_next_completion (CompletionState* cmpl_state)
1946 {
1947   PossibleCompletion* poss = NULL;
1948
1949   cmpl_state->the_completion.text[0] = 0;
1950
1951 #ifdef HAVE_PWD_H
1952   if(cmpl_state->user_completion_index >= 0)
1953     poss = attempt_homedir_completion(cmpl_state->last_completion_text, cmpl_state);
1954   else
1955     poss = attempt_file_completion(cmpl_state);
1956 #else
1957   poss = attempt_file_completion(cmpl_state);
1958 #endif
1959
1960   update_cmpl(poss, cmpl_state);
1961
1962   return poss;
1963 }
1964
1965 /**********************************************************************/
1966 /*                       Directory Operations                         */
1967 /**********************************************************************/
1968
1969 /* Open the directory where completion will begin from, if possible. */
1970 static CompletionDir*
1971 open_ref_dir(gchar* text_to_complete,
1972              gchar** remaining_text,
1973              CompletionState* cmpl_state)
1974 {
1975   gchar* first_slash;
1976   CompletionDir *new_dir;
1977
1978   first_slash = strchr(text_to_complete, G_DIR_SEPARATOR);
1979
1980 #ifdef __CYGWIN32__
1981   if (text_to_complete[0] == '/' && text_to_complete[1] == '/')
1982     {
1983       char root_dir[5];
1984       sprintf(root_dir, "//%c", text_to_complete[2]);
1985
1986       new_dir = open_dir(root_dir, cmpl_state);
1987
1988       if (new_dir) {
1989         *remaining_text = text_to_complete + 4;
1990       }
1991     }
1992 #else
1993   if (FALSE)
1994     ;
1995 #endif
1996   else if (g_path_is_absolute (text_to_complete) || !cmpl_state->reference_dir)
1997     {
1998       char *root;
1999       int rootlen;
2000
2001       rootlen = g_path_skip_root (text_to_complete) - text_to_complete;
2002       root = g_malloc (rootlen + 1);
2003       memcpy (root, text_to_complete, rootlen);
2004       root[rootlen] = '\0';
2005       new_dir = open_dir (root, cmpl_state);
2006       if (new_dir)
2007         *remaining_text = g_path_skip_root (text_to_complete);
2008       g_free (root);
2009     }
2010 #ifdef HAVE_PWD_H
2011   else if (text_to_complete[0] == '~')
2012     {
2013       new_dir = open_user_dir(text_to_complete, cmpl_state);
2014
2015       if(new_dir)
2016         {
2017           if(first_slash)
2018             *remaining_text = first_slash + 1;
2019           else
2020             *remaining_text = text_to_complete + strlen(text_to_complete);
2021         }
2022       else
2023         {
2024           return NULL;
2025         }
2026     }
2027 #endif
2028   else
2029     {
2030       *remaining_text = text_to_complete;
2031
2032       new_dir = open_dir(cmpl_state->reference_dir->fullname, cmpl_state);
2033     }
2034
2035   if(new_dir)
2036     {
2037       new_dir->cmpl_index = -1;
2038       new_dir->cmpl_parent = NULL;
2039     }
2040
2041   return new_dir;
2042 }
2043
2044 #ifdef HAVE_PWD_H
2045
2046 /* open a directory by user name */
2047 static CompletionDir*
2048 open_user_dir(gchar* text_to_complete,
2049               CompletionState *cmpl_state)
2050 {
2051   gchar *first_slash;
2052   gint cmp_len;
2053
2054   g_assert(text_to_complete && text_to_complete[0] == '~');
2055
2056   first_slash = strchr(text_to_complete, G_DIR_SEPARATOR);
2057
2058   if (first_slash)
2059     cmp_len = first_slash - text_to_complete - 1;
2060   else
2061     cmp_len = strlen(text_to_complete + 1);
2062
2063   if(!cmp_len)
2064     {
2065       /* ~/ */
2066       gchar *homedir = g_get_home_dir ();
2067
2068       if (homedir)
2069         return open_dir(homedir, cmpl_state);
2070       else
2071         return NULL;
2072     }
2073   else
2074     {
2075       /* ~user/ */
2076       char* copy = g_new(char, cmp_len + 1);
2077       struct passwd *pwd;
2078       strncpy(copy, text_to_complete + 1, cmp_len);
2079       copy[cmp_len] = 0;
2080       pwd = getpwnam(copy);
2081       g_free(copy);
2082       if (!pwd)
2083         {
2084           cmpl_errno = errno;
2085           return NULL;
2086         }
2087
2088       return open_dir(pwd->pw_dir, cmpl_state);
2089     }
2090 }
2091
2092 #endif
2093
2094 /* open a directory relative the the current relative directory */
2095 static CompletionDir*
2096 open_relative_dir(gchar* dir_name,
2097                   CompletionDir* dir,
2098                   CompletionState *cmpl_state)
2099 {
2100   gchar path_buf[2*MAXPATHLEN];
2101
2102   if(dir->fullname_len + strlen(dir_name) + 2 >= MAXPATHLEN)
2103     {
2104       cmpl_errno = CMPL_ERRNO_TOO_LONG;
2105       return NULL;
2106     }
2107
2108   strcpy(path_buf, dir->fullname);
2109
2110   if(dir->fullname_len > 1)
2111     {
2112       if (path_buf[dir->fullname_len - 1] != G_DIR_SEPARATOR)
2113         {
2114           path_buf[dir->fullname_len] = G_DIR_SEPARATOR;
2115           strcpy (path_buf + dir->fullname_len + 1, dir_name);
2116         }
2117       else
2118         strcpy (path_buf + dir->fullname_len, dir_name);
2119     }
2120   else
2121     {
2122       strcpy(path_buf + dir->fullname_len, dir_name);
2123     }
2124
2125   return open_dir(path_buf, cmpl_state);
2126 }
2127
2128 /* after the cache lookup fails, really open a new directory */
2129 static CompletionDirSent*
2130 open_new_dir(gchar* dir_name, struct stat* sbuf, gboolean stat_subdirs)
2131 {
2132   CompletionDirSent* sent;
2133   DIR* directory;
2134   gchar *buffer_ptr;
2135   struct dirent *dirent_ptr;
2136   gint buffer_size = 0;
2137   gint entry_count = 0;
2138   gint i;
2139   struct stat ent_sbuf;
2140   char path_buf[MAXPATHLEN*2];
2141   gint path_buf_len;
2142
2143   sent = g_new(CompletionDirSent, 1);
2144   sent->mtime = sbuf->st_mtime;
2145   sent->inode = sbuf->st_ino;
2146   sent->device = sbuf->st_dev;
2147
2148   path_buf_len = strlen(dir_name);
2149
2150   if (path_buf_len > MAXPATHLEN)
2151     {
2152       cmpl_errno = CMPL_ERRNO_TOO_LONG;
2153       return NULL;
2154     }
2155
2156   strcpy(path_buf, dir_name);
2157
2158   directory = opendir(dir_name);
2159
2160   if(!directory)
2161     {
2162       cmpl_errno = errno;
2163       return NULL;
2164     }
2165
2166   while((dirent_ptr = readdir(directory)) != NULL)
2167     {
2168       int entry_len = strlen(dirent_ptr->d_name);
2169       buffer_size += entry_len + 1;
2170       entry_count += 1;
2171
2172       if(path_buf_len + entry_len + 2 >= MAXPATHLEN)
2173         {
2174           cmpl_errno = CMPL_ERRNO_TOO_LONG;
2175           closedir(directory);
2176           return NULL;
2177         }
2178     }
2179
2180   sent->name_buffer = g_new(gchar, buffer_size);
2181   sent->entries = g_new(CompletionDirEntry, entry_count);
2182   sent->entry_count = entry_count;
2183
2184   buffer_ptr = sent->name_buffer;
2185
2186   rewinddir(directory);
2187
2188   for(i = 0; i < entry_count; i += 1)
2189     {
2190       dirent_ptr = readdir(directory);
2191
2192       if(!dirent_ptr)
2193         {
2194           cmpl_errno = errno;
2195           closedir(directory);
2196           return NULL;
2197         }
2198
2199       strcpy(buffer_ptr, dirent_ptr->d_name);
2200       sent->entries[i].entry_name = buffer_ptr;
2201       buffer_ptr += strlen(dirent_ptr->d_name);
2202       *buffer_ptr = 0;
2203       buffer_ptr += 1;
2204
2205       if (path_buf[path_buf_len-1] != G_DIR_SEPARATOR)
2206         {
2207           path_buf[path_buf_len] = G_DIR_SEPARATOR;
2208           strcpy(path_buf + path_buf_len + 1, dirent_ptr->d_name);
2209         }
2210       else
2211         strcpy(path_buf + path_buf_len, dirent_ptr->d_name);
2212
2213       if (stat_subdirs)
2214         {
2215           if(stat(path_buf, &ent_sbuf) >= 0 && S_ISDIR(ent_sbuf.st_mode))
2216             sent->entries[i].is_dir = 1;
2217           else
2218             /* stat may fail, and we don't mind, since it could be a
2219              * dangling symlink. */
2220             sent->entries[i].is_dir = 0;
2221         }
2222       else
2223         sent->entries[i].is_dir = 1;
2224     }
2225
2226   qsort(sent->entries, sent->entry_count, sizeof(CompletionDirEntry), compare_cmpl_dir);
2227
2228   closedir(directory);
2229
2230   return sent;
2231 }
2232
2233 #ifndef WIN32
2234
2235 static gboolean
2236 check_dir(gchar *dir_name, struct stat *result, gboolean *stat_subdirs)
2237 {
2238   /* A list of directories that we know only contain other directories.
2239    * Trying to stat every file in these directories would be very
2240    * expensive.
2241    */
2242
2243   static struct {
2244     gchar *name;
2245     gboolean present;
2246     struct stat statbuf;
2247   } no_stat_dirs[] = {
2248     { "/afs", FALSE, { 0 } },
2249     { "/net", FALSE, { 0 } }
2250   };
2251
2252   static const gint n_no_stat_dirs = sizeof(no_stat_dirs) / sizeof(no_stat_dirs[0]);
2253   static gboolean initialized = FALSE;
2254
2255   gint i;
2256
2257   if (!initialized)
2258     {
2259       initialized = TRUE;
2260       for (i = 0; i < n_no_stat_dirs; i++)
2261         {
2262           if (stat (no_stat_dirs[i].name, &no_stat_dirs[i].statbuf) == 0)
2263             no_stat_dirs[i].present = TRUE;
2264         }
2265     }
2266
2267   if(stat(dir_name, result) < 0)
2268     {
2269       cmpl_errno = errno;
2270       return FALSE;
2271     }
2272
2273   *stat_subdirs = TRUE;
2274   for (i=0; i<n_no_stat_dirs; i++)
2275     {
2276       if (no_stat_dirs[i].present &&
2277           (no_stat_dirs[i].statbuf.st_dev == result->st_dev) &&
2278           (no_stat_dirs[i].statbuf.st_ino == result->st_ino))
2279         {
2280           *stat_subdirs = FALSE;
2281           break;
2282         }
2283     }
2284
2285   return TRUE;
2286 }
2287
2288 #endif
2289
2290 /* open a directory by absolute pathname */
2291 static CompletionDir*
2292 open_dir(gchar* dir_name, CompletionState* cmpl_state)
2293 {
2294   struct stat sbuf;
2295   gboolean stat_subdirs;
2296   CompletionDirSent *sent;
2297   GList* cdsl;
2298
2299 #ifndef WIN32
2300   if (!check_dir (dir_name, &sbuf, &stat_subdirs))
2301     return NULL;
2302
2303   cdsl = cmpl_state->directory_sent_storage;
2304
2305   while (cdsl)
2306     {
2307       sent = cdsl->data;
2308
2309       if(sent->inode == sbuf.st_ino &&
2310          sent->mtime == sbuf.st_mtime &&
2311          sent->device == sbuf.st_dev)
2312         return attach_dir(sent, dir_name, cmpl_state);
2313
2314       cdsl = cdsl->next;
2315     }
2316 #else
2317   stat_subdirs = TRUE;
2318 #endif
2319
2320   sent = open_new_dir(dir_name, &sbuf, stat_subdirs);
2321
2322   if (sent) {
2323     cmpl_state->directory_sent_storage =
2324       g_list_prepend(cmpl_state->directory_sent_storage, sent);
2325
2326     return attach_dir(sent, dir_name, cmpl_state);
2327   }
2328
2329   return NULL;
2330 }
2331
2332 static CompletionDir*
2333 attach_dir(CompletionDirSent* sent, gchar* dir_name, CompletionState *cmpl_state)
2334 {
2335   CompletionDir* new_dir;
2336
2337   new_dir = g_new(CompletionDir, 1);
2338
2339   cmpl_state->directory_storage =
2340     g_list_prepend(cmpl_state->directory_storage, new_dir);
2341
2342   new_dir->sent = sent;
2343   new_dir->fullname = g_strdup(dir_name);
2344   new_dir->fullname_len = strlen(dir_name);
2345
2346   return new_dir;
2347 }
2348
2349 static gint
2350 correct_dir_fullname(CompletionDir* cmpl_dir)
2351 {
2352   gint length = strlen(cmpl_dir->fullname);
2353   gchar *first_slash = strchr(cmpl_dir->fullname, G_DIR_SEPARATOR);
2354   struct stat sbuf;
2355
2356   /* Does it end with /. (\.) ? */
2357   if (length >= 2 &&
2358       strcmp(cmpl_dir->fullname + length - 2, G_DIR_SEPARATOR_S ".") == 0)
2359     {
2360       /* Is it just the root directory (on a drive) ? */
2361       if (cmpl_dir->fullname + length - 2 == first_slash)
2362         {
2363           cmpl_dir->fullname[length - 1] = 0;
2364           cmpl_dir->fullname_len = length - 1;
2365           return TRUE;
2366         }
2367       else
2368         {
2369           cmpl_dir->fullname[length - 2] = 0;
2370         }
2371     }
2372
2373   /* Ends with /./ (\.\)? */
2374   else if (length >= 3 &&
2375            strcmp(cmpl_dir->fullname + length - 3,
2376                   G_DIR_SEPARATOR_S "." G_DIR_SEPARATOR_S) == 0)
2377     cmpl_dir->fullname[length - 2] = 0;
2378
2379   /* Ends with /.. (\..) ? */
2380   else if (length >= 3 &&
2381            strcmp(cmpl_dir->fullname + length - 3,
2382                   G_DIR_SEPARATOR_S "..") == 0)
2383     {
2384       /* Is it just /.. (X:\..)? */
2385       if(cmpl_dir->fullname + length - 3 == first_slash)
2386         {
2387           cmpl_dir->fullname[length - 2] = 0;
2388           cmpl_dir->fullname_len = length - 2;
2389           return TRUE;
2390         }
2391
2392       if(stat(cmpl_dir->fullname, &sbuf) < 0)
2393         {
2394           cmpl_errno = errno;
2395           return FALSE;
2396         }
2397
2398       cmpl_dir->fullname[length - 3] = 0;
2399
2400       if(!correct_parent(cmpl_dir, &sbuf))
2401         return FALSE;
2402     }
2403
2404   /* Ends with /../ (\..\)? */
2405   else if (length >= 4 &&
2406            strcmp(cmpl_dir->fullname + length - 4,
2407                   G_DIR_SEPARATOR_S ".." G_DIR_SEPARATOR_S) == 0)
2408     {
2409       /* Is it just /../ (X:\..\)? */
2410       if(cmpl_dir->fullname + length - 4 == first_slash)
2411         {
2412           cmpl_dir->fullname[length - 3] = 0;
2413           cmpl_dir->fullname_len = length - 3;
2414           return TRUE;
2415         }
2416
2417       if(stat(cmpl_dir->fullname, &sbuf) < 0)
2418         {
2419           cmpl_errno = errno;
2420           return FALSE;
2421         }
2422
2423       cmpl_dir->fullname[length - 4] = 0;
2424
2425       if(!correct_parent(cmpl_dir, &sbuf))
2426         return FALSE;
2427     }
2428
2429   cmpl_dir->fullname_len = strlen(cmpl_dir->fullname);
2430
2431   return TRUE;
2432 }
2433
2434 static gint
2435 correct_parent(CompletionDir* cmpl_dir, struct stat *sbuf)
2436 {
2437   struct stat parbuf;
2438   gchar *last_slash;
2439   gchar *first_slash;
2440   gchar *new_name;
2441   gchar c = 0;
2442
2443   last_slash = strrchr(cmpl_dir->fullname, G_DIR_SEPARATOR);
2444   g_assert(last_slash);
2445   first_slash = strchr(cmpl_dir->fullname, G_DIR_SEPARATOR);
2446
2447   /* Clever (?) way to check for top-level directory that works also on
2448    * Win32, where there is a drive letter and colon prefixed...
2449    */
2450   if (last_slash != first_slash)
2451     {
2452       last_slash[0] = 0;
2453     }
2454   else
2455     {
2456       c = last_slash[1];
2457       last_slash[1] = 0;
2458     }
2459
2460   if (stat(cmpl_dir->fullname, &parbuf) < 0)
2461     {
2462       cmpl_errno = errno;
2463       if (!c)
2464         last_slash[0] = G_DIR_SEPARATOR;
2465       return FALSE;
2466     }
2467
2468 #ifndef NATIVE_WIN32            /* No inode numbers on Win32 */
2469   if (parbuf.st_ino == sbuf->st_ino && parbuf.st_dev == sbuf->st_dev)
2470     /* it wasn't a link */
2471     return TRUE;
2472
2473   if(c)
2474     last_slash[1] = c;
2475   else
2476     last_slash[0] = G_DIR_SEPARATOR;
2477
2478   /* it was a link, have to figure it out the hard way */
2479
2480   new_name = find_parent_dir_fullname(cmpl_dir->fullname);
2481
2482   if (!new_name)
2483     return FALSE;
2484
2485   g_free(cmpl_dir->fullname);
2486
2487   cmpl_dir->fullname = new_name;
2488 #endif
2489
2490   return TRUE;
2491 }
2492
2493 #ifndef NATIVE_WIN32
2494
2495 static gchar*
2496 find_parent_dir_fullname(gchar* dirname)
2497 {
2498   gchar *orig_dir;
2499   gchar *result;
2500
2501   orig_dir = g_get_current_dir ();
2502
2503   if(chdir(dirname) != 0 || chdir("..") != 0)
2504     {
2505       cmpl_errno = errno;
2506       return NULL;
2507     }
2508
2509   result = g_get_current_dir ();
2510
2511   if(chdir(orig_dir) != 0)
2512     {
2513       cmpl_errno = errno;
2514       return NULL;
2515     }
2516
2517   g_free (orig_dir);
2518   return result;
2519 }
2520
2521 #endif
2522
2523 /**********************************************************************/
2524 /*                        Completion Operations                       */
2525 /**********************************************************************/
2526
2527 #ifdef HAVE_PWD_H
2528
2529 static PossibleCompletion*
2530 attempt_homedir_completion(gchar* text_to_complete,
2531                            CompletionState *cmpl_state)
2532 {
2533   gint index, length;
2534
2535   if (!cmpl_state->user_dir_name_buffer &&
2536       !get_pwdb(cmpl_state))
2537     return NULL;
2538   length = strlen(text_to_complete) - 1;
2539
2540   cmpl_state->user_completion_index += 1;
2541
2542   while(cmpl_state->user_completion_index < cmpl_state->user_directories_len)
2543     {
2544       index = first_diff_index(text_to_complete + 1,
2545                                cmpl_state->user_directories
2546                                [cmpl_state->user_completion_index].login);
2547
2548       switch(index)
2549         {
2550         case PATTERN_MATCH:
2551           break;
2552         default:
2553           if(cmpl_state->last_valid_char < (index + 1))
2554             cmpl_state->last_valid_char = index + 1;
2555           cmpl_state->user_completion_index += 1;
2556           continue;
2557         }
2558
2559       cmpl_state->the_completion.is_a_completion = 1;
2560       cmpl_state->the_completion.is_directory = 1;
2561
2562       append_completion_text("~", cmpl_state);
2563
2564       append_completion_text(cmpl_state->
2565                               user_directories[cmpl_state->user_completion_index].login,
2566                              cmpl_state);
2567
2568       return append_completion_text(G_DIR_SEPARATOR_S, cmpl_state);
2569     }
2570
2571   if(text_to_complete[1] ||
2572      cmpl_state->user_completion_index > cmpl_state->user_directories_len)
2573     {
2574       cmpl_state->user_completion_index = -1;
2575       return NULL;
2576     }
2577   else
2578     {
2579       cmpl_state->user_completion_index += 1;
2580       cmpl_state->the_completion.is_a_completion = 1;
2581       cmpl_state->the_completion.is_directory = 1;
2582
2583       return append_completion_text("~" G_DIR_SEPARATOR_S, cmpl_state);
2584     }
2585 }
2586
2587 #endif
2588
2589 #ifdef WIN32
2590 #define FOLD(c) (tolower(c))
2591 #else
2592 #define FOLD(c) (c)
2593 #endif
2594
2595 /* returns the index (>= 0) of the first differing character,
2596  * PATTERN_MATCH if the completion matches */
2597 static gint
2598 first_diff_index(gchar* pat, gchar* text)
2599 {
2600   gint diff = 0;
2601
2602   while(*pat && *text && FOLD(*text) == FOLD(*pat))
2603     {
2604       pat += 1;
2605       text += 1;
2606       diff += 1;
2607     }
2608
2609   if(*pat)
2610     return diff;
2611
2612   return PATTERN_MATCH;
2613 }
2614
2615 static PossibleCompletion*
2616 append_completion_text(gchar* text, CompletionState* cmpl_state)
2617 {
2618   gint len, i = 1;
2619
2620   if(!cmpl_state->the_completion.text)
2621     return NULL;
2622
2623   len = strlen(text) + strlen(cmpl_state->the_completion.text) + 1;
2624
2625   if(cmpl_state->the_completion.text_alloc > len)
2626     {
2627       strcat(cmpl_state->the_completion.text, text);
2628       return &cmpl_state->the_completion;
2629     }
2630
2631   while(i < len) { i <<= 1; }
2632
2633   cmpl_state->the_completion.text_alloc = i;
2634
2635   cmpl_state->the_completion.text = (gchar*)g_realloc(cmpl_state->the_completion.text, i);
2636
2637   if(!cmpl_state->the_completion.text)
2638     return NULL;
2639   else
2640     {
2641       strcat(cmpl_state->the_completion.text, text);
2642       return &cmpl_state->the_completion;
2643     }
2644 }
2645
2646 static CompletionDir*
2647 find_completion_dir(gchar* text_to_complete,
2648                     gchar** remaining_text,
2649                     CompletionState* cmpl_state)
2650 {
2651   gchar* first_slash = strchr(text_to_complete, G_DIR_SEPARATOR);
2652   CompletionDir* dir = cmpl_state->reference_dir;
2653   CompletionDir* next;
2654   *remaining_text = text_to_complete;
2655
2656   while(first_slash)
2657     {
2658       gint len = first_slash - *remaining_text;
2659       gint found = 0;
2660       gchar *found_name = NULL;         /* Quiet gcc */
2661       gint i;
2662       gchar* pat_buf = g_new (gchar, len + 1);
2663
2664       strncpy(pat_buf, *remaining_text, len);
2665       pat_buf[len] = 0;
2666
2667       for(i = 0; i < dir->sent->entry_count; i += 1)
2668         {
2669           if(dir->sent->entries[i].is_dir &&
2670              fnmatch(pat_buf, dir->sent->entries[i].entry_name,
2671                      FNMATCH_FLAGS)!= FNM_NOMATCH)
2672             {
2673               if(found)
2674                 {
2675                   g_free (pat_buf);
2676                   return dir;
2677                 }
2678               else
2679                 {
2680                   found = 1;
2681                   found_name = dir->sent->entries[i].entry_name;
2682                 }
2683             }
2684         }
2685
2686       if (!found)
2687         {
2688           /* Perhaps we are trying to open an automount directory */
2689           found_name = pat_buf;
2690         }
2691
2692       next = open_relative_dir(found_name, dir, cmpl_state);
2693       
2694       if(!next)
2695         {
2696           g_free (pat_buf);
2697           return NULL;
2698         }
2699       
2700       next->cmpl_parent = dir;
2701       
2702       dir = next;
2703       
2704       if(!correct_dir_fullname(dir))
2705         {
2706           g_free(pat_buf);
2707           return NULL;
2708         }
2709       
2710       *remaining_text = first_slash + 1;
2711       first_slash = strchr(*remaining_text, G_DIR_SEPARATOR);
2712
2713       g_free (pat_buf);
2714     }
2715
2716   return dir;
2717 }
2718
2719 static void
2720 update_cmpl(PossibleCompletion* poss, CompletionState* cmpl_state)
2721 {
2722   gint cmpl_len;
2723
2724   if(!poss || !cmpl_is_a_completion(poss))
2725     return;
2726
2727   cmpl_len = strlen(cmpl_this_completion(poss));
2728
2729   if(cmpl_state->updated_text_alloc < cmpl_len + 1)
2730     {
2731       cmpl_state->updated_text =
2732         (gchar*)g_realloc(cmpl_state->updated_text,
2733                           cmpl_state->updated_text_alloc);
2734       cmpl_state->updated_text_alloc = 2*cmpl_len;
2735     }
2736
2737   if(cmpl_state->updated_text_len < 0)
2738     {
2739       strcpy(cmpl_state->updated_text, cmpl_this_completion(poss));
2740       cmpl_state->updated_text_len = cmpl_len;
2741       cmpl_state->re_complete = cmpl_is_directory(poss);
2742     }
2743   else if(cmpl_state->updated_text_len == 0)
2744     {
2745       cmpl_state->re_complete = FALSE;
2746     }
2747   else
2748     {
2749       gint first_diff =
2750         first_diff_index(cmpl_state->updated_text,
2751                          cmpl_this_completion(poss));
2752
2753       cmpl_state->re_complete = FALSE;
2754
2755       if(first_diff == PATTERN_MATCH)
2756         return;
2757
2758       if(first_diff > cmpl_state->updated_text_len)
2759         strcpy(cmpl_state->updated_text, cmpl_this_completion(poss));
2760
2761       cmpl_state->updated_text_len = first_diff;
2762       cmpl_state->updated_text[first_diff] = 0;
2763     }
2764 }
2765
2766 static PossibleCompletion*
2767 attempt_file_completion(CompletionState *cmpl_state)
2768 {
2769   gchar *pat_buf, *first_slash;
2770   CompletionDir *dir = cmpl_state->active_completion_dir;
2771
2772   dir->cmpl_index += 1;
2773
2774   if(dir->cmpl_index == dir->sent->entry_count)
2775     {
2776       if(dir->cmpl_parent == NULL)
2777         {
2778           cmpl_state->active_completion_dir = NULL;
2779
2780           return NULL;
2781         }
2782       else
2783         {
2784           cmpl_state->active_completion_dir = dir->cmpl_parent;
2785
2786           return attempt_file_completion(cmpl_state);
2787         }
2788     }
2789
2790   g_assert(dir->cmpl_text);
2791
2792   first_slash = strchr(dir->cmpl_text, G_DIR_SEPARATOR);
2793
2794   if(first_slash)
2795     {
2796       gint len = first_slash - dir->cmpl_text;
2797
2798       pat_buf = g_new (gchar, len + 1);
2799       strncpy(pat_buf, dir->cmpl_text, len);
2800       pat_buf[len] = 0;
2801     }
2802   else
2803     {
2804       gint len = strlen(dir->cmpl_text);
2805
2806       pat_buf = g_new (gchar, len + 2);
2807       strcpy(pat_buf, dir->cmpl_text);
2808       /* Don't append a * if the user entered one herself.
2809        * This way one can complete *.h and don't get matches
2810        * on any .help files, for instance.
2811        */
2812       if (strchr(pat_buf, '*') == NULL)
2813         strcpy(pat_buf + len, "*");
2814     }
2815
2816   if(first_slash)
2817     {
2818       if(dir->sent->entries[dir->cmpl_index].is_dir)
2819         {
2820           if(fnmatch(pat_buf, dir->sent->entries[dir->cmpl_index].entry_name,
2821                      FNMATCH_FLAGS) != FNM_NOMATCH)
2822             {
2823               CompletionDir* new_dir;
2824
2825               new_dir = open_relative_dir(dir->sent->entries[dir->cmpl_index].entry_name,
2826                                           dir, cmpl_state);
2827
2828               if(!new_dir)
2829                 {
2830                   g_free (pat_buf);
2831                   return NULL;
2832                 }
2833
2834               new_dir->cmpl_parent = dir;
2835
2836               new_dir->cmpl_index = -1;
2837               new_dir->cmpl_text = first_slash + 1;
2838
2839               cmpl_state->active_completion_dir = new_dir;
2840
2841               g_free (pat_buf);
2842               return attempt_file_completion(cmpl_state);
2843             }
2844           else
2845             {
2846               g_free (pat_buf);
2847               return attempt_file_completion(cmpl_state);
2848             }
2849         }
2850       else
2851         {
2852           g_free (pat_buf);
2853           return attempt_file_completion(cmpl_state);
2854         }
2855     }
2856   else
2857     {
2858       if(dir->cmpl_parent != NULL)
2859         {
2860           append_completion_text(dir->fullname +
2861                                  strlen(cmpl_state->completion_dir->fullname) + 1,
2862                                  cmpl_state);
2863           append_completion_text(G_DIR_SEPARATOR_S, cmpl_state);
2864         }
2865
2866       append_completion_text(dir->sent->entries[dir->cmpl_index].entry_name, cmpl_state);
2867
2868       cmpl_state->the_completion.is_a_completion =
2869         (fnmatch(pat_buf, dir->sent->entries[dir->cmpl_index].entry_name,
2870                  FNMATCH_FLAGS) != FNM_NOMATCH);
2871
2872       cmpl_state->the_completion.is_directory = dir->sent->entries[dir->cmpl_index].is_dir;
2873       if(dir->sent->entries[dir->cmpl_index].is_dir)
2874         append_completion_text(G_DIR_SEPARATOR_S, cmpl_state);
2875
2876       g_free (pat_buf);
2877       return &cmpl_state->the_completion;
2878     }
2879 }
2880
2881 #ifdef HAVE_PWD_H
2882
2883 static gint
2884 get_pwdb(CompletionState* cmpl_state)
2885 {
2886   struct passwd *pwd_ptr;
2887   gchar* buf_ptr;
2888   gint len = 0, i, count = 0;
2889
2890   if(cmpl_state->user_dir_name_buffer)
2891     return TRUE;
2892   setpwent ();
2893
2894   while ((pwd_ptr = getpwent()) != NULL)
2895     {
2896       len += strlen(pwd_ptr->pw_name);
2897       len += strlen(pwd_ptr->pw_dir);
2898       len += 2;
2899       count += 1;
2900     }
2901
2902   setpwent ();
2903
2904   cmpl_state->user_dir_name_buffer = g_new(gchar, len);
2905   cmpl_state->user_directories = g_new(CompletionUserDir, count);
2906   cmpl_state->user_directories_len = count;
2907
2908   buf_ptr = cmpl_state->user_dir_name_buffer;
2909
2910   for(i = 0; i < count; i += 1)
2911     {
2912       pwd_ptr = getpwent();
2913       if(!pwd_ptr)
2914         {
2915           cmpl_errno = errno;
2916           goto error;
2917         }
2918
2919       strcpy(buf_ptr, pwd_ptr->pw_name);
2920       cmpl_state->user_directories[i].login = buf_ptr;
2921       buf_ptr += strlen(buf_ptr);
2922       buf_ptr += 1;
2923       strcpy(buf_ptr, pwd_ptr->pw_dir);
2924       cmpl_state->user_directories[i].homedir = buf_ptr;
2925       buf_ptr += strlen(buf_ptr);
2926       buf_ptr += 1;
2927     }
2928
2929   qsort(cmpl_state->user_directories,
2930         cmpl_state->user_directories_len,
2931         sizeof(CompletionUserDir),
2932         compare_user_dir);
2933
2934   endpwent();
2935
2936   return TRUE;
2937
2938 error:
2939
2940   if(cmpl_state->user_dir_name_buffer)
2941     g_free(cmpl_state->user_dir_name_buffer);
2942   if(cmpl_state->user_directories)
2943     g_free(cmpl_state->user_directories);
2944
2945   cmpl_state->user_dir_name_buffer = NULL;
2946   cmpl_state->user_directories = NULL;
2947
2948   return FALSE;
2949 }
2950
2951 static gint
2952 compare_user_dir(const void* a, const void* b)
2953 {
2954   return strcmp((((CompletionUserDir*)a))->login,
2955                 (((CompletionUserDir*)b))->login);
2956 }
2957
2958 #endif
2959
2960 static gint
2961 compare_cmpl_dir(const void* a, const void* b)
2962 {
2963 #ifndef WIN32
2964   return strcmp((((CompletionDirEntry*)a))->entry_name,
2965                 (((CompletionDirEntry*)b))->entry_name);
2966 #else
2967   return g_strcasecmp((((CompletionDirEntry*)a))->entry_name,
2968                       (((CompletionDirEntry*)b))->entry_name);
2969 #endif
2970 }
2971
2972 static gint
2973 cmpl_state_okay(CompletionState* cmpl_state)
2974 {
2975   return  cmpl_state && cmpl_state->reference_dir;
2976 }
2977
2978 static gchar*
2979 cmpl_strerror(gint err)
2980 {
2981   if(err == CMPL_ERRNO_TOO_LONG)
2982     return "Name too long";
2983   else
2984     return g_strerror (err);
2985 }