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