]> git.lyx.org Git - lyx.git/blob - src/filedlg.C
Two small bugfixes for tabulars and cursor setting
[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-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 #warning fix!
300                         
301                         Time.erase(10, 9);
302                         Time.erase(15, string::npos);
303                 } else {
304                         Time.erase(16, string::npos);
305                 }
306
307                 Buffer = string(szMode) + ' ' +
308                         tostr(nlink) + ' ' +
309                         user + ' ' +
310                         group + ' ' +
311                         Time.substr(4, string::npos) + ' ';
312
313                 Buffer += pDirEntry->d_name;
314                 Buffer += fileInfo.typeIndicator();
315
316                 if ((isLink = fileInfo.isLink())) {
317                   string Link;
318
319                   if (LyXReadLink(File,Link)) {
320                        Buffer += " -> ";
321                        Buffer += Link;
322
323                        // This gives the FileType of the file that
324                        // is really pointed too after resolving all
325                        // symlinks. This is not necessarily the same
326                        // as the type of Link (which could again be a
327                        // link). Is that intended?
328                        //                              JV 199902
329                        fileInfo.newFile(File);
330                        Buffer += fileInfo.typeIndicator();
331                   }
332                 }
333
334                 // filters files according to pattern and type
335                 if (fileInfo.isRegular()
336                     || fileInfo.isChar()
337                     || fileInfo.isBlock()
338                     || fileInfo.isFifo()) {
339                         if (!regexMatch(fname, pszMask))
340                                 continue;
341                 } else if (!(isDir = fileInfo.isDir()))
342                         continue;
343
344                 // Note pszLsEntry is an string!
345                 pCurrentNames[iNumNames].pszLsEntry = Buffer;
346
347                 // creates used name
348                 string temp = fname;
349                 if (isDir) temp += '/';
350                 pCurrentNames[iNumNames].pszName = temp;
351
352                 // creates displayed name
353                 temp = pDirEntry->d_name;
354                 if (isLink)
355                         temp += '@';
356                 else
357                         temp += fileInfo.typeIndicator();
358                 
359                 pCurrentNames[iNumNames++].pszDisplayed = temp;
360         }
361
362         closedir(pDirectory);
363
364         // Sort the names
365         qsort(pCurrentNames, iNumNames, sizeof(LyXDirEntry), 
366               (int (*)(const void *, const void *))LyXDirEntry::ldeCompProc);
367
368         // Add them to directory box
369         for (i = 0; i < iNumNames; ++i) {
370                 string temp = line + pCurrentNames[i].pszDisplayed;
371                 fl_add_browser_line(pFileDlgForm->List, temp.c_str());
372         }
373         fl_set_browser_topline(pFileDlgForm->List,iDepth);
374         fl_show_object(pFileDlgForm->List);
375         iLastSel = -1;
376 }
377
378
379 // SetDirectory: sets dialog current directory
380 void LyXFileDlg::SetDirectory(string const & Path)
381 {
382         if (!pszDirectory.empty()) {
383                 string TempPath = ExpandPath(Path); // Expand ~/
384                 TempPath = MakeAbsPath(TempPath, pszDirectory);
385                 pszDirectory = MakeAbsPath(TempPath);
386         } else pszDirectory = MakeAbsPath(Path);
387 }
388
389
390 // SetMask: sets dialog file mask
391 void LyXFileDlg::SetMask(string const & NewMask)
392 {
393         pszMask = NewMask;
394         fl_set_input(pFileDlgForm->PatBox, pszMask.c_str());
395 }
396
397
398 // SetInfoLine: sets dialog information line
399 void LyXFileDlg::SetInfoLine(string const & Line)
400 {
401         pszInfoLine = Line;
402         fl_set_object_label(pFileDlgForm->FileInfo, pszInfoLine.c_str());
403 }
404
405
406 LyXFileDlg::LyXFileDlg()
407 {
408         pCurrentNames = 0;
409         pszDirectory = MakeAbsPath(string("."));
410         pszMask = '*';
411
412         // Creates form if necessary. 
413         if (!pFileDlgForm) {
414                 pFileDlgForm = create_form_FileDlg();
415                 // Set callbacks. This means that we don't need a patch file
416                 fl_set_object_callback(pFileDlgForm->DirBox,
417                                        LyXFileDlg::FileDlgCB,0);
418                 fl_set_object_callback(pFileDlgForm->PatBox,
419                                        LyXFileDlg::FileDlgCB,1);
420                 fl_set_object_callback(pFileDlgForm->List,
421                                        LyXFileDlg::FileDlgCB,2);
422                 fl_set_object_callback(pFileDlgForm->Filename,
423                                        LyXFileDlg::FileDlgCB,3);
424                 fl_set_object_callback(pFileDlgForm->Rescan,
425                                        LyXFileDlg::FileDlgCB,10);
426                 fl_set_object_callback(pFileDlgForm->Home,
427                                        LyXFileDlg::FileDlgCB,11);
428                 fl_set_object_callback(pFileDlgForm->User1,
429                                        LyXFileDlg::FileDlgCB,12);
430                 fl_set_object_callback(pFileDlgForm->User2,
431                                        LyXFileDlg::FileDlgCB,13);
432                 
433                 // Make sure pressing the close box doesn't crash LyX. (RvdK)
434                 fl_set_form_atclose(pFileDlgForm->FileDlg, CancelCB, 0);
435                 // Register doubleclick callback
436                 fl_set_browser_dblclick_callback(pFileDlgForm->List,
437                                                  DoubleClickCB,0);
438         }
439         fl_hide_object(pFileDlgForm->User1);
440         fl_hide_object(pFileDlgForm->User2);
441 }
442
443
444 LyXFileDlg::~LyXFileDlg()
445 {
446         // frees directory entries
447         if (pCurrentNames) {
448                 delete [] pCurrentNames;
449         }
450 }
451
452
453 // SetButton: sets file selector user button action
454 void LyXFileDlg::SetButton(int iIndex, string const & pszName, 
455                            string const & pszPath)
456 {
457         FL_OBJECT *pObject;
458         string *pTemp;
459
460         if (iIndex == 0) {
461                 pObject = pFileDlgForm->User1;
462                 pTemp = &pszUserPath1;
463         } else if (iIndex == 1) {                       
464                 pObject = pFileDlgForm->User2;
465                 pTemp = &pszUserPath2;
466         } else return;
467
468         if (!pszName.empty() && !pszPath.empty()) {
469                 fl_set_object_label(pObject, pszName.c_str());
470                 fl_show_object(pObject);
471                 *pTemp = pszPath;
472         } else {
473                 fl_hide_object(pObject);
474                 (*pTemp).clear();
475         }
476 }
477
478
479 // GetDirectory: gets last dialog directory
480 string LyXFileDlg::GetDirectory() 
481 {
482         if (!pszDirectory.empty())
483                 return pszDirectory;
484         else
485                 return string(".");
486 }
487
488
489 // RunDialog: handle dialog during file selection
490 bool LyXFileDlg::RunDialog()
491 {
492         force_cancel = false;
493         force_ok = false;
494         
495         // event loop
496         while(true) {
497
498                 FL_OBJECT * pObject = fl_do_forms();
499
500                 if (pObject == pFileDlgForm->Ready) {
501                         if (HandleOK())
502                                 return true;
503                 } else if (pObject == pFileDlgForm->Cancel 
504                            || force_cancel) 
505                         return false;
506                 else if (force_ok)
507                         return true;
508         }
509 }
510
511
512 // XForms objects callback (static)
513 void LyXFileDlg::FileDlgCB(FL_OBJECT *, long lArgument)
514 {
515         if (!pCurrentDlg) return;
516
517         switch (lArgument) {
518
519         case 0: // get directory
520                 pCurrentDlg->SetDirectory(fl_get_input(pFileDlgForm->DirBox));
521                 pCurrentDlg->Reread();
522                 break;
523
524         case 1: // get mask
525                 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm->PatBox));
526                 pCurrentDlg->Reread();
527                 break;
528
529         case 2: // list
530                 pCurrentDlg->HandleListHit();
531                 break;  
532
533         case 10: // rescan
534                 pCurrentDlg->SetDirectory(fl_get_input(pFileDlgForm->DirBox));
535                 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm->PatBox));
536                 pCurrentDlg->Reread();
537                 break;
538
539         case 11: // home
540                 pCurrentDlg->SetDirectory(GetEnvPath("HOME"));
541                 pCurrentDlg->SetMask(fl_get_input(pFileDlgForm->PatBox));
542                 pCurrentDlg->Reread();
543                 break;
544
545         case 12: // user button 1
546                 if (!pCurrentDlg->pszUserPath1.empty()) {
547                         pCurrentDlg->SetDirectory(pCurrentDlg->pszUserPath1);
548                         pCurrentDlg->SetMask(fl_get_input(pFileDlgForm->PatBox));
549                         pCurrentDlg->Reread();
550                 }
551                 break;
552
553         case 13: // user button 2
554                 if (!pCurrentDlg->pszUserPath2.empty()) {
555                         pCurrentDlg->SetDirectory(pCurrentDlg->pszUserPath2);
556                         pCurrentDlg->SetMask(fl_get_input(pFileDlgForm->PatBox));
557                         pCurrentDlg->Reread();
558                 }
559                 break;
560
561         }
562 }
563
564
565 // Handle callback from list
566 void LyXFileDlg::HandleListHit()
567 {
568         // set info line
569         int iSelect = fl_get_browser(pFileDlgForm->List);
570         if (iSelect > iDepth)  {
571                 SetInfoLine(pCurrentNames[iSelect - iDepth - 1].pszLsEntry);
572         } else {
573                 SetInfoLine(string());
574         }
575 }
576
577
578 // Callback for double click in list
579 void LyXFileDlg::DoubleClickCB(FL_OBJECT *, long)
580 {
581         if (pCurrentDlg->HandleDoubleClick())
582                 // Simulate click on OK button
583                 pCurrentDlg->Force(false);
584 }
585
586
587 // Handle double click from list
588 bool LyXFileDlg::HandleDoubleClick()
589 {
590         bool isDir;
591         string pszTemp;
592         int iSelect;  
593
594         // set info line
595         isDir = true;
596         iSelect = fl_get_browser(pFileDlgForm->List);
597         if (iSelect > iDepth)  {
598                 pszTemp = pCurrentNames[iSelect - iDepth - 1].pszName;
599                 SetInfoLine(pCurrentNames[iSelect - iDepth - 1].pszLsEntry);
600                 if (!suffixIs(pszTemp, '/')) {
601                         isDir = false;
602                         fl_set_input(pFileDlgForm->Filename, pszTemp.c_str());
603                 }
604         } else if (iSelect !=0) {
605                 SetInfoLine(string());
606         } else
607                 return true;
608
609         // executes action
610         if (isDir) {
611
612                 int i;
613                 string Temp;
614
615                 // builds new directory name
616                 if (iSelect > iDepth) {
617                         // Directory deeper down
618                         // First, get directory with trailing /
619                         Temp = fl_get_input(pFileDlgForm->DirBox);
620                         if (!suffixIs(Temp, '/'))
621                                 Temp += '/';
622                         Temp += pszTemp;
623                 } else {
624                         // Directory higher up
625                         Temp.clear();
626                         for (i = 0; i < iSelect; ++i) {
627                                 string piece = fl_get_browser_line(pFileDlgForm->List, i+1);
628                                 // The '+2' is here to count the '@b' (JMarc)
629                                 Temp += piece.substr(i + 2);
630                         }
631                 }
632
633                 // assigns it
634                 SetDirectory(Temp);
635                 Reread();
636                 return false;
637         }
638         return true;
639 }
640
641
642 // Handle OK button call
643 bool LyXFileDlg::HandleOK()
644 {
645         string pszTemp;
646
647         // mask was changed
648         pszTemp = fl_get_input(pFileDlgForm->PatBox);
649         if (pszTemp!=pszMask) {
650                 SetMask(pszTemp);
651                 Reread();
652                 return false;
653         }
654
655         // directory was changed
656         pszTemp = fl_get_input(pFileDlgForm->DirBox);
657         if (pszTemp!=pszDirectory) {
658                 SetDirectory(pszTemp);
659                 Reread();
660                 return false;
661         }
662         
663         // Handle return from list
664         int select = fl_get_browser(pFileDlgForm->List);
665         if (select > iDepth) {
666                 string temp = pCurrentNames[select - iDepth - 1].pszName;
667                 if (!suffixIs(temp, '/')) {
668                         // If user didn't type anything, use browser
669                         string name = fl_get_input(pFileDlgForm->Filename);
670                         if (name.empty()) {
671                                 fl_set_input(pFileDlgForm->Filename, temp.c_str());
672                         }
673                         return true;
674                 }
675         }
676         
677         // Emulate a doubleclick
678         return HandleDoubleClick();
679 }
680
681
682 // Handle Cancel CB from WM close
683 int LyXFileDlg::CancelCB(FL_FORM *, void *)
684 {
685         // Simulate a click on the cancel button
686         pCurrentDlg->Force(true);
687         return FL_IGNORE;
688 }
689
690
691 // Simulates a click on OK/Cancel
692 void LyXFileDlg::Force(bool cancel)
693 {
694         if (cancel) {
695                 force_cancel = true;
696                 fl_set_button(pFileDlgForm->Cancel, 1);
697         } else {
698                 force_ok = true;
699                 fl_set_button(pFileDlgForm->Ready, 1);
700         }
701         // Start timer to break fl_do_forms loop soon
702         fl_set_timer(pFileDlgForm->timer, 0.1);
703 }
704
705
706 // Select: launches dialog and returns selected file
707 string LyXFileDlg::Select(string const & title, string const & path, 
708                            string const & mask, string const & suggested)
709 {
710         bool isOk;
711
712         // handles new mask and path
713         isOk = true;
714         if (!mask.empty()) {
715                 SetMask(mask);
716                 isOk = false;
717         }
718         if (!path.empty()) {
719                 SetDirectory(path);
720                 isOk = false;
721         }
722         if (!isOk) Reread();
723         else {
724                 fl_select_browser_line(pFileDlgForm->List, 1);
725                 fl_set_browser_topline(pFileDlgForm->List, 1);
726         }
727
728         // checks whether dialog can be started
729         if (pCurrentDlg) return string();
730         pCurrentDlg = this;
731
732         // runs dialog
733         SetInfoLine (string());
734         fl_set_input(pFileDlgForm->Filename, suggested.c_str());
735         fl_set_button(pFileDlgForm->Cancel, 0);
736         fl_set_button(pFileDlgForm->Ready, 0);
737         fl_set_focus_object(pFileDlgForm->FileDlg, pFileDlgForm->Filename);
738         fl_deactivate_all_forms();
739         fl_show_form(pFileDlgForm->FileDlg, FL_PLACE_MOUSE | FL_FREE_SIZE,
740                      FL_FULLBORDER, title.c_str());
741
742         isOk = RunDialog();
743
744         fl_hide_form(pFileDlgForm->FileDlg);
745         fl_activate_all_forms();
746         pCurrentDlg = 0;
747
748         // Returns filename or string() if no valid selection was made
749         if (!isOk || !fl_get_input(pFileDlgForm->Filename)[0]) return string();
750
751         pszFileName = fl_get_input(pFileDlgForm->Filename);
752
753         if (!AbsolutePath(pszFileName)) {
754                 pszFileName = AddName(fl_get_input(pFileDlgForm->DirBox), 
755                                       pszFileName);
756         }
757         return pszFileName;
758 }