aboutsummaryrefslogtreecommitdiff
path: root/src/main.cpp
blob: 4d4fa8d8d4eb48fb65e219e8f7835dd7e4dae76a (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
/*
 * 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 "browser.h"
#include "builtins.h"
#include "conf.hpp"
#include "configuration.h"
#include "crashhandler.h"
#include "session/session.h"
#include "session/sessiondialog.h"
#include "util.h"
#include "version.h"
#include <QFile>
#include <QPluginLoader>
#include <QStandardPaths>
#include <args.hxx>
#include <iostream>
#include <memory>
#include <plugininterface.h>
#include <pluginloader.h>
#include <spdlog/spdlog.h>

typedef std::function<void(const std::string &, std::vector<std::string>::const_iterator, std::vector<std::string>::const_iterator)> subcommand_func;
typedef std::unordered_map<std::string, subcommand_func> command_map;

// a helper function to join the keys of a command_map into a string
inline std::string join_keys(const command_map &map, const std::string sep = ", ")
{
    std::vector<std::string> keys(map.size());
    std::transform(map.begin(), map.end(), keys.begin(), [](auto pair) { return pair.first; });
    std::sort(keys.begin(), keys.end());

    std::string k;
    std::for_each(keys.begin(), keys.end() - 1, [&k, &sep](const std::string &piece) { k += piece + sep; });
    k += keys.back();

    return k;
}

#if defined(CONFIG_USEPLASMA) && !defined(PLASMA)
#error "You have enabled Plasma integration, but Frameworks was not found."
#endif

#if defined(CONFIG_USEBREAKPAD) && !defined(BREAKPAD)
#error "You have enabled Breakpad integration, but Breakpad was not found."
#endif

int main(int argc, char **argv)
{
    // change log pattern
    spdlog::set_pattern("[%^%l%$] [%P:%t] %v");
#ifdef QT_DEBUG
    spdlog::set_level(spdlog::level::debug); // Set global log level to debug
#endif

    const std::vector<std::string> args(argv + 1, argv + argc);
    args::ArgumentParser parser("smolbote: yet another no-frills browser", "For more information on usage, refer to the manual page.");
    parser.Prog(argv[0]);

    args::HelpFlag cmd_help(parser, "help", "Display this help message.", { 'h', "help" });
    args::Flag cmd_version(parser, "version", "Display version information.", { 'v', "version" });
    args::Flag cmd_build(parser, "build", "Display build commit.", { 'b', "build" });

    args::ValueFlag<std::string> cmd_config(parser, "config", "Set the configuration file.", { 'c', "config" });

    args::Flag cmd_noRemote(parser, "no-remote", "Do not accept or send remote commands.", { "no-remote" });

    args::Flag cmd_pickSession(parser, "pick-session", "Show all available sessions and select which one to open", { "pick-session" });
    args::ValueFlag<std::string> cmd_session(parser, "session", "Open the specified session.", { 's', "session" });

    args::PositionalList<std::string> cmd_args(parser, "URL(s)", "List of URLs to open");

    try {
        /*auto next = */ parser.ParseArgs(args);

        if(cmd_version)
            return builtins::version();
        if(cmd_build)
            return builtins::build();

    } catch(args::Help &e) {
        std::cout << parser;
        Q_UNUSED(e);
        //std::cout << "Available subcommands: " << command_keys << std::endl;
        return 0;

    } catch(args::Error &e) {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return -1;
    }

    // Disable Chromium's crash handler so breakpad can capture crashes instead.
    // This has to be done before QtWebEngine gets initialized.
    const auto chromiumFlags = qgetenv("QTWEBENGINE_CHROMIUM_FLAGS");
    if(!chromiumFlags.contains("disable-in-process-stack-traces")) {
        qputenv("QTWEBENGINE_CHROMIUM_FLAGS", chromiumFlags + " --disable-in-process-stack-traces");
    }

    // create and load configuration
    const std::string config_path = [&]() {
        std::string path;
        if(cmd_config)
            path = args::get(cmd_config);
        else
            path = std::string(CONFIG_POI_CFG_PATH);

        if(path.front() == '~')
            path.replace(0, 1, QStandardPaths::writableLocation(QStandardPaths::HomeLocation).toStdString());

        return path;
    }();
    spdlog::debug("Opening config file {}", config_path);
    init_conf(config_path);

    QVector<QPluginLoader *> plugins;
    CommandHash_t pluginCommands;

    // Load plugins
    [&]() {
        Configuration conf;
        spdlog::debug("plugins.path={}", conf.value<std::string>("plugins.path").value());
        for(const QString &path : Util::files(conf.value<QString>("plugins.path").value(), { "*.so", "*.dll" })) {
            auto *loader = new PluginLoader(path);
            const bool loaded = loader->load();
            spdlog::info("{} plugin {}", loaded ? "Loaded" : "Failed to load", qUtf8Printable(path));

            if(loaded) {
                plugins.append(loader);
                auto *plugin = qobject_cast<PluginInterface *>(loader->instance());
                pluginCommands.unite(plugin->commands());
            } else {
                spdlog::warn("{}", qUtf8Printable(loader->errorString()));
                delete loader;
            }
        }
    }();

    // argc, argv, allowSecondary
    Browser app(argc, argv);
    // set this, otherwise the webview becomes black when using a stylesheet
    app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings, true);

