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