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