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 bool globMatch(string const & a, string const & pattern)
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 regex = subst(pattern, ".", "\\.");
211 regex = subst(regex, "*", ".*");
213 boost::regex reg(regex);
214 return boost::regex_match(a, reg);
220 // Reread: updates dialog list to match class directory
221 void FileDialog::Private::Reread()
224 DIR * dir = ::opendir(directory_.c_str());
228 Alert::err_alert(_("Warning! Couldn't open directory."),
231 directory_ = getcwd();
232 dir = ::opendir(directory_.c_str());
235 // Clear the present namelist
236 dir_entries_.clear();
239 fl_hide_object(file_dlg_form_->List);
240 fl_clear_browser(file_dlg_form_->List);
241 fl_set_input(file_dlg_form_->DirBox, directory_.c_str());
243 // Splits complete directory name into directories and compute depth
247 string File = directory_;
249 File = split(File, Temp, '/');
251 while (!File.empty() || !Temp.empty()) {
252 string dline = "@b" + line + Temp + '/';
253 fl_add_browser_line(file_dlg_form_->List, dline.c_str());
254 File = split(File, Temp, '/');
259 // Parses all entries of the given subdirectory
260 time_t curTime = time(0);
262 while (dirent * entry = readdir(dir)) {
263 bool isLink = false, isDir = false;
265 // If the pattern doesn't start with a dot, skip hidden files
266 if (!mask_.empty() && mask_[0] != '.' &&
267 entry->d_name[0] == '.')
271 string fname = entry->d_name;
273 // Under all circumstances, "." and ".." are not wanted
274 if (fname == "." || fname == "..")
278 File = AddName(directory_, fname);
280 FileInfo fileInfo(File, true);
282 // can this really happen?
283 if (!fileInfo.isOK())
286 mode = fileInfo.modeString();
287 unsigned int const nlink = fileInfo.getNumberOfLinks();
288 string const user = lyxUserCache.find(fileInfo.getUid());
289 string const group = lyxGroupCache.find(fileInfo.getGid());
291 time_t modtime = fileInfo.getModificationTime();
292 string Time = ctime(&modtime);
294 if (curTime > modtime + SIX_MONTH_SEC
295 || curTime < modtime + ONE_HOUR_SEC) {
296 // The file is fairly old or in the future. POSIX says
297 // the cutoff is 6 months old. Allow a 1 hour slop
298 // factor for what is considered "the future", to
299 // allow for NFS server/client clock disagreement.
300 // Show the year instead of the time of day.
302 Time.erase(15, string::npos);
304 Time.erase(16, string::npos);
307 string buffer = mode + ' ' +
311 Time.substr(4, string::npos) + ' ';
313 buffer += entry->d_name;
314 buffer += fileInfo.typeIndicator();
316 isLink = fileInfo.isLink();
320 if (LyXReadLink(File, Link)) {
324 // This gives the FileType of the file that
325 // is really pointed too after resolving all
326 // symlinks. This is not necessarily the same
327 // as the type of Link (which could again be a
328 // link). Is that intended?
330 fileInfo.newFile(File);
332 buffer += fileInfo.typeIndicator();
338 // filters files according to pattern and type
339 if (fileInfo.isRegular()
341 || fileInfo.isBlock()
342 || fileInfo.isFifo()) {
343 if (!globMatch(fname, mask_))
345 } else if (!(isDir = fileInfo.isDir()))
350 // Note ls_entry_ is an string!
351 tmp.ls_entry_ = buffer;
358 // creates displayed name
359 temp = entry->d_name;
363 temp += fileInfo.typeIndicator();
364 tmp.displayed_ = temp;
366 dir_entries_.push_back(tmp);
372 sort(dir_entries_.begin(), dir_entries_.end(), comp_direntry());
374 // Add them to directory box
375 for (DirEntries::const_iterator cit = dir_entries_.begin();
376 cit != dir_entries_.end(); ++cit) {
377 string const temp = line + cit->displayed_;
378 fl_add_browser_line(file_dlg_form_->List, temp.c_str());
380 fl_set_browser_topline(file_dlg_form_->List, depth_);
381 fl_show_object(file_dlg_form_->List);
386 // SetDirectory: sets dialog current directory
387 void FileDialog::Private::SetDirectory(string const & path)
393 tmp = MakeAbsPath(ExpandPath(path), directory_);
395 // must check the directory exists
396 DIR * dir = ::opendir(tmp.c_str());
400 Alert::err_alert(_("Warning! Couldn't open directory."), tmp);
409 // SetMask: sets dialog file mask
410 void FileDialog::Private::SetMask(string const & newmask)
413 fl_set_input(file_dlg_form_->PatBox, mask_.c_str());
417 // SetInfoLine: sets dialog information line
418 void FileDialog::Private::SetInfoLine(string const & line)
421 fl_set_object_label(file_dlg_form_->FileInfo, info_line_.c_str());
425 FileDialog::Private::Private()
427 directory_ = MakeAbsPath(string("."));
430 // Creates form if necessary.
431 if (!file_dlg_form_) {
432 file_dlg_form_ = build_filedialog(this);
433 minw_ = file_dlg_form_->form->w;
434 minh_ = file_dlg_form_->form->h;
435 // Set callbacks. This means that we don't need a patch file
436 fl_set_object_callback(file_dlg_form_->DirBox,
437 C_LyXFileDlg_FileDlgCB, 0);
438 fl_set_object_callback(file_dlg_form_->PatBox,
439 C_LyXFileDlg_FileDlgCB, 1);
440 fl_set_object_callback(file_dlg_form_->List,
441 C_LyXFileDlg_FileDlgCB, 2);
442 fl_set_object_callback(file_dlg_form_->Filename,
443 C_LyXFileDlg_FileDlgCB, 3);
444 fl_set_object_callback(file_dlg_form_->Rescan,
445 C_LyXFileDlg_FileDlgCB, 10);
446 fl_set_object_callback(file_dlg_form_->Home,
447 C_LyXFileDlg_FileDlgCB, 11);
448 fl_set_object_callback(file_dlg_form_->User1,
449 C_LyXFileDlg_FileDlgCB, 12);
450 fl_set_object_callback(file_dlg_form_->User2,
451 C_LyXFileDlg_FileDlgCB, 13);
453 // Make sure pressing the close box doesn't crash LyX. (RvdK)
454 fl_set_form_atclose(file_dlg_form_->form,
455 C_LyXFileDlg_CancelCB, 0);
456 // Register doubleclick callback
457 fl_set_browser_dblclick_callback(file_dlg_form_->List,
458 C_LyXFileDlg_DoubleClickCB,
461 fl_hide_object(file_dlg_form_->User1);
462 fl_hide_object(file_dlg_form_->User2);
464 r_ = Dialogs::redrawGUI().connect(boost::bind(&FileDialog::Private::redraw, this));
468 FileDialog::Private::~Private()
474 void FileDialog::Private::redraw()
476 if (file_dlg_form_->form && file_dlg_form_->form->visible)
477 fl_redraw_form(file_dlg_form_->form);
481 // SetButton: sets file selector user button action
482 void FileDialog::Private::SetButton(int index, string const & name,
489 ob = file_dlg_form_->User1;
491 } else if (index == 1) {
492 ob = file_dlg_form_->User2;
499 fl_set_object_label(ob, idex(name).c_str());
500 fl_set_button_shortcut(ob, scex(name).c_str(), 1);
510 // GetDirectory: gets last dialog directory
511 string const FileDialog::Private::GetDirectory() const
513 if (!directory_.empty())
520 bool x_sync_kludge(bool ret)
522 XSync(fl_get_display(), false);
527 // RunDialog: handle dialog during file selection
528 bool FileDialog::Private::RunDialog()
530 force_cancel_ = false;
535 FL_OBJECT * ob = fl_do_forms();
537 if (ob == file_dlg_form_->Ready) {
539 return x_sync_kludge(true);
541 } else if (ob == file_dlg_form_->Cancel || force_cancel_)
542 return x_sync_kludge(false);
545 return x_sync_kludge(true);
550 // XForms objects callback (static)
551 void FileDialog::Private::FileDlgCB(FL_OBJECT *, long arg)
558 case 0: // get directory
559 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
560 current_dlg_->Reread();
564 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
565 current_dlg_->Reread();
569 current_dlg_->HandleListHit();
573 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
574 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
575 current_dlg_->Reread();
579 current_dlg_->SetDirectory(GetEnvPath("HOME"));
580 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
581 current_dlg_->Reread();
584 case 12: // user button 1
585 current_dlg_->SetDirectory(current_dlg_->user_path1_);
586 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
587 current_dlg_->Reread();
590 case 13: // user button 2
591 current_dlg_->SetDirectory(current_dlg_->user_path2_);
592 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
593 current_dlg_->Reread();
600 // Handle callback from list
601 void FileDialog::Private::HandleListHit()
604 int const select_ = fl_get_browser(file_dlg_form_->List);
605 if (select_ > depth_)
606 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
608 SetInfoLine(string());
612 // Callback for double click in list
613 void FileDialog::Private::DoubleClickCB(FL_OBJECT *, long)
615 // Simulate click on OK button
616 if (current_dlg_->HandleDoubleClick())
617 current_dlg_->Force(false);
621 // Handle double click from list
622 bool FileDialog::Private::HandleDoubleClick()
628 int const select_ = fl_get_browser(file_dlg_form_->List);
629 if (select_ > depth_) {
630 tmp = dir_entries_[select_ - depth_ - 1].name_;
631 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
632 if (!suffixIs(tmp, '/')) {
634 fl_set_input(file_dlg_form_->Filename, tmp.c_str());
636 } else if (select_ != 0) {
637 SetInfoLine(string());
645 // builds new directory name
646 if (select_ > depth_) {
647 // Directory deeper down
648 // First, get directory with trailing /
649 Temp = fl_get_input(file_dlg_form_->DirBox);
650 if (!suffixIs(Temp, '/'))
654 // Directory higher up
656 for (int i = 0; i < select_; ++i) {
657 string piece = fl_get_browser_line(file_dlg_form_->List, i+1);
658 // The '+2' is here to count the '@b' (JMarc)
659 Temp += piece.substr(i + 2);
672 // Handle OK button call
673 bool FileDialog::Private::HandleOK()
676 string tmp = fl_get_input(file_dlg_form_->PatBox);
683 // directory was changed
684 tmp = fl_get_input(file_dlg_form_->DirBox);
685 if (tmp != directory_) {
691 // Handle return from list
692 int const select = fl_get_browser(file_dlg_form_->List);
693 if (select > depth_) {
694 string const temp = dir_entries_[select - depth_ - 1].name_;
695 if (!suffixIs(temp, '/')) {
696 // If user didn't type anything, use browser
697 string const name = fl_get_input(file_dlg_form_->Filename);
699 fl_set_input(file_dlg_form_->Filename, temp.c_str());
704 // Emulate a doubleclick
705 return HandleDoubleClick();
709 // Handle Cancel CB from WM close
710 int FileDialog::Private::CancelCB(FL_FORM *, void *)
712 // Simulate a click on the cancel button
713 current_dlg_->Force(true);
718 // Simulates a click on OK/Cancel
719 void FileDialog::Private::Force(bool cancel)
722 force_cancel_ = true;
723 fl_set_button(file_dlg_form_->Cancel, 1);
726 fl_set_button(file_dlg_form_->Ready, 1);
728 // Start timer to break fl_do_forms loop soon
729 fl_set_timer(file_dlg_form_->timer, 0.1);
733 // Select: launches dialog and returns selected file
734 string const FileDialog::Private::Select(string const & title,
737 string const & suggested)
739 // handles new mask and path
752 // highlight the suggested file in the browser, if it exists.
754 string const filename = OnlyFilename(suggested);
755 if (!filename.empty()) {
756 for (int i = 0; i < fl_get_browser_maxline(file_dlg_form_->List); ++i) {
757 string s = fl_get_browser_line(file_dlg_form_->List, i + 1);
767 fl_select_browser_line(file_dlg_form_->List, sel);
768 int const top = max(sel - 5, 1);
769 fl_set_browser_topline(file_dlg_form_->List, top);
771 // checks whether dialog can be started
777 SetInfoLine(string());
778 setEnabled(file_dlg_form_->Filename, true);
779 fl_set_input(file_dlg_form_->Filename, suggested.c_str());
780 fl_set_button(file_dlg_form_->Cancel, 0);
781 fl_set_button(file_dlg_form_->Ready, 0);
782 fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->Filename);
783 fl_deactivate_all_forms();
784 // Prevent xforms crashing if the dialog gets too small by preventing
785 // it from being shrunk beyond a minimum size.
786 // calls to fl_set_form_minsize/maxsize apply only to the next
787 // fl_show_form(), so this comes first.
788 fl_set_form_minsize(file_dlg_form_->form, minw_, minh_);
790 fl_show_form(file_dlg_form_->form,
791 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
796 fl_hide_form(file_dlg_form_->form);
797 fl_activate_all_forms();
800 // Returns filename or string() if no valid selection was made
801 if (!isOk || !fl_get_input(file_dlg_form_->Filename)[0])
804 file_name_ = fl_get_input(file_dlg_form_->Filename);
806 if (!AbsolutePath(file_name_))
807 file_name_ = AddName(fl_get_input(file_dlg_form_->DirBox), file_name_);
812 // SelectDir: launches dialog and returns selected directory
813 string const FileDialog::Private::SelectDir(string const & title,
815 string const & suggested)
821 // handle case where path does not end with "/"
822 // remerge path+suggested and check if it is a valid path
823 if (!suggested.empty()) {
824 string tmp = suggested;
825 if (!suffixIs(tmp, '/'))
827 string full_path = path;
829 // check if this is really a directory
830 DIR * dir = ::opendir(full_path.c_str());
832 SetDirectory(full_path);
842 // checks whether dialog can be started
848 SetInfoLine(string());
849 fl_set_input(file_dlg_form_->Filename, "");
850 setEnabled(file_dlg_form_->Filename, false);
851 fl_set_button(file_dlg_form_->Cancel, 0);
852 fl_set_button(file_dlg_form_->Ready, 0);
853 fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->DirBox);
854 fl_deactivate_all_forms();
855 fl_show_form(file_dlg_form_->form,
856 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
861 fl_hide_form(file_dlg_form_->form);
862 fl_activate_all_forms();
865 // Returns directory or string() if no valid selection was made
869 file_name_ = fl_get_input(file_dlg_form_->DirBox);