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>
44 # define dirent direct
46 # include <sys/ndir.h>
56 using lyx::support::AbsolutePath;
57 using lyx::support::AddName;
58 using lyx::support::ExpandPath;
59 using lyx::support::FileInfo;
60 using lyx::support::getcwd;
61 using lyx::support::GetEnvPath;
62 using lyx::support::LyXReadLink;
63 using lyx::support::MakeAbsPath;
64 using lyx::support::OnlyFilename;
65 using lyx::support::regexMatch;
66 using lyx::support::split;
67 using lyx::support::suffixIs;
68 using lyx::support::trim;
78 // six months, in seconds
79 long const SIX_MONTH_SEC = 6L * 30L * 24L * 60L * 60L;
81 long const ONE_HOUR_SEC = 60L * 60L;
86 int C_LyXFileDlg_CancelCB(FL_FORM *fl, void *xev)
88 return FileDialog::Private::CancelCB(fl, xev);
92 void C_LyXFileDlg_DoubleClickCB(FL_OBJECT * ob, long data)
94 FileDialog::Private::DoubleClickCB(ob, data);
98 void C_LyXFileDlg_FileDlgCB(FL_OBJECT * ob, long data)
100 FileDialog::Private::FileDlgCB(ob, data);
105 // *** User cache class implementation
106 /// User cache class definition
109 /// seeks user name from group ID
110 string const & find(uid_t ID) const {
111 Users::const_iterator cit = users.find(ID);
112 if (cit == users.end()) {
120 void add(uid_t ID) const;
122 typedef map<uid_t, string> Users;
128 void UserCache::add(uid_t ID) const
130 struct passwd const * entry = getpwuid(ID);
131 users[ID] = entry ? entry->pw_name : tostr(int(ID));
135 /// Group cache class definition
138 /// seeks group name from group ID
139 string const & find(gid_t ID) const ;
142 void add(gid_t ID) const;
144 typedef map<gid_t, string> Groups;
146 mutable Groups groups;
150 string const & GroupCache::find(gid_t ID) const
152 Groups::const_iterator cit = groups.find(ID);
153 if (cit == groups.end()) {
161 void GroupCache::add(gid_t ID) const
163 struct group const * entry = getgrgid(ID);
164 groups[ID] = entry ? entry->gr_name : tostr(int(ID));
168 UserCache lyxUserCache;
169 GroupCache lyxGroupCache;
171 // compares two LyXDirEntry objects content (used for sort)
172 class comp_direntry {
174 bool operator()(DirEntry const & r1, DirEntry const & r2) const
176 bool const r1d = suffixIs(r1.name_, '/');
177 bool const r2d = suffixIs(r2.name_, '/');
182 return r1.name_ < r2.name_;
191 // *** FileDialog::Private class implementation
194 FD_filedialog * FileDialog::Private::file_dlg_form_ = 0;
195 FileDialog::Private * FileDialog::Private::current_dlg_ = 0;
196 int FileDialog::Private::minw_ = 0;
197 int FileDialog::Private::minh_ = 0;
200 // Reread: updates dialog list to match class directory
201 void FileDialog::Private::Reread()
204 DIR * dir = ::opendir(directory_.c_str());
208 Alert::err_alert(_("Warning! Couldn't open directory."),
211 directory_ = getcwd();
212 dir = ::opendir(directory_.c_str());
215 // Clear the present namelist
216 dir_entries_.clear();
219 fl_hide_object(file_dlg_form_->List);
220 fl_clear_browser(file_dlg_form_->List);
221 fl_set_input(file_dlg_form_->DirBox, directory_.c_str());
223 // Splits complete directory name into directories and compute depth
227 string File = directory_;
229 File = split(File, Temp, '/');
231 while (!File.empty() || !Temp.empty()) {
232 string dline = "@b" + line + Temp + '/';
233 fl_add_browser_line(file_dlg_form_->List, dline.c_str());
234 File = split(File, Temp, '/');
239 // Parses all entries of the given subdirectory
240 time_t curTime = time(0);
242 while (dirent * entry = readdir(dir)) {
243 bool isLink = false, isDir = false;
245 // If the pattern doesn't start with a dot, skip hidden files
246 if (!mask_.empty() && mask_[0] != '.' &&
247 entry->d_name[0] == '.')
251 string fname = entry->d_name;
253 // Under all circumstances, "." and ".." are not wanted
254 if (fname == "." || fname == "..")
258 File = AddName(directory_, fname);
260 FileInfo fileInfo(File, true);
262 // can this really happen?
263 if (!fileInfo.isOK())
266 mode = fileInfo.modeString();
267 unsigned int const nlink = fileInfo.getNumberOfLinks();
268 string const user = lyxUserCache.find(fileInfo.getUid());
269 string const group = lyxGroupCache.find(fileInfo.getGid());
271 time_t modtime = fileInfo.getModificationTime();
272 string Time = ctime(&modtime);
274 if (curTime > modtime + SIX_MONTH_SEC
275 || curTime < modtime + ONE_HOUR_SEC) {
276 // The file is fairly old or in the future. POSIX says
277 // the cutoff is 6 months old. Allow a 1 hour slop
278 // factor for what is considered "the future", to
279 // allow for NFS server/client clock disagreement.
280 // Show the year instead of the time of day.
282 Time.erase(15, string::npos);
284 Time.erase(16, string::npos);
287 string buffer = mode + ' ' +
291 Time.substr(4, string::npos) + ' ';
293 buffer += entry->d_name;
294 buffer += fileInfo.typeIndicator();
296 isLink = fileInfo.isLink();
300 if (LyXReadLink(File, Link)) {
304 // This gives the FileType of the file that
305 // is really pointed too after resolving all
306 // symlinks. This is not necessarily the same
307 // as the type of Link (which could again be a
308 // link). Is that intended?
310 fileInfo.newFile(File);
312 buffer += fileInfo.typeIndicator();
318 // filters files according to pattern and type
319 if (fileInfo.isRegular()
321 || fileInfo.isBlock()
322 || fileInfo.isFifo()) {
323 if (!regexMatch(fname, mask_))
325 } else if (!(isDir = fileInfo.isDir()))
330 // Note ls_entry_ is an string!
331 tmp.ls_entry_ = buffer;
338 // creates displayed name
339 temp = entry->d_name;
343 temp += fileInfo.typeIndicator();
344 tmp.displayed_ = temp;
346 dir_entries_.push_back(tmp);
352 sort(dir_entries_.begin(), dir_entries_.end(), comp_direntry());
354 // Add them to directory box
355 for (DirEntries::const_iterator cit = dir_entries_.begin();
356 cit != dir_entries_.end(); ++cit) {
357 string const temp = line + cit->displayed_;
358 fl_add_browser_line(file_dlg_form_->List, temp.c_str());
360 fl_set_browser_topline(file_dlg_form_->List, depth_);
361 fl_show_object(file_dlg_form_->List);
366 // SetDirectory: sets dialog current directory
367 void FileDialog::Private::SetDirectory(string const & path)
373 tmp = MakeAbsPath(ExpandPath(path), directory_);
375 // must check the directory exists
376 DIR * dir = ::opendir(tmp.c_str());
380 Alert::err_alert(_("Warning! Couldn't open directory."), tmp);
389 // SetMask: sets dialog file mask
390 void FileDialog::Private::SetMask(string const & newmask)
393 fl_set_input(file_dlg_form_->PatBox, mask_.c_str());
397 // SetInfoLine: sets dialog information line
398 void FileDialog::Private::SetInfoLine(string const & line)
401 fl_set_object_label(file_dlg_form_->FileInfo, info_line_.c_str());
405 FileDialog::Private::Private()
407 directory_ = MakeAbsPath(string("."));
410 // Creates form if necessary.
411 if (!file_dlg_form_) {
412 file_dlg_form_ = build_filedialog(this);
413 minw_ = file_dlg_form_->form->w;
414 minh_ = file_dlg_form_->form->h;
415 // Set callbacks. This means that we don't need a patch file
416 fl_set_object_callback(file_dlg_form_->DirBox,
417 C_LyXFileDlg_FileDlgCB, 0);
418 fl_set_object_callback(file_dlg_form_->PatBox,
419 C_LyXFileDlg_FileDlgCB, 1);
420 fl_set_object_callback(file_dlg_form_->List,
421 C_LyXFileDlg_FileDlgCB, 2);
422 fl_set_object_callback(file_dlg_form_->Filename,
423 C_LyXFileDlg_FileDlgCB, 3);
424 fl_set_object_callback(file_dlg_form_->Rescan,
425 C_LyXFileDlg_FileDlgCB, 10);
426 fl_set_object_callback(file_dlg_form_->Home,
427 C_LyXFileDlg_FileDlgCB, 11);
428 fl_set_object_callback(file_dlg_form_->User1,
429 C_LyXFileDlg_FileDlgCB, 12);
430 fl_set_object_callback(file_dlg_form_->User2,
431 C_LyXFileDlg_FileDlgCB, 13);
433 // Make sure pressing the close box doesn't crash LyX. (RvdK)
434 fl_set_form_atclose(file_dlg_form_->form,
435 C_LyXFileDlg_CancelCB, 0);
436 // Register doubleclick callback
437 fl_set_browser_dblclick_callback(file_dlg_form_->List,
438 C_LyXFileDlg_DoubleClickCB,
441 fl_hide_object(file_dlg_form_->User1);
442 fl_hide_object(file_dlg_form_->User2);
444 r_ = Dialogs::redrawGUI().connect(boost::bind(&FileDialog::Private::redraw, this));
448 FileDialog::Private::~Private()
454 void FileDialog::Private::redraw()
456 if (file_dlg_form_->form && file_dlg_form_->form->visible)
457 fl_redraw_form(file_dlg_form_->form);
461 // SetButton: sets file selector user button action
462 void FileDialog::Private::SetButton(int index, string const & name,
469 ob = file_dlg_form_->User1;
471 } else if (index == 1) {
472 ob = file_dlg_form_->User2;
479 fl_set_object_label(ob, idex(name).c_str());
480 fl_set_button_shortcut(ob, scex(name).c_str(), 1);
490 // GetDirectory: gets last dialog directory
491 string const FileDialog::Private::GetDirectory() const
493 if (!directory_.empty())
500 bool x_sync_kludge(bool ret)
502 XSync(fl_get_display(), false);
507 // RunDialog: handle dialog during file selection
508 bool FileDialog::Private::RunDialog()
510 force_cancel_ = false;
515 FL_OBJECT * ob = fl_do_forms();
517 if (ob == file_dlg_form_->Ready) {
519 return x_sync_kludge(true);
521 } else if (ob == file_dlg_form_->Cancel || force_cancel_)
522 return x_sync_kludge(false);
525 return x_sync_kludge(true);
530 // XForms objects callback (static)
531 void FileDialog::Private::FileDlgCB(FL_OBJECT *, long arg)
538 case 0: // get directory
539 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
540 current_dlg_->Reread();
544 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
545 current_dlg_->Reread();
549 current_dlg_->HandleListHit();
553 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
554 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
555 current_dlg_->Reread();
559 current_dlg_->SetDirectory(GetEnvPath("HOME"));
560 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
561 current_dlg_->Reread();
564 case 12: // user button 1
565 current_dlg_->SetDirectory(current_dlg_->user_path1_);
566 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
567 current_dlg_->Reread();
570 case 13: // user button 2
571 current_dlg_->SetDirectory(current_dlg_->user_path2_);
572 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
573 current_dlg_->Reread();
580 // Handle callback from list
581 void FileDialog::Private::HandleListHit()
584 int const select_ = fl_get_browser(file_dlg_form_->List);
585 if (select_ > depth_)
586 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
588 SetInfoLine(string());
592 // Callback for double click in list
593 void FileDialog::Private::DoubleClickCB(FL_OBJECT *, long)
595 // Simulate click on OK button
596 if (current_dlg_->HandleDoubleClick())
597 current_dlg_->Force(false);
601 // Handle double click from list
602 bool FileDialog::Private::HandleDoubleClick()
608 int const select_ = fl_get_browser(file_dlg_form_->List);
609 if (select_ > depth_) {
610 tmp = dir_entries_[select_ - depth_ - 1].name_;
611 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
612 if (!suffixIs(tmp, '/')) {
614 fl_set_input(file_dlg_form_->Filename, tmp.c_str());
616 } else if (select_ != 0) {
617 SetInfoLine(string());
625 // builds new directory name
626 if (select_ > depth_) {
627 // Directory deeper down
628 // First, get directory with trailing /
629 Temp = fl_get_input(file_dlg_form_->DirBox);
630 if (!suffixIs(Temp, '/'))
634 // Directory higher up
636 for (int i = 0; i < select_; ++i) {
637 string piece = fl_get_browser_line(file_dlg_form_->List, i+1);
638 // The '+2' is here to count the '@b' (JMarc)
639 Temp += piece.substr(i + 2);
652 // Handle OK button call
653 bool FileDialog::Private::HandleOK()
656 string tmp = fl_get_input(file_dlg_form_->PatBox);
663 // directory was changed
664 tmp = fl_get_input(file_dlg_form_->DirBox);
665 if (tmp != directory_) {
671 // Handle return from list
672 int const select = fl_get_browser(file_dlg_form_->List);
673 if (select > depth_) {
674 string const temp = dir_entries_[select - depth_ - 1].name_;
675 if (!suffixIs(temp, '/')) {
676 // If user didn't type anything, use browser
677 string const name = fl_get_input(file_dlg_form_->Filename);
679 fl_set_input(file_dlg_form_->Filename, temp.c_str());
684 // Emulate a doubleclick
685 return HandleDoubleClick();
689 // Handle Cancel CB from WM close
690 int FileDialog::Private::CancelCB(FL_FORM *, void *)
692 // Simulate a click on the cancel button
693 current_dlg_->Force(true);
698 // Simulates a click on OK/Cancel
699 void FileDialog::Private::Force(bool cancel)
702 force_cancel_ = true;
703 fl_set_button(file_dlg_form_->Cancel, 1);
706 fl_set_button(file_dlg_form_->Ready, 1);
708 // Start timer to break fl_do_forms loop soon
709 fl_set_timer(file_dlg_form_->timer, 0.1);
713 // Select: launches dialog and returns selected file
714 string const FileDialog::Private::Select(string const & title,
717 string const & suggested)
719 // handles new mask and path
732 // highlight the suggested file in the browser, if it exists.
734 string const filename = OnlyFilename(suggested);
735 if (!filename.empty()) {
736 for (int i = 0; i < fl_get_browser_maxline(file_dlg_form_->List); ++i) {
737 string s = fl_get_browser_line(file_dlg_form_->List, i + 1);
747 fl_select_browser_line(file_dlg_form_->List, sel);
748 int const top = max(sel - 5, 1);
749 fl_set_browser_topline(file_dlg_form_->List, top);
751 // checks whether dialog can be started
757 SetInfoLine(string());
758 setEnabled(file_dlg_form_->Filename, true);
759 fl_set_input(file_dlg_form_->Filename, suggested.c_str());
760 fl_set_button(file_dlg_form_->Cancel, 0);
761 fl_set_button(file_dlg_form_->Ready, 0);
762 fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->Filename);
763 fl_deactivate_all_forms();
764 // Prevent xforms crashing if the dialog gets too small by preventing
765 // it from being shrunk beyond a minimum size.
766 // calls to fl_set_form_minsize/maxsize apply only to the next
767 // fl_show_form(), so this comes first.
768 fl_set_form_minsize(file_dlg_form_->form, minw_, minh_);
770 fl_show_form(file_dlg_form_->form,
771 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
776 fl_hide_form(file_dlg_form_->form);
777 fl_activate_all_forms();
780 // Returns filename or string() if no valid selection was made
781 if (!isOk || !fl_get_input(file_dlg_form_->Filename)[0])
784 file_name_ = fl_get_input(file_dlg_form_->Filename);
786 if (!AbsolutePath(file_name_))
787 file_name_ = AddName(fl_get_input(file_dlg_form_->DirBox), file_name_);
792 // SelectDir: launches dialog and returns selected directory
793 string const FileDialog::Private::SelectDir(string const & title,
795 string const & suggested)
801 // handle case where path does not end with "/"
802 // remerge path+suggested and check if it is a valid path
803 if (!suggested.empty()) {
804 string tmp = suggested;
805 if (!suffixIs(tmp, '/'))
807 string full_path = path;
809 // check if this is really a directory
810 DIR * dir = ::opendir(full_path.c_str());
812 SetDirectory(full_path);
822 // checks whether dialog can be started
828 SetInfoLine(string());
829 fl_set_input(file_dlg_form_->Filename, "");
830 setEnabled(file_dlg_form_->Filename, false);
831 fl_set_button(file_dlg_form_->Cancel, 0);
832 fl_set_button(file_dlg_form_->Ready, 0);
833 fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->DirBox);
834 fl_deactivate_all_forms();
835 fl_show_form(file_dlg_form_->form,
836 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
841 fl_hide_form(file_dlg_form_->form);
842 fl_activate_all_forms();
845 // Returns directory or string() if no valid selection was made
849 file_name_ = fl_get_input(file_dlg_form_->DirBox);