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