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/tostr.h"
30 #include "lyx_forms.h"
32 #include <boost/bind.hpp>
33 #include <boost/regex.hpp>
34 #include <boost/tokenizer.hpp>
50 # define dirent direct
52 # include <sys/ndir.h>
62 using lyx::support::AbsolutePath;
63 using lyx::support::AddName;
64 using lyx::support::ExpandPath;
65 using lyx::support::FileFilterList;
66 using lyx::support::FileInfo;
67 using lyx::support::getcwd;
68 using lyx::support::GetEnvPath;
69 using lyx::support::LyXReadLink;
70 using lyx::support::MakeAbsPath;
71 using lyx::support::OnlyFilename;
72 using lyx::support::split;
73 using lyx::support::subst;
74 using lyx::support::suffixIs;
75 using lyx::support::trim;
79 using std::ostringstream;
84 using namespace lyx::frontend;
88 /** Given a string "<glob> <glob> <glob>", expand each glob in turn.
89 * Any glob that cannot be expanded is ignored silently.
90 * Invokes \c convert_brace_glob and \c glob internally, so use only
91 * on systems supporting the Posix function 'glob'.
92 * \param mask the string "<glob> <glob> <glob>".
93 * \param directory the current working directory from
94 * which \c glob is invoked.
95 * \returns a vector of all matching file names.
97 vector<string> const expand_globs(string const & mask,
98 string const & directory)
100 // Split into individual globs and then call 'glob' on each one.
101 typedef boost::tokenizer<boost::char_separator<char> > Tokenizer;
102 boost::char_separator<char> const separator(" ");
104 vector<string> matches;
105 Tokenizer const tokens(mask, separator);
106 Tokenizer::const_iterator it = tokens.begin();
107 Tokenizer::const_iterator const end = tokens.end();
108 for (; it != end; ++it)
109 lyx::support::glob(matches, *it, directory);
115 // six months, in seconds
116 long const SIX_MONTH_SEC = 6L * 30L * 24L * 60L * 60L;
118 long const ONE_HOUR_SEC = 60L * 60L;
123 int C_LyXFileDlg_CancelCB(FL_FORM *fl, void *xev)
125 return FileDialog::Private::CancelCB(fl, xev);
129 void C_LyXFileDlg_DoubleClickCB(FL_OBJECT * ob, long data)
131 FileDialog::Private::DoubleClickCB(ob, data);
135 void C_LyXFileDlg_FileDlgCB(FL_OBJECT * ob, long data)
137 FileDialog::Private::FileDlgCB(ob, data);
142 // *** User cache class implementation
143 /// User cache class definition
146 /// seeks user name from group ID
147 string const & find(uid_t ID) const {
148 Users::const_iterator cit = users.find(ID);
149 if (cit == users.end()) {
157 void add(uid_t ID) const;
159 typedef map<uid_t, string> Users;
165 void UserCache::add(uid_t ID) const
167 struct passwd const * entry = getpwuid(ID);
168 users[ID] = entry ? entry->pw_name : tostr(int(ID));
172 /// Group cache class definition
175 /// seeks group name from group ID
176 string const & find(gid_t ID) const ;
179 void add(gid_t ID) const;
181 typedef map<gid_t, string> Groups;
183 mutable Groups groups;
187 string const & GroupCache::find(gid_t ID) const
189 Groups::const_iterator cit = groups.find(ID);
190 if (cit == groups.end()) {
198 void GroupCache::add(gid_t ID) const
200 struct group const * entry = getgrgid(ID);
201 groups[ID] = entry ? entry->gr_name : tostr(int(ID));
205 UserCache lyxUserCache;
206 GroupCache lyxGroupCache;
208 // compares two LyXDirEntry objects content (used for sort)
209 class comp_direntry : public std::binary_function<DirEntry, DirEntry, bool> {
211 bool operator()(DirEntry const & r1, DirEntry const & r2) const
213 bool const r1d = suffixIs(r1.name_, '/');
214 bool const r2d = suffixIs(r2.name_, '/');
219 return r1.name_ < r2.name_;
227 // *** FileDialog::Private class implementation
230 FD_filedialog * FileDialog::Private::file_dlg_form_ = 0;
231 FileDialog::Private * FileDialog::Private::current_dlg_ = 0;
232 int FileDialog::Private::minw_ = 0;
233 int FileDialog::Private::minh_ = 0;
236 // Reread: updates dialog list to match class directory
237 void FileDialog::Private::Reread()
240 DIR * dir = ::opendir(directory_.c_str());
244 Alert::err_alert(_("Warning! Couldn't open directory."),
247 directory_ = getcwd();
248 dir = ::opendir(directory_.c_str());
251 // Clear the present namelist
252 dir_entries_.clear();
255 fl_hide_object(file_dlg_form_->List);
256 fl_clear_browser(file_dlg_form_->List);
257 fl_set_input(file_dlg_form_->DirBox, directory_.c_str());
259 // Splits complete directory name into directories and compute depth
263 string File = directory_;
265 File = split(File, Temp, '/');
267 while (!File.empty() || !Temp.empty()) {
268 string dline = "@b" + line + Temp + '/';
269 fl_add_browser_line(file_dlg_form_->List, dline.c_str());
270 File = split(File, Temp, '/');
275 vector<string> const glob_matches = expand_globs(mask_, directory_);
277 time_t curTime = time(0);
279 while (dirent * entry = readdir(dir)) {
280 bool isLink = false, isDir = false;
282 // If the pattern doesn't start with a dot, skip hidden files
283 if (!mask_.empty() && mask_[0] != '.' &&
284 entry->d_name[0] == '.')
288 string fname = entry->d_name;
290 // Under all circumstances, "." and ".." are not wanted
291 if (fname == "." || fname == "..")
295 File = AddName(directory_, fname);
297 FileInfo fileInfo(File, true);
299 // can this really happen?
300 if (!fileInfo.isOK())
303 mode = fileInfo.modeString();
304 unsigned int const nlink = fileInfo.getNumberOfLinks();
305 string const user = lyxUserCache.find(fileInfo.getUid());
306 string const group = lyxGroupCache.find(fileInfo.getGid());
308 time_t modtime = fileInfo.getModificationTime();
309 string Time = ctime(&modtime);
311 if (curTime > modtime + SIX_MONTH_SEC
312 || curTime < modtime + ONE_HOUR_SEC) {
313 // The file is fairly old or in the future. POSIX says
314 // the cutoff is 6 months old. Allow a 1 hour slop
315 // factor for what is considered "the future", to
316 // allow for NFS server/client clock disagreement.
317 // Show the year instead of the time of day.
319 Time.erase(15, string::npos);
321 Time.erase(16, string::npos);
324 string buffer = mode + ' ' +
328 Time.substr(4, string::npos) + ' ';
330 buffer += entry->d_name;
331 buffer += fileInfo.typeIndicator();
333 isLink = fileInfo.isLink();
337 if (LyXReadLink(File, Link)) {
341 // This gives the FileType of the file that
342 // is really pointed to after resolving all
343 // symlinks. This is not necessarily the same
344 // as the type of Link (which could again be a
345 // link). Is that intended?
347 fileInfo.newFile(File);
349 buffer += fileInfo.typeIndicator();
355 // filters files according to pattern and type
356 if (fileInfo.isRegular()
358 || fileInfo.isBlock()
359 || fileInfo.isFifo()) {
360 typedef vector<string>::const_iterator viterator;
361 viterator gbegin = glob_matches.begin();
362 viterator const gend = glob_matches.end();
363 if (std::find(gbegin, gend, fname) == gend)
365 } else if (!(isDir = fileInfo.isDir()))
370 // Note ls_entry_ is an string!
371 tmp.ls_entry_ = buffer;
378 // creates displayed name
379 temp = entry->d_name;
383 temp += fileInfo.typeIndicator();
384 tmp.displayed_ = temp;
386 dir_entries_.push_back(tmp);
392 sort(dir_entries_.begin(), dir_entries_.end(), comp_direntry());
394 // Add them to directory box
395 for (DirEntries::const_iterator cit = dir_entries_.begin();
396 cit != dir_entries_.end(); ++cit) {
397 string const temp = line + cit->displayed_;
398 fl_add_browser_line(file_dlg_form_->List, temp.c_str());
400 fl_set_browser_topline(file_dlg_form_->List, depth_);
401 fl_show_object(file_dlg_form_->List);
406 // SetDirectory: sets dialog current directory
407 void FileDialog::Private::SetDirectory(string const & path)
413 tmp = MakeAbsPath(ExpandPath(path), directory_);
415 // must check the directory exists
416 DIR * dir = ::opendir(tmp.c_str());
420 Alert::err_alert(_("Warning! Couldn't open directory."), tmp);
429 void FileDialog::Private::SetFilters(string const & mask)
431 SetFilters(FileFilterList(mask));
435 void FileDialog::Private::SetFilters(FileFilterList const & filters)
440 // Just take the first one for now.
441 typedef FileFilterList::Filter::glob_iterator glob_iterator;
442 glob_iterator const begin = filters[0].begin();
443 glob_iterator const end = filters[0].end();
448 for (glob_iterator it = begin; it != end; ++it) {
455 fl_set_input(file_dlg_form_->PatBox, mask_.c_str());
459 // SetInfoLine: sets dialog information line
460 void FileDialog::Private::SetInfoLine(string const & line)
463 fl_set_object_label(file_dlg_form_->FileInfo, info_line_.c_str());
467 FileDialog::Private::Private()
469 directory_ = MakeAbsPath(string("."));
471 // Creates form if necessary.
472 if (!file_dlg_form_) {
473 file_dlg_form_ = build_filedialog(this);
474 minw_ = file_dlg_form_->form->w;
475 minh_ = file_dlg_form_->form->h;
476 // Set callbacks. This means that we don't need a patch file
477 fl_set_object_callback(file_dlg_form_->DirBox,
478 C_LyXFileDlg_FileDlgCB, 0);
479 fl_set_object_callback(file_dlg_form_->PatBox,
480 C_LyXFileDlg_FileDlgCB, 1);
481 fl_set_object_callback(file_dlg_form_->List,
482 C_LyXFileDlg_FileDlgCB, 2);
483 fl_set_object_callback(file_dlg_form_->Filename,
484 C_LyXFileDlg_FileDlgCB, 3);
485 fl_set_object_callback(file_dlg_form_->Rescan,
486 C_LyXFileDlg_FileDlgCB, 10);
487 fl_set_object_callback(file_dlg_form_->Home,
488 C_LyXFileDlg_FileDlgCB, 11);
489 fl_set_object_callback(file_dlg_form_->User1,
490 C_LyXFileDlg_FileDlgCB, 12);
491 fl_set_object_callback(file_dlg_form_->User2,
492 C_LyXFileDlg_FileDlgCB, 13);
494 // Make sure pressing the close box doesn't crash LyX. (RvdK)
495 fl_set_form_atclose(file_dlg_form_->form,
496 C_LyXFileDlg_CancelCB, 0);
497 // Register doubleclick callback
498 fl_set_browser_dblclick_callback(file_dlg_form_->List,
499 C_LyXFileDlg_DoubleClickCB,
502 fl_hide_object(file_dlg_form_->User1);
503 fl_hide_object(file_dlg_form_->User2);
505 r_ = Dialogs::redrawGUI().connect(boost::bind(&FileDialog::Private::redraw, this));
509 FileDialog::Private::~Private()
515 void FileDialog::Private::redraw()
517 if (file_dlg_form_->form && file_dlg_form_->form->visible)
518 fl_redraw_form(file_dlg_form_->form);
522 // SetButton: sets file selector user button action
523 void FileDialog::Private::SetButton(int index, string const & name,
530 ob = file_dlg_form_->User1;
532 } else if (index == 1) {
533 ob = file_dlg_form_->User2;
540 fl_set_object_label(ob, idex(name).c_str());
541 fl_set_button_shortcut(ob, scex(name).c_str(), 1);
551 // GetDirectory: gets last dialog directory
552 string const FileDialog::Private::GetDirectory() const
554 if (!directory_.empty())
561 bool x_sync_kludge(bool ret)
563 XSync(fl_get_display(), false);
568 // RunDialog: handle dialog during file selection
569 bool FileDialog::Private::RunDialog()
571 force_cancel_ = false;
576 FL_OBJECT * ob = fl_do_forms();
578 if (ob == file_dlg_form_->Ready) {
580 return x_sync_kludge(true);
582 } else if (ob == file_dlg_form_->Cancel || force_cancel_)
583 return x_sync_kludge(false);
586 return x_sync_kludge(true);
591 // XForms objects callback (static)
592 void FileDialog::Private::FileDlgCB(FL_OBJECT *, long arg)
599 case 0: // get directory
600 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
601 current_dlg_->Reread();
605 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
606 current_dlg_->Reread();
610 current_dlg_->HandleListHit();
614 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
615 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
616 current_dlg_->Reread();
620 current_dlg_->SetDirectory(GetEnvPath("HOME"));
621 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
622 current_dlg_->Reread();
625 case 12: // user button 1
626 current_dlg_->SetDirectory(current_dlg_->user_path1_);
627 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
628 current_dlg_->Reread();
631 case 13: // user button 2
632 current_dlg_->SetDirectory(current_dlg_->user_path2_);
633 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
634 current_dlg_->Reread();
641 // Handle callback from list
642 void FileDialog::Private::HandleListHit()
645 int const select_ = fl_get_browser(file_dlg_form_->List);
646 if (select_ > depth_)
647 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
649 SetInfoLine(string());
653 // Callback for double click in list
654 void FileDialog::Private::DoubleClickCB(FL_OBJECT *, long)
656 // Simulate click on OK button
657 if (current_dlg_->HandleDoubleClick())
658 current_dlg_->Force(false);
662 // Handle double click from list
663 bool FileDialog::Private::HandleDoubleClick()
669 int const select_ = fl_get_browser(file_dlg_form_->List);
670 if (select_ > depth_) {
671 tmp = dir_entries_[select_ - depth_ - 1].name_;
672 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
673 if (!suffixIs(tmp, '/')) {
675 fl_set_input(file_dlg_form_->Filename, tmp.c_str());
677 } else if (select_ != 0) {
678 SetInfoLine(string());
686 // builds new directory name
687 if (select_ > depth_) {
688 // Directory deeper down
689 // First, get directory with trailing /
690 Temp = fl_get_input(file_dlg_form_->DirBox);
691 if (!suffixIs(Temp, '/'))
695 // Directory higher up
697 for (int i = 0; i < select_; ++i) {
698 string piece = fl_get_browser_line(file_dlg_form_->List, i+1);
699 // The '+2' is here to count the '@b' (JMarc)
700 Temp += piece.substr(i + 2);
713 // Handle OK button call
714 bool FileDialog::Private::HandleOK()
717 string tmp = fl_get_input(file_dlg_form_->PatBox);
724 // directory was changed
725 tmp = fl_get_input(file_dlg_form_->DirBox);
726 if (tmp != directory_) {
732 // Handle return from list
733 int const select = fl_get_browser(file_dlg_form_->List);
734 if (select > depth_) {
735 string const temp = dir_entries_[select - depth_ - 1].name_;
736 if (!suffixIs(temp, '/')) {
737 // If user didn't type anything, use browser
738 string const name = fl_get_input(file_dlg_form_->Filename);
740 fl_set_input(file_dlg_form_->Filename, temp.c_str());
745 // Emulate a doubleclick
746 return HandleDoubleClick();
750 // Handle Cancel CB from WM close
751 int FileDialog::Private::CancelCB(FL_FORM *, void *)
753 // Simulate a click on the cancel button
754 current_dlg_->Force(true);
759 // Simulates a click on OK/Cancel
760 void FileDialog::Private::Force(bool cancel)
763 force_cancel_ = true;
764 fl_set_button(file_dlg_form_->Cancel, 1);
767 fl_set_button(file_dlg_form_->Ready, 1);
769 // Start timer to break fl_do_forms loop soon
770 fl_set_timer(file_dlg_form_->timer, 0.1);
774 // Select: launches dialog and returns selected file
775 string const FileDialog::Private::Select(string const & title,
777 FileFilterList const & filters,
778 string const & suggested)
780 // handles new mask and path
785 // highlight the suggested file in the browser, if it exists.
787 string const filename = OnlyFilename(suggested);
788 if (!filename.empty()) {
789 for (int i = 0; i < fl_get_browser_maxline(file_dlg_form_->List); ++i) {
790 string s = fl_get_browser_line(file_dlg_form_->List, i + 1);
800 fl_select_browser_line(file_dlg_form_->List, sel);
801 int const top = max(sel - 5, 1);
802 fl_set_browser_topline(file_dlg_form_->List, top);
804 // checks whether dialog can be started
810 SetInfoLine(string());
811 setEnabled(file_dlg_form_->Filename, true);
812 fl_set_input(file_dlg_form_->Filename, suggested.c_str());
813 fl_set_button(file_dlg_form_->Cancel, 0);
814 fl_set_button(file_dlg_form_->Ready, 0);
815 fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->Filename);
816 fl_deactivate_all_forms();
817 // Prevent xforms crashing if the dialog gets too small by preventing
818 // it from being shrunk beyond a minimum size.
819 // calls to fl_set_form_minsize/maxsize apply only to the next
820 // fl_show_form(), so this comes first.
821 fl_set_form_minsize(file_dlg_form_->form, minw_, minh_);
823 fl_show_form(file_dlg_form_->form,
824 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
827 bool const isOk = RunDialog();
829 fl_hide_form(file_dlg_form_->form);
830 fl_activate_all_forms();
833 // Returns filename or string() if no valid selection was made
834 if (!isOk || !fl_get_input(file_dlg_form_->Filename)[0])
837 file_name_ = fl_get_input(file_dlg_form_->Filename);
839 if (!AbsolutePath(file_name_))
840 file_name_ = AddName(fl_get_input(file_dlg_form_->DirBox), file_name_);
845 // SelectDir: launches dialog and returns selected directory
846 string const FileDialog::Private::SelectDir(string const & title,
848 string const & suggested)
854 // handle case where path does not end with "/"
855 // remerge path+suggested and check if it is a valid path
856 if (!suggested.empty()) {
857 string tmp = suggested;
858 if (!suffixIs(tmp, '/'))
860 string full_path = path;
862 // check if this is really a directory
863 DIR * dir = ::opendir(full_path.c_str());
865 SetDirectory(full_path);
875 // checks whether dialog can be started
881 SetInfoLine(string());
882 fl_set_input(file_dlg_form_->Filename, "");
883 setEnabled(file_dlg_form_->Filename, false);
884 fl_set_button(file_dlg_form_->Cancel, 0);
885 fl_set_button(file_dlg_form_->Ready, 0);
886 fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->DirBox);
887 fl_deactivate_all_forms();
888 fl_show_form(file_dlg_form_->form,
889 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
894 fl_hide_form(file_dlg_form_->form);
895 fl_activate_all_forms();
898 // Returns directory or string() if no valid selection was made
902 file_name_ = fl_get_input(file_dlg_form_->DirBox);