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