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 getRegex(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 return boost::regex_match(a, reg);
226 // Reread: updates dialog list to match class directory
227 void FileDialog::Private::Reread()
230 DIR * dir = ::opendir(directory_.c_str());
234 Alert::err_alert(_("Warning! Couldn't open directory."),
237 directory_ = getcwd();
238 dir = ::opendir(directory_.c_str());
241 // Clear the present namelist
242 dir_entries_.clear();
245 fl_hide_object(file_dlg_form_->List);
246 fl_clear_browser(file_dlg_form_->List);
247 fl_set_input(file_dlg_form_->DirBox, directory_.c_str());
249 // Splits complete directory name into directories and compute depth
253 string File = directory_;
255 File = split(File, Temp, '/');
257 while (!File.empty() || !Temp.empty()) {
258 string dline = "@b" + line + Temp + '/';
259 fl_add_browser_line(file_dlg_form_->List, dline.c_str());
260 File = split(File, Temp, '/');
265 // Parses all entries of the given subdirectory
266 boost::regex reg = getRegex(mask_);
268 time_t curTime = time(0);
270 while (dirent * entry = readdir(dir)) {
271 bool isLink = false, isDir = false;
273 // If the pattern doesn't start with a dot, skip hidden files
274 if (!mask_.empty() && mask_[0] != '.' &&
275 entry->d_name[0] == '.')
279 string fname = entry->d_name;
281 // Under all circumstances, "." and ".." are not wanted
282 if (fname == "." || fname == "..")
286 File = AddName(directory_, fname);
288 FileInfo fileInfo(File, true);
290 // can this really happen?
291 if (!fileInfo.isOK())
294 mode = fileInfo.modeString();
295 unsigned int const nlink = fileInfo.getNumberOfLinks();
296 string const user = lyxUserCache.find(fileInfo.getUid());
297 string const group = lyxGroupCache.find(fileInfo.getGid());
299 time_t modtime = fileInfo.getModificationTime();
300 string Time = ctime(&modtime);
302 if (curTime > modtime + SIX_MONTH_SEC
303 || curTime < modtime + ONE_HOUR_SEC) {
304 // The file is fairly old or in the future. POSIX says
305 // the cutoff is 6 months old. Allow a 1 hour slop
306 // factor for what is considered "the future", to
307 // allow for NFS server/client clock disagreement.
308 // Show the year instead of the time of day.
310 Time.erase(15, string::npos);
312 Time.erase(16, string::npos);
315 string buffer = mode + ' ' +
319 Time.substr(4, string::npos) + ' ';
321 buffer += entry->d_name;
322 buffer += fileInfo.typeIndicator();
324 isLink = fileInfo.isLink();
328 if (LyXReadLink(File, Link)) {
332 // This gives the FileType of the file that
333 // is really pointed too after resolving all
334 // symlinks. This is not necessarily the same
335 // as the type of Link (which could again be a
336 // link). Is that intended?
338 fileInfo.newFile(File);
340 buffer += fileInfo.typeIndicator();
346 // filters files according to pattern and type
347 if (fileInfo.isRegular()
349 || fileInfo.isBlock()
350 || fileInfo.isFifo()) {
351 if (!globMatch(fname, reg))
353 } else if (!(isDir = fileInfo.isDir()))
358 // Note ls_entry_ is an string!
359 tmp.ls_entry_ = buffer;
366 // creates displayed name
367 temp = entry->d_name;
371 temp += fileInfo.typeIndicator();
372 tmp.displayed_ = temp;
374 dir_entries_.push_back(tmp);
380 sort(dir_entries_.begin(), dir_entries_.end(), comp_direntry());
382 // Add them to directory box
383 for (DirEntries::const_iterator cit = dir_entries_.begin();
384 cit != dir_entries_.end(); ++cit) {
385 string const temp = line + cit->displayed_;
386 fl_add_browser_line(file_dlg_form_->List, temp.c_str());
388 fl_set_browser_topline(file_dlg_form_->List, depth_);
389 fl_show_object(file_dlg_form_->List);
394 // SetDirectory: sets dialog current directory
395 void FileDialog::Private::SetDirectory(string const & path)
401 tmp = MakeAbsPath(ExpandPath(path), directory_);
403 // must check the directory exists
404 DIR * dir = ::opendir(tmp.c_str());
408 Alert::err_alert(_("Warning! Couldn't open directory."), tmp);
417 // SetMask: sets dialog file mask
418 void FileDialog::Private::SetMask(string const & newmask)
421 fl_set_input(file_dlg_form_->PatBox, mask_.c_str());
425 // SetInfoLine: sets dialog information line
426 void FileDialog::Private::SetInfoLine(string const & line)
429 fl_set_object_label(file_dlg_form_->FileInfo, info_line_.c_str());
433 FileDialog::Private::Private()
435 directory_ = MakeAbsPath(string("."));
438 // Creates form if necessary.
439 if (!file_dlg_form_) {
440 file_dlg_form_ = build_filedialog(this);
441 minw_ = file_dlg_form_->form->w;
442 minh_ = file_dlg_form_->form->h;
443 // Set callbacks. This means that we don't need a patch file
444 fl_set_object_callback(file_dlg_form_->DirBox,
445 C_LyXFileDlg_FileDlgCB, 0);
446 fl_set_object_callback(file_dlg_form_->PatBox,
447 C_LyXFileDlg_FileDlgCB, 1);
448 fl_set_object_callback(file_dlg_form_->List,
449 C_LyXFileDlg_FileDlgCB, 2);
450 fl_set_object_callback(file_dlg_form_->Filename,
451 C_LyXFileDlg_FileDlgCB, 3);
452 fl_set_object_callback(file_dlg_form_->Rescan,
453 C_LyXFileDlg_FileDlgCB, 10);
454 fl_set_object_callback(file_dlg_form_->Home,
455 C_LyXFileDlg_FileDlgCB, 11);
456 fl_set_object_callback(file_dlg_form_->User1,
457 C_LyXFileDlg_FileDlgCB, 12);
458 fl_set_object_callback(file_dlg_form_->User2,
459 C_LyXFileDlg_FileDlgCB, 13);
461 // Make sure pressing the close box doesn't crash LyX. (RvdK)
462 fl_set_form_atclose(file_dlg_form_->form,
463 C_LyXFileDlg_CancelCB, 0);
464 // Register doubleclick callback
465 fl_set_browser_dblclick_callback(file_dlg_form_->List,
466 C_LyXFileDlg_DoubleClickCB,
469 fl_hide_object(file_dlg_form_->User1);
470 fl_hide_object(file_dlg_form_->User2);
472 r_ = Dialogs::redrawGUI().connect(boost::bind(&FileDialog::Private::redraw, this));
476 FileDialog::Private::~Private()
482 void FileDialog::Private::redraw()
484 if (file_dlg_form_->form && file_dlg_form_->form->visible)
485 fl_redraw_form(file_dlg_form_->form);
489 // SetButton: sets file selector user button action
490 void FileDialog::Private::SetButton(int index, string const & name,
497 ob = file_dlg_form_->User1;
499 } else if (index == 1) {
500 ob = file_dlg_form_->User2;
507 fl_set_object_label(ob, idex(name).c_str());
508 fl_set_button_shortcut(ob, scex(name).c_str(), 1);
518 // GetDirectory: gets last dialog directory
519 string const FileDialog::Private::GetDirectory() const
521 if (!directory_.empty())
528 bool x_sync_kludge(bool ret)
530 XSync(fl_get_display(), false);
535 // RunDialog: handle dialog during file selection
536 bool FileDialog::Private::RunDialog()
538 force_cancel_ = false;
543 FL_OBJECT * ob = fl_do_forms();
545 if (ob == file_dlg_form_->Ready) {
547 return x_sync_kludge(true);
549 } else if (ob == file_dlg_form_->Cancel || force_cancel_)
550 return x_sync_kludge(false);
553 return x_sync_kludge(true);
558 // XForms objects callback (static)
559 void FileDialog::Private::FileDlgCB(FL_OBJECT *, long arg)
566 case 0: // get directory
567 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
568 current_dlg_->Reread();
572 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
573 current_dlg_->Reread();
577 current_dlg_->HandleListHit();
581 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
582 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
583 current_dlg_->Reread();
587 current_dlg_->SetDirectory(GetEnvPath("HOME"));
588 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
589 current_dlg_->Reread();
592 case 12: // user button 1
593 current_dlg_->SetDirectory(current_dlg_->user_path1_);
594 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
595 current_dlg_->Reread();
598 case 13: // user button 2
599 current_dlg_->SetDirectory(current_dlg_->user_path2_);
600 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
601 current_dlg_->Reread();
608 // Handle callback from list
609 void FileDialog::Private::HandleListHit()
612 int const select_ = fl_get_browser(file_dlg_form_->List);
613 if (select_ > depth_)
614 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
616 SetInfoLine(string());
620 // Callback for double click in list
621 void FileDialog::Private::DoubleClickCB(FL_OBJECT *, long)
623 // Simulate click on OK button
624 if (current_dlg_->HandleDoubleClick())
625 current_dlg_->Force(false);
629 // Handle double click from list
630 bool FileDialog::Private::HandleDoubleClick()
636 int const select_ = fl_get_browser(file_dlg_form_->List);
637 if (select_ > depth_) {
638 tmp = dir_entries_[select_ - depth_ - 1].name_;
639 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
640 if (!suffixIs(tmp, '/')) {
642 fl_set_input(file_dlg_form_->Filename, tmp.c_str());
644 } else if (select_ != 0) {
645 SetInfoLine(string());
653 // builds new directory name
654 if (select_ > depth_) {
655 // Directory deeper down
656 // First, get directory with trailing /
657 Temp = fl_get_input(file_dlg_form_->DirBox);
658 if (!suffixIs(Temp, '/'))
662 // Directory higher up
664 for (int i = 0; i < select_; ++i) {
665 string piece = fl_get_browser_line(file_dlg_form_->List, i+1);
666 // The '+2' is here to count the '@b' (JMarc)
667 Temp += piece.substr(i + 2);
680 // Handle OK button call
681 bool FileDialog::Private::HandleOK()
684 string tmp = fl_get_input(file_dlg_form_->PatBox);
691 // directory was changed
692 tmp = fl_get_input(file_dlg_form_->DirBox);
693 if (tmp != directory_) {
699 // Handle return from list
700 int const select = fl_get_browser(file_dlg_form_->List);
701 if (select > depth_) {
702 string const temp = dir_entries_[select - depth_ - 1].name_;
703 if (!suffixIs(temp, '/')) {
704 // If user didn't type anything, use browser
705 string const name = fl_get_input(file_dlg_form_->Filename);
707 fl_set_input(file_dlg_form_->Filename, temp.c_str());
712 // Emulate a doubleclick
713 return HandleDoubleClick();
717 // Handle Cancel CB from WM close
718 int FileDialog::Private::CancelCB(FL_FORM *, void *)
720 // Simulate a click on the cancel button
721 current_dlg_->Force(true);
726 // Simulates a click on OK/Cancel
727 void FileDialog::Private::Force(bool cancel)
730 force_cancel_ = true;
731 fl_set_button(file_dlg_form_->Cancel, 1);
734 fl_set_button(file_dlg_form_->Ready, 1);
736 // Start timer to break fl_do_forms loop soon
737 fl_set_timer(file_dlg_form_->timer, 0.1);
741 // Select: launches dialog and returns selected file
742 string const FileDialog::Private::Select(string const & title,
745 string const & suggested)
747 // handles new mask and path
760 // highlight the suggested file in the browser, if it exists.
762 string const filename = OnlyFilename(suggested);
763 if (!filename.empty()) {
764 for (int i = 0; i < fl_get_browser_maxline(file_dlg_form_->List); ++i) {
765 string s = fl_get_browser_line(file_dlg_form_->List, i + 1);
775 fl_select_browser_line(file_dlg_form_->List, sel);
776 int const top = max(sel - 5, 1);
777 fl_set_browser_topline(file_dlg_form_->List, top);
779 // checks whether dialog can be started
785 SetInfoLine(string());
786 setEnabled(file_dlg_form_->Filename, true);
787 fl_set_input(file_dlg_form_->Filename, suggested.c_str());
788 fl_set_button(file_dlg_form_->Cancel, 0);
789 fl_set_button(file_dlg_form_->Ready, 0);
790 fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->Filename);
791 fl_deactivate_all_forms();
792 // Prevent xforms crashing if the dialog gets too small by preventing
793 // it from being shrunk beyond a minimum size.
794 // calls to fl_set_form_minsize/maxsize apply only to the next
795 // fl_show_form(), so this comes first.
796 fl_set_form_minsize(file_dlg_form_->form, minw_, minh_);
798 fl_show_form(file_dlg_form_->form,
799 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
804 fl_hide_form(file_dlg_form_->form);
805 fl_activate_all_forms();
808 // Returns filename or string() if no valid selection was made
809 if (!isOk || !fl_get_input(file_dlg_form_->Filename)[0])
812 file_name_ = fl_get_input(file_dlg_form_->Filename);
814 if (!AbsolutePath(file_name_))
815 file_name_ = AddName(fl_get_input(file_dlg_form_->DirBox), file_name_);
820 // SelectDir: launches dialog and returns selected directory
821 string const FileDialog::Private::SelectDir(string const & title,
823 string const & suggested)
829 // handle case where path does not end with "/"
830 // remerge path+suggested and check if it is a valid path
831 if (!suggested.empty()) {
832 string tmp = suggested;
833 if (!suffixIs(tmp, '/'))
835 string full_path = path;
837 // check if this is really a directory
838 DIR * dir = ::opendir(full_path.c_str());
840 SetDirectory(full_path);
850 // checks whether dialog can be started
856 SetInfoLine(string());
857 fl_set_input(file_dlg_form_->Filename, "");
858 setEnabled(file_dlg_form_->Filename, false);
859 fl_set_button(file_dlg_form_->Cancel, 0);
860 fl_set_button(file_dlg_form_->Ready, 0);
861 fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->DirBox);
862 fl_deactivate_all_forms();
863 fl_show_form(file_dlg_form_->form,
864 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
869 fl_hide_form(file_dlg_form_->form);
870 fl_activate_all_forms();
873 // Returns directory or string() if no valid selection was made
877 file_name_ = fl_get_input(file_dlg_form_->DirBox);