2 * \file FormFiledialog.C
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
9 * Full author contact details are available in file CREDITS.
14 #include "FormFiledialog.h"
15 #include "forms/form_filedialog.h"
17 #include "forms_gettext.h"
18 #include "xforms_helpers.h"
20 #include "frontends/Dialogs.h"
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"
31 #include "lyx_forms.h"
33 #include <boost/bind.hpp>
34 #include <boost/regex.hpp>
35 #include <boost/tokenizer.hpp>
51 # define dirent direct
53 # include <sys/ndir.h>
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;
81 using std::ostringstream;
86 using namespace lyx::frontend;
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.
99 vector<string> const expand_globs(string const & mask,
100 string const & directory)
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(" ");
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());
120 // six months, in seconds
121 long const SIX_MONTH_SEC = 6L * 30L * 24L * 60L * 60L;
123 long const ONE_HOUR_SEC = 60L * 60L;
128 int C_LyXFileDlg_CancelCB(FL_FORM *fl, void *xev)
130 return FileDialog::Private::CancelCB(fl, xev);
134 void C_LyXFileDlg_DoubleClickCB(FL_OBJECT * ob, long data)
136 FileDialog::Private::DoubleClickCB(ob, data);
140 void C_LyXFileDlg_FileDlgCB(FL_OBJECT * ob, long data)
142 FileDialog::Private::FileDlgCB(ob, data);
147 // *** User cache class implementation
148 /// User cache class definition
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()) {
162 void add(uid_t ID) const;
164 typedef map<uid_t, string> Users;
170 void UserCache::add(uid_t ID) const
172 struct passwd const * entry = getpwuid(ID);
173 users[ID] = entry ? entry->pw_name : tostr(int(ID));
177 /// Group cache class definition
180 /// seeks group name from group ID
181 string const & find(gid_t ID) const ;
184 void add(gid_t ID) const;
186 typedef map<gid_t, string> Groups;
188 mutable Groups groups;
192 string const & GroupCache::find(gid_t ID) const
194 Groups::const_iterator cit = groups.find(ID);
195 if (cit == groups.end()) {
203 void GroupCache::add(gid_t ID) const
205 struct group const * entry = getgrgid(ID);
206 groups[ID] = entry ? entry->gr_name : tostr(int(ID));
210 UserCache lyxUserCache;
211 GroupCache lyxGroupCache;
213 // compares two LyXDirEntry objects content (used for sort)
214 class comp_direntry : public std::binary_function<DirEntry, DirEntry, bool> {
216 bool operator()(DirEntry const & r1, DirEntry const & r2) const
218 bool const r1d = suffixIs(r1.name_, '/');
219 bool const r2d = suffixIs(r2.name_, '/');
224 return r1.name_ < r2.name_;
232 // *** FileDialog::Private class implementation
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;
241 // Reread: updates dialog list to match class directory
242 void FileDialog::Private::Reread()
245 DIR * dir = ::opendir(directory_.c_str());
249 Alert::err_alert(_("Warning! Couldn't open directory."),
252 directory_ = getcwd();
253 dir = ::opendir(directory_.c_str());
256 // Clear the present namelist
257 dir_entries_.clear();
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());
264 // Splits complete directory name into directories and compute depth
268 string File = directory_;
270 File = split(File, Temp, '/');
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, '/');
280 vector<string> const glob_matches = expand_globs(mask_, directory_);
282 time_t curTime = time(0);
284 while (dirent * entry = readdir(dir)) {
285 bool isLink = false, isDir = false;
287 // If the pattern doesn't start with a dot, skip hidden files
288 if (!mask_.empty() && mask_[0] != '.' &&
289 entry->d_name[0] == '.')
293 string fname = entry->d_name;
295 // Under all circumstances, "." and ".." are not wanted
296 if (fname == "." || fname == "..")
300 File = AddName(directory_, fname);
302 FileInfo fileInfo(File, true);
304 // can this really happen?
305 if (!fileInfo.isOK())
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());
313 time_t modtime = fileInfo.getModificationTime();
314 string Time = ctime(&modtime);
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.
324 Time.erase(15, string::npos);
326 Time.erase(16, string::npos);
329 string buffer = mode + ' ' +
333 Time.substr(4, string::npos) + ' ';
335 buffer += entry->d_name;
336 buffer += fileInfo.typeIndicator();
338 isLink = fileInfo.isLink();
342 if (LyXReadLink(File, Link)) {
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?
352 fileInfo.newFile(File);
354 buffer += fileInfo.typeIndicator();
360 // filters files according to pattern and type
361 if (fileInfo.isRegular()
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)
370 } else if (!(isDir = fileInfo.isDir()))
375 // Note ls_entry_ is an string!
376 tmp.ls_entry_ = buffer;
383 // creates displayed name
384 temp = entry->d_name;
388 temp += fileInfo.typeIndicator();
389 tmp.displayed_ = temp;
391 dir_entries_.push_back(tmp);
397 sort(dir_entries_.begin(), dir_entries_.end(), comp_direntry());
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());
405 fl_set_browser_topline(file_dlg_form_->List, depth_);
406 fl_show_object(file_dlg_form_->List);
411 // SetDirectory: sets dialog current directory
412 void FileDialog::Private::SetDirectory(string const & path)
418 tmp = MakeAbsPath(ExpandPath(path), directory_);
420 // must check the directory exists
421 DIR * dir = ::opendir(tmp.c_str());
425 Alert::err_alert(_("Warning! Couldn't open directory."), tmp);
434 void FileDialog::Private::SetFilters(string const & mask)
436 SetFilters(FileFilterList(mask));
440 void FileDialog::Private::SetFilters(FileFilterList const & filters)
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();
453 for (glob_iterator it = begin; it != end; ++it) {
460 fl_set_input(file_dlg_form_->PatBox, mask_.c_str());
464 // SetInfoLine: sets dialog information line
465 void FileDialog::Private::SetInfoLine(string const & line)
468 fl_set_object_label(file_dlg_form_->FileInfo, info_line_.c_str());
472 FileDialog::Private::Private()
474 directory_ = MakeAbsPath(string("."));
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);
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,
507 fl_hide_object(file_dlg_form_->User1);
508 fl_hide_object(file_dlg_form_->User2);
510 r_ = Dialogs::redrawGUI().connect(boost::bind(&FileDialog::Private::redraw, this));
514 FileDialog::Private::~Private()
520 void FileDialog::Private::redraw()
522 if (file_dlg_form_->form && file_dlg_form_->form->visible)
523 fl_redraw_form(file_dlg_form_->form);
527 // SetButton: sets file selector user button action
528 void FileDialog::Private::SetButton(int index, string const & name,
535 ob = file_dlg_form_->User1;
537 } else if (index == 1) {
538 ob = file_dlg_form_->User2;
545 fl_set_object_label(ob, idex(name).c_str());
546 fl_set_button_shortcut(ob, scex(name).c_str(), 1);
556 // GetDirectory: gets last dialog directory
557 string const FileDialog::Private::GetDirectory() const
559 if (!directory_.empty())
566 bool x_sync_kludge(bool ret)
568 XSync(fl_get_display(), false);
573 // RunDialog: handle dialog during file selection
574 bool FileDialog::Private::RunDialog()
576 force_cancel_ = false;
581 FL_OBJECT * ob = fl_do_forms();
583 if (ob == file_dlg_form_->Ready) {
585 return x_sync_kludge(true);
587 } else if (ob == file_dlg_form_->Cancel || force_cancel_)
588 return x_sync_kludge(false);
591 return x_sync_kludge(true);
596 // XForms objects callback (static)
597 void FileDialog::Private::FileDlgCB(FL_OBJECT *, long arg)
604 case 0: // get directory
605 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
606 current_dlg_->Reread();
610 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
611 current_dlg_->Reread();
615 current_dlg_->HandleListHit();
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();
625 current_dlg_->SetDirectory(GetEnvPath("HOME"));
626 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
627 current_dlg_->Reread();
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();
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();
646 // Handle callback from list
647 void FileDialog::Private::HandleListHit()
650 int const select_ = fl_get_browser(file_dlg_form_->List);
651 if (select_ > depth_)
652 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
654 SetInfoLine(string());
658 // Callback for double click in list
659 void FileDialog::Private::DoubleClickCB(FL_OBJECT *, long)
661 // Simulate click on OK button
662 if (current_dlg_->HandleDoubleClick())
663 current_dlg_->Force(false);
667 // Handle double click from list
668 bool FileDialog::Private::HandleDoubleClick()
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, '/')) {
680 fl_set_input(file_dlg_form_->Filename, tmp.c_str());
682 } else if (select_ != 0) {
683 SetInfoLine(string());
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, '/'))
700 // Directory higher up
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);
718 // Handle OK button call
719 bool FileDialog::Private::HandleOK()
722 string tmp = fl_get_input(file_dlg_form_->PatBox);
729 // directory was changed
730 tmp = fl_get_input(file_dlg_form_->DirBox);
731 if (tmp != directory_) {
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);
745 fl_set_input(file_dlg_form_->Filename, temp.c_str());
750 // Emulate a doubleclick
751 return HandleDoubleClick();
755 // Handle Cancel CB from WM close
756 int FileDialog::Private::CancelCB(FL_FORM *, void *)
758 // Simulate a click on the cancel button
759 current_dlg_->Force(true);
764 // Simulates a click on OK/Cancel
765 void FileDialog::Private::Force(bool cancel)
768 force_cancel_ = true;
769 fl_set_button(file_dlg_form_->Cancel, 1);
772 fl_set_button(file_dlg_form_->Ready, 1);
774 // Start timer to break fl_do_forms loop soon
775 fl_set_timer(file_dlg_form_->timer, 0.1);
779 // Select: launches dialog and returns selected file
780 string const FileDialog::Private::Select(string const & title,
782 FileFilterList const & filters,
783 string const & suggested)
785 // handles new mask and path
790 // highlight the suggested file in the browser, if it exists.
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);
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);
809 // checks whether dialog can be started
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_);
828 fl_show_form(file_dlg_form_->form,
829 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
832 bool const isOk = RunDialog();
834 fl_hide_form(file_dlg_form_->form);
835 fl_activate_all_forms();
838 // Returns filename or string() if no valid selection was made
839 if (!isOk || !fl_get_input(file_dlg_form_->Filename)[0])
842 file_name_ = fl_get_input(file_dlg_form_->Filename);
844 if (!AbsolutePath(file_name_))
845 file_name_ = AddName(fl_get_input(file_dlg_form_->DirBox), file_name_);
850 // SelectDir: launches dialog and returns selected directory
851 string const FileDialog::Private::SelectDir(string const & title,
853 string const & suggested)
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, '/'))
865 string full_path = path;
867 // check if this is really a directory
868 DIR * dir = ::opendir(full_path.c_str());
870 SetDirectory(full_path);
880 // checks whether dialog can be started
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,
899 fl_hide_form(file_dlg_form_->form);
900 fl_activate_all_forms();
903 // Returns directory or string() if no valid selection was made
907 file_name_ = fl_get_input(file_dlg_form_->DirBox);