id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11,547
|
mindmapeditor.cpp
|
vnotex_vnote/src/widgets/editors/mindmapeditor.cpp
|
#include "mindmapeditor.h"
#include <QWebChannel>
#include "mindmapeditoradapter.h"
using namespace vnotex;
MindMapEditor::MindMapEditor(MindMapEditorAdapter *p_adapter,
const QColor &p_background,
qreal p_zoomFactor,
QWidget *p_parent)
: WebViewer(p_background, p_zoomFactor, p_parent),
m_adapter(p_adapter)
{
setAcceptDrops(true);
m_adapter->setParent(this);
connect(m_adapter, &MindMapEditorAdapter::contentsChanged,
this, [this]() {
m_modified = true;
emit contentsChanged();
});
auto channel = new QWebChannel(this);
channel->registerObject(QStringLiteral("vxAdapter"), m_adapter);
page()->setWebChannel(channel);
}
MindMapEditorAdapter *MindMapEditor::adapter() const
{
return m_adapter;
}
void MindMapEditor::setModified(bool p_modified)
{
m_modified = p_modified;
}
bool MindMapEditor::isModified() const
{
return m_modified;
}
| 1,032
|
C++
|
.cpp
| 34
| 23.588235
| 68
| 0.653846
|
vnotex/vnote
| 11,753
| 1,213
| 637
|
LGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,549
|
webviewadapter.cpp
|
vnotex_vnote/src/widgets/editors/webviewadapter.cpp
|
#include "webviewadapter.h"
#include <utils/utils.h>
using namespace vnotex;
QJsonObject WebViewAdapter::FindOption::toJson() const
{
QJsonObject obj;
obj["findBackward"] = m_findBackward;
obj["caseSensitive"] = m_caseSensitive;
obj["wholeWordOnly"] = m_wholeWordOnly;
obj["regularExpression"] = m_regularExpression;
return obj;
}
WebViewAdapter::WebViewAdapter(QObject *p_parent)
: QObject(p_parent)
{
}
void WebViewAdapter::setReady(bool p_ready)
{
if (m_ready == p_ready) {
return;
}
m_ready = p_ready;
if (m_ready) {
for (auto &act : m_pendingActions) {
act();
}
m_pendingActions.clear();
emit ready();
} else {
m_pendingActions.clear();
}
}
void WebViewAdapter::pendAction(const std::function<void()> &p_func)
{
Q_ASSERT(!m_ready);
m_pendingActions.append(p_func);
}
bool WebViewAdapter::isReady() const
{
return m_ready;
}
void WebViewAdapter::invokeCallback(quint64 p_id, void *p_data)
{
m_callbackPool.call(p_id, p_data);
}
quint64 WebViewAdapter::addCallback(const CallbackPool::Callback &p_callback)
{
return m_callbackPool.add(p_callback);
}
void WebViewAdapter::findText(const QStringList &p_texts, FindOptions p_options, int p_currentMatchLine)
{
FindOption opts;
if (p_options & vnotex::FindOption::FindBackward) {
opts.m_findBackward = true;
}
if (p_options & vnotex::FindOption::CaseSensitive) {
opts.m_caseSensitive = true;
}
if (p_options & vnotex::FindOption::WholeWordOnly) {
opts.m_wholeWordOnly = true;
}
if (p_options & vnotex::FindOption::RegularExpression) {
opts.m_regularExpression = true;
}
if (isReady()) {
emit findTextRequested(p_texts, opts.toJson(), p_currentMatchLine);
} else {
pendAction([this, p_texts, opts, p_currentMatchLine]() {
// FIXME: highlights will be clear once the page is ready. Add a delay here.
Utils::sleepWait(1000);
emit findTextRequested(p_texts, opts.toJson(), p_currentMatchLine);
});
}
}
void WebViewAdapter::setFindText(const QStringList &p_texts, int p_totalMatches, int p_currentMatchIndex)
{
emit findTextReady(p_texts, p_totalMatches, p_currentMatchIndex);
}
| 2,313
|
C++
|
.cpp
| 78
| 24.935897
| 105
| 0.677623
|
vnotex/vnote
| 11,753
| 1,213
| 637
|
LGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,603
|
mindmapeditorconfig.h
|
vnotex_vnote/src/core/mindmapeditorconfig.h
|
#ifndef MINDMAPEDITORCONFIG_H
#define MINDMAPEDITORCONFIG_H
#include "iconfig.h"
#include "webresource.h"
namespace vnotex
{
class MindMapEditorConfig : public IConfig
{
public:
MindMapEditorConfig(ConfigMgr *p_mgr, IConfig *p_topConfig);
void init(const QJsonObject &p_app, const QJsonObject &p_user) Q_DECL_OVERRIDE;
QJsonObject toJson() const Q_DECL_OVERRIDE;
const WebResource &getEditorResource() const;
private:
friend class MainConfig;
void loadEditorResource(const QJsonObject &p_app, const QJsonObject &p_user);
QJsonObject saveEditorResource() const;
WebResource m_editorResource;
};
}
#endif // MINDMAPEDITORCONFIG_H
| 722
|
C++
|
.h
| 21
| 28.904762
| 87
| 0.729378
|
vnotex/vnote
| 11,753
| 1,213
| 637
|
LGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,623
|
pdfviewerconfig.h
|
vnotex_vnote/src/core/pdfviewerconfig.h
|
#ifndef PDFVIEWERCONFIG_H
#define PDFVIEWERCONFIG_H
#include "iconfig.h"
#include "webresource.h"
namespace vnotex
{
class PdfViewerConfig : public IConfig
{
public:
PdfViewerConfig(ConfigMgr *p_mgr, IConfig *p_topConfig);
void init(const QJsonObject &p_app, const QJsonObject &p_user) Q_DECL_OVERRIDE;
QJsonObject toJson() const Q_DECL_OVERRIDE;
const WebResource &getViewerResource() const;
private:
friend class MainConfig;
void loadViewerResource(const QJsonObject &p_app, const QJsonObject &p_user);
QJsonObject saveViewerResource() const;
WebResource m_viewerResource;
};
}
#endif // PDFVIEWERCONFIG_H
| 702
|
C++
|
.h
| 21
| 27.952381
| 87
| 0.721311
|
vnotex/vnote
| 11,753
| 1,213
| 637
|
LGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,661
|
urlbasedbufferprovider.h
|
vnotex_vnote/src/core/buffer/urlbasedbufferprovider.h
|
#ifndef URLBASEDBUFFERPROVIDER_H
#define URLBASEDBUFFERPROVIDER_H
#include "bufferprovider.h"
#include <QSharedPointer>
namespace vnotex
{
// A wrapper provider to provide URL-based buffer (instead of content-based).
class UrlBasedBufferProvider : public BufferProvider
{
Q_OBJECT
public:
// Will own @p_provider.
UrlBasedBufferProvider(const QSharedPointer<BufferProvider> &p_provider, QObject *p_parent = nullptr)
: BufferProvider(p_parent),
m_provider(p_provider)
{
}
Buffer::ProviderType getType() const Q_DECL_OVERRIDE {
return m_provider->getType();
}
bool match(const Node *p_node) const Q_DECL_OVERRIDE {
return m_provider->match(p_node);
}
bool match(const QString &p_filePath) const Q_DECL_OVERRIDE {
return m_provider->match(p_filePath);
}
QString getName() const Q_DECL_OVERRIDE {
return m_provider->getName();
}
QString getPath() const Q_DECL_OVERRIDE {
return m_provider->getPath();
}
QString getContentPath() const Q_DECL_OVERRIDE {
return m_provider->getContentPath();
}
QString getResourcePath() const Q_DECL_OVERRIDE {
return m_provider->getResourcePath();
}
void write(const QString &p_content) Q_DECL_OVERRIDE {
Q_UNUSED(p_content);
}
QString read() const Q_DECL_OVERRIDE {
const_cast<UrlBasedBufferProvider *>(this)->m_lastModified = getLastModifiedFromFile();
return QString();
}
QString fetchImageFolderPath() Q_DECL_OVERRIDE {
return m_provider->fetchImageFolderPath();
}
bool isChildOf(const Node *p_node) const Q_DECL_OVERRIDE {
return m_provider->isChildOf(p_node);
}
Node *getNode() const Q_DECL_OVERRIDE {
return m_provider->getNode();
}
QString getAttachmentFolder() const Q_DECL_OVERRIDE {
return m_provider->getAttachmentFolder();
}
QString fetchAttachmentFolderPath() Q_DECL_OVERRIDE {
return m_provider->fetchAttachmentFolderPath();
}
QStringList addAttachment(const QString &p_destFolderPath, const QStringList &p_files) Q_DECL_OVERRIDE {
return m_provider->addAttachment(p_destFolderPath, p_files);
}
QString newAttachmentFile(const QString &p_destFolderPath, const QString &p_name) Q_DECL_OVERRIDE {
return m_provider->newAttachmentFile(p_destFolderPath, p_name);
}
QString newAttachmentFolder(const QString &p_destFolderPath, const QString &p_name) Q_DECL_OVERRIDE {
return m_provider->newAttachmentFolder(p_destFolderPath, p_name);
}
QString renameAttachment(const QString &p_path, const QString &p_name) Q_DECL_OVERRIDE {
return m_provider->renameAttachment(p_path, p_name);
}
void removeAttachment(const QStringList &p_paths) Q_DECL_OVERRIDE {
m_provider->removeAttachment(p_paths);
}
QString insertImage(const QString &p_srcImagePath, const QString &p_imageFileName) Q_DECL_OVERRIDE {
return m_provider->insertImage(p_srcImagePath, p_imageFileName);
}
QString insertImage(const QImage &p_image, const QString &p_imageFileName) Q_DECL_OVERRIDE {
return m_provider->insertImage(p_image, p_imageFileName);
}
void removeImage(const QString &p_imagePath) Q_DECL_OVERRIDE {
m_provider->removeImage(p_imagePath);
}
bool isAttachmentSupported() const Q_DECL_OVERRIDE {
return m_provider->isAttachmentSupported();
}
bool isTagSupported() const Q_DECL_OVERRIDE {
return m_provider->isTagSupported();
}
bool isReadOnly() const Q_DECL_OVERRIDE {
return true;
}
QSharedPointer<File> getFile() const Q_DECL_OVERRIDE {
return m_provider->getFile();
}
private:
QSharedPointer<BufferProvider> m_provider;
};
}
#endif // URLBASEDBUFFERPROVIDER_H
| 4,239
|
C++
|
.h
| 101
| 32.366337
| 112
| 0.638666
|
vnotex/vnote
| 11,753
| 1,213
| 637
|
LGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,717
|
pdfviewwindow.h
|
vnotex_vnote/src/widgets/pdfviewwindow.h
|
#ifndef PDFVIEWWINDOW_H
#define PDFVIEWWINDOW_H
#include "viewwindow.h"
#include <QScopedPointer>
class QWebEngineView;
namespace vnotex
{
class PdfViewer;
class PdfViewerAdapter;
class PdfViewWindow : public ViewWindow
{
Q_OBJECT
public:
explicit PdfViewWindow(QWidget *p_parent = nullptr);
QString getLatestContent() const Q_DECL_OVERRIDE;
QString selectedText() const Q_DECL_OVERRIDE;
void setMode(ViewWindowMode p_mode) Q_DECL_OVERRIDE;
void openTwice(const QSharedPointer<FileOpenParameters> &p_paras) Q_DECL_OVERRIDE;
ViewWindowSession saveSession() const Q_DECL_OVERRIDE;
void applySnippet(const QString &p_name) Q_DECL_OVERRIDE;
void applySnippet() Q_DECL_OVERRIDE;
void fetchWordCountInfo(const std::function<void(const WordCountInfo &)> &p_callback) const Q_DECL_OVERRIDE;
public slots:
void handleEditorConfigChange() Q_DECL_OVERRIDE;
protected slots:
void setModified(bool p_modified) Q_DECL_OVERRIDE;
void print() Q_DECL_OVERRIDE;
protected:
void syncEditorFromBuffer() Q_DECL_OVERRIDE;
void syncEditorFromBufferContent() Q_DECL_OVERRIDE;
void scrollUp() Q_DECL_OVERRIDE;
void scrollDown() Q_DECL_OVERRIDE;
void zoom(bool p_zoomIn) Q_DECL_OVERRIDE;
private:
void setupUI();
void setupToolBar();
void setupViewer();
PdfViewerAdapter *adapter() const;
bool updateConfigRevision();
// Managed by QObject.
PdfViewer *m_viewer = nullptr;
int m_viewerConfigRevision = 0;
};
}
#endif // PDFVIEWWINDOW_H
| 1,686
|
C++
|
.h
| 45
| 30.311111
| 116
| 0.69603
|
vnotex/vnote
| 11,753
| 1,213
| 637
|
LGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,779
|
notetemplateselector.h
|
vnotex_vnote/src/widgets/dialogs/notetemplateselector.h
|
#ifndef NOTETEMPLATESELECTOR_H
#define NOTETEMPLATESELECTOR_H
#include <QWidget>
class QComboBox;
class QPlainTextEdit;
namespace vnotex
{
class NoteTemplateSelector : public QWidget
{
Q_OBJECT
public:
explicit NoteTemplateSelector(QWidget *p_parent = nullptr);
QString getCurrentTemplate() const;
bool setCurrentTemplate(const QString &p_template);
const QString& getTemplateContent() const;
signals:
void templateChanged();
private:
void setupUI();
void setupTemplateComboBox(QWidget *p_parent);
void updateCurrentTemplate();
QComboBox *m_templateComboBox = nullptr;
QPlainTextEdit *m_templateTextEdit = nullptr;
QString m_templateContent;
};
}
#endif // NOTETEMPLATESELECTOR_H
| 813
|
C++
|
.h
| 27
| 24.185185
| 67
| 0.714101
|
vnotex/vnote
| 11,753
| 1,213
| 637
|
LGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,798
|
newnotedialog.h
|
vnotex_vnote/src/widgets/dialogs/newnotedialog.h
|
#ifndef NEWNOTEDIALOG_H
#define NEWNOTEDIALOG_H
#include "scrolldialog.h"
namespace vnotex
{
class Notebook;
class Node;
class NodeInfoWidget;
class NoteTemplateSelector;
class NewNoteDialog : public ScrollDialog
{
Q_OBJECT
public:
// New a note under @p_node.
NewNoteDialog(Node *p_node, QWidget *p_parent = nullptr);
const QSharedPointer<Node> &getNewNode() const;
static QSharedPointer<Node> newNote(Notebook *p_notebook,
Node *p_parentNode,
const QString &p_name,
const QString &p_templateContent,
QString &p_errMsg);
protected:
void acceptedButtonClicked() Q_DECL_OVERRIDE;
private:
void setupUI(const Node *p_node);
void setupNodeInfoWidget(const Node *p_node, QWidget *p_parent);
bool validateInputs();
bool validateNameInput(QString &p_msg);
void initDefaultValues(const Node *p_node);
static QString evaluateTemplateContent(const QString &p_content, const QString &p_name);
NodeInfoWidget *m_infoWidget = nullptr;
NoteTemplateSelector *m_templateSelector = nullptr;
QSharedPointer<Node> m_newNode;
static QString s_lastTemplate;
};
} // ns vnotex
#endif // NEWNOTEDIALOG_H
| 1,443
|
C++
|
.h
| 37
| 28.243243
| 96
| 0.614831
|
vnotex/vnote
| 11,753
| 1,213
| 637
|
LGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,801
|
quickaccesspage.h
|
vnotex_vnote/src/widgets/dialogs/settings/quickaccesspage.h
|
#ifndef QUICKACCESSPAGE_H
#define QUICKACCESSPAGE_H
#include "settingspage.h"
#include <core/sessionconfig.h>
class QGroupBox;
class QPlainTextEdit;
class QComboBox;
namespace vnotex
{
class LocationInputWithBrowseButton;
class LineEditWithSnippet;
class NoteTemplateSelector;
class QuickAccessPage : public SettingsPage
{
Q_OBJECT
public:
explicit QuickAccessPage(QWidget *p_parent = nullptr);
QString title() const Q_DECL_OVERRIDE;
protected:
void loadInternal() Q_DECL_OVERRIDE;
bool saveInternal() Q_DECL_OVERRIDE;
private:
void setupUI();
QGroupBox *setupFlashPageGroup();
QGroupBox *setupQuickAccessGroup();
QGroupBox *setupQuickNoteGroup();
void newQuickNoteScheme();
void removeQuickNoteScheme();
void saveCurrentQuickNote();
void loadCurrentQuickNote();
void loadQuickNoteSchemes();
void saveQuickNoteSchemes();
void setCurrentQuickNote(int idx);
static QString getDefaultQuickNoteFolderPath();
LocationInputWithBrowseButton *m_flashPageInput = nullptr;
QPlainTextEdit *m_quickAccessTextEdit = nullptr;
QComboBox *m_quickNoteSchemeComboBox = nullptr;
LocationInputWithBrowseButton *m_quickNoteFolderPathInput = nullptr;
LineEditWithSnippet *m_quickNoteNoteNameLineEdit = nullptr;
NoteTemplateSelector *m_quickNoteTemplateSelector = nullptr;
QGroupBox *m_quickNoteInfoGroupBox = nullptr;
QVector<SessionConfig::QuickNoteScheme> m_quickNoteSchemes;
int m_quickNoteCurrentIndex = -1;
};
}
#endif // QUICKACCESSPAGE_H
| 1,697
|
C++
|
.h
| 46
| 29.934783
| 76
| 0.727329
|
vnotex/vnote
| 11,753
| 1,213
| 637
|
LGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,820
|
mindmapeditoradapter.h
|
vnotex_vnote/src/widgets/editors/mindmapeditoradapter.h
|
#ifndef MINDMAPEDITORADAPTER_H
#define MINDMAPEDITORADAPTER_H
#include "webviewadapter.h"
#include <QString>
#include <QJsonObject>
#include <core/global.h>
namespace vnotex
{
// Adapter and interface between CPP and JS for MindMap.
class MindMapEditorAdapter : public WebViewAdapter
{
Q_OBJECT
public:
explicit MindMapEditorAdapter(QObject *p_parent = nullptr);
~MindMapEditorAdapter() = default;
void setData(const QString &p_data);
void saveData(const std::function<void(const QString &)> &p_callback);
// Functions to be called from web side.
public slots:
void setSavedData(quint64 p_id, const QString &p_data);
void notifyContentsChanged();
// Signals to be connected at web side.
signals:
void dataUpdated(const QString& p_data);
void saveDataRequested(quint64 p_id);
signals:
void contentsChanged();
private:
};
}
#endif // MINDMAPEDITORADAPTER_H
| 1,001
|
C++
|
.h
| 31
| 26.580645
| 78
| 0.697699
|
vnotex/vnote
| 11,753
| 1,213
| 637
|
LGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,822
|
pdfvieweradapter.h
|
vnotex_vnote/src/widgets/editors/pdfvieweradapter.h
|
#ifndef PDFVIEWERADAPTER_H
#define PDFVIEWERADAPTER_H
#include "webviewadapter.h"
namespace vnotex
{
// Adapter and interface between CPP and JS for PDF.
class PdfViewerAdapter : public WebViewAdapter
{
Q_OBJECT
public:
explicit PdfViewerAdapter(QObject *p_parent = nullptr);
~PdfViewerAdapter() = default;
void setUrl(const QString &p_url);
// Functions to be called from web side.
public slots:
// Signals to be connected at web side.
signals:
void urlUpdated(const QString &p_url);
};
}
#endif // PDFVIEWERADAPTER_H
| 610
|
C++
|
.h
| 21
| 23.714286
| 63
| 0.687285
|
vnotex/vnote
| 11,753
| 1,213
| 637
|
LGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,823
|
pdfviewer.h
|
vnotex_vnote/src/widgets/editors/pdfviewer.h
|
#ifndef PDFVIEWER_H
#define PDFVIEWER_H
#include "../webviewer.h"
namespace vnotex
{
class PdfViewerAdapter;
class PdfViewer : public WebViewer
{
Q_OBJECT
public:
PdfViewer(PdfViewerAdapter *p_adapter,
const QColor &p_background,
qreal p_zoomFactor,
QWidget *p_parent = nullptr);
PdfViewerAdapter *adapter() const;
private:
// Managed by QObject.
PdfViewerAdapter *m_adapter = nullptr;
};
}
#endif // PDFVIEWER_H
| 537
|
C++
|
.h
| 21
| 18.666667
| 47
| 0.619608
|
vnotex/vnote
| 11,753
| 1,213
| 637
|
LGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,825
|
webviewadapter.h
|
vnotex_vnote/src/widgets/editors/webviewadapter.h
|
#ifndef WEBVIEWADAPTER_H
#define WEBVIEWADAPTER_H
#include <QObject>
#include <QVector>
#include <utils/callbackpool.h>
#include <core/global.h>
namespace vnotex
{
// Base class of adapter and interface between CPP and JS for WebView.
class WebViewAdapter : public QObject
{
Q_OBJECT
public:
explicit WebViewAdapter(QObject *p_parent = nullptr);
bool isReady() const;
void findText(const QStringList &p_texts, FindOptions p_options, int p_currentMatchLine = -1);
// Functions to be called from web side.
public slots:
void setReady(bool p_ready);
void setFindText(const QStringList &p_texts, int p_totalMatches, int p_currentMatchIndex);
// Signals to be connected at cpp side.
signals:
void ready();
void findTextReady(const QStringList &p_texts, int p_totalMatches, int p_currentMatchIndex);
// Signals to be connected at web side.
signals:
void findTextRequested(const QStringList &p_texts, const QJsonObject &p_options, int p_currentMatchLine);
protected:
void pendAction(const std::function<void()> &p_func);
void invokeCallback(quint64 p_id, void *p_data);
quint64 addCallback(const CallbackPool::Callback &p_callback);
private:
struct FindOption
{
QJsonObject toJson() const;
bool m_findBackward = false;
bool m_caseSensitive = false;
bool m_wholeWordOnly = false;
bool m_regularExpression = false;
};
// Whether web side is ready.
bool m_ready = false;
// Pending actions for the editor once it is ready.
QVector<std::function<void()>> m_pendingActions;
CallbackPool m_callbackPool;
};
}
#endif // WEBVIEWADAPTER_H
| 1,830
|
C++
|
.h
| 48
| 30.729167
| 113
| 0.668562
|
vnotex/vnote
| 11,753
| 1,213
| 637
|
LGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,826
|
mindmapeditor.h
|
vnotex_vnote/src/widgets/editors/mindmapeditor.h
|
#ifndef MINDMAPEDITOR_H
#define MINDMAPEDITOR_H
#include "../webviewer.h"
namespace vnotex
{
class MindMapEditorAdapter;
class MindMapEditor : public WebViewer
{
Q_OBJECT
public:
MindMapEditor(MindMapEditorAdapter *p_adapter,
const QColor &p_background,
qreal p_zoomFactor,
QWidget *p_parent = nullptr);
MindMapEditorAdapter *adapter() const;
void setModified(bool p_modified);
bool isModified() const;
signals:
void contentsChanged();
private:
// Managed by QObject.
MindMapEditorAdapter *m_adapter = nullptr;
bool m_modified = false;
};
}
#endif // MINDMAPEDITOR_H
| 742
|
C++
|
.h
| 26
| 20.807692
| 54
| 0.626591
|
vnotex/vnote
| 11,753
| 1,213
| 637
|
LGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,887
|
datetime_tests.cpp
|
acaudwell_Gource/src/test/datetime_tests.cpp
|
/*
Copyright (C) 2021 Andrew Caudwell (acaudwell@gmail.com)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version
3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../main.h"
#include "../gource_settings.h"
#include <stdlib.h>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE( parse_date_time_tests )
{
time_t timestamp;
BOOST_CHECK_EQUAL(putenv((char*)"TZ=UTC"), 0);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635724800);
BOOST_CHECK_EQUAL(putenv((char*)"TZ=Pacific/Auckland"), 0);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635678000);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01Z", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635724800);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01+0", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635724800);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01+13", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635678000);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01 +13", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635678000);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01+5:30", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635705000);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01 12:01", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635721260);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01 12:01Z", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635768060);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01 12:01+0", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635768060);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01 12:01+13", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635721260);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01 12:01 +13", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635721260);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01 12:01+5:30", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635748260);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01 12:01:59", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635721319);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01T12:01:59.123", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635721319);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01 12:01:59Z", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635768119);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01 12:01:59+0", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635768119);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01 12:01:59+13", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635721319);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01 12:01:59 +13", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635721319);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01 12:01:59+5:30", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635748319);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01T12:01:59", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635721319);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01T12:01:59.123", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635721319);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01T12:01:59Z", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635768119);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01T12:01:59+0", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635768119);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01T12:01:59+13", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635721319);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01T12:01:59+13", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635721319);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01T12:01:59+5:30", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635748319);
BOOST_CHECK(SDLAppSettings::parseDateTime("2021-11-01T12:01:59.123+5:30", timestamp));
BOOST_CHECK_EQUAL(timestamp, 1635748319);
}
| 4,637
|
C++
|
.cpp
| 79
| 53.582278
| 90
| 0.745402
|
acaudwell/Gource
| 11,459
| 723
| 108
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,888
|
regex_tests.cpp
|
acaudwell_Gource/src/test/regex_tests.cpp
|
/*
Copyright (C) 2021 Andrew Caudwell (acaudwell@gmail.com)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version
3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../core/regex.h"
#include <stdlib.h>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE( regex_tests )
{
Regex regex("^[A-Z]+$");
BOOST_CHECK(regex.isValid());
BOOST_CHECK(regex.match("ABC"));
BOOST_CHECK(regex.match("abc") == false);
BOOST_CHECK(regex.match("ABC123") == false);
Regex regex_copy = Regex("^[A-Z]+$");
BOOST_CHECK(regex_copy.isValid());
BOOST_CHECK(regex_copy.match("ABC"));
BOOST_CHECK_THROW(Regex("^[A-Z+$"), RegexCompilationException);
Regex test_regex("^[A-Z+$", true);
BOOST_CHECK(test_regex.isValid() == false);
std::vector<std::string> matches;
Regex capture_regex("([0-9]+)");
BOOST_CHECK(capture_regex.match("ABC123", &matches));
BOOST_CHECK_EQUAL(matches.size(), 1);
BOOST_CHECK_EQUAL(matches[0], "123");
}
| 1,540
|
C++
|
.cpp
| 35
| 39.628571
| 73
| 0.696321
|
acaudwell/Gource
| 11,459
| 723
| 108
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,905
|
main.h
|
acaudwell_Gource/src/main.h
|
/*
Copyright (C) 2009 Andrew Caudwell (acaudwell@gmail.com)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version
3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GOURCE_MAIN_H
#define GOURCE_MAIN_H
#include "gource_shell.h"
#include "gource.h"
#endif
| 820
|
C++
|
.h
| 18
| 41.777778
| 73
| 0.757538
|
acaudwell/Gource
| 11,459
| 723
| 108
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,932
|
sqlitedatabase.cpp
|
zealdocs_zeal/src/libs/util/sqlitedatabase.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2016 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include "sqlitedatabase.h"
#include <sqlite3.h>
using namespace Zeal::Util;
namespace {
constexpr char ListTablesSql[] = "SELECT name"
" FROM"
" (SELECT * FROM sqlite_master UNION ALL"
" SELECT * FROM sqlite_temp_master)"
" WHERE type='table'"
" ORDER BY name";
constexpr char ListViewsSql[] = "SELECT name"
" FROM"
" (SELECT * FROM sqlite_master UNION ALL"
" SELECT * FROM sqlite_temp_master)"
" WHERE type='view'"
" ORDER BY name";
// sqlite3_exec() callback used in tables() and views().
auto ListCallback = [](void *ptr, int, char **data, char **) {
static_cast<QStringList *>(ptr)->append(QString::fromUtf8(data[0]));
return 0;
};
} // namespace
SQLiteDatabase::SQLiteDatabase(const QString &path)
{
if (sqlite3_initialize() != SQLITE_OK) {
return;
}
if (sqlite3_open16(path.constData(), &m_db) != SQLITE_OK) {
updateLastError();
close();
}
}
SQLiteDatabase::~SQLiteDatabase()
{
finalize();
close();
}
bool SQLiteDatabase::isOpen() const
{
return m_db != nullptr;
}
QStringList SQLiteDatabase::tables()
{
if (m_db == nullptr) {
return {};
}
QStringList list;
char *errmsg = nullptr;
const int rc = sqlite3_exec(m_db, ListTablesSql, ListCallback, &list, &errmsg);
if (rc != SQLITE_OK) {
if (errmsg) {
m_lastError = QString::fromUtf8(errmsg);
sqlite3_free(errmsg);
}
return {};
}
return list;
}
QStringList SQLiteDatabase::views()
{
if (m_db == nullptr) {
return {};
}
QStringList list;
char *errmsg = nullptr;
const int rc = sqlite3_exec(m_db, ListViewsSql, ListCallback, &list, &errmsg);
if (rc != SQLITE_OK) {
if (errmsg) {
m_lastError = QString::fromUtf8(errmsg);
sqlite3_free(errmsg);
}
return {};
}
return list;
}
bool SQLiteDatabase::prepare(const QString &sql)
{
if (m_db == nullptr) {
return false;
}
if (m_stmt != nullptr) {
finalize();
}
m_lastError.clear();
sqlite3_mutex_enter(sqlite3_db_mutex(m_db));
const void *pzTail = nullptr;
const int res = sqlite3_prepare16_v2(m_db,
sql.constData(),
(sql.size() + 1) * 2, // 2 = sizeof(QChar)
&m_stmt,
&pzTail);
sqlite3_mutex_leave(sqlite3_db_mutex(m_db));
if (res != SQLITE_OK) {
// "Unable to execute statement"
updateLastError();
finalize();
return false;
}
if (pzTail && !QString(static_cast<const QChar *>(pzTail)).trimmed().isEmpty()) {
// Unable to execute multiple statements at a time
updateLastError();
finalize();
return false;
}
return true;
}
bool SQLiteDatabase::next()
{
if (m_stmt == nullptr) {
return false;
}
sqlite3_mutex_enter(sqlite3_db_mutex(m_db));
const int res = sqlite3_step(m_stmt);
sqlite3_mutex_leave(sqlite3_db_mutex(m_db));
switch (res) {
case SQLITE_ROW:
return true;
case SQLITE_DONE:
case SQLITE_CONSTRAINT:
case SQLITE_ERROR:
case SQLITE_MISUSE:
case SQLITE_BUSY:
default:
updateLastError();
}
return false;
}
bool SQLiteDatabase::execute(const QString &sql)
{
if (m_db == nullptr) {
return false;
}
m_lastError.clear();
char *errmsg = nullptr;
const int rc = sqlite3_exec(m_db, sql.toUtf8(), nullptr, nullptr, &errmsg);
if (rc != SQLITE_OK) {
if (errmsg) {
m_lastError = QString::fromUtf8(errmsg);
sqlite3_free(errmsg);
}
return false;
}
return true;
}
QVariant SQLiteDatabase::value(int index) const
{
Q_ASSERT(index >= 0);
// sqlite3_data_count() returns 0 if m_stmt is nullptr.
if (index >= sqlite3_data_count(m_stmt)) {
return QVariant();
}
sqlite3_mutex_enter(sqlite3_db_mutex(m_db));
const int type = sqlite3_column_type(m_stmt, index);
QVariant ret;
switch (type) {
case SQLITE_INTEGER:
ret = sqlite3_column_int64(m_stmt, index);
break;
case SQLITE_NULL:
ret = QVariant();
break;
default:
ret = QString(static_cast<const QChar *>(sqlite3_column_text16(m_stmt, index)),
sqlite3_column_bytes16(m_stmt, index) / 2); // 2 = sizeof(QChar)
break;
}
sqlite3_mutex_leave(sqlite3_db_mutex(m_db));
return ret;
}
QString SQLiteDatabase::lastError() const
{
return m_lastError;
}
void SQLiteDatabase::close()
{
sqlite3_close(m_db);
m_db = nullptr;
}
void SQLiteDatabase::finalize()
{
sqlite3_finalize(m_stmt);
m_stmt = nullptr;
}
void SQLiteDatabase::updateLastError()
{
if (m_db == nullptr) {
return;
}
m_lastError = QString(static_cast<const QChar *>(sqlite3_errmsg16(m_db)));
}
sqlite3 *SQLiteDatabase::handle() const
{
return m_db;
}
| 5,546
|
C++
|
.cpp
| 197
| 20.766497
| 87
| 0.564127
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,933
|
plist.cpp
|
zealdocs_zeal/src/libs/util/plist.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "plist.h"
#include <QFile>
#include <QXmlStreamReader>
using namespace Zeal::Util;
bool Plist::read(const QString &fileName)
{
QScopedPointer<QFile> file(new QFile(fileName));
if (!file->open(QIODevice::ReadOnly)) {
// TODO: Report/log error
m_hasError = true;
return false;
}
QXmlStreamReader xml(file.data());
while (!xml.atEnd()) {
const QXmlStreamReader::TokenType token = xml.readNext();
if (token != QXmlStreamReader::StartElement)
continue;
if (xml.name() != QLatin1String("key"))
continue; // TODO: Should it fail here?
const QString key = xml.readElementText();
// Skip whitespaces between tags
while (xml.readNext() == QXmlStreamReader::Characters);
if (xml.tokenType() != QXmlStreamReader::StartElement)
continue;
QVariant value;
if (xml.name() == QLatin1String("string"))
value = xml.readElementText();
else if (xml.name() == QLatin1String("true"))
value = true;
else if (xml.name() == QLatin1String("false"))
value = false;
else
continue; // Skip unknown types
insert(key, value);
}
return m_hasError;
}
bool Plist::hasError() const
{
return m_hasError;
}
| 1,443
|
C++
|
.cpp
| 43
| 26.55814
| 65
| 0.618326
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,934
|
applicationsingleton.cpp
|
zealdocs_zeal/src/libs/core/applicationsingleton.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "applicationsingleton.h"
#include <QCoreApplication>
#include <QCryptographicHash>
#include <QDir>
#include <QLocalServer>
#include <QLocalSocket>
#include <QLoggingCategory>
#include <QScopedPointer>
#include <QSharedMemory>
using namespace Zeal::Core;
static Q_LOGGING_CATEGORY(log, "zeal.core.applicationsingleton")
struct SharedData
{
qint64 primaryPid;
};
ApplicationSingleton::ApplicationSingleton(QObject *parent)
: QObject(parent)
{
if (QCoreApplication::instance() == nullptr) {
qFatal("QCoreApplication (or derived type) must be created before ApplicationSingleton.");
}
m_id = computeId();
qCDebug(log, "Singleton ID: %s", qPrintable(m_id));
m_sharedMemory = new QSharedMemory(m_id, this);
m_isPrimary = m_sharedMemory->create(sizeof(SharedData));
if (m_isPrimary) {
setupPrimary();
return;
}
#ifdef Q_OS_UNIX
// Verify it's not a segment that survived an application crash.
m_sharedMemory->attach();
m_sharedMemory->detach();
m_isPrimary = m_sharedMemory->create(sizeof(SharedData));
if (m_isPrimary) {
setupPrimary();
return;
}
#endif
if (!m_sharedMemory->attach(QSharedMemory::ReadOnly)) {
qCWarning(log) << "Cannot attach to the shared memory segment:"
<< m_sharedMemory->errorString();
return;
}
setupSecondary();
}
bool ApplicationSingleton::isPrimary() const
{
return m_isPrimary;
}
bool ApplicationSingleton::isSecondary() const
{
return !m_isPrimary;
}
qint64 ApplicationSingleton::primaryPid() const
{
return m_primaryPid;
}
bool ApplicationSingleton::sendMessage(QByteArray &data, int timeout)
{
// No support for primary to secondary communication.
if (m_isPrimary) {
return false;
}
QScopedPointer<QLocalSocket, QScopedPointerDeleteLater> socket(new QLocalSocket);
socket->connectToServer(m_id);
if (!socket->waitForConnected(timeout)) {
qCWarning(log) << "Cannot connect to the local service:"
<< socket->errorString();
return false;
}
socket->write(data);
socket->flush(); // Required for Linux.
return socket->waitForBytesWritten(timeout);
}
void ApplicationSingleton::setupPrimary()
{
m_primaryPid = QCoreApplication::applicationPid();
qCInfo(log, "Starting as a primary instance. (PID: %lld)", m_primaryPid);
m_sharedMemory->lock();
auto sd = static_cast<SharedData *>(m_sharedMemory->data());
sd->primaryPid = m_primaryPid;
m_sharedMemory->unlock();
QLocalServer::removeServer(m_id);
m_localServer = new QLocalServer(this);
m_localServer->setSocketOptions(QLocalServer::UserAccessOption);
connect(m_localServer, &QLocalServer::newConnection, this, [this] {
QLocalSocket *socket = m_localServer->nextPendingConnection();
connect(socket, &QLocalSocket::readyRead, this, [this, socket] {
QByteArray data = socket->readAll();
emit messageReceived(data);
socket->deleteLater();
});
});
if (!m_localServer->listen(m_id)) {
qCWarning(log) << "Cannot start the local service:"
<< m_localServer->errorString();
return;
}
}
void ApplicationSingleton::setupSecondary()
{
m_sharedMemory->lock();
auto sd = static_cast<SharedData *>(m_sharedMemory->data());
m_primaryPid = sd->primaryPid;
m_sharedMemory->unlock();
qCInfo(log, "Starting as a secondary instance. (Primary PID: %lld)", m_primaryPid);
}
QString ApplicationSingleton::computeId()
{
// Make sure the result can be used as a name for the local socket.
static const QByteArray::Base64Options base64Options
= QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals;
QCryptographicHash hash(QCryptographicHash::Sha256);
hash.addData(QCoreApplication::applicationName().toUtf8());
hash.addData(QCoreApplication::organizationName().toUtf8());
hash.addData(QCoreApplication::organizationDomain().toUtf8());
// Support multi-user setup.
hash.addData(QDir::homePath().toUtf8());
return QString::fromLatin1(hash.result().toBase64(base64Options));
}
| 4,345
|
C++
|
.cpp
| 123
| 30.227642
| 98
| 0.698163
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,935
|
application.cpp
|
zealdocs_zeal/src/libs/core/application.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "application.h"
#include "extractor.h"
#include "filemanager.h"
#include "httpserver.h"
#include "networkaccessmanager.h"
#include "settings.h"
#include <registry/docsetregistry.h>
#include <registry/searchquery.h>
#include <ui/mainwindow.h>
#include <QCoreApplication>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMetaObject>
#include <QNetworkProxy>
#include <QNetworkReply>
#include <QScopedPointer>
#include <QStandardPaths>
#include <QSysInfo>
#include <QThread>
using namespace Zeal;
using namespace Zeal::Core;
namespace {
constexpr char ReleasesApiUrl[] = "https://api.zealdocs.org/v1/releases";
} // namespace
Application *Application::m_instance = nullptr;
Application::Application(QObject *parent)
: QObject(parent)
{
// Ensure only one instance of Application
Q_ASSERT(!m_instance);
m_instance = this;
m_settings = new Settings(this);
m_networkManager = new NetworkAccessManager(this);
m_fileManager = new FileManager(this);
m_httpServer = new HttpServer(this);
connect(m_networkManager, &QNetworkAccessManager::sslErrors,
this, [this](QNetworkReply *reply, const QList<QSslError> &errors) {
if (m_settings->isIgnoreSslErrorsEnabled) {
reply->ignoreSslErrors();
}
});
// Extractor setup
m_extractorThread = new QThread(this);
m_extractor = new Extractor();
m_extractor->moveToThread(m_extractorThread);
m_extractorThread->start();
connect(m_extractor, &Extractor::completed, this, &Application::extractionCompleted);
connect(m_extractor, &Extractor::error, this, &Application::extractionError);
connect(m_extractor, &Extractor::progress, this, &Application::extractionProgress);
m_docsetRegistry = new Registry::DocsetRegistry();
connect(m_settings, &Settings::updated, this, &Application::applySettings);
applySettings();
m_mainWindow = new WidgetUi::MainWindow(this);
if (m_settings->startMinimized) {
if (m_settings->showSystrayIcon && m_settings->minimizeToSystray)
return;
m_mainWindow->showMinimized();
} else {
m_mainWindow->show();
}
}
Application::~Application()
{
m_extractorThread->quit();
m_extractorThread->wait();
delete m_extractor;
delete m_mainWindow;
delete m_docsetRegistry;
}
/*!
* \internal
* \brief Returns a pointer to the Core::Application instance.
* \return A pointer or \c nullptr, if no instance has been created.
*/
Application *Application::instance()
{
return m_instance;
}
WidgetUi::MainWindow *Application::mainWindow() const
{
return m_mainWindow;
}
QNetworkAccessManager *Application::networkManager() const
{
return m_networkManager;
}
Settings *Application::settings() const
{
return m_settings;
}
Registry::DocsetRegistry *Application::docsetRegistry()
{
return m_docsetRegistry;
}
FileManager *Application::fileManager() const
{
return m_fileManager;
}
HttpServer *Application::httpServer() const
{
return m_httpServer;
}
QString Application::cacheLocation()
{
#ifndef PORTABLE_BUILD
return QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
#else
return QCoreApplication::applicationDirPath() + QLatin1String("/cache");
#endif
}
QString Application::configLocation()
{
#ifndef PORTABLE_BUILD
// TODO: Replace 'Zeal/Zeal' with 'zeal'.
return QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
#else
return QCoreApplication::applicationDirPath() + QLatin1String("/config");
#endif
}
QVersionNumber Application::version()
{
static const auto vn = QVersionNumber::fromString(QCoreApplication::applicationVersion());
return vn;
}
QString Application::versionString()
{
static const auto v = QStringLiteral("v%1").arg(QCoreApplication::applicationVersion());
return v;
}
void Application::executeQuery(const Registry::SearchQuery &query, bool preventActivation)
{
m_mainWindow->search(query);
if (preventActivation)
return;
m_mainWindow->bringToFront();
}
void Application::extract(const QString &filePath, const QString &destination, const QString &root)
{
QMetaObject::invokeMethod(m_extractor, "extract", Qt::QueuedConnection,
Q_ARG(QString, filePath), Q_ARG(QString, destination),
Q_ARG(QString, root));
}
QNetworkReply *Application::download(const QUrl &url)
{
static const QString ua = userAgent();
static const QByteArray uaJson = userAgentJson().toUtf8();
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::UserAgentHeader, ua);
if (url.host().endsWith(QLatin1String(".zealdocs.org", Qt::CaseInsensitive)))
request.setRawHeader("X-Zeal-User-Agent", uaJson);
return m_networkManager->get(request);
}
/*!
\internal
Performs a check whether a new Zeal version is available. Setting \a quiet to true suppresses
error and "you are using the latest version" message boxes.
*/
void Application::checkForUpdates(bool quiet)
{
QNetworkReply *reply = download(QUrl(ReleasesApiUrl));
connect(reply, &QNetworkReply::finished, this, [this, quiet]() {
QScopedPointer<QNetworkReply, QScopedPointerDeleteLater> reply(
qobject_cast<QNetworkReply *>(sender()));
if (reply->error() != QNetworkReply::NoError) {
if (!quiet)
emit updateCheckError(reply->errorString());
return;
}
QJsonParseError jsonError;
const QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &jsonError);
if (jsonError.error != QJsonParseError::NoError) {
if (!quiet)
emit updateCheckError(jsonError.errorString());
return;
}
const QJsonObject versionInfo = jsonDoc.array().first().toObject(); // Latest is the first.
const auto latestVersion
= QVersionNumber::fromString(versionInfo[QLatin1String("version")].toString());
if (latestVersion > version()) {
emit updateCheckDone(latestVersion.toString());
} else if (!quiet) {
emit updateCheckDone();
}
});
}
void Application::applySettings()
{
m_docsetRegistry->setStoragePath(m_settings->docsetPath);
m_docsetRegistry->setFuzzySearchEnabled(m_settings->isFuzzySearchEnabled);
// HTTP Proxy Settings
switch (m_settings->proxyType) {
case Settings::ProxyType::None:
QNetworkProxy::setApplicationProxy(QNetworkProxy::NoProxy);
break;
case Settings::ProxyType::System:
QNetworkProxyFactory::setUseSystemConfiguration(true);
break;
case Settings::ProxyType::Http:
case Settings::ProxyType::Socks5: {
const QNetworkProxy::ProxyType type = m_settings->proxyType == Settings::ProxyType::Socks5
? QNetworkProxy::Socks5Proxy
: QNetworkProxy::HttpProxy;
QNetworkProxy proxy(type, m_settings->proxyHost, m_settings->proxyPort);
if (m_settings->proxyAuthenticate) {
proxy.setUser(m_settings->proxyUserName);
proxy.setPassword(m_settings->proxyPassword);
}
QNetworkProxy::setApplicationProxy(proxy);
break;
}
}
// Force NM to pick up changes.
m_networkManager->clearAccessCache();
}
QString Application::userAgent()
{
return QStringLiteral("Zeal/%1").arg(QCoreApplication::applicationVersion());
}
QString Application::userAgentJson() const
{
QJsonObject app = {
{QStringLiteral("version"), QCoreApplication::applicationVersion()},
{QStringLiteral("qt_version"), qVersion()},
{QStringLiteral("install_id"), m_settings->installId}
};
QJsonObject os = {
{QStringLiteral("arch"), QSysInfo::currentCpuArchitecture()},
{QStringLiteral("name"), QSysInfo::prettyProductName()},
{QStringLiteral("product_type"), QSysInfo::productType()},
{QStringLiteral("product_version"), QSysInfo::productVersion()},
{QStringLiteral("kernel_type"), QSysInfo::kernelType()},
{QStringLiteral("kernel_version"), QSysInfo::kernelVersion()},
{QStringLiteral("locale"), QLocale::system().name()}
};
QJsonObject ua = {
{QStringLiteral("app"), app},
{QStringLiteral("os"), os}
};
return QString::fromUtf8(QJsonDocument(ua).toJson(QJsonDocument::Compact));
}
| 8,584
|
C++
|
.cpp
| 243
| 30.201646
| 99
| 0.705492
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,936
|
settings.cpp
|
zealdocs_zeal/src/libs/core/settings.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "settings.h"
#include "application.h"
#include <QApplication>
#include <QDir>
#include <QFileInfo>
#include <QSettings>
#include <QStandardPaths>
#include <QUrl>
#include <QUuid>
#include <QWebEngineProfile>
#include <QWebEngineSettings>
#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
#include <QStyleHints>
#else
#include <QPalette>
#endif
namespace {
// Configuration file groups
constexpr char GroupContent[] = "content";
constexpr char GroupDocsets[] = "docsets";
constexpr char GroupGlobalShortcuts[] = "global_shortcuts";
constexpr char GroupSearch[] = "search";
constexpr char GroupTabs[] = "tabs";
constexpr char GroupInternal[] = "internal";
constexpr char GroupState[] = "state";
constexpr char GroupProxy[] = "proxy";
} // namespace
using namespace Zeal::Core;
Settings::Settings(QObject *parent)
: QObject(parent)
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
qRegisterMetaTypeStreamOperators<ContentAppearance>("ContentAppearance");
qRegisterMetaTypeStreamOperators<ExternalLinkPolicy>("ExternalLinkPolicy");
#else
qRegisterMetaType<ContentAppearance>("ContentAppearance");
qRegisterMetaType<ExternalLinkPolicy>("ExternalLinkPolicy");
#endif
load();
}
Settings::~Settings()
{
save();
}
bool Settings::isDarkModeEnabled() const
{
if (contentAppearance == ContentAppearance::Dark) {
return true;
}
if (contentAppearance == ContentAppearance::Automatic && colorScheme() == ColorScheme::Dark) {
return true;
}
return false;
}
Zeal::Core::Settings::ColorScheme Settings::colorScheme()
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
return QApplication::styleHints()->colorScheme();
#else
// Pre Qt 6.5 detection from https://www.qt.io/blog/dark-mode-on-windows-11-with-qt-6.5.
const QPalette p;
if (p.color(QPalette::WindowText).lightness() > p.color(QPalette::Window).lightness()) {
return ColorScheme::Dark;
}
return ColorScheme::Light;
#endif
}
void Settings::load()
{
QScopedPointer<QSettings> settings(qsettings());
migrate(settings.data());
// TODO: Put everything in groups
startMinimized = settings->value(QStringLiteral("start_minimized"), false).toBool();
checkForUpdate = settings->value(QStringLiteral("check_for_update"), true).toBool();
showSystrayIcon = settings->value(QStringLiteral("show_systray_icon"), true).toBool();
minimizeToSystray = settings->value(QStringLiteral("minimize_to_systray"), false).toBool();
hideOnClose = settings->value(QStringLiteral("hide_on_close"), false).toBool();
settings->beginGroup(GroupGlobalShortcuts);
showShortcut = settings->value(QStringLiteral("show")).value<QKeySequence>();
settings->endGroup();
settings->beginGroup(GroupTabs);
openNewTabAfterActive = settings->value(QStringLiteral("open_new_tab_after_active"), false).toBool();
settings->endGroup();
settings->beginGroup(GroupSearch);
isFuzzySearchEnabled = settings->value(QStringLiteral("fuzzy_search_enabled"), false).toBool();
settings->endGroup();
settings->beginGroup(GroupContent);
contentAppearance = settings->value(QStringLiteral("appearance"),
QVariant::fromValue(ContentAppearance::Automatic)).value<ContentAppearance>();
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) && QT_VERSION < QT_VERSION_CHECK(6, 7, 0)
// Dark mode needs to be applied before Qt WebEngine is initialized.
if (isDarkModeEnabled()) {
qputenv("QTWEBENGINE_CHROMIUM_FLAGS", "--blink-settings=forceDarkModeEnabled=true,darkModeInversionAlgorithm=4");
}
#endif
// Fonts
QWebEngineSettings *webSettings = QWebEngineProfile::defaultProfile()->settings();
serifFontFamily = settings->value(QStringLiteral("serif_font_family"),
webSettings->fontFamily(QWebEngineSettings::SerifFont)).toString();
sansSerifFontFamily = settings->value(QStringLiteral("sans_serif_font_family"),
webSettings->fontFamily(QWebEngineSettings::SansSerifFont)).toString();
fixedFontFamily = settings->value(QStringLiteral("fixed_font_family"),
webSettings->fontFamily(QWebEngineSettings::FixedFont)).toString();
static const QMap<QString, QWebEngineSettings::FontFamily> fontFamilies = {
{QStringLiteral("sans-serif"), QWebEngineSettings::SansSerifFont},
{QStringLiteral("serif"), QWebEngineSettings::SerifFont},
{QStringLiteral("monospace"), QWebEngineSettings::FixedFont}
};
defaultFontFamily = settings->value(QStringLiteral("default_font_family"),
QStringLiteral("serif")).toString();
// Fallback to the serif font family.
if (!fontFamilies.contains(defaultFontFamily)) {
defaultFontFamily = QStringLiteral("serif");
}
webSettings->setFontFamily(QWebEngineSettings::SansSerifFont, sansSerifFontFamily);
webSettings->setFontFamily(QWebEngineSettings::SerifFont, serifFontFamily);
webSettings->setFontFamily(QWebEngineSettings::FixedFont, fixedFontFamily);
const QString defaultFontFamilyResolved = webSettings->fontFamily(fontFamilies.value(defaultFontFamily));
webSettings->setFontFamily(QWebEngineSettings::StandardFont, defaultFontFamilyResolved);
defaultFontSize = settings->value(QStringLiteral("default_font_size"),
webSettings->fontSize(QWebEngineSettings::DefaultFontSize)).toInt();
defaultFixedFontSize = settings->value(QStringLiteral("default_fixed_font_size"),
webSettings->fontSize(QWebEngineSettings::DefaultFixedFontSize)).toInt();
minimumFontSize = settings->value(QStringLiteral("minimum_font_size"),
webSettings->fontSize(QWebEngineSettings::MinimumFontSize)).toInt();
webSettings->setFontSize(QWebEngineSettings::DefaultFontSize, defaultFontSize);
webSettings->setFontSize(QWebEngineSettings::DefaultFixedFontSize, defaultFixedFontSize);
webSettings->setFontSize(QWebEngineSettings::MinimumFontSize, minimumFontSize);
isHighlightOnNavigateEnabled = settings->value(QStringLiteral("highlight_on_navigate"), true).toBool();
customCssFile = settings->value(QStringLiteral("custom_css_file")).toString();
externalLinkPolicy = settings->value(QStringLiteral("external_link_policy"),
QVariant::fromValue(ExternalLinkPolicy::Ask)).value<ExternalLinkPolicy>();
isSmoothScrollingEnabled = settings->value(QStringLiteral("smooth_scrolling"), true).toBool();
settings->endGroup();
settings->beginGroup(GroupProxy);
proxyType = static_cast<ProxyType>(settings->value(QStringLiteral("type"),
ProxyType::System).toUInt());
proxyHost = settings->value(QStringLiteral("host")).toString();
proxyPort = static_cast<quint16>(settings->value(QStringLiteral("port"), 0).toUInt());
proxyAuthenticate = settings->value(QStringLiteral("authenticate"), false).toBool();
proxyUserName = settings->value(QStringLiteral("username")).toString();
proxyPassword = settings->value(QStringLiteral("password")).toString();
isIgnoreSslErrorsEnabled = settings->value(QStringLiteral("ignore_ssl_errors"), false).toBool();
settings->endGroup();
settings->beginGroup(GroupDocsets);
if (settings->contains(QStringLiteral("path"))) {
docsetPath = settings->value(QStringLiteral("path")).toString();
} else {
#ifndef PORTABLE_BUILD
docsetPath = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation)
+ QLatin1String("/docsets");
#else
docsetPath = QStringLiteral("docsets");
#endif
}
settings->endGroup();
// Create the docset storage directory if it doesn't exist.
const QFileInfo fi(docsetPath);
if (!fi.exists()) {
// TODO: Report QDir::mkpath() errors.
if (fi.isRelative()) {
QDir().mkpath(QCoreApplication::applicationDirPath() + "/" + docsetPath);
} else {
QDir().mkpath(docsetPath);
}
}
settings->beginGroup(GroupState);
windowGeometry = settings->value(QStringLiteral("window_geometry")).toByteArray();
verticalSplitterGeometry = settings->value(QStringLiteral("splitter_geometry")).toByteArray();
tocSplitterState = settings->value(QStringLiteral("toc_splitter_state")).toByteArray();
settings->endGroup();
settings->beginGroup(GroupInternal);
installId = settings->value(QStringLiteral("install_id"),
// Avoid curly braces (QTBUG-885)
QUuid::createUuid().toString().mid(1, 36)).toString();
settings->endGroup();
}
void Settings::save()
{
QScopedPointer<QSettings> settings(qsettings());
// TODO: Put everything in groups
settings->setValue(QStringLiteral("start_minimized"), startMinimized);
settings->setValue(QStringLiteral("check_for_update"), checkForUpdate);
settings->setValue(QStringLiteral("show_systray_icon"), showSystrayIcon);
settings->setValue(QStringLiteral("minimize_to_systray"), minimizeToSystray);
settings->setValue(QStringLiteral("hide_on_close"), hideOnClose);
settings->beginGroup(GroupGlobalShortcuts);
settings->setValue(QStringLiteral("show"), showShortcut);
settings->endGroup();
settings->beginGroup(GroupTabs);
settings->setValue(QStringLiteral("open_new_tab_after_active"), openNewTabAfterActive);
settings->endGroup();
settings->beginGroup(GroupSearch);
settings->setValue(QStringLiteral("fuzzy_search_enabled"), isFuzzySearchEnabled);
settings->endGroup();
settings->beginGroup(GroupContent);
settings->setValue(QStringLiteral("default_font_family"), defaultFontFamily);
settings->setValue(QStringLiteral("serif_font_family"), serifFontFamily);
settings->setValue(QStringLiteral("sans_serif_font_family"), sansSerifFontFamily);
settings->setValue(QStringLiteral("fixed_font_family"), fixedFontFamily);
settings->setValue(QStringLiteral("default_font_size"), defaultFontSize);
settings->setValue(QStringLiteral("default_fixed_font_size"), defaultFixedFontSize);
settings->setValue(QStringLiteral("minimum_font_size"), minimumFontSize);
settings->setValue(QStringLiteral("appearance"), QVariant::fromValue(contentAppearance));
settings->setValue(QStringLiteral("highlight_on_navigate"), isHighlightOnNavigateEnabled);
settings->setValue(QStringLiteral("custom_css_file"), customCssFile);
settings->setValue(QStringLiteral("external_link_policy"), QVariant::fromValue(externalLinkPolicy));
settings->setValue(QStringLiteral("smooth_scrolling"), isSmoothScrollingEnabled);
settings->endGroup();
settings->beginGroup(GroupProxy);
settings->setValue(QStringLiteral("type"), proxyType);
settings->setValue(QStringLiteral("host"), proxyHost);
settings->setValue(QStringLiteral("port"), proxyPort);
settings->setValue(QStringLiteral("authenticate"), proxyAuthenticate);
settings->setValue(QStringLiteral("username"), proxyUserName);
settings->setValue(QStringLiteral("password"), proxyPassword);
settings->setValue(QStringLiteral("ignore_ssl_errors"), isIgnoreSslErrorsEnabled);
settings->endGroup();
settings->beginGroup(GroupDocsets);
settings->setValue(QStringLiteral("path"), docsetPath);
settings->endGroup();
settings->beginGroup(GroupState);
settings->setValue(QStringLiteral("window_geometry"), windowGeometry);
settings->setValue(QStringLiteral("splitter_geometry"), verticalSplitterGeometry);
settings->setValue(QStringLiteral("toc_splitter_state"), tocSplitterState);
settings->endGroup();
settings->beginGroup(GroupInternal);
settings->setValue(QStringLiteral("install_id"), installId);
// Version of configuration file format, should match Zeal version. Used for migration rules.
settings->setValue(QStringLiteral("version"), Application::version().toString());
settings->endGroup();
settings->sync();
emit updated();
}
/*!
* \internal
* \brief Migrates settings from older application versions.
* \param settings QSettings object to update.
*
* The settings migration process relies on 'internal/version' option, that was introduced in the
* release 0.2.0, so a missing option indicates pre-0.2 release.
*/
void Settings::migrate(QSettings *settings) const
{
settings->beginGroup(GroupInternal);
const auto version = QVersionNumber::fromString(settings->value(QStringLiteral("version")).toString());
settings->endGroup();
//
// 0.6.0
//
// Unset content.default_fixed_font_size.
// The causing bug was 0.6.1 (#903), but the incorrect setting still comes to haunt us (#1054).
if (version == QVersionNumber(0, 6, 0)) {
settings->beginGroup(GroupContent);
settings->remove(QStringLiteral("default_fixed_font_size"));
settings->endGroup();
}
//
// Pre 0.4
//
// Rename 'browser' group into 'content'.
if (version < QVersionNumber(0, 4, 0)) {
settings->beginGroup(QStringLiteral("browser"));
const QVariant tmpMinimumFontSize = settings->value(QStringLiteral("minimum_font_size"));
settings->endGroup();
settings->remove(QStringLiteral("browser"));
if (tmpMinimumFontSize.isValid()) {
settings->beginGroup(GroupContent);
settings->setValue(QStringLiteral("minimum_font_size"), tmpMinimumFontSize);
settings->endGroup();
}
}
//
// Pre 0.3
//
// Unset 'state/splitter_geometry', because custom styles were removed.
if (version < QVersionNumber(0, 3, 0)) {
settings->beginGroup(GroupState);
settings->remove(QStringLiteral("splitter_geometry"));
settings->endGroup();
}
}
/*!
* \internal
* \brief Returns an initialized QSettings object.
* \param parent Optional parent object.
* \return QSettings object.
*
* QSettings is initialized according to build options, e.g. standard vs portable.
* Caller is responsible for deleting the returned object.
*/
QSettings *Settings::qsettings(QObject *parent)
{
#ifndef PORTABLE_BUILD
return new QSettings(parent);
#else
return new QSettings(QCoreApplication::applicationDirPath() + QLatin1String("/zeal.ini"),
QSettings::IniFormat, parent);
#endif
}
QDataStream &operator<<(QDataStream &out, Settings::ContentAppearance policy)
{
out << static_cast<std::underlying_type<Settings::ContentAppearance>::type>(policy);
return out;
}
QDataStream &operator>>(QDataStream &in, Settings::ContentAppearance &policy)
{
std::underlying_type<Settings::ContentAppearance>::type value;
in >> value;
policy = static_cast<Settings::ContentAppearance>(value);
return in;
}
QDataStream &operator<<(QDataStream &out, Settings::ExternalLinkPolicy policy)
{
out << static_cast<std::underlying_type<Settings::ExternalLinkPolicy>::type>(policy);
return out;
}
QDataStream &operator>>(QDataStream &in, Settings::ExternalLinkPolicy &policy)
{
std::underlying_type<Settings::ExternalLinkPolicy>::type value;
in >> value;
policy = static_cast<Settings::ExternalLinkPolicy>(value);
return in;
}
| 15,528
|
C++
|
.cpp
| 326
| 41.705521
| 121
| 0.718901
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,937
|
httpserver.cpp
|
zealdocs_zeal/src/libs/core/httpserver.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "httpserver.h"
#include "application.h"
#include <httplib.h>
#include <QLoggingCategory>
#include <QRegularExpression>
using namespace Zeal::Core;
namespace {
constexpr char LocalHttpServerHost[] = "127.0.0.1"; // macOS only routes 127.0.0.1 by default.
} // namespace
static Q_LOGGING_CATEGORY(log, "zeal.core.httpserver")
HttpServer::HttpServer(QObject *parent)
: QObject(parent)
{
m_server = std::make_unique<httplib::Server>();
const int port = m_server->bind_to_any_port(LocalHttpServerHost);
m_baseUrl.setScheme(QStringLiteral("http"));
m_baseUrl.setHost(LocalHttpServerHost);
m_baseUrl.setPort(port);
m_server->set_error_handler([](const auto& req, auto& res) {
const QString html = QStringLiteral("<b>ERROR %1</b><br><pre>Request path: %2</pre>")
.arg(res.status)
.arg(QString::fromStdString(req.path));
res.set_content(html.toUtf8().data(), "text/html");
});
m_future = std::async(std::launch::async, &httplib::Server::listen_after_bind, m_server.get());
qCDebug(log, "Listening on %s...", qPrintable(m_baseUrl.toString()));
}
HttpServer::~HttpServer()
{
m_server->stop();
auto status = m_future.wait_for(std::chrono::seconds(2));
if (status != std::future_status::ready) {
qCWarning(log) << "Failed to stop server within timeout.";
}
}
QUrl HttpServer::baseUrl() const
{
return m_baseUrl;
}
QUrl HttpServer::mount(const QString &prefix, const QString &path)
{
const QString pfx = sanitizePrefix(prefix);
const bool ok = m_server->set_mount_point(pfx.toStdString(), path.toStdString());
if (!ok) {
qCWarning(log, "Failed to mount '%s' to '%s'.", qPrintable(path), qPrintable(pfx));
return QUrl();
}
qCDebug(log, "Mounted '%s' to '%s'.", qPrintable(path), qPrintable(pfx));
QUrl mountUrl = m_baseUrl;
mountUrl.setPath(m_baseUrl.path() + pfx);
return mountUrl;
}
bool HttpServer::unmount(const QString &prefix)
{
const QString pfx = sanitizePrefix(prefix);
const bool ok = m_server->remove_mount_point(pfx.toStdString());
if (!ok) {
qCWarning(log, "Failed to unmount '%s' to '%s'.", qPrintable(prefix), qPrintable(pfx));
}
qCDebug(log, "Unmounted prefix '%s' ('%s').", qPrintable(prefix), qPrintable(pfx));
return ok;
}
QString HttpServer::sanitizePrefix(const QString &prefix)
{
QString pfx = (prefix.startsWith(QLatin1String("/")) ? prefix.right(1) : prefix).toLower();
pfx.replace(QRegularExpression(QStringLiteral("[^a-zA-Z0-9-_]")), QStringLiteral("_"));
pfx.prepend(QLatin1Char('/'));
return pfx;
}
| 2,764
|
C++
|
.cpp
| 71
| 34.605634
| 99
| 0.675534
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,938
|
filemanager.cpp
|
zealdocs_zeal/src/libs/core/filemanager.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "filemanager.h"
#include "application.h"
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QFileInfo>
#include <QFutureWatcher>
#include <QLoggingCategory>
#include <future>
using namespace Zeal::Core;
static Q_LOGGING_CATEGORY(log, "zeal.core.filemanager")
FileManager::FileManager(QObject *parent)
: QObject(parent)
{
// Ensure that cache location exists.
// TODO: Check for errors.
QDir().mkpath(Application::cacheLocation());
}
bool FileManager::removeRecursively(const QString &path)
{
qCDebug(log, "Removing '%s'...", qPrintable(path));
if (!QFileInfo(path).isDir()) {
qCWarning(log, "'%s' is not a directory.", qPrintable(path));
return false;
}
const QString deletePath = QStringLiteral("%1.%2.deleteme")
.arg(path, QString::number(QDateTime::currentMSecsSinceEpoch()));
if (!QDir().rename(path, deletePath)) {
qCWarning(log, "Failed to rename '%s' to '%s'.", qPrintable(path), qPrintable(deletePath));
return false;
}
qCDebug(log, "Renamed '%s' to '%s'.", qPrintable(path), qPrintable(deletePath));
std::future<bool> f = std::async(std::launch::async, [deletePath](){
return QDir(deletePath).removeRecursively();
});
f.wait();
if (!f.get()) {
qCWarning(log, "Failed to remove '%s'.", qPrintable(deletePath));
} else {
qCDebug(log, "Removed '%s'.", qPrintable(deletePath));
}
return true;
}
| 1,596
|
C++
|
.cpp
| 45
| 31
| 99
| 0.671661
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,939
|
networkaccessmanager.cpp
|
zealdocs_zeal/src/libs/core/networkaccessmanager.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "networkaccessmanager.h"
#include "application.h"
#include "httpserver.h"
#include <QNetworkRequest>
using namespace Zeal::Core;
NetworkAccessManager::NetworkAccessManager(QObject *parent)
: QNetworkAccessManager(parent)
{
}
bool NetworkAccessManager::isLocalFile(const QUrl &url)
{
return url.isLocalFile() || url.scheme() == QLatin1String("qrc");
}
bool NetworkAccessManager::isLocalUrl(const QUrl &url)
{
if (isLocalFile(url)) {
return true;
}
const QUrl &baseUrl = Application::instance()->httpServer()->baseUrl();
if (baseUrl.isParentOf(url)) {
return true;
}
return false;
}
QNetworkReply *NetworkAccessManager::createRequest(QNetworkAccessManager::Operation op,
const QNetworkRequest &request,
QIODevice *outgoingData)
{
QNetworkRequest overrideRequest(request);
overrideRequest.setAttribute(QNetworkRequest::RedirectPolicyAttribute, true);
// Forward all non-local schemaless URLs via HTTPS.
const QUrl url = request.url();
if (isLocalFile(url) && !url.host().isEmpty()) {
QUrl overrideUrl(url);
overrideUrl.setScheme(QStringLiteral("https"));
overrideRequest.setUrl(overrideUrl);
op = QNetworkAccessManager::GetOperation;
}
QSslConfiguration sslConfig = overrideRequest.sslConfiguration();
sslConfig.setCaCertificates(QSslConfiguration::systemCaCertificates());
overrideRequest.setSslConfiguration(sslConfig);
return QNetworkAccessManager::createRequest(op, overrideRequest, outgoingData);
}
| 1,754
|
C++
|
.cpp
| 45
| 32.711111
| 87
| 0.710153
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,940
|
extractor.cpp
|
zealdocs_zeal/src/libs/core/extractor.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "extractor.h"
#include <QDir>
#include <archive.h>
#include <archive_entry.h>
#include <sys/stat.h>
using namespace Zeal::Core;
Extractor::Extractor(QObject *parent)
: QObject(parent)
{
}
void Extractor::extract(const QString &sourceFile, const QString &destination, const QString &root)
{
ExtractInfo info = {
archive_read_new(), // archiveHandle
sourceFile, // filePath
QFileInfo(sourceFile).size(), // totalBytes
0 // extractedBytes
};
archive_read_support_filter_all(info.archiveHandle);
archive_read_support_format_all(info.archiveHandle);
int r = archive_read_open_filename(info.archiveHandle, qPrintable(sourceFile), 10240);
if (r) {
emit error(sourceFile, QString::fromLocal8Bit(archive_error_string(info.archiveHandle)));
return;
}
QDir destinationDir(destination);
if (!root.isEmpty()) {
destinationDir.setPath(destinationDir.filePath(root));
}
// Destination directory must be created before any other files.
destinationDir.mkpath(QLatin1String("."));
// TODO: Do not strip root directory in archive if it equals to 'root'
archive_entry *entry;
while (archive_read_next_header(info.archiveHandle, &entry) == ARCHIVE_OK) {
// See https://github.com/libarchive/libarchive/issues/587 for more on UTF-8.
QString pathname = QString::fromUtf8(archive_entry_pathname_utf8(entry));
if (!root.isEmpty()) {
pathname.remove(0, pathname.indexOf(QLatin1String("/")) + 1);
}
const QString filePath = destinationDir.absoluteFilePath(pathname);
const auto filetype = archive_entry_filetype(entry);
if (filetype == S_IFDIR) {
QDir().mkpath(QFileInfo(filePath).absolutePath());
continue;
}
if (filetype != S_IFREG) {
qWarning("Unsupported filetype %d for %s!", filetype, qPrintable(pathname));
continue;
}
QScopedPointer<QFile> file(new QFile(filePath));
if (!file->open(QIODevice::WriteOnly)) {
qWarning("Cannot open file for writing: %s", qPrintable(pathname));
continue;
}
const void *buffer;
size_t size;
std::int64_t offset;
for (;;) {
int rc = archive_read_data_block(info.archiveHandle, &buffer, &size, &offset);
if (rc != ARCHIVE_OK) {
if (rc == ARCHIVE_EOF) {
break;
}
qWarning("Cannot read from archive: %s", archive_error_string(info.archiveHandle));
emit error(sourceFile,
QString::fromLocal8Bit(archive_error_string(info.archiveHandle)));
return;
}
file->write(static_cast<const char *>(buffer), size);
}
emitProgress(info);
}
emit completed(sourceFile);
archive_read_free(info.archiveHandle);
}
void Extractor::emitProgress(ExtractInfo &info)
{
const qint64 extractedBytes = archive_filter_bytes(info.archiveHandle, -1);
if (extractedBytes == info.extractedBytes) {
return;
}
info.extractedBytes = extractedBytes;
emit progress(info.filePath, extractedBytes, info.totalBytes);
}
| 3,454
|
C++
|
.cpp
| 86
| 32.232558
| 99
| 0.629674
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,941
|
searchitemdelegate.cpp
|
zealdocs_zeal/src/libs/ui/searchitemdelegate.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include "searchitemdelegate.h"
#include <QAbstractItemView>
#include <QFontMetrics>
#include <QHelpEvent>
#include <QPainter>
#include <QPainterPath>
#include <QToolTip>
using namespace Zeal::WidgetUi;
SearchItemDelegate::SearchItemDelegate(QObject *parent)
: QStyledItemDelegate(parent)
{
}
QList<int> SearchItemDelegate::decorationRoles() const
{
return m_decorationRoles;
}
void SearchItemDelegate::setDecorationRoles(const QList<int> &roles)
{
m_decorationRoles = roles;
}
bool SearchItemDelegate::helpEvent(QHelpEvent *event, QAbstractItemView *view,
const QStyleOptionViewItem &option, const QModelIndex &index)
{
if (event->type() != QEvent::ToolTip)
return QStyledItemDelegate::helpEvent(event, view, option, index);
if (sizeHint(option, index).width() < view->visualRect(index).width()) {
QToolTip::hideText();
return QStyledItemDelegate::helpEvent(event, view, option, index);
}
QToolTip::showText(event->globalPos(), index.data().toString(), view);
return true;
}
void SearchItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QStyleOptionViewItem opt(option);
QStyle *style = opt.widget->style();
// Find decoration roles with data present.
QList<int> roles;
for (int role : m_decorationRoles) {
if (!index.data(role).isNull())
roles.append(role);
}
// TODO: Implemented via initStyleOption() overload
if (!roles.isEmpty()) {
opt.features |= QStyleOptionViewItem::HasDecoration;
opt.icon = index.data(roles.first()).value<QIcon>();
const QSize actualSize = opt.icon.actualSize(opt.decorationSize);
opt.decorationSize = {std::min(opt.decorationSize.width(), actualSize.width()),
std::min(opt.decorationSize.height(), actualSize.height())};
}
style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget);
const int margin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, &opt, opt.widget) + 1;
if (!roles.isEmpty()) {
QIcon::Mode mode = QIcon::Normal;
if (!(opt.state & QStyle::State_Enabled))
mode = QIcon::Disabled;
else if (opt.state & QStyle::State_Selected)
mode = QIcon::Selected;
const QIcon::State state = (opt.state & QStyle::State_Open) ? QIcon::On : QIcon::Off;
// All icons are sized after the first one.
QRect iconRect = style->subElementRect(QStyle::SE_ItemViewItemDecoration, &opt, opt.widget);
// Undo RTL mirroring
iconRect = style->visualRect(opt.direction, opt.rect, iconRect);
const int dx = iconRect.width() + margin;
for (int i = 1; i < roles.size(); ++i) {
opt.decorationSize.rwidth() += dx;
iconRect.translate(dx, 0);
// Redo RTL mirroring
const auto iconVisualRect = style->visualRect(opt.direction, opt.rect, iconRect);
const QIcon icon = index.data(roles[i]).value<QIcon>();
icon.paint(painter, iconVisualRect, opt.decorationAlignment, mode, state);
}
}
// This should not happen unless a docset is corrupted.
if (index.data().isNull())
return;
// Match QCommonStyle behaviour.
opt.features |= QStyleOptionViewItem::HasDisplay;
opt.text = index.data().toString();
const QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &opt, opt.widget)
.adjusted(margin, 0, -margin, 0);
const QFontMetrics &fm = opt.fontMetrics;
const QString elidedText = fm.elidedText(opt.text, opt.textElideMode, textRect.width());
if (!m_highlight.isEmpty()) {
painter->save();
painter->setRenderHint(QPainter::Antialiasing);
painter->setPen(QColor::fromRgb(255, 253, 0));
const QColor highlightColor
= (opt.state & (QStyle::State_Selected | QStyle::State_HasFocus))
? QColor::fromRgb(255, 255, 100, 20) : QColor::fromRgb(255, 255, 100, 120);
for (int i = 0;;) {
const int matchIndex = opt.text.indexOf(m_highlight, i, Qt::CaseInsensitive);
if (matchIndex == -1 || matchIndex >= elidedText.length() - 1)
break;
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
QRect highlightRect = textRect.adjusted(fm.horizontalAdvance(elidedText.left(matchIndex)), 2, 0, -2);
highlightRect.setWidth(fm.horizontalAdvance(elidedText.mid(matchIndex, m_highlight.length())));
#else
QRect highlightRect = textRect.adjusted(fm.width(elidedText.left(matchIndex)), 2, 0, -2);
highlightRect.setWidth(fm.width(elidedText.mid(matchIndex, m_highlight.length())));
#endif
QPainterPath path;
path.addRoundedRect(highlightRect, 2, 2);
painter->fillPath(path, highlightColor);
painter->drawPath(path);
i = matchIndex + m_highlight.length();
}
painter->restore();
}
painter->save();
#ifdef Q_OS_WIN32
// QWindowsVistaStyle overrides highlight colour.
if (style->objectName() == QLatin1String("windowsvista")) {
opt.palette.setColor(QPalette::All, QPalette::HighlightedText,
opt.palette.color(QPalette::Active, QPalette::Text));
}
#endif
const QPalette::ColorGroup cg = (opt.state & QStyle::State_Active)
? QPalette::Normal : QPalette::Inactive;
if (opt.state & QStyle::State_Selected)
painter->setPen(opt.palette.color(cg, QPalette::HighlightedText));
else
painter->setPen(opt.palette.color(cg, QPalette::Text));
// Constant LeftToRight because we don't need to flip it any further.
// Vertically align the text in the middle to match QCommonStyle behaviour.
const auto alignedRect = QStyle::alignedRect(Qt::LeftToRight, opt.displayAlignment,
QSize(textRect.size().width(), fm.height()), textRect);
const auto textPoint = QPoint(alignedRect.x(), alignedRect.y() + fm.ascent());
// Force LTR, so that BiDi won't reorder ellipsis to the left.
painter->drawText(textPoint, elidedText, Qt::TextFlag::TextForceLeftToRight, 0);
painter->restore();
}
QSize SearchItemDelegate::sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QStyleOptionViewItem opt(option);
QStyle *style = opt.widget->style();
QSize size = QStyledItemDelegate::sizeHint(opt, index);
size.setWidth(0);
const int margin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, &opt, opt.widget) + 1;
// Find decoration roles with data present.
QList<int> roles;
for (int role : m_decorationRoles) {
if (!index.data(role).isNull())
roles.append(role);
}
if (!roles.isEmpty()) {
const QIcon icon = index.data(roles.first()).value<QIcon>();
const QSize actualSize = icon.actualSize(opt.decorationSize);
const int decorationWidth = std::min(opt.decorationSize.width(), actualSize.width());
size.rwidth() = (decorationWidth + margin) * roles.size() + margin;
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
size.rwidth() += opt.fontMetrics.horizontalAdvance(index.data().toString()) + margin * 2;
#else
size.rwidth() += opt.fontMetrics.width(index.data().toString()) + margin * 2;
#endif
return size;
}
void SearchItemDelegate::setHighlight(const QString &text)
{
m_highlight = text;
}
| 7,769
|
C++
|
.cpp
| 167
| 38.964072
| 113
| 0.659788
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,942
|
aboutdialog.cpp
|
zealdocs_zeal/src/libs/ui/aboutdialog.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "aboutdialog.h"
#include "ui_aboutdialog.h"
#include <core/application.h>
using namespace Zeal::WidgetUi;
AboutDialog::AboutDialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::AboutDialog)
{
ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
ui->versionLabel->setText(Core::Application::versionString());
ui->buttonBox->setFocus(Qt::OtherFocusReason);
}
AboutDialog::~AboutDialog()
{
delete ui;
}
| 584
|
C++
|
.cpp
| 19
| 27.947368
| 69
| 0.738819
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,943
|
docsetsdialog.cpp
|
zealdocs_zeal/src/libs/ui/docsetsdialog.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include "docsetsdialog.h"
#include "ui_docsetsdialog.h"
#include "docsetlistitemdelegate.h"
#include <core/application.h>
#include <core/filemanager.h>
#include <core/settings.h>
#include <registry/docset.h>
#include <registry/docsetregistry.h>
#include <registry/itemdatarole.h>
#include <QClipboard>
#include <QDateTime>
#include <QDir>
#include <QInputDialog>
#include <QJsonArray>
#include <QJsonDocument>
#include <QLocale>
#include <QMessageBox>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QTemporaryFile>
#include <QUrl>
#include <memory>
using namespace Zeal;
using namespace Zeal::WidgetUi;
#ifdef Q_OS_WIN32
extern Q_CORE_EXPORT int qt_ntfs_permission_lookup;
#endif
namespace {
constexpr char ApiServerUrl[] = "https://api.zealdocs.org/v1";
constexpr char RedirectServerUrl[] = "https://go.zealdocs.org/d/%1/%2/latest";
// TODO: Each source plugin should have its own cache
constexpr char DocsetListCacheFileName[] = "com.kapeli.json";
// TODO: Make the timeout period configurable
constexpr int CacheTimeout = 24 * 60 * 60 * 1000; // 24 hours in microseconds
// QNetworkReply properties
constexpr char DocsetNameProperty[] = "docsetName";
constexpr char DownloadTypeProperty[] = "downloadType";
constexpr char ListItemIndexProperty[] = "listItem";
} // namespace
DocsetsDialog::DocsetsDialog(Core::Application *app, QWidget *parent)
: QDialog(parent)
, ui(new Ui::DocsetsDialog())
, m_application(app)
, m_docsetRegistry(app->docsetRegistry())
{
ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
loadDocsetList();
m_isStorageReadOnly = !isDirWritable(m_application->settings()->docsetPath);
#ifdef Q_OS_MACOS
ui->availableDocsetList->setAttribute(Qt::WA_MacShowFocusRect, false);
ui->installedDocsetList->setAttribute(Qt::WA_MacShowFocusRect, false);
#endif
ui->statusLabel->clear(); // Clear text shown in the designer mode.
ui->storageStatusLabel->setVisible(m_isStorageReadOnly);
const QFileInfo fi(m_application->settings()->docsetPath);
ui->storageStatusLabel->setText(fi.exists() ? tr("<b>Docset storage is read only.</b>")
: tr("<b>Docset storage does not exist.</b>"));
connect(m_application, &Core::Application::extractionCompleted,
this, &DocsetsDialog::extractionCompleted);
connect(m_application, &Core::Application::extractionError,
this, &DocsetsDialog::extractionError);
connect(m_application, &Core::Application::extractionProgress,
this, &DocsetsDialog::extractionProgress);
// Setup signals & slots
connect(ui->buttonBox, &QDialogButtonBox::clicked, this, [this](QAbstractButton *button) {
if (button == ui->buttonBox->button(QDialogButtonBox::Cancel)) {
cancelDownloads();
return;
}
if (button == ui->buttonBox->button(QDialogButtonBox::Close)) {
close();
return;
}
});
setupInstalledDocsetsTab();
setupAvailableDocsetsTab();
if (m_isStorageReadOnly) {
disableControls();
}
}
DocsetsDialog::~DocsetsDialog()
{
delete ui;
}
void DocsetsDialog::addDashFeed()
{
QString clipboardText = QApplication::clipboard()->text();
if (!clipboardText.startsWith(QLatin1String("dash-feed://")))
clipboardText.clear();
QString feedUrl = QInputDialog::getText(this, QStringLiteral("Zeal"), tr("Feed URL:"),
QLineEdit::Normal, clipboardText);
feedUrl = feedUrl.trimmed();
if (feedUrl.isEmpty())
return;
if (feedUrl.startsWith(QLatin1String("dash-feed://"))) {
feedUrl = feedUrl.remove(0, 12);
feedUrl = QUrl::fromPercentEncoding(feedUrl.toUtf8());
}
QNetworkReply *reply = download(QUrl(feedUrl));
reply->setProperty(DownloadTypeProperty, DownloadDashFeed);
}
void DocsetsDialog::updateSelectedDocsets()
{
const auto selectedRows = ui->installedDocsetList->selectionModel()->selectedRows();
for (const QModelIndex &index : selectedRows) {
if (!index.data(Registry::ItemDataRole::UpdateAvailableRole).toBool())
continue;
downloadDashDocset(index);
}
}
void DocsetsDialog::updateAllDocsets()
{
QAbstractItemModel *model = ui->installedDocsetList->model();
for (int i = 0; i < model->rowCount(); ++i) {
const QModelIndex index = model->index(i, 0);
if (!index.data(Registry::ItemDataRole::UpdateAvailableRole).toBool())
continue;
downloadDashDocset(index);
}
}
void DocsetsDialog::removeSelectedDocsets()
{
QItemSelectionModel *selectionModel = ui->installedDocsetList->selectionModel();
if (!selectionModel->hasSelection())
return;
int ret;
const QModelIndexList selectedIndexes = selectionModel->selectedRows();
if (selectedIndexes.size() == 1) {
const QString docsetTitle = selectedIndexes.first().data().toString();
ret = QMessageBox::question(this, QStringLiteral("Zeal"),
tr("Remove <b>%1</b> docset?").arg(docsetTitle));
} else {
ret = QMessageBox::question(this, QStringLiteral("Zeal"),
tr("Remove <b>%n</b> docset(s)?", nullptr,
selectedIndexes.size()));
}
if (ret == QMessageBox::No) {
return;
}
// Gather names first, because model indicies become invalid when docsets are removed.
QStringList names;
for (const QModelIndex &index : selectedIndexes) {
names.append(index.data(Registry::ItemDataRole::DocsetNameRole).toString());
}
for (const QString &name : names) {
removeDocset(name);
}
}
void DocsetsDialog::updateDocsetFilter(const QString &filterString)
{
const bool doSearch = !filterString.simplified().isEmpty();
for (int i = 0; i < ui->availableDocsetList->count(); ++i) {
QListWidgetItem *item = ui->availableDocsetList->item(i);
// Skip installed docsets
if (m_docsetRegistry->contains(item->data(Registry::ItemDataRole::DocsetNameRole).toString()))
continue;
item->setHidden(doSearch && !item->text().contains(filterString, Qt::CaseInsensitive));
}
}
void DocsetsDialog::downloadSelectedDocsets()
{
QItemSelectionModel *selectionModel = ui->availableDocsetList->selectionModel();
const auto selectedRows = selectionModel->selectedRows();
for (const QModelIndex &index : selectedRows) {
selectionModel->select(index, QItemSelectionModel::Deselect);
// Do nothing if a download is already in progress.
if (index.data(DocsetListItemDelegate::ShowProgressRole).toBool())
continue;
QAbstractItemModel *model = ui->availableDocsetList->model();
model->setData(index, tr("Downloading: %p%"), DocsetListItemDelegate::FormatRole);
model->setData(index, 0, DocsetListItemDelegate::ValueRole);
model->setData(index, true, DocsetListItemDelegate::ShowProgressRole);
downloadDashDocset(index);
}
}
/*!
\internal
Should be connected to all \l QNetworkReply::finished signals in order to process possible
HTTP-redirects correctly.
*/
void DocsetsDialog::downloadCompleted()
{
QScopedPointer<QNetworkReply, QScopedPointerDeleteLater> reply(
qobject_cast<QNetworkReply *>(sender()));
m_replies.removeOne(reply.data());
if (reply->error() != QNetworkReply::NoError) {
if (reply->error() != QNetworkReply::OperationCanceledError) {
const QString msg = tr("Download failed!<br><br><b>Error:</b> %1<br><b>URL:</b> %2")
.arg(reply->errorString(), reply->request().url().toString());
const int ret = QMessageBox::warning(this, QStringLiteral("Zeal"), msg,
QMessageBox::Retry | QMessageBox::Cancel);
if (ret == QMessageBox::Retry) {
QNetworkReply *newReply = download(reply->request().url());
// Copy properties
newReply->setProperty(DocsetNameProperty, reply->property(DocsetNameProperty));
newReply->setProperty(DownloadTypeProperty, reply->property(DownloadTypeProperty));
newReply->setProperty(ListItemIndexProperty,
reply->property(ListItemIndexProperty));
return;
}
bool ok;
QListWidgetItem *listItem = ui->availableDocsetList->item(
reply->property(ListItemIndexProperty).toInt(&ok));
if (ok && listItem)
listItem->setData(DocsetListItemDelegate::ShowProgressRole, false);
}
updateStatus();
return;
}
switch (reply->property(DownloadTypeProperty).toUInt()) {
case DownloadDocsetList: {
const QByteArray data = reply->readAll();
QScopedPointer<QFile> file(new QFile(cacheLocation(DocsetListCacheFileName)));
if (file->open(QIODevice::WriteOnly))
file->write(data);
const QString updateTime = QFileInfo(file->fileName())
.lastModified().toString(QLocale::system().dateTimeFormat(QLocale::ShortFormat));
ui->lastUpdatedLabel->setText(updateTime);
QJsonParseError jsonError;
const QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError);
if (jsonError.error != QJsonParseError::NoError) {
// TODO: Log QJsonParseError.
const QMessageBox::StandardButton rc
= QMessageBox::warning(this, QStringLiteral("Zeal"),
tr("Server returned a corrupted docset list."),
QMessageBox::Retry | QMessageBox::Cancel);
if (rc == QMessageBox::Retry) {
downloadDocsetList();
}
break;
}
processDocsetList(jsonDoc.array());
break;
}
case DownloadDashFeed: {
Registry::DocsetMetadata metadata
= Registry::DocsetMetadata::fromDashFeed(reply->request().url(), reply->readAll());
if (metadata.urls().isEmpty()) {
QMessageBox::warning(this, QStringLiteral("Zeal"), tr("Invalid docset feed!"));
break;
}
m_userFeeds[metadata.name()] = metadata;
Registry::Docset *docset = m_docsetRegistry->docset(metadata.name());
if (docset == nullptr) {
// Fetch docset only on first feed download,
// since further downloads are only update checks
QNetworkReply *reply = download(metadata.url());
reply->setProperty(DocsetNameProperty, metadata.name());
reply->setProperty(DownloadTypeProperty, DownloadDocset);
} else {
// Check for feed update
if (metadata.latestVersion() != docset->version()
|| metadata.revision() > docset->revision()) {
docset->hasUpdate = true;
if (!m_isStorageReadOnly) {
ui->updateAllDocsetsButton->setEnabled(true);
}
ui->installedDocsetList->reset();
}
}
break;
}
case DownloadDocset: {
const QString docsetName = reply->property(DocsetNameProperty).toString();
const QString docsetDirectoryName = docsetName + QLatin1String(".docset");
if (QDir(m_application->settings()->docsetPath).exists(docsetDirectoryName)) {
removeDocset(docsetName);
}
QTemporaryFile *tmpFile = m_tmpFiles[docsetName];
if (!tmpFile) {
tmpFile = new QTemporaryFile(QStringLiteral("%1/%2.XXXXXX.tmp").arg(Core::Application::cacheLocation(), docsetName), this);
tmpFile->open();
m_tmpFiles.insert(docsetName, tmpFile);
}
while (reply->bytesAvailable()) {
tmpFile->write(reply->read(1024 * 1024)); // Use small chunks.
}
tmpFile->close();
QListWidgetItem *item = findDocsetListItem(docsetName);
if (item) {
item->setData(DocsetListItemDelegate::ValueRole, 0);
item->setData(DocsetListItemDelegate::FormatRole, tr("Installing: %p%"));
}
m_application->extract(tmpFile->fileName(), m_application->settings()->docsetPath,
docsetDirectoryName);
break;
}
}
// If all enqueued downloads have finished executing.
updateStatus();
}
// creates a total download progress for multiple QNetworkReplies
void DocsetsDialog::downloadProgress(qint64 received, qint64 total)
{
// Don't show progress for non-docset pages
if (total == -1 || received < 10240)
return;
auto reply = qobject_cast<QNetworkReply *>(sender());
if (!reply || !reply->isOpen())
return;
if (reply->property(DownloadTypeProperty).toInt() == DownloadDocset) {
const QString docsetName = reply->property(DocsetNameProperty).toString();
QTemporaryFile *tmpFile = m_tmpFiles[docsetName];
if (!tmpFile) {
tmpFile = new QTemporaryFile(QStringLiteral("%1/%2.XXXXXX.tmp").arg(Core::Application::cacheLocation(), docsetName), this);
tmpFile->open();
m_tmpFiles.insert(docsetName, tmpFile);
}
tmpFile->write(reply->read(received));
}
// Try to get the item associated to the request
QListWidgetItem *item
= ui->availableDocsetList->item(reply->property(ListItemIndexProperty).toInt());
if (item) {
item->setData(DocsetListItemDelegate::ValueRole, percent(received, total));
}
}
void DocsetsDialog::extractionCompleted(const QString &filePath)
{
const QString docsetName = docsetNameForTmpFilePath(filePath);
const QDir dataDir(m_application->settings()->docsetPath);
const QString docsetPath = dataDir.filePath(docsetName + QLatin1String(".docset"));
// Write metadata about docset
Registry::DocsetMetadata metadata = m_availableDocsets.count(docsetName)
? m_availableDocsets[docsetName] : m_userFeeds[docsetName];
metadata.save(docsetPath, metadata.latestVersion());
m_docsetRegistry->loadDocset(docsetPath);
QListWidgetItem *listItem = findDocsetListItem(docsetName);
if (listItem) {
listItem->setHidden(true);
listItem->setData(DocsetListItemDelegate::ShowProgressRole, false);
}
delete m_tmpFiles.take(docsetName);
updateStatus();
}
void DocsetsDialog::extractionError(const QString &filePath, const QString &errorString)
{
const QString docsetName = docsetNameForTmpFilePath(filePath);
QMessageBox::warning(this, QStringLiteral("Zeal"),
tr("Cannot extract docset <b>%1</b>: %2").arg(docsetName, errorString));
QListWidgetItem *listItem = findDocsetListItem(docsetName);
if (listItem)
listItem->setData(DocsetListItemDelegate::ShowProgressRole, false);
delete m_tmpFiles.take(docsetName);
}
void DocsetsDialog::extractionProgress(const QString &filePath, qint64 extracted, qint64 total)
{
const QString docsetName = docsetNameForTmpFilePath(filePath);
QListWidgetItem *listItem = findDocsetListItem(docsetName);
if (listItem)
listItem->setData(DocsetListItemDelegate::ValueRole, percent(extracted, total));
}
void DocsetsDialog::loadDocsetList()
{
loadUserFeedList();
const QFileInfo fi(cacheLocation(DocsetListCacheFileName));
if (!fi.exists() || fi.lastModified().msecsTo(QDateTime::currentDateTime()) > CacheTimeout) {
downloadDocsetList();
return;
}
QScopedPointer<QFile> file(new QFile(fi.filePath()));
if (!file->open(QIODevice::ReadOnly)) {
downloadDocsetList();
return;
}
QJsonParseError jsonError;
const QJsonDocument jsonDoc = QJsonDocument::fromJson(file->readAll(), &jsonError);
if (jsonError.error != QJsonParseError::NoError) {
downloadDocsetList();
return;
}
// TODO: Show more user friendly labels, like "5 hours ago"
const QString updateTime
= fi.lastModified().toString(QLocale::system().dateTimeFormat(QLocale::ShortFormat));
ui->lastUpdatedLabel->setText(updateTime);
processDocsetList(jsonDoc.array());
}
void DocsetsDialog::setupInstalledDocsetsTab()
{
ui->installedDocsetList->setItemDelegate(new DocsetListItemDelegate(this));
ui->installedDocsetList->setModel(m_docsetRegistry->model());
ui->installedDocsetList->setItemsExpandable(false);
ui->installedDocsetList->setRootIsDecorated(false);
ui->installedDocsetList->header()->setStretchLastSection(true);
ui->installedDocsetList->header()->setSectionsMovable(false);
ui->installedDocsetList->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
ui->installedDocsetList->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
if (m_isStorageReadOnly) {
return;
}
connect(ui->installedDocsetList, &QTreeView::activated, this, [this](const QModelIndex &index) {
if (!index.data(Registry::ItemDataRole::UpdateAvailableRole).toBool()) {
return;
}
downloadDashDocset(index);
});
QItemSelectionModel *selectionModel = ui->installedDocsetList->selectionModel();
connect(selectionModel, &QItemSelectionModel::selectionChanged,
this, [this, selectionModel]() {
ui->removeDocsetsButton->setEnabled(selectionModel->hasSelection());
const auto selectedRows = selectionModel->selectedRows();
for (const QModelIndex &index : selectedRows) {
if (index.data(Registry::ItemDataRole::UpdateAvailableRole).toBool()) {
ui->updateSelectedDocsetsButton->setEnabled(true);
return;
}
}
ui->updateSelectedDocsetsButton->setEnabled(false);
});
connect(ui->addFeedButton, &QPushButton::clicked, this, &DocsetsDialog::addDashFeed);
connect(ui->updateSelectedDocsetsButton, &QPushButton::clicked,
this, &DocsetsDialog::updateSelectedDocsets);
connect(ui->updateAllDocsetsButton, &QPushButton::clicked,
this, &DocsetsDialog::updateAllDocsets);
connect(ui->removeDocsetsButton, &QPushButton::clicked,
this, &DocsetsDialog::removeSelectedDocsets);
}
void DocsetsDialog::setupAvailableDocsetsTab()
{
using Registry::DocsetRegistry;
ui->availableDocsetList->setItemDelegate(new DocsetListItemDelegate(this));
connect(m_docsetRegistry, &DocsetRegistry::docsetUnloaded, this, [this](const QString &name) {
QListWidgetItem *item = findDocsetListItem(name);
if (!item)
return;
item->setHidden(false);
});
connect(m_docsetRegistry, &DocsetRegistry::docsetLoaded, this, [this](const QString &name) {
QListWidgetItem *item = findDocsetListItem(name);
if (!item)
return;
item->setHidden(true);
});
connect(ui->refreshButton, &QPushButton::clicked, this, &DocsetsDialog::downloadDocsetList);
connect(ui->docsetFilterInput, &QLineEdit::textEdited,
this, &DocsetsDialog::updateDocsetFilter);
if (m_isStorageReadOnly) {
return;
}
connect(ui->availableDocsetList, &QListView::activated, this, [this](const QModelIndex &index) {
// TODO: Cancel download if it's already in progress.
if (index.data(DocsetListItemDelegate::ShowProgressRole).toBool())
return;
ui->availableDocsetList->selectionModel()->select(index, QItemSelectionModel::Deselect);
QAbstractItemModel *model = ui->availableDocsetList->model();
model->setData(index, tr("Downloading: %p%"), DocsetListItemDelegate::FormatRole);
model->setData(index, 0, DocsetListItemDelegate::ValueRole);
model->setData(index, true, DocsetListItemDelegate::ShowProgressRole);
downloadDashDocset(index);
});
QItemSelectionModel *selectionModel = ui->availableDocsetList->selectionModel();
connect(selectionModel, &QItemSelectionModel::selectionChanged, this, [this, selectionModel]() {
const auto selectedRows = selectionModel->selectedRows();
for (const QModelIndex &index : selectedRows) {
if (!index.data(DocsetListItemDelegate::ShowProgressRole).toBool()) {
ui->downloadDocsetsButton->setEnabled(true);
return;
}
}
ui->downloadDocsetsButton->setEnabled(false);
});
connect(ui->downloadDocsetsButton, &QPushButton::clicked,
this, &DocsetsDialog::downloadSelectedDocsets);
}
void DocsetsDialog::enableControls()
{
if (m_isStorageReadOnly || !m_replies.isEmpty() || !m_tmpFiles.isEmpty()) {
return;
}
// Dialog buttons.
ui->buttonBox->setStandardButtons(QDialogButtonBox::Close);
// Available docsets
ui->refreshButton->setEnabled(true);
// Installed docsets
ui->addFeedButton->setEnabled(true);
QItemSelectionModel *selectionModel = ui->installedDocsetList->selectionModel();
bool hasSelectedUpdates = false;
const auto selectedRows = selectionModel->selectedRows();
for (const QModelIndex &index : selectedRows) {
if (index.data(Registry::ItemDataRole::UpdateAvailableRole).toBool()) {
hasSelectedUpdates = true;
break;
}
}
ui->updateSelectedDocsetsButton->setEnabled(hasSelectedUpdates);
ui->updateAllDocsetsButton->setEnabled(updatesAvailable());
ui->removeDocsetsButton->setEnabled(selectionModel->hasSelection());
}
void DocsetsDialog::disableControls()
{
// Dialog buttons.
if (!m_isStorageReadOnly) {
// Always show the close button if storage is read only.
ui->buttonBox->setStandardButtons(QDialogButtonBox::Cancel);
}
// Installed docsets
ui->addFeedButton->setEnabled(false);
ui->updateSelectedDocsetsButton->setEnabled(false);
ui->updateAllDocsetsButton->setEnabled(false);
ui->downloadDocsetsButton->setEnabled(false);
ui->removeDocsetsButton->setEnabled(false);
// Available docsets
ui->refreshButton->setEnabled(false);
}
QListWidgetItem *DocsetsDialog::findDocsetListItem(const QString &name) const
{
for (int i = 0; i < ui->availableDocsetList->count(); ++i) {
QListWidgetItem *item = ui->availableDocsetList->item(i);
if (item->data(Registry::ItemDataRole::DocsetNameRole).toString() == name)
return item;
}
return nullptr;
}
bool DocsetsDialog::updatesAvailable() const
{
const auto docsets = m_docsetRegistry->docsets();
for (Registry::Docset *docset : docsets) {
if (docset->hasUpdate)
return true;
}
return false;
}
QNetworkReply *DocsetsDialog::download(const QUrl &url)
{
QNetworkReply *reply = m_application->download(url);
connect(reply, &QNetworkReply::downloadProgress, this, &DocsetsDialog::downloadProgress);
connect(reply, &QNetworkReply::finished, this, &DocsetsDialog::downloadCompleted);
m_replies.append(reply);
disableControls();
updateStatus();
return reply;
}
void DocsetsDialog::cancelDownloads()
{
for (QNetworkReply *reply : std::as_const(m_replies)) {
// Hide progress bar
QListWidgetItem *listItem
= ui->availableDocsetList->item(reply->property(ListItemIndexProperty).toInt());
if (listItem)
listItem->setData(DocsetListItemDelegate::ShowProgressRole, false);
if (reply->property(DownloadTypeProperty).toInt() == DownloadDocset)
delete m_tmpFiles.take(reply->property(DocsetNameProperty).toString());
reply->abort();
}
updateStatus();
}
void DocsetsDialog::loadUserFeedList()
{
const auto docsets = m_docsetRegistry->docsets();
for (Registry::Docset *docset : docsets) {
if (!docset->feedUrl().isEmpty()) {
QNetworkReply *reply = download(QUrl(docset->feedUrl()));
reply->setProperty(DownloadTypeProperty, DownloadDashFeed);
}
}
}
void DocsetsDialog::downloadDocsetList()
{
ui->availableDocsetList->clear();
m_availableDocsets.clear();
QNetworkReply *reply = download(QUrl(ApiServerUrl + QLatin1String("/docsets")));
reply->setProperty(DownloadTypeProperty, DownloadDocsetList);
}
void DocsetsDialog::processDocsetList(const QJsonArray &list)
{
for (const QJsonValue &v : list) {
QJsonObject docsetJson = v.toObject();
Registry::DocsetMetadata metadata(docsetJson);
m_availableDocsets.insert({metadata.name(), metadata});
}
// TODO: Move into dedicated method
for (const auto &kv : m_availableDocsets) {
const auto &metadata = kv.second;
auto listItem = new QListWidgetItem(metadata.icon(), metadata.title(), ui->availableDocsetList);
listItem->setData(Registry::ItemDataRole::DocsetNameRole, metadata.name());
if (!m_docsetRegistry->contains(metadata.name())) {
continue;
}
listItem->setHidden(true);
Registry::Docset *docset = m_docsetRegistry->docset(metadata.name());
if (metadata.latestVersion() != docset->version()
|| metadata.revision() > docset->revision()) {
docset->hasUpdate = true;
if (!m_isStorageReadOnly) {
ui->updateAllDocsetsButton->setEnabled(true);
}
}
}
ui->installedDocsetList->reset();
}
void DocsetsDialog::downloadDashDocset(const QModelIndex &index)
{
const QString name = index.data(Registry::ItemDataRole::DocsetNameRole).toString();
if (m_availableDocsets.count(name) == 0 && !m_userFeeds.contains(name))
return;
QUrl url;
if (!m_userFeeds.contains(name)) {
// No feed present means that this is a Kapeli docset
QString urlString = QString(RedirectServerUrl).arg("com.kapeli").arg(name);
url = QUrl(urlString);
} else {
url = m_userFeeds[name].url();
}
QNetworkReply *reply = download(url);
reply->setProperty(DocsetNameProperty, name);
reply->setProperty(DownloadTypeProperty, DownloadDocset);
reply->setProperty(ListItemIndexProperty,
ui->availableDocsetList->row(findDocsetListItem(name)));
}
void DocsetsDialog::removeDocset(const QString &name)
{
if (m_docsetRegistry->contains(name)) {
m_docsetRegistry->unloadDocset(name);
}
const QString docsetPath
= QDir(m_application->settings()->docsetPath).filePath(name + QLatin1String(".docset"));
if (!m_application->fileManager()->removeRecursively(docsetPath)) {
const QString error = tr("Cannot remove directory <b>%1</b>! It might be in use"
" by another process.").arg(docsetPath);
QMessageBox::warning(this, QStringLiteral("Zeal"), error);
return;
}
QListWidgetItem *listItem = findDocsetListItem(name);
if (listItem) {
listItem->setHidden(false);
}
}
void DocsetsDialog::updateStatus()
{
QString text;
if (!m_replies.isEmpty()) {
text = tr("Downloading: %n.", nullptr, m_replies.size());
}
if (!m_tmpFiles.isEmpty()) {
text += QLatin1String(" ") + tr("Installing: %n.", nullptr, m_tmpFiles.size());
}
ui->statusLabel->setText(text);
enableControls();
}
QString DocsetsDialog::docsetNameForTmpFilePath(const QString &filePath) const
{
for (auto it = m_tmpFiles.cbegin(), end = m_tmpFiles.cend(); it != end; ++it) {
if (it.value()->fileName() == filePath) {
return it.key();
}
}
return QString();
}
int DocsetsDialog::percent(qint64 fraction, qint64 total)
{
if (!total)
return 0;
return static_cast<int>(fraction / static_cast<double>(total) * 100);
}
QString DocsetsDialog::cacheLocation(const QString &fileName)
{
return QDir(Core::Application::cacheLocation()).filePath(fileName);
}
bool DocsetsDialog::isDirWritable(const QString &path)
{
auto file = std::make_unique<QTemporaryFile>(path + QLatin1String("/.zeal_writable_check_XXXXXX.tmp"));
return file->open();
}
| 28,515
|
C++
|
.cpp
| 667
| 35.322339
| 135
| 0.673809
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,944
|
settingsdialog.cpp
|
zealdocs_zeal/src/libs/ui/settingsdialog.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include "settingsdialog.h"
#include "ui_settingsdialog.h"
#include <qxtglobalshortcut/qxtglobalshortcut.h>
#include <browser/settings.h>
#include <core/application.h>
#include <core/settings.h>
#include <QDir>
#include <QFileDialog>
#include <QWebEngineProfile>
#include <QWebEngineSettings>
using namespace Zeal;
using namespace Zeal::WidgetUi;
namespace {
// QFontDatabase::standardSizes() lacks some sizes, like 13, which QtWK uses by default.
constexpr int AvailableFontSizes[] = {9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
20, 22, 24, 26, 28, 30, 32, 34, 36,
40, 44, 48, 56, 64, 72};
constexpr QWebEngineSettings::FontFamily BasicFontFamilies[] = {QWebEngineSettings::SerifFont,
QWebEngineSettings::SansSerifFont,
QWebEngineSettings::FixedFont};
} // namespace
SettingsDialog::SettingsDialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::SettingsDialog())
{
ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
// Setup signals & slots
connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &SettingsDialog::saveSettings);
connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &SettingsDialog::loadSettings);
connect(ui->buttonBox, &QDialogButtonBox::clicked, this, [this](QAbstractButton *button) {
if (button == ui->buttonBox->button(QDialogButtonBox::Apply))
saveSettings();
});
// Fonts
ui->defaultFontComboBox->addItem(tr("Serif"), QStringLiteral("serif"));
ui->defaultFontComboBox->addItem(tr("Sans-serif"), QStringLiteral("sans-serif"));
ui->defaultFontComboBox->addItem(tr("Monospace"), QStringLiteral("monospace"));
ui->minFontSizeComboBox->addItem(tr("None"), 0);
for (int fontSize : AvailableFontSizes) {
ui->fontSizeComboBox->addItem(QString::number(fontSize), fontSize);
ui->fixedFontSizeComboBox->addItem(QString::number(fontSize), fontSize);
ui->minFontSizeComboBox->addItem(QString::number(fontSize), fontSize);
}
// Fix tab order.
setTabOrder(ui->defaultFontComboBox, ui->fontSizeComboBox);
setTabOrder(ui->fontSizeComboBox, ui->serifFontComboBox);
// Disable global shortcut settings if not supported.
if (!QxtGlobalShortcut::isSupported()) {
ui->globalHotKeyGroupBox->setEnabled(false);
ui->globalHotKeyGroupBox->setToolTip(tr("Global shortcuts are not supported on the current platform."));
}
QWebEngineSettings *webSettings = Browser::Settings::defaultProfile()->settings();
// Avoid casting in each connect.
auto currentIndexChangedSignal
= static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged);
auto syncStandardFont = [this, webSettings](QWebEngineSettings::FontFamily fontFamily,
const QFont &font) {
const int index = ui->defaultFontComboBox->currentIndex();
if (BasicFontFamilies[index] == fontFamily) {
webSettings->setFontFamily(QWebEngineSettings::StandardFont, font.family());
}
};
connect(ui->defaultFontComboBox, currentIndexChangedSignal,
this, [webSettings](int index) {
const QString fontFamily = webSettings->fontFamily(BasicFontFamilies[index]);
webSettings->setFontFamily(QWebEngineSettings::StandardFont, fontFamily);
});
connect(ui->serifFontComboBox, &QFontComboBox::currentFontChanged,
this, [webSettings, syncStandardFont](const QFont &font) {
webSettings->setFontFamily(QWebEngineSettings::SerifFont, font.family());
syncStandardFont(QWebEngineSettings::SerifFont, font);
});
connect(ui->sansSerifFontComboBox, &QFontComboBox::currentFontChanged,
this, [webSettings, syncStandardFont](const QFont &font) {
webSettings->setFontFamily(QWebEngineSettings::SansSerifFont, font.family());
syncStandardFont(QWebEngineSettings::SansSerifFont, font);
});
connect(ui->fixedFontComboBox, &QFontComboBox::currentFontChanged,
this, [webSettings, syncStandardFont](const QFont &font) {
webSettings->setFontFamily(QWebEngineSettings::FixedFont, font.family());
syncStandardFont(QWebEngineSettings::FixedFont, font);
});
connect(ui->fontSizeComboBox, currentIndexChangedSignal, this, [webSettings](int index) {
webSettings->setFontSize(QWebEngineSettings::DefaultFontSize, AvailableFontSizes[index]);
});
connect(ui->fixedFontSizeComboBox, currentIndexChangedSignal, this, [webSettings](int index) {
webSettings->setFontSize(QWebEngineSettings::DefaultFixedFontSize, AvailableFontSizes[index]);
});
connect(ui->minFontSizeComboBox, currentIndexChangedSignal, this, [webSettings](int index) {
const int fontSize = index == 0 ? 0 : AvailableFontSizes[index-1];
webSettings->setFontSize(QWebEngineSettings::MinimumFontSize, fontSize);
});
loadSettings();
}
SettingsDialog::~SettingsDialog()
{
delete ui;
}
void SettingsDialog::chooseCustomCssFile()
{
const QString file = QFileDialog::getOpenFileName(this, tr("Choose CSS File"),
ui->customCssFileEdit->text(),
tr("CSS Files (*.css);;All Files (*.*)"));
if (file.isEmpty())
return;
ui->customCssFileEdit->setText(QDir::toNativeSeparators(file));
}
void SettingsDialog::chooseDocsetStoragePath()
{
QString path = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
ui->docsetStorageEdit->text());
if (path.isEmpty()) {
return;
}
#ifdef PORTABLE_BUILD
// Use relative path if selected directory is under the application binary path.
if (path.startsWith(QCoreApplication::applicationDirPath() + QLatin1String("/"))) {
const QDir appDirPath(QCoreApplication::applicationDirPath());
path = appDirPath.relativeFilePath(path);
}
#endif
ui->docsetStorageEdit->setText(QDir::toNativeSeparators(path));
}
void SettingsDialog::loadSettings()
{
const Core::Settings * const settings = Core::Application::instance()->settings();
// General Tab
ui->startMinimizedCheckBox->setChecked(settings->startMinimized);
ui->checkForUpdateCheckBox->setChecked(settings->checkForUpdate);
ui->systrayGroupBox->setChecked(settings->showSystrayIcon);
ui->minimizeToSystrayCheckBox->setChecked(settings->minimizeToSystray);
ui->hideToSystrayCheckBox->setChecked(settings->hideOnClose);
ui->toolButton->setKeySequence(settings->showShortcut);
ui->docsetStorageEdit->setText(QDir::toNativeSeparators(settings->docsetPath));
// Tabs Tab
ui->openNewTabAfterActive->setChecked(settings->openNewTabAfterActive);
// Search Tab
ui->fuzzySearchCheckBox->setChecked(settings->isFuzzySearchEnabled);
// Content Tab
for (int i = 0; i < ui->defaultFontComboBox->count(); ++i) {
if (ui->defaultFontComboBox->itemData(i).toString() == settings->defaultFontFamily) {
ui->defaultFontComboBox->setCurrentIndex(i);
break;
}
}
ui->serifFontComboBox->setCurrentText(settings->serifFontFamily);
ui->sansSerifFontComboBox->setCurrentText(settings->sansSerifFontFamily);
ui->fixedFontComboBox->setCurrentText(settings->fixedFontFamily);
ui->fontSizeComboBox->setCurrentText(QString::number(settings->defaultFontSize));
ui->fixedFontSizeComboBox->setCurrentText(QString::number(settings->defaultFixedFontSize));
ui->minFontSizeComboBox->setCurrentText(QString::number(settings->minimumFontSize));
switch (settings->contentAppearance) {
case Core::Settings::ContentAppearance::Automatic:
ui->appearanceAutoRadioButton->setChecked(true);
break;
case Core::Settings::ContentAppearance::Light:
ui->appearanceLightRadioButton->setChecked(true);
break;
case Core::Settings::ContentAppearance::Dark:
ui->appearanceDarkRadioButton->setChecked(true);
break;
}
ui->highlightOnNavigateCheckBox->setChecked(settings->isHighlightOnNavigateEnabled);
ui->customCssFileEdit->setText(QDir::toNativeSeparators(settings->customCssFile));
switch (settings->externalLinkPolicy) {
case Core::Settings::ExternalLinkPolicy::Ask:
ui->radioExternalLinkAsk->setChecked(true);
break;
case Core::Settings::ExternalLinkPolicy::Open:
ui->radioExternalLinkOpen->setChecked(true);
break;
case Core::Settings::ExternalLinkPolicy::OpenInSystemBrowser:
ui->radioExternalLinkOpenDesktop->setChecked(true);
break;
}
ui->useSmoothScrollingCheckBox->setChecked(settings->isSmoothScrollingEnabled);
// Network Tab
switch (settings->proxyType) {
case Core::Settings::ProxyType::None:
ui->noProxySettings->setChecked(true);
break;
case Core::Settings::ProxyType::System:
ui->systemProxySettings->setChecked(true);
break;
case Core::Settings::ProxyType::Http:
ui->manualProxySettings->setChecked(true);
ui->proxyTypeHttpRadioButton->setChecked(true);
break;
case Core::Settings::ProxyType::Socks5:
ui->manualProxySettings->setChecked(true);
ui->proxyTypeSocks5RadioButton->setChecked(true);
break;
}
ui->proxyHostEdit->setText(settings->proxyHost);
ui->proxyPortEdit->setValue(settings->proxyPort);
ui->proxyRequiresAuthCheckBox->setChecked(settings->proxyAuthenticate);
ui->proxyUsernameEdit->setText(settings->proxyUserName);
ui->proxyPasswordEdit->setText(settings->proxyPassword);
ui->ignoreSslErrorsCheckBox->setChecked(settings->isIgnoreSslErrorsEnabled);
}
void SettingsDialog::saveSettings()
{
Core::Settings * const settings = Core::Application::instance()->settings();
// General Tab
settings->startMinimized = ui->startMinimizedCheckBox->isChecked();
settings->checkForUpdate = ui->checkForUpdateCheckBox->isChecked();
settings->showSystrayIcon = ui->systrayGroupBox->isChecked();
settings->minimizeToSystray = ui->minimizeToSystrayCheckBox->isChecked();
settings->hideOnClose = ui->hideToSystrayCheckBox->isChecked();
settings->showShortcut = ui->toolButton->keySequence();
settings->docsetPath = QDir::fromNativeSeparators(ui->docsetStorageEdit->text());
// Tabs Tab
settings->openNewTabAfterActive = ui->openNewTabAfterActive->isChecked();
// Search Tab
settings->isFuzzySearchEnabled = ui->fuzzySearchCheckBox->isChecked();
// Content Tab
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) && QT_VERSION < QT_VERSION_CHECK(6, 7, 0)
// Applying dark mode requires restart.
ui->appearanceLabel->setText(tr("Appearance (requires restart):"));
#endif
settings->defaultFontFamily = ui->defaultFontComboBox->currentData().toString();
settings->serifFontFamily = ui->serifFontComboBox->currentText();
settings->sansSerifFontFamily = ui->sansSerifFontComboBox->currentText();
settings->fixedFontFamily = ui->fixedFontComboBox->currentText();
settings->defaultFontSize = ui->fontSizeComboBox->currentData().toInt();
settings->defaultFixedFontSize = ui->fixedFontSizeComboBox->currentData().toInt();
settings->minimumFontSize = ui->minFontSizeComboBox->currentData().toInt();
if (ui->appearanceAutoRadioButton->isChecked()) {
settings->contentAppearance = Core::Settings::ContentAppearance::Automatic;
} else if (ui->appearanceLightRadioButton->isChecked()) {
settings->contentAppearance = Core::Settings::ContentAppearance::Light;
} else if (ui->appearanceDarkRadioButton->isChecked()) {
settings->contentAppearance = Core::Settings::ContentAppearance::Dark;
}
settings->isHighlightOnNavigateEnabled = ui->highlightOnNavigateCheckBox->isChecked();
settings->customCssFile = QDir::fromNativeSeparators(ui->customCssFileEdit->text());
if (ui->radioExternalLinkAsk->isChecked()) {
settings->externalLinkPolicy = Core::Settings::ExternalLinkPolicy::Ask;
} else if (ui->radioExternalLinkOpen->isChecked()) {
settings->externalLinkPolicy = Core::Settings::ExternalLinkPolicy::Open;
} else if (ui->radioExternalLinkOpenDesktop->isChecked()) {
settings->externalLinkPolicy = Core::Settings::ExternalLinkPolicy::OpenInSystemBrowser;
}
settings->isSmoothScrollingEnabled = ui->useSmoothScrollingCheckBox->isChecked();
// Network Tab
// Proxy settings
if (ui->noProxySettings->isChecked()) {
settings->proxyType = Core::Settings::ProxyType::None;
} else if (ui->systemProxySettings->isChecked()) {
settings->proxyType = Core::Settings::ProxyType::System;
} else if (ui->manualProxySettings->isChecked()) {
if (ui->proxyTypeSocks5RadioButton->isChecked()) {
settings->proxyType = Core::Settings::ProxyType::Socks5;
} else {
settings->proxyType = Core::Settings::ProxyType::Http;
}
}
settings->proxyHost = ui->proxyHostEdit->text();
settings->proxyPort = ui->proxyPortEdit->text().toUShort();
settings->proxyAuthenticate = ui->proxyRequiresAuthCheckBox->isChecked();
settings->proxyUserName = ui->proxyUsernameEdit->text();
settings->proxyPassword = ui->proxyPasswordEdit->text();
settings->isIgnoreSslErrorsEnabled = ui->ignoreSslErrorsCheckBox->isChecked();
settings->save();
}
| 13,803
|
C++
|
.cpp
| 269
| 44.215613
| 112
| 0.71154
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,945
|
mainwindow.cpp
|
zealdocs_zeal/src/libs/ui/mainwindow.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "aboutdialog.h"
#include "browsertab.h"
#include "docsetsdialog.h"
#include "searchsidebar.h"
#include "settingsdialog.h"
#include "sidebarviewprovider.h"
#include <qxtglobalshortcut/qxtglobalshortcut.h>
#include <browser/settings.h>
#include <browser/webbridge.h>
#include <browser/webcontrol.h>
#include <core/application.h>
#include <core/settings.h>
#include <sidebar/container.h>
#include <sidebar/proxyview.h>
#include <QCloseEvent>
#include <QDesktopServices>
#include <QKeyEvent>
#include <QMenu>
#include <QMessageBox>
#include <QShortcut>
#include <QSystemTrayIcon>
#include <QTabBar>
using namespace Zeal;
using namespace Zeal::WidgetUi;
MainWindow::MainWindow(Core::Application *app, QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
, m_application(app)
, m_settings(app->settings())
{
ui->setupUi(this);
// Initialize the global shortcut handler if supported.
if (QxtGlobalShortcut::isSupported()) {
m_globalShortcut = new QxtGlobalShortcut(m_settings->showShortcut, this);
connect(m_globalShortcut, &QxtGlobalShortcut::activated, this, &MainWindow::toggleWindow);
}
setupTabBar();
// Setup application wide shortcuts.
// Focus search bar.
auto shortcut = new QShortcut(QStringLiteral("Ctrl+K"), this);
connect(shortcut, &QShortcut::activated, this, [this]() { currentTab()->searchSidebar()->focusSearchEdit(); });
shortcut = new QShortcut(QStringLiteral("Ctrl+L"), this);
connect(shortcut, &QShortcut::activated, this, [this]() { currentTab()->searchSidebar()->focusSearchEdit(); });
// Duplicate current tab.
shortcut = new QShortcut(QStringLiteral("Ctrl+Alt+T"), this);
connect(shortcut, &QShortcut::activated, this, [this]() { duplicateTab(m_tabBar->currentIndex()); });
// Hide/show sidebar.
// TODO: Move to the View menu.
shortcut = new QShortcut(QStringLiteral("Ctrl+B"), this);
connect(shortcut, &QShortcut::activated, this, [this]() {
auto sb = ui->splitter->widget(0);
if (sb == nullptr) {
// This should not really happen.
return;
}
sb->setVisible(!sb->isVisible());
});
restoreGeometry(m_settings->windowGeometry);
// Menu
// File
// Some platform plugins do not define QKeySequence::Quit.
if (QKeySequence(QKeySequence::Quit).isEmpty())
ui->actionQuit->setShortcut(QStringLiteral("Ctrl+Q"));
else
ui->actionQuit->setShortcut(QKeySequence::Quit);
// Follow Windows HIG.
#ifdef Q_OS_WIN32
ui->actionQuit->setText(tr("E&xit"));
#endif
connect(ui->actionQuit, &QAction::triggered, qApp, &QCoreApplication::quit);
// Edit
ui->actionFind->setShortcut(QKeySequence::Find);
connect(ui->actionFind, &QAction::triggered, this, [this]() {
currentTab()->webControl()->activateSearchBar();
});
if (QKeySequence(QKeySequence::Preferences).isEmpty()) {
ui->actionPreferences->setShortcut(QStringLiteral("Ctrl+,"));
} else {
ui->actionPreferences->setShortcut(QKeySequence::Preferences);
}
connect(ui->actionPreferences, &QAction::triggered, this, [this]() {
if (m_globalShortcut) {
m_globalShortcut->setEnabled(false);
}
QScopedPointer<SettingsDialog> dialog(new SettingsDialog(this));
dialog->exec();
if (m_globalShortcut) {
m_globalShortcut->setEnabled(true);
}
});
shortcut = new QShortcut(QKeySequence::Back, this);
connect(shortcut, &QShortcut::activated, this, [this]() { currentTab()->webControl()->back(); });
shortcut = new QShortcut(QKeySequence::Forward, this);
connect(shortcut, &QShortcut::activated, this, [this]() { currentTab()->webControl()->forward(); });
shortcut = new QShortcut(QKeySequence::ZoomIn, this);
connect(shortcut, &QShortcut::activated, this, [this]() { currentTab()->webControl()->zoomIn(); });
shortcut = new QShortcut(QStringLiteral("Ctrl+="), this);
connect(shortcut, &QShortcut::activated, this, [this]() { currentTab()->webControl()->zoomIn(); });
shortcut = new QShortcut(QKeySequence::ZoomOut, this);
connect(shortcut, &QShortcut::activated, this, [this]() { currentTab()->webControl()->zoomOut(); });
shortcut = new QShortcut(QStringLiteral("Ctrl+0"), this);
connect(shortcut, &QShortcut::activated, this, [this]() { currentTab()->webControl()->resetZoom(); });
// Tools Menu
connect(ui->actionDocsets, &QAction::triggered, this, [this]() {
QScopedPointer<DocsetsDialog> dialog(new DocsetsDialog(m_application, this));
dialog->exec();
});
// Help Menu
connect(ui->actionSubmitFeedback, &QAction::triggered, []() {
QDesktopServices::openUrl(QUrl(QStringLiteral("https://github.com/zealdocs/zeal/issues")));
});
connect(ui->actionCheckForUpdates, &QAction::triggered,
m_application, &Core::Application::checkForUpdates);
connect(ui->actionAboutZeal, &QAction::triggered, this, [this]() {
QScopedPointer<AboutDialog> dialog(new AboutDialog(this));
dialog->exec();
});
// Update check
connect(m_application, &Core::Application::updateCheckError, this, [this](const QString &message) {
QMessageBox::warning(this, QStringLiteral("Zeal"), message);
});
connect(m_application, &Core::Application::updateCheckDone, this, [this](const QString &version) {
if (version.isEmpty()) {
QMessageBox::information(this, QStringLiteral("Zeal"),
tr("You are using the latest version."));
return;
}
// TODO: Remove this ugly workaround for #637.
qApp->setQuitOnLastWindowClosed(false);
const int ret
= QMessageBox::information(this, QStringLiteral("Zeal"),
tr("Zeal <b>%1</b> is available. Open download page?").arg(version),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::Yes);
qApp->setQuitOnLastWindowClosed(true);
if (ret == QMessageBox::Yes) {
QDesktopServices::openUrl(QUrl(QStringLiteral("https://zealdocs.org/download.html")));
}
});
// Setup sidebar.
auto m_sbViewProvider = new SidebarViewProvider(this);
auto sbView = new Sidebar::ProxyView(m_sbViewProvider, QStringLiteral("index"));
auto sb = new Sidebar::Container();
sb->addView(sbView);
// Setup splitter.
ui->splitter->insertWidget(0, sb);
ui->splitter->restoreState(m_settings->verticalSplitterGeometry);
// Setup web settings.
auto webSettings = new Browser::Settings(m_settings, this);
// Setup web bridge.
m_webBridge = new Browser::WebBridge(this);
connect(m_webBridge, &Browser::WebBridge::actionTriggered, this, [this](const QString &action) {
// TODO: In the future connect directly to the ActionManager.
if (action == "openDocsetManager") {
ui->actionDocsets->trigger();
} else if (action == "openPreferences") {
ui->actionPreferences->trigger();
}
});
createTab();
ui->actionNewTab->setShortcut(QKeySequence::AddTab);
connect(ui->actionNewTab, &QAction::triggered, this, [this]() { createTab(); });
addAction(ui->actionNewTab);
connect(m_tabBar, &QTabBar::tabBarDoubleClicked, this, [this](int index) {
if (index == -1)
createTab();
});
ui->actionCloseTab->setShortcuts({QKeySequence(Qt::ControlModifier | Qt::Key_W)});
addAction(ui->actionCloseTab);
connect(ui->actionCloseTab, &QAction::triggered, this, [this]() { closeTab(); });
// TODO: Use QKeySequence::NextChild, when QTBUG-112193 is fixed.
ui->actionNextTab->setShortcuts({QKeySequence(Qt::ControlModifier | Qt::Key_Tab),
QKeySequence(Qt::ControlModifier | Qt::Key_PageDown)});
addAction(ui->actionNextTab);
connect(ui->actionNextTab, &QAction::triggered, this, [this]() {
m_tabBar->setCurrentIndex((m_tabBar->currentIndex() + 1) % m_tabBar->count());
});
// TODO: Use QKeySequence::PreviousChild, when QTBUG-15746 and QTBUG-112193 are fixed.
ui->actionPreviousTab->setShortcuts({QKeySequence(Qt::ControlModifier | Qt::ShiftModifier | Qt::Key_Tab),
QKeySequence(Qt::ControlModifier | Qt::Key_PageUp)});
addAction(ui->actionPreviousTab);
connect(ui->actionPreviousTab, &QAction::triggered, this, [this]() {
m_tabBar->setCurrentIndex((m_tabBar->currentIndex() - 1 + m_tabBar->count()) % m_tabBar->count());
});
connect(m_settings, &Core::Settings::updated, this, &MainWindow::applySettings);
applySettings();
if (m_settings->checkForUpdate)
m_application->checkForUpdates(true);
}
MainWindow::~MainWindow()
{
m_settings->verticalSplitterGeometry = ui->splitter->saveState();
m_settings->windowGeometry = saveGeometry();
delete ui;
}
void MainWindow::search(const Registry::SearchQuery &query)
{
currentTab()->search(query);
}
void MainWindow::closeTab(int index)
{
if (index == -1) {
index = m_tabBar->currentIndex();
}
if (index == -1)
return;
BrowserTab *tab = tabAt(index);
ui->webViewStack->removeWidget(tab);
tab->deleteLater();
// Handle the tab bar last to avoid currentChanged signal coming too early.
m_tabBar->removeTab(index);
if (ui->webViewStack->count() == 0) {
createTab();
}
}
void MainWindow::moveTab(int from, int to)
{
const QSignalBlocker blocker(ui->webViewStack);
QWidget *w = ui->webViewStack->widget(from);
ui->webViewStack->removeWidget(w);
ui->webViewStack->insertWidget(to, w);
}
BrowserTab *MainWindow::createTab()
{
auto tab = new BrowserTab();
tab->navigateToStartPage();
addTab(tab);
return tab;
}
void MainWindow::duplicateTab(int index)
{
BrowserTab *tab = tabAt(index);
if (tab == nullptr)
return;
// Add a duplicate next to the `index`.
addTab(tab->clone(), index + 1);
}
void MainWindow::addTab(BrowserTab *tab, int index)
{
connect(tab, &BrowserTab::iconChanged, this, [this, tab](const QIcon &icon) {
const int index = ui->webViewStack->indexOf(tab);
Q_ASSERT(m_tabBar->tabData(index).value<BrowserTab *>() == tab);
m_tabBar->setTabIcon(index, icon);
});
connect(tab, &BrowserTab::titleChanged, this, [this, tab](const QString &title) {
if (title.isEmpty())
return;
#ifndef PORTABLE_BUILD
setWindowTitle(QStringLiteral("%1 - Zeal").arg(title));
#else
setWindowTitle(QStringLiteral("%1 - Zeal Portable").arg(title));
#endif
const int index = ui->webViewStack->indexOf(tab);
Q_ASSERT(m_tabBar->tabData(index).value<BrowserTab *>() == tab);
m_tabBar->setTabText(index, title);
m_tabBar->setTabToolTip(index, title);
});
tab->webControl()->setWebBridgeObject("zAppBridge", m_webBridge);
tab->searchSidebar()->focusSearchEdit();
if (index == -1) {
index = m_settings->openNewTabAfterActive
? m_tabBar->currentIndex() + 1
: ui->webViewStack->count();
}
ui->webViewStack->insertWidget(index, tab);
m_tabBar->insertTab(index, tr("Loading…"));
m_tabBar->setCurrentIndex(index);
m_tabBar->setTabData(index, QVariant::fromValue(tab));
}
BrowserTab *MainWindow::currentTab() const
{
return tabAt(m_tabBar->currentIndex());
}
BrowserTab *MainWindow::tabAt(int index) const
{
return qobject_cast<BrowserTab *>(ui->webViewStack->widget(index));
}
void MainWindow::setupTabBar()
{
m_tabBar = new QTabBar(this);
m_tabBar->installEventFilter(this);
m_tabBar->setTabsClosable(true);
m_tabBar->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab);
m_tabBar->setExpanding(false);
m_tabBar->setUsesScrollButtons(true);
m_tabBar->setDocumentMode(true);
m_tabBar->setElideMode(Qt::ElideRight);
m_tabBar->setStyleSheet(QStringLiteral("QTabBar::tab { width: 150px; }"));
m_tabBar->setMovable(true);
connect(m_tabBar, &QTabBar::currentChanged, this, [this](int index) {
if (index == -1)
return;
BrowserTab *tab = tabAt(index);
#ifndef PORTABLE_BUILD
setWindowTitle(QStringLiteral("%1 - Zeal").arg(tab->webControl()->title()));
#else
setWindowTitle(QStringLiteral("%1 - Zeal Portable").arg(tab->webControl()->title()));
#endif
ui->webViewStack->setCurrentIndex(index);
emit currentTabChanged();
});
connect(m_tabBar, &QTabBar::tabCloseRequested, this, &MainWindow::closeTab);
connect(m_tabBar, &QTabBar::tabMoved, this, &MainWindow::moveTab);
for (int i = 1; i < 10; i++) {
auto action = new QAction(m_tabBar);
#ifdef Q_OS_LINUX
action->setShortcut(QStringLiteral("Alt+%1").arg(i));
#else
action->setShortcut(QStringLiteral("Ctrl+%1").arg(i));
#endif
if (i == 9) {
connect(action, &QAction::triggered, this, [=]() {
m_tabBar->setCurrentIndex(m_tabBar->count() - 1);
});
} else {
connect(action, &QAction::triggered, this, [=]() {
m_tabBar->setCurrentIndex(i - 1);
});
}
addAction(action);
}
ui->centralWidgetLayout->insertWidget(0, m_tabBar);
}
void MainWindow::createTrayIcon()
{
if (m_trayIcon)
return;
m_trayIcon = new QSystemTrayIcon(this);
m_trayIcon->setIcon(QIcon::fromTheme(QStringLiteral("zeal-tray"), windowIcon()));
m_trayIcon->setToolTip(QStringLiteral("Zeal"));
connect(m_trayIcon, &QSystemTrayIcon::activated, this, [this](QSystemTrayIcon::ActivationReason reason) {
if (reason != QSystemTrayIcon::Trigger && reason != QSystemTrayIcon::DoubleClick)
return;
toggleWindow();
});
auto trayIconMenu = new QMenu(this);
QAction *toggleAction = trayIconMenu->addAction(tr("Show Zeal"),
this, &MainWindow::toggleWindow);
connect(trayIconMenu, &QMenu::aboutToShow, this, [this, toggleAction]() {
toggleAction->setText(isVisible() ? tr("Minimize to Tray") : tr("Show Zeal"));
});
trayIconMenu->addSeparator();
trayIconMenu->addAction(ui->actionQuit);
m_trayIcon->setContextMenu(trayIconMenu);
m_trayIcon->show();
}
void MainWindow::removeTrayIcon()
{
if (!m_trayIcon)
return;
QMenu *trayIconMenu = m_trayIcon->contextMenu();
delete m_trayIcon;
m_trayIcon = nullptr;
delete trayIconMenu;
}
void MainWindow::bringToFront()
{
show();
setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
raise();
activateWindow();
currentTab()->searchSidebar()->focusSearchEdit();
}
void MainWindow::changeEvent(QEvent *event)
{
if (m_settings->showSystrayIcon && m_settings->minimizeToSystray
&& event->type() == QEvent::WindowStateChange && isMinimized()) {
hide();
}
QMainWindow::changeEvent(event);
}
void MainWindow::closeEvent(QCloseEvent *event)
{
if (m_settings->showSystrayIcon && m_settings->hideOnClose) {
event->ignore();
toggleWindow();
}
}
bool MainWindow::eventFilter(QObject *object, QEvent *event)
{
if (object == m_tabBar) {
switch (event->type()) {
case QEvent::MouseButtonRelease: {
auto e = static_cast<QMouseEvent *>(event);
if (e->button() == Qt::MiddleButton) {
const int index = m_tabBar->tabAt(e->pos());
if (index != -1) {
closeTab(index);
return true;
}
}
break;
}
case QEvent::Wheel:
// TODO: Remove in case QTBUG-8428 is fixed on all platforms
return true;
default:
break;
}
}
return QMainWindow::eventFilter(object, event);
}
// Captures global events in order to pass them to the search bar.
void MainWindow::keyPressEvent(QKeyEvent *keyEvent)
{
switch (keyEvent->key()) {
case Qt::Key_Escape:
currentTab()->searchSidebar()->focusSearchEdit(true);
break;
case Qt::Key_Question:
currentTab()->searchSidebar()->focusSearchEdit();
break;
default:
QMainWindow::keyPressEvent(keyEvent);
break;
}
}
void MainWindow::applySettings()
{
if (m_globalShortcut) {
m_globalShortcut->setShortcut(m_settings->showShortcut);
}
if (m_settings->showSystrayIcon)
createTrayIcon();
else
removeTrayIcon();
}
void MainWindow::toggleWindow()
{
const bool checkActive = m_globalShortcut && sender() == m_globalShortcut;
if (!isVisible() || (checkActive && !isActiveWindow())) {
bringToFront();
} else {
if (m_trayIcon) {
hide();
} else {
showMinimized();
}
}
}
| 17,343
|
C++
|
.cpp
| 445
| 32.438202
| 115
| 0.648599
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,946
|
browsertab.cpp
|
zealdocs_zeal/src/libs/ui/browsertab.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "browsertab.h"
#include "searchsidebar.h"
#include "widgets/layouthelper.h"
#include "widgets/toolbarframe.h"
#include <browser/webcontrol.h>
#include <core/application.h>
#include <core/settings.h>
#include <registry/docset.h>
#include <registry/docsetregistry.h>
#include <registry/searchquery.h>
#include <QApplication>
#include <QLabel>
#include <QMenu>
#include <QStyle>
#include <QToolButton>
#include <QVBoxLayout>
#include <QWebEngineHistory>
using namespace Zeal;
using namespace Zeal::WidgetUi;
namespace {
constexpr char WelcomePageUrl[] = "qrc:///browser/welcome.html";
} // namespace
BrowserTab::BrowserTab(QWidget *parent)
: QWidget(parent)
{
// Setup WebControl.
m_webControl = new Browser::WebControl(this);
connect(m_webControl, &Browser::WebControl::titleChanged, this, &BrowserTab::titleChanged);
connect(m_webControl, &Browser::WebControl::urlChanged, this, [this](const QUrl &url) {
// TODO: Check if changed.
emit iconChanged(docsetIcon(url));
Registry::Docset *docset = Core::Application::instance()->docsetRegistry()->docsetForUrl(url);
if (docset) {
searchSidebar()->pageTocModel()->setResults(docset->relatedLinks(url));
m_webControl->setJavaScriptEnabled(docset->isJavaScriptEnabled());
} else {
searchSidebar()->pageTocModel()->setResults();
// Always enable JS outside of docsets.
m_webControl->setJavaScriptEnabled(true);
}
m_backButton->setEnabled(m_webControl->canGoBack());
m_forwardButton->setEnabled(m_webControl->canGoForward());
});
// Setup navigation toolbar.
m_backButton = new QToolButton();
m_backButton->setAutoRaise(true);
m_backButton->setIcon(qApp->style()->standardIcon(QStyle::SP_ArrowBack));
m_backButton->setStyleSheet(QStringLiteral("QToolButton::menu-indicator { image: none; }"));
m_backButton->setText(QStringLiteral("←"));
m_backButton->setToolTip(tr("Go back one page"));
auto backMenu = new QMenu(m_backButton);
connect(backMenu, &QMenu::aboutToShow, this, [this, backMenu]() {
backMenu->clear();
QWebEngineHistory *history = m_webControl->history();
QList<QWebEngineHistoryItem> items = history->backItems(10);
for (auto it = items.crbegin(); it != items.crend(); ++it) {
const QIcon icon = docsetIcon(it->url());
const QWebEngineHistoryItem item = *it;
backMenu->addAction(icon, it->title(), this, [=](bool) { history->goToItem(item); });
}
});
m_backButton->setMenu(backMenu);
connect(m_backButton, &QToolButton::clicked, m_webControl, &Browser::WebControl::back);
m_forwardButton = new QToolButton();
m_forwardButton->setAutoRaise(true);
m_forwardButton->setIcon(qApp->style()->standardIcon(QStyle::SP_ArrowForward));
m_forwardButton->setStyleSheet(QStringLiteral("QToolButton::menu-indicator { image: none; }"));
m_forwardButton->setText(QStringLiteral("→"));
m_forwardButton->setToolTip(tr("Go forward one page"));
auto forwardMenu = new QMenu(m_forwardButton);
connect(forwardMenu, &QMenu::aboutToShow, this, [this, forwardMenu]() {
forwardMenu->clear();
QWebEngineHistory *history = m_webControl->history();
const auto forwardItems = history->forwardItems(10);
for (const QWebEngineHistoryItem &item : forwardItems) {
const QIcon icon = docsetIcon(item.url());
forwardMenu->addAction(icon, item.title(), this, [=](bool) { history->goToItem(item); });
}
});
m_forwardButton->setMenu(forwardMenu);
connect(m_forwardButton, &QToolButton::clicked, m_webControl, &Browser::WebControl::forward);
auto label = new QLabel();
label->setAlignment(Qt::AlignCenter);
connect(m_webControl, &Browser::WebControl::titleChanged, this, [label](const QString &title) {
if (title.isEmpty())
return;
label->setText(title);
});
auto toolBarLayout = new QHBoxLayout();
toolBarLayout->setContentsMargins(4, 0, 4, 0);
toolBarLayout->setSpacing(4);
toolBarLayout->addWidget(m_backButton);
toolBarLayout->addWidget(m_forwardButton);
toolBarLayout->addWidget(label, 1);
auto toolBarFrame = new ToolBarFrame();
toolBarFrame->setLayout(toolBarLayout);
// Setup main layout.
auto layout = LayoutHelper::createBorderlessLayout<QVBoxLayout>();
layout->addWidget(toolBarFrame);
layout->addWidget(m_webControl);
setLayout(layout);
auto registry = Core::Application::instance()->docsetRegistry();
using Registry::DocsetRegistry;
connect(registry, &DocsetRegistry::docsetAboutToBeUnloaded,
this, [this, registry](const QString &name) {
Registry::Docset *docset = registry->docsetForUrl(m_webControl->url());
if (docset == nullptr || docset->name() != name) {
return;
}
// TODO: Add custom 'Page has been removed' page.
navigateToStartPage();
// TODO: Cleanup history.
});
}
BrowserTab *BrowserTab::clone(QWidget *parent) const
{
auto tab = new BrowserTab(parent);
if (m_searchSidebar) {
tab->m_searchSidebar = m_searchSidebar->clone();
connect(tab->m_searchSidebar, &SearchSidebar::activated,
tab->m_webControl, &Browser::WebControl::focus);
connect(tab->m_searchSidebar, &SearchSidebar::navigationRequested,
tab->m_webControl, &Browser::WebControl::load);
}
tab->m_webControl->restoreHistory(m_webControl->saveHistory());
tab->m_webControl->setZoomLevel(m_webControl->zoomLevel());
return tab;
}
BrowserTab::~BrowserTab()
{
if (m_searchSidebar) {
// The sidebar is not in this widget's hierarchy, so direct delete is not safe.
m_searchSidebar->deleteLater();
}
}
Browser::WebControl *BrowserTab::webControl() const
{
return m_webControl;
}
SearchSidebar *BrowserTab::searchSidebar()
{
if (m_searchSidebar == nullptr) {
// Create SearchSidebar managed by this tab.
m_searchSidebar = new SearchSidebar();
connect(m_searchSidebar, &SearchSidebar::activated,
m_webControl, &Browser::WebControl::focus);
connect(m_searchSidebar, &SearchSidebar::navigationRequested,
m_webControl, &Browser::WebControl::load);
}
return m_searchSidebar;
}
void BrowserTab::navigateToStartPage()
{
m_webControl->load(QUrl(WelcomePageUrl));
}
void BrowserTab::search(const Registry::SearchQuery &query)
{
if (query.isEmpty())
return;
m_searchSidebar->search(query);
}
QIcon BrowserTab::docsetIcon(const QUrl &url) const
{
Registry::Docset *docset = Core::Application::instance()->docsetRegistry()->docsetForUrl(url);
return docset ? docset->icon() : QIcon(QStringLiteral(":/icons/logo/icon.png"));
}
| 7,038
|
C++
|
.cpp
| 168
| 36.029762
| 102
| 0.686631
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,947
|
searchsidebar.cpp
|
zealdocs_zeal/src/libs/ui/searchsidebar.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "searchsidebar.h"
#include "searchitemdelegate.h"
#include "widgets/layouthelper.h"
#include "widgets/searchedit.h"
#include "widgets/toolbarframe.h"
#include <core/application.h>
#include <core/settings.h>
#include <registry/docset.h>
#include <registry/docsetregistry.h>
#include <registry/itemdatarole.h>
#include <registry/listmodel.h>
#include <registry/searchmodel.h>
#include <registry/searchquery.h>
#include <QCoreApplication>
#include <QEvent>
#include <QKeyEvent>
#include <QListView>
#include <QScrollBar>
#include <QShortcut>
#include <QSplitter>
#include <QTimer>
#include <QTreeView>
#include <QVBoxLayout>
using namespace Zeal;
using namespace Zeal::WidgetUi;
SearchSidebar::SearchSidebar(QWidget *parent)
: SearchSidebar(nullptr, parent)
{
}
SearchSidebar::SearchSidebar(const SearchSidebar *other, QWidget *parent)
: Sidebar::View(parent)
{
// Setup search result view.
m_treeView = new QTreeView();
m_treeView->setFrameShape(QFrame::NoFrame);
m_treeView->setHeaderHidden(true);
m_treeView->setUniformRowHeights(true);
#ifdef Q_OS_MACOS
m_treeView->setAttribute(Qt::WA_MacShowFocusRect, false);
#endif
// Save expanded items.
connect(m_treeView, &QTreeView::expanded, this, [this](const QModelIndex &index) {
if (m_expandedIndexList.indexOf(index) == -1) {
m_expandedIndexList.append(index);
}
});
connect(m_treeView, &QTreeView::collapsed, this, [this](const QModelIndex &index) {
m_expandedIndexList.removeOne(index);
});
auto delegate = new SearchItemDelegate(m_treeView);
delegate->setDecorationRoles({Registry::ItemDataRole::DocsetIconRole, Qt::DecorationRole});
m_treeView->setItemDelegate(delegate);
connect(m_treeView, &QTreeView::activated, this, &SearchSidebar::navigateToIndexAndActivate);
connect(m_treeView, &QTreeView::clicked, this, &SearchSidebar::navigateToIndex);
// Setup Alt+Up, Alt+Down, etc shortcuts.
const auto keyList = {Qt::Key_Up, Qt::Key_Down,
Qt::Key_PageUp, Qt::Key_PageDown,
Qt::Key_Home, Qt::Key_End};
for (const auto key : keyList) {
auto shortcut = new QShortcut(key | Qt::AltModifier, this);
connect(shortcut, &QShortcut::activated, this, [this, key]() {
QKeyEvent event(QKeyEvent::KeyPress, key, Qt::NoModifier);
QCoreApplication::sendEvent(m_treeView, &event);
});
}
// Setup page TOC view.
// TODO: Move to a separate Sidebar View.
m_pageTocView = new QListView();
m_pageTocView->setFrameShape(QFrame::NoFrame);
m_pageTocView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_pageTocView->setItemDelegate(new SearchItemDelegate(m_pageTocView));
m_pageTocView->setUniformItemSizes(true);
m_pageTocView->setVisible(false);
#ifdef Q_OS_MACOS
m_pageTocView->setAttribute(Qt::WA_MacShowFocusRect, false);
#endif
m_pageTocModel = new Registry::SearchModel(this);
connect(m_pageTocModel, &Registry::SearchModel::updated, this, [this]() {
if (m_pageTocModel->isEmpty()) {
m_pageTocView->hide();
} else {
m_pageTocView->show();
m_splitter->restoreState(Core::Application::instance()->settings()->tocSplitterState);
}
});
m_pageTocView->setModel(m_pageTocModel);
connect(m_pageTocView, &QListView::activated, this, &SearchSidebar::navigateToIndexAndActivate);
connect(m_pageTocView, &QListView::clicked, this, &SearchSidebar::navigateToIndex);
// Setup search input box.
m_searchEdit = new SearchEdit();
m_searchEdit->installEventFilter(this);
setupSearchBoxCompletions();
// Connect delegate first to make cloning work.
connect(m_searchEdit, &QLineEdit::textChanged, this, [delegate](const QString &text) {
delegate->setHighlight(Registry::SearchQuery::fromString(text).query());
});
// Clone state if `other` is provided.
if (other) {
if (other->m_searchEdit->text().isEmpty()) {
m_searchModel = new Registry::SearchModel(this);
setTreeViewModel(Core::Application::instance()->docsetRegistry()->model(), true);
for (const QModelIndex &index : other->m_expandedIndexList) {
m_treeView->expand(index);
}
} else {
m_searchEdit->setText(other->m_searchEdit->text());
m_searchModel = other->m_searchModel->clone(this);
setTreeViewModel(m_searchModel, false);
}
// Clone current selection. Signals must be disabled to avoid crash in the event handler.
m_treeView->selectionModel()->blockSignals(true);
for (const QModelIndex &index : other->m_treeView->selectionModel()->selectedIndexes()) {
m_treeView->selectionModel()->select(index, QItemSelectionModel::Select);
}
m_treeView->selectionModel()->blockSignals(false);
// Cannot update position until layout geometry is calculated, so set it in showEvent().
m_pendingVerticalPosition = other->m_treeView->verticalScrollBar()->value();
} else {
m_searchModel = new Registry::SearchModel(this);
setTreeViewModel(Core::Application::instance()->docsetRegistry()->model(), true);
}
connect(m_searchEdit, &QLineEdit::textChanged, this, [this](const QString &text) {
QItemSelectionModel *oldSelectionModel = m_treeView->selectionModel();
if (text.isEmpty()) {
setTreeViewModel(Core::Application::instance()->docsetRegistry()->model(), true);
} else {
setTreeViewModel(m_searchModel, false);
}
QItemSelectionModel *newSelectionModel = m_treeView->selectionModel();
if (newSelectionModel != oldSelectionModel) {
// TODO: Remove once QTBUG-49966 is addressed.
if (oldSelectionModel) {
oldSelectionModel->deleteLater();
}
// Connect to the new selection model.
connect(m_treeView->selectionModel(), &QItemSelectionModel::selectionChanged,
this, &SearchSidebar::navigateToSelectionWithDelay);
}
m_treeView->reset();
Core::Application::instance()->docsetRegistry()->search(text);
});
auto toolBarLayout = new QVBoxLayout();
toolBarLayout->setContentsMargins(4, 0, 4, 0);
toolBarLayout->setSpacing(4);
toolBarLayout->addWidget(m_searchEdit);
auto toolBarFrame = new ToolBarFrame();
toolBarFrame->setLayout(toolBarLayout);
// Setup splitter.
m_splitter = new QSplitter();
m_splitter->setOrientation(Qt::Vertical);
m_splitter->addWidget(m_treeView);
m_splitter->addWidget(m_pageTocView);
connect(m_splitter, &QSplitter::splitterMoved, this, [this]() {
Core::Application::instance()->settings()->tocSplitterState = m_splitter->saveState();
});
// Setup main layout.
auto layout = LayoutHelper::createBorderlessLayout<QVBoxLayout>();
layout->addWidget(toolBarFrame);
layout->addWidget(m_splitter);
setLayout(layout);
// Setup delayed navigation to a page until user makes a pause in typing a search query.
m_delayedNavigationTimer = new QTimer(this);
m_delayedNavigationTimer->setInterval(400);
m_delayedNavigationTimer->setSingleShot(true);
connect(m_delayedNavigationTimer, &QTimer::timeout, this, [this]() {
const QModelIndex index = m_delayedNavigationTimer->property("index").toModelIndex();
if (!index.isValid()) {
return;
}
navigateToIndex(index);
});
// Setup Docset Registry.
auto registry = Core::Application::instance()->docsetRegistry();
using Registry::DocsetRegistry;
connect(registry, &DocsetRegistry::searchCompleted,
this, [this](const QList<Registry::SearchResult> &results) {
if (!isVisible()) {
return;
}
m_delayedNavigationTimer->stop();
m_searchModel->setResults(results);
const QModelIndex index = m_searchModel->index(0, 0, QModelIndex());
m_treeView->setCurrentIndex(index);
m_delayedNavigationTimer->setProperty("index", index);
m_delayedNavigationTimer->start();
});
connect(registry, &DocsetRegistry::docsetAboutToBeUnloaded, this, [this](const QString &name) {
if (isVisible()) {
// Disable updates because removeSearchResultWithName can
// call {begin,end}RemoveRows multiple times, and cause
// degradation of UI responsiveness.
m_treeView->setUpdatesEnabled(false);
m_searchModel->removeSearchResultWithName(name);
m_treeView->setUpdatesEnabled(true);
} else {
m_searchModel->removeSearchResultWithName(name);
}
setupSearchBoxCompletions();
});
connect(registry, &DocsetRegistry::docsetLoaded, this, [this](const QString &) {
setupSearchBoxCompletions();
});
}
void SearchSidebar::setTreeViewModel(QAbstractItemModel *model, bool isRootDecorated)
{
QItemSelectionModel *oldSelectionModel = m_treeView->selectionModel();
m_treeView->setModel(model);
m_treeView->setRootIsDecorated(isRootDecorated);
// Hide all but the first column.
for (int i = 1; i < model->columnCount(); ++i) {
m_treeView->setColumnHidden(i, true);
}
QItemSelectionModel *newSelectionModel = m_treeView->selectionModel();
if (newSelectionModel != oldSelectionModel) {
// TODO: Remove once QTBUG-49966 is addressed.
if (oldSelectionModel) {
oldSelectionModel->deleteLater();
}
// Connect to the new selection model.
connect(m_treeView->selectionModel(), &QItemSelectionModel::selectionChanged,
this, &SearchSidebar::navigateToSelectionWithDelay);
}
}
SearchSidebar *SearchSidebar::clone(QWidget *parent) const
{
return new SearchSidebar(this, parent);
}
Registry::SearchModel *SearchSidebar::pageTocModel() const
{
return m_pageTocModel;
}
void SearchSidebar::focusSearchEdit(bool clear)
{
if (!isVisible()) {
m_pendingSearchEditFocus = true;
return;
}
m_searchEdit->setFocus();
if (clear) {
m_searchEdit->clearQuery();
}
}
void SearchSidebar::search(const Registry::SearchQuery &query)
{
// TODO: Pass Registry::SearchQuery, converting to QString is dumb at this point.
m_searchEdit->setText(query.toString());
}
void SearchSidebar::navigateToIndex(const QModelIndex &index)
{
// When triggered by click, cancel delayed navigation request caused by the selection change.
if (m_delayedNavigationTimer->isActive()
&& m_delayedNavigationTimer->property("index").toModelIndex() == index) {
m_delayedNavigationTimer->stop();
}
const QVariant url = index.data(Registry::ItemDataRole::UrlRole);
if (url.isNull()) {
return;
}
emit navigationRequested(url.toUrl());
}
void SearchSidebar::navigateToIndexAndActivate(const QModelIndex &index)
{
const QVariant url = index.data(Registry::ItemDataRole::UrlRole);
if (url.isNull()) {
return;
}
emit navigationRequested(url.toUrl());
emit activated();
}
void SearchSidebar::navigateToSelectionWithDelay(const QItemSelection &selection)
{
if (selection.isEmpty()) {
return;
}
m_delayedNavigationTimer->setProperty("index", selection.indexes().first());
m_delayedNavigationTimer->start();
}
void SearchSidebar::setupSearchBoxCompletions()
{
QStringList completions;
const auto docsets = Core::Application::instance()->docsetRegistry()->docsets();
for (const Registry::Docset *docset : docsets) {
const QStringList keywords = docset->keywords();
if (keywords.isEmpty())
continue;
completions << keywords.constFirst() + QLatin1Char(':');
}
if (completions.isEmpty())
return;
m_searchEdit->setCompletions(completions);
}
bool SearchSidebar::eventFilter(QObject *object, QEvent *event)
{
if (object == m_searchEdit && event->type() == QEvent::KeyPress) {
auto e = static_cast<QKeyEvent *>(event);
switch (e->key()) {
case Qt::Key_Return:
emit activated();
break;
case Qt::Key_Home:
case Qt::Key_End:
case Qt::Key_Left:
case Qt::Key_Right:
if (!m_searchEdit->text().isEmpty()) {
break;
}
[[fallthrough]];
case Qt::Key_Down:
case Qt::Key_Up:
case Qt::Key_PageDown:
case Qt::Key_PageUp:
QCoreApplication::sendEvent(m_treeView, event);
break;
}
}
return Sidebar::View::eventFilter(object, event);
}
void SearchSidebar::showEvent(QShowEvent *event)
{
Q_UNUSED(event)
if (m_pendingVerticalPosition > 0) {
m_treeView->verticalScrollBar()->setValue(m_pendingVerticalPosition);
m_pendingVerticalPosition = 0;
}
if (m_pendingSearchEditFocus) {
m_searchEdit->setFocus();
m_pendingSearchEditFocus = false;
}
}
| 13,305
|
C++
|
.cpp
| 331
| 33.519637
| 100
| 0.675812
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,948
|
sidebarviewprovider.cpp
|
zealdocs_zeal/src/libs/ui/sidebarviewprovider.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "sidebarviewprovider.h"
#include "browsertab.h"
#include "mainwindow.h"
#include "searchsidebar.h"
using namespace Zeal;
using namespace Zeal::WidgetUi;
SidebarViewProvider::SidebarViewProvider(MainWindow *mainWindow)
: Sidebar::ViewProvider(mainWindow)
, m_mainWindow(mainWindow)
{
connect(m_mainWindow, &MainWindow::currentTabChanged, this, &SidebarViewProvider::viewChanged, Qt::QueuedConnection);
}
Sidebar::View *SidebarViewProvider::view(const QString &id) const
{
if (id == QLatin1String("index"))
return m_mainWindow->currentTab()->searchSidebar();
return nullptr;
}
| 725
|
C++
|
.cpp
| 20
| 33.55
| 121
| 0.76681
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,949
|
docsetlistitemdelegate.cpp
|
zealdocs_zeal/src/libs/ui/docsetlistitemdelegate.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include "docsetlistitemdelegate.h"
#include <registry/itemdatarole.h>
#include <QPainter>
#include <QProgressBar>
using namespace Zeal::WidgetUi;
namespace {
constexpr int ProgressBarWidth = 150;
} // namespace
DocsetListItemDelegate::DocsetListItemDelegate(QObject *parent)
: QStyledItemDelegate(parent)
{
}
void DocsetListItemDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if (index.model()->data(index, ShowProgressRole).toBool()) {
paintProgressBar(painter, option, index);
return;
}
if (index.column() != Registry::SectionIndex::Actions) {
QStyledItemDelegate::paint(painter, option, index);
return;
}
QStyledItemDelegate::paint(painter, option, index);
if (!index.model()->data(index, Registry::ItemDataRole::UpdateAvailableRole).toBool()) {
return;
}
const QString text = tr("Update available");
QFont font(painter->font());
font.setItalic(true);
const QFontMetrics fontMetrics(font);
const int margin = 4; // Random small number
QRect textRect = option.rect.adjusted(-margin, 0, -margin, 0);
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
textRect.setLeft(textRect.right() - fontMetrics.horizontalAdvance(text) - 2);
#else
textRect.setLeft(textRect.right() - fontMetrics.width(text) - 2);
#endif
textRect = QStyle::visualRect(option.direction, option.rect, textRect);
// Constant LeftToRight because we don't need to flip it any further.
// Vertically align the text in the middle to match QCommonStyle behaviour.
const auto alignedRect = QStyle::alignedRect(Qt::LeftToRight, option.displayAlignment,
QSize(textRect.size().width(), fontMetrics.height()), textRect);
painter->save();
QPalette palette = option.palette;
#ifdef Q_OS_WIN32
// QWindowsVistaStyle overrides highlight colour.
if (option.widget->style()->objectName() == QLatin1String("windowsvista")) {
palette.setColor(QPalette::All, QPalette::HighlightedText,
palette.color(QPalette::Active, QPalette::Text));
}
#endif
const QPalette::ColorGroup cg = (option.state & QStyle::State_Active)
? QPalette::Normal : QPalette::Inactive;
if (option.state & QStyle::State_Selected) {
painter->setPen(palette.color(cg, QPalette::HighlightedText));
} else {
painter->setPen(palette.color(cg, QPalette::Text));
}
painter->setFont(font);
painter->drawText(alignedRect, text);
painter->restore();
}
void DocsetListItemDelegate::paintProgressBar(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
bool ok;
const int value = index.model()->data(index, ValueRole).toInt(&ok);
if (!ok) {
QStyledItemDelegate::paint(painter, option, index);
return;
}
// Adjust maximum text width
QStyleOptionViewItem styleOption = option;
styleOption.rect.setRight(styleOption.rect.right() - ProgressBarWidth);
// Size progress bar
QScopedPointer<QProgressBar> renderer(new QProgressBar());
renderer->resize(ProgressBarWidth, styleOption.rect.height());
renderer->setRange(0, 100);
renderer->setValue(value);
const QString format = index.model()->data(index, FormatRole).toString();
if (!format.isEmpty()) {
renderer->setFormat(format);
}
painter->save();
// Paint progress bar
painter->translate(styleOption.rect.topRight());
renderer->render(painter);
painter->restore();
QStyledItemDelegate::paint(painter, styleOption, index);
}
| 3,980
|
C++
|
.cpp
| 96
| 34.520833
| 113
| 0.675662
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,950
|
shortcutedit.cpp
|
zealdocs_zeal/src/libs/ui/widgets/shortcutedit.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include "shortcutedit.h"
#include <QEvent>
#include <QKeyEvent>
using namespace Zeal::WidgetUi;
ShortcutEdit::ShortcutEdit(QWidget *parent)
: ShortcutEdit(QString(), parent)
{
}
ShortcutEdit::ShortcutEdit(const QString &text, QWidget *parent)
: QLineEdit(text, parent)
{
connect(this, &QLineEdit::textChanged, [this](const QString &text) {
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
m_key = QKeySequence(text, QKeySequence::NativeText)[0];
#else
m_key = QKeySequence(text, QKeySequence::NativeText)[0].toCombined();
#endif
});
}
bool ShortcutEdit::event(QEvent *event)
{
switch (event->type()) {
case QEvent::KeyPress: {
auto keyEvent = static_cast<QKeyEvent *>(event);
switch (keyEvent->key()) {
case Qt::Key_Alt:
case Qt::Key_Control:
case Qt::Key_Meta:
case Qt::Key_Shift:
return true;
default:
m_key = keyEvent->key();
m_key |= translateModifiers(keyEvent->modifiers(), keyEvent->text());
setText(keySequence().toString(QKeySequence::NativeText));
}
return true;
}
case QEvent::ShortcutOverride:
case QEvent::KeyRelease:
case QEvent::Shortcut:
return true;
default:
return QLineEdit::event(event);
}
}
QKeySequence ShortcutEdit::keySequence() const
{
return QKeySequence(m_key);
}
void ShortcutEdit::setKeySequence(const QKeySequence &keySequence)
{
setText(keySequence.toString(QKeySequence::NativeText));
}
// Inspired by QKeySequenceEditPrivate::translateModifiers()
int ShortcutEdit::translateModifiers(Qt::KeyboardModifiers state, const QString &text)
{
int modifiers = 0;
// The shift modifier only counts when it is not used to type a symbol
// that is only reachable using the shift key
if ((state & Qt::ShiftModifier)
&& (text.isEmpty() || !text.at(0).isPrint()
|| text.at(0).isLetterOrNumber() || text.at(0).isSpace())) {
modifiers |= Qt::ShiftModifier;
}
modifiers |= state & Qt::ControlModifier;
modifiers |= state & Qt::MetaModifier;
modifiers |= state & Qt::AltModifier;
return modifiers;
}
| 2,347
|
C++
|
.cpp
| 72
| 27.569444
| 86
| 0.671082
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,951
|
searchedit.cpp
|
zealdocs_zeal/src/libs/ui/widgets/searchedit.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include "searchedit.h"
#include <registry/searchquery.h>
#include <QCompleter>
#include <QKeyEvent>
#include <QLabel>
#include <QStyle>
#include <QTimer>
using namespace Zeal;
using namespace Zeal::WidgetUi;
SearchEdit::SearchEdit(QWidget *parent)
: QLineEdit(parent)
{
setClearButtonEnabled(true);
setPlaceholderText(tr("Search"));
m_completionLabel = new QLabel(this);
m_completionLabel->setObjectName(QStringLiteral("completer"));
m_completionLabel->setStyleSheet(QStringLiteral("QLabel#completer { color: gray; }"));
m_completionLabel->setFont(font());
connect(this, &SearchEdit::textChanged, this, &SearchEdit::showCompletions);
}
// Makes the line edit use autocompletion.
void SearchEdit::setCompletions(const QStringList &completions)
{
delete m_prefixCompleter;
m_prefixCompleter = new QCompleter(completions, this);
m_prefixCompleter->setCompletionMode(QCompleter::InlineCompletion);
m_prefixCompleter->setCaseSensitivity(Qt::CaseInsensitive);
m_prefixCompleter->setWidget(this);
}
// Clear input with consideration to docset filters
void SearchEdit::clearQuery()
{
setText(text().left(queryStart()));
}
void SearchEdit::selectQuery()
{
if (text().isEmpty())
return;
const int pos = hasSelectedText() ? selectionStart() : cursorPosition();
const int queryPos = queryStart();
const int textSize = text().size();
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
if (pos >= queryPos && selectionEnd() < textSize) {
#else
const int selectionEnd = hasSelectedText() ? pos + selectedText().size() : -1;
if (pos >= queryPos && selectionEnd < textSize) {
#endif
setSelection(queryPos, textSize);
return;
}
// Avoid some race condition which breaks Ctrl+K shortcut.
QTimer::singleShot(0, this, &QLineEdit::selectAll);
}
bool SearchEdit::event(QEvent *event)
{
switch (event->type()) {
case QEvent::KeyPress: {
auto keyEvent = static_cast<QKeyEvent *>(event);
// Tab key cannot be overriden in keyPressEvent().
if (keyEvent->key() == Qt::Key_Tab) {
const QString completed = currentCompletion(text());
if (!completed.isEmpty()) {
setText(completed);
}
return true;
} else if (keyEvent->key() == Qt::Key_Escape) {
clearQuery();
return true;
}
break;
}
case QEvent::ShortcutOverride: {
// TODO: Should be obtained from the ActionManager.
static const QStringList focusShortcuts = {
QStringLiteral("Ctrl+K"),
QStringLiteral("Ctrl+L")
};
auto keyEvent = static_cast<QKeyEvent *>(event);
const int keyCode = keyEvent->key() | static_cast<int>(keyEvent->modifiers());
if (focusShortcuts.contains(QKeySequence(keyCode).toString())) {
selectQuery();
event->accept();
return true;
}
break;
}
default:
break;
}
return QLineEdit::event(event);
}
void SearchEdit::focusInEvent(QFocusEvent *event)
{
QLineEdit::focusInEvent(event);
// Do not change the default behaviour when focused with mouse.
if (event->reason() == Qt::MouseFocusReason)
return;
selectQuery();
}
void SearchEdit::showCompletions(const QString &newValue)
{
if (!isVisible())
return;
const int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
const int textWidth = fontMetrics().horizontalAdvance(newValue);
#else
const int textWidth = fontMetrics().width(newValue);
#endif
if (m_prefixCompleter)
m_prefixCompleter->setCompletionPrefix(text());
const QString completed = currentCompletion(newValue).mid(newValue.size());
#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
const QSize labelSize(fontMetrics().horizontalAdvance(completed), size().height());
#else
const QSize labelSize(fontMetrics().width(completed), size().height());
#endif
const int shiftX = static_cast<int>(window()->devicePixelRatioF() * (frameWidth + 2)) + textWidth;
m_completionLabel->setMinimumSize(labelSize);
m_completionLabel->move(shiftX, 0);
m_completionLabel->setText(completed);
}
QString SearchEdit::currentCompletion(const QString &text) const
{
if (text.isEmpty() || !m_prefixCompleter)
return QString();
return m_prefixCompleter->currentCompletion();
}
int SearchEdit::queryStart() const
{
const Registry::SearchQuery currentQuery = Registry::SearchQuery::fromString(text());
// Keep the filter for the first Escape press
return currentQuery.query().isEmpty() ? 0 : currentQuery.keywordPrefixSize();
}
| 4,908
|
C++
|
.cpp
| 137
| 30.693431
| 102
| 0.687408
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,952
|
toolbarframe.cpp
|
zealdocs_zeal/src/libs/ui/widgets/toolbarframe.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "toolbarframe.h"
#include <QPainter>
using namespace Zeal::WidgetUi;
ToolBarFrame::ToolBarFrame(QWidget *parent)
: QWidget(parent)
{
setMaximumHeight(40);
setMinimumHeight(40);
}
void ToolBarFrame::paintEvent(QPaintEvent *event)
{
QWidget::paintEvent(event);
// Draw a line at the bottom.
QPainter painter(this);
painter.setPen(palette().mid().color());
painter.drawLine(0, height() - 1, width() - 1, height() - 1);
}
| 572
|
C++
|
.cpp
| 19
| 27.105263
| 65
| 0.711152
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,955
|
qxtglobalshortcut.cpp
|
zealdocs_zeal/src/libs/ui/qxtglobalshortcut/qxtglobalshortcut.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
/****************************************************************************
// Copyright (C) 2006 - 2011, the LibQxt project.
** See the Qxt AUTHORS file for a list of authors and copyright holders.
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the LibQxt project nor the
** names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
** <http://libqxt.org> <foundation@libqxt.org>
*****************************************************************************/
#include "qxtglobalshortcut.h"
#include "qxtglobalshortcut_p.h"
#include <QAbstractEventDispatcher>
#ifndef Q_OS_MACOS
int QxtGlobalShortcutPrivate::ref = 0;
#endif // Q_OS_MACOS
QHash<QPair<quint32, quint32>, QxtGlobalShortcut *> QxtGlobalShortcutPrivate::shortcuts;
QxtGlobalShortcutPrivate::QxtGlobalShortcutPrivate(QxtGlobalShortcut *qq)
: q_ptr(qq)
{
#ifndef Q_OS_MACOS
if (ref == 0)
QAbstractEventDispatcher::instance()->installNativeEventFilter(this);
++ref;
#endif // Q_OS_MACOS
}
QxtGlobalShortcutPrivate::~QxtGlobalShortcutPrivate()
{
#ifndef Q_OS_MACOS
--ref;
if (ref == 0) {
QAbstractEventDispatcher *ed = QAbstractEventDispatcher::instance();
if (ed != nullptr) {
ed->removeNativeEventFilter(this);
}
}
#endif // Q_OS_MACOS
}
bool QxtGlobalShortcutPrivate::setShortcut(const QKeySequence &shortcut)
{
Q_Q(QxtGlobalShortcut);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
const int combination = shortcut[0];
#else
const int combination = shortcut[0].toCombined();
#endif
key = shortcut.isEmpty() ? Qt::Key(0) : Qt::Key(combination & ~Qt::KeyboardModifierMask);
mods = shortcut.isEmpty() ? Qt::NoModifier : Qt::KeyboardModifiers(combination & Qt::KeyboardModifierMask);
const quint32 nativeKey = nativeKeycode(key);
const quint32 nativeMods = nativeModifiers(mods);
const bool res = registerShortcut(nativeKey, nativeMods);
if (res)
shortcuts.insert({nativeKey, nativeMods}, q);
else
qWarning("QxtGlobalShortcut failed to register: %s", qPrintable(QKeySequence(key | mods).toString()));
return res;
}
bool QxtGlobalShortcutPrivate::unsetShortcut()
{
Q_Q(QxtGlobalShortcut);
bool res = false;
const quint32 nativeKey = nativeKeycode(key);
const quint32 nativeMods = nativeModifiers(mods);
if (shortcuts.value({nativeKey, nativeMods}) == q)
res = unregisterShortcut(nativeKey, nativeMods);
if (res)
shortcuts.remove({nativeKey, nativeMods});
else
qWarning("QxtGlobalShortcut failed to unregister: %s", qPrintable(QKeySequence(key | mods).toString()));
key = Qt::Key(0);
mods = Qt::KeyboardModifiers(Qt::NoModifier);
return res;
}
bool QxtGlobalShortcutPrivate::activateShortcut(quint32 nativeKey, quint32 nativeMods)
{
QxtGlobalShortcut *shortcut = shortcuts.value({nativeKey, nativeMods});
if (!shortcut || !shortcut->isEnabled())
return false;
emit shortcut->activated();
return true;
}
/*!
\class QxtGlobalShortcut
\inmodule QxtWidgets
\brief The QxtGlobalShortcut class provides a global shortcut aka "hotkey".
A global shortcut triggers even if the application is not active. This
makes it easy to implement applications that react to certain shortcuts
still if some other application is active or if the application is for
example minimized to the system tray.
Example usage:
\code
QxtGlobalShortcut *shortcut = new QxtGlobalShortcut(window);
connect(shortcut, SIGNAL(activated()), window, SLOT(toggleVisibility()));
shortcut->setShortcut(QKeySequence("Ctrl+Shift+F12"));
\endcode
\bold {Note:} Since Qxt 0.6 QxtGlobalShortcut no more requires QxtApplication.
*/
/*!
\fn QxtGlobalShortcut::activated()
This signal is emitted when the user types the shortcut's key sequence.
\sa shortcut
*/
/*!
Constructs a new QxtGlobalShortcut with \a parent.
*/
QxtGlobalShortcut::QxtGlobalShortcut(QObject *parent)
: QObject(parent)
, d_ptr(new QxtGlobalShortcutPrivate(this))
{
}
/*!
Constructs a new QxtGlobalShortcut with \a shortcut and \a parent.
*/
QxtGlobalShortcut::QxtGlobalShortcut(const QKeySequence &shortcut, QObject *parent)
: QObject(parent)
, d_ptr(new QxtGlobalShortcutPrivate(this))
{
setShortcut(shortcut);
}
/*!
Destructs the QxtGlobalShortcut.
*/
QxtGlobalShortcut::~QxtGlobalShortcut()
{
Q_D(QxtGlobalShortcut);
if (d->key != 0)
d->unsetShortcut();
delete d;
}
/*!
\property QxtGlobalShortcut::shortcut
\brief the shortcut key sequence
\bold {Note:} Notice that corresponding key press and release events are not
delivered for registered global shortcuts even if they are disabled.
Also, comma separated key sequences are not supported.
Only the first part is used:
\code
qxtShortcut->setShortcut(QKeySequence("Ctrl+Alt+A,Ctrl+Alt+B"));
Q_ASSERT(qxtShortcut->shortcut() == QKeySequence("Ctrl+Alt+A"));
\endcode
*/
QKeySequence QxtGlobalShortcut::shortcut() const
{
Q_D(const QxtGlobalShortcut);
return QKeySequence(d->key | d->mods);
}
bool QxtGlobalShortcut::setShortcut(const QKeySequence &shortcut)
{
Q_D(QxtGlobalShortcut);
if (d->key != 0 && !d->unsetShortcut())
return false;
if (shortcut.isEmpty())
return true;
return d->setShortcut(shortcut);
}
/*!
\property QxtGlobalShortcut::enabled
\brief whether the shortcut is enabled
A disabled shortcut does not get activated.
The default value is \c true.
\sa setDisabled()
*/
bool QxtGlobalShortcut::isEnabled() const
{
Q_D(const QxtGlobalShortcut);
return d->enabled;
}
/*!
* \brief QxtGlobalShortcut::isSupported checks if the current platform is supported.
*/
bool QxtGlobalShortcut::isSupported()
{
return QxtGlobalShortcutPrivate::isSupported();
}
void QxtGlobalShortcut::setEnabled(bool enabled)
{
Q_D(QxtGlobalShortcut);
d->enabled = enabled;
}
| 7,499
|
C++
|
.cpp
| 200
| 33.99
| 112
| 0.72119
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,956
|
qxtglobalshortcut_noop.cpp
|
zealdocs_zeal/src/libs/ui/qxtglobalshortcut/qxtglobalshortcut_noop.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "qxtglobalshortcut_p.h"
bool QxtGlobalShortcutPrivate::isSupported()
{
return false;
}
bool QxtGlobalShortcutPrivate::nativeEventFilter(const QByteArray &eventType,
void *message,
NativeEventFilterResult *result)
{
Q_UNUSED(eventType)
Q_UNUSED(message)
Q_UNUSED(result)
return false;
}
quint32 QxtGlobalShortcutPrivate::nativeModifiers(Qt::KeyboardModifiers modifiers)
{
Q_UNUSED(modifiers)
return 0;
}
quint32 QxtGlobalShortcutPrivate::nativeKeycode(Qt::Key key)
{
Q_UNUSED(key)
return 0;
}
bool QxtGlobalShortcutPrivate::registerShortcut(quint32 nativeKey, quint32 nativeMods)
{
Q_UNUSED(nativeKey)
Q_UNUSED(nativeMods)
return false;
}
bool QxtGlobalShortcutPrivate::unregisterShortcut(quint32 nativeKey, quint32 nativeMods)
{
Q_UNUSED(nativeKey)
Q_UNUSED(nativeMods)
return false;
}
| 1,072
|
C++
|
.cpp
| 38
| 22.736842
| 88
| 0.708415
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,957
|
qxtglobalshortcut_x11.cpp
|
zealdocs_zeal/src/libs/ui/qxtglobalshortcut/qxtglobalshortcut_x11.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
/****************************************************************************
// Copyright (C) 2006 - 2011, the LibQxt project.
** See the Qxt AUTHORS file for a list of authors and copyright holders.
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the LibQxt project nor the
** names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
** <http://libqxt.org> <foundation@libqxt.org>
*****************************************************************************/
#include "qxtglobalshortcut_p.h"
#include <QGuiApplication>
#include <QKeySequence>
#include <QScopedPointer>
#include <QVector>
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
#include <QX11Info>
#else
#include <QtGui/private/qtx11extras_p.h>
#endif
#include <X11/Xlib.h>
#include <xcb/xcb.h>
#include <xcb/xcb_keysyms.h>
namespace {
constexpr quint32 maskModifiers[] = {
0, XCB_MOD_MASK_2, XCB_MOD_MASK_LOCK, (XCB_MOD_MASK_2 | XCB_MOD_MASK_LOCK)
};
} // namespace
bool QxtGlobalShortcutPrivate::isSupported()
{
return QGuiApplication::platformName() == QLatin1String("xcb");
}
bool QxtGlobalShortcutPrivate::nativeEventFilter(const QByteArray &eventType,
void *message, NativeEventFilterResult *result)
{
Q_UNUSED(result)
if (eventType != "xcb_generic_event_t")
return false;
auto event = static_cast<xcb_generic_event_t *>(message);
if ((event->response_type & ~0x80) != XCB_KEY_PRESS)
return false;
auto keyPressEvent = static_cast<xcb_key_press_event_t *>(message);
// Avoid keyboard freeze
xcb_connection_t *xcbConnection = QX11Info::connection();
xcb_allow_events(xcbConnection, XCB_ALLOW_REPLAY_KEYBOARD, keyPressEvent->time);
xcb_flush(xcbConnection);
unsigned int keycode = keyPressEvent->detail;
unsigned int keystate = 0;
if (keyPressEvent->state & XCB_MOD_MASK_1)
keystate |= XCB_MOD_MASK_1;
if (keyPressEvent->state & XCB_MOD_MASK_CONTROL)
keystate |= XCB_MOD_MASK_CONTROL;
if (keyPressEvent->state & XCB_MOD_MASK_4)
keystate |= XCB_MOD_MASK_4;
if (keyPressEvent->state & XCB_MOD_MASK_SHIFT)
keystate |= XCB_MOD_MASK_SHIFT;
return activateShortcut(keycode, keystate);
}
quint32 QxtGlobalShortcutPrivate::nativeModifiers(Qt::KeyboardModifiers modifiers)
{
quint32 native = 0;
if (modifiers & Qt::ShiftModifier)
native |= XCB_MOD_MASK_SHIFT;
if (modifiers & Qt::ControlModifier)
native |= XCB_MOD_MASK_CONTROL;
if (modifiers & Qt::AltModifier)
native |= XCB_MOD_MASK_1;
if (modifiers & Qt::MetaModifier)
native |= XCB_MOD_MASK_4;
return native;
}
quint32 QxtGlobalShortcutPrivate::nativeKeycode(Qt::Key key)
{
quint32 native = 0;
KeySym keysym = XStringToKeysym(QKeySequence(key).toString().toLatin1().data());
if (keysym == XCB_NO_SYMBOL)
keysym = static_cast<ushort>(key);
xcb_key_symbols_t *xcbKeySymbols = xcb_key_symbols_alloc(QX11Info::connection());
QScopedPointer<xcb_keycode_t, QScopedPointerPodDeleter> keycodes(
xcb_key_symbols_get_keycode(xcbKeySymbols, keysym));
if (!keycodes.isNull())
native = keycodes.data()[0]; // Use the first keycode
xcb_key_symbols_free(xcbKeySymbols);
return native;
}
bool QxtGlobalShortcutPrivate::registerShortcut(quint32 nativeKey, quint32 nativeMods)
{
xcb_connection_t *xcbConnection = QX11Info::connection();
QList<xcb_void_cookie_t> xcbCookies;
for (quint32 maskMods : maskModifiers) {
xcbCookies << xcb_grab_key_checked(xcbConnection, 1, QX11Info::appRootWindow(),
nativeMods | maskMods, nativeKey,
XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC);
}
bool failed = false;
for (xcb_void_cookie_t cookie : std::as_const(xcbCookies)) {
QScopedPointer<xcb_generic_error_t, QScopedPointerPodDeleter> error(xcb_request_check(xcbConnection, cookie));
failed = !error.isNull();
}
if (failed)
unregisterShortcut(nativeKey, nativeMods);
return !failed;
}
bool QxtGlobalShortcutPrivate::unregisterShortcut(quint32 nativeKey, quint32 nativeMods)
{
xcb_connection_t *xcbConnection = QX11Info::connection();
QList<xcb_void_cookie_t> xcbCookies;
for (quint32 maskMods : maskModifiers) {
xcb_ungrab_key(xcbConnection, nativeKey, QX11Info::appRootWindow(), nativeMods | maskMods);
}
bool failed = false;
for (xcb_void_cookie_t cookie : xcbCookies) {
QScopedPointer<xcb_generic_error_t, QScopedPointerPodDeleter> error(xcb_request_check(xcbConnection, cookie));
failed = !error.isNull();
}
return !failed;
}
| 6,238
|
C++
|
.cpp
| 138
| 40.369565
| 118
| 0.693904
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,959
|
viewprovider.cpp
|
zealdocs_zeal/src/libs/sidebar/viewprovider.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "viewprovider.h"
using namespace Zeal::Sidebar;
ViewProvider::ViewProvider(QObject *parent)
: QObject(parent)
{
}
| 237
|
C++
|
.cpp
| 8
| 27.75
| 61
| 0.752212
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,960
|
view.cpp
|
zealdocs_zeal/src/libs/sidebar/view.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "view.h"
using namespace Zeal::Sidebar;
View::View(QWidget *parent)
: QWidget(parent)
{
}
| 213
|
C++
|
.cpp
| 8
| 24.75
| 61
| 0.722772
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,961
|
container.cpp
|
zealdocs_zeal/src/libs/sidebar/container.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "container.h"
#include "view.h"
#include <core/application.h>
#include <core/settings.h>
#include <ui/widgets/layouthelper.h>
#include <QSplitter>
#include <QVBoxLayout>
using namespace Zeal;
using namespace Zeal::Sidebar;
Container::Container(QWidget *parent)
: QWidget(parent)
{
setMinimumWidth(150);
// Setup splitter.
m_splitter = new QSplitter();
m_splitter->setOrientation(Qt::Vertical);
connect(m_splitter, &QSplitter::splitterMoved, this, [this]() {
Core::Application::instance()->settings()->tocSplitterState = m_splitter->saveState();
});
// Setup main layout.
auto layout = WidgetUi::LayoutHelper::createBorderlessLayout<QVBoxLayout>();
layout->addWidget(m_splitter);
setLayout(layout);
}
Container::~Container() = default;
void Container::addView(View *view)
{
if (m_views.contains(view))
return;
m_views.append(view);
m_splitter->addWidget(view);
}
| 1,061
|
C++
|
.cpp
| 34
| 27.764706
| 94
| 0.715551
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,962
|
proxyview.cpp
|
zealdocs_zeal/src/libs/sidebar/proxyview.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "proxyview.h"
#include "viewprovider.h"
#include <ui/widgets/layouthelper.h>
#include <QVBoxLayout>
#include <utility>
using namespace Zeal;
using namespace Zeal::Sidebar;
ProxyView::ProxyView(ViewProvider *provider, QString id, QWidget *parent)
: View(parent)
, m_viewProvider(provider)
, m_viewId(std::move(id))
{
setLayout(WidgetUi::LayoutHelper::createBorderlessLayout<QVBoxLayout>());
connect(m_viewProvider, &ViewProvider::viewChanged, this, [this]() {
auto view = m_viewProvider->view(m_viewId);
if (view == nullptr) {
qWarning("ViewProvider returned invalid view!");
return;
}
if (m_view == view)
return;
clearCurrentView();
layout()->addWidget(view);
view->show();
m_view = view;
});
}
ProxyView::~ProxyView()
{
clearCurrentView();
}
void ProxyView::clearCurrentView()
{
// Unparent the view, because we don't own it.
QLayout *l = layout();
if (l->isEmpty())
return;
m_view->hide();
l->removeWidget(m_view);
m_view->setParent(nullptr);
}
| 1,236
|
C++
|
.cpp
| 43
| 23.72093
| 77
| 0.651695
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,963
|
webcontrol.cpp
|
zealdocs_zeal/src/libs/browser/webcontrol.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include "webcontrol.h"
#include "searchtoolbar.h"
#include "webview.h"
#include <core/networkaccessmanager.h>
#include <QDataStream>
#include <QKeyEvent>
#include <QVBoxLayout>
#include <QWebChannel>
#include <QWebEngineHistory>
#include <QWebEnginePage>
#include <QWebEngineSettings>
using namespace Zeal::Browser;
WebControl::WebControl(QWidget *parent)
: QWidget(parent)
{
auto layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
m_webView = new WebView();
setFocusProxy(m_webView);
connect(m_webView->page(), &QWebEnginePage::linkHovered, this, [this](const QString &link) {
if (Core::NetworkAccessManager::isLocalUrl(QUrl(link))) {
return;
}
m_webView->setToolTip(link);
});
connect(m_webView, &QWebEngineView::titleChanged, this, &WebControl::titleChanged);
connect(m_webView, &QWebEngineView::urlChanged, this, &WebControl::urlChanged);
layout->addWidget(m_webView);
setLayout(layout);
}
void WebControl::focus()
{
m_webView->setFocus();
}
int WebControl::zoomLevel() const
{
return m_webView->zoomLevel();
}
void WebControl::setZoomLevel(int level)
{
m_webView->setZoomLevel(level);
}
void WebControl::zoomIn()
{
m_webView->zoomIn();
}
void WebControl::zoomOut()
{
m_webView->zoomOut();
}
void WebControl::resetZoom()
{
m_webView->resetZoom();
}
void WebControl::setJavaScriptEnabled(bool enabled)
{
m_webView->page()->settings()->setAttribute(QWebEngineSettings::JavascriptEnabled, enabled);
}
void WebControl::setWebBridgeObject(const QString &name, QObject *object)
{
QWebEnginePage *page = m_webView->page();
QWebChannel *channel = new QWebChannel(page);
channel->registerObject(name, object);
page->setWebChannel(channel);
}
void WebControl::load(const QUrl &url)
{
m_webView->load(url);
}
void WebControl::activateSearchBar()
{
if (m_searchToolBar == nullptr) {
m_searchToolBar = new SearchToolBar(m_webView);
layout()->addWidget(m_searchToolBar);
}
if (m_webView->hasSelection()) {
const QString selectedText = m_webView->selectedText().simplified();
if (!selectedText.isEmpty()) {
m_searchToolBar->setText(selectedText);
}
}
m_searchToolBar->activate();
}
void WebControl::back()
{
m_webView->back();
}
void WebControl::forward()
{
m_webView->forward();
}
bool WebControl::canGoBack() const
{
return m_webView->history()->canGoBack();
}
bool WebControl::canGoForward() const
{
return m_webView->history()->canGoForward();
}
QString WebControl::title() const
{
return m_webView->title();
}
QUrl WebControl::url() const
{
return m_webView->url();
}
QWebEngineHistory *WebControl::history() const
{
return m_webView->history();
}
void WebControl::restoreHistory(const QByteArray &array)
{
QDataStream stream(array);
stream >> *m_webView->history();
}
QByteArray WebControl::saveHistory() const
{
QByteArray array;
QDataStream stream(&array, QIODevice::WriteOnly);
stream << *m_webView->history();
return array;
}
void WebControl::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Slash:
activateSearchBar();
break;
default:
event->ignore();
break;
}
}
| 3,516
|
C++
|
.cpp
| 138
| 22.021739
| 96
| 0.704457
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,964
|
settings.cpp
|
zealdocs_zeal/src/libs/browser/settings.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "settings.h"
#include "urlrequestinterceptor.h"
#include <core/settings.h>
#include <QFileInfo>
#include <QWebEngineProfile>
#include <QWebEngineSettings>
#include <QWebEngineScript>
#include <QWebEngineScriptCollection>
namespace {
constexpr char DarkModeCssUrl[] = "qrc:///browser/assets/css/darkmode.css";
constexpr char HighlightOnNavigateCssUrl[] = "qrc:///browser/assets/css/highlight.css";
}
using namespace Zeal;
using namespace Zeal::Browser;
QWebEngineProfile *Settings::m_webProfile = nullptr;
Settings::Settings(Core::Settings *appSettings, QObject *parent)
: QObject(parent)
, m_appSettings(appSettings)
{
Q_ASSERT(!m_webProfile);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
// Create a new off-the-record profile.
m_webProfile = new QWebEngineProfile(this);
#else
// Default profile for Qt 6 is off-the-record.
m_webProfile = QWebEngineProfile::defaultProfile();
#endif
// Setup URL interceptor.
#if QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)
m_webProfile->setUrlRequestInterceptor(new UrlRequestInterceptor(this));
#else
m_webProfile->setRequestInterceptor(new UrlRequestInterceptor(this));
#endif
// Listen to settings changes.
connect(m_appSettings, &Core::Settings::updated, this, &Settings::applySettings);
applySettings();
}
void Settings::applySettings()
{
m_webProfile->settings()->setAttribute(QWebEngineSettings::ScrollAnimatorEnabled,
m_appSettings->isSmoothScrollingEnabled);
// Qt 6.7+ does not require restart to enable dark mode.
#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
m_webProfile->settings()->setAttribute(QWebEngineSettings::ForceDarkMode,
m_appSettings->isDarkModeEnabled());
#endif
// Apply custom CSS.
// TODO: Apply to all open pages.
m_webProfile->scripts()->clear(); // Remove all scripts first.
// Qt 5.14+ uses native Chromium dark mode.
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
if (m_appSettings->isDarkModeEnabled()) {
setCustomStyleSheet(QStringLiteral("_zeal_darkstylesheet"), DarkModeCssUrl);
}
#endif
if (m_appSettings->isHighlightOnNavigateEnabled) {
setCustomStyleSheet(QStringLiteral("_zeal_highlightstylesheet"), HighlightOnNavigateCssUrl);
}
if (QFileInfo::exists(m_appSettings->customCssFile)) {
setCustomStyleSheet(QStringLiteral("_zeal_userstylesheet"), m_appSettings->customCssFile);
}
}
QWebEngineProfile *Settings::defaultProfile()
{
Q_ASSERT(m_webProfile);
return m_webProfile;
}
void Settings::setCustomStyleSheet(const QString &name, const QString &cssUrl)
{
QString cssInjectCode = QLatin1String("(function() {"
"let head = document.getElementsByTagName('head')[0];"
"if (!head) { console.error('Cannot set custom stylesheet.'); return; }"
"let link = document.createElement('link');"
"link.rel = 'stylesheet';"
"link.type = 'text/css';"
"link.href = '%1';"
"link.media = 'all';"
"head.appendChild(link);"
"})()");
QWebEngineScript script;
script.setName(name);
script.setSourceCode(cssInjectCode.arg(cssUrl));
script.setInjectionPoint(QWebEngineScript::DocumentReady);
script.setRunsOnSubFrames(true);
m_webProfile->scripts()->insert(script);
}
| 3,542
|
C++
|
.cpp
| 88
| 34.545455
| 100
| 0.694817
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,965
|
webview.cpp
|
zealdocs_zeal/src/libs/browser/webview.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include "webview.h"
#include "webcontrol.h"
#include "webpage.h"
#include <core/application.h>
#include <core/settings.h>
#include <ui/browsertab.h>
#include <ui/mainwindow.h>
#include <QApplication>
#include <QCheckBox>
#include <QDesktopServices>
#include <QMenu>
#include <QMessageBox>
#include <QPushButton>
#include <QVector>
#include <QWebEngineProfile>
#include <QWebEngineSettings>
#include <QWheelEvent>
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
#include <QWebEngineContextMenuData>
#else
#include <QWebEngineContextMenuRequest>
#endif
using namespace Zeal::Browser;
WebView::WebView(QWidget *parent)
: QWebEngineView(parent)
{
setPage(new WebPage(this));
setZoomLevel(defaultZoomLevel());
// Enable plugins for PDF support.
settings()->setAttribute(QWebEngineSettings::PluginsEnabled, true);
settings()->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, false);
QApplication::instance()->installEventFilter(this);
}
int WebView::zoomLevel() const
{
return m_zoomLevel;
}
void WebView::setZoomLevel(int level)
{
if (level == m_zoomLevel) {
return;
}
level = qMax(0, level);
level = qMin(level, availableZoomLevels().size() - 1);
m_zoomLevel = level;
// Scale the webview relative to the DPI of the screen.
const double dpiZoomFactor = logicalDpiY() / 96.0;
setZoomFactor(availableZoomLevels().at(level) / 100.0 * dpiZoomFactor);
emit zoomLevelChanged();
}
const QVector<int> &WebView::availableZoomLevels()
{
static const QVector<int> zoomLevels = {30, 40, 50, 67, 80, 90, 100,
110, 120, 133, 150, 170, 200,
220, 233, 250, 270, 285, 300};
return zoomLevels;
}
int WebView::defaultZoomLevel()
{
static const int level = availableZoomLevels().indexOf(100);
return level;
}
void WebView::zoomIn()
{
setZoomLevel(m_zoomLevel + 1);
}
void WebView::zoomOut()
{
setZoomLevel(m_zoomLevel - 1);
}
void WebView::resetZoom()
{
setZoomLevel(defaultZoomLevel());
}
QWebEngineView *WebView::createWindow(QWebEnginePage::WebWindowType type)
{
Q_UNUSED(type)
return Core::Application::instance()->mainWindow()->createTab()->webControl()->m_webView;
}
void WebView::contextMenuEvent(QContextMenuEvent *event)
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
const QWebEngineContextMenuData& contextData = page()->contextMenuData();
if (!contextData.isValid()) {
QWebEngineView::contextMenuEvent(event);
return;
}
#else
QWebEngineContextMenuRequest *contextMenuRequest = lastContextMenuRequest();
if (contextMenuRequest == nullptr) {
QWebEngineView::contextMenuEvent(event);
return;
}
#endif
event->accept();
if (m_contextMenu) {
m_contextMenu->deleteLater();
}
m_contextMenu = new QMenu(this);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QUrl linkUrl = contextData.linkUrl();
#else
QUrl linkUrl = contextMenuRequest->linkUrl();
#endif
if (linkUrl.isValid()) {
const QString scheme = linkUrl.scheme();
if (scheme != QLatin1String("javascript")) {
m_contextMenu->addAction(tr("Open Link in New Tab"), this, [this]() {
triggerPageAction(QWebEnginePage::WebAction::OpenLinkInNewWindow);
});
}
if (scheme != QLatin1String("qrc")) {
if (scheme != QLatin1String("javascript")) {
m_contextMenu->addAction(tr("Open Link in Desktop Browser"), this, [linkUrl]() {
QDesktopServices::openUrl(linkUrl);
});
}
m_contextMenu->addAction(pageAction(QWebEnginePage::CopyLinkToClipboard));
}
}
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
const QString selectedText = contextData.selectedText();
#else
const QString selectedText = contextMenuRequest->selectedText();
#endif
if (!selectedText.isEmpty()) {
if (!m_contextMenu->isEmpty()) {
m_contextMenu->addSeparator();
}
m_contextMenu->addAction(pageAction(QWebEnginePage::Copy));
}
if (!linkUrl.isValid() && url().scheme() != QLatin1String("qrc")) {
if (!m_contextMenu->isEmpty()) {
m_contextMenu->addSeparator();
}
m_contextMenu->addAction(pageAction(QWebEnginePage::Back));
m_contextMenu->addAction(pageAction(QWebEnginePage::Forward));
m_contextMenu->addSeparator();
m_contextMenu->addAction(tr("Open Page in Desktop Browser"), this, [this]() {
QDesktopServices::openUrl(url());
});
}
if (m_contextMenu->isEmpty()) {
return;
}
m_contextMenu->popup(event->globalPos());
}
bool WebView::handleMouseReleaseEvent(QMouseEvent *event)
{
switch (event->button()) {
case Qt::BackButton:
// Check if cursor is still inside webview.
if (rect().contains(event->pos())) {
back();
}
event->accept();
return true;
case Qt::ForwardButton:
if (rect().contains(event->pos())) {
forward();
}
event->accept();
return true;
default:
break;
}
return false;
}
bool WebView::handleWheelEvent(QWheelEvent *event)
{
if (event->modifiers() & Qt::ControlModifier) {
const QPoint angleDelta = event->angleDelta();
int delta = qAbs(angleDelta.x()) > qAbs(angleDelta.y()) ? angleDelta.x() : angleDelta.y();
const int direction = delta > 0 ? 1 : -1;
int levelDelta = 0;
while (delta * direction >= 120) {
levelDelta += direction;
delta -= 120 * direction;
}
setZoomLevel(m_zoomLevel + levelDelta);
event->accept();
return true;
}
return false;
}
bool WebView::eventFilter(QObject *watched, QEvent *event)
{
if (watched->parent() == this) {
switch (event->type()) {
case QEvent::MouseButtonRelease:
if (handleMouseReleaseEvent(static_cast<QMouseEvent *>(event))) {
return true;
}
break;
case QEvent::Wheel:
if (handleWheelEvent(static_cast<QWheelEvent *>(event))) {
return true;
}
break;
default:
break;
}
}
return QWebEngineView::eventFilter(watched, event);
}
| 6,592
|
C++
|
.cpp
| 208
| 25.475962
| 98
| 0.640588
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,966
|
searchtoolbar.cpp
|
zealdocs_zeal/src/libs/browser/searchtoolbar.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "searchtoolbar.h"
#include <QAction>
#include <QApplication>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QLineEdit>
#include <QStyle>
#include <QToolButton>
#include <QWebEnginePage>
#include <QWebEngineView>
using namespace Zeal::Browser;
SearchToolBar::SearchToolBar(QWebEngineView *webView, QWidget *parent)
: QWidget(parent)
, m_webView(webView)
{
auto layout = new QHBoxLayout(this);
layout->setContentsMargins(4, 4, 4, 4);
layout->setSpacing(4);
m_lineEdit = new QLineEdit();
m_lineEdit->installEventFilter(this);
m_lineEdit->setPlaceholderText(tr("Find in page"));
m_lineEdit->setMaximumWidth(200);
connect(m_lineEdit, &QLineEdit::textChanged, this, &SearchToolBar::findNext);
connect(m_lineEdit, &QLineEdit::textChanged, this, &SearchToolBar::updateHighlight);
layout->addWidget(m_lineEdit);
m_findPreviousButton = new QToolButton();
m_findPreviousButton->setAutoRaise(true);
m_findPreviousButton->setIcon(qApp->style()->standardIcon(QStyle::SP_ArrowBack));
m_findPreviousButton->setToolTip(tr("Previous result"));
connect(m_findPreviousButton, &QToolButton::clicked, this, &SearchToolBar::findPrevious);
layout->addWidget(m_findPreviousButton);
// A workaround for QAbstractButton lacking support for multiple shortcuts.
auto action = new QAction(m_findPreviousButton);
action->setShortcuts(QKeySequence::FindPrevious);
connect(action, &QAction::triggered, this, [this]() { m_findPreviousButton->animateClick(); });
addAction(action);
m_findNextButton = new QToolButton();
m_findNextButton->setAutoRaise(true);
m_findNextButton->setIcon(qApp->style()->standardIcon(QStyle::SP_ArrowForward));
m_findNextButton->setToolTip(tr("Next result"));
connect(m_findNextButton, &QToolButton::clicked, this, &SearchToolBar::findNext);
layout->addWidget(m_findNextButton);
action = new QAction(m_findNextButton);
action->setShortcuts(QKeySequence::FindNext);
connect(action, &QAction::triggered, this, [this]() { m_findNextButton->animateClick(); });
addAction(action);
m_highlightAllButton = new QToolButton();
m_highlightAllButton->setAutoRaise(true);
m_highlightAllButton->setCheckable(true);
m_highlightAllButton->setText(tr("High&light All"));
connect(m_highlightAllButton, &QToolButton::toggled, this, &SearchToolBar::updateHighlight);
layout->addWidget(m_highlightAllButton);
m_matchCaseButton = new QToolButton();
m_matchCaseButton->setAutoRaise(true);
m_matchCaseButton->setCheckable(true);
m_matchCaseButton->setText(tr("Mat&ch Case"));
connect(m_matchCaseButton, &QToolButton::toggled, this, &SearchToolBar::updateHighlight);
layout->addWidget(m_matchCaseButton);
layout->addStretch();
auto closeButton = new QToolButton();
closeButton->setAutoRaise(true);
closeButton->setIcon(qApp->style()->standardIcon(QStyle::SP_TitleBarCloseButton));
closeButton->setToolTip(tr("Close find bar"));
connect(closeButton, &QToolButton::clicked, this, &QWidget::hide);
layout->addWidget(closeButton);
setLayout(layout);
setMaximumHeight(sizeHint().height());
setMinimumWidth(sizeHint().width());
}
void SearchToolBar::setText(const QString &text)
{
m_lineEdit->setText(text);
}
void SearchToolBar::activate()
{
show();
m_lineEdit->selectAll();
m_lineEdit->setFocus();
}
bool SearchToolBar::eventFilter(QObject *object, QEvent *event)
{
if (object == m_lineEdit && event->type() == QEvent::KeyPress) {
auto keyEvent = static_cast<QKeyEvent *>(event);
switch (keyEvent->key()) {
case Qt::Key_Enter:
case Qt::Key_Return:
if (keyEvent->modifiers().testFlag(Qt::ControlModifier)) {
m_highlightAllButton->toggle();
} else if (keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {
findPrevious();
} else {
findNext();
}
return true;
case Qt::Key_Down:
case Qt::Key_Up:
case Qt::Key_PageDown:
case Qt::Key_PageUp:
QCoreApplication::sendEvent(m_webView->focusProxy(), event);
return true;
default:
break;
}
}
return QWidget::eventFilter(object, event);
}
void SearchToolBar::hideEvent(QHideEvent *event)
{
hideHighlight();
m_webView->setFocus();
QWidget::hideEvent(event);
}
void SearchToolBar::showEvent(QShowEvent *event)
{
activate();
QWidget::showEvent(event);
}
void SearchToolBar::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Escape) {
hide();
}
}
void SearchToolBar::findNext()
{
if (!isVisible()) {
return;
}
QWebEnginePage::FindFlags ff;
ff.setFlag(QWebEnginePage::FindCaseSensitively, m_matchCaseButton->isChecked());
m_webView->findText(m_lineEdit->text(), ff);
}
void SearchToolBar::findPrevious()
{
if (!isVisible()) {
return;
}
QWebEnginePage::FindFlags ff;
ff.setFlag(QWebEnginePage::FindCaseSensitively, m_matchCaseButton->isChecked());
ff.setFlag(QWebEnginePage::FindBackward);
m_webView->findText(m_lineEdit->text(), ff);
}
void SearchToolBar::hideHighlight()
{
m_webView->findText(QString());
}
void SearchToolBar::updateHighlight()
{
hideHighlight();
if (m_highlightAllButton->isChecked()) {
QWebEnginePage::FindFlags ff;
ff.setFlag(QWebEnginePage::FindCaseSensitively, m_matchCaseButton->isChecked());
m_webView->findText(m_lineEdit->text(), ff);
}
}
| 5,737
|
C++
|
.cpp
| 157
| 31.464968
| 99
| 0.700973
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,967
|
webpage.cpp
|
zealdocs_zeal/src/libs/browser/webpage.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2019 Kay Gawlik
// SPDX-License-Identifier: GPL-3.0-or-later
#include "webpage.h"
#include "settings.h"
#include <core/application.h>
#include <core/networkaccessmanager.h>
#include <core/settings.h>
#include <QCheckBox>
#include <QDesktopServices>
#include <QFileInfo>
#include <QLoggingCategory>
#include <QMessageBox>
#include <QPushButton>
using namespace Zeal::Browser;
static Q_LOGGING_CATEGORY(log, "zeal.browser.webpage")
WebPage::WebPage(QObject *parent)
: QWebEnginePage(Settings::defaultProfile(), parent)
{
}
bool WebPage::acceptNavigationRequest(const QUrl &requestUrl, QWebEnginePage::NavigationType type, bool isMainFrame)
{
Q_UNUSED(type)
// Local elements are always allowed.
if (Core::NetworkAccessManager::isLocalUrl(requestUrl)) {
return true;
}
// Allow external resources if already on an external page.
const QUrl pageUrl = url();
if (pageUrl.isValid() && !Core::NetworkAccessManager::isLocalUrl(pageUrl)) {
return true;
}
// Block external elements on local pages.
if (!isMainFrame) {
qCDebug(log, "Blocked request to '%s'.", qPrintable(requestUrl.toString()));
return false;
}
auto appSettings = Core::Application::instance()->settings();
// TODO: [C++20] using enum Core::Settings::ExternalLinkPolicy;
typedef Core::Settings::ExternalLinkPolicy ExternalLinkPolicy;
switch (appSettings->externalLinkPolicy) {
case ExternalLinkPolicy::Open:
return true;
case ExternalLinkPolicy::Ask: {
QMessageBox mb;
mb.setIcon(QMessageBox::Question);
mb.setText(tr("How do you want to open the external link?<br>URL: <b>%1</b>")
.arg(requestUrl.toString()));
QCheckBox *checkBox = new QCheckBox("Do ¬ ask again");
mb.setCheckBox(checkBox);
QPushButton *openInBrowserButton = mb.addButton(tr("Open in &Desktop Browser"), QMessageBox::ActionRole);
QPushButton *openInZealButton = mb.addButton(tr("Open in &Zeal"), QMessageBox::ActionRole);
mb.addButton(QMessageBox::Cancel);
mb.setDefaultButton(openInBrowserButton);
if (mb.exec() == QMessageBox::Cancel) {
qCDebug(log, "Blocked request to '%s'.", qPrintable(requestUrl.toString()));
return false;
}
if (mb.clickedButton() == openInZealButton) {
if (checkBox->isChecked()) {
appSettings->externalLinkPolicy = ExternalLinkPolicy::Open;
appSettings->save();
}
return true;
}
if (mb.clickedButton() == openInBrowserButton) {
if (checkBox->isChecked()) {
appSettings->externalLinkPolicy = ExternalLinkPolicy::OpenInSystemBrowser;
appSettings->save();
}
QDesktopServices::openUrl(requestUrl);
return false;
}
break;
}
case ExternalLinkPolicy::OpenInSystemBrowser:
QDesktopServices::openUrl(requestUrl);
return false;
}
// This code should not be reachable so log a warning.
qCWarning(log, "Blocked request to '%s'.", qPrintable(requestUrl.toString()));
return false;
}
void WebPage::javaScriptConsoleMessage(QWebEnginePage::JavaScriptConsoleMessageLevel level, const QString &message, int lineNumber, const QString &sourceId)
{
Q_UNUSED(level)
Q_UNUSED(message)
Q_UNUSED(lineNumber)
Q_UNUSED(sourceId)
}
| 3,552
|
C++
|
.cpp
| 90
| 32.766667
| 156
| 0.677241
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,968
|
webbridge.cpp
|
zealdocs_zeal/src/libs/browser/webbridge.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "webbridge.h"
#include <core/application.h>
#include <QDesktopServices>
#include <QUrl>
using namespace Zeal::Browser;
WebBridge::WebBridge(QObject *parent)
: QObject(parent)
{
}
void WebBridge::openShortUrl(const QString &key)
{
QDesktopServices::openUrl(QUrl(QStringLiteral("https://go.zealdocs.org/l/") + key));
}
void WebBridge::triggerAction(const QString &action)
{
emit actionTriggered(action);
}
QString WebBridge::appVersion() const
{
return Core::Application::versionString();
}
| 629
|
C++
|
.cpp
| 23
| 25.304348
| 88
| 0.76087
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,969
|
urlrequestinterceptor.cpp
|
zealdocs_zeal/src/libs/browser/urlrequestinterceptor.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2019 Kay Gawlik
// SPDX-License-Identifier: GPL-3.0-or-later
#include "urlrequestinterceptor.h"
#include <core/networkaccessmanager.h>
#include <QLoggingCategory>
using namespace Zeal::Browser;
static Q_LOGGING_CATEGORY(log, "zeal.browser.urlrequestinterceptor")
UrlRequestInterceptor::UrlRequestInterceptor(QObject *parent)
: QWebEngineUrlRequestInterceptor(parent)
{
}
void UrlRequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo &info)
{
const QUrl requestUrl = info.requestUrl();
const QUrl firstPartyUrl = info.firstPartyUrl();
#if QT_VERSION < QT_VERSION_CHECK(5, 12, 0)
// Workaround for https://github.com/zealdocs/zeal/issues/1376. Fixed in Qt 5.12.0.
if (!firstPartyUrl.isValid() && requestUrl.scheme() == QLatin1String("blob")) {
return;
}
#endif
// Block invalid requests.
if (!requestUrl.isValid() || !firstPartyUrl.isValid()) {
blockRequest(info);
return;
}
// Direct links are controlled in the WebPage
if (info.resourceType() == QWebEngineUrlRequestInfo::ResourceTypeMainFrame) {
return;
}
bool isFirstPartyUrlLocal = Core::NetworkAccessManager::isLocalUrl(firstPartyUrl);
bool isRequestUrlLocal = Core::NetworkAccessManager::isLocalUrl(requestUrl);
// Allow local resources on local pages and external resources on external pages.
if (isFirstPartyUrlLocal == isRequestUrlLocal) {
return;
}
blockRequest(info);
}
void UrlRequestInterceptor::blockRequest(QWebEngineUrlRequestInfo &info)
{
qCDebug(log, "Blocked request: %s '%s' (resource_type=%d, navigation_type=%d).",
info.requestMethod().data(),
qPrintable(info.requestUrl().toString()),
info.resourceType(), info.navigationType());
info.block(true);
}
| 1,880
|
C++
|
.cpp
| 47
| 35.361702
| 87
| 0.727173
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,970
|
searchmodel.cpp
|
zealdocs_zeal/src/libs/registry/searchmodel.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include "searchmodel.h"
#include "docset.h"
#include "itemdatarole.h"
using namespace Zeal::Registry;
SearchModel::SearchModel(QObject *parent)
: QAbstractListModel(parent)
{
}
SearchModel *SearchModel::clone(QObject *parent)
{
auto model = new SearchModel(parent);
model->m_dataList = m_dataList;
return model;
}
bool SearchModel::isEmpty() const
{
return m_dataList.isEmpty();
}
QVariant SearchModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
auto item = static_cast<SearchResult *>(index.internalPointer());
switch (role) {
case Qt::DisplayRole:
return item->name;
case Qt::DecorationRole:
return item->docset->symbolTypeIcon(item->type);
case ItemDataRole::DocsetIconRole:
return item->docset->icon();
case ItemDataRole::UrlRole:
return item->docset->searchResultUrl(*item);
default:
return QVariant();
}
}
QModelIndex SearchModel::index(int row, int column, const QModelIndex &parent) const
{
if (parent.isValid() || m_dataList.count() <= row || column > 1)
return {};
// FIXME: const_cast
auto item = const_cast<SearchResult *>(&m_dataList.at(row));
return createIndex(row, column, item);
}
int SearchModel::rowCount(const QModelIndex &parent) const
{
if (!parent.isValid())
return m_dataList.count();
return 0;
}
bool SearchModel::removeRows(int row, int count, const QModelIndex &parent)
{
if (row + count <= m_dataList.size() && !parent.isValid()) {
beginRemoveRows(parent, row, row + count - 1);
while (count) {
m_dataList.removeAt(row);
--count;
}
endRemoveRows();
return true;
}
return false;
}
void SearchModel::removeSearchResultWithName(const QString &name)
{
QMutableListIterator<SearchResult> iterator(m_dataList);
int rowNum = 0;
while (iterator.hasNext()) {
if (iterator.next().docset->name() == name) {
beginRemoveRows(QModelIndex(), rowNum, rowNum);
iterator.remove();
rowNum -= 1;
endRemoveRows();
}
rowNum += 1;
}
}
void SearchModel::setResults(const QList<SearchResult> &results)
{
beginResetModel();
m_dataList = results;
endResetModel();
emit updated();
}
| 2,522
|
C++
|
.cpp
| 87
| 24.034483
| 84
| 0.662112
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,971
|
docsetmetadata.cpp
|
zealdocs_zeal/src/libs/registry/docsetmetadata.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include "docsetmetadata.h"
#include <QFile>
#include <QGuiApplication>
#include <QJsonArray>
#include <QJsonDocument>
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
#include <QRandomGenerator>
#endif
#include <QVariant>
#include <QXmlStreamReader>
using namespace Zeal::Registry;
DocsetMetadata::DocsetMetadata(const QJsonObject &jsonObject)
{
m_name = jsonObject[QStringLiteral("name")].toString();
m_title = jsonObject[QStringLiteral("title")].toString();
m_rawIcon = QByteArray::fromBase64(jsonObject[QStringLiteral("icon")].toString().toLocal8Bit());
m_icon.addPixmap(QPixmap::fromImage(QImage::fromData(m_rawIcon)));
m_rawIcon2x = QByteArray::fromBase64(jsonObject[QStringLiteral("icon2x")].toString()
.toLocal8Bit());
if (qApp->devicePixelRatio() > 1.0) {
QPixmap pixmap = QPixmap::fromImage(QImage::fromData(m_rawIcon2x));
pixmap.setDevicePixelRatio(2.0);
m_icon.addPixmap(pixmap);
}
for (const QJsonValueRef vv : jsonObject[QStringLiteral("aliases")].toArray()) {
m_aliases << vv.toString();
}
for (const QJsonValueRef vv : jsonObject[QStringLiteral("versions")].toArray()) {
m_versions << vv.toString();
}
// Unfortunately, API returns revision as a string, so it needs to be converted to integer
// for comparison to work properly.
m_revision = jsonObject[QStringLiteral("revision")].toString().toInt();
m_feedUrl = QUrl(jsonObject[QStringLiteral("feed_url")].toString());
for (const QJsonValueRef vv : jsonObject[QStringLiteral("urls")].toArray()) {
m_urls.append(QUrl(vv.toString()));
}
m_extra = jsonObject[QStringLiteral("extra")].toObject();
}
/*!
Creates meta.json for specified docset \a version in the \a path.
*/
void DocsetMetadata::save(const QString &path, const QString &version)
{
QScopedPointer<QFile> file(new QFile(path + QLatin1String("/meta.json")));
if (!file->open(QIODevice::WriteOnly))
return;
QJsonObject jsonObject;
jsonObject[QStringLiteral("name")] = m_name;
jsonObject[QStringLiteral("title")] = m_title;
if (!version.isEmpty())
jsonObject[QStringLiteral("version")] = version;
if (version == latestVersion() && m_revision > 0)
jsonObject[QStringLiteral("revision")] = QString::number(m_revision);
if (!m_feedUrl.isEmpty())
jsonObject[QStringLiteral("feed_url")] = m_feedUrl.toString();
if (!m_urls.isEmpty()) {
QJsonArray urls;
for (const QUrl &url : std::as_const(m_urls)) {
urls.append(url.toString());
}
jsonObject[QStringLiteral("urls")] = urls;
}
if (!m_extra.isEmpty())
jsonObject[QStringLiteral("extra")] = m_extra;
file->write(QJsonDocument(jsonObject).toJson());
file->close();
if (m_rawIcon.isEmpty())
return;
file->setFileName(path + QLatin1String("/icon.png"));
if (file->open(QIODevice::WriteOnly))
file->write(m_rawIcon);
file->close();
if (m_rawIcon2x.isEmpty())
return;
file->setFileName(path + QLatin1String("/icon@2x.png"));
if (file->open(QIODevice::WriteOnly))
file->write(m_rawIcon2x);
file->close();
}
QString DocsetMetadata::name() const
{
return m_name;
}
QIcon DocsetMetadata::icon() const
{
return m_icon;
}
QString DocsetMetadata::title() const
{
return m_title;
}
QStringList DocsetMetadata::aliases() const
{
return m_aliases;
}
QStringList DocsetMetadata::versions() const
{
return m_versions;
}
QString DocsetMetadata::latestVersion() const
{
return m_versions.isEmpty() ? QString() : m_versions.first();
}
int DocsetMetadata::revision() const
{
return m_revision;
}
QUrl DocsetMetadata::feedUrl() const
{
return m_feedUrl;
}
QUrl DocsetMetadata::url() const
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
return m_urls.at(QRandomGenerator::global()->bounded(m_urls.size()));
#else
return m_urls.at(qrand() % m_urls.size());
#endif
}
QList<QUrl> DocsetMetadata::urls() const
{
return m_urls;
}
DocsetMetadata DocsetMetadata::fromDashFeed(const QUrl &feedUrl, const QByteArray &data)
{
DocsetMetadata metadata;
metadata.m_name = feedUrl.fileName();
// Strip ".xml" extension if any.
if (metadata.m_name.endsWith(QLatin1String(".xml"))) {
metadata.m_name.chop(4);
}
metadata.m_title = metadata.m_name;
metadata.m_title.replace(QLatin1Char('_'), QLatin1Char(' '));
metadata.m_feedUrl = feedUrl;
QXmlStreamReader xml(data);
while (!xml.atEnd()) {
const QXmlStreamReader::TokenType token = xml.readNext();
if (token != QXmlStreamReader::StartElement)
continue;
// Try to pull out the relevant data
if (xml.name() == QLatin1String("version")) {
if (xml.readNext() != QXmlStreamReader::Characters)
continue;
metadata.m_versions << xml.text().toString();
} else if (xml.name() == QLatin1String("url")) {
if (xml.readNext() != QXmlStreamReader::Characters)
continue;
metadata.m_urls.append(QUrl(xml.text().toString()));
}
}
return metadata;
}
| 5,369
|
C++
|
.cpp
| 156
| 29.448718
| 100
| 0.673375
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,972
|
searchquery.cpp
|
zealdocs_zeal/src/libs/registry/searchquery.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include "searchquery.h"
#include <utility>
using namespace Zeal::Registry;
namespace {
const char prefixSeparator = ':';
const char keywordSeparator = ',';
} // namespace
SearchQuery::SearchQuery(QString query, const QStringList &keywords)
: m_query(std::move(query))
{
setKeywords(keywords);
}
SearchQuery SearchQuery::fromString(const QString &str)
{
const int sepAt = str.indexOf(prefixSeparator);
const int next = sepAt + 1;
QString query;
QStringList keywords;
if (sepAt > 0 && (next >= str.size() || str.at(next) != prefixSeparator)) {
query = str.mid(next).trimmed();
const QString keywordStr = str.left(sepAt).trimmed();
keywords = keywordStr.split(keywordSeparator);
} else {
query = str.trimmed();
}
return SearchQuery(query, keywords);
}
QString SearchQuery::toString() const
{
if (m_keywords.isEmpty()) {
return m_query;
}
return m_keywordPrefix + m_query;
}
bool SearchQuery::isEmpty() const
{
return m_query.isEmpty() && m_keywords.isEmpty();
}
QStringList SearchQuery::keywords() const
{
return m_keywords;
}
void SearchQuery::setKeywords(const QStringList &list)
{
if (list.isEmpty())
return;
m_keywords = list;
m_keywordPrefix = list.join(keywordSeparator) + prefixSeparator;
}
bool SearchQuery::hasKeywords() const
{
return !m_keywords.isEmpty();
}
bool SearchQuery::hasKeywords(const QStringList &keywords) const
{
for (const QString &keyword : keywords) {
if (m_keywords.contains(keyword, Qt::CaseInsensitive)) {
return true;
}
}
return false;
}
int SearchQuery::keywordPrefixSize() const
{
return m_keywordPrefix.size();
}
QString SearchQuery::query() const
{
return m_query;
}
void SearchQuery::setQuery(const QString &str)
{
m_query = str;
}
QDataStream &operator<<(QDataStream &out, const Zeal::Registry::SearchQuery &query)
{
out << query.toString();
return out;
}
QDataStream &operator>>(QDataStream &in, Zeal::Registry::SearchQuery &query)
{
QString str;
in >> str;
query = SearchQuery::fromString(str);
return in;
}
| 2,315
|
C++
|
.cpp
| 89
| 22.505618
| 83
| 0.696777
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
11,973
|
listmodel.cpp
|
zealdocs_zeal/src/libs/registry/listmodel.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include "listmodel.h"
#include "docset.h"
#include "docsetregistry.h"
#include "itemdatarole.h"
#include <iterator>
using namespace Zeal::Registry;
ListModel::ListModel(DocsetRegistry *docsetRegistry)
: QAbstractItemModel(docsetRegistry)
, m_docsetRegistry(docsetRegistry)
{
connect(m_docsetRegistry, &DocsetRegistry::docsetLoaded, this, &ListModel::addDocset);
connect(m_docsetRegistry, &DocsetRegistry::docsetAboutToBeUnloaded, this, &ListModel::removeDocset);
}
ListModel::~ListModel()
{
for (auto &kv : m_docsetItems) {
qDeleteAll(kv.second->groups);
delete kv.second;
}
}
QVariant ListModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation != Qt::Horizontal || role != Qt::DisplayRole) {
return QAbstractItemModel::headerData(section, orientation, role);
}
switch (section) {
case SectionIndex::Name:
return tr("Name");
case SectionIndex::SearchPrefix:
return tr("Search prefix");
default:
return QLatin1String();
}
}
QVariant ListModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
switch (role) {
case Qt::DecorationRole:
if (index.column() != SectionIndex::Name) {
return QVariant();
}
switch (indexLevel(index)) {
case IndexLevel::Docset:
return itemInRow(index.row())->docset->icon();
case IndexLevel::Group: {
auto docsetItem = static_cast<DocsetItem *>(index.internalPointer());
const QString symbolType = docsetItem->groups.at(index.row())->symbolType;
return docsetItem->docset->symbolTypeIcon(symbolType);
}
case IndexLevel::Symbol: {
auto groupItem = static_cast<GroupItem *>(index.internalPointer());
return groupItem->docsetItem->docset->symbolTypeIcon(groupItem->symbolType);
}
default:
return QVariant();
}
case Qt::DisplayRole:
switch (indexLevel(index)) {
case IndexLevel::Docset:
switch (index.column()) {
case SectionIndex::Name:
return itemInRow(index.row())->docset->title();
case SectionIndex::SearchPrefix:
return itemInRow(index.row())->docset->keywords().join(QLatin1String(", "));
default:
return QVariant();
}
case IndexLevel::Group: {
auto docsetItem = static_cast<DocsetItem *>(index.internalPointer());
const QString symbolType = docsetItem->groups.at(index.row())->symbolType;
return QStringLiteral("%1 (%2)").arg(pluralize(symbolType),
QString::number(docsetItem->docset->symbolCount(symbolType)));
}
case IndexLevel::Symbol: {
auto groupItem = static_cast<GroupItem *>(index.internalPointer());
auto it = groupItem->docsetItem->docset->symbols(groupItem->symbolType).cbegin();
std::advance(it, index.row());
return it.key();
}
default:
return QVariant();
}
case Qt::ToolTipRole:
if (index.column() != SectionIndex::Name) {
return QVariant();
}
switch (indexLevel(index)) {
case IndexLevel::Docset: {
const auto docset = itemInRow(index.row())->docset;
return tr("Version: %1r%2").arg(docset->version()).arg(docset->revision());
}
default:
return QVariant();
}
case ItemDataRole::UrlRole:
switch (indexLevel(index)) {
case IndexLevel::Docset:
return itemInRow(index.row())->docset->indexFileUrl();
case IndexLevel::Symbol: {
auto groupItem = static_cast<GroupItem *>(index.internalPointer());
auto it = groupItem->docsetItem->docset->symbols(groupItem->symbolType).cbegin();
std::advance(it, index.row());
return it.value();
}
default:
return QVariant();
}
case ItemDataRole::DocsetNameRole:
if (index.parent().isValid())
return QVariant();
return itemInRow(index.row())->docset->name();
case ItemDataRole::UpdateAvailableRole:
if (index.parent().isValid())
return QVariant();
return itemInRow(index.row())->docset->hasUpdate;
default:
return QVariant();
}
}
QModelIndex ListModel::index(int row, int column, const QModelIndex &parent) const
{
if (!hasIndex(row, column, parent)) {
return {};
}
switch (indexLevel(parent)) {
case IndexLevel::Root:
return createIndex(row, column);
case IndexLevel::Docset:
return createIndex(row, column, static_cast<void *>(itemInRow(parent.row())));
case IndexLevel::Group: {
auto docsetItem = static_cast<DocsetItem *>(parent.internalPointer());
return createIndex(row, column, docsetItem->groups.at(parent.row()));
}
default:
return {};
}
}
QModelIndex ListModel::parent(const QModelIndex &child) const
{
switch (indexLevel(child)) {
case IndexLevel::Group: {
auto item = static_cast<DocsetItem *>(child.internalPointer());
auto it = std::find_if(m_docsetItems.cbegin(), m_docsetItems.cend(), [item](const auto &pair) {
return pair.second == item;
});
if (it == m_docsetItems.cend()) {
// TODO: Report error, this should never happen.
return {};
}
const int row = static_cast<int>(std::distance(m_docsetItems.begin(), it));
return createIndex(row, 0);
}
case IndexLevel::Symbol: {
auto item = static_cast<GroupItem *>(child.internalPointer());
return createIndex(item->docsetItem->groups.indexOf(item), 0, item->docsetItem);
}
default:
return {};
}
}
int ListModel::columnCount(const QModelIndex &parent) const
{
if (indexLevel(parent) == IndexLevel::Root) {
return 3;
}
return 1;
}
int ListModel::rowCount(const QModelIndex &parent) const
{
if (parent.column() > 0) {
return 0;
}
switch (indexLevel(parent)) {
case IndexLevel::Root:
return static_cast<int>(m_docsetItems.size());
case IndexLevel::Docset:
return itemInRow(parent.row())->docset->symbolCounts().count();
case IndexLevel::Group: {
auto docsetItem = static_cast<DocsetItem *>(parent.internalPointer());
return docsetItem->docset->symbolCount(docsetItem->groups.at(parent.row())->symbolType);
}
default:
return 0;
}
}
void ListModel::addDocset(const QString &name)
{
const int row = static_cast<int>(std::distance(m_docsetItems.begin(), m_docsetItems.upper_bound(name)));
beginInsertRows(QModelIndex(), row, row);
auto docsetItem = new DocsetItem();
docsetItem->docset = m_docsetRegistry->docset(name);
const auto keys = docsetItem->docset->symbolCounts().keys();
for (const QString &symbolType : keys) {
auto groupItem = new GroupItem();
groupItem->docsetItem = docsetItem;
groupItem->symbolType = symbolType;
docsetItem->groups.append(groupItem);
}
m_docsetItems.insert({name, docsetItem});
endInsertRows();
}
void ListModel::removeDocset(const QString &name)
{
auto it = m_docsetItems.find(name);
if (it == m_docsetItems.cend()) {
// TODO: Investigate why this can happen (see #420)
return;
}
const int row = static_cast<int>(std::distance(m_docsetItems.begin(), it));
beginRemoveRows(QModelIndex(), row, row);
qDeleteAll(it->second->groups);
delete it->second;
m_docsetItems.erase(it);
endRemoveRows();
}
QString ListModel::pluralize(const QString &s)
{
if (s.endsWith(QLatin1String("y"))) {
return s.left(s.length() - 1) + QLatin1String("ies");
}
return s + (s.endsWith('s') ? QLatin1String("es") : QLatin1String("s"));
}
ListModel::IndexLevel ListModel::indexLevel(const QModelIndex &index)
{
if (!index.isValid()) {
return IndexLevel::Root;
}
if (!index.internalPointer()) {
return IndexLevel::Docset;
}
if (*static_cast<IndexLevel *>(index.internalPointer()) == IndexLevel::Docset) {
return IndexLevel::Group;
}
return IndexLevel::Symbol;
}
ListModel::DocsetItem *ListModel::itemInRow(int row) const
{
auto it = m_docsetItems.cbegin();
std::advance(it, row);
return it->second;
}
| 8,768
|
C++
|
.cpp
| 247
| 28.396761
| 111
| 0.631145
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,974
|
docset.cpp
|
zealdocs_zeal/src/libs/registry/docset.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include "docset.h"
#include "cancellationtoken.h"
#include "searchresult.h"
#include <util/plist.h>
#include <util/sqlitedatabase.h>
#include <QDir>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QRegularExpression>
#include <QVarLengthArray>
#include <QVariant>
#include <sqlite3.h>
#include <cstring>
#include <utility>
using namespace Zeal::Registry;
namespace {
constexpr char IndexNamePrefix[] = "__zi_name"; // zi - Zeal index
constexpr char IndexNameVersion[] = "0001"; // Current index version
constexpr char NotFoundPageUrl[] = "qrc:///browser/404.html";
namespace InfoPlist {
constexpr char CFBundleName[] = "CFBundleName";
//const char CFBundleIdentifier[] = "CFBundleIdentifier";
constexpr char DashDocSetFamily[] = "DashDocSetFamily";
constexpr char DashDocSetKeyword[] = "DashDocSetKeyword";
constexpr char DashDocSetPluginKeyword[] = "DashDocSetPluginKeyword";
constexpr char DashIndexFilePath[] = "dashIndexFilePath";
constexpr char DocSetPlatformFamily[] = "DocSetPlatformFamily";
//const char IsDashDocset[] = "isDashDocset";
constexpr char IsJavaScriptEnabled[] = "isJavaScriptEnabled";
} // namespace InfoPlist
} // namespace
static void sqliteScoreFunction(sqlite3_context *context, int argc, sqlite3_value **argv);
Docset::Docset(QString path)
: m_path(std::move(path))
{
QDir dir(m_path);
if (!dir.exists())
return;
loadMetadata();
// Attempt to find the icon in any supported format
const auto iconFiles = dir.entryList({QStringLiteral("icon.*")}, QDir::Files);
for (const QString &iconFile : iconFiles) {
m_icon = QIcon(dir.filePath(iconFile));
if (!m_icon.availableSizes().isEmpty())
break;
}
// TODO: Report errors here and below
if (!dir.cd(QStringLiteral("Contents")))
return;
// TODO: 'info.plist' is invalid according to Apple, and must alsways be 'Info.plist'
// https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPRuntimeConfig
// /Articles/ConfigFiles.html
Util::Plist plist;
if (dir.exists(QStringLiteral("Info.plist")))
plist.read(dir.filePath(QStringLiteral("Info.plist")));
else if (dir.exists(QStringLiteral("info.plist")))
plist.read(dir.filePath(QStringLiteral("info.plist")));
else
return;
if (plist.hasError())
return;
if (m_name.isEmpty()) {
// Fallback if meta.json is absent
if (plist.contains(InfoPlist::CFBundleName)) {
m_name = m_title = plist[InfoPlist::CFBundleName].toString();
// TODO: Remove when MainWindow::docsetName() will not use directory name
m_name.replace(QLatin1Char(' '), QLatin1Char('_'));
} else {
m_name = QFileInfo(m_path).fileName().remove(QStringLiteral(".docset"));
}
}
if (m_title.isEmpty()) {
m_title = m_name;
m_title.replace(QLatin1Char('_'), QLatin1Char(' '));
}
// TODO: Verify if this is needed
if (plist.contains(InfoPlist::DashDocSetFamily)
&& plist[InfoPlist::DashDocSetFamily].toString() == QLatin1String("cheatsheet")) {
m_name = m_name + QLatin1String("cheats");
}
if (!dir.cd(QStringLiteral("Resources")) || !dir.exists(QStringLiteral("docSet.dsidx")))
return;
m_db = new Util::SQLiteDatabase(dir.filePath(QStringLiteral("docSet.dsidx")));
if (!m_db->isOpen()) {
qWarning("SQL Error: %s", qPrintable(m_db->lastError()));
return;
}
sqlite3_create_function(m_db->handle(), "zealScore", 2, SQLITE_UTF8, nullptr,
sqliteScoreFunction, nullptr, nullptr);
m_type = m_db->tables().contains(QStringLiteral("searchIndex"), Qt::CaseInsensitive)
? Type::Dash : Type::ZDash;
createIndex();
if (m_type == Docset::Type::ZDash) {
createView();
}
if (!dir.cd(QStringLiteral("Documents"))) {
m_type = Type::Invalid;
return;
}
// Setup keywords
if (plist.contains(InfoPlist::DocSetPlatformFamily))
m_keywords << plist[InfoPlist::DocSetPlatformFamily].toString();
if (plist.contains(InfoPlist::DashDocSetPluginKeyword))
m_keywords << plist[InfoPlist::DashDocSetPluginKeyword].toString();
if (plist.contains(InfoPlist::DashDocSetKeyword))
m_keywords << plist[InfoPlist::DashDocSetKeyword].toString();
if (plist.contains(InfoPlist::DashDocSetFamily)) {
const QString kw = plist[InfoPlist::DashDocSetFamily].toString();
if (!kw.contains(QLatin1String("dashtoc"))) {
m_keywords << kw;
}
}
if (plist.contains(InfoPlist::IsJavaScriptEnabled)) {
m_isJavaScriptEnabled = plist[InfoPlist::IsJavaScriptEnabled].toBool();
}
m_keywords.removeDuplicates();
// Determine index page. This is ridiculous.
const QString mdIndexFilePath = m_indexFilePath; // Save path from the metadata.
// Prefer index path provided by the docset.
if (plist.contains(InfoPlist::DashIndexFilePath)) {
const QString indexFilePath = plist[InfoPlist::DashIndexFilePath].toString();
if (dir.exists(indexFilePath)) {
m_indexFilePath = indexFilePath;
}
}
// Check the metadata.
if (m_indexFilePath.isEmpty() && !mdIndexFilePath.isEmpty() && dir.exists(mdIndexFilePath)) {
m_indexFilePath = mdIndexFilePath;
}
// What if there is index.html.
if (m_indexFilePath.isEmpty() && dir.exists(QStringLiteral("index.html"))) {
m_indexFilePath = QStringLiteral("index.html");
}
// Log if unable to determine the index page. Otherwise the path will be set in setBaseUrl().
if (m_indexFilePath.isEmpty()) {
qWarning("Cannot determine index file for docset %s", qPrintable(m_name));
m_indexFileUrl.setUrl(NotFoundPageUrl);
} else {
m_indexFileUrl = createPageUrl(m_indexFilePath);
}
countSymbols();
}
Docset::~Docset()
{
delete m_db;
}
bool Docset::isValid() const
{
return m_type != Type::Invalid;
}
QString Docset::name() const
{
return m_name;
}
QString Docset::title() const
{
return m_title;
}
QStringList Docset::keywords() const
{
return m_keywords;
}
QString Docset::version() const
{
return m_version;
}
int Docset::revision() const
{
return m_revision;
}
QString Docset::feedUrl() const
{
return m_feedUrl;
}
QString Docset::path() const
{
return m_path;
}
QString Docset::documentPath() const
{
return QDir(m_path).filePath(QStringLiteral("Contents/Resources/Documents"));
}
QIcon Docset::icon() const
{
return m_icon;
}
QIcon Docset::symbolTypeIcon(const QString &symbolType) const
{
static const QIcon unknownIcon(QStringLiteral("typeIcon:Unknown.png"));
const QIcon icon(QStringLiteral("typeIcon:%1.png").arg(symbolType));
return icon.availableSizes().isEmpty() ? unknownIcon : icon;
}
QUrl Docset::indexFileUrl() const
{
return m_indexFileUrl;
}
QMap<QString, int> Docset::symbolCounts() const
{
return m_symbolCounts;
}
int Docset::symbolCount(const QString &symbolType) const
{
return m_symbolCounts.value(symbolType);
}
const QMultiMap<QString, QUrl> &Docset::symbols(const QString &symbolType) const
{
if (!m_symbols.contains(symbolType))
loadSymbols(symbolType);
return m_symbols[symbolType];
}
QList<SearchResult> Docset::search(const QString &query, const CancellationToken &token) const
{
QString sql;
if (m_type == Docset::Type::Dash) {
if (m_isFuzzySearchEnabled) {
sql = QStringLiteral("SELECT name, type, path, '', zealScore('%1', name) as score"
" FROM searchIndex"
" WHERE score > 0");
} else {
sql = QStringLiteral("SELECT name, type, path, '', -length(name) as score"
" FROM searchIndex"
" WHERE (name LIKE '%%1%' ESCAPE '\\')");
}
} else {
if (m_isFuzzySearchEnabled) {
sql = QStringLiteral("SELECT name, type, path, fragment, zealScore('%1', name) as score"
" FROM searchIndex"
" WHERE score > 0");
} else {
sql = QStringLiteral("SELECT name, type, path, fragment, -length(name) as score"
" FROM searchIndex"
" WHERE (name LIKE '%%1%' ESCAPE '\\')");
}
}
// Limit for very short queries.
// TODO: Show a notification about the reduced result set.
if (query.size() < 3) {
sql += QLatin1String(" LIMIT 1000");
}
// Make it safe to use in a SQL query.
QString sanitizedQuery = query;
sanitizedQuery.replace(QLatin1Char('\''), QLatin1String("''"));
m_db->prepare(sql.arg(sanitizedQuery));
QList<SearchResult> results;
while (m_db->next() && !token.isCanceled()) {
results.append({m_db->value(0).toString(),
parseSymbolType(m_db->value(1).toString()),
m_db->value(2).toString(), m_db->value(3).toString(),
const_cast<Docset *>(this), m_db->value(4).toInt()});
}
return results;
}
QList<SearchResult> Docset::relatedLinks(const QUrl &url) const
{
if (!m_baseUrl.isParentOf(url)) {
return {};
}
// Get page path within the docset.
const QString path = url.path().mid(m_baseUrl.path().length() + 1);
// Prepare the query to look up all pages with the same url.
QString sql;
if (m_type == Docset::Type::Dash) {
sql = QStringLiteral("SELECT name, type, path"
" FROM searchIndex"
" WHERE path LIKE \"%1%%\" AND path <> \"%1\"");
} else if (m_type == Docset::Type::ZDash) {
sql = QStringLiteral("SELECT name, type, path, fragment"
" FROM searchIndex"
" WHERE path = \"%1\" AND fragment IS NOT NULL");
}
QList<SearchResult> results;
m_db->prepare(sql.arg(path));
while (m_db->next()) {
results.append({m_db->value(0).toString(),
parseSymbolType(m_db->value(1).toString()),
m_db->value(2).toString(), m_db->value(3).toString(),
const_cast<Docset *>(this), 0});
}
if (results.size() == 1) {
return {};
}
return results;
}
QUrl Docset::searchResultUrl(const SearchResult &result) const
{
return createPageUrl(result.urlPath, result.urlFragment);
}
void Docset::loadMetadata()
{
const QDir dir(m_path);
// Fallback if meta.json is absent
if (!dir.exists(QStringLiteral("meta.json")))
return;
QScopedPointer<QFile> file(new QFile(dir.filePath(QStringLiteral("meta.json"))));
if (!file->open(QIODevice::ReadOnly))
return;
QJsonParseError jsonError;
const QJsonObject jsonObject = QJsonDocument::fromJson(file->readAll(), &jsonError).object();
if (jsonError.error != QJsonParseError::NoError)
return;
m_name = jsonObject[QStringLiteral("name")].toString();
m_title = jsonObject[QStringLiteral("title")].toString();
m_version = jsonObject[QStringLiteral("version")].toString();
m_revision = jsonObject[QStringLiteral("revision")].toString().toInt();
if (jsonObject.contains(QStringLiteral("feed_url"))) {
m_feedUrl = jsonObject[QStringLiteral("feed_url")].toString();
}
if (jsonObject.contains(QStringLiteral("extra"))) {
const QJsonObject extra = jsonObject[QStringLiteral("extra")].toObject();
if (extra.contains(QStringLiteral("indexFilePath"))) {
m_indexFilePath = extra[QStringLiteral("indexFilePath")].toString();
}
if (extra.contains(QStringLiteral("keywords"))) {
for (const QJsonValueRef kw : extra[QStringLiteral("keywords")].toArray()) {
m_keywords << kw.toString();
}
}
if (extra.contains(QStringLiteral("isJavaScriptEnabled"))) {
m_isJavaScriptEnabled = extra[QStringLiteral("isJavaScriptEnabled")].toBool();
}
}
}
void Docset::countSymbols()
{
static const QString sql = QStringLiteral("SELECT type, COUNT(*)"
" FROM searchIndex"
" GROUP BY type");
if (!m_db->prepare(sql)) {
qWarning("SQL Error: %s", qPrintable(m_db->lastError()));
return;
}
while (m_db->next()) {
const QString symbolTypeStr = m_db->value(0).toString();
// A workaround for https://github.com/zealdocs/zeal/issues/980.
if (symbolTypeStr.isEmpty()) {
qWarning("Empty symbol type in the '%s' docset, skipping...", qPrintable(m_name));
continue;
}
const QString symbolType = parseSymbolType(symbolTypeStr);
m_symbolStrings.insert(symbolType, symbolTypeStr);
m_symbolCounts[symbolType] += m_db->value(1).toInt();
}
}
// TODO: Fetch and cache only portions of symbols
void Docset::loadSymbols(const QString &symbolType) const
{
// Iterator `it` is a QPair<QMap::const_iterator, QMap::const_iterator>,
// with it.first and it.second respectively pointing to the start and the end
// of the range of nodes having symbolType as key. It effectively represents a
// contiguous view over the nodes with a specified key.
for (auto it = std::as_const(m_symbolStrings).equal_range(symbolType); it.first != it.second; ++it.first) {
loadSymbols(symbolType, it.first.value());
}
}
void Docset::loadSymbols(const QString &symbolType, const QString &symbolString) const
{
QString sql;
if (m_type == Docset::Type::Dash) {
sql = QStringLiteral("SELECT name, path"
" FROM searchIndex"
" WHERE type='%1'"
" ORDER BY name");
} else {
sql = QStringLiteral("SELECT name, path, fragment"
" FROM searchIndex"
" WHERE type='%1'"
" ORDER BY name");
}
if (!m_db->prepare(sql.arg(symbolString))) {
qWarning("SQL Error: %s", qPrintable(m_db->lastError()));
return;
}
QMultiMap<QString, QUrl> &symbols = m_symbols[symbolType];
while (m_db->next()) {
symbols.insert(m_db->value(0).toString(),
createPageUrl(m_db->value(1).toString(),
m_db->value(2).toString()));
}
}
void Docset::createIndex()
{
static const QString indexListQuery = QStringLiteral("PRAGMA INDEX_LIST('%1')");
static const QString indexDropQuery = QStringLiteral("DROP INDEX '%1'");
static const QString indexCreateQuery = QStringLiteral("CREATE INDEX IF NOT EXISTS %1%2"
" ON %3 (%4 COLLATE NOCASE)");
const QString tableName = m_type == Type::Dash ? QStringLiteral("searchIndex")
: QStringLiteral("ztoken");
const QString columnName = m_type == Type::Dash ? QStringLiteral("name")
: QStringLiteral("ztokenname");
m_db->prepare(indexListQuery.arg(tableName));
QStringList oldIndexes;
while (m_db->next()) {
const QString indexName = m_db->value(1).toString();
if (!indexName.startsWith(IndexNamePrefix))
continue;
if (indexName.endsWith(IndexNameVersion))
return;
oldIndexes << indexName;
}
// Drop old indexes
for (const QString &oldIndexName : std::as_const(oldIndexes)) {
m_db->execute(indexDropQuery.arg(oldIndexName));
}
m_db->execute(indexCreateQuery.arg(IndexNamePrefix).arg(IndexNameVersion).arg(tableName).arg(columnName));
}
void Docset::createView()
{
static const QString viewCreateQuery
= QStringLiteral("CREATE VIEW IF NOT EXISTS searchIndex AS"
" SELECT"
" ztokenname AS name,"
" ztypename AS type,"
" zpath AS path,"
" zanchor AS fragment"
" FROM ztoken"
" INNER JOIN ztokenmetainformation"
" ON ztoken.zmetainformation = ztokenmetainformation.z_pk"
" INNER JOIN zfilepath"
" ON ztokenmetainformation.zfile = zfilepath.z_pk"
" INNER JOIN ztokentype"
" ON ztoken.ztokentype = ztokentype.z_pk");
m_db->execute(viewCreateQuery);
}
QUrl Docset::createPageUrl(const QString &path, const QString &fragment) const
{
QString realPath;
QString realFragment;
if (fragment.isEmpty()) {
const QStringList urlParts = path.split(QLatin1Char('#'));
realPath = urlParts[0];
if (urlParts.size() > 1)
realFragment = urlParts[1];
} else {
realPath = path;
realFragment = fragment;
}
static const QRegularExpression dashEntryRegExp(QStringLiteral("<dash_entry_.*>"));
realPath.remove(dashEntryRegExp);
realFragment.remove(dashEntryRegExp);
QUrl url = m_baseUrl;
url.setPath(m_baseUrl.path() + "/" + realPath, QUrl::TolerantMode);
if (!realFragment.isEmpty()) {
if (realFragment.startsWith(QLatin1String("//apple_ref"))
|| realFragment.startsWith(QLatin1String("//dash_ref"))) {
url.setFragment(realFragment, QUrl::DecodedMode);
} else {
url.setFragment(realFragment);
}
}
return url;
}
QString Docset::parseSymbolType(const QString &str)
{
// Dash symbol aliases
const static QHash<QString, QString> aliases = {
// Attribute
{QStringLiteral("Package Attributes"), QStringLiteral("Attribute")},
{QStringLiteral("Private Attributes"), QStringLiteral("Attribute")},
{QStringLiteral("Protected Attributes"), QStringLiteral("Attribute")},
{QStringLiteral("Public Attributes"), QStringLiteral("Attribute")},
{QStringLiteral("Static Package Attributes"), QStringLiteral("Attribute")},
{QStringLiteral("Static Private Attributes"), QStringLiteral("Attribute")},
{QStringLiteral("Static Protected Attributes"), QStringLiteral("Attribute")},
{QStringLiteral("Static Public Attributes"), QStringLiteral("Attribute")},
{QStringLiteral("XML Attributes"), QStringLiteral("Attribute")},
// Binding
{QStringLiteral("binding"), QStringLiteral("Binding")},
// Category
{QStringLiteral("cat"), QStringLiteral("Category")},
{QStringLiteral("Groups"), QStringLiteral("Category")},
{QStringLiteral("Pages"), QStringLiteral("Category")},
// Class
{QStringLiteral("cl"), QStringLiteral("Class")},
{QStringLiteral("specialization"), QStringLiteral("Class")},
{QStringLiteral("tmplt"), QStringLiteral("Class")},
// Constant
{QStringLiteral("data"), QStringLiteral("Constant")},
{QStringLiteral("econst"), QStringLiteral("Constant")},
{QStringLiteral("enumdata"), QStringLiteral("Constant")},
{QStringLiteral("enumelt"), QStringLiteral("Constant")},
{QStringLiteral("clconst"), QStringLiteral("Constant")},
{QStringLiteral("structdata"), QStringLiteral("Constant")},
{QStringLiteral("writerid"), QStringLiteral("Constant")},
{QStringLiteral("Notifications"), QStringLiteral("Constant")},
// Constructor
{QStringLiteral("structctr"), QStringLiteral("Constructor")},
{QStringLiteral("Public Constructors"), QStringLiteral("Constructor")},
// Enumeration
{QStringLiteral("enum"), QStringLiteral("Enumeration")},
{QStringLiteral("Enum"), QStringLiteral("Enumeration")},
{QStringLiteral("Enumerations"), QStringLiteral("Enumeration")},
// Event
{QStringLiteral("event"), QStringLiteral("Event")},
{QStringLiteral("Public Events"), QStringLiteral("Event")},
{QStringLiteral("Inherited Events"), QStringLiteral("Event")},
{QStringLiteral("Private Events"), QStringLiteral("Event")},
// Field
{QStringLiteral("Data Fields"), QStringLiteral("Field")},
// Function
{QStringLiteral("dcop"), QStringLiteral("Function")},
{QStringLiteral("func"), QStringLiteral("Function")},
{QStringLiteral("ffunc"), QStringLiteral("Function")},
{QStringLiteral("signal"), QStringLiteral("Function")},
{QStringLiteral("slot"), QStringLiteral("Function")},
{QStringLiteral("grammar"), QStringLiteral("Function")},
{QStringLiteral("Function Prototypes"), QStringLiteral("Function")},
{QStringLiteral("Functions/Subroutines"), QStringLiteral("Function")},
{QStringLiteral("Members"), QStringLiteral("Function")},
{QStringLiteral("Package Functions"), QStringLiteral("Function")},
{QStringLiteral("Private Member Functions"), QStringLiteral("Function")},
{QStringLiteral("Private Slots"), QStringLiteral("Function")},
{QStringLiteral("Protected Member Functions"), QStringLiteral("Function")},
{QStringLiteral("Protected Slots"), QStringLiteral("Function")},
{QStringLiteral("Public Member Functions"), QStringLiteral("Function")},
{QStringLiteral("Public Slots"), QStringLiteral("Function")},
{QStringLiteral("Signals"), QStringLiteral("Function")},
{QStringLiteral("Static Package Functions"), QStringLiteral("Function")},
{QStringLiteral("Static Private Member Functions"), QStringLiteral("Function")},
{QStringLiteral("Static Protected Member Functions"), QStringLiteral("Function")},
{QStringLiteral("Static Public Member Functions"), QStringLiteral("Function")},
// Guide
{QStringLiteral("doc"), QStringLiteral("Guide")},
// Namespace
{QStringLiteral("ns"), QStringLiteral("Namespace")},
// Macro
{QStringLiteral("macro"), QStringLiteral("Macro")},
// Method
{QStringLiteral("clm"), QStringLiteral("Method")},
{QStringLiteral("enumcm"), QStringLiteral("Method")},
{QStringLiteral("enumctr"), QStringLiteral("Method")},
{QStringLiteral("enumm"), QStringLiteral("Method")},
{QStringLiteral("intfctr"), QStringLiteral("Method")},
{QStringLiteral("intfcm"), QStringLiteral("Method")},
{QStringLiteral("intfm"), QStringLiteral("Method")},
{QStringLiteral("intfsub"), QStringLiteral("Method")},
{QStringLiteral("instsub"), QStringLiteral("Method")},
{QStringLiteral("instctr"), QStringLiteral("Method")},
{QStringLiteral("instm"), QStringLiteral("Method")},
{QStringLiteral("structcm"), QStringLiteral("Method")},
{QStringLiteral("structm"), QStringLiteral("Method")},
{QStringLiteral("structsub"), QStringLiteral("Method")},
{QStringLiteral("Class Methods"), QStringLiteral("Method")},
{QStringLiteral("Inherited Methods"), QStringLiteral("Method")},
{QStringLiteral("Instance Methods"), QStringLiteral("Method")},
{QStringLiteral("Private Methods"), QStringLiteral("Method")},
{QStringLiteral("Protected Methods"), QStringLiteral("Method")},
{QStringLiteral("Public Methods"), QStringLiteral("Method")},
// Operator
{QStringLiteral("intfopfunc"), QStringLiteral("Operator")},
{QStringLiteral("opfunc"), QStringLiteral("Operator")},
// Property
{QStringLiteral("enump"), QStringLiteral("Property")},
{QStringLiteral("intfdata"), QStringLiteral("Property")},
{QStringLiteral("intfp"), QStringLiteral("Property")},
{QStringLiteral("instp"), QStringLiteral("Property")},
{QStringLiteral("structp"), QStringLiteral("Property")},
{QStringLiteral("Inherited Properties"), QStringLiteral("Property")},
{QStringLiteral("Private Properties"), QStringLiteral("Property")},
{QStringLiteral("Protected Properties"), QStringLiteral("Property")},
{QStringLiteral("Public Properties"), QStringLiteral("Property")},
// Protocol
{QStringLiteral("intf"), QStringLiteral("Protocol")},
// Structure
{QStringLiteral("_Struct"), QStringLiteral("Structure")},
{QStringLiteral("_Structs"), QStringLiteral("Structure")},
{QStringLiteral("struct"), QStringLiteral("Structure")},
{QStringLiteral("Сontrol Structure"), QStringLiteral("Structure")},
{QStringLiteral("Data Structures"), QStringLiteral("Structure")},
{QStringLiteral("Struct"), QStringLiteral("Structure")},
// Type
{QStringLiteral("tag"), QStringLiteral("Type")},
{QStringLiteral("tdef"), QStringLiteral("Type")},
{QStringLiteral("Data Types"), QStringLiteral("Type")},
{QStringLiteral("Package Types"), QStringLiteral("Type")},
{QStringLiteral("Private Types"), QStringLiteral("Type")},
{QStringLiteral("Protected Types"), QStringLiteral("Type")},
{QStringLiteral("Public Types"), QStringLiteral("Type")},
{QStringLiteral("Typedefs"), QStringLiteral("Type")},
// Variable
{QStringLiteral("var"), QStringLiteral("Variable")}
};
return aliases.value(str, str);
}
QUrl Docset::baseUrl() const
{
return m_baseUrl;
}
void Docset::setBaseUrl(const QUrl &baseUrl)
{
m_baseUrl = baseUrl;
if (!m_indexFilePath.isEmpty()) {
m_indexFileUrl = createPageUrl(m_indexFilePath);
}
}
bool Docset::isFuzzySearchEnabled() const
{
return m_isFuzzySearchEnabled;
}
void Docset::setFuzzySearchEnabled(bool enabled)
{
m_isFuzzySearchEnabled = enabled;
}
bool Docset::isJavaScriptEnabled() const
{
return m_isJavaScriptEnabled;
}
/**
* \brief Returns score based on a substring position in a string.
* \param str Original string.
* \param index Index of the substring within \a str.
* \param length Substring length.
* \return Score value between 1 and 100.
*/
static int scoreFuzzy(const char *str, int index, int length)
{
// Score between 66..99, if the match follows a dot, or starts the string.
if (index == 0 || str[index - 1] == '.') {
return qMax(66, 100 - length);
}
// Score between 33..66, if the match is at the end of the string.
if (str[index + length] == 0) {
return qMax(33, 67 - length);
}
// Score between 1..33 otherwise (match in the middle of the string).
return qMax(1, 34 - length);
}
// Based on https://github.com/bevacqua/fuzzysearch
static void matchFuzzy(const char *needle, int needleLength,
const char *haystack, int haystackLength,
int *start, int *length)
{
static const int MaxDistance = 8;
static const int MaxGroupCount = 3;
*start = -1;
int groupCount = 0;
int bestRecursiveScore = -1;
int bestRecursiveStart = -1;
int bestRecursiveLength = -1;
for (int i = 0, j = 0; i < needleLength; ++i) {
bool found = false;
bool first = true;
int distance = 0;
while (j < haystackLength) {
if (needle[i] == haystack[j++]) {
if (*start == -1) {
*start = j; // first matched char
// try starting the search later in case the first character occurs again later
int recursiveStart;
int recursiveLength;
matchFuzzy(needle, needleLength, haystack + j,
haystackLength - j,
&recursiveStart, &recursiveLength);
if (recursiveStart != -1) {
int recursiveScore = scoreFuzzy(haystack,
recursiveStart,
recursiveLength);
if (recursiveScore > bestRecursiveScore) {
bestRecursiveScore = recursiveScore;
bestRecursiveStart = recursiveStart;
bestRecursiveLength = recursiveLength;
}
}
}
*length = j - *start + 1;
found = true;
break;
}
// Optimizations to reduce returned number of results
// (search was returning too many irrelevant results with large docsets)
// Optimization #1: too many mismatches.
if (first) {
if (++groupCount >= MaxGroupCount) {
break;
}
first = false;
}
// Optimization #2: too large distance between found chars.
if (i != 0 && ++distance >= MaxDistance) {
break;
}
}
if (!found) {
// End of haystack, char not found.
if (bestRecursiveScore != -1) {
// Can still match with the same constraints if matching started later
// (smaller distance from first char to 2nd char)
*start = bestRecursiveStart;
*length = bestRecursiveLength;
} else {
*start = -1;
}
return;
}
}
int score = scoreFuzzy(haystack, *start, *length);
if (bestRecursiveScore > score) {
*start = bestRecursiveStart;
*length = bestRecursiveLength;
}
}
// Ported from DevDocs (https://github.com/Thibaut/devdocs), see app/searcher.coffee.
static int scoreExact(int matchIndex, int matchLen, const char *value, int valueLen)
{
static const char DOT = '.';
int score = 100;
// Remove one point for each unmatched character.
score -= (valueLen - matchLen);
if (matchIndex > 0) {
if (value[matchIndex - 1] == DOT) {
// If the character preceding the query is a dot, assign the same
// score as if the query was found at the beginning of the string,
// minus one.
score += matchIndex - 1;
} else if (matchLen == 1) {
// Don't match a single-character query unless it's found at the
// beginning of the string or is preceded by a dot.
return 0;
} else {
// (1) Remove one point for each unmatched character up to
// the nearest preceding dot or the beginning of the
// string.
// (2) Remove one point for each unmatched character
// following the query.
int i = matchIndex - 2;
while (i >= 0 && value[i] != DOT) {
--i;
}
score -= (matchIndex - i) // (1)
+ (valueLen - matchLen - matchIndex); // (2)
}
// Remove one point for each dot preceding the query, except for the
// one immediately before the query.
for (int i = matchIndex - 2; i >= 0; --i) {
if (value[i] == DOT)
--score;
}
}
// Remove five points for each dot following the query.
for (int i = valueLen - matchLen - matchIndex - 1; i >= 0; --i) {
if (value[matchIndex + matchLen + i] == DOT)
score -= 5;
}
return qMax(1, score);
}
static inline int scoreFunction(const char *needleOrig, const char *haystackOrig)
{
const int needleLength = static_cast<int>(qstrlen(needleOrig));
const int haystackLength = static_cast<int>(qstrlen(haystackOrig));
QVarLengthArray<char, 1024> needle(needleLength + 1);
QVarLengthArray<char, 1024> haystack(haystackLength + 1);
for (int i = 0, j = 0; i <= needleLength; ++i, ++j) {
const char c = needleOrig[i];
if ((i > 0 && needleOrig[i - 1] == ':' && c == ':') // C++ (::)
|| c == '/' || c == '_' || c == ' ') { // Go, some Guides
needle[j] = '.';
} else if (c >= 'A' && c <= 'Z') {
needle[j] = c + 32;
} else {
needle[j] = c;
}
}
for (int i = 0, j = 0; i <= haystackLength; ++i, ++j) {
const char c = haystackOrig[i];
if ((i > 0 && haystackOrig[i - 1] == ':' && c == ':') // C++ (::)
|| c == '/' || c == '_' || c == ' ') { // Go, some Guides
haystack[j] = '.';
} else if (c >= 'A' && c <= 'Z') {
haystack[j] = c + 32;
} else {
haystack[j] = c;
}
}
int score = 0;
int matchIndex = -1;
int matchLength = 0;
int exactIndex = -1;
const char *exactMatch = std::strstr(haystack.data(), needle.data());
if (exactMatch != nullptr) {
exactIndex = exactMatch - haystack.data();
}
if (exactIndex == -1) {
matchFuzzy(needle.data(), needleLength,
haystack.data(), haystackLength,
&matchIndex, &matchLength);
}
if (matchIndex == -1 && exactIndex == -1) {
// no match
return 0;
}
if (exactIndex != -1) {
// +100 to make sure exact matches are always on top.
score = scoreExact(exactIndex, needleLength, haystack.data(), haystackLength) + 100;
} else {
score = scoreFuzzy(haystack.data(), matchIndex, matchLength);
int indexOfLastDot;
for (indexOfLastDot = haystackLength - 1; indexOfLastDot >= 0; --indexOfLastDot) {
if (haystack[indexOfLastDot] == '.')
break;
}
if (indexOfLastDot != -1) {
matchIndex = -1;
matchFuzzy(needle.data(), needleLength,
haystack.data() + indexOfLastDot + 1, haystackLength - (indexOfLastDot + 1),
&matchIndex, &matchLength);
if (matchIndex != -1) {
score = qMax(score, scoreFuzzy(haystack.data() + indexOfLastDot + 1,
matchIndex, matchLength));
}
}
}
return score;
}
static void sqliteScoreFunction(sqlite3_context *context, int argc, sqlite3_value **argv)
{
Q_UNUSED(argc)
auto needle = reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
auto haystack = reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
sqlite3_result_int(context, scoreFunction(needle, haystack));
}
| 35,035
|
C++
|
.cpp
| 824
| 33.690534
| 111
| 0.608022
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,975
|
docsetregistry.cpp
|
zealdocs_zeal/src/libs/registry/docsetregistry.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include "docsetregistry.h"
#include "docset.h"
#include "listmodel.h"
#include "searchquery.h"
#include "searchresult.h"
#include <core/application.h>
#include <core/httpserver.h>
#include <QDir>
#include <QThread>
#include <QtConcurrent>
#include <functional>
#include <future>
using namespace Zeal::Registry;
void MergeQueryResults(QList<SearchResult> &finalResult, const QList<SearchResult> &partial)
{
finalResult << partial;
}
DocsetRegistry::DocsetRegistry(QObject *parent)
: QObject(parent)
, m_model(new ListModel(this))
, m_thread(new QThread(this))
{
// Register for use in signal connections.
qRegisterMetaType<QList<SearchResult>>("QList<SearchResult>");
// FIXME: Only search should be performed in a separate thread
moveToThread(m_thread);
m_thread->start();
}
DocsetRegistry::~DocsetRegistry()
{
m_thread->exit();
m_thread->wait();
qDeleteAll(m_docsets);
}
QAbstractItemModel *DocsetRegistry::model() const
{
return m_model;
}
QString DocsetRegistry::storagePath() const
{
return m_storagePath;
}
void DocsetRegistry::setStoragePath(const QString &path)
{
if (path == m_storagePath) {
return;
}
m_storagePath = path;
unloadAllDocsets();
addDocsetsFromFolder(path);
}
bool DocsetRegistry::isFuzzySearchEnabled() const
{
return m_isFuzzySearchEnabled;
}
void DocsetRegistry::setFuzzySearchEnabled(bool enabled)
{
if (enabled == m_isFuzzySearchEnabled) {
return;
}
m_isFuzzySearchEnabled = enabled;
for (Docset *docset : std::as_const(m_docsets)) {
docset->setFuzzySearchEnabled(enabled);
}
}
int DocsetRegistry::count() const
{
return m_docsets.count();
}
bool DocsetRegistry::contains(const QString &name) const
{
return m_docsets.contains(name);
}
QStringList DocsetRegistry::names() const
{
return m_docsets.keys();
}
void DocsetRegistry::loadDocset(const QString &path)
{
std::future<Docset *> f = std::async(std::launch::async, [path](){
return new Docset(path);
});
f.wait();
Docset *docset = f.get();
// TODO: Emit error
if (!docset->isValid()) {
qWarning("Could not load docset from '%s'. Reinstall the docset.",
qPrintable(docset->path()));
delete docset;
return;
}
docset->setFuzzySearchEnabled(m_isFuzzySearchEnabled);
const QString name = docset->name();
if (m_docsets.contains(name)) {
unloadDocset(name);
}
// Setup HTTP mount.
QUrl url = Core::Application::instance()->httpServer()->mount(name, docset->documentPath());
if (url.isEmpty()) {
qWarning("Could not enable docset from '%s'. Reinstall the docset.",
qPrintable(docset->path()));
delete docset;
return;
}
docset->setBaseUrl(url);
m_docsets[name] = docset;
emit docsetLoaded(name);
}
void DocsetRegistry::unloadDocset(const QString &name)
{
emit docsetAboutToBeUnloaded(name);
Core::Application::instance()->httpServer()->unmount(name);
delete m_docsets.take(name);
emit docsetUnloaded(name);
}
void DocsetRegistry::unloadAllDocsets()
{
const auto keys = m_docsets.keys();
for (const QString &name : keys) {
unloadDocset(name);
}
}
Docset *DocsetRegistry::docset(const QString &name) const
{
return m_docsets[name];
}
Docset *DocsetRegistry::docset(int index) const
{
if (index < 0 || index >= m_docsets.size())
return nullptr;
auto it = m_docsets.cbegin();
std::advance(it, index);
return *it;
}
Docset *DocsetRegistry::docsetForUrl(const QUrl &url)
{
for (Docset *docset : std::as_const(m_docsets)) {
if (docset->baseUrl().isParentOf(url))
return docset;
}
return nullptr;
}
QList<Docset *> DocsetRegistry::docsets() const
{
return m_docsets.values();
}
void DocsetRegistry::search(const QString &query)
{
m_cancellationToken.cancel();
if (query.isEmpty()) {
emit searchCompleted({});
return;
}
QMetaObject::invokeMethod(this, "_runQuery", Qt::QueuedConnection, Q_ARG(QString, query));
}
void DocsetRegistry::_runQuery(const QString &query)
{
m_cancellationToken.reset();
QList<Docset *> enabledDocsets;
const SearchQuery searchQuery = SearchQuery::fromString(query);
if (searchQuery.hasKeywords()) {
for (Docset *docset : std::as_const(m_docsets)) {
if (searchQuery.hasKeywords(docset->keywords()))
enabledDocsets << docset;
}
} else {
enabledDocsets = docsets();
}
QFuture<QList<SearchResult>> queryResultsFuture
= QtConcurrent::mappedReduced(enabledDocsets,
std::bind(&Docset::search,
std::placeholders::_1,
searchQuery.query(),
std::ref(m_cancellationToken)),
&MergeQueryResults);
QList<SearchResult> results = queryResultsFuture.result();
if (m_cancellationToken.isCanceled())
return;
std::sort(results.begin(), results.end());
if (m_cancellationToken.isCanceled())
return;
emit searchCompleted(results);
}
// Recursively finds and adds all docsets in a given directory.
void DocsetRegistry::addDocsetsFromFolder(const QString &path)
{
const QDir dir(path);
const auto subDirectories = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllDirs);
for (const QFileInfo &subdir : subDirectories) {
if (subdir.suffix() == QLatin1String("docset"))
loadDocset(subdir.filePath());
else
addDocsetsFromFolder(subdir.filePath());
}
}
| 5,975
|
C++
|
.cpp
| 198
| 24.565657
| 96
| 0.660147
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,976
|
main.cpp
|
zealdocs_zeal/src/app/main.cpp
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#include <core/application.h>
#include <core/applicationsingleton.h>
#include <registry/searchquery.h>
#include <QApplication>
#include <QCommandLineParser>
#include <QDataStream>
#include <QDesktopServices>
#include <QDir>
#include <QIcon>
#include <QMessageBox>
#include <QTextStream>
#include <QTimer>
#include <QUrlQuery>
#ifdef Q_OS_WIN32
#include <QSettings>
#include <Windows.h>
#endif
#include <cstdlib>
using namespace Zeal;
struct CommandLineParameters
{
bool force;
bool preventActivation;
Registry::SearchQuery query;
#ifdef Q_OS_WIN32
bool registerProtocolHandlers;
bool unregisterProtocolHandlers;
#endif
};
QString stripParameterUrl(const QString &url, const QString &scheme)
{
QString str = url.mid(scheme.length() + 1);
if (str.startsWith(QLatin1String("//"))) {
str = str.mid(2);
}
if (str.endsWith(QLatin1Char('/'))) {
str = str.left(str.length() - 1);
}
return str;
}
CommandLineParameters parseCommandLine(const QStringList &arguments)
{
QCommandLineParser parser;
parser.setApplicationDescription(QObject::tr("Zeal - Offline documentation browser."));
parser.addHelpOption();
parser.addVersionOption();
parser.addOption({{QStringLiteral("f"), QStringLiteral("force")},
QObject::tr("Force the application run.")});
#ifdef Q_OS_WIN32
parser.addOption(QCommandLineOption({QStringLiteral("register")},
QObject::tr("Register protocol handlers")));
parser.addOption(QCommandLineOption({QStringLiteral("unregister")},
QObject::tr("Unregister protocol handlers")));
#endif
parser.addPositionalArgument(QStringLiteral("url"), QObject::tr("dash[-plugin]:// URL"));
parser.process(arguments);
CommandLineParameters clParams;
clParams.force = parser.isSet(QStringLiteral("force"));
clParams.preventActivation = false;
#ifdef Q_OS_WIN32
clParams.registerProtocolHandlers = parser.isSet(QStringLiteral("register"));
clParams.unregisterProtocolHandlers = parser.isSet(QStringLiteral("unregister"));
if (clParams.registerProtocolHandlers && clParams.unregisterProtocolHandlers) {
QTextStream(stderr) << QObject::tr("Parameter conflict: --register and --unregister.\n");
::exit(EXIT_FAILURE);
}
#endif
// TODO: Support dash-feed:// protocol
const QString arg
= QUrl::fromPercentEncoding(parser.positionalArguments().value(0).toUtf8());
if (arg.startsWith(QLatin1String("dash:"))) {
clParams.query.setQuery(stripParameterUrl(arg, QStringLiteral("dash")));
} else if (arg.startsWith(QLatin1String("dash-plugin:"))) {
const QUrlQuery urlQuery(stripParameterUrl(arg, QStringLiteral("dash-plugin")));
const QString keys = urlQuery.queryItemValue(QStringLiteral("keys"));
if (!keys.isEmpty())
clParams.query.setKeywords(keys.split(QLatin1Char(',')));
clParams.query.setQuery(urlQuery.queryItemValue(QStringLiteral("query")));
const QString preventActivation
= urlQuery.queryItemValue(QStringLiteral("prevent_activation"));
clParams.preventActivation = preventActivation == QLatin1String("true");
} else {
clParams.query.setQuery(arg);
}
return clParams;
}
#ifdef Q_OS_WIN32
void registerProtocolHandler(const QString &scheme, const QString &description)
{
const QString appPath = QDir::toNativeSeparators(QCoreApplication::applicationFilePath());
const QString regPath = QStringLiteral("HKEY_CURRENT_USER\\Software\\Classes\\") + scheme;
QScopedPointer<QSettings> reg(new QSettings(regPath, QSettings::NativeFormat));
reg->setValue(QStringLiteral("Default"), description);
reg->setValue(QStringLiteral("URL Protocol"), QString());
reg->beginGroup(QStringLiteral("DefaultIcon"));
reg->setValue(QStringLiteral("Default"), QString("%1,1").arg(appPath));
reg->endGroup();
reg->beginGroup(QStringLiteral("shell"));
reg->beginGroup(QStringLiteral("open"));
reg->beginGroup(QStringLiteral("command"));
reg->setValue(QStringLiteral("Default"), QVariant(appPath + QLatin1String(" %1")));
}
void registerProtocolHandlers(const QHash<QString, QString> &protocols, bool force = false)
{
const QString regPath = QStringLiteral("HKEY_CURRENT_USER\\Software\\Classes");
QScopedPointer<QSettings> reg(new QSettings(regPath, QSettings::NativeFormat));
const QStringList groups = reg->childGroups();
for (auto it = protocols.cbegin(); it != protocols.cend(); ++it) {
if (force || !groups.contains(it.key()))
registerProtocolHandler(it.key(), it.value());
}
}
void unregisterProtocolHandlers(const QHash<QString, QString> &protocols)
{
const QString regPath = QStringLiteral("HKEY_CURRENT_USER\\Software\\Classes");
QScopedPointer<QSettings> reg(new QSettings(regPath, QSettings::NativeFormat));
for (auto it = protocols.cbegin(); it != protocols.cend(); ++it) {
reg->remove(it.key());
}
}
#endif
int main(int argc, char *argv[])
{
// Do not allow Qt version lower than the app was compiled with.
QT_REQUIRE_VERSION(argc, argv, QT_VERSION_STR)
QCoreApplication::setApplicationName(QStringLiteral("Zeal"));
QCoreApplication::setApplicationVersion(ZEAL_VERSION);
QCoreApplication::setOrganizationDomain(QStringLiteral("zealdocs.org"));
QCoreApplication::setOrganizationName(QStringLiteral("Zeal"));
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#endif
// Use Fusion style on Windows 10 & 11. This enables proper dark mode support.
// See https://www.qt.io/blog/dark-mode-on-windows-11-with-qt-6.5.
// TODO: Make style configurable, detect -style argument.
#if defined(Q_OS_WIN) && (QT_VERSION >= QT_VERSION_CHECK(6, 5, 0))
const auto osName = QSysInfo::prettyProductName();
if (osName.startsWith("Windows 10") || osName.startsWith("Windows 11")) {
QApplication::setStyle("fusion");
}
#endif
QScopedPointer<QApplication> qapp(new QApplication(argc, argv));
const CommandLineParameters clParams = parseCommandLine(qapp->arguments());
#ifdef Q_OS_WIN32
const static QHash<QString, QString> protocols = {
{QStringLiteral("dash"), QStringLiteral("URL:Dash Protocol (Zeal)")},
{QStringLiteral("dash-plugin"), QStringLiteral("URL:Dash Plugin Protocol (Zeal)")}
};
if (clParams.registerProtocolHandlers) {
registerProtocolHandlers(protocols, clParams.registerProtocolHandlers);
return EXIT_SUCCESS;
}
if (clParams.unregisterProtocolHandlers) {
unregisterProtocolHandlers(protocols);
return EXIT_SUCCESS;
}
#endif
QScopedPointer<Core::ApplicationSingleton> appSingleton(new Core::ApplicationSingleton());
if (appSingleton->isSecondary()) {
#ifdef Q_OS_WIN32
::AllowSetForegroundWindow(appSingleton->primaryPid());
#endif
QByteArray ba;
QDataStream out(&ba, QIODevice::WriteOnly);
out << clParams.query << clParams.preventActivation;
// TODO: Check for a possible error.
appSingleton->sendMessage(ba);
return EXIT_SUCCESS;
}
// Set application-wide window icon. All message boxes and other windows will use it by default.
qapp->setDesktopFileName(QStringLiteral("org.zealdocs.zeal"));
qapp->setWindowIcon(QIcon::fromTheme(QStringLiteral("zeal"),
QIcon(QStringLiteral(":/zeal.ico"))));
QDir::setSearchPaths(QStringLiteral("typeIcon"), {QStringLiteral(":/icons/type")});
QScopedPointer<Core::Application> app(new Core::Application());
QObject::connect(appSingleton.data(), &Core::ApplicationSingleton::messageReceived,
[&app](const QByteArray &data) {
Registry::SearchQuery query;
bool preventActivation;
QDataStream in(data);
in >> query >> preventActivation;
app->executeQuery(query, preventActivation);
});
if (!clParams.query.isEmpty()) {
QTimer::singleShot(0, app.data(), [&app, clParams] {
app->executeQuery(clParams.query, clParams.preventActivation);
});
}
return qapp->exec();
}
| 8,523
|
C++
|
.cpp
| 194
| 38.262887
| 100
| 0.708177
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
11,978
|
plist.h
|
zealdocs_zeal/src/libs/util/plist.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_UTIL_PLIST_H
#define ZEAL_UTIL_PLIST_H
#include <QHash>
#include <QVariant>
namespace Zeal {
namespace Util {
class Plist : public QHash<QString, QVariant>
{
public:
Plist() = default;
bool read(const QString &fileName);
bool hasError() const;
private:
bool m_hasError = false;
};
} // namespace Util
} // namespace Zeal
#endif // ZEAL_UTIL_PLIST_H
| 493
|
C++
|
.h
| 20
| 22.45
| 61
| 0.724731
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,979
|
caseinsensitivemap.h
|
zealdocs_zeal/src/libs/util/caseinsensitivemap.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_UTIL_CASEINSENSITIVEMAP_H
#define ZEAL_UTIL_CASEINSENSITIVEMAP_H
#include <QString>
#include <map>
namespace Zeal {
namespace Util {
struct CaseInsensitiveStringComparator
{
bool operator()(const QString &lhs, const QString &rhs) const
{
return QString::compare(lhs, rhs, Qt::CaseInsensitive) < 0;
}
};
template<typename T>
using CaseInsensitiveMap = std::map<QString, T, CaseInsensitiveStringComparator>;
} // namespace Util
} // namespace Zeal
#endif // ZEAL_UTIL_CASEINSENSITIVEMAP_H
| 635
|
C++
|
.h
| 20
| 29.35
| 81
| 0.76112
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,980
|
sqlitedatabase.h
|
zealdocs_zeal/src/libs/util/sqlitedatabase.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2016 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_UTIL_SQLITEDATABASE_H
#define ZEAL_UTIL_SQLITEDATABASE_H
#include <QStringList>
#include <QVariant>
struct sqlite3;
struct sqlite3_stmt;
namespace Zeal {
namespace Util {
class SQLiteDatabase
{
Q_DISABLE_COPY(SQLiteDatabase)
public:
explicit SQLiteDatabase(const QString &path);
virtual ~SQLiteDatabase();
bool isOpen() const;
QStringList tables();
QStringList views();
bool prepare(const QString &sql);
bool next();
bool execute(const QString &sql);
QVariant value(int index) const;
QString lastError() const;
sqlite3 *handle() const;
private:
void close();
void finalize();
void updateLastError();
sqlite3 *m_db = nullptr;
sqlite3_stmt *m_stmt = nullptr;
QString m_lastError;
};
} // namespace Util
} // namespace Zeal
#endif // ZEAL_UTIL_SQLITEDATABASE_H
| 1,001
|
C++
|
.h
| 37
| 23.675676
| 61
| 0.725738
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,981
|
filemanager.h
|
zealdocs_zeal/src/libs/core/filemanager.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_CORE_FILEMANAGER_H
#define ZEAL_CORE_FILEMANAGER_H
#include <QObject>
namespace Zeal {
namespace Core {
class FileManager final : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(FileManager)
public:
explicit FileManager(QObject *parent = nullptr);
bool removeRecursively(const QString &path);
};
} // namespace Core
} // namespace Zeal
#endif // ZEAL_CORE_FILEMANAGER_H
| 506
|
C++
|
.h
| 18
| 25.833333
| 61
| 0.756757
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,982
|
extractor.h
|
zealdocs_zeal/src/libs/core/extractor.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_CORE_EXTRACTOR_H
#define ZEAL_CORE_EXTRACTOR_H
#include <QObject>
struct archive;
namespace Zeal {
namespace Core {
class Extractor final : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(Extractor)
public:
explicit Extractor(QObject *parent = nullptr);
public slots:
void extract(const QString &sourceFile,
const QString &destination,
const QString &root = QString());
signals:
void error(const QString &filePath, const QString &message);
void completed(const QString &filePath);
void progress(const QString &filePath, qint64 extracted, qint64 total);
private:
struct ExtractInfo {
archive *archiveHandle;
QString filePath;
qint64 totalBytes;
qint64 extractedBytes;
};
void emitProgress(ExtractInfo &info);
};
} // namespace Core
} // namespace Zeal
#endif // ZEAL_CORE_EXTRACTOR_H
| 1,013
|
C++
|
.h
| 34
| 25.352941
| 75
| 0.71281
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,983
|
httpserver.h
|
zealdocs_zeal/src/libs/core/httpserver.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_CORE_HTTPSERVER_H
#define ZEAL_CORE_HTTPSERVER_H
#include <QObject>
#include <QUrl>
#include <future>
#include <memory>
namespace httplib {
class Server;
} // namespace httplib
namespace Zeal {
namespace Core {
class HttpServer : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(HttpServer)
public:
explicit HttpServer(QObject *parent = nullptr);
~HttpServer() override;
QUrl baseUrl() const;
QUrl mount(const QString &prefix, const QString &path);
bool unmount(const QString &prefix);
private:
static QString sanitizePrefix(const QString &prefix);
std::unique_ptr<httplib::Server> m_server;
std::future<bool> m_future;
QUrl m_baseUrl;
};
} // namespace Core
} // namespace Zeal
#endif // ZEAL_CORE_HTTPSERVER_H
| 881
|
C++
|
.h
| 32
| 24.75
| 61
| 0.739234
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,984
|
applicationsingleton.h
|
zealdocs_zeal/src/libs/core/applicationsingleton.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_CORE_APPLICATIONSINGLETON_H
#define ZEAL_CORE_APPLICATIONSINGLETON_H
#include <QObject>
class QLocalServer;
class QSharedMemory;
namespace Zeal {
namespace Core {
class ApplicationSingleton final : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(ApplicationSingleton)
public:
explicit ApplicationSingleton(QObject *parent = nullptr);
bool isPrimary() const;
bool isSecondary() const;
qint64 primaryPid() const;
bool sendMessage(QByteArray &data, int timeout = 500);
signals:
void messageReceived(const QByteArray &data);
private:
void setupPrimary();
void setupSecondary();
static QString computeId();
QString m_id;
bool m_isPrimary = false;
qint64 m_primaryPid = 0;
QSharedMemory *m_sharedMemory = nullptr;
QLocalServer *m_localServer = nullptr;
};
} // namespace Core
} // namespace Zeal
#endif // ZEAL_CORE_APPLICATIONSINGLETON_H
| 1,025
|
C++
|
.h
| 34
| 26.823529
| 61
| 0.754098
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,985
|
settings.h
|
zealdocs_zeal/src/libs/core/settings.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_CORE_SETTINGS_H
#define ZEAL_CORE_SETTINGS_H
#include <QDataStream>
#include <QKeySequence>
#include <QObject>
class QSettings;
namespace Zeal {
namespace Core {
class Settings final : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(Settings)
public:
/* This public members are here just for simplification and should go away
* once a more advanced settings management come in place.
*/
// Startup
bool startMinimized;
bool checkForUpdate;
// TODO: bool restoreLastState;
// System Tray
bool showSystrayIcon;
bool minimizeToSystray;
bool hideOnClose;
// Global Shortcuts
QKeySequence showShortcut;
// TODO: QKeySequence searchSelectedTextShortcut;
// Tabs Behavior
bool openNewTabAfterActive;
// Search
bool isFuzzySearchEnabled;
// Content
QString defaultFontFamily;
QString serifFontFamily;
QString sansSerifFontFamily;
QString fixedFontFamily;
int defaultFontSize;
int defaultFixedFontSize;
int minimumFontSize;
enum class ExternalLinkPolicy : unsigned int {
Ask = 0,
Open,
OpenInSystemBrowser
};
Q_ENUM(ExternalLinkPolicy)
ExternalLinkPolicy externalLinkPolicy = ExternalLinkPolicy::Ask;
enum class ContentAppearance : unsigned int {
Automatic = 0,
Light,
Dark
};
Q_ENUM(ContentAppearance)
ContentAppearance contentAppearance = ContentAppearance::Automatic;
bool isHighlightOnNavigateEnabled;
QString customCssFile;
bool isSmoothScrollingEnabled;
// Network
enum ProxyType : unsigned int {
None = 0,
System = 1,
Http = 3,
Socks5 = 4
};
Q_ENUM(ProxyType)
// Internal
// --------
// InstallId is a UUID used to identify a Zeal installation. Created on first start or after
// a settings wipe. It is not attached to user hardware or software, and is sent exclusively
// to *.zealdocs.org hosts.
QString installId;
ProxyType proxyType = ProxyType::System;
QString proxyHost;
quint16 proxyPort;
bool proxyAuthenticate;
QString proxyUserName;
QString proxyPassword;
bool isIgnoreSslErrorsEnabled;
// Other
QString docsetPath;
// State
QByteArray windowGeometry;
QByteArray verticalSplitterGeometry;
QByteArray tocSplitterState;
explicit Settings(QObject *parent = nullptr);
~Settings() override;
// Helper functions.
bool isDarkModeEnabled() const;
#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
typedef Qt::ColorScheme ColorScheme;
#else
enum class ColorScheme {
Unknown,
Light,
Dark,
};
#endif
static ColorScheme colorScheme();
public slots:
void load();
void save();
signals:
void updated();
private:
void migrate(QSettings *settings) const;
static QSettings *qsettings(QObject *parent = nullptr);
};
} // namespace Core
} // namespace Zeal
QDataStream &operator<<(QDataStream &out, Zeal::Core::Settings::ContentAppearance policy);
QDataStream &operator>>(QDataStream &in, Zeal::Core::Settings::ContentAppearance &policy);
QDataStream &operator<<(QDataStream &out, Zeal::Core::Settings::ExternalLinkPolicy policy);
QDataStream &operator>>(QDataStream &in, Zeal::Core::Settings::ExternalLinkPolicy &policy);
Q_DECLARE_METATYPE(Zeal::Core::Settings::ContentAppearance)
Q_DECLARE_METATYPE(Zeal::Core::Settings::ExternalLinkPolicy)
#endif // ZEAL_CORE_SETTINGS_H
| 3,609
|
C++
|
.h
| 117
| 26.094017
| 96
| 0.721307
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,986
|
networkaccessmanager.h
|
zealdocs_zeal/src/libs/core/networkaccessmanager.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_CORE_NETWORKACCESSMANAGER_H
#define ZEAL_CORE_NETWORKACCESSMANAGER_H
#include <QNetworkAccessManager>
namespace Zeal {
namespace Core {
class NetworkAccessManager final : public QNetworkAccessManager
{
Q_OBJECT
Q_DISABLE_COPY(NetworkAccessManager)
public:
NetworkAccessManager(QObject *parent = nullptr);
static bool isLocalFile(const QUrl &url);
static bool isLocalUrl(const QUrl &url);
protected:
QNetworkReply *createRequest(Operation op, const QNetworkRequest &request,
QIODevice *outgoingData = nullptr) override;
};
} // namespace Core
} // namespace Zeal
#endif // ZEAL_CORE_NETWORKACCESSMANAGER_H
| 790
|
C++
|
.h
| 22
| 31.954545
| 78
| 0.756579
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,987
|
application.h
|
zealdocs_zeal/src/libs/core/application.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_CORE_APPLICATION_H
#define ZEAL_CORE_APPLICATION_H
#include <QObject>
#include <QVersionNumber>
class QNetworkAccessManager;
class QNetworkReply;
class QThread;
namespace Zeal {
namespace Registry {
class DocsetRegistry;
class SearchQuery;
} // namespace Registry
namespace WidgetUi {
class MainWindow;
} // namespace WidgetUi
namespace Core {
class Extractor;
class FileManager;
class HttpServer;
class Settings;
class Application final : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(Application)
public:
explicit Application(QObject *parent = nullptr);
~Application() override;
static Application *instance();
WidgetUi::MainWindow *mainWindow() const;
QNetworkAccessManager *networkManager() const;
Settings *settings() const;
Registry::DocsetRegistry *docsetRegistry();
FileManager *fileManager() const;
HttpServer *httpServer() const;
static QString cacheLocation();
static QString configLocation();
static QVersionNumber version();
static QString versionString();
public slots:
void executeQuery(const Registry::SearchQuery &query, bool preventActivation);
void extract(const QString &filePath, const QString &destination, const QString &root = QString());
QNetworkReply *download(const QUrl &url);
void checkForUpdates(bool quiet = false);
signals:
void extractionCompleted(const QString &filePath);
void extractionError(const QString &filePath, const QString &errorString);
void extractionProgress(const QString &filePath, qint64 extracted, qint64 total);
void updateCheckDone(const QString &version = QString());
void updateCheckError(const QString &message);
private slots:
void applySettings();
private:
static inline QString userAgent();
QString userAgentJson() const;
static Application *m_instance;
Settings *m_settings = nullptr;
QNetworkAccessManager *m_networkManager = nullptr;
FileManager *m_fileManager = nullptr;
HttpServer *m_httpServer = nullptr;
QThread *m_extractorThread = nullptr;
Extractor *m_extractor = nullptr;
Registry::DocsetRegistry *m_docsetRegistry = nullptr;
WidgetUi::MainWindow *m_mainWindow = nullptr;
};
} // namespace Core
} // namespace Zeal
#endif // ZEAL_CORE_APPLICATION_H
| 2,405
|
C++
|
.h
| 69
| 31.376812
| 103
| 0.767432
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,988
|
browsertab.h
|
zealdocs_zeal/src/libs/ui/browsertab.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_WIDGETUI_BROWSERTAB_H
#define ZEAL_WIDGETUI_BROWSERTAB_H
#include <registry/searchmodel.h>
#include <QModelIndexList>
#include <QWidget>
class QToolButton;
namespace Zeal {
namespace Browser {
class WebControl;
} // namespace Browser
namespace Registry {
class SearchQuery;
} //namespace Registry
namespace WidgetUi {
class SearchSidebar;
class BrowserTab : public QWidget
{
Q_OBJECT
Q_DISABLE_COPY(BrowserTab)
public:
explicit BrowserTab(QWidget *parent = nullptr);
BrowserTab *clone(QWidget *parent = nullptr) const;
~BrowserTab() override;
Browser::WebControl *webControl() const;
SearchSidebar *searchSidebar(); // TODO: const
public slots:
void navigateToStartPage();
void search(const Registry::SearchQuery &query);
signals:
void iconChanged(const QIcon &icon);
void titleChanged(const QString &title);
private:
QIcon docsetIcon(const QUrl &url) const;
// Widgets.
SearchSidebar *m_searchSidebar = nullptr;
Browser::WebControl *m_webControl = nullptr;
QToolButton *m_backButton = nullptr;
QToolButton *m_forwardButton = nullptr;
};
} // namespace WidgetUi
} // namespace Zeal
#endif // ZEAL_WIDGETUI_BROWSERTAB_H
| 1,324
|
C++
|
.h
| 44
| 27.159091
| 61
| 0.759303
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,989
|
sidebarviewprovider.h
|
zealdocs_zeal/src/libs/ui/sidebarviewprovider.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_WIDGETUI_SIDEBARVIEWPROVIDER_H
#define ZEAL_WIDGETUI_SIDEBARVIEWPROVIDER_H
#include <sidebar/viewprovider.h>
namespace Zeal {
namespace WidgetUi {
class MainWindow;
class SidebarViewProvider : public Sidebar::ViewProvider
{
Q_OBJECT
Q_DISABLE_COPY(SidebarViewProvider)
public:
explicit SidebarViewProvider(MainWindow *mainWindow);
Sidebar::View *view(const QString &id = QString()) const override;
private:
MainWindow *m_mainWindow = nullptr;
};
} // namespace WidgetUi
} // namespace Zeal
#endif // ZEAL_WIDGETUI_SIDEBARVIEWPROVIDER_H
| 685
|
C++
|
.h
| 21
| 30.238095
| 70
| 0.784733
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,990
|
docsetlistitemdelegate.h
|
zealdocs_zeal/src/libs/ui/docsetlistitemdelegate.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_WIDGETUI_DOCSETLISTITEMDELEGATE_H
#define ZEAL_WIDGETUI_DOCSETLISTITEMDELEGATE_H
#include <QStyledItemDelegate>
namespace Zeal {
namespace WidgetUi {
class DocsetListItemDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
enum ProgressRoles {
ValueRole = Qt::UserRole + 10,
FormatRole,
ShowProgressRole
};
explicit DocsetListItemDelegate(QObject *parent = nullptr);
void paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const override;
private:
void paintProgressBar(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const;
};
} // namespace WidgetUi
} // namespace Zeal
#endif // ZEAL_WIDGETUI_DOCSETLISTITEMDELEGATE_H
| 993
|
C++
|
.h
| 29
| 28.448276
| 63
| 0.710995
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,991
|
docsetsdialog.h
|
zealdocs_zeal/src/libs/ui/docsetsdialog.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_WIDGETUI_DOCSETSDIALOG_H
#define ZEAL_WIDGETUI_DOCSETSDIALOG_H
#include <registry/docsetmetadata.h>
#include <util/caseinsensitivemap.h>
#include <QDialog>
#include <QHash>
#include <QMap>
class QListWidgetItem;
class QNetworkReply;
class QTemporaryFile;
class QUrl;
namespace Zeal {
namespace Registry {
class DocsetRegistry;
} // namespace Registry
namespace Core {
class Application;
}
namespace WidgetUi {
namespace Ui {
class DocsetsDialog;
} // namespace Ui
class DocsetsDialog : public QDialog
{
Q_OBJECT
public:
explicit DocsetsDialog(Core::Application *app, QWidget *parent = nullptr);
~DocsetsDialog() override;
private slots:
void addDashFeed();
void updateSelectedDocsets();
void updateAllDocsets();
void removeSelectedDocsets();
void updateDocsetFilter(const QString &filterString);
void downloadSelectedDocsets();
void downloadCompleted();
void downloadProgress(qint64 received, qint64 total);
void extractionCompleted(const QString &filePath);
void extractionError(const QString &filePath, const QString &errorString);
void extractionProgress(const QString &filePath, qint64 extracted, qint64 total);
void loadDocsetList();
private:
enum DownloadType {
DownloadDashFeed,
DownloadDocset,
DownloadDocsetList
};
Ui::DocsetsDialog *ui = nullptr;
Core::Application *m_application = nullptr;
Registry::DocsetRegistry *m_docsetRegistry = nullptr;
bool m_isStorageReadOnly = false;
QList<QNetworkReply *> m_replies;
// TODO: Create a special model
Util::CaseInsensitiveMap<Registry::DocsetMetadata> m_availableDocsets;
QMap<QString, Registry::DocsetMetadata> m_userFeeds;
QHash<QString, QTemporaryFile *> m_tmpFiles;
void setupInstalledDocsetsTab();
void setupAvailableDocsetsTab();
void enableControls();
void disableControls();
QListWidgetItem *findDocsetListItem(const QString &name) const;
bool updatesAvailable() const;
QNetworkReply *download(const QUrl &url);
void cancelDownloads();
void loadUserFeedList();
void downloadDocsetList();
void processDocsetList(const QJsonArray &list);
void downloadDashDocset(const QModelIndex &index);
void removeDocset(const QString &name);
void updateStatus();
// FIXME: Come up with a better approach
QString docsetNameForTmpFilePath(const QString &filePath) const;
static inline int percent(qint64 fraction, qint64 total);
static QString cacheLocation(const QString &fileName);
static bool isDirWritable(const QString &path);
};
} // namespace WidgetUi
} // namespace Zeal
#endif // ZEAL_WIDGETUI_DOCSETSDIALOG_H
| 2,861
|
C++
|
.h
| 82
| 31
| 85
| 0.76402
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,992
|
aboutdialog.h
|
zealdocs_zeal/src/libs/ui/aboutdialog.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_WIDGETUI_ABOUTDIALOG_H
#define ZEAL_WIDGETUI_ABOUTDIALOG_H
#include <QDialog>
namespace Zeal {
namespace WidgetUi {
namespace Ui {
class AboutDialog;
} // namespace Ui
class AboutDialog : public QDialog
{
Q_OBJECT
public:
explicit AboutDialog(QWidget *parent = nullptr);
~AboutDialog() override;
private:
Ui::AboutDialog *ui;
};
} // namespace WidgetUi
} // namespace Zeal
#endif // ZEAL_WIDGETUI_ABOUTDIALOG_H
| 555
|
C++
|
.h
| 22
| 23.136364
| 61
| 0.758095
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,993
|
searchitemdelegate.h
|
zealdocs_zeal/src/libs/ui/searchitemdelegate.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_WIDGETUI_SEARCHITEMDELEGATE_H
#define ZEAL_WIDGETUI_SEARCHITEMDELEGATE_H
#include <QStyledItemDelegate>
namespace Zeal {
namespace WidgetUi {
class SearchItemDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
explicit SearchItemDelegate(QObject *parent = nullptr);
QList<int> decorationRoles() const;
void setDecorationRoles(const QList<int> &roles);
bool helpEvent(QHelpEvent *event, QAbstractItemView *view, const QStyleOptionViewItem &option,
const QModelIndex &index) override;
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const override;
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override;
public slots:
void setHighlight(const QString &text);
private:
QList<int> m_decorationRoles = {Qt::DecorationRole};
QString m_highlight;
};
} // namespace WidgetUi
} // namespace Zeal
#endif // ZEAL_WIDGETUI_SEARCHITEMDELEGATE_H
| 1,162
|
C++
|
.h
| 29
| 36.172414
| 98
| 0.764025
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,994
|
mainwindow.h
|
zealdocs_zeal/src/libs/ui/mainwindow.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_WIDGETUI_MAINWINDOW_H
#define ZEAL_WIDGETUI_MAINWINDOW_H
#include <QMainWindow>
class QxtGlobalShortcut;
class QSystemTrayIcon;
class QTabBar;
namespace Zeal {
namespace Browser {
class WebBridge;
} // namespace Browser
namespace Core {
class Application;
class Settings;
} // namespace Core
namespace Registry {
class SearchQuery;
} //namespace Registry
namespace WidgetUi {
namespace Ui {
class MainWindow;
} // namespace Ui
class BrowserTab;
class SidebarViewProvider;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(Core::Application *app, QWidget *parent = nullptr);
~MainWindow() override;
void search(const Registry::SearchQuery &query);
void bringToFront();
BrowserTab *createTab();
public slots:
void toggleWindow();
signals:
void currentTabChanged();
protected:
void changeEvent(QEvent *event) override;
void closeEvent(QCloseEvent *event) override;
bool eventFilter(QObject *object, QEvent *event) override;
void keyPressEvent(QKeyEvent *keyEvent) override;
private slots:
void applySettings();
void closeTab(int index = -1);
void moveTab(int from, int to);
void duplicateTab(int index);
private:
void setupTabBar();
void addTab(BrowserTab *tab, int index = -1);
BrowserTab *currentTab() const;
BrowserTab *tabAt(int index) const;
void createTrayIcon();
void removeTrayIcon();
void syncTabState(BrowserTab *tab);
Ui::MainWindow *ui = nullptr;
Core::Application *m_application = nullptr;
Core::Settings *m_settings = nullptr;
Browser::WebBridge *m_webBridge = nullptr;
QMenu *m_backMenu = nullptr;
QMenu *m_forwardMenu = nullptr;
QxtGlobalShortcut *m_globalShortcut = nullptr;
QTabBar *m_tabBar = nullptr;
friend class SidebarViewProvider;
SidebarViewProvider *m_sbViewProvider = nullptr;
QSystemTrayIcon *m_trayIcon = nullptr;
};
} // namespace WidgetUi
} // namespace Zeal
#endif // ZEAL_WIDGETUI_MAINWINDOW_H
| 2,177
|
C++
|
.h
| 72
| 26.930556
| 75
| 0.751325
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,995
|
settingsdialog.h
|
zealdocs_zeal/src/libs/ui/settingsdialog.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_WIDGETUI_SETTINGSDIALOG_H
#define ZEAL_WIDGETUI_SETTINGSDIALOG_H
#include <QDialog>
namespace Zeal {
namespace WidgetUi {
namespace Ui {
class SettingsDialog;
} // namespace Ui
class SettingsDialog : public QDialog
{
Q_OBJECT
public:
explicit SettingsDialog(QWidget *parent = nullptr);
~SettingsDialog() override;
public slots:
void chooseCustomCssFile();
void chooseDocsetStoragePath();
private:
void loadSettings();
void saveSettings();
private:
Ui::SettingsDialog *ui = nullptr;
friend class Ui::SettingsDialog;
};
} // namespace WidgetUi
} // namespace Zeal
#endif // ZEAL_WIDGETUI_SETTINGSDIALOG_H
| 810
|
C++
|
.h
| 30
| 24.433333
| 61
| 0.760728
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,996
|
searchsidebar.h
|
zealdocs_zeal/src/libs/ui/searchsidebar.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_WIDGETUI_SEARCHSIDEBAR_H
#define ZEAL_WIDGETUI_SEARCHSIDEBAR_H
#include <sidebar/view.h>
#include <QModelIndexList>
#include <QWidget>
class QItemSelection;
class QSplitter;
class QListView;
class QTimer;
class QTreeView;
namespace Zeal {
namespace Registry {
class SearchModel;
class SearchQuery;
} // namespace Registry
namespace WidgetUi {
class SearchEdit;
class SearchSidebar final : public Sidebar::View
{
Q_OBJECT
Q_DISABLE_COPY(SearchSidebar)
public:
explicit SearchSidebar(QWidget *parent = nullptr);
SearchSidebar *clone(QWidget *parent = nullptr) const;
Registry::SearchModel *pageTocModel() const;
signals:
void activated();
void navigationRequested(const QUrl &url);
public slots:
void focusSearchEdit(bool clear = false);
void search(const Registry::SearchQuery &query);
private slots:
void navigateToIndex(const QModelIndex &index);
void navigateToIndexAndActivate(const QModelIndex &index);
void navigateToSelectionWithDelay(const QItemSelection &selection);
void setupSearchBoxCompletions();
protected:
bool eventFilter(QObject *object, QEvent *event) override;
void showEvent(QShowEvent *event) override;
private:
explicit SearchSidebar(const SearchSidebar *other, QWidget *parent = nullptr);
void setTreeViewModel(QAbstractItemModel *model, bool isRootDecorated);
SearchEdit *m_searchEdit = nullptr;
bool m_pendingSearchEditFocus = false;
// Index and search results tree view state.
QTreeView *m_treeView = nullptr;
QModelIndexList m_expandedIndexList;
int m_pendingVerticalPosition = 0;
Registry::SearchModel *m_searchModel = nullptr;
// TOC list view state.
QListView *m_pageTocView = nullptr;
Registry::SearchModel *m_pageTocModel = nullptr;
QSplitter *m_splitter = nullptr;
QTimer *m_delayedNavigationTimer = nullptr;
};
} // namespace WidgetUi
} // namespace Zeal
#endif // ZEAL_WIDGETUI_SEARCHSIDEBAR_H
| 2,086
|
C++
|
.h
| 60
| 31.483333
| 82
| 0.774564
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,997
|
searchedit.h
|
zealdocs_zeal/src/libs/ui/widgets/searchedit.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_WIDGETUI_SEARCHEDIT_H
#define ZEAL_WIDGETUI_SEARCHEDIT_H
#include <QLineEdit>
class QCompleter;
class QEvent;
class QLabel;
namespace Zeal {
namespace WidgetUi {
class SearchEdit : public QLineEdit
{
Q_OBJECT
public:
explicit SearchEdit(QWidget *parent = nullptr);
void clearQuery();
void selectQuery();
void setCompletions(const QStringList &completions);
protected:
bool event(QEvent *event) override;
void focusInEvent(QFocusEvent *event) override;
private slots:
void showCompletions(const QString &text);
private:
QString currentCompletion(const QString &text) const;
int queryStart() const;
QCompleter *m_prefixCompleter = nullptr;
QLabel *m_completionLabel = nullptr;
};
} // namespace WidgetUi
} // namespace Zeal
#endif // ZEAL_WIDGETUI_SEARCHEDIT_H
| 979
|
C++
|
.h
| 33
| 26.848485
| 61
| 0.764454
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,998
|
shortcutedit.h
|
zealdocs_zeal/src/libs/ui/widgets/shortcutedit.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_WIDGETUI_SHORTCUTEDIT_H
#define ZEAL_WIDGETUI_SHORTCUTEDIT_H
#include <QLineEdit>
namespace Zeal {
namespace WidgetUi {
class ShortcutEdit : public QLineEdit
{
Q_OBJECT
public:
explicit ShortcutEdit(QWidget *parent = nullptr);
explicit ShortcutEdit(const QString &text, QWidget *parent = nullptr);
bool event(QEvent *event) override;
QKeySequence keySequence() const;
void setKeySequence(const QKeySequence &keySequence);
private:
int translateModifiers(Qt::KeyboardModifiers state, const QString &text);
int m_key = 0;
};
} // namespace WidgetUi
} // namespace Zeal
#endif // ZEAL_WIDGETUI_SHORTCUTEDIT_H
| 808
|
C++
|
.h
| 24
| 30.916667
| 77
| 0.763566
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
11,999
|
layouthelper.h
|
zealdocs_zeal/src/libs/ui/widgets/layouthelper.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_WIDGETUI_LAYOUTHELPER_H
#define ZEAL_WIDGETUI_LAYOUTHELPER_H
#include <QLayout>
namespace Zeal {
namespace WidgetUi {
namespace LayoutHelper {
template<class Layout>
Layout *createBorderlessLayout()
{
static_assert(std::is_base_of<QLayout, Layout>::value, "Layout must derive from QLayout");
auto layout = new Layout();
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
return layout;
}
} // namespace LayoutHelper
} // namespace WidgetUi
} // namespace Zeal
#endif // ZEAL_WIDGETUI_LAYOUTHELPER_H
| 659
|
C++
|
.h
| 21
| 29.047619
| 94
| 0.752381
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,000
|
toolbarframe.h
|
zealdocs_zeal/src/libs/ui/widgets/toolbarframe.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_WIDGETUI_TOOLBARFRAME_H
#define ZEAL_WIDGETUI_TOOLBARFRAME_H
#include <QWidget>
namespace Zeal {
namespace WidgetUi {
class ToolBarFrame : public QWidget
{
Q_OBJECT
public:
explicit ToolBarFrame(QWidget *parent = nullptr);
private:
void paintEvent(QPaintEvent *event) override;
};
} // namespace WidgetUi
} // namespace Zeal
#endif // ZEAL_WIDGETUI_TOOLBARFRAME_H
| 503
|
C++
|
.h
| 18
| 25.888889
| 61
| 0.771967
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,001
|
qxtglobalshortcut_p.h
|
zealdocs_zeal/src/libs/ui/qxtglobalshortcut/qxtglobalshortcut_p.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
/****************************************************************************
// Copyright (C) 2006 - 2011, the LibQxt project.
** See the Qxt AUTHORS file for a list of authors and copyright holders.
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the LibQxt project nor the
** names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
** <http://libqxt.org> <foundation@libqxt.org>
*****************************************************************************/
#ifndef QXTGLOBALSHORTCUT_P_H
#define QXTGLOBALSHORTCUT_P_H
#include <QAbstractNativeEventFilter>
#include <QHash>
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
#define NativeEventFilterResult long
#else
#define NativeEventFilterResult qintptr
#endif
class QKeySequence;
class QxtGlobalShortcut;
class QxtGlobalShortcutPrivate : public QAbstractNativeEventFilter
{
QxtGlobalShortcut *q_ptr = nullptr;
Q_DECLARE_PUBLIC(QxtGlobalShortcut)
public:
QxtGlobalShortcutPrivate(QxtGlobalShortcut *qq);
~QxtGlobalShortcutPrivate() override;
bool enabled = true;
Qt::Key key = Qt::Key(0);
Qt::KeyboardModifiers mods = Qt::NoModifier;
#ifndef Q_OS_MACOS
static int ref;
#endif // Q_OS_MACOS
bool setShortcut(const QKeySequence &shortcut);
bool unsetShortcut();
bool nativeEventFilter(const QByteArray &eventType, void *message, NativeEventFilterResult *result) override;
static bool isSupported();
static bool activateShortcut(quint32 nativeKey, quint32 nativeMods);
private:
static quint32 nativeKeycode(Qt::Key keycode);
static quint32 nativeModifiers(Qt::KeyboardModifiers modifiers);
static bool registerShortcut(quint32 nativeKey, quint32 nativeMods);
static bool unregisterShortcut(quint32 nativeKey, quint32 nativeMods);
static QHash<QPair<quint32, quint32>, QxtGlobalShortcut *> shortcuts;
};
#endif // QXTGLOBALSHORTCUT_P_H
| 3,377
|
C++
|
.h
| 68
| 47.382353
| 113
| 0.73983
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,002
|
qxtglobalshortcut.h
|
zealdocs_zeal/src/libs/ui/qxtglobalshortcut/qxtglobalshortcut.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
/****************************************************************************
// Copyright (C) 2006 - 2011, the LibQxt project.
** See the Qxt AUTHORS file for a list of authors and copyright holders.
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the LibQxt project nor the
** names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
** <http://libqxt.org> <foundation@libqxt.org>
*****************************************************************************/
#ifndef QXTGLOBALSHORTCUT_H
#define QXTGLOBALSHORTCUT_H
#include <QKeySequence>
#include <QObject>
class QxtGlobalShortcutPrivate;
class QxtGlobalShortcut : public QObject
{
Q_OBJECT
QxtGlobalShortcutPrivate *d_ptr = nullptr;
Q_DECLARE_PRIVATE(QxtGlobalShortcut)
Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled)
Q_PROPERTY(QKeySequence shortcut READ shortcut WRITE setShortcut)
public:
explicit QxtGlobalShortcut(QObject *parent = nullptr);
explicit QxtGlobalShortcut(const QKeySequence &shortcut, QObject *parent = nullptr);
~QxtGlobalShortcut() override;
QKeySequence shortcut() const;
bool setShortcut(const QKeySequence &shortcut);
bool isEnabled() const;
static bool isSupported();
public slots:
void setEnabled(bool enabled);
signals:
void activated();
};
#endif // QXTGLOBALSHORTCUT_H
| 2,839
|
C++
|
.h
| 57
| 47.614035
| 88
| 0.727437
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,003
|
container.h
|
zealdocs_zeal/src/libs/sidebar/container.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_SIDEBAR_CONTAINER_H
#define ZEAL_SIDEBAR_CONTAINER_H
#include <QWidget>
class QSplitter;
namespace Zeal {
namespace Sidebar {
class View;
// TODO: Implement view groups (alt. naming: tabs, pages) (move splitter into a group?).
class Container : public QWidget
{
Q_OBJECT
Q_DISABLE_COPY(Container)
public:
explicit Container(QWidget *parent = nullptr);
~Container() override;
void addView(View *view);
private:
QSplitter *m_splitter = nullptr;
QList<View *> m_views;
};
} // namespace Sidebar
} // namespace Zeal
#endif // ZEAL_SIDEBAR_CONTAINER_H
| 706
|
C++
|
.h
| 25
| 25.68
| 88
| 0.737313
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,004
|
viewprovider.h
|
zealdocs_zeal/src/libs/sidebar/viewprovider.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_SIDEBAR_VIEWPROVIDER_H
#define ZEAL_SIDEBAR_VIEWPROVIDER_H
#include <QObject>
namespace Zeal {
namespace Sidebar {
class View;
class ViewProvider : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(ViewProvider)
public:
explicit ViewProvider(QObject *parent = nullptr);
virtual View *view(const QString &id = QString()) const = 0;
signals:
void viewChanged();
};
} // namespace Sidebar
} // namespace Zeal
#endif // ZEAL_SIDEBAR_VIEWPROVIDER_H
| 584
|
C++
|
.h
| 21
| 25.428571
| 64
| 0.750903
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,005
|
view.h
|
zealdocs_zeal/src/libs/sidebar/view.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_SIDEBAR_VIEW_H
#define ZEAL_SIDEBAR_VIEW_H
#include <QWidget>
namespace Zeal {
namespace Sidebar {
class View : public QWidget
{
Q_OBJECT
Q_DISABLE_COPY(View)
public:
explicit View(QWidget *parent = nullptr);
};
} // namespace Sidebar
} // namespace Zeal
#endif // ZEAL_SIDEBAR_VIEW_H
| 423
|
C++
|
.h
| 17
| 22.823529
| 61
| 0.7375
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,006
|
proxyview.h
|
zealdocs_zeal/src/libs/sidebar/proxyview.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_SIDEBAR_PROXYVIEW_H
#define ZEAL_SIDEBAR_PROXYVIEW_H
#include "view.h"
namespace Zeal {
namespace Sidebar {
class ViewProvider;
class ProxyView final : public View
{
Q_OBJECT
Q_DISABLE_COPY(ProxyView)
public:
explicit ProxyView(ViewProvider *provider, QString id = QString(), QWidget *parent = nullptr);
~ProxyView() override;
private:
void clearCurrentView();
ViewProvider *m_viewProvider = nullptr;
QString m_viewId;
View *m_view = nullptr;
};
} // namespace Sidebar
} // namespace Zeal
#endif // ZEAL_SIDEBAR_PROXYVIEW_H
| 686
|
C++
|
.h
| 24
| 25.833333
| 98
| 0.742331
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,007
|
webview.h
|
zealdocs_zeal/src/libs/browser/webview.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_BROWSER_WEBVIEW_H
#define ZEAL_BROWSER_WEBVIEW_H
#include <QWebEngineView>
namespace Zeal {
namespace Browser {
class WebView final : public QWebEngineView
{
Q_OBJECT
Q_DISABLE_COPY(WebView)
public:
explicit WebView(QWidget *parent = nullptr);
int zoomLevel() const;
void setZoomLevel(int level);
bool eventFilter(QObject *watched, QEvent *event) override;
static const QVector<int> &availableZoomLevels();
static int defaultZoomLevel();
public slots:
void zoomIn();
void zoomOut();
void resetZoom();
signals:
void zoomLevelChanged();
protected:
QWebEngineView *createWindow(QWebEnginePage::WebWindowType type) override;
void contextMenuEvent(QContextMenuEvent *event) override;
private:
bool handleMouseReleaseEvent(QMouseEvent *event);
bool handleWheelEvent(QWheelEvent *event);
QMenu *m_contextMenu = nullptr;
QUrl m_clickedLink;
int m_zoomLevel = 0;
};
} // namespace Browser
} // namespace Zeal
#endif // ZEAL_BROWSER_WEBVIEW_H
| 1,183
|
C++
|
.h
| 38
| 27.763158
| 78
| 0.752431
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,008
|
webpage.h
|
zealdocs_zeal/src/libs/browser/webpage.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2019 Kay Gawlik
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_BROWSER_WEBPAGE_H
#define ZEAL_BROWSER_WEBPAGE_H
#include <QWebEnginePage>
namespace Zeal {
namespace Browser {
class WebPage final : public QWebEnginePage
{
Q_OBJECT
Q_DISABLE_COPY(WebPage)
public:
explicit WebPage(QObject *parent = nullptr);
protected:
bool acceptNavigationRequest(const QUrl &requestUrl, NavigationType type, bool isMainFrame) override;
void javaScriptConsoleMessage(QWebEnginePage::JavaScriptConsoleMessageLevel level, const QString &message, int lineNumber, const QString &sourceId) override;
};
} // namespace Browser
} // namespace Zeal
#endif // ZEAL_BROWSER_WEBPAGE_H
| 774
|
C++
|
.h
| 21
| 34.571429
| 161
| 0.786863
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,009
|
webbridge.h
|
zealdocs_zeal/src/libs/browser/webbridge.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_BROWSER_WEBBRIDGE_H
#define ZEAL_BROWSER_WEBBRIDGE_H
#include <QObject>
namespace Zeal {
namespace Browser {
class WebBridge final : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(WebBridge)
Q_PROPERTY(QString AppVersion READ appVersion CONSTANT)
public:
explicit WebBridge(QObject *parent = nullptr);
signals:
void actionTriggered(const QString &action);
public slots:
Q_INVOKABLE void openShortUrl(const QString &key);
Q_INVOKABLE void triggerAction(const QString &action);
private:
QString appVersion() const;
};
} // namespace Browser
} // namespace Zeal
#endif // ZEAL_BROWSER_WEBBRIDGE_H
| 749
|
C++
|
.h
| 25
| 27.32
| 61
| 0.766434
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,010
|
settings.h
|
zealdocs_zeal/src/libs/browser/settings.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_BROWSER_SETTINGS_H
#define ZEAL_BROWSER_SETTINGS_H
#include <QObject>
class QWebEngineProfile;
namespace Zeal {
namespace Core {
class Settings;
}
namespace Browser {
class Settings final : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(Settings)
public:
explicit Settings(Core::Settings *appSettings, QObject *parent = nullptr);
static QWebEngineProfile *defaultProfile();
private slots:
void applySettings();
private:
void setCustomStyleSheet(const QString &name, const QString &cssUrl);
Core::Settings *m_appSettings = nullptr;
static QWebEngineProfile *m_webProfile;
};
} // namespace Browser
} // namespace Zeal
#endif // ZEAL_BROWSER_SETTINGS_H
| 810
|
C++
|
.h
| 28
| 26.321429
| 78
| 0.76723
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,011
|
searchtoolbar.h
|
zealdocs_zeal/src/libs/browser/searchtoolbar.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_BROWSER_SEARCHTOOLBAR_H
#define ZEAL_BROWSER_SEARCHTOOLBAR_H
#include <QWidget>
class QLineEdit;
class QToolButton;
class QWebEngineView;
namespace Zeal {
namespace Browser {
class SearchToolBar final : public QWidget
{
Q_OBJECT
Q_DISABLE_COPY(SearchToolBar)
public:
explicit SearchToolBar(QWebEngineView *webView, QWidget *parent = nullptr);
void setText(const QString &text);
void activate();
bool eventFilter(QObject *object, QEvent *event) override;
protected:
void hideEvent(QHideEvent *event) override;
void showEvent(QShowEvent *event) override;
void keyPressEvent(QKeyEvent *event) override;
private:
void findNext();
void findPrevious();
void hideHighlight();
void updateHighlight();
QLineEdit *m_lineEdit = nullptr;
QToolButton *m_findNextButton = nullptr;
QToolButton *m_findPreviousButton = nullptr;
QToolButton *m_highlightAllButton = nullptr;
QToolButton *m_matchCaseButton = nullptr;
QWebEngineView *m_webView = nullptr;
};
} // namespace Browser
} // namespace Zeal
#endif // ZEAL_BROWSER_SEARCHTOOLBAR_H
| 1,232
|
C++
|
.h
| 38
| 29.026316
| 79
| 0.759966
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,012
|
webcontrol.h
|
zealdocs_zeal/src/libs/browser/webcontrol.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_BROWSER_WEBCONTROL_H
#define ZEAL_BROWSER_WEBCONTROL_H
#include <QWidget>
class QWebEngineHistory;
namespace Zeal {
namespace Browser {
class SearchToolBar;
class WebView;
class WebControl final : public QWidget
{
Q_OBJECT
Q_DISABLE_COPY(WebControl)
public:
explicit WebControl(QWidget *parent = nullptr);
void focus();
void load(const QUrl &url);
bool canGoBack() const;
bool canGoForward() const;
QString title() const;
QUrl url() const;
QWebEngineHistory *history() const;
void restoreHistory(const QByteArray &array);
QByteArray saveHistory() const;
int zoomLevel() const;
void setZoomLevel(int level);
void setJavaScriptEnabled(bool enabled);
void setWebBridgeObject(const QString &name, QObject *object);
signals:
void titleChanged(const QString &title);
void urlChanged(const QUrl &url);
public slots:
void activateSearchBar();
void back();
void forward();
void zoomIn();
void zoomOut();
void resetZoom();
protected:
void keyPressEvent(QKeyEvent *event) override;
private:
friend class WebView;
WebView *m_webView = nullptr;
SearchToolBar *m_searchToolBar = nullptr;
};
} // namespace Browser
} // namespace Zeal
#endif // ZEAL_BROWSER_WEBCONTROL_H
| 1,447
|
C++
|
.h
| 50
| 25.32
| 66
| 0.735849
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,013
|
urlrequestinterceptor.h
|
zealdocs_zeal/src/libs/browser/urlrequestinterceptor.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2019 Kay Gawlik
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_BROWSER_URLREQUESTINTERCEPTOR_H
#define ZEAL_BROWSER_URLREQUESTINTERCEPTOR_H
#include <QWebEngineUrlRequestInterceptor>
namespace Zeal {
namespace Browser {
class UrlRequestInterceptor final : public QWebEngineUrlRequestInterceptor
{
Q_OBJECT
Q_DISABLE_COPY(UrlRequestInterceptor)
public:
UrlRequestInterceptor(QObject *parent = nullptr);
void interceptRequest(QWebEngineUrlRequestInfo &info) override;
private:
void blockRequest(QWebEngineUrlRequestInfo &info);
};
} // namespace Browser
} // namespace Zeal
#endif // ZEAL_BROWSER_URLREQUESTINTERCEPTOR_H
| 736
|
C++
|
.h
| 21
| 32.761905
| 74
| 0.80791
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,014
|
cancellationtoken.h
|
zealdocs_zeal/src/libs/registry/cancellationtoken.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2015 Artur Spychaj
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_REGISTRY_CANCELLATIONTOKEN_H
#define ZEAL_REGISTRY_CANCELLATIONTOKEN_H
#include <atomic>
namespace Zeal {
namespace Registry {
/// Token that stores whether cancel was called on it.
/// In async code can be used to check if another thread called cancel.
class CancellationToken
{
public:
inline bool isCanceled() const { return m_canceled; }
inline void cancel() { m_canceled = true; }
inline void reset() { m_canceled = false; }
private:
std::atomic_bool m_canceled;
};
} // namespace Registry
} // namespace Zeal
#endif // ZEAL_REGISTRY_CANCELLATIONTOKEN_H
| 739
|
C++
|
.h
| 22
| 31.5
| 71
| 0.748942
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,015
|
searchmodel.h
|
zealdocs_zeal/src/libs/registry/searchmodel.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_REGISTRY_SEARCHMODEL_H
#define ZEAL_REGISTRY_SEARCHMODEL_H
#include "searchresult.h"
#include <QAbstractListModel>
namespace Zeal {
namespace Registry {
class SearchModel final : public QAbstractListModel
{
Q_OBJECT
Q_DISABLE_COPY(SearchModel)
public:
explicit SearchModel(QObject *parent = nullptr);
SearchModel *clone(QObject *parent = nullptr);
bool isEmpty() const;
QVariant data(const QModelIndex &index, int role) const override;
QModelIndex index(int row, int column, const QModelIndex &parent) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override;
void removeSearchResultWithName(const QString &name);
public slots:
void setResults(const QList<SearchResult> &results = QList<SearchResult>());
signals:
void updated();
private:
QList<SearchResult> m_dataList;
};
} // namespace Registry
} // namespace Zeal
#endif // ZEAL_REGISTRY_SEARCHMODEL_H
| 1,199
|
C++
|
.h
| 32
| 34.46875
| 92
| 0.764502
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,016
|
docsetregistry.h
|
zealdocs_zeal/src/libs/registry/docsetregistry.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_REGISTRY_DOCSETREGISTRY_H
#define ZEAL_REGISTRY_DOCSETREGISTRY_H
#include "cancellationtoken.h"
#include "searchresult.h"
#include <QMap>
#include <QObject>
class QAbstractItemModel;
class QThread;
namespace Zeal {
namespace Registry {
class Docset;
class DocsetRegistry final : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(DocsetRegistry)
public:
explicit DocsetRegistry(QObject *parent = nullptr);
~DocsetRegistry() override;
QAbstractItemModel *model() const;
QString storagePath() const;
void setStoragePath(const QString &path);
bool isFuzzySearchEnabled() const;
void setFuzzySearchEnabled(bool enabled);
int count() const;
bool contains(const QString &name) const;
QStringList names() const;
void loadDocset(const QString &path);
void unloadDocset(const QString &name);
void unloadAllDocsets();
Docset *docset(const QString &name) const;
Docset *docset(int index) const;
Docset *docsetForUrl(const QUrl &url);
QList<Docset *> docsets() const;
void search(const QString &query);
const QList<SearchResult> &queryResults();
signals:
void docsetLoaded(const QString &name);
void docsetAboutToBeUnloaded(const QString &name);
void docsetUnloaded(const QString &name);
void searchCompleted(const QList<SearchResult> &results);
private slots:
void _runQuery(const QString &query);
private:
void addDocsetsFromFolder(const QString &path);
QAbstractItemModel *m_model = nullptr;
QString m_storagePath;
bool m_isFuzzySearchEnabled = false;
QThread *m_thread = nullptr;
QMap<QString, Docset *> m_docsets;
CancellationToken m_cancellationToken;
};
} // namespace Registry
} // namespace Zeal
#endif // ZEAL_REGISTRY_DOCSETREGISTRY_H
| 1,939
|
C++
|
.h
| 57
| 30.298246
| 61
| 0.754169
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,017
|
docsetmetadata.h
|
zealdocs_zeal/src/libs/registry/docsetmetadata.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_REGISTRY_DOCSETMETADATA_H
#define ZEAL_REGISTRY_DOCSETMETADATA_H
#include <QIcon>
#include <QJsonObject>
#include <QStringList>
#include <QUrl>
namespace Zeal {
namespace Registry {
class DocsetMetadata
{
public:
explicit DocsetMetadata() = default;
explicit DocsetMetadata(const QJsonObject &jsonObject);
void save(const QString &path, const QString &version);
QString name() const;
QString title() const;
QStringList aliases() const;
QStringList versions() const;
QString latestVersion() const;
int revision() const;
QIcon icon() const;
QUrl feedUrl() const;
QUrl url() const;
QList<QUrl> urls() const;
static DocsetMetadata fromDashFeed(const QUrl &feedUrl, const QByteArray &data);
private:
QString m_name;
QString m_title;
QStringList m_aliases;
QStringList m_versions;
int m_revision = 0;
QByteArray m_rawIcon;
QByteArray m_rawIcon2x;
QIcon m_icon;
QJsonObject m_extra;
QUrl m_feedUrl;
QList<QUrl> m_urls;
};
} // namespace Registry
} // namespace Zeal
#endif // ZEAL_REGISTRY_DOCSETMETADATA_H
| 1,274
|
C++
|
.h
| 44
| 25.363636
| 84
| 0.731086
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,018
|
docset.h
|
zealdocs_zeal/src/libs/registry/docset.h
|
// Copyright (C) Oleg Shparber, et al. <https://zealdocs.org>
// Copyright (C) 2013-2014 Jerzy Kozera
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef ZEAL_REGISTRY_DOCSET_H
#define ZEAL_REGISTRY_DOCSET_H
#include <QIcon>
#include <QMap>
#include <QMetaObject>
#include <QMultiMap>
#include <QUrl>
namespace Zeal {
namespace Util {
class SQLiteDatabase;
}
namespace Registry {
class CancellationToken;
struct SearchResult;
class Docset final
{
Q_DISABLE_COPY(Docset)
public:
explicit Docset(QString path);
virtual ~Docset();
bool isValid() const;
QString name() const;
QString title() const;
QStringList keywords() const;
QString version() const;
int revision() const;
QString feedUrl() const;
QString path() const;
QString documentPath() const;
QIcon icon() const;
QIcon symbolTypeIcon(const QString &symbolType) const;
QUrl indexFileUrl() const;
QMap<QString, int> symbolCounts() const;
int symbolCount(const QString &symbolType) const;
const QMultiMap<QString, QUrl> &symbols(const QString &symbolType) const;
QList<SearchResult> search(const QString &query, const CancellationToken &token) const;
QList<SearchResult> relatedLinks(const QUrl &url) const;
// FIXME: This a temporary solution to create URL on demand.
QUrl searchResultUrl(const SearchResult &result) const;
// FIXME: This is an ugly workaround before we have a proper docset sources implementation
bool hasUpdate = false;
QUrl baseUrl() const;
void setBaseUrl(const QUrl &baseUrl);
bool isFuzzySearchEnabled() const;
void setFuzzySearchEnabled(bool enabled);
bool isJavaScriptEnabled() const;
private:
enum class Type {
Invalid,
Dash,
ZDash
};
void loadMetadata();
void countSymbols();
void loadSymbols(const QString &symbolType) const;
void loadSymbols(const QString &symbolType, const QString &symbolString) const;
void createIndex();
void createView();
QUrl createPageUrl(const QString &path, const QString &fragment = QString()) const;
static QString parseSymbolType(const QString &str);
QString m_name;
QString m_title;
QStringList m_keywords;
QString m_version;
int m_revision = 0;
QString m_feedUrl;
Docset::Type m_type = Type::Invalid;
QString m_path;
QIcon m_icon;
QUrl m_indexFileUrl;
QString m_indexFilePath;
QMultiMap<QString, QString> m_symbolStrings;
QMap<QString, int> m_symbolCounts;
mutable QMap<QString, QMultiMap<QString, QUrl>> m_symbols;
Util::SQLiteDatabase *m_db = nullptr;
bool m_isFuzzySearchEnabled = false;
bool m_isJavaScriptEnabled = false;
QUrl m_baseUrl;
};
} // namespace Registry
} // namespace Zeal
#endif // ZEAL_REGISTRY_DOCSET_H
| 2,819
|
C++
|
.h
| 85
| 28.858824
| 94
| 0.72902
|
zealdocs/zeal
| 11,372
| 778
| 177
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.