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/filetools.h"
24 #include "support/globbing.h"
25 #include "support/lstrings.h"
26 #include "support/lyxlib.h"
27 #include "support/tostr.h"
29 #include "lyx_forms.h"
31 #include <boost/bind.hpp>
32 #include <boost/regex.hpp>
46 # define dirent direct
48 # include <sys/ndir.h>
58 using lyx::support::AbsolutePath;
59 using lyx::support::AddName;
60 using lyx::support::ExpandPath;
61 using lyx::support::FileInfo;
62 using lyx::support::getcwd;
63 using lyx::support::GetEnvPath;
64 using lyx::support::LyXReadLink;
65 using lyx::support::MakeAbsPath;
66 using lyx::support::OnlyFilename;
67 using lyx::support::split;
68 using lyx::support::subst;
69 using lyx::support::suffixIs;
70 using lyx::support::trim;
81 // six months, in seconds
82 long const SIX_MONTH_SEC = 6L * 30L * 24L * 60L * 60L;
84 long const ONE_HOUR_SEC = 60L * 60L;
89 int C_LyXFileDlg_CancelCB(FL_FORM *fl, void *xev)
91 return FileDialog::Private::CancelCB(fl, xev);
95 void C_LyXFileDlg_DoubleClickCB(FL_OBJECT * ob, long data)
97 FileDialog::Private::DoubleClickCB(ob, data);
101 void C_LyXFileDlg_FileDlgCB(FL_OBJECT * ob, long data)
103 FileDialog::Private::FileDlgCB(ob, data);
108 // *** User cache class implementation
109 /// User cache class definition
112 /// seeks user name from group ID
113 string const & find(uid_t ID) const {
114 Users::const_iterator cit = users.find(ID);
115 if (cit == users.end()) {
123 void add(uid_t ID) const;
125 typedef map<uid_t, string> Users;
131 void UserCache::add(uid_t ID) const
133 struct passwd const * entry = getpwuid(ID);
134 users[ID] = entry ? entry->pw_name : tostr(int(ID));
138 /// Group cache class definition
141 /// seeks group name from group ID
142 string const & find(gid_t ID) const ;
145 void add(gid_t ID) const;
147 typedef map<gid_t, string> Groups;
149 mutable Groups groups;
153 string const & GroupCache::find(gid_t ID) const
155 Groups::const_iterator cit = groups.find(ID);
156 if (cit == groups.end()) {
164 void GroupCache::add(gid_t ID) const
166 struct group const * entry = getgrgid(ID);
167 groups[ID] = entry ? entry->gr_name : tostr(int(ID));
171 UserCache lyxUserCache;
172 GroupCache lyxGroupCache;
174 // compares two LyXDirEntry objects content (used for sort)
175 class comp_direntry {
177 bool operator()(DirEntry const & r1, DirEntry const & r2) const
179 bool const r1d = suffixIs(r1.name_, '/');
180 bool const r2d = suffixIs(r2.name_, '/');
185 return r1.name_ < r2.name_;
194 // *** FileDialog::Private class implementation
197 FD_filedialog * FileDialog::Private::file_dlg_form_ = 0;
198 FileDialog::Private * FileDialog::Private::current_dlg_ = 0;
199 int FileDialog::Private::minw_ = 0;
200 int FileDialog::Private::minh_ = 0;
203 // Reread: updates dialog list to match class directory
204 void FileDialog::Private::Reread()
207 DIR * dir = ::opendir(directory_.c_str());
211 Alert::err_alert(_("Warning! Couldn't open directory."),
214 directory_ = getcwd();
215 dir = ::opendir(directory_.c_str());
218 // Clear the present namelist
219 dir_entries_.clear();
222 fl_hide_object(file_dlg_form_->List);
223 fl_clear_browser(file_dlg_form_->List);
224 fl_set_input(file_dlg_form_->DirBox, directory_.c_str());
226 // Splits complete directory name into directories and compute depth
230 string File = directory_;
232 File = split(File, Temp, '/');
234 while (!File.empty() || !Temp.empty()) {
235 string dline = "@b" + line + Temp + '/';
236 fl_add_browser_line(file_dlg_form_->List, dline.c_str());
237 File = split(File, Temp, '/');
242 vector<string> const glob_matches =
243 lyx::support::expand_globs(mask_, directory_);
245 time_t curTime = time(0);
247 while (dirent * entry = readdir(dir)) {
248 bool isLink = false, isDir = false;
250 // If the pattern doesn't start with a dot, skip hidden files
251 if (!mask_.empty() && mask_[0] != '.' &&
252 entry->d_name[0] == '.')
256 string fname = entry->d_name;
258 // Under all circumstances, "." and ".." are not wanted
259 if (fname == "." || fname == "..")
263 File = AddName(directory_, fname);
265 FileInfo fileInfo(File, true);
267 // can this really happen?
268 if (!fileInfo.isOK())
271 mode = fileInfo.modeString();
272 unsigned int const nlink = fileInfo.getNumberOfLinks();
273 string const user = lyxUserCache.find(fileInfo.getUid());
274 string const group = lyxGroupCache.find(fileInfo.getGid());
276 time_t modtime = fileInfo.getModificationTime();
277 string Time = ctime(&modtime);
279 if (curTime > modtime + SIX_MONTH_SEC
280 || curTime < modtime + ONE_HOUR_SEC) {
281 // The file is fairly old or in the future. POSIX says
282 // the cutoff is 6 months old. Allow a 1 hour slop
283 // factor for what is considered "the future", to
284 // allow for NFS server/client clock disagreement.
285 // Show the year instead of the time of day.
287 Time.erase(15, string::npos);
289 Time.erase(16, string::npos);
292 string buffer = mode + ' ' +
296 Time.substr(4, string::npos) + ' ';
298 buffer += entry->d_name;
299 buffer += fileInfo.typeIndicator();
301 isLink = fileInfo.isLink();
305 if (LyXReadLink(File, Link)) {
309 // This gives the FileType of the file that
310 // is really pointed to after resolving all
311 // symlinks. This is not necessarily the same
312 // as the type of Link (which could again be a
313 // link). Is that intended?
315 fileInfo.newFile(File);
317 buffer += fileInfo.typeIndicator();
323 // filters files according to pattern and type
324 if (fileInfo.isRegular()
326 || fileInfo.isBlock()
327 || fileInfo.isFifo()) {
328 typedef vector<string>::const_iterator viterator;
329 viterator gbegin = glob_matches.begin();
330 viterator const gend = glob_matches.end();
331 if (std::find(gbegin, gend, fname) == gend)
333 } else if (!(isDir = fileInfo.isDir()))
338 // Note ls_entry_ is an string!
339 tmp.ls_entry_ = buffer;
346 // creates displayed name
347 temp = entry->d_name;
351 temp += fileInfo.typeIndicator();
352 tmp.displayed_ = temp;
354 dir_entries_.push_back(tmp);
360 sort(dir_entries_.begin(), dir_entries_.end(), comp_direntry());
362 // Add them to directory box
363 for (DirEntries::const_iterator cit = dir_entries_.begin();
364 cit != dir_entries_.end(); ++cit) {
365 string const temp = line + cit->displayed_;
366 fl_add_browser_line(file_dlg_form_->List, temp.c_str());
368 fl_set_browser_topline(file_dlg_form_->List, depth_);
369 fl_show_object(file_dlg_form_->List);
374 // SetDirectory: sets dialog current directory
375 void FileDialog::Private::SetDirectory(string const & path)
381 tmp = MakeAbsPath(ExpandPath(path), directory_);
383 // must check the directory exists
384 DIR * dir = ::opendir(tmp.c_str());
388 Alert::err_alert(_("Warning! Couldn't open directory."), tmp);
397 // SetMask: sets dialog file mask
398 void FileDialog::Private::SetMask(string const & newmask)
400 mask_ = trim(newmask);
404 fl_set_input(file_dlg_form_->PatBox, mask_.c_str());
408 // SetInfoLine: sets dialog information line
409 void FileDialog::Private::SetInfoLine(string const & line)
412 fl_set_object_label(file_dlg_form_->FileInfo, info_line_.c_str());
416 FileDialog::Private::Private()
418 directory_ = MakeAbsPath(string("."));
421 // Creates form if necessary.
422 if (!file_dlg_form_) {
423 file_dlg_form_ = build_filedialog(this);
424 minw_ = file_dlg_form_->form->w;
425 minh_ = file_dlg_form_->form->h;
426 // Set callbacks. This means that we don't need a patch file
427 fl_set_object_callback(file_dlg_form_->DirBox,
428 C_LyXFileDlg_FileDlgCB, 0);
429 fl_set_object_callback(file_dlg_form_->PatBox,
430 C_LyXFileDlg_FileDlgCB, 1);
431 fl_set_object_callback(file_dlg_form_->List,
432 C_LyXFileDlg_FileDlgCB, 2);
433 fl_set_object_callback(file_dlg_form_->Filename,
434 C_LyXFileDlg_FileDlgCB, 3);
435 fl_set_object_callback(file_dlg_form_->Rescan,
436 C_LyXFileDlg_FileDlgCB, 10);
437 fl_set_object_callback(file_dlg_form_->Home,
438 C_LyXFileDlg_FileDlgCB, 11);
439 fl_set_object_callback(file_dlg_form_->User1,
440 C_LyXFileDlg_FileDlgCB, 12);
441 fl_set_object_callback(file_dlg_form_->User2,
442 C_LyXFileDlg_FileDlgCB, 13);
444 // Make sure pressing the close box doesn't crash LyX. (RvdK)
445 fl_set_form_atclose(file_dlg_form_->form,
446 C_LyXFileDlg_CancelCB, 0);
447 // Register doubleclick callback
448 fl_set_browser_dblclick_callback(file_dlg_form_->List,
449 C_LyXFileDlg_DoubleClickCB,
452 fl_hide_object(file_dlg_form_->User1);
453 fl_hide_object(file_dlg_form_->User2);
455 r_ = Dialogs::redrawGUI().connect(boost::bind(&FileDialog::Private::redraw, this));
459 FileDialog::Private::~Private()
465 void FileDialog::Private::redraw()
467 if (file_dlg_form_->form && file_dlg_form_->form->visible)
468 fl_redraw_form(file_dlg_form_->form);
472 // SetButton: sets file selector user button action
473 void FileDialog::Private::SetButton(int index, string const & name,
480 ob = file_dlg_form_->User1;
482 } else if (index == 1) {
483 ob = file_dlg_form_->User2;
490 fl_set_object_label(ob, idex(name).c_str());
491 fl_set_button_shortcut(ob, scex(name).c_str(), 1);
501 // GetDirectory: gets last dialog directory
502 string const FileDialog::Private::GetDirectory() const
504 if (!directory_.empty())
511 bool x_sync_kludge(bool ret)
513 XSync(fl_get_display(), false);
518 // RunDialog: handle dialog during file selection
519 bool FileDialog::Private::RunDialog()
521 force_cancel_ = false;
526 FL_OBJECT * ob = fl_do_forms();
528 if (ob == file_dlg_form_->Ready) {
530 return x_sync_kludge(true);
532 } else if (ob == file_dlg_form_->Cancel || force_cancel_)
533 return x_sync_kludge(false);
536 return x_sync_kludge(true);
541 // XForms objects callback (static)
542 void FileDialog::Private::FileDlgCB(FL_OBJECT *, long arg)
549 case 0: // get directory
550 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
551 current_dlg_->Reread();
555 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
556 current_dlg_->Reread();
560 current_dlg_->HandleListHit();
564 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
565 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
566 current_dlg_->Reread();
570 current_dlg_->SetDirectory(GetEnvPath("HOME"));
571 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
572 current_dlg_->Reread();
575 case 12: // user button 1
576 current_dlg_->SetDirectory(current_dlg_->user_path1_);
577 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
578 current_dlg_->Reread();
581 case 13: // user button 2
582 current_dlg_->SetDirectory(current_dlg_->user_path2_);
583 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
584 current_dlg_->Reread();
591 // Handle callback from list
592 void FileDialog::Private::HandleListHit()
595 int const select_ = fl_get_browser(file_dlg_form_->List);
596 if (select_ > depth_)
597 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
599 SetInfoLine(string());
603 // Callback for double click in list
604 void FileDialog::Private::DoubleClickCB(FL_OBJECT *, long)
606 // Simulate click on OK button
607 if (current_dlg_->HandleDoubleClick())
608 current_dlg_->Force(false);
612 // Handle double click from list
613 bool FileDialog::Private::HandleDoubleClick()
619 int const select_ = fl_get_browser(file_dlg_form_->List);
620 if (select_ > depth_) {
621 tmp = dir_entries_[select_ - depth_ - 1].name_;
622 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
623 if (!suffixIs(tmp, '/')) {
625 fl_set_input(file_dlg_form_->Filename, tmp.c_str());
627 } else if (select_ != 0) {
628 SetInfoLine(string());
636 // builds new directory name
637 if (select_ > depth_) {
638 // Directory deeper down
639 // First, get directory with trailing /
640 Temp = fl_get_input(file_dlg_form_->DirBox);
641 if (!suffixIs(Temp, '/'))
645 // Directory higher up
647 for (int i = 0; i < select_; ++i) {
648 string piece = fl_get_browser_line(file_dlg_form_->List, i+1);
649 // The '+2' is here to count the '@b' (JMarc)
650 Temp += piece.substr(i + 2);
663 // Handle OK button call
664 bool FileDialog::Private::HandleOK()
667 string tmp = fl_get_input(file_dlg_form_->PatBox);
674 // directory was changed
675 tmp = fl_get_input(file_dlg_form_->DirBox);
676 if (tmp != directory_) {
682 // Handle return from list
683 int const select = fl_get_browser(file_dlg_form_->List);
684 if (select > depth_) {
685 string const temp = dir_entries_[select - depth_ - 1].name_;
686 if (!suffixIs(temp, '/')) {
687 // If user didn't type anything, use browser
688 string const name = fl_get_input(file_dlg_form_->Filename);
690 fl_set_input(file_dlg_form_->Filename, temp.c_str());
695 // Emulate a doubleclick
696 return HandleDoubleClick();
700 // Handle Cancel CB from WM close
701 int FileDialog::Private::CancelCB(FL_FORM *, void *)
703 // Simulate a click on the cancel button
704 current_dlg_->Force(true);
709 // Simulates a click on OK/Cancel
710 void FileDialog::Private::Force(bool cancel)
713 force_cancel_ = true;
714 fl_set_button(file_dlg_form_->Cancel, 1);
717 fl_set_button(file_dlg_form_->Ready, 1);
719 // Start timer to break fl_do_forms loop soon
720 fl_set_timer(file_dlg_form_->timer, 0.1);
724 // Select: launches dialog and returns selected file
725 string const FileDialog::Private::Select(string const & title,
728 string const & suggested)
730 // handles new mask and path
743 // highlight the suggested file in the browser, if it exists.
745 string const filename = OnlyFilename(suggested);
746 if (!filename.empty()) {
747 for (int i = 0; i < fl_get_browser_maxline(file_dlg_form_->List); ++i) {
748 string s = fl_get_browser_line(file_dlg_form_->List, i + 1);
758 fl_select_browser_line(file_dlg_form_->List, sel);
759 int const top = max(sel - 5, 1);
760 fl_set_browser_topline(file_dlg_form_->List, top);
762 // checks whether dialog can be started
768 SetInfoLine(string());
769 setEnabled(file_dlg_form_->Filename, true);
770 fl_set_input(file_dlg_form_->Filename, suggested.c_str());
771 fl_set_button(file_dlg_form_->Cancel, 0);
772 fl_set_button(file_dlg_form_->Ready, 0);
773 fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->Filename);
774 fl_deactivate_all_forms();
775 // Prevent xforms crashing if the dialog gets too small by preventing
776 // it from being shrunk beyond a minimum size.
777 // calls to fl_set_form_minsize/maxsize apply only to the next
778 // fl_show_form(), so this comes first.
779 fl_set_form_minsize(file_dlg_form_->form, minw_, minh_);
781 fl_show_form(file_dlg_form_->form,
782 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
787 fl_hide_form(file_dlg_form_->form);
788 fl_activate_all_forms();
791 // Returns filename or string() if no valid selection was made
792 if (!isOk || !fl_get_input(file_dlg_form_->Filename)[0])
795 file_name_ = fl_get_input(file_dlg_form_->Filename);
797 if (!AbsolutePath(file_name_))
798 file_name_ = AddName(fl_get_input(file_dlg_form_->DirBox), file_name_);
803 // SelectDir: launches dialog and returns selected directory
804 string const FileDialog::Private::SelectDir(string const & title,
806 string const & suggested)
812 // handle case where path does not end with "/"
813 // remerge path+suggested and check if it is a valid path
814 if (!suggested.empty()) {
815 string tmp = suggested;
816 if (!suffixIs(tmp, '/'))
818 string full_path = path;
820 // check if this is really a directory
821 DIR * dir = ::opendir(full_path.c_str());
823 SetDirectory(full_path);
833 // checks whether dialog can be started
839 SetInfoLine(string());
840 fl_set_input(file_dlg_form_->Filename, "");
841 setEnabled(file_dlg_form_->Filename, false);
842 fl_set_button(file_dlg_form_->Cancel, 0);
843 fl_set_button(file_dlg_form_->Ready, 0);
844 fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->DirBox);
845 fl_deactivate_all_forms();
846 fl_show_form(file_dlg_form_->form,
847 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
852 fl_hide_form(file_dlg_form_->form);
853 fl_activate_all_forms();
856 // Returns directory or string() if no valid selection was made
860 file_name_ = fl_get_input(file_dlg_form_->DirBox);