]> Pileus Git - ~andy/gtk/blob - gtk/gtkfilesel.c
Argh, decided not to return a string that must be freed from
[~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             callback_arg->directory = g_strdup ("");
1308           } else {
1309             callback_arg->directory = g_strdup (current_dir);
1310           }
1311           
1312           fs->history_list = g_list_append (fs->history_list, callback_arg);
1313           
1314           gtk_signal_connect (GTK_OBJECT (menu_item), "activate",
1315                               (GtkSignalFunc) gtk_file_selection_history_callback,
1316                               (gpointer) fs);
1317           gtk_menu_append (GTK_MENU (fs->history_menu), menu_item);
1318           gtk_widget_show (menu_item);
1319         }
1320     }
1321
1322   gtk_option_menu_set_menu (GTK_OPTION_MENU (fs->history_pulldown), 
1323                             fs->history_menu);
1324   g_free (current_dir);
1325 }
1326
1327 static void
1328 gtk_file_selection_file_button (GtkWidget *widget,
1329                                gint row, 
1330                                gint column, 
1331                                GdkEventButton *bevent,
1332                                gpointer user_data)
1333 {
1334   GtkFileSelection *fs = NULL;
1335   gchar *filename, *temp = NULL;
1336   
1337   g_return_if_fail (GTK_IS_CLIST (widget));
1338
1339   fs = user_data;
1340   g_return_if_fail (fs != NULL);
1341   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1342   
1343   gtk_clist_get_text (GTK_CLIST (fs->file_list), row, 0, &temp);
1344   filename = g_strdup (temp);
1345
1346 #ifdef G_WITH_CYGWIN
1347   /* Check to see if the selection was a drive selector */
1348   if (isalpha(filename[0]) && (filename[1] == ':')) {
1349     /* It is... map it to a CYGWIN32 drive */
1350     char temp_filename[10];
1351
1352     sprintf(temp_filename, "//%c/", tolower(filename[0]));
1353     g_free(filename);
1354     filename = g_strdup(temp_filename);
1355   }
1356 #endif /* G_WITH_CYGWIN */
1357
1358   if (filename)
1359     {
1360       if (bevent)
1361         switch (bevent->type)
1362           {
1363           case GDK_2BUTTON_PRESS:
1364             gtk_button_clicked (GTK_BUTTON (fs->ok_button));
1365             break;
1366             
1367           default:
1368             gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), filename);
1369             break;
1370           }
1371       else
1372         gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), filename);
1373
1374       g_free (filename);
1375     }
1376 }
1377
1378 static void
1379 gtk_file_selection_dir_button (GtkWidget *widget,
1380                                gint row, 
1381                                gint column, 
1382                                GdkEventButton *bevent,
1383                                gpointer user_data)
1384 {
1385   GtkFileSelection *fs = NULL;
1386   gchar *filename, *temp = NULL;
1387
1388   g_return_if_fail (GTK_IS_CLIST (widget));
1389
1390   fs = GTK_FILE_SELECTION (user_data);
1391   g_return_if_fail (fs != NULL);
1392   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1393
1394   gtk_clist_get_text (GTK_CLIST (fs->dir_list), row, 0, &temp);
1395   filename = g_strdup (temp);
1396
1397   if (filename)
1398     {
1399       if (bevent)
1400         switch (bevent->type)
1401           {
1402           case GDK_2BUTTON_PRESS:
1403             gtk_file_selection_populate (fs, filename, FALSE);
1404             break;
1405           
1406           default:
1407             gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), filename);
1408             break;
1409           }
1410       else
1411         gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), filename);
1412
1413       g_free (filename);
1414     }
1415 }
1416
1417 #if defined(G_OS_WIN32) || defined(G_WITH_CYGWIN)
1418
1419 static void
1420 win32_gtk_add_drives_to_dir_list(GtkWidget *the_dir_list)
1421 {
1422   gchar *text[2], *textPtr;
1423   gchar buffer[128];
1424   char volumeNameBuf[128];
1425   char formatBuffer[128];
1426   gint row;
1427
1428   text[1] = NULL;
1429
1430   /* Get the Drives string */
1431   GetLogicalDriveStrings(sizeof(buffer), buffer);
1432
1433   /* Add the drives as necessary */
1434   textPtr = buffer;
1435   while (*textPtr != '\0') {
1436     /* Get the volume information for this drive */
1437     if ((tolower(textPtr[0]) != 'a') && (tolower(textPtr[0]) != 'b'))
1438       {
1439         /* Ignore floppies (?) */
1440         DWORD maxComponentLength, flags;
1441
1442         GetVolumeInformation(textPtr,
1443                              volumeNameBuf, sizeof(volumeNameBuf),
1444                              NULL, &maxComponentLength,
1445                              &flags, NULL, 0);
1446         /* Build the actual displayable string */
1447
1448         sprintf(formatBuffer, "%c:\\", toupper(textPtr[0]));
1449 #if 0 /* HB: removed to allow drive change AND directory update with one click */
1450         if (strlen(volumeNameBuf) > 0)
1451           sprintf(formatBuffer, "%s (%s)", formatBuffer, volumeNameBuf);
1452 #endif
1453         /* Add to the list */
1454         text[0] = formatBuffer;
1455         row = gtk_clist_append (GTK_CLIST (the_dir_list), text);
1456       }
1457     textPtr += (strlen(textPtr) + 1);
1458   }
1459 }
1460 #endif
1461
1462 static void
1463 gtk_file_selection_populate (GtkFileSelection *fs,
1464                              gchar            *rel_path,
1465                              gint              try_complete)
1466 {
1467   CompletionState *cmpl_state;
1468   PossibleCompletion* poss;
1469   gchar* filename;
1470   gint row;
1471   gchar* rem_path = rel_path;
1472   gchar* sel_text;
1473   gchar* text[2];
1474   gint did_recurse = FALSE;
1475   gint possible_count = 0;
1476   gint selection_index = -1;
1477   gint file_list_width;
1478   gint dir_list_width;
1479   
1480   g_return_if_fail (fs != NULL);
1481   g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
1482   
1483   cmpl_state = (CompletionState*) fs->cmpl_state;
1484   poss = cmpl_completion_matches (rel_path, &rem_path, cmpl_state);
1485
1486   if (!cmpl_state_okay (cmpl_state))
1487     {
1488       /* Something went wrong. */
1489       gtk_file_selection_abort (fs);
1490       return;
1491     }
1492
1493   g_assert (cmpl_state->reference_dir);
1494
1495   gtk_clist_freeze (GTK_CLIST (fs->dir_list));
1496   gtk_clist_clear (GTK_CLIST (fs->dir_list));
1497   gtk_clist_freeze (GTK_CLIST (fs->file_list));
1498   gtk_clist_clear (GTK_CLIST (fs->file_list));
1499
1500   /* Set the dir_list to include ./ and ../ */
1501   text[1] = NULL;
1502   text[0] = "." G_DIR_SEPARATOR_S;
1503   row = gtk_clist_append (GTK_CLIST (fs->dir_list), text);
1504
1505   text[0] = ".." G_DIR_SEPARATOR_S;
1506   row = gtk_clist_append (GTK_CLIST (fs->dir_list), text);
1507
1508   /*reset the max widths of the lists*/
1509   dir_list_width = gdk_string_width(fs->dir_list->style->font,".." G_DIR_SEPARATOR_S);
1510   gtk_clist_set_column_width(GTK_CLIST(fs->dir_list),0,dir_list_width);
1511   file_list_width = 1;
1512   gtk_clist_set_column_width(GTK_CLIST(fs->file_list),0,file_list_width);
1513
1514   while (poss)
1515     {
1516       if (cmpl_is_a_completion (poss))
1517         {
1518           possible_count += 1;
1519
1520           filename = cmpl_this_completion (poss);
1521
1522           text[0] = filename;
1523           
1524           if (cmpl_is_directory (poss))
1525             {
1526               if (strcmp (filename, "." G_DIR_SEPARATOR_S) != 0 &&
1527                   strcmp (filename, ".." G_DIR_SEPARATOR_S) != 0)
1528                 {
1529                   int width = gdk_string_width(fs->dir_list->style->font,
1530                                                filename);
1531                   row = gtk_clist_append (GTK_CLIST (fs->dir_list), text);
1532                   if(width > dir_list_width)
1533                     {
1534                       dir_list_width = width;
1535                       gtk_clist_set_column_width(GTK_CLIST(fs->dir_list),0,
1536                                                  width);
1537                     }
1538                 }
1539             }
1540           else
1541             {
1542               int width = gdk_string_width(fs->file_list->style->font,
1543                                            filename);
1544               row = gtk_clist_append (GTK_CLIST (fs->file_list), text);
1545               if(width > file_list_width)
1546                 {
1547                   file_list_width = width;
1548                   gtk_clist_set_column_width(GTK_CLIST(fs->file_list),0,
1549                                              width);
1550                 }
1551             }
1552         }
1553
1554       poss = cmpl_next_completion (cmpl_state);
1555     }
1556
1557 #if defined(G_OS_WIN32) || defined(G_WITH_CYGWIN)
1558   /* For Windows, add drives as potential selections */
1559   win32_gtk_add_drives_to_dir_list (fs->dir_list);
1560 #endif
1561
1562   gtk_clist_thaw (GTK_CLIST (fs->dir_list));
1563   gtk_clist_thaw (GTK_CLIST (fs->file_list));
1564
1565   /* File lists are set. */
1566
1567   g_assert (cmpl_state->reference_dir);
1568
1569   if (try_complete)
1570     {
1571
1572       /* User is trying to complete filenames, so advance the user's input
1573        * string to the updated_text, which is the common leading substring
1574        * of all possible completions, and if its a directory attempt
1575        * attempt completions in it. */
1576
1577       if (cmpl_updated_text (cmpl_state)[0])
1578         {
1579
1580           if (cmpl_updated_dir (cmpl_state))
1581             {
1582               gchar* dir_name = g_strdup (cmpl_updated_text (cmpl_state));
1583
1584               did_recurse = TRUE;
1585
1586               gtk_file_selection_populate (fs, dir_name, TRUE);
1587
1588               g_free (dir_name);
1589             }
1590           else
1591             {
1592               if (fs->selection_entry)
1593                       gtk_entry_set_text (GTK_ENTRY (fs->selection_entry),
1594                                           cmpl_updated_text (cmpl_state));
1595             }
1596         }
1597       else
1598         {
1599           selection_index = cmpl_last_valid_char (cmpl_state) -
1600                             (strlen (rel_path) - strlen (rem_path));
1601           if (fs->selection_entry)
1602             gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), rem_path);
1603         }
1604     }
1605   else
1606     {
1607       if (fs->selection_entry)
1608         gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), "");
1609     }
1610
1611   if (!did_recurse)
1612     {
1613       if (fs->selection_entry)
1614         gtk_entry_set_position (GTK_ENTRY (fs->selection_entry), selection_index);
1615
1616       if (fs->selection_entry)
1617         {
1618           sel_text = g_strconcat (_("Selection: "),
1619                                   cmpl_reference_position (cmpl_state),
1620                                   NULL);
1621
1622           gtk_label_set_text (GTK_LABEL (fs->selection_text), sel_text);
1623           g_free (sel_text);
1624         }
1625
1626       if (fs->history_pulldown) 
1627         {
1628           gtk_file_selection_update_history_menu (fs, cmpl_reference_position (cmpl_state));
1629         }
1630       
1631     }
1632 }
1633
1634 static void
1635 gtk_file_selection_abort (GtkFileSelection *fs)
1636 {
1637   gchar err_buf[256];
1638
1639   sprintf (err_buf, _("Directory unreadable: %s"), cmpl_strerror (cmpl_errno));
1640
1641   /*  BEEP gdk_beep();  */
1642
1643   if (fs->selection_entry)
1644     gtk_label_set_text (GTK_LABEL (fs->selection_text), err_buf);
1645 }
1646
1647 /**********************************************************************/
1648 /*                        External Interface                          */
1649 /**********************************************************************/
1650
1651 /* The four completion state selectors
1652  */
1653 static gchar*
1654 cmpl_updated_text (CompletionState* cmpl_state)
1655 {
1656   return cmpl_state->updated_text;
1657 }
1658
1659 static gboolean
1660 cmpl_updated_dir (CompletionState* cmpl_state)
1661 {
1662   return cmpl_state->re_complete;
1663 }
1664
1665 static gchar*
1666 cmpl_reference_position (CompletionState* cmpl_state)
1667 {
1668   return cmpl_state->reference_dir->fullname;
1669 }
1670
1671 static gint
1672 cmpl_last_valid_char (CompletionState* cmpl_state)
1673 {
1674   return cmpl_state->last_valid_char;
1675 }
1676
1677 static gchar*
1678 cmpl_completion_fullname (gchar* text, CompletionState* cmpl_state)
1679 {
1680   static char nothing[2] = "";
1681
1682   if (!cmpl_state_okay (cmpl_state))
1683     {
1684       return nothing;
1685     }
1686   else if (g_path_is_absolute (text))
1687     {
1688       strcpy (cmpl_state->updated_text, text);
1689     }
1690 #ifdef HAVE_PWD_H
1691   else if (text[0] == '~')
1692     {
1693       CompletionDir* dir;
1694       char* slash;
1695
1696       dir = open_user_dir (text, cmpl_state);
1697
1698       if (!dir)
1699         {
1700           /* spencer says just return ~something, so
1701            * for now just do it. */
1702           strcpy (cmpl_state->updated_text, text);
1703         }
1704       else
1705         {
1706
1707           strcpy (cmpl_state->updated_text, dir->fullname);
1708
1709           slash = strchr (text, G_DIR_SEPARATOR);
1710
1711           if (slash)
1712             strcat (cmpl_state->updated_text, slash);
1713         }
1714     }
1715 #endif
1716   else
1717     {
1718       strcpy (cmpl_state->updated_text, cmpl_state->reference_dir->fullname);
1719       if (cmpl_state->updated_text[strlen (cmpl_state->updated_text) - 1] != G_DIR_SEPARATOR)
1720         strcat (cmpl_state->updated_text, G_DIR_SEPARATOR_S);
1721       strcat (cmpl_state->updated_text, text);
1722     }
1723
1724   return cmpl_state->updated_text;
1725 }
1726
1727 /* The three completion selectors
1728  */
1729 static gchar*
1730 cmpl_this_completion (PossibleCompletion* pc)
1731 {
1732   return pc->text;
1733 }
1734
1735 static gboolean
1736 cmpl_is_directory (PossibleCompletion* pc)
1737 {
1738   return pc->is_directory;
1739 }
1740
1741 static gint
1742 cmpl_is_a_completion (PossibleCompletion* pc)
1743 {
1744   return pc->is_a_completion;
1745 }
1746
1747 /**********************************************************************/
1748 /*                       Construction, deletion                       */
1749 /**********************************************************************/
1750
1751 static CompletionState*
1752 cmpl_init_state (void)
1753 {
1754   gchar *getcwd_buf;
1755   CompletionState *new_state;
1756
1757   new_state = g_new (CompletionState, 1);
1758
1759   getcwd_buf = g_get_current_dir ();
1760
1761 tryagain:
1762
1763   new_state->reference_dir = NULL;
1764   new_state->completion_dir = NULL;
1765   new_state->active_completion_dir = NULL;
1766   new_state->directory_storage = NULL;
1767   new_state->directory_sent_storage = NULL;
1768   new_state->last_valid_char = 0;
1769   new_state->updated_text = g_new (gchar, MAXPATHLEN);
1770   new_state->updated_text_alloc = MAXPATHLEN;
1771   new_state->the_completion.text = g_new (gchar, MAXPATHLEN);
1772   new_state->the_completion.text_alloc = MAXPATHLEN;
1773   new_state->user_dir_name_buffer = NULL;
1774   new_state->user_directories = NULL;
1775
1776   new_state->reference_dir =  open_dir (getcwd_buf, new_state);
1777
1778   if (!new_state->reference_dir)
1779     {
1780       /* Directories changing from underneath us, grumble */
1781       strcpy (getcwd_buf, G_DIR_SEPARATOR_S);
1782       goto tryagain;
1783     }
1784
1785   g_free (getcwd_buf);
1786   return new_state;
1787 }
1788
1789 static void
1790 cmpl_free_dir_list(GList* dp0)
1791 {
1792   GList *dp = dp0;
1793
1794   while (dp) {
1795     free_dir (dp->data);
1796     dp = dp->next;
1797   }
1798
1799   g_list_free(dp0);
1800 }
1801
1802 static void
1803 cmpl_free_dir_sent_list(GList* dp0)
1804 {
1805   GList *dp = dp0;
1806
1807   while (dp) {
1808     free_dir_sent (dp->data);
1809     dp = dp->next;
1810   }
1811
1812   g_list_free(dp0);
1813 }
1814
1815 static void
1816 cmpl_free_state (CompletionState* cmpl_state)
1817 {
1818   cmpl_free_dir_list (cmpl_state->directory_storage);
1819   cmpl_free_dir_sent_list (cmpl_state->directory_sent_storage);
1820
1821   if (cmpl_state->user_dir_name_buffer)
1822     g_free (cmpl_state->user_dir_name_buffer);
1823   if (cmpl_state->user_directories)
1824     g_free (cmpl_state->user_directories);
1825   if (cmpl_state->the_completion.text)
1826     g_free (cmpl_state->the_completion.text);
1827   if (cmpl_state->updated_text)
1828     g_free (cmpl_state->updated_text);
1829
1830   g_free (cmpl_state);
1831 }
1832
1833 static void
1834 free_dir(CompletionDir* dir)
1835 {
1836   g_free(dir->fullname);
1837   g_free(dir);
1838 }
1839
1840 static void
1841 free_dir_sent(CompletionDirSent* sent)
1842 {
1843   gint i;
1844   for (i = 0; i < sent->entry_count; i++)
1845     g_free(sent->entries[i].entry_name);
1846   g_free(sent->entries);
1847   g_free(sent);
1848 }
1849
1850 static void
1851 prune_memory_usage(CompletionState *cmpl_state)
1852 {
1853   GList* cdsl = cmpl_state->directory_sent_storage;
1854   GList* cdl = cmpl_state->directory_storage;
1855   GList* cdl0 = cdl;
1856   gint len = 0;
1857
1858   for(; cdsl && len < CMPL_DIRECTORY_CACHE_SIZE; len += 1)
1859     cdsl = cdsl->next;
1860
1861   if (cdsl) {
1862     cmpl_free_dir_sent_list(cdsl->next);
1863     cdsl->next = NULL;
1864   }
1865
1866   cmpl_state->directory_storage = NULL;
1867   while (cdl) {
1868     if (cdl->data == cmpl_state->reference_dir)
1869       cmpl_state->directory_storage = g_list_prepend(NULL, cdl->data);
1870     else
1871       free_dir (cdl->data);
1872     cdl = cdl->next;
1873   }
1874
1875   g_list_free(cdl0);
1876 }
1877
1878 /**********************************************************************/
1879 /*                        The main entrances.                         */
1880 /**********************************************************************/
1881
1882 static PossibleCompletion*
1883 cmpl_completion_matches (gchar* text_to_complete,
1884                          gchar** remaining_text,
1885                          CompletionState* cmpl_state)
1886 {
1887   gchar* first_slash;
1888   PossibleCompletion *poss;
1889
1890   prune_memory_usage(cmpl_state);
1891
1892   g_assert (text_to_complete != NULL);
1893
1894   cmpl_state->user_completion_index = -1;
1895   cmpl_state->last_completion_text = text_to_complete;
1896   cmpl_state->the_completion.text[0] = 0;
1897   cmpl_state->last_valid_char = 0;
1898   cmpl_state->updated_text_len = -1;
1899   cmpl_state->updated_text[0] = 0;
1900   cmpl_state->re_complete = FALSE;
1901
1902 #ifdef HAVE_PWD_H
1903   first_slash = strchr (text_to_complete, G_DIR_SEPARATOR);
1904
1905   if (text_to_complete[0] == '~' && !first_slash)
1906     {
1907       /* Text starts with ~ and there is no slash, show all the
1908        * home directory completions.
1909        */
1910       poss = attempt_homedir_completion (text_to_complete, cmpl_state);
1911
1912       update_cmpl(poss, cmpl_state);
1913
1914       return poss;
1915     }
1916 #endif
1917   cmpl_state->reference_dir =
1918     open_ref_dir (text_to_complete, remaining_text, cmpl_state);
1919
1920   if(!cmpl_state->reference_dir)
1921     return NULL;
1922
1923   cmpl_state->completion_dir =
1924     find_completion_dir (*remaining_text, remaining_text, cmpl_state);
1925
1926   cmpl_state->last_valid_char = *remaining_text - text_to_complete;
1927
1928   if(!cmpl_state->completion_dir)
1929     return NULL;
1930
1931   cmpl_state->completion_dir->cmpl_index = -1;
1932   cmpl_state->completion_dir->cmpl_parent = NULL;
1933   cmpl_state->completion_dir->cmpl_text = *remaining_text;
1934
1935   cmpl_state->active_completion_dir = cmpl_state->completion_dir;
1936
1937   cmpl_state->reference_dir = cmpl_state->completion_dir;
1938
1939   poss = attempt_file_completion(cmpl_state);
1940
1941   update_cmpl(poss, cmpl_state);
1942
1943   return poss;
1944 }
1945
1946 static PossibleCompletion*
1947 cmpl_next_completion (CompletionState* cmpl_state)
1948 {
1949   PossibleCompletion* poss = NULL;
1950
1951   cmpl_state->the_completion.text[0] = 0;
1952
1953 #ifdef HAVE_PWD_H
1954   if(cmpl_state->user_completion_index >= 0)
1955     poss = attempt_homedir_completion(cmpl_state->last_completion_text, cmpl_state);
1956   else
1957     poss = attempt_file_completion(cmpl_state);
1958 #else
1959   poss = attempt_file_completion(cmpl_state);
1960 #endif
1961
1962   update_cmpl(poss, cmpl_state);
1963
1964   return poss;
1965 }
1966
1967 /**********************************************************************/
1968 /*                       Directory Operations                         */
1969 /**********************************************************************/
1970
1971 /* Open the directory where completion will begin from, if possible. */
1972 static CompletionDir*
1973 open_ref_dir(gchar* text_to_complete,
1974              gchar** remaining_text,
1975              CompletionState* cmpl_state)
1976 {
1977   gchar* first_slash;
1978   CompletionDir *new_dir;
1979
1980   first_slash = strchr(text_to_complete, G_DIR_SEPARATOR);
1981
1982 #ifdef G_WITH_CYGWIN
1983   if (text_to_complete[0] == '/' && text_to_complete[1] == '/')
1984     {
1985       char root_dir[5];
1986       sprintf(root_dir, "//%c", text_to_complete[2]);
1987
1988       new_dir = open_dir(root_dir, cmpl_state);
1989
1990       if (new_dir) {
1991         *remaining_text = text_to_complete + 4;
1992       }
1993     }
1994 #else
1995   if (FALSE)
1996     ;
1997 #endif
1998   else if (g_path_is_absolute (text_to_complete) || !cmpl_state->reference_dir)
1999     {
2000       char *root;
2001       int rootlen;
2002
2003       rootlen = g_path_skip_root (text_to_complete) - text_to_complete;
2004       root = g_malloc (rootlen + 1);
2005       memcpy (root, text_to_complete, rootlen);
2006       root[rootlen] = '\0';
2007       new_dir = open_dir (root, cmpl_state);
2008       if (new_dir)
2009         *remaining_text = g_path_skip_root (text_to_complete);
2010       g_free (root);
2011     }
2012 #ifdef HAVE_PWD_H
2013   else if (text_to_complete[0] == '~')
2014     {
2015       new_dir = open_user_dir(text_to_complete, cmpl_state);
2016
2017       if(new_dir)
2018         {
2019           if(first_slash)
2020             *remaining_text = first_slash + 1;
2021           else
2022             *remaining_text = text_to_complete + strlen(text_to_complete);
2023         }
2024       else
2025         {
2026           return NULL;
2027         }
2028     }
2029 #endif
2030   else
2031     {
2032       *remaining_text = text_to_complete;
2033
2034       new_dir = open_dir(cmpl_state->reference_dir->fullname, cmpl_state);
2035     }
2036
2037   if(new_dir)
2038     {
2039       new_dir->cmpl_index = -1;
2040       new_dir->cmpl_parent = NULL;
2041     }
2042
2043   return new_dir;
2044 }
2045
2046 #ifdef HAVE_PWD_H
2047
2048 /* open a directory by user name */
2049 static CompletionDir*
2050 open_user_dir(gchar* text_to_complete,
2051               CompletionState *cmpl_state)
2052 {
2053   gchar *first_slash;
2054   gint cmp_len;
2055
2056   g_assert(text_to_complete && text_to_complete[0] == '~');
2057
2058   first_slash = strchr(text_to_complete, G_DIR_SEPARATOR);
2059
2060   if (first_slash)
2061     cmp_len = first_slash - text_to_complete - 1;
2062   else
2063     cmp_len = strlen(text_to_complete + 1);
2064
2065   if(!cmp_len)
2066     {
2067       /* ~/ */
2068       gchar *homedir = g_get_home_dir ();
2069
2070       if (homedir)
2071         return open_dir(homedir, cmpl_state);
2072       else
2073         return NULL;
2074     }
2075   else
2076     {
2077       /* ~user/ */
2078       char* copy = g_new(char, cmp_len + 1);
2079       struct passwd *pwd;
2080       strncpy(copy, text_to_complete + 1, cmp_len);
2081       copy[cmp_len] = 0;
2082       pwd = getpwnam(copy);
2083       g_free(copy);
2084       if (!pwd)
2085         {
2086           cmpl_errno = errno;
2087           return NULL;
2088         }
2089
2090       return open_dir(pwd->pw_dir, cmpl_state);
2091     }
2092 }
2093
2094 #endif
2095
2096 /* open a directory relative the the current relative directory */
2097 static CompletionDir*
2098 open_relative_dir(gchar* dir_name,
2099                   CompletionDir* dir,
2100                   CompletionState *cmpl_state)
2101 {
2102   CompletionDir *result;
2103   GString *path;
2104
2105   path = g_string_sized_new (dir->fullname_len + strlen (dir_name) + 10);
2106   g_string_assign (path, dir->fullname);
2107
2108   if(dir->fullname_len > 1
2109     && path->str[dir->fullname_len - 1] != G_DIR_SEPARATOR)
2110      g_string_append_c (path, G_DIR_SEPARATOR);
2111   g_string_append (path, dir_name);
2112
2113   result = open_dir(path->str, cmpl_state);
2114
2115   g_string_free (path, TRUE);
2116
2117   return result;
2118 }
2119
2120 /* after the cache lookup fails, really open a new directory */
2121 static CompletionDirSent*
2122 open_new_dir(gchar* dir_name, struct stat* sbuf, gboolean stat_subdirs)
2123 {
2124   CompletionDirSent* sent;
2125   DIR* directory;
2126   gchar *buffer_ptr;
2127   struct dirent *dirent_ptr;
2128   gint entry_count = 0;
2129   gint i;
2130   struct stat ent_sbuf;
2131   GString *path;
2132   gchar *xdir, *xname;
2133   int entry_len;
2134
2135   sent = g_new(CompletionDirSent, 1);
2136   sent->mtime = sbuf->st_mtime;
2137   sent->inode = sbuf->st_ino;
2138   sent->device = sbuf->st_dev;
2139
2140   path = g_string_sized_new (2*MAXPATHLEN + 10);
2141
2142   xdir = g_filename_from_utf8 (dir_name);
2143   directory = opendir(xdir);
2144   g_free (xdir);
2145
2146   if(!directory)
2147     {
2148       cmpl_errno = errno;
2149       return NULL;
2150     }
2151
2152   while((dirent_ptr = readdir(directory)) != NULL)
2153     {
2154       entry_count++;
2155     }
2156
2157   sent->entries = g_new(CompletionDirEntry, entry_count);
2158   sent->entry_count = entry_count;
2159
2160   rewinddir(directory);
2161
2162   for(i = 0; i < entry_count; i += 1)
2163     {
2164       dirent_ptr = readdir(directory);
2165
2166       if(!dirent_ptr)
2167         {
2168           cmpl_errno = errno;
2169           closedir(directory);
2170           return NULL;
2171         }
2172
2173       sent->entries[i].entry_name = g_filename_to_utf8 (dirent_ptr->d_name);
2174
2175       g_string_assign (path, dir_name);
2176       if (path->str[path->len-1] != G_DIR_SEPARATOR)
2177         {
2178           g_string_append_c (path, G_DIR_SEPARATOR);
2179         }
2180       g_string_append (path, dirent_ptr->d_name);
2181
2182       if (stat_subdirs)
2183         {
2184           if(stat(path->str, &ent_sbuf) >= 0 && S_ISDIR(ent_sbuf.st_mode))
2185             sent->entries[i].is_dir = TRUE;
2186           else
2187             /* stat may fail, and we don't mind, since it could be a
2188              * dangling symlink. */
2189             sent->entries[i].is_dir = FALSE;
2190         }
2191       else
2192         sent->entries[i].is_dir = 1;
2193     }
2194
2195   g_string_free (path, TRUE);
2196   qsort(sent->entries, sent->entry_count, sizeof(CompletionDirEntry), compare_cmpl_dir);
2197
2198   closedir(directory);
2199
2200   return sent;
2201 }
2202
2203 #if !defined(G_OS_WIN32) && !defined(G_WITH_CYGWIN)
2204
2205 static gboolean
2206 check_dir(gchar *dir_name, struct stat *result, gboolean *stat_subdirs)
2207 {
2208   /* A list of directories that we know only contain other directories.
2209    * Trying to stat every file in these directories would be very
2210    * expensive.
2211    */
2212
2213   static struct {
2214     gchar *name;
2215     gboolean present;
2216     struct stat statbuf;
2217   } no_stat_dirs[] = {
2218     { "/afs", FALSE, { 0 } },
2219     { "/net", FALSE, { 0 } }
2220   };
2221
2222   static const gint n_no_stat_dirs = sizeof(no_stat_dirs) / sizeof(no_stat_dirs[0]);
2223   static gboolean initialized = FALSE;
2224
2225   gint i;
2226
2227   if (!initialized)
2228     {
2229       initialized = TRUE;
2230       for (i = 0; i < n_no_stat_dirs; i++)
2231         {
2232           if (stat (no_stat_dirs[i].name, &no_stat_dirs[i].statbuf) == 0)
2233             no_stat_dirs[i].present = TRUE;
2234         }
2235     }
2236
2237   if(stat(dir_name, result) < 0)
2238     {
2239       cmpl_errno = errno;
2240       return FALSE;
2241     }
2242
2243   *stat_subdirs = TRUE;
2244   for (i=0; i<n_no_stat_dirs; i++)
2245     {
2246       if (no_stat_dirs[i].present &&
2247           (no_stat_dirs[i].statbuf.st_dev == result->st_dev) &&
2248           (no_stat_dirs[i].statbuf.st_ino == result->st_ino))
2249         {
2250           *stat_subdirs = FALSE;
2251           break;
2252         }
2253     }
2254
2255   return TRUE;
2256 }
2257
2258 #endif
2259
2260 /* open a directory by absolute pathname */
2261 static CompletionDir*
2262 open_dir(gchar* dir_name, CompletionState* cmpl_state)
2263 {
2264   struct stat sbuf;
2265   gboolean stat_subdirs;
2266   CompletionDirSent *sent;
2267   GList* cdsl;
2268
2269 #if !defined(G_OS_WIN32) && !defined(G_WITH_CYGWIN)
2270   if (!check_dir (dir_name, &sbuf, &stat_subdirs))
2271     return NULL;
2272
2273   cdsl = cmpl_state->directory_sent_storage;
2274
2275   while (cdsl)
2276     {
2277       sent = cdsl->data;
2278
2279       if(sent->inode == sbuf.st_ino &&
2280          sent->mtime == sbuf.st_mtime &&
2281          sent->device == sbuf.st_dev)
2282         return attach_dir(sent, dir_name, cmpl_state);
2283
2284       cdsl = cdsl->next;
2285     }
2286 #else
2287   stat_subdirs = TRUE;
2288 #endif
2289
2290   sent = open_new_dir(dir_name, &sbuf, stat_subdirs);
2291
2292   if (sent) {
2293     cmpl_state->directory_sent_storage =
2294       g_list_prepend(cmpl_state->directory_sent_storage, sent);
2295
2296     return attach_dir(sent, dir_name, cmpl_state);
2297   }
2298
2299   return NULL;
2300 }
2301
2302 static CompletionDir*
2303 attach_dir(CompletionDirSent* sent, gchar* dir_name, CompletionState *cmpl_state)
2304 {
2305   CompletionDir* new_dir;
2306
2307   new_dir = g_new(CompletionDir, 1);
2308
2309   cmpl_state->directory_storage =
2310     g_list_prepend(cmpl_state->directory_storage, new_dir);
2311
2312   new_dir->sent = sent;
2313   new_dir->fullname = g_strdup(dir_name);
2314   new_dir->fullname_len = strlen(dir_name);
2315
2316   return new_dir;
2317 }
2318
2319 static gint
2320 correct_dir_fullname(CompletionDir* cmpl_dir)
2321 {
2322   gint length = strlen(cmpl_dir->fullname);
2323   gchar *first_slash = strchr(cmpl_dir->fullname, G_DIR_SEPARATOR);
2324   struct stat sbuf;
2325
2326   /* Does it end with /. (\.) ? */
2327   if (length >= 2 &&
2328       strcmp(cmpl_dir->fullname + length - 2, G_DIR_SEPARATOR_S ".") == 0)
2329     {
2330       /* Is it just the root directory (on a drive) ? */
2331       if (cmpl_dir->fullname + length - 2 == first_slash)
2332         {
2333           cmpl_dir->fullname[length - 1] = 0;
2334           cmpl_dir->fullname_len = length - 1;
2335           return TRUE;
2336         }
2337       else
2338         {
2339           cmpl_dir->fullname[length - 2] = 0;
2340         }
2341     }
2342
2343   /* Ends with /./ (\.\)? */
2344   else if (length >= 3 &&
2345            strcmp(cmpl_dir->fullname + length - 3,
2346                   G_DIR_SEPARATOR_S "." G_DIR_SEPARATOR_S) == 0)
2347     cmpl_dir->fullname[length - 2] = 0;
2348
2349   /* Ends with /.. (\..) ? */
2350   else if (length >= 3 &&
2351            strcmp(cmpl_dir->fullname + length - 3,
2352                   G_DIR_SEPARATOR_S "..") == 0)
2353     {
2354       /* Is it just /.. (X:\..)? */
2355       if(cmpl_dir->fullname + length - 3 == first_slash)
2356         {
2357           cmpl_dir->fullname[length - 2] = 0;
2358           cmpl_dir->fullname_len = length - 2;
2359           return TRUE;
2360         }
2361
2362       if(stat(cmpl_dir->fullname, &sbuf) < 0)
2363         {
2364           cmpl_errno = errno;
2365           return FALSE;
2366         }
2367
2368       cmpl_dir->fullname[length - 3] = 0;
2369
2370       if(!correct_parent(cmpl_dir, &sbuf))
2371         return FALSE;
2372     }
2373
2374   /* Ends with /../ (\..\)? */
2375   else if (length >= 4 &&
2376            strcmp(cmpl_dir->fullname + length - 4,
2377                   G_DIR_SEPARATOR_S ".." G_DIR_SEPARATOR_S) == 0)
2378     {
2379       /* Is it just /../ (X:\..\)? */
2380       if(cmpl_dir->fullname + length - 4 == first_slash)
2381         {
2382           cmpl_dir->fullname[length - 3] = 0;
2383           cmpl_dir->fullname_len = length - 3;
2384           return TRUE;
2385         }
2386
2387       if(stat(cmpl_dir->fullname, &sbuf) < 0)
2388         {
2389           cmpl_errno = errno;
2390           return FALSE;
2391         }
2392
2393       cmpl_dir->fullname[length - 4] = 0;
2394
2395       if(!correct_parent(cmpl_dir, &sbuf))
2396         return FALSE;
2397     }
2398
2399   cmpl_dir->fullname_len = strlen(cmpl_dir->fullname);
2400
2401   return TRUE;
2402 }
2403
2404 static gint
2405 correct_parent(CompletionDir* cmpl_dir, struct stat *sbuf)
2406 {
2407   struct stat parbuf;
2408   gchar *last_slash;
2409   gchar *first_slash;
2410   gchar *new_name;
2411   gchar c = 0;
2412
2413   last_slash = strrchr(cmpl_dir->fullname, G_DIR_SEPARATOR);
2414   g_assert(last_slash);
2415   first_slash = strchr(cmpl_dir->fullname, G_DIR_SEPARATOR);
2416
2417   /* Clever (?) way to check for top-level directory that works also on
2418    * Win32, where there is a drive letter and colon prefixed...
2419    */
2420   if (last_slash != first_slash)
2421     {
2422       last_slash[0] = 0;
2423     }
2424   else
2425     {
2426       c = last_slash[1];
2427       last_slash[1] = 0;
2428     }
2429
2430   if (stat(cmpl_dir->fullname, &parbuf) < 0)
2431     {
2432       cmpl_errno = errno;
2433       if (!c)
2434         last_slash[0] = G_DIR_SEPARATOR;
2435       return FALSE;
2436     }
2437
2438 #ifndef G_OS_WIN32              /* No inode numbers on Win32 */
2439   if (parbuf.st_ino == sbuf->st_ino && parbuf.st_dev == sbuf->st_dev)
2440     /* it wasn't a link */
2441     return TRUE;
2442
2443   if(c)
2444     last_slash[1] = c;
2445   else
2446     last_slash[0] = G_DIR_SEPARATOR;
2447
2448   /* it was a link, have to figure it out the hard way */
2449
2450   new_name = find_parent_dir_fullname(cmpl_dir->fullname);
2451
2452   if (!new_name)
2453     return FALSE;
2454
2455   g_free(cmpl_dir->fullname);
2456
2457   cmpl_dir->fullname = new_name;
2458 #endif
2459
2460   return TRUE;
2461 }
2462
2463 #ifndef G_OS_WIN32
2464
2465 static gchar*
2466 find_parent_dir_fullname(gchar* dirname)
2467 {
2468   gchar *orig_dir;
2469   gchar *result;
2470
2471   orig_dir = g_get_current_dir ();
2472
2473   if(chdir(dirname) != 0 || chdir("..") != 0)
2474     {
2475       cmpl_errno = errno;
2476       return NULL;
2477     }
2478
2479   result = g_get_current_dir ();
2480
2481   if(chdir(orig_dir) != 0)
2482     {
2483       cmpl_errno = errno;
2484       return NULL;
2485     }
2486
2487   g_free (orig_dir);
2488   return result;
2489 }
2490
2491 #endif
2492
2493 /**********************************************************************/
2494 /*                        Completion Operations                       */
2495 /**********************************************************************/
2496
2497 #ifdef HAVE_PWD_H
2498
2499 static PossibleCompletion*
2500 attempt_homedir_completion(gchar* text_to_complete,
2501                            CompletionState *cmpl_state)
2502 {
2503   gint index, length;
2504
2505   if (!cmpl_state->user_dir_name_buffer &&
2506       !get_pwdb(cmpl_state))
2507     return NULL;
2508   length = strlen(text_to_complete) - 1;
2509
2510   cmpl_state->user_completion_index += 1;
2511
2512   while(cmpl_state->user_completion_index < cmpl_state->user_directories_len)
2513     {
2514       index = first_diff_index(text_to_complete + 1,
2515                                cmpl_state->user_directories
2516                                [cmpl_state->user_completion_index].login);
2517
2518       switch(index)
2519         {
2520         case PATTERN_MATCH:
2521           break;
2522         default:
2523           if(cmpl_state->last_valid_char < (index + 1))
2524             cmpl_state->last_valid_char = index + 1;
2525           cmpl_state->user_completion_index += 1;
2526           continue;
2527         }
2528
2529       cmpl_state->the_completion.is_a_completion = 1;
2530       cmpl_state->the_completion.is_directory = TRUE;
2531
2532       append_completion_text("~", cmpl_state);
2533
2534       append_completion_text(cmpl_state->
2535                               user_directories[cmpl_state->user_completion_index].login,
2536                              cmpl_state);
2537
2538       return append_completion_text(G_DIR_SEPARATOR_S, cmpl_state);
2539     }
2540
2541   if(text_to_complete[1] ||
2542      cmpl_state->user_completion_index > cmpl_state->user_directories_len)
2543     {
2544       cmpl_state->user_completion_index = -1;
2545       return NULL;
2546     }
2547   else
2548     {
2549       cmpl_state->user_completion_index += 1;
2550       cmpl_state->the_completion.is_a_completion = 1;
2551       cmpl_state->the_completion.is_directory = TRUE;
2552
2553       return append_completion_text("~" G_DIR_SEPARATOR_S, cmpl_state);
2554     }
2555 }
2556
2557 #endif
2558
2559 #if defined(G_OS_WIN32) || defined(G_WITH_CYGWIN)
2560 #define FOLD(c) (tolower(c))
2561 #else
2562 #define FOLD(c) (c)
2563 #endif
2564
2565 /* returns the index (>= 0) of the first differing character,
2566  * PATTERN_MATCH if the completion matches */
2567 static gint
2568 first_diff_index(gchar* pat, gchar* text)
2569 {
2570   gint diff = 0;
2571
2572   while(*pat && *text && FOLD(*text) == FOLD(*pat))
2573     {
2574       pat += 1;
2575       text += 1;
2576       diff += 1;
2577     }
2578
2579   if(*pat)
2580     return diff;
2581
2582   return PATTERN_MATCH;
2583 }
2584
2585 static PossibleCompletion*
2586 append_completion_text(gchar* text, CompletionState* cmpl_state)
2587 {
2588   gint len, i = 1;
2589
2590   if(!cmpl_state->the_completion.text)
2591     return NULL;
2592
2593   len = strlen(text) + strlen(cmpl_state->the_completion.text) + 1;
2594
2595   if(cmpl_state->the_completion.text_alloc > len)
2596     {
2597       strcat(cmpl_state->the_completion.text, text);
2598       return &cmpl_state->the_completion;
2599     }
2600
2601   while(i < len) { i <<= 1; }
2602
2603   cmpl_state->the_completion.text_alloc = i;
2604
2605   cmpl_state->the_completion.text = (gchar*)g_realloc(cmpl_state->the_completion.text, i);
2606
2607   if(!cmpl_state->the_completion.text)
2608     return NULL;
2609   else
2610     {
2611       strcat(cmpl_state->the_completion.text, text);
2612       return &cmpl_state->the_completion;
2613     }
2614 }
2615
2616 static CompletionDir*
2617 find_completion_dir(gchar* text_to_complete,
2618                     gchar** remaining_text,
2619                     CompletionState* cmpl_state)
2620 {
2621   gchar* first_slash = strchr(text_to_complete, G_DIR_SEPARATOR);
2622   CompletionDir* dir = cmpl_state->reference_dir;
2623   CompletionDir* next;
2624   *remaining_text = text_to_complete;
2625
2626   while(first_slash)
2627     {
2628       gint len = first_slash - *remaining_text;
2629       gint found = 0;
2630       gchar *found_name = NULL;         /* Quiet gcc */
2631       gint i;
2632       gchar* pat_buf = g_new (gchar, len + 1);
2633
2634       strncpy(pat_buf, *remaining_text, len);
2635       pat_buf[len] = 0;
2636
2637       for(i = 0; i < dir->sent->entry_count; i += 1)
2638         {
2639           if(dir->sent->entries[i].is_dir &&
2640              fnmatch(pat_buf, dir->sent->entries[i].entry_name,
2641                      FNMATCH_FLAGS)!= FNM_NOMATCH)
2642             {
2643               if(found)
2644                 {
2645                   g_free (pat_buf);
2646                   return dir;
2647                 }
2648               else
2649                 {
2650                   found = 1;
2651                   found_name = dir->sent->entries[i].entry_name;
2652                 }
2653             }
2654         }
2655
2656       if (!found)
2657         {
2658           /* Perhaps we are trying to open an automount directory */
2659           found_name = pat_buf;
2660         }
2661
2662       next = open_relative_dir(found_name, dir, cmpl_state);
2663       
2664       if(!next)
2665         {
2666           g_free (pat_buf);
2667           return NULL;
2668         }
2669       
2670       next->cmpl_parent = dir;
2671       
2672       dir = next;
2673       
2674       if(!correct_dir_fullname(dir))
2675         {
2676           g_free(pat_buf);
2677           return NULL;
2678         }
2679       
2680       *remaining_text = first_slash + 1;
2681       first_slash = strchr(*remaining_text, G_DIR_SEPARATOR);
2682
2683       g_free (pat_buf);
2684     }
2685
2686   return dir;
2687 }
2688
2689 static void
2690 update_cmpl(PossibleCompletion* poss, CompletionState* cmpl_state)
2691 {
2692   gint cmpl_len;
2693
2694   if(!poss || !cmpl_is_a_completion(poss))
2695     return;
2696
2697   cmpl_len = strlen(cmpl_this_completion(poss));
2698
2699   if(cmpl_state->updated_text_alloc < cmpl_len + 1)
2700     {
2701       cmpl_state->updated_text =
2702         (gchar*)g_realloc(cmpl_state->updated_text,
2703                           cmpl_state->updated_text_alloc);
2704       cmpl_state->updated_text_alloc = 2*cmpl_len;
2705     }
2706
2707   if(cmpl_state->updated_text_len < 0)
2708     {
2709       strcpy(cmpl_state->updated_text, cmpl_this_completion(poss));
2710       cmpl_state->updated_text_len = cmpl_len;
2711       cmpl_state->re_complete = cmpl_is_directory(poss);
2712     }
2713   else if(cmpl_state->updated_text_len == 0)
2714     {
2715       cmpl_state->re_complete = FALSE;
2716     }
2717   else
2718     {
2719       gint first_diff =
2720         first_diff_index(cmpl_state->updated_text,
2721                          cmpl_this_completion(poss));
2722
2723       cmpl_state->re_complete = FALSE;
2724
2725       if(first_diff == PATTERN_MATCH)
2726         return;
2727
2728       if(first_diff > cmpl_state->updated_text_len)
2729         strcpy(cmpl_state->updated_text, cmpl_this_completion(poss));
2730
2731       cmpl_state->updated_text_len = first_diff;
2732       cmpl_state->updated_text[first_diff] = 0;
2733     }
2734 }
2735
2736 static PossibleCompletion*
2737 attempt_file_completion(CompletionState *cmpl_state)
2738 {
2739   gchar *pat_buf, *first_slash;
2740   CompletionDir *dir = cmpl_state->active_completion_dir;
2741
2742   dir->cmpl_index += 1;
2743
2744   if(dir->cmpl_index == dir->sent->entry_count)
2745     {
2746       if(dir->cmpl_parent == NULL)
2747         {
2748           cmpl_state->active_completion_dir = NULL;
2749
2750           return NULL;
2751         }
2752       else
2753         {
2754           cmpl_state->active_completion_dir = dir->cmpl_parent;
2755
2756           return attempt_file_completion(cmpl_state);
2757         }
2758     }
2759
2760   g_assert(dir->cmpl_text);
2761
2762   first_slash = strchr(dir->cmpl_text, G_DIR_SEPARATOR);
2763
2764   if(first_slash)
2765     {
2766       gint len = first_slash - dir->cmpl_text;
2767
2768       pat_buf = g_new (gchar, len + 1);
2769       strncpy(pat_buf, dir->cmpl_text, len);
2770       pat_buf[len] = 0;
2771     }
2772   else
2773     {
2774       gint len = strlen(dir->cmpl_text);
2775
2776       pat_buf = g_new (gchar, len + 2);
2777       strcpy(pat_buf, dir->cmpl_text);
2778       /* Don't append a * if the user entered one herself.
2779        * This way one can complete *.h and don't get matches
2780        * on any .help files, for instance.
2781        */
2782       if (strchr(pat_buf, '*') == NULL)
2783         strcpy(pat_buf + len, "*");
2784     }
2785
2786   if(first_slash)
2787     {
2788       if(dir->sent->entries[dir->cmpl_index].is_dir)
2789         {
2790           if(fnmatch(pat_buf, dir->sent->entries[dir->cmpl_index].entry_name,
2791                      FNMATCH_FLAGS) != FNM_NOMATCH)
2792             {
2793               CompletionDir* new_dir;
2794
2795               new_dir = open_relative_dir(dir->sent->entries[dir->cmpl_index].entry_name,
2796                                           dir, cmpl_state);
2797
2798               if(!new_dir)
2799                 {
2800                   g_free (pat_buf);
2801                   return NULL;
2802                 }
2803
2804               new_dir->cmpl_parent = dir;
2805
2806               new_dir->cmpl_index = -1;
2807               new_dir->cmpl_text = first_slash + 1;
2808
2809               cmpl_state->active_completion_dir = new_dir;
2810
2811               g_free (pat_buf);
2812               return attempt_file_completion(cmpl_state);
2813             }
2814           else
2815             {
2816               g_free (pat_buf);
2817               return attempt_file_completion(cmpl_state);
2818             }
2819         }
2820       else
2821         {
2822           g_free (pat_buf);
2823           return attempt_file_completion(cmpl_state);
2824         }
2825     }
2826   else
2827     {
2828       if(dir->cmpl_parent != NULL)
2829         {
2830           append_completion_text(dir->fullname +
2831                                  strlen(cmpl_state->completion_dir->fullname) + 1,
2832                                  cmpl_state);
2833           append_completion_text(G_DIR_SEPARATOR_S, cmpl_state);
2834         }
2835
2836       append_completion_text(dir->sent->entries[dir->cmpl_index].entry_name, cmpl_state);
2837
2838       cmpl_state->the_completion.is_a_completion =
2839         (fnmatch(pat_buf, dir->sent->entries[dir->cmpl_index].entry_name,
2840                  FNMATCH_FLAGS) != FNM_NOMATCH);
2841
2842       cmpl_state->the_completion.is_directory = dir->sent->entries[dir->cmpl_index].is_dir;
2843       if(dir->sent->entries[dir->cmpl_index].is_dir)
2844         append_completion_text(G_DIR_SEPARATOR_S, cmpl_state);
2845
2846       g_free (pat_buf);
2847       return &cmpl_state->the_completion;
2848     }
2849 }
2850
2851 #ifdef HAVE_PWD_H
2852
2853 static gint
2854 get_pwdb(CompletionState* cmpl_state)
2855 {
2856   struct passwd *pwd_ptr;
2857   gchar* buf_ptr;
2858   gint len = 0, i, count = 0;
2859
2860   if(cmpl_state->user_dir_name_buffer)
2861     return TRUE;
2862   setpwent ();
2863
2864   while ((pwd_ptr = getpwent()) != NULL)
2865     {
2866       len += strlen(pwd_ptr->pw_name);
2867       len += strlen(pwd_ptr->pw_dir);
2868       len += 2;
2869       count += 1;
2870     }
2871
2872   setpwent ();
2873
2874   cmpl_state->user_dir_name_buffer = g_new(gchar, len);
2875   cmpl_state->user_directories = g_new(CompletionUserDir, count);
2876   cmpl_state->user_directories_len = count;
2877
2878   buf_ptr = cmpl_state->user_dir_name_buffer;
2879
2880   for(i = 0; i < count; i += 1)
2881     {
2882       pwd_ptr = getpwent();
2883       if(!pwd_ptr)
2884         {
2885           cmpl_errno = errno;
2886           goto error;
2887         }
2888
2889       strcpy(buf_ptr, pwd_ptr->pw_name);
2890       cmpl_state->user_directories[i].login = buf_ptr;
2891       buf_ptr += strlen(buf_ptr);
2892       buf_ptr += 1;
2893       strcpy(buf_ptr, pwd_ptr->pw_dir);
2894       cmpl_state->user_directories[i].homedir = buf_ptr;
2895       buf_ptr += strlen(buf_ptr);
2896       buf_ptr += 1;
2897     }
2898
2899   qsort(cmpl_state->user_directories,
2900         cmpl_state->user_directories_len,
2901         sizeof(CompletionUserDir),
2902         compare_user_dir);
2903
2904   endpwent();
2905
2906   return TRUE;
2907
2908 error:
2909
2910   if(cmpl_state->user_dir_name_buffer)
2911     g_free(cmpl_state->user_dir_name_buffer);
2912   if(cmpl_state->user_directories)
2913     g_free(cmpl_state->user_directories);
2914
2915   cmpl_state->user_dir_name_buffer = NULL;
2916   cmpl_state->user_directories = NULL;
2917
2918   return FALSE;
2919 }
2920
2921 static gint
2922 compare_user_dir(const void* a, const void* b)
2923 {
2924   return strcmp((((CompletionUserDir*)a))->login,
2925                 (((CompletionUserDir*)b))->login);
2926 }
2927
2928 #endif
2929
2930 static gint
2931 compare_cmpl_dir(const void* a, const void* b)
2932 {
2933 #if !defined(G_OS_WIN32) && !defined(G_WITH_CYGWIN)
2934   return strcmp((((CompletionDirEntry*)a))->entry_name,
2935                 (((CompletionDirEntry*)b))->entry_name);
2936 #else
2937   return g_strcasecmp((((CompletionDirEntry*)a))->entry_name,
2938                       (((CompletionDirEntry*)b))->entry_name);
2939 #endif
2940 }
2941
2942 static gint
2943 cmpl_state_okay(CompletionState* cmpl_state)
2944 {
2945   return  cmpl_state && cmpl_state->reference_dir;
2946 }
2947
2948 static gchar*
2949 cmpl_strerror(gint err)
2950 {
2951   if(err == CMPL_ERRNO_TOO_LONG)
2952     return "Name too long";
2953   else
2954     return g_strerror (err);
2955 }