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>
47 # define dirent direct
49 # include <sys/ndir.h>
59 using lyx::support::AbsolutePath;
60 using lyx::support::AddName;
61 using lyx::support::ExpandPath;
62 using lyx::support::FileFilterList;
63 using lyx::support::FileInfo;
64 using lyx::support::getcwd;
65 using lyx::support::GetEnvPath;
66 using lyx::support::LyXReadLink;
67 using lyx::support::MakeAbsPath;
68 using lyx::support::OnlyFilename;
69 using lyx::support::split;
70 using lyx::support::subst;
71 using lyx::support::suffixIs;
72 using lyx::support::trim;
80 using namespace lyx::frontend;
84 // six months, in seconds
85 long const SIX_MONTH_SEC = 6L * 30L * 24L * 60L * 60L;
87 long const ONE_HOUR_SEC = 60L * 60L;
92 int C_LyXFileDlg_CancelCB(FL_FORM *fl, void *xev)
94 return FileDialog::Private::CancelCB(fl, xev);
98 void C_LyXFileDlg_DoubleClickCB(FL_OBJECT * ob, long data)
100 FileDialog::Private::DoubleClickCB(ob, data);
104 void C_LyXFileDlg_FileDlgCB(FL_OBJECT * ob, long data)
106 FileDialog::Private::FileDlgCB(ob, data);
111 // *** User cache class implementation
112 /// User cache class definition
115 /// seeks user name from group ID
116 string const & find(uid_t ID) const {
117 Users::const_iterator cit = users.find(ID);
118 if (cit == users.end()) {
126 void add(uid_t ID) const;
128 typedef map<uid_t, string> Users;
134 void UserCache::add(uid_t ID) const
136 struct passwd const * entry = getpwuid(ID);
137 users[ID] = entry ? entry->pw_name : tostr(int(ID));
141 /// Group cache class definition
144 /// seeks group name from group ID
145 string const & find(gid_t ID) const ;
148 void add(gid_t ID) const;
150 typedef map<gid_t, string> Groups;
152 mutable Groups groups;
156 string const & GroupCache::find(gid_t ID) const
158 Groups::const_iterator cit = groups.find(ID);
159 if (cit == groups.end()) {
167 void GroupCache::add(gid_t ID) const
169 struct group const * entry = getgrgid(ID);
170 groups[ID] = entry ? entry->gr_name : tostr(int(ID));
174 UserCache lyxUserCache;
175 GroupCache lyxGroupCache;
177 // compares two LyXDirEntry objects content (used for sort)
178 class comp_direntry : public std::binary_function<DirEntry, DirEntry, bool> {
180 bool operator()(DirEntry const & r1, DirEntry const & r2) const
182 bool const r1d = suffixIs(r1.name_, '/');
183 bool const r2d = suffixIs(r2.name_, '/');
188 return r1.name_ < r2.name_;
196 // *** FileDialog::Private class implementation
199 FD_filedialog * FileDialog::Private::file_dlg_form_ = 0;
200 FileDialog::Private * FileDialog::Private::current_dlg_ = 0;
201 int FileDialog::Private::minw_ = 0;
202 int FileDialog::Private::minh_ = 0;
205 // Reread: updates dialog list to match class directory
206 void FileDialog::Private::Reread()
209 DIR * dir = ::opendir(directory_.c_str());
213 Alert::err_alert(_("Warning! Couldn't open directory."),
216 directory_ = getcwd();
217 dir = ::opendir(directory_.c_str());
220 // Clear the present namelist
221 dir_entries_.clear();
224 fl_hide_object(file_dlg_form_->List);
225 fl_clear_browser(file_dlg_form_->List);
226 fl_set_input(file_dlg_form_->DirBox, directory_.c_str());
228 // Splits complete directory name into directories and compute depth
232 string File = directory_;
234 File = split(File, Temp, '/');
236 while (!File.empty() || !Temp.empty()) {
237 string dline = "@b" + line + Temp + '/';
238 fl_add_browser_line(file_dlg_form_->List, dline.c_str());
239 File = split(File, Temp, '/');
244 vector<string> const glob_matches =
245 lyx::support::expand_globs(mask_, directory_);
247 time_t curTime = time(0);
249 while (dirent * entry = readdir(dir)) {
250 bool isLink = false, isDir = false;
252 // If the pattern doesn't start with a dot, skip hidden files
253 if (!mask_.empty() && mask_[0] != '.' &&
254 entry->d_name[0] == '.')
258 string fname = entry->d_name;
260 // Under all circumstances, "." and ".." are not wanted
261 if (fname == "." || fname == "..")
265 File = AddName(directory_, fname);
267 FileInfo fileInfo(File, true);
269 // can this really happen?
270 if (!fileInfo.isOK())
273 mode = fileInfo.modeString();
274 unsigned int const nlink = fileInfo.getNumberOfLinks();
275 string const user = lyxUserCache.find(fileInfo.getUid());
276 string const group = lyxGroupCache.find(fileInfo.getGid());
278 time_t modtime = fileInfo.getModificationTime();
279 string Time = ctime(&modtime);
281 if (curTime > modtime + SIX_MONTH_SEC
282 || curTime < modtime + ONE_HOUR_SEC) {
283 // The file is fairly old or in the future. POSIX says
284 // the cutoff is 6 months old. Allow a 1 hour slop
285 // factor for what is considered "the future", to
286 // allow for NFS server/client clock disagreement.
287 // Show the year instead of the time of day.
289 Time.erase(15, string::npos);
291 Time.erase(16, string::npos);
294 string buffer = mode + ' ' +
298 Time.substr(4, string::npos) + ' ';
300 buffer += entry->d_name;
301 buffer += fileInfo.typeIndicator();
303 isLink = fileInfo.isLink();
307 if (LyXReadLink(File, Link)) {
311 // This gives the FileType of the file that
312 // is really pointed to after resolving all
313 // symlinks. This is not necessarily the same
314 // as the type of Link (which could again be a
315 // link). Is that intended?
317 fileInfo.newFile(File);
319 buffer += fileInfo.typeIndicator();
325 // filters files according to pattern and type
326 if (fileInfo.isRegular()
328 || fileInfo.isBlock()
329 || fileInfo.isFifo()) {
330 typedef vector<string>::const_iterator viterator;
331 viterator gbegin = glob_matches.begin();
332 viterator const gend = glob_matches.end();
333 if (std::find(gbegin, gend, fname) == gend)
335 } else if (!(isDir = fileInfo.isDir()))
340 // Note ls_entry_ is an string!
341 tmp.ls_entry_ = buffer;
348 // creates displayed name
349 temp = entry->d_name;
353 temp += fileInfo.typeIndicator();
354 tmp.displayed_ = temp;
356 dir_entries_.push_back(tmp);
362 sort(dir_entries_.begin(), dir_entries_.end(), comp_direntry());
364 // Add them to directory box
365 for (DirEntries::const_iterator cit = dir_entries_.begin();
366 cit != dir_entries_.end(); ++cit) {
367 string const temp = line + cit->displayed_;
368 fl_add_browser_line(file_dlg_form_->List, temp.c_str());
370 fl_set_browser_topline(file_dlg_form_->List, depth_);
371 fl_show_object(file_dlg_form_->List);
376 // SetDirectory: sets dialog current directory
377 void FileDialog::Private::SetDirectory(string const & path)
383 tmp = MakeAbsPath(ExpandPath(path), directory_);
385 // must check the directory exists
386 DIR * dir = ::opendir(tmp.c_str());
390 Alert::err_alert(_("Warning! Couldn't open directory."), tmp);
399 void FileDialog::Private::SetFilters(string const & mask)
401 SetFilters(FileFilterList(mask));
405 void FileDialog::Private::SetFilters(FileFilterList const & filters)
407 // Just take the first one for now.
408 mask_ = filters.filters()[0].globs();
409 fl_set_input(file_dlg_form_->PatBox, mask_.c_str());
413 // SetInfoLine: sets dialog information line
414 void FileDialog::Private::SetInfoLine(string const & line)
417 fl_set_object_label(file_dlg_form_->FileInfo, info_line_.c_str());
421 FileDialog::Private::Private()
423 directory_ = MakeAbsPath(string("."));
425 // Creates form if necessary.
426 if (!file_dlg_form_) {
427 file_dlg_form_ = build_filedialog(this);
428 minw_ = file_dlg_form_->form->w;
429 minh_ = file_dlg_form_->form->h;
430 // Set callbacks. This means that we don't need a patch file
431 fl_set_object_callback(file_dlg_form_->DirBox,
432 C_LyXFileDlg_FileDlgCB, 0);
433 fl_set_object_callback(file_dlg_form_->PatBox,
434 C_LyXFileDlg_FileDlgCB, 1);
435 fl_set_object_callback(file_dlg_form_->List,
436 C_LyXFileDlg_FileDlgCB, 2);
437 fl_set_object_callback(file_dlg_form_->Filename,
438 C_LyXFileDlg_FileDlgCB, 3);
439 fl_set_object_callback(file_dlg_form_->Rescan,
440 C_LyXFileDlg_FileDlgCB, 10);
441 fl_set_object_callback(file_dlg_form_->Home,
442 C_LyXFileDlg_FileDlgCB, 11);
443 fl_set_object_callback(file_dlg_form_->User1,
444 C_LyXFileDlg_FileDlgCB, 12);
445 fl_set_object_callback(file_dlg_form_->User2,
446 C_LyXFileDlg_FileDlgCB, 13);
448 // Make sure pressing the close box doesn't crash LyX. (RvdK)
449 fl_set_form_atclose(file_dlg_form_->form,
450 C_LyXFileDlg_CancelCB, 0);
451 // Register doubleclick callback
452 fl_set_browser_dblclick_callback(file_dlg_form_->List,
453 C_LyXFileDlg_DoubleClickCB,
456 fl_hide_object(file_dlg_form_->User1);
457 fl_hide_object(file_dlg_form_->User2);
459 r_ = Dialogs::redrawGUI().connect(boost::bind(&FileDialog::Private::redraw, this));
463 FileDialog::Private::~Private()
469 void FileDialog::Private::redraw()
471 if (file_dlg_form_->form && file_dlg_form_->form->visible)
472 fl_redraw_form(file_dlg_form_->form);
476 // SetButton: sets file selector user button action
477 void FileDialog::Private::SetButton(int index, string const & name,
484 ob = file_dlg_form_->User1;
486 } else if (index == 1) {
487 ob = file_dlg_form_->User2;
494 fl_set_object_label(ob, idex(name).c_str());
495 fl_set_button_shortcut(ob, scex(name).c_str(), 1);
505 // GetDirectory: gets last dialog directory
506 string const FileDialog::Private::GetDirectory() const
508 if (!directory_.empty())
515 bool x_sync_kludge(bool ret)
517 XSync(fl_get_display(), false);
522 // RunDialog: handle dialog during file selection
523 bool FileDialog::Private::RunDialog()
525 force_cancel_ = false;
530 FL_OBJECT * ob = fl_do_forms();
532 if (ob == file_dlg_form_->Ready) {
534 return x_sync_kludge(true);
536 } else if (ob == file_dlg_form_->Cancel || force_cancel_)
537 return x_sync_kludge(false);
540 return x_sync_kludge(true);
545 // XForms objects callback (static)
546 void FileDialog::Private::FileDlgCB(FL_OBJECT *, long arg)
553 case 0: // get directory
554 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
555 current_dlg_->Reread();
559 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
560 current_dlg_->Reread();
564 current_dlg_->HandleListHit();
568 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
569 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
570 current_dlg_->Reread();
574 current_dlg_->SetDirectory(GetEnvPath("HOME"));
575 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
576 current_dlg_->Reread();
579 case 12: // user button 1
580 current_dlg_->SetDirectory(current_dlg_->user_path1_);
581 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
582 current_dlg_->Reread();
585 case 13: // user button 2
586 current_dlg_->SetDirectory(current_dlg_->user_path2_);
587 current_dlg_->SetFilters(fl_get_input(file_dlg_form_->PatBox));
588 current_dlg_->Reread();
595 // Handle callback from list
596 void FileDialog::Private::HandleListHit()
599 int const select_ = fl_get_browser(file_dlg_form_->List);
600 if (select_ > depth_)
601 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
603 SetInfoLine(string());
607 // Callback for double click in list
608 void FileDialog::Private::DoubleClickCB(FL_OBJECT *, long)
610 // Simulate click on OK button
611 if (current_dlg_->HandleDoubleClick())
612 current_dlg_->Force(false);
616 // Handle double click from list
617 bool FileDialog::Private::HandleDoubleClick()
623 int const select_ = fl_get_browser(file_dlg_form_->List);
624 if (select_ > depth_) {
625 tmp = dir_entries_[select_ - depth_ - 1].name_;
626 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
627 if (!suffixIs(tmp, '/')) {
629 fl_set_input(file_dlg_form_->Filename, tmp.c_str());
631 } else if (select_ != 0) {
632 SetInfoLine(string());
640 // builds new directory name
641 if (select_ > depth_) {
642 // Directory deeper down
643 // First, get directory with trailing /
644 Temp = fl_get_input(file_dlg_form_->DirBox);
645 if (!suffixIs(Temp, '/'))
649 // Directory higher up
651 for (int i = 0; i < select_; ++i) {
652 string piece = fl_get_browser_line(file_dlg_form_->List, i+1);
653 // The '+2' is here to count the '@b' (JMarc)
654 Temp += piece.substr(i + 2);
667 // Handle OK button call
668 bool FileDialog::Private::HandleOK()
671 string tmp = fl_get_input(file_dlg_form_->PatBox);
678 // directory was changed
679 tmp = fl_get_input(file_dlg_form_->DirBox);
680 if (tmp != directory_) {
686 // Handle return from list
687 int const select = fl_get_browser(file_dlg_form_->List);
688 if (select > depth_) {
689 string const temp = dir_entries_[select - depth_ - 1].name_;
690 if (!suffixIs(temp, '/')) {
691 // If user didn't type anything, use browser
692 string const name = fl_get_input(file_dlg_form_->Filename);
694 fl_set_input(file_dlg_form_->Filename, temp.c_str());
699 // Emulate a doubleclick
700 return HandleDoubleClick();
704 // Handle Cancel CB from WM close
705 int FileDialog::Private::CancelCB(FL_FORM *, void *)
707 // Simulate a click on the cancel button
708 current_dlg_->Force(true);
713 // Simulates a click on OK/Cancel
714 void FileDialog::Private::Force(bool cancel)
717 force_cancel_ = true;
718 fl_set_button(file_dlg_form_->Cancel, 1);
721 fl_set_button(file_dlg_form_->Ready, 1);
723 // Start timer to break fl_do_forms loop soon
724 fl_set_timer(file_dlg_form_->timer, 0.1);
728 // Select: launches dialog and returns selected file
729 string const FileDialog::Private::Select(string const & title,
731 FileFilterList const & filters,
732 string const & suggested)
734 // handles new mask and path
739 // highlight the suggested file in the browser, if it exists.
741 string const filename = OnlyFilename(suggested);
742 if (!filename.empty()) {
743 for (int i = 0; i < fl_get_browser_maxline(file_dlg_form_->List); ++i) {
744 string s = fl_get_browser_line(file_dlg_form_->List, i + 1);
754 fl_select_browser_line(file_dlg_form_->List, sel);
755 int const top = max(sel - 5, 1);
756 fl_set_browser_topline(file_dlg_form_->List, top);
758 // checks whether dialog can be started
764 SetInfoLine(string());
765 setEnabled(file_dlg_form_->Filename, true);
766 fl_set_input(file_dlg_form_->Filename, suggested.c_str());
767 fl_set_button(file_dlg_form_->Cancel, 0);
768 fl_set_button(file_dlg_form_->Ready, 0);
769 fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->Filename);
770 fl_deactivate_all_forms();
771 // Prevent xforms crashing if the dialog gets too small by preventing
772 // it from being shrunk beyond a minimum size.
773 // calls to fl_set_form_minsize/maxsize apply only to the next
774 // fl_show_form(), so this comes first.
775 fl_set_form_minsize(file_dlg_form_->form, minw_, minh_);
777 fl_show_form(file_dlg_form_->form,
778 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
781 bool const isOk = RunDialog();
783 fl_hide_form(file_dlg_form_->form);
784 fl_activate_all_forms();
787 // Returns filename or string() if no valid selection was made
788 if (!isOk || !fl_get_input(file_dlg_form_->Filename)[0])
791 file_name_ = fl_get_input(file_dlg_form_->Filename);
793 if (!AbsolutePath(file_name_))
794 file_name_ = AddName(fl_get_input(file_dlg_form_->DirBox), file_name_);
799 // SelectDir: launches dialog and returns selected directory
800 string const FileDialog::Private::SelectDir(string const & title,
802 string const & suggested)
808 // handle case where path does not end with "/"
809 // remerge path+suggested and check if it is a valid path
810 if (!suggested.empty()) {
811 string tmp = suggested;
812 if (!suffixIs(tmp, '/'))
814 string full_path = path;
816 // check if this is really a directory
817 DIR * dir = ::opendir(full_path.c_str());
819 SetDirectory(full_path);
829 // checks whether dialog can be started
835 SetInfoLine(string());
836 fl_set_input(file_dlg_form_->Filename, "");
837 setEnabled(file_dlg_form_->Filename, false);
838 fl_set_button(file_dlg_form_->Cancel, 0);
839 fl_set_button(file_dlg_form_->Ready, 0);
840 fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->DirBox);
841 fl_deactivate_all_forms();
842 fl_show_form(file_dlg_form_->form,
843 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
848 fl_hide_form(file_dlg_form_->form);
849 fl_activate_all_forms();
852 // Returns directory or string() if no valid selection was made
856 file_name_ = fl_get_input(file_dlg_form_->DirBox);