]> git.lyx.org Git - lyx.git/blob - src/frontends/xforms/FormFiledialog.C
Clean-up FileFilterList API.
[lyx.git] / src / frontends / xforms / FormFiledialog.C
1 /**
2  * \file FormFiledialog.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author unknown
7  * \author John Levon
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "FormFiledialog.h"
15 #include "forms/form_filedialog.h"
16
17 #include "forms_gettext.h"
18 #include "xforms_helpers.h"
19
20 #include "frontends/Dialogs.h"
21
22 #include "support/FileInfo.h"
23 #include "support/filefilterlist.h"
24 #include "support/filetools.h"
25 #include "support/globbing.h"
26 #include "support/lstrings.h"
27 #include "support/lyxlib.h"
28 #include "support/path.h"
29 #include "support/tostr.h"
30
31 #include "lyx_forms.h"
32
33 #include <boost/bind.hpp>
34 #include <boost/regex.hpp>
35 #include <boost/tokenizer.hpp>
36
37 #include <algorithm>
38 #include <map>
39 #include <sstream>
40
41 #include <grp.h>
42 #include <pwd.h>
43
44 //#ifdef HAVE_ERRNO_H
45 //#include <cerrno>
46 //#endif
47
48 #if HAVE_DIRENT_H
49 # include <dirent.h>
50 #else
51 # define dirent direct
52 # if HAVE_SYS_NDIR_H
53 #  include <sys/ndir.h>
54 # endif
55 # if HAVE_SYS_DIR_H
56 #  include <sys/dir.h>
57 # endif
58 # if HAVE_NDIR_H
59 #  include <ndir.h>
60 # endif
61 #endif
62
63 using lyx::support::AbsolutePath;
64 using lyx::support::AddName;
65 using lyx::support::ExpandPath;
66 using lyx::support::FileFilterList;
67 using lyx::support::FileInfo;
68 using lyx::support::getcwd;
69 using lyx::support::GetEnvPath;
70 using lyx::support::LyXReadLink;
71 using lyx::support::MakeAbsPath;
72 using lyx::support::OnlyFilename;
73 using lyx::support::Path;
74 using lyx::support::split;
75 using lyx::support::subst;
76 using lyx::support::suffixIs;
77 using lyx::support::trim;
78
79 using std::max;
80 using std::sort;
81 using std::ostringstream;
82 using std::string;
83 using std::map;
84 using std::vector;
85
86 using namespace lyx::frontend;
87
88 namespace {
89
90 /** Given a string "<glob> <glob> <glob>", expand each glob in turn.
91  *  Any glob that cannot be expanded is ignored silently.
92  *  Invokes \c convert_brace_glob and \c glob internally, so use only
93  *  on systems supporting the Posix function 'glob'.
94  *  \param mask the string "<glob> <glob> <glob>".
95  *  \param directory the current working directory from
96  *  which \c glob is invoked.
97  *  \returns a vector of all matching file names.
98  */
99 vector<string> const expand_globs(string const & mask,
100                                   string const & directory)
101 {
102         Path p(directory);
103
104         // Split into individual globs and then call 'glob' on each one.
105         typedef boost::tokenizer<boost::char_separator<char> > Tokenizer;
106         boost::char_separator<char> const separator(" ");
107
108         vector<string> matches;
109         Tokenizer const tokens(mask, separator);
110         Tokenizer::const_iterator it = tokens.begin();
111         Tokenizer::const_iterator const end = tokens.end();
112         for (; it != end; ++it) {
113                 vector<string> const tmp = lyx::support::glob(*it);
114                 matches.insert(matches.end(), tmp.begin(), tmp.end());
115         }
116         return matches;
117 }
118
119
120 // six months, in seconds
121 long const SIX_MONTH_SEC = 6L * 30L * 24L * 60L * 60L;
122 //static
123 long const ONE_HOUR_SEC = 60L * 60L;
124
125 extern "C" {
126
127         static
128         int C_LyXFileDlg_CancelCB(FL_FORM *fl, void *xev)
129         {
130                 return FileDialog::Private::CancelCB(fl, xev);
131         }
132
133         static
134         void C_LyXFileDlg_DoubleClickCB(FL_OBJECT * ob, long data)
135         {
136                 FileDialog::Private::DoubleClickCB(ob, data);
137         }
138
139         static
140         void C_LyXFileDlg_FileDlgCB(FL_OBJECT * ob, long data)
141         {
142                 FileDialog::Private::FileDlgCB(ob, data);
143         }
144
145 }
146
147 // *** User cache class implementation
148 /// User cache class definition
149 class UserCache {
150 public:
151         /// seeks user name from group ID
152         string const & find(uid_t ID) const {
153                 Users::const_iterator cit = users.find(ID);
154                 if (cit == users.end()) {
155                         add(ID);
156                         return users[ID];
157                 }
158                 return cit->second;
159         }
160 private:
161         ///
162         void add(uid_t ID) const;
163         ///
164         typedef map<uid_t, string> Users;
165         ///
166         mutable Users users;
167 };
168
169
170 void UserCache::add(uid_t ID) const
171 {
172         struct passwd const * entry = getpwuid(ID);
173         users[ID] = entry ? entry->pw_name : tostr(int(ID));
174 }
175
176
177 /// Group cache class definition
178 class GroupCache {
179 public:
180         /// seeks group name from group ID
181         string const & find(gid_t ID) const ;
182 private:
183         ///
184         void add(gid_t ID) const;
185         ///
186         typedef map<gid_t, string> Groups;
187         ///
188         mutable Groups groups;
189 };
190
191
192 string const & GroupCache::find(gid_t ID) const
193 {
194         Groups::const_iterator cit = groups.find(ID);
195         if (cit == groups.end()) {
196                 add(ID);
197                 return groups[ID];
198         }
199         return cit->second;
200 }
201
202
203 void GroupCache::add(gid_t ID) const
204 {
205         struct group const * entry = getgrgid(ID);
206         groups[ID] = entry ? entry->gr_name : tostr(int(ID));
207 }
208
209 // local instances
210 UserCache lyxUserCache;
211 GroupCache lyxGroupCache;
212
213 // compares two LyXDirEntry objects content (used for sort)
214 class comp_direntry : public std::binary_function<DirEntry, DirEntry, bool> {
215 public:
216         bool operator()(DirEntry const & r1, DirEntry const & r2) const
217         {
218                 bool const r1d = suffixIs(r1.name_, '/');
219                 bool const r2d = suffixIs(r2.name_, '/');
220                 if (r1d && !r2d)
221                         return true;
222                 if (!r1d && r2d)
223                         return false;
224                 return r1.name_ < r2.name_;
225         }
226 };
227
228 } // namespace anon
229
230
231
232 // *** FileDialog::Private class implementation
233
234 // static members
235 FD_filedialog * FileDialog::Private::file_dlg_form_ = 0;
236 FileDialog::Private * FileDialog::Private::current_dlg_ = 0;
237 int FileDialog::Private::minw_ = 0;
238 int FileDialog::Private::minh_ = 0;
239
240
241 // Reread: updates dialog list to match class directory
242 void FileDialog::Private::Reread()
243 {
244         // Opens directory
245         DIR * dir = ::opendir(directory_.c_str());
246         if (!dir) {
247 // FIXME: re-add ...
248 #if 0
249                 Alert::err_alert(_("Warning! Couldn't open directory."),
250                         directory_);
251 #endif
252                 directory_ = getcwd();
253                 dir = ::opendir(directory_.c_str());
254         }
255
256         // Clear the present namelist
257         dir_entries_.clear();
258
259         // Updates display
260         fl_hide_object(file_dlg_form_->List);
261         fl_clear_browser(file_dlg_form_->List);
262         fl_set_input(file_dlg_form_->DirBox, directory_.c_str());
263
264         // Splits complete directory name into directories and compute depth
265         depth_ = 0;
266         string line, Temp;
267         string mode;
268         string File = directory_;
269         if (File != "/")
270                 File = split(File, Temp, '/');
271
272         while (!File.empty() || !Temp.empty()) {
273                 string dline = "@b" + line + Temp + '/';
274                 fl_add_browser_line(file_dlg_form_->List, dline.c_str());
275                 File = split(File, Temp, '/');
276                 line += ' ';
277                 ++depth_;
278         }
279
280         vector<string> const glob_matches = expand_globs(mask_, directory_);
281
282         time_t curTime = time(0);
283         rewinddir(dir);
284         while (dirent * entry = readdir(dir)) {
285                 bool isLink = false, isDir = false;
286
287                 // If the pattern doesn't start with a dot, skip hidden files
288                 if (!mask_.empty() && mask_[0] != '.' &&
289                     entry->d_name[0] == '.')
290                         continue;
291
292                 // Gets filename
293                 string fname = entry->d_name;
294
295                 // Under all circumstances, "." and ".." are not wanted
296                 if (fname == "." || fname == "..")
297                         continue;
298
299                 // gets file status
300                 File = AddName(directory_, fname);
301
302                 FileInfo fileInfo(File, true);
303
304                 // can this really happen?
305                 if (!fileInfo.isOK())
306                         continue;
307
308                 mode = fileInfo.modeString();
309                 unsigned int const nlink = fileInfo.getNumberOfLinks();
310                 string const user  = lyxUserCache.find(fileInfo.getUid());
311                 string const group = lyxGroupCache.find(fileInfo.getGid());
312
313                 time_t modtime = fileInfo.getModificationTime();
314                 string Time = ctime(&modtime);
315
316                 if (curTime > modtime + SIX_MONTH_SEC
317                     || curTime < modtime + ONE_HOUR_SEC) {
318                         // The file is fairly old or in the future. POSIX says
319                         // the cutoff is 6 months old. Allow a 1 hour slop
320                         // factor for what is considered "the future", to
321                         // allow for NFS server/client clock disagreement.
322                         // Show the year instead of the time of day.
323                         Time.erase(10, 9);
324                         Time.erase(15, string::npos);
325                 } else {
326                         Time.erase(16, string::npos);
327                 }
328
329                 string buffer = mode + ' ' +
330                         tostr(nlink) + ' ' +
331                         user + ' ' +
332                         group + ' ' +
333                         Time.substr(4, string::npos) + ' ';
334
335                 buffer += entry->d_name;
336                 buffer += fileInfo.typeIndicator();
337
338                 isLink = fileInfo.isLink();
339                 if (isLink) {
340                         string Link;
341
342                         if (LyXReadLink(File, Link)) {
343                                 buffer += " -> ";
344                                 buffer += Link;
345
346                                 // This gives the FileType of the file that
347                                 // is really pointed to after resolving all
348                                 // symlinks. This is not necessarily the same
349                                 // as the type of Link (which could again be a
350                                 // link). Is that intended?
351                                 //                              JV 199902
352                                 fileInfo.newFile(File);
353                                 if (fileInfo.isOK())
354                                         buffer += fileInfo.typeIndicator();
355                                 else
356                                         continue;
357                         }
358                 }
359
360                 // filters files according to pattern and type
361                 if (fileInfo.isRegular()
362                     || fileInfo.isChar()
363                     || fileInfo.isBlock()
364                     || fileInfo.isFifo()) {
365                         typedef vector<string>::const_iterator viterator;
366                         viterator gbegin = glob_matches.begin();
367                         viterator const gend = glob_matches.end();
368                         if (std::find(gbegin, gend, fname) == gend)
369                                 continue;
370                 } else if (!(isDir = fileInfo.isDir()))
371                         continue;
372
373                 DirEntry tmp;
374
375                 // Note ls_entry_ is an string!
376                 tmp.ls_entry_ = buffer;
377                 // creates used name
378                 string temp = fname;
379                 if (isDir)
380                         temp += '/';
381
382                 tmp.name_ = temp;
383                 // creates displayed name
384                 temp = entry->d_name;
385                 if (isLink)
386                         temp += '@';
387                 else
388                         temp += fileInfo.typeIndicator();
389                 tmp.displayed_ = temp;
390
391                 dir_entries_.push_back(tmp);
392         }
393
394         closedir(dir);
395
396         // Sort the names
397         sort(dir_entries_.begin(), dir_entries_.end(), comp_direntry());
398
399         // Add them to directory box
400         for (DirEntries::const_iterator cit = dir_entries_.begin();
401              cit != dir_entries_.end(); ++cit) {
402                 string const temp = line + cit->displayed_;
403                 fl_add_browser_line(file_dlg_form_->List, temp.c_str());
404         }
405         fl_set_browser_topline(file_dlg_form_->List, depth_);
406         fl_show_object(file_dlg_form_->List);
407         last_sel_ = -1;
408 }
409
410
411 // SetDirectory: sets dialog current directory
412 void FileDialog::Private::SetDirectory(string const & path)
413 {
414         string tmp;
415         if (path.empty())
416                 tmp = getcwd();
417         else
418                 tmp = MakeAbsPath(ExpandPath(path), directory_);
419
420         // must check the directory exists
421         DIR * dir = ::opendir(tmp.c_str());
422         if (!dir) {
423 // FIXME: re-add ...
424 #if 0
425                 Alert::err_alert(_("Warning! Couldn't open directory."), tmp);
426 #endif
427         } else {
428                 ::closedir(dir);
429                 directory_ = tmp;
430         }
431 }
432
433
434 void FileDialog::Private::SetFilters(string const & mask)
435 {
436         SetFilters(FileFilterList(mask));
437 }
438
439
440 void FileDialog::Private::SetFilters(FileFilterList const & filters)
441 {
442         if (filters.empty())
443                 return;
444
445         // Just take the first one for now.
446         typedef FileFilterList::Filter::glob_iterator glob_iterator;
447         glob_iterator const begin = filters[0].begin();
448         glob_iterator const end = filters[0].end();
449         if (begin == end)
450                 return;
451
452         ostringstream ss;
453         for (glob_iterator it = begin; it != end; ++it) {
454                 if (it != begin)
455                         ss << ' ';
456                 ss << *it;
457         }
458                 
459         mask_ = ss.str();
460         fl_set_input(file_dlg_form_->PatBox, mask_.c_str());
461 }
462
463
464 // SetInfoLine: sets dialog information line
465 void FileDialog::Private::SetInfoLine(string const & line)
466 {
467         info_line_ = line;
468         fl_set_object_label(file_dlg_form_->FileInfo, info_line_.c_str());
469 }
470
471
472 FileDialog::Private::Private()
473 {
474         directory_ = MakeAbsPath(string("."));
475
476         // Creates form if necessary.
477         if (!file_dlg_form_) {
478                 file_dlg_form_ = build_filedialog(this);
479                 minw_ = file_dlg_form_->form->w;
480                 minh_ = file_dlg_form_->form->h;
481                 // Set callbacks. This means that we don't need a patch file
482                 fl_set_object_callback(file_dlg_form_->DirBox,
483                                        C_LyXFileDlg_FileDlgCB, 0);
484                 fl_set_object_callback(file_dlg_form_->PatBox,
485                                        C_LyXFileDlg_FileDlgCB, 1);
486                 fl_set_object_callback(file_dlg_form_->List,
487                                        C_LyXFileDlg_FileDlgCB, 2);
488                 fl_set_object_callback(file_dlg_form_->Filename,
489                                        C_LyXFileDlg_FileDlgCB, 3);
490                 fl_set_object_callback(file_dlg_form_->Rescan,
491                                        C_LyXFileDlg_FileDlgCB, 10);
492                 fl_set_object_callback(file_dlg_form_->Home,
493                                        C_LyXFileDlg_FileDlgCB, 11);
494                 fl_set_object_callback(file_dlg_form_->User1,
495                                        C_LyXFileDlg_FileDlgCB, 12);
496                 fl_set_object_callback(file_dlg_form_->User2,
497                                        C_LyXFileDlg_FileDlgCB, 13);
498
499                 // Make sure pressing the close box doesn't crash LyX. (RvdK)
500                 fl_set_form_atclose(file_dlg_form_->form,
501                                     C_LyXFileDlg_CancelCB, 0);
502                 // Register doubleclick callback
503                 fl_set_browser_dblclick_callback(file_dlg_form_->List,
504                                                  C_LyXFileDlg_DoubleClickCB,
505                                                  0);
506         }
507         fl_hide_object(file_dlg_form_->User1);
508         fl_hide_object(file_dlg_form_->User2);
509
510         r_ = Dialogs::redrawGUI().connect(boost::bind(&FileDialog::Private::redraw, this));
511 }
512
513
514 FileDialog::Private::~Private()
515 {
516         r_.disconnect();
517 }
518
519
520 void FileDialog::Private::redraw()
521 {
522         if (file_dlg_form_->form && file_dlg_form_->form->visible)
523                 fl_redraw_form(file_dlg_form_->form);
524 }
525
526
527 // SetButton: sets file selector user button action
528 void FileDialog::Private::SetButton(int index, string const & name,
529                            string const & path)
530 {
531         FL_OBJECT * ob;
532         string * tmp;
533
534         if (index == 0) {
535                 ob = file_dlg_form_->User1;
536                 tmp = &user_path1_;
537         } else if (index == 1) {
538                 ob = file_dlg_form_->User2;
539                 tmp = &user_path2_;
540         } else {
541                 return;
542         }
543
544         if (!name.empty()) {
545                 fl_set_object_label(ob, idex(name).c_str());
546                 fl_set_button_shortcut(ob, scex(name).c_str(), 1);
547                 fl_show_object(ob);
548                 *tmp = path;
549         } else {
550                 fl_hide_object(ob);
551                 tmp->erase();
552         }
553 }
554
555
556 // GetDirectory: gets last dialog directory
557 string const FileDialog::Private::GetDirectory() const
558 {
559         if (!directory_.empty())
560                 return directory_;
561         else
562                 return string(".");
563 }
564
565 namespace {
566         bool x_sync_kludge(bool ret)
567         {
568                 XSync(fl_get_display(), false);
569                 return ret;
570         }
571 } // namespace anon
572
573 // RunDialog: handle dialog during file selection
574 bool FileDialog::Private::RunDialog()
575 {
576         force_cancel_ = false;
577         force_ok_ = false;
578
579         // event loop
580         while (true) {
581                 FL_OBJECT * ob = fl_do_forms();
582
583                 if (ob == file_dlg_form_->Ready) {
584                         if (HandleOK())
585                                 return x_sync_kludge(true);
586
587                 } else if (ob == file_dlg_form_->Cancel || force_cancel_)
588                         return x_sync_kludge(false);
589
590                 else if (force_ok_)
591                         return x_sync_kludge(true);
592         }
593 }
594
595
596 // XForms objects callback (static)
597 void FileDialog::Private::FileDlgCB(FL_OBJECT *, long arg)
598 {
599         if (!current_dlg_)
600                 return;
601
602         switch (arg) {
603
604         case 0: // get directory
605                 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
606                 current_dlg_->Reread();
607                 break;
608
609         case 1: // get mask
610                 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
611                 current_dlg_->Reread();
612                 break;
613
614         case 2: // list
615                 current_dlg_->HandleListHit();
616                 break;
617
618         case 10: // rescan
619                 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
620                 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
621                 current_dlg_->Reread();
622                 break;
623
624         case 11: // home
625                 current_dlg_->SetDirectory(GetEnvPath("HOME"));
626                 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
627                 current_dlg_->Reread();
628                 break;
629
630         case 12: // user button 1
631                 current_dlg_->SetDirectory(current_dlg_->user_path1_);
632                 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
633                 current_dlg_->Reread();
634                 break;
635
636         case 13: // user button 2
637                 current_dlg_->SetDirectory(current_dlg_->user_path2_);
638                 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
639                 current_dlg_->Reread();
640                 break;
641
642         }
643 }
644
645
646 // Handle callback from list
647 void FileDialog::Private::HandleListHit()
648 {
649         // set info line
650         int const select_ = fl_get_browser(file_dlg_form_->List);
651         if (select_ > depth_)
652                 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
653         else
654                 SetInfoLine(string());
655 }
656
657
658 // Callback for double click in list
659 void FileDialog::Private::DoubleClickCB(FL_OBJECT *, long)
660 {
661         // Simulate click on OK button
662         if (current_dlg_->HandleDoubleClick())
663                 current_dlg_->Force(false);
664 }
665
666
667 // Handle double click from list
668 bool FileDialog::Private::HandleDoubleClick()
669 {
670         string tmp;
671
672         // set info line
673         bool isDir = true;
674         int const select_ = fl_get_browser(file_dlg_form_->List);
675         if (select_ > depth_) {
676                 tmp = dir_entries_[select_ - depth_ - 1].name_;
677                 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
678                 if (!suffixIs(tmp, '/')) {
679                         isDir = false;
680                         fl_set_input(file_dlg_form_->Filename, tmp.c_str());
681                 }
682         } else if (select_ != 0) {
683                 SetInfoLine(string());
684         } else
685                 return true;
686
687         // executes action
688         if (isDir) {
689                 string Temp;
690
691                 // builds new directory name
692                 if (select_ > depth_) {
693                         // Directory deeper down
694                         // First, get directory with trailing /
695                         Temp = fl_get_input(file_dlg_form_->DirBox);
696                         if (!suffixIs(Temp, '/'))
697                                 Temp += '/';
698                         Temp += tmp;
699                 } else {
700                         // Directory higher up
701                         Temp.erase();
702                         for (int i = 0; i < select_; ++i) {
703                                 string piece = fl_get_browser_line(file_dlg_form_->List, i+1);
704                                 // The '+2' is here to count the '@b' (JMarc)
705                                 Temp += piece.substr(i + 2);
706                         }
707                 }
708
709                 // assigns it
710                 SetDirectory(Temp);
711                 Reread();
712                 return false;
713         }
714         return true;
715 }
716
717
718 // Handle OK button call
719 bool FileDialog::Private::HandleOK()
720 {
721         // mask was changed
722         string tmp = fl_get_input(file_dlg_form_->PatBox);
723         if (tmp != mask_) {
724                 SetFilters(tmp);
725                 Reread();
726                 return false;
727         }
728
729         // directory was changed
730         tmp = fl_get_input(file_dlg_form_->DirBox);
731         if (tmp != directory_) {
732                 SetDirectory(tmp);
733                 Reread();
734                 return false;
735         }
736
737         // Handle return from list
738         int const select = fl_get_browser(file_dlg_form_->List);
739         if (select > depth_) {
740                 string const temp = dir_entries_[select - depth_ - 1].name_;
741                 if (!suffixIs(temp, '/')) {
742                         // If user didn't type anything, use browser
743                         string const name = fl_get_input(file_dlg_form_->Filename);
744                         if (name.empty())
745                                 fl_set_input(file_dlg_form_->Filename, temp.c_str());
746                         return true;
747                 }
748         }
749
750         // Emulate a doubleclick
751         return HandleDoubleClick();
752 }
753
754
755 // Handle Cancel CB from WM close
756 int FileDialog::Private::CancelCB(FL_FORM *, void *)
757 {
758         // Simulate a click on the cancel button
759         current_dlg_->Force(true);
760         return FL_IGNORE;
761 }
762
763
764 // Simulates a click on OK/Cancel
765 void FileDialog::Private::Force(bool cancel)
766 {
767         if (cancel) {
768                 force_cancel_ = true;
769                 fl_set_button(file_dlg_form_->Cancel, 1);
770         } else {
771                 force_ok_ = true;
772                 fl_set_button(file_dlg_form_->Ready, 1);
773         }
774         // Start timer to break fl_do_forms loop soon
775         fl_set_timer(file_dlg_form_->timer, 0.1);
776 }
777
778
779 // Select: launches dialog and returns selected file
780 string const FileDialog::Private::Select(string const & title,
781                                          string const & path,
782                                          FileFilterList const & filters,
783                                          string const & suggested)
784 {
785         // handles new mask and path
786         SetFilters(filters);
787         SetDirectory(path);
788         Reread();
789
790         // highlight the suggested file in the browser, if it exists.
791         int sel = 0;
792         string const filename = OnlyFilename(suggested);
793         if (!filename.empty()) {
794                 for (int i = 0; i < fl_get_browser_maxline(file_dlg_form_->List); ++i) {
795                         string s = fl_get_browser_line(file_dlg_form_->List, i + 1);
796                         s = trim(s);
797                         if (s == filename) {
798                                 sel = i + 1;
799                                 break;
800                         }
801                 }
802         }
803
804         if (sel != 0)
805                 fl_select_browser_line(file_dlg_form_->List, sel);
806         int const top = max(sel - 5, 1);
807         fl_set_browser_topline(file_dlg_form_->List, top);
808
809         // checks whether dialog can be started
810         if (current_dlg_)
811                 return string();
812         current_dlg_ = this;
813
814         // runs dialog
815         SetInfoLine(string());
816         setEnabled(file_dlg_form_->Filename, true);
817         fl_set_input(file_dlg_form_->Filename, suggested.c_str());
818         fl_set_button(file_dlg_form_->Cancel, 0);
819         fl_set_button(file_dlg_form_->Ready, 0);
820         fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->Filename);
821         fl_deactivate_all_forms();
822         // Prevent xforms crashing if the dialog gets too small by preventing
823         // it from being shrunk beyond a minimum size.
824         // calls to fl_set_form_minsize/maxsize apply only to the next
825         // fl_show_form(), so this comes first.
826         fl_set_form_minsize(file_dlg_form_->form, minw_, minh_);
827
828         fl_show_form(file_dlg_form_->form,
829                      FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
830                      title.c_str());
831
832         bool const isOk = RunDialog();
833
834         fl_hide_form(file_dlg_form_->form);
835         fl_activate_all_forms();
836         current_dlg_ = 0;
837
838         // Returns filename or string() if no valid selection was made
839         if (!isOk || !fl_get_input(file_dlg_form_->Filename)[0])
840                 return string();
841
842         file_name_ = fl_get_input(file_dlg_form_->Filename);
843
844         if (!AbsolutePath(file_name_))
845                 file_name_ = AddName(fl_get_input(file_dlg_form_->DirBox), file_name_);
846         return file_name_;
847 }
848
849
850 // SelectDir: launches dialog and returns selected directory
851 string const FileDialog::Private::SelectDir(string const & title,
852                                          string const & path,
853                                          string const & suggested)
854 {
855         SetFilters("*/");
856         // handles new path
857         bool isOk = true;
858         if (!path.empty()) {
859                 // handle case where path does not end with "/"
860                 // remerge path+suggested and check if it is a valid path
861                 if (!suggested.empty()) {
862                         string tmp = suggested;
863                         if (!suffixIs(tmp, '/'))
864                                 tmp += '/';
865                         string full_path = path;
866                         full_path += tmp;
867                         // check if this is really a directory
868                         DIR * dir = ::opendir(full_path.c_str());
869                         if (dir)
870                                 SetDirectory(full_path);
871                         else
872                                 SetDirectory(path);
873                 } else
874                         SetDirectory(path);
875                 isOk = false;
876         }
877         if (!isOk)
878                 Reread();
879
880         // checks whether dialog can be started
881         if (current_dlg_)
882                 return string();
883         current_dlg_ = this;
884
885         // runs dialog
886         SetInfoLine(string());
887         fl_set_input(file_dlg_form_->Filename, "");
888         setEnabled(file_dlg_form_->Filename, false);
889         fl_set_button(file_dlg_form_->Cancel, 0);
890         fl_set_button(file_dlg_form_->Ready, 0);
891         fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->DirBox);
892         fl_deactivate_all_forms();
893         fl_show_form(file_dlg_form_->form,
894                      FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
895                      title.c_str());
896
897         isOk = RunDialog();
898
899         fl_hide_form(file_dlg_form_->form);
900         fl_activate_all_forms();
901         current_dlg_ = 0;
902
903         // Returns directory or string() if no valid selection was made
904         if (!isOk)
905                 return string();
906
907         file_name_ = fl_get_input(file_dlg_form_->DirBox);
908         return file_name_;
909 }