]> Pileus Git - ~andy/gtk/blob - gtk/gtkfilesel.c
Merges from gtk-1-2
[~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     {
677       gtk_widget_destroy (filesel->fileop_ren_file);
678       filesel->fileop_ren_file = NULL;
679     }
680
681   if (filesel->fileop_del_file)
682     {
683       gtk_widget_destroy (filesel->fileop_del_file);
684       filesel->fileop_del_file = NULL;
685     }
686
687   if (filesel->fileop_c_dir)
688     {
689       gtk_widget_destroy (filesel->fileop_c_dir);
690       filesel->fileop_c_dir = NULL;
691     }
692 }
693
694
695
696 void
697 gtk_file_selection_set_filename (GtkFileSelection *filesel,
698                                  const gchar      *filename)
699 {
700   gchar *buf;
701   const char *name, *last_slash;
702
703   g_return_if_fail (filesel != NULL);
704   g_return_if_fail (GTK_IS_FILE_SELECTION (filesel));
705   g_return_if_fail (filename != NULL);
706
707   last_slash = strrchr (filename, G_DIR_SEPARATOR);
708
709   if (!last_slash)
710     {
711       buf = g_strdup ("");
712       name = filename;
713     }
714   else
715     {
716       buf = g_strdup (filename);
717       buf[last_slash - filename + 1] = 0;
718       name = last_slash + 1;
719     }
720
721   gtk_file_selection_populate (filesel, buf, FALSE);
722
723   if (filesel->selection_entry)
724     gtk_entry_set_text (GTK_ENTRY (filesel->selection_entry), name);
725   g_free (buf);
726 }
727
728 gchar*
729 gtk_file_selection_get_filename (GtkFileSelection *filesel)
730 {
731   static gchar nothing[2] = "";
732   static gchar something[MAXPATHLEN*2];
733   char *filename;
734   char *text;
735
736   g_return_val_if_fail (filesel != NULL, nothing);
737   g_return_val_if_fail (GTK_IS_FILE_SELECTION (filesel), nothing);
738
739 #ifdef G_WITH_CYGWIN
740   translate_win32_path(filesel);
741 #endif
742   text = gtk_entry_get_text (GTK_ENTRY (filesel->selection_entry));
743   if (text)
744     {
745       filename = g_filename_from_utf8 (cmpl_completion_fullname (text, filesel->cmpl_state));
746       strncpy (something, filename, sizeof (something));
747       g_free (filename);
748       return something;
749     }
750
751   return nothing;
752 }
753
754 void
755 gtk_file_selection_complete (GtkFileSelection *filesel,
756                              const gchar      *pattern)
757 {
758   g_return_if_fail (filesel != NULL);
759   g_return_if_fail (GTK_IS_FILE_SELECTION (filesel));
760   g_return_if_fail (pattern != NULL);
761
762   if (filesel->selection_entry)
763     gtk_entry_set_text (GTK_ENTRY (filesel->selection_entry), pattern);
764   gtk_file_selection_populate (filesel, (gchar*) pattern, TRUE);
765 }
766
767 static void
768 gtk_file_selection_destroy (GtkObject *object)
769 {
770   GtkFileSelection *filesel;
771   GList *list;
772   HistoryCallbackArg *callback_arg;
773
774   g_return_if_fail (object != NULL);
775   g_return_if_fail (GTK_IS_FILE_SELECTION (object));
776
777   filesel = GTK_FILE_SELECTION (object);
778   
779   if (filesel->fileop_dialog)
780           gtk_widget_destroy (filesel->fileop_dialog);
781   
782   if (filesel->history_list)
783     {
784       list = filesel->history_list;
785       while (list)
786         {
787           callback_arg = list->data;
788           g_free (callback_arg->directory);
789           g_free (callback_arg);
790           list = list->next;
791         }
792       g_list_free (filesel->history_list);
793       filesel->history_list = NULL;
794     }
795   
796   cmpl_free_state (filesel->cmpl_state);
797   filesel->cmpl_state = NULL;
798
799   if (GTK_OBJECT_CLASS (parent_class)->destroy)
800     (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
801 }
802
803 /* Begin file operations callbacks */
804
805 static void
806 gtk_file_selection_fileop_error (GtkFileSelection *fs, gchar *error_message)
807 {
808   GtkWidget *label;
809   GtkWidget *vbox;
810   GtkWidget *button;
811   GtkWidget *dialog;
812   
813   g_return_if_fail (error_message != NULL);
814   
815   /* main dialog */
816   dialog = gtk_dialog_new ();
817   /*
818   gtk_signal_connect (GTK_OBJECT (dialog), "destroy",
819                       (GtkSignalFunc) gtk_file_selection_fileop_destroy, 
820                       (gpointer) fs);
821   */
822   gtk_window_set_title (GTK_WINDOW (dialog), _("Error"));
823   gtk_window_set_position (GTK_WINDOW (dialog), GTK_WIN_POS_MOUSE);
824   
825   /* If file dialog is grabbed, make this dialog modal too */
826   /* When error dialog is closed, file dialog will be grabbed again */
827   if (GTK_WINDOW(fs)->modal)
828       gtk_window_set_modal (GTK_WINDOW(dialog), TRUE);
829
830   vbox = gtk_vbox_new(FALSE, 0);
831   gtk_container_set_border_width(GTK_CONTAINER(vbox), 8);
832   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), vbox,
833                      FALSE, FALSE, 0);
834   gtk_widget_show(vbox);
835
836   label = gtk_label_new(error_message);
837   gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
838   gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 5);
839   gtk_widget_show(label);
840
841   /* yes, we free it */
842   g_free (error_message);
843   
844   /* close button */
845   button = gtk_button_new_with_label (_("Close"));
846   gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
847                              (GtkSignalFunc) gtk_widget_destroy, 
848                              (gpointer) dialog);
849   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),
850                      button, TRUE, TRUE, 0);
851   GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
852   gtk_widget_grab_default(button);
853   gtk_widget_show (button);
854
855   gtk_widget_show (dialog);
856 }
857
858 static void
859 gtk_file_selection_fileop_destroy (GtkWidget *widget, gpointer data)
860 {
861   GtkFileSelection *fs = data;
862
863   g_return_if_fail (fs != NULL);
864   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
865   
866   fs->fileop_dialog = NULL;
867 }
868
869
870 static void
871 gtk_file_selection_create_dir_confirmed (GtkWidget *widget, gpointer data)
872 {
873   GtkFileSelection *fs = data;
874   gchar *dirname;
875   gchar *path;
876   gchar *full_path;
877   gchar *buf;
878   CompletionState *cmpl_state;
879   
880   g_return_if_fail (fs != NULL);
881   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
882
883   dirname = gtk_entry_get_text (GTK_ENTRY (fs->fileop_entry));
884   cmpl_state = (CompletionState*) fs->cmpl_state;
885   path = cmpl_reference_position (cmpl_state);
886   
887   full_path = g_strconcat (path, G_DIR_SEPARATOR_S, dirname, NULL);
888   if ( (mkdir (full_path, 0755) < 0) ) 
889     {
890       buf = g_strconcat ("Error creating directory \"", dirname, "\":  ", 
891                          g_strerror(errno), NULL);
892       gtk_file_selection_fileop_error (fs, buf);
893     }
894   g_free (full_path);
895   
896   gtk_widget_destroy (fs->fileop_dialog);
897   gtk_file_selection_populate (fs, "", FALSE);
898 }
899   
900 static void
901 gtk_file_selection_create_dir (GtkWidget *widget, gpointer data)
902 {
903   GtkFileSelection *fs = data;
904   GtkWidget *label;
905   GtkWidget *dialog;
906   GtkWidget *vbox;
907   GtkWidget *button;
908
909   g_return_if_fail (fs != NULL);
910   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
911
912   if (fs->fileop_dialog)
913           return;
914   
915   /* main dialog */
916   fs->fileop_dialog = dialog = gtk_dialog_new ();
917   gtk_signal_connect (GTK_OBJECT (dialog), "destroy",
918                       (GtkSignalFunc) gtk_file_selection_fileop_destroy, 
919                       (gpointer) fs);
920   gtk_window_set_title (GTK_WINDOW (dialog), _("Create Directory"));
921   gtk_window_set_position (GTK_WINDOW (dialog), GTK_WIN_POS_MOUSE);
922
923   /* If file dialog is grabbed, grab option dialog */
924   /* When option dialog is closed, file dialog will be grabbed again */
925   if (GTK_WINDOW(fs)->modal)
926       gtk_window_set_modal (GTK_WINDOW(dialog), TRUE);
927
928   vbox = gtk_vbox_new(FALSE, 0);
929   gtk_container_set_border_width(GTK_CONTAINER(vbox), 8);
930   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), vbox,
931                      FALSE, FALSE, 0);
932   gtk_widget_show(vbox);
933   
934   label = gtk_label_new(_("Directory name:"));
935   gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
936   gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 5);
937   gtk_widget_show(label);
938
939   /*  The directory entry widget  */
940   fs->fileop_entry = gtk_entry_new ();
941   gtk_box_pack_start (GTK_BOX (vbox), fs->fileop_entry, 
942                       TRUE, TRUE, 5);
943   GTK_WIDGET_SET_FLAGS(fs->fileop_entry, GTK_CAN_DEFAULT);
944   gtk_widget_show (fs->fileop_entry);
945   
946   /* buttons */
947   button = gtk_button_new_with_label (_("Create"));
948   gtk_signal_connect (GTK_OBJECT (button), "clicked",
949                       (GtkSignalFunc) gtk_file_selection_create_dir_confirmed, 
950                       (gpointer) fs);
951   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),
952                      button, TRUE, TRUE, 0);
953   GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
954   gtk_widget_show(button);
955   
956   button = gtk_button_new_with_label (_("Cancel"));
957   gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
958                              (GtkSignalFunc) gtk_widget_destroy, 
959                              (gpointer) dialog);
960   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),
961                      button, TRUE, TRUE, 0);
962   GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
963   gtk_widget_grab_default(button);
964   gtk_widget_show (button);
965
966   gtk_widget_show (dialog);
967 }
968
969 static void
970 gtk_file_selection_delete_file_confirmed (GtkWidget *widget, gpointer data)
971 {
972   GtkFileSelection *fs = data;
973   CompletionState *cmpl_state;
974   gchar *path;
975   gchar *full_path;
976   gchar *buf;
977   
978   g_return_if_fail (fs != NULL);
979   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
980
981   cmpl_state = (CompletionState*) fs->cmpl_state;
982   path = cmpl_reference_position (cmpl_state);
983   
984   full_path = g_strconcat (path, G_DIR_SEPARATOR_S, fs->fileop_file, NULL);
985   if ( (unlink (full_path) < 0) ) 
986     {
987       buf = g_strconcat ("Error deleting file \"", fs->fileop_file, "\":  ", 
988                          g_strerror(errno), NULL);
989       gtk_file_selection_fileop_error (fs, buf);
990     }
991   g_free (full_path);
992   
993   gtk_widget_destroy (fs->fileop_dialog);
994   gtk_file_selection_populate (fs, "", FALSE);
995 }
996
997 static void
998 gtk_file_selection_delete_file (GtkWidget *widget, gpointer data)
999 {
1000   GtkFileSelection *fs = data;
1001   GtkWidget *label;
1002   GtkWidget *vbox;
1003   GtkWidget *button;
1004   GtkWidget *dialog;
1005   gchar *filename;
1006   gchar *buf;
1007   
1008   g_return_if_fail (fs != NULL);
1009   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1010
1011   if (fs->fileop_dialog)
1012           return;
1013
1014 #ifdef G_WITH_CYGWIN
1015   translate_win32_path(fs);
1016 #endif
1017
1018   filename = gtk_entry_get_text (GTK_ENTRY (fs->selection_entry));
1019   if (strlen(filename) < 1)
1020           return;
1021
1022   fs->fileop_file = filename;
1023   
1024   /* main dialog */
1025   fs->fileop_dialog = dialog = gtk_dialog_new ();
1026   gtk_signal_connect (GTK_OBJECT (dialog), "destroy",
1027                       (GtkSignalFunc) gtk_file_selection_fileop_destroy, 
1028                       (gpointer) fs);
1029   gtk_window_set_title (GTK_WINDOW (dialog), _("Delete File"));
1030   gtk_window_set_position (GTK_WINDOW (dialog), GTK_WIN_POS_MOUSE);
1031
1032   /* If file dialog is grabbed, grab option dialog */
1033   /* When option dialog is closed, file dialog will be grabbed again */
1034   if (GTK_WINDOW(fs)->modal)
1035       gtk_window_set_modal (GTK_WINDOW(dialog), TRUE);
1036   
1037   vbox = gtk_vbox_new(FALSE, 0);
1038   gtk_container_set_border_width(GTK_CONTAINER(vbox), 8);
1039   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), vbox,
1040                      FALSE, FALSE, 0);
1041   gtk_widget_show(vbox);
1042
1043   buf = g_strconcat ("Really delete file \"", filename, "\" ?", NULL);
1044   label = gtk_label_new(buf);
1045   gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
1046   gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 5);
1047   gtk_widget_show(label);
1048   g_free(buf);
1049   
1050   /* buttons */
1051   button = gtk_button_new_with_label (_("Delete"));
1052   gtk_signal_connect (GTK_OBJECT (button), "clicked",
1053                       (GtkSignalFunc) gtk_file_selection_delete_file_confirmed, 
1054                       (gpointer) fs);
1055   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),
1056                      button, TRUE, TRUE, 0);
1057   GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1058   gtk_widget_show(button);
1059   
1060   button = gtk_button_new_with_label (_("Cancel"));
1061   gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
1062                              (GtkSignalFunc) gtk_widget_destroy, 
1063                              (gpointer) dialog);
1064   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),
1065                      button, TRUE, TRUE, 0);
1066   GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1067   gtk_widget_grab_default(button);
1068   gtk_widget_show (button);
1069
1070   gtk_widget_show (dialog);
1071
1072 }
1073
1074 static void
1075 gtk_file_selection_rename_file_confirmed (GtkWidget *widget, gpointer data)
1076 {
1077   GtkFileSelection *fs = data;
1078   gchar *buf;
1079   gchar *file;
1080   gchar *path;
1081   gchar *new_filename;
1082   gchar *old_filename;
1083   CompletionState *cmpl_state;
1084   
1085   g_return_if_fail (fs != NULL);
1086   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1087
1088   file = gtk_entry_get_text (GTK_ENTRY (fs->fileop_entry));
1089   cmpl_state = (CompletionState*) fs->cmpl_state;
1090   path = cmpl_reference_position (cmpl_state);
1091   
1092   new_filename = g_strconcat (path, G_DIR_SEPARATOR_S, file, NULL);
1093   old_filename = g_strconcat (path, G_DIR_SEPARATOR_S, fs->fileop_file, NULL);
1094
1095   if ( (rename (old_filename, new_filename)) < 0) 
1096     {
1097       buf = g_strconcat ("Error renaming file \"", file, "\":  ", 
1098                          g_strerror(errno), NULL);
1099       gtk_file_selection_fileop_error (fs, buf);
1100     }
1101   g_free (new_filename);
1102   g_free (old_filename);
1103   
1104   gtk_widget_destroy (fs->fileop_dialog);
1105   gtk_file_selection_populate (fs, "", FALSE);
1106 }
1107   
1108 static void
1109 gtk_file_selection_rename_file (GtkWidget *widget, gpointer data)
1110 {
1111   GtkFileSelection *fs = data;
1112   GtkWidget *label;
1113   GtkWidget *dialog;
1114   GtkWidget *vbox;
1115   GtkWidget *button;
1116   gchar *buf;
1117   
1118   g_return_if_fail (fs != NULL);
1119   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1120
1121   if (fs->fileop_dialog)
1122           return;
1123
1124   fs->fileop_file = gtk_entry_get_text (GTK_ENTRY (fs->selection_entry));
1125   if (strlen(fs->fileop_file) < 1)
1126           return;
1127   
1128   /* main dialog */
1129   fs->fileop_dialog = dialog = gtk_dialog_new ();
1130   gtk_signal_connect (GTK_OBJECT (dialog), "destroy",
1131                       (GtkSignalFunc) gtk_file_selection_fileop_destroy, 
1132                       (gpointer) fs);
1133   gtk_window_set_title (GTK_WINDOW (dialog), _("Rename File"));
1134   gtk_window_set_position (GTK_WINDOW (dialog), GTK_WIN_POS_MOUSE);
1135
1136   /* If file dialog is grabbed, grab option dialog */
1137   /* When option dialog  closed, file dialog will be grabbed again */
1138   if (GTK_WINDOW(fs)->modal)
1139     gtk_window_set_modal (GTK_WINDOW(dialog), TRUE);
1140   
1141   vbox = gtk_vbox_new(FALSE, 0);
1142   gtk_container_set_border_width (GTK_CONTAINER(vbox), 8);
1143   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), vbox,
1144                      FALSE, FALSE, 0);
1145   gtk_widget_show(vbox);
1146   
1147   buf = g_strconcat ("Rename file \"", fs->fileop_file, "\" to:", NULL);
1148   label = gtk_label_new(buf);
1149   gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
1150   gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 5);
1151   gtk_widget_show(label);
1152   g_free(buf);
1153
1154   /* New filename entry */
1155   fs->fileop_entry = gtk_entry_new ();
1156   gtk_box_pack_start (GTK_BOX (vbox), fs->fileop_entry, 
1157                       TRUE, TRUE, 5);
1158   GTK_WIDGET_SET_FLAGS(fs->fileop_entry, GTK_CAN_DEFAULT);
1159   gtk_widget_show (fs->fileop_entry);
1160   
1161   gtk_entry_set_text (GTK_ENTRY (fs->fileop_entry), fs->fileop_file);
1162   gtk_editable_select_region (GTK_EDITABLE (fs->fileop_entry),
1163                               0, strlen (fs->fileop_file));
1164
1165   /* buttons */
1166   button = gtk_button_new_with_label (_("Rename"));
1167   gtk_signal_connect (GTK_OBJECT (button), "clicked",
1168                       (GtkSignalFunc) gtk_file_selection_rename_file_confirmed, 
1169                       (gpointer) fs);
1170   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),
1171                      button, TRUE, TRUE, 0);
1172   GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1173   gtk_widget_show(button);
1174   
1175   button = gtk_button_new_with_label (_("Cancel"));
1176   gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
1177                              (GtkSignalFunc) gtk_widget_destroy, 
1178                              (gpointer) dialog);
1179   gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),
1180                      button, TRUE, TRUE, 0);
1181   GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1182   gtk_widget_grab_default(button);
1183   gtk_widget_show (button);
1184
1185   gtk_widget_show (dialog);
1186 }
1187
1188
1189 static gint
1190 gtk_file_selection_key_press (GtkWidget   *widget,
1191                               GdkEventKey *event,
1192                               gpointer     user_data)
1193 {
1194   GtkFileSelection *fs;
1195   char *text;
1196
1197   g_return_val_if_fail (widget != NULL, FALSE);
1198   g_return_val_if_fail (event != NULL, FALSE);
1199
1200   if (event->keyval == GDK_Tab)
1201     {
1202       fs = GTK_FILE_SELECTION (user_data);
1203 #ifdef G_WITH_CYGWIN
1204       translate_win32_path(fs);
1205 #endif
1206       text = gtk_entry_get_text (GTK_ENTRY (fs->selection_entry));
1207
1208       text = g_strdup (text);
1209
1210       gtk_file_selection_populate (fs, text, TRUE);
1211
1212       g_free (text);
1213
1214       gtk_signal_emit_stop_by_name (GTK_OBJECT (widget), "key_press_event");
1215
1216       return TRUE;
1217     }
1218
1219   return FALSE;
1220 }
1221
1222
1223 static void
1224 gtk_file_selection_history_callback (GtkWidget *widget, gpointer data)
1225 {
1226   GtkFileSelection *fs = data;
1227   HistoryCallbackArg *callback_arg;
1228   GList *list;
1229
1230   g_return_if_fail (fs != NULL);
1231   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1232
1233   list = fs->history_list;
1234   
1235   while (list) {
1236     callback_arg = list->data;
1237     
1238     if (callback_arg->menu_item == widget)
1239       {
1240         gtk_file_selection_populate (fs, callback_arg->directory, FALSE);
1241         break;
1242       }
1243     
1244     list = list->next;
1245   }
1246 }
1247
1248 static void 
1249 gtk_file_selection_update_history_menu (GtkFileSelection *fs,
1250                                         gchar *current_directory)
1251 {
1252   HistoryCallbackArg *callback_arg;
1253   GtkWidget *menu_item;
1254   GList *list;
1255   gchar *current_dir;
1256   gint dir_len;
1257   gint i;
1258   
1259   g_return_if_fail (fs != NULL);
1260   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1261   g_return_if_fail (current_directory != NULL);
1262   
1263   list = fs->history_list;
1264
1265   if (fs->history_menu) 
1266     {
1267       while (list) {
1268         callback_arg = list->data;
1269         g_free (callback_arg->directory);
1270         g_free (callback_arg);
1271         list = list->next;
1272       }
1273       g_list_free (fs->history_list);
1274       fs->history_list = NULL;
1275       
1276       gtk_widget_destroy (fs->history_menu);
1277     }
1278   
1279   fs->history_menu = gtk_menu_new();
1280
1281   current_dir = g_strdup (current_directory);
1282
1283   dir_len = strlen (current_dir);
1284
1285   for (i = dir_len; i >= 0; i--)
1286     {
1287       /* the i == dir_len is to catch the full path for the first 
1288        * entry. */
1289       if ( (current_dir[i] == G_DIR_SEPARATOR) || (i == dir_len))
1290         {
1291           /* another small hack to catch the full path */
1292           if (i != dir_len) 
1293                   current_dir[i + 1] = '\0';
1294 #ifdef G_WITH_CYGWIN
1295           if (!strcmp(current_dir, "//"))
1296             continue;
1297 #endif
1298           menu_item = gtk_menu_item_new_with_label (current_dir);
1299           
1300           callback_arg = g_new (HistoryCallbackArg, 1);
1301           callback_arg->menu_item = menu_item;
1302           
1303           /* since the autocompletion gets confused if you don't 
1304            * supply a trailing '/' on a dir entry, set the full
1305            * (current) path to "" which just refreshes the filesel */
1306           if (dir_len == i)
1307             {
1308               callback_arg->directory = g_strdup ("");
1309             }
1310           else
1311             {
1312               callback_arg->directory = g_strdup (current_dir);
1313             }
1314           
1315           fs->history_list = g_list_append (fs->history_list, callback_arg);
1316           
1317           gtk_signal_connect (GTK_OBJECT (menu_item), "activate",
1318                               (GtkSignalFunc) gtk_file_selection_history_callback,
1319                               (gpointer) fs);
1320           gtk_menu_append (GTK_MENU (fs->history_menu), menu_item);
1321           gtk_widget_show (menu_item);
1322         }
1323     }
1324
1325   gtk_option_menu_set_menu (GTK_OPTION_MENU (fs->history_pulldown), 
1326                             fs->history_menu);
1327   g_free (current_dir);
1328 }
1329
1330 static void
1331 gtk_file_selection_file_button (GtkWidget *widget,
1332                                gint row, 
1333                                gint column, 
1334                                GdkEventButton *bevent,
1335                                gpointer user_data)
1336 {
1337   GtkFileSelection *fs = NULL;
1338   gchar *filename, *temp = NULL;
1339   
1340   g_return_if_fail (GTK_IS_CLIST (widget));
1341
1342   fs = user_data;
1343   g_return_if_fail (fs != NULL);
1344   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1345   
1346   gtk_clist_get_text (GTK_CLIST (fs->file_list), row, 0, &temp);
1347   filename = g_strdup (temp);
1348
1349 #ifdef G_WITH_CYGWIN
1350   /* Check to see if the selection was a drive selector */
1351   if (isalpha(filename[0]) && (filename[1] == ':')) {
1352     /* It is... map it to a CYGWIN32 drive */
1353     char temp_filename[10];
1354
1355     sprintf(temp_filename, "//%c/", tolower(filename[0]));
1356     g_free(filename);
1357     filename = g_strdup(temp_filename);
1358   }
1359 #endif /* G_WITH_CYGWIN */
1360
1361   if (filename)
1362     {
1363       if (bevent)
1364         switch (bevent->type)
1365           {
1366           case GDK_2BUTTON_PRESS:
1367             gtk_button_clicked (GTK_BUTTON (fs->ok_button));
1368             break;
1369             
1370           default:
1371             gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), filename);
1372             break;
1373           }
1374       else
1375         gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), filename);
1376
1377       g_free (filename);
1378     }
1379 }
1380
1381 static void
1382 gtk_file_selection_dir_button (GtkWidget *widget,
1383                                gint row, 
1384                                gint column, 
1385                                GdkEventButton *bevent,
1386                                gpointer user_data)
1387 {
1388   GtkFileSelection *fs = NULL;
1389   gchar *filename, *temp = NULL;
1390
1391   g_return_if_fail (GTK_IS_CLIST (widget));
1392
1393   fs = GTK_FILE_SELECTION (user_data);
1394   g_return_if_fail (fs != NULL);
1395   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1396
1397   gtk_clist_get_text (GTK_CLIST (fs->dir_list), row, 0, &temp);
1398   filename = g_strdup (temp);
1399
1400   if (filename)
1401     {
1402       if (bevent)
1403         switch (bevent->type)
1404           {
1405           case GDK_2BUTTON_PRESS:
1406             gtk_file_selection_populate (fs, filename, FALSE);
1407             break;
1408           
1409           default:
1410             gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), filename);
1411             break;
1412           }
1413       else
1414         gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), filename);
1415
1416       g_free (filename);
1417     }
1418 }
1419
1420 #if defined(G_OS_WIN32) || defined(G_WITH_CYGWIN)
1421
1422 static void
1423 win32_gtk_add_drives_to_dir_list(GtkWidget *the_dir_list)
1424 {
1425   gchar *text[2], *textPtr;
1426   gchar buffer[128];
1427   char volumeNameBuf[128];
1428   char formatBuffer[128];
1429   gint row;
1430
1431   text[1] = NULL;
1432
1433   /* Get the Drives string */
1434   GetLogicalDriveStrings(sizeof(buffer), buffer);
1435
1436   /* Add the drives as necessary */
1437   textPtr = buffer;
1438   while (*textPtr != '\0') {
1439     /* Get the volume information for this drive */
1440     if ((tolower(textPtr[0]) != 'a') && (tolower(textPtr[0]) != 'b'))
1441       {
1442         /* Ignore floppies (?) */
1443         DWORD maxComponentLength, flags;
1444
1445         GetVolumeInformation(textPtr,
1446                              volumeNameBuf, sizeof(volumeNameBuf),
1447                              NULL, &maxComponentLength,
1448                              &flags, NULL, 0);
1449         /* Build the actual displayable string */
1450
1451         sprintf(formatBuffer, "%c:\\", toupper(textPtr[0]));
1452 #if 0 /* HB: removed to allow drive change AND directory update with one click */
1453         if (strlen(volumeNameBuf) > 0)
1454           sprintf(formatBuffer, "%s (%s)", formatBuffer, volumeNameBuf);
1455 #endif
1456         /* Add to the list */
1457         text[0] = formatBuffer;
1458         row = gtk_clist_append (GTK_CLIST (the_dir_list), text);
1459       }
1460     textPtr += (strlen(textPtr) + 1);
1461   }
1462 }
1463 #endif
1464
1465 static void
1466 gtk_file_selection_populate (GtkFileSelection *fs,
1467                              gchar            *rel_path,
1468                              gint              try_complete)
1469 {
1470   CompletionState *cmpl_state;
1471   PossibleCompletion* poss;
1472   gchar* filename;
1473   gint row;
1474   gchar* rem_path = rel_path;
1475   gchar* sel_text;
1476   gchar* text[2];
1477   gint did_recurse = FALSE;
1478   gint possible_count = 0;
1479   gint selection_index = -1;
1480   gint file_list_width;
1481   gint dir_list_width;
1482   
1483   g_return_if_fail (fs != NULL);
1484   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1485   
1486   cmpl_state = (CompletionState*) fs->cmpl_state;
1487   poss = cmpl_completion_matches (rel_path, &rem_path, cmpl_state);
1488
1489   if (!cmpl_state_okay (cmpl_state))
1490     {
1491       /* Something went wrong. */
1492       gtk_file_selection_abort (fs);
1493       return;
1494     }
1495
1496   g_assert (cmpl_state->reference_dir);
1497
1498   gtk_clist_freeze (GTK_CLIST (fs->dir_list));
1499   gtk_clist_clear (GTK_CLIST (fs->dir_list));
1500   gtk_clist_freeze (GTK_CLIST (fs->file_list));
1501   gtk_clist_clear (GTK_CLIST (fs->file_list));
1502
1503   /* Set the dir_list to include ./ and ../ */
1504   text[1] = NULL;
1505   text[0] = "." G_DIR_SEPARATOR_S;
1506   row = gtk_clist_append (GTK_CLIST (fs->dir_list), text);
1507
1508   text[0] = ".." G_DIR_SEPARATOR_S;
1509   row = gtk_clist_append (GTK_CLIST (fs->dir_list), text);
1510
1511   /*reset the max widths of the lists*/
1512   dir_list_width = gdk_string_width(fs->dir_list->style->font,".." G_DIR_SEPARATOR_S);
1513   gtk_clist_set_column_width(GTK_CLIST(fs->dir_list),0,dir_list_width);
1514   file_list_width = 1;
1515   gtk_clist_set_column_width(GTK_CLIST(fs->file_list),0,file_list_width);
1516
1517   while (poss)
1518     {
1519       if (cmpl_is_a_completion (poss))
1520         {
1521           possible_count += 1;
1522
1523           filename = cmpl_this_completion (poss);
1524
1525           text[0] = filename;
1526           
1527           if (cmpl_is_directory (poss))
1528             {
1529               if (strcmp (filename, "." G_DIR_SEPARATOR_S) != 0 &&
1530                   strcmp (filename, ".." G_DIR_SEPARATOR_S) != 0)
1531                 {
1532                   int width = gdk_string_width(fs->dir_list->style->font,
1533                                                filename);
1534                   row = gtk_clist_append (GTK_CLIST (fs->dir_list), text);
1535                   if(width > dir_list_width)
1536                     {
1537                       dir_list_width = width;
1538                       gtk_clist_set_column_width(GTK_CLIST(fs->dir_list),0,
1539                                                  width);
1540                     }
1541                 }
1542             }
1543           else
1544             {
1545               int width = gdk_string_width(fs->file_list->style->font,
1546                                            filename);
1547               row = gtk_clist_append (GTK_CLIST (fs->file_list), text);
1548               if(width > file_list_width)
1549                 {
1550                   file_list_width = width;
1551                   gtk_clist_set_column_width(GTK_CLIST(fs->file_list),0,
1552                                              width);
1553                 }
1554             }
1555         }
1556
1557       poss = cmpl_next_completion (cmpl_state);
1558     }
1559
1560 #if defined(G_OS_WIN32) || defined(G_WITH_CYGWIN)
1561   /* For Windows, add drives as potential selections */
1562   win32_gtk_add_drives_to_dir_list (fs->dir_list);
1563 #endif
1564
1565   gtk_clist_thaw (GTK_CLIST (fs->dir_list));
1566   gtk_clist_thaw (GTK_CLIST (fs->file_list));
1567
1568   /* File lists are set. */
1569
1570   g_assert (cmpl_state->reference_dir);
1571
1572   if (try_complete)
1573     {
1574
1575       /* User is trying to complete filenames, so advance the user's input
1576        * string to the updated_text, which is the common leading substring
1577        * of all possible completions, and if its a directory attempt
1578        * attempt completions in it. */
1579
1580       if (cmpl_updated_text (cmpl_state)[0])
1581         {
1582
1583           if (cmpl_updated_dir (cmpl_state))
1584             {
1585               gchar* dir_name = g_strdup (cmpl_updated_text (cmpl_state));
1586
1587               did_recurse = TRUE;
1588
1589               gtk_file_selection_populate (fs, dir_name, TRUE);
1590
1591               g_free (dir_name);
1592             }
1593           else
1594             {
1595               if (fs->selection_entry)
1596                       gtk_entry_set_text (GTK_ENTRY (fs->selection_entry),
1597                                           cmpl_updated_text (cmpl_state));
1598             }
1599         }
1600       else
1601         {
1602           selection_index = cmpl_last_valid_char (cmpl_state) -
1603                             (strlen (rel_path) - strlen (rem_path));
1604           if (fs->selection_entry)
1605             gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), rem_path);
1606         }
1607     }
1608   else
1609     {
1610       if (fs->selection_entry)
1611         gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), "");
1612     }
1613
1614   if (!did_recurse)
1615     {
1616       if (fs->selection_entry)
1617         gtk_entry_set_position (GTK_ENTRY (fs->selection_entry), selection_index);
1618
1619       if (fs->selection_entry)
1620         {
1621           sel_text = g_strconcat (_("Selection: "),
1622                                   cmpl_reference_position (cmpl_state),
1623                                   NULL);
1624
1625           gtk_label_set_text (GTK_LABEL (fs->selection_text), sel_text);
1626           g_free (sel_text);
1627         }
1628
1629       if (fs->history_pulldown) 
1630         {
1631           gtk_file_selection_update_history_menu (fs, cmpl_reference_position (cmpl_state));
1632         }
1633       
1634     }
1635 }
1636
1637 static void
1638 gtk_file_selection_abort (GtkFileSelection *fs)
1639 {
1640   gchar err_buf[256];
1641
1642   sprintf (err_buf, _("Directory unreadable: %s"), cmpl_strerror (cmpl_errno));
1643
1644   /*  BEEP gdk_beep();  */
1645
1646   if (fs->selection_entry)
1647     gtk_label_set_text (GTK_LABEL (fs->selection_text), err_buf);
1648 }
1649
1650 /**********************************************************************/
1651 /*                        External Interface                          */
1652 /**********************************************************************/
1653
1654 /* The four completion state selectors
1655  */
1656 static gchar*
1657 cmpl_updated_text (CompletionState* cmpl_state)
1658 {
1659   return cmpl_state->updated_text;
1660 }
1661
1662 static gboolean
1663 cmpl_updated_dir (CompletionState* cmpl_state)
1664 {
1665   return cmpl_state->re_complete;
1666 }
1667
1668 static gchar*
1669 cmpl_reference_position (CompletionState* cmpl_state)
1670 {
1671   return cmpl_state->reference_dir->fullname;
1672 }
1673
1674 static gint
1675 cmpl_last_valid_char (CompletionState* cmpl_state)
1676 {
1677   return cmpl_state->last_valid_char;
1678 }
1679
1680 static gchar*
1681 cmpl_completion_fullname (gchar* text, CompletionState* cmpl_state)
1682 {
1683   static char nothing[2] = "";
1684
1685   if (!cmpl_state_okay (cmpl_state))
1686     {
1687       return nothing;
1688     }
1689   else if (g_path_is_absolute (text))
1690     {
1691       strcpy (cmpl_state->updated_text, text);
1692     }
1693 #ifdef HAVE_PWD_H
1694   else if (text[0] == '~')
1695     {
1696       CompletionDir* dir;
1697       char* slash;
1698
1699       dir = open_user_dir (text, cmpl_state);
1700
1701       if (!dir)
1702         {
1703           /* spencer says just return ~something, so
1704            * for now just do it. */
1705           strcpy (cmpl_state->updated_text, text);
1706         }
1707       else
1708         {
1709
1710           strcpy (cmpl_state->updated_text, dir->fullname);
1711
1712           slash = strchr (text, G_DIR_SEPARATOR);
1713
1714           if (slash)
1715             strcat (cmpl_state->updated_text, slash);
1716         }
1717     }
1718 #endif
1719   else
1720     {
1721       strcpy (cmpl_state->updated_text, cmpl_state->reference_dir->fullname);
1722       if (cmpl_state->updated_text[strlen (cmpl_state->updated_text) - 1] != G_DIR_SEPARATOR)
1723         strcat (cmpl_state->updated_text, G_DIR_SEPARATOR_S);
1724       strcat (cmpl_state->updated_text, text);
1725     }
1726
1727   return cmpl_state->updated_text;
1728 }
1729
1730 /* The three completion selectors
1731  */
1732 static gchar*
1733 cmpl_this_completion (PossibleCompletion* pc)
1734 {
1735   return pc->text;
1736 }
1737
1738 static gboolean
1739 cmpl_is_directory (PossibleCompletion* pc)
1740 {
1741   return pc->is_directory;
1742 }
1743
1744 static gint
1745 cmpl_is_a_completion (PossibleCompletion* pc)
1746 {
1747   return pc->is_a_completion;
1748 }
1749
1750 /**********************************************************************/
1751 /*                       Construction, deletion                       */
1752 /**********************************************************************/
1753
1754 static CompletionState*
1755 cmpl_init_state (void)
1756 {
1757   gchar *getcwd_buf;
1758   CompletionState *new_state;
1759
1760   new_state = g_new (CompletionState, 1);
1761
1762   getcwd_buf = g_get_current_dir ();
1763
1764 tryagain:
1765
1766   new_state->reference_dir = NULL;
1767   new_state->completion_dir = NULL;
1768   new_state->active_completion_dir = NULL;
1769   new_state->directory_storage = NULL;
1770   new_state->directory_sent_storage = NULL;
1771   new_state->last_valid_char = 0;
1772   new_state->updated_text = g_new (gchar, MAXPATHLEN);
1773   new_state->updated_text_alloc = MAXPATHLEN;
1774   new_state->the_completion.text = g_new (gchar, MAXPATHLEN);
1775   new_state->the_completion.text_alloc = MAXPATHLEN;
1776   new_state->user_dir_name_buffer = NULL;
1777   new_state->user_directories = NULL;
1778
1779   new_state->reference_dir =  open_dir (getcwd_buf, new_state);
1780
1781   if (!new_state->reference_dir)
1782     {
1783       /* Directories changing from underneath us, grumble */
1784       strcpy (getcwd_buf, G_DIR_SEPARATOR_S);
1785       goto tryagain;
1786     }
1787
1788   g_free (getcwd_buf);
1789   return new_state;
1790 }
1791
1792 static void
1793 cmpl_free_dir_list(GList* dp0)
1794 {
1795   GList *dp = dp0;
1796
1797   while (dp) {
1798     free_dir (dp->data);
1799     dp = dp->next;
1800   }
1801
1802   g_list_free(dp0);
1803 }
1804
1805 static void
1806 cmpl_free_dir_sent_list(GList* dp0)
1807 {
1808   GList *dp = dp0;
1809
1810   while (dp) {
1811     free_dir_sent (dp->data);
1812     dp = dp->next;
1813   }
1814
1815   g_list_free(dp0);
1816 }
1817
1818 static void
1819 cmpl_free_state (CompletionState* cmpl_state)
1820 {
1821   cmpl_free_dir_list (cmpl_state->directory_storage);
1822   cmpl_free_dir_sent_list (cmpl_state->directory_sent_storage);
1823
1824   if (cmpl_state->user_dir_name_buffer)
1825     g_free (cmpl_state->user_dir_name_buffer);
1826   if (cmpl_state->user_directories)
1827     g_free (cmpl_state->user_directories);
1828   if (cmpl_state->the_completion.text)
1829     g_free (cmpl_state->the_completion.text);
1830   if (cmpl_state->updated_text)
1831     g_free (cmpl_state->updated_text);
1832
1833   g_free (cmpl_state);
1834 }
1835
1836 static void
1837 free_dir(CompletionDir* dir)
1838 {
1839   g_free(dir->fullname);
1840   g_free(dir);
1841 }
1842
1843 static void
1844 free_dir_sent(CompletionDirSent* sent)
1845 {
1846   gint i;
1847   for (i = 0; i < sent->entry_count; i++)
1848     g_free(sent->entries[i].entry_name);
1849   g_free(sent->entries);
1850   g_free(sent);
1851 }
1852
1853 static void
1854 prune_memory_usage(CompletionState *cmpl_state)
1855 {
1856   GList* cdsl = cmpl_state->directory_sent_storage;
1857   GList* cdl = cmpl_state->directory_storage;
1858   GList* cdl0 = cdl;
1859   gint len = 0;
1860
1861   for(; cdsl && len < CMPL_DIRECTORY_CACHE_SIZE; len += 1)
1862     cdsl = cdsl->next;
1863
1864   if (cdsl) {
1865     cmpl_free_dir_sent_list(cdsl->next);
1866     cdsl->next = NULL;
1867   }
1868
1869   cmpl_state->directory_storage = NULL;
1870   while (cdl) {
1871     if (cdl->data == cmpl_state->reference_dir)
1872       cmpl_state->directory_storage = g_list_prepend(NULL, cdl->data);
1873     else
1874       free_dir (cdl->data);
1875     cdl = cdl->next;
1876   }
1877
1878   g_list_free(cdl0);
1879 }
1880
1881 /**********************************************************************/
1882 /*                        The main entrances.                         */
1883 /**********************************************************************/
1884
1885 static PossibleCompletion*
1886 cmpl_completion_matches (gchar* text_to_complete,
1887                          gchar** remaining_text,
1888                          CompletionState* cmpl_state)
1889 {
1890   gchar* first_slash;
1891   PossibleCompletion *poss;
1892
1893   prune_memory_usage(cmpl_state);
1894
1895   g_assert (text_to_complete != NULL);
1896
1897   cmpl_state->user_completion_index = -1;
1898   cmpl_state->last_completion_text = text_to_complete;
1899   cmpl_state->the_completion.text[0] = 0;
1900   cmpl_state->last_valid_char = 0;
1901   cmpl_state->updated_text_len = -1;
1902   cmpl_state->updated_text[0] = 0;
1903   cmpl_state->re_complete = FALSE;
1904
1905 #ifdef HAVE_PWD_H
1906   first_slash = strchr (text_to_complete, G_DIR_SEPARATOR);
1907
1908   if (text_to_complete[0] == '~' && !first_slash)
1909     {
1910       /* Text starts with ~ and there is no slash, show all the
1911        * home directory completions.
1912        */
1913       poss = attempt_homedir_completion (text_to_complete, cmpl_state);
1914
1915       update_cmpl(poss, cmpl_state);
1916
1917       return poss;
1918     }
1919 #endif
1920   cmpl_state->reference_dir =
1921     open_ref_dir (text_to_complete, remaining_text, cmpl_state);
1922
1923   if(!cmpl_state->reference_dir)
1924     return NULL;
1925
1926   cmpl_state->completion_dir =
1927     find_completion_dir (*remaining_text, remaining_text, cmpl_state);
1928
1929   cmpl_state->last_valid_char = *remaining_text - text_to_complete;
1930
1931   if(!cmpl_state->completion_dir)
1932     return NULL;
1933
1934   cmpl_state->completion_dir->cmpl_index = -1;
1935   cmpl_state->completion_dir->cmpl_parent = NULL;
1936   cmpl_state->completion_dir->cmpl_text = *remaining_text;
1937
1938   cmpl_state->active_completion_dir = cmpl_state->completion_dir;
1939
1940   cmpl_state->reference_dir = cmpl_state->completion_dir;
1941
1942   poss = attempt_file_completion(cmpl_state);
1943
1944   update_cmpl(poss, cmpl_state);
1945
1946   return poss;
1947 }
1948
1949 static PossibleCompletion*
1950 cmpl_next_completion (CompletionState* cmpl_state)
1951 {
1952   PossibleCompletion* poss = NULL;
1953
1954   cmpl_state->the_completion.text[0] = 0;
1955
1956 #ifdef HAVE_PWD_H
1957   if(cmpl_state->user_completion_index >= 0)
1958     poss = attempt_homedir_completion(cmpl_state->last_completion_text, cmpl_state);
1959   else
1960     poss = attempt_file_completion(cmpl_state);
1961 #else
1962   poss = attempt_file_completion(cmpl_state);
1963 #endif
1964
1965   update_cmpl(poss, cmpl_state);
1966
1967   return poss;
1968 }
1969
1970 /**********************************************************************/
1971 /*                       Directory Operations                         */
1972 /**********************************************************************/
1973
1974 /* Open the directory where completion will begin from, if possible. */
1975 static CompletionDir*
1976 open_ref_dir(gchar* text_to_complete,
1977              gchar** remaining_text,
1978              CompletionState* cmpl_state)
1979 {
1980   gchar* first_slash;
1981   CompletionDir *new_dir;
1982
1983   first_slash = strchr(text_to_complete, G_DIR_SEPARATOR);
1984
1985 #ifdef G_WITH_CYGWIN
1986   if (text_to_complete[0] == '/' && text_to_complete[1] == '/')
1987     {
1988       char root_dir[5];
1989       sprintf(root_dir, "//%c", text_to_complete[2]);
1990
1991       new_dir = open_dir(root_dir, cmpl_state);
1992
1993       if (new_dir) {
1994         *remaining_text = text_to_complete + 4;
1995       }
1996     }
1997 #else
1998   if (FALSE)
1999     ;
2000 #endif
2001 #ifdef HAVE_PWD_H
2002   else if (text_to_complete[0] == '~')
2003     {
2004       new_dir = open_user_dir(text_to_complete, cmpl_state);
2005
2006       if(new_dir)
2007         {
2008           if(first_slash)
2009             *remaining_text = first_slash + 1;
2010           else
2011             *remaining_text = text_to_complete + strlen(text_to_complete);
2012         }
2013       else
2014         {
2015           return NULL;
2016         }
2017     }
2018 #endif
2019   else if (g_path_is_absolute (text_to_complete) || !cmpl_state->reference_dir)
2020     {
2021       gchar *tmp = g_strdup(text_to_complete);
2022       gchar *p;
2023
2024       p = tmp;
2025       while (*p && *p != '*' && *p != '?')
2026         p++;
2027
2028       *p = '\0';
2029       p = strrchr(tmp, G_DIR_SEPARATOR);
2030       if (p)
2031         {
2032           if (p == tmp)
2033             p++;
2034       
2035           *p = '\0';
2036
2037           new_dir = open_dir(tmp, cmpl_state);
2038
2039           if(new_dir)
2040             *remaining_text = text_to_complete + 
2041               ((p == tmp + 1) ? (p - tmp) : (p + 1 - tmp));
2042         }
2043       else
2044         {
2045           /* If no possible candidates, use the cwd */
2046           gchar *curdir = g_get_current_dir ();
2047           
2048           new_dir = open_dir(curdir, cmpl_state);
2049
2050           if (new_dir)
2051             *remaining_text = text_to_complete;
2052
2053           g_free (curdir);
2054         }
2055
2056       g_free (tmp);
2057     }
2058   else
2059     {
2060       *remaining_text = text_to_complete;
2061
2062       new_dir = open_dir(cmpl_state->reference_dir->fullname, cmpl_state);
2063     }
2064
2065   if(new_dir)
2066     {
2067       new_dir->cmpl_index = -1;
2068       new_dir->cmpl_parent = NULL;
2069     }
2070
2071   return new_dir;
2072 }
2073
2074 #ifdef HAVE_PWD_H
2075
2076 /* open a directory by user name */
2077 static CompletionDir*
2078 open_user_dir(gchar* text_to_complete,
2079               CompletionState *cmpl_state)
2080 {
2081   gchar *first_slash;
2082   gint cmp_len;
2083
2084   g_assert(text_to_complete && text_to_complete[0] == '~');
2085
2086   first_slash = strchr(text_to_complete, G_DIR_SEPARATOR);
2087
2088   if (first_slash)
2089     cmp_len = first_slash - text_to_complete - 1;
2090   else
2091     cmp_len = strlen(text_to_complete + 1);
2092
2093   if(!cmp_len)
2094     {
2095       /* ~/ */
2096       gchar *homedir = g_get_home_dir ();
2097
2098       if (homedir)
2099         return open_dir(homedir, cmpl_state);
2100       else
2101         return NULL;
2102     }
2103   else
2104     {
2105       /* ~user/ */
2106       char* copy = g_new(char, cmp_len + 1);
2107       struct passwd *pwd;
2108       strncpy(copy, text_to_complete + 1, cmp_len);
2109       copy[cmp_len] = 0;
2110       pwd = getpwnam(copy);
2111       g_free(copy);
2112       if (!pwd)
2113         {
2114           cmpl_errno = errno;
2115           return NULL;
2116         }
2117
2118       return open_dir(pwd->pw_dir, cmpl_state);
2119     }
2120 }
2121
2122 #endif
2123
2124 /* open a directory relative the the current relative directory */
2125 static CompletionDir*
2126 open_relative_dir(gchar* dir_name,
2127                   CompletionDir* dir,
2128                   CompletionState *cmpl_state)
2129 {
2130   CompletionDir *result;
2131   GString *path;
2132
2133   path = g_string_sized_new (dir->fullname_len + strlen (dir_name) + 10);
2134   g_string_assign (path, dir->fullname);
2135
2136   if(dir->fullname_len > 1
2137     && path->str[dir->fullname_len - 1] != G_DIR_SEPARATOR)
2138      g_string_append_c (path, G_DIR_SEPARATOR);
2139   g_string_append (path, dir_name);
2140
2141   result = open_dir(path->str, cmpl_state);
2142
2143   g_string_free (path, TRUE);
2144
2145   return result;
2146 }
2147
2148 /* after the cache lookup fails, really open a new directory */
2149 static CompletionDirSent*
2150 open_new_dir(gchar* dir_name, struct stat* sbuf, gboolean stat_subdirs)
2151 {
2152   CompletionDirSent* sent;
2153   DIR* directory;
2154   struct dirent *dirent_ptr;
2155   gint entry_count = 0;
2156   gint i;
2157   struct stat ent_sbuf;
2158   GString *path;
2159   gchar *xdir;
2160
2161   sent = g_new(CompletionDirSent, 1);
2162   sent->mtime = sbuf->st_mtime;
2163   sent->inode = sbuf->st_ino;
2164   sent->device = sbuf->st_dev;
2165
2166   path = g_string_sized_new (2*MAXPATHLEN + 10);
2167
2168   xdir = g_filename_from_utf8 (dir_name);
2169   directory = opendir(xdir);
2170   g_free (xdir);
2171
2172   if(!directory)
2173     {
2174       cmpl_errno = errno;
2175       return NULL;
2176     }
2177
2178   while((dirent_ptr = readdir(directory)) != NULL)
2179     {
2180       entry_count++;
2181     }
2182
2183   sent->entries = g_new(CompletionDirEntry, entry_count);
2184   sent->entry_count = entry_count;
2185
2186   rewinddir(directory);
2187
2188   for(i = 0; i < entry_count; i += 1)
2189     {
2190       dirent_ptr = readdir(directory);
2191
2192       if(!dirent_ptr)
2193         {
2194           cmpl_errno = errno;
2195           closedir(directory);
2196           return NULL;
2197         }
2198
2199       sent->entries[i].entry_name = g_filename_to_utf8 (dirent_ptr->d_name);
2200
2201       g_string_assign (path, dir_name);
2202       if (path->str[path->len-1] != G_DIR_SEPARATOR)
2203         {
2204           g_string_append_c (path, G_DIR_SEPARATOR);
2205         }
2206       g_string_append (path, dirent_ptr->d_name);
2207
2208       if (stat_subdirs)
2209         {
2210           if(stat(path->str, &ent_sbuf) >= 0 && S_ISDIR(ent_sbuf.st_mode))
2211             sent->entries[i].is_dir = TRUE;
2212           else
2213             /* stat may fail, and we don't mind, since it could be a
2214              * dangling symlink. */
2215             sent->entries[i].is_dir = FALSE;
2216         }
2217       else
2218         sent->entries[i].is_dir = 1;
2219     }
2220
2221   g_string_free (path, TRUE);
2222   qsort(sent->entries, sent->entry_count, sizeof(CompletionDirEntry), compare_cmpl_dir);
2223
2224   closedir(directory);
2225
2226   return sent;
2227 }
2228
2229 #if !defined(G_OS_WIN32) && !defined(G_WITH_CYGWIN)
2230
2231 static gboolean
2232 check_dir(gchar *dir_name, struct stat *result, gboolean *stat_subdirs)
2233 {
2234   /* A list of directories that we know only contain other directories.
2235    * Trying to stat every file in these directories would be very
2236    * expensive.
2237    */
2238
2239   static struct {
2240     gchar *name;
2241     gboolean present;
2242     struct stat statbuf;
2243   } no_stat_dirs[] = {
2244     { "/afs", FALSE, { 0 } },
2245     { "/net", FALSE, { 0 } }
2246   };
2247
2248   static const gint n_no_stat_dirs = sizeof(no_stat_dirs) / sizeof(no_stat_dirs[0]);
2249   static gboolean initialized = FALSE;
2250
2251   gint i;
2252
2253   if (!initialized)
2254     {
2255       initialized = TRUE;
2256       for (i = 0; i < n_no_stat_dirs; i++)
2257         {
2258           if (stat (no_stat_dirs[i].name, &no_stat_dirs[i].statbuf) == 0)
2259             no_stat_dirs[i].present = TRUE;
2260         }
2261     }
2262
2263   if(stat(dir_name, result) < 0)
2264     {
2265       cmpl_errno = errno;
2266       return FALSE;
2267     }
2268
2269   *stat_subdirs = TRUE;
2270   for (i=0; i<n_no_stat_dirs; i++)
2271     {
2272       if (no_stat_dirs[i].present &&
2273           (no_stat_dirs[i].statbuf.st_dev == result->st_dev) &&
2274           (no_stat_dirs[i].statbuf.st_ino == result->st_ino))
2275         {
2276           *stat_subdirs = FALSE;
2277           break;
2278         }
2279     }
2280
2281   return TRUE;
2282 }
2283
2284 #endif
2285
2286 /* open a directory by absolute pathname */
2287 static CompletionDir*
2288 open_dir(gchar* dir_name, CompletionState* cmpl_state)
2289 {
2290   struct stat sbuf;
2291   gboolean stat_subdirs;
2292   CompletionDirSent *sent;
2293   GList* cdsl;
2294
2295 #if !defined(G_OS_WIN32) && !defined(G_WITH_CYGWIN)
2296   if (!check_dir (dir_name, &sbuf, &stat_subdirs))
2297     return NULL;
2298
2299   cdsl = cmpl_state->directory_sent_storage;
2300
2301   while (cdsl)
2302     {
2303       sent = cdsl->data;
2304
2305       if(sent->inode == sbuf.st_ino &&
2306          sent->mtime == sbuf.st_mtime &&
2307          sent->device == sbuf.st_dev)
2308         return attach_dir(sent, dir_name, cmpl_state);
2309
2310       cdsl = cdsl->next;
2311     }
2312 #else
2313   stat_subdirs = TRUE;
2314 #endif
2315
2316   sent = open_new_dir(dir_name, &sbuf, stat_subdirs);
2317
2318   if (sent) {
2319     cmpl_state->directory_sent_storage =
2320       g_list_prepend(cmpl_state->directory_sent_storage, sent);
2321
2322     return attach_dir(sent, dir_name, cmpl_state);
2323   }
2324
2325   return NULL;
2326 }
2327
2328 static CompletionDir*
2329 attach_dir(CompletionDirSent* sent, gchar* dir_name, CompletionState *cmpl_state)
2330 {
2331   CompletionDir* new_dir;
2332
2333   new_dir = g_new(CompletionDir, 1);
2334
2335   cmpl_state->directory_storage =
2336     g_list_prepend(cmpl_state->directory_storage, new_dir);
2337
2338   new_dir->sent = sent;
2339   new_dir->fullname = g_strdup(dir_name);
2340   new_dir->fullname_len = strlen(dir_name);
2341
2342   return new_dir;
2343 }
2344
2345 static gint
2346 correct_dir_fullname(CompletionDir* cmpl_dir)
2347 {
2348   gint length = strlen(cmpl_dir->fullname);
2349   gchar *first_slash = strchr(cmpl_dir->fullname, G_DIR_SEPARATOR);
2350   struct stat sbuf;
2351
2352   /* Does it end with /. (\.) ? */
2353   if (length >= 2 &&
2354       strcmp(cmpl_dir->fullname + length - 2, G_DIR_SEPARATOR_S ".") == 0)
2355     {
2356       /* Is it just the root directory (on a drive) ? */
2357       if (cmpl_dir->fullname + length - 2 == first_slash)
2358         {
2359           cmpl_dir->fullname[length - 1] = 0;
2360           cmpl_dir->fullname_len = length - 1;
2361           return TRUE;
2362         }
2363       else
2364         {
2365           cmpl_dir->fullname[length - 2] = 0;
2366         }
2367     }
2368
2369   /* Ends with /./ (\.\)? */
2370   else if (length >= 3 &&
2371            strcmp(cmpl_dir->fullname + length - 3,
2372                   G_DIR_SEPARATOR_S "." G_DIR_SEPARATOR_S) == 0)
2373     cmpl_dir->fullname[length - 2] = 0;
2374
2375   /* Ends with /.. (\..) ? */
2376   else if (length >= 3 &&
2377            strcmp(cmpl_dir->fullname + length - 3,
2378                   G_DIR_SEPARATOR_S "..") == 0)
2379     {
2380       /* Is it just /.. (X:\..)? */
2381       if(cmpl_dir->fullname + length - 3 == first_slash)
2382         {
2383           cmpl_dir->fullname[length - 2] = 0;
2384           cmpl_dir->fullname_len = length - 2;
2385           return TRUE;
2386         }
2387
2388       if(stat(cmpl_dir->fullname, &sbuf) < 0)
2389         {
2390           cmpl_errno = errno;
2391           return FALSE;
2392         }
2393
2394       cmpl_dir->fullname[length - 3] = 0;
2395
2396       if(!correct_parent(cmpl_dir, &sbuf))
2397         return FALSE;
2398     }
2399
2400   /* Ends with /../ (\..\)? */
2401   else if (length >= 4 &&
2402            strcmp(cmpl_dir->fullname + length - 4,
2403                   G_DIR_SEPARATOR_S ".." G_DIR_SEPARATOR_S) == 0)
2404     {
2405       /* Is it just /../ (X:\..\)? */
2406       if(cmpl_dir->fullname + length - 4 == first_slash)
2407         {
2408           cmpl_dir->fullname[length - 3] = 0;
2409           cmpl_dir->fullname_len = length - 3;
2410           return TRUE;
2411         }
2412
2413       if(stat(cmpl_dir->fullname, &sbuf) < 0)
2414         {
2415           cmpl_errno = errno;
2416           return FALSE;
2417         }
2418
2419       cmpl_dir->fullname[length - 4] = 0;
2420
2421       if(!correct_parent(cmpl_dir, &sbuf))
2422         return FALSE;
2423     }
2424
2425   cmpl_dir->fullname_len = strlen(cmpl_dir->fullname);
2426
2427   return TRUE;
2428 }
2429
2430 static gint
2431 correct_parent(CompletionDir* cmpl_dir, struct stat *sbuf)
2432 {
2433   struct stat parbuf;
2434   gchar *last_slash;
2435   gchar *first_slash;
2436   gchar *new_name;
2437   gchar c = 0;
2438
2439   last_slash = strrchr(cmpl_dir->fullname, G_DIR_SEPARATOR);
2440   g_assert(last_slash);
2441   first_slash = strchr(cmpl_dir->fullname, G_DIR_SEPARATOR);
2442
2443   /* Clever (?) way to check for top-level directory that works also on
2444    * Win32, where there is a drive letter and colon prefixed...
2445    */
2446   if (last_slash != first_slash)
2447     {
2448       last_slash[0] = 0;
2449     }
2450   else
2451     {
2452       c = last_slash[1];
2453       last_slash[1] = 0;
2454     }
2455
2456   if (stat(cmpl_dir->fullname, &parbuf) < 0)
2457     {
2458       cmpl_errno = errno;
2459       if (!c)
2460         last_slash[0] = G_DIR_SEPARATOR;
2461       return FALSE;
2462     }
2463
2464 #ifndef G_OS_WIN32              /* No inode numbers on Win32 */
2465   if (parbuf.st_ino == sbuf->st_ino && parbuf.st_dev == sbuf->st_dev)
2466     /* it wasn't a link */
2467     return TRUE;
2468
2469   if(c)
2470     last_slash[1] = c;
2471   else
2472     last_slash[0] = G_DIR_SEPARATOR;
2473
2474   /* it was a link, have to figure it out the hard way */
2475
2476   new_name = find_parent_dir_fullname(cmpl_dir->fullname);
2477
2478   if (!new_name)
2479     return FALSE;
2480
2481   g_free(cmpl_dir->fullname);
2482
2483   cmpl_dir->fullname = new_name;
2484 #endif
2485
2486   return TRUE;
2487 }
2488
2489 #ifndef G_OS_WIN32
2490
2491 static gchar*
2492 find_parent_dir_fullname(gchar* dirname)
2493 {
2494   gchar *orig_dir;
2495   gchar *result;
2496
2497   orig_dir = g_get_current_dir ();
2498
2499   if(chdir(dirname) != 0 || chdir("..") != 0)
2500     {
2501       cmpl_errno = errno;
2502       return NULL;
2503     }
2504
2505   result = g_get_current_dir ();
2506
2507   if(chdir(orig_dir) != 0)
2508     {
2509       cmpl_errno = errno;
2510       return NULL;
2511     }
2512
2513   g_free (orig_dir);
2514   return result;
2515 }
2516
2517 #endif
2518
2519 /**********************************************************************/
2520 /*                        Completion Operations                       */
2521 /**********************************************************************/
2522
2523 #ifdef HAVE_PWD_H
2524
2525 static PossibleCompletion*
2526 attempt_homedir_completion(gchar* text_to_complete,
2527                            CompletionState *cmpl_state)
2528 {
2529   gint index, length;
2530
2531   if (!cmpl_state->user_dir_name_buffer &&
2532       !get_pwdb(cmpl_state))
2533     return NULL;
2534   length = strlen(text_to_complete) - 1;
2535
2536   cmpl_state->user_completion_index += 1;
2537
2538   while(cmpl_state->user_completion_index < cmpl_state->user_directories_len)
2539     {
2540       index = first_diff_index(text_to_complete + 1,
2541                                cmpl_state->user_directories
2542                                [cmpl_state->user_completion_index].login);
2543
2544       switch(index)
2545         {
2546         case PATTERN_MATCH:
2547           break;
2548         default:
2549           if(cmpl_state->last_valid_char < (index + 1))
2550             cmpl_state->last_valid_char = index + 1;
2551           cmpl_state->user_completion_index += 1;
2552           continue;
2553         }
2554
2555       cmpl_state->the_completion.is_a_completion = 1;
2556       cmpl_state->the_completion.is_directory = TRUE;
2557
2558       append_completion_text("~", cmpl_state);
2559
2560       append_completion_text(cmpl_state->
2561                               user_directories[cmpl_state->user_completion_index].login,
2562                              cmpl_state);
2563
2564       return append_completion_text(G_DIR_SEPARATOR_S, cmpl_state);
2565     }
2566
2567   if(text_to_complete[1] ||
2568      cmpl_state->user_completion_index > cmpl_state->user_directories_len)
2569     {
2570       cmpl_state->user_completion_index = -1;
2571       return NULL;
2572     }
2573   else
2574     {
2575       cmpl_state->user_completion_index += 1;
2576       cmpl_state->the_completion.is_a_completion = 1;
2577       cmpl_state->the_completion.is_directory = TRUE;
2578
2579       return append_completion_text("~" G_DIR_SEPARATOR_S, cmpl_state);
2580     }
2581 }
2582
2583 #endif
2584
2585 #if defined(G_OS_WIN32) || defined(G_WITH_CYGWIN)
2586 #define FOLD(c) (tolower(c))
2587 #else
2588 #define FOLD(c) (c)
2589 #endif
2590
2591 /* returns the index (>= 0) of the first differing character,
2592  * PATTERN_MATCH if the completion matches */
2593 static gint
2594 first_diff_index(gchar* pat, gchar* text)
2595 {
2596   gint diff = 0;
2597
2598   while(*pat && *text && FOLD(*text) == FOLD(*pat))
2599     {
2600       pat += 1;
2601       text += 1;
2602       diff += 1;
2603     }
2604
2605   if(*pat)
2606     return diff;
2607
2608   return PATTERN_MATCH;
2609 }
2610
2611 static PossibleCompletion*
2612 append_completion_text(gchar* text, CompletionState* cmpl_state)
2613 {
2614   gint len, i = 1;
2615
2616   if(!cmpl_state->the_completion.text)
2617     return NULL;
2618
2619   len = strlen(text) + strlen(cmpl_state->the_completion.text) + 1;
2620
2621   if(cmpl_state->the_completion.text_alloc > len)
2622     {
2623       strcat(cmpl_state->the_completion.text, text);
2624       return &cmpl_state->the_completion;
2625     }
2626
2627   while(i < len) { i <<= 1; }
2628
2629   cmpl_state->the_completion.text_alloc = i;
2630
2631   cmpl_state->the_completion.text = (gchar*)g_realloc(cmpl_state->the_completion.text, i);
2632
2633   if(!cmpl_state->the_completion.text)
2634     return NULL;
2635   else
2636     {
2637       strcat(cmpl_state->the_completion.text, text);
2638       return &cmpl_state->the_completion;
2639     }
2640 }
2641
2642 static CompletionDir*
2643 find_completion_dir(gchar* text_to_complete,
2644                     gchar** remaining_text,
2645                     CompletionState* cmpl_state)
2646 {
2647   gchar* first_slash = strchr(text_to_complete, G_DIR_SEPARATOR);
2648   CompletionDir* dir = cmpl_state->reference_dir;
2649   CompletionDir* next;
2650   *remaining_text = text_to_complete;
2651
2652   while(first_slash)
2653     {
2654       gint len = first_slash - *remaining_text;
2655       gint found = 0;
2656       gchar *found_name = NULL;         /* Quiet gcc */
2657       gint i;
2658       gchar* pat_buf = g_new (gchar, len + 1);
2659
2660       strncpy(pat_buf, *remaining_text, len);
2661       pat_buf[len] = 0;
2662
2663       for(i = 0; i < dir->sent->entry_count; i += 1)
2664         {
2665           if(dir->sent->entries[i].is_dir &&
2666              fnmatch(pat_buf, dir->sent->entries[i].entry_name,
2667                      FNMATCH_FLAGS)!= FNM_NOMATCH)
2668             {
2669               if(found)
2670                 {
2671                   g_free (pat_buf);
2672                   return dir;
2673                 }
2674               else
2675                 {
2676                   found = 1;
2677                   found_name = dir->sent->entries[i].entry_name;
2678                 }
2679             }
2680         }
2681
2682       if (!found)
2683         {
2684           /* Perhaps we are trying to open an automount directory */
2685           found_name = pat_buf;
2686         }
2687
2688       next = open_relative_dir(found_name, dir, cmpl_state);
2689       
2690       if(!next)
2691         {
2692           g_free (pat_buf);
2693           return NULL;
2694         }
2695       
2696       next->cmpl_parent = dir;
2697       
2698       dir = next;
2699       
2700       if(!correct_dir_fullname(dir))
2701         {
2702           g_free(pat_buf);
2703           return NULL;
2704         }
2705       
2706       *remaining_text = first_slash + 1;
2707       first_slash = strchr(*remaining_text, G_DIR_SEPARATOR);
2708
2709       g_free (pat_buf);
2710     }
2711
2712   return dir;
2713 }
2714
2715 static void
2716 update_cmpl(PossibleCompletion* poss, CompletionState* cmpl_state)
2717 {
2718   gint cmpl_len;
2719
2720   if(!poss || !cmpl_is_a_completion(poss))
2721     return;
2722
2723   cmpl_len = strlen(cmpl_this_completion(poss));
2724
2725   if(cmpl_state->updated_text_alloc < cmpl_len + 1)
2726     {
2727       cmpl_state->updated_text =
2728         (gchar*)g_realloc(cmpl_state->updated_text,
2729                           cmpl_state->updated_text_alloc);
2730       cmpl_state->updated_text_alloc = 2*cmpl_len;
2731     }
2732
2733   if(cmpl_state->updated_text_len < 0)
2734     {
2735       strcpy(cmpl_state->updated_text, cmpl_this_completion(poss));
2736       cmpl_state->updated_text_len = cmpl_len;
2737       cmpl_state->re_complete = cmpl_is_directory(poss);
2738     }
2739   else if(cmpl_state->updated_text_len == 0)
2740     {
2741       cmpl_state->re_complete = FALSE;
2742     }
2743   else
2744     {
2745       gint first_diff =
2746         first_diff_index(cmpl_state->updated_text,
2747                          cmpl_this_completion(poss));
2748
2749       cmpl_state->re_complete = FALSE;
2750
2751       if(first_diff == PATTERN_MATCH)
2752         return;
2753
2754       if(first_diff > cmpl_state->updated_text_len)
2755         strcpy(cmpl_state->updated_text, cmpl_this_completion(poss));
2756
2757       cmpl_state->updated_text_len = first_diff;
2758       cmpl_state->updated_text[first_diff] = 0;
2759     }
2760 }
2761
2762 static PossibleCompletion*
2763 attempt_file_completion(CompletionState *cmpl_state)
2764 {
2765   gchar *pat_buf, *first_slash;
2766   CompletionDir *dir = cmpl_state->active_completion_dir;
2767
2768   dir->cmpl_index += 1;
2769
2770   if(dir->cmpl_index == dir->sent->entry_count)
2771     {
2772       if(dir->cmpl_parent == NULL)
2773         {
2774           cmpl_state->active_completion_dir = NULL;
2775
2776           return NULL;
2777         }
2778       else
2779         {
2780           cmpl_state->active_completion_dir = dir->cmpl_parent;
2781
2782           return attempt_file_completion(cmpl_state);
2783         }
2784     }
2785
2786   g_assert(dir->cmpl_text);
2787
2788   first_slash = strchr(dir->cmpl_text, G_DIR_SEPARATOR);
2789
2790   if(first_slash)
2791     {
2792       gint len = first_slash - dir->cmpl_text;
2793
2794       pat_buf = g_new (gchar, len + 1);
2795       strncpy(pat_buf, dir->cmpl_text, len);
2796       pat_buf[len] = 0;
2797     }
2798   else
2799     {
2800       gint len = strlen(dir->cmpl_text);
2801
2802       pat_buf = g_new (gchar, len + 2);
2803       strcpy(pat_buf, dir->cmpl_text);
2804       /* Don't append a * if the user entered one herself.
2805        * This way one can complete *.h and don't get matches
2806        * on any .help files, for instance.
2807        */
2808       if (strchr(pat_buf, '*') == NULL)
2809         strcpy(pat_buf + len, "*");
2810     }
2811
2812   if(first_slash)
2813     {
2814       if(dir->sent->entries[dir->cmpl_index].is_dir)
2815         {
2816           if(fnmatch(pat_buf, dir->sent->entries[dir->cmpl_index].entry_name,
2817                      FNMATCH_FLAGS) != FNM_NOMATCH)
2818             {
2819               CompletionDir* new_dir;
2820
2821               new_dir = open_relative_dir(dir->sent->entries[dir->cmpl_index].entry_name,
2822                                           dir, cmpl_state);
2823
2824               if(!new_dir)
2825                 {
2826                   g_free (pat_buf);
2827                   return NULL;
2828                 }
2829
2830               new_dir->cmpl_parent = dir;
2831
2832               new_dir->cmpl_index = -1;
2833               new_dir->cmpl_text = first_slash + 1;
2834
2835               cmpl_state->active_completion_dir = new_dir;
2836
2837               g_free (pat_buf);
2838               return attempt_file_completion(cmpl_state);
2839             }
2840           else
2841             {
2842               g_free (pat_buf);
2843               return attempt_file_completion(cmpl_state);
2844             }
2845         }
2846       else
2847         {
2848           g_free (pat_buf);
2849           return attempt_file_completion(cmpl_state);
2850         }
2851     }
2852   else
2853     {
2854       if(dir->cmpl_parent != NULL)
2855         {
2856           append_completion_text(dir->fullname +
2857                                  strlen(cmpl_state->completion_dir->fullname) + 1,
2858                                  cmpl_state);
2859           append_completion_text(G_DIR_SEPARATOR_S, cmpl_state);
2860         }
2861
2862       append_completion_text(dir->sent->entries[dir->cmpl_index].entry_name, cmpl_state);
2863
2864       cmpl_state->the_completion.is_a_completion =
2865         (fnmatch(pat_buf, dir->sent->entries[dir->cmpl_index].entry_name,
2866                  FNMATCH_FLAGS) != FNM_NOMATCH);
2867
2868       cmpl_state->the_completion.is_directory = dir->sent->entries[dir->cmpl_index].is_dir;
2869       if(dir->sent->entries[dir->cmpl_index].is_dir)
2870         append_completion_text(G_DIR_SEPARATOR_S, cmpl_state);
2871
2872       g_free (pat_buf);
2873       return &cmpl_state->the_completion;
2874     }
2875 }
2876
2877 #ifdef HAVE_PWD_H
2878
2879 static gint
2880 get_pwdb(CompletionState* cmpl_state)
2881 {
2882   struct passwd *pwd_ptr;
2883   gchar* buf_ptr;
2884   gint len = 0, i, count = 0;
2885
2886   if(cmpl_state->user_dir_name_buffer)
2887     return TRUE;
2888   setpwent ();
2889
2890   while ((pwd_ptr = getpwent()) != NULL)
2891     {
2892       len += strlen(pwd_ptr->pw_name);
2893       len += strlen(pwd_ptr->pw_dir);
2894       len += 2;
2895       count += 1;
2896     }
2897
2898   setpwent ();
2899
2900   cmpl_state->user_dir_name_buffer = g_new(gchar, len);
2901   cmpl_state->user_directories = g_new(CompletionUserDir, count);
2902   cmpl_state->user_directories_len = count;
2903
2904   buf_ptr = cmpl_state->user_dir_name_buffer;
2905
2906   for(i = 0; i < count; i += 1)
2907     {
2908       pwd_ptr = getpwent();
2909       if(!pwd_ptr)
2910         {
2911           cmpl_errno = errno;
2912           goto error;
2913         }
2914
2915       strcpy(buf_ptr, pwd_ptr->pw_name);
2916       cmpl_state->user_directories[i].login = buf_ptr;
2917       buf_ptr += strlen(buf_ptr);
2918       buf_ptr += 1;
2919       strcpy(buf_ptr, pwd_ptr->pw_dir);
2920       cmpl_state->user_directories[i].homedir = buf_ptr;
2921       buf_ptr += strlen(buf_ptr);
2922       buf_ptr += 1;
2923     }
2924
2925   qsort(cmpl_state->user_directories,
2926         cmpl_state->user_directories_len,
2927         sizeof(CompletionUserDir),
2928         compare_user_dir);
2929
2930   endpwent();
2931
2932   return TRUE;
2933
2934 error:
2935
2936   if(cmpl_state->user_dir_name_buffer)
2937     g_free(cmpl_state->user_dir_name_buffer);
2938   if(cmpl_state->user_directories)
2939     g_free(cmpl_state->user_directories);
2940
2941   cmpl_state->user_dir_name_buffer = NULL;
2942   cmpl_state->user_directories = NULL;
2943
2944   return FALSE;
2945 }
2946
2947 static gint
2948 compare_user_dir(const void* a, const void* b)
2949 {
2950   return strcmp((((CompletionUserDir*)a))->login,
2951                 (((CompletionUserDir*)b))->login);
2952 }
2953
2954 #endif
2955
2956 static gint
2957 compare_cmpl_dir(const void* a, const void* b)
2958 {
2959 #if !defined(G_OS_WIN32) && !defined(G_WITH_CYGWIN)
2960   return strcmp((((CompletionDirEntry*)a))->entry_name,
2961                 (((CompletionDirEntry*)b))->entry_name);
2962 #else
2963   return g_strcasecmp((((CompletionDirEntry*)a))->entry_name,
2964                       (((CompletionDirEntry*)b))->entry_name);
2965 #endif
2966 }
2967
2968 static gint
2969 cmpl_state_okay(CompletionState* cmpl_state)
2970 {
2971   return  cmpl_state && cmpl_state->reference_dir;
2972 }
2973
2974 static gchar*
2975 cmpl_strerror(gint err)
2976 {
2977   if(err == CMPL_ERRNO_TOO_LONG)
2978     return "Name too long";
2979   else
2980     return g_strerror (err);
2981 }