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/lyxlib.h"
24 #include "support/lstrings.h"
25 #include "support/tostr.h"
26 #include "support/filetools.h"
28 #include "lyx_forms.h"
30 #include <boost/bind.hpp>
31 #include <boost/regex.hpp>
45 # define dirent direct
47 # include <sys/ndir.h>
57 using lyx::support::AbsolutePath;
58 using lyx::support::AddName;
59 using lyx::support::ExpandPath;
60 using lyx::support::FileInfo;
61 using lyx::support::getcwd;
62 using lyx::support::GetEnvPath;
63 using lyx::support::LyXReadLink;
64 using lyx::support::MakeAbsPath;
65 using lyx::support::OnlyFilename;
66 using lyx::support::split;
67 using lyx::support::subst;
68 using lyx::support::suffixIs;
69 using lyx::support::trim;
79 // six months, in seconds
80 long const SIX_MONTH_SEC = 6L * 30L * 24L * 60L * 60L;
82 long const ONE_HOUR_SEC = 60L * 60L;
87 int C_LyXFileDlg_CancelCB(FL_FORM *fl, void *xev)
89 return FileDialog::Private::CancelCB(fl, xev);
93 void C_LyXFileDlg_DoubleClickCB(FL_OBJECT * ob, long data)
95 FileDialog::Private::DoubleClickCB(ob, data);
99 void C_LyXFileDlg_FileDlgCB(FL_OBJECT * ob, long data)
101 FileDialog::Private::FileDlgCB(ob, data);
106 // *** User cache class implementation
107 /// User cache class definition
110 /// seeks user name from group ID
111 string const & find(uid_t ID) const {
112 Users::const_iterator cit = users.find(ID);
113 if (cit == users.end()) {
121 void add(uid_t ID) const;
123 typedef map<uid_t, string> Users;
129 void UserCache::add(uid_t ID) const
131 struct passwd const * entry = getpwuid(ID);
132 users[ID] = entry ? entry->pw_name : tostr(int(ID));
136 /// Group cache class definition
139 /// seeks group name from group ID
140 string const & find(gid_t ID) const ;
143 void add(gid_t ID) const;
145 typedef map<gid_t, string> Groups;
147 mutable Groups groups;
151 string const & GroupCache::find(gid_t ID) const
153 Groups::const_iterator cit = groups.find(ID);
154 if (cit == groups.end()) {
162 void GroupCache::add(gid_t ID) const
164 struct group const * entry = getgrgid(ID);
165 groups[ID] = entry ? entry->gr_name : tostr(int(ID));
169 UserCache lyxUserCache;
170 GroupCache lyxGroupCache;
172 // compares two LyXDirEntry objects content (used for sort)
173 class comp_direntry {
175 bool operator()(DirEntry const & r1, DirEntry const & r2) const
177 bool const r1d = suffixIs(r1.name_, '/');
178 bool const r2d = suffixIs(r2.name_, '/');
183 return r1.name_ < r2.name_;
192 // *** FileDialog::Private class implementation
195 FD_filedialog * FileDialog::Private::file_dlg_form_ = 0;
196 FileDialog::Private * FileDialog::Private::current_dlg_ = 0;
197 int FileDialog::Private::minw_ = 0;
198 int FileDialog::Private::minh_ = 0;
203 boost::regex glob2regex(string const & pat)
205 // We massage the pattern a bit so that the usual
206 // shell pattern we all are used to will work.
207 // One nice thing about using a real regex is that
208 // things like "*.*[^~]" will work also.
209 // build the regex string.
210 string pattern = subst(pat, ".", "\\.");
211 pattern = subst(pattern, "*", ".*");
213 boost::regex reg(pattern);
218 bool globMatch(string const & a, boost::regex const & reg)
220 // If the glob is invalid then match everything.
221 return reg.empty() ? true : boost::regex_match(a, reg);
227 // Reread: updates dialog list to match class directory
228 void FileDialog::Private::Reread()
231 DIR * dir = ::opendir(directory_.c_str());
235 Alert::err_alert(_("Warning! Couldn't open directory."),
238 directory_ = getcwd();
239 dir = ::opendir(directory_.c_str());
242 // Clear the present namelist
243 dir_entries_.clear();
246 fl_hide_object(file_dlg_form_->List);
247 fl_clear_browser(file_dlg_form_->List);
248 fl_set_input(file_dlg_form_->DirBox, directory_.c_str());
250 // Splits complete directory name into directories and compute depth
254 string File = directory_;
256 File = split(File, Temp, '/');
258 while (!File.empty() || !Temp.empty()) {
259 string dline = "@b" + line + Temp + '/';
260 fl_add_browser_line(file_dlg_form_->List, dline.c_str());
261 File = split(File, Temp, '/');
266 // Parses all entries of the given subdirectory
267 boost::regex const mask_regex = glob2regex(mask_);
269 time_t curTime = time(0);
271 while (dirent * entry = readdir(dir)) {
272 bool isLink = false, isDir = false;
274 // If the pattern doesn't start with a dot, skip hidden files
275 if (!mask_.empty() && mask_[0] != '.' &&
276 entry->d_name[0] == '.')
280 string fname = entry->d_name;
282 // Under all circumstances, "." and ".." are not wanted
283 if (fname == "." || fname == "..")
287 File = AddName(directory_, fname);
289 FileInfo fileInfo(File, true);
291 // can this really happen?
292 if (!fileInfo.isOK())
295 mode = fileInfo.modeString();
296 unsigned int const nlink = fileInfo.getNumberOfLinks();
297 string const user = lyxUserCache.find(fileInfo.getUid());
298 string const group = lyxGroupCache.find(fileInfo.getGid());
300 time_t modtime = fileInfo.getModificationTime();
301 string Time = ctime(&modtime);
303 if (curTime > modtime + SIX_MONTH_SEC
304 || curTime < modtime + ONE_HOUR_SEC) {
305 // The file is fairly old or in the future. POSIX says
306 // the cutoff is 6 months old. Allow a 1 hour slop
307 // factor for what is considered "the future", to
308 // allow for NFS server/client clock disagreement.
309 // Show the year instead of the time of day.
311 Time.erase(15, string::npos);
313 Time.erase(16, string::npos);
316 string buffer = mode + ' ' +
320 Time.substr(4, string::npos) + ' ';
322 buffer += entry->d_name;
323 buffer += fileInfo.typeIndicator();
325 isLink = fileInfo.isLink();
329 if (LyXReadLink(File, Link)) {
333 // This gives the FileType of the file that
334 // is really pointed too after resolving all
335 // symlinks. This is not necessarily the same
336 // as the type of Link (which could again be a
337 // link). Is that intended?
339 fileInfo.newFile(File);
341 buffer += fileInfo.typeIndicator();
347 // filters files according to pattern and type
348 if (fileInfo.isRegular()
350 || fileInfo.isBlock()
351 || fileInfo.isFifo()) {
352 if (!globMatch(fname, mask_regex))
354 } else if (!(isDir = fileInfo.isDir()))
359 // Note ls_entry_ is an string!
360 tmp.ls_entry_ = buffer;
367 // creates displayed name
368 temp = entry->d_name;
372 temp += fileInfo.typeIndicator();
373 tmp.displayed_ = temp;
375 dir_entries_.push_back(tmp);
381 sort(dir_entries_.begin(), dir_entries_.end(), comp_direntry());
383 // Add them to directory box
384 for (DirEntries::const_iterator cit = dir_entries_.begin();
385 cit != dir_entries_.end(); ++cit) {
386 string const temp = line + cit->displayed_;
387 fl_add_browser_line(file_dlg_form_->List, temp.c_str());
389 fl_set_browser_topline(file_dlg_form_->List, depth_);
390 fl_show_object(file_dlg_form_->List);
395 // SetDirectory: sets dialog current directory
396 void FileDialog::Private::SetDirectory(string const & path)
402 tmp = MakeAbsPath(ExpandPath(path), directory_);
404 // must check the directory exists
405 DIR * dir = ::opendir(tmp.c_str());
409 Alert::err_alert(_("Warning! Couldn't open directory."), tmp);
418 // SetMask: sets dialog file mask
419 void FileDialog::Private::SetMask(string const & newmask)
421 mask_ = trim(newmask);
425 fl_set_input(file_dlg_form_->PatBox, mask_.c_str());
429 // SetInfoLine: sets dialog information line
430 void FileDialog::Private::SetInfoLine(string const & line)
433 fl_set_object_label(file_dlg_form_->FileInfo, info_line_.c_str());
437 FileDialog::Private::Private()
439 directory_ = MakeAbsPath(string("."));
442 // Creates form if necessary.
443 if (!file_dlg_form_) {
444 file_dlg_form_ = build_filedialog(this);
445 minw_ = file_dlg_form_->form->w;
446 minh_ = file_dlg_form_->form->h;
447 // Set callbacks. This means that we don't need a patch file
448 fl_set_object_callback(file_dlg_form_->DirBox,
449 C_LyXFileDlg_FileDlgCB, 0);
450 fl_set_object_callback(file_dlg_form_->PatBox,
451 C_LyXFileDlg_FileDlgCB, 1);
452 fl_set_object_callback(file_dlg_form_->List,
453 C_LyXFileDlg_FileDlgCB, 2);
454 fl_set_object_callback(file_dlg_form_->Filename,
455 C_LyXFileDlg_FileDlgCB, 3);
456 fl_set_object_callback(file_dlg_form_->Rescan,
457 C_LyXFileDlg_FileDlgCB, 10);
458 fl_set_object_callback(file_dlg_form_->Home,
459 C_LyXFileDlg_FileDlgCB, 11);
460 fl_set_object_callback(file_dlg_form_->User1,
461 C_LyXFileDlg_FileDlgCB, 12);
462 fl_set_object_callback(file_dlg_form_->User2,
463 C_LyXFileDlg_FileDlgCB, 13);
465 // Make sure pressing the close box doesn't crash LyX. (RvdK)
466 fl_set_form_atclose(file_dlg_form_->form,
467 C_LyXFileDlg_CancelCB, 0);
468 // Register doubleclick callback
469 fl_set_browser_dblclick_callback(file_dlg_form_->List,
470 C_LyXFileDlg_DoubleClickCB,
473 fl_hide_object(file_dlg_form_->User1);
474 fl_hide_object(file_dlg_form_->User2);
476 r_ = Dialogs::redrawGUI().connect(boost::bind(&FileDialog::Private::redraw, this));
480 FileDialog::Private::~Private()
486 void FileDialog::Private::redraw()
488 if (file_dlg_form_->form && file_dlg_form_->form->visible)
489 fl_redraw_form(file_dlg_form_->form);
493 // SetButton: sets file selector user button action
494 void FileDialog::Private::SetButton(int index, string const & name,
501 ob = file_dlg_form_->User1;
503 } else if (index == 1) {
504 ob = file_dlg_form_->User2;
511 fl_set_object_label(ob, idex(name).c_str());
512 fl_set_button_shortcut(ob, scex(name).c_str(), 1);
522 // GetDirectory: gets last dialog directory
523 string const FileDialog::Private::GetDirectory() const
525 if (!directory_.empty())
532 bool x_sync_kludge(bool ret)
534 XSync(fl_get_display(), false);
539 // RunDialog: handle dialog during file selection
540 bool FileDialog::Private::RunDialog()
542 force_cancel_ = false;
547 FL_OBJECT * ob = fl_do_forms();
549 if (ob == file_dlg_form_->Ready) {
551 return x_sync_kludge(true);
553 } else if (ob == file_dlg_form_->Cancel || force_cancel_)
554 return x_sync_kludge(false);
557 return x_sync_kludge(true);
562 // XForms objects callback (static)
563 void FileDialog::Private::FileDlgCB(FL_OBJECT *, long arg)
570 case 0: // get directory
571 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
572 current_dlg_->Reread();
576 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
577 current_dlg_->Reread();
581 current_dlg_->HandleListHit();
585 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
586 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
587 current_dlg_->Reread();
591 current_dlg_->SetDirectory(GetEnvPath("HOME"));
592 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
593 current_dlg_->Reread();
596 case 12: // user button 1
597 current_dlg_->SetDirectory(current_dlg_->user_path1_);
598 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
599 current_dlg_->Reread();
602 case 13: // user button 2
603 current_dlg_->SetDirectory(current_dlg_->user_path2_);
604 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
605 current_dlg_->Reread();
612 // Handle callback from list
613 void FileDialog::Private::HandleListHit()
616 int const select_ = fl_get_browser(file_dlg_form_->List);
617 if (select_ > depth_)
618 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
620 SetInfoLine(string());
624 // Callback for double click in list
625 void FileDialog::Private::DoubleClickCB(FL_OBJECT *, long)
627 // Simulate click on OK button
628 if (current_dlg_->HandleDoubleClick())
629 current_dlg_->Force(false);
633 // Handle double click from list
634 bool FileDialog::Private::HandleDoubleClick()
640 int const select_ = fl_get_browser(file_dlg_form_->List);
641 if (select_ > depth_) {
642 tmp = dir_entries_[select_ - depth_ - 1].name_;
643 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
644 if (!suffixIs(tmp, '/')) {
646 fl_set_input(file_dlg_form_->Filename, tmp.c_str());
648 } else if (select_ != 0) {
649 SetInfoLine(string());
657 // builds new directory name
658 if (select_ > depth_) {
659 // Directory deeper down
660 // First, get directory with trailing /
661 Temp = fl_get_input(file_dlg_form_->DirBox);
662 if (!suffixIs(Temp, '/'))
666 // Directory higher up
668 for (int i = 0; i < select_; ++i) {
669 string piece = fl_get_browser_line(file_dlg_form_->List, i+1);
670 // The '+2' is here to count the '@b' (JMarc)
671 Temp += piece.substr(i + 2);
684 // Handle OK button call
685 bool FileDialog::Private::HandleOK()
688 string tmp = fl_get_input(file_dlg_form_->PatBox);
695 // directory was changed
696 tmp = fl_get_input(file_dlg_form_->DirBox);
697 if (tmp != directory_) {
703 // Handle return from list
704 int const select = fl_get_browser(file_dlg_form_->List);
705 if (select > depth_) {
706 string const temp = dir_entries_[select - depth_ - 1].name_;
707 if (!suffixIs(temp, '/')) {
708 // If user didn't type anything, use browser
709 string const name = fl_get_input(file_dlg_form_->Filename);
711 fl_set_input(file_dlg_form_->Filename, temp.c_str());
716 // Emulate a doubleclick
717 return HandleDoubleClick();
721 // Handle Cancel CB from WM close
722 int FileDialog::Private::CancelCB(FL_FORM *, void *)
724 // Simulate a click on the cancel button
725 current_dlg_->Force(true);
730 // Simulates a click on OK/Cancel
731 void FileDialog::Private::Force(bool cancel)
734 force_cancel_ = true;
735 fl_set_button(file_dlg_form_->Cancel, 1);
738 fl_set_button(file_dlg_form_->Ready, 1);
740 // Start timer to break fl_do_forms loop soon
741 fl_set_timer(file_dlg_form_->timer, 0.1);
745 // Select: launches dialog and returns selected file
746 string const FileDialog::Private::Select(string const & title,
749 string const & suggested)
751 // handles new mask and path
764 // highlight the suggested file in the browser, if it exists.
766 string const filename = OnlyFilename(suggested);
767 if (!filename.empty()) {
768 for (int i = 0; i < fl_get_browser_maxline(file_dlg_form_->List); ++i) {
769 string s = fl_get_browser_line(file_dlg_form_->List, i + 1);
779 fl_select_browser_line(file_dlg_form_->List, sel);
780 int const top = max(sel - 5, 1);
781 fl_set_browser_topline(file_dlg_form_->List, top);
783 // checks whether dialog can be started
789 SetInfoLine(string());
790 setEnabled(file_dlg_form_->Filename, true);
791 fl_set_input(file_dlg_form_->Filename, suggested.c_str());
792 fl_set_button(file_dlg_form_->Cancel, 0);
793 fl_set_button(file_dlg_form_->Ready, 0);
794 fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->Filename);
795 fl_deactivate_all_forms();
796 // Prevent xforms crashing if the dialog gets too small by preventing
797 // it from being shrunk beyond a minimum size.
798 // calls to fl_set_form_minsize/maxsize apply only to the next
799 // fl_show_form(), so this comes first.
800 fl_set_form_minsize(file_dlg_form_->form, minw_, minh_);
802 fl_show_form(file_dlg_form_->form,
803 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
808 fl_hide_form(file_dlg_form_->form);
809 fl_activate_all_forms();
812 // Returns filename or string() if no valid selection was made
813 if (!isOk || !fl_get_input(file_dlg_form_->Filename)[0])
816 file_name_ = fl_get_input(file_dlg_form_->Filename);
818 if (!AbsolutePath(file_name_))
819 file_name_ = AddName(fl_get_input(file_dlg_form_->DirBox), file_name_);
824 // SelectDir: launches dialog and returns selected directory
825 string const FileDialog::Private::SelectDir(string const & title,
827 string const & suggested)
833 // handle case where path does not end with "/"
834 // remerge path+suggested and check if it is a valid path
835 if (!suggested.empty()) {
836 string tmp = suggested;
837 if (!suffixIs(tmp, '/'))
839 string full_path = path;
841 // check if this is really a directory
842 DIR * dir = ::opendir(full_path.c_str());
844 SetDirectory(full_path);
854 // checks whether dialog can be started
860 SetInfoLine(string());
861 fl_set_input(file_dlg_form_->Filename, "");
862 setEnabled(file_dlg_form_->Filename, false);
863 fl_set_button(file_dlg_form_->Cancel, 0);
864 fl_set_button(file_dlg_form_->Ready, 0);
865 fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->DirBox);
866 fl_deactivate_all_forms();
867 fl_show_form(file_dlg_form_->form,
868 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
873 fl_hide_form(file_dlg_form_->form);
874 fl_activate_all_forms();
877 // Returns directory or string() if no valid selection was made
881 file_name_ = fl_get_input(file_dlg_form_->DirBox);