summaryrefslogtreecommitdiff
path: root/src/main_window.cpp
blob: 007705fd69a279889d0319a605fbcd8fc2270775 (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
#include "main_window.hpp"

#include "config.hpp"
#include "luacxx.hpp"

#include <QString>
#include <cerrno>
#include <filesystem>
#include <fud_result.hpp>
#include <fud_status.hpp>
#include <string>
#include <sys/stat.h>
#include <fcntl.h>
#include <vector>

namespace getsuyomi {

using fud::FudStatus;
using GetEnvResult = fud::Result<GetsuyomiConfig, FudStatus>;
using GetConfigResult = fud::Result<GetsuyomiConfig, FudStatus>;

constexpr const char* HOME{"HOME"};

std::optional<std::string> getEnvVar(const char* envVar);
void getEnvVar(const std::string& homeVar, const std::string& envVar, std::string& envValue, const char* backup);
GetEnvResult getEnvironment();

FudStatus createXdgDirectory(const std::string& directoryName)
{
    constexpr mode_t xdgMode = 0700;
    auto dirStatus = mkdir(directoryName.c_str(), xdgMode);
    if (dirStatus == 0)
    {
        return FudStatus::Success;
    }

    if (errno != EEXIST) {
        return FudStatus::Failure;
    }
    struct stat statBuffer{};
    dirStatus = stat(directoryName.c_str(), &statBuffer);

    if (dirStatus != 0) {
        return FudStatus::Failure;
    }

    if ((statBuffer.st_mode & S_IFMT) != S_IFDIR) {
        return FudStatus::Failure;
    }

    return FudStatus::Success;
}

GetConfigResult getUserConfig()
{
    auto configResult = getEnvironment();
    if (configResult.isError()) {
        return GetConfigResult::error(configResult.getError());
    }
    auto config = configResult.getOkay();

    auto dirStatus = createXdgDirectory(config.dataHome);
    if (dirStatus != FudStatus::Success) {
        return GetConfigResult::error(dirStatus);
    }
    dirStatus = createXdgDirectory(config.configHome);
    if (dirStatus != FudStatus::Success) {
        return GetConfigResult::error(dirStatus);
    }
    dirStatus = createXdgDirectory(config.stateHome);
    if (dirStatus != FudStatus::Success) {
        return GetConfigResult::error(dirStatus);
    }

    LuaContext luaContext{};
    if (!luaContext.valid()) {
        return GetConfigResult::error(FudStatus::Failure);
    }

    auto configFileName = std::filesystem::path(config.configHome).append("config.lua");
    qDebug("configFileName is %s", configFileName.c_str());

    constexpr mode_t configFileMode = 0600;
    auto fdResult = open(configFileName.c_str(), O_CREAT, configFileMode);
    if (fdResult == -1) {
        if (errno != EEXIST) {
            return GetConfigResult::error(FudStatus::Failure);
        }
    }
    close(fdResult);

    auto luaStatus = luaContext.loadFile(configFileName.c_str());
    if (luaStatus != FudStatus::Success)
    {
        qCritical("Failed to load file in lua %s", fud::FudStatusToString(luaStatus));
        return GetConfigResult::error(luaStatus);
    }

    auto result = luaContext.getGlobalString(actionTypeToString(ActionType::OpenFile));
    if (result.isError())
    {
        qCritical("Failed to get variable from lua %s", fud::FudStatusToString(result.getError()));
        return GetConfigResult::error(result.getError());
    }

    return GetConfigResult::okay(config);
}

GetsuyomiApp::GetsuyomiApp() : QMainWindow(nullptr), m_getsuyomi{new Getsuyomi(this)}
{
    readSettings();
}

FudStatus GetsuyomiApp::setup()
{
    setCentralWidget(m_getsuyomi);

    QCoreApplication::setApplicationName(AppName);
    QCoreApplication::setApplicationVersion(AppVersionString);
    setWindowTitle(AppName);

    auto envResult = getUserConfig();
    if (envResult.isError()) {
        qCritical("Failure %s", fud::FudStatusToString(envResult.getError()));
        return envResult.getError();
    }
    m_config = envResult.getOkay();

    createActions();
    createMenus();
    createToolBar();

    constexpr int minimumWidth = 640;
    constexpr int minimumHeight = 480;
    setMinimumSize(minimumWidth, minimumHeight);

    show();

    return FudStatus::Success;
}

void GetsuyomiApp::createActions()
{
    m_openFile = new QAction(QIcon::fromTheme(QIcon::ThemeIcon::DocumentOpen), tr("&Open File"), this);
    m_openFile->setShortcuts(QKeySequence::Open);
    m_openFile->setStatusTip(tr("Open a file"));
    connect(m_openFile, &QAction::triggered, this, &GetsuyomiApp::openFile);

    m_openDirectory = new QAction(QIcon::fromTheme(QIcon::ThemeIcon::FolderOpen), tr("Open &Directory"), this);
    m_openDirectory->setShortcut(Qt::CTRL | Qt::ALT | Qt::Key_O);
    m_openDirectory->setStatusTip(tr("Open a directory"));
    connect(m_openDirectory, &QAction::triggered, this, &GetsuyomiApp::openDirectory);

    m_quitAction = new QAction(QIcon::fromTheme(QIcon::ThemeIcon::ApplicationExit), tr("&Quit"), this);
    m_quitAction->setShortcuts(QKeySequence::Quit);
    m_quitAction->setStatusTip(tr("Quit"));
    connect(m_quitAction, &QAction::triggered, this, &GetsuyomiApp::quit);

    m_settingsAction = new QAction(QIcon("resources/gear.svg"), tr("&Settings"), this);
    m_settingsAction->setShortcut(Qt::CTRL | Qt::Key_P);
    m_settingsAction->setStatusTip(tr("Configure getsuyomi"));
    connect(m_settingsAction, &QAction::triggered, this, &GetsuyomiApp::configure);

    auto nextShortcuts = QList<QKeySequence>{};
    nextShortcuts.append(QKeySequence{Qt::Key_L});
    nextShortcuts.append(QKeySequence{Qt::Key_Right});
    nextShortcuts.append(QKeySequence{Qt::Key_Down});
    m_nextAction = new QAction(QIcon::fromTheme(QIcon::ThemeIcon::GoNext), tr("Next"), this);
    m_nextAction->setShortcuts(nextShortcuts);
    m_nextAction->setStatusTip(tr("Next"));
    connect(m_nextAction, &QAction::triggered, this, &GetsuyomiApp::next);

    auto backShortcuts = QList<QKeySequence>{};
    backShortcuts.append(QKeySequence{Qt::Key_H});
    backShortcuts.append(QKeySequence{Qt::Key_Left});
    backShortcuts.append(QKeySequence{Qt::Key_Up});
    m_backAction = new QAction(QIcon::fromTheme(QIcon::ThemeIcon::GoPrevious), tr("Back"), this);
    m_backAction->setShortcuts(backShortcuts);
    m_backAction->setStatusTip(tr("Back"));
    connect(m_backAction, &QAction::triggered, this, &GetsuyomiApp::back);

    m_setSinglePageLayout = new QAction(QIcon("../resources/pageSingle.png"), tr("Single Page Layout"), this);
    m_setSinglePageLayout->setShortcut(QKeySequence{Qt::Key_S});
    m_setSinglePageLayout->setStatusTip(tr("Set Single Page Layout"));
    connect(m_setSinglePageLayout, &QAction::triggered, this, &GetsuyomiApp::setSinglePageLayout);

    m_setDualPageLayout = new QAction(QIcon("../resources/pageDual.png"), tr("Dual Page Layout"), this);
    m_setDualPageLayout->setShortcut(QKeySequence{Qt::Key_D});
    m_setDualPageLayout->setStatusTip(tr("Set Dual Page Layout"));
    connect(m_setDualPageLayout, &QAction::triggered, this, &GetsuyomiApp::setDualPageLayout);

    m_setMangaLayout = new QAction(QIcon("../resources/pageManga.png"), tr("Manga Page Layout"), this);
    m_setMangaLayout->setShortcut(QKeySequence{Qt::Key_M});
    m_setMangaLayout->setStatusTip(tr("Set Manga Page Layout"));
    connect(m_setMangaLayout, &QAction::triggered, this, &GetsuyomiApp::setMangaLayout);

    m_setPageLayoutGroup = new QActionGroup(this);
    m_setPageLayoutGroup->addAction(m_setSinglePageLayout);
    m_setPageLayoutGroup->addAction(m_setDualPageLayout);
    m_setPageLayoutGroup->addAction(m_setMangaLayout);
    m_setPageLayoutGroup->setExclusionPolicy(QActionGroup::ExclusionPolicy::Exclusive);
}

void GetsuyomiApp::createMenus()
{
    m_fileMenu = menuBar()->addMenu(tr("&File"));
    m_fileMenu->addAction(m_openFile);
    m_fileMenu->addAction(m_openDirectory);
    m_fileMenu->addAction(m_quitAction);

    m_SettingsMenu = menuBar()->addMenu(tr("&Settings"));
    m_SettingsMenu->addAction(m_settingsAction);
}

void GetsuyomiApp::createToolBar()
{
    m_toolBar = addToolBar(tr("&Navigation"));
    m_toolBar->setObjectName("Navigation");

    // goto first
    m_toolBar->addAction(m_backAction);
    m_toolBar->addAction(m_nextAction);
    // goto last

    m_toolBar->addSeparator();

    m_toolBar->addAction(m_setSinglePageLayout);
    m_toolBar->addAction(m_setDualPageLayout);
    m_toolBar->addAction(m_setMangaLayout);
}

void GetsuyomiApp::openFile()
{
    auto dialog = QFileDialog(
        this,
        tr("Open Archive"),
        m_lastOpenedDirectory,
        tr("Archive types (*.zip *.cbz *.cbr *.gz)"));
    dialog.setFileMode(QFileDialog::ExistingFile);
    QString filename;
    if (dialog.exec()) {
        auto filenames = dialog.selectedFiles();
        if (filenames.length() == 0) {
            qWarning("No files selected.");
            return;
        } else if (filenames.length() > 1) {
            qWarning("Too many files selected %llu.", filenames.length());
            return;
        }
        filename = filenames[0];
        m_lastOpenedDirectory = dialog.directory().absolutePath();
        qDebug("Last opened directory is %s", qPrintable(m_lastOpenedDirectory));
    } else {
        qWarning("File dialog did not execute");
        return;
    }

    if (filename.endsWith(".zip")) {
        auto* archive = new ZipArchive(filename);
        if (!archive->valid()) {
            qCritical("Failed to change archive");
        } else {
            m_getsuyomi->setArchive(archive);
        }
    } else {
        qCritical("Unsupported file extension");
    }
}

void GetsuyomiApp::openDirectory()
{
    auto dialog = QFileDialog(this, tr("Open Directory"), m_lastOpenedDirectory);
    dialog.setFileMode(QFileDialog::Directory);
    QString directoryName;
    if (dialog.exec()) {
        auto filenames = dialog.selectedFiles();
        if (filenames.length() == 0) {
            qWarning("No files selected.");
            return;
        } else if (filenames.length() > 1) {
            qWarning("Too many files selected %llu.", filenames.length());
            return;
        }
        directoryName = filenames[0];
        m_lastOpenedDirectory = dialog.directory().absolutePath();
    } else {
        qWarning("File dialog did not execute");
        return;
    }
    qDebug("Opened directory %s", qPrintable(directoryName));
}

void GetsuyomiApp::quit()
{
    QCoreApplication::quit();
}

void GetsuyomiApp::configure()
{
    Settings settings(this, m_config.shortcuts());
    if (!settings.valid()) {
        qCritical("Invalid settings");
        return;
    }
    settings.exec();
}

void GetsuyomiApp::next()
{
    m_getsuyomi->next();
}

void GetsuyomiApp::back()
{
    m_getsuyomi->back();
}

void GetsuyomiApp::setSinglePageLayout()
{
    m_getsuyomi->setPageLayout(PageLayout::Single);
    m_setSinglePageLayout->setEnabled(false);
    m_setDualPageLayout->setEnabled(true);
    m_setMangaLayout->setEnabled(true);
}

void GetsuyomiApp::setDualPageLayout()
{
    m_getsuyomi->setPageLayout(PageLayout::Dual);
    m_setSinglePageLayout->setEnabled(true);
    m_setDualPageLayout->setEnabled(false);
    m_setMangaLayout->setEnabled(true);
}

void GetsuyomiApp::setMangaLayout()
{
    m_getsuyomi->setPageLayout(PageLayout::Manga);
    m_setSinglePageLayout->setEnabled(true);
    m_setDualPageLayout->setEnabled(true);
    m_setMangaLayout->setEnabled(false);
}

void GetsuyomiApp::closeEvent(QCloseEvent* event)
{
    writeSettings();
    QMainWindow::closeEvent(event);
}

void GetsuyomiApp::readSettings()
{

    QSettings settings{AppVendor, AppName};
    restoreGeometry(settings.value("geometry").toByteArray());
    restoreState(settings.value("windowState").toByteArray());
    m_lastOpenedDirectory = settings.value("lastOpenedDirectory", QDir::homePath()).toString();
}

void GetsuyomiApp::writeSettings()
{
    QSettings settings{AppVendor, AppName};
    settings.setValue("geometry", saveGeometry());
    settings.setValue("windowState", saveState());
    settings.setValue("lastOpenedDirectory", m_lastOpenedDirectory);
    settings.sync();
}

std::optional<std::string> getEnvVar(const char* envVar)
{
    const QByteArray defaultArray{};
    if (envVar == nullptr) {
        return std::nullopt;
    }
    QByteArray varArray = qgetenv(envVar);
    if (varArray == defaultArray) {
        return std::nullopt;
    }
    return varArray.toStdString();
}

void getEnvVar(const std::string& homeVar, const std::string& envVar, std::string& envValue, const char* backup)
{
    auto envValueOpt = getEnvVar(envVar.c_str());
    std::filesystem::path envValuePath{homeVar};
    if (envValueOpt == std::nullopt || envValueOpt->length() == 0) {
        envValuePath.append(backup);
    } else {
        envValuePath = *envValueOpt;
    }
    envValuePath.append(AppName);
    envValue = envValuePath;
    // qDebug("%s is %s", envVar.c_str(), envValue.c_str());
}

GetEnvResult getEnvironment()
{
    GetsuyomiConfig config{};

    auto homeOpt = getEnvVar(HOME);
    if (homeOpt == std::nullopt || homeOpt->length() == 0) {
        qCritical("Error getting home");
        return GetEnvResult::error(FudStatus::Failure);
    }
    config.home = *homeOpt;
    // qDebug("Home is %s", config.home.c_str());

    /* If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share should be used. */
    const std::string XdgDataHome{"XDG_DATA_HOME"};
    getEnvVar(config.home, XdgDataHome, config.dataHome, ".local/share");

    /* If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used. */
    const std::string XdgConfigHome{"XDG_CONFIG_HOME"};
    getEnvVar(config.home, XdgConfigHome, config.configHome, ".config");

    /* If $XDG_STATE_HOME is either not set or empty, a default equal to $HOME/.local/state should be used. */
    const std::string XdgStateHome{"XDG_STATE_HOME"};
    getEnvVar(config.home, XdgStateHome, config.stateHome, ".local/state");

    return GetEnvResult::okay(config);
}

} // namespace getsuyomi