]> git.lyx.org Git - lyx.git/blob - src/frontends/xforms/FormFiledialog.C
53cbf5e0420a9c613c55600b23277b09d2195ceb
[lyx.git] / src / frontends / xforms / FormFiledialog.C
1 /**
2  * \file FormFiledialog.C
3  * Copyright 2001 the LyX Team
4  * Read the file COPYING
5  *
6  * \author unknown
7  * \author John Levon
8  */
9
10 #include <config.h>
11
12 #include <unistd.h>
13 #include <cstdlib>
14 #include <pwd.h>
15 #include <grp.h>
16 //#include <cstring>
17 #include <map>
18 #include <algorithm>
19
20 using std::map;
21 using std::max;
22 using std::sort;
23
24 #include "frontends/Alert.h"
25 #include "support/FileInfo.h"
26 #include "support/lyxlib.h"
27 #include "support/lstrings.h"
28 #include "gettext.h"
29 #include "frontends/Dialogs.h"
30
31 #ifdef HAVE_ERRNO_H
32 #include <cerrno>
33 #endif
34
35 #if HAVE_DIRENT_H
36 # include <dirent.h>
37 # define NAMLEN(dirent) strlen((dirent)->d_name)
38 #else
39 # define dirent direct
40 # define NAMLEN(dirent) (dirent)->d_namlen
41 # if HAVE_SYS_NDIR_H
42 #  include <sys/ndir.h>
43 # endif
44 # if HAVE_SYS_DIR_H
45 #  include <sys/dir.h>
46 # endif
47 # if HAVE_NDIR_H
48 #  include <ndir.h>
49 # endif
50 #endif
51
52 #if TIME_WITH_SYS_TIME
53 # include <sys/time.h>
54 # include <ctime>
55 #else
56 # if HAVE_SYS_TIME_H
57 #  include <sys/time.h>
58 # else
59 #  include <ctime>
60 # endif
61 #endif
62
63 // FIXME: should be autoconfiscated
64 #ifdef BROKEN_HEADERS
65 extern "C" int gettimeofday(struct timeval *, struct timezone *);
66 #endif
67
68 #ifdef __GNUG__
69 #pragma implementation
70 #endif
71
72 #include "support/filetools.h"
73 #include "FormFiledialog.h"
74
75 namespace {
76
77 // six months, in seconds
78 long const SIX_MONTH_SEC = 6L * 30L * 24L * 60L * 60L;
79 //static
80 long const ONE_HOUR_SEC = 60L * 60L;
81
82 extern "C" {
83         
84         static
85         int C_LyXFileDlg_CancelCB(FL_FORM *fl, void *xev)
86         {
87                 return FileDialog::Private::CancelCB(fl, xev);
88         }
89         
90         static
91         void C_LyXFileDlg_DoubleClickCB(FL_OBJECT * ob, long data)
92         {
93                 FileDialog::Private::DoubleClickCB(ob, data);
94         }
95
96         static
97         void C_LyXFileDlg_FileDlgCB(FL_OBJECT * ob, long data)
98         {
99                 FileDialog::Private::FileDlgCB(ob, data);
100         }
101
102 }
103
104 } // namespace anon
105
106
107 // *** User cache class implementation
108 /// User cache class definition
109 class UserCache {
110 public:
111         /// seeks user name from group ID
112         string const & find(uid_t ID) const {
113                 Users::const_iterator cit = users.find(ID);
114                 if (cit == users.end()) {
115                         add(ID);
116                         return users[ID];
117                 }
118                 return cit->second;
119         }
120 private:
121         ///
122         void add(uid_t ID) const;
123         ///
124         typedef map<uid_t, string> Users;
125         ///
126         mutable Users users;
127 };
128
129
130 void UserCache::add(uid_t ID) const
131 {
132         string pszNewName;
133         struct passwd * pEntry;
134         
135         // gets user name
136         if ((pEntry = getpwuid(ID)))
137                 pszNewName = pEntry->pw_name;
138         else {
139                 pszNewName = tostr(ID);
140         }
141         
142         // adds new node
143         users[ID] = pszNewName;
144 }       
145
146
147 /// Group cache class definition
148 class GroupCache {
149 public:
150         /// seeks group name from group ID
151         string const & find(gid_t ID) const ;
152 private:
153         ///
154         void add(gid_t ID) const;
155         ///
156         typedef map<gid_t, string> Groups;
157         ///
158         mutable Groups groups;
159 };
160
161
162 string const & GroupCache::find(gid_t ID) const
163 {
164         Groups::const_iterator cit = groups.find(ID);
165         if (cit == groups.end()) {
166                 add(ID);
167                 return groups[ID];
168         }
169         return cit->second;
170 }
171
172
173 void GroupCache::add(gid_t ID) const
174 {
175         string pszNewName;
176         struct group * pEntry;
177         
178         // gets user name
179         if ((pEntry = getgrgid(ID))) pszNewName = pEntry->gr_name;
180         else {
181                 pszNewName = tostr(ID);
182         }
183         // adds new node
184         groups[ID] = pszNewName;
185 }
186
187
188 namespace {
189
190 // local instances
191 UserCache lyxUserCache;
192 GroupCache lyxGroupCache;
193
194 } // namespace anon
195
196
197 // compares two LyXDirEntry objects content (used for sort)
198 class comp_direntry {
199 public:
200         int operator()(DirEntry const & r1,
201                        DirEntry const & r2) const ;
202 };
203         int comp_direntry::operator()(DirEntry const & r1,
204                        DirEntry const & r2) const {
205                 bool r1d = suffixIs(r1.pszName, '/');
206                 bool r2d = suffixIs(r2.pszName, '/');
207                 if (r1d && !r2d) return 1;
208                 if (!r1d && r2d) return 0;
209                 return r1.pszName < r2.pszName;
210         }
211
212
213 // *** FileDialog::Private class implementation
214
215 // static members
216 FD_form_filedialog * FileDialog::Private::pFileDlgForm = 0;
217 FileDialog::Private * FileDialog::Private::pCurrentDlg = 0;
218
219
220 // Reread: updates dialog list to match class directory
221 void FileDialog::Private::Reread()
222 {
223         // Opens directory
224         DIR * pDirectory = ::opendir(pszDirectory.c_str());
225         if (!pDirectory) {
226                 Alert::err_alert(_("Warning! Couldn't open directory."),
227                              pszDirectory);
228                 pszDirectory = lyx::getcwd();
229                 pDirectory = ::opendir(pszDirectory.c_str());
230         }
231
232         // Clear the present namelist
233         direntries.clear();
234
235         // Updates display
236         fl_hide_object(pFileDlgForm->List);
237         fl_clear_browser(pFileDlgForm->List);
238         fl_set_input(pFileDlgForm->DirBox, pszDirectory.c_str());
239
240         // Splits complete directory name into directories and compute depth
241         iDepth = 0;
242         string line, Temp;
243         char szMode[15];
244         string File = pszDirectory;
245         if (File != "/") {
246                 File = split(File, Temp, '/');
247         }
248         while (!File.empty() || !Temp.empty()) {
249                 string dline = "@b"+line + Temp + '/';          
250                 fl_add_browser_line(pFileDlgForm->List, dline.c_str());
251                 File = split(File, Temp, '/');
252                 line += ' ';
253                 ++iDepth;
254         }
255
256         // Parses all entries of the given subdirectory
257         time_t curTime = time(0);
258         rewinddir(pDirectory);
259         struct dirent * pDirEntry;
260         while ((pDirEntry = readdir(pDirectory))) {
261                 bool isLink = false, isDir = false;
262
263                 // If the pattern doesn't start with a dot, skip hidden files
264                 if (!pszMask.empty() && pszMask[0] != '.' &&
265                     pDirEntry->d_name[0] == '.')
266                         continue;
267
268                 // Gets filename
269                 string fname = pDirEntry->d_name;
270
271                 // Under all circumstances, "." and ".." are not wanted
272                 if (fname == "." || fname == "..")
273                         continue;
274
275                 // gets file status
276                 File = AddName(pszDirectory, fname);
277
278                 // FIXME: we don't get this file exists/stattable
279                 FileInfo fileInfo(File, true);
280                 fileInfo.modeString(szMode);
281                 unsigned int nlink = fileInfo.getNumberOfLinks();
282                 string user =   lyxUserCache.find(fileInfo.getUid());
283                 string group = lyxGroupCache.find(fileInfo.getGid());
284
285                 time_t modtime = fileInfo.getModificationTime();
286                 string Time = ctime(&modtime);
287                 
288                 if (curTime > modtime + SIX_MONTH_SEC
289                     || curTime < modtime + ONE_HOUR_SEC) {
290                         // The file is fairly old or in the future. POSIX says
291                         // the cutoff is 6 months old. Allow a 1 hour slop
292                         // factor for what is considered "the future", to
293                         // allow for NFS server/client clock disagreement.
294                         // Show the year instead of the time of day.
295                         Time.erase(10, 9);
296                         Time.erase(15, string::npos);
297                 } else {
298                         Time.erase(16, string::npos);
299                 }
300
301                 string Buffer = string(szMode) + ' ' +
302                         tostr(nlink) + ' ' +
303                         user + ' ' +
304                         group + ' ' +
305                         Time.substr(4, string::npos) + ' ';
306
307                 Buffer += pDirEntry->d_name;
308                 Buffer += fileInfo.typeIndicator();
309
310                 if ((isLink = fileInfo.isLink())) {
311                         string Link;
312
313                         if (LyXReadLink(File, Link)) {
314                                 Buffer += " -> ";
315                                 Buffer += Link;
316
317                                 // This gives the FileType of the file that
318                                 // is really pointed too after resolving all
319                                 // symlinks. This is not necessarily the same
320                                 // as the type of Link (which could again be a
321                                 // link). Is that intended?
322                                 //                              JV 199902
323                                 fileInfo.newFile(File);
324                                 Buffer += fileInfo.typeIndicator();
325                         }
326                 }
327
328                 // filters files according to pattern and type
329                 if (fileInfo.isRegular()
330                     || fileInfo.isChar()
331                     || fileInfo.isBlock()
332                     || fileInfo.isFifo()) {
333                         if (!regexMatch(fname, pszMask))
334                                 continue;
335                 } else if (!(isDir = fileInfo.isDir()))
336                         continue;
337
338                 DirEntry tmp;
339
340                 // Note pszLsEntry is an string!
341                 tmp.pszLsEntry = Buffer;
342                 // creates used name
343                 string temp = fname;
344                 if (isDir) temp += '/';
345
346                 tmp.pszName = temp;
347                 // creates displayed name
348                 temp = pDirEntry->d_name;
349                 if (isLink)
350                         temp += '@';
351                 else
352                         temp += fileInfo.typeIndicator();
353                 tmp.pszDisplayed = temp;
354
355                 direntries.push_back(tmp);
356         }
357
358         closedir(pDirectory);
359
360         // Sort the names
361         sort(direntries.begin(), direntries.end(), comp_direntry());
362         
363         // Add them to directory box
364         for (DirEntries::const_iterator cit = direntries.begin();
365              cit != direntries.end(); ++cit) {
366                 string const temp = line + cit->pszDisplayed;
367                 fl_add_browser_line(pFileDlgForm->List, temp.c_str());
368         }
369         fl_set_browser_topline(pFileDlgForm->List, iDepth);
370         fl_show_object(pFileDlgForm->List);
371         iLastSel = -1;
372 }
373
374
375 // SetDirectory: sets dialog current directory
376 void FileDialog::Private::SetDirectory(string const & Path)
377 {
378         
379         string tmp;
380
381         if (Path.empty()) 
382                 tmp = lyx::getcwd();
383         else
384                 tmp = MakeAbsPath(ExpandPath(Path), pszDirectory);
385  
386         // must check the directory exists
387         DIR * pDirectory = ::opendir(tmp.c_str());
388         if (!pDirectory) {
389                 Alert::err_alert(_("Warning! Couldn't open directory."), tmp);
390         } else {
391                 ::closedir(pDirectory);
392                 pszDirectory = tmp;
393         }
394 }
395
396
397 // SetMask: sets dialog file mask
398 void FileDialog::Private::SetMask(string const & NewMask)
399 {
400         pszMask = NewMask;
401         fl_set_input(pFileDlgForm->PatBox, pszMask.c_str());
402 }
403
404
405 // SetInfoLine: sets dialog information line
406 void FileDialog::Private::SetInfoLine(string const & Line)
407 {
408         pszInfoLine = Line;
409         fl_set_object_label(pFileDlgForm->FileInfo, pszInfoLine.c_str());
410 }
411
412
413 FileDialog::Private::Private()
414 {
415         pszDirectory = MakeAbsPath(string("."));
416         pszMask = '*';
417
418         // Creates form if necessary.
419         if (!pFileDlgForm) {
420                 pFileDlgForm = build_filedialog();
421                 // Set callbacks. This means that we don't need a patch file
422                 fl_set_object_callback(pFileDlgForm->DirBox,
423                                        C_LyXFileDlg_FileDlgCB, 0);
424                 fl_set_object_callback(pFileDlgForm->PatBox,
425                                        C_LyXFileDlg_FileDlgCB, 1);
426                 fl_set_object_callback(pFileDlgForm->List,
427                                        C_LyXFileDlg_FileDlgCB, 2);
428                 fl_set_object_callback(pFileDlgForm->Filename,
429                                        C_LyXFileDlg_FileDlgCB, 3);
430                 fl_set_object_callback(pFileDlgForm->Rescan,
431                                        C_LyXFileDlg_FileDlgCB, 10);
432                 fl_set_object_callback(pFileDlgForm->Home,
433                                        C_LyXFileDlg_FileDlgCB, 11);
434                 fl_set_object_callback(pFileDlgForm->User1,
435                                        C_LyXFileDlg_FileDlgCB, 12);
436                 fl_set_object_callback(pFileDlgForm->User2,
437                                        C_LyXFileDlg_FileDlgCB, 13);
438                 
439                 // Make sure pressing the close box doesn't crash LyX. (RvdK)
440                 fl_set_form_atclose(pFileDlgForm->form,
441                                     C_LyXFileDlg_CancelCB, 0);
442                 // Register doubleclick callback
443                 fl_set_browser_dblclick_callback(pFileDlgForm->List,
444                                                  C_LyXFileDlg_DoubleClickCB,
445                                                  0);
446         }
447         fl_hide_object(pFileDlgForm->User1);
448         fl_hide_object(pFileDlgForm->User2);
449
450         r_ = Dialogs::redrawGUI.connect(SigC::slot(this, &FileDialog::Private::redraw));
451 }
452
453
454 FileDialog::Private::~Private()
455 {
456         r_.disconnect();
457 }
458
459
460 void FileDialog::Private::redraw()
461 {
462         if (pFileDlgForm->form && pFileDlgForm->form->visible)
463                 fl_redraw_form(pFileDlgForm->form);
464 }
465
466
467 // SetButton: sets file selector user button action
468 void FileDialog::Private::SetButton(int iIndex, string const & pszName,
469                            string const & pszPath)
470 {
471         FL_OBJECT * pObject;
472         string * pTemp;
473
474         if (iIndex == 0) {
475                 pObject = pFileDlgForm->User1;
476                 pTemp = &pszUserPath1;
477         } else if (iIndex == 1) {                       
478                 pObject = pFileDlgForm->User2;
479                 pTemp = &pszUserPath2;
480         } else return;
481
482         if (!pszName.empty()) {
483                 fl_set_object_label(pObject, pszName.c_str());
484                 fl_show_object(pObject);
485                 *pTemp = pszPath;
486         } else {
487                 fl_hide_object(pObject);
488                 pTemp->erase();
489         }
490 }
491
492
493 // GetDirectory: gets last dialog directory
494 string const FileDialog::Private::GetDirectory() const
495 {
496         if (!pszDirectory.empty())
497                 return pszDirectory;
498         else
499                 return string(".");
500 }
501
502
503 // RunDialog: handle dialog during file selection
504 bool FileDialog::Private::RunDialog()
505 {
506         force_cancel = false;
507         force_ok = false;
508         
509         // event loop
510         while (true) {
511                 FL_OBJECT * pObject = fl_do_forms();
512
513                 if (pObject == pFileDlgForm->Ready) {
514                         if (HandleOK())
515                                 return true;
516                 } else if (pObject == pFileDlgForm->Cancel
517                            || force_cancel)
518                         return false;
519                 else if (force_ok)
520                         return true;
521         }
522 }
523
524
525 // XForms objects callback (static)
526 void FileDialog::Private::FileDlgCB(FL_OBJECT *, long lArgument)
527 {
528         if (!pCurrentDlg) return;
529
530         switch (lArgument) {
531
532         case 0: // get directory
533                 pCurrentDlg->SetDirectory(fl_get_input(pFileDlgForm->DirBox));
534                 pCurrentDlg->Reread();
535                 break;
536
537         case 1: // get mask
538                 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm->PatBox));
539                 pCurrentDlg->Reread();
540                 break;
541
542         case 2: // list
543                 pCurrentDlg->HandleListHit();
544                 break;  
545
546         case 10: // rescan
547                 pCurrentDlg->SetDirectory(fl_get_input(pFileDlgForm->DirBox));
548                 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm->PatBox));
549                 pCurrentDlg->Reread();
550                 break;
551
552         case 11: // home
553                 pCurrentDlg->SetDirectory(GetEnvPath("HOME"));
554                 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm->PatBox));
555                 pCurrentDlg->Reread();
556                 break;
557
558         case 12: // user button 1
559                 pCurrentDlg->SetDirectory(pCurrentDlg->pszUserPath1);
560                 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm
561                                                   ->PatBox));
562                 pCurrentDlg->Reread();
563                 break;
564
565         case 13: // user button 2
566                 pCurrentDlg->SetDirectory(pCurrentDlg->pszUserPath2);
567                 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm
568                                                   ->PatBox));
569                 pCurrentDlg->Reread();
570                 break;
571
572         }
573 }
574
575
576 // Handle callback from list
577 void FileDialog::Private::HandleListHit()
578 {
579         // set info line
580         int const iSelect = fl_get_browser(pFileDlgForm->List);
581         if (iSelect > iDepth)  {
582                 SetInfoLine(direntries[iSelect - iDepth - 1].pszLsEntry);
583         } else {
584                 SetInfoLine(string());
585         }
586 }
587
588
589 // Callback for double click in list
590 void FileDialog::Private::DoubleClickCB(FL_OBJECT *, long)
591 {
592         if (pCurrentDlg->HandleDoubleClick())
593                 // Simulate click on OK button
594                 pCurrentDlg->Force(false);
595 }
596
597
598 // Handle double click from list
599 bool FileDialog::Private::HandleDoubleClick()
600 {
601         string pszTemp;
602
603         // set info line
604         bool isDir = true;
605         int const iSelect = fl_get_browser(pFileDlgForm->List);
606         if (iSelect > iDepth)  {
607                 pszTemp = direntries[iSelect - iDepth - 1].pszName;
608                 SetInfoLine(direntries[iSelect - iDepth - 1].pszLsEntry);
609                 if (!suffixIs(pszTemp, '/')) {
610                         isDir = false;
611                         fl_set_input(pFileDlgForm->Filename, pszTemp.c_str());
612                 }
613         } else if (iSelect != 0) {
614                 SetInfoLine(string());
615         } else
616                 return true;
617
618         // executes action
619         if (isDir) {
620                 string Temp;
621
622                 // builds new directory name
623                 if (iSelect > iDepth) {
624                         // Directory deeper down
625                         // First, get directory with trailing /
626                         Temp = fl_get_input(pFileDlgForm->DirBox);
627                         if (!suffixIs(Temp, '/'))
628                                 Temp += '/';
629                         Temp += pszTemp;
630                 } else {
631                         // Directory higher up
632                         Temp.erase();
633                         for (int i = 0; i < iSelect; ++i) {
634                                 string piece = fl_get_browser_line(pFileDlgForm->List, i+1);
635                                 // The '+2' is here to count the '@b' (JMarc)
636                                 Temp += piece.substr(i + 2);
637                         }
638                 }
639
640                 // assigns it
641                 SetDirectory(Temp);
642                 Reread();
643                 return false;
644         }
645         return true;
646 }
647
648
649 // Handle OK button call
650 bool FileDialog::Private::HandleOK()
651 {
652         // mask was changed
653         string pszTemp = fl_get_input(pFileDlgForm->PatBox);
654         if (pszTemp != pszMask) {
655                 SetMask(pszTemp);
656                 Reread();
657                 return false;
658         }
659
660         // directory was changed
661         pszTemp = fl_get_input(pFileDlgForm->DirBox);
662         if (pszTemp!= pszDirectory) {
663                 SetDirectory(pszTemp);
664                 Reread();
665                 return false;
666         }
667         
668         // Handle return from list
669         int const select = fl_get_browser(pFileDlgForm->List);
670         if (select > iDepth) {
671                 string const temp = direntries[select - iDepth - 1].pszName;
672                 if (!suffixIs(temp, '/')) {
673                         // If user didn't type anything, use browser
674                         string const name =
675                                 fl_get_input(pFileDlgForm->Filename);
676                         if (name.empty()) {
677                                 fl_set_input(pFileDlgForm->Filename, temp.c_str());
678                         }
679                         return true;
680                 }
681         }
682
683         // Emulate a doubleclick
684         return HandleDoubleClick();
685 }
686
687
688 // Handle Cancel CB from WM close
689 int FileDialog::Private::CancelCB(FL_FORM *, void *)
690 {
691         // Simulate a click on the cancel button
692         pCurrentDlg->Force(true);
693         return FL_IGNORE;
694 }
695
696
697 // Simulates a click on OK/Cancel
698 void FileDialog::Private::Force(bool cancel)
699 {
700         if (cancel) {
701                 force_cancel = true;
702                 fl_set_button(pFileDlgForm->Cancel, 1);
703         } else {
704                 force_ok = true;
705                 fl_set_button(pFileDlgForm->Ready, 1);
706         }
707         // Start timer to break fl_do_forms loop soon
708         fl_set_timer(pFileDlgForm->timer, 0.1);
709 }
710
711
712 // Select: launches dialog and returns selected file
713 string const FileDialog::Private::Select(string const & title,
714                                          string const & path,
715                                          string const & mask,
716                                          string const & suggested)
717 {
718         // handles new mask and path
719         bool isOk = true;
720         if (!mask.empty()) {
721                 SetMask(mask);
722                 isOk = false;
723         }
724         if (!path.empty()) {
725                 SetDirectory(path);
726                 isOk = false;
727         }
728         if (!isOk) Reread();
729
730         // highlight the suggested file in the browser, if it exists.
731         int sel = 0;
732         string const filename = OnlyFilename(suggested);
733         if (!filename.empty()) {
734                 for (int i = 0;
735                      i < fl_get_browser_maxline(pFileDlgForm->List); ++i) {
736                         string s =
737                                 fl_get_browser_line(pFileDlgForm->List, i + 1);
738                         s = strip(frontStrip(s));
739                         if (s == filename) {
740                                 sel = i + 1;
741                                 break;
742                         }
743                 }
744         }
745         
746         if (sel != 0) fl_select_browser_line(pFileDlgForm->List, sel);
747         int const top = max(sel - 5, 1);
748         fl_set_browser_topline(pFileDlgForm->List, top);
749
750         // checks whether dialog can be started
751         if (pCurrentDlg) return string();
752         pCurrentDlg = this;
753
754         // runs dialog
755         SetInfoLine(string());
756         fl_set_input(pFileDlgForm->Filename, suggested.c_str());
757         fl_set_button(pFileDlgForm->Cancel, 0);
758         fl_set_button(pFileDlgForm->Ready, 0);
759         fl_set_focus_object(pFileDlgForm->form, pFileDlgForm->Filename);
760         fl_deactivate_all_forms();
761         fl_show_form(pFileDlgForm->form,
762                      FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
763                      title.c_str());
764
765         isOk = RunDialog();
766         
767         fl_hide_form(pFileDlgForm->form);
768         fl_activate_all_forms();
769         pCurrentDlg = 0;
770
771         // Returns filename or string() if no valid selection was made
772         if (!isOk || !fl_get_input(pFileDlgForm->Filename)[0]) return string();
773
774         pszFileName = fl_get_input(pFileDlgForm->Filename);
775
776         if (!AbsolutePath(pszFileName)) {
777                 pszFileName = AddName(fl_get_input(pFileDlgForm->DirBox),
778                                       pszFileName);
779         }
780         return pszFileName;
781 }