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