aboutsummaryrefslogtreecommitdiff
path: root/src/mainwindow/mainwindow.cpp
blob: 1f81b86cd322b610b020c2ff47d93a2fcd0fce31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
 * This file is part of smolbote. It's copyrighted by the contributors recorded
 * in the version control history of the file, available from its original
 * location: https://neueland.iserlohn-fortress.net/gitea/aqua/smolbote
 *
 * SPDX-License-Identifier: GPL-3.0
 */

#include "mainwindow.h"
#include "addressbar/addressbar.h"
#include "browser.h"
#include "session.h"
#include "subwindow/subwindow.h"
#include "ui_mainwindow.h"
#include "webengine/webview.h"
#include "widgets/dockwidget.h"
#include "widgets/navigationbar.h"
#include "widgets/searchform.h"
#include <QApplication>
#include <QCloseEvent>
#include <QFileDialog>
#include <QJsonArray>
#include <QJsonObject>
#include <QLineEdit>
#include <QMdiArea>
#include <QMdiSubWindow>
#include <QMenuBar>
#include <QMessageBox>
#include <QPrintDialog>
#include <QPrinter>
#include <QPrinterInfo>
#include <QShortcut>
#include <QStatusBar>
#include <QToolBar>
#include <QUrl>
#include <QVBoxLayout>
#include <configuration/configuration.h>
#include <web/profilemanager.h>
#include <web/webprofile.h>
#ifdef PLASMA_BLUR
#include <KWindowEffects>
#endif

inline QDialog *createDevToolsDialog(QWebEnginePage *page)
{
    Q_CHECK_PTR(page);

    auto *popup = new QDialog(nullptr);
    popup->setWindowTitle(QObject::tr("Developer Tools"));
    popup->setAttribute(Qt::WA_DeleteOnClose, true);
    popup->resize(800, 600);

    auto *view = new QWebEngineView(popup);
    auto *devPage = new QWebEnginePage(view);

    view->setPage(devPage);
    page->setDevToolsPage(devPage);

    QObject::connect(popup, &QDialog::destroyed, [page]() {
        page->setDevToolsPage(nullptr);
    });

    auto *l = new QVBoxLayout(popup);
    l->setContentsMargins(0, 0, 0, 0);
    l->addWidget(view);

    return popup;
}

