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