2 * \file FormFiledialog.C
3 * Copyright 2001 the LyX Team
4 * Read the file COPYING
7 * \author John Levon, moz@compsoc.man.ac.uk
24 #include "frontends/Alert.h"
25 #include "support/FileInfo.h"
26 #include "support/lyxlib.h"
27 #include "support/lstrings.h"
29 #include "frontends/Dialogs.h"
30 #include "forms_gettext.h"
32 #include <boost/bind.hpp>
40 # define NAMLEN(dirent) strlen((dirent)->d_name)
42 # define dirent direct
43 # define NAMLEN(dirent) (dirent)->d_namlen
45 # include <sys/ndir.h>
55 #if TIME_WITH_SYS_TIME
56 # include <sys/time.h>
60 # include <sys/time.h>
66 // FIXME: should be autoconfiscated
68 extern "C" int gettimeofday(struct timeval *, struct timezone *);
72 #pragma implementation
75 #include "support/filetools.h"
76 #include "FormFiledialog.h"
77 #include "forms/form_filedialog.h"
78 #include FORMS_H_LOCATION
82 // six months, in seconds
83 long const SIX_MONTH_SEC = 6L * 30L * 24L * 60L * 60L;
85 long const ONE_HOUR_SEC = 60L * 60L;
90 int C_LyXFileDlg_CancelCB(FL_FORM *fl, void *xev)
92 return FileDialog::Private::CancelCB(fl, xev);
96 void C_LyXFileDlg_DoubleClickCB(FL_OBJECT * ob, long data)
98 FileDialog::Private::DoubleClickCB(ob, data);
102 void C_LyXFileDlg_FileDlgCB(FL_OBJECT * ob, long data)
104 FileDialog::Private::FileDlgCB(ob, data);
112 // *** User cache class implementation
113 /// User cache class definition
116 /// seeks user name from group ID
117 string const & find(uid_t ID) const {
118 Users::const_iterator cit = users.find(ID);
119 if (cit == users.end()) {
127 void add(uid_t ID) const;
129 typedef map<uid_t, string> Users;
135 void UserCache::add(uid_t ID) const
138 struct passwd * pEntry;
141 if ((pEntry = getpwuid(ID)))
142 pszNewName = pEntry->pw_name;
144 pszNewName = tostr(ID);
148 users[ID] = pszNewName;
152 /// Group cache class definition
155 /// seeks group name from group ID
156 string const & find(gid_t ID) const ;
159 void add(gid_t ID) const;
161 typedef map<gid_t, string> Groups;
163 mutable Groups groups;
167 string const & GroupCache::find(gid_t ID) const
169 Groups::const_iterator cit = groups.find(ID);
170 if (cit == groups.end()) {
178 void GroupCache::add(gid_t ID) const
181 struct group * pEntry;
184 if ((pEntry = getgrgid(ID))) pszNewName = pEntry->gr_name;
186 pszNewName = tostr(ID);
189 groups[ID] = pszNewName;
196 UserCache lyxUserCache;
197 GroupCache lyxGroupCache;
202 // compares two LyXDirEntry objects content (used for sort)
203 class comp_direntry {
205 int operator()(DirEntry const & r1,
206 DirEntry const & r2) const ;
208 int comp_direntry::operator()(DirEntry const & r1,
209 DirEntry const & r2) const {
210 bool r1d = suffixIs(r1.pszName, '/');
211 bool r2d = suffixIs(r2.pszName, '/');
212 if (r1d && !r2d) return 1;
213 if (!r1d && r2d) return 0;
214 return r1.pszName < r2.pszName;
218 // *** FileDialog::Private class implementation
221 FD_filedialog * FileDialog::Private::pFileDlgForm = 0;
222 FileDialog::Private * FileDialog::Private::pCurrentDlg = 0;
225 // Reread: updates dialog list to match class directory
226 void FileDialog::Private::Reread()
229 DIR * pDirectory = ::opendir(pszDirectory.c_str());
231 Alert::err_alert(_("Warning! Couldn't open directory."),
233 pszDirectory = lyx::getcwd();
234 pDirectory = ::opendir(pszDirectory.c_str());
237 // Clear the present namelist
241 fl_hide_object(pFileDlgForm->List);
242 fl_clear_browser(pFileDlgForm->List);
243 fl_set_input(pFileDlgForm->DirBox, pszDirectory.c_str());
245 // Splits complete directory name into directories and compute depth
249 string File = pszDirectory;
251 File = split(File, Temp, '/');
253 while (!File.empty() || !Temp.empty()) {
254 string dline = "@b"+line + Temp + '/';
255 fl_add_browser_line(pFileDlgForm->List, dline.c_str());
256 File = split(File, Temp, '/');
261 // Parses all entries of the given subdirectory
262 time_t curTime = time(0);
263 rewinddir(pDirectory);
264 struct dirent * pDirEntry;
265 while ((pDirEntry = readdir(pDirectory))) {
266 bool isLink = false, isDir = false;
268 // If the pattern doesn't start with a dot, skip hidden files
269 if (!pszMask.empty() && pszMask[0] != '.' &&
270 pDirEntry->d_name[0] == '.')
274 string fname = pDirEntry->d_name;
276 // Under all circumstances, "." and ".." are not wanted
277 if (fname == "." || fname == "..")
281 File = AddName(pszDirectory, fname);
283 FileInfo fileInfo(File, true);
285 // can this really happen?
286 if (!fileInfo.isOK())
289 fileInfo.modeString(szMode);
290 unsigned int nlink = fileInfo.getNumberOfLinks();
291 string user = lyxUserCache.find(fileInfo.getUid());
292 string group = lyxGroupCache.find(fileInfo.getGid());
294 time_t modtime = fileInfo.getModificationTime();
295 string Time = ctime(&modtime);
297 if (curTime > modtime + SIX_MONTH_SEC
298 || curTime < modtime + ONE_HOUR_SEC) {
299 // The file is fairly old or in the future. POSIX says
300 // the cutoff is 6 months old. Allow a 1 hour slop
301 // factor for what is considered "the future", to
302 // allow for NFS server/client clock disagreement.
303 // Show the year instead of the time of day.
305 Time.erase(15, string::npos);
307 Time.erase(16, string::npos);
310 string Buffer = string(szMode) + ' ' +
314 Time.substr(4, string::npos) + ' ';
316 Buffer += pDirEntry->d_name;
317 Buffer += fileInfo.typeIndicator();
319 if ((isLink = fileInfo.isLink())) {
322 if (LyXReadLink(File, Link)) {
326 // This gives the FileType of the file that
327 // is really pointed too after resolving all
328 // symlinks. This is not necessarily the same
329 // as the type of Link (which could again be a
330 // link). Is that intended?
332 fileInfo.newFile(File);
334 Buffer += fileInfo.typeIndicator();
340 // filters files according to pattern and type
341 if (fileInfo.isRegular()
343 || fileInfo.isBlock()
344 || fileInfo.isFifo()) {
345 if (!regexMatch(fname, pszMask))
347 } else if (!(isDir = fileInfo.isDir()))
352 // Note pszLsEntry is an string!
353 tmp.pszLsEntry = Buffer;
356 if (isDir) temp += '/';
359 // creates displayed name
360 temp = pDirEntry->d_name;
364 temp += fileInfo.typeIndicator();
365 tmp.pszDisplayed = temp;
367 direntries.push_back(tmp);
370 closedir(pDirectory);
373 sort(direntries.begin(), direntries.end(), comp_direntry());
375 // Add them to directory box
376 for (DirEntries::const_iterator cit = direntries.begin();
377 cit != direntries.end(); ++cit) {
378 string const temp = line + cit->pszDisplayed;
379 fl_add_browser_line(pFileDlgForm->List, temp.c_str());
381 fl_set_browser_topline(pFileDlgForm->List, iDepth);
382 fl_show_object(pFileDlgForm->List);
387 // SetDirectory: sets dialog current directory
388 void FileDialog::Private::SetDirectory(string const & Path)
396 tmp = MakeAbsPath(ExpandPath(Path), pszDirectory);
398 // must check the directory exists
399 DIR * pDirectory = ::opendir(tmp.c_str());
401 Alert::err_alert(_("Warning! Couldn't open directory."), tmp);
403 ::closedir(pDirectory);
409 // SetMask: sets dialog file mask
410 void FileDialog::Private::SetMask(string const & NewMask)
413 fl_set_input(pFileDlgForm->PatBox, pszMask.c_str());
417 // SetInfoLine: sets dialog information line
418 void FileDialog::Private::SetInfoLine(string const & Line)
421 fl_set_object_label(pFileDlgForm->FileInfo, pszInfoLine.c_str());
425 FileDialog::Private::Private(Dialogs & dia)
427 pszDirectory = MakeAbsPath(string("."));
430 // Creates form if necessary.
432 pFileDlgForm = build_filedialog(this);
433 // Set callbacks. This means that we don't need a patch file
434 fl_set_object_callback(pFileDlgForm->DirBox,
435 C_LyXFileDlg_FileDlgCB, 0);
436 fl_set_object_callback(pFileDlgForm->PatBox,
437 C_LyXFileDlg_FileDlgCB, 1);
438 fl_set_object_callback(pFileDlgForm->List,
439 C_LyXFileDlg_FileDlgCB, 2);
440 fl_set_object_callback(pFileDlgForm->Filename,
441 C_LyXFileDlg_FileDlgCB, 3);
442 fl_set_object_callback(pFileDlgForm->Rescan,
443 C_LyXFileDlg_FileDlgCB, 10);
444 fl_set_object_callback(pFileDlgForm->Home,
445 C_LyXFileDlg_FileDlgCB, 11);
446 fl_set_object_callback(pFileDlgForm->User1,
447 C_LyXFileDlg_FileDlgCB, 12);
448 fl_set_object_callback(pFileDlgForm->User2,
449 C_LyXFileDlg_FileDlgCB, 13);
451 // Make sure pressing the close box doesn't crash LyX. (RvdK)
452 fl_set_form_atclose(pFileDlgForm->form,
453 C_LyXFileDlg_CancelCB, 0);
454 // Register doubleclick callback
455 fl_set_browser_dblclick_callback(pFileDlgForm->List,
456 C_LyXFileDlg_DoubleClickCB,
459 fl_hide_object(pFileDlgForm->User1);
460 fl_hide_object(pFileDlgForm->User2);
462 r_ = dia.redrawGUI.connect(boost::bind(&FileDialog::Private::redraw, this));
466 FileDialog::Private::~Private()
472 void FileDialog::Private::redraw()
474 if (pFileDlgForm->form && pFileDlgForm->form->visible)
475 fl_redraw_form(pFileDlgForm->form);
479 // SetButton: sets file selector user button action
480 void FileDialog::Private::SetButton(int iIndex, string const & pszName,
481 string const & pszPath)
487 pObject = pFileDlgForm->User1;
488 pTemp = &pszUserPath1;
489 } else if (iIndex == 1) {
490 pObject = pFileDlgForm->User2;
491 pTemp = &pszUserPath2;
494 if (!pszName.empty()) {
495 fl_set_object_label(pObject, idex(pszName.c_str()));
496 fl_set_button_shortcut(pObject, scex(pszName.c_str()), 1);
497 fl_show_object(pObject);
500 fl_hide_object(pObject);
506 // GetDirectory: gets last dialog directory
507 string const FileDialog::Private::GetDirectory() const
509 if (!pszDirectory.empty())
516 bool x_sync_kludge(bool ret)
518 XSync(fl_get_display(), false);
523 // RunDialog: handle dialog during file selection
524 bool FileDialog::Private::RunDialog()
526 force_cancel = false;
531 FL_OBJECT * pObject = fl_do_forms();
533 if (pObject == pFileDlgForm->Ready) {
535 return x_sync_kludge(true);
537 } else if (pObject == pFileDlgForm->Cancel
539 return x_sync_kludge(false);
542 return x_sync_kludge(true);
547 // XForms objects callback (static)
548 void FileDialog::Private::FileDlgCB(FL_OBJECT *, long lArgument)
550 if (!pCurrentDlg) return;
554 case 0: // get directory
555 pCurrentDlg->SetDirectory(fl_get_input(pFileDlgForm->DirBox));
556 pCurrentDlg->Reread();
560 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm->PatBox));
561 pCurrentDlg->Reread();
565 pCurrentDlg->HandleListHit();
569 pCurrentDlg->SetDirectory(fl_get_input(pFileDlgForm->DirBox));
570 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm->PatBox));
571 pCurrentDlg->Reread();
575 pCurrentDlg->SetDirectory(GetEnvPath("HOME"));
576 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm->PatBox));
577 pCurrentDlg->Reread();
580 case 12: // user button 1
581 pCurrentDlg->SetDirectory(pCurrentDlg->pszUserPath1);
582 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm
584 pCurrentDlg->Reread();
587 case 13: // user button 2
588 pCurrentDlg->SetDirectory(pCurrentDlg->pszUserPath2);
589 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm
591 pCurrentDlg->Reread();
598 // Handle callback from list
599 void FileDialog::Private::HandleListHit()
602 int const iSelect = fl_get_browser(pFileDlgForm->List);
603 if (iSelect > iDepth) {
604 SetInfoLine(direntries[iSelect - iDepth - 1].pszLsEntry);
606 SetInfoLine(string());
611 // Callback for double click in list
612 void FileDialog::Private::DoubleClickCB(FL_OBJECT *, long)
614 if (pCurrentDlg->HandleDoubleClick())
615 // Simulate click on OK button
616 pCurrentDlg->Force(false);
620 // Handle double click from list
621 bool FileDialog::Private::HandleDoubleClick()
627 int const iSelect = fl_get_browser(pFileDlgForm->List);
628 if (iSelect > iDepth) {
629 pszTemp = direntries[iSelect - iDepth - 1].pszName;
630 SetInfoLine(direntries[iSelect - iDepth - 1].pszLsEntry);
631 if (!suffixIs(pszTemp, '/')) {
633 fl_set_input(pFileDlgForm->Filename, pszTemp.c_str());
635 } else if (iSelect != 0) {
636 SetInfoLine(string());
644 // builds new directory name
645 if (iSelect > iDepth) {
646 // Directory deeper down
647 // First, get directory with trailing /
648 Temp = fl_get_input(pFileDlgForm->DirBox);
649 if (!suffixIs(Temp, '/'))
653 // Directory higher up
655 for (int i = 0; i < iSelect; ++i) {
656 string piece = fl_get_browser_line(pFileDlgForm->List, i+1);
657 // The '+2' is here to count the '@b' (JMarc)
658 Temp += piece.substr(i + 2);
671 // Handle OK button call
672 bool FileDialog::Private::HandleOK()
675 string pszTemp = fl_get_input(pFileDlgForm->PatBox);
676 if (pszTemp != pszMask) {
682 // directory was changed
683 pszTemp = fl_get_input(pFileDlgForm->DirBox);
684 if (pszTemp!= pszDirectory) {
685 SetDirectory(pszTemp);
690 // Handle return from list
691 int const select = fl_get_browser(pFileDlgForm->List);
692 if (select > iDepth) {
693 string const temp = direntries[select - iDepth - 1].pszName;
694 if (!suffixIs(temp, '/')) {
695 // If user didn't type anything, use browser
697 fl_get_input(pFileDlgForm->Filename);
699 fl_set_input(pFileDlgForm->Filename, temp.c_str());
705 // Emulate a doubleclick
706 return HandleDoubleClick();
710 // Handle Cancel CB from WM close
711 int FileDialog::Private::CancelCB(FL_FORM *, void *)
713 // Simulate a click on the cancel button
714 pCurrentDlg->Force(true);
719 // Simulates a click on OK/Cancel
720 void FileDialog::Private::Force(bool cancel)
724 fl_set_button(pFileDlgForm->Cancel, 1);
727 fl_set_button(pFileDlgForm->Ready, 1);
729 // Start timer to break fl_do_forms loop soon
730 fl_set_timer(pFileDlgForm->timer, 0.1);
734 // Select: launches dialog and returns selected file
735 string const FileDialog::Private::Select(string const & title,
738 string const & suggested)
740 // 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()) {
757 i < fl_get_browser_maxline(pFileDlgForm->List); ++i) {
759 fl_get_browser_line(pFileDlgForm->List, i + 1);
760 s = strip(frontStrip(s));
768 if (sel != 0) fl_select_browser_line(pFileDlgForm->List, sel);
769 int const top = max(sel - 5, 1);
770 fl_set_browser_topline(pFileDlgForm->List, top);
772 // checks whether dialog can be started
773 if (pCurrentDlg) return string();
777 SetInfoLine(string());
778 fl_set_input(pFileDlgForm->Filename, suggested.c_str());
779 fl_set_button(pFileDlgForm->Cancel, 0);
780 fl_set_button(pFileDlgForm->Ready, 0);
781 fl_set_focus_object(pFileDlgForm->form, pFileDlgForm->Filename);
782 fl_deactivate_all_forms();
783 fl_show_form(pFileDlgForm->form,
784 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
789 fl_hide_form(pFileDlgForm->form);
790 fl_activate_all_forms();
793 // Returns filename or string() if no valid selection was made
794 if (!isOk || !fl_get_input(pFileDlgForm->Filename)[0]) return string();
796 pszFileName = fl_get_input(pFileDlgForm->Filename);
798 if (!AbsolutePath(pszFileName)) {
799 pszFileName = AddName(fl_get_input(pFileDlgForm->DirBox),