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