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