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