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