]> git.lyx.org Git - lyx.git/blob - src/frontends/xforms/FormFiledialog.C
* disable loading of xpm files by the xforms image loader.
[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 int FileDialog::Private::minw_ = 0;
184 int FileDialog::Private::minh_ = 0;
185
186
187 // Reread: updates dialog list to match class directory
188 void FileDialog::Private::Reread()
189 {
190         // Opens directory
191         DIR * dir = ::opendir(directory_.c_str());
192         if (!dir) {
193                 Alert::err_alert(_("Warning! Couldn't open directory."),
194                         directory_);
195                 directory_ = lyx::getcwd();
196                 dir = ::opendir(directory_.c_str());
197         }
198
199         // Clear the present namelist
200         dir_entries_.clear();
201
202         // Updates display
203         fl_hide_object(file_dlg_form_->List);
204         fl_clear_browser(file_dlg_form_->List);
205         fl_set_input(file_dlg_form_->DirBox, directory_.c_str());
206
207         // Splits complete directory name into directories and compute depth
208         depth_ = 0;
209         string line, Temp;
210         string mode;
211         string File = directory_;
212         if (File != "/") {
213                 File = split(File, Temp, '/');
214         }
215         while (!File.empty() || !Temp.empty()) {
216                 string dline = "@b" + line + Temp + '/';
217                 fl_add_browser_line(file_dlg_form_->List, dline.c_str());
218                 File = split(File, Temp, '/');
219                 line += ' ';
220                 ++depth_;
221         }
222
223         // Parses all entries of the given subdirectory
224         time_t curTime = time(0);
225         rewinddir(dir);
226         while (dirent * entry = readdir(dir)) {
227                 bool isLink = false, isDir = false;
228
229                 // If the pattern doesn't start with a dot, skip hidden files
230                 if (!mask_.empty() && mask_[0] != '.' &&
231                     entry->d_name[0] == '.')
232                         continue;
233
234                 // Gets filename
235                 string fname = entry->d_name;
236
237                 // Under all circumstances, "." and ".." are not wanted
238                 if (fname == "." || fname == "..")
239                         continue;
240
241                 // gets file status
242                 File = AddName(directory_, fname);
243
244                 FileInfo fileInfo(File, true);
245
246                 // can this really happen?
247                 if (!fileInfo.isOK())
248                         continue;
249
250                 mode = fileInfo.modeString();
251                 unsigned int const nlink = fileInfo.getNumberOfLinks();
252                 string const user  = lyxUserCache.find(fileInfo.getUid());
253                 string const group = lyxGroupCache.find(fileInfo.getGid());
254
255                 time_t modtime = fileInfo.getModificationTime();
256                 string Time = ctime(&modtime);
257
258                 if (curTime > modtime + SIX_MONTH_SEC
259                     || curTime < modtime + ONE_HOUR_SEC) {
260                         // The file is fairly old or in the future. POSIX says
261                         // the cutoff is 6 months old. Allow a 1 hour slop
262                         // factor for what is considered "the future", to
263                         // allow for NFS server/client clock disagreement.
264                         // Show the year instead of the time of day.
265                         Time.erase(10, 9);
266                         Time.erase(15, string::npos);
267                 } else {
268                         Time.erase(16, string::npos);
269                 }
270
271                 string buffer = mode + ' ' +
272                         tostr(nlink) + ' ' +
273                         user + ' ' +
274                         group + ' ' +
275                         Time.substr(4, string::npos) + ' ';
276
277                 buffer += entry->d_name;
278                 buffer += fileInfo.typeIndicator();
279
280                 isLink = fileInfo.isLink();
281                 if (isLink) {
282                         string Link;
283
284                         if (LyXReadLink(File, Link)) {
285                                 buffer += " -> ";
286                                 buffer += Link;
287
288                                 // This gives the FileType of the file that
289                                 // is really pointed too after resolving all
290                                 // symlinks. This is not necessarily the same
291                                 // as the type of Link (which could again be a
292                                 // link). Is that intended?
293                                 //                              JV 199902
294                                 fileInfo.newFile(File);
295                                 if (fileInfo.isOK())
296                                         buffer += fileInfo.typeIndicator();
297                                 else
298                                         continue;
299                         }
300                 }
301
302                 // filters files according to pattern and type
303                 if (fileInfo.isRegular()
304                     || fileInfo.isChar()
305                     || fileInfo.isBlock()
306                     || fileInfo.isFifo()) {
307                         if (!regexMatch(fname, mask_))
308                                 continue;
309                 } else if (!(isDir = fileInfo.isDir()))
310                         continue;
311
312                 DirEntry tmp;
313
314                 // Note ls_entry_ is an string!
315                 tmp.ls_entry_ = buffer;
316                 // creates used name
317                 string temp = fname;
318                 if (isDir)
319                         temp += '/';
320
321                 tmp.name_ = temp;
322                 // creates displayed name
323                 temp = entry->d_name;
324                 if (isLink)
325                         temp += '@';
326                 else
327                         temp += fileInfo.typeIndicator();
328                 tmp.displayed_ = temp;
329
330                 dir_entries_.push_back(tmp);
331         }
332
333         closedir(dir);
334
335         // Sort the names
336         sort(dir_entries_.begin(), dir_entries_.end(), comp_direntry());
337
338         // Add them to directory box
339         for (DirEntries::const_iterator cit = dir_entries_.begin();
340              cit != dir_entries_.end(); ++cit) {
341                 string const temp = line + cit->displayed_;
342                 fl_add_browser_line(file_dlg_form_->List, temp.c_str());
343         }
344         fl_set_browser_topline(file_dlg_form_->List, depth_);
345         fl_show_object(file_dlg_form_->List);
346         last_sel_ = -1;
347 }
348
349
350 // SetDirectory: sets dialog current directory
351 void FileDialog::Private::SetDirectory(string const & path)
352 {
353         string tmp;
354         if (path.empty())
355                 tmp = lyx::getcwd();
356         else
357                 tmp = MakeAbsPath(ExpandPath(path), directory_);
358
359         // must check the directory exists
360         DIR * dir = ::opendir(tmp.c_str());
361         if (!dir) {
362                 Alert::err_alert(_("Warning! Couldn't open directory."), tmp);
363         } else {
364                 ::closedir(dir);
365                 directory_ = tmp;
366         }
367 }
368
369
370 // SetMask: sets dialog file mask
371 void FileDialog::Private::SetMask(string const & newmask)
372 {
373         mask_ = newmask;
374         fl_set_input(file_dlg_form_->PatBox, mask_.c_str());
375 }
376
377
378 // SetInfoLine: sets dialog information line
379 void FileDialog::Private::SetInfoLine(string const & line)
380 {
381         info_line_ = line;
382         fl_set_object_label(file_dlg_form_->FileInfo, info_line_.c_str());
383 }
384
385
386 FileDialog::Private::Private(Dialogs & dia)
387 {
388         directory_ = MakeAbsPath(string("."));
389         mask_ = '*';
390
391         // Creates form if necessary.
392         if (!file_dlg_form_) {
393                 file_dlg_form_ = build_filedialog(this);
394                 minw_ = file_dlg_form_->form->w;
395                 minh_ = file_dlg_form_->form->h;
396                 // Set callbacks. This means that we don't need a patch file
397                 fl_set_object_callback(file_dlg_form_->DirBox,
398                                        C_LyXFileDlg_FileDlgCB, 0);
399                 fl_set_object_callback(file_dlg_form_->PatBox,
400                                        C_LyXFileDlg_FileDlgCB, 1);
401                 fl_set_object_callback(file_dlg_form_->List,
402                                        C_LyXFileDlg_FileDlgCB, 2);
403                 fl_set_object_callback(file_dlg_form_->Filename,
404                                        C_LyXFileDlg_FileDlgCB, 3);
405                 fl_set_object_callback(file_dlg_form_->Rescan,
406                                        C_LyXFileDlg_FileDlgCB, 10);
407                 fl_set_object_callback(file_dlg_form_->Home,
408                                        C_LyXFileDlg_FileDlgCB, 11);
409                 fl_set_object_callback(file_dlg_form_->User1,
410                                        C_LyXFileDlg_FileDlgCB, 12);
411                 fl_set_object_callback(file_dlg_form_->User2,
412                                        C_LyXFileDlg_FileDlgCB, 13);
413
414                 // Make sure pressing the close box doesn't crash LyX. (RvdK)
415                 fl_set_form_atclose(file_dlg_form_->form,
416                                     C_LyXFileDlg_CancelCB, 0);
417                 // Register doubleclick callback
418                 fl_set_browser_dblclick_callback(file_dlg_form_->List,
419                                                  C_LyXFileDlg_DoubleClickCB,
420                                                  0);
421         }
422         fl_hide_object(file_dlg_form_->User1);
423         fl_hide_object(file_dlg_form_->User2);
424
425         r_ = dia.redrawGUI().connect(boost::bind(&FileDialog::Private::redraw, this));
426 }
427
428
429 FileDialog::Private::~Private()
430 {
431         r_.disconnect();
432 }
433
434
435 void FileDialog::Private::redraw()
436 {
437         if (file_dlg_form_->form && file_dlg_form_->form->visible)
438                 fl_redraw_form(file_dlg_form_->form);
439 }
440
441
442 // SetButton: sets file selector user button action
443 void FileDialog::Private::SetButton(int index, string const & name,
444                            string const & path)
445 {
446         FL_OBJECT * ob;
447         string * tmp;
448
449         if (index == 0) {
450                 ob = file_dlg_form_->User1;
451                 tmp = &user_path1_;
452         } else if (index == 1) {
453                 ob = file_dlg_form_->User2;
454                 tmp = &user_path2_;
455         } else {
456                 return;
457         }
458
459         if (!name.empty()) {
460                 fl_set_object_label(ob, idex(name).c_str());
461                 fl_set_button_shortcut(ob, scex(name).c_str(), 1);
462                 fl_show_object(ob);
463                 *tmp = path;
464         } else {
465                 fl_hide_object(ob);
466                 tmp->erase();
467         }
468 }
469
470
471 // GetDirectory: gets last dialog directory
472 string const FileDialog::Private::GetDirectory() const
473 {
474         if (!directory_.empty())
475                 return directory_;
476         else
477                 return string(".");
478 }
479
480 namespace {
481         bool x_sync_kludge(bool ret)
482         {
483                 XSync(fl_get_display(), false);
484                 return ret;
485         }
486 } // namespace anon
487
488 // RunDialog: handle dialog during file selection
489 bool FileDialog::Private::RunDialog()
490 {
491         force_cancel_ = false;
492         force_ok_ = false;
493
494         // event loop
495         while (true) {
496                 FL_OBJECT * ob = fl_do_forms();
497
498                 if (ob == file_dlg_form_->Ready) {
499                         if (HandleOK())
500                                 return x_sync_kludge(true);
501
502                 } else if (ob == file_dlg_form_->Cancel || force_cancel_)
503                         return x_sync_kludge(false);
504
505                 else if (force_ok_)
506                         return x_sync_kludge(true);
507         }
508 }
509
510
511 // XForms objects callback (static)
512 void FileDialog::Private::FileDlgCB(FL_OBJECT *, long arg)
513 {
514         if (!current_dlg_)
515                 return;
516
517         switch (arg) {
518
519         case 0: // get directory
520                 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
521                 current_dlg_->Reread();
522                 break;
523
524         case 1: // get mask
525                 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
526                 current_dlg_->Reread();
527                 break;
528
529         case 2: // list
530                 current_dlg_->HandleListHit();
531                 break;
532
533         case 10: // rescan
534                 current_dlg_->SetDirectory(fl_get_input(file_dlg_form_->DirBox));
535                 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
536                 current_dlg_->Reread();
537                 break;
538
539         case 11: // home
540                 current_dlg_->SetDirectory(GetEnvPath("HOME"));
541                 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
542                 current_dlg_->Reread();
543                 break;
544
545         case 12: // user button 1
546                 current_dlg_->SetDirectory(current_dlg_->user_path1_);
547                 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
548                 current_dlg_->Reread();
549                 break;
550
551         case 13: // user button 2
552                 current_dlg_->SetDirectory(current_dlg_->user_path2_);
553                 current_dlg_->SetMask(fl_get_input(file_dlg_form_->PatBox));
554                 current_dlg_->Reread();
555                 break;
556
557         }
558 }
559
560
561 // Handle callback from list
562 void FileDialog::Private::HandleListHit()
563 {
564         // set info line
565         int const select_ = fl_get_browser(file_dlg_form_->List);
566         if (select_ > depth_)
567                 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
568         else
569                 SetInfoLine(string());
570 }
571
572
573 // Callback for double click in list
574 void FileDialog::Private::DoubleClickCB(FL_OBJECT *, long)
575 {
576         // Simulate click on OK button
577         if (current_dlg_->HandleDoubleClick())
578                 current_dlg_->Force(false);
579 }
580
581
582 // Handle double click from list
583 bool FileDialog::Private::HandleDoubleClick()
584 {
585         string tmp;
586
587         // set info line
588         bool isDir = true;
589         int const select_ = fl_get_browser(file_dlg_form_->List);
590         if (select_ > depth_) {
591                 tmp = dir_entries_[select_ - depth_ - 1].name_;
592                 SetInfoLine(dir_entries_[select_ - depth_ - 1].ls_entry_);
593                 if (!suffixIs(tmp, '/')) {
594                         isDir = false;
595                         fl_set_input(file_dlg_form_->Filename, tmp.c_str());
596                 }
597         } else if (select_ != 0) {
598                 SetInfoLine(string());
599         } else
600                 return true;
601
602         // executes action
603         if (isDir) {
604                 string Temp;
605
606                 // builds new directory name
607                 if (select_ > depth_) {
608                         // Directory deeper down
609                         // First, get directory with trailing /
610                         Temp = fl_get_input(file_dlg_form_->DirBox);
611                         if (!suffixIs(Temp, '/'))
612                                 Temp += '/';
613                         Temp += tmp;
614                 } else {
615                         // Directory higher up
616                         Temp.erase();
617                         for (int i = 0; i < select_; ++i) {
618                                 string piece = fl_get_browser_line(file_dlg_form_->List, i+1);
619                                 // The '+2' is here to count the '@b' (JMarc)
620                                 Temp += piece.substr(i + 2);
621                         }
622                 }
623
624                 // assigns it
625                 SetDirectory(Temp);
626                 Reread();
627                 return false;
628         }
629         return true;
630 }
631
632
633 // Handle OK button call
634 bool FileDialog::Private::HandleOK()
635 {
636         // mask was changed
637         string tmp = fl_get_input(file_dlg_form_->PatBox);
638         if (tmp != mask_) {
639                 SetMask(tmp);
640                 Reread();
641                 return false;
642         }
643
644         // directory was changed
645         tmp = fl_get_input(file_dlg_form_->DirBox);
646         if (tmp != directory_) {
647                 SetDirectory(tmp);
648                 Reread();
649                 return false;
650         }
651
652         // Handle return from list
653         int const select = fl_get_browser(file_dlg_form_->List);
654         if (select > depth_) {
655                 string const temp = dir_entries_[select - depth_ - 1].name_;
656                 if (!suffixIs(temp, '/')) {
657                         // If user didn't type anything, use browser
658                         string const name = fl_get_input(file_dlg_form_->Filename);
659                         if (name.empty())
660                                 fl_set_input(file_dlg_form_->Filename, temp.c_str());
661                         return true;
662                 }
663         }
664
665         // Emulate a doubleclick
666         return HandleDoubleClick();
667 }
668
669
670 // Handle Cancel CB from WM close
671 int FileDialog::Private::CancelCB(FL_FORM *, void *)
672 {
673         // Simulate a click on the cancel button
674         current_dlg_->Force(true);
675         return FL_IGNORE;
676 }
677
678
679 // Simulates a click on OK/Cancel
680 void FileDialog::Private::Force(bool cancel)
681 {
682         if (cancel) {
683                 force_cancel_ = true;
684                 fl_set_button(file_dlg_form_->Cancel, 1);
685         } else {
686                 force_ok_ = true;
687                 fl_set_button(file_dlg_form_->Ready, 1);
688         }
689         // Start timer to break fl_do_forms loop soon
690         fl_set_timer(file_dlg_form_->timer, 0.1);
691 }
692
693
694 // Select: launches dialog and returns selected file
695 string const FileDialog::Private::Select(string const & title,
696                                          string const & path,
697                                          string const & mask,
698                                          string const & suggested)
699 {
700         // handles new mask and path
701         bool isOk = true;
702         if (!mask.empty()) {
703                 SetMask(mask);
704                 isOk = false;
705         }
706         if (!path.empty()) {
707                 SetDirectory(path);
708                 isOk = false;
709         }
710         if (!isOk)
711                 Reread();
712
713         // highlight the suggested file in the browser, if it exists.
714         int sel = 0;
715         string const filename = OnlyFilename(suggested);
716         if (!filename.empty()) {
717                 for (int i = 0; i < fl_get_browser_maxline(file_dlg_form_->List); ++i) {
718                         string s = fl_get_browser_line(file_dlg_form_->List, i + 1);
719                         s = trim(s);
720                         if (s == filename) {
721                                 sel = i + 1;
722                                 break;
723                         }
724                 }
725         }
726
727         if (sel != 0)
728                 fl_select_browser_line(file_dlg_form_->List, sel);
729         int const top = max(sel - 5, 1);
730         fl_set_browser_topline(file_dlg_form_->List, top);
731
732         // checks whether dialog can be started
733         if (current_dlg_)
734                 return string();
735         current_dlg_ = this;
736
737         // runs dialog
738         SetInfoLine(string());
739         fl_set_input(file_dlg_form_->Filename, suggested.c_str());
740         fl_set_button(file_dlg_form_->Cancel, 0);
741         fl_set_button(file_dlg_form_->Ready, 0);
742         fl_set_focus_object(file_dlg_form_->form, file_dlg_form_->Filename);
743         fl_deactivate_all_forms();
744         // Prevent xforms crashing if the dialog gets too small by preventing
745         // it from being shrunk beyond a minimum size.
746         // calls to fl_set_form_minsize/maxsize apply only to the next
747         // fl_show_form(), so this comes first.
748         fl_set_form_minsize(file_dlg_form_->form, minw_, minh_);
749
750         fl_show_form(file_dlg_form_->form,
751                      FL_PLACE_MOUSE | FL_FREE_SIZE, 0,
752                      title.c_str());
753
754         isOk = RunDialog();
755
756         fl_hide_form(file_dlg_form_->form);
757         fl_activate_all_forms();
758         current_dlg_ = 0;
759
760         // Returns filename or string() if no valid selection was made
761         if (!isOk || !fl_get_input(file_dlg_form_->Filename)[0])
762                 return string();
763
764         file_name_ = fl_get_input(file_dlg_form_->Filename);
765
766         if (!AbsolutePath(file_name_))
767                 file_name_ = AddName(fl_get_input(file_dlg_form_->DirBox), file_name_);
768         return file_name_;
769 }