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