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