MainWindow::MainWindow(const std::unique_ptr<Configuration> &config, QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , mdiArea(new QMdiArea(this))
{
    Q_ASSERT(config);

    ui->setupUi(this);

#ifdef PLASMA_BLUR
    setAttribute(Qt::WA_TranslucentBackground, true);
    KWindowEffects::enableBlurBehind(this->winId(), true);
#endif

    // create UI
    setWindowTitle(config->value<QString>("mainwindow.title").value());
    resize(config->value<int>("mainwindow.width").value(), config->value<int>("mainwindow.height").value());
    if(config->value<bool>("mainwindow.maximized").value()) {
        setWindowState(Qt::WindowMaximized);
    }
    show();

    // connect smolbote menu
    {
        connect(ui->actionNewSubwindow, &QAction::triggered, this, [this, &config]() {
            auto *profile = WebProfile::defaultProfile();
            auto *window = createSubWindow(config, profile);
            window->addTab(profile->newtab(), profile);
        });
        config->setShortcut(ui->actionNewSubwindow, "mainwindow.shortcuts.newGroup");

        connect(ui->actionNewWindow, &QAction::triggered, this, []() {
            auto *browser = qobject_cast<Browser *>(qApp);
            if(browser)
                browser->createWindow();
        });
        config->setShortcut(ui->actionNewWindow, "mainwindow.shortcuts.newWindow");

        connect(ui->actionAbout, &QAction::triggered, qobject_cast<Browser *>(qApp), &Browser::about);
        config->setShortcut(ui->actionAbout, "mainwindow.shortcuts.about");

        connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);

        connect(ui->actionQuit, &QAction::triggered, qApp, &QApplication::quit);
        config->setShortcut(ui->actionQuit, "mainwindow.shortcuts.quit");
    }

    // connect session menu
    {
        connect(ui->actionSaveSession, &QAction::triggered, this, [this]() {
            const QString filename = QFileDialog::getSaveFileName(this, tr("Save Session"), QDir::homePath(), tr("JSON (*.json)"));
            QFile output(filename);
            if(output.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {
                output.write(QJsonDocument(Session::window(this)).toJson());
                output.close();
            }
        });
        connect(ui->actionLoadSession, &QAction::triggered, this, [this]() {
            const QString filename = QFileDialog::getOpenFileName(this, tr("Load Session"), QDir::homePath(), tr("JSON (*.json)"));
            QFile json(filename);
            if(json.open(QIODevice::ReadOnly | QIODevice::Text)) {
                auto *browser = qobject_cast<Browser *>(qApp);
                auto doc = QJsonDocument::fromJson(json.readAll());
                browser->createSession(doc.object());
                json.close();
            }
        });
    }

    // connect window menu
    {
        connect(ui->actionTileSubwindows, &QAction::triggered, mdiArea, &QMdiArea::tileSubWindows);
        config->setShortcut(ui->actionTileSubwindows, "mainwindow.shortcuts.tileWindows");

        connect(ui->actionCascadeSubwindows, &QAction::triggered, mdiArea, &QMdiArea::cascadeSubWindows);
        config->setShortcut(ui->actionCascadeSubwindows, "mainwindow.shortcuts.cascadeWindows");
    }

    // connect page menu
    {
        connect(ui->actionBookmarkPage, &QAction::triggered, this, [this]() {
            if(currentView != nullptr)
                emit createBookmark(currentView->title(), currentView->url().toString());
        });
        connect(ui->actionSavePage, &QAction::triggered, this, [this]() {
            if(currentView != nullptr)
                currentView->triggerPageAction(QWebEnginePage::SavePage);
        });
        connect(ui->actionPrintPage, &QAction::triggered, this, [this]() {
            if(currentView != nullptr) {
                auto *printer = new QPrinter(QPrinterInfo::defaultPrinter());
                QPrintDialog dlg(printer, this);
                if(dlg.exec() == QDialog::Accepted) {
                    currentView->page()->print(printer, [printer](bool success) {
                        Q_UNUSED(success);
                        delete printer;
                    });
                }
            }
        });
        connect(ui->actionPrintPageToPdf, &QAction::triggered, this, [this]() {
            if(currentView != nullptr) {
                const QString path = QFileDialog::getSaveFileName(this, tr("Print to PDF"), QDir::homePath(), tr("PDF files (*.pdf)"));
                currentView->page()->printToPdf(path);
            }
        });

        connect(ui->actionDeveloperTools, &QAction::triggered, this, [this]() {
            if(currentView != nullptr)
                createDevToolsDialog(currentView->page())->show();
        });

        pageLoadProfileMenu = ui->menuPage->addMenu(tr("Load Profile"));
        connect(pageLoadProfileMenu, &QMenu::aboutToShow, this, &MainWindow::updatePageLoadProfileMenu);
    }

    // current subwindow shortcut
    {
        QAction *subwindowMenuAction = new QAction(this);
        QMainWindow::addAction(subwindowMenuAction);
        config->setShortcut(subwindowMenuAction, "subwindow.shortcuts.menu");
        connect(subwindowMenuAction, &QAction::triggered, this, [this]() {
            QMdiSubWindow *window = mdiArea->currentSubWindow();
            if(window) {
                // show the menu at the subwindow position
                // position has to be global, and mapped by the mdiArea (parentWidget() of the subwindow)
                const auto position = mdiArea->mapToGlobal(window->pos());
                window->systemMenu()->exec(position);
            }
        });
    }

    navigationToolBar = new NavigationBar(config->section("navigation"), this);
    navigationToolBar->setMovable(config->value<bool>("navigation.movable").value());
    addToolBar(Qt::TopToolBarArea, navigationToolBar);
    navigationToolBar->connectWebView(nullptr);

    addressBar = new AddressBar(config->section("addressbar"), this);
    navigationToolBar->addWidget(addressBar);

    mdiArea->setBackground(Qt::NoBrush);
    setCentralWidget(mdiArea);
    mdiArea->setFocus();

    // status bar
    searchBox = new SearchForm(this);
    statusBar()->addPermanentWidget(searchBox);
    searchBox->setVisible(false);

    // connect signlas
    connect(mdiArea, &QMdiArea::subWindowActivated, this, [this](QMdiSubWindow *window) {
        disconnect(viewChangedConnection);
        disconnect(searchBoxConnection);
        disconnect(statusBarConnection);
        ui->actionCurrentSubwindow->setMenu(nullptr);

        auto *w = qobject_cast<SubWindow *>(window);
        if(w == nullptr) {
            // no current subwindow, clear everything
            setView(nullptr);
            ui->actionCurrentSubwindow->setMenu(nullptr);
        } else {
            setView(w->currentView());
            ui->actionCurrentSubwindow->setMenu(w->systemMenu());
            viewChangedConnection = connect(w, &SubWindow::currentViewChanged, this, &MainWindow::setView);
            statusBarConnection = connect(w, &SubWindow::showStatusMessage, statusBar(), &QStatusBar::showMessage);
        }
    });

    // address bar
    connect(addressBar, &AddressBar::search, this, [this](const QString &term) {
        if(this->currentView) {
            currentView->search(term);
            currentView->setFocus();
        }
    });
    connect(addressBar, &AddressBar::load, this, [this](const QUrl &url) {
        if(this->currentView) {
            currentView->load(url);
            currentView->setFocus();
        }
    });

    connect(addressBar, &AddressBar::giveFocus, this, [this]() {
        if(this->currentView) {
            currentView->setFocus();
        }
    });

    // search box
    auto *searchAction = new QAction(this);
    config->setShortcut(searchAction, "mainwindow.shortcuts.search");
    connect(searchAction, &QAction::triggered, this, [=]() {
        /* QTBUG-18665
         * When focusing out of the search box and hiding it, the first
         * (or earlier?) subwindow gets activated for some reason.
         */
        if(searchBox->isVisible()) {
            auto *w = mdiArea->currentSubWindow();
            searchBox->hide();
            mdiArea->setActiveSubWindow(w);
        } else {
            searchBox->show();
        }
    });
    QMainWindow::addAction(searchAction);
}

MainWindow::~MainWindow()
{
    disconnect(viewChangedConnection);
    disconnect(searchBoxConnection);
    disconnect(statusBarConnection);

    disconnect(addressBar);
}

void MainWindow::addAction(ActionLocation where, QAction *action)
{
    switch(where) {
    case ToolsMenu:
        ui->menuTools->addAction(action);
        break;
    default:
        QMainWindow::addAction(action);
        break;
    }
}

void MainWindow::addDockWidget(Qt::DockWidgetArea area, QWidget *widget)
{
    QDockWidget *lastDock = nullptr;
    const auto docks = findChildren<QDockWidget *>();
    for(QDockWidget *dock : docks) {
        if(dockWidgetArea(dock) == area)
            lastDock = dock;
    }

    DockWidget *dock = new DockWidget(widget->windowTitle(), this);
    dock->setMinimumWidth(460);
    dock->setWidget(widget);

    if(lastDock == nullptr)
        QMainWindow::addDockWidget(area, dock);
    else
        tabifyDockWidget(lastDock, dock);
}

void MainWindow::removeDockWidget(QWidget *widget)
{
    const auto docks = this->findChildren<QDockWidget *>();
    for(QDockWidget *dock : docks) {
        if(dock->widget() == widget) {
            dock->widget()->setParent(nullptr);
            dock->close();
        }
    }
}

void MainWindow::createTab(const QUrl &url)
{
    auto *w = qobject_cast<SubWindow *>(mdiArea->currentSubWindow());
    if(w != nullptr) {
        w->addTab(url);
    }
}

const QVector<SubWindow *> MainWindow::subWindows() const
{
    QVector<SubWindow *> list;
    const auto subwindows = mdiArea->subWindowList();
    for(auto *w : subwindows) {
        auto *subwindow = qobject_cast<SubWindow *>(w);
        if(subwindow != nullptr)
            list.append(subwindow);
    }

    return list;
}

SubWindow *MainWindow::currentSubWindow() const
{
    return qobject_cast<SubWindow *>(mdiArea->currentSubWindow());
}

SubWindow *MainWindow::createSubWindow(const std::unique_ptr<Configuration> &config, WebProfile *profile)
{
    bool shouldMaximize = true;
    // if there is a current window, use its maximize state
    if(auto *currentWindow = qobject_cast<SubWindow *>(mdiArea->currentSubWindow()); currentWindow != nullptr) {
        shouldMaximize = currentWindow->isMaximized();
    }

    auto *w = new SubWindow(config, this);
    w->setProfile(profile);
    mdiArea->addSubWindow(w);
    if(shouldMaximize)
        w->showMaximized();
    else
        w->show();

    w->setFocus();
    return w;
}

void MainWindow::setView(WebView *view)
{
    if(currentView) {
        // disconnect old view
        disconnect(currentView, 0, addressBar, 0);
    }
    currentView = view;

    if(view) {
        connect(view, &WebView::urlChanged, addressBar, &AddressBar::setUrl);
        addressBar->setUrl(view->url());

        connect(view, &WebView::loadProgress, addressBar, &AddressBar::setProgress);
        addressBar->setProgress(100);

    } else {
        addressBar->setUrl(QUrl());
        addressBar->setProgress(100);
    }

    navigationToolBar->connectWebView(view);
    searchBox->setView(view);
}

void MainWindow::updatePageLoadProfileMenu()
{
    Q_CHECK_PTR(pageLoadProfileMenu);
    pageLoadProfileMenu->clear();

    if(currentView == nullptr)
        return;

    auto *profileManager = dynamic_cast<Browser *>(qApp)->getProfileManager();
    pageLoadProfileMenu->addActions(profileManager->createProfileMenu([this](WebProfile *profile) {
                                                      this->currentView->setProfile(profile);
                                                  },
                                                      this)
                                        ->actions());
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if(mdiArea->subWindowList().count() > 1) {
        int choice = QMessageBox::question(this, tr("Close multiple subwindows?"), tr("Do you want to close all subwindows?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
        if(choice == QMessageBox::No) {
            event->ignore();
            return;
        }
    }

    mdiArea->closeAllSubWindows();
    if(mdiArea->currentSubWindow())
        event->ignore();
    else
        event->accept();
}