Compare commits

..
37 Commits
Author SHA1 Message Date
yyc12345 e01718928c feat: remove checkerboard icon and change bottom toolbar 2026-07-25 12:23:00 +08:00
yyc12345 f5dbf44ec7 refactor: add possible optimization in graphics view 2026-07-25 12:15:17 +08:00
yyc12345 f55f8c731d refactor: use extensible design for fetching playlist from single file 2026-07-25 12:06:11 +08:00
yyc12345 4ed491c78a refactor: remove closeWindow because no one need it 2026-07-24 15:17:05 +08:00
yyc12345 b54cde2cbf refactor: remove "auto" in window-size behavior
- "auto" is not essential for our hard fork, so i simply remove it.
- remove all useless code after removing it.
- enlarge the min size of window because previous may trigger bad layout when showing navigation view.
2026-07-24 15:14:24 +08:00
yyc12345 b1d12cc406 refactor: remove double-click-window behavior
- remove double-click-window behavior entirely
- remove the icon of copy image action
2026-07-24 15:07:30 +08:00
yyc12345 aa13355966 refactor: use UI file for main window
- main window now use UI file for layout.
- remove all manual computed widget position code. use full Qt layout implementation instead.
- remove useless functions in main window
- change style changed slot as private
2026-07-24 14:57:41 +08:00
yyc12345 bd35a8c3e0 feat: use submenu in right click menu to reduce the height of menu panel 2026-07-15 21:59:30 +08:00
yyc12345 81413b51da feat: support explorer sort and hidden on Window
now playlist can use Windows Explorer's sort and hidden file display options to build it own for better browse experience on Windows
2026-07-14 13:22:23 +08:00
yyc12345 a01d640c27 refactor: remove frameless window
remove frameless window and merge it into mainwindow. because we do not need frameless and transparent window, so most of its functions are removed in previous commits.
2026-07-13 15:59:39 +08:00
yyc12345 16800df138 refactor: remove useless function in main window 2026-07-13 15:50:30 +08:00
yyc12345 7e8fd4ea21 refactor: use class member menu instead of runtime created menu 2026-07-13 15:47:17 +08:00
yyc12345 04fa491cd8 refactor: fully refactor playlist manager
- refactor playlist manager. remove useless qt model design.
- update action updator function.
2026-07-13 15:40:59 +08:00
yyc12345 dbf8c09368 feat: update action manager
- add and delete some actions in action manager.
- rename "fit to view" to "fit to screen".
- update main window right click menu and toolbar.
- use special state update slot in action manager instead of function located in main window.
2026-07-12 21:00:11 +08:00
yyc12345 369a17ed7d fix: fix typo about checkerboard 2026-07-12 19:54:37 +08:00
yyc12345 b19a4f8723 doc: add help for checkboard shift modifier 2026-07-09 13:06:14 +08:00
yyc12345 a8e5464e9f fix: remove useless mouse tracking setting 2026-07-08 20:18:52 +08:00
yyc12345 46f46480cb feat: change application style
- change default dark theme to light
- disable dark mode on windows 10 because Qt's windows 11 theme has bad support on windows 10 (icon display error)
- level required minimum qt version up to 6.5 for color schema.
2026-07-08 20:15:22 +08:00
yyc12345 c06f900ac5 refactor: use ui file to replace manual layout in metadata dialog 2026-07-07 12:16:36 +08:00
yyc12345 31303a20c7 refactor: set openExternalLinks in ui file instead of cpp file 2026-07-06 20:42:23 +08:00
yyc12345 319fd64fc6 refactor: use html resource to replace manual html in code 2026-07-06 20:34:41 +08:00
yyc12345 cdd0b764a7 refactor: use .ui to replace manual layout for aboutdialog 2026-07-06 09:44:38 +08:00
yyc12345 2a69482adb fix: change default settings
- change default settings to make the default behavior more close to legacy Windows Photo Viewer.
- remove redundant fallback for fetching enum settings.
2026-07-05 09:05:58 +08:00
yyc12345 fc3ef1cd7f fix: fix not thread-safe settings singleton.
fix not thread-safe way for fetching settings singleton.
remove qApp from Settings' parent, use nullptr replace it and leak it anyway.
because we may initialize it before initializing QApplication.
in that time, qApp is nullptr.
2026-07-05 08:57:49 +08:00
yyc12345 1de1517a81 refactor: use .ui file instead of manual layout in settings dialog.
- enable Qt UIC in cmake file.
- use .ui file to replace manually written layout in settings dialog.
2026-07-04 22:17:40 +08:00
yyc12345 04a4ab9bff feat: make the default window size bigger 2026-07-04 16:54:48 +08:00
yyc12345 011c1e858f feat: update the layout of main window.
update the layout of main window to make it looks more like
legacy Windows Photo Viewer.
2026-07-04 15:20:14 +08:00
yyc12345 4fe09757b3 revert: remove user custom shortcut 2026-07-04 14:59:02 +08:00
yyc12345 82f1f10cca refactor: rename m_gv to m_nav and m_graphicsView to m_gv for better abbr. 2026-07-04 14:35:28 +08:00
yyc12345 60eebea741 revert: remove the ability that drag window body to move 2026-07-04 14:32:20 +08:00
blumiaandyyc12345 9b151e2fea chore: update release info to 1.5.0 2026-07-03 19:37:54 +08:00
blumiaandyyc12345 9db9c3e9f7 chore(AppStream): add vcs-browser link 2026-07-03 19:37:03 +08:00
yyc12345 9a18a41b8f revert: remove OpacityHelper
- remove OpacityHelper
- remove all related animation
- now bottom toolbar and navigation view are always visible
2026-07-03 16:40:04 +08:00
yyc12345 c93ed94210 refactor: fully remove ToolButton because no one require it.
- fully remove ToolButton.
- make loadHidpiIcon as a static function in ActionManager because no outside function may call it.
2026-07-03 15:37:20 +08:00
yyc12345 f4d272e014 refactor: merge retranslateUi into setupAction in ActionManager 2026-07-03 15:12:15 +08:00
yyc12345 d536e8c611 refactor: move prev/next picture button to bottom toolbar. 2026-07-03 14:56:54 +08:00
yyc12345 c8dfccb460 revert: remove protected mode
protected mode is designed for borderless and transparent window.
it is not suit for the goal of this fork.
2026-07-03 14:32:36 +08:00
50 changed files with 2232 additions and 1860 deletions
+22 -10
View File
@@ -4,7 +4,7 @@
cmake_minimum_required(VERSION 3.16) cmake_minimum_required(VERSION 3.16)
project(pineapple-pictures VERSION 1.4.1) # don't forget to update NEWS file and AppStream metadata. project(pineapple-pictures VERSION 1.5.0) # don't forget to update NEWS file and AppStream metadata.
include(GNUInstallDirs) include(GNUInstallDirs)
include(FeatureSummary) include(FeatureSummary)
@@ -16,10 +16,11 @@ set (CMAKE_CXX_STANDARD 17)
set (CMAKE_CXX_STANDARD_REQUIRED ON) set (CMAKE_CXX_STANDARD_REQUIRED ON)
set (CMAKE_AUTOMOC ON) set (CMAKE_AUTOMOC ON)
set (CMAKE_AUTORCC ON) set (CMAKE_AUTORCC ON)
set (CMAKE_AUTOUIC ON)
find_package(QT NAMES Qt6 REQUIRED COMPONENTS Core) find_package(QT NAMES Qt6 REQUIRED COMPONENTS Core)
set (QT_MINIMUM_VERSION "6.4") set (QT_MINIMUM_VERSION "6.5")
find_package(Qt${QT_VERSION_MAJOR} ${QT_MINIMUM_VERSION} REQUIRED find_package(Qt${QT_VERSION_MAJOR} ${QT_MINIMUM_VERSION} REQUIRED
COMPONENTS Widgets Svg SvgWidgets LinguistTools COMPONENTS Widgets Svg SvgWidgets LinguistTools
@@ -38,15 +39,12 @@ endif ()
set (PPIC_CPP_FILES set (PPIC_CPP_FILES
app/main.cpp app/main.cpp
app/framelesswindow.cpp
app/mainwindow.cpp app/mainwindow.cpp
app/actionmanager.cpp app/actionmanager.cpp
app/graphicsview.cpp app/graphicsview.cpp
app/graphicsscene.cpp app/graphicsscene.cpp
app/bottombuttongroup.cpp app/bottombuttongroup.cpp
app/navigatorview.cpp app/navigatorview.cpp
app/opacityhelper.cpp
app/toolbutton.cpp
app/settings.cpp app/settings.cpp
app/settingsdialog.cpp app/settingsdialog.cpp
app/aboutdialog.cpp app/aboutdialog.cpp
@@ -54,20 +52,19 @@ set (PPIC_CPP_FILES
app/metadatadialog.cpp app/metadatadialog.cpp
app/exiv2wrapper.cpp app/exiv2wrapper.cpp
app/playlistmanager.cpp app/playlistmanager.cpp
app/shortcutedit.cpp
app/fileopeneventhandler.cpp app/fileopeneventhandler.cpp
app/playlistscout.cpp
app/playlistscouts/qtscout.cpp
app/playlistscouts/explorerscout.cpp
) )
set (PPIC_HEADER_FILES set (PPIC_HEADER_FILES
app/framelesswindow.h
app/mainwindow.h app/mainwindow.h
app/actionmanager.h app/actionmanager.h
app/graphicsview.h app/graphicsview.h
app/graphicsscene.h app/graphicsscene.h
app/bottombuttongroup.h app/bottombuttongroup.h
app/navigatorview.h app/navigatorview.h
app/opacityhelper.h
app/toolbutton.h
app/settings.h app/settings.h
app/settingsdialog.h app/settingsdialog.h
app/aboutdialog.h app/aboutdialog.h
@@ -75,8 +72,17 @@ set (PPIC_HEADER_FILES
app/metadatadialog.h app/metadatadialog.h
app/exiv2wrapper.h app/exiv2wrapper.h
app/playlistmanager.h app/playlistmanager.h
app/shortcutedit.h
app/fileopeneventhandler.h app/fileopeneventhandler.h
app/playlistscout.h
app/playlistscouts/qtscout.h
app/playlistscouts/explorerscout.h
)
set (PPIC_UI_FILES
app/settingsdialog.ui
app/aboutdialog.ui
app/metadatadialog.ui
app/mainwindow.ui
) )
set (PPIC_QRC_FILES set (PPIC_QRC_FILES
@@ -101,6 +107,7 @@ endif ()
add_executable (${EXE_NAME} add_executable (${EXE_NAME}
${PPIC_HEADER_FILES} ${PPIC_HEADER_FILES}
${PPIC_CPP_FILES} ${PPIC_CPP_FILES}
${PPIC_UI_FILES}
${PPIC_QRC_FILES} ${PPIC_QRC_FILES}
${PPIC_RC_FILES} ${PPIC_RC_FILES}
) )
@@ -117,6 +124,11 @@ else()
qt_add_translations(${EXE_NAME} ${ADD_TRANSLATIONS_ADDITIONAL_ARGS} TS_FILES ${PPIC_TS_FILES} QM_FILES_OUTPUT_VARIABLE PPIC_QM_FILES) qt_add_translations(${EXE_NAME} ${ADD_TRANSLATIONS_ADDITIONAL_ARGS} TS_FILES ${PPIC_TS_FILES} QM_FILES_OUTPUT_VARIABLE PPIC_QM_FILES)
endif() endif()
# YYC MARK:
# This is essential, otherwise Qt UIC generated UI header file
# can not find our header files if there are custom widgets inside UI file.
target_include_directories(${EXE_NAME} PRIVATE app/)
target_sources(${EXE_NAME} PRIVATE ${PPIC_QM_FILES}) target_sources(${EXE_NAME} PRIVATE ${PPIC_QM_FILES})
target_link_libraries (${EXE_NAME} Qt${QT_VERSION_MAJOR}::Widgets Qt${QT_VERSION_MAJOR}::Svg Qt${QT_VERSION_MAJOR}::SvgWidgets) target_link_libraries (${EXE_NAME} Qt${QT_VERSION_MAJOR}::Widgets Qt${QT_VERSION_MAJOR}::Svg Qt${QT_VERSION_MAJOR}::SvgWidgets)
+18
View File
@@ -1,3 +1,21 @@
Version 1.5.0
~~~~~~~~~~~~~
Released: 2026-07-04
Features:
* Introduced an optional titlebar that display file name and allows drag and double-click to move and toggle maximize state
* Windows: Now the application will use the system's built-in animation for open window animation
Bugfixes:
* Show empty url list should also reset window title to blank
Miscellaneous:
* Update translations
* Add vcs-browser link to AppStream metadata
Contributors:
Heimen Stoffels (vistaus), VenusGirl (VenusGirl)
Version 1.4.1 Version 1.4.1
~~~~~~~~~~~~~ ~~~~~~~~~~~~~
Released: 2026-04-05 Released: 2026-04-05
+59 -141
View File
@@ -3,176 +3,94 @@
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
#include "aboutdialog.h" #include "aboutdialog.h"
#include "ui_aboutdialog.h"
#include <QAbstractButton>
#include <QDialogButtonBox>
#include <QTextBrowser>
#include <QTabWidget>
#include <QVBoxLayout>
#include <QApplication> #include <QApplication>
#include <QLabel>
#include <QPushButton>
#include <QFile> #include <QFile>
using namespace Qt::Literals::StringLiterals; using namespace Qt::Literals::StringLiterals;
static QString loadEmbeddedHtml(QString&& path) {
QFile htmlFile(path);
bool canOpenFile = htmlFile.open(QIODevice::ReadOnly);
QByteArray htmlRawContent = canOpenFile ? htmlFile.readAll() : QByteArrayLiteral("");
return QString::fromUtf8(htmlRawContent);
}
AboutDialog::AboutDialog(QWidget *parent) AboutDialog::AboutDialog(QWidget *parent)
: QDialog(parent) : QDialog(parent), ui(new QT_PREPEND_NAMESPACE(Ui::AboutDialog))
, m_tabWidget(new QTabWidget)
, m_buttonBox(new QDialogButtonBox)
, m_helpTextEdit(new QTextBrowser)
, m_aboutTextEdit(new QTextBrowser)
, m_specialThanksTextEdit(new QTextBrowser)
, m_licenseTextEdit(new QTextBrowser)
, m_3rdPartyLibsTextEdit(new QTextBrowser)
{ {
this->setWindowTitle(tr("About")); ui->setupUi(this);
setWindowFlag(Qt::WindowContextHelpButtonHint, false);
const QStringList helpStr {
u"<p>%1</p>"_s.arg(tr("Launch application with image file path as argument to load the file.")),
u"<p>%1</p>"_s.arg(tr("Drag and drop image file onto the window is also supported.")),
u"<p>%1</p>"_s.arg(tr("None of the operations in this application will alter the pictures on disk.")),
u"<p>%1</p>"_s.arg(tr("Context menu option explanation:")),
u"<ul>"_s,
// blumia: Chain two arg() here since it seems lupdate will remove one of them if we use // blumia: Chain two arg() here since it seems lupdate will remove one of them if we use
// the old `arg(QCoreApp::translate(), tr())` way, but it's worth to mention // the old `arg(QCoreApp::translate(), tr())` way, but it's worth to mention
// `arg(QCoreApp::translate(), this->tr())` works, but lupdate will complain about the usage. // `arg(QCoreApp::translate(), this->tr())` works, but lupdate will complain about the usage.
u"<li><b>%1</b>:<br/>%2</li>"_s const QString HELP_HTML = loadEmbeddedHtml(u":/plain/help.html"_s)
.arg(QCoreApplication::translate("MainWindow", "Stay on top")) .arg(tr("General Help"))
.arg(tr("Make window stay on top of all other windows.")), .arg(tr("Launch application with image file path as argument to load the file."))
u"<li><b>%1</b>:<br/>%2</li>"_s .arg(tr("Passing in a single image file will load all the images in that directory and start viewing from that image."))
.arg(QCoreApplication::translate("MainWindow", "Protected mode")) .arg(tr("Passing in multiple image files lets you view them one by one."))
.arg(tr("Avoid close window accidentally. (eg. by double clicking the window)")), .arg(tr("Drag and drop image file onto the window is also supported."))
u"<li><b>%1</b>:<br/>%2</li>"_s .arg(tr("None of the operations in this application will alter the pictures on disk."))
.arg(QCoreApplication::translate("MainWindow", "Keep transformation", "The 'transformation' means the flip/rotation status that currently applied to the image view")) .arg(tr("Context Menu Help"))
.arg(tr("Avoid resetting the zoom/rotation/flip state that was applied to the image view when switching between images.")), .arg(tr("Keep transformation", "The same meaning of MainWindow's Keep transformation."))
u"</ul>"_s .arg(tr("Avoid resetting the zoom/rotation/flip state that was applied to the image view when switching between images."))
}; .arg(tr("Checkerboard", "The same meaning of MainWindow's Checkerboard."))
.arg(tr("Checkerboard light and dark theme can be adjusted in the configuration window, or easily switch it by holding Shift and clicking the button."));
const QStringList aboutStr { const QString APP_NAME_ARG = qApp->applicationDisplayName();
u"<center><img width='128' height='128' src=':/icons/app-icon.svg'/><br/>"_s, const QString APP_VERSION_ARG =
qApp->applicationDisplayName(),
(u"<br/>"_s + tr("Version: %1").arg(
#ifdef GIT_DESCRIBE_VERSION_STRING #ifdef GIT_DESCRIBE_VERSION_STRING
GIT_DESCRIBE_VERSION_STRING GIT_DESCRIBE_VERSION_STRING;
#else #else
qApp->applicationVersion() qApp->applicationVersion();
#endif // GIT_DESCRIBE_VERSION_STRING #endif // GIT_DESCRIBE_VERSION_STRING
)), const QString QT_VERSION_ARG = QT_VERSION_STR;
u"<hr/>"_s, const QString QT_ARCH_ARG = QSysInfo::buildCpuArchitecture();
tr("Copyright (c) %1 %2", "%1 is year, %2 is the name of copyright holder(s)") const QString ABOUT_HTML = loadEmbeddedHtml(u":/plain/about.html"_s)
.arg(u"2026"_s, u"<a href='https://github.com/BLumia'>@BLumia</a>"_s), .arg(APP_NAME_ARG)
u"<br/>"_s, .arg(tr("Version: %1").arg(APP_VERSION_ARG))
tr("Logo designed by %1").arg(u"<a href='https://github.com/Lovelyblack'>@Lovelyblack</a>"_s), .arg(tr("Upstream author"))
u"<hr/>"_s, .arg(tr("Hard fork author"))
tr("Built with Qt %1 (%2)").arg(QT_VERSION_STR, QSysInfo::buildCpuArchitecture()), .arg(tr("Logo designer"))
QStringLiteral("<br/><a href='%1'>%2</a>").arg("https://github.com/BLumia/pineapple-pictures", tr("Source code")), .arg(tr("Built with Qt %1 (%2)").arg(QT_VERSION_ARG).arg(QT_ARCH_ARG))
u"</center>"_s .arg(tr("Source code"));
};
QFile translaterHtml(u":/plain/translators.html"_s); const QString SPECIAL_THANKS_HTML = loadEmbeddedHtml(u":/plain/special-thanks.html"_s)
bool canOpenFile = translaterHtml.open(QIODevice::ReadOnly); .arg(tr("Contributors"))
const QByteArray & translatorList = canOpenFile ? translaterHtml.readAll() : QByteArrayLiteral(""); .arg(tr("List of contributors on GitHub"))
.arg(tr("Thanks to all people who contributed to this project."))
.arg(tr("Translators"))
.arg(tr("I would like to thank the following people who volunteered to translate this application."));
const QStringList specialThanksStr { const QString LICENSE_HTML = loadEmbeddedHtml(u":/plain/license.html"_s)
u"<h1 align='center'>%1</h1><a href='%2'>%3</a><p>%4</p>"_s.arg( .arg(tr("License"))
tr("Contributors"), .arg(tr("This application is released under the MIT License."))
u"https://github.com/BLumia/pineapple-pictures/graphs/contributors"_s, .arg(tr("License Verbatim Copy"));
tr("List of contributors on GitHub"),
tr("Thanks to all people who contributed to this project.")
),
u"<h1 align='center'>%1</h1><p>%2</p>%3"_s.arg( const QString THIRD_PARTY_LIBS_HTML = loadEmbeddedHtml(u":/plain/third-party-libs.html"_s)
tr("Translators"), .arg(tr("Third-party Libraries"))
tr("I would like to thank the following people who volunteered to translate this application."), .arg(tr("This application is built on the following free software libraries.", "Free as in freedom"))
translatorList .arg(tr("Some of them are optional and might not be included with this distribution depending on the build environment."));
)
};
const QStringList licenseStr { ui->m_helpTextEdit->setHtml(HELP_HTML);
u"<h1 align='center'><b>%1</b></h1>"_s.arg(tr("Your Rights")), ui->m_aboutTextEdit->setHtml(ABOUT_HTML);
u"<p>%1</p><p>%2</p><ul><li>%3</li><li>%4</li><li>%5</li><li>%6</li></ul>"_s.arg( ui->m_specialThanksTextEdit->setHtml(SPECIAL_THANKS_HTML);
tr("%1 is released under the MIT License."), // %1 ui->m_licenseTextEdit->setHtml(LICENSE_HTML);
tr("This license grants people a number of freedoms:"), // %2 ui->m_3rdPartyLibsTextEdit->setHtml(THIRD_PARTY_LIBS_HTML);
tr("You are free to use %1, for any purpose"), // %3
tr("You are free to distribute %1"), // %4
tr("You can study how %1 works and change it"), // %5
tr("You can distribute changed versions of %1") // %6
).arg(u"<i>%1</i>"_s),
u"<p>%1</p>"_s.arg(tr("The MIT license guarantees you this freedom. Nobody is ever permitted to take it away.")),
u"<hr/><pre>%2</pre>"_s
};
const QString mitLicense(QStringLiteral(R"(Expat/MIT License connect(ui->m_buttonBox, QOverload<QAbstractButton *>::of(&QDialogButtonBox::clicked), this, [this](QAbstractButton * btn){
Q_UNUSED(btn)
Copyright &copy; 2026 BLumia
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
)"));
const QStringList thirdPartyLibsStr {
u"<h1 align='center'><b>%1</b></h1>"_s.arg(tr("Third-party Libraries used by %1")),
tr("%1 is built on the following free software libraries:", "Free as in freedom"),
u"<ul>"_s,
#ifdef HAVE_EXIV2_VERSION
u"<li><a href='%1'>%2</a>: %3</li>"_s.arg("https://www.exiv2.org/", "Exiv2", "GPLv2"),
#endif // EXIV2_VERSION
u"<li><a href='%1'>%2</a>: %3</li>"_s.arg("https://www.qt.io/", "Qt", "GPLv2 + GPLv3 + LGPLv2.1 + LGPLv3"),
u"</ul>"_s
};
m_helpTextEdit->setText(helpStr.join('\n'));
m_aboutTextEdit->setText(aboutStr.join('\n'));
m_aboutTextEdit->setOpenExternalLinks(true);
m_specialThanksTextEdit->setText(specialThanksStr.join('\n'));
m_specialThanksTextEdit->setOpenExternalLinks(true);
m_licenseTextEdit->setText(licenseStr.join('\n').arg(qApp->applicationDisplayName(), mitLicense));
m_3rdPartyLibsTextEdit->setText(thirdPartyLibsStr.join('\n').arg(u"<i>%1</i>"_s).arg(qApp->applicationDisplayName()));
m_3rdPartyLibsTextEdit->setOpenExternalLinks(true);
m_tabWidget->addTab(m_helpTextEdit, tr("&Help"));
m_tabWidget->addTab(m_aboutTextEdit, tr("&About"));
m_tabWidget->addTab(m_specialThanksTextEdit, tr("&Special Thanks"));
m_tabWidget->addTab(m_licenseTextEdit, tr("&License"));
m_tabWidget->addTab(m_3rdPartyLibsTextEdit, tr("&Third-party Libraries"));
m_buttonBox->setStandardButtons(QDialogButtonBox::Close);
connect(m_buttonBox, QOverload<QAbstractButton *>::of(&QDialogButtonBox::clicked), this, [this](){
this->close(); this->close();
}); });
setLayout(new QVBoxLayout);
layout()->addWidget(m_tabWidget);
layout()->addWidget(m_buttonBox);
setMinimumSize(361, 161); // not sure why it complain "Unable to set geometry" setMinimumSize(361, 161); // not sure why it complain "Unable to set geometry"
setWindowFlag(Qt::WindowContextHelpButtonHint, false);
} }
AboutDialog::~AboutDialog() AboutDialog::~AboutDialog()
{ {
delete ui;
} }
QSize AboutDialog::sizeHint() const QSize AboutDialog::sizeHint() const
+4 -11
View File
@@ -8,9 +8,9 @@
#include <QDialog> #include <QDialog>
QT_BEGIN_NAMESPACE QT_BEGIN_NAMESPACE
class QTextBrowser; namespace Ui {
class QTabWidget; class AboutDialog;
class QDialogButtonBox; }
QT_END_NAMESPACE QT_END_NAMESPACE
class AboutDialog : public QDialog class AboutDialog : public QDialog
@@ -23,14 +23,7 @@ public:
QSize sizeHint() const override; QSize sizeHint() const override;
private: private:
QTabWidget * m_tabWidget = nullptr; QT_PREPEND_NAMESPACE(Ui::AboutDialog) *ui;
QDialogButtonBox * m_buttonBox = nullptr;
QTextBrowser * m_helpTextEdit = nullptr;
QTextBrowser * m_aboutTextEdit = nullptr;
QTextBrowser * m_specialThanksTextEdit = nullptr;
QTextBrowser * m_licenseTextEdit = nullptr;
QTextBrowser * m_3rdPartyLibsTextEdit = nullptr;
}; };
#endif // ABOUTDIALOG_H #endif // ABOUTDIALOG_H
+106
View File
@@ -0,0 +1,106 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>AboutDialog</class>
<widget class="QDialog" name="AboutDialog">
<property name="windowModality">
<enum>Qt::NonModal</enum>
</property>
<property name="windowTitle">
<string>About</string>
</property>
<property name="minimumSize">
<size>
<width>361</width>
<height>161</height>
</size>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QTabWidget" name="m_tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="helpTab">
<attribute name="title">
<string>&amp;Help</string>
</attribute>
<layout class="QVBoxLayout" name="helpTabLayout">
<item>
<widget class="QTextBrowser" name="m_helpTextEdit">
<property name="openExternalLinks">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="aboutTab">
<attribute name="title">
<string>&amp;About</string>
</attribute>
<layout class="QVBoxLayout" name="aboutTabLayout">
<item>
<widget class="QTextBrowser" name="m_aboutTextEdit">
<property name="openExternalLinks">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="specialThanksTab">
<attribute name="title">
<string>&amp;Special Thanks</string>
</attribute>
<layout class="QVBoxLayout" name="specialThanksTabLayout">
<item>
<widget class="QTextBrowser" name="m_specialThanksTextEdit">
<property name="openExternalLinks">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="licenseTab">
<attribute name="title">
<string>&amp;License</string>
</attribute>
<layout class="QVBoxLayout" name="licenseTabLayout">
<item>
<widget class="QTextBrowser" name="m_licenseTextEdit">
<property name="openExternalLinks">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="thirdPartyLibsTab">
<attribute name="title">
<string>&amp;Third-party Libraries</string>
</attribute>
<layout class="QVBoxLayout" name="thirdPartyLibsTabLayout">
<item>
<widget class="QTextBrowser" name="m_3rdPartyLibsTextEdit">
<property name="openExternalLinks">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="m_buttonBox">
<property name="standardButtons">
<set>QDialogButtonBox::Close</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
+137 -74
View File
@@ -4,19 +4,17 @@
#include "actionmanager.h" #include "actionmanager.h"
#include "settings.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "playlistmanager.h"
#include "graphicsview.h"
#include "graphicsscene.h"
#include <QGuiApplication> #include <QGuiApplication>
#include <QSvgRenderer> #include <QSvgRenderer>
#include <QPainter> #include <QPainter>
#define ICON_NAME(name)\ static QIcon loadHidpiIcon(const QString &resp, QSize sz = QSize(32, 32))
QStringLiteral(":/icons/" #name ".svg")
#define ACTION_NAME(s) QStringLiteral(STRIFY(s))
#define STRIFY(s) #s
QIcon ActionManager::loadHidpiIcon(const QString &resp, QSize sz)
{ {
QSvgRenderer r(resp); QSvgRenderer r(resp);
QPixmap pm = QPixmap(sz * qApp->devicePixelRatio()); QPixmap pm = QPixmap(sz * qApp->devicePixelRatio());
@@ -29,85 +27,110 @@ QIcon ActionManager::loadHidpiIcon(const QString &resp, QSize sz)
void ActionManager::setupAction(MainWindow *mainWindow) void ActionManager::setupAction(MainWindow *mainWindow)
{ {
// region: Action and Its Icon Creation
// Declare some convenient macros and lambdas.
#define ICON_NAME(name)\
QStringLiteral(":/icons/" #name ".svg")
#define ACTION_NAME(s) QStringLiteral(STRIFY(s))
#define STRIFY(s) #s
auto create_action = [] (QWidget *w, QAction **a, QString i, QString an, bool iconFromTheme = false) { auto create_action = [] (QWidget *w, QAction **a, QString i, QString an, bool iconFromTheme = false) {
*a = new QAction(w); *a = new QAction(w);
if (!i.isNull()) if (!i.isNull())
(*a)->setIcon(iconFromTheme ? QIcon::fromTheme(i) : ActionManager::loadHidpiIcon(i)); (*a)->setIcon(iconFromTheme ? QIcon::fromTheme(i) : loadHidpiIcon(i));
(*a)->setObjectName(an); (*a)->setObjectName(an);
w->addAction(*a); w->addAction(*a);
}; };
#define CREATE_NEW_ICON_ACTION(w, a, i) create_action(w, &a, ICON_NAME(i), ACTION_NAME(a))
/// This macro for register normal action.
#define CREATE_NEW_ACTION(w, a) create_action(w, &a, QString(), ACTION_NAME(a))
/// This macro for register Qt theme action.
#define CREATE_NEW_THEMEICON_ACTION(w, a, i) create_action(w, &a, QLatin1String(STRIFY(i)), ACTION_NAME(a), true)
/// This macro for register action with our custom icon.
#define CREATE_NEW_ICON_ACTION(w, a, i) create_action(w, &a, ICON_NAME(i), ACTION_NAME(a), false)
// TODO: We may replace all Qt theme icons to our custom icon for visual consistency.
// TODO: Some icons are invalid.
CREATE_NEW_ACTION(mainWindow, actionCopyPixmap);
CREATE_NEW_ACTION(mainWindow, actionCopyFilePath);
CREATE_NEW_ICON_ACTION(mainWindow, actionPrevPicture, go-previous);
CREATE_NEW_ICON_ACTION(mainWindow, actionNextPicture, go-next);
CREATE_NEW_ICON_ACTION(mainWindow, actionActualSize, zoom-original); CREATE_NEW_ICON_ACTION(mainWindow, actionActualSize, zoom-original);
CREATE_NEW_ICON_ACTION(mainWindow, actionToggleMaximize, view-fullscreen); CREATE_NEW_ICON_ACTION(mainWindow, actionFitToScreen, app-icon);
CREATE_NEW_ICON_ACTION(mainWindow, actionFitByWidth, app-icon);
CREATE_NEW_ICON_ACTION(mainWindow, actionFitByHeight, app-icon);
CREATE_NEW_ICON_ACTION(mainWindow, actionZoomIn, zoom-in); CREATE_NEW_ICON_ACTION(mainWindow, actionZoomIn, zoom-in);
CREATE_NEW_ICON_ACTION(mainWindow, actionZoomOut, zoom-out); CREATE_NEW_ICON_ACTION(mainWindow, actionZoomOut, zoom-out);
CREATE_NEW_ICON_ACTION(mainWindow, actionToggleCheckerboard, view-background-checkerboard);
CREATE_NEW_ICON_ACTION(mainWindow, actionFlipHorizontal, app-icon);
CREATE_NEW_ICON_ACTION(mainWindow, actionFlipVertical, app-icon);
CREATE_NEW_ICON_ACTION(mainWindow, actionRotateClockwise, object-rotate-right); CREATE_NEW_ICON_ACTION(mainWindow, actionRotateClockwise, object-rotate-right);
#undef CREATE_NEW_ICON_ACTION CREATE_NEW_ICON_ACTION(mainWindow, actionRotateCounterClockwise, app-icon);
#define CREATE_NEW_ACTION(w, a) create_action(w, &a, QString(), ACTION_NAME(a))
#define CREATE_NEW_THEMEICON_ACTION(w, a, i) create_action(w, &a, QLatin1String(STRIFY(i)), ACTION_NAME(a), true)
CREATE_NEW_ACTION(mainWindow, actionRotateCounterClockwise);
CREATE_NEW_ACTION(mainWindow, actionPrevPicture);
CREATE_NEW_ACTION(mainWindow, actionNextPicture);
CREATE_NEW_ACTION(mainWindow, actionToggleAvoidResetTransform);
CREATE_NEW_ACTION(mainWindow, actionToggleCheckerboard);
CREATE_NEW_ACTION(mainWindow, actionTogglePauseAnimation); CREATE_NEW_ACTION(mainWindow, actionTogglePauseAnimation);
CREATE_NEW_ACTION(mainWindow, actionAnimationNextFrame); CREATE_NEW_ACTION(mainWindow, actionAnimationNextFrame);
CREATE_NEW_THEMEICON_ACTION(mainWindow, actionOpen, document-open);
CREATE_NEW_ACTION(mainWindow, actionHorizontalFlip);
CREATE_NEW_ACTION(mainWindow, actionFitInView);
CREATE_NEW_ACTION(mainWindow, actionFitByWidth);
CREATE_NEW_THEMEICON_ACTION(mainWindow, actionCopyPixmap, edit-copy);
CREATE_NEW_ACTION(mainWindow, actionCopyFilePath);
CREATE_NEW_THEMEICON_ACTION(mainWindow, actionPaste, edit-paste);
CREATE_NEW_THEMEICON_ACTION(mainWindow, actionTrash, edit-delete); CREATE_NEW_THEMEICON_ACTION(mainWindow, actionTrash, edit-delete);
CREATE_NEW_ACTION(mainWindow, actionToggleProtectMode);
CREATE_NEW_ACTION(mainWindow, actionToggleAvoidResetTransform);
CREATE_NEW_ACTION(mainWindow, actionSettings);
CREATE_NEW_THEMEICON_ACTION(mainWindow, actionHelp, system-help);
CREATE_NEW_THEMEICON_ACTION(mainWindow, actionLocateInFileManager, system-file-manager); CREATE_NEW_THEMEICON_ACTION(mainWindow, actionLocateInFileManager, system-file-manager);
CREATE_NEW_THEMEICON_ACTION(mainWindow, actionProperties, document-properties); CREATE_NEW_THEMEICON_ACTION(mainWindow, actionProperties, document-properties);
CREATE_NEW_ACTION(mainWindow, actionQuitApp);
#undef CREATE_NEW_ACTION CREATE_NEW_ACTION(mainWindow, actionSettings);
CREATE_NEW_THEMEICON_ACTION(mainWindow, actionHelp, system-help);
// Remove convenient macros
#undef CREATE_NEW_ICON_ACTION
#undef CREATE_NEW_THEMEICON_ACTION #undef CREATE_NEW_THEMEICON_ACTION
#undef CREATE_NEW_ACTION
retranslateUi(mainWindow); #undef STRIFY
#undef ACTION_NAME
#undef ICON_NAME
QMetaObject::connectSlotsByName(mainWindow); // endregion
}
void ActionManager::retranslateUi(MainWindow *mainWindow) // region: Setup Checkable Action
{
Q_UNUSED(mainWindow);
actionOpen->setText(QCoreApplication::translate("MainWindow", "&Open...", nullptr)); actionToggleAvoidResetTransform->setCheckable(true);
actionToggleCheckerboard->setCheckable(true);
actionTogglePauseAnimation->setCheckable(true);
actionActualSize->setText(QCoreApplication::translate("MainWindow", "Actual size", nullptr)); // endregion
actionToggleMaximize->setText(QCoreApplication::translate("MainWindow", "Toggle maximize", nullptr));
actionZoomIn->setText(QCoreApplication::translate("MainWindow", "Zoom in", nullptr)); // region: Action Translatable Text Setup
actionZoomOut->setText(QCoreApplication::translate("MainWindow", "Zoom out", nullptr));
actionToggleCheckerboard->setText(QCoreApplication::translate("MainWindow", "Toggle Checkerboard", nullptr)); actionCopyPixmap->setText(QCoreApplication::translate("MainWindow", "Copy P&ixmap", nullptr));
actionRotateClockwise->setText(QCoreApplication::translate("MainWindow", "Rotate right", nullptr)); actionCopyFilePath->setText(QCoreApplication::translate("MainWindow", "Copy &File Path", nullptr));
actionRotateCounterClockwise->setText(QCoreApplication::translate("MainWindow", "Rotate left", nullptr));
actionPrevPicture->setText(QCoreApplication::translate("MainWindow", "Previous image", nullptr)); actionPrevPicture->setText(QCoreApplication::translate("MainWindow", "Previous image", nullptr));
actionNextPicture->setText(QCoreApplication::translate("MainWindow", "Next image", nullptr)); actionNextPicture->setText(QCoreApplication::translate("MainWindow", "Next image", nullptr));
actionActualSize->setText(QCoreApplication::translate("MainWindow", "Actual size", nullptr));
actionFitToScreen->setText(QCoreApplication::translate("MainWindow", "Fit to screen", nullptr));
actionFitByWidth->setText(QCoreApplication::translate("MainWindow", "Fit by width", nullptr));
actionFitByHeight->setText(QCoreApplication::translate("MainWindow", "Fit by height", nullptr));
actionZoomIn->setText(QCoreApplication::translate("MainWindow", "Zoom in", nullptr));
actionZoomOut->setText(QCoreApplication::translate("MainWindow", "Zoom out", nullptr));
actionFlipHorizontal->setText(QCoreApplication::translate("MainWindow", "Flip &Horizontally", nullptr));
actionFlipVertical->setText(QCoreApplication::translate("MainWindow", "Flip &Vertically", nullptr));
actionRotateClockwise->setText(QCoreApplication::translate("MainWindow", "Rotate right", nullptr));
actionRotateCounterClockwise->setText(QCoreApplication::translate("MainWindow", "Rotate left", nullptr));
actionToggleAvoidResetTransform->setText(QCoreApplication::translate("MainWindow", "Keep transformation", "The 'transformation' means the flip/rotation status that currently applied to the image view"));
actionToggleCheckerboard->setText(QCoreApplication::translate("MainWindow", "Toggle Checkerboard", nullptr));
actionTogglePauseAnimation->setText(QCoreApplication::translate("MainWindow", "Pause/Resume Animation", nullptr)); actionTogglePauseAnimation->setText(QCoreApplication::translate("MainWindow", "Pause/Resume Animation", nullptr));
actionAnimationNextFrame->setText(QCoreApplication::translate("MainWindow", "Animation Go to Next Frame", nullptr)); actionAnimationNextFrame->setText(QCoreApplication::translate("MainWindow", "Animation Go to Next Frame", nullptr));
actionHorizontalFlip->setText(QCoreApplication::translate("MainWindow", "Flip &Horizontally", nullptr));
actionFitInView->setText(QCoreApplication::translate("MainWindow", "Fit to view", nullptr));
actionFitByWidth->setText(QCoreApplication::translate("MainWindow", "Fit to width", nullptr));
actionCopyPixmap->setText(QCoreApplication::translate("MainWindow", "Copy P&ixmap", nullptr));
actionCopyFilePath->setText(QCoreApplication::translate("MainWindow", "Copy &File Path", nullptr));
actionPaste->setText(QCoreApplication::translate("MainWindow", "&Paste", nullptr));
actionTrash->setText(QCoreApplication::translate("MainWindow", "Move to Trash", nullptr)); actionTrash->setText(QCoreApplication::translate("MainWindow", "Move to Trash", nullptr));
actionToggleProtectMode->setText(QCoreApplication::translate("MainWindow", "Protected mode", nullptr));
actionToggleAvoidResetTransform->setText(QCoreApplication::translate("MainWindow", "Keep transformation", "The 'transformation' means the flip/rotation status that currently applied to the image view"));
actionSettings->setText(QCoreApplication::translate("MainWindow", "Configure...", nullptr));
actionHelp->setText(QCoreApplication::translate("MainWindow", "Help", nullptr));
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
actionLocateInFileManager->setText( actionLocateInFileManager->setText(
QCoreApplication::translate( QCoreApplication::translate(
@@ -119,33 +142,73 @@ void ActionManager::retranslateUi(MainWindow *mainWindow)
actionLocateInFileManager->setText(QCoreApplication::translate("MainWindow", "Show in directory", nullptr)); actionLocateInFileManager->setText(QCoreApplication::translate("MainWindow", "Show in directory", nullptr));
#endif // Q_OS_WIN #endif // Q_OS_WIN
actionProperties->setText(QCoreApplication::translate("MainWindow", "Properties", nullptr)); actionProperties->setText(QCoreApplication::translate("MainWindow", "Properties", nullptr));
actionQuitApp->setText(QCoreApplication::translate("MainWindow", "Quit", nullptr));
actionSettings->setText(QCoreApplication::translate("MainWindow", "Configure...", nullptr));
actionHelp->setText(QCoreApplication::translate("MainWindow", "Help", nullptr));
// endregion
QMetaObject::connectSlotsByName(mainWindow);
} }
void ActionManager::setupShortcuts() void ActionManager::setupShortcuts()
{ {
actionOpen->setShortcut(QKeySequence::Open); actionCopyPixmap->setShortcut(QKeySequence::Copy);
actionPrevPicture->setShortcuts({
QKeySequence(Qt::Key_Left),
QKeySequence(Qt::Key_PageUp),
});
actionNextPicture->setShortcuts({
QKeySequence(Qt::Key_Right),
QKeySequence(Qt::Key_PageDown),
});
actionActualSize->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_0)); actionActualSize->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_0));
actionZoomIn->setShortcut(QKeySequence::ZoomIn); actionZoomIn->setShortcut(QKeySequence::ZoomIn);
actionZoomOut->setShortcut(QKeySequence::ZoomOut); actionZoomOut->setShortcut(QKeySequence::ZoomOut);
actionPrevPicture->setShortcuts({
QKeySequence(Qt::Key_PageUp),
QKeySequence(Qt::Key_Left),
});
actionNextPicture->setShortcuts({
QKeySequence(Qt::Key_PageDown),
QKeySequence(Qt::Key_Right),
});
actionHorizontalFlip->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_R));
actionCopyPixmap->setShortcut(QKeySequence::Copy);
actionPaste->setShortcut(QKeySequence::Paste);
actionTrash->setShortcut(QKeySequence::Delete); actionTrash->setShortcut(QKeySequence::Delete);
actionHelp->setShortcut(QKeySequence::HelpContents);
actionSettings->setShortcut(QKeySequence::Preferences);
actionProperties->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_I)); actionProperties->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_I));
actionQuitApp->setShortcuts({
QKeySequence(Qt::Key_Space), actionSettings->setShortcut(QKeySequence::Preferences);
QKeySequence(Qt::Key_Escape) actionHelp->setShortcut(QKeySequence::HelpContents);
}); }
void ActionManager::updateActionState(PlaylistManager* pm, GraphicsView* gv)
{
const auto* gs = gv->scene();
const auto* settings = Settings::instance();
// Update copy actions
bool canCopy = pm->currentIndex().has_value();
actionCopyPixmap->setEnabled(canCopy);
actionCopyFilePath->setEnabled(canCopy);
// Update Prev/Next Picture State
const int galleryFileCount = pm->totalCount();
const bool loopGallery = settings->loopGallery();
actionPrevPicture->setEnabled(galleryFileCount > 1 && (loopGallery || !pm->isFirstIndex()));
actionNextPicture->setEnabled(galleryFileCount > 1 && (loopGallery || !pm->isLastIndex()));
// Update Avoid Reset Transform
actionToggleAvoidResetTransform->setChecked(gv->isAvoidResetTransform());
// Update Checkerboard
actionToggleCheckerboard->setChecked(gv->isCheckerboard());
// Update Animation Graphics Action
bool canPauseAnimation = gs->canPauseAnimation();
actionTogglePauseAnimation->setEnabled(canPauseAnimation);
if (canPauseAnimation) {
actionTogglePauseAnimation->setChecked(gs->isPauseAnimation());
} else {
actionTogglePauseAnimation->setChecked(false);
}
bool canSkipAnimation = gs->canSkipAnimationFrame();
actionAnimationNextFrame->setEnabled(canSkipAnimation);
// Update trash, located in explorer and properties.
bool hasLoadedFile = pm->currentIndex().has_value();
actionTrash->setEnabled(hasLoadedFile);
actionLocateInFileManager->setEnabled(hasLoadedFile);
actionProperties->setEnabled(hasLoadedFile);
} }
+25 -22
View File
@@ -8,7 +8,11 @@
#include <QAction> #include <QAction>
class MainWindow; class MainWindow;
class PlaylistManager;
class GraphicsView;
/// Action Manager is separated from Main Window
/// to manage all actions specifically.
class ActionManager class ActionManager
{ {
public: public:
@@ -16,42 +20,41 @@ public:
~ActionManager() = default; ~ActionManager() = default;
void setupAction(MainWindow * mainWindow); void setupAction(MainWindow * mainWindow);
void retranslateUi(MainWindow *MainWindow);
void setupShortcuts(); void setupShortcuts();
static QIcon loadHidpiIcon(const QString &resp, QSize sz = QSize(32, 32)); public slots:
void updateActionState(PlaylistManager* pm, GraphicsView* gv);
public: public:
QAction *actionOpen; QAction *actionCopyPixmap;
QAction *actionCopyFilePath;
QAction *actionActualSize;
QAction *actionToggleMaximize;
QAction *actionZoomIn;
QAction *actionZoomOut;
QAction *actionToggleCheckerboard;
QAction *actionRotateClockwise;
QAction *actionRotateCounterClockwise;
QAction *actionPrevPicture; QAction *actionPrevPicture;
QAction *actionNextPicture; QAction *actionNextPicture;
QAction *actionActualSize;
QAction *actionFitToScreen;
QAction *actionFitByWidth;
QAction *actionFitByHeight;
QAction *actionZoomIn;
QAction *actionZoomOut;
QAction *actionFlipHorizontal;
QAction *actionFlipVertical;
QAction *actionRotateClockwise;
QAction *actionRotateCounterClockwise;
QAction *actionToggleAvoidResetTransform;
QAction *actionToggleCheckerboard;
QAction *actionTogglePauseAnimation; QAction *actionTogglePauseAnimation;
QAction *actionAnimationNextFrame; QAction *actionAnimationNextFrame;
QAction *actionHorizontalFlip;
QAction *actionFitInView;
QAction *actionFitByWidth;
QAction *actionCopyPixmap;
QAction *actionCopyFilePath;
QAction *actionPaste;
QAction *actionTrash; QAction *actionTrash;
QAction *actionToggleProtectMode;
QAction *actionToggleAvoidResetTransform;
QAction *actionSettings;
QAction *actionHelp;
QAction *actionLocateInFileManager; QAction *actionLocateInFileManager;
QAction *actionProperties; QAction *actionProperties;
QAction *actionQuitApp;
QAction *actionSettings;
QAction *actionHelp;
}; };
#endif // ACTIONMANAGER_H #endif // ACTIONMANAGER_H
+21 -33
View File
@@ -4,54 +4,42 @@
#include "bottombuttongroup.h" #include "bottombuttongroup.h"
#include "opacityhelper.h"
#include <QToolButton> #include <QToolButton>
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QDebug> #include <QDebug>
BottomButtonGroup::BottomButtonGroup(const std::vector<QAction *> &actionList, QWidget *parent) BottomButtonGroup::BottomButtonGroup(QWidget *parent)
: QGroupBox (parent) : QGroupBox (parent)
, m_opacityHelper(new OpacityHelper(this))
{ {
QHBoxLayout * mainLayout = new QHBoxLayout(this); QHBoxLayout * mainLayout = new QHBoxLayout(this);
mainLayout->setSizeConstraint(QLayout::SetFixedSize); mainLayout->setSizeConstraint(QLayout::SetFixedSize);
this->setLayout(mainLayout); this->setLayout(mainLayout);
this->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); this->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
this->setStyleSheet("BottomButtonGroup {" this->setStyleSheet(R"#(
"border: 1px solid gray;" BottomButtonGroup {
"border-top-left-radius: 10px;" border-style: none;
"border-top-right-radius: 10px;" background: transparent;
"border-style: none;" }
"background-color:rgba(0,0,0,120)" QToolButton {
"}" background: transparent;
"QToolButton {" border-style: none;
"background:transparent;" }
"}" )#");
"QToolButton:!focus {" }
"border-style: none;"
"}");
auto newActionBtn = [this](QAction * action) -> QToolButton * { void BottomButtonGroup::addActions(const std::vector<QAction *> & actionList) {
for (QAction * action : actionList) {
// Create button
QToolButton * btn = new QToolButton(this); QToolButton * btn = new QToolButton(this);
btn->setDefaultAction(action); btn->setDefaultAction(action);
btn->setIconSize(QSize(32, 32)); btn->setIconSize(QSize(32, 32));
btn->setFixedSize(40, 40); btn->setFixedSize(40, 40);
return btn; // Add button
}; layout()->addWidget(btn);
for (QAction * action : actionList) {
addButton(newActionBtn(action));
} }
}
void BottomButtonGroup::setOpacity(qreal opacity, bool animated)
{
m_opacityHelper->setOpacity(opacity, animated);
}
void BottomButtonGroup::addButton(QAbstractButton *button)
{
layout()->addWidget(button);
updateGeometry(); updateGeometry();
} }
void BottomButtonGroup::addAction(QAction* action) {
addActions({action});
}
+3 -7
View File
@@ -10,18 +10,14 @@
#include <QAbstractButton> #include <QAbstractButton>
#include <QGroupBox> #include <QGroupBox>
class OpacityHelper;
class BottomButtonGroup : public QGroupBox class BottomButtonGroup : public QGroupBox
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit BottomButtonGroup(const std::vector<QAction *> & actionList, QWidget *parent = nullptr); explicit BottomButtonGroup(QWidget *parent = nullptr);
void setOpacity(qreal opacity, bool animated = true); void addActions(const std::vector<QAction *> & actionList);
void addButton(QAbstractButton *button); void addAction(QAction* action);
private:
OpacityHelper * m_opacityHelper;
}; };
#endif // BOTTOMBUTTONGROUP_H #endif // BOTTOMBUTTONGROUP_H
-32
View File
@@ -1,32 +0,0 @@
// SPDX-FileCopyrightText: 2022 Gary Wang <wzc782970009@gmail.com>
// SPDX-FileCopyrightText: 2023 Tad Young <yyc12321@outlook.com>
//
// SPDX-License-Identifier: MIT
#include "framelesswindow.h"
#include <QMouseEvent>
#include <QHoverEvent>
#include <QApplication>
#include <QVBoxLayout>
#include <QWindow>
FramelessWindow::FramelessWindow(QWidget *parent)
: QWidget(parent)
, m_centralLayout(new QVBoxLayout(this))
{
this->setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);
m_centralLayout->setContentsMargins(QMargins());
}
void FramelessWindow::setCentralWidget(QWidget *widget)
{
if (m_centralWidget) {
m_centralLayout->removeWidget(m_centralWidget);
m_centralWidget->deleteLater();
}
m_centralLayout->addWidget(widget);
m_centralWidget = widget;
}
-27
View File
@@ -1,27 +0,0 @@
// SPDX-FileCopyrightText: 2022 Gary Wang <wzc782970009@gmail.com>
//
// SPDX-License-Identifier: MIT
#ifndef FRAMELESSWINDOW_H
#define FRAMELESSWINDOW_H
#include <QWidget>
QT_BEGIN_NAMESPACE
class QVBoxLayout;
QT_END_NAMESPACE
class FramelessWindow : public QWidget
{
Q_OBJECT
public:
explicit FramelessWindow(QWidget *parent = nullptr);
void setCentralWidget(QWidget * widget);
private:
QVBoxLayout * m_centralLayout = nullptr;
QWidget * m_centralWidget = nullptr; // just a pointer, doesn't take the ownership.
};
#endif // FRAMELESSWINDOW_H
+82 -10
View File
@@ -6,6 +6,9 @@
#include "settings.h" #include "settings.h"
#include <QStyleHints>
#include <QOperatingSystemVersion>
#include <QGuiApplication>
#include <QGraphicsSceneMouseEvent> #include <QGraphicsSceneMouseEvent>
#include <QMimeData> #include <QMimeData>
#include <QDebug> #include <QDebug>
@@ -16,6 +19,33 @@
#include <QMovie> #include <QMovie>
#include <QPainter> #include <QPainter>
static const QColor& ColorSchemaToTextForeground(Qt::ColorScheme colorScheme) {
// YYC MARK:
// If we are using Windows 10 and lower system or Qt which do not support "Windows 11"
// theme (lower than Qt 6.7), we should only support light mode.
// Because Qt's dark-mode-aware "Windows 11" theme is only well-supported on Windows 11.
#if defined(Q_OS_WIN)
#if QT_VERSION < QT_VERSION_CHECK(6, 7, 0)
colorScheme = Qt::ColorScheme::Light;
#else
if (QOperatingSystemVersion::current() < QOperatingSystemVersion::Windows11) {
colorScheme = Qt::ColorScheme::Light;
}
#endif // QT_VERSION < QT_VERSION_CHECK(6, 7, 0)
#endif // defined(Q_OS_WIN)
switch (colorScheme) {
case Qt::ColorScheme::Dark:
static QColor WHITE = QColor("White");
return WHITE;
case Qt::ColorScheme::Light:
case Qt::ColorScheme::Unknown:
default:
static QColor BLACK = QColor("Black");
return BLACK;
}
}
class PGraphicsPixmapItem : public QGraphicsPixmapItem class PGraphicsPixmapItem : public QGraphicsPixmapItem
{ {
public: public:
@@ -99,7 +129,8 @@ private:
GraphicsScene::GraphicsScene(QObject *parent) GraphicsScene::GraphicsScene(QObject *parent)
: QGraphicsScene(parent) : QGraphicsScene(parent)
{ {
showText(tr("Drag image here")); showText(tr("Drag image here", "The same meaning of MainWindow's hint."));
connect(qGuiApp->styleHints(), &QStyleHints::colorSchemeChanged, this, &GraphicsScene::updateStyle);
} }
GraphicsScene::~GraphicsScene() GraphicsScene::~GraphicsScene()
@@ -121,7 +152,7 @@ void GraphicsScene::showText(const QString &text)
{ {
this->clear(); this->clear();
QGraphicsTextItem * textItem = this->addText(text); QGraphicsTextItem * textItem = this->addText(text);
textItem->setDefaultTextColor(QColor("White")); textItem->setDefaultTextColor(ColorSchemaToTextForeground(qGuiApp->styleHints()->colorScheme()));
m_theThing = textItem; m_theThing = textItem;
this->setSceneRect(m_theThing->boundingRect()); this->setSceneRect(m_theThing->boundingRect());
} }
@@ -169,27 +200,57 @@ bool GraphicsScene::trySetTransformationMode(Qt::TransformationMode mode, float
return false; return false;
} }
/// Fetch graphics item as our custom animated item.
/// Return nullptr means this item is not animated item.
static PGraphicsMovieItem* fetchAnimatedItem(QGraphicsItem *item) {
return qgraphicsitem_cast<PGraphicsMovieItem *>(item);
}
bool GraphicsScene::canPauseAnimation() const {
return fetchAnimatedItem(m_theThing) != nullptr;
}
bool GraphicsScene::isPauseAnimation() const {
auto* animatedItem = fetchAnimatedItem(m_theThing);
if (animatedItem != nullptr) {
return animatedItem->movie()->state() == QMovie::Paused;
} else {
return false;
}
}
bool GraphicsScene::togglePauseAnimation() bool GraphicsScene::togglePauseAnimation()
{ {
PGraphicsMovieItem * animatedItem = qgraphicsitem_cast<PGraphicsMovieItem *>(m_theThing); auto* animatedItem = fetchAnimatedItem(m_theThing);
if (animatedItem) { if (animatedItem != nullptr) {
animatedItem->movie()->setPaused(animatedItem->movie()->state() != QMovie::Paused); animatedItem->movie()->setPaused(animatedItem->movie()->state() != QMovie::Paused);
return true; return true;
} } else {
return false; return false;
}
}
bool GraphicsScene::canSkipAnimationFrame() const {
return isPauseAnimation();
} }
bool GraphicsScene::skipAnimationFrame(int delta) bool GraphicsScene::skipAnimationFrame(int delta)
{ {
PGraphicsMovieItem * animatedItem = qgraphicsitem_cast<PGraphicsMovieItem *>(m_theThing); auto* animatedItem = fetchAnimatedItem(m_theThing);
if (animatedItem) {
// Only paused animated item can skip frame
if (animatedItem == nullptr) {
return false;
}
if (animatedItem->movie()->state() != QMovie::Paused) {
return false;
}
// Perform skip
const int frameCount = animatedItem->movie()->frameCount(); const int frameCount = animatedItem->movie()->frameCount();
const int currentFrame = animatedItem->movie()->currentFrameNumber(); const int currentFrame = animatedItem->movie()->currentFrameNumber();
const int targetFrame = (currentFrame + delta) % frameCount; const int targetFrame = (currentFrame + delta) % frameCount;
animatedItem->movie()->setPaused(true);
return animatedItem->movie()->jumpToFrame(targetFrame); return animatedItem->movie()->jumpToFrame(targetFrame);
}
return false;
} }
QPixmap GraphicsScene::renderToPixmap() QPixmap GraphicsScene::renderToPixmap()
@@ -206,3 +267,14 @@ QPixmap GraphicsScene::renderToPixmap()
return pixmap; return pixmap;
} }
void GraphicsScene::updateStyle(Qt::ColorScheme colorScheme) {
Q_UNUSED(colorScheme)
QGraphicsItem * item = this->m_theThing;
if (item == nullptr) return;
QGraphicsTextItem * textItem = qgraphicsitem_cast<QGraphicsTextItem*>(item);
if (textItem == nullptr) return;
textItem->setDefaultTextColor(ColorSchemaToTextForeground(colorScheme));
}
+15
View File
@@ -21,11 +21,26 @@ public:
bool trySetTransformationMode(Qt::TransformationMode mode, float scaleHint); bool trySetTransformationMode(Qt::TransformationMode mode, float scaleHint);
/// Check whether current thing is animation.
/// Only animation thing can be paused.
bool canPauseAnimation() const;
/// Check whether we are pasuing an animation graphics.
bool isPauseAnimation() const;
/// Toggle animation graphics pause state.
/// Return true for successfully toggle, otherwise false.
bool togglePauseAnimation(); bool togglePauseAnimation();
/// Check whether we can skip animation frame.
/// Only paused animation graphics can skip frame.
bool canSkipAnimationFrame() const;
/// Skip paused animation graphics with given frame.
/// Return true for successfully skip, otherwise false.
bool skipAnimationFrame(int delta = 1); bool skipAnimationFrame(int delta = 1);
QPixmap renderToPixmap(); QPixmap renderToPixmap();
private slots:
void updateStyle(Qt::ColorScheme colorScheme);
private: private:
QGraphicsItem * m_theThing = nullptr; QGraphicsItem * m_theThing = nullptr;
}; };
+66 -13
View File
@@ -7,6 +7,8 @@
#include "graphicsscene.h" #include "graphicsscene.h"
#include "settings.h" #include "settings.h"
#include <QStyleHints>
#include <QOperatingSystemVersion>
#include <QDebug> #include <QDebug>
#include <QColorSpace> #include <QColorSpace>
#include <QMouseEvent> #include <QMouseEvent>
@@ -23,11 +25,12 @@ GraphicsView::GraphicsView(QWidget *parent)
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setResizeAnchor(QGraphicsView::AnchorUnderMouse); setResizeAnchor(QGraphicsView::AnchorUnderMouse);
setTransformationAnchor(QGraphicsView::AnchorUnderMouse); setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
setStyleSheet("background-color: rgba(0, 0, 0, 220);"
"border-radius: 3px;");
setAcceptDrops(false); setAcceptDrops(false);
setCheckerboardEnabled(false); setCheckerboardEnabled(false);
updateStyle(qGuiApp->styleHints()->colorScheme());
connect(qGuiApp->styleHints(), &QStyleHints::colorSchemeChanged, this, &GraphicsView::updateStyle);
connect(horizontalScrollBar(), &QScrollBar::valueChanged, this, &GraphicsView::viewportRectChanged); connect(horizontalScrollBar(), &QScrollBar::valueChanged, this, &GraphicsView::viewportRectChanged);
connect(verticalScrollBar(), &QScrollBar::valueChanged, this, &GraphicsView::viewportRectChanged); connect(verticalScrollBar(), &QScrollBar::valueChanged, this, &GraphicsView::viewportRectChanged);
} }
@@ -137,7 +140,7 @@ void GraphicsView::resetTransform()
void GraphicsView::zoomView(qreal scaleFactor) void GraphicsView::zoomView(qreal scaleFactor)
{ {
m_enableFitInView = false; m_enableFitToScreen = false;
scale(scaleFactor, scaleFactor); scale(scaleFactor, scaleFactor);
applyTransformationModeByScaleFactor(); applyTransformationModeByScaleFactor();
emit navigatorViewRequired(!isThingSmallerThanWindowWith(transform()), transform()); emit navigatorViewRequired(!isThingSmallerThanWindowWith(transform()), transform());
@@ -221,6 +224,19 @@ void GraphicsView::fitByOrientation(Qt::Orientation ori, bool scaleDownOnly)
QRectF originalScene = sceneRect(); QRectF originalScene = sceneRect();
QTransform currentTransform = transform(); QTransform currentTransform = transform();
// TODO:
// I guess following code may be optimized by matrix arithmetic operation.
// There is an AI given solution. But I didn't use it.
// Because I want to keep the same behavior of upstream.
// // Horizontal fit: Let the position of top center of viewport, (cx, 0), be inversely mapped to scene.
// // And compensate the behavior of `centerOn` which put given point to the center of viewport.
// QTransform inv = currentTransform.inverted();
// QPointF viewCx = viewport()->rect().center().x();
// QPointF viewCy = viewport()->rect().center().y();
// // The target is viewport top center. Its y=0, so `centerOn` required scene point is (viewCx, -viewCy).
// centerOn(inv.map(QPointF(viewCx, -viewCy)));
if (ori == Qt::Horizontal) { if (ori == Qt::Horizontal) {
// For horizontal fit (fit by width), position at top (for tall images) // For horizontal fit (fit by width), position at top (for tall images)
// Find the scene point that corresponds to the top-center of the transformed image // Find the scene point that corresponds to the top-center of the transformed image
@@ -273,7 +289,7 @@ void GraphicsView::fitByOrientation(Qt::Orientation ori, bool scaleDownOnly)
centerOn(sceneLeftCenter); centerOn(sceneLeftCenter);
} }
m_enableFitInView = false; m_enableFitToScreen = false;
applyTransformationModeByScaleFactor(); applyTransformationModeByScaleFactor();
emit navigatorViewRequired(!isThingSmallerThanWindowWith(transform()), transform()); emit navigatorViewRequired(!isThingSmallerThanWindowWith(transform()), transform());
@@ -296,7 +312,7 @@ void GraphicsView::displayScene()
emit navigatorViewRequired(false, transform()); emit navigatorViewRequired(false, transform());
} }
m_enableFitInView = true; m_enableFitToScreen = true;
m_firstUserMediaLoaded = true; m_firstUserMediaLoaded = true;
} }
@@ -310,12 +326,12 @@ bool GraphicsView::isSceneBiggerThanView() const
} }
// Automately do fit in view when viewport(window) smaller than image original size. // Automately do fit in view when viewport(window) smaller than image original size.
void GraphicsView::setEnableAutoFitInView(bool enable) void GraphicsView::setEnableAutoFitToScreen(bool enable)
{ {
m_enableFitInView = enable; m_enableFitToScreen = enable;
} }
bool GraphicsView::avoidResetTransform() const bool GraphicsView::isAvoidResetTransform() const
{ {
return m_avoidResetTransform; return m_avoidResetTransform;
} }
@@ -325,6 +341,15 @@ void GraphicsView::setAvoidResetTransform(bool avoidReset)
m_avoidResetTransform = avoidReset; m_avoidResetTransform = avoidReset;
} }
bool GraphicsView::isCheckerboard() const {
return m_checkerboardEnabled;
}
void GraphicsView::toggleCheckerboard(bool invertCheckerboardColor)
{
setCheckerboardEnabled(!m_checkerboardEnabled, invertCheckerboardColor);
}
inline double zeroOrOne(double number) inline double zeroOrOne(double number)
{ {
return qFuzzyIsNull(number) ? 0 : (number > 0 ? 1 : -1); return qFuzzyIsNull(number) ? 0 : (number > 0 ? 1 : -1);
@@ -339,9 +364,37 @@ QTransform GraphicsView::resetScale(const QTransform & orig)
orig.dx(), orig.dy()); orig.dx(), orig.dy());
} }
void GraphicsView::toggleCheckerboard(bool invertCheckerboardColor) void GraphicsView::updateStyle(Qt::ColorScheme colorScheme) {
{ // YYC MARK:
setCheckerboardEnabled(!m_checkerboardEnabled, invertCheckerboardColor); // If we are using Windows 10 and lower system or Qt which do not support "Windows 11"
// theme (lower than Qt 6.7), we should only support light mode.
// Because Qt's dark-mode-aware "Windows 11" theme is only well-supported on Windows 11.
#if defined(Q_OS_WIN)
#if QT_VERSION < QT_VERSION_CHECK(6, 7, 0)
colorScheme = Qt::ColorScheme::Light;
#else
if (QOperatingSystemVersion::current() < QOperatingSystemVersion::Windows11) {
colorScheme = Qt::ColorScheme::Light;
}
#endif // QT_VERSION < QT_VERSION_CHECK(6, 7, 0)
#endif // defined(Q_OS_WIN)
switch (colorScheme) {
case Qt::ColorScheme::Dark:
setStyleSheet(R"#(
border-style: none;
background-color: black;
)#");
break;
case Qt::ColorScheme::Light:
case Qt::ColorScheme::Unknown:
default:
setStyleSheet(R"#(
border-style: none;
background-color: white;
)#");
break;
}
} }
void GraphicsView::mousePressEvent(QMouseEvent *event) void GraphicsView::mousePressEvent(QMouseEvent *event)
@@ -387,11 +440,11 @@ void GraphicsView::wheelEvent(QWheelEvent *event)
void GraphicsView::resizeEvent(QResizeEvent *event) void GraphicsView::resizeEvent(QResizeEvent *event)
{ {
if (m_enableFitInView) { if (m_enableFitToScreen) {
bool originalSizeSmallerThanWindow = isThingSmallerThanWindowWith(resetScale(transform())); bool originalSizeSmallerThanWindow = isThingSmallerThanWindowWith(resetScale(transform()));
if (originalSizeSmallerThanWindow && scaleFactor() >= 1) { if (originalSizeSmallerThanWindow && scaleFactor() >= 1) {
// no longer need to do fitInView() // no longer need to do fitInView()
// but we leave the m_enableFitInView value unchanged in case // but we leave the m_enableToScreen value unchanged in case
// user resize down the window again. // user resize down the window again.
} else if (originalSizeSmallerThanWindow && scaleFactor() < 1) { } else if (originalSizeSmallerThanWindow && scaleFactor() < 1) {
resetScale(); resetScale();
+8 -5
View File
@@ -38,19 +38,22 @@ public:
void displayScene(); void displayScene();
bool isSceneBiggerThanView() const; bool isSceneBiggerThanView() const;
void setEnableAutoFitInView(bool enable = true); void setEnableAutoFitToScreen(bool enable = true);
bool avoidResetTransform() const; bool isAvoidResetTransform() const;
void setAvoidResetTransform(bool avoidReset); void setAvoidResetTransform(bool avoidReset);
bool isCheckerboard() const;
void toggleCheckerboard(bool invertCheckerboardColor = false);
static QTransform resetScale(const QTransform & orig); static QTransform resetScale(const QTransform & orig);
signals: signals:
void navigatorViewRequired(bool required, QTransform transform); void navigatorViewRequired(bool required, QTransform transform);
void viewportRectChanged(); void viewportRectChanged();
public slots: private slots:
void toggleCheckerboard(bool invertCheckerboardColor = false); void updateStyle(Qt::ColorScheme colorScheme);
private: private:
void mousePressEvent(QMouseEvent * event) override; void mousePressEvent(QMouseEvent * event) override;
@@ -69,7 +72,7 @@ private:
// Consider switch to 3 state for "no fit", "always fit" and "fit when view is smaller"? // Consider switch to 3 state for "no fit", "always fit" and "fit when view is smaller"?
// ... or even more? e.g. "fit/snap width" things... // ... or even more? e.g. "fit/snap width" things...
// Currently it's "no fit" when it's false and "fit when view is smaller" when it's true. // Currently it's "no fit" when it's false and "fit when view is smaller" when it's true.
bool m_enableFitInView = false; bool m_enableFitToScreen = false;
bool m_avoidResetTransform = false; bool m_avoidResetTransform = false;
bool m_checkerboardEnabled = false; bool m_checkerboardEnabled = false;
bool m_useLightCheckerboard = false; bool m_useLightCheckerboard = false;
+5 -12
View File
@@ -4,7 +4,6 @@
#include "mainwindow.h" #include "mainwindow.h"
#include "playlistmanager.h"
#include "settings.h" #include "settings.h"
#ifdef Q_OS_MACOS #ifdef Q_OS_MACOS
@@ -68,21 +67,19 @@ int main(int argc, char *argv[])
a.installEventFilter(fileOpenEventHandler); a.installEventFilter(fileOpenEventHandler);
a.connect(fileOpenEventHandler, &FileOpenEventHandler::fileOpen, [&w](const QUrl & url){ a.connect(fileOpenEventHandler, &FileOpenEventHandler::fileOpen, [&w](const QUrl & url){
if (w.isHidden()) { if (w.isHidden()) {
w.setWindowOpacity(1);
w.showNormal(); w.showNormal();
} else { } else {
w.activateWindow(); w.activateWindow();
} }
w.showUrls({url}); w.showFiles({url});
w.initWindowSize(); w.initWindowSize();
}); });
// Handle dock icon clicks to show hidden window // Handle dock icon clicks to show hidden window
a.connect(&a, &QApplication::applicationStateChanged, [&w](Qt::ApplicationState state) { a.connect(&a, &QApplication::applicationStateChanged, [&w](Qt::ApplicationState state) {
if (state == Qt::ApplicationActive && w.isHidden()) { if (state == Qt::ApplicationActive && w.isHidden()) {
w.showUrls({}); w.showFiles({});
w.galleryCurrent(true, true); w.galleryCurrent(false);
w.setWindowOpacity(1);
w.showNormal(); w.showNormal();
w.raise(); w.raise();
w.activateWindow(); w.activateWindow();
@@ -90,12 +87,8 @@ int main(int argc, char *argv[])
}); });
#endif // Q_OS_MACOS #endif // Q_OS_MACOS
QStringList urlStrList = parser.positionalArguments(); QStringList fileList = parser.positionalArguments();
QList<QUrl> && urlList = PlaylistManager::convertToUrlList(urlStrList); w.showFiles(fileList);
if (!urlList.isEmpty()) {
w.showUrls(urlList);
}
w.initWindowSize(); w.initWindowSize();
+247 -544
View File
@@ -3,9 +3,9 @@
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
#include "mainwindow.h" #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "settings.h" #include "settings.h"
#include "toolbutton.h"
#include "bottombuttongroup.h" #include "bottombuttongroup.h"
#include "graphicsview.h" #include "graphicsview.h"
#include "navigatorview.h" #include "navigatorview.h"
@@ -47,179 +47,165 @@
using namespace Qt::Literals::StringLiterals; using namespace Qt::Literals::StringLiterals;
MainWindow::MainWindow(QWidget *parent) MainWindow::MainWindow(QWidget *parent)
: FramelessWindow(parent) : QWidget(parent)
, ui(new QT_PREPEND_NAMESPACE(Ui::MainWindow))
, m_am(new ActionManager) , m_am(new ActionManager)
, m_pm(new PlaylistManager(this)) , m_pm(new PlaylistManager(this))
, m_fileSystemWatcher(new QFileSystemWatcher(this)) , m_fileSystemWatcher(new QFileSystemWatcher(this))
{ {
this->setAttribute(Qt::WA_TranslucentBackground, true); ui->setupUi(this);
this->setMinimumSize(350, 330); this->setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);
// YYC MARK:
// Blumis set original value is 350 x 330.
// It is too small for modern device,
// so I level it up to SVGA resolution 800 x 600.
this->setMinimumSize(800, 600);
this->setWindowIcon(QIcon(u":/icons/app-icon.svg"_s)); this->setWindowIcon(QIcon(u":/icons/app-icon.svg"_s));
this->setMouseTracking(true);
this->setAcceptDrops(true); this->setAcceptDrops(true);
m_pm->setAutoLoadFilterSuffixes(supportedImageFormats()); // Initialize playlist manager
m_pm->setAllowedSuffixes(supportedImageFormats());
// Initialize graphics scene
GraphicsScene * scene = new GraphicsScene(this); GraphicsScene * scene = new GraphicsScene(this);
// Setup graphics view (main photo view)
m_graphicsView = new GraphicsView(this); ui->m_gv->setScene(scene);
m_graphicsView->setScene(scene); // Setup navigator view (right-bottom corner thumbnail view)
this->setCentralWidget(m_graphicsView); ui->m_nav->setScene(scene);
ui->m_nav->setMainView(ui->m_gv);
m_gv = new NavigatorView(this); ui->m_nav->fitInView(ui->m_nav->sceneRect(), Qt::KeepAspectRatio);
m_gv->setFixedSize(220, 160); // Binding graphics and navigator views signals
m_gv->setScene(scene); connect(ui->m_gv, &GraphicsView::navigatorViewRequired,
m_gv->setMainView(m_graphicsView);
m_gv->fitInView(m_gv->sceneRect(), Qt::KeepAspectRatio);
connect(m_graphicsView, &GraphicsView::navigatorViewRequired,
this, [this](bool required, const QTransform & tf){ this, [this](bool required, const QTransform & tf){
m_gv->setTransform(GraphicsView::resetScale(tf)); ui->m_nav->setTransform(GraphicsView::resetScale(tf));
m_gv->fitInView(m_gv->sceneRect(), Qt::KeepAspectRatio); ui->m_nav->fitInView(ui->m_nav->sceneRect(), Qt::KeepAspectRatio);
m_gv->setVisible(required); ui->m_nav->setVisible(required);
m_gv->updateMainViewportRegion(); ui->m_navPH->setVisible(required);
ui->m_nav->updateMainViewportRegion();
}); });
connect(ui->m_gv, &GraphicsView::viewportRectChanged,
ui->m_nav, &NavigatorView::updateMainViewportRegion);
connect(m_graphicsView, &GraphicsView::viewportRectChanged, // Setup action manager
m_gv, &NavigatorView::updateMainViewportRegion);
m_prevButton = new ToolButton(false, m_graphicsView);
m_prevButton->setIconSize(QSize(75, 75));
m_prevButton->setIconResourcePath(":/icons/go-previous.svg");
m_prevButton->setVisible(false);
m_prevButton->setOpacity(0, false);
m_nextButton = new ToolButton(false, m_graphicsView);
m_nextButton->setIconSize(QSize(75, 75));
m_nextButton->setIconResourcePath(":/icons/go-next.svg");
m_nextButton->setVisible(false);
m_nextButton->setOpacity(0, false);
connect(m_prevButton, &QAbstractButton::clicked,
this, &MainWindow::galleryPrev);
connect(m_nextButton, &QAbstractButton::clicked,
this, &MainWindow::galleryNext);
m_am->setupAction(this); m_am->setupAction(this);
// Setup bottom button group
m_bottomButtonGroup = new BottomButtonGroup({ ui->m_bottomButtonGroup->addActions({
m_am->actionActualSize, m_am->actionActualSize,
m_am->actionToggleMaximize, m_am->actionFitToScreen,
m_am->actionZoomIn, m_am->actionZoomIn,
m_am->actionZoomOut, m_am->actionZoomOut,
m_am->actionToggleCheckerboard, m_am->actionPrevPicture,
m_am->actionRotateClockwise m_am->actionProperties,
}, this); m_am->actionNextPicture,
m_am->actionRotateCounterClockwise,
m_am->actionRotateClockwise,
m_am->actionFlipHorizontal,
m_am->actionFlipVertical,
});
// Setup right click menus
{
ui->m_subMenuCopy->addAction(m_am->actionCopyPixmap);
ui->m_subMenuCopy->addAction(m_am->actionCopyFilePath);
}
{
ui->m_subMenuTransform->addAction(m_am->actionActualSize);
ui->m_subMenuTransform->addAction(m_am->actionFitToScreen);
ui->m_subMenuTransform->addAction(m_am->actionFitByWidth);
ui->m_subMenuTransform->addAction(m_am->actionFitByHeight);
ui->m_subMenuTransform->addAction(m_am->actionZoomIn);
ui->m_subMenuTransform->addAction(m_am->actionZoomOut);
m_bottomButtonGroup->setOpacity(0, false); ui->m_subMenuTransform->addSeparator();
m_gv->setOpacity(0, false);
connect(m_pm, &PlaylistManager::totalCountChanged, this, &MainWindow::updateGalleryButtonsVisibility); ui->m_subMenuTransform->addAction(m_am->actionFlipHorizontal);
ui->m_subMenuTransform->addAction(m_am->actionFlipVertical);
ui->m_subMenuTransform->addAction(m_am->actionRotateClockwise);
ui->m_subMenuTransform->addAction(m_am->actionRotateCounterClockwise);
}
{
ui->m_menu->addMenu(ui->m_subMenuCopy);
connect(m_pm->model(), &PlaylistModel::modelReset, this, std::bind(&MainWindow::galleryCurrent, this, false, false)); ui->m_menu->addSeparator();
connect(m_pm, &PlaylistManager::currentIndexChanged, this, std::bind(&MainWindow::galleryCurrent, this, true, false));
ui->m_menu->addAction(m_am->actionPrevPicture);
ui->m_menu->addAction(m_am->actionNextPicture);
ui->m_menu->addSeparator();
ui->m_menu->addMenu(ui->m_subMenuTransform);
ui->m_menu->addSeparator();
ui->m_menu->addAction(m_am->actionToggleAvoidResetTransform);
ui->m_menu->addAction(m_am->actionToggleCheckerboard);
ui->m_menu->addAction(m_am->actionTogglePauseAnimation);
ui->m_menu->addAction(m_am->actionAnimationNextFrame);
ui->m_menu->addSeparator();
ui->m_menu->addAction(m_am->actionTrash);
ui->m_menu->addAction(m_am->actionLocateInFileManager);
ui->m_menu->addAction(m_am->actionProperties);
ui->m_menu->addSeparator();
ui->m_menu->addAction(m_am->actionSettings);
ui->m_menu->addAction(m_am->actionHelp);
}
// Connect playlist manager and file watcher signals for photo browsering.
connect(m_pm, &PlaylistManager::playlistChanged, this, std::bind(&MainWindow::updateActionState, this));
connect(m_pm, &PlaylistManager::playlistChanged, this, std::bind(&MainWindow::galleryCurrent, this, false));
connect(m_pm, &PlaylistManager::currentIndexChanged, this, std::bind(&MainWindow::galleryCurrent, this, false));
connect(m_fileSystemWatcher, &QFileSystemWatcher::fileChanged, this, [this](){ connect(m_fileSystemWatcher, &QFileSystemWatcher::fileChanged, this, [this](){
QTimer::singleShot(500, this, std::bind(&MainWindow::galleryCurrent, this, false, true)); QTimer::singleShot(500, this, std::bind(&MainWindow::galleryCurrent, this, true));
}); });
QShortcut * fullscreenShorucut = new QShortcut(QKeySequence(QKeySequence::FullScreen), this); // Change window location
connect(fullscreenShorucut, &QShortcut::activated,
this, &MainWindow::toggleFullscreen);
centerWindow(); centerWindow();
QTimer::singleShot(0, this, [this](){ QTimer::singleShot(0, this, [this](){
m_am->setupShortcuts(); m_am->setupShortcuts();
Settings::instance()->applyUserShortcuts(this);
}); });
} }
MainWindow::~MainWindow() MainWindow::~MainWindow()
{ {
delete ui;
} }
void MainWindow::showUrls(const QList<QUrl> &urls) void MainWindow::showFiles(const QStringList &files)
{ {
if (!urls.isEmpty()) { m_pm->loadPlaylist(files);
const QUrl & firstUrl = urls.first(); ui->m_nav->fitInView(ui->m_nav->sceneRect(), Qt::KeepAspectRatio);
if (urls.count() == 1) { }
const QString lowerCaseUrlPath(firstUrl.path().toLower());
if (lowerCaseUrlPath.endsWith(".m3u8") || lowerCaseUrlPath.endsWith(".m3u")) {
m_pm->loadM3U8Playlist(firstUrl);
galleryCurrent(true, true);
return;
}
}
m_graphicsView->showFileFromPath(firstUrl.toLocalFile());
m_pm->loadPlaylist(urls);
} else {
m_graphicsView->showText(tr("File url list is empty"));
m_pm->setPlaylist(urls);
return;
}
m_gv->fitInView(m_gv->sceneRect(), Qt::KeepAspectRatio); void MainWindow::showFiles(const QList<QUrl>& urls)
{
m_pm->loadPlaylist(urls);
ui->m_nav->fitInView(ui->m_nav->sceneRect(), Qt::KeepAspectRatio);
} }
void MainWindow::initWindowSize() void MainWindow::initWindowSize()
{ {
switch (Settings::instance()->initWindowSizeBehavior()) { switch (Settings::instance()->initWindowSizeBehavior()) {
case Settings::WindowSizeBehavior::Auto:
adjustWindowSizeBySceneRect();
break;
case Settings::WindowSizeBehavior::Maximized: case Settings::WindowSizeBehavior::Maximized:
showMaximized(); showMaximized();
break; break;
case Settings::WindowSizeBehavior::Windowed: case Settings::WindowSizeBehavior::Windowed:
default:
showNormal(); showNormal();
break; break;
default:
adjustWindowSizeBySceneRect();
break;
} }
} }
void MainWindow::adjustWindowSizeBySceneRect()
{
if (m_pm->totalCount() < 1) return;
QSize sceneSize = m_graphicsView->sceneRect().toRect().size();
QSize sceneSizeWithMargins = sceneSize + QSize(130, 125);
if (m_graphicsView->scaleFactor() < 1 || size().expandedTo(sceneSizeWithMargins) != size()) {
// if it scaled down by the resize policy:
QSize screenSize = qApp->screenAt(QCursor::pos())->availableSize();
if (screenSize.expandedTo(sceneSize) == screenSize) {
// we can show the picture by increase the window size.
QSize finalSize = (screenSize.expandedTo(sceneSizeWithMargins) == screenSize) ?
sceneSizeWithMargins : screenSize;
// We have a very reasonable sizeHint() value ;P
this->resize(finalSize.expandedTo(this->sizeHint()));
// We're sure the window can display the whole thing with 1:1 scale.
// The old window size may cause fitInView call from resize() and the
// above resize() call won't reset the scale back to 1:1, so we
// just call resetScale() here to ensure the thing is no longer scaled.
m_graphicsView->resetScale();
centerWindow();
} else {
// toggle maximum
showMaximized();
}
}
}
// can be empty if it is NOT from a local file.
QUrl MainWindow::currentImageFileUrl() const
{
return m_pm->urlByIndex(m_pm->curIndex());
}
void MainWindow::clearGallery() void MainWindow::clearGallery()
{ {
m_pm->setPlaylist({}); m_pm->clearPlaylist();
} }
void MainWindow::galleryPrev() void MainWindow::galleryPrev()
@@ -227,10 +213,9 @@ void MainWindow::galleryPrev()
const bool loopGallery = Settings::instance()->loopGallery(); const bool loopGallery = Settings::instance()->loopGallery();
if (!loopGallery && m_pm->isFirstIndex()) return; if (!loopGallery && m_pm->isFirstIndex()) return;
QModelIndex index = m_pm->previousIndex(); auto index = m_pm->previousIndex();
if (index.isValid()) { if (index.has_value()) {
m_pm->setCurrentIndex(index); m_pm->setCurrentIndex(*index);
m_graphicsView->showFileFromPath(m_pm->localFileByIndex(index));
} }
} }
@@ -239,31 +224,29 @@ void MainWindow::galleryNext()
const bool loopGallery = Settings::instance()->loopGallery(); const bool loopGallery = Settings::instance()->loopGallery();
if (!loopGallery && m_pm->isLastIndex()) return; if (!loopGallery && m_pm->isLastIndex()) return;
QModelIndex index = m_pm->nextIndex(); auto index = m_pm->nextIndex();
if (index.isValid()) { if (index.has_value()) {
m_pm->setCurrentIndex(index); m_pm->setCurrentIndex(*index);
m_graphicsView->showFileFromPath(m_pm->localFileByIndex(index));
} }
} }
// Only use this to update minor information. void MainWindow::galleryCurrent(bool fromFileWatcher)
void MainWindow::galleryCurrent(bool showLoadImageHintWhenEmpty, bool reloadImage)
{ {
QModelIndex index = m_pm->curIndex(); auto index = m_pm->currentIndex();
bool shouldResetfileWatcher = true; if (index.has_value()) {
if (index.isValid()) { QString localFilePath = m_pm->localFileByIndex(*index);
const QString & localFilePath(m_pm->localFileByIndex(index)); ui->m_gv->showFileFromPath(localFilePath);
if (reloadImage) m_graphicsView->showFileFromPath(localFilePath); if (!fromFileWatcher) {
shouldResetfileWatcher = !updateFileWatcher(localFilePath); updateFileWatcher(localFilePath);
setWindowTitle(m_pm->urlByIndex(index).fileName()); setWindowTitle(m_pm->urlByIndex(*index).fileName());
} else if (showLoadImageHintWhenEmpty && m_pm->totalCount() <= 0) { }
m_graphicsView->showText(QCoreApplication::translate("GraphicsScene", "Drag image here")); } else {
ui->m_gv->showText(tr("Drag image here"));
setWindowTitle(QString()); setWindowTitle(QString());
updateFileWatcher();
} }
updateGalleryButtonsVisibility(); updateActionState();
if (shouldResetfileWatcher) updateFileWatcher();
} }
QStringList MainWindow::supportedImageFormats() QStringList MainWindow::supportedImageFormats()
@@ -279,106 +262,6 @@ QStringList MainWindow::supportedImageFormats()
return formatFilters; return formatFilters;
} }
void MainWindow::showEvent(QShowEvent *event)
{
updateWidgetsPosition();
return FramelessWindow::showEvent(event);
}
void MainWindow::enterEvent(QEnterEvent *event)
{
m_bottomButtonGroup->setOpacity(1);
m_gv->setOpacity(1);
m_prevButton->setOpacity(1);
m_nextButton->setOpacity(1);
return FramelessWindow::enterEvent(event);
}
void MainWindow::leaveEvent(QEvent *event)
{
m_bottomButtonGroup->setOpacity(0);
m_gv->setOpacity(0);
m_prevButton->setOpacity(0);
m_nextButton->setOpacity(0);
return FramelessWindow::leaveEvent(event);
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton && !isMaximized()) {
m_clickedOnWindow = true;
m_oldMousePos = event->pos();
// qDebug() << m_oldMousePos << m_graphicsView->transform().m11()
// << m_graphicsView->transform().m22() << m_graphicsView->matrix().m12();
event->accept();
}
return FramelessWindow::mousePressEvent(event);
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton && m_clickedOnWindow && !isMaximized() && !isFullScreen()) {
if (!window()->windowHandle()->startSystemMove()) {
move(event->globalPosition().toPoint() - m_oldMousePos);
}
event->accept();
}
return FramelessWindow::mouseMoveEvent(event);
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
m_clickedOnWindow = false;
// It seems the forward/back mouse button won't generate a key event [1] so we can't use
// QShortcut or QKeySequence to indicate these shortcuts, so we do it here.
// Reference:
// [1]: https://codereview.qt-project.org/c/qt/qtbase/+/177475
if (event->button() == Qt::ForwardButton || event->button() == Qt::BackButton) {
event->button() == Qt::BackButton ? galleryPrev() : galleryNext();
event->accept();
}
return FramelessWindow::mouseReleaseEvent(event);
}
void MainWindow::mouseDoubleClickEvent(QMouseEvent *event)
{
// The forward/back mouse button can also used to trigger a mouse double-click event
// Since we use that for gallery navigation so we ignore these two buttons.
if (event->buttons() & Qt::ForwardButton || event->buttons() & Qt::BackButton) {
return;
}
switch (Settings::instance()->doubleClickBehavior()) {
case Settings::DoubleClickBehavior::Close:
quitAppAction();
event->accept();
break;
case Settings::DoubleClickBehavior::Maximize:
toggleMaximize();
event->accept();
break;
case Settings::DoubleClickBehavior::FullScreen:
toggleFullscreen();
event->accept();
break;
case Settings::DoubleClickBehavior::Ignore:
break;
}
// blumia: don't call parent constructor here, seems it will cause mouse move
// event get called even if we set event->accept();
// return QMainWindow::mouseDoubleClickEvent(event);
}
void MainWindow::wheelEvent(QWheelEvent *event) void MainWindow::wheelEvent(QWheelEvent *event)
{ {
QPoint numDegrees = event->angleDelta() / 8; QPoint numDegrees = event->angleDelta() / 8;
@@ -411,99 +294,26 @@ void MainWindow::wheelEvent(QWheelEvent *event)
} }
event->accept(); event->accept();
} else { } else {
FramelessWindow::wheelEvent(event); QWidget::wheelEvent(event);
} }
} }
void MainWindow::resizeEvent(QResizeEvent *event)
{
updateWidgetsPosition();
return FramelessWindow::resizeEvent(event);
}
void MainWindow::contextMenuEvent(QContextMenuEvent *event) void MainWindow::contextMenuEvent(QContextMenuEvent *event)
{ {
QMenu * menu = new QMenu; ui->m_menu->exec(mapToGlobal(event->pos()));
QMenu * copyMenu = new QMenu(tr("&Copy"));
QUrl currentFileUrl = currentImageFileUrl();
QAction * copyPixmap = m_am->actionCopyPixmap; return QWidget::contextMenuEvent(event);
QAction * copyFilePath = m_am->actionCopyFilePath;
copyMenu->setIcon(QIcon::fromTheme(u"edit-copy"_s));
copyMenu->addAction(copyPixmap);
if (currentFileUrl.isValid()) {
copyMenu->addAction(copyFilePath);
}
QAction * paste = m_am->actionPaste;
QAction * trash = m_am->actionTrash;
QAction * protectedMode = m_am->actionToggleProtectMode;
protectedMode->setCheckable(true);
protectedMode->setChecked(m_protectedMode);
QAction * avoidResetTransform = m_am->actionToggleAvoidResetTransform;
avoidResetTransform->setCheckable(true);
avoidResetTransform->setChecked(m_graphicsView->avoidResetTransform());
QAction * toggleSettings = m_am->actionSettings;
QAction * helpAction = m_am->actionHelp;
QAction * propertiesAction = m_am->actionProperties;
#if 0
menu->addAction(m_am->actionOpen);
#endif // 0
if (copyMenu->actions().count() == 1) {
menu->addActions(copyMenu->actions());
} else {
menu->addMenu(copyMenu);
}
if (canPaste()) {
menu->addAction(paste);
}
menu->addSeparator();
menu->addAction(m_am->actionHorizontalFlip);
#if 0
menu->addAction(m_am->actionFitInView);
menu->addAction(m_am->actionFitByWidth);
#endif // 0
menu->addSeparator();
menu->addAction(protectedMode);
menu->addAction(avoidResetTransform);
menu->addSeparator();
menu->addAction(toggleSettings);
menu->addAction(helpAction);
if (currentFileUrl.isValid()) {
menu->addSeparator();
if (currentFileUrl.isLocalFile()) {
menu->addAction(trash);
menu->addAction(m_am->actionLocateInFileManager);
}
menu->addAction(propertiesAction);
}
menu->exec(mapToGlobal(event->pos()));
menu->deleteLater();
copyMenu->deleteLater();
return FramelessWindow::contextMenuEvent(event);
} }
void MainWindow::dragEnterEvent(QDragEnterEvent *event) void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{ {
if (event->mimeData()->hasUrls() || event->mimeData()->hasImage() || event->mimeData()->hasText()) { if (event->mimeData()->hasUrls()) {
event->acceptProposedAction(); event->acceptProposedAction();
} else { } else {
event->ignore(); event->ignore();
} }
return FramelessWindow::dragEnterEvent(event); return QWidget::dragEnterEvent(event);
} }
void MainWindow::dragMoveEvent(QDragMoveEvent *event) void MainWindow::dragMoveEvent(QDragMoveEvent *event)
@@ -516,26 +326,10 @@ void MainWindow::dropEvent(QDropEvent *event)
event->acceptProposedAction(); event->acceptProposedAction();
const QMimeData * mimeData = event->mimeData(); const QMimeData * mimeData = event->mimeData();
if (mimeData->hasUrls()) { if (mimeData->hasUrls()) {
const QList<QUrl> &urls = mimeData->urls(); showFiles(mimeData->urls());
if (urls.isEmpty()) {
m_graphicsView->showText(tr("File url list is empty"));
} else { } else {
showUrls(urls); ui->m_gv->showText(tr("Not supported mimedata: %1").arg(mimeData->formats().first()));
}
} else if (mimeData->hasImage()) {
QImage img = qvariant_cast<QImage>(mimeData->imageData());
QPixmap pixmap = QPixmap::fromImage(img);
if (pixmap.isNull()) {
m_graphicsView->showText(tr("Image data is invalid"));
} else {
m_graphicsView->showImage(pixmap);
}
} else if (mimeData->hasText()) {
m_graphicsView->showText(mimeData->text());
} else {
m_graphicsView->showText(tr("Not supported mimedata: %1").arg(mimeData->formats().first()));
} }
} }
@@ -551,54 +345,9 @@ void MainWindow::centerWindow()
); );
} }
void MainWindow::closeWindow()
{
}
void MainWindow::updateWidgetsPosition()
{
m_prevButton->move(25, (height() - m_prevButton->sizeHint().height()) / 2);
m_nextButton->move(width() - m_nextButton->sizeHint().width() - 25,
(height() - m_prevButton->sizeHint().height()) / 2);
m_bottomButtonGroup->move((width() - m_bottomButtonGroup->width()) / 2,
height() - m_bottomButtonGroup->height());
m_gv->move(width() - m_gv->width(), height() - m_gv->height());
}
void MainWindow::toggleProtectedMode()
{
m_protectedMode = !m_protectedMode;
updateGalleryButtonsVisibility();
}
void MainWindow::toggleAvoidResetTransform() void MainWindow::toggleAvoidResetTransform()
{ {
m_graphicsView->setAvoidResetTransform(!m_graphicsView->avoidResetTransform()); ui->m_gv->setAvoidResetTransform(!ui->m_gv->isAvoidResetTransform());
}
bool MainWindow::canPaste() const
{
const QMimeData * clipboardData = QApplication::clipboard()->mimeData();
if (clipboardData->hasImage()) {
return true;
} else if (clipboardData->hasText()) {
QString clipboardText(clipboardData->text());
if (clipboardText.startsWith("PICTURE:")) {
QString maybeFilename(clipboardText.mid(8));
if (QFile::exists(maybeFilename)) {
return true;
}
}
}
return false;
}
void MainWindow::quitAppAction(bool force)
{
if (!m_protectedMode || force) {
closeWindow();
}
} }
void MainWindow::toggleFullscreen() void MainWindow::toggleFullscreen()
@@ -624,140 +373,21 @@ QSize MainWindow::sizeHint() const
return QSize(710, 530); return QSize(710, 530);
} }
void MainWindow::on_actionOpen_triggered() // region: Action Trigger
{
QStringList picturesLocations = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation);
QUrl pictureUrl = picturesLocations.isEmpty() ? QUrl::fromLocalFile(picturesLocations.first())
: QUrl::fromLocalFile(QDir::homePath());
QList<QUrl> urls(QFileDialog::getOpenFileUrls(this, QString(), pictureUrl));
if (!urls.isEmpty()) {
showUrls(urls);
}
}
void MainWindow::on_actionActualSize_triggered()
{
m_graphicsView->resetScale();
m_graphicsView->setEnableAutoFitInView(false);
}
void MainWindow::on_actionToggleMaximize_triggered()
{
toggleMaximize();
}
void MainWindow::on_actionZoomIn_triggered()
{
if (m_graphicsView->scaleFactor() < 1000) {
m_graphicsView->zoomView(1.25);
}
}
void MainWindow::on_actionZoomOut_triggered()
{
m_graphicsView->zoomView(0.8);
}
void MainWindow::on_actionHorizontalFlip_triggered()
{
m_graphicsView->flipView();
}
void MainWindow::on_actionFitInView_triggered()
{
m_graphicsView->fitInView(m_gv->sceneRect(), Qt::KeepAspectRatio);
m_graphicsView->setEnableAutoFitInView(m_graphicsView->scaleFactor() <= 1);
}
void MainWindow::on_actionFitByWidth_triggered()
{
m_graphicsView->fitByOrientation();
}
void MainWindow::on_actionCopyPixmap_triggered() void MainWindow::on_actionCopyPixmap_triggered()
{ {
QClipboard *cb = QApplication::clipboard(); QClipboard *cb = QApplication::clipboard();
cb->setPixmap(m_graphicsView->scene()->renderToPixmap()); cb->setPixmap(ui->m_gv->scene()->renderToPixmap());
} }
void MainWindow::on_actionCopyFilePath_triggered() void MainWindow::on_actionCopyFilePath_triggered()
{ {
QUrl currentFileUrl(currentImageFileUrl()); auto index = m_pm->currentIndex();
if (currentFileUrl.isValid()) { if (!index.has_value()) return;
QClipboard *cb = QApplication::clipboard(); QClipboard *cb = QApplication::clipboard();
cb->setText(currentFileUrl.toLocalFile()); cb->setText(m_pm->localFileByIndex(*index));
}
}
void MainWindow::on_actionPaste_triggered()
{
QImage clipboardImage;
QUrl clipboardFileUrl;
const QMimeData * clipboardData = QApplication::clipboard()->mimeData();
if (clipboardData->hasImage()) {
QVariant imageVariant(clipboardData->imageData());
if (imageVariant.isValid()) {
clipboardImage = qvariant_cast<QImage>(imageVariant);
}
} else if (clipboardData->hasText()) {
QString clipboardText(clipboardData->text());
if (clipboardText.startsWith("PICTURE:")) {
QString maybeFilename(clipboardText.mid(8));
if (QFile::exists(maybeFilename)) {
clipboardFileUrl = QUrl::fromLocalFile(maybeFilename);
}
}
}
if (!clipboardImage.isNull()) {
setWindowTitle(tr("Image From Clipboard"));
m_graphicsView->showImage(clipboardImage);
clearGallery();
} else if (clipboardFileUrl.isValid()) {
m_graphicsView->showFileFromPath(clipboardFileUrl.toLocalFile());
m_pm->loadPlaylist(clipboardFileUrl);
}
}
void MainWindow::on_actionTrash_triggered()
{
QModelIndex index = m_pm->curIndex();
if (!m_pm->urlByIndex(index).isLocalFile()) return;
QFile file(m_pm->localFileByIndex(index));
QFileInfo fileInfo(file.fileName());
QMessageBox::StandardButton result = QMessageBox::question(this, tr("Move to Trash"),
tr("Are you sure you want to move \"%1\" to recycle bin?").arg(fileInfo.fileName()));
if (result == QMessageBox::Yes) {
bool succ = file.moveToTrash();
if (!succ) {
QMessageBox::warning(this, tr("Failed to move file to trash"),
tr("Move to trash failed, it might caused by file permission issue, file system limitation, or platform limitation."));
} else {
m_pm->removeAt(index);
galleryCurrent(true, true);
}
}
}
void MainWindow::on_actionToggleCheckerboard_triggered()
{
// TODO: is that okay to do this since we plan to support custom shortcuts?
m_graphicsView->toggleCheckerboard(QGuiApplication::queryKeyboardModifiers().testFlag(Qt::ShiftModifier));
}
void MainWindow::on_actionRotateClockwise_triggered()
{
m_graphicsView->rotateView();
m_graphicsView->displayScene();
}
void MainWindow::on_actionRotateCounterClockwise_triggered()
{
m_graphicsView->rotateView(false);
m_graphicsView->displayScene();
} }
void MainWindow::on_actionPrevPicture_triggered() void MainWindow::on_actionPrevPicture_triggered()
@@ -770,19 +400,60 @@ void MainWindow::on_actionNextPicture_triggered()
galleryNext(); galleryNext();
} }
void MainWindow::on_actionTogglePauseAnimation_triggered() void MainWindow::on_actionActualSize_triggered()
{ {
m_graphicsView->scene()->togglePauseAnimation(); ui->m_gv->resetScale();
ui->m_gv->setEnableAutoFitToScreen(false);
} }
void MainWindow::on_actionAnimationNextFrame_triggered() void MainWindow::on_actionFitToScreen_triggered()
{ {
m_graphicsView->scene()->skipAnimationFrame(1); ui->m_gv->fitInView(ui->m_nav->sceneRect(), Qt::KeepAspectRatio);
ui->m_gv->setEnableAutoFitToScreen(ui->m_gv->scaleFactor() <= 1);
} }
void MainWindow::on_actionToggleProtectMode_triggered() void MainWindow::on_actionFitByWidth_triggered()
{ {
toggleProtectedMode(); ui->m_gv->fitByOrientation(Qt::Orientation::Horizontal);
}
void MainWindow::on_actionFitByHeight_triggered()
{
ui->m_gv->fitByOrientation(Qt::Orientation::Vertical);
}
void MainWindow::on_actionZoomIn_triggered()
{
if (ui->m_gv->scaleFactor() < 1000) {
ui->m_gv->zoomView(1.25);
}
}
void MainWindow::on_actionZoomOut_triggered()
{
ui->m_gv->zoomView(0.8);
}
void MainWindow::on_actionFlipHorizontal_triggered()
{
ui->m_gv->flipView(true);
}
void MainWindow::on_actionFlipVertical_triggered()
{
ui->m_gv->flipView(false);
}
void MainWindow::on_actionRotateClockwise_triggered()
{
ui->m_gv->rotateView(true);
ui->m_gv->displayScene();
}
void MainWindow::on_actionRotateCounterClockwise_triggered()
{
ui->m_gv->rotateView(false);
ui->m_gv->displayScene();
} }
void MainWindow::on_actionToggleAvoidResetTransform_triggered() void MainWindow::on_actionToggleAvoidResetTransform_triggered()
@@ -790,37 +461,48 @@ void MainWindow::on_actionToggleAvoidResetTransform_triggered()
toggleAvoidResetTransform(); toggleAvoidResetTransform();
} }
void MainWindow::on_actionSettings_triggered() void MainWindow::on_actionToggleCheckerboard_triggered()
{ {
SettingsDialog * sd = new SettingsDialog(this); ui->m_gv->toggleCheckerboard(QGuiApplication::queryKeyboardModifiers().testFlag(Qt::ShiftModifier));
sd->exec();
sd->deleteLater();
} }
void MainWindow::on_actionHelp_triggered() void MainWindow::on_actionTogglePauseAnimation_triggered()
{ {
AboutDialog * ad = new AboutDialog(this); ui->m_gv->scene()->togglePauseAnimation();
ad->exec();
ad->deleteLater();
} }
void MainWindow::on_actionProperties_triggered() void MainWindow::on_actionAnimationNextFrame_triggered()
{ {
QUrl currentFileUrl = currentImageFileUrl(); ui->m_gv->scene()->skipAnimationFrame(1);
if (!currentFileUrl.isValid()) return; }
MetadataModel * md = new MetadataModel(); void MainWindow::on_actionTrash_triggered()
md->setFile(currentFileUrl.toLocalFile()); {
auto index = m_pm->currentIndex();
if (!index.has_value()) return;
if (!m_pm->urlByIndex(*index).isLocalFile()) return;
MetadataDialog * ad = new MetadataDialog(this); QFile file(m_pm->localFileByIndex(*index));
ad->setMetadataModel(md); QFileInfo fileInfo(file.fileName());
ad->exec();
ad->deleteLater(); QMessageBox::StandardButton result = QMessageBox::question(this, tr("Move to Trash"),
tr("Are you sure you want to move \"%1\" to recycle bin?").arg(fileInfo.fileName()));
if (result == QMessageBox::Yes) {
bool succ = file.moveToTrash();
if (!succ) {
QMessageBox::warning(this, tr("Failed to move file to trash"),
tr("Move to trash failed, it might caused by file permission issue, file system limitation, or platform limitation."));
} else {
m_pm->removeFromPlaylist(*index);
}
}
} }
void MainWindow::on_actionLocateInFileManager_triggered() void MainWindow::on_actionLocateInFileManager_triggered()
{ {
QUrl currentFileUrl = currentImageFileUrl(); auto index = m_pm->currentIndex();
if (!index.has_value()) return;
QUrl currentFileUrl = m_pm->urlByIndex(*index);
if (!currentFileUrl.isValid()) return; if (!currentFileUrl.isValid()) return;
QFileInfo fileInfo(currentFileUrl.toLocalFile()); QFileInfo fileInfo(currentFileUrl.toLocalFile());
@@ -853,11 +535,38 @@ void MainWindow::on_actionLocateInFileManager_triggered()
#endif // Q_OS_WIN #endif // Q_OS_WIN
} }
void MainWindow::on_actionQuitApp_triggered() void MainWindow::on_actionProperties_triggered()
{ {
quitAppAction(false); auto index = m_pm->currentIndex();
if (!index.has_value()) return;
QUrl currentFileUrl = m_pm->urlByIndex(*index);
if (!currentFileUrl.isValid()) return;
MetadataModel * md = new MetadataModel();
md->setFile(currentFileUrl.toLocalFile());
MetadataDialog * ad = new MetadataDialog(this);
ad->setMetadataModel(md);
ad->exec();
ad->deleteLater();
} }
void MainWindow::on_actionSettings_triggered()
{
SettingsDialog * sd = new SettingsDialog(this);
sd->exec();
sd->deleteLater();
}
void MainWindow::on_actionHelp_triggered()
{
AboutDialog * ad = new AboutDialog(this);
ad->exec();
ad->deleteLater();
}
// endregion
bool MainWindow::updateFileWatcher(const QString &basePath) bool MainWindow::updateFileWatcher(const QString &basePath)
{ {
m_fileSystemWatcher->removePaths(m_fileSystemWatcher->files()); m_fileSystemWatcher->removePaths(m_fileSystemWatcher->files());
@@ -865,12 +574,6 @@ bool MainWindow::updateFileWatcher(const QString &basePath)
return false; return false;
} }
void MainWindow::updateGalleryButtonsVisibility() void MainWindow::updateActionState() {
{ m_am->updateActionState(m_pm, ui->m_gv);
const int galleryFileCount = m_pm->totalCount();
const bool loopGallery = Settings::instance()->loopGallery();
m_prevButton->setVisible(!m_protectedMode && galleryFileCount > 1);
m_nextButton->setVisible(!m_protectedMode && galleryFileCount > 1);
m_prevButton->setEnabled(loopGallery || !m_pm->isFirstIndex());
m_nextButton->setEnabled(loopGallery || !m_pm->isLastIndex());
} }
+31 -59
View File
@@ -5,25 +5,19 @@
#ifndef MAINWINDOW_H #ifndef MAINWINDOW_H
#define MAINWINDOW_H #define MAINWINDOW_H
#include "framelesswindow.h" #include <QWidget>
#include <QParallelAnimationGroup>
#include <QPropertyAnimation>
#include <QPushButton>
QT_BEGIN_NAMESPACE QT_BEGIN_NAMESPACE
class QGraphicsOpacityEffect;
class QGraphicsView;
class QFileSystemWatcher; class QFileSystemWatcher;
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE QT_END_NAMESPACE
class ActionManager; class ActionManager;
class PlaylistManager; class PlaylistManager;
class ToolButton;
class GraphicsView; class MainWindow : public QWidget
class NavigatorView;
class BottomButtonGroup;
class MainWindow : public FramelessWindow
{ {
Q_OBJECT Q_OBJECT
@@ -31,40 +25,26 @@ public:
explicit MainWindow(QWidget *parent = nullptr); explicit MainWindow(QWidget *parent = nullptr);
~MainWindow() override; ~MainWindow() override;
void showUrls(const QList<QUrl> &urls); void showFiles(const QStringList& files);
void showFiles(const QList<QUrl>& urls);
void initWindowSize(); void initWindowSize();
void adjustWindowSizeBySceneRect();
QUrl currentImageFileUrl() const;
void clearGallery(); void clearGallery();
void galleryPrev(); void galleryPrev();
void galleryNext(); void galleryNext();
void galleryCurrent(bool showLoadImageHintWhenEmpty, bool reloadImage); void galleryCurrent(bool fromFileWatcher);
static QStringList supportedImageFormats(); static QStringList supportedImageFormats();
protected slots: protected slots:
void showEvent(QShowEvent *event) override;
void enterEvent(QEnterEvent *event) override;
void leaveEvent(QEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void mouseDoubleClickEvent(QMouseEvent *event) override;
void wheelEvent(QWheelEvent *event) override; void wheelEvent(QWheelEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
void contextMenuEvent(QContextMenuEvent *event) override; void contextMenuEvent(QContextMenuEvent *event) override;
void dragEnterEvent(QDragEnterEvent *event) override; void dragEnterEvent(QDragEnterEvent *event) override;
void dragMoveEvent(QDragMoveEvent *event) override; void dragMoveEvent(QDragMoveEvent *event) override;
void dropEvent(QDropEvent *event) override; void dropEvent(QDropEvent *event) override;
void centerWindow(); void centerWindow();
void closeWindow();
void updateWidgetsPosition();
void toggleProtectedMode();
void toggleAvoidResetTransform(); void toggleAvoidResetTransform();
bool canPaste() const;
void quitAppAction(bool force = false);
void toggleFullscreen(); void toggleFullscreen();
void toggleMaximize(); void toggleMaximize();
@@ -72,54 +52,46 @@ protected:
QSize sizeHint() const override; QSize sizeHint() const override;
private slots: private slots:
void on_actionOpen_triggered(); void on_actionCopyPixmap_triggered();
void on_actionCopyFilePath_triggered();
void on_actionActualSize_triggered();
void on_actionToggleMaximize_triggered();
void on_actionZoomIn_triggered();
void on_actionZoomOut_triggered();
void on_actionToggleCheckerboard_triggered();
void on_actionRotateClockwise_triggered();
void on_actionRotateCounterClockwise_triggered();
void on_actionPrevPicture_triggered(); void on_actionPrevPicture_triggered();
void on_actionNextPicture_triggered(); void on_actionNextPicture_triggered();
void on_actionActualSize_triggered();
void on_actionFitToScreen_triggered();
void on_actionFitByWidth_triggered();
void on_actionFitByHeight_triggered();
void on_actionZoomIn_triggered();
void on_actionZoomOut_triggered();
void on_actionFlipHorizontal_triggered();
void on_actionFlipVertical_triggered();
void on_actionRotateClockwise_triggered();
void on_actionRotateCounterClockwise_triggered();
void on_actionToggleAvoidResetTransform_triggered();
void on_actionToggleCheckerboard_triggered();
void on_actionTogglePauseAnimation_triggered(); void on_actionTogglePauseAnimation_triggered();
void on_actionAnimationNextFrame_triggered(); void on_actionAnimationNextFrame_triggered();
void on_actionHorizontalFlip_triggered();
void on_actionFitInView_triggered();
void on_actionFitByWidth_triggered();
void on_actionCopyPixmap_triggered();
void on_actionCopyFilePath_triggered();
void on_actionPaste_triggered();
void on_actionTrash_triggered(); void on_actionTrash_triggered();
void on_actionToggleProtectMode_triggered(); void on_actionLocateInFileManager_triggered();
void on_actionToggleAvoidResetTransform_triggered(); void on_actionProperties_triggered();
void on_actionSettings_triggered(); void on_actionSettings_triggered();
void on_actionHelp_triggered(); void on_actionHelp_triggered();
void on_actionProperties_triggered();
void on_actionLocateInFileManager_triggered();
void on_actionQuitApp_triggered();
private: private:
bool updateFileWatcher(const QString & basePath = QString()); bool updateFileWatcher(const QString & basePath = QString());
void updateGalleryButtonsVisibility(); void updateActionState();
private: private:
QT_PREPEND_NAMESPACE(Ui::MainWindow) *ui;
ActionManager *m_am; ActionManager *m_am;
PlaylistManager *m_pm; PlaylistManager *m_pm;
QPoint m_oldMousePos;
QFileSystemWatcher *m_fileSystemWatcher; QFileSystemWatcher *m_fileSystemWatcher;
ToolButton *m_prevButton;
ToolButton *m_nextButton;
GraphicsView *m_graphicsView;
NavigatorView *m_gv;
BottomButtonGroup *m_bottomButtonGroup;
bool m_protectedMode = false;
bool m_clickedOnWindow = false;
}; };
#endif // MAINWINDOW_H #endif // MAINWINDOW_H
+172
View File
@@ -0,0 +1,172 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QWidget" name="MainWindow">
<property name="windowModality">
<enum>Qt::NonModal</enum>
</property>
<property name="minimumSize">
<size>
<width>640</width>
<height>480</height>
</size>
</property>
<property name="acceptDrops">
<bool>true</bool>
</property>
<layout class="QVBoxLayout" name="m_centralLayout">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="GraphicsView" name="m_gv">
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="verticalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="horizontalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
</widget>
</item>
<item>
<widget class="QWidget" name="bottomBar" native="true">
<property name="minimumSize">
<size>
<width>0</width>
<height>72</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>72</height>
</size>
</property>
<layout class="QHBoxLayout" name="bottomBarLayout">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QWidget" name="m_navPH" native="true">
<property name="minimumSize">
<size>
<width>99</width>
<height>72</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>99</width>
<height>72</height>
</size>
</property>
</widget>
</item>
<item>
<spacer name="leftSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</spacer>
</item>
<item>
<widget class="BottomButtonGroup" name="m_bottomButtonGroup"/>
</item>
<item>
<spacer name="rightSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</spacer>
</item>
<item>
<widget class="NavigatorView" name="m_nav">
<property name="minimumSize">
<size>
<width>99</width>
<height>72</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>99</width>
<height>72</height>
</size>
</property>
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="verticalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="horizontalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
<widget class="QMenu" name="m_subMenuCopy">
<property name="title">
<string>&amp;Copy</string>
</property>
<property name="icon">
<iconset theme="edit-copy"/>
</property>
</widget>
<widget class="QMenu" name="m_subMenuTransform">
<property name="title">
<string>&amp;Transform</string>
</property>
</widget>
<widget class="QMenu" name="m_menu"/>
</widget>
<customwidgets>
<customwidget>
<class>GraphicsView</class>
<extends>QGraphicsView</extends>
<header>graphicsview.h</header>
</customwidget>
<customwidget>
<class>NavigatorView</class>
<extends>QGraphicsView</extends>
<header>navigatorview.h</header>
</customwidget>
<customwidget>
<class>BottomButtonGroup</class>
<extends>QGroupBox</extends>
<header>bottombuttongroup.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
+18 -15
View File
@@ -3,12 +3,12 @@
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
#include "metadatadialog.h" #include "metadatadialog.h"
#include "ui_metadatadialog.h"
#include <QDialogButtonBox> #include <QDialogButtonBox>
#include <QPainter> #include <QPainter>
#include <QStyledItemDelegate> #include <QStyledItemDelegate>
#include <QTreeView> #include <QTreeView>
#include <QVBoxLayout>
#include <QHeaderView> #include <QHeaderView>
#include "metadatamodel.h" #include "metadatamodel.h"
@@ -73,30 +73,33 @@ protected:
}; };
MetadataDialog::MetadataDialog(QWidget *parent) MetadataDialog::MetadataDialog(QWidget *parent)
: QDialog(parent) : QDialog(parent), ui(new QT_PREPEND_NAMESPACE(Ui::MetadataDialog))
, m_treeView(new PropertyTreeView(this))
{ {
ui->setupUi(this);
setWindowFlag(Qt::WindowContextHelpButtonHint, false);
// YYC MARK:
// Because we use custom QTreeView and we do not want to expose it to public domain.
// So I have to use this way as the compromise.
// Create our custom QTreeView and insert them
m_treeView = new PropertyTreeView(this);
auto* layout = ui->verticalLayout;
const int index = layout->indexOf(ui->m_buttonBox);
layout->insertWidget(index, m_treeView);
// Setup our custom QTreeView
m_treeView->setRootIsDecorated(false); m_treeView->setRootIsDecorated(false);
m_treeView->setIndentation(0); m_treeView->setIndentation(0);
m_treeView->setItemDelegate(new PropertyTreeItemDelegate(m_treeView)); m_treeView->setItemDelegate(new PropertyTreeItemDelegate(m_treeView));
m_treeView->header()->resizeSection(0, sizeHint().width() / 2); m_treeView->header()->resizeSection(0, sizeHint().width() / 2);
setWindowTitle(tr("Image Metadata")); connect(ui->m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::close);
QDialogButtonBox * buttonBox = new QDialogButtonBox(QDialogButtonBox::Close);
setLayout(new QVBoxLayout);
layout()->addWidget(m_treeView);
layout()->addWidget(buttonBox);
connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::close);
setWindowFlag(Qt::WindowContextHelpButtonHint, false);
} }
MetadataDialog::~MetadataDialog() MetadataDialog::~MetadataDialog()
{ {
delete ui;
} }
void MetadataDialog::setMetadataModel(MetadataModel * model) void MetadataDialog::setMetadataModel(MetadataModel * model)
+7
View File
@@ -11,6 +11,12 @@ QT_BEGIN_NAMESPACE
class QTreeView; class QTreeView;
QT_END_NAMESPACE QT_END_NAMESPACE
QT_BEGIN_NAMESPACE
namespace Ui {
class MetadataDialog;
}
QT_END_NAMESPACE
class MetadataModel; class MetadataModel;
class MetadataDialog : public QDialog class MetadataDialog : public QDialog
{ {
@@ -25,6 +31,7 @@ public:
private: private:
QTreeView * m_treeView = nullptr; QTreeView * m_treeView = nullptr;
QT_PREPEND_NAMESPACE(Ui::MetadataDialog) *ui;
}; };
#endif // METADATADIALOG_H #endif // METADATADIALOG_H
+23
View File
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MetadataDialog</class>
<widget class="QDialog" name="MetadataDialog">
<property name="windowModality">
<enum>Qt::NonModal</enum>
</property>
<property name="windowTitle">
<string>Image Metadata</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QDialogButtonBox" name="m_buttonBox">
<property name="standardButtons">
<set>QDialogButtonBox::Close</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
+38 -9
View File
@@ -5,8 +5,9 @@
#include "navigatorview.h" #include "navigatorview.h"
#include "graphicsview.h" #include "graphicsview.h"
#include "opacityhelper.h"
#include <QStyleHints>
#include <QOperatingSystemVersion>
#include <QMouseEvent> #include <QMouseEvent>
#include <QDebug> #include <QDebug>
#include <QTimer> #include <QTimer>
@@ -14,12 +15,12 @@
NavigatorView::NavigatorView(QWidget *parent) NavigatorView::NavigatorView(QWidget *parent)
: QGraphicsView (parent) : QGraphicsView (parent)
, m_viewportRegion(this->rect()) , m_viewportRegion(this->rect())
, m_opacityHelper(new OpacityHelper(this))
{ {
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setStyleSheet("background-color: rgba(0, 0, 0, 120);"
"border-radius: 3px;"); updateStyle(qGuiApp->styleHints()->colorScheme());
connect(qGuiApp->styleHints(), &QStyleHints::colorSchemeChanged, this, &NavigatorView::updateStyle);
} }
// doesn't take or manage its ownership // doesn't take or manage its ownership
@@ -28,11 +29,6 @@ void NavigatorView::setMainView(GraphicsView *mainView)
m_mainView = mainView; m_mainView = mainView;
} }
void NavigatorView::setOpacity(qreal opacity, bool animated)
{
m_opacityHelper->setOpacity(opacity, animated);
}
void NavigatorView::updateMainViewportRegion() void NavigatorView::updateMainViewportRegion()
{ {
// Use QTimer::singleShot with lambda to delay the update // Use QTimer::singleShot with lambda to delay the update
@@ -45,6 +41,39 @@ void NavigatorView::updateMainViewportRegion()
}); });
} }
void NavigatorView::updateStyle(Qt::ColorScheme colorScheme) {
// YYC MARK:
// If we are using Windows 10 and lower system or Qt which do not support "Windows 11"
// theme (lower than Qt 6.7), we should only support light mode.
// Because Qt's dark-mode-aware "Windows 11" theme is only well-supported on Windows 11.
#if defined(Q_OS_WIN)
#if QT_VERSION < QT_VERSION_CHECK(6, 7, 0)
colorScheme = Qt::ColorScheme::Light;
#else
if (QOperatingSystemVersion::current() < QOperatingSystemVersion::Windows11) {
colorScheme = Qt::ColorScheme::Light;
}
#endif // QT_VERSION < QT_VERSION_CHECK(6, 7, 0)
#endif // defined(Q_OS_WIN)
switch (colorScheme) {
case Qt::ColorScheme::Dark:
setStyleSheet(R"#(
border-style: none;
background-color: rgba(255, 255, 255, 70);
)#");
break;
case Qt::ColorScheme::Light:
case Qt::ColorScheme::Unknown:
default:
setStyleSheet(R"#(
border-style: none;
background-color: rgba(0, 0, 0, 70);
)#");
break;
}
}
void NavigatorView::mousePressEvent(QMouseEvent *event) void NavigatorView::mousePressEvent(QMouseEvent *event)
{ {
m_mouseDown = true; m_mouseDown = true;
+3 -3
View File
@@ -7,7 +7,6 @@
#include <QGraphicsView> #include <QGraphicsView>
class OpacityHelper;
class GraphicsView; class GraphicsView;
class NavigatorView : public QGraphicsView class NavigatorView : public QGraphicsView
{ {
@@ -16,11 +15,13 @@ public:
NavigatorView(QWidget *parent = nullptr); NavigatorView(QWidget *parent = nullptr);
void setMainView(GraphicsView *mainView); void setMainView(GraphicsView *mainView);
void setOpacity(qreal opacity, bool animated = true);
public slots: public slots:
void updateMainViewportRegion(); void updateMainViewportRegion();
private slots:
void updateStyle(Qt::ColorScheme colorScheme);
private: private:
void mousePressEvent(QMouseEvent * event) override; void mousePressEvent(QMouseEvent * event) override;
void mouseMoveEvent(QMouseEvent * event) override; void mouseMoveEvent(QMouseEvent * event) override;
@@ -32,7 +33,6 @@ private:
bool m_mouseDown = false; bool m_mouseDown = false;
QPolygon m_viewportRegion; QPolygon m_viewportRegion;
QGraphicsView *m_mainView = nullptr; QGraphicsView *m_mainView = nullptr;
OpacityHelper *m_opacityHelper = nullptr;
}; };
#endif // NAVIGATORVIEW_H #endif // NAVIGATORVIEW_H
-31
View File
@@ -1,31 +0,0 @@
// SPDX-FileCopyrightText: 2022 Gary Wang <wzc782970009@gmail.com>
//
// SPDX-License-Identifier: MIT
#include "opacityhelper.h"
#include <QGraphicsOpacityEffect>
#include <QPropertyAnimation>
OpacityHelper::OpacityHelper(QWidget *parent)
: QObject(parent)
, m_opacityFx(new QGraphicsOpacityEffect(parent))
, m_opacityAnimation(new QPropertyAnimation(m_opacityFx, "opacity"))
{
parent->setGraphicsEffect(m_opacityFx);
m_opacityAnimation->setDuration(300);
}
void OpacityHelper::setOpacity(qreal opacity, bool animated)
{
if (!animated) {
m_opacityFx->setOpacity(opacity);
return;
}
m_opacityAnimation->stop();
m_opacityAnimation->setStartValue(m_opacityFx->opacity());
m_opacityAnimation->setEndValue(opacity);
m_opacityAnimation->start();
}
-27
View File
@@ -1,27 +0,0 @@
// SPDX-FileCopyrightText: 2022 Gary Wang <wzc782970009@gmail.com>
//
// SPDX-License-Identifier: MIT
#ifndef OPACITYHELPER_H
#define OPACITYHELPER_H
#include <QWidget>
QT_BEGIN_NAMESPACE
class QGraphicsOpacityEffect;
class QPropertyAnimation;
QT_END_NAMESPACE
class OpacityHelper : QObject
{
public:
OpacityHelper(QWidget * parent);
void setOpacity(qreal opacity, bool animated = true);
protected:
QGraphicsOpacityEffect * m_opacityFx;
QPropertyAnimation * m_opacityAnimation;
};
#endif // OPACITYHELPER_H
+213 -201
View File
@@ -3,158 +3,20 @@
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
#include "playlistmanager.h" #include "playlistmanager.h"
#include "playlistscout.h"
#include <QCollator> #include <QCollator>
#include <QDir> #include <QDir>
#include <QFileInfo> #include <QFileInfo>
#include <QUrl> #include <QUrl>
PlaylistModel::PlaylistModel(QObject *parent)
: QAbstractListModel(parent)
{
}
PlaylistModel::~PlaylistModel()
= default;
void PlaylistModel::setPlaylist(const QList<QUrl> &urls)
{
beginResetModel();
m_playlist = urls;
endResetModel();
}
QModelIndex PlaylistModel::loadPlaylist(const QList<QUrl> & urls)
{
if (urls.isEmpty()) return {};
if (urls.count() == 1) {
return loadPlaylist(urls.constFirst());
} else {
setPlaylist(urls);
return index(0);
}
}
QModelIndex PlaylistModel::loadPlaylist(const QUrl &url)
{
QFileInfo info(url.toLocalFile());
QDir dir(info.path());
QString && currentFileName = info.fileName();
if (dir.path() == m_currentDir) {
int idx = indexOf(url);
return idx == -1 ? appendToPlaylist(url) : index(idx);
}
QStringList entryList = dir.entryList(
m_autoLoadSuffixes,
QDir::Files | QDir::NoSymLinks, QDir::NoSort);
QCollator collator;
collator.setNumericMode(true);
std::sort(entryList.begin(), entryList.end(), collator);
QList<QUrl> playlist;
int idx = -1;
for (int i = 0; i < entryList.count(); i++) {
const QString & fileName = entryList.at(i);
const QString & oneEntry = dir.absoluteFilePath(fileName);
const QUrl & url = QUrl::fromLocalFile(oneEntry);
playlist.append(url);
if (fileName == currentFileName) {
idx = i;
}
}
if (idx == -1) {
idx = playlist.count();
playlist.append(url);
}
m_currentDir = dir.path();
setPlaylist(playlist);
return index(idx);
}
QModelIndex PlaylistModel::appendToPlaylist(const QUrl &url)
{
const int lastIndex = rowCount();
beginInsertRows(QModelIndex(), lastIndex, lastIndex);
m_playlist.append(url);
endInsertRows();
return index(lastIndex);
}
bool PlaylistModel::removeAt(int index)
{
if (index < 0 || index >= rowCount()) return false;
beginRemoveRows(QModelIndex(), index, index);
m_playlist.removeAt(index);
endRemoveRows();
return true;
}
int PlaylistModel::indexOf(const QUrl &url) const
{
return m_playlist.indexOf(url);
}
QUrl PlaylistModel::urlByIndex(int index) const
{
return m_playlist.value(index);
}
QStringList PlaylistModel::autoLoadFilterSuffixes() const
{
return m_autoLoadSuffixes;
}
QHash<int, QByteArray> PlaylistModel::roleNames() const
{
QHash<int, QByteArray> result = QAbstractListModel::roleNames();
result.insert(UrlRole, "url");
return result;
}
int PlaylistModel::rowCount(const QModelIndex &parent) const
{
return m_playlist.count();
}
QVariant PlaylistModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) return {};
switch (role) {
case Qt::DisplayRole:
return m_playlist.at(index.row()).fileName();
case UrlRole:
return m_playlist.at(index.row());
}
return {};
}
PlaylistManager::PlaylistManager(QObject *parent) PlaylistManager::PlaylistManager(QObject *parent)
: QObject(parent) : QObject(parent)
, m_currentIndex(std::nullopt)
, m_playlist()
, m_allowedSuffixes()
{ {
connect(&m_model, &PlaylistModel::rowsRemoved, this,
[this](const QModelIndex &, int, int) {
if (m_model.rowCount() <= m_currentIndex) {
setProperty("currentIndex", m_currentIndex - 1);
}
});
auto onRowCountChanged = [this](){
emit totalCountChanged(m_model.rowCount());
};
connect(&m_model, &PlaylistModel::rowsInserted, this, onRowCountChanged);
connect(&m_model, &PlaylistModel::rowsRemoved, this, onRowCountChanged);
connect(&m_model, &PlaylistModel::modelReset, this, onRowCountChanged);
} }
PlaylistManager::~PlaylistManager() PlaylistManager::~PlaylistManager()
@@ -162,35 +24,86 @@ PlaylistManager::~PlaylistManager()
} }
PlaylistModel *PlaylistManager::model() // region: Allowed Suffixes Operations
{
return &m_model; const QStringList& PlaylistManager::allowedSuffixes() const {
return m_allowedSuffixes;
} }
void PlaylistManager::setPlaylist(const QList<QUrl> &urls) void PlaylistManager::setAllowedSuffixes(const QStringList& nameFilters) {
{ m_allowedSuffixes = nameFilters;
m_model.setPlaylist(urls); emit allowedSuffixesChanged(m_allowedSuffixes);
} }
QModelIndex PlaylistManager::loadPlaylist(const QList<QUrl> &urls) // endregion
{
QModelIndex idx = m_model.loadPlaylist(urls); // region: Playlist Loader and Reset
setProperty("currentIndex", idx.row());
return idx; bool PlaylistManager::loadPlaylist(const QStringList& files) {
// Convert string list to url list first
QList<QUrl> urls;
for (const QString & file : std::as_const(files)) {
urls.append(urlFromString(file));
}
return loadPlaylist(urls);
} }
QModelIndex PlaylistManager::loadPlaylist(const QUrl &url) bool PlaylistManager::loadPlaylist(const QList<QUrl>& urls) {
{ // Check its count, and check M3U8 playlist for single file case.
QModelIndex idx = m_model.loadPlaylist(url); if (urls.isEmpty()) {
setProperty("currentIndex", idx.row()); clearPlaylist();
return idx; return true;
} else if (urls.count() == 1) {
const QUrl& firstUrl = urls.first();
const QString lowerCaseUrlPath(firstUrl.path().toLower());
if (lowerCaseUrlPath.endsWith(".m3u8") || lowerCaseUrlPath.endsWith(".m3u")) {
return loadM3U8Playlist(firstUrl);
} else {
return loadSingleFilePlaylist(firstUrl);
}
} else {
return loadMultipleFilesPlaylist(std::move(urls));
}
} }
QModelIndex PlaylistManager::loadM3U8Playlist(const QUrl &url) bool PlaylistManager::loadSingleFilePlaylist(const QUrl& url) {
{ // Check URL at first
if (!checkUrl(url))
return false;
// Scout playlist by given file
auto scoutResult = PlaylistScout::scout(url, m_allowedSuffixes);
if (!scoutResult.has_value()) {
return false;
}
// Setup playlist with index
setPlaylist(std::move(scoutResult->playlist), scoutResult->indexHint);
return true;
}
bool PlaylistManager::loadMultipleFilesPlaylist(const QList<QUrl>&& urls) {
// Check all of them are valid
for (const auto& url : std::as_const(urls)) {
if (!checkUrl(url)) {
return false;
}
}
// Set playlist and return
setPlaylist(std::move(urls));
return true;
}
bool PlaylistManager::loadM3U8Playlist(const QUrl& url) {
// Check URL at first
if (!checkUrl(url))
return false;
QList<QUrl> urls;
QFile file(url.toLocalFile()); QFile file(url.toLocalFile());
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QList<QUrl> urls;
while (!file.atEnd()) { while (!file.atEnd()) {
QString line = file.readLine(); QString line = file.readLine();
if (line.startsWith('#')) { if (line.startsWith('#')) {
@@ -198,86 +111,185 @@ QModelIndex PlaylistManager::loadM3U8Playlist(const QUrl &url)
} }
QFileInfo fileInfo(file); QFileInfo fileInfo(file);
QUrl item = QUrl::fromUserInput(line, fileInfo.absolutePath()); QUrl item = QUrl::fromUserInput(line, fileInfo.absolutePath());
if (!checkUrl(item)) {
return false;
}
urls.append(item); urls.append(item);
} }
return loadPlaylist(urls);
} else { } else {
return {}; return false;
}
setPlaylist(std::move(urls));
return true;
}
void PlaylistManager::setPlaylist(const QList<QUrl>&& urls, std::optional<qsizetype> indexHint) {
// Setup playlist
m_playlist = std::move(urls);
// Set index with hint
if (indexHint.has_value()) {
m_currentIndex = *indexHint;
}
sanitizeIndex();
// Raise signal
emit playlistChanged(totalCount());
}
void PlaylistManager::clearPlaylist() {
m_playlist.clear();
sanitizeIndex();
emit playlistChanged(this->totalCount());
}
// endregion
// region: Playlist Operations
void PlaylistManager::appendToPlaylist(const QString &file)
{
return appendToPlaylist(urlFromString(file));
}
void PlaylistManager::appendToPlaylist(const QUrl &url)
{
m_playlist.append(url);
sanitizeIndex();
emit playlistChanged(totalCount());
}
bool PlaylistManager::insertIntoPlaylist(qsizetype index, const QString &file)
{
return insertIntoPlaylist(index, urlFromString(file));
}
bool PlaylistManager::insertIntoPlaylist(qsizetype index, const QUrl &url)
{
if (index < 0 || index > totalCount()) {
return false;
} else {
m_playlist.insert(index, url);
sanitizeIndex();
emit playlistChanged(totalCount());
return true;
} }
} }
int PlaylistManager::totalCount() const bool PlaylistManager::removeFromPlaylist(qsizetype index)
{ {
return m_model.rowCount(); if (index < 0 || index >= totalCount()) {
return false;
} else {
m_playlist.removeAt(index);
sanitizeIndex();
emit playlistChanged(totalCount());
return true;
}
} }
QModelIndex PlaylistManager::previousIndex() const // endregion
{
int count = totalCount();
if (count == 0) return {};
return m_model.index(isFirstIndex() ? count - 1 : m_currentIndex - 1); // region: Index Operations
qsizetype PlaylistManager::totalCount() const
{
return m_playlist.count();
} }
QModelIndex PlaylistManager::nextIndex() const std::optional<qsizetype> PlaylistManager::previousIndex() const
{ {
int count = totalCount(); if (!m_currentIndex.has_value() || totalCount() <= 0) return std::nullopt;
if (count == 0) return {}; return (isFirstIndex() ? totalCount() - 1 : *m_currentIndex - 1);
return m_model.index(isLastIndex() ? 0 : m_currentIndex + 1);
} }
QModelIndex PlaylistManager::curIndex() const std::optional<qsizetype> PlaylistManager::nextIndex() const
{ {
return m_model.index(m_currentIndex); if (!m_currentIndex.has_value() || totalCount() <= 0) return std::nullopt;
return (isLastIndex() ? 0 : *m_currentIndex + 1);
} }
bool PlaylistManager::isFirstIndex() const bool PlaylistManager::isFirstIndex() const
{ {
return m_currentIndex == 0; return m_currentIndex.has_value() && *m_currentIndex == 0;
} }
bool PlaylistManager::isLastIndex() const bool PlaylistManager::isLastIndex() const
{ {
return m_currentIndex + 1 == totalCount(); return m_currentIndex.has_value() && *m_currentIndex + 1 == totalCount();
} }
void PlaylistManager::setCurrentIndex(const QModelIndex &index) std::optional<qsizetype> PlaylistManager::currentIndex() const
{ {
if (index.isValid() && index.row() >= 0 && index.row() < totalCount()) { return m_currentIndex;
setProperty("currentIndex", index.row()); }
bool PlaylistManager::setCurrentIndex(qsizetype index)
{
if (!m_currentIndex.has_value()) {
return false;
} }
if (index < 0 || index >= totalCount()) {
return false;
}
if (*m_currentIndex == index) {
return true;
}
m_currentIndex = index;
emit currentIndexChanged(index);
return true;
} }
QUrl PlaylistManager::urlByIndex(const QModelIndex &index) QUrl PlaylistManager::urlByIndex(qsizetype index) const
{ {
return m_model.urlByIndex(index.row()); return m_playlist.value(index);
} }
QString PlaylistManager::localFileByIndex(const QModelIndex &index) QString PlaylistManager::localFileByIndex(qsizetype index) const
{ {
return urlByIndex(index).toLocalFile(); return urlByIndex(index).toLocalFile();
} }
bool PlaylistManager::removeAt(const QModelIndex &index) // endregion
{
return m_model.removeAt(index.row());
}
void PlaylistManager::setAutoLoadFilterSuffixes(const QStringList &nameFilters) // region: Misc
{
m_model.setProperty("autoLoadFilterSuffixes", nameFilters);
}
QList<QUrl> PlaylistManager::convertToUrlList(const QStringList &files) void PlaylistManager::sanitizeIndex()
{ {
QList<QUrl> urlList; auto cnt = totalCount();
for (const QString & str : std::as_const(files)) { if (cnt == 0) {
QUrl url = QUrl::fromLocalFile(str); // If playlist is empty, current index should be invalid.
if (url.isValid()) { m_currentIndex = std::nullopt;
urlList.append(url); } else {
if (m_currentIndex.has_value()) {
// Clamp current index in playlist range.
// If it is already in range, not change was done.
auto currentIndex = *m_currentIndex;
if (currentIndex < 0) {
m_currentIndex = 0;
} else if (currentIndex >= cnt) {
m_currentIndex = cnt - 1;
} else {
; // No change.
}
} else {
// If there is no set value for current index,
// set it at the beginning of playlist.
m_currentIndex = 0;
} }
} }
return urlList;
} }
bool PlaylistManager::checkUrl(const QUrl& url)
{
return url.isValid() && url.isLocalFile();
}
QUrl PlaylistManager::urlFromString(const QString& file)
{
return QUrl::fromLocalFile(file);
}
// endregion
+107 -65
View File
@@ -5,84 +5,126 @@
#pragma once #pragma once
#include <QUrl> #include <QUrl>
#include <QAbstractListModel> #include <QObject>
#include <optional>
class PlaylistModel : public QAbstractListModel
{
Q_OBJECT
public:
enum PlaylistRole {
UrlRole = Qt::UserRole
};
Q_ENUM(PlaylistRole)
Q_PROPERTY(QStringList autoLoadFilterSuffixes MEMBER m_autoLoadSuffixes NOTIFY autoLoadFilterSuffixesChanged)
explicit PlaylistModel(QObject *parent = nullptr);
~PlaylistModel() override;
void setPlaylist(const QList<QUrl> & urls);
QModelIndex loadPlaylist(const QList<QUrl> & urls);
QModelIndex loadPlaylist(const QUrl & url);
QModelIndex appendToPlaylist(const QUrl & url);
bool removeAt(int index);
int indexOf(const QUrl & url) const;
QUrl urlByIndex(int index) const;
QStringList autoLoadFilterSuffixes() const;
QHash<int, QByteArray> roleNames() const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
signals:
void autoLoadFilterSuffixesChanged(QStringList suffixes);
private:
// model data
QList<QUrl> m_playlist;
// properties
QStringList m_autoLoadSuffixes = {};
// internal
QString m_currentDir;
};
/// The manager of playlist.
class PlaylistManager : public QObject class PlaylistManager : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
Q_PROPERTY(int currentIndex MEMBER m_currentIndex NOTIFY currentIndexChanged) /// Constructs a PlaylistManager with an optional parent QObject.
Q_PROPERTY(QStringList autoLoadFilterSuffixes WRITE setAutoLoadFilterSuffixes) explicit PlaylistManager(QObject* parent = nullptr);
Q_PROPERTY(PlaylistModel * model READ model CONSTANT) /// Destructor.
explicit PlaylistManager(QObject *parent = nullptr);
~PlaylistManager(); ~PlaylistManager();
PlaylistModel * model(); /// Get the allowed file suffixes of this playlist.
/// @return The current list of allowed suffixes.
const QStringList& allowedSuffixes() const;
/// Set the allowed file suffixes of this playlist.
/// @remark This only works for "load the whole directory by one file" case.
/// @param[in] nameFilters The new list of allowed suffixes.
void setAllowedSuffixes(const QStringList& nameFilters);
void setPlaylist(const QList<QUrl> & url); /// Load user specified files as playlist.
Q_INVOKABLE QModelIndex loadPlaylist(const QList<QUrl> & urls); /// @remark The wrapper for another overload.
Q_INVOKABLE QModelIndex loadPlaylist(const QUrl & url); /// @return True for successful load, otherwise false.
Q_INVOKABLE QModelIndex loadM3U8Playlist(const QUrl & url); bool loadPlaylist(const QStringList& files);
/// Load user specified URLs as playlist.
/// @remark This function automatically dispatch these files into correct sub-load functions.
/// @return True for successful load, otherwise false.
bool loadPlaylist(const QList<QUrl>& urls);
/// Clear the entire playlist and reset current index.
void clearPlaylist();
int totalCount() const; /// Append a local file path to the playlist.
QModelIndex previousIndex() const; void appendToPlaylist(const QString& file);
QModelIndex nextIndex() const; /// Append a URL to the playlist.
QModelIndex curIndex() const; void appendToPlaylist(const QUrl& url);
/// Insert a local file path at the given index.
/// @return True if inserted successfully, false if index is out of range.
bool insertIntoPlaylist(qsizetype index, const QString& file);
/// Insert a URL at the given index.
/// @return True if inserted successfully, false if index is out of range.
bool insertIntoPlaylist(qsizetype index, const QUrl& url);
/// Remove the entry at the given index.
/// @return True if removed successfully, false if index is out of range.
bool removeFromPlaylist(qsizetype index);
/// Returns the total number of items in the playlist.
/// @return Total count of entries in the playlist.
qsizetype totalCount() const;
/// Try fetching previous index.
/// @details This previous index is gallery-loop-aware.
/// @return std::nullopt if playlist is empty, otherwise the previous index considering gallery loop.
std::optional<qsizetype> previousIndex() const;
/// Try fetching next index.
/// @details This next index is gallery-loop-aware.
/// @return std::nullopt if playlist is empty, otherwise the next index considering gallery loop.
std::optional<qsizetype> nextIndex() const;
/// Check whether current index is the first index.
/// @return False if current index is not the first index or playlist is empty, otherwise true.
bool isFirstIndex() const; bool isFirstIndex() const;
/// Check whether current index is the last index.
/// @return False if current index is not the last index or playlist is empty, otherwise true.
bool isLastIndex() const; bool isLastIndex() const;
void setCurrentIndex(const QModelIndex & index); /// Returns the current index.
QUrl urlByIndex(const QModelIndex & index); /// @return std::nullopt if the playlist is empty, otherwise the current index.
QString localFileByIndex(const QModelIndex & index); std::optional<qsizetype> currentIndex() const;
bool removeAt(const QModelIndex & index); /// Set the current index.
/// @remark Index only can be set when playlist is not empty.
void setAutoLoadFilterSuffixes(const QStringList &nameFilters); /// @return True if successful set, including "not changed" set, otherwise false.
/// This return value only indicates whether we can set index and given index is valid for setting.
static QList<QUrl> convertToUrlList(const QStringList & files); /// If "no changed" set occurs, this function returns true, but doesn't raise current index changed signal.
bool setCurrentIndex(qsizetype index);
/// Returns the URL at the given index.
/// @return The URL if index is valid.
/// This class guarantee that this QUrl is pointing to a local file.
QUrl urlByIndex(qsizetype index) const;
/// Returns the local file path at the given index.
/// @return The local file path if index is valid.
/// This class guarantee that local file path always is valid.
QString localFileByIndex(qsizetype index) const;
signals: signals:
void currentIndexChanged(int index); void allowedSuffixesChanged(const QStringList& suffixes);
void totalCountChanged(int count); /// Raised when index was changed bu setter.
/// The argument holds the new current index.
/// Please note that this signal will NOT be raised by the whole playlist change caused index change.
void currentIndexChanged(qsizetype index);
/// The whole playlist was changed, involving loading, editing and deleting some or full entries.
/// The argument holds the total count of new play list.
void playlistChanged(qsizetype count);
private: private:
int m_currentIndex = -1; /// The fundamental playlist setter.
PlaylistModel m_model; /// @details All playlist load functions will call this function to set playlist at last.
/// @param[in] urls ALl urls in this list should be checked by checkUrl() function.
/// @param[in] indexHint Try to set current index to this index if possible.
void setPlaylist(const QList<QUrl>&& urls, std::optional<qsizetype> indexHint = std::nullopt);
/// Load playlist from a single file.
/// @details This function scans the same directory for siblings matching allowed suffixes, sorted naturally.
/// @return True if the playlist was loaded successfully, false otherwise.
bool loadSingleFilePlaylist(const QUrl& url);
/// Load playlist from multiple URLs directly.
/// @return True if all URLs are valid, false otherwise.
bool loadMultipleFilesPlaylist(const QList<QUrl>&& urls);
/// Load playlist from an M3U/M3U8 playlist file.
/// @return True if loaded successfully, false otherwise.
bool loadM3U8Playlist(const QUrl& url);
/// Make sure that current index is valid.
/// @details This function usually is used by those functions manipulating playlist.
void sanitizeIndex();
/// Check whether given QUrl is proper to be put into playlist.
/// @details Only the url pointing to local file can be put into playlist.
static bool checkUrl(const QUrl& url);
/// Convert a string to local file into a QUrl.
/// @param[in] file The string pointing to local file.
static QUrl urlFromString(const QString& file);
std::optional<qsizetype> m_currentIndex;
QList<QUrl> m_playlist;
QStringList m_allowedSuffixes;
}; };
+25
View File
@@ -0,0 +1,25 @@
// SPDX-FileCopyrightText: 2026 yyc12345 <yyc12321@outlook.com>
//
// SPDX-License-Identifier: MIT
#include "playlistscout.h"
#include "playlistscouts/qtscout.h"
#include "playlistscouts/explorerscout.h"
std::optional<PlaylistScout::ScoutResult> PlaylistScout::scout(
const QUrl &url, const QStringList &allowedSuffixes) {
#ifdef Q_OS_WIN
// In Windows, Qt approach can not aware Windows Explorer custom sort order.
// So we need to try using Win32 functions for fetching it at first.
if (auto rv = PlaylistScout::Explorer::scout(url, allowedSuffixes); rv.has_value()) {
return rv;
}
#endif // Q_OS_WIN
// TODO: We may add macOS Finder, KDE Dolphin and etc supports in future.
// Qt way is the last fallback.
return PlaylistScout::Qt::scout(url, allowedSuffixes);
}
+31
View File
@@ -0,0 +1,31 @@
// SPDX-FileCopyrightText: 2026 yyc12345 <yyc12321@outlook.com>
//
// SPDX-License-Identifier: MIT
#pragma once
#include <QUrl>
#include <QStringList>
#include <QList>
#include <optional>
namespace PlaylistScout {
/// The result of scout
struct ScoutResult {
/// The final fetched playlist (it can be empty).
/// Each item must be a QUrl pointing to a local file.
QList<QUrl> playlist;
/// The index of given file located in playlist.
/// Nullopt if it is not presented in playlist.
std::optional<qsizetype> indexHint;
};
/// @brief Scout available image files in given file's parent dir with given allowed suffixes.
/// @param[in] url The path to file whose parent dir is our target dir for finding image files.
/// @param[in] allowedSuffixes
/// Each items in this list is a wildcard pattern for matching allowed file name, like \c *.png .
/// The fetched item will be preserved if its name matching any of them.
/// If this list is empty, there is no restrictions for finding files.
/// @return Scout result if success, otherwise nullopt.
std::optional<ScoutResult> scout(const QUrl &url, const QStringList &allowedSuffixes);
}
+332
View File
@@ -0,0 +1,332 @@
// SPDX-FileCopyrightText: 2026 yyc12345 <yyc12321@outlook.com>
//
// SPDX-License-Identifier: MIT
#include "explorerscout.h"
#ifdef Q_OS_WIN
#include <QDir>
#include <QDebug>
#include <QFileInfo>
#include <QRegularExpression>
#include <optional>
#include <exdisp.h> // IShellWindows, CLSID_ShellWindows
#include <servprov.h> // IServiceProvider
#include <shlguid.h> // SID_STopLevelBrowser
#include <shlobj.h>
// YYC MARK:
// We use custom RAII wrappers instead of existing COM smart pointers because the
// project may be built with MinGW, which does not have good compatibility with
// CComPtr and Microsoft's WRL ComPtr (<wrl/client.h>).
// Furthermore, PIDLs are not COM objects (they are freed via ILFree, not Release),
// so no standard smart pointer covers them regardless of compiler.
/// RAII wrapper for COM initialization (CoInitialize / CoUninitialize).
/// Must be declared before any COM objects (e.g., ComPtr, UniquePidl) so that
/// CoUninitialize runs after all COM objects are released during scope exit.
class ComGuard {
public:
ComGuard() : m_hr(CoInitialize(nullptr)) {}
~ComGuard() { if (SUCCEEDED(m_hr)) CoUninitialize(); }
ComGuard(const ComGuard&) = delete;
ComGuard& operator=(const ComGuard&) = delete;
bool IsInitialized() const { return SUCCEEDED(m_hr); }
private:
HRESULT m_hr;
};
/// RAII wrapper for COM interface pointers.
template <typename T>
class ComPtr {
public:
ComPtr() = default;
ComPtr(std::nullptr_t) {}
~ComPtr() { Reset(); }
ComPtr(const ComPtr&) = delete;
ComPtr& operator=(const ComPtr&) = delete;
ComPtr(ComPtr&& other) noexcept : m_ptr(other.m_ptr) { other.m_ptr = nullptr; }
ComPtr& operator=(ComPtr&& other) noexcept {
if (this != &other) {
Reset();
m_ptr = other.m_ptr;
other.m_ptr = nullptr;
}
return *this;
}
T* operator->() const { return m_ptr; }
T* Get() const { return m_ptr; }
T** GetAddressOf() { return &m_ptr; }
explicit operator bool() const { return m_ptr != nullptr; }
void Reset() { if (m_ptr) { m_ptr->Release(); m_ptr = nullptr; } }
private:
T* m_ptr = nullptr;
};
/// RAII wrapper for PIDL (Item ID List).
class UniquePidl {
public:
UniquePidl() = default;
explicit UniquePidl(LPITEMIDLIST pidl) : m_pidl(pidl) {}
~UniquePidl() { Reset(); }
UniquePidl(const UniquePidl&) = delete;
UniquePidl& operator=(const UniquePidl&) = delete;
UniquePidl(UniquePidl&& other) noexcept : m_pidl(other.m_pidl) { other.m_pidl = nullptr; }
UniquePidl& operator=(UniquePidl&& other) noexcept {
if (this != &other) {
Reset();
m_pidl = other.m_pidl;
other.m_pidl = nullptr;
}
return *this;
}
LPCITEMIDLIST Get() const { return m_pidl; }
LPITEMIDLIST* GetAddressOf() { return &m_pidl; }
explicit operator bool() const { return m_pidl != nullptr; }
void Reset() { if (m_pidl) { ILFree(m_pidl); m_pidl = nullptr; } }
private:
LPITEMIDLIST m_pidl = nullptr;
};
/// Outputs a diagnostic warning for debugging Windows Explorer integration failures.
static void ReportError(const QString& detail)
{
qWarning("Windows Explorer file list fetch error: %s",
qPrintable(detail));
}
/// Normalizes a Windows directory path for case-insensitive comparison:
/// converts to native separators, lowercases, and ensures a trailing backslash.
static QString NormalizePath(const QString& path)
{
QString result = QDir::toNativeSeparators(path).toLower();
if (!result.endsWith(QChar('\\'))) {
result += QChar('\\');
}
return result;
}
/// Checks whether the Explorer window represented by the given IDispatch is
/// displaying the target folder. Returns its IFolderView2 on match, or null.
static ComPtr<IFolderView2> TryMatchWindow(IDispatch* dispatch, const QString& normalizedTarget)
{
// Navigate: IDispatch -> IServiceProvider -> IShellBrowser.
ComPtr<IServiceProvider> serviceProvider;
if (FAILED(dispatch->QueryInterface(IID_PPV_ARGS(serviceProvider.GetAddressOf())))) {
return nullptr;
}
ComPtr<IShellBrowser> shellBrowser;
if (FAILED(serviceProvider->QueryService(SID_STopLevelBrowser,
IID_PPV_ARGS(shellBrowser.GetAddressOf())))) {
return nullptr;
}
// IShellBrowser -> active IShellView.
ComPtr<IShellView> shellView;
if (FAILED(shellBrowser->QueryActiveShellView(shellView.GetAddressOf()))) {
return nullptr;
}
// Retrieve the folder's path via IPersistIDList.
ComPtr<IPersistIDList> persistIdList;
if (FAILED(shellView->QueryInterface(IID_PPV_ARGS(persistIdList.GetAddressOf())))) {
return nullptr;
}
UniquePidl folderPidl;
if (FAILED(persistIdList->GetIDList(folderPidl.GetAddressOf()))) {
return nullptr;
}
PWSTR pathStr = nullptr;
if (FAILED(SHGetNameFromIDList(folderPidl.Get(), SIGDN_DESKTOPABSOLUTEPARSING, &pathStr))) {
return nullptr;
}
QString windowPath = NormalizePath(QString::fromWCharArray(pathStr));
CoTaskMemFree(pathStr);
if (windowPath != normalizedTarget) {
return nullptr;
}
// Path matches — query IFolderView2 from the ShellView.
ComPtr<IFolderView2> folderView2;
if (FAILED(shellView->QueryInterface(IID_PPV_ARGS(folderView2.GetAddressOf())))) {
return nullptr;
}
return folderView2;
}
/// Tries to find a live Explorer window that is currently displaying the given
/// folder path. Returns the IFolderView2 from that window, or an empty ComPtr.
///
/// Explorer's sort order is stored only in the running Explorer process's memory.
/// Creating a new shell view via IShellFolder::CreateViewObject yields a default
/// sort (always by name), so we must find the actual live IFolderView2 instead.
///
/// Reference:
/// - https://www.stephenli.ca/getting-windows-explorers-current-directory-sort-order
/// - https://github.com/d2phap/ImageGlass/blob/75a296287f338edcf409eee3917531b25ff5d927/v9/Components/ImageGlass.Base/FileSystem/FileFinder.cs
/// - NuGet Package: D2Phap.EggShell
static ComPtr<IFolderView2> FindLiveFolderView(const QString& targetFolderPath)
{
// Create the Shell windows collection (all open Explorer windows).
ComPtr<IShellWindows> shellWindows;
if (FAILED(CoCreateInstance(CLSID_ShellWindows, nullptr, CLSCTX_ALL,
IID_PPV_ARGS(shellWindows.GetAddressOf())))) {
ReportError("Failed to create IShellWindows instance");
return nullptr;
}
QString normalizedTarget = NormalizePath(targetFolderPath);
// 1. Try the Desktop window first — it may contain the file the user opened.
{
VARIANT varLoc;
VariantInit(&varLoc);
varLoc.vt = VT_I4;
varLoc.lVal = 0;
VARIANT varLocRoot;
VariantInit(&varLocRoot);
long desktopHwnd = 0;
ComPtr<IDispatch> desktopDispatch;
HRESULT findHr = shellWindows->FindWindowSW(
&varLoc, &varLocRoot, SWC_DESKTOP,
&desktopHwnd, SWFO_NEEDDISPATCH,
desktopDispatch.GetAddressOf());
VariantClear(&varLoc);
VariantClear(&varLocRoot);
if (SUCCEEDED(findHr) && desktopDispatch) {
ComPtr<IFolderView2> result = TryMatchWindow(desktopDispatch.Get(), normalizedTarget);
if (result) return result;
}
}
// 2. Iterate regular Explorer windows.
LONG count = 0;
shellWindows->get_Count(&count);
for (LONG i = 0; i < count; i++) {
VARIANT varIndex;
VariantInit(&varIndex);
varIndex.vt = VT_I4;
varIndex.lVal = i;
ComPtr<IDispatch> dispatch;
HRESULT itemHr = shellWindows->Item(varIndex, dispatch.GetAddressOf());
VariantClear(&varIndex);
if (FAILED(itemHr) || !dispatch) {
continue;
}
ComPtr<IFolderView2> result = TryMatchWindow(dispatch.Get(), normalizedTarget);
if (result) return result;
}
return nullptr;
}
std::optional<PlaylistScout::ScoutResult> PlaylistScout::Explorer::scout(
const QUrl &url, const QStringList &allowedSuffixes) {
PlaylistScout::ScoutResult rv;
QFileInfo info(url.toLocalFile());
QString folderPath = info.path();
QString currentFileName = info.fileName();
// Pre-compile wildcard suffix filters into regular expressions for performance.
QList<QRegularExpression> nameRegexps;
for (const QString &pattern : allowedSuffixes) {
nameRegexps.append(QRegularExpression(
QRegularExpression::wildcardToRegularExpression(pattern),
QRegularExpression::CaseInsensitiveOption));
}
// Initialize COM. The ComGuard must be declared before any COM objects
// below so that CoUninitialize runs after all of them are released.
ComGuard comGuard;
if (!comGuard.IsInitialized()) {
ReportError("COM initialization failed");
return std::nullopt;
}
// Find a live Explorer window that is currently displaying the target folder.
ComPtr<IFolderView2> folderView2 = FindLiveFolderView(folderPath);
if (!folderView2) {
ReportError("No open Explorer window matches the folder: " + folderPath);
return std::nullopt;
}
// Get items already sorted in Explorer's view order, as an IShellItemArray.
// SVGIO_ALLVIEW returns all items; SVGIO_FLAG_VIEWORDER respects the view's sort.
ComPtr<IShellItemArray> itemArray;
if (FAILED(folderView2->Items(SVGIO_ALLVIEW | SVGIO_FLAG_VIEWORDER,
IID_PPV_ARGS(itemArray.GetAddressOf())))) {
ReportError("IFolderView2::Items(SVGIO_ALLVIEW | SVGIO_FLAG_VIEWORDER) failed");
return std::nullopt;
}
DWORD itemCount = 0;
itemArray->GetCount(&itemCount);
// Enumerate sorted items, filter by pattern, and build the playlist.
for (DWORD i = 0; i < itemCount; i++) {
ComPtr<IShellItem> shellItem;
if (FAILED(itemArray->GetItemAt(i, shellItem.GetAddressOf()))) {
continue;
}
// Get the full parsing path of the item.
PWSTR pathStr = nullptr;
if (FAILED(shellItem->GetDisplayName(SIGDN_DESKTOPABSOLUTEPARSING, &pathStr)) || !pathStr) {
continue;
}
QString filePath = QString::fromWCharArray(pathStr);
CoTaskMemFree(pathStr);
// Skip directories — the view may include folders alongside files.
QFileInfo fileInfo(filePath);
if (!fileInfo.isFile()) {
continue;
}
QString fileName = fileInfo.fileName();
// Match against compiled wildcard patterns.
bool matches = nameRegexps.isEmpty();
for (const QRegularExpression &re : std::as_const(nameRegexps)) {
if (re.match(fileName).hasMatch()) {
matches = true;
break;
}
}
if (!matches) {
continue;
}
rv.playlist.append(QUrl::fromLocalFile(filePath));
if (fileName == currentFileName) {
rv.indexHint = rv.playlist.size() - 1;
}
}
return rv;
}
#endif // Q_OS_WIN
+16
View File
@@ -0,0 +1,16 @@
// SPDX-FileCopyrightText: 2026 yyc12345 <yyc12321@outlook.com>
//
// SPDX-License-Identifier: MIT
#pragma once
#include "../playlistscout.h"
#include <QtSystemDetection>
#ifdef Q_OS_WIN
namespace PlaylistScout::Explorer {
std::optional<ScoutResult> scout(const QUrl &url, const QStringList &allowedSuffixes);
}
#endif // Q_OS_WIN
+40
View File
@@ -0,0 +1,40 @@
// SPDX-FileCopyrightText: 2025 Gary Wang <git@blumia.net>
// SPDX-FileCopyrightText: 2026 yyc12345 <yyc12321@outlook.com>
//
// SPDX-License-Identifier: MIT
#include "qtscout.h"
#include <QFileInfo>
#include <QDir>
#include <QCollator>
std::optional<PlaylistScout::ScoutResult> PlaylistScout::Qt::scout(
const QUrl &url, const QStringList &allowedSuffixes) {
PlaylistScout::ScoutResult rv;
QFileInfo info(url.toLocalFile());
QDir dir(info.path());
QString currentFileName = info.fileName();
QStringList entryList = dir.entryList(
allowedSuffixes, QDir::Files | QDir::NoSymLinks, QDir::NoSort);
QCollator collator;
collator.setNumericMode(true);
std::sort(entryList.begin(), entryList.end(), collator);
for (qsizetype i = 0; i < entryList.count(); i++) {
const QString &fileName = entryList.at(i);
const QString &oneEntry = dir.absoluteFilePath(fileName);
const QUrl &url = QUrl::fromLocalFile(oneEntry);
rv.playlist.append(url);
if (fileName == currentFileName) {
rv.indexHint = i;
}
}
return rv;
}
+11
View File
@@ -0,0 +1,11 @@
// SPDX-FileCopyrightText: 2026 yyc12345 <yyc12321@outlook.com>
//
// SPDX-License-Identifier: MIT
#pragma once
#include "../playlistscout.h"
namespace PlaylistScout::Qt {
std::optional<ScoutResult> scout(const QUrl &url, const QStringList &allowedSuffixes);
}
+14 -74
View File
@@ -13,6 +13,14 @@
#include <QKeySequence> #include <QKeySequence>
#include <QMetaEnum> #include <QMetaEnum>
Settings *Settings::instance()
{
// SAFETY:
// This is a global singleton and it is leaked by design.
static Settings* INSTANCE = new Settings(nullptr);
return INSTANCE;
}
namespace QEnumHelper namespace QEnumHelper
{ {
template <typename E> template <typename E>
@@ -34,17 +42,6 @@ namespace QEnumHelper
} }
} }
Settings *Settings::m_settings_instance = nullptr;
Settings *Settings::instance()
{
if (!m_settings_instance) {
m_settings_instance = new Settings;
}
return m_settings_instance;
}
bool Settings::useLightCheckerboard() const bool Settings::useLightCheckerboard() const
{ {
return m_qsettings->value("use_light_checkerboard", false).toBool(); return m_qsettings->value("use_light_checkerboard", false).toBool();
@@ -68,31 +65,21 @@ bool Settings::svgTiny12Only() const
#endif // QT_VERSION < QT_VERSION_CHECK(6, 9, 3) #endif // QT_VERSION < QT_VERSION_CHECK(6, 9, 3)
} }
Settings::DoubleClickBehavior Settings::doubleClickBehavior() const
{
QString result = m_qsettings->value("double_click_behavior", "Close").toString();
return QEnumHelper::fromString<DoubleClickBehavior>(result, DoubleClickBehavior::Close);
}
Settings::MouseWheelBehavior Settings::mouseWheelBehavior() const Settings::MouseWheelBehavior Settings::mouseWheelBehavior() const
{ {
QString result = m_qsettings->value("mouse_wheel_behavior", "Zoom").toString(); QString result = m_qsettings->value("mouse_wheel_behavior", "").toString();
return QEnumHelper::fromString<MouseWheelBehavior>(result, MouseWheelBehavior::Zoom); return QEnumHelper::fromString<MouseWheelBehavior>(result, MouseWheelBehavior::Zoom);
} }
Settings::WindowSizeBehavior Settings::initWindowSizeBehavior() const Settings::WindowSizeBehavior Settings::initWindowSizeBehavior() const
{ {
QString result = m_qsettings->value("init_window_size_behavior", "Auto").toString(); QString result = m_qsettings->value("init_window_size_behavior", "").toString();
return QEnumHelper::fromString<WindowSizeBehavior>(result, WindowSizeBehavior::Windowed);
return QEnumHelper::fromString<WindowSizeBehavior>(result, WindowSizeBehavior::Auto);
} }
Qt::HighDpiScaleFactorRoundingPolicy Settings::hiDpiScaleFactorBehavior() const Qt::HighDpiScaleFactorRoundingPolicy Settings::hiDpiScaleFactorBehavior() const
{ {
QString result = m_qsettings->value("hidpi_scale_factor_behavior", "PassThrough").toString(); QString result = m_qsettings->value("hidpi_scale_factor_behavior", "").toString();
return QEnumHelper::fromString<Qt::HighDpiScaleFactorRoundingPolicy>(result, Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); return QEnumHelper::fromString<Qt::HighDpiScaleFactorRoundingPolicy>(result, Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
} }
@@ -114,12 +101,6 @@ void Settings::setSvgTiny12Only(bool on)
m_qsettings->sync(); m_qsettings->sync();
} }
void Settings::setDoubleClickBehavior(DoubleClickBehavior dcb)
{
m_qsettings->setValue("double_click_behavior", QEnumHelper::toString(dcb));
m_qsettings->sync();
}
void Settings::setMouseWheelBehavior(MouseWheelBehavior mwb) void Settings::setMouseWheelBehavior(MouseWheelBehavior mwb)
{ {
m_qsettings->setValue("mouse_wheel_behavior", QEnumHelper::toString(mwb)); m_qsettings->setValue("mouse_wheel_behavior", QEnumHelper::toString(mwb));
@@ -138,47 +119,6 @@ void Settings::setHiDpiScaleFactorBehavior(Qt::HighDpiScaleFactorRoundingPolicy
m_qsettings->sync(); m_qsettings->sync();
} }
void Settings::applyUserShortcuts(QWidget *widget)
{
m_qsettings->beginGroup("shortcuts");
const QStringList shortcutNames = m_qsettings->allKeys();
for (const QString & name : shortcutNames) {
QList<QKeySequence> shortcuts = m_qsettings->value(name).value<QList<QKeySequence>>();
setShortcutsForAction(widget, name, shortcuts, false);
}
m_qsettings->endGroup();
}
bool Settings::setShortcutsForAction(QWidget *widget, const QString &objectName,
QList<QKeySequence> shortcuts, bool writeConfig)
{
QAction * targetAction = nullptr;
for (QAction * action : widget->actions()) {
if (action->objectName() == objectName) {
targetAction = action;
} else {
for (const QKeySequence & shortcut : std::as_const(shortcuts)) {
if (action->shortcuts().contains(shortcut)) {
return false;
}
}
}
}
if (targetAction) {
targetAction->setShortcuts(shortcuts);
}
if (targetAction && writeConfig) {
m_qsettings->beginGroup("shortcuts");
m_qsettings->setValue(objectName, QVariant::fromValue(shortcuts));
m_qsettings->endGroup();
m_qsettings->sync();
}
return true;
}
#if defined(FLAG_PORTABLE_MODE_SUPPORT) && defined(Q_OS_WIN) #if defined(FLAG_PORTABLE_MODE_SUPPORT) && defined(Q_OS_WIN)
#include <windows.h> #include <windows.h>
// QCoreApplication::applicationDirPath() parses the "applicationDirPath" from arg0, which... // QCoreApplication::applicationDirPath() parses the "applicationDirPath" from arg0, which...
@@ -197,8 +137,8 @@ QString getApplicationDirPath()
} }
#endif // defined(FLAG_PORTABLE_MODE_SUPPORT) && defined(Q_OS_WIN) #endif // defined(FLAG_PORTABLE_MODE_SUPPORT) && defined(Q_OS_WIN)
Settings::Settings() Settings::Settings(QObject *parent)
: QObject(qApp) : QObject(parent)
{ {
QString configPath; QString configPath;
+1 -18
View File
@@ -11,14 +11,6 @@ class Settings : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
enum DoubleClickBehavior {
Ignore,
Close,
Maximize,
FullScreen,
};
Q_ENUM(DoubleClickBehavior)
enum MouseWheelBehavior { enum MouseWheelBehavior {
Zoom, Zoom,
Switch, Switch,
@@ -26,7 +18,6 @@ public:
Q_ENUM(MouseWheelBehavior) Q_ENUM(MouseWheelBehavior)
enum WindowSizeBehavior { enum WindowSizeBehavior {
Auto,
Maximized, Maximized,
Windowed, Windowed,
}; };
@@ -37,7 +28,6 @@ public:
bool useLightCheckerboard() const; bool useLightCheckerboard() const;
bool loopGallery() const; bool loopGallery() const;
bool svgTiny12Only() const; bool svgTiny12Only() const;
DoubleClickBehavior doubleClickBehavior() const;
MouseWheelBehavior mouseWheelBehavior() const; MouseWheelBehavior mouseWheelBehavior() const;
WindowSizeBehavior initWindowSizeBehavior() const; WindowSizeBehavior initWindowSizeBehavior() const;
Qt::HighDpiScaleFactorRoundingPolicy hiDpiScaleFactorBehavior() const; Qt::HighDpiScaleFactorRoundingPolicy hiDpiScaleFactorBehavior() const;
@@ -45,19 +35,12 @@ public:
void setUseLightCheckerboard(bool light); void setUseLightCheckerboard(bool light);
void setLoopGallery(bool on); void setLoopGallery(bool on);
void setSvgTiny12Only(bool on); void setSvgTiny12Only(bool on);
void setDoubleClickBehavior(DoubleClickBehavior dcb);
void setMouseWheelBehavior(MouseWheelBehavior mwb); void setMouseWheelBehavior(MouseWheelBehavior mwb);
void setInitWindowSizeBehavior(WindowSizeBehavior wsb); void setInitWindowSizeBehavior(WindowSizeBehavior wsb);
void setHiDpiScaleFactorBehavior(Qt::HighDpiScaleFactorRoundingPolicy hidpi); void setHiDpiScaleFactorBehavior(Qt::HighDpiScaleFactorRoundingPolicy hidpi);
void applyUserShortcuts(QWidget * widget);
bool setShortcutsForAction(QWidget * widget, const QString & objectName,
QList<QKeySequence> shortcuts, bool writeConfig = true);
private: private:
Settings(); Settings(QObject *parent = nullptr);
static Settings *m_settings_instance;
QSettings *m_qsettings; QSettings *m_qsettings;
+97 -150
View File
@@ -3,149 +3,94 @@
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
#include "settingsdialog.h" #include "settingsdialog.h"
#include "ui_settingsdialog.h"
#include "settings.h" #include "settings.h"
#include "shortcutedit.h"
#include <QAction> #include <QApplication>
#include <QCheckBox> #include <QTimer>
#include <QComboBox>
#include <QFormLayout>
#include <QKeySequenceEdit>
#include <QScrollArea>
#include <QSplitter>
#include <QStringListModel> #include <QStringListModel>
#include <QMessageBox> #include <type_traits>
template <typename E, typename = std::enable_if_t<std::is_enum_v<E>>>
class EnumComboBoxTransformer {
public:
using Pair = QPair<E, QString>;
using Pairs = QList<QPair<E, QString>>;
EnumComboBoxTransformer(Pairs &&pairs) : pairs(std::move(pairs)) {}
~EnumComboBoxTransformer() = default;
Q_DISABLE_COPY_MOVE(EnumComboBoxTransformer)
/// Build Qt model used for QComboBox
QStringListModel* buildComboBoxModel(QObject *parent = nullptr) const {
QStringList dropDownEntries;
for (const auto& pair : std::as_const(this->pairs)) {
dropDownEntries.append(pair.second);
}
return new QStringListModel(dropDownEntries, parent);
}
/// Convert QComboBox index to enum value.
E to_value(int index) const {
return this->pairs.at(static_cast<qsizetype>(index)).first;
}
/// Convert enum value to QComboBox index.
int to_index(E value) const {
for (qsizetype i = 0; i < pairs.size(); ++i) {
if (pairs.at(i).first == value) {
return static_cast<int>(i);
}
}
// Value not found
throw std::invalid_argument("invalid enum value for finding index");
}
private:
Pairs pairs;
};
static EnumComboBoxTransformer<Settings::MouseWheelBehavior, QString> MW_OPTIONS {
{
{ Settings::MouseWheelBehavior::Zoom, QCoreApplication::translate("SettingsDialog", "Zoom in and out") },
{ Settings::MouseWheelBehavior::Switch, QCoreApplication::translate("SettingsDialog", "View next or previous item") }
}
};
static EnumComboBoxTransformer<Settings::WindowSizeBehavior, QString> IWS_OPTIONS {
{
{ Settings::WindowSizeBehavior::Maximized, QCoreApplication::translate("SettingsDialog", "Maximized") },
{ Settings::WindowSizeBehavior::Windowed, QCoreApplication::translate("SettingsDialog", "Windowed") }
}
};
static EnumComboBoxTransformer<Qt::HighDpiScaleFactorRoundingPolicy, QString> HIDPI_OPTIONS {
{
{ Qt::HighDpiScaleFactorRoundingPolicy::Round, QCoreApplication::translate("SettingsDialog", "Round (Integer scaling)", "This option means round up for .5 and above") },
{ Qt::HighDpiScaleFactorRoundingPolicy::Ceil, QCoreApplication::translate("SettingsDialog", "Ceil (Integer scaling)", "This option means always round up") },
{ Qt::HighDpiScaleFactorRoundingPolicy::Floor, QCoreApplication::translate("SettingsDialog", "Floor (Integer scaling)", "This option means always round down") },
{ Qt::HighDpiScaleFactorRoundingPolicy::PassThrough, QCoreApplication::translate("SettingsDialog", "Follow system (Fractional scaling)", "This option means don't round") }
}
};
SettingsDialog::SettingsDialog(QWidget *parent) SettingsDialog::SettingsDialog(QWidget *parent)
: QDialog(parent) : QDialog(parent), ui(new QT_PREPEND_NAMESPACE(Ui::SettingsDialog))
, m_useLightCheckerboard(new QCheckBox)
, m_loopGallery(new QCheckBox)
, m_svgTiny12Only(new QCheckBox)
, m_doubleClickBehavior(new QComboBox)
, m_mouseWheelBehavior(new QComboBox)
, m_initWindowSizeBehavior(new QComboBox)
, m_hiDpiRoundingPolicyBehavior(new QComboBox)
{ {
this->setWindowTitle(tr("Settings")); ui->setupUi(this);
setWindowFlag(Qt::WindowContextHelpButtonHint, false);
QHBoxLayout * mainLayout = new QHBoxLayout(this); auto* settings = Settings::instance();
QTabWidget * settingsTabs = new QTabWidget(this); ui->m_useLightCheckerboard->setChecked(settings->useLightCheckerboard());
mainLayout->addWidget(settingsTabs); ui->m_loopGallery->setChecked(settings->loopGallery());
ui->m_svgTiny12Only->setChecked(settings->svgTiny12Only());
QWidget * settingsFormHolder = new QWidget; ui->m_mouseWheelBehavior->setModel(MW_OPTIONS.buildComboBoxModel(this));
QFormLayout * settingsForm = new QFormLayout(settingsFormHolder); Settings::MouseWheelBehavior mwb = settings->mouseWheelBehavior();
settingsTabs->addTab(settingsFormHolder, tr("Options")); ui->m_mouseWheelBehavior->setCurrentIndex(MW_OPTIONS.to_index(mwb));
ui->m_initWindowSizeBehavior->setModel(IWS_OPTIONS.buildComboBoxModel(this));
QSplitter * shortcutEditorSplitter = new QSplitter; Settings::WindowSizeBehavior iwsb = settings->initWindowSizeBehavior();
shortcutEditorSplitter->setOrientation(Qt::Vertical); ui->m_initWindowSizeBehavior->setCurrentIndex(IWS_OPTIONS.to_index(iwsb));
shortcutEditorSplitter->setChildrenCollapsible(false); ui->m_hiDpiRoundingPolicyBehavior->setModel(HIDPI_OPTIONS.buildComboBoxModel(this));
QScrollArea * shortcutScrollArea = new QScrollArea; Qt::HighDpiScaleFactorRoundingPolicy hidpi = settings->hiDpiScaleFactorBehavior();
shortcutEditorSplitter->addWidget(shortcutScrollArea); ui->m_hiDpiRoundingPolicyBehavior->setCurrentIndex(HIDPI_OPTIONS.to_index(hidpi));
shortcutScrollArea->setWidgetResizable(true);
shortcutScrollArea->setMinimumHeight(200);
QWidget * shortcutsFormHolder = new QWidget;
QFormLayout * shortcutsForm = new QFormLayout(shortcutsFormHolder);
shortcutScrollArea->setWidget(shortcutsFormHolder);
settingsTabs->addTab(shortcutEditorSplitter, tr("Shortcuts"));
for (const QAction * action : parent->actions()) {
ShortcutEdit * shortcutEdit = new ShortcutEdit;
shortcutEdit->setObjectName(QLatin1String("shortcut_") + action->objectName());
shortcutEdit->setShortcuts(action->shortcuts());
shortcutsForm->addRow(action->text(), shortcutEdit);
connect(shortcutEdit, &ShortcutEdit::editButtonClicked, this, [=](){
if (shortcutEditorSplitter->count() == 1) shortcutEditorSplitter->addWidget(new QWidget);
ShortcutEditor * shortcutEditor = new ShortcutEditor(shortcutEdit);
shortcutEditor->setDescription(tr("Editing shortcuts for action \"%1\":").arg(action->text()));
QWidget * oldEditor = shortcutEditorSplitter->replaceWidget(1, shortcutEditor);
shortcutEditorSplitter->setSizes({shortcutEditorSplitter->height(), 1});
oldEditor->deleteLater();
});
connect(shortcutEdit, &ShortcutEdit::applyShortcutsRequested, this, [=](QList<QKeySequence> newShortcuts){
bool succ = Settings::instance()->setShortcutsForAction(parent, shortcutEdit->objectName().mid(9),
newShortcuts);
if (!succ) {
QMessageBox::warning(this, tr("Failed to set shortcuts"),
tr("Please check if shortcuts are duplicated with existing shortcuts."));
}
shortcutEdit->setShortcuts(action->shortcuts());
});
}
static QList< QPair<Settings::DoubleClickBehavior, QString> > _dc_options {
{ Settings::DoubleClickBehavior::Ignore, tr("Do nothing") },
{ Settings::DoubleClickBehavior::Close, tr("Close the window") },
{ Settings::DoubleClickBehavior::Maximize, tr("Toggle maximize") },
{ Settings::DoubleClickBehavior::FullScreen, tr("Toggle fullscreen") }
};
static QList< QPair<Settings::MouseWheelBehavior, QString> > _mw_options {
{ Settings::MouseWheelBehavior::Zoom, tr("Zoom in and out") },
{ Settings::MouseWheelBehavior::Switch, tr("View next or previous item") }
};
static QList< QPair<Settings::WindowSizeBehavior, QString> > _iws_options {
{ Settings::WindowSizeBehavior::Auto, tr("Auto size") },
{ Settings::WindowSizeBehavior::Maximized, tr("Maximized") },
{ Settings::WindowSizeBehavior::Windowed, tr("Windowed") }
};
static QList< QPair<Qt::HighDpiScaleFactorRoundingPolicy, QString> > _hidpi_options {
{ Qt::HighDpiScaleFactorRoundingPolicy::Round, tr("Round (Integer scaling)", "This option means round up for .5 and above") },
{ Qt::HighDpiScaleFactorRoundingPolicy::Ceil, tr("Ceil (Integer scaling)", "This option means always round up") },
{ Qt::HighDpiScaleFactorRoundingPolicy::Floor, tr("Floor (Integer scaling)", "This option means always round down") },
{ Qt::HighDpiScaleFactorRoundingPolicy::PassThrough, tr("Follow system (Fractional scaling)", "This option means don't round") }
};
QStringList dcbDropDown;
for (const QPair<Settings::DoubleClickBehavior, QString> & dcOption : _dc_options) {
dcbDropDown.append(dcOption.second);
}
QStringList mwbDropDown;
for (const QPair<Settings::MouseWheelBehavior, QString> & mwOption : _mw_options) {
mwbDropDown.append(mwOption.second);
}
QStringList iwsbDropDown;
for (const QPair<Settings::WindowSizeBehavior, QString> & iwsOption : _iws_options) {
iwsbDropDown.append(iwsOption.second);
}
QStringList hidpiDropDown;
for (const QPair<Qt::HighDpiScaleFactorRoundingPolicy, QString> & hidpiOption : _hidpi_options) {
hidpiDropDown.append(hidpiOption.second);
}
settingsForm->addRow(tr("Use light-color checkerboard"), m_useLightCheckerboard);
settingsForm->addRow(tr("Loop the loaded gallery"), m_loopGallery);
settingsForm->addRow(tr("Limit SVG support to SVG Tiny 1.2"), m_svgTiny12Only);
settingsForm->addRow(tr("Double-click behavior"), m_doubleClickBehavior);
settingsForm->addRow(tr("Mouse wheel behavior"), m_mouseWheelBehavior);
settingsForm->addRow(tr("Default window size"), m_initWindowSizeBehavior);
settingsForm->addRow(tr("HiDPI scale factor rounding policy"), m_hiDpiRoundingPolicyBehavior);
m_useLightCheckerboard->setChecked(Settings::instance()->useLightCheckerboard());
m_loopGallery->setChecked(Settings::instance()->loopGallery());
m_svgTiny12Only->setChecked(Settings::instance()->svgTiny12Only());
m_doubleClickBehavior->setModel(new QStringListModel(dcbDropDown));
Settings::DoubleClickBehavior dcb = Settings::instance()->doubleClickBehavior();
m_doubleClickBehavior->setCurrentIndex(static_cast<int>(dcb));
m_mouseWheelBehavior->setModel(new QStringListModel(mwbDropDown));
Settings::MouseWheelBehavior mwb = Settings::instance()->mouseWheelBehavior();
m_mouseWheelBehavior->setCurrentIndex(static_cast<int>(mwb));
m_initWindowSizeBehavior->setModel(new QStringListModel(iwsbDropDown));
Settings::WindowSizeBehavior iwsb = Settings::instance()->initWindowSizeBehavior();
m_initWindowSizeBehavior->setCurrentIndex(static_cast<int>(iwsb));
m_hiDpiRoundingPolicyBehavior->setModel(new QStringListModel(hidpiDropDown));
Qt::HighDpiScaleFactorRoundingPolicy hidpi = Settings::instance()->hiDpiScaleFactorBehavior();
for (int i = 0; i < _hidpi_options.count(); i++) {
if (_hidpi_options.at(i).first == hidpi) {
m_hiDpiRoundingPolicyBehavior->setCurrentIndex(i);
break;
}
}
#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) #if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
# define QCHECKBOX_CHECKSTATECHANGED QCheckBox::checkStateChanged # define QCHECKBOX_CHECKSTATECHANGED QCheckBox::checkStateChanged
@@ -155,39 +100,41 @@ SettingsDialog::SettingsDialog(QWidget *parent)
# define QT_CHECKSTATE int # define QT_CHECKSTATE int
#endif // QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) #endif // QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
connect(m_useLightCheckerboard, &QCHECKBOX_CHECKSTATECHANGED, this, [ = ](QT_CHECKSTATE state){ connect(ui->m_useLightCheckerboard, &QCHECKBOX_CHECKSTATECHANGED, this, [ = ](QT_CHECKSTATE state){
Settings::instance()->setUseLightCheckerboard(state == Qt::Checked); Settings::instance()->setUseLightCheckerboard(state == Qt::Checked);
}); });
connect(m_loopGallery, &QCHECKBOX_CHECKSTATECHANGED, this, [ = ](QT_CHECKSTATE state){ connect(ui->m_loopGallery, &QCHECKBOX_CHECKSTATECHANGED, this, [ = ](QT_CHECKSTATE state){
Settings::instance()->setLoopGallery(state == Qt::Checked); Settings::instance()->setLoopGallery(state == Qt::Checked);
}); });
connect(m_svgTiny12Only, &QCHECKBOX_CHECKSTATECHANGED, this, [ = ](QT_CHECKSTATE state){ connect(ui->m_svgTiny12Only, &QCHECKBOX_CHECKSTATECHANGED, this, [ = ](QT_CHECKSTATE state){
Settings::instance()->setSvgTiny12Only(state == Qt::Checked); Settings::instance()->setSvgTiny12Only(state == Qt::Checked);
}); });
connect(m_doubleClickBehavior, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [ = ](int index){ connect(ui->m_mouseWheelBehavior, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [ = ](int index){
Settings::instance()->setDoubleClickBehavior(_dc_options.at(index).first); Settings::instance()->setMouseWheelBehavior(MW_OPTIONS.to_value(index));
}); });
connect(m_mouseWheelBehavior, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [ = ](int index){ connect(ui->m_initWindowSizeBehavior, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [ = ](int index){
Settings::instance()->setMouseWheelBehavior(_mw_options.at(index).first); Settings::instance()->setInitWindowSizeBehavior(IWS_OPTIONS.to_value(index));
}); });
connect(m_initWindowSizeBehavior, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [ = ](int index){ connect(ui->m_hiDpiRoundingPolicyBehavior, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [ = ](int index){
Settings::instance()->setInitWindowSizeBehavior(_iws_options.at(index).first); Settings::instance()->setHiDpiScaleFactorBehavior(HIDPI_OPTIONS.to_value(index));
}); });
connect(m_hiDpiRoundingPolicyBehavior, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [ = ](int index){ // YYC MARK:
Settings::instance()->setHiDpiScaleFactorBehavior(_hidpi_options.at(index).first); // Use adjustSize() to make sure all ComboBox are expanded by its items.
// Because items are added after inserting them into layout.
// It is inviable to call this function in ctor because this relys on Qt event system.
// It only can be done by QTimer::singleShot().
QTimer::singleShot(0, this, [this](){
this->adjustSize();
}); });
adjustSize();
setWindowFlag(Qt::WindowContextHelpButtonHint, false);
} }
SettingsDialog::~SettingsDialog() SettingsDialog::~SettingsDialog()
{ {
delete ui;
} }
+7 -14
View File
@@ -5,11 +5,14 @@
#ifndef SETTINGSDIALOG_H #ifndef SETTINGSDIALOG_H
#define SETTINGSDIALOG_H #define SETTINGSDIALOG_H
#include <QObject>
#include <QDialog> #include <QDialog>
class QCheckBox; QT_BEGIN_NAMESPACE
class QComboBox; namespace Ui {
class SettingsDialog;
}
QT_END_NAMESPACE
class SettingsDialog : public QDialog class SettingsDialog : public QDialog
{ {
Q_OBJECT Q_OBJECT
@@ -17,18 +20,8 @@ public:
explicit SettingsDialog(QWidget *parent = nullptr); explicit SettingsDialog(QWidget *parent = nullptr);
~SettingsDialog(); ~SettingsDialog();
signals:
public slots:
private: private:
QCheckBox * m_useLightCheckerboard = nullptr; QT_PREPEND_NAMESPACE(Ui::SettingsDialog) *ui;
QCheckBox * m_loopGallery = nullptr;
QCheckBox * m_svgTiny12Only = nullptr;
QComboBox * m_doubleClickBehavior = nullptr;
QComboBox * m_mouseWheelBehavior = nullptr;
QComboBox * m_initWindowSizeBehavior = nullptr;
QComboBox * m_hiDpiRoundingPolicyBehavior = nullptr;
}; };
#endif // SETTINGSDIALOG_H #endif // SETTINGSDIALOG_H
+81
View File
@@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>SettingsDialog</class>
<widget class="QDialog" name="SettingsDialog">
<property name="windowModality">
<enum>Qt::NonModal</enum>
</property>
<property name="windowTitle">
<string>Settings</string>
</property>
<layout class="QHBoxLayout" name="mainLayout">
<item>
<widget class="QTabWidget" name="settingsTabs">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="optionsTab">
<attribute name="title">
<string>Options</string>
</attribute>
<layout class="QFormLayout" name="settingsForm">
<item row="0" column="0" colspan="2">
<widget class="QCheckBox" name="m_useLightCheckerboard">
<property name="text">
<string>Use light-color checkerboard</string>
</property>
</widget>
</item>
<item row="1" column="0" colspan="2">
<widget class="QCheckBox" name="m_loopGallery">
<property name="text">
<string>Loop the loaded gallery</string>
</property>
</widget>
</item>
<item row="2" column="0" colspan="2">
<widget class="QCheckBox" name="m_svgTiny12Only">
<property name="text">
<string>Limit SVG support to SVG Tiny 1.2</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="m_mouseWheelBehaviorLabel">
<property name="text">
<string>Mouse wheel behavior</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QComboBox" name="m_mouseWheelBehavior"/>
</item>
<item row="4" column="0">
<widget class="QLabel" name="m_initWindowSizeBehaviorLabel">
<property name="text">
<string>Default window size</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QComboBox" name="m_initWindowSizeBehavior"/>
</item>
<item row="5" column="0">
<widget class="QLabel" name="m_hiDpiRoundingPolicyBehaviorLabel">
<property name="text">
<string>HiDPI scale factor rounding policy</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QComboBox" name="m_hiDpiRoundingPolicyBehavior"/>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>
-126
View File
@@ -1,126 +0,0 @@
// SPDX-FileCopyrightText: 2024 Gary Wang <opensource@blumia.net>
//
// SPDX-License-Identifier: MIT
#include "shortcutedit.h"
#include <QLabel>
#include <QToolButton>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QDialogButtonBox>
#include <QKeySequenceEdit>
ShortcutEditor::ShortcutEditor(ShortcutEdit * shortcutEdit, QWidget * parent)
: QWidget(parent)
, m_descriptionLabel(new QLabel)
, m_shortcutEdit(shortcutEdit)
, m_shortcutLayout(new QFormLayout)
{
Q_CHECK_PTR(m_shortcutEdit);
QDialogButtonBox * buttons = new QDialogButtonBox(QDialogButtonBox::Apply | QDialogButtonBox::Discard);
QVBoxLayout * layout = new QVBoxLayout(this);
layout->addWidget(m_descriptionLabel);
layout->addLayout(m_shortcutLayout);
layout->addWidget(buttons);
connect(buttons, &QDialogButtonBox::clicked, this, [=](QAbstractButton *button){
if ((QPushButton *)button == buttons->button(QDialogButtonBox::Apply)) {
applyShortcuts();
} else {
reloadShortcuts();
}
});
connect(shortcutEdit, &ShortcutEdit::shortcutsChanged, this, &ShortcutEditor::reloadShortcuts);
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
reloadShortcuts();
}
void ShortcutEditor::setDescription(const QString &desc)
{
m_descriptionLabel->setText(desc);
}
void ShortcutEditor::reloadShortcuts()
{
if (!m_keySequenceEdits.isEmpty()) {
for (QKeySequenceEdit * keyseqEdit : m_keySequenceEdits) {
m_shortcutLayout->removeRow(keyseqEdit);
}
m_keySequenceEdits.clear();
}
QList<QKeySequence> shortcuts = m_shortcutEdit->shortcuts();
shortcuts.append(QKeySequence());
for (const QKeySequence & shortcut : shortcuts) {
QKeySequenceEdit * keyseqEdit = new QKeySequenceEdit(this);
keyseqEdit->setClearButtonEnabled(true);
#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
keyseqEdit->setMaximumSequenceLength(1);
#endif // QT_VERSION >= QT_VERSION_CHECK(6, 5, 0)
keyseqEdit->setKeySequence(shortcut);
m_keySequenceEdits.append(keyseqEdit);
}
for (int i = 0; i < m_keySequenceEdits.count(); i++) {
m_shortcutLayout->addRow(tr("Shortcut #%1").arg(i + 1), m_keySequenceEdits.at(i));
}
}
void ShortcutEditor::applyShortcuts()
{
QList<QKeySequence> shortcuts;
for (const QKeySequenceEdit * keyseqEdit : m_keySequenceEdits) {
if (!keyseqEdit->keySequence().isEmpty() && !shortcuts.contains(keyseqEdit->keySequence())) {
shortcuts.append(keyseqEdit->keySequence());
}
}
emit m_shortcutEdit->applyShortcutsRequested(shortcuts);
}
// ----------------------------------------
ShortcutEdit::ShortcutEdit(QWidget *parent)
: QWidget(parent)
, m_shortcutsLabel(new QLabel(this))
, m_setShortcutButton(new QToolButton(this))
{
m_setShortcutButton->setText("...");
QHBoxLayout * layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(m_shortcutsLabel, 1);
layout->addWidget(m_setShortcutButton);
connect(this, &ShortcutEdit::shortcutsChanged, this, [=](){
QStringList shortcutTexts;
for (const QKeySequence & shortcut : std::as_const(m_shortcuts)) {
shortcutTexts.append(shortcut.toString(QKeySequence::NativeText));
}
m_shortcutsLabel->setText(shortcutTexts.isEmpty() ? tr("No shortcuts") : shortcutTexts.join(", "));
m_shortcutsLabel->setDisabled(shortcutTexts.isEmpty());
});
connect(m_setShortcutButton, &QToolButton::clicked, this, &ShortcutEdit::editButtonClicked);
adjustSize();
}
ShortcutEdit::~ShortcutEdit()
{
}
QList<QKeySequence> ShortcutEdit::shortcuts() const
{
return m_shortcuts;
}
void ShortcutEdit::setShortcuts(const QList<QKeySequence> &shortcuts)
{
m_shortcuts = shortcuts;
emit shortcutsChanged();
}
-55
View File
@@ -1,55 +0,0 @@
// SPDX-FileCopyrightText: 2024 Gary Wang <opensource@blumia.net>
//
// SPDX-License-Identifier: MIT
#pragma once
#include <QWidget>
#include <QList>
#include <QKeySequence>
class QLabel;
class QFormLayout;
class QToolButton;
class QKeySequenceEdit;
class ShortcutEdit;
class ShortcutEditor : public QWidget
{
Q_OBJECT
public:
explicit ShortcutEditor(ShortcutEdit * shortcutEdit, QWidget * parent = nullptr);
~ShortcutEditor() = default;
void setDescription(const QString & desc);
void reloadShortcuts();
void applyShortcuts();
private:
QLabel * m_descriptionLabel;
ShortcutEdit * m_shortcutEdit;
QFormLayout * m_shortcutLayout;
QList<QKeySequenceEdit *> m_keySequenceEdits;
};
class ShortcutEdit : public QWidget
{
Q_OBJECT
Q_PROPERTY(QList<QKeySequence> shortcuts MEMBER m_shortcuts WRITE setShortcuts NOTIFY shortcutsChanged)
public:
explicit ShortcutEdit(QWidget * parent = nullptr);
~ShortcutEdit();
QList<QKeySequence> shortcuts() const;
void setShortcuts(const QList<QKeySequence> &shortcuts);
signals:
void shortcutsChanged();
void editButtonClicked();
void applyShortcutsRequested(QList<QKeySequence> newShortcuts);
private:
QList<QKeySequence> m_shortcuts;
QLabel * m_shortcutsLabel;
QToolButton * m_setShortcutButton;
};
-38
View File
@@ -1,38 +0,0 @@
// SPDX-FileCopyrightText: 2022 Gary Wang <wzc782970009@gmail.com>
//
// SPDX-License-Identifier: MIT
#include "toolbutton.h"
#include "actionmanager.h"
#include "opacityhelper.h"
#include <QPainter>
#include <QGraphicsOpacityEffect>
#include <QPropertyAnimation>
ToolButton::ToolButton(bool hoverColor, QWidget *parent)
: QPushButton(parent)
, m_opacityHelper(new OpacityHelper(this))
{
setFlat(true);
QString qss = "QPushButton {"
"background: transparent;"
"}";
if (hoverColor) {
qss += "QPushButton:hover {"
"background: red;"
"}";
}
setStyleSheet(qss);
}
void ToolButton::setIconResourcePath(const QString &iconp)
{
this->setIcon(ActionManager::loadHidpiIcon(iconp, this->iconSize()));
}
void ToolButton::setOpacity(qreal opacity, bool animated)
{
m_opacityHelper->setOpacity(opacity, animated);
}
-25
View File
@@ -1,25 +0,0 @@
// SPDX-FileCopyrightText: 2022 Gary Wang <wzc782970009@gmail.com>
//
// SPDX-License-Identifier: MIT
#ifndef TOOLBUTTON_H
#define TOOLBUTTON_H
#include <QPushButton>
class OpacityHelper;
class ToolButton : public QPushButton
{
Q_OBJECT
public:
ToolButton(bool hoverColor = false, QWidget * parent = nullptr);
void setIconResourcePath(const QString &iconp);
public slots:
void setOpacity(qreal opacity, bool animated = true);
private:
OpacityHelper * m_opacityHelper;
};
#endif // TOOLBUTTON_H
+29
View File
@@ -0,0 +1,29 @@
<center>
<p>
<img width='128' height='128' src=':/icons/app-icon.svg'/>
<br/>
<!-- Application name -->
<span>%1</span>
<br/>
<!-- Version info -->
<span>%2</span>
</p>
<hr/>
<p>
<!-- Upstream author and fork author -->
<span>%3</span><span>:&nbsp;</span><a href='https://github.com/BLumia'>@BLumia</a>
<br/>
<span>%4</span><span>:&nbsp;</span><a href='https://github.com/yyc12345'>@yyc12345</a>
<br/>
<!-- Icon author -->
<span>%5</span><span>:&nbsp;</span><a href='https://github.com/Lovelyblack'>@Lovelyblack</a>
</p>
<hr/>
<p>
<!-- Built Qt version info -->
<span>%6</span>
<br/>
<!-- Source code -->
<span>%7</span><span>:&nbsp;</span><a href='https://github.com/BLumia/pineapple-pictures'>GitHub</a>
</p>
</center>
+29
View File
@@ -0,0 +1,29 @@
<!-- General help -->
<h1 align='center'>%1</h1>
<ul>
<li>
<span>%2</span>
<ul>
<li>%3</li>
<li>%4</li>
</ul>
</li>
<li>%5</li>
<li>%6</li>
</ul>
<hr/>
<!-- Context menu option help -->
<h1 align='center'>%7</h1>
<!-- Context menu option list -->
<ul>
<li>
<b>%8</b><span>:</span>
<br/>
<span>%9</span>
</li>
<li>
<b>%10</b><span>:</span>
<br/>
<span>%11</span>
</li>
</ul>
+29
View File
@@ -0,0 +1,29 @@
<!-- License -->
<h1 align='center'><b>%1</b></h1>
<p>%2</p>
<hr/>
<!-- VErbatime license -->
<h1 align='center'><b>%3</b></h1>
<pre>
Expat/MIT License
Copyright &copy; 2026 BLumia
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
</pre>
@@ -1,3 +1,14 @@
<!-- Contributor title -->
<h1 align='center'>%1</h1>
<!-- Contributor list -->
<a href='https://github.com/BLumia/pineapple-pictures/graphs/contributors'>%2</a>
<!-- The message to thank these contributors -->
<p>%3</p>
<!-- Translator title -->
<h1 align='center'>%4</h1>
<!-- The message to thank these translators -->
<p>%5</p>
<ul> <ul>
<li><u>Catalan</u>: Toni Estévez</li> <li><u>Catalan</u>: Toni Estévez</li>
<li><u>Chinese (Simplified)</u>: Percy Hong</li> <li><u>Chinese (Simplified)</u>: Percy Hong</li>
+15
View File
@@ -0,0 +1,15 @@
<!-- Title -->
<h1 align='center'><b>%1</b></h1>
<!-- List intro message -->
<p>%2</p>
<p>%3</p>
<ul>
<li>
<a href='https://www.qt.io/'>Qt</a><span>: </span>
<span>GPLv2 + GPLv3 + LGPLv2.1 + LGPLv3</span>
</li>
<li style="display: none;">
<a href='https://www.exiv2.org/'>Exiv2</a><span>: </span>
<span>GPLv2</span>
</li>
</ul>
+5 -1
View File
@@ -10,6 +10,10 @@
<file>icons/window-close.svg</file> <file>icons/window-close.svg</file>
<file>icons/go-next.svg</file> <file>icons/go-next.svg</file>
<file>icons/go-previous.svg</file> <file>icons/go-previous.svg</file>
<file>plain/translators.html</file> <file>plain/help.html</file>
<file>plain/about.html</file>
<file>plain/special-thanks.html</file>
<file>plain/license.html</file>
<file>plain/third-party-libs.html</file>
</qresource> </qresource>
</RCC> </RCC>
@@ -53,6 +53,7 @@
<url type="bugtracker">https://github.com/BLumia/pineapple-pictures/issues</url> <url type="bugtracker">https://github.com/BLumia/pineapple-pictures/issues</url>
<url type="donation">https://ko-fi.com/blumia</url> <url type="donation">https://ko-fi.com/blumia</url>
<url type="translate">https://hosted.weblate.org/projects/pineapple-pictures/</url> <url type="translate">https://hosted.weblate.org/projects/pineapple-pictures/</url>
<url type="vcs-browser">https://github.com/BLumia/pineapple-pictures</url>
<provides> <provides>
<binary>ppic</binary> <binary>ppic</binary>
</provides> </provides>
@@ -101,6 +102,26 @@
</screenshot> </screenshot>
</screenshots> </screenshots>
<releases> <releases>
<release type="stable" version="1.5.0" date="2026-07-04T00:00:00Z">
<description>
<p>This release adds the following features:</p>
<ul>
<li>Introduced an optional titlebar that display file name and allows drag and double-click to move and toggle maximize state</li>
<li>Windows: Now the application will use the system's built-in animation for open window animation</li>
</ul>
<p>This release fixes the following bug:</p>
<ul>
<li>Show empty url list should also reset window title to blank</li>
</ul>
<p>This release includes the following changes:</p>
<ul>
<li>Update translations</li>
<li>Add vcs-browser link to AppStream metadata</li>
</ul>
<p>With contributions from:</p>
<p>Heimen Stoffels (vistaus), VenusGirl (VenusGirl)</p>
</description>
</release>
<release type="stable" version="1.4.1" date="2026-04-05T00:00:00Z"> <release type="stable" version="1.4.1" date="2026-04-05T00:00:00Z">
<description> <description>
<p>This release includes the following changes:</p> <p>This release includes the following changes:</p>