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