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