2 * \file GuiLyXFiles.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Jürgen Spitzmüller
8 * Full author contact details are available in file CREDITS.
13 #include "GuiLyXFiles.h"
14 #include "GuiApplication.h"
15 #include "qt_helpers.h"
17 #include "FileDialog.h"
18 #include "FuncRequest.h"
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"
30 #include <QDirIterator>
31 #include <QTreeWidget>
34 using namespace lyx::support;
41 QString const guiString(QString const & in)
43 // recode specially encoded chars in file names (URL encoding and underbar)
44 return QString::fromUtf8(QByteArray::fromPercentEncoding(in.toUtf8())).replace('_', ' ');
50 QMap<QString, QString> GuiLyXFiles::getFiles()
52 QMap<QString, QString> result;
53 // We look for lyx files in the subdirectory dir of
55 // 2) build_lyxdir (if not empty)
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.
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_));
68 available_languages_.insert(toqstr("en"), qt_("English"));
70 QString const type = fileTypeCO->itemData(fileTypeCO->currentIndex()).toString();
72 // Search in the base paths
73 if (type == "all" || type == "user")
75 if (type == "all" || type == "system")
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()))
86 QString relpath = toqstr(makeRelPath(qstring_to_ucs4(fn),
87 qstring_to_ucs4(dir)));
89 int s = relpath.indexOf('/', 0);
90 QString cat = qt_("General");
91 QString localization = "en";
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());
102 int sc = relpath.indexOf('/', s + 1);
103 cat = (sc == -1) ? qt_("General") : relpath.mid(s + 1, sc - 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())
114 if (!relpaths.contains(relpath)) {
115 relpaths.append(relpath);
116 if (localization != "en")
118 relpath = relpath.mid(relpath.indexOf('/') + 1);
119 result.insert(relpath, cat);
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);
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);
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);
144 // pre-fill the language combo (it will be updated once an item
147 QMap<QString, QString>::const_iterator i =available_languages_.constBegin();
148 while (i != available_languages_.constEnd()) {
149 languageCO->addItem(i.value(), i.key());
157 GuiLyXFiles::GuiLyXFiles(GuiView & lv)
158 : GuiDialog(lv, "lyxfiles", qt_("New File From Template"))
162 // Get all supported languages (by code) in order to exclude those
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()));
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()));
181 string lang = getGuiMessages().language();
182 string const language = getEnv("LANGUAGE");
183 if (!language.empty())
184 lang += ":" + language;
185 guilangs_ = getVectorFromString(lang, ":");
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); });
195 filterBarL->addWidget(filter_, 0);
196 findKeysLA->setBuddy(filter_);
198 connect(buttonBox, SIGNAL(clicked(QAbstractButton *)),
199 this, SLOT(slotButtonBox(QAbstractButton *)));
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()));
210 bc().setPolicy(ButtonPolicy::OkApplyCancelPolicy);
211 bc().setOK(buttonBox->button(QDialogButtonBox::Open));
212 bc().setCancel(buttonBox->button(QDialogButtonBox::Cancel));
214 //filesLW->setViewMode(QListView::ListMode);
215 filesLW->setIconSize(QSize(22, 22));
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"));
223 setFocusProxy(filter_);
227 QString const GuiLyXFiles::getSuffix()
229 if (type_ == "bind" || type_ == "ui")
230 return toqstr(".") + type_;
231 else if (type_ == "kbd")
238 bool GuiLyXFiles::translateName() const
240 return (type_ == "templates" || type_ == "examples");
244 void GuiLyXFiles::fileSelectionChanged()
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);
256 void GuiLyXFiles::on_fileTypeCO_activated(int)
262 void GuiLyXFiles::on_languageCO_activated(int i)
264 savelang_ = languageCO->itemData(i).toString();
265 if (!filesLW->currentItem())
268 filesLW->currentItem()->setData(0, Qt::ToolTipRole, getRealPath());
273 void GuiLyXFiles::on_filesLW_itemDoubleClicked(QTreeWidgetItem * item, int)
275 if (!item || !item->data(0, Qt::UserRole).toString().endsWith(getSuffix())) {
276 // not a file (probably a header)
277 bc().setValid(false);
286 void GuiLyXFiles::on_filesLW_itemClicked(QTreeWidgetItem * item, int)
289 bc().setValid(false);
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);
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());
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);
319 void GuiLyXFiles::setLanguage()
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."));
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_);
338 languageCO->setCurrentIndex(index);
342 // next, try GUI lang
343 if (!guilang_.isEmpty()) {
344 int index = languageCO->findData(guilang_);
346 languageCO->setCurrentIndex(index);
350 // Finally, fall back to English (which should be always there)
351 int index = languageCO->findData(toqstr("en"));
353 languageCO->setCurrentIndex(index);
358 void GuiLyXFiles::on_browsePB_pressed()
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");
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");
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");
380 title = qt_("Chose UI file");
381 filter = qt_("LyX UI Files (*.ui)");
383 if (type_ == "bind") {
384 title = qt_("Chose bind file");
385 filter = qt_("LyX Bind Files (*.bind)");
387 if (type_ == "kbd") {
388 title = qt_("Chose keyboard map");
389 filter = qt_("LyX Keymap Files (*.kmap)");
392 FileDialog dlg(title);
393 dlg.setButton1(b1, path1);
394 dlg.setButton2(b2, path2);
396 FileDialog::Result result = dlg.open(path2, QStringList(filter));
398 if (result.first != FileDialog::Later && !result.second.isEmpty()) {
399 file_ = toqstr(FileName(fromqstr(result.second)).absFileName());
406 void GuiLyXFiles::updateContents()
409 QMap<QString, QString> files = getFiles();
410 languageCO->model()->sort(0);
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"));
418 QMap<QString, QString>::const_iterator it = files.constBegin();
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();
427 if (cat.contains('/')) {
429 cat = catsave.left(catsave.indexOf('/'));
430 subcat = toqstr(translateIfPossible(
431 qstring_to_ucs4(guiString(catsave.mid(catsave.indexOf('/') + 1)))));
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);
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);
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);
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);
480 subcatItem->addChild(item);
481 catItem->addChild(subcatItem);
485 filesLW->sortItems(0, Qt::AscendingOrder);
491 void GuiLyXFiles::slotButtonBox(QAbstractButton * button)
493 switch (buttonBox->standardButton(button)) {
494 case QDialogButtonBox::Open:
497 case QDialogButtonBox::Cancel:
506 void GuiLyXFiles::filterLabels()
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);
515 if ((*it)->childCount() > 0) {
516 // Unhide parents (will be hidden
517 // below if necessary)
518 (*it)->setHidden(false);
522 bool const match = (*it)->text(0).contains(filter_->text(), cs);
524 // Register parents of matched entries
525 // so we don't hide those later.
526 QTreeWidgetItem * twi = *it;
530 activeCats << twi->parent();
531 // ascend further up if possible
535 (*it)->setHidden(!match);
538 // Iterate through parents once more
539 // to hide empty categories
540 it = QTreeWidgetItemIterator(filesLW);
542 if ((*it)->childCount() == 0) {
546 (*it)->setHidden(!activeCats.contains(*it));
552 void GuiLyXFiles::resetFilter()
554 filter_->setText(QString());
558 QString const GuiLyXFiles::getRealPath(QString relpath)
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();
575 void GuiLyXFiles::applyView()
577 file_ = getRealPath();
581 bool GuiLyXFiles::isValid()
583 return filesLW->currentItem() && filesLW->currentItem()->isSelected();
587 bool GuiLyXFiles::initialiseParams(string const & type)
589 type_ = type.empty() ? toqstr("templates") : toqstr(type);
595 void GuiLyXFiles::passParams(string const & data)
597 initialiseParams(data);
602 void GuiLyXFiles::selectItem(QString const & item)
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
608 Qt::MatchFlags const flags(Qt::MatchExactly|Qt::MatchRecursive);
609 QList<QTreeWidgetItem *> twi = filesLW->findItems(item, flags);
611 twi.first()->setSelected(true);
615 void GuiLyXFiles::paramsToDialog()
617 if (type_ == "examples")
618 setTitle(qt_("Open Example File"));
619 else if (type_ == "templates")
620 setTitle(qt_("New File From Template"));
622 setTitle(qt_("Open File"));
624 bc().setValid(isValid());
628 void GuiLyXFiles::dispatchParams()
634 if (type_ == "templates")
636 arg += quoteName(fromqstr(file_));
637 FuncCode const lfun = getLfun();
639 if (lfun == LFUN_NOACTION)
643 dispatch(FuncRequest(lfun, arg));
647 FuncCode GuiLyXFiles::getLfun() const
649 if (type_ == "examples")
650 return LFUN_FILE_OPEN;
651 else if (type_ == "templates")
652 return LFUN_BUFFER_NEW_TEMPLATE;
653 return LFUN_NOACTION;
657 } // namespace frontend
660 #include "moc_GuiLyXFiles.cpp"