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