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