1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of Qt Creator.
7 **
8 ** Commercial License Usage
9 ** Licensees holding valid commercial Qt licenses may use this file in
10 ** accordance with the commercial license agreement provided with the
11 ** Software or, alternatively, in accordance with the terms contained in
12 ** a written agreement between you and The Qt Company. For licensing terms
13 ** and conditions see https://www.qt.io/terms-conditions. For further
14 ** information use the contact form at https://www.qt.io/contact-us.
15 **
16 ** GNU General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU
18 ** General Public License version 3 as published by the Free Software
19 ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
20 ** included in the packaging of this file. Please review the following
21 ** information to ensure the GNU General Public License requirements will
22 ** be met: https://www.gnu.org/licenses/gpl-3.0.html.
23 **
24 ****************************************************************************/
25
26 #include "docsettingspage.h"
27
28 #include "helpconstants.h"
29 #include "helpmanager.h"
30 #include "ui_docsettingspage.h"
31
32 #include <utils/algorithm.h>
33
34 #include <QFileDialog>
35 #include <QKeyEvent>
36 #include <QMessageBox>
37
38 #include <QAbstractListModel>
39 #include <QCoreApplication>
40 #include <QDir>
41 #include <QSortFilterProxyModel>
42 #include <QVariant>
43 #include <QVector>
44
45 #include <algorithm>
46
47 namespace Help {
48 namespace Internal {
49
50 class DocEntry
51 {
52 public:
53 QString name;
54 QString fileName;
55 QString nameSpace;
56 };
57
operator <(const DocEntry & d1,const DocEntry & d2)58 bool operator<(const DocEntry &d1, const DocEntry &d2)
59 { return d1.name < d2.name; }
60
61 class DocModel : public QAbstractListModel
62 {
63 public:
64 using DocEntries = QVector<DocEntry>;
65
66 DocModel() = default;
setEntries(const DocEntries & e)67 void setEntries(const DocEntries &e) { m_docEntries = e; }
68
rowCount(const QModelIndex &=QModelIndex ()) const69 int rowCount(const QModelIndex & = QModelIndex()) const override { return m_docEntries.size(); }
70 QVariant data(const QModelIndex &index, int role) const override;
71
72 void insertEntry(const DocEntry &e);
73 void removeAt(int row);
74
entryAt(int row) const75 const DocEntry &entryAt(int row) const { return m_docEntries.at(row); }
76
77 private:
78 DocEntries m_docEntries;
79 };
80
81 class DocSettingsPageWidget : public Core::IOptionsPageWidget
82 {
83 Q_DECLARE_TR_FUNCTIONS(Help::DocSettingsPageWidget)
84
85 public:
86 DocSettingsPageWidget();
87
88 private:
89 void apply() final;
90
91 void addDocumentation();
92
93 bool eventFilter(QObject *object, QEvent *event) final;
94 void removeDocumentation(const QList<QModelIndex> &items);
95
96 QList<QModelIndex> currentSelection() const;
97
98 Ui::DocSettingsPage m_ui;
99
100 QString m_recentDialogPath;
101
102 using NameSpaceToPathHash = QMultiHash<QString, QString>;
103 NameSpaceToPathHash m_filesToRegister;
104 QHash<QString, bool> m_filesToRegisterUserManaged;
105 NameSpaceToPathHash m_filesToUnregister;
106
107 QSortFilterProxyModel m_proxyModel;
108 DocModel m_model;
109 };
110
createEntry(const QString & nameSpace,const QString & fileName,bool userManaged)111 static DocEntry createEntry(const QString &nameSpace, const QString &fileName, bool userManaged)
112 {
113 DocEntry result;
114 result.name = userManaged ? nameSpace
115 : DocSettingsPageWidget::tr("%1 (auto-detected)").arg(nameSpace);
116 result.fileName = fileName;
117 result.nameSpace = nameSpace;
118 return result;
119 }
120
data(const QModelIndex & index,int role) const121 QVariant DocModel::data(const QModelIndex &index, int role) const
122 {
123 QVariant result;
124 const int row = index.row();
125 if (index.isValid() && row < m_docEntries.size()) {
126 switch (role) {
127 case Qt::DisplayRole:
128 result = QVariant(m_docEntries.at(row).name);
129 break;
130 case Qt::ToolTipRole:
131 result = QVariant(QDir::toNativeSeparators(m_docEntries.at(row).fileName));
132 break;
133 case Qt::UserRole:
134 result = QVariant(m_docEntries.at(row).nameSpace);
135 break;
136 default:
137 break;
138 }
139 }
140 return result;
141 }
142
insertEntry(const DocEntry & e)143 void DocModel::insertEntry(const DocEntry &e)
144 {
145 const auto it = std::lower_bound(m_docEntries.begin(), m_docEntries.end(), e);
146 const int index = int(it - m_docEntries.begin());
147 beginInsertRows(QModelIndex(), index, index);
148 m_docEntries.insert(it, e);
149 endInsertRows();
150 }
151
removeAt(int row)152 void DocModel::removeAt(int row)
153 {
154 beginRemoveRows(QModelIndex(), row, row);
155 m_docEntries.removeAt(row);
156 endRemoveRows();
157 }
158
159 } // namespace Internal
160
161 using namespace Help::Internal;
162
DocSettingsPageWidget()163 DocSettingsPageWidget::DocSettingsPageWidget()
164 {
165 m_ui.setupUi(this);
166
167 const QStringList nameSpaces = HelpManager::registeredNamespaces();
168 const QSet<QString> userDocumentationPaths = HelpManager::userDocumentationPaths();
169
170 DocModel::DocEntries entries;
171 entries.reserve(nameSpaces.size());
172 for (const QString &nameSpace : nameSpaces) {
173 const QString filePath = HelpManager::fileFromNamespace(nameSpace);
174 bool user = userDocumentationPaths.contains(filePath);
175 entries.append(createEntry(nameSpace, filePath, user));
176 m_filesToRegister.insert(nameSpace, filePath);
177 m_filesToRegisterUserManaged.insert(nameSpace, user);
178 }
179 std::stable_sort(entries.begin(), entries.end());
180 m_model.setEntries(entries);
181
182 m_proxyModel.setSourceModel(&m_model);
183 m_ui.docsListView->setModel(&m_proxyModel);
184 m_ui.filterLineEdit->setFiltering(true);
185 connect(m_ui.filterLineEdit,
186 &QLineEdit::textChanged,
187 &m_proxyModel,
188 &QSortFilterProxyModel::setFilterFixedString);
189
190 connect(m_ui.addButton,
191 &QAbstractButton::clicked,
192 this,
193 &DocSettingsPageWidget::addDocumentation);
194 connect(m_ui.removeButton, &QAbstractButton::clicked, this, [this]() {
195 removeDocumentation(currentSelection());
196 });
197
198 m_ui.docsListView->installEventFilter(this);
199 }
200
addDocumentation()201 void DocSettingsPageWidget::addDocumentation()
202 {
203 const QStringList &files =
204 QFileDialog::getOpenFileNames(m_ui.addButton->parentWidget(),
205 tr("Add Documentation"), m_recentDialogPath, tr("Qt Help Files (*.qch)"));
206
207 if (files.isEmpty())
208 return;
209 m_recentDialogPath = QFileInfo(files.first()).canonicalPath();
210
211 NameSpaceToPathHash docsUnableToRegister;
212 for (const QString &file : files) {
213 const QString filePath = QDir::cleanPath(file);
214 const QString &nameSpace = HelpManager::namespaceFromFile(filePath);
215 if (nameSpace.isEmpty()) {
216 docsUnableToRegister.insert("UnknownNamespace", QDir::toNativeSeparators(filePath));
217 continue;
218 }
219
220 if (m_filesToRegister.contains(nameSpace)) {
221 docsUnableToRegister.insert(nameSpace, QDir::toNativeSeparators(filePath));
222 continue;
223 }
224
225 m_model.insertEntry(createEntry(nameSpace, file, true /* user managed */));
226
227 m_filesToRegister.insert(nameSpace, filePath);
228 m_filesToRegisterUserManaged.insert(nameSpace, true/*user managed*/);
229
230 // If the files to unregister contains the namespace, grab a copy of all paths added and try to
231 // remove the current file path. Afterwards remove the whole entry and add the clean list back.
232 // Possible outcome:
233 // - might not add the entry back at all if we register the same file again
234 // - might add the entry back with paths to other files with the same namespace
235 // The reason to do this is, if we remove a file with a given namespace/ path and re-add another
236 // file with the same namespace but a different path, we need to unregister the namespace before
237 // we can register the new one. Help engine allows just one registered namespace.
238 if (m_filesToUnregister.contains(nameSpace)) {
239 QSet<QString> values = Utils::toSet(m_filesToUnregister.values(nameSpace));
240 values.remove(filePath);
241 m_filesToUnregister.remove(nameSpace);
242 foreach (const QString &value, values)
243 m_filesToUnregister.insert(nameSpace, value);
244 }
245 }
246
247 QString formatedFail;
248 if (docsUnableToRegister.contains("UnknownNamespace")) {
249 formatedFail += QString::fromLatin1("<ul><li><b>%1</b>").arg(tr("Invalid documentation file:"));
250 foreach (const QString &value, docsUnableToRegister.values("UnknownNamespace"))
251 formatedFail += QString::fromLatin1("<ul><li>%2</li></ul>").arg(value);
252 formatedFail += "</li></ul>";
253 docsUnableToRegister.remove("UnknownNamespace");
254 }
255
256 if (!docsUnableToRegister.isEmpty()) {
257 formatedFail += QString::fromLatin1("<ul><li><b>%1</b>").arg(tr("Namespace already registered:"));
258 const NameSpaceToPathHash::ConstIterator cend = docsUnableToRegister.constEnd();
259 for (NameSpaceToPathHash::ConstIterator it = docsUnableToRegister.constBegin(); it != cend; ++it) {
260 formatedFail += QString::fromLatin1("<ul><li>%1 - %2</li></ul>").arg(it.key(), it.value());
261 }
262 formatedFail += "</li></ul>";
263 }
264
265 if (!formatedFail.isEmpty()) {
266 QMessageBox::information(m_ui.addButton->parentWidget(), tr("Registration Failed"),
267 tr("Unable to register documentation.") + formatedFail, QMessageBox::Ok);
268 }
269 }
270
apply()271 void DocSettingsPageWidget::apply()
272 {
273 HelpManager::unregisterNamespaces(m_filesToUnregister.keys());
274 QStringList files;
275 auto it = m_filesToRegisterUserManaged.constBegin();
276 while (it != m_filesToRegisterUserManaged.constEnd()) {
277 if (it.value()/*userManaged*/)
278 files << m_filesToRegister.value(it.key());
279 ++it;
280 }
281 HelpManager::registerUserDocumentation(files);
282
283 m_filesToUnregister.clear();
284 }
285
eventFilter(QObject * object,QEvent * event)286 bool DocSettingsPageWidget::eventFilter(QObject *object, QEvent *event)
287 {
288 if (object != m_ui.docsListView)
289 return IOptionsPageWidget::eventFilter(object, event);
290
291 if (event->type() == QEvent::KeyPress) {
292 auto ke = static_cast<const QKeyEvent*>(event);
293 switch (ke->key()) {
294 case Qt::Key_Backspace:
295 case Qt::Key_Delete:
296 removeDocumentation(currentSelection());
297 break;
298 default: break;
299 }
300 }
301
302 return IOptionsPageWidget::eventFilter(object, event);
303 }
304
removeDocumentation(const QList<QModelIndex> & items)305 void DocSettingsPageWidget::removeDocumentation(const QList<QModelIndex> &items)
306 {
307 if (items.isEmpty())
308 return;
309
310 QList<QModelIndex> itemsByDecreasingRow = items;
311 Utils::sort(itemsByDecreasingRow, [](const QModelIndex &i1, const QModelIndex &i2) {
312 return i1.row() > i2.row();
313 });
314 for (const QModelIndex &item : qAsConst(itemsByDecreasingRow)) {
315 const int row = item.row();
316 const QString nameSpace = m_model.entryAt(row).nameSpace;
317
318 m_filesToRegister.remove(nameSpace);
319 m_filesToRegisterUserManaged.remove(nameSpace);
320 m_filesToUnregister.insert(nameSpace, QDir::cleanPath(HelpManager::fileFromNamespace(nameSpace)));
321
322 m_model.removeAt(row);
323 }
324
325 const int newlySelectedRow = qMax(itemsByDecreasingRow.last().row() - 1, 0);
326 const QModelIndex index = m_proxyModel.mapFromSource(m_model.index(newlySelectedRow));
327 m_ui.docsListView->selectionModel()->select(index, QItemSelectionModel::ClearAndSelect);
328 }
329
currentSelection() const330 QList<QModelIndex> DocSettingsPageWidget::currentSelection() const
331 {
332 return Utils::transform(m_ui.docsListView->selectionModel()->selectedRows(),
333 [this](const QModelIndex &index) { return m_proxyModel.mapToSource(index); });
334 }
335
DocSettingsPage()336 DocSettingsPage::DocSettingsPage()
337 {
338 setId("B.Documentation");
339 setDisplayName(DocSettingsPageWidget::tr("Documentation"));
340 setCategory(Help::Constants::HELP_CATEGORY);
341 setWidgetCreator([] { return new DocSettingsPageWidget; });
342 }
343
344 } // namespace Help
345