]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiLyXFiles.cpp
Get rid of Qt4 code in src/
[lyx.git] / src / frontends / qt / GuiLyXFiles.cpp
1 /**
2  * \file GuiLyXFiles.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Spitzmüller
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "GuiLyXFiles.h"
14 #include "GuiApplication.h"
15 #include "qt_helpers.h"
16
17 #include "FileDialog.h"
18 #include "FuncRequest.h"
19 #include "Language.h"
20 #include "LyXRC.h"
21
22 #include "support/environment.h"
23 #include "support/gettext.h"
24 #include "support/lstrings.h"
25 #include "support/Messages.h"
26 #include "support/qstring_helpers.h"
27 #include "support/Package.h"
28
29 #include <QVector>
30 #include <QDirIterator>
31 #include <QTreeWidget>
32
33 using namespace std;
34 using namespace lyx::support;
35
36 namespace lyx {
37 namespace frontend {
38
39 namespace {
40
41 QString const guiString(QString const & in)
42 {
43         // recode specially encoded chars in file names (URL encoding and underbar)
44         return QString::fromUtf8(QByteArray::fromPercentEncoding(in.toUtf8())).replace('_', ' ');
45 }
46
47 } // namespace anon
48
49
50 QMap<QString, QString> GuiLyXFiles::getFiles()
51 {
52         QMap<QString, QString> result;
53         // We look for lyx files in the subdirectory dir of
54         //   1) user_lyxdir
55         //   2) build_lyxdir (if not empty)
56         //   3) system_lyxdir
57         // in this order. Files with a given sub-hierarchy will
58         // only be listed once.
59         // We also consider i18n subdirectories and store them separately.
60         QStringList dirs;
61         QStringList relpaths;
62
63         // The three locations to look at.
64         string const user = addPath(package().user_support().absFileName(), fromqstr(type_));
65         string const build = addPath(package().build_support().absFileName(), fromqstr(type_));
66         string const system = addPath(package().system_support().absFileName(), fromqstr(type_));
67
68         available_languages_.insert(toqstr("en"), qt_("English"));
69
70         QString const type = fileTypeCO->itemData(fileTypeCO->currentIndex()).toString();
71
72         // Search in the base paths
73         if (type == "all" || type == "user")
74                 dirs << toqstr(user);
75         if (type == "all" || type == "system")
76                 dirs << toqstr(build)
77                      << toqstr(system);
78
79         for (int i = 0; i < dirs.size(); ++i) {
80                 QString const & dir = dirs.at(i);
81                 QDirIterator it(dir, QDir::Files, QDirIterator::Subdirectories);
82                 while (it.hasNext()) {
83                         QString fn(QFile(it.next()).fileName());
84                         if (!fn.endsWith(getSuffix()))
85                                 continue;
86                         QString relpath = toqstr(makeRelPath(qstring_to_ucs4(fn),
87                                                              qstring_to_ucs4(dir)));
88                         // <cat>/
89                         int s = relpath.indexOf('/', 0);
90                         QString cat = qt_("General");
91                         QString localization = "en";
92                         if (s != -1) {
93                                 // <cat>/<subcat>/
94                                 cat = relpath.left(s);
95                                 if (all_languages_.contains(cat)
96                                     && !all_languages_.contains(dir.right(dir.lastIndexOf('/')))) {
97                                         QMap<QString, QString>::const_iterator li = all_languages_.find(cat);
98                                         // Skip i18n dir, but add language to the combo
99                                         if (!available_languages_.contains(li.key()))
100                                                 available_languages_.insert(li.key(), li.value());
101                                         localization = cat;
102                                         int sc = relpath.indexOf('/', s + 1);
103                                         cat = (sc == -1) ? qt_("General") : relpath.mid(s + 1, sc - s - 1);
104                                         s = sc;
105                                 }
106                                 if (s != -1) {
107                                         int sc = relpath.indexOf('/', s + 1);
108                                         QString const subcat = (sc == -1) ?
109                                                                 QString() : relpath.mid(s + 1, sc - s - 1);
110                                         if (!subcat.isEmpty())
111                                                 cat += '/' + subcat;
112                                 }
113                         }
114                         if (!relpaths.contains(relpath)) {
115                                 relpaths.append(relpath);
116                                 if (localization != "en")
117                                         // strip off lang/
118                                         relpath = relpath.mid(relpath.indexOf('/') + 1);
119                                 result.insert(relpath, cat);
120                                                                         
121                                 QMap<QString, QString> lm;
122                                 if (localizations_.contains(relpath))
123                                         lm = localizations_.find(relpath).value();
124                                 lm.insert(localization, fn);
125                                 localizations_.insert(relpath, lm);
126                         }
127                 }
128         }
129         // Find and store GUI language
130         for (auto const & l : guilangs_) {
131                 // First try with the full name
132                 // `en' files are not in a subdirectory
133                 if (available_languages_.contains(toqstr(l))) {
134                         guilang_ = toqstr(l);
135                         break;
136                 }
137                 // Then the name without country code
138                 string const shortl = token(l, '_', 0);
139                 if (available_languages_.contains(toqstr(shortl))) {
140                         guilang_ = toqstr(shortl);
141                         break;
142                 }
143         }
144         // pre-fill the language combo (it will be updated once an item 
145         // has been clicked)
146         languageCO->clear();
147         QMap<QString, QString>::const_iterator i =available_languages_.constBegin();
148         while (i != available_languages_.constEnd()) {
149                 languageCO->addItem(i.value(), i.key());
150                 ++i;
151         }
152         setLanguage();
153         return result;
154 }
155
156
157 GuiLyXFiles::GuiLyXFiles(GuiView & lv)
158         : GuiDialog(lv, "lyxfiles", qt_("New File From Template"))
159 {
160         setupUi(this);
161
162         // Get all supported languages (by code) in order to exclude those
163         // dirs later.
164         QAbstractItemModel * language_model = guiApp->languageModel();
165         language_model->sort(0);
166         for (int i = 0; i != language_model->rowCount(); ++i) {
167                 QModelIndex index = language_model->index(i, 0);
168                 Language const * lang =
169                         languages.getLanguage(fromqstr(index.data(Qt::UserRole).toString()));
170                 if (!lang)
171                         continue;
172                 QString const code = toqstr(lang->code());
173                 if (!all_languages_.contains(code))
174                         all_languages_.insert(code, qt_(lang->display()));
175                 // Also store code without country code
176                 QString const shortcode = code.left(code.indexOf('_'));
177                 if (shortcode != code && !all_languages_.contains(shortcode))
178                         all_languages_.insert(shortcode, qt_(lang->display()));
179         }
180         // Get GUI language
181         string lang = getGuiMessages().language();
182         string const language = getEnv("LANGUAGE");
183         if (!language.empty())
184                 lang += ":" + language;
185         guilangs_ =  getVectorFromString(lang, ":");
186
187         // The filter bar
188         filter_ = new FancyLineEdit(this);
189         filter_->setClearButton(true);
190         filter_->setPlaceholderText(qt_("All available files"));
191         filter_->setToolTip(qt_("Enter string to filter the list of available files"));
192         connect(filter_, &FancyLineEdit::downPressed,
193                 filesLW, [this](){ focusAndHighlight(filesLW); });
194
195         filterBarL->addWidget(filter_, 0);
196         findKeysLA->setBuddy(filter_);
197
198         connect(buttonBox, SIGNAL(clicked(QAbstractButton *)),
199                 this, SLOT(slotButtonBox(QAbstractButton *)));
200
201         connect(filesLW, SIGNAL(itemClicked(QTreeWidgetItem *, int)),
202                 this, SLOT(fileSelectionChanged()));
203         connect(filesLW, SIGNAL(itemSelectionChanged()),
204                 this, SLOT(fileSelectionChanged()));
205         connect(filter_, SIGNAL(textEdited(QString)),
206                 this, SLOT(filterLabels()));
207         connect(filter_, SIGNAL(rightButtonClicked()),
208                 this, SLOT(resetFilter()));
209
210         bc().setPolicy(ButtonPolicy::OkApplyCancelPolicy);
211         bc().setOK(buttonBox->button(QDialogButtonBox::Open));
212         bc().setCancel(buttonBox->button(QDialogButtonBox::Cancel));
213
214         //filesLW->setViewMode(QListView::ListMode);
215         filesLW->setIconSize(QSize(22, 22));
216
217         QIcon user_icon(getPixmap("images/", "lyxfiles-user", "svgz,png"));
218         QIcon system_icon(getPixmap("images/", "lyxfiles-system", "svgz,png"));
219         fileTypeCO->addItem(qt_("User and System Files"), toqstr("all"));
220         fileTypeCO->addItem(user_icon, qt_("User Files Only"), toqstr("user"));
221         fileTypeCO->addItem(system_icon, qt_("System Files Only"), toqstr("system"));
222
223         setFocusProxy(filter_);
224 }
225
226
227 QString const GuiLyXFiles::getSuffix()
228 {
229         if (type_ == "bind" || type_ == "ui")
230                 return toqstr(".") + type_;
231         else if (type_ == "kbd")
232                 return ".kmap";
233         
234         return ".lyx";
235 }
236
237
238 bool GuiLyXFiles::translateName() const
239 {
240         return (type_ == "templates" || type_ == "examples");
241 }
242
243
244 void GuiLyXFiles::fileSelectionChanged()
245 {
246         if (!filesLW->currentItem()
247             || !filesLW->currentItem()->data(0, Qt::UserRole).toString().endsWith(getSuffix())) {
248                 // not a file (probably a header)
249                 bc().setValid(false);
250                 return;
251         }
252         changed();
253 }
254
255
256 void GuiLyXFiles::on_fileTypeCO_activated(int)
257 {
258         updateContents();
259 }
260
261
262 void GuiLyXFiles::on_languageCO_activated(int i)
263 {
264         savelang_ = languageCO->itemData(i).toString();
265         if (!filesLW->currentItem())
266                 return;
267
268         filesLW->currentItem()->setData(0, Qt::ToolTipRole, getRealPath());
269         changed();
270 }
271
272
273 void GuiLyXFiles::on_filesLW_itemDoubleClicked(QTreeWidgetItem * item, int)
274 {
275         if (!item || !item->data(0, Qt::UserRole).toString().endsWith(getSuffix())) {
276                 // not a file (probably a header)
277                 bc().setValid(false);
278                 return;
279         }
280
281         applyView();
282         dispatchParams();
283         close();
284 }
285
286 void GuiLyXFiles::on_filesLW_itemClicked(QTreeWidgetItem * item, int)
287 {
288         if (!item) {
289                 bc().setValid(false);
290                 return;
291         }
292
293         QString const data = item->data(0, Qt::UserRole).toString();
294         if (!data.endsWith(getSuffix())) {
295                 // not a file (probably a header)
296                 bc().setValid(false);
297                 return;
298         }
299
300         languageCO->clear();
301         QMap<QString, QString>::const_iterator i =available_languages_.constBegin();
302         while (i != available_languages_.constEnd()) {
303                 if (localizations_.contains(data)
304                     && localizations_.find(data).value().contains(i.key()))
305                         languageCO->addItem(i.value(), i.key());
306                 ++i;
307         }
308         setLanguage();
309         QString const realpath = getRealPath();
310         filesLW->currentItem()->setData(0, Qt::ToolTipRole, realpath);
311         QIcon user_icon(getPixmap("images/", "lyxfiles-user", "svgz,png"));
312         QIcon system_icon(getPixmap("images/", "lyxfiles-system", "svgz,png"));
313         QIcon file_icon = (realpath.startsWith(toqstr(package().user_support().absFileName()))) ?
314                         user_icon : system_icon;
315         item->setIcon(0, file_icon);
316 }
317
318
319 void GuiLyXFiles::setLanguage()
320 {
321         // Enable language selection only if there is a selection.
322         bool const item_selected =  filesLW->currentItem();
323         bool const language_alternatives = languageCO->count() > 1;
324         languageCO->setEnabled(item_selected && language_alternatives);
325         languageLA->setEnabled(item_selected && language_alternatives);
326         if (item_selected && language_alternatives)
327                 languageCO->setToolTip(qt_("All available languages of the selected file are displayed here.\n"
328                                            "The selected language version will be opened."));
329         else if (item_selected)
330                 languageCO->setToolTip(qt_("No alternative language versions available for the selected file."));
331         else
332                 languageCO->setToolTip(qt_("If alternative languages are available for a given file,\n"
333                                            "they can be chosen here if a file is selected."));
334         // first try last setting
335         if (!savelang_.isEmpty()) {
336                 int index = languageCO->findData(savelang_);
337                 if (index != -1) {
338                         languageCO->setCurrentIndex(index);
339                         return;
340                 }
341         }
342         // next, try GUI lang
343         if (!guilang_.isEmpty()) {
344                 int index = languageCO->findData(guilang_);
345                 if (index != -1) {
346                         languageCO->setCurrentIndex(index);
347                         return;
348                 }
349         }
350         // Finally, fall back to English (which should be always there)
351         int index = languageCO->findData(toqstr("en"));
352         if (index != -1) {
353                 languageCO->setCurrentIndex(index);
354         }
355 }
356
357
358 void GuiLyXFiles::on_browsePB_pressed()
359 {
360         QString path1 = toqstr(lyxrc.document_path);
361         QString path2 = toqstr(lyxrc.example_path);
362         QString title = qt_("Select example file");
363         QString filter = qt_("LyX Documents (*.lyx)");
364         QString b1 = qt_("D&ocuments");
365         QString b2 = qt_("&Examples");
366
367         if (type_ == "templates") {
368                 path2 = toqstr(lyxrc.template_path);
369                 title = qt_("Select template file");
370                 b1 = qt_("D&ocuments");
371                 b2 = qt_("&Templates");
372         }
373         else if (type_ != "examples") {
374                 path1 = toqstr(addName(package().user_support().absFileName(), fromqstr(type_)));
375                 path2 = toqstr(addName(package().system_support().absFileName(), fromqstr(type_)));
376                 b1 = qt_("&User files");
377                 b2 = qt_("&System files");
378         }
379         if (type_ == "ui") {
380                 title = qt_("Chose UI file");
381                 filter = qt_("LyX UI Files (*.ui)");
382         }
383         if (type_ == "bind") {
384                 title = qt_("Chose bind file");
385                 filter = qt_("LyX Bind Files (*.bind)");
386         }
387         if (type_ == "kbd") {
388                 title = qt_("Chose keyboard map");
389                 filter = qt_("LyX Keymap Files (*.kmap)");
390         }
391
392         FileDialog dlg(title);
393         dlg.setButton1(b1, path1);
394         dlg.setButton2(b2, path2);
395
396         FileDialog::Result result = dlg.open(path2, QStringList(filter));
397
398         if (result.first != FileDialog::Later && !result.second.isEmpty()) {
399                 file_ = toqstr(FileName(fromqstr(result.second)).absFileName());
400                 dispatchParams();
401                 close();
402         }
403 }
404
405
406 void GuiLyXFiles::updateContents()
407 {
408         languageCO->clear();
409         QMap<QString, QString> files = getFiles();
410         languageCO->model()->sort(0);
411
412         filesLW->clear();
413         QIcon user_icon(getPixmap("images/", "lyxfiles-user", "svgz,png"));
414         QIcon system_icon(getPixmap("images/", "lyxfiles-system", "svgz,png"));
415         QIcon user_folder_icon(getPixmap("images/", "lyxfiles-user-folder", "svgz,png"));
416         QIcon system_folder_icon(getPixmap("images/", "lyxfiles-system-folder", "svgz,png"));
417         QStringList cats;
418         QMap<QString, QString>::const_iterator it = files.constBegin();
419         QFont capfont;
420         capfont.setBold(true);
421         while (it != files.constEnd()) {
422                 QFileInfo const info = QFileInfo(it.key());
423                 QString const realpath = getRealPath(it.key());
424                 QString cat = it.value();
425                 QString subcat;
426                 QString catsave;
427                 if (cat.contains('/')) {
428                         catsave = cat;
429                         cat = catsave.left(catsave.indexOf('/'));
430                         subcat = toqstr(translateIfPossible(
431                                         qstring_to_ucs4(guiString(catsave.mid(catsave.indexOf('/') + 1)))));
432                 }
433                 cat =  toqstr(translateIfPossible(qstring_to_ucs4(guiString(cat))));
434                 QTreeWidgetItem * catItem;
435                 if (!cats.contains(cat)) {
436                         catItem = new QTreeWidgetItem();
437                         catItem->setText(0, cat);
438                         catItem->setFont(0, capfont);
439                         filesLW->insertTopLevelItem(0, catItem);
440                         catItem->setExpanded(true);
441                         cats << cat;
442                 } else
443                         catItem = filesLW->findItems(cat, Qt::MatchExactly).first();
444                 QTreeWidgetItem * item = new QTreeWidgetItem();
445                 QString const filename = info.fileName();
446                 QString guiname = filename.left(filename.lastIndexOf(getSuffix())).replace('_', ' ');
447                 // Special case: defaults.lyx
448                 if (type_ == "templates" && guiname == "defaults")
449                         guiname = qt_("Default Template");
450                 else if (translateName())
451                         guiname = toqstr(translateIfPossible(qstring_to_ucs4(guiString(guiname))));
452                 bool const user = realpath.startsWith(toqstr(package().user_support().absFileName()));
453                 QIcon file_icon = user ? user_icon : system_icon;
454                 item->setIcon(0, file_icon);
455                 item->setData(0, Qt::UserRole, it.key());
456                 item->setData(0, Qt::DisplayRole, guiname);
457                 item->setData(0, Qt::ToolTipRole, realpath);
458                 if (subcat.isEmpty())
459                         catItem->addChild(item);
460                 else {
461                         QTreeWidgetItem * subcatItem = nullptr;
462                         if (cats.contains(catsave)) {
463                                 QList<QTreeWidgetItem *> pcats = filesLW->findItems(cat, Qt::MatchExactly);
464                                 for (auto const & pcat : pcats) {
465                                         for (int cit = 0; cit < pcat->childCount(); ++cit) {
466                                                 if (pcat->child(cit)->text(0) == subcat) {
467                                                         subcatItem = pcat->child(cit);
468                                                         break;
469                                                 }
470                                         }
471                                 }
472                         }
473                         if (!subcatItem) {
474                                 subcatItem = new QTreeWidgetItem();
475                                 subcatItem->setText(0, subcat);
476                                 file_icon = user ? user_folder_icon : system_folder_icon;
477                                 subcatItem->setIcon(0, file_icon);
478                                 cats << catsave;
479                         }
480                         subcatItem->addChild(item);
481                         catItem->addChild(subcatItem);
482                 }
483                 ++it;
484         }
485         filesLW->sortItems(0, Qt::AscendingOrder);
486         // redo filter
487         filterLabels();
488 }
489
490
491 void GuiLyXFiles::slotButtonBox(QAbstractButton * button)
492 {
493         switch (buttonBox->standardButton(button)) {
494         case QDialogButtonBox::Open:
495                 slotOK();
496                 break;
497         case QDialogButtonBox::Cancel:
498                 slotClose();
499                 break;
500         default:
501                 break;
502         }
503 }
504
505
506 void GuiLyXFiles::filterLabels()
507 {
508         Qt::CaseSensitivity cs = csFindCB->isChecked() ?
509                 Qt::CaseSensitive : Qt::CaseInsensitive;
510         // Collect "active" categories (containing entries
511         // that match the filter)
512         QVector<QTreeWidgetItem*> activeCats;
513         QTreeWidgetItemIterator it(filesLW);
514         while (*it) {
515                 if ((*it)->childCount() > 0) {
516                         // Unhide parents (will be hidden
517                         // below if necessary)
518                         (*it)->setHidden(false);
519                         ++it;
520                         continue;
521                 }
522                 bool const match = (*it)->text(0).contains(filter_->text(), cs);
523                 if (match) {
524                         // Register parents of matched entries
525                         // so we don't hide those later.
526                         QTreeWidgetItem * twi = *it;
527                         while (true) {
528                                 if (!twi->parent())
529                                         break;
530                                 activeCats << twi->parent();
531                                 // ascend further up if possible
532                                 twi = twi->parent();
533                         }
534                 }
535                 (*it)->setHidden(!match);
536                 ++it;
537         }
538         // Iterate through parents once more
539         // to hide empty categories
540         it = QTreeWidgetItemIterator(filesLW);
541         while (*it) {
542                 if ((*it)->childCount() == 0) {
543                         ++it;
544                         continue;
545                 }
546                 (*it)->setHidden(!activeCats.contains(*it));
547                 ++it;
548         }
549 }
550
551
552 void GuiLyXFiles::resetFilter()
553 {
554         filter_->setText(QString());
555         filterLabels();
556 }
557
558 QString const GuiLyXFiles::getRealPath(QString relpath)
559 {
560         if (relpath.isEmpty() && filesLW->currentItem() != nullptr)
561                 relpath = filesLW->currentItem()->data(0, Qt::UserRole).toString();
562         QString const language = languageCO->itemData(languageCO->currentIndex()).toString();
563         if (localizations_.contains(relpath)) {
564                 if (localizations_.find(relpath).value().contains(language))
565                         return localizations_.find(relpath).value().find(language).value();
566                 else if (localizations_.find(relpath).value().contains(guilang_))
567                         return localizations_.find(relpath).value().find(guilang_).value();
568                 else if (localizations_.find(relpath).value().contains(toqstr("en")))
569                         return localizations_.find(relpath).value().find(toqstr("en")).value();
570         }
571         return QString();
572 }
573
574
575 void GuiLyXFiles::applyView()
576 {
577         file_ = getRealPath();
578 }
579
580
581 bool GuiLyXFiles::isValid()
582 {
583         return filesLW->currentItem() && filesLW->currentItem()->isSelected();
584 }
585
586
587 bool GuiLyXFiles::initialiseParams(string const & type)
588 {
589         type_ = type.empty() ? toqstr("templates") : toqstr(type);
590         paramsToDialog();
591         return true;
592 }
593
594
595 void GuiLyXFiles::passParams(string const & data)
596 {
597         initialiseParams(data);
598         updateContents();
599 }
600
601
602 void GuiLyXFiles::selectItem(QString const & item)
603 {
604         /* Using an intermediary variable flags is needed up to at least
605          * Qt 5.5 because of a subtle namespace issue. See:
606          *   https://stackoverflow.com/questions/10755058/qflags-enum-type-conversion-fails-all-of-a-sudden
607          * for details.*/
608         Qt::MatchFlags const flags(Qt::MatchExactly|Qt::MatchRecursive);
609         QList<QTreeWidgetItem *> twi = filesLW->findItems(item, flags);
610         if (!twi.isEmpty())
611                 twi.first()->setSelected(true);
612 }
613
614
615 void GuiLyXFiles::paramsToDialog()
616 {
617         if (type_ == "examples")
618                 setTitle(qt_("Open Example File"));
619         else if (type_ == "templates")
620                 setTitle(qt_("New File From Template"));
621         else
622                 setTitle(qt_("Open File"));
623
624         bc().setValid(isValid());
625 }
626
627
628 void GuiLyXFiles::dispatchParams()
629 {
630         if (file_.isEmpty())
631                 return;
632
633         string arg;
634         if (type_ == "templates")
635                 arg = "newfile ";
636         arg += quoteName(fromqstr(file_));
637         FuncCode const lfun = getLfun();
638
639         if (lfun == LFUN_NOACTION)
640                 // emit signal
641                 fileSelected(file_);
642         else
643                 dispatch(FuncRequest(lfun, arg));
644 }
645
646
647 FuncCode GuiLyXFiles::getLfun() const
648 {
649         if (type_ == "examples")
650                 return LFUN_FILE_OPEN;
651         else if (type_ == "templates")
652                 return LFUN_BUFFER_NEW_TEMPLATE;
653         return LFUN_NOACTION;
654 }
655
656
657 } // namespace frontend
658 } // namespace lyx
659
660 #include "moc_GuiLyXFiles.cpp"