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