Debian Codegraph @

garglk/sysqt.cpp

raw symbols SCIP
1 // Copyright (C) 2006-2009 by Tor Andersson.
2 // Copyright (C) 2010 by Ben Cressey.
3 // Copyright (C) 2010-2021 by Chris Spiegel.
4 //
5 // This file is part of Gargoyle.
6 //
7 // Gargoyle is free software; you can redistribute it and/or modify
8 // it under the terms of the GNU General Public License as published by
9 // the Free Software Foundation; either version 2 of the License, or
10 // (at your option) any later version.
11 //
12 // Gargoyle is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 // GNU General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with Gargoyle; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20
21 #include <QApplication>
22 #include <QChar>
23 #include <QClipboard>
24 #include <QCursor>
25 #include <QDesktopServices>
26 #include <QDir>
27 #include <QFileDialog>
28 #include <QFileInfo>
29 #include <QGraphicsView>
30 #include <QLabel>
31 #include <QList>
32 #include <QMainWindow>
33 #include <QMessageBox>
34 #include <QMoveEvent>
35 #include <QObject>
36 #include <QPainter>
37 #include <QPalette>
38 #include <QProcess>
39 #include <QResizeEvent>
40 #include <QSettings>
41 #include <QStandardPaths>
42 #include <QString>
43 #include <QStringList>
44 #include <QTimer>
45 #include <QUrl>
46 #include <QWidget>
47 #include <QtGlobal>
48
49 #if GARGLK_CONFIG_HAS_QDBUS
50 #include <QtDBus/QDBusInterface>
51 #include <QtDBus/QDBusReply>
52 #endif
53
54 #ifdef GARGLK_CONFIG_KDE
55 #include <kio_version.h>
56
57 #if KIO_VERSION >= ((5 << 16) | (69 << 8))
58 #define GARGLK_KDE_HAS_APPLICATION_LAUNCHER
59 #include <KApplicationTrader>
60 #include <KIO/ApplicationLauncherJob>
61 #if KIO_VERSION >= ((5 << 16) | (98 << 8))
62 #include <KIO/JobUiDelegateFactory>
63 #define create_delegate(window) (KIO::createDefaultJobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, window))
64 #else
65 #include <KIO/JobUiDelegate>
66 #define create_delegate(window) (new KIO::JobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, window))
67 #endif
68 #else
69 #include <KRun>
70 #endif
71 #endif
72
73 #include <algorithm>
74 #include <atomic>
75 #include <chrono>
76 #include <cstdlib>
77 #include <cstring>
78 #include <ctime>
79 #include <iostream>
80 #include <limits>
81 #include <map>
82 #include <stdexcept>
83 #include <string>
84 #include <thread>
85 #include <unordered_map>
86 #include <utility>
87 #include <vector>
88
89 #include "format.h"
90 #include "optional.hpp"
91
92 #include "sysqt.h"
93 #include "moc_sysqt.cpp"
94
95 #include "garversion.h"
96 #include "glk.h"
97 #include "garglk.h"
98
99 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
100 #define HAS_QT6
101 #endif
102
103 // buffer for clipboard text
104 static QString cliptext;
105
106 // filters and extensions for file dialogs
107 static const std::unordered_map<FileFilter, std::pair<QString, QString>> filters = {
108 {FileFilter::Save, std::make_pair("Saved game files (*.glksave *.sav)", "glksave")},
109 {FileFilter::Text, std::make_pair("Text files (*.txt)", "txt")},
110 {FileFilter::Data, std::make_pair("Data files (*.glkdata)", "glkdata")},
111 };
112
113 static QApplication *app;
114 static garglk::Window *window;
115
116 static bool refresh_needed = true;
117
118 static constexpr int TICK_PERIOD_MILLIS = 10;
119 static std::atomic<bool> process_events(false);
120
121 static void handle_input(const QString &input, bool from_paste)
122 {
123 auto fn = from_paste ? gli_input_handle_key_paste :
124 gli_input_handle_key;
125
126 for (const uint &c : input.toUcs4()) {
127 if (c == '\r' || c == '\n') {
128 fn(keycode_Return);
129 } else if (QChar::isPrint(c)) {
130 fn(c);
131 }
132 }
133 }
134
135 void glk_request_timer_events(glui32 ms)
136 {
137 window->start_timer(ms);
138 }
139
140 void gli_notification_waiting()
141 {
142 QApplication::postEvent(window, new QEvent(QEvent::None));
143 }
144
145 void garglk::winabort(const std::string &msg)
146 {
147 std::cerr << "fatal: " << msg << std::endl;
148 QMessageBox::critical(nullptr, "Error", msg.c_str());
149 gli_exit(EXIT_FAILURE);
150 }
151
152 void garglk::winwarning(const std::string &title, const std::string &msg)
153 {
154 std::cerr << "warning: " << msg << std::endl;
155 QMessageBox::warning(nullptr, title.c_str(), msg.c_str());
156 }
157
158 void winexit()
159 {
160 gli_exit(0);
161 }
162
163 enum class Action { Open, Save };
164
165 static std::string winchoosefile(const QString &prompt, FileFilter filter, Action action)
166 {
167 QString filename;
168 QFileDialog::Options options;
169 #ifdef GARGLK_CONFIG_NO_NATIVE_FILE_DIALOGS
170 options |= QFileDialog::DontUseNativeDialog;
171 #endif
172
173 QString dir = "";
174
175 if (gli_conf_gamedata_location == GamedataLocation::Dedicated && gli_workfile.has_value()) {
176 auto path = QFileInfo(QString::fromStdString(*gli_workfile));
177 if (!path.fileName().isEmpty()) {
178 QDir basedir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
179 QDir savepath = QDir(basedir.filePath("gamedata")).filePath(path.fileName());
180 if (savepath.mkpath(savepath.absolutePath())) {
181 dir = savepath.absolutePath();
182 }
183 }
184 } else if (gli_conf_gamedata_location == GamedataLocation::Gamedir) {
185 dir = QString::fromStdString(gli_workdir);
186 }
187
188 if (action == Action::Open) {
189 QString filterstring = QString("%1;;All files (*)").arg(filters.at(filter).first);
190 filename = QFileDialog::getOpenFileName(window, prompt, dir, filterstring, nullptr, options);
191 } else {
192 if (dir == "") {
193 dir += ".";
194 }
195 dir += QString("/Untitled.%1").arg(filters.at(filter).second);
196 filename = QFileDialog::getSaveFileName(window, prompt, dir, filters.at(filter).first, nullptr, options);
197 }
198
199 // toStdString() converts to UTF-8, which is not used by Windows (at
200 // least not by default). toLocal8Bit() will use the current locale
201 // to determine an encoding. This allows many non-ASCII characters
202 // in filenames, although only those that are in the current
203 // codepage. In the future, explore Windows' UTF-8 support to
204 // hopefully fully support Unicode.
205 #ifdef _WIN32
206 return filename.toLocal8Bit().toStdString();
207 #else
208 return filename.toStdString();
209 #endif
210 }
211
212 std::string garglk::winopenfile(const char *prompt, FileFilter filter)
213 {
214 QString realprompt = QString("Open: %1").arg(prompt);
215 return winchoosefile(realprompt, filter, Action::Open);
216 }
217
218 std::string garglk::winsavefile(const char *prompt, FileFilter filter)
219 {
220 QString realprompt = QString("Save: %1").arg(prompt);
221 return winchoosefile(realprompt, filter, Action::Save);
222 }
223
224 void winclipstore(const std::vector<glui32> &text)
225 {
226 cliptext = QString::fromUcs4(reinterpret_cast<const char32_t *>(text.data()), text.size());
227 }
228
229 static void winclipsend(QClipboard::Mode mode)
230 {
231 if (cliptext.isEmpty()) {
232 return;
233 }
234
235 QClipboard *clipboard = QGuiApplication::clipboard();
236
237 clipboard->setText(cliptext, mode);
238 }
239
240 static void winclipreceive(QClipboard::Mode mode)
241 {
242 QClipboard *clipboard = QGuiApplication::clipboard();
243 QString text = clipboard->text(mode);
244
245 handle_input(text, true);
246 }
247
248 garglk::Window::Window() :
249 m_view(new View(this)),
250 m_timer(new QTimer(this)),
251 // Qt programs have an organization and name that can be set, and
252 // Gargoyle used to set these to "io.github.garglk" and "Gargoyle".
253 // The QSettings here followed that. However, Gargoyle now uses an
254 // empty organization and the name "gargoyle" (on Unix) so that
255 // directories are more conventionally-named, e.g. /usr/share/gargoyle
256 // instead of /usr/share/io.github.garglk/Gargoyle. But QSettings
257 // _requires_ an organization name. Given that this is a setting
258 // users aren't ever supposed to see anyhow, and that these exact
259 // names were used in the past, keep them the same so that older
260 // configurations can be loaded. Ideally this would probably just be
261 // "gargoyle" and "gargoyle" but aesthetics are nowhere near as
262 // important as not losing settings; and since nobody is going to
263 // see these names in the normal course of using Gargoyle, it
264 // doesn't really matter anyway.
265 m_settings(new QSettings("io.github.garglk", "Gargoyle", this))
266 {
267 m_timer->setTimerType(Qt::TimerType::PreciseTimer);
268 connect(m_timer, &QTimer::timeout, this, [&]() {
269 m_timed_out = true;
270 });
271 }
272
273 void garglk::Window::closeEvent(QCloseEvent *)
274 {
275 gli_exit(0);
276 }
277
278 void garglk::Window::resizeEvent(QResizeEvent *event)
279 {
280 static bool first_resize = true;
281
282 QMainWindow::resizeEvent(event);
283
284 m_view->resize(event->size());
285
286 int newwid = event->size().width();
287 int newhgt = event->size().height();
288
289 if (newwid == gli_image_rgb.width() && newhgt == gli_image_rgb.height()) {
290 return;
291 }
292
293 refresh_needed = true;
294
295 // On startup, Qt posts a resize event as the window is created.
296 // This resize occurs before the Glk program even starts, so
297 // shouldn't create an arrange event.
298 gli_windows_size_change(newwid, newhgt, !first_resize);
299
300 if (gli_conf_save_window_size) {
301 m_settings->setValue("window/size", event->size());
302 }
303
304 if (gli_conf_save_window_location || gli_conf_save_window_size) {
305 m_settings->setValue("window/fullscreen", ::window->isFullScreen());
306 }
307
308 event->accept();
309
310 first_resize = false;
311 }
312
313 void garglk::Window::moveEvent(QMoveEvent *event)
314 {
315 if (gli_conf_save_window_location) {
316 m_settings->setValue("window/position", event->pos());
317 }
318
319 event->accept();
320 }
321
322 QVariant garglk::View::inputMethodQuery(Qt::InputMethodQuery query) const
323 {
324 switch (query) {
325 case Qt::ImEnabled:
326 return QVariant(true);
327 default:
328 return QVariant();
329 }
330 }
331
332 // Handle compose key events (probably other input method events too).
333 // See https://stackoverflow.com/questions/28793356/qt-and-dead-keys-in-a-custom-widget
334 void garglk::View::inputMethodEvent(QInputMethodEvent *event)
335 {
336 if (!event->commitString().isEmpty()) {
337 QKeyEvent key_event(QEvent::KeyPress, 0, Qt::NoModifier, event->commitString());
338 keyPressEvent(&key_event);
339 }
340 event->accept();
341 }
342
343 void garglk::View::refresh()
344 {
345 if (!gli_drawselect) {
346 gli_windows_redraw();
347 } else {
348 gli_drawselect = false;
349 }
350
351 update();
352 refresh_needed = false;
353 }
354
355 void garglk::View::paintEvent(QPaintEvent *event)
356 {
357 QImage image(gli_image_rgb.data(), gli_image_rgb.width(), gli_image_rgb.height(), gli_image_rgb.stride(), QImage::Format_RGB888);
358 QPainter painter(this);
359 painter.drawImage(QPoint(0, 0), image);
360 event->accept();
361 }
362
363 void garglk::Window::start_timer(unsigned long ms)
364 {
365 if (m_timer->isActive()) {
366 m_timer->stop();
367 }
368
369 // QTimer::setInterval() takes int, so limit to avoid wrapping.
370 if (ms > std::numeric_limits<int>::max()) {
371 ms = std::numeric_limits<int>::max();
372 }
373
374 if (ms != 0) {
375 m_timer->setInterval(ms);
376 m_timer->start();
377 }
378 }
379
380 void gli_edit_config()
381 {
382 try {
383 auto config = garglk::user_config();
384 #ifdef __APPLE__
385 // QDesktopServices::openUrl uses the default handler for the
386 // specified file. One possible filename is garglk.ini, meaning
387 // that the handler for INI files will be used. This at least
388 // works by default under Plasma & Gnome on Unix, and on
389 // Windows. But on macOS, INI files aren't associated with a
390 // text editor, so use "open -t" to explicitly request a text
391 // editor. This would actually be the best solution on all
392 // platforms, but Qt doesn't appear to be able to look up the
393 // default program for a specific MIME type, so finding a user's
394 // text editor can't be done easily.
395 QProcess proc;
396 QStringList args;
397 args << "-t" << config.c_str();
398 proc.startDetached("open", args);
399 #elif defined(GARGLK_CONFIG_KDE)
400 // If KDE is available, it provides a way to query the user's
401 // preferred text editor, allowing an approximation of the Mac
402 // behavior. Fall back to QDesktopServices::openUrl otherwise.
403 QUrl url(QUrl::fromLocalFile(config.c_str()));
404 #ifdef GARGLK_KDE_HAS_APPLICATION_LAUNCHER
405 auto service = KApplicationTrader::preferredService("text/plain");
406 auto *job = new KIO::ApplicationLauncherJob(service);
407 job->setUiDelegate(create_delegate(window));
408 job->setUrls({url});
409 job->start();
410 #else
411 KRun::runUrl(url, "text/plain", window);
412 #endif
413 #else
414 if (!QDesktopServices::openUrl(QUrl::fromLocalFile(config.c_str()))) {
415 QMessageBox::warning(nullptr, "Warning", "Unable to find a text editor");
416 }
417 #endif
418 } catch (std::runtime_error &e) {
419 QMessageBox::warning(nullptr, "Warning", e.what());
420 }
421 }
422
423 static void show_paths()
424 {
425 // Convert to native separators and return absolute path.
426 auto canonicalize = [](const std::string &path) {
427 auto qpath = QString::fromStdString(path);
428 qpath = QDir(qpath).absolutePath();
429 return QDir::toNativeSeparators(qpath);
430 };
431
432 QString text("<p>Configuration file paths:</p><pre>");
433
434 for (const auto &config : garglk::all_configs) {
435 auto path = canonicalize(config.path);
436 auto type = QString::fromStdString(config.format_type());
437
438 text += QString("%1 %2\n").arg(path).arg(type);
439 }
440
441 text += "</pre><p>Theme paths:</p><pre>";
442 auto theme_paths = garglk::theme::paths();
443 std::reverse(theme_paths.begin(), theme_paths.end());
444 for (const auto &path : theme_paths) {
445 text += canonicalize(path) + "\n";
446 }
447 text += "</pre>";
448
449 QMessageBox box(QMessageBox::Icon::Information, "Paths", text);
450 box.setTextFormat(Qt::TextFormat::RichText);
451 box.exec();
452 }
453
454 static void show_themes()
455 {
456 QString text("The following themes are available:\n\n");
457
458 for (const auto &theme_name : garglk::theme::names()) {
459 text += QString("• ") + QString::fromStdString(theme_name) + "\n";
460 }
461
462 QMessageBox box(QMessageBox::Icon::Information, "Themes", text);
463 box.setTextFormat(Qt::TextFormat::PlainText);
464 box.exec();
465 }
466
467 // On Mac, Qt::ControlModifier means the command key. But for Emacs
468 // keys, we need the actual control key.
469 #ifdef Q_OS_MAC
470 static constexpr Qt::KeyboardModifier RealCtrl = Qt::MetaModifier;
471 #else
472 static constexpr Qt::KeyboardModifier RealCtrl = Qt::ControlModifier;
473 #endif
474
475 void garglk::View::keyPressEvent(QKeyEvent *event)
476 {
477 Qt::KeyboardModifiers modmasked = event->modifiers() & (Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier);
478
479 refresh_needed = true;
480
481 static const std::map<QKeySequence::StandardKey, std::function<void()>> sequences = {
482 {QKeySequence::Cut, []{ winclipsend(QClipboard::Clipboard); }},
483 {QKeySequence::Copy, []{ winclipsend(QClipboard::Clipboard); }},
484 {QKeySequence::Paste, []{ winclipreceive(QClipboard::Clipboard); }},
485 {QKeySequence::MoveToPreviousWord, []{ gli_input_handle_key(keycode_SkipWordLeft); }},
486 {QKeySequence::MoveToNextWord, []{ gli_input_handle_key(keycode_SkipWordRight); }},
487 {QKeySequence::Quit, []{ gli_exit(0); }},
488 {QKeySequence::Delete, []{ gli_input_handle_key(keycode_Erase); }},
489 {QKeySequence::MoveToStartOfLine, []{ gli_input_handle_key(keycode_Home); }},
490 {QKeySequence::MoveToEndOfLine, []{ gli_input_handle_key(keycode_End); }},
491 {QKeySequence::MoveToPreviousPage, []{ gli_input_handle_key(keycode_PageUp); }},
492 {QKeySequence::MoveToNextPage, []{ gli_input_handle_key(keycode_PageDown); }},
493 };
494
495 static const std::map<std::pair<decltype(modmasked), decltype(event->key())>, std::function<void()>> keys = {
496 // Emacs keys.
497 {{RealCtrl, Qt::Key_A}, []{ gli_input_handle_key(keycode_Home); }},
498 {{RealCtrl, Qt::Key_B}, []{ gli_input_handle_key(keycode_Left); }},
499 {{RealCtrl, Qt::Key_D}, []{ gli_input_handle_key(keycode_Erase); }},
500 {{RealCtrl, Qt::Key_E}, []{ gli_input_handle_key(keycode_End); }},
501 {{RealCtrl, Qt::Key_F}, []{ gli_input_handle_key(keycode_Right); }},
502 {{RealCtrl, Qt::Key_H}, []{ gli_input_handle_key(keycode_Delete); }},
503 {{RealCtrl, Qt::Key_N}, []{ gli_input_handle_key(keycode_Down); }},
504 {{RealCtrl, Qt::Key_P}, []{ gli_input_handle_key(keycode_Up); }},
505 {{RealCtrl, Qt::Key_U}, []{ gli_input_handle_key(keycode_Escape); }},
506
507 #ifdef Q_OS_WIN
508 // Qt doesn't assign Ctrl-Q to QKeySequence::Quit on Windows.
509 {{Qt::ControlModifier, Qt::Key_Q}, []{ gli_exit(0); }},
510 #endif
511
512 #ifdef __HAIKU__
513 // For some reason, on Haiku, the "shifted" versions of comma/period are
514 // used, which, on US English keyboards, at least, are less-than/
515 // greater-than signs. I assume this is a bug in translating
516 // Haiku input to Qt input, but I'm also not completely sure it's wrong,
517 // either; the QKeyEvent documentations says that key() "does not
518 // distinguish between capital and non-capital letters", but these
519 // aren't letters...
520 {{Qt::ControlModifier, Qt::Key_Less}, gli_edit_config},
521 {{Qt::ControlModifier, Qt::Key_Greater}, show_paths},
522 #else
523 {{Qt::ControlModifier, Qt::Key_Comma}, gli_edit_config},
524 {{Qt::ControlModifier, Qt::Key_Period}, show_paths},
525 #endif
526
527 {{Qt::ShiftModifier | Qt::ControlModifier, Qt::Key_T}, [] { show_themes(); }},
528
529 {{Qt::ShiftModifier, Qt::Key_Backspace}, []{ gli_input_handle_key(keycode_Delete); }},
530
531 {{Qt::NoModifier, Qt::Key_Escape}, []{ gli_input_handle_key(keycode_Escape); }},
532 {{Qt::NoModifier, Qt::Key_Tab}, []{ gli_input_handle_key(keycode_Tab); }},
533 {{Qt::NoModifier, Qt::Key_Backspace}, []{ gli_input_handle_key(keycode_Delete); }},
534 {{Qt::NoModifier, Qt::Key_Return}, []{ gli_input_handle_key(keycode_Return); }},
535 {{Qt::NoModifier, Qt::Key_Enter}, []{ gli_input_handle_key(keycode_Return); }},
536 {{Qt::NoModifier, Qt::Key_Left}, []{ gli_input_handle_key(keycode_Left); }},
537 {{Qt::NoModifier, Qt::Key_Up}, []{ gli_input_handle_key(keycode_Up); }},
538 {{Qt::NoModifier, Qt::Key_Right}, []{ gli_input_handle_key(keycode_Right); }},
539 {{Qt::NoModifier, Qt::Key_Down}, []{ gli_input_handle_key(keycode_Down); }},
540 {{Qt::NoModifier, Qt::Key_F1}, []{ gli_input_handle_key(keycode_Func1); }},
541 {{Qt::NoModifier, Qt::Key_F2}, []{ gli_input_handle_key(keycode_Func2); }},
542 {{Qt::NoModifier, Qt::Key_F3}, []{ gli_input_handle_key(keycode_Func3); }},
543 {{Qt::NoModifier, Qt::Key_F4}, []{ gli_input_handle_key(keycode_Func4); }},
544 {{Qt::NoModifier, Qt::Key_F5}, []{ gli_input_handle_key(keycode_Func5); }},
545 {{Qt::NoModifier, Qt::Key_F6}, []{ gli_input_handle_key(keycode_Func6); }},
546 {{Qt::NoModifier, Qt::Key_F7}, []{ gli_input_handle_key(keycode_Func7); }},
547 {{Qt::NoModifier, Qt::Key_F8}, []{ gli_input_handle_key(keycode_Func8); }},
548 {{Qt::NoModifier, Qt::Key_F9}, []{ gli_input_handle_key(keycode_Func9); }},
549 {{Qt::NoModifier, Qt::Key_F10}, []{ gli_input_handle_key(keycode_Func10); }},
550 {{Qt::NoModifier, Qt::Key_F11}, []{ gli_input_handle_key(keycode_Func11); }},
551 {{Qt::NoModifier, Qt::Key_F12}, []{ gli_input_handle_key(keycode_Func12); }},
552
553 {{Qt::ShiftModifier | Qt::ControlModifier, Qt::Key_S}, []{
554 auto text = gli_get_scrollback();
555 if (text.has_value()) {
556 auto filename = QFileDialog::getSaveFileName(::window, "Save transcript", "transcript.txt", "Text files (*.txt)");
557 if (!filename.isNull()) {
558 QFile file(filename);
559 if (file.open(QIODevice::WriteOnly)) {
560 std::size_t n = file.write(text->data(), text->size());
561 if (n != text->size()) {
562 QMessageBox::critical(nullptr, "Error", "Error writing entire transcript.");
563 }
564 } else {
565 QMessageBox::critical(nullptr, "Error", "Unable to open file for writing.");
566 }
567 }
568 } else {
569 QMessageBox::warning(nullptr, "Warning", "Could not find appropriate window for scrollback.");
570 }
571 }},
572
573 // Don't use QKeySequence::FullScreen here, as that takes over
574 // F11 on X, and F11 can be bound by Glk; and it doesn't bind
575 // Alt-Enter on X, either, meaning the existing behavior would
576 // change. For Mac, use Meta+Ctrl+F, and Alt-Enter everywhere
577 // else.
578 #ifdef Q_OS_MAC
579 {{Qt::MetaModifier | Qt::ControlModifier, Qt::Key_F}, [this]{
580 #else
581 {{Qt::AltModifier, Qt::Key_Return}, [this]{
582 #endif
583 if (::window->isFullScreen()) {
584 if (m_fullscreen_from_maximized) {
585 ::window->showMaximized();
586 } else {
587 ::window->showNormal();
588 }
589 } else {
590 m_fullscreen_from_maximized = ::window->isMaximized();
591 ::window->showFullScreen();
592 }
593 }},
594 };
595
596 for (const auto &pair : sequences) {
597 if (event->matches(pair.first)) {
598 pair.second();
599 return;
600 }
601 }
602
603 try {
604 keys.at(std::make_pair(modmasked, event->key()))();
605 return;
606 } catch (const std::out_of_range &) {
607 }
608
609 handle_input(event->text(), false);
610 }
611
612 void garglk::View::mouseMoveEvent(QMouseEvent *event)
613 {
614 // hyperlinks and selection
615 if (gli_copyselect) {
616 setCursor(Qt::IBeamCursor);
617 gli_move_selection(event->pos().x(), event->pos().y());
618 } else {
619 if (gli_get_hyperlink(event->pos().x(), event->pos().y()) != 0) {
620 setCursor(Qt::PointingHandCursor);
621 } else {
622 unsetCursor();
623 }
624 }
625
626 event->accept();
627 }
628
629 void garglk::View::mousePressEvent(QMouseEvent *event)
630 {
631 if (event->button() == Qt::LeftButton) {
632 gli_input_handle_click(event->pos().x(), event->pos().y());
633 } else if (event->button() == Qt::MiddleButton) {
634 winclipreceive(QClipboard::Selection);
635 }
636
637 event->accept();
638 }
639
640 void garglk::View::mouseReleaseEvent(QMouseEvent *event)
641 {
642 if (event->button() == Qt::LeftButton) {
643 gli_copyselect = false;
644 unsetCursor();
645 winclipsend(QClipboard::Selection);
646 }
647
648 event->accept();
649 }
650
651 void garglk::View::wheelEvent(QWheelEvent *event)
652 {
653 QPoint pixels = event->pixelDelta();
654 QPoint degrees = event->angleDelta() / 8;
655 int change = 0;
656 bool page = event->modifiers() == Qt::ShiftModifier;
657
658 if (!pixels.isNull()) {
659 change = pixels.y();
660 } else if (!degrees.isNull()) {
661 change = degrees.y();
662 }
663
664 if (change == 0) {
665 return;
666 }
667
668 if (change > 0) {
669 if (page) {
670 gli_input_handle_key(keycode_PageUp);
671 } else {
672 gli_input_handle_key(keycode_MouseWheelUp);
673 }
674
675 } else if (change < 0) {
676 if (page) {
677 gli_input_handle_key(keycode_PageDown);
678 } else {
679 gli_input_handle_key(keycode_MouseWheelDown);
680 }
681 }
682
683 event->accept();
684 }
685
686 void wininit()
687 {
688 // QApplication takes argc by reference (because it might modify
689 // it), and thus requires it to live at least as long as the
690 // QApplication instance. This isn't really a Qt program in the
691 // normal sense, so doesn't need to provide Qt command-line
692 // arguments (such as -style). Create static dummy argument data
693 // here so it will live the entire life of the program and thus
694 // fulfill QApplication's requirements.
695 static int argc = 1;
696 static char *argv[] = {const_cast<char *>("gargoyle"), nullptr};
697 app = new QApplication(argc, argv);
698 QApplication::setApplicationVersion(GARGOYLE_VERSION);
699
700 // The convention on Windows & Mac is capitalized directories,
701 // whereas on Unix it's all lowercase. Qt uses the application name
702 // when finding paths with QStandardDirectories, so set the expected
703 // name based on operating system.
704 #if defined(Q_OS_WIN) || defined(Q_OS_MAC)
705 QApplication::setApplicationName("Gargoyle");
706 #else
707 QApplication::setApplicationName("gargoyle");
708 #endif
709
710 std::thread([]() {
711 while (true) {
712 std::this_thread::sleep_for(std::chrono::milliseconds(TICK_PERIOD_MILLIS));
713 process_events.store(true, std::memory_order_relaxed);
714 }
715 })
716 .detach();
717 }
718
719 void winopen()
720 {
721 window = new garglk::Window();
722
723 window->setMinimumSize(gli_wmarginx * 2, gli_wmarginy * 2);
724
725 int defw = gli_wmarginx * 2 + gli_cellw * gli_cols;
726 int defh = gli_wmarginy * 2 + gli_cellh * gli_rows;
727 QSize size(defw, defh);
728 if (gli_conf_save_window_size) {
729 auto stored_size = window->settings()->value("window/size");
730 if (stored_size.canConvert<QSize>()) {
731 size = stored_size.toSize();
732 }
733 }
734 window->resize(size);
735
736 if (gli_conf_save_window_location) {
737 auto position = window->settings()->value("window/position");
738 if (position.canConvert<QPoint>()) {
739 window->move(position.toPoint());
740 }
741 }
742
743 wintitle();
744
745 bool do_fullscreen = gli_conf_fullscreen;
746
747 if (gli_conf_save_window_location || gli_conf_save_window_size) {
748 auto fullscreen = window->settings()->value("window/fullscreen");
749 if (fullscreen.canConvert<bool>()) {
750 do_fullscreen = fullscreen.toBool();
751 }
752 }
753
754 if (do_fullscreen) {
755 window->showFullScreen();
756 } else {
757 window->show();
758 }
759 }
760
761 void wintitle()
762 {
763 QString title;
764
765 if (!gli_story_title.empty()) {
766 title = QString::fromStdString(gli_story_title);
767 } else if (!gli_story_name.empty()) {
768 title = QString("%1 - %2").arg(QString::fromStdString(gli_story_name), QString::fromStdString(gli_program_name));
769 } else {
770 title = QString::fromStdString(gli_program_name);
771 }
772
773 window->setWindowTitle(title);
774 }
775
776 void winrepaint(int x0, int y0, int x1, int y1)
777 {
778 refresh_needed = true;
779 }
780
781 bool windark()
782 {
783 #if GARGLK_CONFIG_HAS_QDBUS
784 // https://flatpak.github.io/xdg-desktop-portal/
785 QDBusInterface interface("org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Settings");
786 QDBusReply<QVariant> reply = interface.call("Read", "org.freedesktop.appearance", "color-scheme");
787 if (reply.isValid()) {
788 auto dbusvar = qvariant_cast<QDBusVariant>(reply.value());
789 QVariant result = dbusvar.variant();
790 #ifdef HAS_QT6
791 if (result.typeId() == QMetaType::Type::UInt) {
792 #else
793 if (result.type() == QVariant::UInt) {
794 #endif
795 return result.toUInt() == 1;
796 }
797 }
798 #endif
799
800 // From https://stackoverflow.com/a/69705673/1017090
801 // Is there really no builtin way in Qt to check this?
802 QLabel label("");
803 auto text_hsv_value = label.palette().color(QPalette::WindowText).value();
804 auto bg_hsv_value = label.palette().color(QPalette::Window).value();
805
806 return text_hsv_value > bg_hsv_value;
807 }
808
809 nonstd::optional<std::string> garglk::winfontpath(const std::string &filename)
810 {
811 return Format("{}/{}", QCoreApplication::applicationDirPath().toStdString(), filename);
812 }
813
814 std::string garglk::windatadir()
815 {
816 #if defined(_WIN32)
817 return garglk::winappdir().value_or(".");
818 #elif GARGLK_CONFIG_APPIMAGE
819 // For AppImages, hard-code the "known" path to app data (in this
820 // case that's <binary>/../share/gargoyle).
821 auto dir = QCoreApplication::applicationDirPath().toStdString();
822 return Format("{}/../share/gargoyle", dir);
823 #elif defined(GARGLK_CONFIG_DATADIR)
824 return GARGLK_CONFIG_DATADIR;
825 #else
826 return ".";
827 #endif
828 }
829
830 std::vector<std::string> garglk::winthemedirs()
831 {
832 std::vector<std::string> paths;
833
834 for (const auto &path : QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)) {
835 paths.push_back(path.toStdString() + "/themes");
836 }
837
838 #ifdef _WIN32
839 // On Windows, also search the executable's directory.
840 paths.push_back(QCoreApplication::applicationDirPath().toStdString() + "/themes");
841 #endif
842
843 #if GARGLK_CONFIG_APPIMAGE
844 paths.push_back(Format("{}/themes", garglk::windatadir()));
845 #endif
846
847 // QStandardPaths returns higher priority directories first: reverse
848 // so that higher priority directories come later, so entries there
849 // can overwrite earlier entries.
850 std::reverse(paths.begin(), paths.end());
851
852 return paths;
853 }
854
855 nonstd::optional<std::string> garglk::winlegacythemedir() {
856 #ifdef _WIN32
857 const char *appdata = std::getenv("APPDATA");
858 if (appdata == nullptr) {
859 return nonstd::nullopt;
860 }
861
862 return std::string(appdata) + "\\io.github.garglk\\Gargoyle\\themes";
863 #else
864 QString user_share = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);
865 QDir legacy_themes = QDir(user_share).filePath("io.github.garglk/Gargoyle/themes");
866 return legacy_themes.path().toStdString();
867 #endif
868 }
869
870 nonstd::optional<std::string> garglk::winappdir()
871 {
872 return QCoreApplication::applicationDirPath().toStdString();
873 }
874
875 bool garglk::winisfullscreen()
876 {
877 return window->isFullScreen();
878 }
879
880 void gli_tick()
881 {
882 // Qt needs to keep processing events even in the absence of calls
883 // to glk_select(). Processing Qt events is expensive, so should not
884 // be done each tick (which generally happens each VM instruction).
885 // Originally this waited at least 10ms between calls, but the mere
886 // act of checking a timer each iteration was too expensive. Now a
887 // separate thread sits and atomically updates "process_events"
888 // every 10ms, since checking this atomic variable is much faster
889 // than checking a timer.
890 if (process_events.load(std::memory_order_relaxed)) {
891 app->processEvents(QEventLoop::ExcludeUserInputEvents);
892 process_events.store(false, std::memory_order_relaxed);
893 }
894 }
895
896 void gli_select(event_t *event, bool polled)
897 {
898 gli_event_clearevent(event);
899
900 app->processEvents();
901
902 gli_dispatch_event(event, polled);
903
904 if (refresh_needed) {
905 window->refresh();
906 }
907
908 if (!polled) {
909 while (event->type == evtype_None && !window->timed_out()) {
910 if (refresh_needed) {
911 window->refresh();
912 }
913
914 app->processEvents(QEventLoop::WaitForMoreEvents);
915 gli_dispatch_event(event, polled);
916 }
917 }
918
919 if (event->type == evtype_None && window->timed_out()) {
920 gli_event_store(evtype_Timer, nullptr, 0, 0);
921 gli_dispatch_event(event, polled);
922 window->reset_timeout();
923 }
924
925 process_events.store(false, std::memory_order_relaxed);
926 }