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