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