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