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