]> git.lyx.org Git - features.git/blob - src/filedlg.C
clear()->erase() ; lots of using directives for cxx
[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-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 extern "C" void C_LyXFileDlg_FileDlgCB(FL_OBJECT * ob, long data) 
517 {
518         LyXFileDlg::FileDlgCB(ob, data);
519 }
520
521
522 // Handle callback from list
523 void LyXFileDlg::HandleListHit()
524 {
525         // set info line
526         int iSelect = fl_get_browser(pFileDlgForm->List);
527         if (iSelect > iDepth)  {
528                 SetInfoLine(direntries[iSelect - iDepth - 1].pszLsEntry);
529         } else {
530                 SetInfoLine(string());
531         }
532 }
533
534
535 // Callback for double click in list
536 void LyXFileDlg::DoubleClickCB(FL_OBJECT *, long)
537 {
538         if (pCurrentDlg->HandleDoubleClick())
539                 // Simulate click on OK button
540                 pCurrentDlg->Force(false);
541 }
542
543 extern "C" void C_LyXFileDlg_DoubleClickCB(FL_OBJECT * ob, long data)
544 {
545         LyXFileDlg::DoubleClickCB(ob, data);
546 }
547
548 // Handle double click from list
549 bool LyXFileDlg::HandleDoubleClick()
550 {
551         string pszTemp;
552
553         // set info line
554         bool isDir = true;
555         int iSelect = fl_get_browser(pFileDlgForm->List);
556         if (iSelect > iDepth)  {
557                 pszTemp = direntries[iSelect - iDepth - 1].pszName;
558                 SetInfoLine(direntries[iSelect - iDepth - 1].pszLsEntry);
559                 if (!suffixIs(pszTemp, '/')) {
560                         isDir = false;
561                         fl_set_input(pFileDlgForm->Filename, pszTemp.c_str());
562                 }
563         } else if (iSelect != 0) {
564                 SetInfoLine(string());
565         } else
566                 return true;
567
568         // executes action
569         if (isDir) {
570                 string Temp;
571
572                 // builds new directory name
573                 if (iSelect > iDepth) {
574                         // Directory deeper down
575                         // First, get directory with trailing /
576                         Temp = fl_get_input(pFileDlgForm->DirBox);
577                         if (!suffixIs(Temp, '/'))
578                                 Temp += '/';
579                         Temp += pszTemp;
580                 } else {
581                         // Directory higher up
582                         Temp.erase();
583                         for (int i = 0; i < iSelect; ++i) {
584                                 string piece = fl_get_browser_line(pFileDlgForm->List, i+1);
585                                 // The '+2' is here to count the '@b' (JMarc)
586                                 Temp += piece.substr(i + 2);
587                         }
588                 }
589
590                 // assigns it
591                 SetDirectory(Temp);
592                 Reread();
593                 return false;
594         }
595         return true;
596 }
597
598
599 // Handle OK button call
600 bool LyXFileDlg::HandleOK()
601 {
602         // mask was changed
603         string pszTemp = fl_get_input(pFileDlgForm->PatBox);
604         if (pszTemp!= pszMask) {
605                 SetMask(pszTemp);
606                 Reread();
607                 return false;
608         }
609
610         // directory was changed
611         pszTemp = fl_get_input(pFileDlgForm->DirBox);
612         if (pszTemp!= pszDirectory) {
613                 SetDirectory(pszTemp);
614                 Reread();
615                 return false;
616         }
617         
618         // Handle return from list
619         int select = fl_get_browser(pFileDlgForm->List);
620         if (select > iDepth) {
621                 string temp = direntries[select - iDepth - 1].pszName;
622                 if (!suffixIs(temp, '/')) {
623                         // If user didn't type anything, use browser
624                         string name = fl_get_input(pFileDlgForm->Filename);
625                         if (name.empty()) {
626                                 fl_set_input(pFileDlgForm->Filename, temp.c_str());
627                         }
628                         return true;
629                 }
630         }
631         
632         // Emulate a doubleclick
633         return HandleDoubleClick();
634 }
635
636
637 // Handle Cancel CB from WM close
638 int LyXFileDlg::CancelCB(FL_FORM *, void *)
639 {
640         // Simulate a click on the cancel button
641         pCurrentDlg->Force(true);
642         return FL_IGNORE;
643 }
644
645
646 extern "C" int C_LyXFileDlg_CancelCB(FL_FORM *fl, void *xev)
647 {
648         return LyXFileDlg::CancelCB(fl, xev);
649 }
650
651
652 // Simulates a click on OK/Cancel
653 void LyXFileDlg::Force(bool cancel)
654 {
655         if (cancel) {
656                 force_cancel = true;
657                 fl_set_button(pFileDlgForm->Cancel, 1);
658         } else {
659                 force_ok = true;
660                 fl_set_button(pFileDlgForm->Ready, 1);
661         }
662         // Start timer to break fl_do_forms loop soon
663         fl_set_timer(pFileDlgForm->timer, 0.1);
664 }
665
666
667 // Select: launches dialog and returns selected file
668 string LyXFileDlg::Select(string const & title, string const & path, 
669                           string const & mask, string const & suggested)
670 {
671         // handles new mask and path
672         bool isOk = true;
673         if (!mask.empty()) {
674                 SetMask(mask);
675                 isOk = false;
676         }
677         if (!path.empty()) {
678                 SetDirectory(path);
679                 isOk = false;
680         }
681         if (!isOk) Reread();
682         else {
683                 fl_select_browser_line(pFileDlgForm->List, 1);
684                 fl_set_browser_topline(pFileDlgForm->List, 1);
685         }
686
687         // checks whether dialog can be started
688         if (pCurrentDlg) return string();
689         pCurrentDlg = this;
690
691         // runs dialog
692         SetInfoLine (string());
693         fl_set_input(pFileDlgForm->Filename, suggested.c_str());
694         fl_set_button(pFileDlgForm->Cancel, 0);
695         fl_set_button(pFileDlgForm->Ready, 0);
696         fl_set_focus_object(pFileDlgForm->FileDlg, pFileDlgForm->Filename);
697         fl_deactivate_all_forms();
698         fl_show_form(pFileDlgForm->FileDlg, FL_PLACE_MOUSE | FL_FREE_SIZE,
699                      FL_FULLBORDER, title.c_str());
700
701         isOk = RunDialog();
702
703         fl_hide_form(pFileDlgForm->FileDlg);
704         fl_activate_all_forms();
705         pCurrentDlg = 0;
706
707         // Returns filename or string() if no valid selection was made
708         if (!isOk || !fl_get_input(pFileDlgForm->Filename)[0]) return string();
709
710         pszFileName = fl_get_input(pFileDlgForm->Filename);
711
712         if (!AbsolutePath(pszFileName)) {
713                 pszFileName = AddName(fl_get_input(pFileDlgForm->DirBox), 
714                                       pszFileName);
715         }
716         return pszFileName;
717 }