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