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 "xforms_helpers.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"
80 // six months, in seconds
81 long const SIX_MONTH_SEC = 6L * 30L * 24L * 60L * 60L;
83 long const ONE_HOUR_SEC = 60L * 60L;
88 int C_LyXFileDlg_CancelCB(FL_FORM *fl, void *xev)
90 return FileDialog::Private::CancelCB(fl, xev);
94 void C_LyXFileDlg_DoubleClickCB(FL_OBJECT * ob, long data)
96 FileDialog::Private::DoubleClickCB(ob, data);
100 void C_LyXFileDlg_FileDlgCB(FL_OBJECT * ob, long data)
102 FileDialog::Private::FileDlgCB(ob, data);
110 // *** User cache class implementation
111 /// User cache class definition
114 /// seeks user name from group ID
115 string const & find(uid_t ID) const {
116 Users::const_iterator cit = users.find(ID);
117 if (cit == users.end()) {
125 void add(uid_t ID) const;
127 typedef map<uid_t, string> Users;
133 void UserCache::add(uid_t ID) const
136 struct passwd * pEntry;
139 if ((pEntry = getpwuid(ID)))
140 pszNewName = pEntry->pw_name;
142 pszNewName = tostr(ID);
146 users[ID] = pszNewName;
150 /// Group cache class definition
153 /// seeks group name from group ID
154 string const & find(gid_t ID) const ;
157 void add(gid_t ID) const;
159 typedef map<gid_t, string> Groups;
161 mutable Groups groups;
165 string const & GroupCache::find(gid_t ID) const
167 Groups::const_iterator cit = groups.find(ID);
168 if (cit == groups.end()) {
176 void GroupCache::add(gid_t ID) const
179 struct group * pEntry;
182 if ((pEntry = getgrgid(ID))) pszNewName = pEntry->gr_name;
184 pszNewName = tostr(ID);
187 groups[ID] = pszNewName;
194 UserCache lyxUserCache;
195 GroupCache lyxGroupCache;
200 // compares two LyXDirEntry objects content (used for sort)
201 class comp_direntry {
203 int operator()(DirEntry const & r1,
204 DirEntry const & r2) const ;
206 int comp_direntry::operator()(DirEntry const & r1,
207 DirEntry const & r2) const {
208 bool r1d = suffixIs(r1.pszName, '/');
209 bool r2d = suffixIs(r2.pszName, '/');
210 if (r1d && !r2d) return 1;
211 if (!r1d && r2d) return 0;
212 return r1.pszName < r2.pszName;
216 // *** FileDialog::Private class implementation
219 FD_form_filedialog * FileDialog::Private::pFileDlgForm = 0;
220 FileDialog::Private * FileDialog::Private::pCurrentDlg = 0;
223 // Reread: updates dialog list to match class directory
224 void FileDialog::Private::Reread()
227 DIR * pDirectory = ::opendir(pszDirectory.c_str());
229 Alert::err_alert(_("Warning! Couldn't open directory."),
231 pszDirectory = lyx::getcwd();
232 pDirectory = ::opendir(pszDirectory.c_str());
235 // Clear the present namelist
239 fl_hide_object(pFileDlgForm->List);
240 fl_clear_browser(pFileDlgForm->List);
241 fl_set_input(pFileDlgForm->DirBox, pszDirectory.c_str());
243 // Splits complete directory name into directories and compute depth
247 string File = pszDirectory;
249 File = split(File, Temp, '/');
251 while (!File.empty() || !Temp.empty()) {
252 string dline = "@b"+line + Temp + '/';
253 fl_add_browser_line(pFileDlgForm->List, dline.c_str());
254 File = split(File, Temp, '/');
259 // Parses all entries of the given subdirectory
260 time_t curTime = time(0);
261 rewinddir(pDirectory);
262 struct dirent * pDirEntry;
263 while ((pDirEntry = readdir(pDirectory))) {
264 bool isLink = false, isDir = false;
266 // If the pattern doesn't start with a dot, skip hidden files
267 if (!pszMask.empty() && pszMask[0] != '.' &&
268 pDirEntry->d_name[0] == '.')
272 string fname = pDirEntry->d_name;
274 // Under all circumstances, "." and ".." are not wanted
275 if (fname == "." || fname == "..")
279 File = AddName(pszDirectory, fname);
281 FileInfo fileInfo(File, true);
283 // can this really happen?
284 if (!fileInfo.isOK())
287 fileInfo.modeString(szMode);
288 unsigned int nlink = fileInfo.getNumberOfLinks();
289 string user = lyxUserCache.find(fileInfo.getUid());
290 string group = lyxGroupCache.find(fileInfo.getGid());
292 time_t modtime = fileInfo.getModificationTime();
293 string Time = ctime(&modtime);
295 if (curTime > modtime + SIX_MONTH_SEC
296 || curTime < modtime + ONE_HOUR_SEC) {
297 // The file is fairly old or in the future. POSIX says
298 // the cutoff is 6 months old. Allow a 1 hour slop
299 // factor for what is considered "the future", to
300 // allow for NFS server/client clock disagreement.
301 // Show the year instead of the time of day.
303 Time.erase(15, string::npos);
305 Time.erase(16, string::npos);
308 string Buffer = string(szMode) + ' ' +
312 Time.substr(4, string::npos) + ' ';
314 Buffer += pDirEntry->d_name;
315 Buffer += fileInfo.typeIndicator();
317 if ((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 (!regexMatch(fname, pszMask))
345 } else if (!(isDir = fileInfo.isDir()))
350 // Note pszLsEntry is an string!
351 tmp.pszLsEntry = Buffer;
354 if (isDir) temp += '/';
357 // creates displayed name
358 temp = pDirEntry->d_name;
362 temp += fileInfo.typeIndicator();
363 tmp.pszDisplayed = temp;
365 direntries.push_back(tmp);
368 closedir(pDirectory);
371 sort(direntries.begin(), direntries.end(), comp_direntry());
373 // Add them to directory box
374 for (DirEntries::const_iterator cit = direntries.begin();
375 cit != direntries.end(); ++cit) {
376 string const temp = line + cit->pszDisplayed;
377 fl_add_browser_line(pFileDlgForm->List, temp.c_str());
379 fl_set_browser_topline(pFileDlgForm->List, iDepth);
380 fl_show_object(pFileDlgForm->List);
385 // SetDirectory: sets dialog current directory
386 void FileDialog::Private::SetDirectory(string const & Path)
394 tmp = MakeAbsPath(ExpandPath(Path), pszDirectory);
396 // must check the directory exists
397 DIR * pDirectory = ::opendir(tmp.c_str());
399 Alert::err_alert(_("Warning! Couldn't open directory."), tmp);
401 ::closedir(pDirectory);
407 // SetMask: sets dialog file mask
408 void FileDialog::Private::SetMask(string const & NewMask)
411 fl_set_input(pFileDlgForm->PatBox, pszMask.c_str());
415 // SetInfoLine: sets dialog information line
416 void FileDialog::Private::SetInfoLine(string const & Line)
419 fl_set_object_label(pFileDlgForm->FileInfo, pszInfoLine.c_str());
423 FileDialog::Private::Private()
425 pszDirectory = MakeAbsPath(string("."));
428 // Creates form if necessary.
430 pFileDlgForm = build_filedialog();
431 // Set callbacks. This means that we don't need a patch file
432 fl_set_object_callback(pFileDlgForm->DirBox,
433 C_LyXFileDlg_FileDlgCB, 0);
434 fl_set_object_callback(pFileDlgForm->PatBox,
435 C_LyXFileDlg_FileDlgCB, 1);
436 fl_set_object_callback(pFileDlgForm->List,
437 C_LyXFileDlg_FileDlgCB, 2);
438 fl_set_object_callback(pFileDlgForm->Filename,
439 C_LyXFileDlg_FileDlgCB, 3);
440 fl_set_object_callback(pFileDlgForm->Rescan,
441 C_LyXFileDlg_FileDlgCB, 10);
442 fl_set_object_callback(pFileDlgForm->Home,
443 C_LyXFileDlg_FileDlgCB, 11);
444 fl_set_object_callback(pFileDlgForm->User1,
445 C_LyXFileDlg_FileDlgCB, 12);
446 fl_set_object_callback(pFileDlgForm->User2,
447 C_LyXFileDlg_FileDlgCB, 13);
449 // Make sure pressing the close box doesn't crash LyX. (RvdK)
450 fl_set_form_atclose(pFileDlgForm->form,
451 C_LyXFileDlg_CancelCB, 0);
452 // Register doubleclick callback
453 fl_set_browser_dblclick_callback(pFileDlgForm->List,
454 C_LyXFileDlg_DoubleClickCB,
457 fl_hide_object(pFileDlgForm->User1);
458 fl_hide_object(pFileDlgForm->User2);
460 r_ = Dialogs::redrawGUI.connect(boost::bind(&FileDialog::Private::redraw, this));
464 FileDialog::Private::~Private()
470 void FileDialog::Private::redraw()
472 if (pFileDlgForm->form && pFileDlgForm->form->visible)
473 fl_redraw_form(pFileDlgForm->form);
477 // SetButton: sets file selector user button action
478 void FileDialog::Private::SetButton(int iIndex, string const & pszName,
479 string const & pszPath)
485 pObject = pFileDlgForm->User1;
486 pTemp = &pszUserPath1;
487 } else if (iIndex == 1) {
488 pObject = pFileDlgForm->User2;
489 pTemp = &pszUserPath2;
492 if (!pszName.empty()) {
493 fl_set_object_label(pObject, idex(pszName.c_str()));
494 fl_set_button_shortcut(pObject, scex(pszName.c_str()), 1);
495 fl_show_object(pObject);
498 fl_hide_object(pObject);
504 // GetDirectory: gets last dialog directory
505 string const FileDialog::Private::GetDirectory() const
507 if (!pszDirectory.empty())
514 bool x_sync_kludge(bool ret)
516 XSync(fl_get_display(), false);
521 // RunDialog: handle dialog during file selection
522 bool FileDialog::Private::RunDialog()
524 force_cancel = false;
529 FL_OBJECT * pObject = fl_do_forms();
531 if (pObject == pFileDlgForm->Ready) {
533 return x_sync_kludge(true);
535 } else if (pObject == pFileDlgForm->Cancel
537 return x_sync_kludge(false);
540 return x_sync_kludge(true);
545 // XForms objects callback (static)
546 void FileDialog::Private::FileDlgCB(FL_OBJECT *, long lArgument)
548 if (!pCurrentDlg) return;
552 case 0: // get directory
553 pCurrentDlg->SetDirectory(fl_get_input(pFileDlgForm->DirBox));
554 pCurrentDlg->Reread();
558 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm->PatBox));
559 pCurrentDlg->Reread();
563 pCurrentDlg->HandleListHit();
567 pCurrentDlg->SetDirectory(fl_get_input(pFileDlgForm->DirBox));
568 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm->PatBox));
569 pCurrentDlg->Reread();
573 pCurrentDlg->SetDirectory(GetEnvPath("HOME"));
574 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm->PatBox));
575 pCurrentDlg->Reread();
578 case 12: // user button 1
579 pCurrentDlg->SetDirectory(pCurrentDlg->pszUserPath1);
580 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm
582 pCurrentDlg->Reread();
585 case 13: // user button 2
586 pCurrentDlg->SetDirectory(pCurrentDlg->pszUserPath2);
587 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm
589 pCurrentDlg->Reread();
596 // Handle callback from list
597 void FileDialog::Private::HandleListHit()
600 int const iSelect = fl_get_browser(pFileDlgForm->List);
601 if (iSelect > iDepth) {
602 SetInfoLine(direntries[iSelect - iDepth - 1].pszLsEntry);
604 SetInfoLine(string());
609 // Callback for double click in list
610 void FileDialog::Private::DoubleClickCB(FL_OBJECT *, long)
612 if (pCurrentDlg->HandleDoubleClick())
613 // Simulate click on OK button
614 pCurrentDlg->Force(false);
618 // Handle double click from list
619 bool FileDialog::Private::HandleDoubleClick()
625 int const iSelect = fl_get_browser(pFileDlgForm->List);
626 if (iSelect > iDepth) {
627 pszTemp = direntries[iSelect - iDepth - 1].pszName;
628 SetInfoLine(direntries[iSelect - iDepth - 1].pszLsEntry);
629 if (!suffixIs(pszTemp, '/')) {
631 fl_set_input(pFileDlgForm->Filename, pszTemp.c_str());
633 } else if (iSelect != 0) {
634 SetInfoLine(string());
642 // builds new directory name
643 if (iSelect > iDepth) {
644 // Directory deeper down
645 // First, get directory with trailing /
646 Temp = fl_get_input(pFileDlgForm->DirBox);
647 if (!suffixIs(Temp, '/'))
651 // Directory higher up
653 for (int i = 0; i < iSelect; ++i) {
654 string piece = fl_get_browser_line(pFileDlgForm->List, i+1);
655 // The '+2' is here to count the '@b' (JMarc)
656 Temp += piece.substr(i + 2);
669 // Handle OK button call
670 bool FileDialog::Private::HandleOK()
673 string pszTemp = fl_get_input(pFileDlgForm->PatBox);
674 if (pszTemp != pszMask) {
680 // directory was changed
681 pszTemp = fl_get_input(pFileDlgForm->DirBox);
682 if (pszTemp!= pszDirectory) {
683 SetDirectory(pszTemp);
688 // Handle return from list
689 int const select = fl_get_browser(pFileDlgForm->List);
690 if (select > iDepth) {
691 string const temp = direntries[select - iDepth - 1].pszName;
692 if (!suffixIs(temp, '/')) {
693 // If user didn't type anything, use browser
695 fl_get_input(pFileDlgForm->Filename);
697 fl_set_input(pFileDlgForm->Filename, temp.c_str());
703 // Emulate a doubleclick
704 return HandleDoubleClick();
708 // Handle Cancel CB from WM close
709 int FileDialog::Private::CancelCB(FL_FORM *, void *)
711 // Simulate a click on the cancel button
712 pCurrentDlg->Force(true);
717 // Simulates a click on OK/Cancel
718 void FileDialog::Private::Force(bool cancel)
722 fl_set_button(pFileDlgForm->Cancel, 1);
725 fl_set_button(pFileDlgForm->Ready, 1);
727 // Start timer to break fl_do_forms loop soon
728 fl_set_timer(pFileDlgForm->timer, 0.1);
732 // Select: launches dialog and returns selected file
733 string const FileDialog::Private::Select(string const & title,
736 string const & suggested)
738 // handles new mask and path
750 // highlight the suggested file in the browser, if it exists.
752 string const filename = OnlyFilename(suggested);
753 if (!filename.empty()) {
755 i < fl_get_browser_maxline(pFileDlgForm->List); ++i) {
757 fl_get_browser_line(pFileDlgForm->List, i + 1);
758 s = strip(frontStrip(s));
766 if (sel != 0) fl_select_browser_line(pFileDlgForm->List, sel);
767 int const top = max(sel - 5, 1);
768 fl_set_browser_topline(pFileDlgForm->List, top);
770 // checks whether dialog can be started
771 if (pCurrentDlg) return string();
775 SetInfoLine(string());
776 fl_set_input(pFileDlgForm->Filename, suggested.c_str());
777 fl_set_button(pFileDlgForm->Cancel, 0);
778 fl_set_button(pFileDlgForm->Ready, 0);
779 fl_set_focus_object(pFileDlgForm->form, pFileDlgForm->Filename);
780 fl_deactivate_all_forms();
781 fl_show_form(pFileDlgForm->form,
782 FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
787 fl_hide_form(pFileDlgForm->form);
788 fl_activate_all_forms();
791 // Returns filename or string() if no valid selection was made
792 if (!isOk || !fl_get_input(pFileDlgForm->Filename)[0]) return string();
794 pszFileName = fl_get_input(pFileDlgForm->Filename);
796 if (!AbsolutePath(pszFileName)) {
797 pszFileName = AddName(fl_get_input(pFileDlgForm->DirBox),