#ifdef CONFIG_USEBREAKPAD
    const std::string crashpath = config->value<std::string>("browser.crash.path").value_or("/tmp");
    assert(!crashpath.empty());

    CrashHandler::BreakpadContext ctx;
    google_breakpad::MinidumpDescriptor descriptor(crashpath.c_str());

    const auto crashHandler = config->value<std::string>("browser.crash.handler");
    if(crashHandler) {
        const int length = crashHandler.value().length() + 1;
        ctx.handler = new char[length];
        crashHandler.value().copy(ctx.handler, length - 1);
        ctx.handler[length - 1] = '\0';
    }

    // minidump descriptor, filter callback, minidump callback, callback_context, install handler, server_fd
    google_breakpad::ExceptionHandler eh(descriptor, nullptr, CrashHandler::dumpCallback, &ctx, true, -1);

    spdlog::debug("Installed breakpad exception handler (path {})", crashpath);
#endif // CONFIG_USEBREAKPAD

    const auto profile = []() {
        Configuration c;
        return c.value<QString>("profile.default").value();
    }();

    app.setup(plugins);

    QStringList urls;

    for(const auto &u : args::get(cmd_args)) {
        if(pluginCommands.contains(QString::fromStdString(u))) {
            return pluginCommands.value(QString::fromStdString(u))();
        } else {
            urls.append(QString::fromStdString(u));
        }
    }
    if(urls.isEmpty())
        urls.append(QString());

    // if app is primary, create new sessions from received messages
    if(app.isPrimary() && !cmd_noRemote) {
        QObject::connect(&app, &Browser::receivedMessage, &app, [](quint32 instanceId, QByteArray message) {
            Q_UNUSED(instanceId);
            auto doc = QJsonDocument::fromJson(message);
            Session::restoreSession(doc.object());
        });
    }

    {
        QJsonObject sessionData;

        if(cmd_pickSession) {
            auto *dlg = new SessionDialog();
            if(const auto pick = dlg->pickSession())
                sessionData = pick.value();
            else
                sessionData = Session::fromCommandLine(profile, urls);
        } else if(cmd_session) {
            QFile sessionJson(QString::fromStdString(args::get(cmd_session)));
            if(sessionJson.open(QIODevice::ReadOnly | QIODevice::Text)) {
                sessionData = QJsonDocument::fromJson(sessionJson.readAll()).object();
                sessionJson.close();
            }
        } else {
            sessionData = Session::fromCommandLine(profile, urls);
        }

        if(app.isPrimary() || cmd_noRemote) {
            Session::restoreSession(sessionData);
        } else {
            // app is secondary and not standalone
            return app.sendMessage(QJsonDocument(sessionData).toJson());
        }
    }

    return app.exec();
}