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