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