diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..1df6c35 --- /dev/null +++ b/.clang-format @@ -0,0 +1,199 @@ +# Commented out parameters are those with the same value as base LLVM style. +# We can uncomment them if we want to change their value, or enforce the +# chosen value in case the base style changes (last sync: Clang 14.0). +--- +### General config, applies to all languages ### +BasedOnStyle: LLVM +AccessModifierOffset: -4 +AlignAfterOpenBracket: DontAlign +# AlignArrayOfStructures: None +# AlignConsecutiveMacros: None +# AlignConsecutiveAssignments: None +# AlignConsecutiveBitFields: None +# AlignConsecutiveDeclarations: None +# AlignEscapedNewlines: Right +AlignOperands: DontAlign +AlignTrailingComments: false +# AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: false +# AllowShortEnumsOnASingleLine: true +# AllowShortBlocksOnASingleLine: Never +# AllowShortCaseLabelsOnASingleLine: false +# AllowShortFunctionsOnASingleLine: All +# AllowShortLambdasOnASingleLine: All +# AllowShortIfStatementsOnASingleLine: Never +# AllowShortLoopsOnASingleLine: false +# AlwaysBreakAfterDefinitionReturnType: None +# AlwaysBreakAfterReturnType: None +# AlwaysBreakBeforeMultilineStrings: false +# AlwaysBreakTemplateDeclarations: MultiLine +# AttributeMacros: +# - __capability +# BinPackArguments: true +# BinPackParameters: true +# BraceWrapping: +# AfterCaseLabel: false +# AfterClass: false +# AfterControlStatement: Never +# AfterEnum: false +# AfterFunction: false +# AfterNamespace: false +# AfterObjCDeclaration: false +# AfterStruct: false +# AfterUnion: false +# AfterExternBlock: false +# BeforeCatch: false +# BeforeElse: false +# BeforeLambdaBody: false +# BeforeWhile: false +# IndentBraces: false +# SplitEmptyFunction: true +# SplitEmptyRecord: true +# SplitEmptyNamespace: true +# BreakBeforeBinaryOperators: None +# BreakBeforeConceptDeclarations: true +# BreakBeforeBraces: Attach +# BreakBeforeInheritanceComma: false +# BreakInheritanceList: BeforeColon +# BreakBeforeTernaryOperators: true +# BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: AfterColon +# BreakStringLiterals: true +ColumnLimit: 0 +# CommentPragmas: '^ IWYU pragma:' +# QualifierAlignment: Leave +# CompactNamespaces: false +ConstructorInitializerIndentWidth: 8 +ContinuationIndentWidth: 8 +Cpp11BracedListStyle: false +# DeriveLineEnding: true +# DerivePointerAlignment: false +# DisableFormat: false +# EmptyLineAfterAccessModifier: Never +# EmptyLineBeforeAccessModifier: LogicalBlock +# ExperimentalAutoDetectBinPacking: false +# PackConstructorInitializers: BinPack +ConstructorInitializerAllOnOneLineOrOnePerLine: true +# AllowAllConstructorInitializersOnNextLine: true +# FixNamespaceComments: true +# ForEachMacros: +# - foreach +# - Q_FOREACH +# - BOOST_FOREACH +# IfMacros: +# - KJ_IF_MAYBE +# IncludeBlocks: Preserve +IncludeCategories: + - Regex: '".*"' + Priority: 1 + - Regex: '^<.*\.h>' + Priority: 2 + - Regex: '^<.*' + Priority: 3 +# IncludeIsMainRegex: '(Test)?$' +# IncludeIsMainSourceRegex: '' +# IndentAccessModifiers: false +IndentCaseLabels: true +# IndentCaseBlocks: false +# IndentGotoLabels: true +# IndentPPDirectives: None +# IndentExternBlock: AfterExternBlock +# IndentRequires: false +IndentWidth: 4 +# IndentWrappedFunctionNames: false +# InsertTrailingCommas: None +# JavaScriptQuotes: Leave +# JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +# LambdaBodyIndentation: Signature +# MacroBlockBegin: '' +# MacroBlockEnd: '' +# MaxEmptyLinesToKeep: 1 +# NamespaceIndentation: None +# PenaltyBreakAssignment: 2 +# PenaltyBreakBeforeFirstCallParameter: 19 +# PenaltyBreakComment: 300 +# PenaltyBreakFirstLessLess: 120 +# PenaltyBreakOpenParenthesis: 0 +# PenaltyBreakString: 1000 +# PenaltyBreakTemplateDeclaration: 10 +# PenaltyExcessCharacter: 1000000 +# PenaltyReturnTypeOnItsOwnLine: 60 +# PenaltyIndentedWhitespace: 0 +# PointerAlignment: Right +# PPIndentWidth: -1 +# ReferenceAlignment: Pointer +# ReflowComments: true +# RemoveBracesLLVM: false +# SeparateDefinitionBlocks: Leave +# ShortNamespaceLines: 1 +# SortIncludes: CaseSensitive +# SortJavaStaticImport: Before +# SortUsingDeclarations: true +# SpaceAfterCStyleCast: false +# SpaceAfterLogicalNot: false +# SpaceAfterTemplateKeyword: true +# SpaceBeforeAssignmentOperators: true +# SpaceBeforeCaseColon: false +# SpaceBeforeCpp11BracedList: false +# SpaceBeforeCtorInitializerColon: true +# SpaceBeforeInheritanceColon: true +# SpaceBeforeParens: ControlStatements +# SpaceBeforeParensOptions: +# AfterControlStatements: true +# AfterForeachMacros: true +# AfterFunctionDefinitionName: false +# AfterFunctionDeclarationName: false +# AfterIfMacros: true +# AfterOverloadedOperator: false +# BeforeNonEmptyParentheses: false +# SpaceAroundPointerQualifiers: Default +# SpaceBeforeRangeBasedForLoopColon: true +# SpaceInEmptyBlock: false +# SpaceInEmptyParentheses: false +# SpacesBeforeTrailingComments: 1 +# SpacesInAngles: Never +# SpacesInConditionalStatement: false +# SpacesInContainerLiterals: true +# SpacesInCStyleCastParentheses: false +## Godot TODO: We'll want to use a min of 1, but we need to see how to fix +## our comment capitalization at the same time. +SpacesInLineCommentPrefix: + Minimum: 0 + Maximum: -1 +# SpacesInParentheses: false +# SpacesInSquareBrackets: false +# SpaceBeforeSquareBrackets: false +# BitFieldColonSpacing: Both +# StatementAttributeLikeMacros: +# - Q_EMIT +# StatementMacros: +# - Q_UNUSED +# - QT_REQUIRE_VERSION +TabWidth: 4 +# UseCRLF: false +UseTab: Always +# WhitespaceSensitiveMacros: +# - STRINGIZE +# - PP_STRINGIZE +# - BOOST_PP_STRINGIZE +# - NS_SWIFT_NAME +# - CF_SWIFT_NAME +--- +### C++ specific config ### +Language: Cpp +Standard: c++17 +--- +### ObjC specific config ### +Language: ObjC +# ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 4 +# ObjCBreakBeforeNestedBlockParam: true +# ObjCSpaceAfterProperty: false +# ObjCSpaceBeforeProtocolList: true +--- +### Java specific config ### +Language: Java +# BreakAfterJavaFieldAnnotations: false +JavaImportGroups: ['org.godotengine', 'android', 'androidx', 'com.android', 'com.google', 'java', 'javax'] +... diff --git a/README.md b/README.md index c77cddb..01e6903 100644 --- a/README.md +++ b/README.md @@ -47,3 +47,12 @@ I suggest you visit the [wiki](https://github.com/Quill-OS/quill/wiki). Feel fre If you like this project and want to improve it in some way, feel free to fork this repository or [one of the subprojects this organization hosts](https://github.com/Quill-OS), then make a [pull request](https://github.com/Quill-OS/quill/pulls). I'll be happy to review it when I have time. You can also join the official [Matrix space](https://matrix.to/#/#inkbox-os-project:matrix.org), [Discord server](https://discord.com/invite/uSWtWbY23m) or [Linen](https://www.linen.dev/s/quill-os) if you'd like to chat a bit.

On the other hand, if you don't have the appropriate coding skills or just want to help in some way, feel free to make a donation at my [PayPal account](https://paypal.me/inkboxos/), [LiberaPay](https://liberapay.com/tux-linux/), or via Bitcoin: 3MmXq5o78b4C7ub5sb7F5WVC86jzc6PzSN . I'm a student and motivation has been the only thing that has helped me maintain this project for the last few years. Developing an entire operating system on my own was not an easy task. I have time, but I like to spend it wisely. + + +## Building + +Make sure you have the following requirements installed on your system: +* a c/cpp profiler +* `libsndfile-dev` + +Next open the `inkbox.pro` file qith QTCreator \ No newline at end of file diff --git a/inkbox.pro b/inkbox.pro index e5ed15d..3562e29 100644 --- a/inkbox.pro +++ b/inkbox.pro @@ -24,148 +24,172 @@ DEFINES += GIT_COMMIT=\\\"$$GIT_COMMIT\\\" #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ - src/apps/todo.cpp \ + src/platform/device.cpp \ + src/platform/device_desktop.cpp \ + src/platform/device_kindle_touch.cpp \ + src/platform/device_kobo_aura_edition2.cpp \ + src/platform/device_kobo_clarahd.cpp \ + src/platform/device_kobo_glo.cpp \ + src/platform/device_kobo_glohd.cpp \ + src/platform/device_kobo_libra.cpp \ + src/platform/device_kobo_mini.cpp \ + src/platform/device_kobo_nia.cpp \ + src/platform/device_kobo_touch.cpp \ + src/ui/apps/todo.cpp \ src/audio/audiothread.cpp \ - src/splash/alert.cpp \ - src/apps/apps.cpp \ + src/ui/apps/apps.cpp \ src/telemetry/telemetry.cpp \ - src/widgets/dialogs/audio/audiodialog.cpp \ - src/widgets/dialogs/audio/audiofile.cpp \ - src/widgets/dialogs/audio/audiofilequeue.cpp \ - src/widgets/dialogs/library/bookinfodialog.cpp \ - src/widgets/dialogs/library/bookoptionsdialog.cpp \ - src/widgets/dialogs/brightnessdialog.cpp \ - src/apps/calendarapp.cpp \ - src/widgets/dialogs/reader/highlightslistdialog.cpp \ - src/widgets/dialogs/reader/textdialog.cpp \ - src/widgets/dialogs/wifi/connectiondialog.cpp \ - src/widgets/dialogs/wifi/network.cpp \ - src/widgets/dialogs/wifi/wifilogger.cpp \ - src/widgets/misc/egg.cpp \ - src/widgets/reader/dictionarywidget.cpp \ - src/encfs/encryptionmanager.cpp \ - src/widgets/dialogs/generaldialog.cpp \ - src/homeWidget/homepagewidget.cpp \ - src/widgets/misc/hourglassanimationwidget.cpp \ - src/widgets/dialogs/kobox/koboxappsdialog.cpp \ - src/settings/koboxsettings.cpp \ - src/onlineLibrary/librarywidget.cpp \ - src/localLibrary/locallibrarywidget.cpp \ + src/ui/splash/splashAlert.cpp \ + src/ui/ui.cpp \ + src/ui/widgets/dialogs/audio/audiodialog.cpp \ + src/ui/widgets/dialogs/audio/audiofile.cpp \ + src/ui/widgets/dialogs/audio/audiofilequeue.cpp \ + src/ui/widgets/dialogs/library/bookinfodialog.cpp \ + src/ui/widgets/dialogs/library/bookoptionsdialog.cpp \ + src/ui/widgets/dialogs/brightnessdialog.cpp \ + src/ui/apps/calendarapp.cpp \ + src/ui/widgets/dialogs/reader/highlightslistdialog.cpp \ + src/ui/widgets/dialogs/reader/textdialog.cpp \ + src/ui/widgets/dialogs/wifi/connectiondialog.cpp \ + src/ui/widgets/dialogs/wifi/network.cpp \ + src/ui/widgets/dialogs/wifi/wifilogger.cpp \ + src/ui/widgets/misc/egg.cpp \ + src/ui/widgets/reader/dictionarywidget.cpp \ + src/ui/crypto/encryptionmanager.cpp \ + src/ui/widgets/dialogs/generaldialog.cpp \ + src/ui/home/homepagewidget.cpp \ + src/ui/widgets/misc/hourglassanimationwidget.cpp \ + src/ui/widgets/dialogs/kobox/koboxappsdialog.cpp \ + src/ui/settings/koboxsettings.cpp \ + src/ui/onlineLibrary/librarywidget.cpp \ + src/ui/localLibrary/locallibrarywidget.cpp \ src/main.cpp \ - src/homeWidget/mainwindow.cpp \ - src/otaUpdate/otamanager.cpp \ - src/widgets/interfaceWidgets/qclickablelabel.cpp \ - src/widgets/interfaceWidgets/qtooltiplabel.cpp \ - src/quit/quit.cpp \ - src/reader/reader.cpp \ - src/apps/savedwords.cpp \ - src/widgets/text/searchresultswidget.cpp \ - src/settings/settings.cpp \ - src/settings/settingschooser.cpp \ - src/widgets/text/textwidget.cpp \ - src/widgets/interfaceWidgets/toast.cpp \ - src/splash/usbmsSplash.cpp \ - src/apps/userapps.cpp \ - src/widgets/virtualKeyboard/virtualkeyboard.cpp \ - src/widgets/virtualKeyboard/virtualkeypad.cpp \ - src/widgets/dialogs/wifi/wifidialog.cpp \ - src/widgets/dialogs/powerDaemon/sleepdialog.cpp \ + src/ui/home/mainwindow.cpp \ + src/ui/otaUpdate/otamanager.cpp \ + src/ui/widgets/interfaceWidgets/qclickablelabel.cpp \ + src/ui/widgets/interfaceWidgets/qtooltiplabel.cpp \ + src/ui/quit/quit.cpp \ + src/ui/reader/reader.cpp \ + src/ui/apps/savedwords.cpp \ + src/ui/widgets/text/searchresultswidget.cpp \ + src/ui/settings/settings.cpp \ + src/ui/settings/settingschooser.cpp \ + src/ui/widgets/text/textwidget.cpp \ + src/ui/widgets/interfaceWidgets/toast.cpp \ + src/ui/splash/usbmsSplash.cpp \ + src/ui/apps/userapps.cpp \ + src/ui/widgets/virtualKeyboard/virtualkeyboard.cpp \ + src/ui/widgets/virtualKeyboard/virtualkeypad.cpp \ + src/ui/widgets/dialogs/wifi/wifidialog.cpp \ + src/ui/widgets/dialogs/powerDaemon/sleepdialog.cpp \ src/powerDaemon/sleepthread.cpp \ - src/settings/powerdaemonsettings.cpp + src/ui/settings/powerdaemonsettings.cpp HEADERS += \ src/audio/audiothread.h \ - src/apps/todo.h \ - src/splash/alert.h \ - src/apps/apps.h \ + src/platform/device.h \ + src/platform/device_desktop.h \ + src/platform/device_kindle_touch.h \ + src/platform/device_kobo_aura_edition2.h \ + src/platform/device_kobo_clarahd.h \ + src/platform/device_kobo_glo.h \ + src/platform/device_kobo_glohd.h \ + src/platform/device_kobo_libra.h \ + src/platform/device_kobo_mini.h \ + src/platform/device_kobo_nia.h \ + src/platform/device_kobo_touch.h \ + src/ui/apps/todo.h \ + src/ui/apps/apps.h \ src/telemetry/telemetry.h \ - src/widgets/dialogs/audio/audiodialog.h \ - src/widgets/dialogs/audio/audiofile.h \ - src/widgets/dialogs/audio/audiofilequeue.h \ - src/widgets/dialogs/library/bookinfodialog.h \ - src/widgets/dialogs/library/bookoptionsdialog.h \ - src/widgets/dialogs/brightnessdialog.h \ - src/apps/calendarapp.h \ - src/widgets/dialogs/reader/highlightslistdialog.h \ - src/widgets/dialogs/reader/textdialog.h \ - src/widgets/dialogs/wifi/connectiondialog.h \ - src/widgets/dialogs/wifi/network.h \ - src/widgets/dialogs/wifi/wifilogger.h \ - src/widgets/misc/egg.h \ - src/widgets/reader/dictionarywidget.h \ - src/encfs/encryptionmanager.h \ + src/ui/splash/splashAlert.h \ + src/ui/ui.h \ + src/ui/widgets/dialogs/audio/audiodialog.h \ + src/ui/widgets/dialogs/audio/audiofile.h \ + src/ui/widgets/dialogs/audio/audiofilequeue.h \ + src/ui/widgets/dialogs/library/bookinfodialog.h \ + src/ui/widgets/dialogs/library/bookoptionsdialog.h \ + src/ui/widgets/dialogs/brightnessdialog.h \ + src/ui/apps/calendarapp.h \ + src/ui/widgets/dialogs/reader/highlightslistdialog.h \ + src/ui/widgets/dialogs/reader/textdialog.h \ + src/ui/widgets/dialogs/wifi/connectiondialog.h \ + src/ui/widgets/dialogs/wifi/network.h \ + src/ui/widgets/dialogs/wifi/wifilogger.h \ + src/ui/widgets/misc/egg.h \ + src/ui/widgets/reader/dictionarywidget.h \ + src/ui/crypto/encryptionmanager.h \ src/functions.h \ - src/widgets/dialogs/generaldialog.h \ - src/homeWidget/homepagewidget.h \ - src/widgets/misc/hourglassanimationwidget.h \ - src/widgets/dialogs/kobox/koboxappsdialog.h \ - src/settings/koboxsettings.h \ - src/onlineLibrary/librarywidget.h \ - src/localLibrary/locallibrarywidget.h \ - src/homeWidget/mainwindow.h \ - src/otaUpdate/otamanager.h \ - src/widgets/interfaceWidgets/qclickablelabel.h \ - src/widgets/interfaceWidgets/qtooltiplabel.h \ - src/quit/quit.h \ - src/reader/reader.h \ - src/apps/savedwords.h \ - src/widgets/text/searchresultswidget.h \ - src/settings/settings.h \ - src/settings/settingschooser.h \ - src/widgets/text/textwidget.h \ - src/widgets/interfaceWidgets/toast.h \ - src/splash/usbmsSplash.h \ - src/apps/userapps.h \ - src/widgets/virtualKeyboard/virtualkeyboard.h \ - src/widgets/virtualKeyboard/virtualkeypad.h \ - src/widgets/dialogs/wifi/wifidialog.h \ - src/widgets/dialogs/powerDaemon/sleepdialog.h \ + src/ui/widgets/dialogs/generaldialog.h \ + src/ui/home/homepagewidget.h \ + src/ui/widgets/misc/hourglassanimationwidget.h \ + src/ui/widgets/dialogs/kobox/koboxappsdialog.h \ + src/ui/settings/koboxsettings.h \ + src/ui/onlineLibrary/librarywidget.h \ + src/ui/localLibrary/locallibrarywidget.h \ + src/ui/home/mainwindow.h \ + src/ui/otaUpdate/otamanager.h \ + src/ui/widgets/interfaceWidgets/qclickablelabel.h \ + src/ui/widgets/interfaceWidgets/qtooltiplabel.h \ + src/ui/quit/quit.h \ + src/ui/reader/reader.h \ + src/ui/apps/savedwords.h \ + src/ui/widgets/text/searchresultswidget.h \ + src/ui/settings/settings.h \ + src/ui/settings/settingschooser.h \ + src/ui/widgets/text/textwidget.h \ + src/ui/widgets/interfaceWidgets/toast.h \ + src/ui/splash/usbmsSplash.h \ + src/ui/apps/userapps.h \ + src/ui/widgets/virtualKeyboard/virtualkeyboard.h \ + src/ui/widgets/virtualKeyboard/virtualkeypad.h \ + src/ui/widgets/dialogs/wifi/wifidialog.h \ + src/ui/widgets/dialogs/powerDaemon/sleepdialog.h \ src/powerDaemon/sleepthread.h \ - src/settings/powerdaemonsettings.h + src/ui/settings/powerdaemonsettings.h FORMS += \ - src/apps/todo.ui \ - src/splash/alert.ui \ - src/apps/apps.ui \ - src/widgets/dialogs/audio/audiodialog.ui \ - src/widgets/dialogs/audio/audiofile.ui \ - src/widgets/dialogs/audio/audiofilequeue.ui \ - src/widgets/dialogs/library/bookinfodialog.ui \ - src/widgets/dialogs/library/bookoptionsdialog.ui \ - src/widgets/dialogs/brightnessdialog.ui \ - src/apps/calendarapp.ui \ - src/widgets/dialogs/reader/highlightslistdialog.ui \ - src/widgets/dialogs/reader/textdialog.ui \ - src/widgets/dialogs/wifi/connectiondialog.ui \ - src/widgets/dialogs/wifi/network.ui \ - src/widgets/dialogs/wifi/wifilogger.ui \ - src/widgets/misc/egg.ui \ - src/widgets/reader/dictionarywidget.ui \ - src/encfs/encryptionmanager.ui \ - src/widgets/dialogs/generaldialog.ui \ - src/homeWidget/homepagewidget.ui \ - src/widgets/misc/hourglassanimationwidget.ui \ - src/widgets/dialogs/kobox/koboxappsdialog.ui \ - src/settings/koboxsettings.ui \ - src/onlineLibrary/librarywidget.ui \ - src/localLibrary/locallibrarywidget.ui \ - src/homeWidget/mainwindow.ui \ - src/otaUpdate/otamanager.ui \ - src/quit/quit.ui \ - src/reader/reader.ui \ - src/apps/savedwords.ui \ - src/widgets/text/searchresultswidget.ui \ - src/settings/settings.ui \ - src/settings/settingschooser.ui \ - src/widgets/text/textwidget.ui \ - src/widgets/interfaceWidgets/toast.ui \ - src/splash/usbmsSplash.ui \ - src/apps/userapps.ui \ - src/widgets/virtualKeyboard/virtualkeyboard.ui \ - src/widgets/virtualKeyboard/virtualkeypad.ui \ - src/widgets/dialogs/wifi/wifidialog.ui \ - src/widgets/dialogs/powerDaemon/sleepdialog.ui \ - src/settings/powerdaemonsettings.ui + src/ui/apps/todo.ui \ + src/ui/apps/apps.ui \ + src/ui/splash/splashAlert.ui \ + src/ui/widgets/dialogs/audio/audiodialog.ui \ + src/ui/widgets/dialogs/audio/audiofile.ui \ + src/ui/widgets/dialogs/audio/audiofilequeue.ui \ + src/ui/widgets/dialogs/library/bookinfodialog.ui \ + src/ui/widgets/dialogs/library/bookoptionsdialog.ui \ + src/ui/widgets/dialogs/brightnessdialog.ui \ + src/ui/apps/calendarapp.ui \ + src/ui/widgets/dialogs/reader/highlightslistdialog.ui \ + src/ui/widgets/dialogs/reader/textdialog.ui \ + src/ui/widgets/dialogs/wifi/connectiondialog.ui \ + src/ui/widgets/dialogs/wifi/network.ui \ + src/ui/widgets/dialogs/wifi/wifilogger.ui \ + src/ui/widgets/misc/egg.ui \ + src/ui/widgets/reader/dictionarywidget.ui \ + src/ui/crypto/encryptionmanager.ui \ + src/ui/widgets/dialogs/generaldialog.ui \ + src/ui/home/homepagewidget.ui \ + src/ui/widgets/misc/hourglassanimationwidget.ui \ + src/ui/widgets/dialogs/kobox/koboxappsdialog.ui \ + src/ui/settings/koboxsettings.ui \ + src/ui/onlineLibrary/librarywidget.ui \ + src/ui/localLibrary/locallibrarywidget.ui \ + src/ui/home/mainwindow.ui \ + src/ui/otaUpdate/otamanager.ui \ + src/ui/quit/quit.ui \ + src/ui/reader/reader.ui \ + src/ui/apps/savedwords.ui \ + src/ui/widgets/text/searchresultswidget.ui \ + src/ui/settings/settings.ui \ + src/ui/settings/settingschooser.ui \ + src/ui/widgets/text/textwidget.ui \ + src/ui/widgets/interfaceWidgets/toast.ui \ + src/ui/splash/usbmsSplash.ui \ + src/ui/apps/userapps.ui \ + src/ui/widgets/virtualKeyboard/virtualkeyboard.ui \ + src/ui/widgets/virtualKeyboard/virtualkeypad.ui \ + src/ui/widgets/dialogs/wifi/wifidialog.ui \ + src/ui/widgets/dialogs/powerDaemon/sleepdialog.ui \ + src/ui/settings/powerdaemonsettings.ui # Default rules for deployment. qnx: target.path = /tmp/$${TARGET}/bin @@ -173,7 +197,7 @@ else: unix:!android: target.path = /opt/$${TARGET}/bin !isEmpty(target.path): INSTALLS += target RESOURCES += \ - src/eink.qrc + src/ui/eink.qrc INCLUDEPATH += $$system(find ./ -type d -print -path ./.git -prune | grep -v "./.git") INCLUDEPATH += $$PWD/libs/libsndfile/include/ diff --git a/src/apps/calendarapp.cpp b/src/apps/calendarapp.cpp deleted file mode 100644 index fec6610..0000000 --- a/src/apps/calendarapp.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "calendarapp.h" -#include "ui_calendarapp.h" - -#include - -calendarApp::calendarApp(QWidget *parent) : - QWidget(parent), - ui(new Ui::calendarApp) -{ - ui->setupUi(this); - calendarApp::setFont(QFont("u001")); - ui->backBtn->setFont(QFont("Inter")); - ui->backBtn->setStyleSheet("font-weight: bold"); - - // Stylesheet - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - ui->backBtn->setProperty("type", "borderless"); -} - -calendarApp::~calendarApp() -{ - delete ui; -} - -void calendarApp::on_backBtn_clicked() -{ - calendarApp::close(); -} diff --git a/src/apps/savedwords.cpp b/src/apps/savedwords.cpp deleted file mode 100644 index a3baabb..0000000 --- a/src/apps/savedwords.cpp +++ /dev/null @@ -1,86 +0,0 @@ -#include "savedwords.h" -#include "ui_savedwords.h" -#include "functions.h" -#include -#include -#include - -savedwords::savedwords(QWidget *parent) : - QWidget(parent), - ui(new Ui::savedwords) -{ - ui->setupUi(this); - savedwords::setFont(QFont("u001")); - ui->savedWordsLabel->setFont(QFont("Inter")); - ui->backBtn->setFont(QFont("Inter")); - ui->clearBtn->setFont(QFont("Inter")); - - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - ui->backBtn->setProperty("type", "borderless"); - ui->clearBtn->setProperty("type", "borderless"); - - ui->savedWordsLabel->setStyleSheet("font-weight: bold"); - ui->wordsList->setStyleSheet("font-size: 10pt"); - ui->backBtn->setStyleSheet("font-weight: bold"); - ui->clearBtn->setStyleSheet("font-weight: bold"); - - checkwords(); - - QStringListModel * model = new QStringListModel(this); - QStringList list = words.split("\n", QString::SkipEmptyParts); - model->setStringList(list); - ui->wordsList->setModel(model); - ui->wordsList->setEditTriggers(QAbstractItemView::NoEditTriggers); -} - -savedwords::~savedwords() -{ - delete ui; -} - -void savedwords::on_backBtn_clicked() -{ - // Workaround for the random strange memory corruption error - QProcess process; - process.startDetached("inkbox", QStringList()); - qApp->quit(); -} - -void savedwords::on_clearBtn_clicked() -{ - // Warning: possible memory leak here. Though, usually, when you press the "Clear" button and all clears up, you don't have to press it again ;) - log("Wiping Saved Words list", className); - save_word_init(); - checkwords(); - QStringListModel* model = new QStringListModel(this); - QStringList list = words.split("\n", QString::SkipEmptyParts); - model->setStringList(list); - ui->wordsList->setModel(model); - ui->wordsList->setEditTriggers(QAbstractItemView::NoEditTriggers); -} - -void savedwords::checkwords() { - QFile words_list(".config/06-words/config"); - words_list.open(QIODevice::ReadWrite); - QTextStream in (&words_list); - words = in.readAll(); - words_list.close(); -} - -void savedwords::save_word_init() { - QFile words(".config/06-words/config"); - words.open(QIODevice::ReadWrite); - QTextStream in (&words); - QString words_list = in.readAll(); - string words_list_str = words_list.toStdString(); - words.close(); - - ofstream fhandler; - fhandler.open(".config/06-words/config"); - fhandler << ""; - fhandler.close(); -} diff --git a/src/audio/audiothread.cpp b/src/audio/audiothread.cpp index 3164b09..6191b54 100644 --- a/src/audio/audiothread.cpp +++ b/src/audio/audiothread.cpp @@ -10,9 +10,9 @@ #include -audiothread::audiothread() {} +AudioThread::AudioThread() {} -void audiothread::start() { +void AudioThread::start() { log("Audio thread monitor available", className); // QTimer doesn't work in such loops @@ -86,7 +86,7 @@ void audiothread::start() { // I have no explanation as to why this needs to connect/disconnect every time. // while (recv(client_sockfd, buffer_tmp, 1, 0) > 0) { // ^ This line makes InkBox freeze -void audiothread::sendInfo(QString message) { +void AudioThread::sendInfo(QString message) { log("Sending message: *" + message + "*", className); // Send sockfd = socket(AF_UNIX, SOCK_STREAM, 0); @@ -113,7 +113,7 @@ void audiothread::sendInfo(QString message) { } // Mutex managed outside of the function -void audiothread::audioProgress() { +void AudioThread::audioProgress() { global::audio::progressSeconds = global::audio::progressSeconds + 1; // log("Progress, +1 sec: " + QString::number(global::audio::progressSeconds), className); if(global::audio::progressSeconds >= global::audio::queue[global::audio::itemCurrentlyPlaying].lengths) { diff --git a/src/audio/audiothread.h b/src/audio/audiothread.h index e8547e9..202acb4 100644 --- a/src/audio/audiothread.h +++ b/src/audio/audiothread.h @@ -5,13 +5,13 @@ #include #include -class audiothread : public QObject +class AudioThread : public QObject { Q_OBJECT public: QString className = this->metaObject()->className(); - audiothread(); + AudioThread(); void sendInfo(QString message); int sockfd; struct sockaddr_un addr; diff --git a/src/eink.qrc b/src/eink.qrc deleted file mode 100644 index 981b094..0000000 --- a/src/eink.qrc +++ /dev/null @@ -1,124 +0,0 @@ - - - resources/checkbox-checked.png - resources/checkbox-unchecked.png - resources/align-center.png - resources/align-justify.png - resources/align-left.png - resources/align-right.png - resources/chesterton.jpg - resources/alcott.jpg - resources/davies.jpg - resources/king.jpg - resources/star.png - resources/starred_star.png - resources/close.png - resources/chevron-left.png - resources/chevron-right.png - resources/chevron-down.png - resources/chevron-up.png - resources/christie.png - resources/exit.png - resources/usbms.png - resources/settings.png - resources/search.png - resources/power.png - resources/book.png - resources/apps.png - resources/battery_half.png - resources/battery_full.png - resources/battery_empty.png - resources/battery_charging.png - resources/alert.png - resources/eink-dark.qss - resources/frontlight.png - resources/fonts/CrimsonPro-Bold.ttf - resources/fonts/CrimsonPro-Italic.ttf - resources/fonts/CrimsonPro-Regular.ttf - resources/check.png - resources/minus.png - resources/plus.png - resources/battery_alert.png - resources/apps-inverted.png - resources/home.png - resources/settings-inverted.png - resources/kobox-icon.png - resources/X11.png - resources/info.png - resources/nightmode-empty.png - resources/nightmode-full.png - resources/backspace.png - resources/x-circle.png - resources/fonts/Bitter-MediumItalic.ttf - resources/fonts/Bitter-Medium.ttf - resources/fonts/Bitter-Bold.ttf - resources/fonts/Bitter-BoldItalic.ttf - resources/fonts/CrimsonPro-BoldItalic.ttf - resources/fonts/IbarraRealNova-MediumItalic.ttf - resources/fonts/IbarraRealNova-Medium.ttf - resources/fonts/IbarraRealNova-BoldItalic.ttf - resources/fonts/IbarraRealNova-Bold.ttf - resources/wifi-connected.png - resources/wifi-off.png - resources/wifi-standby.png - resources/zoom-in.png - resources/zoom-out.png - resources/encryption.png - resources/check-display.png - resources/hourglass-bottom.png - resources/hourglass-top.png - resources/error.png - resources/alert-triangle.png - resources/online-library.png - resources/online-library-inverted.png - resources/cover_unavailable.png - resources/clock-inverted.png - resources/clock.png - resources/eink-square-encfs.qss - resources/tzlist - resources/edit.png - resources/save.png - resources/book_inverted.png - resources/arrow-left.png - resources/arrow-right.png - resources/file-text.png - resources/pin.png - resources/highlight.png - resources/unhighlight.png - resources/view-highlights.png - resources/stop.png - resources/refresh.png - resources/hide.png - resources/show.png - resources/christie.jpg - resources/encryption-small.png - resources/lock.png - resources/public.png - resources/wifi-0.png - resources/wifi-25.png - resources/wifi-50.png - resources/wifi-75.png - resources/wifi-100.png - resources/log.png - resources/new.png - resources/checkbox-unchecked-small.png - resources/checkbox-checked-small.png - resources/checkbox-x-small.png - resources/checkbox-x.png - resources/folder.png - resources/question-mark.png - resources/refresh-small.png - resources/checkbox-indeterminate.png - resources/egg/0.jpg - resources/egg/1.jpg - resources/music-note.png - resources/music-library.png - resources/next.png - resources/music-queue.png - resources/play.png - resources/previous.png - resources/pause.png - resources/clean.png - resources/usbms-inverted.png - - diff --git a/src/encfs/encryptionmanager.cpp b/src/encfs/encryptionmanager.cpp deleted file mode 100644 index 0f25ad3..0000000 --- a/src/encfs/encryptionmanager.cpp +++ /dev/null @@ -1,384 +0,0 @@ -#include "encryptionmanager.h" -#include "ui_encryptionmanager.h" - -#include -#include -#include -#include -#include -#include -#include -#include "usbmsSplash.h" -#include "functions.h" - -encryptionManager::encryptionManager(QWidget *parent) : - QWidget(parent), - ui(new Ui::encryptionManager) -{ - ui->setupUi(this); - ui->descriptionLabel->setFont(QFont("u001")); - ui->successDescriptionLabel->setFont(QFont("u001")); - ui->failureDescriptionLabel->setFont(QFont("u001")); - ui->warningDescriptionLabel->setFont(QFont("u001")); - - // Stylesheet - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - ui->encryptionSetupLabel->setStyleSheet("font-size: 15pt; font-weight: bold"); - ui->descriptionLabel->setStyleSheet("font-size: 10pt"); - ui->successLabel->setStyleSheet("font-size: 15pt; font-weight: bold"); - ui->successDescriptionLabel->setStyleSheet("font-size: 10pt"); - ui->failureLabel->setStyleSheet("font-size: 15pt; font-weight: bold"); - ui->failureDescriptionLabel->setStyleSheet("font-size: 10pt"); - ui->setupContinueBtn->setStyleSheet("background: lightGrey; border: 3px solid black; color: black; padding: 10px; outline: none; font-size: 10pt; font-weight: bold; border-radius: 10px"); - ui->setupAbortBtn->setStyleSheet("background: lightGrey; border: 3px solid black; color: black; padding: 10px; outline: none; font-size: 10pt; font-weight: bold; border-radius: 10px"); - ui->exitSuccessBtn->setStyleSheet("background: lightGrey; border: 3px solid black; color: black; padding: 10px; outline: none; font-size: 10pt; font-weight: bold; border-radius: 10px"); - ui->failureContinueBtn->setStyleSheet("background: lightGrey; border: 3px solid black; color: black; padding: 10px; outline: none; font-size: 10pt; font-weight: bold; border-radius: 10px"); - ui->acceptBtn->setStyleSheet("background: lightGrey; border: 3px solid black; color: black; padding: 10px; outline: none; font-size: 10pt; font-weight: bold; border-radius: 10px"); - ui->usbmsBtn->setStyleSheet("background: lightGrey; border: 3px solid black; color: black; padding: 10px; outline: none; font-size: 10pt; font-weight: bold; border-radius: 10px"); - ui->warningLabel->setStyleSheet("font-size: 15pt; font-weight: bold"); - ui->warningDescriptionLabel->setStyleSheet("font-size: 10pt"); - - // Getting the screen's size - float sW = QGuiApplication::screens()[0]->size().width(); - float sH = QGuiApplication::screens()[0]->size().height(); - float stdIconWidth; - float stdIconHeight; - { - stdIconWidth = sW / 1.50; - stdIconHeight = sH / 1.50; - QPixmap pixmap(":/resources/encryption.png"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->encryptionImageLabel->setPixmap(scaledPixmap); - } - { - stdIconWidth = sW / 1.65; - stdIconHeight = sH / 1.65; - QPixmap pixmap(":/resources/check-display.png"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->checkImageLabel->setPixmap(scaledPixmap); - } - { - stdIconWidth = sW / 1.65; - stdIconHeight = sH / 1.65; - QPixmap pixmap(":/resources/error.png"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->failureImageLabel->setPixmap(scaledPixmap); - } - { - stdIconWidth = sW / 1.50; - stdIconHeight = sH / 1.50; - QPixmap pixmap(":/resources/alert-triangle.png"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->warningImageLabel->setPixmap(scaledPixmap); - } - - hourglassAnimationWidgetWindow = new hourglassAnimationWidget(); - ui->hourglassWidget->insertWidget(0, hourglassAnimationWidgetWindow); - ui->hourglassWidget->setCurrentIndex(0); - - setDefaultWorkDir(); - if(checkconfig(".config/18-encrypted_storage/initial_setup_done") == true or checkconfig("/external_root/run/encfs_repack") == true) { - ui->activityWidget->hide(); - if(checkconfig("/external_root/run/encfs_repack") == false) { - setupPassphraseDialogMode = 1; - } - else { - setupPassphraseDialogMode = 2; - } - QTimer::singleShot(500, this, SLOT(setupPassphraseDialog())); - } - else { - QDir dir("/mnt/onboard/onboard/encfs-dropbox"); - if(dir.isEmpty()) { - ui->activityWidget->setCurrentIndex(4); - mkEncfsDirs(); - } - } -} - -encryptionManager::~encryptionManager() -{ - delete ui; -} - -void encryptionManager::on_setupContinueBtn_clicked() -{ - setupPassphraseDialogMode = 0; - setupPassphraseDialog(); -} - -void encryptionManager::setupPassphraseDialog() { - /* - * setupPassphraseDialogMode can be: - * 0: Initial setup - * 1: Normal behavior - * 2: Repack - */ - log("Showing passphrase dialog for mode " + QString::number(setupPassphraseDialogMode), className); - ui->activityWidget->hide(); - this->setStyleSheet("background-color: black"); - global::keyboard::keyboardDialog = true; - global::keyboard::encfsDialog = true; - global::keyboard::keyboardText = ""; - generalDialogWindow = new generalDialog(); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - connect(generalDialogWindow, SIGNAL(refreshScreen()), SLOT(refreshScreen())); - if(setupPassphraseDialogMode == 0) { - connect(generalDialogWindow, SIGNAL(destroyed(QObject*)), SLOT(setupEncryptedStorage())); - } - else if(setupPassphraseDialogMode == 1) { - connect(generalDialogWindow, SIGNAL(destroyed(QObject*)), SLOT(unlockEncryptedStorage())); - } - else { - connect(generalDialogWindow, SIGNAL(destroyed(QObject*)), SLOT(repackEncryptedStorage())); - } - connect(generalDialogWindow, SIGNAL(showToast(QString)), SLOT(showToast(QString))); - generalDialogWindow->show(); -} - - -void encryptionManager::on_setupAbortBtn_clicked() -{ - log("Aborting setup", className); - setDefaultWorkDir(); - writeFile(".config/18-encrypted_storage/status", "false"); - quit_restart(); -} - -void encryptionManager::quit_restart() { - log("Restarting InkBox", className); - QProcess process; - process.startDetached("inkbox", QStringList()); - qApp->quit(); -} - -void encryptionManager::refreshScreen() { - this->repaint(); -} - -void encryptionManager::showToast(QString messageToDisplay) { - global::toast::message = messageToDisplay; - toastWindow = new toast(this); - toastWindow->setAttribute(Qt::WA_DeleteOnClose); - connect(toastWindow, SIGNAL(refreshScreen()), SLOT(refreshScreen())); - toastWindow->show(); -} - -void encryptionManager::setupEncryptedStorage() { - log("Setting up encrypted storage", className); - this->setStyleSheet("background-color: white"); - ui->activityWidget->show(); - if(global::encfs::cancelSetup == true) { - global::encfs::cancelSetup = false; - ui->activityWidget->setCurrentIndex(0); - } - else { - mkEncfsDirs(); - QString bootstrapPassphrase = global::encfs::passphrase; - global::encfs::passphrase = ""; - writeFile("/external_root/run/encfs/encrypted_storage_create", "true"); - writeFile("/external_root/run/encfs/encrypted_storage_bootstrap_files_location", "/data/onboard/encfs-dropbox"); - writeFile("/external_root/run/encfs/encrypted_storage_bootstrap_archive_location", "/data/onboard/data.encfs"); - writeFile("/external_root/run/encfs/encrypted_storage_bootstrap_passphrase", bootstrapPassphrase); - setDefaultWorkDir(); - writeFile(".config/18-encrypted_storage/storage_list", "/data/onboard/encfs-decrypted"); - writeFile("/opt/ibxd", "encfs_restart\n"); - bool exitStatus; - ui->activityWidget->setCurrentIndex(3); - QTimer * t = new QTimer(this); - t->setInterval(1000); - connect(t, &QTimer::timeout, [&]() { - if(QFile::exists("/external_root/run/encrypted_storage_bootstrap_setup")) { - exitStatus = checkconfig("/external_root/run/encrypted_storage_bootstrap_setup"); - QFile::remove("/external_root/run/encrypted_storage_bootstrap_setup"); - setupExitWidget(exitStatus); - } - } ); - t->start(); - } -} - -void encryptionManager::unlockEncryptedStorage() { - log("Trying to unlock encrypted storage", className); - if(global::encfs::cancelSetup == true) { - global::encfs::cancelSetup = false; - poweroff(true); - qApp->quit(); - } - else { - this->setStyleSheet("background-color: white"); - ui->activityWidget->show(); - mkEncfsDirs(); - QString passphrase = global::encfs::passphrase; - global::encfs::passphrase = ""; - writeFile("/external_root/run/encfs/encrypted_storage_archive", "/data/onboard/data.encfs"); - writeFile("/external_root/run/encfs/encrypted_storage_mountpoint", "/data/onboard/encfs-decrypted"); - writeFile("/external_root/run/encfs/encrypted_storage_bindmount", "/kobo/mnt/onboard/onboard/encfs-decrypted"); - writeFile("/external_root/run/encfs/encrypted_storage_passphrase", passphrase); - writeFile("/opt/ibxd", "encfs_restart\n"); - bool exitStatus; - - QString passphraseTriesStr = readFile("/inkbox/encryptedStoragePassphraseTries"); - if(passphraseTriesStr.isEmpty()) { - passphraseTries = 0; - } - else { - passphraseTries = passphraseTriesStr.toInt(); - passphraseTries++; - } - - ui->activityWidget->setCurrentIndex(3); - QTimer * t = new QTimer(this); - t->setInterval(1000); - connect(t, &QTimer::timeout, [&]() { - if(QFile::exists("/external_root/run/encfs_mounted")) { - exitStatus = true; - if(readFile("/external_root/run/encfs_mounted") != "true\n") { - exitStatus = false; - QFile::remove("/external_root/run/encfs_mounted"); - QString function = __func__; log(function + ": Invalid passphrase", className); - if(setupMessageBoxRan == false) { - int delay = 0; - if(passphraseTries <= 3) { - if(passphraseTries == 0) { - writeFile("/inkbox/encryptedStoragePassphraseTries", "0"); - delay = 5000; - } - else if(passphraseTries == 1) { - writeFile("/inkbox/encryptedStoragePassphraseTries", "1"); - delay = 10000; - } - else if(passphraseTries == 2) { - writeFile("/inkbox/encryptedStoragePassphraseTries", "2"); - delay = 20000; - } - else if(passphraseTries >= 3) { - writeFile("/inkbox/encryptedStoragePassphraseTries", "3"); - unsigned long currentEpoch = QDateTime::currentSecsSinceEpoch(); - currentEpoch += 86400; - QString unlockTime_str = QString::number(currentEpoch); - global::encfs::unlockTime = QDateTime::fromTime_t(currentEpoch).toString(); - global::encfs::lockdownMessage = "FATAL: 4 invalid passphrase tries, locking down device until " + global::encfs::unlockTime; - writeFile("/external_root/boot/flags/ENCRYPT_LOCK", unlockTime_str + "\n"); - global::encfs::lockdown = true; - setupMessageBoxRan = true; - - alertWindow = new alert(); - alertWindow->setAttribute(Qt::WA_DeleteOnClose); - alertWindow->showFullScreen(); - } - - if(passphraseTries <= 2) { - QTimer::singleShot(delay, this, SLOT(setupFailedAuthenticationMessageBox())); - setupMessageBoxRan = true; - } - } - } - } - else { - log("Unlocking successful", className); - quit_restart(); - } - } - } ); - t->start(); - } -} - -void encryptionManager::mkEncfsDirs() { - log("Creating encrypted storage directories", className); - QDir encfsDir; - QString encfsPath("/external_root/run/encfs"); - encfsDir.mkpath(encfsPath); - QDir dumpDir; - QString dumpPath("/mnt/onboard/onboard/encfs-dropbox"); - dumpDir.mkpath(dumpPath); - QDir decDir; - QString decPath("/mnt/onboard/onboard/encfs-decrypted"); - decDir.mkpath(decPath); -} - -void encryptionManager::on_exitSuccessBtn_clicked() -{ - setDefaultWorkDir(); - writeFile(".config/18-encrypted_storage/initial_setup_done", "true"); - quit_restart(); -} - -void encryptionManager::setupExitWidget(bool exitStatus) { - if(setupExitWidgetRan == false) { - if(exitStatus == true) { - ui->activityWidget->setCurrentIndex(1); - } - else { - writeFile(".config/18-encrypted_storage/status", "false"); - ui->activityWidget->setCurrentIndex(2); - } - setupExitWidgetRan = true; - } -} - -void encryptionManager::on_failureContinueBtn_clicked() -{ - setDefaultWorkDir(); - writeFile(".config/18-encrypted_storage/initial_setup_done", "true"); - quit_restart(); -} - -void encryptionManager::setupFailedAuthenticationMessageBox() { - log("Showing 'Authentication failed' message box", className); - ui->activityWidget->hide(); - QMessageBox::critical(this, tr("Invalid argument"), tr("Invalid passphrase. Please try again.")); - quit_restart(); -} - -void encryptionManager::on_acceptBtn_clicked() -{ - writeFile(".config/18-encrypted_storage/status", "false"); - quit_restart(); -} - - -void encryptionManager::on_usbmsBtn_clicked() -{ - log("Showing USBMS splash", className); - global::usbms::launchUsbms = true; - usbmsWindow = new usbmsSplash(); - usbmsWindow->setAttribute(Qt::WA_DeleteOnClose); - usbmsWindow->setGeometry(QRect(QPoint(0,0), screen()->geometry ().size())); - usbmsWindow->show(); -} - -void encryptionManager::repackEncryptedStorage() { - log("Repacking encrypted storage", className); - if(global::encfs::cancelSetup == true) { - global::encfs::cancelSetup = false; - quit_restart(); - } - else { - this->setStyleSheet("background-color: white"); - ui->activityWidget->show(); - mkEncfsDirs(); - QString passphrase = global::encfs::passphrase; - global::encfs::passphrase = ""; - writeFile("/external_root/run/encfs/encrypted_storage_repack_passphrase", passphrase); - QFile::remove("/external_root/run/openrc/started/encfs"); - writeFile("/opt/ibxd", "encfs_restart\n"); - bool exitStatus; - ui->activityWidget->setCurrentIndex(3); - QTimer * t = new QTimer(this); - t->setInterval(1000); - connect(t, &QTimer::timeout, [&]() { - if(QFile::exists("/external_root/run/encfs_repack_status")) { - exitStatus = checkconfig("/external_root/run/encfs_repack_status"); - QFile::remove("/external_root/run/encfs_repack_status"); - setupExitWidget(exitStatus); - } - } ); - t->start(); - } -} diff --git a/src/functions.h b/src/functions.h index 531dc30..6787227 100644 --- a/src/functions.h +++ b/src/functions.h @@ -1,1234 +1,838 @@ #ifndef FUNCTIONS_H #define FUNCTIONS_H +#include +#include +#include +#include +#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include -#include #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include -#include #include +#include #include #include +#include "device.h" + // WoW, global variables and namespaces are awesome namespace global { - namespace battery { - inline bool showLowBatteryDialog; - inline bool showCriticalBatteryAlert; - inline bool batteryAlertLock; - } - namespace reader { - inline QString bookFile; - inline int pageNumber; - inline int bookNumber; - inline bool skipOpenDialog; - inline bool startBatteryWatchdog; - inline bool startUsbmsPrompt; - inline bool bookIsEpub; - inline bool globalReadingSettings; - inline int pdfOrientation; - inline bool highlightAlreadyDone; - inline int textAlignment; - inline int lineSpacing; - inline QString font; - static inline int initialFontSize = 6; - inline int fontSize; - inline int margins; - inline QString currentViewportText; - } - namespace kobox { - inline bool showKoboxSplash; - inline bool koboxSettingsRebootDialog; - inline bool resetKoboxUserDataBool; - inline bool resetKoboxDialog; - } - namespace mainwindow { - namespace tabSwitcher { - inline bool repaint; - inline bool homePageWidgetCreated; - inline bool appsWidgetCreated; - inline bool appsWidgetSelected; - inline bool settingsChooserWidgetCreated; - inline bool settingsChooserWidgetSelected; - inline bool libraryWidgetCreated; - inline bool libraryWidgetSelected; - inline bool localLibraryWidgetCreated; - inline bool localLibraryWidgetSelected; - } - inline bool updateDialog; - inline bool lowBatteryDialog; - } - namespace usbms { - inline bool usbmsDialog; - inline bool showUsbmsDialog; - inline bool launchUsbms; - inline bool koboxExportExtensions; - } - namespace settings { - inline bool settingsRebootDialog; - } - namespace text { - inline bool textBrowserDialog; - inline QString textBrowserContents; - inline QString textBrowserTitle = ""; // At default: empty; "Information" will be displayed - } - namespace keyboard { - inline bool keyboardDialog; - inline bool keypadDialog; - inline bool searchDialog; - inline bool encfsDialog; - inline bool vncDialog; - inline bool wifiPassphraseDialog; - inline bool telemetryMessageDialog; - inline QString keyboardText; - inline QString keypadText; - inline bool embed = true; - } - namespace toast { - inline QString message; - inline bool modalToast; - inline bool indefiniteToast; - inline int delay; - } - namespace device { - inline bool isWifiAble; - } - namespace otaUpdate { - inline bool isUpdateOta; - inline bool downloadOta; - } - namespace encfs { - inline QString passphrase; - inline QString unlockTime; - inline QString lockdownMessage; - inline bool cancelSetup; - inline bool cancelUnlock; - inline bool lockdown; - inline bool enableStorageEncryptionDialog; - inline bool disableStorageEncryptionDialog; - inline bool errorNoBooksInDropboxDialog; - inline bool repackDialog; - } - namespace library { - inline unsigned long bookId; - inline bool isLatestBook; - inline int latestBookNumber; - inline QString bookTitle; - inline bool librarySearchDialog; - inline bool libraryResults; - inline bool librarySyncDialog; - } - namespace bookInfoDialog { - inline bool localInfoDialog; - } - namespace localLibrary { - static inline QString rawDatabasePath = "/inkbox/LocalLibrary.db.raw"; - static inline QString databaseDirectoryPath = "/mnt/onboard/onboard/.database/"; - static inline QString databasePath = databaseDirectoryPath + "LocalLibrary.db"; - static inline QString recentBooksDatabasePath = databaseDirectoryPath + "RecentBooks.db"; - static inline QString pinnedBooksDatabasePath = databaseDirectoryPath + "PinnedBooks.db"; - static inline QString highlightsDatabasePath = databaseDirectoryPath + "Highlights.db"; - static inline QString todoDatabasePath = databaseDirectoryPath + "ToDo.db"; - // Maximum signed integer value for 32-bit systems - static inline int folderID = 2147483647; - inline bool headless; - namespace bookOptionsDialog { - inline int bookID; - inline bool deleteOption = true; - inline bool bookDeleted; - inline bool bookPinAction; - inline QString folderPath; - inline bool isFolder = false; - } - } - namespace localStorage { - inline QStringList searchResultsPaths; - } - namespace logger { - inline bool status; - } - namespace userApps { - inline bool appCompatibilityDialog; - inline QString appCompatibilityText; - inline bool appCompatibilityLastContinueStatus = true; // This is for RequiredFeatures to show only one dialog if 'Cancel' is clicked. - inline bool appInfoDialog; - inline bool launchApp; - } - namespace homePageWidget { - static inline int recentBooksNumber = 8; - static inline int recentBooksNumberPerRow = 4; - static inline int recentBooksRowNumber = global::homePageWidget::recentBooksNumber / global::homePageWidget::recentBooksNumberPerRow; - static inline int pinnedBooksNumber = 4; - static inline int pinnedBooksNumberPerRow = 4; - static inline int pinnedBooksRowNumber = global::homePageWidget::pinnedBooksNumber / global::homePageWidget::pinnedBooksNumberPerRow; - } - namespace highlightsListDialog { - inline QString bookPath; - } - namespace wifi { - enum class wifiState { - configured, - enabled, - disabled, - unknown, // To not confuse lastWifiState - }; - inline bool isConnected; - class wifiNetworkData { - public: - QString mac; - QString name; - bool encryption; - int signal; - }; - } - namespace audio { - inline bool enabled = false; - struct musicFile { - QString path; - QString name; // Cut path for easier use in names - int lengths; // length Seconds - QString length; // In minutes:seconds - int id; - }; - // 'None' is when 'currentAction' is empty - enum class Action { // Function will be called with this enum - Play, - Next, - Previous, - Pause, - Continue, - Stop, // Sets 'paused' to false, 'isSomethingCurrentlyPlaying' to false, and 'itemCurrentlyPlaying' to -1; also stops playing - SetVolume, - }; - inline QVector currentAction; - inline QVector queue; - inline QVector fileList; - inline int itemCurrentlyPlaying = -1; // Also indicates in the queue menu which a gray color which is playing - inline QMutex audioMutex; // These variables will be shared between threads, so here, it's to protect it - inline int progressSeconds = -5; // -5 at default to avoid cutting song too early... yea - inline bool paused = false; - inline bool isSomethingCurrentlyPlaying = false; // Pause and continue - inline bool firstScan = true; - inline int volumeLevel = 40; // Default save value - inline bool songChanged = false; - } - namespace telemetry { - inline bool enabled = false; - inline bool telemetryDialog = false; - } - inline QString systemInfoText; - inline bool forbidOpenSearchDialog; - inline bool isN705 = false; - inline bool isN905C = false; - inline bool isN613 = false; - inline bool isN873 = false; - inline bool isN236 = false; - inline bool isN437 = false; - inline bool isN306 = false; - inline bool isN249 = false; - inline bool isKT = false; - inline bool runningInstanceIsReaderOnly; - inline QString deviceID; +namespace battery { +inline bool showLowBatteryDialog; +inline bool showCriticalBatteryAlert; +inline bool batteryAlertLock; +} //namespace battery +namespace reader { +inline QString bookFile; +inline int pageNumber; +inline int bookNumber; +inline bool skipOpenDialog; +inline bool startBatteryWatchdog; +inline bool startUsbmsPrompt; +inline bool bookIsEpub; +inline bool globalReadingSettings; +inline int pdfOrientation; +inline bool highlightAlreadyDone; +inline int textAlignment; +inline int lineSpacing; +inline QString font; +static inline int initialFontSize = 6; +inline int fontSize; +inline int margins; +inline QString currentViewportText; +} //namespace reader +namespace kobox { +inline bool showKoboxSplash; +inline bool koboxSettingsRebootDialog; +inline bool resetKoboxUserDataBool; +inline bool resetKoboxDialog; +} //namespace kobox +namespace mainwindow { +namespace tabSwitcher { +inline bool repaint; +inline bool homePageWidgetCreated; +inline bool appsWidgetCreated; +inline bool appsWidgetSelected; +inline bool settingsChooserWidgetCreated; +inline bool settingsChooserWidgetSelected; +inline bool libraryWidgetCreated; +inline bool libraryWidgetSelected; +inline bool localLibraryWidgetCreated; +inline bool localLibraryWidgetSelected; +} //namespace tabSwitcher +inline bool updateDialog; +inline bool lowBatteryDialog; +} //namespace mainwindow +namespace usbms { +inline bool usbmsDialog; +inline bool showUsbmsDialog; +inline bool launchUsbms; +inline bool koboxExportExtensions; +} //namespace usbms +namespace settings { +inline bool settingsRebootDialog; } +namespace text { +inline bool textBrowserDialog; +inline QString textBrowserContents; +inline QString textBrowserTitle = ""; // At default: empty; "Information" will be displayed +} //namespace text +namespace keyboard { +inline bool keyboardDialog; +inline bool keypadDialog; +inline bool searchDialog; +inline bool encfsDialog; +inline bool vncDialog; +inline bool wifiPassphraseDialog; +inline bool telemetryMessageDialog; +inline QString keyboardText; +inline QString keypadText; +inline bool embed = true; +} //namespace keyboard +namespace toast { +inline QString message; +inline bool modalToast; +inline bool indefiniteToast; +inline int delay; +} //namespace toast +namespace otaUpdate { +inline bool isUpdateOta; +inline bool downloadOta; +} //namespace otaUpdate +namespace encfs { +inline QString passphrase; +inline QString unlockTime; +inline QString lockdownMessage; +inline bool cancelSetup; +inline bool cancelUnlock; +inline bool lockdown; +inline bool enableStorageEncryptionDialog; +inline bool disableStorageEncryptionDialog; +inline bool errorNoBooksInDropboxDialog; +inline bool repackDialog; +} //namespace encfs +namespace library { +inline unsigned long bookId; +inline bool isLatestBook; +inline int latestBookNumber; +inline QString bookTitle; +inline bool librarySearchDialog; +inline bool libraryResults; +inline bool librarySyncDialog; +} //namespace library +namespace bookInfoDialog { +inline bool localInfoDialog; +} +namespace localLibrary { +static inline QString rawDatabasePath = "/inkbox/LocalLibrary.db.raw"; +static inline QString databaseDirectoryPath = "/mnt/onboard/onboard/.database/"; +static inline QString databasePath = databaseDirectoryPath + "LocalLibrary.db"; +static inline QString recentBooksDatabasePath = databaseDirectoryPath + "RecentBooks.db"; +static inline QString pinnedBooksDatabasePath = databaseDirectoryPath + "PinnedBooks.db"; +static inline QString highlightsDatabasePath = databaseDirectoryPath + "Highlights.db"; +static inline QString todoDatabasePath = databaseDirectoryPath + "ToDo.db"; +// Maximum signed integer value for 32-bit systems +static inline int folderID = 2147483647; +inline bool headless; +namespace bookOptionsDialog { +inline int bookID; +inline bool deleteOption = true; +inline bool bookDeleted; +inline bool bookPinAction; +inline QString folderPath; +inline bool isFolder = false; +} //namespace bookOptionsDialog +} //namespace localLibrary +namespace localStorage { +inline QStringList searchResultsPaths; +} +namespace logger { +inline bool status; +} +namespace userApps { +inline bool appCompatibilityDialog; +inline QString appCompatibilityText; +inline bool appCompatibilityLastContinueStatus = true; // This is for RequiredFeatures to show only one dialog if 'Cancel' is clicked. +inline bool appInfoDialog; +inline bool launchApp; +} //namespace userApps +namespace homePageWidget { +static inline int recentBooksNumber = 8; +static inline int recentBooksNumberPerRow = 4; +static inline int recentBooksRowNumber = global::homePageWidget::recentBooksNumber / global::homePageWidget::recentBooksNumberPerRow; +static inline int pinnedBooksNumber = 4; +static inline int pinnedBooksNumberPerRow = 4; +static inline int pinnedBooksRowNumber = global::homePageWidget::pinnedBooksNumber / global::homePageWidget::pinnedBooksNumberPerRow; +} //namespace homePageWidget +namespace highlightsListDialog { +inline QString bookPath; +} +namespace wifi { +enum class wifiState { + configured, + enabled, + disabled, + unknown, // To not confuse lastWifiState +}; +inline bool isConnected; +class wifiNetworkData { +public: + QString mac; + QString name; + bool encryption; + int signal; +}; +} //namespace wifi +namespace audio { +inline bool enabled = false; +struct musicFile { + QString path; + QString name; // Cut path for easier use in names + int lengths; // length Seconds + QString length; // In minutes:seconds + int id; +}; +// 'None' is when 'currentAction' is empty +enum class Action { // Function will be called with this enum + Play, + Next, + Previous, + Pause, + Continue, + Stop, // Sets 'paused' to false, 'isSomethingCurrentlyPlaying' to false, and 'itemCurrentlyPlaying' to -1; also stops playing + SetVolume, +}; +inline QVector currentAction; +inline QVector queue; +inline QVector fileList; +inline int itemCurrentlyPlaying = -1; // Also indicates in the queue menu which a gray color which is playing +inline QMutex audioMutex; // These variables will be shared between threads, so here, it's to protect it +inline int progressSeconds = -5; // -5 at default to avoid cutting song too early... yea +inline bool paused = false; +inline bool isSomethingCurrentlyPlaying = false; // Pause and continue +inline bool firstScan = true; +inline int volumeLevel = 40; // Default save value +inline bool songChanged = false; +} //namespace audio +namespace telemetry { +inline bool enabled = false; +inline bool telemetryDialog = false; +} //namespace telemetry +inline bool forbidOpenSearchDialog; +inline bool runningInstanceIsReaderOnly; +} //namespace global // https://stackoverflow.com/questions/6080853/c-multiple-definition-error-for-global-functions-in-the-header-file/20679534#20679534 namespace { - QString deviceUID; - QString device; - QString batteryLevel; - QString kernelVersion; - int batteryLevelInt; - int defaultEpubPageWidth; - int defaultEpubPageHeight; - int defaultPdfPageWidth; - int defaultPdfPageHeight; - bool checked_box = false; - QFile logFile("/external_root/var/log/inkbox-gui.log"); - void log(QString message, QString className = "undefined", bool applicationStart = false) { - if(global::logger::status == true) { - QString initialTime; - if(applicationStart == true) { - initialTime = QDateTime::currentDateTime().toString("dd/MM/yyyy @ hh:mm:ss"); - } - QDebug logger = qDebug(); - logger.noquote(); +int defaultEpubPageWidth; +int defaultEpubPageHeight; +int defaultPdfPageWidth; +int defaultPdfPageHeight; +bool checked_box = false; +QFile logFile("/external_root/var/log/inkbox-gui.log"); +void log(QString message, QString className = "undefined", bool applicationStart = false) { + if (global::logger::status == true) { + QString initialTime; + if (applicationStart == true) { + initialTime = QDateTime::currentDateTime().toString("dd/MM/yyyy @ hh:mm:ss"); + } + QDebug logger = qDebug(); + logger.noquote(); - QStringList logStringList; - logStringList << QDateTime::currentDateTime().toString("dd/MM/yyyy @ hh:mm:ss") << "|" << className + ":" << message.trimmed(); - QString logString = logStringList.join(" "); + QStringList logStringList; + logStringList << QDateTime::currentDateTime().toString("dd/MM/yyyy @ hh:mm:ss") << "|" << className + ":" << message.trimmed(); + QString logString = logStringList.join(" "); - logger << logString; - if(!logFile.isOpen()) { - logFile.open(QIODevice::Append|QIODevice::Text); - } - QTextStream logFileOut(&logFile); - if(applicationStart == true) { - logFileOut << "========== InkBox binary start at " << initialTime << " ==========" << Qt::endl; - } - logFileOut << logString << Qt::endl; - logFile.close(); - } - } - void logEnabled(QString configOption, QString className) { - log("Enabling " + configOption + " setting", className); - } - void logDisabled(QString configOption, QString className) { - log("Disabling " + configOption + " setting", className); - } - bool checkconfig(QString file) { - if(QFile::exists(file)) { - QFile config(file); - config.open(QIODevice::ReadOnly); - QTextStream in (&config); - const QString content = in.readAll(); - config.close(); - if(content.contains("true")) { - return true; - } - else { - return false; - } - } - else { - QString function = __func__; log(function + ": Warning: File '" + file + "' doesn't exist, returning false", "functions"); - return false; - } - return 0; - }; - void setDefaultWorkDir() { - QDir::setCurrent("/mnt/onboard/.adds/inkbox"); - } - int brightnessCheckconfig(QString file) { - if(QFile::exists(file)) { - QFile config(file); - config.open(QIODevice::ReadWrite); - QTextStream in (&config); - const QString content = in.readAll(); - int contentInt = content.toInt(); - return contentInt; - config.close(); - } - else { - return EXIT_FAILURE; - } - return 0; - } - void setBrightness(int value) { - if(global::deviceID == "n249\n") { - if(QFile::exists("/var/run/brightness_write")) { - std::ofstream fhandler; - fhandler.open("/var/run/brightness_write"); - fhandler << value; - fhandler.close(); - } - } - else { - if(QFile::exists("/var/run/brightness")) { - std::ofstream fhandler; - fhandler.open("/var/run/brightness"); - fhandler << value; - fhandler.close(); - } - } - } - void setBrightness_ntxio(int value) { - // Thanks to Kevin Short for this (GloLight) - int light; - if((light = open("/dev/ntx_io", O_RDWR)) == -1) { - fprintf(stderr, "Error opening ntx_io device\n"); - } - ioctl(light, 241, value); - close(light); - } - int displayQuote() { - int quoteNumber = QRandomGenerator::global()->bounded(1, 6); - return quoteNumber; - } - bool writeFile(QString filename, QString content) { - QFile file(filename); - if(file.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text)) { - QTextStream stream(&file); - stream << content; - return true; - } - else { - QString function = __func__; log(function + ": Failed to write string '" + content + "' to file '" + filename + "'", "functions"); - return false; - } - } - QString readFile(QString file) { - if(QFile::exists(file)) { - QFile fileToRead(file); - fileToRead.open(QIODevice::ReadOnly); - QTextStream in (&fileToRead); - QString content = in.readAll(); - return content; - } - else { - return NULL; - } - } - void brightnessWriteconfig(int value) { - std::ofstream fhandler; - fhandler.open(".config/03-brightness/config"); - fhandler << value; - fhandler.close(); - } - void warmthWriteconfig(int value) { - std::ofstream fhandler; - fhandler.open(".config/03-brightness/config-warmth"); - fhandler << value; - fhandler.close(); - } - int getBrightness() { - if(global::deviceID == "n613\n") { - QString brightnessConfig = readFile(".config/03-brightness/config"); - int brightness; - if(brightnessConfig.isEmpty()) { - brightness = 0; - } - else { - brightness = brightnessConfig.toInt(); - } - return brightness; - } - else { - if(QFile::exists("/var/run/brightness")) { - QFile brightness("/var/run/brightness"); - brightness.open(QIODevice::ReadOnly); - QString valuestr = brightness.readAll(); - int value = valuestr.toInt(); - brightness.close(); - return value; - } - else { - return 0; - } - } - return 0; - } - QString getPowerSupplyOfType(QString type) { - QDirIterator supplies("/sys/class/power_supply", QDirIterator::NoIteratorFlags); - while(supplies.hasNext()) { - supplies.next(); - QString supply = supplies.filePath(); - // Badly-classified device by some ntx kernels, ignore - if ((type == "Battery") && - (supplies.fileName() == "mc13892_charger")) { - continue; - } - if (readFile(supplies.filePath() + "/type").trimmed() == type) { - return supply; - } - } - return NULL; - } - QString getBatteryFile() { - static QString capacity; - if (capacity.isNull()) { - QString battery = getPowerSupplyOfType("Battery"); - if (!battery.isNull()) { - capacity = battery + "/capacity"; - } - } - return capacity; - } - void getBatteryLevel() { - batteryLevelInt = 100; - batteryLevel = "100%"; - if(global::deviceID == "kt\n") { - if(QFile::exists("/sys/devices/system/yoshi_battery/yoshi_battery0/battery_capacity")) { - batteryLevel = readFile("/sys/devices/system/yoshi_battery/yoshi_battery0/battery_capacity").trimmed(); - batteryLevelInt = batteryLevel.toInt(); - batteryLevel.append("%"); - } - } - else { - // probably superfluous, catched by default - if(QFile::exists("/sys/devices/platform/pmic_battery.1/power_supply/mc13892_bat/capacity")) { - batteryLevel = readFile("/sys/devices/platform/pmic_battery.1/power_supply/mc13892_bat/capacity").trimmed(); - batteryLevelInt = batteryLevel.toInt(); - batteryLevel.append("%"); - } - else { - QString path = getBatteryFile(); - if(QFile::exists(path)) { - batteryLevel = readFile(path).trimmed(); - batteryLevelInt = batteryLevel.toInt(); - batteryLevel.append("%"); - } - } - } - } - void writeconfig(std::string file, std::string config) { - std::ofstream fhandler; - fhandler.open(file); - fhandler << config << std::boolalpha << checked_box << std::endl; - fhandler.close(); - } - bool checkconfig_match(QString file, std::string pattern) { - QFile config(file); - config.open(QIODevice::ReadWrite); - QTextStream in (&config); - const QString content = in.readAll(); - std::string contentstr = content.toStdString(); - config.close(); - - // Thanks to https://stackoverflow.com/questions/22516463/how-do-i-find-a-complete-word-not-part-of-it-in-a-string-in-c - std::regex r("\\b" + pattern + "\\b"); - std::smatch m; - - if(std::regex_search(contentstr, m, r)) { - return true; - } - else { - return false; - } - return 0; - }; - bool isBatteryLow() { - // Checks if battery level is under 15% of total capacity. - getBatteryLevel(); - if(batteryLevelInt <= 15) { - return true; - } - else { - return false; - } - return 0; - } - bool isBatteryCritical() { - // Checks if the battery level is critical (i.e. <= 5%) - getBatteryLevel(); - if(batteryLevelInt <= 5) { - QString function = __func__; log(function + ": Battery is at a critical charge level!", "functions"); - return true; - } - else { - return false; - } - return 0; - } - void zeroBrightness() { - if(global::deviceID != "n613\n") { - setBrightness(0); - } - else { - setBrightness_ntxio(0); - } - } - void poweroff(bool splash) { - log("Powering off", "functions"); - if(splash == true) { - QString prog ("/sbin/poweroff"); - QStringList args; - QProcess *proc = new QProcess(); - proc->start(prog, args); - proc->waitForFinished(); - proc->deleteLater(); - } - else { - QString prog ("/sbin/poweroff"); - QStringList args; - args << "no_splash"; - QProcess *proc = new QProcess(); - proc->start(prog, args); - proc->waitForFinished(); - proc->deleteLater(); - } - } - void reboot(bool splash) { - log("Rebooting", "functions"); - if(splash == true) { - QString prog ("/sbin/reboot"); - QStringList args; - if(global::kobox::resetKoboxUserDataBool == true) { - args << "splash" << "reset_kobox"; - } - QProcess *proc = new QProcess(); - proc->start(prog, args); - proc->waitForFinished(); - proc->deleteLater(); - } - else { - QString prog ("/sbin/reboot"); - QStringList args; - if(global::kobox::resetKoboxUserDataBool == true) { - args << "no_splash" << "reset_kobox"; - } - else { - args << "no_splash"; - } - QProcess *proc = new QProcess(); - proc->start(prog, args); - proc->waitForFinished(); - proc->deleteLater(); - } - } - QString getUID() { - QString prog ("dd"); - QStringList args; - args << "if=/dev/mmcblk0" << "bs=512" << "skip=1" << "count=1" << "status=none"; - QProcess *proc = new QProcess(); - proc->start(prog, args); - proc->waitForFinished(); - - deviceUID = proc->readAllStandardOutput(); - deviceUID = deviceUID.left(256); - - proc->deleteLater(); - - return deviceUID; - } - void getKernelVersion() { - QString prog ("uname"); - QStringList args; - args << "-r"; - QProcess *proc = new QProcess(); - proc->start(prog, args); - proc->waitForFinished(); - - kernelVersion = proc->readAllStandardOutput(); - kernelVersion = kernelVersion.trimmed(); - - proc->deleteLater(); - - setDefaultWorkDir(); - writeFile("/external_root/run/initrd-fifo", "get_kernel_build_id\n"); - QThread::msleep(100); - writeFile("/external_root/run/initrd-fifo", "get_kernel_commit\n"); - QThread::msleep(100); - - QString kernelBuildID = readFile("/external_root/run/kernel_build_id").trimmed(); - kernelVersion.append(", build "); - kernelVersion.append(kernelBuildID); - - QString kernelCommit = readFile("/external_root/run/kernel_commit").trimmed(); - kernelVersion.append(", commit "); - kernelVersion.append(kernelCommit); - } - QString getConnectionInformation() { - QString getIpProg ("sh"); - QStringList getIpArgs; - if(global::deviceID != "n437\n" and global::deviceID != "n249\n") { - getIpArgs << "-c" << "/sbin/ifconfig eth0 | grep 'inet addr' | cut -d: -f2 | awk '{print $1}'"; - } - else { - getIpArgs << "-c" << "/sbin/ifconfig wlan0 | grep 'inet addr' | cut -d: -f2 | awk '{print $1}'"; - } - QProcess *getIpProc = new QProcess(); - getIpProc->start(getIpProg, getIpArgs); - getIpProc->waitForFinished(); - - QString ipAddress = getIpProc->readAllStandardOutput(); - if(ipAddress == "") { - ipAddress = "Not available"; - } - - getIpProc->deleteLater(); - return ipAddress; - } - void getSystemInfo() { - getUID(); - getKernelVersion(); - global::systemInfoText = "InkBox OS version "; - global::systemInfoText.append(readFile("/external_root/opt/isa/version")); - global::systemInfoText.append("
Copyright © 2021-2024 Nicolas Mailloux and contributors
Special thanks to: Szybet, NiLuJe, akemnade, Rain92 (GitHub)"); - global::systemInfoText.append("
GUI Git commit: "); - global::systemInfoText.append(GIT_VERSION); - global::systemInfoText.append("
Device UID: "); - global::systemInfoText.append(deviceUID); - global::systemInfoText.append("
Kernel version: "); - global::systemInfoText.append(kernelVersion); - global::systemInfoText.append("
Device: "); - QString device = global::deviceID.trimmed(); - global::systemInfoText.append(device); - QString ipAddress = getConnectionInformation(); - global::systemInfoText.append("
IP address: "); - global::systemInfoText.append(ipAddress); - - } - void resetKoboxUserData() { - log("Resetting KoBox user data", "functions"); - global::kobox::resetKoboxUserDataBool = true; - reboot(true); - } - QString findEpubMetadata(QString book_file, QString metadata) { - log("Finding ePUB metadata, query: " + metadata, "functions"); - setDefaultWorkDir(); - QString prog ("sh"); - QStringList args; - args << "find_epub_metadata.sh" << book_file << metadata; - QProcess *proc = new QProcess(); - proc->start(prog, args); - proc->waitForFinished(); - - QString returnedMetadata = proc->readAllStandardOutput(); - QString function = __func__; log(function + ": ePUB metadata is: " + returnedMetadata, "functions"); - return returnedMetadata; - } - void defineDefaultPageSize(int fileType) { - /* fileType can be: - * 0: ePUB - * 1: PDF - */ - if(fileType == 0) { - if(global::deviceID == "n705\n") { - defaultEpubPageHeight = 365; - defaultEpubPageWidth = 365; - } - else if(global::deviceID == "n905\n" or global::deviceID == "kt\n") { - defaultEpubPageHeight = 425; - defaultEpubPageWidth = 425; - } - else if(global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n437\n" or global::deviceID == "n306\n" or global::deviceID == "n249\n" or global::deviceID == "emu\n") { - defaultEpubPageHeight = 450; - defaultEpubPageWidth = 450; - } - else if(global::deviceID == "n873\n") { - defaultEpubPageHeight = 525; - defaultEpubPageWidth = 525; - } - QString function = __func__; - log(function + ": Defined default ePUB page height to " + QString::number(defaultEpubPageHeight), "functions"); - log(function + ": Defined default ePUB page width to " + QString::number(defaultEpubPageWidth), "functions"); - } - else if(fileType == 1) { - if(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "kt\n") { - if(global::reader::pdfOrientation == 0) { - defaultPdfPageHeight = 750; - defaultPdfPageWidth = 550; - } - else { - defaultPdfPageHeight = 550; - defaultPdfPageWidth = 750; - } - } - else if(global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n306\n" or global::deviceID == "emu\n") { - if(global::reader::pdfOrientation == 0) { - defaultPdfPageHeight = 974; - defaultPdfPageWidth = 708; - } - else { - defaultPdfPageHeight = 708; - defaultPdfPageWidth = 974; - } - } - else if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { - if(global::reader::pdfOrientation == 0) { - defaultPdfPageHeight = 1398; - defaultPdfPageWidth = 1022; - } - else { - defaultPdfPageHeight = 1022; - defaultPdfPageWidth = 1398; - } - } - else if(global::deviceID == "n873\n") { - if(global::reader::pdfOrientation == 0) { - defaultPdfPageHeight = 1630; - defaultPdfPageWidth = 1214; - } - else { - defaultPdfPageHeight = 1214; - defaultPdfPageWidth = 1630; - } - } - QString function = __func__; - log(function + "Defined default PDF page height to " + QString::number(defaultPdfPageHeight), "functions"); - log(function + "Defined default PDF page width to " + QString::number(defaultPdfPageWidth), "functions"); - } - } - void preSetBrightness(int brightnessValue) { - if(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "n873\n" or global::deviceID == "n236\n" or global::deviceID == "n437\n" or global::deviceID == "n306\n" or global::deviceID == "n249\n" or global::deviceID == "kt\n") { - setBrightness(brightnessValue); - } - else if(global::deviceID == "n613\n") { - setBrightness_ntxio(brightnessValue); - } - else { - setBrightness(brightnessValue); - } - } - void cinematicBrightness(int value, int mode) { - /* mode can be 0, 1, or 2, respectively: - * 0: Bring UP brightness - * 1: Bring DOWN brightness - * 2: Auto; smooth brightness transition between two brightness levels - */ - if(global::deviceID != "n705\n" && global::deviceID != "n905\n" && global::deviceID != "kt\n") { - QString function = __func__; log(function + ": Setting brightness to " + QString::number(value), "functions"); - } - if(mode == 0) { - int brightness = 0; - while(brightness != value) { - brightness = brightness + 1; - preSetBrightness(brightness); - QThread::msleep(30); - } - } - else if(mode == 1) { - int brightness = getBrightness(); - while(brightness != 0) { - brightness = brightness - 1; - preSetBrightness(brightness); - QThread::msleep(30); - } - } - else if(mode == 2) { - int brightness = getBrightness(); - if(brightness <= value) { - while(brightness != value) { - brightness = brightness + 1; - preSetBrightness(brightness); - QThread::msleep(30); - } - } - else if(brightness >= value) { - while(brightness != value) { - brightness = brightness - 1; - preSetBrightness(brightness); - QThread::msleep(30); - } - } - } - } - int getWarmth() { - QString sysfsWarmthPath; - int warmthValue; - if(global::deviceID == "n873\n") { - sysfsWarmthPath = "/sys/class/backlight/lm3630a_led/color"; - } - else if(global::deviceID == "n249\n") { - sysfsWarmthPath = "/sys/class/backlight/backlight_warm/actual_brightness"; - } - QString warmthConfig = readFile(sysfsWarmthPath); - warmthValue = warmthConfig.toInt(); - if (global::deviceID == "n873\n") { - warmthValue = 10 - warmthValue; - } - return warmthValue; - } - void setWarmth(int warmthValue) { - QString sysfsWarmthPath; - QString warmthValueStr; - if(global::deviceID == "n873\n") { - // Value 0 gives a warmer lighting than value 10 - warmthValue = 10 - warmthValue; - warmthValueStr = QString::number(warmthValue); - sysfsWarmthPath = "/sys/class/backlight/lm3630a_led/color"; - } - else if(global::deviceID == "n249\n") { - warmthValueStr = QString::number(warmthValue); - sysfsWarmthPath = "/sys/class/backlight/backlight_warm/brightness"; - } - writeFile(sysfsWarmthPath, warmthValueStr); - } - void cinematicWarmth(int warmthValue) { - int currentWarmth = getWarmth(); - if(warmthValue < currentWarmth) { - while(warmthValue < currentWarmth) { - currentWarmth--; - setWarmth(currentWarmth); - QThread::msleep(30); - } - } - else if(warmthValue > currentWarmth) { - while(warmthValue > currentWarmth) { - currentWarmth++; - setWarmth(currentWarmth); - QThread::msleep(30); - } - } - } - void installUpdate() { - log("Installing update package", "functions"); - writeFile("/mnt/onboard/onboard/.inkbox/can_really_update", "true\n"); - writeFile("/external_root/opt/update/will_update", "true\n"); - writeFile("/external_root/boot/flags/WILL_UPDATE", "true\n"); - reboot(true); - } - bool getEncFSStatus() { - return checkconfig("/external_root/run/encfs_mounted"); - } - bool isUsbPluggedIn() { - if(global::deviceID == "kt\n") { - if(readFile("/sys/devices/system/yoshi_battery/yoshi_battery0/battery_status") == "1\n") { - return 1; - } - else { - return 0; - } - } - else if(global::deviceID == "n249\n") { - if(readFile("/sys/class/power_supply/rn5t618-battery/status") != "Discharging\n") { - return 1; - } - else { - return 0; - } - } - else { - // Thanks to https://github.com/koreader/KoboUSBMS/blob/2efdf9d920c68752b2933f21c664dc1afb28fc2e/usbms.c#L148-L158 - int ntxfd; - if((ntxfd = open("/dev/ntx_io", O_RDWR)) == -1) { - fprintf(stderr, "Error opening ntx_io device\n"); - } - unsigned long ptr = 0U; - ioctl(ntxfd, 108, &ptr); - close(ntxfd); - return !!ptr; - } - } - void updateUserAppsMainJsonFile() { - QDirIterator appsDir("/mnt/onboard/onboard/.apps", QDirIterator::NoIteratorFlags); - QFile newJsonFile = QFile{"/mnt/onboard/onboard/.apps/apps.json"}; - QJsonDocument newJsonDocument; - QJsonArray array; - - while (appsDir.hasNext()) - { - QDir dir(appsDir.next()); - if(dir.exists() == true) { - if(dir.path().split("/").last().contains(".") == false) { - QFile jsonSmall = QFile{dir.path() + "/app.json"}; - if(jsonSmall.exists() == true) { - jsonSmall.open(QIODevice::ReadOnly | QIODevice::Text); - QString jsonString = jsonSmall.readAll(); - jsonSmall.close(); - - QJsonDocument jsonSmallDoc = QJsonDocument::fromJson(jsonString.toUtf8()); - if(jsonSmallDoc["app"].isObject() == true) { - QJsonObject jsonSmallMainObj = jsonSmallDoc["app"].toObject(); - array.append(jsonSmallMainObj); - - } - else { - log("Error: User application '" + appsDir.path() + "''s JSON file descriptor is missing main object 'app'", "main"); - } - - } - else { - QString message = "User application '" + appsDir.path() + "' does not contain any 'app.json' file: "; - message.append(jsonSmall.fileName()); - log(message, "main"); - } - } - } - } - // https://forum.qt.io/topic/104791/how-i-can-create-json-format-in-qt/5 - QJsonObject root; - root["list"] = array; - newJsonDocument.setObject(root); - - newJsonFile.open(QFile::WriteOnly | QFile::Text | QFile::Truncate); - newJsonFile.write(newJsonDocument.toJson()); - newJsonFile.flush(); - newJsonFile.close(); - } - void updateUserAppsSmallJsonFiles() { - QFile jsonFile = QFile{"/mnt/onboard/onboard/.apps/apps.json"}; - - jsonFile.open(QIODevice::ReadOnly | QIODevice::Text); - QString fileRead = jsonFile.readAll(); - jsonFile.close(); - QJsonDocument jsonDocument = QJsonDocument::fromJson(fileRead.toUtf8()); - - if(jsonDocument["list"].isArray() == true) { - QJsonArray jsonArray = jsonDocument["list"].toArray(); - for(QJsonValueRef refJsonObject: jsonArray) { - QJsonObject jsonMainObject = refJsonObject.toObject(); - QString appName = jsonMainObject["Name"].toString(); - - // This needs to be here and not at the beggining of this function because it is an iterator - QDirIterator appsDir("/mnt/onboard/onboard/.apps", QDirIterator::NoIteratorFlags); - while (appsDir.hasNext()) { - QDir dir(appsDir.next()); - if(dir.exists() == true) { - if(dir.path().split("/").last().toLower().contains(appName.toLower()) == true) { - QJsonObject root; - root["app"] = refJsonObject.toObject();; - QJsonDocument newJsonDocument; - newJsonDocument.setObject(root); - - QFile newSmallJson = QFile{dir.path() + "/" + "app.json"}; - - newSmallJson.open(QIODevice::ReadWrite); - QTextStream stream(&newSmallJson); - stream << newJsonDocument.toJson() << Qt::endl; - newSmallJson.flush(); - newSmallJson.close(); - } - } - } - } - } - } - QString fileChecksum(const QString &fileName, QCryptographicHash::Algorithm hashAlgorithm) { - QFile f(fileName); - if (f.open(QFile::ReadOnly)) { - QCryptographicHash hash(hashAlgorithm); - if (hash.addData(&f)) { - return hash.result().toHex(); - } - } - } - QJsonObject getBookMetadata(int bookID) { - // Read library database from file - QFile database(global::localLibrary::databasePath); - QByteArray data; - if(database.open(QIODevice::ReadOnly)) { - data = database.readAll(); - database.close(); - } - else { - QString function = __func__; log(function + ": Failed to open local library database file for reading at '" + database.fileName() + "'", "functions"); - } - - // Parse JSON data - QJsonObject jsonObject = QJsonDocument::fromJson(qUncompress(QByteArray::fromBase64(data))).object(); - QJsonArray jsonArrayList = jsonObject["database"].toArray(); - return jsonArrayList.at(bookID - 1).toObject(); - } - QJsonObject readHighlightsDatabase() { - // Read highlights database from file - QFile database(global::localLibrary::highlightsDatabasePath); - QByteArray data; - if(database.open(QIODevice::ReadOnly)) { - data = database.readAll(); - database.close(); - } - else { - QString function = __func__; log(function + ": Failed to open highlights database file for reading at '" + database.fileName() + "'", "functions"); - } - - // Parse JSON data - return QJsonDocument::fromJson(qUncompress(QByteArray::fromBase64(data))).object(); - } - void writeHighlightsDatabase(QJsonObject jsonObject) { - QFile::remove(global::localLibrary::highlightsDatabasePath); - writeFile(global::localLibrary::highlightsDatabasePath, qCompress(QJsonDocument(jsonObject).toJson()).toBase64()); - } - QJsonDocument readTodoDatabase() { - // Read To-Do database from file - QFile database(global::localLibrary::todoDatabasePath); - QByteArray data; - if(database.open(QIODevice::ReadOnly)) { - data = database.readAll(); - database.close(); - } - else { - QString function = __func__; log(function + ": Failed to open To-Do database file for reading at '" + database.fileName() + "'", "functions"); - } - - // Parse JSON data - return QJsonDocument::fromJson(data); - } - void writeTodoDatabase(QJsonDocument jsonDocument) { - QFile::remove(global::localLibrary::todoDatabasePath); - writeFile(global::localLibrary::todoDatabasePath, jsonDocument.toJson()); - } - void highlightBookText(QString text, QString bookPath, bool remove) { - if(remove == false) { - if(!QFile::exists(global::localLibrary::highlightsDatabasePath)) { - QJsonObject mainJsonObject; - QJsonObject firstJsonObject; - firstJsonObject.insert("BookPath", QJsonValue(bookPath)); - firstJsonObject.insert("T-" + QUuid::createUuid().toString(QUuid::WithoutBraces), QJsonValue(text)); - mainJsonObject["Book1"] = firstJsonObject; - writeHighlightsDatabase(mainJsonObject); - } - else { - QJsonObject jsonObject = readHighlightsDatabase(); - bool highlightWrote = false; - int length = jsonObject.length(); - for(int i = 1; i <= length; i++) { - if(jsonObject["Book" + QString::number(i)].toObject().value("BookPath").toString() == bookPath) { - log("highlightBookText: Found existing book in database with path '" + bookPath + "'", "functions"); - - // Insert highlight - QJsonObject highlightJsonObject = jsonObject["Book" + QString::number(i)].toObject(); - // Finding available slot for highlight in case the one we are looking for is already occupied - QString uuid = "T-"+ QUuid::createUuid().toString(QUuid::WithoutBraces); - if(highlightJsonObject.contains(uuid)) { - while(true) { - if(highlightJsonObject.contains(uuid)) { - uuid = "T-" + QUuid::createUuid().toString(QUuid::WithoutBraces); - } - else { - break; - } - } - } - highlightJsonObject.insert(uuid, text); - jsonObject["Book" + QString::number(i)] = highlightJsonObject; - - writeHighlightsDatabase(jsonObject); - highlightWrote = true; - } - } - - if(highlightWrote == false) { - // This block of code is called when the book is referenced in the database, but no highlights are currently indexed - QJsonObject bookJsonObject; - bookJsonObject.insert("BookPath", QJsonValue(bookPath)); - bookJsonObject.insert("T-" + QUuid::createUuid().toString(QUuid::WithoutBraces), QJsonValue(text)); - jsonObject["Book" + QString::number(length + 1)] = bookJsonObject; - - writeHighlightsDatabase(jsonObject); - highlightWrote = true; - } - } - } - else { - QJsonObject jsonObject = readHighlightsDatabase(); - int length = jsonObject.length(); - for(int i = 1; i <= length; i++) { - if(jsonObject["Book" + QString::number(i)].toObject().value("BookPath").toString() == bookPath) { - QJsonObject bookJsonObject = jsonObject["Book" + QString::number(i)].toObject(); - foreach(const QString& key, bookJsonObject.keys()) { - if(bookJsonObject.value(key).toString() == text) { - log("Found matching highlight to remove with text '" + text + "'", "functions.h"); - bookJsonObject.remove(key); - } - } - jsonObject["Book" + QString::number(i)] = bookJsonObject; - writeHighlightsDatabase(jsonObject); - } - } - } - } - QJsonObject getHighlightsForBook(QString bookPath) { - QJsonObject jsonObject = readHighlightsDatabase(); - int length = jsonObject.length(); - for(int i = 1; i <= length; i++) { - if(jsonObject["Book" + QString::number(i)].toObject().value("BookPath").toString() == bookPath) { - return jsonObject["Book" + QString::number(i)].toObject(); - break; - } - } - return QJsonObject(); - } - float determineYIncrease() { - if(global::deviceID == "n705\n" or global::deviceID == "n905\n") { - return 2; - } - else if(global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n306\n" or global::deviceID == "emu\n") { - return 2.6; - } - else if(global::deviceID == "n437\n" or global::deviceID == "n249\n" or global::deviceID == "n873\n") { - return 3; - } - else { - return 2; - } - } - global::wifi::wifiState checkWifiState() { - QString interfaceName; - if(global::deviceID == "n437\n" or global::deviceID == "n249\n" or global::deviceID == "kt\n") { - interfaceName = "wlan0"; - } - else { - interfaceName = "eth0"; - } - - // Check if network interface has an IP address - QNetworkInterface iface = QNetworkInterface::interfaceFromName(interfaceName); - QList entries = iface.addressEntries(); - if(!entries.isEmpty()) { - // Interface is up and has an IP address - global::wifi::isConnected = true; - return global::wifi::wifiState::configured; - } - else { - if(QFile::exists("/sys/class/net/" + interfaceName + "/operstate")) { - // Interface is up but doesn't have an IP address - global::wifi::isConnected = false; - return global::wifi::wifiState::enabled; - } - else { - // Interface is not up - global::wifi::isConnected = false; - return global::wifi::wifiState::disabled; - } - } - } - int testPing(QString ipAddress = "1.1.1.1") { - // For some reason, implementing a non-blocking version of this functions triggers a "terminate called without an active exception" error with a platform plugin compiled with a newer GCC 11 toolchain. The problem has been solved by transplanting this function into the related area which uses it. - QString function = __func__; log(function + ": pinging IP address " + ipAddress, "functions"); - QProcess *pingProcess = new QProcess(); - QString pingProg = "ping"; - QStringList pingArgs; - pingArgs << "-c" << "1" << ipAddress; - pingProcess->start(pingProg, pingArgs); - pingProcess->waitForFinished(); - int exitCode = pingProcess->exitCode(); - pingProcess->deleteLater(); - if(exitCode == 0) { - log("Ping successful", "functions"); - global::wifi::isConnected = true; - } - else { - log("Ping unsuccessful", "functions"); - if(ipAddress == "1.1.1.1") { - global::wifi::isConnected = false; - } - } - return exitCode; - } - bool checkProcessName(QString name) { - QDirIterator appsDir("/proc", QDirIterator::NoIteratorFlags); - while (appsDir.hasNext()) { - QDir dir(appsDir.next()); - QFile process = QFile(dir.path() + "/cmdline"); - if(process.exists() == true) { - process.open(QIODevice::ReadOnly); - QTextStream stream(&process); - if(stream.readLine().contains(name) == true) { - process.close(); - return true; - } - process.close(); - } - } - return false; - } - QString purgeHtml(QString text) { - // https://stackoverflow.com/questions/2799379/is-there-an-easy-way-to-strip-html-from-a-qstring-in-qt - // This can cause problems if someone names their directory with HTML tags, so stop here. Anki, which is a big project, also doesn't care about this - return text.remove(QRegExp("<[^>]*>")); - } - void bool_writeconfig(QString file, bool option) { - QString str; - if(option == true) { - str = "true"; - } - else { - str = "false"; - } - std::ofstream fhandler; - fhandler.open(file.toStdString()); - fhandler << str.toStdString(); - fhandler.close(); - } + logger << logString; + if (!logFile.isOpen()) { + logFile.open(QIODevice::Append | QIODevice::Text); + } + QTextStream logFileOut(&logFile); + if (applicationStart == true) { + logFileOut << "========== InkBox binary start at " << initialTime << " ==========" << Qt::endl; + } + logFileOut << logString << Qt::endl; + logFile.close(); + } +} +void logEnabled(QString configOption, QString className) { + log("Enabling " + configOption + " setting", className); +} +void logDisabled(QString configOption, QString className) { + log("Disabling " + configOption + " setting", className); +} +bool checkconfig(QString file) { + if (QFile::exists(file)) { + QFile config(file); + config.open(QIODevice::ReadOnly); + QTextStream in(&config); + const QString content = in.readAll(); + config.close(); + if (content.contains("true")) { + return true; + } else { + return false; + } + } else { + QString function = __func__; + log(function + ": Warning: File '" + file + "' doesn't exist, returning false", "functions"); + return false; + } + return 0; +}; +void setDefaultWorkDir() { + QDir::setCurrent("/mnt/onboard/.adds/inkbox"); } +int displayQuote() { + int quoteNumber = QRandomGenerator::global()->bounded(1, 6); + return quoteNumber; +} +bool writeFile(QString filename, QString content) { + QFile file(filename); + if (file.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text)) { + QTextStream stream(&file); + stream << content; + return true; + } else { + QString function = __func__; + log(function + ": Failed to write string '" + content + "' to file '" + filename + "'", "functions"); + return false; + } +} +QString readFile(QString file) { + if (QFile::exists(file)) { + QFile fileToRead(file); + fileToRead.open(QIODevice::ReadOnly); + QTextStream in(&fileToRead); + QString content = in.readAll(); + return content; + } else { + return NULL; + } +} + +void writeconfig(std::string file, std::string config) { + std::ofstream fhandler; + fhandler.open(file); + fhandler << config << std::boolalpha << checked_box << std::endl; + fhandler.close(); +} +bool checkconfig_match(QString file, std::string pattern) { + QFile config(file); + config.open(QIODevice::ReadWrite); + QTextStream in(&config); + const QString content = in.readAll(); + std::string contentstr = content.toStdString(); + config.close(); + + // Thanks to https://stackoverflow.com/questions/22516463/how-do-i-find-a-complete-word-not-part-of-it-in-a-string-in-c + std::regex r("\\b" + pattern + "\\b"); + std::smatch m; + + if (std::regex_search(contentstr, m, r)) { + return true; + } else { + return false; + } + return 0; +}; + +void poweroff(bool splash) { + log("Powering off", "functions"); + if (splash == true) { + QString prog("/sbin/poweroff"); + QStringList args; + QProcess *proc = new QProcess(); + proc->start(prog, args); + proc->waitForFinished(); + proc->deleteLater(); + } else { + QString prog("/sbin/poweroff"); + QStringList args; + args << "no_splash"; + QProcess *proc = new QProcess(); + proc->start(prog, args); + proc->waitForFinished(); + proc->deleteLater(); + } +} +void reboot(bool splash) { + log("Rebooting", "functions"); + if (splash == true) { + QString prog("/sbin/reboot"); + QStringList args; + if (global::kobox::resetKoboxUserDataBool == true) { + args << "splash" + << "reset_kobox"; + } + QProcess *proc = new QProcess(); + proc->start(prog, args); + proc->waitForFinished(); + proc->deleteLater(); + } else { + QString prog("/sbin/reboot"); + QStringList args; + if (global::kobox::resetKoboxUserDataBool == true) { + args << "no_splash" + << "reset_kobox"; + } else { + args << "no_splash"; + } + QProcess *proc = new QProcess(); + proc->start(prog, args); + proc->waitForFinished(); + proc->deleteLater(); + } +} + +QString getConnectionInformation() { + QString getIpProg("sh"); + QStringList getIpArgs; + + getIpArgs << "-c" + << "/sbin/ifconfig " + Device::getSingleton()->getNetworkInterfaceName() + " | grep 'inet addr' | cut -d: -f2 | awk '{print $1}'"; + + QProcess *getIpProc = new QProcess(); + getIpProc->start(getIpProg, getIpArgs); + getIpProc->waitForFinished(); + + QString ipAddress = getIpProc->readAllStandardOutput(); + if (ipAddress == "") { + ipAddress = "Not available"; + } + + getIpProc->deleteLater(); + return ipAddress; +} + +void resetKoboxUserData() { + log("Resetting KoBox user data", "functions"); + global::kobox::resetKoboxUserDataBool = true; + reboot(true); +} +QString findEpubMetadata(QString book_file, QString metadata) { + log("Finding ePUB metadata, query: " + metadata, "functions"); + setDefaultWorkDir(); + QString prog("sh"); + QStringList args; + args << "find_epub_metadata.sh" << book_file << metadata; + QProcess *proc = new QProcess(); + proc->start(prog, args); + proc->waitForFinished(); + + QString returnedMetadata = proc->readAllStandardOutput(); + QString function = __func__; + log(function + ": ePUB metadata is: " + returnedMetadata, "functions"); + return returnedMetadata; +} +void defineDefaultPageSize(int fileType) { + /* fileType can be: + * 0: ePUB + * 1: PDF + */ + Device *device = Device::getSingleton(); + Device::ScreenSize screenSize = device->getScreenSize(); + + if (fileType == 0) { + if (screenSize == Device::ScreenSize::SMALL) { + defaultEpubPageHeight = 365; + defaultEpubPageWidth = 365; + } else if (screenSize == Device::ScreenSize::MEDIUM) { + defaultEpubPageHeight = 425; + defaultEpubPageWidth = 425; + } else if (screenSize == Device::ScreenSize::LARGE) { + defaultEpubPageHeight = 450; + defaultEpubPageWidth = 450; + } else if (screenSize == Device::ScreenSize::VERY_LARGE) { + defaultEpubPageHeight = 525; + defaultEpubPageWidth = 525; + } + QString function = __func__; + log(function + ": Defined default ePUB page height to " + QString::number(defaultEpubPageHeight), "functions"); + log(function + ": Defined default ePUB page width to " + QString::number(defaultEpubPageWidth), "functions"); + } else if (fileType == 1) { + if (screenSize == Device::ScreenSize::SMALL) { + if (global::reader::pdfOrientation == 0) { + defaultPdfPageHeight = 750; + defaultPdfPageWidth = 550; + } else { + defaultPdfPageHeight = 550; + defaultPdfPageWidth = 750; + } + } else if (screenSize == Device::ScreenSize::MEDIUM) { + if (global::reader::pdfOrientation == 0) { + defaultPdfPageHeight = 974; + defaultPdfPageWidth = 708; + } else { + defaultPdfPageHeight = 708; + defaultPdfPageWidth = 974; + } + } else if (screenSize == Device::ScreenSize::LARGE) { + if (global::reader::pdfOrientation == 0) { + defaultPdfPageHeight = 1398; + defaultPdfPageWidth = 1022; + } else { + defaultPdfPageHeight = 1022; + defaultPdfPageWidth = 1398; + } + } else if (screenSize == Device::ScreenSize::VERY_LARGE) { + if (global::reader::pdfOrientation == 0) { + defaultPdfPageHeight = 1630; + defaultPdfPageWidth = 1214; + } else { + defaultPdfPageHeight = 1214; + defaultPdfPageWidth = 1630; + } + } + QString function = __func__; + log(function + "Defined default PDF page height to " + QString::number(defaultPdfPageHeight), "functions"); + log(function + "Defined default PDF page width to " + QString::number(defaultPdfPageWidth), "functions"); + } +} + +void installUpdate() { + log("Installing update package", "functions"); + writeFile("/mnt/onboard/onboard/.inkbox/can_really_update", "true\n"); + writeFile("/external_root/opt/update/will_update", "true\n"); + writeFile("/external_root/boot/flags/WILL_UPDATE", "true\n"); + reboot(true); +} +bool getEncFSStatus() { + return checkconfig("/external_root/run/encfs_mounted"); +} + +void updateUserAppsMainJsonFile() { + QDirIterator appsDir("/mnt/onboard/onboard/.apps", QDirIterator::NoIteratorFlags); + QFile newJsonFile = QFile{ "/mnt/onboard/onboard/.apps/apps.json" }; + QJsonDocument newJsonDocument; + QJsonArray array; + + while (appsDir.hasNext()) { + QDir dir(appsDir.next()); + if (dir.exists() == true) { + if (dir.path().split("/").last().contains(".") == false) { + QFile jsonSmall = QFile{ dir.path() + "/app.json" }; + if (jsonSmall.exists() == true) { + jsonSmall.open(QIODevice::ReadOnly | QIODevice::Text); + QString jsonString = jsonSmall.readAll(); + jsonSmall.close(); + + QJsonDocument jsonSmallDoc = QJsonDocument::fromJson(jsonString.toUtf8()); + if (jsonSmallDoc["app"].isObject() == true) { + QJsonObject jsonSmallMainObj = jsonSmallDoc["app"].toObject(); + array.append(jsonSmallMainObj); + + } else { + log("Error: User application '" + appsDir.path() + "''s JSON file descriptor is missing main object 'app'", "main"); + } + + } else { + QString message = "User application '" + appsDir.path() + "' does not contain any 'app.json' file: "; + message.append(jsonSmall.fileName()); + log(message, "main"); + } + } + } + } + // https://forum.qt.io/topic/104791/how-i-can-create-json-format-in-qt/5 + QJsonObject root; + root["list"] = array; + newJsonDocument.setObject(root); + + newJsonFile.open(QFile::WriteOnly | QFile::Text | QFile::Truncate); + newJsonFile.write(newJsonDocument.toJson()); + newJsonFile.flush(); + newJsonFile.close(); +} +void updateUserAppsSmallJsonFiles() { + QFile jsonFile = QFile{ "/mnt/onboard/onboard/.apps/apps.json" }; + + jsonFile.open(QIODevice::ReadOnly | QIODevice::Text); + QString fileRead = jsonFile.readAll(); + jsonFile.close(); + QJsonDocument jsonDocument = QJsonDocument::fromJson(fileRead.toUtf8()); + + if (jsonDocument["list"].isArray() == true) { + QJsonArray jsonArray = jsonDocument["list"].toArray(); + for (QJsonValueRef refJsonObject : jsonArray) { + QJsonObject jsonMainObject = refJsonObject.toObject(); + QString appName = jsonMainObject["Name"].toString(); + + // This needs to be here and not at the beggining of this function because it is an iterator + QDirIterator appsDir("/mnt/onboard/onboard/.apps", QDirIterator::NoIteratorFlags); + while (appsDir.hasNext()) { + QDir dir(appsDir.next()); + if (dir.exists() == true) { + if (dir.path().split("/").last().toLower().contains(appName.toLower()) == true) { + QJsonObject root; + root["app"] = refJsonObject.toObject(); + ; + QJsonDocument newJsonDocument; + newJsonDocument.setObject(root); + + QFile newSmallJson = QFile{ dir.path() + "/" + "app.json" }; + + newSmallJson.open(QIODevice::ReadWrite); + QTextStream stream(&newSmallJson); + stream << newJsonDocument.toJson() << Qt::endl; + newSmallJson.flush(); + newSmallJson.close(); + } + } + } + } + } +} +QString fileChecksum(const QString &fileName, QCryptographicHash::Algorithm hashAlgorithm) { + QFile f(fileName); + if (f.open(QFile::ReadOnly)) { + QCryptographicHash hash(hashAlgorithm); + if (hash.addData(&f)) { + return hash.result().toHex(); + } + } +} +QJsonObject getBookMetadata(int bookID) { + // Read library database from file + QFile database(global::localLibrary::databasePath); + QByteArray data; + if (database.open(QIODevice::ReadOnly)) { + data = database.readAll(); + database.close(); + } else { + QString function = __func__; + log(function + ": Failed to open local library database file for reading at '" + database.fileName() + "'", "functions"); + } + + // Parse JSON data + QJsonObject jsonObject = QJsonDocument::fromJson(qUncompress(QByteArray::fromBase64(data))).object(); + QJsonArray jsonArrayList = jsonObject["database"].toArray(); + return jsonArrayList.at(bookID - 1).toObject(); +} +QJsonObject readHighlightsDatabase() { + // Read highlights database from file + QFile database(global::localLibrary::highlightsDatabasePath); + QByteArray data; + if (database.open(QIODevice::ReadOnly)) { + data = database.readAll(); + database.close(); + } else { + QString function = __func__; + log(function + ": Failed to open highlights database file for reading at '" + database.fileName() + "'", "functions"); + } + + // Parse JSON data + return QJsonDocument::fromJson(qUncompress(QByteArray::fromBase64(data))).object(); +} +void writeHighlightsDatabase(QJsonObject jsonObject) { + QFile::remove(global::localLibrary::highlightsDatabasePath); + writeFile(global::localLibrary::highlightsDatabasePath, qCompress(QJsonDocument(jsonObject).toJson()).toBase64()); +} +QJsonDocument readTodoDatabase() { + // Read To-Do database from file + QFile database(global::localLibrary::todoDatabasePath); + QByteArray data; + if (database.open(QIODevice::ReadOnly)) { + data = database.readAll(); + database.close(); + } else { + QString function = __func__; + log(function + ": Failed to open To-Do database file for reading at '" + database.fileName() + "'", "functions"); + } + + // Parse JSON data + return QJsonDocument::fromJson(data); +} +void writeTodoDatabase(QJsonDocument jsonDocument) { + QFile::remove(global::localLibrary::todoDatabasePath); + writeFile(global::localLibrary::todoDatabasePath, jsonDocument.toJson()); +} +void highlightBookText(QString text, QString bookPath, bool remove) { + if (remove == false) { + if (!QFile::exists(global::localLibrary::highlightsDatabasePath)) { + QJsonObject mainJsonObject; + QJsonObject firstJsonObject; + firstJsonObject.insert("BookPath", QJsonValue(bookPath)); + firstJsonObject.insert("T-" + QUuid::createUuid().toString(QUuid::WithoutBraces), QJsonValue(text)); + mainJsonObject["Book1"] = firstJsonObject; + writeHighlightsDatabase(mainJsonObject); + } else { + QJsonObject jsonObject = readHighlightsDatabase(); + bool highlightWrote = false; + int length = jsonObject.length(); + for (int i = 1; i <= length; i++) { + if (jsonObject["Book" + QString::number(i)].toObject().value("BookPath").toString() == bookPath) { + log("highlightBookText: Found existing book in database with path '" + bookPath + "'", "functions"); + + // Insert highlight + QJsonObject highlightJsonObject = jsonObject["Book" + QString::number(i)].toObject(); + // Finding available slot for highlight in case the one we are looking for is already occupied + QString uuid = "T-" + QUuid::createUuid().toString(QUuid::WithoutBraces); + if (highlightJsonObject.contains(uuid)) { + while (true) { + if (highlightJsonObject.contains(uuid)) { + uuid = "T-" + QUuid::createUuid().toString(QUuid::WithoutBraces); + } else { + break; + } + } + } + highlightJsonObject.insert(uuid, text); + jsonObject["Book" + QString::number(i)] = highlightJsonObject; + + writeHighlightsDatabase(jsonObject); + highlightWrote = true; + } + } + + if (highlightWrote == false) { + // This block of code is called when the book is referenced in the database, but no highlights are currently indexed + QJsonObject bookJsonObject; + bookJsonObject.insert("BookPath", QJsonValue(bookPath)); + bookJsonObject.insert("T-" + QUuid::createUuid().toString(QUuid::WithoutBraces), QJsonValue(text)); + jsonObject["Book" + QString::number(length + 1)] = bookJsonObject; + + writeHighlightsDatabase(jsonObject); + highlightWrote = true; + } + } + } else { + QJsonObject jsonObject = readHighlightsDatabase(); + int length = jsonObject.length(); + for (int i = 1; i <= length; i++) { + if (jsonObject["Book" + QString::number(i)].toObject().value("BookPath").toString() == bookPath) { + QJsonObject bookJsonObject = jsonObject["Book" + QString::number(i)].toObject(); + foreach (const QString &key, bookJsonObject.keys()) { + if (bookJsonObject.value(key).toString() == text) { + log("Found matching highlight to remove with text '" + text + "'", "functions.h"); + bookJsonObject.remove(key); + } + } + jsonObject["Book" + QString::number(i)] = bookJsonObject; + writeHighlightsDatabase(jsonObject); + } + } + } +} +QJsonObject getHighlightsForBook(QString bookPath) { + QJsonObject jsonObject = readHighlightsDatabase(); + int length = jsonObject.length(); + for (int i = 1; i <= length; i++) { + if (jsonObject["Book" + QString::number(i)].toObject().value("BookPath").toString() == bookPath) { + return jsonObject["Book" + QString::number(i)].toObject(); + break; + } + } + return QJsonObject(); +} +float determineYIncrease() { + Device::ScreenSize screenSize = Device::getSingleton()->getScreenSize(); + if (screenSize == Device::ScreenSize::SMALL) { + return 2; + } else if (screenSize <= Device::ScreenSize::LARGE) { + return 2.6; + } else if (screenSize == Device::ScreenSize::VERY_LARGE) { + return 3; + } + + return 2; +} +global::wifi::wifiState checkWifiState() { + QString interfaceName = Device::getSingleton()->getNetworkInterfaceName(); + + // Check if network interface has an IP address + QNetworkInterface iface = QNetworkInterface::interfaceFromName(interfaceName); + QList entries = iface.addressEntries(); + if (!entries.isEmpty()) { + // Interface is up and has an IP address + global::wifi::isConnected = true; + return global::wifi::wifiState::configured; + } else { + if (QFile::exists("/sys/class/net/" + interfaceName + "/operstate")) { + // Interface is up but doesn't have an IP address + global::wifi::isConnected = false; + return global::wifi::wifiState::enabled; + } else { + // Interface is not up + global::wifi::isConnected = false; + return global::wifi::wifiState::disabled; + } + } +} +int testPing(QString ipAddress = "1.1.1.1") { + // For some reason, implementing a non-blocking version of this functions triggers a "terminate called without an active exception" error with a platform plugin compiled with a newer GCC 11 toolchain. The problem has been solved by transplanting this function into the related area which uses it. + QString function = __func__; + log(function + ": pinging IP address " + ipAddress, "functions"); + QProcess *pingProcess = new QProcess(); + QString pingProg = "ping"; + QStringList pingArgs; + pingArgs << "-c" + << "1" << ipAddress; + pingProcess->start(pingProg, pingArgs); + pingProcess->waitForFinished(); + int exitCode = pingProcess->exitCode(); + pingProcess->deleteLater(); + if (exitCode == 0) { + log("Ping successful", "functions"); + global::wifi::isConnected = true; + } else { + log("Ping unsuccessful", "functions"); + if (ipAddress == "1.1.1.1") { + global::wifi::isConnected = false; + } + } + return exitCode; +} +bool checkProcessName(QString name) { + QDirIterator appsDir("/proc", QDirIterator::NoIteratorFlags); + while (appsDir.hasNext()) { + QDir dir(appsDir.next()); + QFile process = QFile(dir.path() + "/cmdline"); + if (process.exists() == true) { + process.open(QIODevice::ReadOnly); + QTextStream stream(&process); + if (stream.readLine().contains(name) == true) { + process.close(); + return true; + } + process.close(); + } + } + return false; +} +QString purgeHtml(QString text) { + // https://stackoverflow.com/questions/2799379/is-there-an-easy-way-to-strip-html-from-a-qstring-in-qt + // This can cause problems if someone names their directory with HTML tags, so stop here. Anki, which is a big project, also doesn't care about this + return text.remove(QRegExp("<[^>]*>")); +} +void bool_writeconfig(QString file, bool option) { + QString str; + if (option == true) { + str = "true"; + } else { + str = "false"; + } + std::ofstream fhandler; + fhandler.open(file.toStdString()); + fhandler << str.toStdString(); + fhandler.close(); +} +} //namespace + #endif // FUNCTIONS_H diff --git a/src/homeWidget/mainwindow.cpp b/src/homeWidget/mainwindow.cpp deleted file mode 100644 index 2467cdc..0000000 --- a/src/homeWidget/mainwindow.cpp +++ /dev/null @@ -1,1123 +0,0 @@ -#include "mainwindow.h" -#include "ui_mainwindow.h" -#include "settings.h" -#include "ui_settings.h" -#include "apps.h" -#include "ui_apps.h" -#include "functions.h" -#include "audiodialog.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; - -MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent) - , ui(new Ui::MainWindow) -{ - ui->setupUi(this); - - // Needed, the screen is shifted? - // ~Szybet - if(global::deviceID == "n306\n") { - ui->centralwidget->layout()->setContentsMargins(4, 5, 8, 8); - } - - ui->inkboxLabel->setFont(QFont("u001")); - - ui->settingsBtn->setProperty("type", "borderless"); - ui->appsBtn->setProperty("type", "borderless"); - ui->quitBtn->setProperty("type", "borderless"); - ui->searchBtn->setProperty("type", "borderless"); - ui->pushButton->setProperty("type", "borderless"); - ui->libraryButton->setProperty("type", "borderless"); - ui->brightnessBtn->setProperty("type", "borderless"); - ui->homeBtn->setProperty("type", "borderless"); - ui->wifiBtn->setProperty("type", "borderless"); - ui->audioBtn->setProperty("type", "borderless"); - - ui->settingsBtn->setText(""); - ui->appsBtn->setText(""); - ui->pushButton->setText("\t\tReader"); - ui->libraryButton->setText("\t\tLibrary"); - ui->quitBtn->setText(""); - ui->searchBtn->setText(""); - ui->brightnessBtn->setText(""); - ui->homeBtn->setText(""); - ui->quoteLabel->setText(""); - ui->wifiBtn->setText(""); - ui->audioBtn->setText(""); - - ui->quotePictureLabel->setText(""); - - ui->quoteHeadingLabel->setStyleSheet("padding: 30px"); - ui->inkboxLabel->setStyleSheet("font-size: 10.5pt"); - ui->homeBtn->setStyleSheet("padding: 5px"); - - // Initializing some variables - global::battery::showLowBatteryDialog = true; - global::battery::showCriticalBatteryAlert = true; - global::usbms::showUsbmsDialog = true; - global::usbms::launchUsbms = false; - global::usbms::koboxExportExtensions = false; - global::mainwindow::tabSwitcher::repaint = true; - resetFullWindowException = false; - - // Getting the screen's size - sW = QGuiApplication::screens()[0]->size().width(); - sH = QGuiApplication::screens()[0]->size().height(); - - // Defining what the default icon size will be - if(global::deviceID == "n705\n") { - stdIconWidth = sW / 12; - stdIconHeight = sH / 12; - brightnessIconWidth = sW / 24; - brightnessIconHeight = sH / 24; - homeIconWidth = sW / 18; - homeIconHeight = sW / 18; - wifiIconWidth = sW / 20.5; - wifiIconHeight = sH / 20.5; - } - else if(global::deviceID == "n905\n" or global::deviceID == "kt\n") { - stdIconWidth = sW / 14; - stdIconHeight = sH / 14; - brightnessIconWidth = sW / 26; - brightnessIconHeight = sH / 26; - homeIconWidth = sW / 20; - homeIconHeight = sW / 20; - wifiIconWidth = sW / 22.5; - wifiIconHeight = sH / 22.5; - } - else if(global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n437\n" or global::deviceID == "n306\n" or global::deviceID == "n249\n" or global::deviceID == "emu\n") { - stdIconWidth = sW / 12.5; - stdIconHeight = sH / 12.5; - brightnessIconWidth = sW / 24.5; - brightnessIconHeight = sH / 24.5; - homeIconWidth = sW / 18.5; - homeIconHeight = sW / 18.5; - wifiIconWidth = sW / 21; - wifiIconHeight = sH / 21; - } - else { - stdIconWidth = sW / 14; - stdIconHeight = sH / 14; - brightnessIconWidth = sW / 26; - brightnessIconHeight = sH / 26; - homeIconWidth = sW / 20; - homeIconHeight = sW / 20; - wifiIconWidth = sW / 22.5; - wifiIconHeight = sH / 22.5; - } - - // Setting icons up - ui->pushButton->setIcon(QIcon(":/resources/book.png")); - ui->pushButton->setIconSize(QSize(stdIconWidth, stdIconHeight)); - ui->libraryButton->setIcon(QIcon(":/resources/online-library.png")); - ui->libraryButton->setIconSize(QSize(stdIconWidth, stdIconHeight)); - ui->searchBtn->setIcon(QIcon(":/resources/search.png")); - ui->searchBtn->setIconSize(QSize(stdIconWidth, stdIconHeight)); - ui->settingsBtn->setIcon(QIcon(":/resources/settings.png")); - ui->settingsBtn->setIconSize(QSize(stdIconWidth, stdIconHeight)); - ui->appsBtn->setIcon(QIcon(":/resources/apps.png")); - ui->appsBtn->setIconSize(QSize(stdIconWidth, stdIconHeight)); - ui->quitBtn->setIcon(QIcon(":/resources/power.png")); - ui->quitBtn->setIconSize(QSize(stdIconWidth, stdIconHeight)); - - ui->homeBtn->setIcon(QIcon(":/resources/home.png")); - ui->homeBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); - - ui->brightnessBtn->setIcon(QIcon(":/resources/frontlight.png")); - ui->brightnessBtn->setIconSize(QSize(brightnessIconWidth, brightnessIconHeight)); - - if(global::audio::enabled == false) { - ui->audioBtn->hide(); - ui->audioLine->hide(); - } - else { - ui->audioBtn->setIcon(QIcon(":/resources/music-note.png")); - ui->audioBtn->setIconSize(QSize(wifiIconWidth, wifiIconHeight)); - ui->labelLine_1->hide(); - ui->labelLine_2->hide(); - } - - updateWifiAble(); - if(global::device::isWifiAble == true) { - // Start Wi-Fi icon updater - QTimer *wifiIconTimer = new QTimer(this); - wifiIconTimer->setInterval(2500); - connect(wifiIconTimer, SIGNAL(timeout()), this, SLOT(updateWifiIcon())); - wifiIconTimer->start(); - } - setBatteryIcon(); - - ui->brightnessBtn->setStyleSheet("font-size: 9pt; padding-bottom: 5px; padding-top: 5px; padding-left: 8px; padding-right: 8px;"); - ui->wifiBtn->setStyleSheet("font-size: 9pt; padding-bottom: 0px; padding-top: 0px; padding-left: 8px; padding-right: 8px"); - - // Checking if we have a Mini or Touch there - if(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "kt\n") { - ui->batteryIcon->setStyleSheet("font-size: 5pt; padding-bottom: 0px; padding-top: 0px; padding-left: 1px; padding-right: 1px;"); - } - else if(global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n437\n" or global::deviceID == "n306\n" or global::deviceID == "n249\n" or global::deviceID == "emu\n") { - ui->batteryIcon->setStyleSheet("font-size: 5pt; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; padding-right: 0px;"); - } - else if(global::deviceID == "n873\n") { - ui->batteryIcon->setStyleSheet("font-size: 5pt; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; padding-right: 0px;"); - } - else { - ui->batteryIcon->setStyleSheet("font-size: 5pt; padding-bottom: 0px; padding-top: 0px; padding-left: 8px; padding-right: 8px;"); - } - - ui->line_7->setStyleSheet("padding: 0px"); - ui->batteryIcon->setText(""); - ui->batteryLabel->setText(""); - ui->timeLabel->setText(""); - ui->batteryLabel->setStyleSheet("padding-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px"); - - // Deleting/Hiding "Library" button if device is not WiFi-able - // NOTE: Using deleteLater() on these elements causes a segmentation fault and aborts the whole program when the Settings, Apps or Home button is pressed. No idea why. - if(global::device::isWifiAble == false && global::deviceID != "emu\n") { - ui->libraryButton->hide(); - ui->line_10->hide(); - } - - // Stylesheet - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - // Custom settings - // Reading from the config files and tweaking the program according to the options set - // Demo setting, changes "Welcome to InkBox" label to "InkBox" - if(checkconfig(".config/01-demo/config") == true) { - ui->inkboxLabel->setText("InkBox"); - } - - // Dark mode; write to the Kobo Nightmode FIFO - if(checkconfig(".config/10-dark_mode/config") == true) { - writeFile("/tmp/invertScreen", "y"); - } - else { - writeFile("/tmp/invertScreen", "n"); - } - - // Clock setting to show seconds - if(checkconfig(".config/02-clock/config") == true) { - QTimer *t = new QTimer(this); - t->setInterval(500); - connect(t, &QTimer::timeout, [&]() { - QString time = QTime::currentTime().toString("hh:mm:ss"); - getBatteryLevel(); - ui->timeLabel->setText(time); - ui->batteryLabel->setText(batteryLevel); - } ); - t->start(); - } - else { - QTimer *t = new QTimer(this); - t->setInterval(500); - connect(t, &QTimer::timeout, [&]() { - QString time = QTime::currentTime().toString("hh:mm"); - getBatteryLevel(); - ui->timeLabel->setText(time); - ui->batteryLabel->setText(batteryLevel); - } ); - t->start(); - } - - // Battery watchdog - QTimer *batteryWatchdog = new QTimer(this); - batteryWatchdog->setInterval(2000); - connect(batteryWatchdog, &QTimer::timeout, [&]() { - // Checking if battery level is low - if(global::battery::showCriticalBatteryAlert != true) { - ; - } - else { - if(isBatteryCritical() == true) { - if(isUsbPluggedIn() == true) { - ; - } - else { - log("Warning! Battery is at a critical charge level!", className); - openCriticalBatteryAlertWindow(); - } - } - } - - if(global::battery::showLowBatteryDialog != true) { - // Do nothing, since a dialog should already have been displayed and (probably) dismissed - ; - } - else { - if(isBatteryLow() == true) { - if(global::battery::batteryAlertLock == true) { - ; - } - else { - if(isUsbPluggedIn() == true) { - ; - } - else { - log("Warning! Battery is low!", className); - openLowBatteryDialog(); - } - } - } - } - } ); - batteryWatchdog->start(); - - // We set the brightness level saved in the config file - QTimer::singleShot(2000, this, SLOT(setInitialBrightness())); - - // If new files are found in /mnt/onboard/onboard/encfs-dropbox, ask if user wants to encrypt them - if(checkconfig(".config/18-encrypted_storage/status") == true) { - QDir encfsDropboxDir("/mnt/onboard/onboard/encfs-dropbox"); - if(!encfsDropboxDir.isEmpty()) { - QTimer::singleShot(1000, this, SLOT(openEncfsRepackDialog())); - } - } - - // Global reading settings - if(readFile(".config/16-global_reading_settings/config").isEmpty()) { - checked_box = false; - writeconfig(".config/16-global_reading_settings/config", "GlobalReadingSettings="); - } - - if(checkconfig(".config/05-quote/config") == false) { - stdIconWidth = sW / 2; - stdIconHeight = sH / 2; - int quote_value = displayQuote(); - if(quote_value == 1) { - QPixmap pixmap(":/resources/chesterton.jpg"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->quotePictureLabel->setPixmap(scaledPixmap); - ui->quoteLabel->setText("“A good novel tells us the truth about its hero; but a bad novel tells us the truth about its author.”\n― G.K. Chesterton"); - } - if(quote_value == 2) { - QPixmap pixmap(":/resources/alcott.jpg"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->quotePictureLabel->setPixmap(scaledPixmap); - ui->quoteLabel->setText("“I've got the key to my castle in the air, but whether I can unlock the door remains to be seen.”\n― Louisa May Alcott"); - } - if(quote_value == 3) { - QPixmap pixmap(":/resources/king.jpg"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->quotePictureLabel->setPixmap(scaledPixmap); - ui->quoteLabel->setText("“Quiet people have the loudest minds”\n― Stephen King"); - } - if(quote_value == 4) { - QPixmap pixmap(":/resources/davies.jpg"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->quotePictureLabel->setPixmap(scaledPixmap); - ui->quoteLabel->setText("“Authors like cats because they are such quiet, lovable, wise creatures, and cats like authors for the same reasons.”\n― Robertson Davies"); - } - if(quote_value == 5) { - QPixmap pixmap(":/resources/christie.png"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->quotePictureLabel->setPixmap(scaledPixmap); - ui->quoteLabel->setText("“One of the saddest things in life, is the things one remembers.”\n― Agatha Christie"); - } - ui->homeStackedWidget->setCurrentIndex(0); - } - else { - setupHomePageWidget(); - } - - // Check if it's the first boot since an update and confirm that it installed successfully - if(checkconfig("/opt/inkbox_genuine") == true) { - if(checkconfig("/external_root/opt/update/inkbox_updated") == true) { - QString version = readFile("/external_root/opt/isa/version"); - QString updatemsg = "InkBox update to version "; - updatemsg = updatemsg.append(version); - updatemsg = updatemsg.remove(QRegExp("[\n]")); - updatemsg = updatemsg.append(" completed successfully.

Changelog:
"); - QString changelog = readFile("/external_root/opt/isa/changelog"); - updatemsg = updatemsg.append(changelog); - updatemsg = updatemsg.append("
"); - log("Showing update changelog", className); - QMessageBox::information(this, tr("Information"), updatemsg); - writeFile("/external_root/opt/update/inkbox_updated", "false"); - - // Trigger Gutenberg re-sync, because we deleted the .inkbox folder ;) - if(QFile::exists("/external_root/opt/storage/gutenberg/last_sync")) { - QFile::remove("/external_root/opt/storage/gutenberg/last_sync"); - } - } - } - - // OTA update - if(!QFile(updatesCheckConfigPath).exists()) { - writeFile(updatesCheckConfigPath, "true"); - } - - if(checkconfig(updatesCheckConfigPath) == true) { - // Check for an update and ask if the user wants to install it - checkForUpdate(); - // Check for an OTA update - QTimer::singleShot(1000, this, SLOT(checkForOtaUpdate())); - } - - // USB mass storage prompt - if(!QFile(usbConfigPath).exists()) { - writeFile(usbConfigPath, "true"); - } - - if(checkconfig(usbConfigPath) == true) { - QTimer *usbmsPrompt = new QTimer(this); - usbmsPrompt->setInterval(500); - connect(usbmsPrompt, &QTimer::timeout, [&]() { - if(checkconfig("/opt/inkbox_genuine") == true) { - if(global::usbms::showUsbmsDialog != true) { - if(isUsbPluggedIn() != usbmsStatus) { - global::usbms::showUsbmsDialog = true; - } - } - else { - usbmsStatus = isUsbPluggedIn(); - if(usbmsStatus == false) { - // Loop again... - ; - } - else { - // An USB cable is connected! - setBatteryIcon(); - openUsbmsDialog(); - } - } - } - else { - // Do nothing, we're running along with Nickel & friends... - ; - } - } ); - usbmsPrompt->start(); - } - - // If the DEVKEY file is present, install a developer key - if(QFile::exists("/mnt/onboard/onboard/.inkbox/DEVKEY") == true && QFile::exists("/mnt/onboard/onboard/.inkbox/DEVKEY.dgst") == true) { - QString developerKey = readFile("/mnt/onboard/onboard/.inkbox/DEVKEY").left(256); - - setDefaultWorkDir(); - QString prog ("sh"); - QStringList args; - args << "install_developer-key.sh" << developerKey << "/mnt/onboard/onboard/.inkbox/DEVKEY.dgst"; - QProcess *proc = new QProcess(); - proc->start(prog, args); - proc->waitForFinished(); - proc->deleteLater(); - - QFile::remove("/mnt/onboard/onboard/.inkbox/DEVKEY"); - QFile::remove("/mnt/onboard/onboard/.inkbox/DEVKEY.dgst"); - - reboot(true); - qApp->quit(); - } - - // Write version control info to file in tmpfs - if(checkconfig("/opt/inkbox_genuine") == true) { - writeFile("/external_root/run/inkbox_gui_git_commit", GIT_COMMIT); - } - - // Telemetry - if(checkconfig(".config/24-telemetry/enabled") == false && checkconfig(".config/24-telemetry/asked") == false) { - if(testPing("23.163.0.39") == 0) { - QTimer::singleShot(1000, this, SLOT(openTelemetryDialog())); - } - } -} - -MainWindow::~MainWindow() -{ - delete ui; -} - -void MainWindow::openUpdateDialog() { - log("Showing Update dialog", className); - global::mainwindow::updateDialog = true; - // Write to a temporary file to show an "Update" prompt - writeFile("/inkbox/updateDialog", "true"); - - // Setup the dialog - generalDialogWindow = new generalDialog(this); - connect(generalDialogWindow, SIGNAL(showToast(QString)), SLOT(showToast(QString))); - connect(generalDialogWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToast())); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - QApplication::processEvents(); -} - -void MainWindow::openLowBatteryDialog() { - log("Showing Low Battery Dialog", className); - global::mainwindow::lowBatteryDialog = true; - global::battery::batteryAlertLock = true; - - generalDialogWindow = new generalDialog(this); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - QApplication::processEvents(); -} - -void MainWindow::openUsbmsDialog() { - log("Showing USB Mass Storage dialog", className); - global::usbms::showUsbmsDialog = false; - global::usbms::usbmsDialog = true; - - generalDialogWindow = new generalDialog(this); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - QApplication::processEvents(); -} - -void MainWindow::openCriticalBatteryAlertWindow() { - global::battery::showCriticalBatteryAlert = true; - global::battery::showLowBatteryDialog = false; - - alertWindow = new alert(); - alertWindow->setAttribute(Qt::WA_DeleteOnClose); - alertWindow->setGeometry(QRect(QPoint(0,0), screen()->geometry ().size())); - alertWindow->show(); -} - -void MainWindow::on_settingsBtn_clicked() -{ - log("Opening Settings Chooser widget", className); - resetFullWindowException = true; - resetWindow(false); - if(global::mainwindow::tabSwitcher::settingsChooserWidgetSelected != true) { - ui->settingsBtn->setStyleSheet("background: black"); - ui->settingsBtn->setIcon(QIcon(":/resources/settings-inverted.png")); - - // Create widget and make necessary connections - settingsChooserWindow = new settingsChooser(); - connect(settingsChooserWindow, SIGNAL(showToast(QString)), SLOT(showToast(QString))); - connect(settingsChooserWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToast())); - ui->stackedWidget->insertWidget(2, settingsChooserWindow); - global::mainwindow::tabSwitcher::settingsChooserWidgetCreated = true; - - // Switch tab - ui->stackedWidget->setCurrentIndex(2); - global::mainwindow::tabSwitcher::settingsChooserWidgetSelected = true; - - // Repaint - this->repaint(); - } - else { - ; - } -} - -void MainWindow::on_appsBtn_clicked() -{ - log("Opening Apps widget", className); - resetFullWindowException = true; - resetWindow(false); - if(global::mainwindow::tabSwitcher::appsWidgetSelected != true) { - ui->appsBtn->setStyleSheet("background: black"); - ui->appsBtn->setIcon(QIcon(":/resources/apps-inverted.png")); - - // Create widget - appsWindow = new apps(); - connect(appsWindow, SIGNAL(refreshScreen()), SLOT(refreshScreen())); - connect(appsWindow, SIGNAL(showToast(QString)), SLOT(showToast(QString))); - ui->stackedWidget->insertWidget(1, appsWindow); - global::mainwindow::tabSwitcher::appsWidgetCreated = true; - - // Switch tab - ui->stackedWidget->setCurrentIndex(1); - global::mainwindow::tabSwitcher::appsWidgetSelected = true; - - // Repaint - this->repaint(); - } - else { - ; - } -} - -void MainWindow::on_pushButton_clicked() -{ - resetFullWindowException = true; - resetWindow(false); - if(global::mainwindow::tabSwitcher::localLibraryWidgetSelected != true) { - ui->pushButton->setStyleSheet("background: black; color: white"); - ui->pushButton->setIcon(QIcon(":/resources/book_inverted.png")); - - // Create widget - setupLocalLibraryWidget(); - global::mainwindow::tabSwitcher::localLibraryWidgetCreated = true; - - // Switch tab - ui->stackedWidget->setCurrentIndex(0); - global::mainwindow::tabSwitcher::localLibraryWidgetSelected = true; - - // Repaint - this->repaint(); - } -} - -void MainWindow::on_searchBtn_clicked() -{ - global::forbidOpenSearchDialog = false; - setupSearchDialog(); -} - -void MainWindow::on_quitBtn_clicked() -{ - log("Opening Quit widget", className); - quitWindow = new quit(); - quitWindow->setAttribute(Qt::WA_DeleteOnClose); - quitWindow->showFullScreen(); -} - -void MainWindow::on_brightnessBtn_clicked() -{ - log("Showing Brightness Dialog", className); - brightnessDialogWindow = new brightnessDialog(); - brightnessDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - brightnessDialogWindow->show(); -} - -void MainWindow::on_homeBtn_clicked() -{ - log("Showing home screen", className); - if(global::localLibrary::bookOptionsDialog::bookPinAction == true) { - global::localLibrary::bookOptionsDialog::bookPinAction = false; - global::mainwindow::tabSwitcher::repaint = false; - } - else { - global::mainwindow::tabSwitcher::repaint = true; - } - resetFullWindowException = true; - resetWindow(true); -} - -void MainWindow::resetWindow(bool resetStackedWidget) { - // Reset layout - bool authorQuote = false; - if(resetStackedWidget == true) { - if(checkconfig(".config/05-quote/config") == false) { - authorQuote = true; - ui->homeStackedWidget->setCurrentIndex(0); - } - else { - ui->homeStackedWidget->setCurrentIndex(2); - } - ui->stackedWidget->setCurrentIndex(0); - } - - // Destroy widgets - if(global::mainwindow::tabSwitcher::homePageWidgetCreated == true) { - homePageWidgetWindow->deleteLater(); - } - if(global::mainwindow::tabSwitcher::appsWidgetCreated == true) { - appsWindow->deleteLater(); - } - if(global::mainwindow::tabSwitcher::settingsChooserWidgetCreated == true) { - settingsChooserWindow->deleteLater(); - } - if(global::mainwindow::tabSwitcher::libraryWidgetCreated == true) { - libraryWidgetWindow->deleteLater(); - } - if(global::mainwindow::tabSwitcher::localLibraryWidgetCreated == true) { - localLibraryWidgetWindow->deleteLater(); - } - - global::mainwindow::tabSwitcher::homePageWidgetCreated = false; - global::mainwindow::tabSwitcher::appsWidgetCreated = false; - global::mainwindow::tabSwitcher::settingsChooserWidgetCreated = false; - global::mainwindow::tabSwitcher::appsWidgetSelected = false; - global::mainwindow::tabSwitcher::settingsChooserWidgetSelected = false; - global::mainwindow::tabSwitcher::libraryWidgetCreated = false; - global::mainwindow::tabSwitcher::libraryWidgetSelected = false; - global::mainwindow::tabSwitcher::localLibraryWidgetCreated = false; - global::mainwindow::tabSwitcher::localLibraryWidgetSelected = false; - - resetIcons(); - setBatteryIcon(); - if(global::mainwindow::tabSwitcher::repaint == true) { - this->repaint(); - } - if(resetStackedWidget == true && authorQuote == false) { - setupHomePageWidget(); - } -} - -void MainWindow::resetIcons() { - // Reset icons - ui->appsBtn->setStyleSheet("background: white"); - ui->appsBtn->setIcon(QIcon(":/resources/apps.png")); - ui->settingsBtn->setStyleSheet("background: white"); - ui->settingsBtn->setIcon(QIcon(":/resources/settings.png")); - ui->libraryButton->setStyleSheet("background: white"); - ui->libraryButton->setIcon(QIcon(":/resources/online-library.png")); - ui->pushButton->setStyleSheet("background: white"); - ui->pushButton->setIcon(QIcon(":/resources/book.png")); -} - -void MainWindow::setBatteryIcon() { - // Battery - if(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "n613\n" or global::deviceID == "n873\n" or global::deviceID == "n236\n" or global::deviceID == "n437\n" or global::deviceID == "n306\n" or global::deviceID == "n249\n" or global::deviceID == "kt\n") { - // Hide brightness controls; they won't be very useful there anyway (for anything but the Glo (HD)/Libra/Aura 2) ... - if(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "kt\n") { - ui->brightnessBtn->hide(); - ui->line_7->hide(); - } - - // Setting icons up - stdIconWidth = sW / 16; - stdIconHeight = sH / 16; - - QPixmap chargingPixmap(":/resources/battery_charging.png"); - QPixmap scaledChargingPixmap = chargingPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - QPixmap fullPixmap(":/resources/battery_full.png"); - QPixmap scaledFullPixmap = fullPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - QPixmap halfPixmap(":/resources/battery_half.png"); - QPixmap scaledHalfPixmap = halfPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - QPixmap emptyPixmap(":/resources/battery_empty.png"); - QPixmap scaledEmptyPixmap = emptyPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - - // Checking battery level and status, then displaying the relevant icon on batteryIcon - if(isUsbPluggedIn() == true) { - ui->batteryIcon->setPixmap(scaledChargingPixmap); - } - else { - getBatteryLevel(); - if(batteryLevelInt >= 75 && batteryLevelInt <= 100) { - ui->batteryIcon->setPixmap(scaledFullPixmap); - } - else if(batteryLevelInt >= 25 && batteryLevelInt <= 74) { - ui->batteryIcon->setPixmap(scaledHalfPixmap); - } - else if(batteryLevelInt >= 0 && batteryLevelInt <= 24) { - ui->batteryIcon->setPixmap(scaledEmptyPixmap); - } - } - } - else { - // Setting icons up - stdIconWidth = sW / 19; - stdIconHeight = sH / 19; - QPixmap chargingPixmap(":/resources/battery_charging.png"); - QPixmap scaledChargingPixmap = chargingPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - QPixmap fullPixmap(":/resources/battery_full.png"); - QPixmap scaledFullPixmap = fullPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - QPixmap halfPixmap(":/resources/battery_half.png"); - QPixmap scaledHalfPixmap = halfPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - QPixmap emptyPixmap(":/resources/battery_empty.png"); - QPixmap scaledEmptyPixmap = emptyPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - - // Checking battery level and status, then displaying the relevant icon on batteryIcon - if(isUsbPluggedIn() == true) { - ui->batteryIcon->setPixmap(scaledChargingPixmap); - } - else { - getBatteryLevel(); - if(batteryLevelInt >= 75 && batteryLevelInt <= 100) { - ui->batteryIcon->setPixmap(scaledFullPixmap); - } - else if(batteryLevelInt >= 25 && batteryLevelInt <= 74) { - ui->batteryIcon->setPixmap(scaledHalfPixmap); - } - else if(batteryLevelInt >= 0 && batteryLevelInt <= 24) { - ui->batteryIcon->setPixmap(scaledEmptyPixmap); - } - } - } -} - -void MainWindow::setInitialBrightness() { - if(global::deviceID == "n249\n" or global::deviceID == "n873\n") { - int warmth; - QString warmthConfig = readFile(".config/03-brightness/config-warmth"); - if(warmthConfig.isEmpty()) { - warmth = 0; - } - else { - warmth = warmthConfig.toInt(); - } - cinematicWarmth(warmth); - } - int brightness_value = brightnessCheckconfig(".config/03-brightness/config"); - if(global::deviceID != "n705\n" and global::deviceID != "n905\n" and global::deviceID != "kt\n") { - log("Setting initial brightness to " + QString::number(brightness_value), className); - } - if(checkconfig("/tmp/oobe-inkbox_completed") == true) { - // Coming from OOBE setup; not doing that fancy stuff again ;p - QFile::remove("/tmp/oobe-inkbox_completed"); - preSetBrightness(brightness_value); - log("Ignoring cinematic brightness call because it has already been done", className); - } - else { - // Fancy brightness fade-in - if(checkconfig("/tmp/inkbox-cinematicBrightness_auto") == true) { - QFile::remove("/tmp/inkbox-cinematicBrightness_auto"); - cinematicBrightness(brightness_value, 2); - } - else { - if(checkconfig("/tmp/inkbox-cinematicBrightness_ran") == false) { - writeFile("/tmp/inkbox-cinematicBrightness_ran", "true"); - cinematicBrightness(brightness_value, 0); - } - else { - log("Ignoring cinematic brightness call because it has already been done", className); - } - } - } -} - -void MainWindow::refreshScreen() { - this->repaint(); -} - -void MainWindow::setupSearchDialog() { - if(global::forbidOpenSearchDialog == false) { - log("Launching Search dialog", className); - global::keyboard::keyboardDialog = true; - global::keyboard::searchDialog = true; - global::keyboard::keyboardText = ""; - generalDialogWindow = new generalDialog(); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - connect(generalDialogWindow, SIGNAL(destroyed(QObject*)), SLOT(setupSearchDialog())); - connect(generalDialogWindow, SIGNAL(refreshScreen()), SLOT(refreshScreen())); - connect(generalDialogWindow, SIGNAL(showToast(QString)), SLOT(showToast(QString))); - connect(generalDialogWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToast())); - connect(generalDialogWindow, SIGNAL(openBookFile(QString, bool)), SLOT(openBookFile(QString, bool))); - generalDialogWindow->show(); - } - else { - ; - } -} - -void MainWindow::updateWifiIcon() { - /* Usage: - * Mode 0 (looping it) is handled in MainWindow - */ - - global::wifi::wifiState currentWifiState = checkWifiState(); - - // It's executing only in enabled mode, which is a mode between connected and disabled, so don't worry about performance - if(isConnecting == false and isReconnecting == false) { - if(currentWifiState == global::wifi::wifiState::enabled) { - if(checkProcessName("connection_manager.sh") == true) { - isConnecting = true; - } - else if(checkProcessName("connect_to_network.sh") == true){ - isConnecting = true; - isReconnecting = true; - } - } - } - - // ms can make a difference, so: - currentWifiState = checkWifiState(); - - if(lastWifiState != currentWifiState) { - if(currentWifiState == global::wifi::wifiState::disabled) { - if(isConnecting == true) { - if(checkconfig("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/stopped") == false) { - if(isReconnecting == true) { - showToast("Reconnection failed"); - isReconnecting = false; - } - else { - showToast("Connection failed"); - } - isConnecting = false; - QFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/essid").remove(); - QFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/passphrase").remove(); - } - else { - QFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/stopped").remove(); - } - } - lastWifiState = global::wifi::wifiState::disabled; - ui->wifiBtn->setIcon(QIcon(":/resources/wifi-off.png")); - ui->wifiBtn->setIconSize(QSize(wifiIconWidth, wifiIconHeight)); - } - if(currentWifiState == global::wifi::wifiState::enabled) { - lastWifiState = global::wifi::wifiState::enabled; - ui->wifiBtn->setIcon(QIcon(":/resources/wifi-standby.png")); - ui->wifiBtn->setIconSize(QSize(wifiIconWidth, wifiIconHeight)); - } - if(currentWifiState == global::wifi::wifiState::configured) { - if(isConnecting == true) { - setDefaultWorkDir(); - if(isReconnecting == true) { - showToast("Reconnection successful"); - isReconnecting = false; - } - else { - showToast("Connection successful"); - } - isConnecting = false; - QFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/stopped").remove(); - } - lastWifiState = global::wifi::wifiState::configured; - ui->wifiBtn->setIcon(QIcon(":/resources/wifi-100.png")); - ui->wifiBtn->setIconSize(QSize(wifiIconWidth, wifiIconHeight)); - } - } -} - -void MainWindow::updateWifiAble() { - if(global::device::isWifiAble == false) { - ui->wifiBtn->hide(); - ui->line_9->hide(); - } -} - -void MainWindow::on_wifiBtn_clicked() -{ - wifiDialog* newWifiDialog = new wifiDialog(); - QObject::connect(newWifiDialog, &wifiDialog::showToast, this, &MainWindow::showToast); - newWifiDialog->exec(); -} - -void MainWindow::showToast(QString messageToDisplay) { - global::toast::message = messageToDisplay; - toastWindow = new toast(this); - toastWindow->setAttribute(Qt::WA_DeleteOnClose); - connect(toastWindow, SIGNAL(refreshScreen()), SLOT(refreshScreen())); - connect(toastWindow, SIGNAL(showToast(QString)), SLOT(showToast(QString))); - connect(toastWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToast())); - toastWindow->show(); - - // I will soon manage the update thing in a more proper way somewhere else... ~ Szybet - if(messageToDisplay.contains("onnected successfully") == true) { - // Give the toast some time to vanish away, then launch OTA updater - QTimer::singleShot(5000, this, SLOT(launchOtaUpdater())); - } -} - -void MainWindow::hello(int testNumber) { - log("Hello" + QString::number(testNumber), className); -} - -void MainWindow::closeIndefiniteToast() { - // Warning: use with caution - toastWindow->close(); -} - -void MainWindow::openUpdateDialogOTA(bool open) { - if(open == true) { - QString function = __func__; log(function + ": Showing update dialog (OTA)", className); - global::otaUpdate::isUpdateOta = true; - openUpdateDialog(); - } - else { - ; - } -} - -void MainWindow::launchOtaUpdater() { - log("Launching OTA updater", className); - otaManagerWindow = new otaManager(this); - connect(otaManagerWindow, SIGNAL(canOtaUpdate(bool)), SLOT(openUpdateDialogOTA(bool))); - otaManagerWindow->setAttribute(Qt::WA_DeleteOnClose); -} - -void MainWindow::openBookFile(QString book, bool relativePath) { - if(relativePath == true) { - if(checkconfig("/opt/inkbox_genuine") == true) { - book.prepend("/mnt/onboard/onboard/"); - } - else { - book.prepend("/mnt/onboard/"); - } - } - - global::reader::skipOpenDialog = true; - global::reader::bookFile = book; - openReaderFramework(); -} - -void MainWindow::openReaderFramework() { - log("Launching Reader Framework", className); - readerWindow = new reader(); - readerWindow->setAttribute(Qt::WA_DeleteOnClose); - connect(readerWindow, SIGNAL(openBookFile(QString, bool)), SLOT(openBookFile(QString, bool))); - readerWindow->showFullScreen(); -} - -void MainWindow::checkForUpdate() { - log("Checking for available updates", className); - if(checkconfig("/mnt/onboard/onboard/.inkbox/can_update") == true) { - if(checkconfig("/tmp/cancelUpdateDialog") == false) { - // I'm sorry. - QString function = __func__; log(function + ": An update is available.", className); - QTimer::singleShot(2000, this, SLOT(openUpdateDialog())); - } - else { - QString function = __func__; log(function + ": Not showing update dialog, user dismissed it", className); - } - } - else { - QString function = __func__; log(function + ": No update available.", className); - } -} - -void MainWindow::openEncfsRepackDialog() { - log("Showing encrypted storage repack dialog", className); - global::encfs::repackDialog = true; - global::usbms::showUsbmsDialog = false; - global::usbms::usbmsDialog = false; - generalDialogWindow = new generalDialog(this); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); -} - -void MainWindow::on_libraryButton_clicked() -{ - log("Launching Online Library", className); - if(testPing() == 0 or global::deviceID == "emu\n") { - // 'Do you want to sync?' dialog - bool willSync = false; - QString syncEpochQStr = readFile("/external_root/opt/storage/gutenberg/last_sync"); - if(!syncEpochQStr.isEmpty()) { - unsigned long currentEpoch = QDateTime::currentSecsSinceEpoch(); - unsigned long syncEpoch = syncEpochQStr.toULong(); - unsigned long allowSyncEpoch = syncEpoch + 86400; - if(currentEpoch > allowSyncEpoch) { - willSync = true; - } - } - else if(syncEpochQStr.isEmpty()) { - willSync = true; - } - - if(willSync == true) { - log("Showing 'Sync required' dialog", className); - global::library::librarySyncDialog = true; - generalDialogWindow = new generalDialog(this); - QObject::connect(generalDialogWindow, &generalDialog::syncOnlineLibrary, this, &MainWindow::launchOnlineLibrary); - QObject::connect(generalDialogWindow, &generalDialog::noSyncOnlineLibrary, this, &MainWindow::on_homeBtn_clicked); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - generalDialogWindow->show(); - } - else { - launchOnlineLibrary(); - } - } - else { - showToast("Wi-Fi connection error"); - } -} - -void MainWindow::launchOnlineLibrary() { - resetFullWindowException = true; - resetWindow(false); - if(global::mainwindow::tabSwitcher::libraryWidgetSelected != true) { - ui->libraryButton->setStyleSheet("background: black; color: white"); - ui->libraryButton->setIcon(QIcon(":/resources/online-library-inverted.png")); - - // Create widget - libraryWidgetWindow = new libraryWidget(); - connect(libraryWidgetWindow, SIGNAL(destroyed(QObject*)), SLOT(resetFullWindow())); - libraryWidgetWindow->setAttribute(Qt::WA_DeleteOnClose); - ui->stackedWidget->insertWidget(3, libraryWidgetWindow); - global::mainwindow::tabSwitcher::libraryWidgetCreated = true; - - // Switch tab - ui->stackedWidget->setCurrentIndex(3); - global::mainwindow::tabSwitcher::libraryWidgetSelected = true; - - // Repaint - this->repaint(); - } -} - -void MainWindow::resetFullWindow() { - if(resetFullWindowException == false) { - resetWindow(true); - } - else { - resetFullWindowException = false; - } -} - -void MainWindow::checkForOtaUpdate() { - if(global::wifi::isConnected == true) { - QString lastSync = readFile("/external_root/opt/storage/update/last_sync"); - if(!lastSync.isEmpty()) { - unsigned long currentEpoch = QDateTime::currentSecsSinceEpoch(); - unsigned long syncEpoch = lastSync.toULong(); - unsigned long allowSyncEpoch = syncEpoch + 86400; - if(currentEpoch > allowSyncEpoch) { - launchOtaUpdater(); - } - } - else { - launchOtaUpdater(); - } - } -} - -void MainWindow::setupLocalLibraryWidget() { - localLibraryWidgetWindow = new localLibraryWidget(this); - QObject::connect(localLibraryWidgetWindow, &localLibraryWidget::openBookSignal, this, &MainWindow::openBookFile); - QObject::connect(localLibraryWidgetWindow, &localLibraryWidget::refreshScreen, this, &MainWindow::refreshScreen); - localLibraryWidgetWindow->setAttribute(Qt::WA_DeleteOnClose); - ui->homeStackedWidget->insertWidget(1, localLibraryWidgetWindow); - ui->homeStackedWidget->setCurrentIndex(1); -} - -void MainWindow::setupHomePageWidget() { - homePageWidgetWindow = new homePageWidget(this); - QObject::connect(homePageWidgetWindow, &homePageWidget::openBookSignal, this, &MainWindow::openBookFile); - QObject::connect(homePageWidgetWindow, &homePageWidget::refreshScreen, this, &MainWindow::refreshScreen); - QObject::connect(homePageWidgetWindow, &homePageWidget::relaunchHomePageWidget, this, &MainWindow::on_homeBtn_clicked); - homePageWidgetWindow->setAttribute(Qt::WA_DeleteOnClose); - ui->homeStackedWidget->insertWidget(2, homePageWidgetWindow); - ui->homeStackedWidget->setCurrentIndex(2); - global::mainwindow::tabSwitcher::homePageWidgetCreated = true; -} - -void MainWindow::on_audioBtn_clicked() -{ - QDialog* newAudioDialog = new audioDialog(this); - newAudioDialog->exec(); -} - -void MainWindow::openTelemetryDialog() { - log("Showing telemetry request dialog", className); - // Preventing a small race condition - global::usbms::usbmsDialog = false; - - global::telemetry::telemetryDialog = true; - - generalDialogWindow = new generalDialog(this); - QObject::connect(generalDialogWindow, &generalDialog::destroyed, this, &MainWindow::openTelemetryMessageDialog); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - QApplication::processEvents(); -} - -void MainWindow::openTelemetryMessageDialog() { - if(global::keyboard::telemetryMessageDialog == true) { - log("Showing telemetry message dialog", className); - global::keyboard::keyboardDialog = true; - global::keyboard::keyboardText = ""; - generalDialogWindow = new generalDialog(this); - QObject::connect(generalDialogWindow, &generalDialog::telemetryMessage, this, &MainWindow::sendDeviceInformationSlot); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - QApplication::processEvents(); - } -} - -void MainWindow::sendDeviceInformationSlot(QString message) { - telemetryInstance = new telemetry(this); - QObject::connect(telemetryInstance, &telemetry::showToast, this, &MainWindow::showToast); - telemetryInstance->message = message; -} diff --git a/src/main.cpp b/src/main.cpp index eba29f2..7457bac 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,263 +1,196 @@ /* - InkBox: Open-source Qt-based eBook reader - Copyright (C) 2021-2024 Nicolas Mailloux - SPDX-License-Identifier: GPL-3.0-only + InkBox: Open-source Qt-based eBook reader + Copyright (C) 2021-2024 Nicolas Mailloux + SPDX-License-Identifier: GPL-3.0-only - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see . + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ -#include "mainwindow.h" -#include "alert.h" -#include "generaldialog.h" -#include "functions.h" -#include "reader.h" -#include "encryptionmanager.h" -#include "sleepthread.h" -#include "sleepdialog.h" #include "audiothread.h" +#include "encryptionmanager.h" +#include "functions.h" +#include "generaldialog.h" +#include "mainwindow.h" +#include "reader.h" +#include "sleepdialog.h" +#include "sleepthread.h" +#include "splashAlert.h" +#include "ui.h" +#include "device.h" #include #include -#include #include #include #include +#include -int main(int argc, char *argv[]) -{ - QApplication a(argc, argv); - QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf8")); +int main(int argc, char *argv[]) { + QApplication a(argc, argv); + QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf8")); - if(char * debug = std::getenv("DEBUG")) { - if(std::atoi(debug) == 1) { - global::logger::status = true; - } - } + if (char *debug = std::getenv("DEBUG")) { + if (std::atoi(debug) == 1) { + global::logger::status = true; + } + } - global::deviceID = readFile("/opt/inkbox_device"); - log("Running on device " + global::deviceID, "main", true); + QString deviceID = readFile("/opt/inkbox_device"); + if (deviceID.isEmpty()) { + // we don't have a device id, assume that this is running in an emu + deviceID = "emu"; + } + log("Running on device " + deviceID, "main", true); + // initialize the platform singleton + Device::setup(deviceID); - // Tell the OS that we're currently running - writeFile("/tmp/inkbox_running", "true"); + // Tell the OS that we're currently running + writeFile("/tmp/inkbox_running", "true"); - setDefaultWorkDir(); - if(checkconfig("/run/wifi_able") == true) { - log("Device has Wi-Fi capabilities", "main"); - global::device::isWifiAble = true; - } - else { - log("Device does not have Wi-Fi capabilities", "main"); - global::device::isWifiAble = false; - } + setDefaultWorkDir(); + if (Device::getSingleton()->supportsWifi()) { + log("Device has Wi-Fi capabilities", "main"); + } else { + log("Device does not have Wi-Fi capabilities", "main"); + } - if(QFile::exists("/tmp/currentlyRunningUserApplication")) { - QFile::remove("/tmp/currentlyRunningUserApplication"); - } + if (QFile::exists("/tmp/currentlyRunningUserApplication")) { + QFile::remove("/tmp/currentlyRunningUserApplication"); + } - if(QFile::exists("/tmp/rescan_userapps")) { - QFile::remove("/tmp/rescan_userapps"); - log("Re-scanning user applications from explicit request", "main"); - writeFile("/opt/ibxd", "gui_apps_stop\n"); - while(true) { - if(QFile::exists("/tmp/gui_apps_stopped")) { - QFile::remove("/tmp/gui_apps_stopped"); - break; - } - QThread::msleep(500); - } - writeFile("/opt/ibxd", "gui_apps_start\n"); - while(true) { - if(QFile::exists("/tmp/gui_apps_started")) { - if(checkconfig("/tmp/gui_apps_started") == true) { - log("GUI apps service started successfully", "main"); - QFile::remove("/tmp/gui_apps_started"); - updateUserAppsMainJsonFile(); - break; - } - else { - log("GUI apps service failed to start", "main"); - QFile::remove("/tmp/gui_apps_started"); - break; - } - } - QThread::msleep(500); - } - updateUserAppsMainJsonFile(); - } + if (QFile::exists("/tmp/rescan_userapps")) { + QFile::remove("/tmp/rescan_userapps"); + log("Re-scanning user applications from explicit request", "main"); + writeFile("/opt/ibxd", "gui_apps_stop\n"); + while (true) { + if (QFile::exists("/tmp/gui_apps_stopped")) { + QFile::remove("/tmp/gui_apps_stopped"); + break; + } + QThread::msleep(500); + } + writeFile("/opt/ibxd", "gui_apps_start\n"); + while (true) { + if (QFile::exists("/tmp/gui_apps_started")) { + if (checkconfig("/tmp/gui_apps_started") == true) { + log("GUI apps service started successfully", "main"); + QFile::remove("/tmp/gui_apps_started"); + updateUserAppsMainJsonFile(); + break; + } else { + log("GUI apps service failed to start", "main"); + QFile::remove("/tmp/gui_apps_started"); + break; + } + } + QThread::msleep(500); + } + updateUserAppsMainJsonFile(); + } - // Power daemon-related stuff - sleepDialog * sleepDialogWindow = new sleepDialog; - // https://wiki.qt.io/QThreads_general_usage - QThread * IPDThread = new QThread(); - sleepThread * sleepThreadWindow = new sleepThread(); - sleepThreadWindow->moveToThread(IPDThread); - QObject::connect(IPDThread, &QThread::started, sleepThreadWindow, &sleepThread::start); - QObject::connect(sleepThreadWindow, &sleepThread::startDialog, sleepDialogWindow, &sleepDialog::launchSleepDialog); - QObject::connect(sleepThreadWindow, &sleepThread::stopDialog, sleepDialogWindow, &sleepDialog::hideSleepDialog); - IPDThread->start(); + // Power daemon-related stuff + SleepDialog *sleepDialogWindow = new SleepDialog; + // https://wiki.qt.io/QThreads_general_usage + QThread *IPDThread = new QThread(); + SleepThread *sleepThreadWindow = new SleepThread(); + sleepThreadWindow->moveToThread(IPDThread); + QObject::connect(IPDThread, &QThread::started, sleepThreadWindow, &SleepThread::start); + QObject::connect(sleepThreadWindow, &SleepThread::startDialog, sleepDialogWindow, &SleepDialog::launchSleepDialog); + QObject::connect(sleepThreadWindow, &SleepThread::stopDialog, sleepDialogWindow, &SleepDialog::hideSleepDialog); + IPDThread->start(); - // Audio stuff - if(checkconfig(".config/e-2-audio/enabled") == true) { - log("Audio is enabled", "main"); - global::audio::enabled = true; - QThread * audioThread = new QThread(); - audiothread * audioObject = new audiothread(); - audioObject->moveToThread(audioThread); - QObject::connect(audioThread, &QThread::started, audioObject, &audiothread::start); - audioThread->start(); - } - else { - log("Audio is disabled", "main"); - } + // Audio stuff + if (checkconfig(".config/e-2-audio/enabled") == true) { + log("Audio is enabled", "main"); + global::audio::enabled = true; + QThread *audioThread = new QThread(); + AudioThread *audioObject = new AudioThread(); + audioObject->moveToThread(audioThread); + QObject::connect(audioThread, &QThread::started, audioObject, &AudioThread::start); + audioThread->start(); + } else { + log("Audio is disabled", "main"); + } - if(checkconfig(".config/18-encrypted_storage/status") == true and checkconfig("/external_root/run/encfs_mounted") == false) { - // Open Encryption Manager to unlock encrypted storage - encryptionManager w; - const QScreen * screen = qApp->primaryScreen(); - w.setGeometry(QRect(QPoint(0,0), screen->geometry().size())); - w.show(); - return a.exec(); - } - else if(checkconfig("/external_root/run/encfs_mounted") == true and checkconfig("/external_root/run/encfs_repack") == true) { - log("Launching encryptionManager", "main"); - encryptionManager w; - const QScreen * screen = qApp->primaryScreen(); - w.setGeometry(QRect(QPoint(0,0), screen->geometry().size())); - w.show(); - return a.exec(); - } - else { - // Variables - global::reader::startBatteryWatchdog = false; - global::reader::startUsbmsPrompt = false; + if (checkconfig(".config/18-encrypted_storage/status") == true and checkconfig("/external_root/run/encfs_mounted") == false) { + // Open Encryption Manager to unlock encrypted storage + CryptoManagerWidget w; + const QScreen *screen = qApp->primaryScreen(); + w.setGeometry(QRect(QPoint(0, 0), screen->geometry().size())); + w.show(); + return a.exec(); + } else if (checkconfig("/external_root/run/encfs_mounted") == true and checkconfig("/external_root/run/encfs_repack") == true) { + log("Launching encryptionManager", "main"); + CryptoManagerWidget w; + const QScreen *screen = qApp->primaryScreen(); + w.setGeometry(QRect(QPoint(0, 0), screen->geometry().size())); + w.show(); + return a.exec(); + } else { + // Variables + global::reader::startBatteryWatchdog = false; + global::reader::startUsbmsPrompt = false; - // Checking if battery level is critical; if true (and if it is not charging), then display a "Please charge your eReader" splash and power off. - if(global::deviceID != "emu\n") { - if(isBatteryCritical() == true) { - if(!isUsbPluggedIn()) { - global::battery::showCriticalBatteryAlert = true; - alert w; + // Checking if battery level is critical; if true (and if it is not charging), then display a "Please charge your eReader" splash and power off. + if (Device::getSingleton()->getBatteryLevel() <= 5) { + if (!Device::getSingleton()->isUSBPluggedIn()) { + global::battery::showCriticalBatteryAlert = true; + SplashAlertWidget w; - const QScreen * screen = qApp->primaryScreen(); - w.setGeometry(QRect(QPoint(0,0), screen->geometry().size())); - w.show(); - return a.exec(); - } - } - } + const QScreen *screen = qApp->primaryScreen(); + w.setGeometry(QRect(QPoint(0, 0), screen->geometry().size())); + w.show(); + return a.exec(); + } + } - // Checking if there has been an ALERT flag set up, and if there is, show a big warning - if(checkconfig("/external_root/boot/flags/ALERT") == true) { - alert w; + // Checking if there has been an ALERT flag set up, and if there is, show a big warning + if (checkconfig("/external_root/boot/flags/ALERT") == true) { + SplashAlertWidget w; - const QScreen * screen = qApp->primaryScreen(); - w.setGeometry(QRect(QPoint(0,0), screen->geometry().size())); - w.show(); - return a.exec(); - } - // If we're waking from sleep and we have the lockscreen enabled, we'll "resume" the book from scratch - else if(checkconfig("/tmp/suspendBook") == true && checkconfig("/inkbox/bookIsEpub") == false) { - // Start the low/critical battery alert timer from the Reader framework since MainWindow is not going to be shown - global::runningInstanceIsReaderOnly = true; - global::reader::startBatteryWatchdog = true; - global::reader::startUsbmsPrompt = true; - global::reader::skipOpenDialog = true; + const QScreen *screen = qApp->primaryScreen(); + w.setGeometry(QRect(QPoint(0, 0), screen->geometry().size())); + w.show(); + return a.exec(); + } + // If we're waking from sleep and we have the lockscreen enabled, we'll "resume" the book from scratch + else if (checkconfig("/tmp/suspendBook") == true && checkconfig("/inkbox/bookIsEpub") == false) { + // Start the low/critical battery alert timer from the Reader framework since MainWindow is not going to be shown + global::runningInstanceIsReaderOnly = true; + global::reader::startBatteryWatchdog = true; + global::reader::startUsbmsPrompt = true; + global::reader::skipOpenDialog = true; - writeFile("/inkbox/skip_opendialog", "true"); - if(global::deviceID == "n705\n") { - global::isN705 = true; - } - else if(global::deviceID == "n905\n") { - global::isN905C = true; - } - else if(global::deviceID == "n613\n") { - global::isN613 = true; - } - else if(global::deviceID == "n873\n") { - global::isN873 = true; - } - else if(global::deviceID == "n236\n") { - global::isN236 = true; - } - else if(global::deviceID == "n437\n") { - global::isN437 = true; - } - else if(global::deviceID == "n306\n") { - global::isN306 = true; - } - else if(global::deviceID == "n249\n") { - global::isN249 = true; - } - else if(global::deviceID == "kt\n") { - global::isKT = true; - } - else { - ; - } + writeFile("/inkbox/skip_opendialog", "true"); - reader w; + ReaderWidget w; - const QScreen* screen = qApp->primaryScreen(); - w.setGeometry(QRect(QPoint(0,0), screen->geometry().size())); - w.show(); - return a.exec(); + const QScreen *screen = qApp->primaryScreen(); + w.setGeometry(QRect(QPoint(0, 0), screen->geometry().size())); + w.show(); + return a.exec(); - } - else { - QProcess::execute("remount_tmpfs_launch.sh", QStringList()); + } else { + QProcess::execute("remount_tmpfs_launch.sh", QStringList()); - MainWindow w; + MainWindow w; - QApplication::setStyle("windows"); - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - w.setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); + QApplication::setStyle("windows"); + UI::applyStyle(w, "eink"); - if(global::deviceID == "n705\n") { - global::isN705 = true; - } - else if(global::deviceID == "n905\n") { - global::isN905C = true; - } - else if(global::deviceID == "n613\n") { - global::isN613 = true; - } - else if(global::deviceID == "n873\n") { - global::isN873 = true; - } - else if(global::deviceID == "n236\n") { - global::isN236 = true; - } - else if(global::deviceID == "n437\n") { - global::isN437 = true; - } - else if(global::deviceID == "n306\n") { - global::isN306 = true; - } - else if(global::deviceID == "n249\n") { - global::isN249 = true; - } - else if(global::deviceID == "kt\n") { - global::isKT = true; - } - else { - ; - } - - const QScreen * screen = qApp->primaryScreen(); - w.setGeometry(QRect(QPoint(0,0), screen->geometry().size())); - w.show(); - return a.exec(); - } - } + const QScreen *screen = qApp->primaryScreen(); + w.setGeometry(QRect(QPoint(0, 0), screen->geometry().size())); + w.show(); + return a.exec(); + } + } } diff --git a/src/platform/device.cpp b/src/platform/device.cpp new file mode 100644 index 0000000..9cb1210 --- /dev/null +++ b/src/platform/device.cpp @@ -0,0 +1,239 @@ +#include "device.h" +#include "functions.h" + +#include + +#include "device_desktop.h" +#include "device_kindle_touch.h" +#include "device_kobo_aura_edition2.h" +#include "device_kobo_clarahd.h" +#include "device_kobo_glo.h" +#include "device_kobo_glohd.h" +#include "device_kobo_libra.h" +#include "device_kobo_mini.h" +#include "device_kobo_nia.h" +#include "device_kobo_touch.h" + + +Device* Device::instance = nullptr; + +Device::Device() +{ + powerSupplyPath = getPowerSupplyPath(); +} + +Device* Device::getSingleton() { + return instance; +} + + + + +void Device::setup(QString &platformName){ + QString name = platformName.trimmed(); + Device* temp; + +#define SETUP_DEVICE(x) { \ + temp = new x(); \ + if(temp->getID() == name) { \ + Device::instance = temp;\ + log("Setting up Device "+Device::instance->getID()+".", "Device::setup"); \ + return; \ + } else { \ + delete temp; \ + } \ +} + + SETUP_DEVICE(DeviceKindleTouch) + + SETUP_DEVICE(DeviceKoboAuraEdition2) + SETUP_DEVICE(DeviceKoboClaraHD) + SETUP_DEVICE(DeviceKoboGlo) + SETUP_DEVICE(DeviceKoboGloHD) + SETUP_DEVICE(DeviceKoboLibra) + SETUP_DEVICE(DeviceKoboMini) + SETUP_DEVICE(DeviceKoboNia) + SETUP_DEVICE(DeviceKoboTouch) + + // Fallback if none of the devices above worked + Device::instance = new DeviceDesktop(); + + log("Setting up Device "+Device::instance->getID()+".", "Device::setup"); + fprintf(stderr, "Device has fallen back to desktop.\n"); +} + +void Device::writeFile(QString path, QString content) { + QFile file(path); + if(file.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text)) { + QTextStream stream(&file); + stream << content; + } else { + fprintf(stderr, ("Failed to write to file: ")); + } +} + +QString Device::readFile(QString path) { + QFile file(path); + file.open(QIODevice::ReadOnly); + QTextStream in (&file); + QString content = in.readAll(); + file.close(); + + return content.trimmed(); +} + +QString Device::getPowerSupplyPath() { + // get the path to the battery so we can check the charge latter + QString result; + QDirIterator supplies("/sys/class/power_supply", QDirIterator::NoIteratorFlags); + while(supplies.hasNext()) { + QString supply = supplies.filePath(); + + // Badly-classified device by some ntx kernels, ignore + if (supplies.fileName() == "mc13892_charger") { + continue; + } + + if(QFile::exists(supply + "/type")) { + QString content = readFile(supply + "/type"); + if(content == "Battery"){ + result = supply; + break; + } + + } + + supplies.next(); + } + return result; +} + + +const QString Device::getStyleSheetPath() { + return "/mnt/onboard/.adds/inkbox/"; +} + +Device::SysInfo Device::getSystemInfo() { + // get UID + QString prog ("dd"); + QStringList args; + args << "if=/dev/mmcblk0" << "bs=512" << "skip=1" << "count=1" << "status=none"; + QProcess *proc = new QProcess(); + proc->start(prog, args); + proc->waitForFinished(); + + QString deviceUID = proc->readAllStandardOutput(); + deviceUID = deviceUID.left(256); + proc->deleteLater(); + + // get Kernel Version + prog = "uname"; + args = QStringList(); + args << "-r"; + proc = new QProcess(); + proc->start(prog, args); + proc->waitForFinished(); + + QString kernelVersion = proc->readAllStandardOutput(); + kernelVersion = kernelVersion.trimmed(); + + proc->deleteLater(); + + setDefaultWorkDir(); + writeFile("/external_root/run/initrd-fifo", "get_kernel_build_id\n"); + QThread::msleep(100); + writeFile("/external_root/run/initrd-fifo", "get_kernel_commit\n"); + QThread::msleep(100); + + QString kernelBuildID = readFile("/external_root/run/kernel_build_id").trimmed(); + + QString kernelCommit = readFile("/external_root/run/kernel_commit").trimmed(); + + + SysInfo info = { + .uid= deviceUID, + .kernelVersion= kernelVersion, + .kernelBuild= kernelBuildID, + .kernelCommit= kernelCommit, + + .inkOSVersion= readFile("/external_root/opt/isa/version"), + .inkGitVersion = GIT_VERSION, + + .ipAddress = getConnectionInformation() + }; + + return info; +} + + +bool Device::supportsWifi() { + return checkconfig("/run/wifi_able"); +} + +int Device::getBatteryLevel() { + int value = 100; + if(QFile::exists("/sys/devices/platform/pmic_battery.1/power_supply/mc13892_bat/capacity")) { + value = readFile("/sys/devices/platform/pmic_battery.1/power_supply/mc13892_bat/capacity").toInt(); + } else if(QFile::exists(powerSupplyPath + "/capacity")) { + value = readFile(powerSupplyPath + "/capacity").toInt(); + } + + return value; +} + +int Device::getBrightness() { + if(QFile::exists("/var/run/brightness")) { + return readFile("/var/run/brightness").toInt(); + } + else { + return 0; + } +} + +void Device::setBrightness(int value) { + if(QFile::exists("/var/run/brightness")) { + std::ofstream fhandler; + fhandler.open("/var/run/brightness"); + fhandler << value; + fhandler.close(); + } else if(QFile::exists("/var/run/brightness_write")) { + // this is for N249 devices. Overwrite this virtual method for that platform instead + std::ofstream fhandler; + fhandler.open("/var/run/brightness_write"); + fhandler << value; + fhandler.close(); + } +} + +bool Device::supportsNightmode() { + return true; +} + +int Device::getBaseDPI() { + return 125; +} + +bool Device::isUSBPluggedIn() { + // Thanks to https://github.com/koreader/KoboUSBMS/blob/2efdf9d920c68752b2933f21c664dc1afb28fc2e/usbms.c#L148-L158 + int ntxfd; + if((ntxfd = open("/dev/ntx_io", O_RDWR)) == -1) { + fprintf(stderr, "Error opening ntx_io device\n"); + return false; + } + unsigned long ptr = 0U; + ioctl(ntxfd, 108, &ptr); + close(ntxfd); + return !!ptr; +} + +void Device::loadUSBMassStorageModule() { + +} + +QString Device::getUSBMassStorageModule() { + return "/external_root/lib/modules/g_mass_storage.ko"; +} + +QString Device::getNetworkInterfaceName() { + return "wlan0"; +} diff --git a/src/platform/device.h b/src/platform/device.h new file mode 100644 index 0000000..5fc998b --- /dev/null +++ b/src/platform/device.h @@ -0,0 +1,130 @@ +#ifndef PLATFORM_H +#define PLATFORM_H + +#include + +class Device +{ +private: + static Device* instance; + QString powerSupplyPath; + + QString getPowerSupplyPath(); + +protected: + Device(); + + void writeFile(QString path, QString content); + QString readFile(QString path); + +public: + virtual ~Device() = default; + + static void setup(QString& platformName); + /* + + if(global::deviceID == "n705\n") { + global::isN705 = true; + } + else if(global::deviceID == "n905\n") { + global::isN905C = true; + } + else if(global::deviceID == "n613\n") { + global::isN613 = true; + } + else if(global::deviceID == "n873\n") { + global::isN873 = true; + } + else if(global::deviceID == "n236\n") { + global::isN236 = true; + } + else if(global::deviceID == "n437\n") { + global::isN437 = true; + } + else if(global::deviceID == "n306\n") { + global::isN306 = true; + } + ^else if(global::deviceID == "n249\n") { + global::isN249 = true; + } + else if(global::deviceID == "kt\n") { + global::isKT = true; + } + else { + ; + } + +*/ + + static Device* getSingleton(); + + virtual QString getID() = 0; + + struct SysInfo { + QString uid; + + QString kernelVersion; + QString kernelBuild; + QString kernelCommit; + + QString inkOSVersion; + QString inkGitVersion; + + QString ipAddress; + }; + virtual SysInfo getSystemInfo(); + + virtual bool hasNavButtons() = 0; + + virtual bool supportsWifi() = 0; + + // BATTERY stuff + + virtual bool hasBattery() = 0; + virtual int getBatteryLevel(); + // Generic Battery Utility functions + bool isBatteryCritical() { + return getBatteryLevel() < 5; + } + bool isBatteryLow() { + return getBatteryLevel() < 15; + } + + // only true for isN249 and isN873 + virtual bool supportsWarmLight() = 0; + // 100 for N249 and 10 for N873 + virtual int getMaxWarmLightValue() = 0; + virtual int getWarmth() = 0; + virtual void setWarmth(int value) = 0; + + virtual bool supportsBrightness()=0; + + virtual int getBrightness(); + virtual void setBrightness(int value); + + virtual bool supportsNightmode(); + + virtual int getBaseDPI(); + + enum ScreenSize { + SMALL, // Kobo Mini (705) + MEDIUM, + LARGE, // Kobo Glo HD (437), 249 + VERY_LARGE // Kobo Libra (873) + }; + virtual ScreenSize getScreenSize() = 0; + + // USB Mass Storage Stuff + virtual bool isUSBPluggedIn(); + virtual void loadUSBMassStorageModule(); + virtual QString getUSBMassStorageModule(); + + // NETWORK + virtual QString getNetworkInterfaceName(); + + // PATHS + virtual const QString getStyleSheetPath(); + +}; + +#endif // PLATFORM_H diff --git a/src/platform/device_desktop.cpp b/src/platform/device_desktop.cpp new file mode 100644 index 0000000..13db22e --- /dev/null +++ b/src/platform/device_desktop.cpp @@ -0,0 +1,6 @@ +#include "device_desktop.h" + +DeviceDesktop::DeviceDesktop() +{ + +} diff --git a/src/platform/device_desktop.h b/src/platform/device_desktop.h new file mode 100644 index 0000000..1c5ecc7 --- /dev/null +++ b/src/platform/device_desktop.h @@ -0,0 +1,53 @@ +#ifndef DEVICEDESKTOP_H +#define DEVICEDESKTOP_H + +#include "device.h" + +class DeviceDesktop : public Device +{ +public: + DeviceDesktop(); + + virtual QString getID() override { + return "desktop"; + } + + virtual bool hasNavButtons() override { + return false; + } + + virtual bool supportsWifi() override { + return true; + } + + // BATTERY + virtual bool hasBattery() override { + return true; + } + + // SCREEN + // WARM LIGHT + virtual bool supportsWarmLight() override { + return false; + }; + virtual int getMaxWarmLightValue() override { + return 0; + }; + virtual int getWarmth() override {return 0;}; + virtual void setWarmth(int value) override {}; + + // BRIGHTNESS + virtual bool supportsBrightness() override { + return true; + }; + + // SIZE + virtual int getBaseDPI() override { + return 125; + } + virtual ScreenSize getScreenSize() override { + return ScreenSize::VERY_LARGE; + } +}; + +#endif // DEVICEDESKTOP_H diff --git a/src/platform/device_kindle_touch.cpp b/src/platform/device_kindle_touch.cpp new file mode 100644 index 0000000..121c38e --- /dev/null +++ b/src/platform/device_kindle_touch.cpp @@ -0,0 +1,29 @@ +#include "device_kindle_touch.h" + +#include +#include + +DeviceKindleTouch::DeviceKindleTouch() +{ + +} + +int DeviceKindleTouch::getBatteryLevel() { + if(QFile::exists("/sys/devices/system/yoshi_battery/yoshi_battery0/battery_capacity")) { + return readFile("/sys/devices/system/yoshi_battery/yoshi_battery0/battery_capacity").toInt(); + + } + return 100; +} + +bool DeviceKindleTouch::isUSBPluggedIn() { + return readFile("/sys/devices/system/yoshi_battery/yoshi_battery0/battery_status").toInt() == 1; +} + +void DeviceKindleTouch::loadUSBMassStorageModule() { + QProcess::execute("insmod", QStringList() << "/external_root/lib/modules/2.6.35-inkbox/kernel/drivers/usb/gadget/arcotg_udc.ko"); +} + +QString DeviceKindleTouch::getUSBMassStorageModule() { + return "/external_root/lib/modules/2.6.35-inkbox/kernel/drivers/usb/gadget/g_file_storage.ko"; +} diff --git a/src/platform/device_kindle_touch.h b/src/platform/device_kindle_touch.h new file mode 100644 index 0000000..01fdbc4 --- /dev/null +++ b/src/platform/device_kindle_touch.h @@ -0,0 +1,61 @@ +#ifndef DEVICEKINDLETOUCH_H +#define DEVICEKINDLETOUCH_H + +#include "device.h" + +class DeviceKindleTouch : public Device +{ +public: + DeviceKindleTouch(); + + virtual QString getID() override { + return "kt"; + } + + virtual bool hasNavButtons() override { + return false; + } + + virtual bool supportsWifi() override { + return true; + } + + // BATTERY + virtual bool hasBattery() override { + return true; + } + virtual int getBatteryLevel() override; + + + // SCREEN + // WARM LIGHT + virtual bool supportsWarmLight() override { + return false; + }; + virtual int getMaxWarmLightValue() override { + return 0; + }; + virtual int getWarmth() override {return 0;}; + virtual void setWarmth(int value) override {}; + + // BRIGHTNESS + virtual bool supportsBrightness() override { + return true; + }; + + // SIZE + virtual int getBaseDPI() override { + return 125; + } + virtual ScreenSize getScreenSize() override { + return ScreenSize::MEDIUM; + } + + // USB + virtual bool isUSBPluggedIn() override; + virtual void loadUSBMassStorageModule() override; + virtual QString getUSBMassStorageModule() override; + +}; + +#endif // DEVICEKINDLETOUCH_H diff --git a/src/platform/device_kobo_aura_edition2.cpp b/src/platform/device_kobo_aura_edition2.cpp new file mode 100644 index 0000000..e1ab82d --- /dev/null +++ b/src/platform/device_kobo_aura_edition2.cpp @@ -0,0 +1,6 @@ +#include "device_kobo_aura_edition2.h" + +DeviceKoboAuraEdition2::DeviceKoboAuraEdition2() +{ + +} diff --git a/src/platform/device_kobo_aura_edition2.h b/src/platform/device_kobo_aura_edition2.h new file mode 100644 index 0000000..5d22192 --- /dev/null +++ b/src/platform/device_kobo_aura_edition2.h @@ -0,0 +1,53 @@ +#ifndef KOBOAURAEDITION2_H +#define KOBOAURAEDITION2_H + +#include "device.h" + +class DeviceKoboAuraEdition2 : public Device +{ +public: + DeviceKoboAuraEdition2(); + + virtual QString getID() override { + return "n236"; + } + + virtual bool hasNavButtons() override { + return false; + } + + virtual bool supportsWifi() override { + return true; + } + + // BATTERY + virtual bool hasBattery() override { + return true; + } + + // SCREEN + // WARM LIGHT + virtual bool supportsWarmLight() override { + return false; + }; + virtual int getMaxWarmLightValue() override { + return 0; + }; + virtual int getWarmth() override {return 0;}; + virtual void setWarmth(int value) override {}; + + // BRIGHTNESS + virtual bool supportsBrightness() override { + return true; + }; + + // SIZE + virtual int getBaseDPI() override { + return 175; + } + virtual ScreenSize getScreenSize() override { + return ScreenSize::MEDIUM; + } +}; + +#endif // KOBOAURAEDITION2_H diff --git a/src/platform/device_kobo_clarahd.cpp b/src/platform/device_kobo_clarahd.cpp new file mode 100644 index 0000000..08fd2ae --- /dev/null +++ b/src/platform/device_kobo_clarahd.cpp @@ -0,0 +1,43 @@ +#include "device_kobo_clarahd.h" + +#include +#include + +DeviceKoboClaraHD::DeviceKoboClaraHD() +{ + +} + +int DeviceKoboClaraHD::getWarmth() { + QString sysfsWarmthPath = "/sys/class/backlight/backlight_warm/actual_brightness"; + int warmthValue; + + QString warmthConfig = readFile(sysfsWarmthPath); + warmthValue = warmthConfig.toInt(); + return warmthValue; +} + +void DeviceKoboClaraHD::setWarmth(int value) { + QString sysfsWarmthPath = "/sys/class/backlight/backlight_warm/brightness"; + QString warmthValueStr =QString::number(value); + + writeFile(sysfsWarmthPath, warmthValueStr); +} + +void DeviceKoboClaraHD::setBrightness(int value) { + if(QFile::exists("/var/run/brightness_write")) { + writeFile("/var/run/brightness_write", QString::number(value)); + } +} + + +//USB +bool DeviceKoboClaraHD::isUSBPluggedIn() { + return (readFile("/sys/class/power_supply/rn5t618-battery/status") != "Discharging\n"); +} + +void DeviceKoboClaraHD::loadUSBMassStorageModule() { + QProcess::execute("insmod", QStringList() << "/external_root/lib/modules/fs/configfs/configfs.ko"); + QProcess::execute("insmod", QStringList() << "/external_root/lib/modules/drivers/usb/gadget/libcomposite.ko"); + QProcess::execute("insmod", QStringList() << "/external_root/lib/modules/drivers/usb/gadget/function/usb_f_mass_storage.ko"); +} diff --git a/src/platform/device_kobo_clarahd.h b/src/platform/device_kobo_clarahd.h new file mode 100644 index 0000000..2a714ab --- /dev/null +++ b/src/platform/device_kobo_clarahd.h @@ -0,0 +1,63 @@ +#ifndef DEVICEKOBOCLARAHD_H +#define DEVICEKOBOCLARAHD_H + +#include "device.h" + +class DeviceKoboClaraHD : public Device +{ +public: + DeviceKoboClaraHD(); + + virtual QString getID() override { + return "n249"; + } + + virtual bool hasNavButtons() override { + return false; + } + + virtual bool supportsWifi() override { + return true; + } + + // BATTERY + virtual bool hasBattery() override { + return true; + } + + // SCREEN + // WARM LIGHT + virtual bool supportsWarmLight() override { + return true; + }; + virtual int getMaxWarmLightValue() override { + return 100; + }; + virtual int getWarmth() override; + virtual void setWarmth(int value) override; + + // BRIGHTNESS + virtual bool supportsBrightness() override { + return true; + }; + virtual void setBrightness(int value) override; + + // SIZE + virtual int getBaseDPI() override { + return 225; + } + virtual ScreenSize getScreenSize() override { + return ScreenSize::LARGE; + } + + //USB + virtual bool isUSBPluggedIn() override; + virtual void loadUSBMassStorageModule() override; + + // NETWORK + virtual QString getNetworkInterfaceName() override { + return "etho0"; + } +}; + +#endif // DEVICEKOBOCLARAHD_H diff --git a/src/platform/device_kobo_glo.cpp b/src/platform/device_kobo_glo.cpp new file mode 100644 index 0000000..438854d --- /dev/null +++ b/src/platform/device_kobo_glo.cpp @@ -0,0 +1,34 @@ +#include "device_kobo_glo.h" +#include +#include +#include +#include +#include + +#include +#include + +DeviceKoboGlo::DeviceKoboGlo() +{ + +} + +int DeviceKoboGlo::getBrightness() { + return readFile(".config/03-brightness/config").toInt(); +} + +void DeviceKoboGlo::setBrightness(int value) { + int fd; + if((fd = open("/dev/ntx_io", O_RDWR)) == -1) { + fprintf(stderr, "Error opening ntx_io device while setting brightness.\n"); + return; + } + ioctl(fd, 241, value); + close(fd); + + // also store it somewhere so we can load it when we need it for getBrightness + std::ofstream fhandler; + fhandler.open(".config/03-brightness/config"); + fhandler << value; + fhandler.close(); +} diff --git a/src/platform/device_kobo_glo.h b/src/platform/device_kobo_glo.h new file mode 100644 index 0000000..53879b3 --- /dev/null +++ b/src/platform/device_kobo_glo.h @@ -0,0 +1,56 @@ +#ifndef DEVICEKOBOGLO_H +#define DEVICEKOBOGLO_H + +#include "device.h" + +class DeviceKoboGlo : public Device +{ +public: + DeviceKoboGlo(); + + virtual QString getID() override { + return "n613"; + } + + virtual bool hasNavButtons() override { + return false; + } + + virtual bool supportsWifi() override { + return true; + } + + // BATTERY + virtual bool hasBattery() override { + return true; + } + + // SCREEN + // WARM LIGHT + virtual bool supportsWarmLight() override { + return false; + }; + virtual int getMaxWarmLightValue() override { + return 0; + }; + virtual int getWarmth() override {return 0;}; + virtual void setWarmth(int value) override {}; + + // BRIGHTNESS + virtual bool supportsBrightness() override { + return true; + }; + virtual int getBrightness() override; + virtual void setBrightness(int value) override; + + + // SIZE + virtual int getBaseDPI() override { + return 175; + }; + virtual ScreenSize getScreenSize() override { + return ScreenSize::MEDIUM; + } +}; + +#endif // DEVICEKOBOGLO_H diff --git a/src/platform/device_kobo_glohd.cpp b/src/platform/device_kobo_glohd.cpp new file mode 100644 index 0000000..01de26b --- /dev/null +++ b/src/platform/device_kobo_glohd.cpp @@ -0,0 +1,6 @@ +#include "device_kobo_glohd.h" + +DeviceKoboGloHD::DeviceKoboGloHD() +{ + +} diff --git a/src/platform/device_kobo_glohd.h b/src/platform/device_kobo_glohd.h new file mode 100644 index 0000000..8f3acf5 --- /dev/null +++ b/src/platform/device_kobo_glohd.h @@ -0,0 +1,58 @@ +#ifndef DEVICEKOBOGLOHD_H +#define DEVICEKOBOGLOHD_H + +#include "device.h" + +class DeviceKoboGloHD : public Device +{ +public: + DeviceKoboGloHD(); + + virtual QString getID() override { + return "n437"; + } + + virtual bool hasNavButtons() override { + return false; + } + + virtual bool supportsWifi() override { + return true; + } + + // BATTERY + virtual bool hasBattery() override { + return true; + } + + // SCREEN + // WARM LIGHT + virtual bool supportsWarmLight() override { + return false; + }; + virtual int getMaxWarmLightValue() override { + return 0; + }; + virtual int getWarmth() override {return 0;}; + virtual void setWarmth(int value) override {}; + + // BRIGHTNESS + virtual bool supportsBrightness() override { + return true; + }; + + // SIZE + virtual int getBaseDPI() override { + return 225; + } + virtual ScreenSize getScreenSize() override { + return ScreenSize::LARGE; + } + + //NETWORK + virtual QString getNetworkInterfaceName() override { + return "eth0"; + } +}; + +#endif // DEVICEKOBOGLOHD_H diff --git a/src/platform/device_kobo_libra.cpp b/src/platform/device_kobo_libra.cpp new file mode 100644 index 0000000..fb5c674 --- /dev/null +++ b/src/platform/device_kobo_libra.cpp @@ -0,0 +1,35 @@ +#include "device_kobo_libra.h" +#include + +DeviceKoboLibra::DeviceKoboLibra() +{ + +} + +int DeviceKoboLibra::getWarmth() { + QString sysfsWarmthPath = "/sys/class/backlight/lm3630a_led/color"; + int warmthValue; + QString warmthConfig = readFile(sysfsWarmthPath); + warmthValue = warmthConfig.toInt(); + warmthValue = 10 - warmthValue; + + return warmthValue; +} + +void DeviceKoboLibra::setWarmth(int value) { + QString sysfsWarmthPath; + QString warmthValueStr; + // Value 0 gives a warmer lighting than value 10 + value = 10 - value; + warmthValueStr = QString::number(value); + sysfsWarmthPath = "/sys/class/backlight/lm3630a_led/color"; + + writeFile(sysfsWarmthPath, warmthValueStr); +} + +void DeviceKoboLibra::loadUSBMassStorageModule() { + QProcess::execute("insmod", QStringList() << "/external_root/lib/modules/fs/configfs/configfs.ko"); + QProcess::execute("insmod", QStringList() << "/external_root/lib/modules/drivers/usb/gadget/libcomposite.ko"); + QProcess::execute("insmod", QStringList() << "/external_root/lib/modules/drivers/usb/gadget/function/usb_f_mass_storage.ko"); + +} diff --git a/src/platform/device_kobo_libra.h b/src/platform/device_kobo_libra.h new file mode 100644 index 0000000..5c366df --- /dev/null +++ b/src/platform/device_kobo_libra.h @@ -0,0 +1,56 @@ +#ifndef DEVICEKOBOLIBRA_H +#define DEVICEKOBOLIBRA_H + +#include "device.h" + +class DeviceKoboLibra : public Device +{ +public: + DeviceKoboLibra(); + + virtual QString getID() override { + return "n873"; + } + + virtual bool hasNavButtons() override { + return true; + } + + virtual bool supportsWifi() override { + return true; + } + + // BATTERY + virtual bool hasBattery() override { + return true; + } + + // SCREEN + // WARM LIGHT + virtual bool supportsWarmLight() override { + return true; + }; + virtual int getMaxWarmLightValue() override { + return 10; + }; + virtual int getWarmth() override; + virtual void setWarmth(int value) override; + + // BRIGHTNESS + virtual bool supportsBrightness() override { + return true; + }; + + // SIZE + virtual int getBaseDPI() override { + return 250; + } + virtual ScreenSize getScreenSize() override { + return ScreenSize::VERY_LARGE; + } + + //USB + virtual void loadUSBMassStorageModule() override; +}; + +#endif // DEVICEKOBOLIBRA_H diff --git a/src/platform/device_kobo_mini.cpp b/src/platform/device_kobo_mini.cpp new file mode 100644 index 0000000..dce9aa2 --- /dev/null +++ b/src/platform/device_kobo_mini.cpp @@ -0,0 +1,13 @@ +#include "device_kobo_mini.h" + +#include +#include +#include + + +DeviceKoboMini::DeviceKoboMini() +{ + +} + + diff --git a/src/platform/device_kobo_mini.h b/src/platform/device_kobo_mini.h new file mode 100644 index 0000000..cda8dd7 --- /dev/null +++ b/src/platform/device_kobo_mini.h @@ -0,0 +1,50 @@ +#ifndef DEVICEKOBOMINI_H +#define DEVICEKOBOMINI_H + +#include "device.h" + +class DeviceKoboMini : public Device +{ +public: + DeviceKoboMini(); + + virtual QString getID() override { + return "n705"; + } + + virtual bool hasNavButtons() override { + return false; + } + + virtual bool supportsWifi() override { + return true; + } + + // BATTERY + virtual bool hasBattery() override { + return true; + } + + // SCREEN + // WARM LIGHT + virtual bool supportsWarmLight() override { + return false; + }; + virtual int getMaxWarmLightValue() override { + return 0; + }; + virtual int getWarmth() override {return 0;}; + virtual void setWarmth(int value) override {}; + + // BRIGHTNESS + virtual bool supportsBrightness() override { + return true; + }; + + // SIZE + virtual ScreenSize getScreenSize() override { + return ScreenSize::SMALL; + } +}; + +#endif // DEVICEKOBOMINI_H diff --git a/src/platform/device_kobo_nia.cpp b/src/platform/device_kobo_nia.cpp new file mode 100644 index 0000000..865521a --- /dev/null +++ b/src/platform/device_kobo_nia.cpp @@ -0,0 +1,16 @@ +#include "device_kobo_nia.h" + +#include + +DeviceKoboNia::DeviceKoboNia() +{ + +} + + +void DeviceKoboNia::loadUSBMassStorageModule() { + QProcess::execute("insmod", QStringList() << "/external_root/lib/modules/fs/configfs/configfs.ko"); + QProcess::execute("insmod", QStringList() << "/external_root/lib/modules/drivers/usb/gadget/libcomposite.ko"); + QProcess::execute("insmod", QStringList() << "/external_root/lib/modules/drivers/usb/gadget/function/usb_f_mass_storage.ko"); + +} diff --git a/src/platform/device_kobo_nia.h b/src/platform/device_kobo_nia.h new file mode 100644 index 0000000..b6f05be --- /dev/null +++ b/src/platform/device_kobo_nia.h @@ -0,0 +1,56 @@ +#ifndef DEVICEKOBONIA_H +#define DEVICEKOBONIA_H + +#include "device.h" + +class DeviceKoboNia : public Device +{ +public: + DeviceKoboNia(); + + virtual QString getID() override { + return "n306"; + } + + virtual bool hasNavButtons() override { + return false; + } + + virtual bool supportsWifi() override { + return true; + } + + // BATTERY + virtual bool hasBattery() override { + return true; + } + + // SCREEN + // WARM LIGHT + virtual bool supportsWarmLight() override { + return false; + }; + virtual int getMaxWarmLightValue() override { + return 0; + }; + virtual int getWarmth() override {return 0;}; + virtual void setWarmth(int value) override {}; + + // BRIGHTNESS + virtual bool supportsBrightness() override { + return true; + }; + + // SIZE + virtual int getBaseDPI() override { + return 175; + } + virtual ScreenSize getScreenSize() override { + return ScreenSize::MEDIUM; + } + + //USB + virtual void loadUSBMassStorageModule() override; +}; + +#endif // DEVICEKOBONIA_H diff --git a/src/platform/device_kobo_touch.cpp b/src/platform/device_kobo_touch.cpp new file mode 100644 index 0000000..2a6ddfc --- /dev/null +++ b/src/platform/device_kobo_touch.cpp @@ -0,0 +1,6 @@ +#include "device_kobo_touch.h" + +DeviceKoboTouch::DeviceKoboTouch() +{ + +} diff --git a/src/platform/device_kobo_touch.h b/src/platform/device_kobo_touch.h new file mode 100644 index 0000000..9e39467 --- /dev/null +++ b/src/platform/device_kobo_touch.h @@ -0,0 +1,53 @@ +#ifndef DEVICEKOBOTOUCH_H +#define DEVICEKOBOTOUCH_H + +#include "device.h" + +class DeviceKoboTouch : public Device +{ +public: + DeviceKoboTouch(); + + + + virtual QString getID() override { + return "n905"; + } + + virtual bool hasNavButtons() override { + return false; + } + + virtual bool supportsWifi() override { + return true; + } + + // BATTERY + virtual bool hasBattery() override { + return true; + } + + // SCREEN + // WARM LIGHT + virtual bool supportsWarmLight() override { + return false; + }; + virtual int getMaxWarmLightValue() override { + return 0; + }; + virtual int getWarmth() override {return 0;}; + virtual void setWarmth(int value) override {}; + + // BRIGHTNESS + virtual bool supportsBrightness() override { + return true; + }; + + // SIZE + virtual ScreenSize getScreenSize() override { + return ScreenSize::MEDIUM; + } + +}; + +#endif // DEVICEKOBOTOUCH_H diff --git a/src/powerDaemon/sleepthread.cpp b/src/powerDaemon/sleepthread.cpp index 3891718..65c19f1 100644 --- a/src/powerDaemon/sleepthread.cpp +++ b/src/powerDaemon/sleepthread.cpp @@ -3,9 +3,9 @@ #include -sleepThread::sleepThread() {} +SleepThread::SleepThread() {} -void sleepThread::start() +void SleepThread::start() { log("Sleep pipe thread active", className); QDir pipeDirPath = QDir("/dev/ipd"); diff --git a/src/powerDaemon/sleepthread.h b/src/powerDaemon/sleepthread.h index fb510f0..4e143af 100644 --- a/src/powerDaemon/sleepthread.h +++ b/src/powerDaemon/sleepthread.h @@ -3,11 +3,11 @@ #include -class sleepThread : public QObject { +class SleepThread : public QObject { Q_OBJECT public: QString className = this->metaObject()->className(); - sleepThread(); + SleepThread(); public slots: void start(); diff --git a/src/quit/quit.cpp b/src/quit/quit.cpp deleted file mode 100644 index c3306a0..0000000 --- a/src/quit/quit.cpp +++ /dev/null @@ -1,99 +0,0 @@ -#include "quit.h" -#include "ui_quit.h" -#include "functions.h" -#include -#include -#include -#include -#include -#include -#include - -quit::quit(QWidget *parent) : - QWidget(parent), - ui(new Ui::quit) -{ - ui->setupUi(this); - ui->backBtn->setFont(QFont("u001")); - - ui->pushButton->setProperty("type", "borderless"); - ui->pushButton_2->setProperty("type", "borderless"); - ui->pushButton_3->setProperty("type", "borderless"); - ui->pushButton_4->setProperty("type", "borderless"); - ui->backBtn->setProperty("type", "borderless"); - - // Stylesheet - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - // Getting the screen's size - float sW = QGuiApplication::screens()[0]->size().width(); - float sH = QGuiApplication::screens()[0]->size().height(); - // Defining what the "Quit" icon size will be - float stdIconWidth = sW / 1.25; - float stdIconHeight = sH / 1.25; - - QPixmap pixmap(":/resources/exit.png"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->label->setPixmap(scaledPixmap); - - if(checkconfig("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/9-deepSleep") == true) { - ui->pushButton_3->setText("Deep suspend"); - } -} - -quit::~quit() -{ - delete ui; -} - -void quit::on_pushButton_clicked() -{ - // Prevent strange "appearing from nowhere" low battery or critical battery alerts due to sysfs unmount - global::battery::showCriticalBatteryAlert = false; - global::battery::showLowBatteryDialog = false; - - // GUI apps - updateUserAppsMainJsonFile(); - - poweroff(true); - qApp->quit(); -} - -void quit::on_pushButton_2_clicked() -{ - global::battery::showCriticalBatteryAlert = false; - global::battery::showLowBatteryDialog = false; - - // GUI apps - updateUserAppsMainJsonFile(); - - reboot(true); - qApp->quit(); -} - -void quit::on_pushButton_4_clicked() -{ - log("Restarting InkBox", className); - QProcess process; - process.startDetached("inkbox", QStringList()); - qApp->quit(); -} - -void quit::on_backBtn_clicked() -{ - quit::close(); -} - -void quit::on_pushButton_3_clicked() -{ - log("Suspending", className); - if(checkconfig("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/9-deepSleep") == true) { - writeFile("/dev/ipd/sleepCall", "deepSleep"); - } - else { - writeFile("/dev/ipd/sleepCall", "sleep"); - } -} diff --git a/src/reader/reader.cpp b/src/reader/reader.cpp deleted file mode 100644 index a1371e3..0000000 --- a/src/reader/reader.cpp +++ /dev/null @@ -1,2258 +0,0 @@ -#include "reader.h" -#include "ui_reader.h" -#include "functions.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; - -reader::reader(QWidget *parent) : - QWidget(parent), - ui(new Ui::reader) -{ - // Elements - graphicsScene = new QGraphicsScene(this); - - // Variables - global::battery::showLowBatteryDialog = true; - global::battery::showCriticalBatteryAlert = true; - global::reader::highlightAlreadyDone = false; - if(global::reader::bookIsEpub == true) { - is_epub = true; - } - mupdf::convertRelativeValues = false; - wordwidgetLock = false; - textDialogLock = false; - goToSavedPageDone = false; - initialPdfRotationDone = false; - global::reader::textAlignment = 0; - global::reader::lineSpacing = 0; - global::reader::font = "Source Serif Pro"; - global::reader::fontSize = 10; - global::reader::margins = 1; - global::reader::currentViewportText = ""; - - ui->setupUi(this); - ui->fontLabel->setFont(QFont("u001")); - ui->sizeLabel->setFont(QFont("u001")); - ui->sizeValueLabel->setFont(QFont("Inter")); - ui->lineSpacingLabel->setFont(QFont("u001")); - ui->lineSpacingValueLabel->setFont(QFont("Inter")); - ui->marginsLabel->setFont(QFont("u001")); - ui->marginsValueLabel->setFont(QFont("Inter")); - ui->alignmentLabel->setFont(QFont("u001")); - ui->fontChooser->setFont(QFont("u001")); - ui->definitionStatusLabel->setFont(QFont("u001")); - ui->pageProgressBar->setFont(QFont("u001")); - - ui->previousBtn->setProperty("type", "borderless"); - ui->nextBtn->setProperty("type", "borderless"); - ui->optionsBtn->setProperty("type", "borderless"); - ui->homeBtn->setProperty("type", "borderless"); - ui->brightnessBtn->setProperty("type", "borderless"); - ui->alignLeftBtn->setProperty("type", "borderless"); - ui->alignRightBtn->setProperty("type", "borderless"); - ui->alignCenterBtn->setProperty("type", "borderless"); - ui->alignLeftBtn->setProperty("type", "borderless"); - ui->alignJustifyBtn->setProperty("type", "borderless"); - ui->infoCloseBtn->setProperty("type", "borderless"); - ui->saveWordBtn->setProperty("type", "borderless"); - ui->previousDefinitionBtn->setProperty("type", "borderless"); - ui->nextDefinitionBtn->setProperty("type", "borderless"); - ui->nightModeBtn->setProperty("type", "borderless"); - ui->searchBtn->setProperty("type", "borderless"); - ui->gotoBtn->setProperty("type", "borderless"); - ui->increaseScaleBtn->setProperty("type", "borderless"); - ui->decreaseScaleBtn->setProperty("type", "borderless"); - ui->quitBtn->setProperty("type", "borderless"); - ui->viewHighlightsBtn->setProperty("type", "borderless"); - - // Icons - ui->alignLeftBtn->setText(""); - ui->alignLeftBtn->setIcon(QIcon(":/resources/align-left.png")); - ui->alignRightBtn->setText(""); - ui->alignRightBtn->setIcon(QIcon(":/resources/align-right.png")); - ui->alignCenterBtn->setText(""); - ui->alignCenterBtn->setIcon(QIcon(":/resources/align-center.png")); - ui->alignJustifyBtn->setText(""); - ui->alignJustifyBtn->setIcon(QIcon(":/resources/align-justify.png")); - ui->infoCloseBtn->setText(""); - ui->infoCloseBtn->setIcon(QIcon(":/resources/close.png")); - ui->saveWordBtn->setText(""); - ui->saveWordBtn->setIcon(QIcon(":/resources/star.png")); - ui->previousDefinitionBtn->setText(""); - ui->previousDefinitionBtn->setIcon(QIcon(":/resources/chevron-left.png")); - ui->nextDefinitionBtn->setText(""); - ui->nextDefinitionBtn->setIcon(QIcon(":/resources/chevron-right.png")); - ui->homeBtn->setText(""); - ui->homeBtn->setIcon(QIcon(":/resources/home.png")); - ui->brightnessBtn->setText(""); - ui->brightnessBtn->setIcon(QIcon(":/resources/frontlight.png")); - ui->searchBtn->setText(""); - ui->searchBtn->setIcon(QIcon(":/resources/search.png")); - ui->increaseScaleBtn->setText(""); - ui->increaseScaleBtn->setIcon(QIcon(":/resources/zoom-in.png")); - ui->decreaseScaleBtn->setText(""); - ui->decreaseScaleBtn->setIcon(QIcon(":/resources/zoom-out.png")); - ui->quitBtn->setText(""); - ui->quitBtn->setIcon(QIcon(":/resources/power.png")); - ui->previousBtn->setText(""); - ui->previousBtn->setIcon(QIcon(":/resources/arrow-left.png")); - ui->optionsBtn->setText(""); - ui->optionsBtn->setIcon(QIcon(":/resources/settings.png")); - ui->nextBtn->setText(""); - ui->nextBtn->setIcon(QIcon(":/resources/arrow-right.png")); - ui->viewHighlightsBtn->setText(""); - ui->viewHighlightsBtn->setIcon(QIcon(":/resources/view-highlights.png")); - - // Style misc. - ui->bookInfoLabel->setStyleSheet("font-style: italic"); - - // Making text selectable - ui->text->setTextInteractionFlags(Qt::TextSelectableByMouse); - - // Font misc. - int id = QFontDatabase::addApplicationFont(":/resources/fonts/CrimsonPro-Italic.ttf"); - QString family = QFontDatabase::applicationFontFamilies(id).at(0); - QFont crimson(family); - - // Stylesheet + misc. - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - // We have to get the file's path - if(global::reader::skipOpenDialog == true) { - if(checkconfig("/tmp/suspendBook") == true) { - wakeFromSleep = true; - // Prevent from opening the Reader framework next time unless the condition is reset - writeFile("/tmp/suspendBook", "false"); - book_file = "/inkbox/book/book.txt"; - } - else if(global::reader::bookFile.isEmpty() == false) { - book_file = global::reader::bookFile; - global::reader::bookFile = ""; - } - } - else { - if(checkconfig("/opt/inkbox_genuine") == true) { - if(checkconfig("/external_root/run/encfs_mounted") == true) { - QDir::setCurrent("/mnt/onboard/onboard/encfs-decrypted"); - } - else { - QDir::setCurrent("/mnt/onboard/onboard"); - } - QFileDialog *dialog = new QFileDialog(this); - // https://forum.qt.io/topic/29471/solve-how-to-show-qfiledialog-at-center-position-screen/4 - QDesktopWidget desk; - QRect screenres = desk.screenGeometry(0); dialog->setGeometry(QRect(screenres.width()/4,screenres.height() /4,screenres.width()/2,screenres.height()/2)); - stylesheetFile.open(QFile::ReadOnly); - dialog->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - book_file = dialog->getOpenFileName(dialog, tr("Open File"), QDir::currentPath()); - - if(!book_file.isEmpty()) { - setDefaultWorkDir(); - } - else { - // User clicked "Cancel" button - // Restarting InkBox - setDefaultWorkDir(); - QProcess process; - process.startDetached("inkbox", QStringList()); - qApp->quit(); - } - } - else { - if(checkconfig("/external_root/run/encfs_mounted") == true) { - QDir::setCurrent("/mnt/onboard/onboard/encfs-decrypted"); - } - else { - QDir::setCurrent("/mnt/onboard/onboard"); - } - QDir::setCurrent("/mnt/onboard"); - QFileDialog *dialog = new QFileDialog(this); - // https://forum.qt.io/topic/29471/solve-how-to-show-qfiledialog-at-center-position-screen/4 - QDesktopWidget desk; - QRect screenres = desk.screenGeometry(0); dialog->setGeometry(QRect(screenres.width()/4,screenres.height() /4,screenres.width()/2,screenres.height()/2)); - stylesheetFile.open(QFile::ReadOnly); - dialog->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - book_file = dialog->getOpenFileName(dialog, tr("Open File"), QDir::currentPath()); - - if(!book_file.isEmpty()) { - setDefaultWorkDir(); - } - else { - // User clicked "Cancel" button - // Restarting InkBox - setDefaultWorkDir(); - QProcess process; - process.startDetached("inkbox", QStringList()); - qApp->quit(); - } - } - } - log("Opening file '" + book_file + "'", className); - - // Writing book path to file - writeFile("/tmp/inkboxBookPath", book_file); - - // Calling InkBox daemon (ibxd) via FIFO interface to run bookconfig_mount - if(!book_file.isEmpty()) { - if(checkconfig(".config/16-global_reading_settings/config") == false) { - global::reader::globalReadingSettings = false; - writeFile("/opt/ibxd", "bookconfig_mount\n"); - // Callback handler to wait until bookconfig_mount has finished execution - while(true) { - if(QFile::exists("/inkbox/bookConfigSetUp")) { - QFile::remove("/inkbox/bookConfigSetUp"); - setupLocalSettingsEnvironment(); - break; - } - } - } - else { - global::reader::globalReadingSettings = true; - } - } - - // Custom settings - // Brightness - QTimer::singleShot(0, this, SLOT(setCinematicBrightnessWarmthSlot())); - // Font - global::reader::font = readFile(".config/04-book/font"); - if(global::reader::font == "u001") { - ui->fontChooser->setCurrentText("Univers (u001)"); - } - else { - ui->fontChooser->setCurrentText(global::reader::font); - } - // Night mode - if(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n437\n" or global::deviceID == "n306\n") { - if(checkconfig(".config/10-dark_mode/config") == true) { - log("Setting night mode to ON", className); - writeFile("/tmp/invertScreen", "y"); - ui->nightModeBtn->setText(""); - ui->nightModeBtn->setIcon(QIcon(":/resources/nightmode-full.png")); - isNightModeActive = true; - } - else { - log("Setting night mode to OFF", className); - writeFile("/tmp/invertScreen", "n"); - ui->nightModeBtn->setText(""); - ui->nightModeBtn->setIcon(QIcon(":/resources/nightmode-empty.png")); - isNightModeActive = false; - } - } - else { - log("Night mode disabled by software", className); - ui->line_7->hide(); - ui->line_7->deleteLater(); - ui->nightModeBtn->hide(); - ui->nightModeBtn->deleteLater(); - } - - if(global::deviceID == "n873\n") { - ui->nextBtn->setStyleSheet("padding: 13.5px"); - ui->previousBtn->setStyleSheet("padding: 13.5px"); - ui->optionsBtn->setStyleSheet("padding: 13.5px"); - } - else if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { - ui->nextBtn->setStyleSheet("padding: 12.5px"); - ui->previousBtn->setStyleSheet("padding: 12.5px"); - ui->optionsBtn->setStyleSheet("padding: 12.5px"); - } - else { - ui->nextBtn->setStyleSheet("padding: 10px"); - ui->previousBtn->setStyleSheet("padding: 10px"); - ui->optionsBtn->setStyleSheet("padding: 10px"); - } - ui->sizeValueLabel->setStyleSheet("font-size: 9pt; font-weight: bold"); - ui->lineSpacingValueLabel->setStyleSheet("font-size: 9pt; font-weight: bold"); - ui->marginsValueLabel->setStyleSheet("font-size: 9pt; font-weight: bold"); - ui->homeBtn->setStyleSheet("font-size: 9pt; padding: 5px"); - ui->brightnessBtn->setStyleSheet("font-size: 9pt; padding: 5px"); - ui->fontChooser->setStyleSheet("font-size: 9pt"); - ui->gotoBtn->setStyleSheet("font-size: 9pt; padding: 9px; font-weight: bold; background: lightGrey"); - ui->pageNumberLabel->setFont(QFont("Source Serif Pro")); - ui->viewHighlightsBtn->setStyleSheet("padding: 9px"); - - // Hiding the menubar + definition widget + brightness button + buttons bar widget - ui->menuWidget->setVisible(false); - if(!(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "kt\n")) { - ui->brightnessBtn->setVisible(true); - ui->line_15->setVisible(true); - } - else { - ui->brightnessBtn->setVisible(false); - ui->brightnessBtn->deleteLater(); - ui->line_15->setVisible(false); - ui->line_15->deleteLater(); - } - ui->menuBarWidget->setVisible(false); - ui->buttonsBarWidget->setVisible(false); - ui->pdfScaleWidget->setVisible(false); - ui->wordWidget->setVisible(false); - if(checkconfig(".config/11-menubar/sticky") == true) { - ui->menuWidget->setVisible(true); - ui->statusBarWidget->setVisible(true); - } - else { - ui->menuWidget->setVisible(false); - ui->statusBarWidget->setVisible(false); - } - ui->pageWidget->hide(); - if(pdf_file_match(book_file) == true) { - ui->line_4->setLineWidth(2); - } - - // Topbar widget / book info - ui->topbarStackedWidget->setVisible(true); - showTopbarWidget = true; - ui->bookInfoLabel->setFont(crimson); - - // Defining pixmaps - // Getting the screen's size - float sW = QGuiApplication::screens()[0]->size().width(); - float sH = QGuiApplication::screens()[0]->size().height(); - // Defining what the icons' size will be - if(checkconfig("/opt/inkbox_genuine") == true) { - float stdIconWidth; - float stdIconHeight; - if(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n437\n" or global::deviceID == "n306\n" or global::deviceID == "n249\n" or global::deviceID == "kt\n" or global::deviceID == "emu\n") { - stdIconWidth = sW / 16; - stdIconHeight = sW / 16; - } - else { - stdIconWidth = sW / 19; - stdIconHeight = sH / 19; - } - QPixmap chargingPixmap(":/resources/battery_charging.png"); - scaledChargingPixmap = chargingPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - QPixmap fullPixmap(":/resources/battery_full.png"); - scaledFullPixmap = fullPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - QPixmap halfPixmap(":/resources/battery_half.png"); - scaledHalfPixmap = halfPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - QPixmap emptyPixmap(":/resources/battery_empty.png"); - scaledEmptyPixmap = emptyPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - } - else { - float stdIconWidth = sW / 19; - float stdIconHeight = sH / 19; - QPixmap chargingPixmap(":/resources/battery_charging.png"); - scaledChargingPixmap = chargingPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - QPixmap fullPixmap(":/resources/battery_full.png"); - scaledFullPixmap = fullPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - QPixmap halfPixmap(":/resources/battery_half.png"); - scaledHalfPixmap = halfPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - QPixmap emptyPixmap(":/resources/battery_empty.png"); - scaledEmptyPixmap = emptyPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - } - - // Checking if there is a page refresh setting set - if(readFile(".config/04-book/refresh").isEmpty()) { - // Writing the default, refresh every 3 pages - writeFile(".config/04-book/refresh", "3"); - } - pageRefreshSetting = readFile(".config/04-book/refresh").toInt(); - // Checking if that config option was set to "Never refresh"... - if(pageRefreshSetting == -1) { - log("Setting page refresh to 'disabled'", className); - neverRefresh = true; - } - else { - log("Setting page refresh to each " + QString::number(pageRefreshSetting) + " pages", className); - // Safety measure - neverRefresh = false; - } - - // Clock setting to show seconds + battery level - if(checkconfig(".config/02-clock/config") == true) { - QTimer *t = new QTimer(this); - t->setInterval(500); - connect(t, &QTimer::timeout, [&]() { - QString time = QTime::currentTime().toString("hh:mm:ss"); - getBatteryLevel(); - ui->batteryLabel->setText(batteryLevel); - ui->timeLabel->setText(time); - } ); - t->start(); - } - else { - QTimer *t = new QTimer(this); - t->setInterval(500); - connect(t, &QTimer::timeout, [&]() { - QString time = QTime::currentTime().toString("hh:mm"); - getBatteryLevel(); - ui->batteryLabel->setText(batteryLevel); - ui->timeLabel->setText(time); - } ); - t->start(); - } - - // Checking if we're waking from sleep and have lockscreen enabled; if so, do nothing there because the book should already have been parsed - if(wakeFromSleep != true) { - // Remount tmpfs - writeFile("/inkbox/remount", "true"); - - // Counting number of parsed files - split_total = setup_book(book_file, 0, true); - split_files_number = split_total; - split_total = split_total - 1; - - writeconfig_pagenumber(false); - } - else { - // Retrieve split_total from tmpfs - split_total = readFile("/tmp/inkboxPageNumber").toInt(); - setup_book(book_file, 0, true); - } - - // Get text; no need to do it multiple times for ePUB books - if(is_epub == false && is_pdf == false && is_image == false) { - setDefaultWorkDir(); - if(global::reader::globalReadingSettings == false) { - QString splitTotalPageNumber = readFile(".config/A-page_number/config"); - if(!splitTotalPageNumber.isEmpty()) { - split_total = splitTotalPageNumber.toInt(); - } - } - setup_book(book_file, split_total, true); - } - - // Display text - // If needed, show scroll bar when rendering engine isn't doing its job properly - if(checkconfig(".config/14-reader_scrollbar/config") == true) { - ui->text->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - ui->text->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - } - else { - ui->text->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - ui->text->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - } - - // Line spacing, margins and text alignment - QString lineSpacingString = readFile(".config/04-book/line_spacing"); - if(!lineSpacingString.isEmpty()) { - global::reader::lineSpacing = lineSpacingString.toInt(); - } - - QString marginsString = readFile(".config/04-book/margins"); - if(!marginsString.isEmpty()) { - global::reader::margins = marginsString.toInt(); - } - - QString alignment = readFile(".config/04-book/alignment"); - if(alignment == "Left") { - global::reader::textAlignment = 0; - } - else if(alignment == "Center") { - global::reader::textAlignment = 1; - } - else if(alignment == "Right") { - global::reader::textAlignment = 2; - } - else if(alignment == "Justify") { - global::reader::textAlignment = 3; - } - else { - alignment = "Left"; - global::reader::textAlignment = 0; - } - log("Setting text alignment to '" + alignment + "'", className); - - // Don't ask me why it doesn't work without that QTimer - QTimer::singleShot(0, this, SLOT(setInitialTextProperties())); - - // Wheeee! - if(is_epub == true) { - ui->graphicsView->hide(); - ui->graphicsView->deleteLater(); - ui->text->setText(epubPageContent); - global::reader::currentViewportText = ui->text->toHtml(); - } - else if(is_pdf == true) { - ui->text->hide(); - ui->text->deleteLater(); - ui->line_20->hide(); - ui->line_20->deleteLater(); - ui->viewHighlightsBtn->hide(); - ui->viewHighlightsBtn->deleteLater(); - setupPng(); - } - else if(is_image == true) { - ui->text->hide(); - ui->text->deleteLater(); - ui->line_20->hide(); - ui->line_20->deleteLater(); - ui->viewHighlightsBtn->hide(); - ui->viewHighlightsBtn->deleteLater(); - setupPng(); - } - else { - ui->graphicsView->hide(); - ui->graphicsView->deleteLater(); - global::reader::currentViewportText = ui->text->toHtml(); - ui->text->setText(ittext); - } - - // Topbar info widget - if(is_epub == true) { - QString bookCreator = findEpubMetadata(book_file, "creator"); - QString bookTitle = findEpubMetadata(book_file, "title"); - bookCreator = bookCreator.trimmed(); - bookTitle = bookTitle.trimmed(); - - QString infoLabelContent = bookCreator; - infoLabelContent.append(" ― "); - infoLabelContent.append(bookTitle); - int infoLabelLength = infoLabelContent.length(); - int infoLabelDefinedLength; - if(global::deviceID == "n705\n") { - infoLabelDefinedLength = 35; - } - else if(global::deviceID == "n905\n" or global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n437\n" or global::deviceID == "n306\n" or global::deviceID == "n249\n" or global::deviceID == "kt\n" or global::deviceID == "emu\n") { - infoLabelDefinedLength = 50; - } - else { - infoLabelDefinedLength = 50; - } - - if(infoLabelLength <= infoLabelDefinedLength) { - ui->bookInfoLabel->setWordWrap(false); - } - else { - ui->bookInfoLabel->setWordWrap(true); - } - ui->bookInfoLabel->setText(infoLabelContent); - } - else { - QString bookReadRelativePath; - if(wakeFromSleep == true) { - bookReadRelativePath = readFile("/tmp/inkboxBookPath").split("/").last(); - } - else { - bookReadRelativePath = book_file.split("/").last(); - } - - int infoLabelDefinedLength; - if(global::deviceID == "n705\n") { - infoLabelDefinedLength = 35; - } - else if(global::deviceID == "n905\n" or global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n437\n" or global::deviceID == "n306\n" or global::deviceID == "n249\n" or global::deviceID == "kt\n" or global::deviceID == "emu\n") { - infoLabelDefinedLength = 50; - } - else { - infoLabelDefinedLength = 50; - } - - if(bookReadRelativePath <= infoLabelDefinedLength) { - ui->bookInfoLabel->setWordWrap(false); - } - else { - ui->bookInfoLabel->setWordWrap(true); - } - ui->bookInfoLabel->setText(bookReadRelativePath); - } - - // Clean up - writeFile("/inkbox/remount", "true"); - - // Way to tell shell scripts that we're in the Reader framework - writeFile("/tmp/inkboxReading", "true"); - - // Maintain a 'Recent books' list - QJsonObject recentBooksObject; - if(QFile::exists(global::localLibrary::recentBooksDatabasePath)) { - log("Reading recent books database", className); - QFile recentBooksDatabase(global::localLibrary::recentBooksDatabasePath); - QByteArray recentBooksData; - if(recentBooksDatabase.open(QIODevice::ReadOnly)) { - recentBooksData = recentBooksDatabase.readAll(); - recentBooksDatabase.close(); - } - else { - QString function = __func__; log(function + ": Failed to open recent books database file for reading at '" + recentBooksDatabase.fileName() + "'", className); - } - QJsonObject mainJsonObject = QJsonDocument::fromJson(qUncompress(QByteArray::fromBase64(recentBooksData))).object(); - for(int i = 1; i <= global::homePageWidget::recentBooksNumber; i++) { - QString objectName = "Book" + QString::number(i); - QJsonObject jsonObject = mainJsonObject[objectName].toObject(); - if(i == 1) { - if(jsonObject.value("BookPath").toString() != book_file) { - // Circular buffer - for(int i = global::homePageWidget::recentBooksNumber; i >= 2; i--) { - mainJsonObject["Book" + QString::number(i)] = mainJsonObject["Book" + QString::number(i - 1)]; - } - jsonObject.insert("BookPath", QJsonValue(book_file)); - mainJsonObject[objectName] = jsonObject; - } - } - } - recentBooksObject = mainJsonObject; - } - else { - QJsonObject mainJsonObject; - QJsonObject firstJsonObject; - firstJsonObject.insert("BookPath", QJsonValue(book_file)); - mainJsonObject["Book1"] = firstJsonObject; - - for(int i = 2; i <= global::homePageWidget::recentBooksNumber; i++) { - QJsonObject jsonObject; - jsonObject.insert("BookPath", QJsonValue("")); - mainJsonObject["Book" + QString::number(i)] = jsonObject; - } - recentBooksObject = mainJsonObject; - } - QFile::remove(global::localLibrary::recentBooksDatabasePath); - writeFile(global::localLibrary::recentBooksDatabasePath, qCompress(QJsonDocument(recentBooksObject).toJson()).toBase64()); - - // USB mass storage prompt - if(global::reader::startUsbmsPrompt == true) { - QTimer *usbmsPrompt = new QTimer(this); - usbmsPrompt->setInterval(500); - connect(usbmsPrompt, &QTimer::timeout, [&]() { - if(checkconfig("/opt/inkbox_genuine") == true) { - if(global::usbms::showUsbmsDialog != true) { - if(isUsbPluggedIn() != usbmsStatus) { - global::usbms::showUsbmsDialog = true; - } - } - else { - usbmsStatus = isUsbPluggedIn(); - if(usbmsStatus == false) { - // Loop again... - ; - } - else { - // An USB cable is connected! - openUsbmsDialog(); - } - } - } - else { - // Do nothing, we're running along with Nickel & friends... - ; - } - } ); - usbmsPrompt->start(); - } - - // Battery watchdog - if(global::reader::startBatteryWatchdog == true) { - QTimer *t = new QTimer(this); - t->setInterval(2000); - connect(t, &QTimer::timeout, [&]() { - // Checking if battery level is low - if(global::battery::showCriticalBatteryAlert != true) { - ; - } - else { - if(isBatteryCritical() == true) { - log("Warning! Battery is at a critical charge level!", className); - openCriticalBatteryAlertWindow(); - } - } - - if(global::battery::showLowBatteryDialog != true) { - // Do nothing, since a dialog should already have been displayed and (probably) dismissed - ; - } - else { - if(isBatteryLow() == true) { - if(global::battery::batteryAlertLock == true) { - ; - } - else { - if(isUsbPluggedIn()) { - ; - } - else { - log("Warning! Battery is low!", className); - openLowBatteryDialog(); - } - } - } - } - } ); - if(global::deviceID != "emu\n") { - t->start(); - } - } - - // Pages number info label - if(is_pdf == true) { - getTotalPdfPagesNumber(); - } - // The total pages number is already known for ePUBs at this point - setupPageWidget(); - - // Reading settings auto-save timer - if(global::reader::globalReadingSettings == false) { - QTimer * saveSettingsTimer = new QTimer(this); - saveSettingsTimer->setInterval(900000); // 15 minutes - connect(saveSettingsTimer, SIGNAL(timeout()), this, SLOT(saveReadingSettings())); - saveSettingsTimer->start(); - } -} - -reader::~reader() -{ - delete ui; -} - -int reader::setup_book(QString book, int i, bool run_parser) { - // Parse eBook - if(remount == true) { - QString mount_prog ("sh"); - QStringList mount_args; - mount_args << "split.sh"; - QProcess * mount_proc = new QProcess(); - mount_proc->start(mount_prog, mount_args); - mount_proc->waitForFinished(); - mount_proc->deleteLater(); - remount = false; - } - else { - writeFile("/inkbox/remount", "false"); - QString mount_prog ("sh"); - QStringList mount_args; - mount_args << "split.sh"; - QProcess * mount_proc = new QProcess(); - mount_proc->start(mount_prog, mount_args); - mount_proc->waitForFinished(); - mount_proc->deleteLater(); - } - - if(filematch_ran == false) { - if(epub_file_match(book) == true) { - QFile::remove("/run/book.epub"); - QFile::copy(book, "/run/book.epub"); - - getTotalEpubPagesNumber(); - - filematch_ran = true; - is_epub = true; - } - else if(pdf_file_match(book) == true) { - getPdfOrientation(book); - QString pdfProg("/usr/local/bin/mutool"); - QStringList pdfArgs; - convertMuPdfVars(1, true); - pdfArgs << "convert" << "-F" << "png" << "-O" << "width=" + mupdf::pdf::width_qstr + ",height=" + mupdf::pdf::height_qstr << "-o" << "/run/page.png" << book_file << mupdf::pdf::pdfPageNumber_qstr; - QProcess * pdfProc = new QProcess(); - pdfProc->start(pdfProg, pdfArgs); - pdfProc->waitForFinished(); - pdfProc->deleteLater(); - - filematch_ran = true; - is_pdf = true; - } - else if(image_file_match(book) == true) { - ui->previousBtn->hide(); - ui->nextBtn->hide(); - ui->line->hide(); - ui->line_3->hide(); - ui->previousBtn->deleteLater(); - ui->nextBtn->deleteLater(); - ui->line->deleteLater(); - ui->line_3->deleteLater(); - - writeFile("/tmp/inkboxImagePath", book); - writeFile("/opt/ibxd", "inkbox_convert_image\n"); - - while(true) { - if(QFile::exists("/inkbox/convertImageDone")) { - if(checkconfig("/inkbox/convertImageDone") == true) { - filematch_ran = true; - is_image = true; - break; - } - else { - showToast("Failed to display image"); - break; - } - QFile::remove("/inkbox/convertImageDone"); - } - } - - filematch_ran = true; - is_image = true; - } - else { - // This is likely not an ePUB, a PDF or a picture. - // Copying book specified in the function call - QFile::copy(book, "/inkbox/book/book.txt"); - - filematch_ran = true; - is_epub = false; - } - } - - // Checking whether or not the user has defined an option for the number of words per page; if not, then setting the default. - // NOTE: This is only for plain text files. - setDefaultWorkDir(); - if(readFile(".config/07-words_number/config").isEmpty()) { - writeFile(".config/07-words_number/config", "100"); - } - QString wordsNumberConfig = readFile(".config/07-words_number/config"); - - // Parsing file - if(is_epub == true) { - if(run_parser == true) { - if(filematch_ran == true) { - QString epubProg ("sh"); - QStringList epubArgs; - convertMuPdfVars(0, false); - epubArgs << "/mnt/onboard/.adds/inkbox/epub.sh" << "0" << "0" << "0" << mupdf::epub::epubPageNumber_qstr; - QProcess * epubProc = new QProcess(); - epubProc->start(epubProg, epubArgs); - epubProc->waitForFinished(); - epubProc->deleteLater(); - } - } - } - else if(is_pdf == true) { - if(run_parser == true) { - if(filematch_ran == true) { - QString pdfProg("/usr/local/bin/mutool"); - QStringList pdfArgs; - convertMuPdfVars(1, true); - pdfArgs << "convert" << "-F" << "png" << "-O" << "width=" + mupdf::pdf::width_qstr + ",height=" + mupdf::pdf::height_qstr << "-o" << "/run/page.png" << book_file << mupdf::pdf::pdfPageNumber_qstr; - QProcess * pdfProc = new QProcess(); - pdfProc->start(pdfProg, pdfArgs); - pdfProc->waitForFinished(); - pdfProc->deleteLater(); - } - } - } - else if(is_image == true) { - // Do nothing, since images won't have pages - ; - } - else { - QString parse_prog ("/mnt/onboard/.adds/inkbox/system/bin/split-txt"); - QStringList parse_args; - parse_args << wordsNumberConfig; - QProcess * parse_proc = new QProcess(); - parse_proc->start(parse_prog, parse_args); - parse_proc->waitForFinished(); - parse_proc->deleteLater(); - } - - // Reading files - if(is_epub == false && is_pdf == false && is_image == false) { - if(run_parser == true) { - QDirIterator it("/inkbox/book/split"); - while (it.hasNext()) { - QFile f(it.next()); - f.open(QIODevice::ReadOnly); - content << f.readAll(); - f.close(); - } - // These characters are replaced for consistency with ePUB text handling, highlighting and text alignment. - content[i].replace("\n", "
"); - content[i].replace("\t", "    "); - ittext = content[i]; - return content.size(); - } - else { - content[i].replace("\n", "
"); - content[i].replace("\t", "    "); - ittext = content[i]; - } - } - else { - QFile epubPage("/inkbox/book/page"); - epubPage.open(QIODevice::ReadOnly); - QTextStream in(&epubPage); - epubPageContent = in.readAll(); - epubPage.close(); - } - return 0; -} - -void reader::checkwords() { - QFile words_list(".config/06-words/config"); - words_list.open(QIODevice::ReadWrite); - QTextStream in (&words_list); - words = in.readAll(); - words_list.close(); -} - -bool reader::epub_file_match(QString file) { - QString fileExt = file.right(4); - - if(fileExt == "epub" or fileExt == "EPUB") { - log("Book file format: ePUB", className); - writeFile("/inkbox/bookIsEpub", "true"); - return true; - } - else { - writeFile("/inkbox/bookIsEpub", "false"); - return false; - } -} - -void reader::dictionary_lookup(string word, QString first_letter, int position) { - log("Dictionary lookup requested for word '" + QString::fromStdString(word) + "', position " + QString::number(position), className); - ofstream fhandler; - fhandler.open("/inkbox/dictionary/word"); - fhandler << word; - fhandler.close(); - - QDir::setCurrent("dictionary"); - QDir::setCurrent(first_letter); - QString lookup_prog ("sh"); - QStringList lookup_args; - QString position_str = QString::number(position); - lookup_args << "../scripts/lookup.sh" << position_str; - QProcess * lookup_proc = new QProcess(); - lookup_proc->start(lookup_prog, lookup_args); - lookup_proc->waitForFinished(); - lookup_proc->deleteLater(); - - QFile definition_file("/inkbox/dictionary/definition"); - definition_file.open(QIODevice::ReadWrite); - QTextStream in (&definition_file); - definition = in.readAll(); - definition = definition.remove(QRegExp("[\n]")); - if(definition == "No definition found.") { - nextdefinition_lock = true; - } - else { - nextdefinition_lock = false; - } - definition_file.close(); - - setDefaultWorkDir(); -} - -void reader::save_word(string word, bool remove) { - if(remove == false) { - QFile words(".config/06-words/config"); - words.open(QIODevice::ReadWrite); - QTextStream in (&words); - QString words_list = in.readAll(); - string words_list_str = words_list.toStdString(); - words.close(); - - log("Saving word '" + QString::fromStdString(word) + "' in Saved Words list", className); - ofstream fhandler; - fhandler.open(".config/06-words/config"); - fhandler << words_list_str << word << "\n"; - fhandler.close(); - } - else { - ofstream fhandler; - fhandler.open(".config/06-words/config"); - fhandler << word; - fhandler.close(); - } -} - -void reader::on_nextBtn_clicked() -{ - // ui->nextBtn->setEnabled(false); - if(is_epub == false and is_pdf == false) { - if(split_total - 1 == 1 or split_total - 1 == 0) { - showToast("You've reached the end of the document"); - } - else { - split_total = split_total - 1; - log("'Next' button clicked", className); - - setup_book(book_file, split_total, false); - ui->text->setText(""); - ui->text->setText(ittext); - global::reader::currentViewportText = ui->text->toHtml(); - - pagesTurned = pagesTurned + 1; - writeconfig_pagenumber(false); - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); - } - } - else if(is_epub == true) { - if(mupdf::epub::epubPageNumber + 1 > totalPagesInt) { - showToast("You've reached the end of the document"); - } - else { - mupdf::epub::epubPageNumber = mupdf::epub::epubPageNumber + 1; - log("'Next' button clicked: going to page " + QString::number(mupdf::epub::epubPageNumber), className); - setup_book(book_file, mupdf::epub::epubPageNumber, true); - ui->text->setText(""); - ui->text->setText(epubPageContent); - global::reader::currentViewportText = ui->text->toHtml(); - - pagesTurned = pagesTurned + 1; - writeconfig_pagenumber(false); - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); - } - } - else if(is_pdf == true) { - if(mupdf::pdf::pdfPageNumber + 1 > totalPagesInt) { - showToast("You've reached the end of the document"); - } - else { - mupdf::pdf::pdfPageNumber = mupdf::pdf::pdfPageNumber + 1; - log("'Next' button clicked: going to page " + QString::number(mupdf::pdf::pdfPageNumber), className); - if(ui->pdfScaleSlider->value() != 1) { - mupdf::convertRelativeValues = true; - } - setup_book(book_file, mupdf::pdf::pdfPageNumber, true); - setupPng(); - - pagesTurned = pagesTurned + 1; - writeconfig_pagenumber(false); - } - } - setupPageWidget(); - refreshScreen(); - // ui->nextBtn->setEnabled(true); -} - -void reader::on_previousBtn_clicked() -{ - // ui->previousBtn->setEnabled(false); - if(is_epub == false and is_pdf == false) { - // Making sure we won't encounter a "List index out of range" error ;) - if(split_total >= split_files_number - 1) { - showToast("No previous page"); - } - else { - split_total = split_total + 1; - log("'Previous' button clicked", className); - - setup_book(book_file, split_total, false); - ui->text->setText(""); - ui->text->setText(ittext); - global::reader::currentViewportText = ui->text->toHtml(); - - // We always increment pagesTurned regardless whether we press the Previous or Next button or not - pagesTurned = pagesTurned + 1; - writeconfig_pagenumber(false); - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); - } - } - else if (is_pdf == true) { - if(mupdf::pdf::pdfPageNumber - 1 <= 0) { - showToast("No previous page"); - } - else { - mupdf::pdf::pdfPageNumber = mupdf::pdf::pdfPageNumber - 1; - log("'Previous' button clicked: going to page " + QString::number(mupdf::pdf::pdfPageNumber), className); - if(ui->pdfScaleSlider->value() != 1) { - mupdf::convertRelativeValues = true; - } - setup_book(book_file, mupdf::pdf::pdfPageNumber, true); - setupPng(); - - // We always increment pagesTurned regardless whether we press the Previous or Next button or not - pagesTurned = pagesTurned + 1; - writeconfig_pagenumber(false); - } - } - else { - if(mupdf::epub::epubPageNumber - 1 <= 0) { - showToast("No previous page"); - } - else { - mupdf::epub::epubPageNumber = mupdf::epub::epubPageNumber - 1; - log("'Previous' button clicked: going to page " + QString::number(mupdf::epub::epubPageNumber), className); - setup_book(book_file, mupdf::epub::epubPageNumber, true); - ui->text->setText(""); - ui->text->setText(epubPageContent); - global::reader::currentViewportText = ui->text->toHtml(); - - // We always increment pagesTurned regardless whether we press the Previous or Next button or not - pagesTurned = pagesTurned + 1; - writeconfig_pagenumber(false); - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); - } - } - setupPageWidget(); - refreshScreen(); - // ui->previousBtn->setEnabled(true); -} - -void reader::refreshScreen() { - if(neverRefresh == true) { - // Do nothing; "Never refresh" was set - ; - } - else { - if(pagesTurned >= pageRefreshSetting) { - // Refreshing the screen - this->repaint(); - // Reset count - pagesTurned = 0; - } - } -} - -void reader::on_optionsBtn_clicked() -{ - log("'Options' button clicked", className); - if(menubar_shown == true) { - menubar_hide(); - if(global::deviceID == "n873\n") { - ui->optionsBtn->setStyleSheet("background: white; color: black; padding: 13.5px"); - } - else if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { - ui->optionsBtn->setStyleSheet("background: white; color: black; padding: 12.5px"); - } - else { - ui->optionsBtn->setStyleSheet("background: white; color: black; padding: 10px"); - } - ui->optionsBtn->setIcon(QIcon(":/resources/settings.png")); - // The Glo HD (N437) has a newer platform plugin that doesn't need this - if(global::deviceID != "n437\n" or global::deviceID != "n306\n" or global::deviceID != "n249\n") { - QTimer::singleShot(500, this, SLOT(repaint())); - } - menubar_shown = false; - } - else { - menubar_show(); - if(global::deviceID == "n873\n") { - ui->optionsBtn->setStyleSheet("background: black; color: white; padding: 13.5px"); - } - else if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { - ui->optionsBtn->setStyleSheet("background: black; color: white; padding: 12.5px"); - } - else { - ui->optionsBtn->setStyleSheet("background: black; color: white; padding: 10px"); - } - ui->optionsBtn->setIcon(QIcon(":/resources/settings-inverted.png")); - this->repaint(); - menubar_shown = true; - } -} - -void reader::on_homeBtn_clicked() -{ - log("Returning to Home screen", className); - // We're leaving reading mode - writeFile("/tmp/inkboxReading", "false"); - // Remount tmpfs - writeFile("/inkbox/remount", "true"); - // Specify cinematic brightness mode - writeFile("/tmp/inkbox-cinematicBrightness_auto", "true"); - - // Relaunching process - quit_restart(); -} - -void reader::on_fontChooser_currentIndexChanged(const QString &arg1) -{ - log("Setting font to '" + arg1 + "'", className); - global::reader::font = arg1; - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); -} - -void reader::on_alignLeftBtn_clicked() -{ - log("Setting text alignment to 'Left'", className); - global::reader::textAlignment = 0; - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); - writeFile(".config/04-book/alignment", "Left"); -} - -void reader::on_alignCenterBtn_clicked() -{ - log("Setting text alignment to 'Center'", className); - global::reader::textAlignment = 1; - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); - writeFile(".config/04-book/alignment", "Center"); -} - -void reader::on_alignRightBtn_clicked() -{ - log("Setting text alignment to 'Right'", className); - global::reader::textAlignment = 2; - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); - writeFile(".config/04-book/alignment", "Right"); -} - -void reader::on_alignJustifyBtn_clicked() -{ - log("Setting text alignment to 'Justify'", className); - global::reader::textAlignment = 3; - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); - writeFile(".config/04-book/alignment", "Justify"); -} - -void reader::setTextProperties(int alignment, int lineSpacing, int margins, QString font, int fontSize) { - // Don't try to improve this - // I have spent more time on it than I would care to admit - - // Alignment - /* - * 0 - Left - * 1 - Center - * 2 - Right - * 3 - Justify - */ - - // Selection color - ui->text->setStyleSheet("QTextEdit { selection-background-color: white; color: white; }"); - // Font - { - if(font == "Crimson Pro") { - // As adding Crimson Pro to the default fonts bundled along with the Qt libs breaks the general u001/Inter homogeneity, it is incorporated on-demand here. - { - QString family; - { - int id = QFontDatabase::addApplicationFont(":/resources/fonts/CrimsonPro-Regular.ttf"); - family = QFontDatabase::applicationFontFamilies(id).at(0); - } - { - int id = QFontDatabase::addApplicationFont(":/resources/fonts/CrimsonPro-Italic.ttf"); - family = QFontDatabase::applicationFontFamilies(id).at(0); - } - { - int id = QFontDatabase::addApplicationFont(":/resources/fonts/CrimsonPro-Bold.ttf"); - family = QFontDatabase::applicationFontFamilies(id).at(0); - } - { - int id = QFontDatabase::addApplicationFont(":/resources/fonts/CrimsonPro-BoldItalic.ttf"); - family = QFontDatabase::applicationFontFamilies(id).at(0); - } - ui->text->setFont(QFont(family)); - } - writeFile(".config/04-book/font", "Crimson Pro"); - } - else if(font == "Bitter") { - { - QString family; - { - int id = QFontDatabase::addApplicationFont(":/resources/fonts/Bitter-Medium.ttf"); - family = QFontDatabase::applicationFontFamilies(id).at(0); - } - { - int id = QFontDatabase::addApplicationFont(":/resources/fonts/Bitter-MediumItalic.ttf"); - family = QFontDatabase::applicationFontFamilies(id).at(0); - } - { - int id = QFontDatabase::addApplicationFont(":/resources/fonts/Bitter-Bold.ttf"); - family = QFontDatabase::applicationFontFamilies(id).at(0); - } - { - int id = QFontDatabase::addApplicationFont(":/resources/fonts/Bitter-BoldItalic.ttf"); - family = QFontDatabase::applicationFontFamilies(id).at(0); - } - ui->text->setFont(QFont(family)); - } - writeFile(".config/04-book/font", "Bitter"); - } - else if(font == "Ibarra Real Nova") { - { - QString family; - { - int id = QFontDatabase::addApplicationFont(":/resources/fonts/IbarraRealNova-Medium.ttf"); - family = QFontDatabase::applicationFontFamilies(id).at(0); - } - { - int id = QFontDatabase::addApplicationFont(":/resources/fonts/IbarraRealNova-MediumItalic.ttf"); - family = QFontDatabase::applicationFontFamilies(id).at(0); - } - { - int id = QFontDatabase::addApplicationFont(":/resources/fonts/IbarraRealNova-Bold.ttf"); - family = QFontDatabase::applicationFontFamilies(id).at(0); - } - { - int id = QFontDatabase::addApplicationFont(":/resources/fonts/IbarraRealNova-BoldItalic.ttf"); - family = QFontDatabase::applicationFontFamilies(id).at(0); - } - ui->text->setFont(QFont(family)); - } - writeFile(".config/04-book/font", "Ibarra Real Nova"); - } - else if(font == "Univers (u001)" or font == "u001") { - ui->text->setFont(QFont("u001")); - writeFile(".config/04-book/font", "Univers (u001)"); - } - else { - ui->text->setFont(QFont(font)); - writeFile(".config/04-book/font", font); - } - } - - // Highlighting - QString htmlText = global::reader::currentViewportText; - QJsonObject jsonObject = getHighlightsForBook(book_file); - int keyCount = 1; - foreach(const QString& key, jsonObject.keys()) { - if(keyCount <= 1) { - keyCount++; - continue; - } - else { - QString highlight = jsonObject.value(key).toString(); - if(htmlText.contains(highlight)) { - htmlText.replace(highlight, "" + highlight + ""); - } - } - keyCount++; - } - htmlText.replace(QRegExp("font-family:'.*';"), ""); - ui->text->setHtml(htmlText); - - // Line spacing, margins - setLineSpacing(lineSpacing, false); - ui->lineSpacingSlider->setValue(lineSpacing); - setMargins(margins, false); - ui->marginsSlider->setValue(margins); - - textDialogLock = true; - QTextCursor cursor = ui->text->textCursor(); - // Kudos to Qt for not implementing the opposite of the following function /)_-) - ui->text->selectAll(); - // Text alignment - if(alignment == 0) { - ui->text->setAlignment(Qt::AlignLeft); - } - else if(alignment == 1) { - ui->text->setAlignment(Qt::AlignHCenter); - } - else if(alignment == 2) { - ui->text->setAlignment(Qt::AlignRight); - } - else if(alignment == 3) { - ui->text->setAlignment(Qt::AlignJustify); - } - // Font size - ui->text->setFontPointSize(fontSize); - ui->text->setTextCursor(cursor); - // Selection color - ui->text->setStyleSheet("QTextEdit { selection-background-color: black; color: black; }"); - textDialogLock = false; -} - -void reader::menubar_show() { - log("Showing menu bar", className); - // Checking battery level and status, then displaying the relevant icon on batteryIconLabel - if(isUsbPluggedIn() == true) { - ui->batteryIconLabel->setPixmap(scaledChargingPixmap); - } - else { - getBatteryLevel(); - if(batteryLevelInt >= 75 && batteryLevelInt <= 100) { - ui->batteryIconLabel->setPixmap(scaledFullPixmap); - } - if(batteryLevelInt >= 25 && batteryLevelInt <= 74) { - ui->batteryIconLabel->setPixmap(scaledHalfPixmap); - } - if(batteryLevelInt >= 0 && batteryLevelInt <= 24) { - ui->batteryIconLabel->setPixmap(scaledEmptyPixmap); - } - } - - ui->menuWidget->setVisible(true); - if(is_pdf == false && is_image == false) { - ui->menuBarWidget->setVisible(true); - } - else { - if(is_pdf == true) { - ui->pdfScaleWidget->setVisible(true); - } - ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); - ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - } - ui->buttonsBarWidget->setVisible(true); - ui->statusBarWidget->setVisible(true); - if(is_image == true) { - ui->pageWidget->setVisible(false); - } - else { - ui->pageWidget->setVisible(true); - } - - menubar_shown = true; -} - -void reader::menubar_hide() { - log("Hiding menu bar", className); - - if(is_pdf == false && is_image == false) { - ui->menuBarWidget->setVisible(false); - } - else { - ui->pdfScaleWidget->setVisible(false); - if(checkconfig(".config/14-reader_scrollbar/config") == true) { - ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); - ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - } - else { - ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - } - } - ui->buttonsBarWidget->setVisible(false); - ui->pageWidget->setVisible(false); - if(checkconfig(".config/11-menubar/sticky") == true) { - ui->statusBarWidget->setVisible(true); - } - else { - ui->statusBarWidget->setVisible(false); - ui->menuWidget->setVisible(false); - } - menubar_shown = false; -} - -void reader::wordwidget_show() { - log("Showing word widget", className); - if(menubar_shown == true) { - menubar_hide(); - ui->optionsBtn->hide(); - ui->line->hide(); - ui->wordWidget->setVisible(true); - } - else { - ui->optionsBtn->hide(); - ui->line->hide(); - ui->wordWidget->setVisible(true); - } -} - -void reader::wordwidget_hide() { - log("Hiding word widget", className); - ui->wordWidget->setVisible(false); - ui->optionsBtn->setStyleSheet("background: white; color: black"); - ui->optionsBtn->show(); - ui->line->show(); - wordwidgetLock = false; -} - -void reader::on_infoCloseBtn_clicked() -{ - wordwidget_hide(); - dictionary_position = 1; - QString dictionary_position_str = QString::number(dictionary_position); - ui->definitionStatusLabel->setText(dictionary_position_str); - - QTextCursor cursor = ui->text->textCursor(); - cursor.clearSelection(); - ui->text->setTextCursor(cursor); -} - -void reader::on_previousDefinitionBtn_clicked() -{ - dictionary_position = dictionary_position - 1; - if(dictionary_position <= 0) { - dictionary_position = 1; - } - else { - dictionary_lookup(selected_text_str, letter, dictionary_position); - ui->definitionLabel->setText(definition); - QString dictionary_position_str = QString::number(dictionary_position); - ui->definitionStatusLabel->setText(dictionary_position_str); - } -} - -void reader::on_nextDefinitionBtn_clicked() -{ - dictionary_position = dictionary_position + 1; - dictionary_lookup(selected_text_str, letter, dictionary_position); - if(nextdefinition_lock == true) { - dictionary_position = dictionary_position - 1; - } - else { - ui->definitionLabel->setText(definition); - QString dictionary_position_str = QString::number(dictionary_position); - ui->definitionStatusLabel->setText(dictionary_position_str); - } -} - -void reader::on_saveWordBtn_clicked() -{ - if(checkconfig_match(".config/06-words/config", selected_text_str) == true) { - log("Removing word '" + QString::fromStdString(selected_text_str) + "' from Saved Words list", className); - checkwords(); - word = word.append("\n"); - words = words.replace(word, ""); - string words_std_string = words.toStdString(); - save_word(words_std_string, true); - ui->saveWordBtn->setText(""); - ui->saveWordBtn->setIcon(QIcon(":/resources/star.png")); - } - else { - save_word(selected_text_str, false); - ui->saveWordBtn->setText(""); - ui->saveWordBtn->setIcon(QIcon(":/resources/starred_star.png")); - } -} - -void reader::on_sizeSlider_valueChanged(int value) -{ - // Font size - log("Setting font size to " + QString::number(value + global::reader::initialFontSize + 1) + " points", className); - ui->sizeValueLabel->setText(QString::number(value + 1)); - - global::reader::fontSize = global::reader::initialFontSize + value + 1; - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); - - writeFile(".config/04-book/size", QString::number(value)); -} - -void reader::writeconfig_pagenumber(bool persistent) { - // Saving the page number in tmpfs and in persistent storage if requested - if(is_epub == true) { - QString epubPageNumberStr = QString::number(mupdf::epub::epubPageNumber); - writeFile("/tmp/inkboxPageNumber", epubPageNumberStr); - if(persistent == true) { - log("Writing page number config for page '" + QString::number(mupdf::epub::epubPageNumber) + "'", className); - epubPageNumberStr.append("\n"); - writeFile(".config/A-page_number/config", epubPageNumberStr); - } - } - else if(is_pdf == true) { - QString pdfPageNumberStr = QString::number(mupdf::pdf::pdfPageNumber); - writeFile("/tmp/inkboxPageNumber", pdfPageNumberStr); - if(persistent == true) { - log("Writing page number config for page '" + pdfPageNumberStr + "'", className); - pdfPageNumberStr.append("\n"); - writeFile(".config/A-page_number/config", pdfPageNumberStr); - } - } - else { - QString splitTotalStr = QString::number(split_total); - writeFile("/tmp/inkboxPageNumber", splitTotalStr); - if(persistent == true) { - log("Writing page number config for split total '" + splitTotalStr + "'", className); - splitTotalStr.append("\n"); - writeFile(".config/A-page_number/config", splitTotalStr); - } - } -} - -void reader::quit_restart() { - log("Restarting InkBox", className); - - // Saving current page number - saveReadingSettings(); - - // Cleaning bookconfig_mount mountpoint - writeFile("/opt/ibxd", "bookconfig_unmount\n"); - - // Restarting InkBox - QProcess process; - process.startDetached("inkbox", QStringList()); - qApp->quit(); -} - -void reader::openLowBatteryDialog() { - log("Showing low battery dialog", className); - global::mainwindow::lowBatteryDialog = true; - global::battery::batteryAlertLock = true; - - generalDialogWindow = new generalDialog(this); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - QApplication::processEvents(); -} - -void reader::openCriticalBatteryAlertWindow() { - log("Showing critical battery alert splash", className); - global::battery::showCriticalBatteryAlert = true; - global::battery::showLowBatteryDialog = false; - - alertWindow = new alert(); - alertWindow->setAttribute(Qt::WA_DeleteOnClose); - alertWindow->setGeometry(QRect(QPoint(0,0), screen()->geometry ().size())); - alertWindow->show(); -} - -void reader::convertMuPdfVars(int fileType, bool convertAll) { - /* fileType can be: - * 0: ePUB - * 1: PDF - * 2: Image - */ - if(fileType == 0) { - if(convertAll == 1) { - setPageStyle(0); - mupdf::epub::fontSize = 12; - mupdf::epub::fontSize_qstr = QString::number(mupdf::epub::fontSize); - mupdf::epub::width_qstr = QString::number(mupdf::epub::width); - mupdf::epub::height_qstr = QString::number(mupdf::epub::height); - } - if(global::reader::globalReadingSettings == false) { - if(goToSavedPageDone == false) { - mupdf::epub::epubPageNumber = readFile(".config/A-page_number/config").toInt(); - goToSavedPageDone = true; - } - } - if(mupdf::epub::epubPageNumber <= 0) { - mupdf::epub::epubPageNumber = 1; - } - mupdf::epub::epubPageNumber_qstr = QString::number(mupdf::epub::epubPageNumber); - } - else if(fileType == 1) { - setPageStyle(1); - mupdf::pdf::width = defaultPdfPageWidth; - mupdf::pdf::height = defaultPdfPageHeight; - if(mupdf::convertRelativeValues == true) { - // For scaling - mupdf::pdf::width_qstr = QString::number(mupdf::pdf::relativeWidth); - mupdf::pdf::height_qstr = QString::number(mupdf::pdf::relativeHeight); - } - else { - // Default - mupdf::pdf::width_qstr = QString::number(mupdf::pdf::width); - mupdf::pdf::height_qstr = QString::number(mupdf::pdf::height); - } - if(global::reader::globalReadingSettings == false) { - if(goToSavedPageDone == false) { - mupdf::pdf::pdfPageNumber = readFile(".config/A-page_number/config").toInt(); - goToSavedPageDone = true; - } - } - if(mupdf::pdf::pdfPageNumber <= 0) { - mupdf::pdf::pdfPageNumber = 1; - } - mupdf::pdf::pdfPageNumber_qstr = QString::number(mupdf::pdf::pdfPageNumber); - } - else if(fileType == 2) { - ; - } - if(mupdf::convertRelativeValues == true) { - mupdf::convertRelativeValues = false; - } -} - -void reader::setPageStyle(int fileType) { - /* fileType can be: - * 0: ePUB - * 1: PDF - * 2: Image - */ - if(fileType == 0) { - // General page size - defineDefaultPageSize(0); - - if(readFile(".config/13-epub_page_size/width").isEmpty()) { - QString pageWidth = QString::number(defaultEpubPageWidth); - writeFile(".config/13-epub_page_size/width", pageWidth); - writeFile(".config/13-epub_page_size/set", "true"); - } - mupdf::epub::width = readFile(".config/13-epub_page_size/width").toInt(); - - if(readFile(".config/13-epub_page_size/height").isEmpty()) { - QString pageHeight = QString::number(defaultEpubPageHeight); - writeFile(".config/13-epub_page_size/height", pageHeight); - writeFile(".config/13-epub_page_size/set", "true"); - } - mupdf::epub::height = readFile(".config/13-epub_page_size/height").toInt(); - } - else if(fileType == 1) { - defineDefaultPageSize(1); - } -} - -void reader::delay(int mseconds) { - // https://stackoverflow.com/questions/3752742/how-do-i-create-a-pause-wait-function-using-qt - QTime dieTime = QTime::currentTime().addMSecs(mseconds); - while (QTime::currentTime() < dieTime) - QCoreApplication::processEvents(QEventLoop::AllEvents, 100); -} - -void reader::on_text_selectionChanged() { - delay(100); - if(wordwidgetLock == false and textDialogLock == false) { - QTextCursor cursor = ui->text->textCursor(); - selected_text = cursor.selectedText(); - if(!selected_text.isEmpty()) { - log("Text selection changed; selected text: '" + selected_text + "'", className); - if(!selected_text.contains(" ")) { - // Word selection - QString dictionary_position_str = QString::number(dictionary_position); - ui->definitionStatusLabel->setText(dictionary_position_str); - - selected_text = selected_text.toLower(); - QStringList parts = selected_text.split(' ', QString::SkipEmptyParts); - for (int i = 0; i < parts.size(); ++i) - parts[i].replace(0, 1, parts[i][0].toUpper()); - word = parts.join(" "); - letter = word.left(1); - selected_text_str = word.toStdString(); - dictionary_lookup(selected_text_str, letter, dictionary_position); - ui->wordLabel->setText(word); - ui->definitionLabel->setText(definition); - if(checkconfig_match(".config/06-words/config", selected_text_str) == true) { - ui->saveWordBtn->setText(""); - ui->saveWordBtn->setIcon(QIcon(":/resources/starred_star.png")); - } - else { - ui->saveWordBtn->setText(""); - ui->saveWordBtn->setIcon(QIcon(":/resources/star.png")); - } - wordwidgetLock = true; - wordwidget_show(); - } - else { - // Highlight - textDialogLock = true; - global::reader::highlightAlreadyDone = false; - QJsonObject jsonObject = getHighlightsForBook(book_file); - QString htmlText = ui->text->toHtml(); - if(htmlText.contains("" + selected_text + "") or htmlText.contains("" + selected_text + "")) { - log("Highlight already done", className); - global::reader::highlightAlreadyDone = true; - } - - textDialog * textDialogWindow = new textDialog(this); - QObject::connect(textDialogWindow, &textDialog::destroyed, this, &reader::unsetTextDialogLock); - QObject::connect(textDialogWindow, &textDialog::highlightText, this, &reader::highlightText); - QObject::connect(textDialogWindow, &textDialog::unhighlightText, this, &reader::unhighlightText); - textDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - textDialogWindow->setWindowFlags(Qt::FramelessWindowHint | Qt::Popup); - textDialogWindow->move(mapFromGlobal(ui->text->cursorRect().bottomRight())); - textDialogWindow->show(); - } - } - else { - ; - } - } -} - -void reader::on_nightModeBtn_clicked() -{ - if(isNightModeActive == true) { - // Disabling night/dark mode - log("Setting night mode to OFF", className); - writeFile("/tmp/invertScreen", "n"); - writeFile(".config/10-dark_mode/config", "false"); - ui->nightModeBtn->setIcon(QIcon(":/resources/nightmode-empty.png")); - isNightModeActive = false; - } - else { - // Enabling night/dark mode - log("Setting night mode to ON", className); - writeFile("/tmp/invertScreen", "y"); - writeFile(".config/10-dark_mode/config", "true"); - ui->nightModeBtn->setIcon(QIcon(":/resources/nightmode-full.png")); - isNightModeActive = true; - } -} - -void reader::openUsbmsDialog() { - log("Showing USBMS dialog", className); - global::usbms::showUsbmsDialog = false; - global::usbms::usbmsDialog = true; - - generalDialogWindow = new generalDialog(this); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - QApplication::processEvents(); -} - -QString reader::setPageNumberLabelContent() { - QString content; - if(is_epub == true) { - QString pageNumber; - QString totalPages; - pageNumberInt = mupdf::epub::epubPageNumber; - pageNumber = QString::number(pageNumberInt); - totalPages = QString::number(totalPagesInt); - content.append(pageNumber); - content.append(" of "); - content.append(totalPages); - } - else if(is_pdf == true) { - QString pageNumber; - QString totalPages; - pageNumberInt = mupdf::pdf::pdfPageNumber; - pageNumber = QString::number(pageNumberInt); - totalPages = QString::number(totalPagesInt); - content.append(pageNumber); - content.append(" of "); - content.append(totalPages); - } - else { - QString pageNumber; - QString totalPages; - pageNumberInt = split_files_number - split_total; - totalPagesInt = split_files_number - 2; - pageNumber = QString::number(pageNumberInt); - totalPages = QString::number(totalPagesInt); - content.append(pageNumber); - content.append(" of "); - content.append(totalPages); - } - return content; -} - -void reader::setupPageWidget() { - QString pageNumberInfoLabelContent = setPageNumberLabelContent(); - ui->pageNumberLabel->setText(pageNumberInfoLabelContent); - ui->pageProgressBar->setMaximum(totalPagesInt); - ui->pageProgressBar->setMinimum(1); - ui->pageProgressBar->setValue(pageNumberInt); -} - -void reader::getTotalEpubPagesNumber() { - QString epubProg ("sh"); - QStringList epubArgs; - convertMuPdfVars(0, true); - epubArgs << "/mnt/onboard/.adds/inkbox/epub.sh" << mupdf::epub::fontSize_qstr << mupdf::epub::width_qstr << mupdf::epub::height_qstr << mupdf::epub::epubPageNumber_qstr << "get_pages_number"; - QProcess *epubProc = new QProcess(); - epubProc->start(epubProg, epubArgs); - epubProc->waitForFinished(); - epubProc->deleteLater(); - - QString totalPages = readFile("/run/epub_total_pages_number"); - totalPagesInt = totalPages.toInt(); - log("ePUB total pages number: " + totalPages, className); - QFile::remove("/run/epub_total_pages_number"); -} - -void reader::on_gotoBtn_clicked() -{ - log("Showing 'Go to page' dialog", className); - global::keyboard::keypadDialog = true; - generalDialogWindow = new generalDialog(); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - connect(generalDialogWindow, SIGNAL(gotoPageSelected(int)), SLOT(gotoPage(int))); -} - -void reader::gotoPage(int pageNumber) { - log("Going to page " + QString::number(pageNumber), className); - if(is_epub == true) { - if(pageNumber > totalPagesInt or pageNumber < 1) { - showToast("Request is beyond page range"); - } - else { - mupdf::epub::epubPageNumber = pageNumber; - setup_book(book_file, mupdf::epub::epubPageNumber, true); - ui->text->setText(""); - ui->text->setText(epubPageContent); - global::reader::currentViewportText = ui->text->toHtml(); - - pagesTurned = 0; - writeconfig_pagenumber(false); - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); - } - } - else if(is_pdf == true) { - if(pageNumber > totalPagesInt or pageNumber < 1) { - showToast("Request is beyond page range"); - } - else { - mupdf::pdf::pdfPageNumber = pageNumber; - setup_book(book_file, mupdf::pdf::pdfPageNumber, true); - setupPng(); - - pagesTurned = 0; - writeconfig_pagenumber(false); - } - } - else { - if(split_files_number - pageNumber < 2 or split_files_number - pageNumber > split_files_number - 1) { - showToast("You've reached the end of the document"); - } - else { - split_total = split_files_number - pageNumber; - - setup_book(book_file, split_total, false); - ui->text->setText(""); - ui->text->setText(ittext); - - pagesTurned = 0; - writeconfig_pagenumber(false); - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); - } - } - setupPageWidget(); - refreshScreen(); -} - -void reader::on_searchBtn_clicked() -{ - global::forbidOpenSearchDialog = false; - setupSearchDialog(); -} - -void reader::setupSearchDialog() { - if(global::forbidOpenSearchDialog == false) { - log("Launching Search dialog", className); - global::keyboard::keyboardDialog = true; - global::keyboard::searchDialog = true; - global::keyboard::keyboardText = ""; - generalDialogWindow = new generalDialog(); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - connect(generalDialogWindow, SIGNAL(refreshScreen()), SLOT(searchRefreshScreen())); - connect(generalDialogWindow, SIGNAL(destroyed(QObject*)), SLOT(setupSearchDialog())); - connect(generalDialogWindow, SIGNAL(openBookFile(QString, bool)), SLOT(openBookFileNative(QString, bool))); - connect(generalDialogWindow, SIGNAL(showToast(QString)), SLOT(showToast(QString))); - connect(generalDialogWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToast())); - generalDialogWindow->show(); - } - else { - ; - } -} - -void reader::searchRefreshScreen() { - this->repaint(); -} - -void reader::showToast(QString messageToDisplay) { - global::toast::message = messageToDisplay; - toastWindow = new toast(this); - toastWindow->setAttribute(Qt::WA_DeleteOnClose); - toastWindow->show(); -} - -void reader::saveReadingSettings() { - writeconfig_pagenumber(true); -} - -void reader::setupLocalSettingsEnvironment() { - log("Setting local settings environment up", className); - QString pageNumberDirPath = ".config/A-page_number"; - QDir pageNumberDir; - pageNumberDir.mkpath(pageNumberDirPath); -} - -void reader::setupPng() { - if(is_pdf == true) { - // Note: Output file is supposed to be '/run/page.png', but somehow mutool puts it in '/run/page1.png' - QPixmap pixmap("/run/page1.png"); - QFile::remove("/run/page1.png"); - // Initialized above - graphicsScene->clear(); - graphicsScene->addPixmap(pixmap); - // Shrinking scene if item is smaller than previous one - QRectF rect = graphicsScene->itemsBoundingRect(); - graphicsScene->setSceneRect(rect); - ui->graphicsView->items().clear(); - ui->graphicsView->setScene(graphicsScene); - if(global::reader::pdfOrientation == 1) { - if(!initialPdfRotationDone) { - ui->graphicsView->rotate(270); - initialPdfRotationDone = true; - } - } - } - else if(is_image == true) { - QPixmap pixmap("/run/image.png"); - QFile::remove("/run/image.png"); - // Initialized above - graphicsScene->clear(); - graphicsScene->addPixmap(pixmap); - // Shrinking scene if item is smaller than previous one - QRectF rect = graphicsScene->itemsBoundingRect(); - graphicsScene->setSceneRect(rect); - ui->graphicsView->items().clear(); - ui->graphicsView->setScene(graphicsScene); - } -} - -bool reader::pdf_file_match(QString file) { - QString fileExt = file.right(3); - - if(fileExt == "pdf" or fileExt == "PDF") { - log("Book file format: PDF", className); - writeFile("/inkbox/bookIsPdf", "true"); - return true; - } - else { - writeFile("/inkbox/bookIsPdf", "false"); - return false; - } -} - -bool reader::image_file_match(QString file) { - if(file.right(3) == "png" or file.right(3) == "PNG" or file.right(3) == "jpg" or file.right(3) == "JPG" or file.right(3) == "bmp" or file.right(3) == "BMP" or file.right(3) == "tif" or file.right(3) == "TIF") { - log("File format: image", className); - writeFile("/inkbox/bookIsImage", "true"); - return true; - } - else if(file.right(4) == "jpeg" or file.right(4) == "JPEG" or file.right(4) == "tiff" or file.right(4) == "TIFF") { - log("File format: image", className); - writeFile("/inkbox/bookIsImage", "true"); - return true; - } - else { - writeFile("/inkbox/bookIsImage", "false"); - return false; - } -} - -void reader::getTotalPdfPagesNumber() { - QString epubProg ("sh"); - QStringList epubArgs; - convertMuPdfVars(0, true); - epubArgs << "/mnt/onboard/.adds/inkbox/pdf_get_total_pages_number.sh" << book_file; - QProcess * epubProc = new QProcess(); - epubProc->start(epubProg, epubArgs); - epubProc->waitForFinished(); - epubProc->deleteLater(); - - QString totalPages = readFile("/run/pdf_total_pages_number"); - totalPagesInt = totalPages.toInt(); - log("Total PDF pages number: " + totalPages, className); - QFile::remove("/run/pdf_total_pages_number"); -} - -void reader::on_pdfScaleSlider_valueChanged(int value) -{ - log("Setting PDF scale to " + QString::number(value), className); - if(value == 1) { - mupdf::pdf::relativeWidth = 1 * mupdf::pdf::width; - mupdf::pdf::relativeHeight = 1 * mupdf::pdf::height; - } - else if(value == 2) { - mupdf::pdf::relativeWidth = 1.50 * mupdf::pdf::width; - mupdf::pdf::relativeHeight = 1.50 * mupdf::pdf::height; - } - else if(value == 3) { - mupdf::pdf::relativeWidth = 2 * mupdf::pdf::width; - mupdf::pdf::relativeHeight = 2 * mupdf::pdf::height; - } - else if(value == 4) { - mupdf::pdf::relativeWidth = 2.50 * mupdf::pdf::width; - mupdf::pdf::relativeHeight = 2.50 * mupdf::pdf::height; - } - - if(value != 1) { - ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); - ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - } - else { - if(checkconfig(".config/14-reader_scrollbar/config") == true) { - ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); - ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - } - else { - ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - } - } - - mupdf::convertRelativeValues = true; - setup_book(book_file, mupdf::pdf::pdfPageNumber, true); - setupPng(); -} - -void reader::on_decreaseScaleBtn_clicked() -{ - int sliderCurrentValue; - int sliderWantedValue; - sliderCurrentValue = ui->pdfScaleSlider->value(); - sliderWantedValue = sliderCurrentValue - 1; - if(sliderWantedValue < ui->pdfScaleSlider->QAbstractSlider::minimum()) { - showToast("Minimum scale reached"); - } - else { - ui->pdfScaleSlider->setValue(sliderWantedValue); - } -} - -void reader::on_increaseScaleBtn_clicked() -{ - int sliderCurrentValue; - int sliderWantedValue; - sliderCurrentValue = ui->pdfScaleSlider->value(); - sliderWantedValue = sliderCurrentValue + 1; - if(sliderWantedValue > ui->pdfScaleSlider->QAbstractSlider::maximum()) { - showToast("Maximum scale reached"); - } - else { - ui->pdfScaleSlider->setValue(sliderWantedValue); - } -} - -void reader::openBookFileNative(QString book, bool relativePath) { - if(global::runningInstanceIsReaderOnly == false) { - emit openBookFile(book, relativePath); - } - else { - showToast("Not supported"); - } -} - -void reader::on_quitBtn_clicked() -{ - log("Showing Quit window", className); - writeconfig_pagenumber(true); - quitWindow = new quit(); - quitWindow->setAttribute(Qt::WA_DeleteOnClose); - quitWindow->showFullScreen(); -} - -void reader::closeIndefiniteToast() { - // Warning: use with caution - toastWindow->close(); -} - -void reader::getPdfOrientation(QString file) { - log("Getting viewport orientation for PDF file '" + file + "'", className); - writeFile("/inkbox/pdf_orientation_file_request", file); - writeFile("/opt/ibxd", "get_pdf_orientation\n"); - while(true) { - if(QFile::exists("/inkbox/pdf_orientation_result")) { - QString result = readFile("/inkbox/pdf_orientation_result").trimmed(); - if(result == "Portrait") { - QString function = __func__; log(function + ": Orientation is portrait", className); - global::reader::pdfOrientation = 0; - } - else { - QString function = __func__; log(function + ": Orientation is landscape", className); - global::reader::pdfOrientation = 1; - } - break; - } - } -} - -void reader::unsetTextDialogLock() { - QTextCursor cursor = ui->text->textCursor(); - cursor.clearSelection(); - ui->text->setTextCursor(cursor); - - textDialogLock = false; -} - -void reader::highlightText() { - log("Highlighting text '" + selected_text + "'", className); - highlightBookText(selected_text, book_file, false); - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); -} - -void reader::unhighlightText() { - log("Removing highlighted text '" + selected_text + "'", className); - highlightBookText(selected_text, book_file, true); - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); -} - -void reader::on_viewHighlightsBtn_clicked() -{ - log("Launching highlights list dialog for book '" + book_file + "'", className); - QJsonObject jsonObject = getHighlightsForBook(book_file); - if(jsonObject.isEmpty() or jsonObject.length() <= 1) { - global::toast::delay = 3000; - showToast("No highlights for this book"); - } - else { - global::highlightsListDialog::bookPath = book_file; - highlightsListDialog * highlightsListDialogWindow = new highlightsListDialog(this); - QObject::connect(highlightsListDialogWindow, &highlightsListDialog::destroyed, this, &reader::setTextPropertiesSlot); - QObject::connect(highlightsListDialogWindow, &highlightsListDialog::showToast, this, &reader::showToast); - highlightsListDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - } -} - -void reader::setTextPropertiesSlot() { - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); -} - -void reader::setInitialTextProperties() { - // Checking saved font size if any, and if there is, set it - QString fontSizeString = readFile(".config/04-book/size"); - if(!fontSizeString.isEmpty()) { - global::reader::fontSize = fontSizeString.toInt(); - ui->sizeSlider->setValue(global::reader::fontSize); - } - else { - global::reader::fontSize = 4; - } -} - -void reader::setLineSpacing(int spacing, bool write) { - global::reader::lineSpacing = spacing; - if(write == true and readFile(".config/04-book/line_spacing") != QString::number(global::reader::lineSpacing)) { - writeFile(".config/04-book/line_spacing", QString::number(global::reader::lineSpacing)); - } - - if(write == false) { - log("Setting line spacing to " + QString::number(global::reader::lineSpacing + 1), className); - QTextCursor textCursor = ui->text->textCursor(); - - QTextBlockFormat * newFormat = new QTextBlockFormat(); - textCursor.clearSelection(); - textCursor.select(QTextCursor::Document); - newFormat->setLineHeight((global::reader::lineSpacing * 10 + 100), QTextBlockFormat::ProportionalHeight); - newFormat->setLeftMargin(global::reader::margins * 10); - newFormat->setRightMargin(global::reader::margins * 10); - textCursor.setBlockFormat(*newFormat); - } -} - -void reader::setMargins(int margins, bool write) { - global::reader::margins = margins; - if(write == true and readFile(".config/04-book/margins") != QString::number(global::reader::margins)) { - writeFile(".config/04-book/margins", QString::number(global::reader::margins)); - } - - if(write == false) { - log("Setting margins to " + QString::number(global::reader::margins), className); - QTextCursor textCursor = ui->text->textCursor(); - - QTextBlockFormat * newFormat = new QTextBlockFormat(); - textCursor.clearSelection(); - textCursor.select(QTextCursor::Document); - newFormat->setLineHeight((global::reader::lineSpacing * 10 + 100), QTextBlockFormat::ProportionalHeight); - newFormat->setLeftMargin(global::reader::margins * 10); - newFormat->setRightMargin(global::reader::margins * 10); - textCursor.setBlockFormat(*newFormat); - } -} - -void reader::on_lineSpacingSlider_valueChanged(int value) -{ - global::reader::lineSpacing = value; - // Write setting once - setLineSpacing(global::reader::lineSpacing, true); - // Be consistent with other settings - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); - ui->lineSpacingValueLabel->setText(QString::number(value + 1)); -} - -void reader::on_marginsSlider_valueChanged(int value) -{ - global::reader::margins = value; - // Write setting once - setMargins(global::reader::margins, true); - // Be consistent with other settings - setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); - ui->marginsValueLabel->setText(QString::number(value + 1)); -} - -void reader::on_brightnessBtn_clicked() -{ - log("Showing Brightness Dialog", className); - brightnessDialogWindow = new brightnessDialog(); - brightnessDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - brightnessDialogWindow->show(); -} - -void reader::setCinematicBrightnessWarmthSlot() { - if(global::reader::globalReadingSettings == false) { - if(global::deviceID != "n705\n" and global::deviceID != "n905\n" and global::deviceID != "kt\n") { - int brightness_value = brightnessCheckconfig(".config/03-brightness/config"); - log("Local Reading Settings: Setting brightness to " + QString::number(brightness_value), className); - cinematicBrightness(brightness_value, 2); - } - if(global::deviceID == "n249\n" or global::deviceID == "n873\n") { - int warmthValue = readFile(".config/03-brightness/config-warmth").toInt(); - log("Local Reading Settings: Setting warmth to " + QString::number(warmthValue), className); - cinematicWarmth(warmthValue); - } - } -} diff --git a/src/settings/koboxsettings.cpp b/src/settings/koboxsettings.cpp deleted file mode 100644 index d6ec532..0000000 --- a/src/settings/koboxsettings.cpp +++ /dev/null @@ -1,136 +0,0 @@ -#include "koboxsettings.h" -#include "ui_koboxsettings.h" -#include "functions.h" - -#include -#include - -koboxSettings::koboxSettings(QWidget *parent) : - QWidget(parent), - ui(new Ui::koboxSettings) -{ - ui->setupUi(this); - koboxSettings::setFont(QFont("u001")); - ui->okBtn->setFont(QFont("Inter")); - - // UI tweaks - ui->okBtn->setProperty("type", "borderless"); - ui->pushButton->setProperty("type", "borderless"); - ui->resetKoboxBtn->setProperty("type", "borderless"); - ui->pushButton->setStyleSheet("font-weight: bold"); - ui->resetKoboxBtn->setStyleSheet("font-weight: bold"); - ui->okBtn->setStyleSheet("font-weight: bold"); - - // Stylesheet - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - if(checkconfig("/external_root/boot/flags/X11_START") == true) { - ui->koboxStatusLabel->setText("KoBox is enabled"); - not_user_change = true; - ui->checkBox->click(); - ui->runtimeSettingsWidget->setVisible(true); - } - else { - ui->koboxStatusLabel->setText("KoBox is disabled"); - ui->runtimeSettingsWidget->setVisible(false); - } - - // DPI setting - QString dpiSetting; - QString dpiSettingStr = readFile(".config/00-kobox/dpiSetting"); - if(dpiSettingStr.isEmpty()) { - if(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "kt\n") { - dpiSetting = "125"; - } - else if(global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n306\n" or global::deviceID == "emu\n") { - dpiSetting = "175"; - } - else if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { - dpiSetting = "225"; - } - else if(global::deviceID == "n873\n") { - dpiSetting = "250"; - } - else { - dpiSetting = "125"; - } - writeFile(".config/00-kobox/dpiSetting", dpiSetting); - } - - readFile(".config/00-kobox/dpiSetting"); - int dpi_setting = dpiSettingStr.toInt(); - ui->spinBox->setValue(dpi_setting); -} - -koboxSettings::~koboxSettings() -{ - delete ui; -} - -void koboxSettings::on_okBtn_clicked() -{ - koboxSettings::close(); -} - -void koboxSettings::on_checkBox_toggled(bool checked) -{ - if(checked == true) { - if(not_user_change != true) { - log("Enabling KoBox subsystem", className); - writeFile("/external_root/boot/flags/X11_START", "true\n"); - openSettingsRebootDialog(); - } - else { - not_user_change = false; - } - } - else { - log("Disabling KoBox subsystem", className); - writeFile("/external_root/boot/flags/X11_START", "false\n"); - openSettingsRebootDialog(); - } -} - -void koboxSettings::openSettingsRebootDialog() { - log("Showing reboot dialog", className); - global::settings::settingsRebootDialog = true; - global::kobox::koboxSettingsRebootDialog = true; - generalDialogWindow = new generalDialog(this); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); -} -void koboxSettings::openResetKoboxDialog() { - log("Showing KoBox reset dialog", className); - global::kobox::resetKoboxDialog = true; - generalDialogWindow = new generalDialog(this); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); -} - -void koboxSettings::on_spinBox_valueChanged(int arg1) -{ - QString number = QString::number(arg1); - writeFile(".config/00-kobox/dpiSetting", number); - log("X11 DPI set to " + number, className); -} - -void koboxSettings::on_pushButton_clicked() -{ - // Export Extensions disk image over USB with g_mass_storage/g_file_storage - global::usbms::usbmsDialog = false; - global::usbms::launchUsbms = true; - global::usbms::koboxExportExtensions = true; - - log("Exporting KoBox extensions onboard storage via USB", className); - log("Showing USBMS splash", className); - usbmsWindow = new usbmsSplash(); - usbmsWindow->setAttribute(Qt::WA_DeleteOnClose); - usbmsWindow->setGeometry(QRect(QPoint(0,0), screen()->geometry ().size())); - usbmsWindow->show(); -} - -void koboxSettings::on_resetKoboxBtn_clicked() -{ - openResetKoboxDialog(); -} diff --git a/src/settings/powerdaemonsettings.cpp b/src/settings/powerdaemonsettings.cpp deleted file mode 100644 index 39ff48e..0000000 --- a/src/settings/powerdaemonsettings.cpp +++ /dev/null @@ -1,434 +0,0 @@ -#include "powerdaemonsettings.h" -#include "ui_powerdaemonsettings.h" -#include "functions.h" - -#include - -powerDaemonSettings::powerDaemonSettings(QWidget *parent) : - QWidget(parent), - ui(new Ui::powerDaemonSettings) -{ - ui->setupUi(this); - powerDaemonSettings::setFont(QFont("u001")); - ui->mainLabel->setFont(QFont("Inter")); - - // Avoid some display issues (label moving because width of text would change with a proportional font) - ui->CBSLabel->setFont(QFont("Roboto Mono")); - ui->idleSleepLabel->setFont(QFont("Roboto Mono")); - - // Font tweaks - ui->label_2->setFont(QFont("Inter")); - ui->exitBtn->setFont(QFont("Inter")); - - // UI tweaks - ui->exitBtn->setProperty("type", "borderless"); - ui->expBtn->setProperty("type", "borderless"); - ui->hWhenChargerSleepBtn->setProperty("type", "borderless"); - ui->hChargerWakeUpBtn->setProperty("type", "borderless"); - ui->wifiReconnectBtn->setProperty("type", "borderless"); - ui->ledUsageBtn->setProperty("type", "borderless"); - ui->hCustomCaseBtn->setProperty("type", "borderless"); - ui->deepSleepBtn->setProperty("type", "borderless"); - - ui->mainLabel->setStyleSheet("font-weight: bold"); - ui->CBSLabel->setStyleSheet("font-weight: bold"); - ui->idleSleepLabel->setStyleSheet("font-weight: bold"); - ui->exitBtn->setStyleSheet("font-weight: bold"); - // Experimental features label - ui->label_2->setStyleSheet("font-weight: bold"); - - // Icons - int controlBtnFixedWidth; - if(global::deviceID == "n705\n") { - controlBtnFixedWidth = 50; - } - else { - controlBtnFixedWidth = 80; - } - - ui->CBSDecreaseBtn->setIcon(QIcon(":/resources/minus.png")); - ui->CBSDecreaseBtn->setFixedWidth(controlBtnFixedWidth); - ui->CBSIncreaseBtn->setIcon(QIcon(":/resources/plus.png")); - ui->CBSIncreaseBtn->setFixedWidth(controlBtnFixedWidth); - - - int idleBtnsFixedWidth; - if(global::deviceID == "n705\n") { - idleBtnsFixedWidth = 80; - } - else { - idleBtnsFixedWidth = 100; - } - ui->idleSleepDecreaseBtn->setFixedWidth(idleBtnsFixedWidth); - ui->idleSleepIncreaseBtn->setFixedWidth(idleBtnsFixedWidth); - ui->idleSleepDecreaseMBtn->setFixedWidth(idleBtnsFixedWidth); - ui->idleSleepIncreaseMBtn->setFixedWidth(idleBtnsFixedWidth); - - // Padding - ui->CBSDecreaseBtn->setStyleSheet("padding: 10px; font-size: 10pt"); - ui->CBSIncreaseBtn->setStyleSheet("padding: 10px; font-size: 10pt"); - ui->idleSleepDecreaseBtn->setStyleSheet("font-family: 'Roboto Mono'; font-weight: bold; padding: 10px; font-size: 10pt"); - ui->idleSleepIncreaseBtn->setStyleSheet("font-family: 'Roboto Mono'; font-weight: bold; padding: 10px; font-size: 10pt"); - ui->idleSleepDecreaseMBtn->setStyleSheet("font-family: 'Roboto Mono'; font-weight: bold; padding: 10px; font-size: 10pt"); - ui->idleSleepIncreaseMBtn->setStyleSheet("font-family: 'Roboto Mono'; font-weight: bold; padding: 10px; font-size: 10pt"); - - // Stylesheet - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - // Button tweaks - int autoRepeatDelay = 1250; - int autoRepeatInterval = 20; - - ui->CBSDecreaseBtn->setAutoRepeat(true); - ui->CBSDecreaseBtn->setAutoRepeatDelay(autoRepeatDelay); - ui->CBSDecreaseBtn->setAutoRepeatInterval(autoRepeatInterval); - - ui->CBSIncreaseBtn->setAutoRepeat(true); - ui->CBSIncreaseBtn->setAutoRepeatDelay(autoRepeatDelay); - ui->CBSIncreaseBtn->setAutoRepeatInterval(autoRepeatInterval); - - ui->idleSleepDecreaseBtn->setAutoRepeat(true); - ui->idleSleepDecreaseBtn->setAutoRepeatDelay(autoRepeatDelay); - ui->idleSleepDecreaseBtn->setAutoRepeatInterval(autoRepeatInterval); - - ui->idleSleepIncreaseBtn->setAutoRepeat(true); - ui->idleSleepIncreaseBtn->setAutoRepeatDelay(autoRepeatDelay); - ui->idleSleepIncreaseBtn->setAutoRepeatInterval(autoRepeatInterval); - - ui->idleSleepDecreaseMBtn->setAutoRepeat(true); - ui->idleSleepDecreaseMBtn->setAutoRepeatDelay(autoRepeatDelay); - ui->idleSleepDecreaseMBtn->setAutoRepeatInterval(autoRepeatInterval); - - ui->idleSleepIncreaseMBtn->setAutoRepeat(true); - ui->idleSleepIncreaseMBtn->setAutoRepeatDelay(autoRepeatDelay); - ui->idleSleepIncreaseMBtn->setAutoRepeatInterval(autoRepeatInterval); - - // Hide items - ui->hLabel_3->hide(); - ui->hCpuFreqComboBox->hide(); - - ui->hWhenChargerSleepBtn->hide(); - ui->hChargerWakeUpBtn->hide(); - ui->hCustomCaseBtn->hide(); - - // Prepare variables from system configuration (20-sleep_daemon) - log("Reading variables from power daemon configuration", className); - - // 1 - cinematicBrightnessDelayMs - QString cinematicBrightnessMs = readFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/1-cinematicBrightnessDelayMs"); - - cinematicBrightnessInt = cinematicBrightnessMs.toInt(); - convertCinematicInt(); - - // 2 - cpuGovernor - QString cpuGovernor = readFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/2-cpuGovernor"); - - QStringList cpuGovernorList = QStringList{cpuGovernor}; - if(cpuGovernorList.contains("interactive") == false) { - cpuGovernorList.append("interactive"); - } - if(cpuGovernorList.contains("conservative") == false) { - cpuGovernorList.append("conservative"); - } - if(cpuGovernorList.contains("userspace") == false) { - cpuGovernorList.append("userspace"); - } - if(cpuGovernorList.contains("powersave") == false) { - cpuGovernorList.append("powersave"); - } - if(cpuGovernorList.contains("ondemand") == false) { - cpuGovernorList.append("ondemand"); - } - if(cpuGovernorList.contains("performance") == false) { - cpuGovernorList.append("performance"); - } - - ui->hCpuFreqComboBox->addItems(cpuGovernorList); - ui->hCpuFreqComboBox->setCurrentIndex(0); - - // 3 - whenChargerSleep - if(checkconfig("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/3-whenChargerSleep") == true) { - whenChargerSleepBool = true; - ui->hWhenChargerSleepBtn->click(); - } - else { - whenChargerSleepBool = false; - } - - // 4 - chargerWakeUp - if(checkconfig("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/4-chargerWakeUp") == true) { - chargerWakeUpBool = true; - ui->hChargerWakeUpBtn->click(); - } - else { - chargerWakeUpBool = false; - } - - // 5 - wifiReconnect - if(checkconfig("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/5-wifiReconnect") == true) { - ui->wifiReconnectBtn->click(); - wifiReconnectBool = true; - } - else { - wifiReconnectBool = false; - } - - // 6 - ledUsage - if(checkconfig("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/6-ledUsage") == true) { - ui->ledUsageBtn->click(); - ledUsageBool = true; - } - else { - ledUsageBool = false; - } - - // 7 - idleSleep - QString idleSleepString = readFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/7-idleSleep"); - idleSleepInt = idleSleepString.replace("\n", "").toInt(); - convertIdleSleepInt(); - - // 8 - customCase - if(checkconfig("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/8-customCase") == true) { - ui->hCustomCaseBtn->click(); - customCaseBool = true; - } - else { - customCaseBool = false; - } - - // 9 - deepSleep - if(checkconfig("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/9-deepSleep") == true) { - ui->deepSleepBtn->click(); - deepSleepBool = true; - } - else { - deepSleepBool = false; - } -} - -powerDaemonSettings::~powerDaemonSettings() -{ - delete ui; -} - -void powerDaemonSettings::on_CBSIncreaseBtn_clicked() -{ - if(cinematicBrightnessInt < 500) { - cinematicBrightnessInt = cinematicBrightnessInt + 1; - convertCinematicInt(); - } -} - -void powerDaemonSettings::on_CBSDecreaseBtn_clicked() -{ - if(cinematicBrightnessInt != 0) { - cinematicBrightnessInt = cinematicBrightnessInt - 1; - convertCinematicInt(); - } -} - -void powerDaemonSettings::on_exitBtn_clicked() -{ - // Save all to files - // 1 - cinematicBrightnessdelayMs - writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/1-cinematicBrightnessDelayMs", QString::number(cinematicBrightnessInt)); - // 2 - cpuGovernor - writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/2-cpuGovernor", ui->hCpuFreqComboBox->currentText()); - // 3 - whenChargerSleep - writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/3-whenChargerSleep", QVariant(whenChargerSleepBool).toString()); - // 4 - chargerWakeUp - writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/4-chargerWakeUp", QVariant(chargerWakeUpBool).toString()); - // 5 - wifiReconnect - writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/5-wifiReconnect", QVariant(wifiReconnectBool).toString()); - // 6 - ledUsage - writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/6-ledUsage", QVariant(ledUsageBool).toString()); - // 7 - idleSleep - writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/7-idleSleep", QString::number(idleSleepInt)); - // 8 - customCase - writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/8-customCase", QVariant(customCaseBool).toString()); - // 9 - deepSleep - writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/9-deepSleep", QVariant(deepSleepBool).toString()); - - // Notify power daemon of configuration update - writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/updateConfig", "true"); - - powerDaemonSettings::close(); -} - -void powerDaemonSettings::on_expBtn_clicked() -{ - // TODO: Implement additional warning - ui->hLabel_3->show(); - ui->hCpuFreqComboBox->show(); - - ui->hWhenChargerSleepBtn->show(); - ui->hChargerWakeUpBtn->show(); - ui->hCustomCaseBtn->show(); - - ui->expBtn->hide(); -} - -void powerDaemonSettings::on_hWhenChargerSleepBtn_clicked(bool checked) -{ - QString settingString = "suspend when charging"; - if(checked == true) { - logEnabled(settingString, className); - whenChargerSleepBool = true; - } - else { - logDisabled(settingString, className); - whenChargerSleepBool = false; - } -} - -void powerDaemonSettings::on_hChargerWakeUpBtn_clicked(bool checked) -{ - QString settingString = "ignore charger wake-up events"; - if(checked == true) { - logEnabled(settingString, className); - chargerWakeUpBool = true; - } - else { - logDisabled(settingString, className); - chargerWakeUpBool = false; - } -} - -void powerDaemonSettings::on_wifiReconnectBtn_clicked(bool checked) -{ - QString settingString = "Wi-Fi reconnection on wake-up"; - if(checked == true) { - logEnabled(settingString, className); - wifiReconnectBool = true; - } - else { - logDisabled(settingString, className); - wifiReconnectBool = false; - } -} - -void powerDaemonSettings::on_ledUsageBtn_clicked(bool checked) -{ - QString settingString = "use LED"; - if(checked == true) { - logEnabled(settingString, className); - ledUsageBool = true; - } - else { - logDisabled(settingString, className); - ledUsageBool = false; - } -} - -void powerDaemonSettings::on_idleSleepIncreaseBtn_clicked() -{ - if(idleSleepInt >= 15) { - idleSleepInt = idleSleepInt + 1; - } - else { - idleSleepInt = 15; - } - convertIdleSleepInt(); -} - -void powerDaemonSettings::on_idleSleepDecreaseBtn_clicked() { - if(idleSleepInt >= 15) { - idleSleepInt = idleSleepInt - 1; - if(idleSleepInt == 14) { - idleSleepInt = 0; - } - } - else { - idleSleepInt = 0; - } - - convertIdleSleepInt(); -} - -void powerDaemonSettings::convertIdleSleepInt() -{ - int copiedIdleSleepInt = idleSleepInt; - int minutes = 0; - int seconds = 0; - if(copiedIdleSleepInt == 0) { - ui->idleSleepLabel->setText("Never"); - return; - } - while(copiedIdleSleepInt >= 60) { - minutes = minutes + 1; - copiedIdleSleepInt = copiedIdleSleepInt - 60; - } - seconds = copiedIdleSleepInt; - - QString text; - if(minutes != 0) { - text.append(QString::number(minutes) + "m"); - } - if(seconds != 0) { - text.append(" "); - text.append(QString::number(seconds) + "s"); - } - ui->idleSleepLabel->setText(text); -} - -void powerDaemonSettings::on_hCustomCaseBtn_clicked(bool checked) -{ - QString settingString = "custom case"; - if(checked == true) { - logEnabled(settingString, className); - customCaseBool = true; - } - else { - logDisabled(settingString, className); - customCaseBool = false; - } -} - -void powerDaemonSettings::on_deepSleepBtn_clicked(bool checked) -{ - QString settingString = "deep sleep"; - if(checked == true) { - logEnabled(settingString, className); - deepSleepBool = true; - } - else { - logDisabled(settingString, className); - deepSleepBool = false; - } -} - -void powerDaemonSettings::convertCinematicInt() { - QString text = QString::number(cinematicBrightnessInt); - // To avoid moving other widgets when the value changes - text.append(" ms"); - ui->CBSLabel->setText(text); -} - -void powerDaemonSettings::on_idleSleepIncreaseMBtn_clicked() -{ - if(idleSleepInt >= 15) { - idleSleepInt = idleSleepInt + 60; - } - else { - idleSleepInt = 60; - } - convertIdleSleepInt(); -} - -void powerDaemonSettings::on_idleSleepDecreaseMBtn_clicked() -{ - if(idleSleepInt >= 60) { - idleSleepInt = idleSleepInt - 60; - if(idleSleepInt < 14) { - idleSleepInt = 0; - } - } - else { - idleSleepInt = 0; - } - - convertIdleSleepInt(); -} diff --git a/src/settings/settings.cpp b/src/settings/settings.cpp deleted file mode 100644 index bea05bf..0000000 --- a/src/settings/settings.cpp +++ /dev/null @@ -1,1183 +0,0 @@ -#include "settings.h" -#include "ui_settings.h" -#include "mainwindow.h" -#include "ui_mainwindow.h" -#include "functions.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; - -settings::settings(QWidget *parent) : - QWidget(parent), - ui(new Ui::settings) -{ - ui->setupUi(this); - settings::setFont(QFont("u001")); - ui->comboBox->setFont(QFont("u001")); - ui->tzComboBox->setFont(QFont("u001")); - ui->uiScaleNumberLabel->setFont(QFont("Inter")); - ui->aboutBtn->setFont(QFont("u001")); - ui->headerBtn->setFont(QFont("Inter")); - ui->headerLabel->setFont(QFont("Chivo")); - ui->readingSettingsBtn->setFont(QFont("Chivo")); - ui->homeSettingsBtn->setFont(QFont("Chivo")); - ui->librarySettingsBtn->setFont(QFont("Chivo")); - ui->storageSettingsBtn->setFont(QFont("Chivo")); - ui->systemSettingsBtn->setFont(QFont("Chivo")); - ui->securitySettingsBtn->setFont(QFont("Chivo")); - ui->okBtn->setFont(QFont("Inter")); - - ui->setPasscodeBtn->setProperty("type", "borderless"); - ui->okBtn->setProperty("type", "borderless"); - ui->aboutBtn->setProperty("type", "borderless"); - ui->requestLeaseBtn->setProperty("type", "borderless"); - ui->usbmsBtn->setProperty("type", "borderless"); - ui->updateBtn->setProperty("type", "borderless"); - ui->resetBtn->setProperty("type", "borderless"); - ui->showSystemInfoBtn->setProperty("type", "borderless"); - ui->generateSystemReportBtn->setProperty("type", "borderless"); - ui->checkOtaUpdateBtn->setProperty("type", "borderless"); - ui->repackBtn->setProperty("type", "borderless"); - ui->exportHighlightsBtn->setProperty("type", "borderless"); - ui->label->setStyleSheet("font-size: 10.5pt; font-weight: bold"); - ui->okBtn->setStyleSheet("font-weight: bold"); - ui->aboutBtn->setStyleSheet("font-size: 9pt"); - ui->requestLeaseBtn->setStyleSheet("font-size: 9pt"); - ui->usbmsBtn->setStyleSheet("font-size: 9pt"); - ui->updateBtn->setStyleSheet("font-size: 9pt"); - ui->resetBtn->setStyleSheet("font-size: 9pt"); - ui->showSystemInfoBtn->setStyleSheet("font-size: 9pt"); - ui->generateSystemReportBtn->setStyleSheet("font-size: 9pt"); - ui->checkOtaUpdateBtn->setStyleSheet("font-size: 9pt"); - ui->comboBox->setStyleSheet("font-size: 9pt"); - ui->tzComboBox->setStyleSheet("font-size: 9pt"); - ui->setPasscodeBtn->setStyleSheet("font-size: 9pt"); - ui->repackBtn->setStyleSheet("font-size: 9pt"); - ui->exportHighlightsBtn->setStyleSheet("font-size: 9pt"); - ui->uiScaleNumberLabel->setStyleSheet("font-size: 9pt; font-weight: bold"); - - // Getting the screen's size - sW = QGuiApplication::screens()[0]->size().width(); - sH = QGuiApplication::screens()[0]->size().height(); - - // Defining what the default icon size will be - if(global::deviceID == "n705\n") { - homeIconWidth = sW / 18; - homeIconHeight = sW / 18; - } - else { - homeIconWidth = sW / 20; - homeIconHeight = sW / 20; - } - - ui->headerStackedWidget->hide(); - - ui->headerBtn->setIcon(QIcon(":/resources/chevron-left.png")); - ui->headerBtn->setProperty("type", "borderless"); - ui->headerBtn->setStyleSheet("font-size: 9pt; font-weight: bold; padding: 15px"); - ui->headerLabel->setStyleSheet("padding: 15px"); - - ui->readingSettingsBtn->setText("\t\t\tReading"); - ui->readingSettingsBtn->setProperty("type", "borderless"); - ui->readingSettingsBtn->setStyleSheet("padding: 25px; Text-align: left"); - ui->readingSettingsBtn->setIcon(QIcon(":/resources/book.png")); - ui->readingSettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); - - ui->homeSettingsBtn->setText("\t\t\tHome"); - ui->homeSettingsBtn->setProperty("type", "borderless"); - ui->homeSettingsBtn->setStyleSheet("padding: 25px; Text-align:left"); - ui->homeSettingsBtn->setIcon(QIcon(":/resources/home.png")); - ui->homeSettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); - - ui->librarySettingsBtn->setText("\t\t\t Library"); - ui->librarySettingsBtn->setProperty("type", "borderless"); - ui->librarySettingsBtn->setStyleSheet("padding: 25px; Text-align:left"); - ui->librarySettingsBtn->setIcon(QIcon(":/resources/online-library.png")); - ui->storageSettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); - - ui->storageSettingsBtn->setText("\t\t\tStorage"); - ui->storageSettingsBtn->setProperty("type", "borderless"); - ui->storageSettingsBtn->setStyleSheet("padding: 25px; Text-align:left"); - ui->storageSettingsBtn->setIcon(QIcon(":/resources/usbms-inverted.png")); - ui->storageSettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); - - ui->systemSettingsBtn->setText("\t\t\tSystem"); - ui->systemSettingsBtn->setProperty("type", "borderless"); - ui->systemSettingsBtn->setStyleSheet("padding: 25px; Text-align:left"); - ui->systemSettingsBtn->setIcon(QIcon(":/resources/settings.png")); - ui->systemSettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); - - ui->securitySettingsBtn->setText("\t\t\tSecurity"); - ui->securitySettingsBtn->setProperty("type", "borderless"); - ui->securitySettingsBtn->setStyleSheet("padding: 25px; Text-align:left"); - ui->securitySettingsBtn->setIcon(QIcon(":/resources/lock.png")); - ui->securitySettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); - - ui->usbNetworkingCheckBox->hide(); - ui->requestLeaseBtn->hide(); - ui->usbmsBtn->hide(); - ui->label_4->hide(); - ui->label_6->hide(); - ui->updateBtn->hide(); - ui->updateLabel->hide(); - ui->enableLockscreenCheckBox->hide(); - ui->setPasscodeBtn->hide(); - ui->setPasscodeLabel->hide(); - - // Variables - defineDefaultPageSize(0); - defineDefaultPageSize(1); - - // Settings tweaking + enabling specific features whether it's running on the provided integrated OS or Kobo firmware - if(checkconfig(".config/01-demo/config") == true) { - ui->demoCheckBox->click(); - } - if(checkconfig(".config/02-clock/config") == true) { - ui->clockCheckBox->click(); - } - if(checkconfig(".config/05-quote/config") == true) { - ui->quoteCheckBox->click(); - } - - if(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n437\n" or global::deviceID == "n306\n") { - if(checkconfig(".config/10-dark_mode/config") == true) { - ui->darkModeCheckBox->click(); - } - } - else { - ui->darkModeCheckBox->hide(); - ui->darkModeCheckBox->deleteLater(); - } - - // Words number - QString wordsNumberConfigStr = readFile(".config/07-words_number/config"); - if(wordsNumberConfigStr.isEmpty()) { - if(global::deviceID == "n705\n") { - wordsNumberSaved = 120; - } - else if(global::deviceID == "n873\n") { - wordsNumberSaved = 250; - } - else { - wordsNumberSaved = 175; - } - } - else { - QString words_number = wordsNumberConfigStr; - wordsNumberSaved = wordsNumberConfigStr.toInt(); - } - ui->wordsNumberValueLabel->setText(QString::number(wordsNumberSaved)); - - - // ePUB page size - if(checkconfig(".config/13-epub_page_size/set") == true) { - QString epubPageWidthSettingStr = readFile(".config/13-epub_page_size/width"); - if(!epubPageWidthSettingStr.isEmpty()) { - QString pageWidth = epubPageWidthSettingStr; - ui->pageSizeWidthLabel->setText(pageWidth); - pageSizeWidthSaved = pageWidth.toInt(); - } - else { - // Failsafe: setting default - ui->pageSizeWidthLabel->setText(QString::number(defaultEpubPageWidth)); - pageSizeWidthSaved = defaultEpubPageWidth; - } - QString epubPageHeightSettingStr = readFile(".config/13-epub_page_size/height"); - if(!epubPageHeightSettingStr.isEmpty()) { - QString pageHeight = epubPageHeightSettingStr; - ui->pageSizeHeightLabel->setText(pageHeight); - pageSizeHeightSaved = pageHeight.toInt(); - } - else { - // Failsafe: setting default - ui->pageSizeHeightLabel->setText(QString::number(defaultEpubPageHeight)); - pageSizeHeightSaved = defaultEpubPageHeight; - } - } - else { - ui->pageSizeWidthLabel->setText(QString::number(defaultEpubPageWidth)); - ui->pageSizeHeightLabel->setText(QString::number(defaultEpubPageHeight)); - pageSizeHeightSaved = defaultEpubPageHeight; - pageSizeWidthSaved = defaultEpubPageWidth; - } - - // QTextEdit scroll bar in Reader framework - if(checkconfig(".config/14-reader_scrollbar/config") == true) { - ui->readerScrollBarCheckBox->click(); - } - - // Sticky menubar - if(checkconfig(".config/11-menubar/sticky") == true) { - ui->menuBarCheckBox->click(); - } - - // Scaling - QString dpiSettingStr = readFile(".config/09-dpi/config"); - if(dpiSettingStr.isEmpty()) { - // Writing default value depending on the device - if(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "kt\n") { - writeFile(".config/09-dpi/config", "160"); - } - else if(global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n306\n" or global::deviceID == "emu\n") { - writeFile(".config/09-dpi/config", "195"); - } - else if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { - writeFile(".config/09-dpi/config", "275"); - } - else if(global::deviceID == "n873\n") { - writeFile(".config/09-dpi/config", "285"); - } - else { - writeFile(".config/09-dpi/config", "187"); - } - } - else { - int dpi_number = dpiSettingStr.toInt(); - if(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "kt\n") { - if(dpi_number == 160) { - ui->uiScalingSlider->setValue(0); - } - if(dpi_number == 187) { - ui->uiScalingSlider->setValue(1); - } - if(dpi_number == 200) { - ui->uiScalingSlider->setValue(2); - } - } - else if(global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "emu\n") { - if(dpi_number == 195) { - ui->uiScalingSlider->setValue(0); - } - if(dpi_number == 210) { - ui->uiScalingSlider->setValue(1); - } - if(dpi_number == 225) { - ui->uiScalingSlider->setValue(2); - } - } - else if(global::deviceID == "n306\n") { - if(dpi_number == 212) { - ui->uiScalingSlider->setValue(0); - } - if(dpi_number == 227) { - ui->uiScalingSlider->setValue(1); - } - if(dpi_number == 242) { - ui->uiScalingSlider->setValue(3); - } - } - else if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { - if(dpi_number == 275) { - ui->uiScalingSlider->setValue(0); - } - if(dpi_number == 290) { - ui->uiScalingSlider->setValue(1); - } - if(dpi_number == 305) { - ui->uiScalingSlider->setValue(2); - } - } - else if(global::deviceID == "n873\n") { - if(dpi_number == 285) { - ui->uiScalingSlider->setValue(0); - } - if(dpi_number == 300) { - ui->uiScalingSlider->setValue(1); - } - if(dpi_number == 315) { - ui->uiScalingSlider->setValue(2); - } - } - else { - if(dpi_number == 160) { - ui->uiScalingSlider->setValue(0); - } - if(dpi_number == 187) { - ui->uiScalingSlider->setValue(1); - } - if(dpi_number == 200) { - ui->uiScalingSlider->setValue(2); - } - } - } - - // Refresh - QString refreshSettingStr = readFile(".config/04-book/refresh"); - if(refreshSettingStr.isEmpty()) { - // Set default option, 3 - writeFile(".config/04-book/refresh", "3"); - ui->comboBox->setCurrentText("3 pages"); - } - else { - int refreshInt = refreshSettingStr.toInt(); - if(refreshInt == -1) { - ui->comboBox->setCurrentText("Never refresh"); - } - if(refreshInt == 0) { - ui->comboBox->setCurrentText("Every page"); - } - if(refreshInt == 1) { - ui->comboBox->setCurrentText("1 page"); - } - if(refreshInt == 2) { - ui->comboBox->setCurrentText("2 pages"); - } - if(refreshInt == 3) { - ui->comboBox->setCurrentText("3 pages"); - } - if(refreshInt == 4) { - ui->comboBox->setCurrentText("4 pages"); - } - if(refreshInt == 5) { - ui->comboBox->setCurrentText("5 pages"); - } - if(refreshInt == 6) { - ui->comboBox->setCurrentText("6 pages"); - } - } - - // Lock screen - if(checkconfig(".config/12-lockscreen/config") == true) { - ui->enableLockscreenCheckBox->click(); - } - - // Global reading settings - if(checkconfig(".config/16-global_reading_settings/config") == true) { - ui->globalReadingSettingsCheckBox->click(); - } - - // Encrypted storage - if(checkconfig(".config/18-encrypted_storage/status") == true) { - ui->enableEncryptedStorageCheckBox->click(); - } - else { - // Next interaction will be by the user - enableEncryptedStorageUserChange = true; - } - if(getEncFSStatus() == false) { - ui->repackLabel->hide(); - ui->repackBtn->hide(); - } - - // Timezone - ui->tzComboBox->addItems(QStringList(readFile(":/resources/tzlist").split("\n", Qt::SkipEmptyParts))); - timezone_not_user_change = true; - if(readFile(".config/19-timezone/config-name").isEmpty()) { - ui->tzComboBox->setCurrentText("UTC"); - } - else { - ui->tzComboBox->setCurrentText(readFile(".config/19-timezone/config-name")); - } - - // Local library folders support - if(checkconfig(".config/21-local_library/folders") == true) { - ui->localLibraryShowFoldersCheckBox->click(); - } - - // USB show dialog - if(checkconfig(".config/22-usb/show-dialog") == true) { - ui->usbmsDialogBox->click(); - } - - // Automatic updates - if(checkconfig(".config/23-updates/check-updates") == true) { - ui->autoCheckUpdatesBox->click(); - } - - // 'Export highlights' button - if(!QFile::exists(global::localLibrary::highlightsDatabasePath) or readFile(global::localLibrary::highlightsDatabasePath).isEmpty()) { - ui->exportHighlightsBtn->setEnabled(false); - } - - if(readFile(".config/12-lockscreen/background") == "blank") { - ui->lockscreenBackgroundComboBox->setCurrentIndex(0); - } - else if(readFile(".config/12-lockscreen/background") == "screenSaver") { - ui->lockscreenBackgroundComboBox->setCurrentIndex(1); - } - else if(readFile(".config/12-lockscreen/background") == "background") { - ui->lockscreenBackgroundComboBox->setCurrentIndex(2); - } - - if(checkconfig("/opt/inkbox_genuine") == true) { - // Enforcing security policy if the user has not rooted the device - if(checkconfig("/external_root/opt/root/rooted") == true) { - ui->usbNetworkingCheckBox->show(); - if(checkconfig("/external_root/boot/flags/USBNET_ENABLE")) { - ui->usbNetworkingCheckBox->click(); - } - ui->requestLeaseBtn->show(); - ui->label_4->show(); - } - else { - ui->usbNetworkingCheckBox->hide(); - ui->requestLeaseBtn->hide(); - ui->label_4->hide(); - } - ui->enableLockscreenCheckBox->show(); - ui->setPasscodeBtn->show(); - ui->setPasscodeLabel->show(); - ui->usbmsBtn->show(); - ui->label_6->show(); - } - else { - ui->label_8->setText("Reset InkBox"); - } - - if(global::device::isWifiAble == false) { - ui->checkOtaUpdateLabel->hide(); - ui->checkOtaUpdateBtn->hide(); - ui->checkOtaUpdateLabel->deleteLater(); - ui->checkOtaUpdateBtn->deleteLater(); - ui->checkOtaUpdateGridLayout->deleteLater(); - } - - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); -} - -settings::~settings() -{ - delete ui; -} - -void settings::on_okBtn_clicked() { - saveDeferredSettings(); - - // Prevent potential unknown damage launching via shell script this could do - if(launch_sh == true) { - if(ui_enable_changed == true) { - ui_enable_changed = false; - global::settings::settingsRebootDialog = true; - generalDialogWindow = new generalDialog(); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - } - else { - QProcess process; - process.startDetached("inkbox.sh", QStringList()); - qApp->quit(); - } - } - else { - QProcess process; - process.startDetached("inkbox", QStringList()); - qApp->quit(); - } -} - -void settings::saveDeferredSettings() { - // Save things - writeFile(".config/07-words_number/config", QString::number(wordsNumberSaved)); - log("Set text files words number to " + QString::number(wordsNumberSaved), className); - - writeFile(".config/13-epub_page_size/width", QString::number(pageSizeWidthSaved)); - writeFile(".config/13-epub_page_size/set", "true"); - - writeFile(".config/13-epub_page_size/height", QString::number(pageSizeHeightSaved)); - writeFile(".config/13-epub_page_size/set", "true"); - - // Notify power daemon of a potential configuration update - writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/updateConfig", "true"); -} - -void settings::on_aboutBtn_clicked() -{ - log("Showing About message box", className); - if(checkconfig("/opt/inkbox_genuine") == true) { - QString aboutmsg = "InkBox is an open-source, Qt-based eBook reader. It aims to bring you the latest Qt features while being also fast and responsive."; - aboutmsg.prepend(""); - aboutmsg.append("

InkBox "); - aboutmsg.append(readFile("/external_root/opt/isa/version")); - aboutmsg.append("
"); - QMessageBox::information(this, tr("Information"), aboutmsg); - } - else { - QMessageBox::information(this, tr("About"), tr("InkBox is an open-source Qt-based eBook reader. It aims to bring you the latest Qt features while being also fast and responsive.")); - } -} - -void settings::on_demoCheckBox_toggled(bool checked) -{ - QString settingString = "change MainWindow label demo"; - // Write to config file - if(checked == true) { - logEnabled(settingString, className); - checked_box = true; - writeconfig(".config/01-demo/config", "InkboxChangeLabel="); - } - else { - logDisabled(settingString, className); - checked_box = false; - writeconfig(".config/01-demo/config", "InkboxChangeLabel="); - } -} - -void settings::on_clockCheckBox_toggled(bool checked) -{ - QString settingString = "clock with seconds"; - // Write to config file - if(checked == true) { - logEnabled(settingString, className); - checked_box = true; - writeconfig(".config/02-clock/config", "ClockShowSeconds="); - } - else { - logDisabled(settingString, className); - checked_box = false; - writeconfig(".config/02-clock/config", "ClockShowSeconds="); - } -} - -void settings::on_quoteCheckBox_toggled(bool checked) -{ - QString settingString = "disable show quotes"; - if(checked == true) { - logEnabled(settingString, className); - checked_box = true; - writeconfig(".config/05-quote/config", "DisableQuote="); - } - else { - logDisabled(settingString, className); - checked_box = false; - writeconfig(".config/05-quote/config", "DisableQuote="); - } -} - -void settings::on_requestLeaseBtn_clicked() -{ - log("Requesting DHCP lease", className); - QString prog ("chroot"); - QStringList args; - args << "/external_root" << "/usr/sbin/dhclient"; - QProcess *proc = new QProcess(); - proc->start(prog, args); - proc->waitForFinished(); - proc->deleteLater(); -} - -void settings::on_usbmsBtn_clicked() -{ - usbms_launch(); -} - -void settings::on_updateBtn_clicked() -{ - log("'Update' button clicked", className); - writeFile("/mnt/onboard/onboard/.inkbox/can_really_update", "true\n"); - writeFile("/external_root/opt/update/will_update", "true\n"); - writeFile("/external_root/boot/flags/WILL_UPDATE", "true\n"); - QString prog ("/sbin/reboot"); - QStringList args; - QProcess *proc = new QProcess(); - proc->start(prog, args); - proc->waitForFinished(); - proc->deleteLater(); -} - -void settings::on_darkModeCheckBox_toggled(bool checked) -{ - QString settingString = "dark mode"; - if(checked == true) { - logEnabled(settingString, className); - writeFile(".config/10-dark_mode/config", "true"); - writeFile("/tmp/invertScreen", "y"); - } - else { - logDisabled(settingString, className); - writeFile(".config/10-dark_mode/config", "false"); - writeFile("/tmp/invertScreen", "n"); - } -} - -void settings::on_uiScalingSlider_valueChanged(int value) -{ - log("Setting DPI level to " + QString::number(value), className); - if(value == 0) { - if(global::deviceID == "n705\n") { - writeFile(".config/09-dpi/config", "187"); - } - if(global::deviceID == "n905\n" or global::deviceID == "kt\n") { - writeFile(".config/09-dpi/config", "160"); - } - if(global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "emu\n") { - writeFile(".config/09-dpi/config", "195"); - } - if(global::deviceID == "n306\n") { - writeFile(".config/09-dpi/config", "212"); - } - if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { - writeFile(".config/09-dpi/config", "275"); - } - if(global::deviceID == "n873\n") { - writeFile(".config/09-dpi/config", "285"); - } - } - if(value == 1) { - if(global::deviceID == "n705\n") { - writeFile(".config/09-dpi/config", "214"); - } - if(global::deviceID == "n905\n" or global::deviceID == "kt\n") { - writeFile(".config/09-dpi/config", "187"); - } - if(global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "emu\n") { - writeFile(".config/09-dpi/config", "210"); - } - if(global::deviceID == "n306\n") { - writeFile(".config/09-dpi/config", "227"); - } - if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { - writeFile(".config/09-dpi/config", "290"); - } - if(global::deviceID == "n873\n") { - writeFile(".config/09-dpi/config", "300"); - } - } - if(value == 2) { - if(global::deviceID == "n705\n") { - writeFile(".config/09-dpi/config", "227"); - } - if(global::deviceID == "n905\n" or global::deviceID == "kt\n") { - writeFile(".config/09-dpi/config", "200"); - } - if(global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "emu\n") { - writeFile(".config/09-dpi/config", "225"); - } - if(global::deviceID == "n306\n") { - writeFile(".config/09-dpi/config", "242"); - } - if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { - writeFile(".config/09-dpi/config", "305"); - } - if(global::deviceID == "n873\n") { - writeFile(".config/09-dpi/config", "315"); - } - } - - // Making sense for the user - value = value + 1; - QString value_qstr = QString::number(value); - ui->uiScaleNumberLabel->setText(value_qstr); - - if(not_user_change == true) { - launch_sh = false; - // If value is changed, it will launch inkbox.sh detached when "OK" is pressed. - not_user_change = false; - } - else { - // This is supposed to happen when the user clicks the slider, and not the software. Refer to setValue() methods for uiScalingSlider in main(). - launch_sh = true; - } -} - -void settings::on_menuBarCheckBox_toggled(bool checked) -{ - QString settingString = "sticky menu bar"; - if(checked == true) { - logEnabled(settingString, className); - checked_box = true; - writeconfig(".config/11-menubar/sticky", "StickyMenuBar="); - } - else { - logDisabled(settingString, className); - checked_box = false; - writeconfig(".config/11-menubar/sticky", "StickyMenuBar="); - } -} - -void settings::on_comboBox_currentIndexChanged(const QString &arg1) -{ - log("Setting page refresh setting to " + arg1, className); - if(arg1 == "Every page") { - writeFile(".config/04-book/refresh", "0"); - } - if(arg1 == "1 page") { - writeFile(".config/04-book/refresh", "1"); - } - if(arg1 == "2 pages") { - writeFile(".config/04-book/refresh", "2"); - } - if(arg1 == "3 pages") { - writeFile(".config/04-book/refresh", "3"); - } - if(arg1 == "4 pages") { - writeFile(".config/04-book/refresh", "4"); - } - if(arg1 == "5 pages") { - writeFile(".config/04-book/refresh", "5"); - } - if(arg1 == "6 pages") { - writeFile(".config/04-book/refresh", "6"); - } - if(arg1 == "Never refresh") { - writeFile(".config/04-book/refresh", "-1"); - } -} - -void settings::on_resetBtn_clicked() -{ - log("'Reset' button clicked", className); - // We write to a temporary file to show a "Reset" prompt - writeFile("/inkbox/resetDialog", "true"); - - // We setup the dialog - log("Showing reset dialog", className); - generalDialogWindow = new generalDialog(); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); -} - -void settings::on_setPasscodeBtn_clicked() -{ - log("'Set passcode' button clicked", className); - log("Launching lockscreen binary", className); - saveDeferredSettings(); - writeFile("/tmp/setPasscode", "true"); - QProcess process; - process.startDetached("lockscreen", QStringList()); - qApp->quit(); -} - -void settings::on_enableLockscreenCheckBox_toggled(bool checked) -{ - QString settingString = "lockscreen"; - if(checked == true) { - logEnabled(settingString, className); - writeFile(".config/12-lockscreen/config", "true"); - // Launching passcode setup wizard if none seems to be set at the moment - if(!(QFile::exists(".config/12-lockscreen/passcode") && QFile::exists(".config/12-lockscreen/salt"))) { - ui->setPasscodeBtn->click(); - } - } - else { - logDisabled(settingString, className); - writeFile(".config/12-lockscreen/config", "false"); - } -} - -void settings::on_showSystemInfoBtn_clicked() -{ - log("'Show system info' button clicked", className); - getSystemInfo(); - global::usbms::usbmsDialog = false; - global::text::textBrowserContents = global::systemInfoText; - global::text::textBrowserDialog = true; - - // Show a system info dialog - log("Showing system info dialog", className); - generalDialogWindow = new generalDialog(); - generalDialogWindow->yIncrease = determineYIncrease(); - generalDialogWindow->increaseSize(); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); -} - -void settings::on_readerScrollBarCheckBox_toggled(bool checked) -{ - QString settingString = "scrollbar display if necessary"; - if(checked == true) { - logEnabled(settingString, className); - writeFile(".config/14-reader_scrollbar/config", "true"); - } - else { - logDisabled(settingString, className); - writeFile(".config/14-reader_scrollbar/config", "false"); - } -} - -void settings::brightnessDown() { - cinematicBrightness(0, 1); -} - -void settings::on_globalReadingSettingsCheckBox_toggled(bool checked) -{ - QString settingString = "global reading settings"; - if(checked == true) { - logEnabled(settingString, className); - checked_box = true; - writeconfig(".config/16-global_reading_settings/config", "GlobalReadingSettings="); - } - else { - logDisabled(settingString, className); - checked_box = false; - writeconfig(".config/16-global_reading_settings/config", "GlobalReadingSettings="); - } -} - -void settings::on_checkOtaUpdateBtn_clicked() -{ - log("'Check for OTA update' button clicked", className); - if(testPing() == 0 or global::deviceID == "emu\n") { - launchOtaUpdater(); - } - else { - emit showToast("Wi-Fi connection error"); - } -} - -void settings::openUpdateDialog() { - log("Showing update dialog", className); - global::mainwindow::updateDialog = true; - // Write to a temporary file to show an "Update" prompt - writeFile("/inkbox/updateDialog", "true"); - - // Show the dialog - generalDialogWindow = new generalDialog(this); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - connect(generalDialogWindow, SIGNAL(showToast(QString)), SLOT(showToastNative(QString))); - connect(generalDialogWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToastNative())); - QApplication::processEvents(); -} - -void settings::launchOtaUpdater() { - global::toast::modalToast = true; - global::toast::indefiniteToast = true; - emit showToast("Checking for updates"); - otaManagerWindow = new otaManager(this); - connect(otaManagerWindow, SIGNAL(canOtaUpdate(bool)), SLOT(openUpdateDialogOTA(bool))); - otaManagerWindow->setAttribute(Qt::WA_DeleteOnClose); -} - -void settings::openUpdateDialogOTA(bool open) { - emit closeIndefiniteToast(); - if(open == true) { - global::otaUpdate::isUpdateOta = true; - openUpdateDialog(); - } - else { - emit showToast("No update available"); - } -} - -void settings::showToastNative(QString messageToDisplay) { - emit showToast(messageToDisplay); -} - -void settings::closeIndefiniteToastNative() { - emit closeIndefiniteToast(); -} - -void settings::usbms_launch() -{ - log("Showing USBMS splash", className); - global::usbms::launchUsbms = true; - - usbmsWindow = new usbmsSplash(); - usbmsWindow->setAttribute(Qt::WA_DeleteOnClose); - usbmsWindow->setGeometry(QRect(QPoint(0,0), screen()->geometry ().size())); - usbmsWindow->show(); -} - -void settings::quit_restart() { - // If existing, cleaning bookconfig_mount mountpoint - writeFile("/opt/ibxd", "bookconfig_unmount\n"); - - // Restarting InkBox - QProcess process; - process.startDetached("inkbox", QStringList()); - qApp->quit(); -} - -void settings::on_enableEncryptedStorageCheckBox_toggled(bool checked) -{ - QString settingString = "encrypted storage"; - if(checked == true) { - if(enableEncryptedStorageUserChange == true) { - logEnabled(settingString, className); - setDefaultWorkDir(); - writeFile(".config/18-encrypted_storage/initial_setup_done", "false"); - writeFile(".config/18-encrypted_storage/status", "true"); - if(QFile::exists(".config/18-encrypted_storage/storage_list")) { - QFile::remove(".config/18-encrypted_storage/storage_list"); - } - global::settings::settingsRebootDialog = true; - global::encfs::enableStorageEncryptionDialog = true; - generalDialogWindow = new generalDialog(this); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - } - else { - enableEncryptedStorageUserChange = true; - } - } - else { - logDisabled(settingString, className); - global::encfs::disableStorageEncryptionDialog = true; - generalDialogWindow = new generalDialog(this); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - connect(generalDialogWindow, SIGNAL(cancelDisableStorageEncryption()), SLOT(cancelDisableStorageEncryption())); - connect(generalDialogWindow, SIGNAL(disableStorageEncryption()), SLOT(disableStorageEncryption())); - } -} - -void settings::disableStorageEncryption() { - log("Disabling encrypted storage", className); - setDefaultWorkDir(); - writeFile("/external_root/run/encfs_stop_cleanup", "true"); - writeFile("/opt/ibxd", "encfs_stop\n"); - QThread::msleep(5000); - - writeFile(".config/18-encrypted_storage/status", "false"); - QFile::remove(".config/18-encrypted_storage/initial_setup_done"); - QFile::remove(".config/18-encrypted_storage/storage_list"); - QFile::remove("/mnt/onboard/onboard/data.encfs"); - - QDir dumpDir("/mnt/onboard/onboard/encfs-dropbox"); - dumpDir.removeRecursively(); - QDir decDir("/mnt/onboard/onboard/encfs-decrypted"); - decDir.removeRecursively(); - - global::settings::settingsRebootDialog = true; - generalDialogWindow = new generalDialog(this); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); -} - -void settings::cancelDisableStorageEncryption() { - enableEncryptedStorageUserChange = false; - ui->enableEncryptedStorageCheckBox->click(); -} - -void settings::on_repackBtn_clicked() -{ - log("'Repack encrypted storage' button clicked", className); - QDir dir("/mnt/onboard/onboard/encfs-dropbox"); - if(dir.isEmpty()) { - log("Showing encrypted storage repack error dialog ('encfs-dropbox' directory is empty)", className); - global::encfs::errorNoBooksInDropboxDialog = true; - generalDialogWindow = new generalDialog(this); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - } - else { - log("Showing encrypted storage repack dialog", className); - writeFile("/external_root/run/encfs_repack", "true"); - quit_restart(); - } -} - -void settings::on_generateSystemReportBtn_clicked() -{ - log("'Generate system report' button clicked", className); - log("Generating system report", className); - writeFile("/opt/ibxd", "generate_system_report\n"); - while(true) { - if(QFile::exists("/inkbox/systemReportDone")) { - if(checkconfig("/inkbox/systemReportDone") == true) { - QFile::remove(global::localLibrary::databasePath); - emit showToast("System report generated successfully"); - } - else { - emit showToast("Error in generating system report"); - } - QFile::remove("/inkbox/systemReportDone"); - break; - } - } -} - -void settings::on_tzComboBox_currentTextChanged(const QString &arg1) -{ - if(timezone_not_user_change == true) { - timezone_not_user_change = false; - } - else { - log("Setting timezone to " + arg1, className); - setDefaultWorkDir(); - // Preventing unnecessary (e)MMC writes - if(readFile(".config/19-timezone/config-name") != arg1) { - QProcess::execute("ln", QStringList() << "-sf" << "/usr/share/zoneinfo/" + arg1 << ".config/19-timezone/config"); - writeFile(".config/19-timezone/config-name", arg1); - writeFile("/opt/ibxd", "gui_remount_localtime\n"); - QThread::msleep(500); - } - } -} - -void settings::on_exportHighlightsBtn_clicked() -{ - QJsonObject jsonObject = readHighlightsDatabase(); - writeFile("/mnt/onboard/onboard/highlights-" + QDateTime::currentDateTime().toString("dd-MM-yy_hh.mm.ss") + ".json", QJsonDocument(jsonObject).toJson()); - showToast("Highlights exported successfully"); -} - -void settings::on_wordsNumberIncBtn_clicked() -{ - wordsNumberSaved = wordsNumberSaved + 5; - ui->wordsNumberValueLabel->setText(QString::number(wordsNumberSaved)); - -} - -void settings::on_wordsNumberDecBtn_clicked() -{ - if(wordsNumberSaved > 10) { - wordsNumberSaved = wordsNumberSaved - 5; - ui->wordsNumberValueLabel->setText(QString::number(wordsNumberSaved)); - } -} - -void settings::on_pageSizeHeightDecBtn_clicked() -{ - if(pageSizeHeightSaved > 100) { - pageSizeHeightSaved = pageSizeHeightSaved - 5; - ui->pageSizeHeightLabel->setText(QString::number(pageSizeHeightSaved)); - } -} - -void settings::on_pageSizeHeightIncBtn_clicked() -{ - pageSizeHeightSaved = pageSizeHeightSaved + 5; - ui->pageSizeHeightLabel->setText(QString::number(pageSizeHeightSaved)); -} - -void settings::on_pageSizeWidthDecBtn_clicked() -{ - if(pageSizeWidthSaved > 100) { - pageSizeWidthSaved = pageSizeWidthSaved - 5; - ui->pageSizeWidthLabel->setText(QString::number(pageSizeWidthSaved)); - } -} - -void settings::on_pageSizeWidthIncBtn_clicked() -{ - pageSizeWidthSaved = pageSizeWidthSaved + 5; - ui->pageSizeWidthLabel->setText(QString::number(pageSizeWidthSaved)); -} - -void settings::on_localLibraryShowFoldersCheckBox_toggled(bool checked) -{ - QString settingString = "local library folders support"; - if(checked == true) { - logEnabled(settingString, className); - checked_box = true; - writeconfig(".config/21-local_library/folders", "Folders="); - } - else { - logDisabled(settingString, className); - checked_box = false; - writeconfig(".config/21-local_library/folders", "Folders="); - } -} - - -void settings::on_usbmsDialogBox_clicked(bool checked) -{ - QString settingString = "USB Mass Storage dialog display"; - if(checked == true) { - logEnabled(settingString, className); - writeFile(".config/22-usb/show-dialog", "true"); - } - else { - logDisabled(settingString, className); - writeFile(".config/22-usb/show-dialog", "false"); - } -} - -void settings::on_autoCheckUpdatesBox_clicked(bool checked) -{ - QString settingString = "automatic updates checking"; - if(checked == true) { - logEnabled(settingString, className); - writeFile(".config/23-updates/check-updates", "true"); - } - else { - logDisabled(settingString, className); - writeFile(".config/23-updates/check-updates", "false"); - } -} - -void settings::on_lockscreenBackgroundComboBox_currentTextChanged(const QString &arg1) -{ - if(arg1 == "Blank") { - writeFile(".config/12-lockscreen/background", "blank"); - log("Set lockscreen background to 'blank'", className); - } - else if(arg1 == "Screensaver picture") { - writeFile(".config/12-lockscreen/background", "screenSaver"); - log("Set lockscreen background to 'screenSaver'", className); - } - else if(arg1 == "Device's screen") { - writeFile(".config/12-lockscreen/background", "background"); - log("Set lockscreen background to 'background'", className); - } -} - -void settings::on_settingsStackedWidget_currentChanged(int arg1) -{ - if(ui->settingsStackedWidget->currentIndex() != 0) { - ui->headerLabel->setText(ui->settingsStackedWidget->currentWidget()->objectName()); - ui->headerStackedWidget->show(); - } - else { - ui->headerStackedWidget->hide(); - } -} - - -void settings::on_readingSettingsBtn_clicked() -{ - log("'Reading settings' button clicked", className); - ui->settingsStackedWidget->setCurrentIndex(1); -} - - -void settings::on_homeSettingsBtn_clicked() -{ - log("'Home settings' button clicked", className); - ui->settingsStackedWidget->setCurrentIndex(2); -} - - -void settings::on_librarySettingsBtn_clicked() -{ - log("'Library settings' button clicked", className); - ui->settingsStackedWidget->setCurrentIndex(3); -} - - -void settings::on_storageSettingsBtn_clicked() -{ - log("'Storage settings' button clicked", className); - ui->settingsStackedWidget->setCurrentIndex(4); -} - - -void settings::on_systemSettingsBtn_clicked() -{ - log("'System settings' button clicked", className); - ui->settingsStackedWidget->setCurrentIndex(5); -} - - -void settings::on_securitySettingsBtn_clicked() -{ - log("'Security settings' button clicked", className); - ui->settingsStackedWidget->setCurrentIndex(6); -} - - -void settings::on_headerBtn_clicked() -{ - // "Home" button - log("'Home' button clicked", className); - ui->settingsStackedWidget->setCurrentIndex(0); -} - -void settings::on_usbNetworkingCheckBox_toggled(bool checked) -{ - if(checked) { - writeFile("/external_root/boot/flags/USBNET_ENABLE", "true"); - writeFile("/opt/ibxd", "usbnet_start\n"); - } - else { - writeFile("/external_root/boot/flags/USBNET_ENABLE", "false"); - writeFile("/opt/ibxd", "usbnet_stop\n"); - } -} diff --git a/src/settings/settingschooser.cpp b/src/settings/settingschooser.cpp deleted file mode 100644 index 13af7d0..0000000 --- a/src/settings/settingschooser.cpp +++ /dev/null @@ -1,110 +0,0 @@ -#include "settingschooser.h" -#include "ui_settingschooser.h" -#include "functions.h" -#include "powerdaemonsettings.h" - -#include -#include - -settingsChooser::settingsChooser(QWidget *parent) : - QWidget(parent), - ui(new Ui::settingsChooser) -{ - ui->setupUi(this); - - // Stylesheet - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - // UI tweaks - if(checkconfig("/opt/inkbox_kobox_support") == false) { - ui->koboxSettingsBtn->hide(); - ui->line_3->hide(); - } - - // Getting the screen's size - sW = QGuiApplication::screens()[0]->size().width(); - sH = QGuiApplication::screens()[0]->size().height(); - - // Defining what the default icon size will be - if(global::deviceID == "n705\n") { - homeIconWidth = sW / 18; - homeIconHeight = sW / 18; - } - else { - homeIconWidth = sW / 20; - homeIconHeight = sW / 20; - } - - ui->inkboxSettingsBtn->setProperty("type", "borderless"); - ui->koboxSettingsBtn->setProperty("type", "borderless"); - ui->powerSettingsBtn->setProperty("type", "borderless"); - - if(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "kt\n") { - ui->inkboxSettingsBtn->setStyleSheet("padding: 20px; Text-align: left"); - ui->koboxSettingsBtn->setStyleSheet("padding: 20px; Text-align: left"); - ui->powerSettingsBtn->setStyleSheet("padding: 20px; Text-align: left"); - } - else if(global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n306\n" or global::deviceID == "emu\n") { - ui->inkboxSettingsBtn->setStyleSheet("padding: 25px; Text-align: left"); - ui->koboxSettingsBtn->setStyleSheet("padding:25px; Text-align: left"); - ui->powerSettingsBtn->setStyleSheet("padding:25px; Text-align: left"); - } - else { - ui->inkboxSettingsBtn->setStyleSheet("padding: 40px; Text-align: left"); - ui->koboxSettingsBtn->setStyleSheet("padding: 40px; Text-align: left"); - ui->powerSettingsBtn->setStyleSheet("padding: 40px; Text-align: left"); - } - - ui->inkboxSettingsBtn->setText("\t\t\tInkBox settings"); - ui->koboxSettingsBtn->setText("\t\t\tKoBox settings"); - ui->powerSettingsBtn->setText("\t\t\tPower settings"); - - ui->inkboxSettingsBtn->setIcon(QIcon(":/resources/settings.png")); - ui->inkboxSettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); - ui->koboxSettingsBtn->setIcon(QIcon(":/resources/X11.png")); - ui->koboxSettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); - ui->powerSettingsBtn->setIcon(QIcon(":/resources/power.png")); - ui->powerSettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); -} - -settingsChooser::~settingsChooser() -{ - delete ui; -} - -void settingsChooser::on_inkboxSettingsBtn_clicked() -{ - log("Launching InkBox Settings", className); - settingsWindow = new settings(); - settingsWindow->setAttribute(Qt::WA_DeleteOnClose); - connect(settingsWindow, SIGNAL(showToast(QString)), SLOT(showToastNative(QString))); - connect(settingsWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToastNative())); - settingsWindow->showFullScreen(); -} - -void settingsChooser::on_koboxSettingsBtn_clicked() -{ - log("Launching KoBox Settings", className); - koboxSettingsWindow = new koboxSettings(); - koboxSettingsWindow->setAttribute(Qt::WA_DeleteOnClose); - koboxSettingsWindow->showFullScreen(); -} - -void settingsChooser::on_powerSettingsBtn_clicked() -{ - log("Launching Power Daemon Settings", className); - powerDaemonSettings * powerSettingsWindow = new powerDaemonSettings(); - powerSettingsWindow->setAttribute(Qt::WA_DeleteOnClose); - powerSettingsWindow->showFullScreen(); -} - -void settingsChooser::showToastNative(QString messageToDisplay) { - emit showToast(messageToDisplay); -} - -void settingsChooser::closeIndefiniteToastNative() { - emit closeIndefiniteToast(); -} diff --git a/src/splash/alert.cpp b/src/splash/alert.cpp deleted file mode 100644 index 832e87d..0000000 --- a/src/splash/alert.cpp +++ /dev/null @@ -1,167 +0,0 @@ -#include "alert.h" -#include "ui_alert.h" -#include "functions.h" - -#include -#include -#include -#include - -alert::alert(QWidget *parent) : - QWidget(parent), - ui(new Ui::alert) -{ - ui->setupUi(this); - ui->messageLabel->setFont(QFont("u001")); - - // Getting the screen's size - float sW = QGuiApplication::screens()[0]->size().width(); - float sH = QGuiApplication::screens()[0]->size().height(); - // Defining what the "Alert" icon size will be - float stdIconWidth = sW / 1.7; - float stdIconHeight = sH / 1.7; - - // General stylesheet - QFile stylesheetFile(":/resources/eink-dark.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - // Default icon in case none of the conditions below are met - QPixmap pixmap(":/resources/alert.png"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->alertIconLabel->setPixmap(scaledPixmap); - - // Checking if the update's signature is untrusted. The signature error will always take precedence over the downgrade one (c.f. update.sh script) - if(checkconfig("/external_root/boot/flags/ALERT_SIGN") == true) { - QPixmap pixmap(":/resources/alert.png"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->alertIconLabel->setPixmap(scaledPixmap); - - signatureError = true; - log("Displaying signature error alert splash", className); - ui->securityLabel->setText("Failed to update InkBox."); - ui->messageLabel->setText("The digital signature of the update is untrusted.\nFor security reasons, it cannot be installed."); - ui->stackedWidget->setCurrentIndex(1); - } - if(checkconfig("/external_root/boot/flags/ALERT_DOWNGRADE") == true) { - QPixmap pixmap(":/resources/alert.png"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->alertIconLabel->setPixmap(scaledPixmap); - - log("Displaying downgrade error alert splash", className); - downgradeError = true; - ui->securityLabel->setText("Failed to update InkBox."); - ui->messageLabel->setText("An error occured during the update process.\nThe update package's version is lower than the actual installed version."); - ui->stackedWidget->setCurrentIndex(1); - } - if(global::encfs::lockdown == true) { - ui->stackedWidget->setVisible(false); - ui->stackedWidget->deleteLater(); - QPixmap pixmap(":/resources/alert.png"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->alertIconLabel->setPixmap(scaledPixmap); - - ui->warningLabel->setText("Fatal error"); - ui->securityLabel->setText("Device lockdown"); - log(global::encfs::lockdownMessage, className); - QString message = "Due to multiple incorrect passphrase attempts, this device is locked down until\n" + global::encfs::unlockTime + "\nand won't boot."; - ui->messageLabel->setText(message); - poweroff(false); - QTimer::singleShot(1000, this, SLOT(quit())); - } - if(global::battery::showCriticalBatteryAlert == true) { - global::battery::showCriticalBatteryAlert = false; - ui->stackedWidget->setVisible(false); - ui->stackedWidget->deleteLater(); - - QPixmap pixmap(":/resources/battery_alert.png"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->alertIconLabel->setPixmap(scaledPixmap); - - log("Displaying critical battery alert splash", className); - criticalBattery = true; - ui->warningLabel->setText("Please charge your eReader."); - ui->securityLabel->setText("The battery's charge level is critical."); - ui->messageLabel->setText("To prevent damage, your device has been turned off.\nPlease consider charging it."); - // The Mini (N705) has a higher DPI and otherwise the text doesn't fit - if(global::deviceID == "n705\n") { - ui->warningLabel->setStyleSheet("QLabel { background-color : black; color : white; font-size: 14pt }"); - } - else { - ui->warningLabel->setStyleSheet("QLabel { background-color : black; color : white; font-size: 16pt }"); - } - poweroff(false); - QTimer::singleShot(1000, this, SLOT(quit())); - } - - ui->messageLabel->setStyleSheet("QLabel { background-color : black; color : white; font-size: 10pt }"); - ui->securityLabel->setStyleSheet("QLabel { background-color : black; color : white; font-size: 11pt }"); - ui->continueBtn->setProperty("type", "borderless"); - ui->resetBtn->setProperty("type", "borderless"); - ui->continueBtn->setStyleSheet("padding: 20px"); - ui->resetBtn->setStyleSheet("padding: 20px"); - ui->continue2Btn->setProperty("type", "borderless"); - ui->continue2Btn->setStyleSheet("padding: 20px"); -} - -alert::~alert() -{ - delete ui; -} - -void alert::on_continueBtn_clicked() -{ - // We continue anyway and re-set the ALERT flag - writeFile("/external_root/boot/flags/ALERT", "false\n"); - writeFile("/external_root/boot/flags/ALERT_SIGN", "false\n"); - updateReset(); - QProcess process; - process.startDetached("inkbox", QStringList()); - qApp->quit(); -} - -void alert::on_resetBtn_clicked() -{ - // We set the DO_FACTORY_RESET flag and we restart the device - log("Factory reset requested; setting required flags", className); - writeFile("/external_root/boot/flags/DO_FACTORY_RESET", "true\n"); - writeFile("/external_root/boot/flags/DIAGS_BOOT", "true\n"); - QString reboot_prog ("/sbin/reboot"); - QStringList reboot_args; - reboot_args << "no_splash"; - QProcess *reboot_proc = new QProcess(); - reboot_proc->start(reboot_prog, reboot_args); - reboot_proc->waitForFinished(); - reboot_proc->deleteLater(); -} - -void alert::on_continue2Btn_clicked() -{ - // We continue anyway and re-set the ALERT flag - writeFile("/external_root/boot/flags/ALERT", "false\n"); - updateReset(); - - log("Restarting InkBox", className); - if(signatureError == true) { - writeFile("/external_root/boot/flags/ALERT_SIGN", "false\n"); - QProcess process; - process.startDetached("inkbox", QStringList()); - qApp->quit(); - } - if(downgradeError == true) { - writeFile("/external_root/boot/flags/ALERT_DOWNGRADE", "false\n"); - QProcess process; - process.startDetached("inkbox", QStringList()); - qApp->quit(); - } -} - -void alert::updateReset() { - writeFile("/mnt/onboard/onboard/.inkbox/can_really_update", "false\n"); - writeFile("/mnt/onboard/onboard/.inkbox/can_update", "false\n"); -} - -void alert::quit() { - qApp->quit(); -} diff --git a/src/splash/usbmsSplash.cpp b/src/splash/usbmsSplash.cpp deleted file mode 100644 index 4a49587..0000000 --- a/src/splash/usbmsSplash.cpp +++ /dev/null @@ -1,287 +0,0 @@ -#include "usbmsSplash.h" -#include "ui_usbmsSplash.h" - -#include -#include -#include - -#include "functions.h" - -usbmsSplash::usbmsSplash(QWidget *parent) : - QWidget(parent), - ui(new Ui::usbmsSplash) -{ - ui->setupUi(this); - usbmsSplash::setFont(QFont("u001")); - ui->label->setFont(QFont("Inter")); - - // Getting the screen's size - sW = QGuiApplication::screens()[0]->size().width(); - sH = QGuiApplication::screens()[0]->size().height(); - - // Defining what the default icon size will be - if(global::kobox::showKoboxSplash == true) { - float stdIconWidth = sW / 1.30; - float stdIconHeight = sH / 1.30; - - // Stylesheet - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - ui->label->setFont(QFont("Inter")); - ui->label->setText("Launching KoBox subsystem"); - ui->label->setStyleSheet("font-size: 14pt; font-weight: bold"); - ui->label_3->setText("Please wait, this could take a while."); - if(global::deviceID == "n905\n" or global::deviceID == "kt\n") { - ui->label_3->setStyleSheet("font-size: 11pt"); - } - else { - ui->label_3->setStyleSheet("font-size: 10pt"); - } - - QPixmap pixmap(":/resources/kobox-icon.png"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->label_2->setPixmap(scaledPixmap); - } - else { - float stdIconWidth = sW / 1.15; - float stdIconHeight = sH / 1.15; - - this->setStyleSheet("background-color:black;"); - ui->label->setStyleSheet("QLabel { background-color : black; color : white; font-size: 15pt; font-weight: bold }"); - ui->label_3->setStyleSheet("QLabel { background-color : black; color : white; font-size: 10pt }"); - - QPixmap pixmap(":/resources/usbms.png"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->label_2->setPixmap(scaledPixmap); - } - - if(global::usbms::launchUsbms == true) { - global::usbms::launchUsbms = false; - usbmsLaunch(); - } -} - -void usbmsSplash::usbmsLaunch() -{ - log("Entering USBMS session", className); - writeFile("/tmp/in_usbms", "true"); - QTimer::singleShot(1500, this, SLOT(brightnessDown())); - QTimer::singleShot(1500, this, SLOT(warmthDown())); - - if(global::usbms::koboxExportExtensions == true) { - writeFile("/opt/ibxd", "kobox_extensions_storage_unmount\n"); - } - if(checkconfig("/external_root/run/encfs_mounted") == true) { - writeFile("/external_root/run/encfs_stop_cleanup", "true"); - writeFile("/opt/ibxd", "encfs_stop\n"); - while(true) { - if(QFile::exists("/tmp/encfs_stopped")) { - QFile::remove("/tmp/encfs_stopped"); - break; - } - QThread::msleep(500); - } - } - - writeFile("/opt/ibxd", "gui_apps_stop\n"); - while(true) { - if(QFile::exists("/tmp/gui_apps_stopped")) { - QFile::remove("/tmp/gui_apps_stopped"); - break; - } - QThread::msleep(500); - } - - writeFile("/opt/ibxd", "onboard_unmount\n"); - while(true) { - if(QFile::exists("/tmp/onboard_unmounted")) { - QFile::remove("/tmp/onboard_unmounted"); - break; - } - QThread::msleep(500); - } - - writeFile("/opt/ibxd", "usbnet_stop\n"); - while(true) { - if(QFile::exists("/tmp/usbnet_stopped")) { - QFile::remove("/tmp/usbnet_stopped"); - break; - } - QThread::msleep(500); - } - - if(global::deviceID == "n306\n" or global::deviceID == "n249\n" or global::deviceID == "n873\n") { - QProcess::execute("insmod", QStringList() << "/external_root/lib/modules/fs/configfs/configfs.ko"); - QProcess::execute("insmod", QStringList() << "/external_root/lib/modules/drivers/usb/gadget/libcomposite.ko"); - QProcess::execute("insmod", QStringList() << "/external_root/lib/modules/drivers/usb/gadget/function/usb_f_mass_storage.ko"); - } - else if(global::deviceID == "kt\n") { - QProcess::execute("insmod", QStringList() << "/external_root/lib/modules/2.6.35-inkbox/kernel/drivers/usb/gadget/arcotg_udc.ko"); - } - - QString prog_1 ("insmod"); - QStringList args_1; - - if(global::deviceID == "kt\n") { - massStorageModule = "/external_root/lib/modules/2.6.35-inkbox/kernel/drivers/usb/gadget/g_file_storage.ko"; - } - else { - massStorageModule = "/external_root/lib/modules/g_mass_storage.ko"; - } - - if(global::usbms::koboxExportExtensions == true) { - args_1 << massStorageModule << "file=/external_root/opt/storage/X11/extensions-user.img" << "removable=y" << "stall=0"; - } - else { - args_1 << massStorageModule << "file=/external_root/opt/storage/onboard" << "removable=y" << "stall=0"; - } - - QProcess *proc_1 = new QProcess(); - proc_1->start(prog_1, args_1); - proc_1->waitForFinished(); - proc_1->deleteLater(); - - bool exitUsbMsDone = false; - QTimer *usbms_t = new QTimer(this); - usbms_t->setInterval(1000); - connect(usbms_t, &QTimer::timeout, [&]() { - if(exitUsbMsDone == false) { - if(isUsbPluggedIn() == 0) { - if(global::usbms::koboxExportExtensions == true) { - reboot(false); - qApp->quit(); - } - else { - log("Exiting USBMS session", className); - // '' bit: because nothing else works ... - ui->label->setText("Processing content"); - ui->label->setFont(QFont("Inter")); - ui->label_3->setText("Please wait"); - ui->label_3->setFont(QFont("u001")); - ui->label->setStyleSheet("QLabel { background-color : black; color : white; font-size: 15pt; font-weight: bold }"); - ui->label_3->setStyleSheet("QLabel { background-color : black; color : white; font-size: 11pt }"); - ui->label->setFont(QFont("u001")); - - float stdIconWidth = sW / 2; - float stdIconHeight = sH / 2; - - QPixmap pixmap(":/resources/clock-inverted.png"); - QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->label_2->setPixmap(scaledPixmap); - - this->repaint(); - - QString prog("rmmod"); - QStringList args; - args << massStorageModule; - QProcess * proc = new QProcess(); - proc->start(prog, args); - proc->waitForFinished(); - proc->deleteLater(); - - QTimer::singleShot(500, this, SLOT(restartServices())); - } - exitUsbMsDone = true; - } - else { - ; - } - } - } ); - usbms_t->start(); -} - -usbmsSplash::~usbmsSplash() -{ - delete ui; -} - -void usbmsSplash::brightnessDown() { - cinematicBrightness(0, 1); - writeFile("/tmp/inkbox-cinematicBrightness_ran", "false"); -} - -void usbmsSplash::warmthDown() { - if(global::deviceID == "n249\n" or global::deviceID == "n873\n") { - cinematicWarmth(0); - } -} - -void usbmsSplash::quit_restart() { - // If existing, cleaning bookconfig_mount mountpoint - writeFile("/opt/ibxd", "bookconfig_unmount\n"); - - // Restarting InkBox - QProcess process; - process.startDetached("inkbox", QStringList()); - qApp->quit(); -} - -void usbmsSplash::restartServices() { - // Restarting USBNet - // NOTE: USBNet is only started if required conditions are met (see https://github.com/Kobo-InkBox/rootfs/blob/master/etc/init.d/usbnet) - writeFile("/opt/ibxd", "usbnet_start\n"); - while(true) { - if(QFile::exists("/tmp/usbnet_started")) { - QFile::remove("/tmp/usbnet_started"); - break; - } - QThread::msleep(500); - } - - // Mounting onboard storage - writeFile("/opt/ibxd", "onboard_mount\n"); - while(true) { - if(QFile::exists("/tmp/onboard_mounted")) { - QFile::remove("/tmp/onboard_mounted"); - break; - } - QThread::msleep(500); - } - - // Checking for updates - writeFile("/opt/ibxd", "update_inkbox_restart\n"); - while(true) { - if(QFile::exists("/tmp/update_inkbox_restarted")) { - QFile::remove("/tmp/update_inkbox_restarted"); - break; - } - QThread::msleep(500); - } - - QFile::remove("/tmp/in_usbms"); - // GUI apps: update main JSON file - writeFile("/opt/ibxd", "gui_apps_start\n"); - while(true) { - if(QFile::exists("/tmp/gui_apps_started")) { - if(checkconfig("/tmp/gui_apps_started") == true) { - QFile::remove("/tmp/gui_apps_started"); - updateUserAppsMainJsonFile(); - break; - } - else { - log("GUI apps service failed to start", className); - QFile::remove("/tmp/gui_apps_started"); - break; - } - } - QThread::msleep(500); - } - // Remove macOS dotfiles - { - QString prog("busybox-initrd"); - QStringList args; - args << "find" << "/mnt/onboard/onboard" << "-type" << "f" << "-name" << "._*" << "-delete"; - QProcess * proc = new QProcess(); - proc->start(prog, args); - proc->waitForFinished(); - proc->deleteLater(); - } - // Re-generate local library on next launch - QFile::remove(global::localLibrary::databasePath); - - quit_restart(); -} diff --git a/src/telemetry/telemetry.cpp b/src/telemetry/telemetry.cpp index 74e3358..9735bcb 100644 --- a/src/telemetry/telemetry.cpp +++ b/src/telemetry/telemetry.cpp @@ -1,16 +1,19 @@ #include "telemetry.h" +#include "device.h" -telemetry::telemetry(QObject *parent) +Telemetry::Telemetry(QObject *parent) : QObject{parent} { QTimer::singleShot(100, this, SLOT(telemetrySlot())); } -QJsonObject telemetry::collectDeviceInformation() { +QJsonObject Telemetry::collectDeviceInformation() { + Device::SysInfo info = Device::getSingleton()->getSystemInfo(); + QJsonObject data; - data.insert("DeviceUID", getUID()); + data.insert("DeviceUID", info.uid); data.insert("SystemVersion", readFile("/opt/version").trimmed()); - data.insert("Device", global::deviceID.trimmed()); + data.insert("Device", Device::getSingleton()->getID()); if(checkconfig("/external_root/opt/root/rooted")) { data.insert("DeviceRooted", "true"); } @@ -27,7 +30,7 @@ QJsonObject telemetry::collectDeviceInformation() { return data; } -bool telemetry::sendDeviceInformation(QJsonObject data) { +bool Telemetry::sendDeviceInformation(QJsonObject data) { log("Telemetry data to be sent to server: " + QJsonDocument(data).toJson(QJsonDocument::Compact), className); // NOTE: This URL *will* change in the future @@ -46,7 +49,7 @@ bool telemetry::sendDeviceInformation(QJsonObject data) { return true; } -void telemetry::telemetrySlot() { +void Telemetry::telemetrySlot() { QJsonObject data = collectDeviceInformation(); if(sendDeviceInformation(data)) { writeFile("/mnt/onboard/.adds/inkbox/.config/24-telemetry/asked", "true"); diff --git a/src/telemetry/telemetry.h b/src/telemetry/telemetry.h index 1a27ad6..5f7d56d 100644 --- a/src/telemetry/telemetry.h +++ b/src/telemetry/telemetry.h @@ -7,11 +7,11 @@ #include #include "functions.h" -class telemetry : public QObject +class Telemetry : public QObject { Q_OBJECT public: - explicit telemetry(QObject *parent = nullptr); + explicit Telemetry(QObject *parent = nullptr); QString className = this->metaObject()->className(); QString message; QString deviceUID; diff --git a/src/apps/apps.cpp b/src/ui/apps/apps.cpp similarity index 60% rename from src/apps/apps.cpp rename to src/ui/apps/apps.cpp index 2368721..539f302 100644 --- a/src/apps/apps.cpp +++ b/src/ui/apps/apps.cpp @@ -1,20 +1,22 @@ #include "apps.h" -#include "ui_apps.h" #include "mainwindow.h" +#include "ui_apps.h" #include "userapps.h" +#include "ui.h" #include -#include -#include -#include -#include #include +#include +#include +#include +#include #include -apps::apps(QWidget *parent) : - QWidget(parent), - ui(new Ui::apps) -{ +AppsWidget::AppsWidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::AppsWidget) { + Device *device = Device::getSingleton(); + ui->setupUi(this); ui->koboxAppsOpenButton->setProperty("type", "borderless"); ui->calendarLaunchBtn->setProperty("type", "borderless"); @@ -38,23 +40,22 @@ apps::apps(QWidget *parent) : ui->noUserAppsAvailableLabel->hide(); // Hiding KoBox apps button and label if X11 isn't enabled/wasn't started - if(checkconfig("/external_root/boot/flags/X11_START") == false or checkconfig("/external_root/boot/flags/X11_STARTED") == false) { + if (checkconfig("/external_root/boot/flags/X11_START") == false or checkconfig("/external_root/boot/flags/X11_STARTED") == false) { ui->label_5->hide(); ui->koboxAppsOpenButton->hide(); ui->label_5->deleteLater(); ui->koboxAppsOpenButton->deleteLater(); } // Hiding VNC viewer button and label if device is not rooted and doesn't have a working Wi-Fi adapter, or if X11 is not running - if(checkconfig("/external_root/opt/root/rooted") == false) { - if(global::device::isWifiAble == false or checkconfig("/external_root/boot/flags/X11_START") == false or checkconfig("/external_root/boot/flags/X11_STARTED") == false) { + if (checkconfig("/external_root/opt/root/rooted") == false) { + if (device->supportsWifi() == false or checkconfig("/external_root/boot/flags/X11_START") == false or checkconfig("/external_root/boot/flags/X11_STARTED") == false) { ui->vncViewerLabel->hide(); ui->vncLaunchBtn->hide(); ui->vncViewerLabel->deleteLater(); ui->vncLaunchBtn->deleteLater(); } - } - else { - if(checkconfig("/external_root/boot/flags/X11_START") == false or checkconfig("/external_root/boot/flags/X11_STARTED") == false) { + } else { + if (checkconfig("/external_root/boot/flags/X11_START") == false or checkconfig("/external_root/boot/flags/X11_STARTED") == false) { ui->vncViewerLabel->hide(); ui->vncLaunchBtn->hide(); ui->vncViewerLabel->deleteLater(); @@ -71,202 +72,191 @@ apps::apps(QWidget *parent) : jsonParseSuccess = parseJson(); showUserApps(false); - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); + UI::applyStyle(*this, "eink"); } -apps::~apps() -{ +AppsWidget::~AppsWidget() { delete ui; } -void apps::exitSlot() { - apps::close(); +void AppsWidget::exitSlot() { + AppsWidget::close(); } -void apps::on_savedWordsLaunchBtn_clicked() -{ +void AppsWidget::on_savedWordsLaunchBtn_clicked() { log("Launching Saved Words app", className); - savedWordsWindow = new savedwords(); + savedWordsWindow = new SavedWordsAppWidget(); savedWordsWindow->setAttribute(Qt::WA_DeleteOnClose); savedWordsWindow->showFullScreen(); } -void apps::on_calendarLaunchBtn_clicked() -{ +void AppsWidget::on_calendarLaunchBtn_clicked() { log("Launching Calendar app", className); - calendarWindow = new calendarApp(); + calendarWindow = new CalendarAppWidget(); calendarWindow->setAttribute(Qt::WA_DeleteOnClose); calendarWindow->showFullScreen(); } -void apps::on_calculatorLaunchBtn_clicked() -{ +void AppsWidget::on_calculatorLaunchBtn_clicked() { log("Launching external Qalculate! app", className); QProcess process; process.startDetached("qalculate", QStringList()); qApp->quit(); } -void apps::on_koboxAppsOpenButton_clicked() -{ +void AppsWidget::on_koboxAppsOpenButton_clicked() { log("Showing KoBox Apps Dialog", className); - koboxAppsDialogWindow = new koboxAppsDialog(); + koboxAppsDialogWindow = new KoboxAppsDialog(); connect(koboxAppsDialogWindow, SIGNAL(showToast(QString)), SLOT(showToastNative(QString))); koboxAppsDialogWindow->setAttribute(Qt::WA_DeleteOnClose); koboxAppsDialogWindow->show(); } -void apps::on_vncLaunchBtn_clicked() -{ +void AppsWidget::on_vncLaunchBtn_clicked() { log("Showing VNC dialog", className); global::keyboard::keyboardDialog = true; global::keyboard::vncDialog = true; global::keyboard::keyboardText = ""; - generalDialogWindow = new generalDialog(); + generalDialogWindow = new GeneralDialog(); generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); connect(generalDialogWindow, SIGNAL(refreshScreen()), SLOT(refreshScreenNative())); generalDialogWindow->show(); } -void apps::refreshScreenNative() { +void AppsWidget::refreshScreenNative() { emit refreshScreen(); } -void apps::on_reversiLaunchBtn_clicked() -{ +void AppsWidget::on_reversiLaunchBtn_clicked() { log("Launching external Reversi app", className); QProcess process; process.startDetached("qreversi", QStringList()); qApp->quit(); } -void apps::on_g2048LaunchBtn_clicked() -{ +void AppsWidget::on_g2048LaunchBtn_clicked() { log("Launching external 2048 app", className); QProcess process; process.startDetached("2048", QStringList()); qApp->quit(); } -void apps::showToastNative(QString messageToDisplay) { +void AppsWidget::showToastNative(QString messageToDisplay) { emit showToast(messageToDisplay); } /* * This function opens and reads the main GUI user applications' JSON file, parses and verifies its contents to avoid issues in the future. -*/ -bool apps::parseJson() { + */ +bool AppsWidget::parseJson() { // If the path changes, it is also used statically in showUserApps() jsonFile.setFileName("/mnt/onboard/onboard/.apps/apps.json"); bool jsonCheckSuccess = true; - if(jsonFile.exists() == false) { + if (jsonFile.exists() == false) { log("GUI user applications' main JSON file is missing", className); jsonCheckSuccess = false; - } - else { + } else { jsonFile.open(QIODevice::ReadOnly | QIODevice::Text); QString fileRead = jsonFile.readAll(); jsonFile.close(); jsonDocument = QJsonDocument::fromJson(fileRead.toUtf8()); - if(jsonDocument.isNull() == true) { + if (jsonDocument.isNull() == true) { log("GUI user applications' main JSON file is invalid", className); jsonCheckSuccess = false; - } - else { + } else { QJsonObject jsonObject = jsonDocument.object(); - if(jsonObject["list"].isArray() == true) { + if (jsonObject["list"].isArray() == true) { QJsonArray jsonArray = jsonObject["list"].toArray(); - for(QJsonValueRef refJsonObject: jsonArray) { - if(refJsonObject.isObject()) { + for (QJsonValueRef refJsonObject : jsonArray) { + if (refJsonObject.isObject()) { QJsonObject jsonMainObject = refJsonObject.toObject(); - if(jsonMainObject.size() == 9) { - if(!jsonMainObject["Name"].isString()) { - QString function = __func__; log(function + ": Invalid 'Name' type inside object", className); + if (jsonMainObject.size() == 9) { + if (!jsonMainObject["Name"].isString()) { + QString function = __func__; + log(function + ": Invalid 'Name' type inside object", className); jsonCheckSuccess = false; - } - if(!jsonMainObject["Author"].isString()) { - QString function = __func__; log(function + ": Invalid 'Author' type inside object", className); + if (!jsonMainObject["Author"].isString()) { + QString function = __func__; + log(function + ": Invalid 'Author' type inside object", className); jsonCheckSuccess = false; - } - if(!jsonMainObject["AuthorContact"].isString()) { - QString function = __func__; log(function + ": Invalid 'AuthorContact' type inside object", className); + if (!jsonMainObject["AuthorContact"].isString()) { + QString function = __func__; + log(function + ": Invalid 'AuthorContact' type inside object", className); jsonCheckSuccess = false; - } - if(!jsonMainObject["Version"].isString()) { - QString function = __func__; log(function + ": Invalid 'Version' type inside object", className); + if (!jsonMainObject["Version"].isString()) { + QString function = __func__; + log(function + ": Invalid 'Version' type inside object", className); jsonCheckSuccess = false; - } - if(!jsonMainObject["IconPath"].isString()) { + if (!jsonMainObject["IconPath"].isString()) { log("JSON: Invalid IconPath type inside object", className); jsonCheckSuccess = false; - } - if(!jsonMainObject["ExecPath"].isString()) { - QString function = __func__; log(function + ": Invalid 'ExecPath' type inside object", className); + if (!jsonMainObject["ExecPath"].isString()) { + QString function = __func__; + log(function + ": Invalid 'ExecPath' type inside object", className); jsonCheckSuccess = false; - } - else { - if(jsonMainObject["ExecPath"].toString().contains("..")) { + } else { + if (jsonMainObject["ExecPath"].toString().contains("..")) { // Possible security risk showToastNative("ERROR: 'ExecPath' has invalid path"); - QString function = __func__; log(function + ": 'ExecPath' contains \"..\"", className); + QString function = __func__; + log(function + ": 'ExecPath' contains \"..\"", className); jsonCheckSuccess = false; } } - if(!jsonMainObject["Enabled"].isBool()) { - QString function = __func__; log(function + ": Invalid 'Enabled' type inside object", className); + if (!jsonMainObject["Enabled"].isBool()) { + QString function = __func__; + log(function + ": Invalid 'Enabled' type inside object", className); + jsonCheckSuccess = false; + } + if (!jsonMainObject["SupportedDevices"].isArray()) { + QString function = __func__; + log(function + ": Invalid 'SupportedDevices' type inside object", className); jsonCheckSuccess = false; - } - if(!jsonMainObject["SupportedDevices"].isArray()) { - QString function = __func__; log(function + ": Invalid 'SupportedDevices' type inside object", className); - jsonCheckSuccess = false; - - } - else { + } else { QJsonArray jsonArray = jsonMainObject["SupportedDevices"].toArray(); - for(QJsonValueRef refJsonObject: jsonArray) { + for (QJsonValueRef refJsonObject : jsonArray) { // https://doc.qt.io/qt-5/qjsonvalue.html#toInt - if(!refJsonObject.isString()) { - QString function = __func__; log(function + ": Array from 'RequiredFeatures' contains a wrong type", className); + if (!refJsonObject.isString()) { + QString function = __func__; + log(function + ": Array from 'RequiredFeatures' contains a wrong type", className); jsonCheckSuccess = false; } } } - if(!jsonMainObject["RequiredFeatures"].isArray()) { - QString function = __func__; log(function + ": Invalid 'RequiredFeatures' type inside object", className); + if (!jsonMainObject["RequiredFeatures"].isArray()) { + QString function = __func__; + log(function + ": Invalid 'RequiredFeatures' type inside object", className); jsonCheckSuccess = false; - } - else { + } else { QJsonArray jsonArray = jsonMainObject["RequiredFeatures"].toArray(); - for(QJsonValueRef refJsonObject: jsonArray) { + for (QJsonValueRef refJsonObject : jsonArray) { // https://doc.qt.io/qt-5/qjsonvalue.html#toInt - if(!refJsonObject.isDouble()) { - QString function = __func__; log(function + ": Array from 'RequiredFeatures' contains a wrong type", className); + if (!refJsonObject.isDouble()) { + QString function = __func__; + log(function + ": Array from 'RequiredFeatures' contains a wrong type", className); jsonCheckSuccess = false; } } } - } - else { - QString function = __func__; QString message = function + ": An object inside list array has too many items (or not enough): "; + } else { + QString function = __func__; + QString message = function + ": An object inside list array has too many items (or not enough): "; message.append(QString::number(jsonMainObject.size())); log(message, className); jsonCheckSuccess = false; } - } - else { - QString function = __func__; log(function + ": List array has an item of other type than object", className); + } else { + QString function = __func__; + log(function + ": List array has an item of other type than object", className); jsonCheckSuccess = false; } } @@ -276,9 +266,8 @@ bool apps::parseJson() { return jsonCheckSuccess; } -void apps::on_editUserAppsBtn_clicked() -{ - if(userAppsSecondPage == false) { +void AppsWidget::on_editUserAppsBtn_clicked() { + if (userAppsSecondPage == false) { userAppsSecondPage = true; // Settings page @@ -287,8 +276,7 @@ void apps::on_editUserAppsBtn_clicked() emit showUserAppsEdit(userAppsSecondPage); QTimer::singleShot(500, this, SLOT(refreshScreenNative())); - } - else { + } else { userAppsSecondPage = false; userAppsAvailable = false; @@ -307,18 +295,18 @@ void apps::on_editUserAppsBtn_clicked() } } -void apps::showUserApps(bool showDisabledJson) -{ +void AppsWidget::showUserApps(bool showDisabledJson) { emit clearAppsLayout(); - if(jsonParseSuccess == true) { - QString function = __func__; log(function + ": Main user applications' JSON is valid", className); + if (jsonParseSuccess == true) { + QString function = __func__; + log(function + ": Main user applications' JSON is valid", className); QJsonArray jsonListArray = jsonDocument.object()["list"].toArray(); - for(QJsonValueRef refJsonObject: jsonListArray) { + for (QJsonValueRef refJsonObject : jsonListArray) { QJsonObject appInfo = refJsonObject.toObject(); - if(appInfo["Enabled"].toBool() == true or showDisabledJson == true) { + if (appInfo["Enabled"].toBool() == true or showDisabledJson == true) { userAppsAvailable = true; - userapps * newUserApp = new userapps; + UserAppsWidget *newUserApp = new UserAppsWidget; newUserApp->provideInfo(appInfo); connect(this, SIGNAL(clearAppsLayout()), newUserApp, SLOT(deleteLater())); connect(this, SIGNAL(showUserAppsEdit(bool)), newUserApp, SLOT(changePageEnabling(bool))); @@ -330,20 +318,19 @@ void apps::showUserApps(bool showDisabledJson) } } - if(userAppsAvailable == false) { + if (userAppsAvailable == false) { ui->noUserAppsAvailableLabel->show(); - } - else { + } else { ui->noUserAppsAvailableLabel->hide(); } - } - else { - if(QFile::exists("/mnt/onboard/onboard/.apps/apps.json")) { - QString function = __func__; log(function + ": Main user applications' JSON file is invalid", className); + } else { + if (QFile::exists("/mnt/onboard/onboard/.apps/apps.json")) { + QString function = __func__; + log(function + ": Main user applications' JSON file is invalid", className); QTimer::singleShot(500, this, SLOT(showFailedToParseMainUserAppsJsonFile())); - } - else { - QString function = __func__; log(function + ": Main user applications' JSON file doesn't exist; assuming that no user applications are currently installed", className); + } else { + QString function = __func__; + log(function + ": Main user applications' JSON file doesn't exist; assuming that no user applications are currently installed", className); } ui->editUserAppsBtn->hide(); @@ -358,21 +345,19 @@ void apps::showUserApps(bool showDisabledJson) } } -void apps::updateJsonFileSlot(QJsonDocument jsonDocumentFunc) -{ +void AppsWidget::updateJsonFileSlot(QJsonDocument jsonDocumentFunc) { jsonDocument = jsonDocumentFunc; emit updateJsonFileSignal(jsonDocument); } -void apps::showFailedToParseMainUserAppsJsonFile() { - emit showToast("Failed to parse 'apps.json'"); +void AppsWidget::showFailedToParseMainUserAppsJsonFile() { + emit showToast("Failed to parse 'apps.json'"); } -void apps::on_todoLaunchBtn_clicked() -{ - todo * todoWindow = new todo(); - QObject::connect(todoWindow, &todo::showToast, this, &apps::showToast); +void AppsWidget::on_todoLaunchBtn_clicked() { + TodoAppWidget *todoWindow = new TodoAppWidget(); + QObject::connect(todoWindow, &TodoAppWidget::showToast, this, &AppsWidget::showToast); todoWindow->setAttribute(Qt::WA_DeleteOnClose); - todoWindow->setGeometry(QRect(QPoint(0,0), qApp->primaryScreen()->geometry().size())); + todoWindow->setGeometry(QRect(QPoint(0, 0), qApp->primaryScreen()->geometry().size())); todoWindow->show(); } diff --git a/src/apps/apps.h b/src/ui/apps/apps.h similarity index 79% rename from src/apps/apps.h rename to src/ui/apps/apps.h index d9d138b..1ed4b74 100644 --- a/src/apps/apps.h +++ b/src/ui/apps/apps.h @@ -11,17 +11,17 @@ #include namespace Ui { -class apps; +class AppsWidget; } -class apps : public QWidget +class AppsWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit apps(QWidget *parent = nullptr); - ~apps(); + explicit AppsWidget(QWidget *parent = nullptr); + ~AppsWidget(); private slots: void exitSlot(); @@ -42,12 +42,12 @@ private slots: void on_todoLaunchBtn_clicked(); private: - Ui::apps * ui; - savedwords * savedWordsWindow; - calendarApp * calendarWindow; - koboxAppsDialog * koboxAppsDialogWindow; - generalDialog * generalDialogWindow; - todo * todoWindow; + Ui::AppsWidget * ui; + SavedWordsAppWidget * savedWordsWindow; + CalendarAppWidget * calendarWindow; + KoboxAppsDialog * koboxAppsDialogWindow; + GeneralDialog * generalDialogWindow; + TodoAppWidget * todoWindow; QFile jsonFile; QJsonDocument jsonDocument; diff --git a/src/apps/apps.ui b/src/ui/apps/apps.ui similarity index 99% rename from src/apps/apps.ui rename to src/ui/apps/apps.ui index c43b243..e723937 100644 --- a/src/apps/apps.ui +++ b/src/ui/apps/apps.ui @@ -1,7 +1,7 @@ - apps - + AppsWidget + 0 diff --git a/src/ui/apps/calendarapp.cpp b/src/ui/apps/calendarapp.cpp new file mode 100644 index 0000000..5cc19a9 --- /dev/null +++ b/src/ui/apps/calendarapp.cpp @@ -0,0 +1,27 @@ +#include "calendarapp.h" +#include "ui.h" +#include "ui_calendarapp.h" + +#include + +CalendarAppWidget::CalendarAppWidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::CalendarAppWidget) { + ui->setupUi(this); + CalendarAppWidget::setFont(QFont("u001")); + ui->backBtn->setFont(QFont("Inter")); + ui->backBtn->setStyleSheet("font-weight: bold"); + + // Stylesheet + UI::applyStyle(*this, "eink"); + + ui->backBtn->setProperty("type", "borderless"); +} + +CalendarAppWidget::~CalendarAppWidget() { + delete ui; +} + +void CalendarAppWidget::on_backBtn_clicked() { + CalendarAppWidget::close(); +} diff --git a/src/apps/calendarapp.h b/src/ui/apps/calendarapp.h similarity index 57% rename from src/apps/calendarapp.h rename to src/ui/apps/calendarapp.h index 98560e2..87672e0 100644 --- a/src/apps/calendarapp.h +++ b/src/ui/apps/calendarapp.h @@ -4,23 +4,23 @@ #include namespace Ui { -class calendarApp; +class CalendarAppWidget; } -class calendarApp : public QWidget +class CalendarAppWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit calendarApp(QWidget *parent = nullptr); - ~calendarApp(); + explicit CalendarAppWidget(QWidget *parent = nullptr); + ~CalendarAppWidget(); private slots: void on_backBtn_clicked(); private: - Ui::calendarApp *ui; + Ui::CalendarAppWidget *ui; }; #endif // CALENDARAPP_H diff --git a/src/apps/calendarapp.ui b/src/ui/apps/calendarapp.ui similarity index 93% rename from src/apps/calendarapp.ui rename to src/ui/apps/calendarapp.ui index 9ec29c3..5620627 100644 --- a/src/apps/calendarapp.ui +++ b/src/ui/apps/calendarapp.ui @@ -1,7 +1,7 @@ - calendarApp - + CalendarAppWidget + 0 diff --git a/src/ui/apps/savedwords.cpp b/src/ui/apps/savedwords.cpp new file mode 100644 index 0000000..cf411e0 --- /dev/null +++ b/src/ui/apps/savedwords.cpp @@ -0,0 +1,81 @@ +#include "savedwords.h" +#include "functions.h" +#include "ui.h" +#include "ui_savedwords.h" + +#include +#include +#include + +SavedWordsAppWidget::SavedWordsAppWidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::SavedWordsAppWidget) { + ui->setupUi(this); + SavedWordsAppWidget::setFont(QFont("u001")); + ui->savedWordsLabel->setFont(QFont("Inter")); + ui->backBtn->setFont(QFont("Inter")); + ui->clearBtn->setFont(QFont("Inter")); + + UI::applyStyle(*this, "eink"); + + ui->backBtn->setProperty("type", "borderless"); + ui->clearBtn->setProperty("type", "borderless"); + + ui->savedWordsLabel->setStyleSheet("font-weight: bold"); + ui->wordsList->setStyleSheet("font-size: 10pt"); + ui->backBtn->setStyleSheet("font-weight: bold"); + ui->clearBtn->setStyleSheet("font-weight: bold"); + + checkwords(); + + QStringListModel *model = new QStringListModel(this); + QStringList list = words.split("\n", QString::SkipEmptyParts); + model->setStringList(list); + ui->wordsList->setModel(model); + ui->wordsList->setEditTriggers(QAbstractItemView::NoEditTriggers); +} + +SavedWordsAppWidget::~SavedWordsAppWidget() { + delete ui; +} + +void SavedWordsAppWidget::on_backBtn_clicked() { + // Workaround for the random strange memory corruption error + QProcess process; + process.startDetached("inkbox", QStringList()); + qApp->quit(); +} + +void SavedWordsAppWidget::on_clearBtn_clicked() { + // Warning: possible memory leak here. Though, usually, when you press the "Clear" button and all clears up, you don't have to press it again ;) + log("Wiping Saved Words list", className); + save_word_init(); + checkwords(); + QStringListModel *model = new QStringListModel(this); + QStringList list = words.split("\n", QString::SkipEmptyParts); + model->setStringList(list); + ui->wordsList->setModel(model); + ui->wordsList->setEditTriggers(QAbstractItemView::NoEditTriggers); +} + +void SavedWordsAppWidget::checkwords() { + QFile words_list(".config/06-words/config"); + words_list.open(QIODevice::ReadWrite); + QTextStream in(&words_list); + words = in.readAll(); + words_list.close(); +} + +void SavedWordsAppWidget::save_word_init() { + QFile words(".config/06-words/config"); + words.open(QIODevice::ReadWrite); + QTextStream in(&words); + QString words_list = in.readAll(); + string words_list_str = words_list.toStdString(); + words.close(); + + ofstream fhandler; + fhandler.open(".config/06-words/config"); + fhandler << ""; + fhandler.close(); +} diff --git a/src/apps/savedwords.h b/src/ui/apps/savedwords.h similarity index 70% rename from src/apps/savedwords.h rename to src/ui/apps/savedwords.h index 4957804..1ea978e 100644 --- a/src/apps/savedwords.h +++ b/src/ui/apps/savedwords.h @@ -11,17 +11,17 @@ using namespace std; namespace Ui { -class savedwords; +class SavedWordsAppWidget; } -class savedwords : public QWidget +class SavedWordsAppWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit savedwords(QWidget *parent = nullptr); - ~savedwords(); + explicit SavedWordsAppWidget(QWidget *parent = nullptr); + ~SavedWordsAppWidget(); QString words; void checkwords(); void save_word_init(); @@ -31,7 +31,7 @@ private slots: void on_clearBtn_clicked(); private: - Ui::savedwords *ui; + Ui::SavedWordsAppWidget *ui; }; #endif // SAVEDWORDS_H diff --git a/src/apps/savedwords.ui b/src/ui/apps/savedwords.ui similarity index 96% rename from src/apps/savedwords.ui rename to src/ui/apps/savedwords.ui index 85b78be..4fa28d3 100644 --- a/src/apps/savedwords.ui +++ b/src/ui/apps/savedwords.ui @@ -1,7 +1,7 @@ - savedwords - + SavedWordsAppWidget + 0 diff --git a/src/apps/todo.cpp b/src/ui/apps/todo.cpp similarity index 88% rename from src/apps/todo.cpp rename to src/ui/apps/todo.cpp index 35c7709..dc8f572 100644 --- a/src/apps/todo.cpp +++ b/src/ui/apps/todo.cpp @@ -1,12 +1,14 @@ #include "todo.h" #include "ui_todo.h" +#include "device.h" #include "functions.h" -todo::todo(QWidget *parent) : +TodoAppWidget::TodoAppWidget(QWidget *parent) : QWidget(parent), - ui(new Ui::todo) + ui(new Ui::TodoAppWidget) { + Device* device = Device::getSingleton(); ui->setupUi(this); this->setStyleSheet(readFile("/mnt/onboard/.adds/inkbox/eink.qss")); this->setFont(QFont("u001")); @@ -17,7 +19,7 @@ todo::todo(QWidget *parent) : ui->setupBtn->setEnabled(false); buttonPadding; - if(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "kt\n") { + if(device->getScreenSize() <= Device::ScreenSize::MEDIUM) { buttonPadding = 5; } else { @@ -66,12 +68,12 @@ todo::todo(QWidget *parent) : refreshList(); } -todo::~todo() +TodoAppWidget::~TodoAppWidget() { delete ui; } -void todo::on_closeBtn_clicked() +void TodoAppWidget::on_closeBtn_clicked() { if(currentView == currentView::home) { this->close(); @@ -82,19 +84,19 @@ void todo::on_closeBtn_clicked() } } -void todo::on_newBtn_clicked() +void TodoAppWidget::on_newBtn_clicked() { global::keyboard::embed = false; global::keyboard::keyboardText = ""; virtualkeyboard * virtualKeyboardWidget = new virtualkeyboard(this); virtualKeyboardWidget->setAttribute(Qt::WA_DeleteOnClose); - QObject::connect(virtualKeyboardWidget, &virtualkeyboard::enterBtnPressed, this, &todo::createNewList); - QObject::connect(virtualKeyboardWidget, &virtualkeyboard::closeBtnPressed, this, &todo::setDefaultHomePageStatusText); + QObject::connect(virtualKeyboardWidget, &virtualkeyboard::enterBtnPressed, this, &TodoAppWidget::createNewList); + QObject::connect(virtualKeyboardWidget, &virtualkeyboard::closeBtnPressed, this, &TodoAppWidget::setDefaultHomePageStatusText); ui->statusLabel->setText("Enter the list's name"); virtualKeyboardWidget->show(); } -void todo::createNewList(QString listName) { +void TodoAppWidget::createNewList(QString listName) { log("Initializing new To-Do list with name '" + listName + "'", className); QJsonDocument document; QJsonArray mainArray; @@ -117,7 +119,7 @@ void todo::createNewList(QString listName) { refreshList(); } -void todo::addItem(QString itemName) { +void TodoAppWidget::addItem(QString itemName) { log("Adding item with name '" + itemName + "' to current list", className); // Accessing the current list's items array QJsonDocument document = readTodoDatabase(); @@ -142,7 +144,7 @@ void todo::addItem(QString itemName) { setupList(listArray.at(0).toString()); } -void todo::refreshList() { +void TodoAppWidget::refreshList() { if(QFile::exists(global::localLibrary::todoDatabasePath)) { ui->listWidget->clear(); QJsonArray array = readTodoDatabase().object()["List"].toArray(); @@ -155,7 +157,7 @@ void todo::refreshList() { } } -void todo::setupList(QString listName) { +void TodoAppWidget::setupList(QString listName) { log("Setting up list with name '" + listName + "'", className); QJsonArray array = readTodoDatabase().object()["List"].toArray(); // Iterate through the To-Do lists array to find the list's array index @@ -197,7 +199,7 @@ void todo::setupList(QString listName) { ui->statusLabel->setText("Select or create a new item"); } -void todo::on_setupBtn_clicked() +void TodoAppWidget::on_setupBtn_clicked() { ui->deleteBtn->setEnabled(false); ui->setupBtn->setEnabled(false); @@ -205,13 +207,13 @@ void todo::on_setupBtn_clicked() } -void todo::on_listWidget_itemClicked(QListWidgetItem *item) +void TodoAppWidget::on_listWidget_itemClicked(QListWidgetItem *item) { ui->deleteBtn->setEnabled(true); ui->setupBtn->setEnabled(true); } -void todo::saveCurrentList() { +void TodoAppWidget::saveCurrentList() { QJsonDocument document = readTodoDatabase(); QJsonObject object = document.object(); QJsonArray mainArray = object["List"].toArray(); @@ -235,7 +237,7 @@ void todo::saveCurrentList() { writeTodoDatabase(document); } -void todo::on_deleteBtn_clicked() +void TodoAppWidget::on_deleteBtn_clicked() { QJsonDocument document = readTodoDatabase(); QJsonObject object = document.object(); @@ -251,19 +253,19 @@ void todo::on_deleteBtn_clicked() refreshList(); } -void todo::on_newItemBtn_clicked() +void TodoAppWidget::on_newItemBtn_clicked() { global::keyboard::embed = false; global::keyboard::keyboardText = ""; virtualkeyboard * virtualKeyboardWidget = new virtualkeyboard(this); virtualKeyboardWidget->setAttribute(Qt::WA_DeleteOnClose); - QObject::connect(virtualKeyboardWidget, &virtualkeyboard::enterBtnPressed, this, &todo::addItem); - QObject::connect(virtualKeyboardWidget, &virtualkeyboard::closeBtnPressed, this, &todo::setDefaultListPageStatusText); + QObject::connect(virtualKeyboardWidget, &virtualkeyboard::enterBtnPressed, this, &TodoAppWidget::addItem); + QObject::connect(virtualKeyboardWidget, &virtualkeyboard::closeBtnPressed, this, &TodoAppWidget::setDefaultListPageStatusText); ui->statusLabel->setText("Enter the item's name"); virtualKeyboardWidget->show(); } -void todo::switchViewHome() { +void TodoAppWidget::switchViewHome() { ui->itemsListWidget->clear(); switchItemsSelectionMode(false); ui->stackedWidget->setCurrentIndex(0); @@ -276,7 +278,7 @@ void todo::switchViewHome() { currentView = currentView::home; } -void todo::on_selectItemsModeBtn_clicked() +void TodoAppWidget::on_selectItemsModeBtn_clicked() { if(selectItemsMode == false) { switchItemsSelectionMode(true); @@ -286,7 +288,7 @@ void todo::on_selectItemsModeBtn_clicked() } } -void todo::switchItemsSelectionMode(bool selectionMode) { +void TodoAppWidget::switchItemsSelectionMode(bool selectionMode) { if(selectionMode == true) { log("Entering selection mode", className); saveCurrentList(); @@ -308,7 +310,7 @@ void todo::switchItemsSelectionMode(bool selectionMode) { QTimer::singleShot(500, this, SLOT(resize())); } -void todo::on_deleteItemBtn_clicked() +void TodoAppWidget::on_deleteItemBtn_clicked() { QList itemsToDelete; for(int i = 1; i < ui->itemsListWidget->count() + 1; i++) { @@ -350,7 +352,7 @@ void todo::on_deleteItemBtn_clicked() } } -void todo::on_selectAllItemsBtn_clicked() +void TodoAppWidget::on_selectAllItemsBtn_clicked() { int range = ui->itemsListWidget->count(); for(int i = 0; i < range; i++) { @@ -358,15 +360,15 @@ void todo::on_selectAllItemsBtn_clicked() } } -void todo::setDefaultHomePageStatusText() { +void TodoAppWidget::setDefaultHomePageStatusText() { ui->statusLabel->setText("Select or create a new list"); } -void todo::setDefaultListPageStatusText() { +void TodoAppWidget::setDefaultListPageStatusText() { ui->statusLabel->setText("Select or create a new item"); } -void todo::on_deselectAllItemsBtn_clicked() +void TodoAppWidget::on_deselectAllItemsBtn_clicked() { int range = ui->itemsListWidget->count(); for(int i = 0; i < range; i++) { @@ -374,13 +376,13 @@ void todo::on_deselectAllItemsBtn_clicked() } } -void todo::on_saveCurrentListViewBtn_clicked() +void TodoAppWidget::on_saveCurrentListViewBtn_clicked() { saveCurrentList(); switchItemsSelectionMode(false); } -void todo::on_editItemBtn_clicked() +void TodoAppWidget::on_editItemBtn_clicked() { QList selectedItems; for(int i = 1; i < ui->itemsListWidget->count() + 1; i++) { @@ -395,8 +397,8 @@ void todo::on_editItemBtn_clicked() global::keyboard::keyboardText = ui->itemsListWidget->item(currentEditItemIndex - 1)->text(); virtualkeyboard * virtualKeyboardWidget = new virtualkeyboard(this); virtualKeyboardWidget->setAttribute(Qt::WA_DeleteOnClose); - QObject::connect(virtualKeyboardWidget, &virtualkeyboard::enterBtnPressed, this, &todo::editItemWrapper); - QObject::connect(virtualKeyboardWidget, &virtualkeyboard::closeBtnPressed, this, &todo::setDefaultListPageStatusText); + QObject::connect(virtualKeyboardWidget, &virtualkeyboard::enterBtnPressed, this, &TodoAppWidget::editItemWrapper); + QObject::connect(virtualKeyboardWidget, &virtualkeyboard::closeBtnPressed, this, &TodoAppWidget::setDefaultListPageStatusText); ui->statusLabel->setText("Enter the edited item's name"); virtualKeyboardWidget->show(); } @@ -410,7 +412,7 @@ void todo::on_editItemBtn_clicked() } } -void todo::editItem(int index, QString replacement) { +void TodoAppWidget::editItem(int index, QString replacement) { QJsonDocument document = readTodoDatabase(); QJsonObject object = document.object(); QJsonArray mainArray = object["List"].toArray(); @@ -430,17 +432,17 @@ void todo::editItem(int index, QString replacement) { setupList(listArray.at(0).toString()); } -void todo::editItemWrapper(QString replacement) { +void TodoAppWidget::editItemWrapper(QString replacement) { editItem(currentEditItemIndex, replacement); currentEditItemIndex = NULL; } -void todo::resize() { +void TodoAppWidget::resize() { this->setGeometry(QRect(QPoint(0,0), qApp->primaryScreen()->geometry().size())); this->repaint(); } -void todo::on_itemsListWidget_itemClicked(QListWidgetItem *item) +void TodoAppWidget::on_itemsListWidget_itemClicked(QListWidgetItem *item) { if(item->checkState() == Qt::Unchecked) { item->setCheckState(Qt::Checked); diff --git a/src/apps/todo.h b/src/ui/apps/todo.h similarity index 90% rename from src/apps/todo.h rename to src/ui/apps/todo.h index 770a9b3..f176d03 100644 --- a/src/apps/todo.h +++ b/src/ui/apps/todo.h @@ -8,17 +8,17 @@ #include "virtualkeyboard.h" namespace Ui { -class todo; +class TodoAppWidget; } -class todo : public QWidget +class TodoAppWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit todo(QWidget *parent = nullptr); - ~todo(); + explicit TodoAppWidget(QWidget *parent = nullptr); + ~TodoAppWidget(); enum class currentView { home, list @@ -61,7 +61,7 @@ signals: void showToast(QString messageToDisplay); private: - Ui::todo *ui; + Ui::TodoAppWidget *ui; virtualkeyboard * virtualKeyboardWidget; }; diff --git a/src/apps/todo.ui b/src/ui/apps/todo.ui similarity index 99% rename from src/apps/todo.ui rename to src/ui/apps/todo.ui index d0cdb02..6e81b30 100644 --- a/src/apps/todo.ui +++ b/src/ui/apps/todo.ui @@ -1,7 +1,7 @@ - todo - + TodoAppWidget + 0 diff --git a/src/apps/userapps.cpp b/src/ui/apps/userapps.cpp similarity index 88% rename from src/apps/userapps.cpp rename to src/ui/apps/userapps.cpp index c25133d..784d62c 100644 --- a/src/apps/userapps.cpp +++ b/src/ui/apps/userapps.cpp @@ -3,9 +3,9 @@ #include "mainwindow.h" #include "generaldialog.h" -userapps::userapps(QWidget *parent) : +UserAppsWidget::UserAppsWidget(QWidget *parent) : QWidget(parent), - ui(new Ui::userapps) + ui(new Ui::UserAppsWidget) { ui->setupUi(this); ui->launchBtn->setProperty("type", "borderless"); @@ -21,12 +21,12 @@ userapps::userapps(QWidget *parent) : ui->statusBtn->setStyleSheet("background: lightGrey; font-size: 9pt; padding: 8px"); } -userapps::~userapps() +UserAppsWidget::~UserAppsWidget() { delete ui; } -void userapps::provideInfo(QJsonObject jsonInfo) +void UserAppsWidget::provideInfo(QJsonObject jsonInfo) { QString name = jsonInfo["Name"].toString(); appName = name; // It is for searching for json entry while disabling / enabling @@ -67,7 +67,7 @@ void userapps::provideInfo(QJsonObject jsonInfo) } // This function is needed when we dont want to repaint all widgets, but only change the the page (when no changes to the main JSON file were applied) -void userapps::changePageEnabling(bool SecondPage) +void UserAppsWidget::changePageEnabling(bool SecondPage) { if(SecondPage == true){ ui->stackedWidget->setCurrentIndex(1); @@ -77,7 +77,7 @@ void userapps::changePageEnabling(bool SecondPage) } } -void userapps::on_infoBtn_clicked() +void UserAppsWidget::on_infoBtn_clicked() { log("Launching user application information dialog", className); // https://stackoverflow.com/questions/28181627/how-to-convert-a-qjsonobject-to-qstring @@ -85,12 +85,12 @@ void userapps::on_infoBtn_clicked() global::text::textBrowserContents = jsonStringParsed; global::userApps::appInfoDialog = true; - generalDialogWindow = new generalDialog(); + generalDialogWindow = new GeneralDialog(); generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); generalDialogWindow->show(); } -void userapps::on_statusBtn_clicked() +void UserAppsWidget::on_statusBtn_clicked() { ui->statusBtn->setEnabled(false); @@ -129,22 +129,22 @@ void userapps::on_statusBtn_clicked() ui->statusBtn->setEnabled(true); } -void userapps::updateJsonFileSlotUA(QJsonDocument jsonDocumentProvided) +void UserAppsWidget::updateJsonFileSlotUA(QJsonDocument jsonDocumentProvided) { jsonDocument = jsonDocumentProvided; } -void userapps::on_launchBtn_clicked() +void UserAppsWidget::on_launchBtn_clicked() { // Some command to execute script or binary at "ExecPath" QJsonArray supportedDevices = jsonObject["SupportedDevices"].toArray(); // This will work even if we are looking for 'n306' and there is a device named 'n306b' because QJsonArray::contains() works that way - if(supportedDevices.contains("all") == false and supportedDevices.contains(global::deviceID.trimmed()) == false) { + if(supportedDevices.contains("all") == false and supportedDevices.contains(Device::getSingleton()->getID()) == false) { log("Warning: User application '" + appName + "' does not support this device", className); global::userApps::appCompatibilityDialog = true; global::userApps::appCompatibilityText = "Your device is not compatible with this app.
Continue anyway
?"; - generalDialogWindow = new generalDialog(); + generalDialogWindow = new GeneralDialog(); generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); generalDialogWindow->exec(); @@ -173,7 +173,7 @@ void userapps::on_launchBtn_clicked() } } -bool userapps::manageRequiredFeatures() +bool UserAppsWidget::manageRequiredFeatures() { // This should be already set to 'true', but just in case global::userApps::appCompatibilityLastContinueStatus = true; @@ -183,13 +183,11 @@ bool userapps::manageRequiredFeatures() int featureId = refJsonObject.toInt(); // Wi-Fi connection required if(featureId == 0) { - // Double 'if' conditions to avoid launching unnecesery testPing() in emu - if(global::deviceID != "emu\n") { - if(checkWifiState() != global::wifi::wifiState::configured) { - global::userApps::appCompatibilityText = "This app needs a Wi-Fi connection, continue anyway?"; - launchDialog = true; - } + if(checkWifiState() != global::wifi::wifiState::configured) { + global::userApps::appCompatibilityText = "This app needs a Wi-Fi connection, continue anyway?"; + launchDialog = true; } + } // Rooted kernel required if(featureId == 1) { @@ -202,7 +200,7 @@ bool userapps::manageRequiredFeatures() if(launchDialog == true) { global::userApps::appCompatibilityDialog = true; - generalDialogWindow = new generalDialog(); + generalDialogWindow = new GeneralDialog(); generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); generalDialogWindow->exec(); } @@ -214,7 +212,7 @@ bool userapps::manageRequiredFeatures() return true; } -QString userapps::parseJsonShow(QJsonObject json) +QString UserAppsWidget::parseJsonShow(QJsonObject json) { QString mainString; foreach(const QString& key, json.keys()) { diff --git a/src/apps/userapps.h b/src/ui/apps/userapps.h similarity index 84% rename from src/apps/userapps.h rename to src/ui/apps/userapps.h index 3063844..567d1bb 100644 --- a/src/apps/userapps.h +++ b/src/ui/apps/userapps.h @@ -13,17 +13,17 @@ #include namespace Ui { - class userapps; + class UserAppsWidget; } -class userapps : public QWidget +class UserAppsWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit userapps(QWidget * parent = nullptr); - ~userapps(); + explicit UserAppsWidget(QWidget * parent = nullptr); + ~UserAppsWidget(); QJsonDocument jsonDocument; // TODO: Optimize for RAM usage QJsonObject jsonObject; // Needed for 'App info' button QString jsonFilePath; @@ -46,8 +46,8 @@ private slots: void on_launchBtn_clicked(); private: - Ui::userapps * ui; - generalDialog * generalDialogWindow; + Ui::UserAppsWidget * ui; + GeneralDialog * generalDialogWindow; QDir appDir; QFile execPath; diff --git a/src/apps/userapps.ui b/src/ui/apps/userapps.ui similarity index 98% rename from src/apps/userapps.ui rename to src/ui/apps/userapps.ui index 8a075b0..6cbf575 100644 --- a/src/apps/userapps.ui +++ b/src/ui/apps/userapps.ui @@ -1,7 +1,7 @@ - userapps - + UserAppsWidget + 0 diff --git a/src/ui/crypto/encryptionmanager.cpp b/src/ui/crypto/encryptionmanager.cpp new file mode 100644 index 0000000..c9b9365 --- /dev/null +++ b/src/ui/crypto/encryptionmanager.cpp @@ -0,0 +1,360 @@ +#include "encryptionmanager.h" +#include "ui.h" +#include "ui_encryptionmanager.h" + +#include "functions.h" +#include "usbmsSplash.h" +#include +#include +#include +#include +#include +#include +#include + +CryptoManagerWidget::CryptoManagerWidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::CryptoManagerWidget) { + ui->setupUi(this); + ui->descriptionLabel->setFont(QFont("u001")); + ui->successDescriptionLabel->setFont(QFont("u001")); + ui->failureDescriptionLabel->setFont(QFont("u001")); + ui->warningDescriptionLabel->setFont(QFont("u001")); + + // Stylesheet + UI::applyStyle(*this, "eink"); + + ui->encryptionSetupLabel->setStyleSheet("font-size: 15pt; font-weight: bold"); + ui->descriptionLabel->setStyleSheet("font-size: 10pt"); + ui->successLabel->setStyleSheet("font-size: 15pt; font-weight: bold"); + ui->successDescriptionLabel->setStyleSheet("font-size: 10pt"); + ui->failureLabel->setStyleSheet("font-size: 15pt; font-weight: bold"); + ui->failureDescriptionLabel->setStyleSheet("font-size: 10pt"); + ui->setupContinueBtn->setStyleSheet("background: lightGrey; border: 3px solid black; color: black; padding: 10px; outline: none; font-size: 10pt; font-weight: bold; border-radius: 10px"); + ui->setupAbortBtn->setStyleSheet("background: lightGrey; border: 3px solid black; color: black; padding: 10px; outline: none; font-size: 10pt; font-weight: bold; border-radius: 10px"); + ui->exitSuccessBtn->setStyleSheet("background: lightGrey; border: 3px solid black; color: black; padding: 10px; outline: none; font-size: 10pt; font-weight: bold; border-radius: 10px"); + ui->failureContinueBtn->setStyleSheet("background: lightGrey; border: 3px solid black; color: black; padding: 10px; outline: none; font-size: 10pt; font-weight: bold; border-radius: 10px"); + ui->acceptBtn->setStyleSheet("background: lightGrey; border: 3px solid black; color: black; padding: 10px; outline: none; font-size: 10pt; font-weight: bold; border-radius: 10px"); + ui->usbmsBtn->setStyleSheet("background: lightGrey; border: 3px solid black; color: black; padding: 10px; outline: none; font-size: 10pt; font-weight: bold; border-radius: 10px"); + ui->warningLabel->setStyleSheet("font-size: 15pt; font-weight: bold"); + ui->warningDescriptionLabel->setStyleSheet("font-size: 10pt"); + + // Getting the screen's size + float sW = QGuiApplication::screens()[0]->size().width(); + float sH = QGuiApplication::screens()[0]->size().height(); + float stdIconWidth; + float stdIconHeight; + { + stdIconWidth = sW / 1.50; + stdIconHeight = sH / 1.50; + QPixmap pixmap(":/resources/encryption.png"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->encryptionImageLabel->setPixmap(scaledPixmap); + } + { + stdIconWidth = sW / 1.65; + stdIconHeight = sH / 1.65; + QPixmap pixmap(":/resources/check-display.png"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->checkImageLabel->setPixmap(scaledPixmap); + } + { + stdIconWidth = sW / 1.65; + stdIconHeight = sH / 1.65; + QPixmap pixmap(":/resources/error.png"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->failureImageLabel->setPixmap(scaledPixmap); + } + { + stdIconWidth = sW / 1.50; + stdIconHeight = sH / 1.50; + QPixmap pixmap(":/resources/alert-triangle.png"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->warningImageLabel->setPixmap(scaledPixmap); + } + + hourglassAnimationWidgetWindow = new hourglassAnimationWidget(); + ui->hourglassWidget->insertWidget(0, hourglassAnimationWidgetWindow); + ui->hourglassWidget->setCurrentIndex(0); + + setDefaultWorkDir(); + if (checkconfig(".config/18-encrypted_storage/initial_setup_done") == true or checkconfig("/external_root/run/encfs_repack") == true) { + ui->activityWidget->hide(); + if (checkconfig("/external_root/run/encfs_repack") == false) { + setupPassphraseDialogMode = 1; + } else { + setupPassphraseDialogMode = 2; + } + QTimer::singleShot(500, this, SLOT(setupPassphraseDialog())); + } else { + QDir dir("/mnt/onboard/onboard/encfs-dropbox"); + if (dir.isEmpty()) { + ui->activityWidget->setCurrentIndex(4); + mkEncfsDirs(); + } + } +} + +CryptoManagerWidget::~CryptoManagerWidget() { + delete ui; +} + +void CryptoManagerWidget::on_setupContinueBtn_clicked() { + setupPassphraseDialogMode = 0; + setupPassphraseDialog(); +} + +void CryptoManagerWidget::setupPassphraseDialog() { + /* + * setupPassphraseDialogMode can be: + * 0: Initial setup + * 1: Normal behavior + * 2: Repack + */ + log("Showing passphrase dialog for mode " + QString::number(setupPassphraseDialogMode), className); + ui->activityWidget->hide(); + this->setStyleSheet("background-color: black"); + global::keyboard::keyboardDialog = true; + global::keyboard::encfsDialog = true; + global::keyboard::keyboardText = ""; + generalDialogWindow = new GeneralDialog(); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + connect(generalDialogWindow, SIGNAL(refreshScreen()), SLOT(refreshScreen())); + if (setupPassphraseDialogMode == 0) { + connect(generalDialogWindow, SIGNAL(destroyed(QObject *)), SLOT(setupEncryptedStorage())); + } else if (setupPassphraseDialogMode == 1) { + connect(generalDialogWindow, SIGNAL(destroyed(QObject *)), SLOT(unlockEncryptedStorage())); + } else { + connect(generalDialogWindow, SIGNAL(destroyed(QObject *)), SLOT(repackEncryptedStorage())); + } + connect(generalDialogWindow, SIGNAL(showToast(QString)), SLOT(showToast(QString))); + generalDialogWindow->show(); +} + +void CryptoManagerWidget::on_setupAbortBtn_clicked() { + log("Aborting setup", className); + setDefaultWorkDir(); + writeFile(".config/18-encrypted_storage/status", "false"); + quit_restart(); +} + +void CryptoManagerWidget::quit_restart() { + log("Restarting InkBox", className); + QProcess process; + process.startDetached("inkbox", QStringList()); + qApp->quit(); +} + +void CryptoManagerWidget::refreshScreen() { + this->repaint(); +} + +void CryptoManagerWidget::showToast(QString messageToDisplay) { + global::toast::message = messageToDisplay; + toastWindow = new toast(this); + toastWindow->setAttribute(Qt::WA_DeleteOnClose); + connect(toastWindow, SIGNAL(refreshScreen()), SLOT(refreshScreen())); + toastWindow->show(); +} + +void CryptoManagerWidget::setupEncryptedStorage() { + log("Setting up encrypted storage", className); + this->setStyleSheet("background-color: white"); + ui->activityWidget->show(); + if (global::encfs::cancelSetup == true) { + global::encfs::cancelSetup = false; + ui->activityWidget->setCurrentIndex(0); + } else { + mkEncfsDirs(); + QString bootstrapPassphrase = global::encfs::passphrase; + global::encfs::passphrase = ""; + writeFile("/external_root/run/encfs/encrypted_storage_create", "true"); + writeFile("/external_root/run/encfs/encrypted_storage_bootstrap_files_location", "/data/onboard/encfs-dropbox"); + writeFile("/external_root/run/encfs/encrypted_storage_bootstrap_archive_location", "/data/onboard/data.encfs"); + writeFile("/external_root/run/encfs/encrypted_storage_bootstrap_passphrase", bootstrapPassphrase); + setDefaultWorkDir(); + writeFile(".config/18-encrypted_storage/storage_list", "/data/onboard/encfs-decrypted"); + writeFile("/opt/ibxd", "encfs_restart\n"); + bool exitStatus; + ui->activityWidget->setCurrentIndex(3); + QTimer *t = new QTimer(this); + t->setInterval(1000); + connect(t, &QTimer::timeout, [&]() { + if (QFile::exists("/external_root/run/encrypted_storage_bootstrap_setup")) { + exitStatus = checkconfig("/external_root/run/encrypted_storage_bootstrap_setup"); + QFile::remove("/external_root/run/encrypted_storage_bootstrap_setup"); + setupExitWidget(exitStatus); + } + }); + t->start(); + } +} + +void CryptoManagerWidget::unlockEncryptedStorage() { + log("Trying to unlock encrypted storage", className); + if (global::encfs::cancelSetup == true) { + global::encfs::cancelSetup = false; + poweroff(true); + qApp->quit(); + } else { + this->setStyleSheet("background-color: white"); + ui->activityWidget->show(); + mkEncfsDirs(); + QString passphrase = global::encfs::passphrase; + global::encfs::passphrase = ""; + writeFile("/external_root/run/encfs/encrypted_storage_archive", "/data/onboard/data.encfs"); + writeFile("/external_root/run/encfs/encrypted_storage_mountpoint", "/data/onboard/encfs-decrypted"); + writeFile("/external_root/run/encfs/encrypted_storage_bindmount", "/kobo/mnt/onboard/onboard/encfs-decrypted"); + writeFile("/external_root/run/encfs/encrypted_storage_passphrase", passphrase); + writeFile("/opt/ibxd", "encfs_restart\n"); + bool exitStatus; + + QString passphraseTriesStr = readFile("/inkbox/encryptedStoragePassphraseTries"); + if (passphraseTriesStr.isEmpty()) { + passphraseTries = 0; + } else { + passphraseTries = passphraseTriesStr.toInt(); + passphraseTries++; + } + + ui->activityWidget->setCurrentIndex(3); + QTimer *t = new QTimer(this); + t->setInterval(1000); + connect(t, &QTimer::timeout, [&]() { + if (QFile::exists("/external_root/run/encfs_mounted")) { + exitStatus = true; + if (readFile("/external_root/run/encfs_mounted") != "true\n") { + exitStatus = false; + QFile::remove("/external_root/run/encfs_mounted"); + QString function = __func__; + log(function + ": Invalid passphrase", className); + if (setupMessageBoxRan == false) { + int delay = 0; + if (passphraseTries <= 3) { + if (passphraseTries == 0) { + writeFile("/inkbox/encryptedStoragePassphraseTries", "0"); + delay = 5000; + } else if (passphraseTries == 1) { + writeFile("/inkbox/encryptedStoragePassphraseTries", "1"); + delay = 10000; + } else if (passphraseTries == 2) { + writeFile("/inkbox/encryptedStoragePassphraseTries", "2"); + delay = 20000; + } else if (passphraseTries >= 3) { + writeFile("/inkbox/encryptedStoragePassphraseTries", "3"); + unsigned long currentEpoch = QDateTime::currentSecsSinceEpoch(); + currentEpoch += 86400; + QString unlockTime_str = QString::number(currentEpoch); + global::encfs::unlockTime = QDateTime::fromTime_t(currentEpoch).toString(); + global::encfs::lockdownMessage = "FATAL: 4 invalid passphrase tries, locking down device until " + global::encfs::unlockTime; + writeFile("/external_root/boot/flags/ENCRYPT_LOCK", unlockTime_str + "\n"); + global::encfs::lockdown = true; + setupMessageBoxRan = true; + + alertWindow = new SplashAlertWidget(); + alertWindow->setAttribute(Qt::WA_DeleteOnClose); + alertWindow->showFullScreen(); + } + + if (passphraseTries <= 2) { + QTimer::singleShot(delay, this, SLOT(setupFailedAuthenticationMessageBox())); + setupMessageBoxRan = true; + } + } + } + } else { + log("Unlocking successful", className); + quit_restart(); + } + } + }); + t->start(); + } +} + +void CryptoManagerWidget::mkEncfsDirs() { + log("Creating encrypted storage directories", className); + QDir encfsDir; + QString encfsPath("/external_root/run/encfs"); + encfsDir.mkpath(encfsPath); + QDir dumpDir; + QString dumpPath("/mnt/onboard/onboard/encfs-dropbox"); + dumpDir.mkpath(dumpPath); + QDir decDir; + QString decPath("/mnt/onboard/onboard/encfs-decrypted"); + decDir.mkpath(decPath); +} + +void CryptoManagerWidget::on_exitSuccessBtn_clicked() { + setDefaultWorkDir(); + writeFile(".config/18-encrypted_storage/initial_setup_done", "true"); + quit_restart(); +} + +void CryptoManagerWidget::setupExitWidget(bool exitStatus) { + if (setupExitWidgetRan == false) { + if (exitStatus == true) { + ui->activityWidget->setCurrentIndex(1); + } else { + writeFile(".config/18-encrypted_storage/status", "false"); + ui->activityWidget->setCurrentIndex(2); + } + setupExitWidgetRan = true; + } +} + +void CryptoManagerWidget::on_failureContinueBtn_clicked() { + setDefaultWorkDir(); + writeFile(".config/18-encrypted_storage/initial_setup_done", "true"); + quit_restart(); +} + +void CryptoManagerWidget::setupFailedAuthenticationMessageBox() { + log("Showing 'Authentication failed' message box", className); + ui->activityWidget->hide(); + QMessageBox::critical(this, tr("Invalid argument"), tr("Invalid passphrase. Please try again.")); + quit_restart(); +} + +void CryptoManagerWidget::on_acceptBtn_clicked() { + writeFile(".config/18-encrypted_storage/status", "false"); + quit_restart(); +} + +void CryptoManagerWidget::on_usbmsBtn_clicked() { + log("Showing USBMS splash", className); + global::usbms::launchUsbms = true; + usbmsWindow = new USBMSSplashWidget(); + usbmsWindow->setAttribute(Qt::WA_DeleteOnClose); + usbmsWindow->setGeometry(QRect(QPoint(0, 0), screen()->geometry().size())); + usbmsWindow->show(); +} + +void CryptoManagerWidget::repackEncryptedStorage() { + log("Repacking encrypted storage", className); + if (global::encfs::cancelSetup == true) { + global::encfs::cancelSetup = false; + quit_restart(); + } else { + this->setStyleSheet("background-color: white"); + ui->activityWidget->show(); + mkEncfsDirs(); + QString passphrase = global::encfs::passphrase; + global::encfs::passphrase = ""; + writeFile("/external_root/run/encfs/encrypted_storage_repack_passphrase", passphrase); + QFile::remove("/external_root/run/openrc/started/encfs"); + writeFile("/opt/ibxd", "encfs_restart\n"); + bool exitStatus; + ui->activityWidget->setCurrentIndex(3); + QTimer *t = new QTimer(this); + t->setInterval(1000); + connect(t, &QTimer::timeout, [&]() { + if (QFile::exists("/external_root/run/encfs_repack_status")) { + exitStatus = checkconfig("/external_root/run/encfs_repack_status"); + QFile::remove("/external_root/run/encfs_repack_status"); + setupExitWidget(exitStatus); + } + }); + t->start(); + } +} diff --git a/src/encfs/encryptionmanager.h b/src/ui/crypto/encryptionmanager.h similarity index 77% rename from src/encfs/encryptionmanager.h rename to src/ui/crypto/encryptionmanager.h index e90fdb3..125da05 100644 --- a/src/encfs/encryptionmanager.h +++ b/src/ui/crypto/encryptionmanager.h @@ -5,20 +5,20 @@ #include "generaldialog.h" #include "toast.h" #include "hourglassanimationwidget.h" -#include "alert.h" +#include "splashAlert.h" namespace Ui { -class encryptionManager; +class CryptoManagerWidget; } -class encryptionManager : public QWidget +class CryptoManagerWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit encryptionManager(QWidget *parent = nullptr); - ~encryptionManager(); + explicit CryptoManagerWidget(QWidget *parent = nullptr); + ~CryptoManagerWidget(); bool setupExitWidgetRan = false; int setupPassphraseDialogMode; bool setupMessageBoxRan = false; @@ -43,12 +43,12 @@ private slots: void repackEncryptedStorage(); private: - Ui::encryptionManager *ui; - generalDialog * generalDialogWindow; + Ui::CryptoManagerWidget *ui; + GeneralDialog * generalDialogWindow; toast * toastWindow; hourglassAnimationWidget * hourglassAnimationWidgetWindow; - alert * alertWindow; - usbmsSplash *usbmsWindow; + SplashAlertWidget * alertWindow; + USBMSSplashWidget *usbmsWindow; }; #endif // ENCRYPTIONMANAGER_H diff --git a/src/encfs/encryptionmanager.ui b/src/ui/crypto/encryptionmanager.ui similarity index 99% rename from src/encfs/encryptionmanager.ui rename to src/ui/crypto/encryptionmanager.ui index 27bc478..595628e 100644 --- a/src/encfs/encryptionmanager.ui +++ b/src/ui/crypto/encryptionmanager.ui @@ -1,7 +1,7 @@ - encryptionManager - + CryptoManagerWidget + 0 diff --git a/src/ui/eink.qrc b/src/ui/eink.qrc new file mode 100644 index 0000000..4ca53b5 --- /dev/null +++ b/src/ui/eink.qrc @@ -0,0 +1,124 @@ + + + ../resources/checkbox-checked.png + ../resources/checkbox-unchecked.png + ../resources/align-center.png + ../resources/align-justify.png + ../resources/align-left.png + ../resources/align-right.png + ../resources/chesterton.jpg + ../resources/alcott.jpg + ../resources/davies.jpg + ../resources/king.jpg + ../resources/star.png + ../resources/starred_star.png + ../resources/close.png + ../resources/chevron-left.png + ../resources/chevron-right.png + ../resources/chevron-down.png + ../resources/chevron-up.png + ../resources/christie.png + ../resources/exit.png + ../resources/usbms.png + ../resources/settings.png + ../resources/search.png + ../resources/power.png + ../resources/book.png + ../resources/apps.png + ../resources/battery_half.png + ../resources/battery_full.png + ../resources/battery_empty.png + ../resources/battery_charging.png + ../resources/alert.png + ../resources/eink-dark.qss + ../resources/frontlight.png + ../resources/fonts/CrimsonPro-Bold.ttf + ../resources/fonts/CrimsonPro-Italic.ttf + ../resources/fonts/CrimsonPro-Regular.ttf + ../resources/check.png + ../resources/minus.png + ../resources/plus.png + ../resources/battery_alert.png + ../resources/apps-inverted.png + ../resources/home.png + ../resources/settings-inverted.png + ../resources/kobox-icon.png + ../resources/X11.png + ../resources/info.png + ../resources/nightmode-empty.png + ../resources/nightmode-full.png + ../resources/backspace.png + ../resources/x-circle.png + ../resources/fonts/Bitter-MediumItalic.ttf + ../resources/fonts/Bitter-Medium.ttf + ../resources/fonts/Bitter-Bold.ttf + ../resources/fonts/Bitter-BoldItalic.ttf + ../resources/fonts/CrimsonPro-BoldItalic.ttf + ../resources/fonts/IbarraRealNova-MediumItalic.ttf + ../resources/fonts/IbarraRealNova-Medium.ttf + ../resources/fonts/IbarraRealNova-BoldItalic.ttf + ../resources/fonts/IbarraRealNova-Bold.ttf + ../resources/wifi-connected.png + ../resources/wifi-off.png + ../resources/wifi-standby.png + ../resources/zoom-in.png + ../resources/zoom-out.png + ../resources/encryption.png + ../resources/check-display.png + ../resources/hourglass-bottom.png + ../resources/hourglass-top.png + ../resources/error.png + ../resources/alert-triangle.png + ../resources/online-library.png + ../resources/online-library-inverted.png + ../resources/cover_unavailable.png + ../resources/clock-inverted.png + ../resources/clock.png + ../resources/eink-square-encfs.qss + ../resources/tzlist + ../resources/edit.png + ../resources/save.png + ../resources/book_inverted.png + ../resources/arrow-left.png + ../resources/arrow-right.png + ../resources/file-text.png + ../resources/pin.png + ../resources/highlight.png + ../resources/unhighlight.png + ../resources/view-highlights.png + ../resources/stop.png + ../resources/refresh.png + ../resources/hide.png + ../resources/show.png + ../resources/christie.jpg + ../resources/encryption-small.png + ../resources/lock.png + ../resources/public.png + ../resources/wifi-0.png + ../resources/wifi-25.png + ../resources/wifi-50.png + ../resources/wifi-75.png + ../resources/wifi-100.png + ../resources/log.png + ../resources/new.png + ../resources/checkbox-unchecked-small.png + ../resources/checkbox-checked-small.png + ../resources/checkbox-x-small.png + ../resources/checkbox-x.png + ../resources/folder.png + ../resources/question-mark.png + ../resources/refresh-small.png + ../resources/checkbox-indeterminate.png + ../resources/egg/0.jpg + ../resources/egg/1.jpg + ../resources/music-note.png + ../resources/music-library.png + ../resources/next.png + ../resources/music-queue.png + ../resources/play.png + ../resources/previous.png + ../resources/pause.png + ../resources/clean.png + ../resources/usbms-inverted.png + + diff --git a/src/homeWidget/homepagewidget.cpp b/src/ui/home/homepagewidget.cpp similarity index 85% rename from src/homeWidget/homepagewidget.cpp rename to src/ui/home/homepagewidget.cpp index 1e60bb0..96e68ac 100644 --- a/src/homeWidget/homepagewidget.cpp +++ b/src/ui/home/homepagewidget.cpp @@ -1,36 +1,52 @@ #include "homepagewidget.h" #include "ui_homepagewidget.h" +#include "device.h" #include #include "functions.h" -homePageWidget::homePageWidget(QWidget *parent) : +HomePageWidget::HomePageWidget(QWidget *parent) : QWidget(parent), - ui(new Ui::homePageWidget) + ui(new Ui::HomePageWidget) { + Device * device = Device::getSingleton(); + Device::ScreenSize screenSize = device->getScreenSize(); + ui->setupUi(this); // Getting the screen's size sW = QGuiApplication::screens()[0]->size().width(); sH = QGuiApplication::screens()[0]->size().height(); - if(global::deviceID == "n705\n") { + + if(screenSize == Device::ScreenSize::SMALL) { stdIconWidth = sW / 23; stdIconHeight = sH / 23; - } - else if(global::deviceID == "n905\n" or global::deviceID == "kt\n") { - stdIconWidth = sW / 25; - stdIconHeight = sH / 25; - } - else if(global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n437\n" or global::deviceID == "n306\n" or global::deviceID == "n249\n" or global::deviceID == "emu\n") { + bookTitleTruncateThreshold = 20; + stdIconWidthDivider = 8; + stdIconHeightDivider = 8; + } else if(screenSize == Device::ScreenSize::MEDIUM) { stdIconWidth = sW / 23.5; stdIconHeight = sH / 23.5; - } - else { + bookTitleTruncateThreshold = 25; + stdIconWidthDivider = 7; + stdIconHeightDivider = 7; + } else if(screenSize == Device::ScreenSize::LARGE) { + stdIconWidth = sW / 24; + stdIconHeight = sH / 24; + bookTitleTruncateThreshold = 25; + stdIconWidthDivider = 6.5; + stdIconHeightDivider = 6.5; + } else if(screenSize == Device::ScreenSize::VERY_LARGE) { stdIconWidth = sW / 25; stdIconHeight = sH / 25; + bookTitleTruncateThreshold = 35; + stdIconWidthDivider = 6; + stdIconHeightDivider = 6; } + + ui->recentBooksIconLabel->setPixmap(QPixmap(":/resources/file-text.png").scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation)); ui->pinnedBooksIconLabel->setPixmap(QPixmap(":/resources/pin.png").scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation)); @@ -43,46 +59,8 @@ homePageWidget::homePageWidget(QWidget *parent) : pinnedBooksBtnArray.resize(global::homePageWidget::pinnedBooksNumber); pinnedBooksTitleArray.resize(global::homePageWidget::pinnedBooksNumber); - if(global::deviceID == "n705\n") { - bookTitleTruncateThreshold = 20; - } - else if(global::deviceID == "n873\n") { - bookTitleTruncateThreshold = 35; - } - else { - bookTitleTruncateThreshold = 25; - } - - if(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "kt\n") { - stdIconWidthDivider = 8; - stdIconHeightDivider = 8; - stdIconWidth = sW / stdIconWidthDivider; - stdIconHeight = sH / stdIconHeightDivider; - } - else if(global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n306\n" or global::deviceID == "emu\n") { - stdIconWidthDivider = 7; - stdIconHeightDivider = 7; - stdIconWidth = sW / stdIconWidthDivider; - stdIconHeight = sH / stdIconHeightDivider; - } - else if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { - stdIconWidthDivider = 6.5; - stdIconHeightDivider = 6.5; - stdIconWidth = sW / stdIconWidthDivider; - stdIconHeight = sH / stdIconHeightDivider; - } - else if(global::deviceID == "n873\n") { - stdIconWidthDivider = 6; - stdIconHeightDivider = 6; - stdIconWidth = sW / stdIconWidthDivider; - stdIconHeight = sH / stdIconHeightDivider; - } - else { - stdIconWidthDivider = 8; - stdIconHeightDivider = 8; - stdIconWidth = sW / stdIconWidthDivider; - stdIconHeight = sH / stdIconHeightDivider; - } + stdIconWidth = sW / stdIconWidthDivider; + stdIconHeight = sH / stdIconHeightDivider; if(!QFile::exists(global::localLibrary::databasePath)) { global::toast::modalToast = true; @@ -95,12 +73,12 @@ homePageWidget::homePageWidget(QWidget *parent) : } } -homePageWidget::~homePageWidget() +HomePageWidget::~HomePageWidget() { delete ui; } -void homePageWidget::openBook(QString bookPath) { +void HomePageWidget::openBook(QString bookPath) { if(!bookPath.isEmpty()) { emit openBookSignal(bookPath, false); } @@ -109,11 +87,11 @@ void homePageWidget::openBook(QString bookPath) { } } -void homePageWidget::refreshScreenNative() { +void HomePageWidget::refreshScreenNative() { emit refreshScreen(); } -void homePageWidget::setupDisplay(bool databaseGenerated) { +void HomePageWidget::setupDisplay(bool databaseGenerated) { if(databaseGenerated == true) { toastWindow->close(); } @@ -173,8 +151,8 @@ void homePageWidget::setupDisplay(bool databaseGenerated) { verticalLayoutArray[i] = new QVBoxLayout(); // Book icon button - QObject::connect(bookBtnArray[i], &QClickableLabel::bookPath, this, &homePageWidget::openBook); - QObject::connect(bookBtnArray[i], &QClickableLabel::longPressString, this, &homePageWidget::openBookOptionsDialog); + QObject::connect(bookBtnArray[i], &QClickableLabel::bookPath, this, &HomePageWidget::openBook); + QObject::connect(bookBtnArray[i], &QClickableLabel::longPressString, this, &HomePageWidget::openBookOptionsDialog); bookBtnArray[i]->setAlignment(Qt::AlignCenter); bookBtnArray[i]->setFont(QFont("u001")); bookBtnArray[i]->setStyleSheet("color: black; background-color: white; border-radius: 10px; padding: 10px"); @@ -277,8 +255,8 @@ void homePageWidget::setupDisplay(bool databaseGenerated) { pinnedBooksVerticalLayoutArray[i] = new QVBoxLayout(); // Book icon button - QObject::connect(pinnedBooksBtnArray[i], &QClickableLabel::bookPath, this, &homePageWidget::openBook); - QObject::connect(pinnedBooksBtnArray[i], &QClickableLabel::longPressString, this, &homePageWidget::openBookOptionsDialog); + QObject::connect(pinnedBooksBtnArray[i], &QClickableLabel::bookPath, this, &HomePageWidget::openBook); + QObject::connect(pinnedBooksBtnArray[i], &QClickableLabel::longPressString, this, &HomePageWidget::openBookOptionsDialog); pinnedBooksBtnArray[i]->setAlignment(Qt::AlignCenter); pinnedBooksBtnArray[i]->setFont(QFont("u001")); pinnedBooksBtnArray[i]->setStyleSheet("color: black; background-color: white; border-radius: 10px; padding: 10px"); @@ -355,26 +333,26 @@ void homePageWidget::setupDisplay(bool databaseGenerated) { QTimer::singleShot(500, this, SLOT(refreshScreenNative())); } -void homePageWidget::setupDisplaySlot() { +void HomePageWidget::setupDisplaySlot() { setupDisplay(true); } -void homePageWidget::setupDisplayWithDatabase() { +void HomePageWidget::setupDisplayWithDatabase() { global::localLibrary::headless = true; - localLibraryWidget * localLibraryWidgetWindow = new localLibraryWidget(this); + LocalLibraryWidget * localLibraryWidgetWindow = new LocalLibraryWidget(this); localLibraryWidgetWindow->setAttribute(Qt::WA_DeleteOnClose); localLibraryWidgetWindow->hide(); - QObject::connect(localLibraryWidgetWindow, &localLibraryWidget::destroyed, this, &homePageWidget::setupDisplaySlot); + QObject::connect(localLibraryWidgetWindow, &LocalLibraryWidget::destroyed, this, &HomePageWidget::setupDisplaySlot); } -void homePageWidget::showToast(QString messageToDisplay) { +void HomePageWidget::showToast(QString messageToDisplay) { global::toast::message = messageToDisplay; toastWindow = new toast(this); toastWindow->setAttribute(Qt::WA_DeleteOnClose); toastWindow->show(); } -void homePageWidget::openBookOptionsDialog(QString bookPath) { +void HomePageWidget::openBookOptionsDialog(QString bookPath) { int bookID; // Finding bookID from bookPath @@ -403,23 +381,23 @@ void homePageWidget::openBookOptionsDialog(QString bookPath) { log("Opening book options dialog for book with path '" + bookPath + "', ID " + QString::number(bookID), className); global::localLibrary::bookOptionsDialog::bookID = bookID; global::localLibrary::bookOptionsDialog::deleteOption = false; - bookOptionsDialog * bookOptionsDialogWindow = new bookOptionsDialog(this); - QObject::connect(bookOptionsDialogWindow, &bookOptionsDialog::openLocalBookInfoDialog, this, &homePageWidget::openLocalBookInfoDialog); - QObject::connect(bookOptionsDialogWindow, &bookOptionsDialog::showToast, this, &homePageWidget::showToast); - QObject::connect(bookOptionsDialogWindow, &bookOptionsDialog::destroyed, this, &homePageWidget::handlePossibleBookPin); + BookOptionsDialog * bookOptionsDialogWindow = new BookOptionsDialog(this); + QObject::connect(bookOptionsDialogWindow, &BookOptionsDialog::openLocalBookInfoDialog, this, &HomePageWidget::openLocalBookInfoDialog); + QObject::connect(bookOptionsDialogWindow, &BookOptionsDialog::showToast, this, &HomePageWidget::showToast); + QObject::connect(bookOptionsDialogWindow, &BookOptionsDialog::destroyed, this, &HomePageWidget::handlePossibleBookPin); bookOptionsDialogWindow->setAttribute(Qt::WA_DeleteOnClose); bookOptionsDialogWindow->setWindowFlags(Qt::FramelessWindowHint | Qt::Popup); bookOptionsDialogWindow->show(); } -void homePageWidget::openLocalBookInfoDialog() { +void HomePageWidget::openLocalBookInfoDialog() { global::bookInfoDialog::localInfoDialog = true; - bookInfoDialog * bookInfoDialogWindow = new bookInfoDialog(this); + BookInfoDialog * bookInfoDialogWindow = new BookInfoDialog(this); bookInfoDialogWindow->setAttribute(Qt::WA_DeleteOnClose); bookInfoDialogWindow->show(); } -void homePageWidget::handlePossibleBookPin() { +void HomePageWidget::handlePossibleBookPin() { if(global::localLibrary::bookOptionsDialog::bookPinAction == true) { QTimer::singleShot(3100, this, [&]() { emit relaunchHomePageWidget(); diff --git a/src/homeWidget/homepagewidget.h b/src/ui/home/homepagewidget.h similarity index 83% rename from src/homeWidget/homepagewidget.h rename to src/ui/home/homepagewidget.h index 1273688..86f04e2 100644 --- a/src/homeWidget/homepagewidget.h +++ b/src/ui/home/homepagewidget.h @@ -11,17 +11,17 @@ #include "bookinfodialog.h" namespace Ui { -class homePageWidget; +class HomePageWidget; } -class homePageWidget : public QWidget +class HomePageWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit homePageWidget(QWidget *parent = nullptr); - ~homePageWidget(); + explicit HomePageWidget(QWidget *parent = nullptr); + ~HomePageWidget(); int sW; int sH; int stdIconWidth; @@ -48,11 +48,11 @@ private slots: void handlePossibleBookPin(); private: - Ui::homePageWidget *ui; - localLibraryWidget * localLibraryWidgetWindow; + Ui::HomePageWidget *ui; + LocalLibraryWidget * localLibraryWidgetWindow; toast * toastWindow; - bookOptionsDialog * bookOptionsDialogWindow; - bookInfoDialog * bookInfoDialogWindow; + BookOptionsDialog * bookOptionsDialogWindow; + BookInfoDialog * bookInfoDialogWindow; QVector bookTitleArray; QVector horizontalLayoutArray; QVector verticalLayoutArray; diff --git a/src/homeWidget/homepagewidget.ui b/src/ui/home/homepagewidget.ui similarity index 98% rename from src/homeWidget/homepagewidget.ui rename to src/ui/home/homepagewidget.ui index 23ee70e..e1cf0bc 100644 --- a/src/homeWidget/homepagewidget.ui +++ b/src/ui/home/homepagewidget.ui @@ -1,7 +1,7 @@ - homePageWidget - + HomePageWidget + 0 diff --git a/src/ui/home/mainwindow.cpp b/src/ui/home/mainwindow.cpp new file mode 100644 index 0000000..72736f0 --- /dev/null +++ b/src/ui/home/mainwindow.cpp @@ -0,0 +1,1032 @@ +#include "mainwindow.h" +#include "apps.h" +#include "audiodialog.h" +#include "device.h" +#include "functions.h" +#include "settings.h" +#include "ui.h" +#include "ui_apps.h" +#include "ui_mainwindow.h" +#include "ui_settings.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +MainWindow::MainWindow(QWidget *parent) : + QMainWindow(parent), ui(new Ui::MainWindow) { + ui->setupUi(this); + + Device *device = Device::getSingleton(); + Device::ScreenSize screenSize = device->getScreenSize(); + + // Needed, the screen is shifted? + // ~Szybet + if (device->getID() == "n306") { + ui->centralwidget->layout()->setContentsMargins(4, 5, 8, 8); + } + + ui->inkboxLabel->setFont(QFont("u001")); + + ui->settingsBtn->setProperty("type", "borderless"); + ui->appsBtn->setProperty("type", "borderless"); + ui->quitBtn->setProperty("type", "borderless"); + ui->searchBtn->setProperty("type", "borderless"); + ui->pushButton->setProperty("type", "borderless"); + ui->libraryButton->setProperty("type", "borderless"); + ui->brightnessBtn->setProperty("type", "borderless"); + ui->homeBtn->setProperty("type", "borderless"); + ui->wifiBtn->setProperty("type", "borderless"); + ui->audioBtn->setProperty("type", "borderless"); + + ui->settingsBtn->setText(""); + ui->appsBtn->setText(""); + ui->pushButton->setText("\t\tReader"); + ui->libraryButton->setText("\t\tLibrary"); + ui->quitBtn->setText(""); + ui->searchBtn->setText(""); + ui->brightnessBtn->setText(""); + ui->homeBtn->setText(""); + ui->quoteLabel->setText(""); + ui->wifiBtn->setText(""); + ui->audioBtn->setText(""); + + ui->quotePictureLabel->setText(""); + + ui->quoteHeadingLabel->setStyleSheet("padding: 30px"); + ui->inkboxLabel->setStyleSheet("font-size: 10.5pt"); + ui->homeBtn->setStyleSheet("padding: 5px"); + + // Initializing some variables + global::battery::showLowBatteryDialog = true; + global::battery::showCriticalBatteryAlert = true; + global::usbms::showUsbmsDialog = true; + global::usbms::launchUsbms = false; + global::usbms::koboxExportExtensions = false; + global::mainwindow::tabSwitcher::repaint = true; + resetFullWindowException = false; + + // Getting the screen's size + sW = QGuiApplication::screens()[0]->size().width(); + sH = QGuiApplication::screens()[0]->size().height(); + + // Defining what the default icon size will be + if (screenSize == Device::ScreenSize::SMALL) { + stdIconWidth = sW / 12; + stdIconHeight = sH / 12; + brightnessIconWidth = sW / 24; + brightnessIconHeight = sH / 24; + homeIconWidth = sW / 18; + homeIconHeight = sW / 18; + wifiIconWidth = sW / 20.5; + wifiIconHeight = sH / 20.5; + } else if (screenSize == Device::ScreenSize::MEDIUM) { + stdIconWidth = sW / 14; + stdIconHeight = sH / 14; + brightnessIconWidth = sW / 26; + brightnessIconHeight = sH / 26; + homeIconWidth = sW / 20; + homeIconHeight = sW / 20; + wifiIconWidth = sW / 22.5; + wifiIconHeight = sH / 22.5; + } else if (screenSize == Device::ScreenSize::LARGE) { + stdIconWidth = sW / 12.5; + stdIconHeight = sH / 12.5; + brightnessIconWidth = sW / 24.5; + brightnessIconHeight = sH / 24.5; + homeIconWidth = sW / 18.5; + homeIconHeight = sW / 18.5; + wifiIconWidth = sW / 21; + wifiIconHeight = sH / 21; + } else { + stdIconWidth = sW / 14; + stdIconHeight = sH / 14; + brightnessIconWidth = sW / 26; + brightnessIconHeight = sH / 26; + homeIconWidth = sW / 20; + homeIconHeight = sW / 20; + wifiIconWidth = sW / 22.5; + wifiIconHeight = sH / 22.5; + } + + // Setting icons up + ui->pushButton->setIcon(QIcon(":/resources/book.png")); + ui->pushButton->setIconSize(QSize(stdIconWidth, stdIconHeight)); + ui->libraryButton->setIcon(QIcon(":/resources/online-library.png")); + ui->libraryButton->setIconSize(QSize(stdIconWidth, stdIconHeight)); + ui->searchBtn->setIcon(QIcon(":/resources/search.png")); + ui->searchBtn->setIconSize(QSize(stdIconWidth, stdIconHeight)); + ui->settingsBtn->setIcon(QIcon(":/resources/settings.png")); + ui->settingsBtn->setIconSize(QSize(stdIconWidth, stdIconHeight)); + ui->appsBtn->setIcon(QIcon(":/resources/apps.png")); + ui->appsBtn->setIconSize(QSize(stdIconWidth, stdIconHeight)); + ui->quitBtn->setIcon(QIcon(":/resources/power.png")); + ui->quitBtn->setIconSize(QSize(stdIconWidth, stdIconHeight)); + + ui->homeBtn->setIcon(QIcon(":/resources/home.png")); + ui->homeBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); + + ui->brightnessBtn->setIcon(QIcon(":/resources/frontlight.png")); + ui->brightnessBtn->setIconSize(QSize(brightnessIconWidth, brightnessIconHeight)); + + if (global::audio::enabled == false) { + ui->audioBtn->hide(); + ui->audioLine->hide(); + } else { + ui->audioBtn->setIcon(QIcon(":/resources/music-note.png")); + ui->audioBtn->setIconSize(QSize(wifiIconWidth, wifiIconHeight)); + ui->labelLine_1->hide(); + ui->labelLine_2->hide(); + } + + updateWifiAble(); + if (device->supportsWifi()) { + // Start Wi-Fi icon updater + QTimer *wifiIconTimer = new QTimer(this); + wifiIconTimer->setInterval(2500); + connect(wifiIconTimer, SIGNAL(timeout()), this, SLOT(updateWifiIcon())); + wifiIconTimer->start(); + } + setBatteryIcon(); + + ui->brightnessBtn->setStyleSheet("font-size: 9pt; padding-bottom: 5px; padding-top: 5px; padding-left: 8px; padding-right: 8px;"); + ui->wifiBtn->setStyleSheet("font-size: 9pt; padding-bottom: 0px; padding-top: 0px; padding-left: 8px; padding-right: 8px"); + + // Checking if we have a Mini or Touch there + if (screenSize <= Device::ScreenSize::MEDIUM) { + ui->batteryIcon->setStyleSheet("font-size: 5pt; padding-bottom: 0px; padding-top: 0px; padding-left: 1px; padding-right: 1px;"); + } else if (screenSize == Device::ScreenSize::LARGE) { + ui->batteryIcon->setStyleSheet("font-size: 5pt; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; padding-right: 0px;"); + } else if (screenSize == Device::ScreenSize::VERY_LARGE) { + ui->batteryIcon->setStyleSheet("font-size: 5pt; padding-bottom: 0px; padding-top: 0px; padding-left: 0px; padding-right: 0px;"); + } + + ui->line_7->setStyleSheet("padding: 0px"); + ui->batteryIcon->setText(""); + ui->batteryLabel->setText(""); + ui->timeLabel->setText(""); + ui->batteryLabel->setStyleSheet("padding-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px"); + + // Deleting/Hiding "Library" button if device is not WiFi-able + // NOTE: Using deleteLater() on these elements causes a segmentation fault and aborts the whole program when the Settings, Apps or Home button is pressed. No idea why. + if (!device->supportsWifi()) { + ui->libraryButton->hide(); + ui->line_10->hide(); + } + + // Stylesheet + UI::applyStyle(*this, "eink"); + + // Custom settings + // Reading from the config files and tweaking the program according to the options set + // Demo setting, changes "Welcome to InkBox" label to "InkBox" + if (checkconfig(".config/01-demo/config") == true) { + ui->inkboxLabel->setText("InkBox"); + } + + // Dark mode; write to the Kobo Nightmode FIFO + if (checkconfig(".config/10-dark_mode/config") == true) { + writeFile("/tmp/invertScreen", "y"); + } else { + writeFile("/tmp/invertScreen", "n"); + } + + // Clock setting to show seconds + if (checkconfig(".config/02-clock/config") == true) { + QTimer *t = new QTimer(this); + t->setInterval(500); + connect(t, &QTimer::timeout, [&]() { + QString time = QTime::currentTime().toString("hh:mm:ss"); + ui->timeLabel->setText(time); + ui->batteryLabel->setText(QString::number(Device::getSingleton()->getBatteryLevel())); + }); + t->start(); + } else { + QTimer *t = new QTimer(this); + t->setInterval(500); + connect(t, &QTimer::timeout, [&]() { + QString time = QTime::currentTime().toString("hh:mm"); + ui->timeLabel->setText(time); + ui->batteryLabel->setText(QString::number(Device::getSingleton()->getBatteryLevel())); + }); + t->start(); + } + + // Battery watchdog + QTimer *batteryWatchdog = new QTimer(this); + batteryWatchdog->setInterval(2000); + connect(batteryWatchdog, &QTimer::timeout, [&]() { + // Checking if battery level is low + if (global::battery::showCriticalBatteryAlert != true) { + ; + } else { + if (Device::getSingleton()->isBatteryCritical() && !Device::getSingleton()->isUSBPluggedIn()) { + log("Warning! Battery is at a critical charge level!", className); + openCriticalBatteryAlertWindow(); + } + } + + if (global::battery::showLowBatteryDialog != true) { + // Do nothing, since a dialog should already have been displayed and (probably) dismissed + ; + } else { + if (Device::getSingleton()->isBatteryLow() && !Device::getSingleton()->isUSBPluggedIn()) { + if (global::battery::batteryAlertLock == true) { + ; + } else { + log("Warning! Battery is low!", className); + openLowBatteryDialog(); + } + } + } + }); + batteryWatchdog->start(); + + // We set the brightness level saved in the config file + QTimer::singleShot(2000, this, SLOT(setInitialBrightness())); + + // If new files are found in /mnt/onboard/onboard/encfs-dropbox, ask if user wants to encrypt them + if (checkconfig(".config/18-encrypted_storage/status") == true) { + QDir encfsDropboxDir("/mnt/onboard/onboard/encfs-dropbox"); + if (!encfsDropboxDir.isEmpty()) { + QTimer::singleShot(1000, this, SLOT(openEncfsRepackDialog())); + } + } + + // Global reading settings + if (readFile(".config/16-global_reading_settings/config").isEmpty()) { + checked_box = false; + writeconfig(".config/16-global_reading_settings/config", "GlobalReadingSettings="); + } + + if (checkconfig(".config/05-quote/config") == false) { + stdIconWidth = sW / 2; + stdIconHeight = sH / 2; + int quote_value = displayQuote(); + if (quote_value == 1) { + QPixmap pixmap(":/resources/chesterton.jpg"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->quotePictureLabel->setPixmap(scaledPixmap); + ui->quoteLabel->setText("“A good novel tells us the truth about its hero; but a bad novel tells us the truth about its author.”\n― G.K. Chesterton"); + } + if (quote_value == 2) { + QPixmap pixmap(":/resources/alcott.jpg"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->quotePictureLabel->setPixmap(scaledPixmap); + ui->quoteLabel->setText("“I've got the key to my castle in the air, but whether I can unlock the door remains to be seen.”\n― Louisa May Alcott"); + } + if (quote_value == 3) { + QPixmap pixmap(":/resources/king.jpg"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->quotePictureLabel->setPixmap(scaledPixmap); + ui->quoteLabel->setText("“Quiet people have the loudest minds”\n― Stephen King"); + } + if (quote_value == 4) { + QPixmap pixmap(":/resources/davies.jpg"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->quotePictureLabel->setPixmap(scaledPixmap); + ui->quoteLabel->setText("“Authors like cats because they are such quiet, lovable, wise creatures, and cats like authors for the same reasons.”\n― Robertson Davies"); + } + if (quote_value == 5) { + QPixmap pixmap(":/resources/christie.png"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->quotePictureLabel->setPixmap(scaledPixmap); + ui->quoteLabel->setText("“One of the saddest things in life, is the things one remembers.”\n― Agatha Christie"); + } + ui->homeStackedWidget->setCurrentIndex(0); + } else { + setupHomePageWidget(); + } + + // Check if it's the first boot since an update and confirm that it installed successfully + if (checkconfig("/opt/inkbox_genuine") == true) { + if (checkconfig("/external_root/opt/update/inkbox_updated") == true) { + QString version = readFile("/external_root/opt/isa/version"); + QString updatemsg = "InkBox update to version "; + updatemsg = updatemsg.append(version); + updatemsg = updatemsg.remove(QRegExp("[\n]")); + updatemsg = updatemsg.append(" completed successfully.

Changelog:
"); + QString changelog = readFile("/external_root/opt/isa/changelog"); + updatemsg = updatemsg.append(changelog); + updatemsg = updatemsg.append("
"); + log("Showing update changelog", className); + QMessageBox::information(this, tr("Information"), updatemsg); + writeFile("/external_root/opt/update/inkbox_updated", "false"); + + // Trigger Gutenberg re-sync, because we deleted the .inkbox folder ;) + if (QFile::exists("/external_root/opt/storage/gutenberg/last_sync")) { + QFile::remove("/external_root/opt/storage/gutenberg/last_sync"); + } + } + } + + // OTA update + if (!QFile(updatesCheckConfigPath).exists()) { + writeFile(updatesCheckConfigPath, "true"); + } + + if (checkconfig(updatesCheckConfigPath) == true) { + // Check for an update and ask if the user wants to install it + checkForUpdate(); + // Check for an OTA update + QTimer::singleShot(1000, this, SLOT(checkForOtaUpdate())); + } + + // USB mass storage prompt + if (!QFile(usbConfigPath).exists()) { + writeFile(usbConfigPath, "true"); + } + + if (checkconfig(usbConfigPath) == true) { + QTimer *usbmsPrompt = new QTimer(this); + usbmsPrompt->setInterval(500); + connect(usbmsPrompt, &QTimer::timeout, [&]() { + if (checkconfig("/opt/inkbox_genuine") == true) { + if (global::usbms::showUsbmsDialog != true) { + if (device->isUSBPluggedIn() != usbmsStatus) { + global::usbms::showUsbmsDialog = true; + } + } else { + usbmsStatus = device->isUSBPluggedIn(); + if (usbmsStatus == false) { + // Loop again... + ; + } else { + // An USB cable is connected! + setBatteryIcon(); + openUsbmsDialog(); + } + } + } else { + // Do nothing, we're running along with Nickel & friends... + ; + } + }); + usbmsPrompt->start(); + } + + // If the DEVKEY file is present, install a developer key + if (QFile::exists("/mnt/onboard/onboard/.inkbox/DEVKEY") == true && QFile::exists("/mnt/onboard/onboard/.inkbox/DEVKEY.dgst") == true) { + QString developerKey = readFile("/mnt/onboard/onboard/.inkbox/DEVKEY").left(256); + + setDefaultWorkDir(); + QString prog("sh"); + QStringList args; + args << "install_developer-key.sh" << developerKey << "/mnt/onboard/onboard/.inkbox/DEVKEY.dgst"; + QProcess *proc = new QProcess(); + proc->start(prog, args); + proc->waitForFinished(); + proc->deleteLater(); + + QFile::remove("/mnt/onboard/onboard/.inkbox/DEVKEY"); + QFile::remove("/mnt/onboard/onboard/.inkbox/DEVKEY.dgst"); + + reboot(true); + qApp->quit(); + } + + // Write version control info to file in tmpfs + if (checkconfig("/opt/inkbox_genuine") == true) { + writeFile("/external_root/run/inkbox_gui_git_commit", GIT_COMMIT); + } + + // Telemetry + if (checkconfig(".config/24-telemetry/enabled") == false && checkconfig(".config/24-telemetry/asked") == false) { + if (testPing("23.163.0.39") == 0) { + QTimer::singleShot(1000, this, SLOT(openTelemetryDialog())); + } + } +} + +MainWindow::~MainWindow() { + delete ui; +} + +void MainWindow::openUpdateDialog() { + log("Showing Update dialog", className); + global::mainwindow::updateDialog = true; + // Write to a temporary file to show an "Update" prompt + writeFile("/inkbox/updateDialog", "true"); + + // Setup the dialog + generalDialogWindow = new GeneralDialog(this); + connect(generalDialogWindow, SIGNAL(showToast(QString)), SLOT(showToast(QString))); + connect(generalDialogWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToast())); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + QApplication::processEvents(); +} + +void MainWindow::openLowBatteryDialog() { + log("Showing Low Battery Dialog", className); + global::mainwindow::lowBatteryDialog = true; + global::battery::batteryAlertLock = true; + + generalDialogWindow = new GeneralDialog(this); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + QApplication::processEvents(); +} + +void MainWindow::openUsbmsDialog() { + log("Showing USB Mass Storage dialog", className); + global::usbms::showUsbmsDialog = false; + global::usbms::usbmsDialog = true; + + generalDialogWindow = new GeneralDialog(this); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + QApplication::processEvents(); +} + +void MainWindow::openCriticalBatteryAlertWindow() { + global::battery::showCriticalBatteryAlert = true; + global::battery::showLowBatteryDialog = false; + + alertWindow = new SplashAlertWidget(); + alertWindow->setAttribute(Qt::WA_DeleteOnClose); + alertWindow->setGeometry(QRect(QPoint(0, 0), screen()->geometry().size())); + alertWindow->show(); +} + +void MainWindow::on_settingsBtn_clicked() { + log("Opening Settings Chooser widget", className); + resetFullWindowException = true; + resetWindow(false); + if (global::mainwindow::tabSwitcher::settingsChooserWidgetSelected != true) { + ui->settingsBtn->setStyleSheet("background: black"); + ui->settingsBtn->setIcon(QIcon(":/resources/settings-inverted.png")); + + // Create widget and make necessary connections + settingsChooserWindow = new SettingsChooserWidget(); + connect(settingsChooserWindow, SIGNAL(showToast(QString)), SLOT(showToast(QString))); + connect(settingsChooserWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToast())); + ui->stackedWidget->insertWidget(2, settingsChooserWindow); + global::mainwindow::tabSwitcher::settingsChooserWidgetCreated = true; + + // Switch tab + ui->stackedWidget->setCurrentIndex(2); + global::mainwindow::tabSwitcher::settingsChooserWidgetSelected = true; + + // Repaint + this->repaint(); + } else { + ; + } +} + +void MainWindow::on_appsBtn_clicked() { + log("Opening Apps widget", className); + resetFullWindowException = true; + resetWindow(false); + if (global::mainwindow::tabSwitcher::appsWidgetSelected != true) { + ui->appsBtn->setStyleSheet("background: black"); + ui->appsBtn->setIcon(QIcon(":/resources/apps-inverted.png")); + + // Create widget + appsWindow = new AppsWidget(); + connect(appsWindow, SIGNAL(refreshScreen()), SLOT(refreshScreen())); + connect(appsWindow, SIGNAL(showToast(QString)), SLOT(showToast(QString))); + ui->stackedWidget->insertWidget(1, appsWindow); + global::mainwindow::tabSwitcher::appsWidgetCreated = true; + + // Switch tab + ui->stackedWidget->setCurrentIndex(1); + global::mainwindow::tabSwitcher::appsWidgetSelected = true; + + // Repaint + this->repaint(); + } else { + ; + } +} + +void MainWindow::on_pushButton_clicked() { + resetFullWindowException = true; + resetWindow(false); + if (global::mainwindow::tabSwitcher::localLibraryWidgetSelected != true) { + ui->pushButton->setStyleSheet("background: black; color: white"); + ui->pushButton->setIcon(QIcon(":/resources/book_inverted.png")); + + // Create widget + setupLocalLibraryWidget(); + global::mainwindow::tabSwitcher::localLibraryWidgetCreated = true; + + // Switch tab + ui->stackedWidget->setCurrentIndex(0); + global::mainwindow::tabSwitcher::localLibraryWidgetSelected = true; + + // Repaint + this->repaint(); + } +} + +void MainWindow::on_searchBtn_clicked() { + global::forbidOpenSearchDialog = false; + setupSearchDialog(); +} + +void MainWindow::on_quitBtn_clicked() { + log("Opening Quit widget", className); + quitWindow = new QuitWidget(); + quitWindow->setAttribute(Qt::WA_DeleteOnClose); + quitWindow->showFullScreen(); +} + +void MainWindow::on_brightnessBtn_clicked() { + log("Showing Brightness Dialog", className); + brightnessDialogWindow = new BrightnessDialog(); + brightnessDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + brightnessDialogWindow->show(); +} + +void MainWindow::on_homeBtn_clicked() { + log("Showing home screen", className); + if (global::localLibrary::bookOptionsDialog::bookPinAction == true) { + global::localLibrary::bookOptionsDialog::bookPinAction = false; + global::mainwindow::tabSwitcher::repaint = false; + } else { + global::mainwindow::tabSwitcher::repaint = true; + } + resetFullWindowException = true; + resetWindow(true); +} + +void MainWindow::resetWindow(bool resetStackedWidget) { + // Reset layout + bool authorQuote = false; + if (resetStackedWidget == true) { + if (checkconfig(".config/05-quote/config") == false) { + authorQuote = true; + ui->homeStackedWidget->setCurrentIndex(0); + } else { + ui->homeStackedWidget->setCurrentIndex(2); + } + ui->stackedWidget->setCurrentIndex(0); + } + + // Destroy widgets + if (global::mainwindow::tabSwitcher::homePageWidgetCreated == true) { + homePageWidgetWindow->deleteLater(); + } + if (global::mainwindow::tabSwitcher::appsWidgetCreated == true) { + appsWindow->deleteLater(); + } + if (global::mainwindow::tabSwitcher::settingsChooserWidgetCreated == true) { + settingsChooserWindow->deleteLater(); + } + if (global::mainwindow::tabSwitcher::libraryWidgetCreated == true) { + libraryWidgetWindow->deleteLater(); + } + if (global::mainwindow::tabSwitcher::localLibraryWidgetCreated == true) { + localLibraryWidgetWindow->deleteLater(); + } + + global::mainwindow::tabSwitcher::homePageWidgetCreated = false; + global::mainwindow::tabSwitcher::appsWidgetCreated = false; + global::mainwindow::tabSwitcher::settingsChooserWidgetCreated = false; + global::mainwindow::tabSwitcher::appsWidgetSelected = false; + global::mainwindow::tabSwitcher::settingsChooserWidgetSelected = false; + global::mainwindow::tabSwitcher::libraryWidgetCreated = false; + global::mainwindow::tabSwitcher::libraryWidgetSelected = false; + global::mainwindow::tabSwitcher::localLibraryWidgetCreated = false; + global::mainwindow::tabSwitcher::localLibraryWidgetSelected = false; + + resetIcons(); + setBatteryIcon(); + if (global::mainwindow::tabSwitcher::repaint == true) { + this->repaint(); + } + if (resetStackedWidget == true && authorQuote == false) { + setupHomePageWidget(); + } +} + +void MainWindow::resetIcons() { + // Reset icons + ui->appsBtn->setStyleSheet("background: white"); + ui->appsBtn->setIcon(QIcon(":/resources/apps.png")); + ui->settingsBtn->setStyleSheet("background: white"); + ui->settingsBtn->setIcon(QIcon(":/resources/settings.png")); + ui->libraryButton->setStyleSheet("background: white"); + ui->libraryButton->setIcon(QIcon(":/resources/online-library.png")); + ui->pushButton->setStyleSheet("background: white"); + ui->pushButton->setIcon(QIcon(":/resources/book.png")); +} + +void MainWindow::setBatteryIcon() { + // Battery + Device *device = Device::getSingleton(); + int batteryValue = device->getBatteryLevel(); + + int iconWidth = 0; + int iconHeight = 0; + + // Hide brightness controls; they won't be very useful there anyway (for anything but the Glo (HD)/Libra/Aura 2) ... + if (device->getScreenSize() <= Device::ScreenSize::MEDIUM) { + ui->brightnessBtn->hide(); + ui->line_7->hide(); + } + + if (device->getScreenSize() <= Device::ScreenSize::LARGE) { + // Setting icons up + iconWidth = sW / 16; + iconHeight = sH / 16; + } else { + iconWidth = sW / 19; + iconHeight = sH / 19; + } + + QPixmap chargingPixmap(":/resources/battery_charging.png"); + QPixmap scaledChargingPixmap = chargingPixmap.scaled(iconWidth, iconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + QPixmap fullPixmap(":/resources/battery_full.png"); + QPixmap scaledFullPixmap = fullPixmap.scaled(iconWidth, iconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + QPixmap halfPixmap(":/resources/battery_half.png"); + QPixmap scaledHalfPixmap = halfPixmap.scaled(iconWidth, iconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + QPixmap emptyPixmap(":/resources/battery_empty.png"); + QPixmap scaledEmptyPixmap = emptyPixmap.scaled(iconWidth, iconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + + // Checking battery level and status, then displaying the relevant icon on batteryIcon + if (device->isUSBPluggedIn() == true) { + ui->batteryIcon->setPixmap(scaledChargingPixmap); + } else { + if (batteryValue >= 75 && batteryValue <= 100) { + ui->batteryIcon->setPixmap(scaledFullPixmap); + } else if (batteryValue >= 25 && batteryValue <= 74) { + ui->batteryIcon->setPixmap(scaledHalfPixmap); + } else if (batteryValue >= 0 && batteryValue <= 24) { + ui->batteryIcon->setPixmap(scaledEmptyPixmap); + } + } +} + +void MainWindow::setInitialBrightness() { + Device *device = Device::getSingleton(); + + int brightness_value = device->getBrightness(); + if (checkconfig("/tmp/oobe-inkbox_completed") == true) { + // Coming from OOBE setup; not doing that fancy stuff again ;p + QFile::remove("/tmp/oobe-inkbox_completed"); + device->setBrightness(brightness_value); + log("Ignoring cinematic brightness call because it has already been done", className); + } else { + // Fancy brightness fade-in + if (checkconfig("/tmp/inkbox-cinematicBrightness_auto") == true) { + QFile::remove("/tmp/inkbox-cinematicBrightness_auto"); + + //FIXME: I don't see the point of this, it is changing the brightness from the current value to the current value + UI::transitionBrightness(brightness_value); + //cinematicBrightness(brightness_value, 2); + } else { + if (checkconfig("/tmp/inkbox-cinematicBrightness_ran") == false) { + writeFile("/tmp/inkbox-cinematicBrightness_ran", "true"); + device->setBrightness(0); + UI::transitionBrightness(brightness_value); + } else { + log("Ignoring cinematic brightness call because it has already been done", className); + } + } + } +} + +void MainWindow::refreshScreen() { + this->repaint(); +} + +void MainWindow::setupSearchDialog() { + if (global::forbidOpenSearchDialog == false) { + log("Launching Search dialog", className); + global::keyboard::keyboardDialog = true; + global::keyboard::searchDialog = true; + global::keyboard::keyboardText = ""; + generalDialogWindow = new GeneralDialog(); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + connect(generalDialogWindow, SIGNAL(destroyed(QObject *)), SLOT(setupSearchDialog())); + connect(generalDialogWindow, SIGNAL(refreshScreen()), SLOT(refreshScreen())); + connect(generalDialogWindow, SIGNAL(showToast(QString)), SLOT(showToast(QString))); + connect(generalDialogWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToast())); + connect(generalDialogWindow, SIGNAL(openBookFile(QString, bool)), SLOT(openBookFile(QString, bool))); + generalDialogWindow->show(); + } else { + ; + } +} + +void MainWindow::updateWifiIcon() { + /* Usage: + * Mode 0 (looping it) is handled in MainWindow + */ + + global::wifi::wifiState currentWifiState = checkWifiState(); + + // It's executing only in enabled mode, which is a mode between connected and disabled, so don't worry about performance + if (isConnecting == false and isReconnecting == false) { + if (currentWifiState == global::wifi::wifiState::enabled) { + if (checkProcessName("connection_manager.sh") == true) { + isConnecting = true; + } else if (checkProcessName("connect_to_network.sh") == true) { + isConnecting = true; + isReconnecting = true; + } + } + } + + // ms can make a difference, so: + currentWifiState = checkWifiState(); + + if (lastWifiState != currentWifiState) { + if (currentWifiState == global::wifi::wifiState::disabled) { + if (isConnecting == true) { + if (checkconfig("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/stopped") == false) { + if (isReconnecting == true) { + showToast("Reconnection failed"); + isReconnecting = false; + } else { + showToast("Connection failed"); + } + isConnecting = false; + QFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/essid").remove(); + QFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/passphrase").remove(); + } else { + QFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/stopped").remove(); + } + } + lastWifiState = global::wifi::wifiState::disabled; + ui->wifiBtn->setIcon(QIcon(":/resources/wifi-off.png")); + ui->wifiBtn->setIconSize(QSize(wifiIconWidth, wifiIconHeight)); + } + if (currentWifiState == global::wifi::wifiState::enabled) { + lastWifiState = global::wifi::wifiState::enabled; + ui->wifiBtn->setIcon(QIcon(":/resources/wifi-standby.png")); + ui->wifiBtn->setIconSize(QSize(wifiIconWidth, wifiIconHeight)); + } + if (currentWifiState == global::wifi::wifiState::configured) { + if (isConnecting == true) { + setDefaultWorkDir(); + if (isReconnecting == true) { + showToast("Reconnection successful"); + isReconnecting = false; + } else { + showToast("Connection successful"); + } + isConnecting = false; + QFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/stopped").remove(); + } + lastWifiState = global::wifi::wifiState::configured; + ui->wifiBtn->setIcon(QIcon(":/resources/wifi-100.png")); + ui->wifiBtn->setIconSize(QSize(wifiIconWidth, wifiIconHeight)); + } + } +} + +void MainWindow::updateWifiAble() { + if (!Device::getSingleton()->supportsWifi()) { + ui->wifiBtn->hide(); + ui->line_9->hide(); + } +} + +void MainWindow::on_wifiBtn_clicked() { + WifiDialog *newWifiDialog = new WifiDialog(); + QObject::connect(newWifiDialog, &WifiDialog::showToast, this, &MainWindow::showToast); + newWifiDialog->exec(); +} + +void MainWindow::showToast(QString messageToDisplay) { + global::toast::message = messageToDisplay; + toastWindow = new toast(this); + toastWindow->setAttribute(Qt::WA_DeleteOnClose); + connect(toastWindow, SIGNAL(refreshScreen()), SLOT(refreshScreen())); + connect(toastWindow, SIGNAL(showToast(QString)), SLOT(showToast(QString))); + connect(toastWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToast())); + toastWindow->show(); + + // I will soon manage the update thing in a more proper way somewhere else... ~ Szybet + if (messageToDisplay.contains("onnected successfully") == true) { + // Give the toast some time to vanish away, then launch OTA updater + QTimer::singleShot(5000, this, SLOT(launchOtaUpdater())); + } +} + +void MainWindow::hello(int testNumber) { + log("Hello" + QString::number(testNumber), className); +} + +void MainWindow::closeIndefiniteToast() { + // Warning: use with caution + toastWindow->close(); +} + +void MainWindow::openUpdateDialogOTA(bool open) { + if (open == true) { + QString function = __func__; + log(function + ": Showing update dialog (OTA)", className); + global::otaUpdate::isUpdateOta = true; + openUpdateDialog(); + } else { + ; + } +} + +void MainWindow::launchOtaUpdater() { + log("Launching OTA updater", className); + otaManagerWindow = new OTAUpdateManagerWidget(this); + connect(otaManagerWindow, SIGNAL(canOtaUpdate(bool)), SLOT(openUpdateDialogOTA(bool))); + otaManagerWindow->setAttribute(Qt::WA_DeleteOnClose); +} + +void MainWindow::openBookFile(QString book, bool relativePath) { + if (relativePath == true) { + if (checkconfig("/opt/inkbox_genuine") == true) { + book.prepend("/mnt/onboard/onboard/"); + } else { + book.prepend("/mnt/onboard/"); + } + } + + global::reader::skipOpenDialog = true; + global::reader::bookFile = book; + openReaderFramework(); +} + +void MainWindow::openReaderFramework() { + log("Launching Reader Framework", className); + readerWindow = new ReaderWidget(); + readerWindow->setAttribute(Qt::WA_DeleteOnClose); + connect(readerWindow, SIGNAL(openBookFile(QString, bool)), SLOT(openBookFile(QString, bool))); + readerWindow->showFullScreen(); +} + +void MainWindow::checkForUpdate() { + log("Checking for available updates", className); + if (checkconfig("/mnt/onboard/onboard/.inkbox/can_update") == true) { + if (checkconfig("/tmp/cancelUpdateDialog") == false) { + // I'm sorry. + QString function = __func__; + log(function + ": An update is available.", className); + QTimer::singleShot(2000, this, SLOT(openUpdateDialog())); + } else { + QString function = __func__; + log(function + ": Not showing update dialog, user dismissed it", className); + } + } else { + QString function = __func__; + log(function + ": No update available.", className); + } +} + +void MainWindow::openEncfsRepackDialog() { + log("Showing encrypted storage repack dialog", className); + global::encfs::repackDialog = true; + global::usbms::showUsbmsDialog = false; + global::usbms::usbmsDialog = false; + generalDialogWindow = new GeneralDialog(this); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); +} + +void MainWindow::on_libraryButton_clicked() { + log("Launching Online Library", className); + if (testPing() == 0) { + // 'Do you want to sync?' dialog + bool willSync = false; + QString syncEpochQStr = readFile("/external_root/opt/storage/gutenberg/last_sync"); + if (!syncEpochQStr.isEmpty()) { + unsigned long currentEpoch = QDateTime::currentSecsSinceEpoch(); + unsigned long syncEpoch = syncEpochQStr.toULong(); + unsigned long allowSyncEpoch = syncEpoch + 86400; + if (currentEpoch > allowSyncEpoch) { + willSync = true; + } + } else if (syncEpochQStr.isEmpty()) { + willSync = true; + } + + if (willSync == true) { + log("Showing 'Sync required' dialog", className); + global::library::librarySyncDialog = true; + generalDialogWindow = new GeneralDialog(this); + QObject::connect(generalDialogWindow, &GeneralDialog::syncOnlineLibrary, this, &MainWindow::launchOnlineLibrary); + QObject::connect(generalDialogWindow, &GeneralDialog::noSyncOnlineLibrary, this, &MainWindow::on_homeBtn_clicked); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + generalDialogWindow->show(); + } else { + launchOnlineLibrary(); + } + } else { + showToast("Wi-Fi connection error"); + } +} + +void MainWindow::launchOnlineLibrary() { + resetFullWindowException = true; + resetWindow(false); + if (global::mainwindow::tabSwitcher::libraryWidgetSelected != true) { + ui->libraryButton->setStyleSheet("background: black; color: white"); + ui->libraryButton->setIcon(QIcon(":/resources/online-library-inverted.png")); + + // Create widget + libraryWidgetWindow = new LibraryWidget(); + connect(libraryWidgetWindow, SIGNAL(destroyed(QObject *)), SLOT(resetFullWindow())); + libraryWidgetWindow->setAttribute(Qt::WA_DeleteOnClose); + ui->stackedWidget->insertWidget(3, libraryWidgetWindow); + global::mainwindow::tabSwitcher::libraryWidgetCreated = true; + + // Switch tab + ui->stackedWidget->setCurrentIndex(3); + global::mainwindow::tabSwitcher::libraryWidgetSelected = true; + + // Repaint + this->repaint(); + } +} + +void MainWindow::resetFullWindow() { + if (resetFullWindowException == false) { + resetWindow(true); + } else { + resetFullWindowException = false; + } +} + +void MainWindow::checkForOtaUpdate() { + if (global::wifi::isConnected == true) { + QString lastSync = readFile("/external_root/opt/storage/update/last_sync"); + if (!lastSync.isEmpty()) { + unsigned long currentEpoch = QDateTime::currentSecsSinceEpoch(); + unsigned long syncEpoch = lastSync.toULong(); + unsigned long allowSyncEpoch = syncEpoch + 86400; + if (currentEpoch > allowSyncEpoch) { + launchOtaUpdater(); + } + } else { + launchOtaUpdater(); + } + } +} + +void MainWindow::setupLocalLibraryWidget() { + localLibraryWidgetWindow = new LocalLibraryWidget(this); + QObject::connect(localLibraryWidgetWindow, &LocalLibraryWidget::openBookSignal, this, &MainWindow::openBookFile); + QObject::connect(localLibraryWidgetWindow, &LocalLibraryWidget::refreshScreen, this, &MainWindow::refreshScreen); + localLibraryWidgetWindow->setAttribute(Qt::WA_DeleteOnClose); + ui->homeStackedWidget->insertWidget(1, localLibraryWidgetWindow); + ui->homeStackedWidget->setCurrentIndex(1); +} + +void MainWindow::setupHomePageWidget() { + homePageWidgetWindow = new HomePageWidget(this); + QObject::connect(homePageWidgetWindow, &HomePageWidget::openBookSignal, this, &MainWindow::openBookFile); + QObject::connect(homePageWidgetWindow, &HomePageWidget::refreshScreen, this, &MainWindow::refreshScreen); + QObject::connect(homePageWidgetWindow, &HomePageWidget::relaunchHomePageWidget, this, &MainWindow::on_homeBtn_clicked); + homePageWidgetWindow->setAttribute(Qt::WA_DeleteOnClose); + ui->homeStackedWidget->insertWidget(2, homePageWidgetWindow); + ui->homeStackedWidget->setCurrentIndex(2); + global::mainwindow::tabSwitcher::homePageWidgetCreated = true; +} + +void MainWindow::on_audioBtn_clicked() { + QDialog *newAudioDialog = new AudioDialog(this); + newAudioDialog->exec(); +} + +void MainWindow::openTelemetryDialog() { + log("Showing telemetry request dialog", className); + // Preventing a small race condition + global::usbms::usbmsDialog = false; + + global::telemetry::telemetryDialog = true; + + generalDialogWindow = new GeneralDialog(this); + QObject::connect(generalDialogWindow, &GeneralDialog::destroyed, this, &MainWindow::openTelemetryMessageDialog); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + QApplication::processEvents(); +} + +void MainWindow::openTelemetryMessageDialog() { + if (global::keyboard::telemetryMessageDialog == true) { + log("Showing telemetry message dialog", className); + global::keyboard::keyboardDialog = true; + global::keyboard::keyboardText = ""; + generalDialogWindow = new GeneralDialog(this); + QObject::connect(generalDialogWindow, &GeneralDialog::telemetryMessage, this, &MainWindow::sendDeviceInformationSlot); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + QApplication::processEvents(); + } +} + +void MainWindow::sendDeviceInformationSlot(QString message) { + telemetryInstance = new Telemetry(this); + QObject::connect(telemetryInstance, &Telemetry::showToast, this, &MainWindow::showToast); + telemetryInstance->message = message; +} diff --git a/src/homeWidget/mainwindow.h b/src/ui/home/mainwindow.h similarity index 82% rename from src/homeWidget/mainwindow.h rename to src/ui/home/mainwindow.h index 6261fb1..78d69a2 100644 --- a/src/homeWidget/mainwindow.h +++ b/src/ui/home/mainwindow.h @@ -7,7 +7,7 @@ #include "apps.h" #include "reader.h" #include "quit.h" -#include "alert.h" +#include "splashAlert.h" #include "usbmsSplash.h" #include "brightnessdialog.h" #include "generaldialog.h" @@ -110,24 +110,24 @@ private slots: private: Ui::MainWindow * ui; - settingsChooser * settingsChooserWindow; - apps * appsWindow; - reader * readerWindow; - quit * quitWindow; - alert * alertWindow; - usbmsSplash * usbmsWindow; - brightnessDialog * brightnessDialogWindow; - generalDialog * generalDialogWindow; - koboxSettings * koboxSettingsWindow; - koboxAppsDialog * koboxAppsDialogWindow; + SettingsChooserWidget * settingsChooserWindow; + AppsWidget * appsWindow; + ReaderWidget * readerWindow; + QuitWidget * quitWindow; + SplashAlertWidget * alertWindow; + USBMSSplashWidget * usbmsWindow; + BrightnessDialog * brightnessDialogWindow; + GeneralDialog * generalDialogWindow; + KoboxSettingsWidget * koboxSettingsWindow; + KoboxAppsDialog * koboxAppsDialogWindow; textwidget * textwidgetWindow; virtualkeypad * keypadWidget; toast * toastWindow; - otaManager * otaManagerWindow; - libraryWidget * libraryWidgetWindow; - localLibraryWidget * localLibraryWidgetWindow; - homePageWidget * homePageWidgetWindow; - telemetry * telemetryInstance; + OTAUpdateManagerWidget * otaManagerWindow; + LibraryWidget * libraryWidgetWindow; + LocalLibraryWidget * localLibraryWidgetWindow; + HomePageWidget * homePageWidgetWindow; + Telemetry * telemetryInstance; }; #endif // MAINWINDOW_H diff --git a/src/homeWidget/mainwindow.ui b/src/ui/home/mainwindow.ui similarity index 100% rename from src/homeWidget/mainwindow.ui rename to src/ui/home/mainwindow.ui diff --git a/src/localLibrary/locallibrarywidget.cpp b/src/ui/localLibrary/locallibrarywidget.cpp similarity index 89% rename from src/localLibrary/locallibrarywidget.cpp rename to src/ui/localLibrary/locallibrarywidget.cpp index efec498..a58eae6 100644 --- a/src/localLibrary/locallibrarywidget.cpp +++ b/src/ui/localLibrary/locallibrarywidget.cpp @@ -1,17 +1,21 @@ #include "locallibrarywidget.h" #include "ui_locallibrarywidget.h" +#include "device.h" #include #include #include -localLibraryWidget::localLibraryWidget(QWidget *parent) : +LocalLibraryWidget::LocalLibraryWidget(QWidget *parent) : QWidget(parent), - ui(new Ui::localLibraryWidget) + ui(new Ui::LocalLibraryWidget) { + Device *device = Device::getSingleton(); + Device::ScreenSize screenSize = device->getScreenSize(); + ui->setupUi(this); this->setFont(QFont("u001")); - QObject::connect(ui->pageNumberLabel, &QClickableLabel::clicked, this, &localLibraryWidget::openGoToPageDialog); + QObject::connect(ui->pageNumberLabel, &QClickableLabel::clicked, this, &LocalLibraryWidget::openGoToPageDialog); ui->previousPageBtn->setProperty("type", "borderless"); ui->previousPageBtn->setEnabled(false); @@ -25,23 +29,23 @@ localLibraryWidget::localLibraryWidget(QWidget *parent) : ui->goUpBtn->setEnabled(false); - if(global::deviceID == "n705\n") { + if(screenSize == Device::ScreenSize::SMALL) { buttonsNumber = 3; } - else if(global::deviceID == "n873\n") { + else if(screenSize >= Device::ScreenSize::VERY_LARGE) { buttonsNumber = 5; } else { buttonsNumber = 4; } - if(global::deviceID == "n705\n") { + if(screenSize == Device::ScreenSize::SMALL) { bookTitleTruncateThreshold = 27; } - else if(global::deviceID == "n873\n") { + else if(screenSize >= Device::ScreenSize::VERY_LARGE) { bookTitleTruncateThreshold = 45; } - else if(global::deviceID == "n306\n") { + else if(screenSize == Device::ScreenSize::MEDIUM) { bookTitleTruncateThreshold = 32; } else { @@ -57,34 +61,21 @@ localLibraryWidget::localLibraryWidget(QWidget *parent) : sW = QGuiApplication::screens()[0]->size().width(); sH = QGuiApplication::screens()[0]->size().height(); - if(global::deviceID == "n705\n") { + + if(screenSize == Device::ScreenSize::SMALL) { stdIconWidthDivider = 7.2; stdIconHeightDivider = 7.2; - } - else if(global::deviceID == "n905\n" or global::deviceID == "kt\n") { - stdIconWidthDivider = 9.5; - stdIconHeightDivider = 9.5; - } - else if(global::deviceID == "n613\n" or global::deviceID == "emu\n") { - stdIconWidthDivider = 8.7; - stdIconHeightDivider = 8.7; - } - else if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { + } else if(screenSize == Device::ScreenSize::MEDIUM) { stdIconWidthDivider = 8.1; stdIconHeightDivider = 8.1; - } - else if(global::deviceID == "n873\n") { + } else if(screenSize == Device::ScreenSize::LARGE) { + stdIconWidthDivider = 8.5; + stdIconHeightDivider = 8.5; + } else if(screenSize >= Device::ScreenSize::VERY_LARGE) { stdIconWidthDivider = 9.7; stdIconHeightDivider = 9.7; } - else if(global::deviceID == "n236\n" or global::deviceID == "n306\n") { - stdIconWidthDivider = 9.1; - stdIconHeightDivider = 9.1; - } - else { - stdIconWidthDivider = 9.5; - stdIconHeightDivider = 9.5; - } + stdIconWidth = sW / stdIconWidthDivider; stdIconHeight = sH / stdIconHeightDivider; @@ -109,12 +100,12 @@ localLibraryWidget::localLibraryWidget(QWidget *parent) : } } -localLibraryWidget::~localLibraryWidget() +LocalLibraryWidget::~LocalLibraryWidget() { delete ui; } -void localLibraryWidget::setupDatabase() { +void LocalLibraryWidget::setupDatabase() { setDefaultWorkDir(); if(!QFile::exists(global::localLibrary::databasePath)) { log("Generating database", className); @@ -195,11 +186,11 @@ void localLibraryWidget::setupDatabase() { if(global::localLibrary::headless == true) { global::localLibrary::headless = false; - localLibraryWidget::close(); + LocalLibraryWidget::close(); } } -void localLibraryWidget::setupBooksList(int pageNumber) { +void LocalLibraryWidget::setupBooksList(int pageNumber) { idList.clear(); int in = 1; for(int i = (1 * pageNumber * buttonsNumber) - (buttonsNumber - 1); i <= (1 * pageNumber * buttonsNumber); i++) { @@ -279,7 +270,7 @@ void localLibraryWidget::setupBooksList(int pageNumber) { } } -void localLibraryWidget::on_previousPageBtn_clicked() +void LocalLibraryWidget::on_previousPageBtn_clicked() { log("Previous button clicked", className); @@ -303,7 +294,7 @@ void localLibraryWidget::on_previousPageBtn_clicked() } -void localLibraryWidget::on_nextPageBtn_clicked() +void LocalLibraryWidget::on_nextPageBtn_clicked() { currentPageNumber++; setupBooksListToggle(currentPageNumber); @@ -315,14 +306,14 @@ void localLibraryWidget::on_nextPageBtn_clicked() } } -void localLibraryWidget::openBook(int bookID) { +void LocalLibraryWidget::openBook(int bookID) { QJsonObject jsonObject = databaseJsonArrayList.at(bookID - 1).toObject(); QString bookPath = jsonObject["BookPath"].toString(); log("Opening book with ID " + QString::number(bookID) + ", path '" + bookPath + "'", className); emit openBookSignal(bookPath, false); } -void localLibraryWidget::btnOpenBook(int buttonNumber) { +void LocalLibraryWidget::btnOpenBook(int buttonNumber) { log("Book/directory button clicked, buttonNumber is " + QString::number(buttonNumber), className); if(mainPathIsEmpty == true) { return void(); @@ -339,23 +330,23 @@ void localLibraryWidget::btnOpenBook(int buttonNumber) { else { log("A book was selected", className); openBook(id); - localLibraryWidget::close(); + LocalLibraryWidget::close(); } } -void localLibraryWidget::openGoToPageDialog() { +void LocalLibraryWidget::openGoToPageDialog() { if(mainPathIsEmpty == true) { return void(); } log("Showing 'Go to page' dialog", className); global::keyboard::keypadDialog = true; - generalDialogWindow = new generalDialog(); + generalDialogWindow = new GeneralDialog(); generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - QObject::connect(generalDialogWindow, &generalDialog::gotoPageSelected, this, &localLibraryWidget::goToPage); + QObject::connect(generalDialogWindow, &GeneralDialog::gotoPageSelected, this, &LocalLibraryWidget::goToPage); } -void localLibraryWidget::goToPage(int page) { +void LocalLibraryWidget::goToPage(int page) { checkIfMainPathIsEmpty(); if(mainPathIsEmpty == true) { return void(); @@ -375,11 +366,11 @@ void localLibraryWidget::goToPage(int page) { } } -void localLibraryWidget::refreshScreenNative() { +void LocalLibraryWidget::refreshScreenNative() { emit refreshScreen(); } -void localLibraryWidget::setupDisplay() { +void LocalLibraryWidget::setupDisplay() { setupDatabase(); if(noBooksInDatabase == false) { // Prevent segmentation fault if a book was the last of its page @@ -403,14 +394,14 @@ void localLibraryWidget::setupDisplay() { global::localLibrary::bookOptionsDialog::bookDeleted = false; } -void localLibraryWidget::showToast(QString messageToDisplay) { +void LocalLibraryWidget::showToast(QString messageToDisplay) { global::toast::message = messageToDisplay; toastWindow = new toast(this); toastWindow->setAttribute(Qt::WA_DeleteOnClose); toastWindow->show(); } -void localLibraryWidget::openBookOptionsDialog(int pseudoBookID) { +void LocalLibraryWidget::openBookOptionsDialog(int pseudoBookID) { if(mainPathIsEmpty == true) { return void(); } @@ -440,17 +431,17 @@ void localLibraryWidget::openBookOptionsDialog(int pseudoBookID) { log("Opening book options dialog for book with pseudo-ID " + QString::number(pseudoBookID) + ", ID " + QString::number(bookID), className); // Here, ID should go because of idList.at(pseudoBookID - 1); global::localLibrary::bookOptionsDialog::bookID = id; - bookOptionsDialog * bookOptionsDialogWindow = new bookOptionsDialog(this); - QObject::connect(bookOptionsDialogWindow, &bookOptionsDialog::openLocalBookInfoDialog, this, &localLibraryWidget::openLocalBookInfoDialog); - QObject::connect(bookOptionsDialogWindow, &bookOptionsDialog::showToast, this, &localLibraryWidget::showToast); - QObject::connect(bookOptionsDialogWindow, &bookOptionsDialog::destroyed, this, &localLibraryWidget::handlePossibleBookDeletion); - QObject::connect(bookOptionsDialogWindow, &bookOptionsDialog::removedFolder, this, &localLibraryWidget::refreshFolders); + BookOptionsDialog * bookOptionsDialogWindow = new BookOptionsDialog(this); + QObject::connect(bookOptionsDialogWindow, &BookOptionsDialog::openLocalBookInfoDialog, this, &LocalLibraryWidget::openLocalBookInfoDialog); + QObject::connect(bookOptionsDialogWindow, &BookOptionsDialog::showToast, this, &LocalLibraryWidget::showToast); + QObject::connect(bookOptionsDialogWindow, &BookOptionsDialog::destroyed, this, &LocalLibraryWidget::handlePossibleBookDeletion); + QObject::connect(bookOptionsDialogWindow, &BookOptionsDialog::removedFolder, this, &LocalLibraryWidget::refreshFolders); bookOptionsDialogWindow->setAttribute(Qt::WA_DeleteOnClose); bookOptionsDialogWindow->setWindowFlags(Qt::FramelessWindowHint | Qt::Popup); bookOptionsDialogWindow->show(); } -void localLibraryWidget::handlePossibleBookDeletion() { +void LocalLibraryWidget::handlePossibleBookDeletion() { if(global::localLibrary::bookOptionsDialog::bookDeleted == true) { QTimer::singleShot(3100, this, [&]() { global::toast::modalToast = true; @@ -461,14 +452,14 @@ void localLibraryWidget::handlePossibleBookDeletion() { } } -void localLibraryWidget::openLocalBookInfoDialog() { +void LocalLibraryWidget::openLocalBookInfoDialog() { global::bookInfoDialog::localInfoDialog = true; - bookInfoDialog * bookInfoDialogWindow = new bookInfoDialog(this); + BookInfoDialog * bookInfoDialogWindow = new BookInfoDialog(this); bookInfoDialogWindow->setAttribute(Qt::WA_DeleteOnClose); bookInfoDialogWindow->show(); } -void localLibraryWidget::setupBooksListToggle(int pageNumber) { +void LocalLibraryWidget::setupBooksListToggle(int pageNumber) { if(folderFeatureEnabled == true) { setupBooksListFolders(pageNumber); } @@ -477,7 +468,7 @@ void localLibraryWidget::setupBooksListToggle(int pageNumber) { } } -void localLibraryWidget::setupBooksListFolders(int pageNumber) { +void LocalLibraryWidget::setupBooksListFolders(int pageNumber) { log("Showing folders for page: " + QString::number(pageNumber), className); QStringList directoryList = QDir(pathForFolders).entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name); log("Full directory list is '" + directoryList.join(", ") + "'", className); @@ -644,7 +635,7 @@ void localLibraryWidget::setupBooksListFolders(int pageNumber) { } // Sets pagesNumber for folders feature, and everything else -void localLibraryWidget::calculateMaximumPagesNumberForFolders() { +void LocalLibraryWidget::calculateMaximumPagesNumberForFolders() { log("Main path is '" + pathForFolders + "'", className); checkIfMainPathIsEmpty(); @@ -713,7 +704,7 @@ void localLibraryWidget::calculateMaximumPagesNumberForFolders() { // Sorting the vector if needed should be done here } -void localLibraryWidget::calculateIndexForPage(int pageNumber) { +void LocalLibraryWidget::calculateIndexForPage(int pageNumber) { if(pageNumber == firstPageForBooks + 1) { log("Variable firstPageForBooks is 0", className); bookIndexVector = 0; @@ -747,7 +738,7 @@ void localLibraryWidget::calculateIndexForPage(int pageNumber) { } } -void localLibraryWidget::changePathAndRefresh(QString directory) { +void LocalLibraryWidget::changePathAndRefresh(QString directory) { log("Changing path", className); QString temporaryPathForFolders = pathForFolders + directory + "/"; if(QDir(temporaryPathForFolders).isEmpty() == false) { @@ -762,12 +753,12 @@ void localLibraryWidget::changePathAndRefresh(QString directory) { } } -void localLibraryWidget::on_goUpBtn_clicked() +void LocalLibraryWidget::on_goUpBtn_clicked() { goUpFunction(); } -void localLibraryWidget::goUpFunction() { +void LocalLibraryWidget::goUpFunction() { if(pathForFolders != "/mnt/onboard/onboard/") { log("Changing path; going back", className); // This can't be a one-liner @@ -786,7 +777,7 @@ void localLibraryWidget::goUpFunction() { } } -void localLibraryWidget::on_pathBtn_clicked() +void LocalLibraryWidget::on_pathBtn_clicked() { log("Showing path dialog", className); QString pathForFoldersSaved = pathForFolders; @@ -794,14 +785,14 @@ void localLibraryWidget::on_pathBtn_clicked() pathForFolders = pathForFoldersSaved; } -void localLibraryWidget::refreshFolders() { +void LocalLibraryWidget::refreshFolders() { log("Called refresh folders"); calculateMaximumPagesNumberForFolders(); bookIndexVector = 0; goToPage(1); } -void localLibraryWidget::checkIfMainPathIsEmpty() { +void LocalLibraryWidget::checkIfMainPathIsEmpty() { if(folderFeatureEnabled == true) { // If the main path is empty, prevent it from freezing and using the CPU at 100% because of a while loop if(pathForFolders == "/mnt/onboard/onboard/") { @@ -827,8 +818,8 @@ void localLibraryWidget::checkIfMainPathIsEmpty() { } } -void localLibraryWidget::setupButtonsLook() { - for(int i = 1; i <= buttonsNumber; i++) { +void LocalLibraryWidget::setupButtonsLook() { + for(int i = 0; i < buttonsNumber; i++) { // Horizontal layout that will contain the book button and its icon horizontalLayoutArray[i] = new QHBoxLayout(this); @@ -839,8 +830,8 @@ void localLibraryWidget::setupButtonsLook() { // Book button bookBtnArray[i] = new QClickableLabel(this); bookBtnArray[i]->setObjectName(QString::number(i)); - QObject::connect(bookBtnArray[i], &QClickableLabel::bookID, this, &localLibraryWidget::btnOpenBook); - QObject::connect(bookBtnArray[i], &QClickableLabel::longPressInt, this, &localLibraryWidget::openBookOptionsDialog); + QObject::connect(bookBtnArray[i], &QClickableLabel::bookID, this, &LocalLibraryWidget::btnOpenBook); + QObject::connect(bookBtnArray[i], &QClickableLabel::longPressInt, this, &LocalLibraryWidget::openBookOptionsDialog); bookBtnArray[i]->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); bookBtnArray[i]->setStyleSheet("color: black; background-color: white; border-radius: 10px; padding: 10px"); bookBtnArray[i]->setFont(QFont("u001")); @@ -860,7 +851,7 @@ void localLibraryWidget::setupButtonsLook() { } } -void localLibraryWidget::cleanButtons() { +void LocalLibraryWidget::cleanButtons() { log("Hiding items", className); for(int i = 1; i <= buttonsNumber; i++) { if(bookIconArray[i]->isHidden() == false) { diff --git a/src/localLibrary/locallibrarywidget.h b/src/ui/localLibrary/locallibrarywidget.h similarity index 89% rename from src/localLibrary/locallibrarywidget.h rename to src/ui/localLibrary/locallibrarywidget.h index 6c3b12b..c286d20 100644 --- a/src/localLibrary/locallibrarywidget.h +++ b/src/ui/localLibrary/locallibrarywidget.h @@ -13,17 +13,17 @@ #include "bookinfodialog.h" namespace Ui { -class localLibraryWidget; +class LocalLibraryWidget; } -class localLibraryWidget : public QWidget +class LocalLibraryWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit localLibraryWidget(QWidget *parent = nullptr); - ~localLibraryWidget(); + explicit LocalLibraryWidget(QWidget *parent = nullptr); + ~LocalLibraryWidget(); int buttonsNumber; int sW; int sH; @@ -87,11 +87,11 @@ private slots: void on_pathBtn_clicked(); private: - Ui::localLibraryWidget * ui; - generalDialog * generalDialogWindow; - bookOptionsDialog * bookOptionsDialogWindow; + Ui::LocalLibraryWidget * ui; + GeneralDialog * generalDialogWindow; + BookOptionsDialog * bookOptionsDialogWindow; toast * toastWindow; - bookInfoDialog * bookInfoDialogWindow; + BookInfoDialog * bookInfoDialogWindow; QVector horizontalLayoutArray; QVector bookIconArray; QVector bookBtnArray; diff --git a/src/localLibrary/locallibrarywidget.ui b/src/ui/localLibrary/locallibrarywidget.ui similarity index 98% rename from src/localLibrary/locallibrarywidget.ui rename to src/ui/localLibrary/locallibrarywidget.ui index fcad662..8ecdb81 100644 --- a/src/localLibrary/locallibrarywidget.ui +++ b/src/ui/localLibrary/locallibrarywidget.ui @@ -1,7 +1,7 @@ - localLibraryWidget - + LocalLibraryWidget + 0 diff --git a/src/onlineLibrary/librarywidget.cpp b/src/ui/onlineLibrary/librarywidget.cpp similarity index 88% rename from src/onlineLibrary/librarywidget.cpp rename to src/ui/onlineLibrary/librarywidget.cpp index b8fbf93..c619875 100644 --- a/src/onlineLibrary/librarywidget.cpp +++ b/src/ui/onlineLibrary/librarywidget.cpp @@ -1,6 +1,7 @@ #include "librarywidget.h" #include "ui_librarywidget.h" #include "functions.h" +#include "device.h" #include #include @@ -8,10 +9,11 @@ #include #include -libraryWidget::libraryWidget(QWidget *parent) : +LibraryWidget::LibraryWidget(QWidget *parent) : QWidget(parent), - ui(new Ui::libraryWidget) + ui(new Ui::LibraryWidget) { + Device* device = Device::getSingleton(); ui->setupUi(this); ui->booksStackedWidget->hide(); @@ -34,7 +36,9 @@ libraryWidget::libraryWidget(QWidget *parent) : } QFont crimson(family); - if(global::deviceID != "n705\n" and global::deviceID != "n905\n" and global::deviceID != "kt\n") { + + + if(device->getScreenSize() <= Device::ScreenSize::MEDIUM) { ui->previousBtn->setText(""); ui->previousBtn->setProperty("type", "borderless"); ui->nextBtn->setText(""); @@ -70,7 +74,7 @@ libraryWidget::libraryWidget(QWidget *parent) : ui->book6Btn->setProperty("type", "borderless"); ui->book7Btn->setProperty("type", "borderless"); ui->book8Btn->setProperty("type", "borderless"); - if(global::deviceID != "n705\n" and global::deviceID != "n905\n" and global::deviceID != "kt\n") { + if(device->getScreenSize() > Device::ScreenSize::MEDIUM) { ui->book9Btn->setText(""); ui->book10Btn->setText(""); ui->book11Btn->setText(""); @@ -114,7 +118,7 @@ libraryWidget::libraryWidget(QWidget *parent) : ui->book6Label->setStyleSheet("font-size: 8.5pt; font-style: italic"); ui->book7Label->setStyleSheet("font-size: 8.5pt; font-style: italic"); ui->book8Label->setStyleSheet("font-size: 8.5pt; font-style: italic"); - if(global::deviceID != "n705\n" and global::deviceID != "n905\n" and global::deviceID != "kt\n") { + if(device->getScreenSize() > Device::ScreenSize::MEDIUM) { ui->book9Label->setStyleSheet("font-size: 8.5pt; font-style: italic"); ui->book10Label->setStyleSheet("font-size: 8.5pt; font-style: italic"); ui->book11Label->setStyleSheet("font-size: 8.5pt; font-style: italic"); @@ -150,7 +154,7 @@ libraryWidget::libraryWidget(QWidget *parent) : ui->book6Label->setFont(crimson); ui->book7Label->setFont(crimson); ui->book8Label->setFont(crimson); - if(global::deviceID != "n705\n" and global::deviceID != "n905\n" and global::deviceID != "kt\n") { + if(device->getScreenSize() > Device::ScreenSize::MEDIUM) { ui->book9Label->setFont(crimson); ui->book10Label->setFont(crimson); ui->book11Label->setFont(crimson); @@ -183,15 +187,16 @@ libraryWidget::libraryWidget(QWidget *parent) : } } -libraryWidget::~libraryWidget() +LibraryWidget::~LibraryWidget() { delete ui; } -void libraryWidget::setupView() { +void LibraryWidget::setupView() { + Device *device = Device::getSingleton(); ui->booksStackedWidget->show(); - if(global::deviceID == "n705\n") { + if(device->getScreenSize() == Device::ScreenSize::SMALL) { stdIconWidth = sW / 7 ; stdIconHeight = sH / 7; @@ -209,7 +214,7 @@ void libraryWidget::setupView() { ui->book6Label->setText(readFile("/mnt/onboard/onboard/.inkbox/gutenberg-data/latest-books/6/title")); ui->book7Label->setText(readFile("/mnt/onboard/onboard/.inkbox/gutenberg-data/latest-books/7/title")); ui->book8Label->setText(readFile("/mnt/onboard/onboard/.inkbox/gutenberg-data/latest-books/8/title")); - if(global::deviceID != "n705\n" and global::deviceID != "n905\n" and global::deviceID != "kt\n") { + if(device->getScreenSize() > Device::ScreenSize::MEDIUM) { ui->book9Label->setText(readFile("/mnt/onboard/onboard/.inkbox/gutenberg-data/latest-books/9/title")); ui->book10Label->setText(readFile("/mnt/onboard/onboard/.inkbox/gutenberg-data/latest-books/10/title")); ui->book11Label->setText(readFile("/mnt/onboard/onboard/.inkbox/gutenberg-data/latest-books/11/title")); @@ -236,7 +241,7 @@ void libraryWidget::setupView() { ui->book7Btn->setIconSize(QSize(stdIconWidth, stdIconHeight)); ui->book8Btn->setIcon(QIcon("/mnt/onboard/onboard/.inkbox/gutenberg-data/latest-books/8/cover.jpg")); ui->book8Btn->setIconSize(QSize(stdIconWidth, stdIconHeight)); - if(global::deviceID != "n705\n" and global::deviceID != "n905\n" and global::deviceID != "kt\n") { + if(device->getScreenSize() > Device::ScreenSize::MEDIUM) { ui->book9Btn->setIcon(QIcon("/mnt/onboard/onboard/.inkbox/gutenberg-data/latest-books/9/cover.jpg")); ui->book9Btn->setIconSize(QSize(stdIconWidth, stdIconHeight)); ui->book10Btn->setIcon(QIcon("/mnt/onboard/onboard/.inkbox/gutenberg-data/latest-books/10/cover.jpg")); @@ -256,19 +261,19 @@ void libraryWidget::setupView() { } } -void libraryWidget::showToast(QString messageToDisplay) { +void LibraryWidget::showToast(QString messageToDisplay) { global::toast::message = messageToDisplay; toastWindow = new toast(this); toastWindow->setAttribute(Qt::WA_DeleteOnClose); toastWindow->show(); } -void libraryWidget::closeIndefiniteToast() { +void LibraryWidget::closeIndefiniteToast() { // Warning: use with caution toastWindow->close(); } -void libraryWidget::syncCatalog() { +void LibraryWidget::syncCatalog() { global::toast::modalToast = true; global::toast::indefiniteToast = true; log("Gutenberg sync in progress", className); @@ -276,7 +281,7 @@ void libraryWidget::syncCatalog() { QTimer::singleShot(500, this, SLOT(syncCatalogSlot())); } -void libraryWidget::syncCatalogSlot() { +void LibraryWidget::syncCatalogSlot() { bool syncDone = false; writeFile("/opt/ibxd", "gutenberg_sync\n"); while(true) { @@ -301,20 +306,20 @@ void libraryWidget::syncCatalogSlot() { } } -void libraryWidget::on_previousBtn_clicked() +void LibraryWidget::on_previousBtn_clicked() { ui->booksStackedWidget->setCurrentIndex(0); ui->pageLabel->setText("1 of 2"); } -void libraryWidget::on_nextBtn_clicked() +void LibraryWidget::on_nextBtn_clicked() { ui->booksStackedWidget->setCurrentIndex(1); ui->pageLabel->setText("2 of 2"); } -QString libraryWidget::getTitle(int bookNumber) { +QString LibraryWidget::getTitle(int bookNumber) { QString bookNumberQstr = QString::number(bookNumber); QString fullTitlePath = "/mnt/onboard/onboard/.inkbox/gutenberg-data/latest-books/"; fullTitlePath = fullTitlePath.append(bookNumberQstr); @@ -323,7 +328,7 @@ QString libraryWidget::getTitle(int bookNumber) { return readFile(fullTitlePath); } -void libraryWidget::openLatestBookInfoDialog(int bookNumber, QString title) { +void LibraryWidget::openLatestBookInfoDialog(int bookNumber, QString title) { QString idPath = "/mnt/onboard/onboard/.inkbox/gutenberg-data/latest-books/"; idPath = idPath.append(bookNumber); idPath = idPath.append("/id"); @@ -332,7 +337,7 @@ void libraryWidget::openLatestBookInfoDialog(int bookNumber, QString title) { global::library::latestBookNumber = bookNumber; global::library::bookTitle = title; - bookInfoDialogWindow = new bookInfoDialog(this); + bookInfoDialogWindow = new BookInfoDialog(this); connect(bookInfoDialogWindow, SIGNAL(showToast(QString)), SLOT(showToast(QString))); connect(bookInfoDialogWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToast())); bookInfoDialogWindow->setAttribute(Qt::WA_DeleteOnClose); @@ -341,111 +346,111 @@ void libraryWidget::openLatestBookInfoDialog(int bookNumber, QString title) { } -void libraryWidget::on_book1Btn_clicked() +void LibraryWidget::on_book1Btn_clicked() { QString title = getTitle(1); openLatestBookInfoDialog(1, title); } -void libraryWidget::on_book2Btn_clicked() +void LibraryWidget::on_book2Btn_clicked() { QString title = getTitle(2); openLatestBookInfoDialog(2, title); } -void libraryWidget::on_book3Btn_clicked() +void LibraryWidget::on_book3Btn_clicked() { QString title = getTitle(3); openLatestBookInfoDialog(3, title); } -void libraryWidget::on_book4Btn_clicked() +void LibraryWidget::on_book4Btn_clicked() { QString title = getTitle(4); openLatestBookInfoDialog(4, title); } -void libraryWidget::on_book5Btn_clicked() +void LibraryWidget::on_book5Btn_clicked() { QString title = getTitle(5); openLatestBookInfoDialog(5, title); } -void libraryWidget::on_book6Btn_clicked() +void LibraryWidget::on_book6Btn_clicked() { QString title = getTitle(6); openLatestBookInfoDialog(6, title); } -void libraryWidget::on_book7Btn_clicked() +void LibraryWidget::on_book7Btn_clicked() { QString title = getTitle(7); openLatestBookInfoDialog(7, title); } -void libraryWidget::on_book8Btn_clicked() +void LibraryWidget::on_book8Btn_clicked() { QString title = getTitle(8); openLatestBookInfoDialog(8, title); } -void libraryWidget::on_book9Btn_clicked() +void LibraryWidget::on_book9Btn_clicked() { QString title = getTitle(9); openLatestBookInfoDialog(9, title); } -void libraryWidget::on_book10Btn_clicked() +void LibraryWidget::on_book10Btn_clicked() { QString title = getTitle(10); openLatestBookInfoDialog(10, title); } -void libraryWidget::on_book11Btn_clicked() +void LibraryWidget::on_book11Btn_clicked() { QString title = getTitle(11); openLatestBookInfoDialog(11, title); } -void libraryWidget::on_book12Btn_clicked() +void LibraryWidget::on_book12Btn_clicked() { QString title = getTitle(12); openLatestBookInfoDialog(12, title); } -void libraryWidget::on_book13Btn_clicked() +void LibraryWidget::on_book13Btn_clicked() { QString title = getTitle(13); openLatestBookInfoDialog(13, title); } -void libraryWidget::on_book14Btn_clicked() +void LibraryWidget::on_book14Btn_clicked() { QString title = getTitle(14); openLatestBookInfoDialog(14, title); } -void libraryWidget::on_book15Btn_clicked() +void LibraryWidget::on_book15Btn_clicked() { QString title = getTitle(15); openLatestBookInfoDialog(15, title); } -void libraryWidget::on_book16Btn_clicked() +void LibraryWidget::on_book16Btn_clicked() { QString title = getTitle(16); openLatestBookInfoDialog(16, title); diff --git a/src/onlineLibrary/librarywidget.h b/src/ui/onlineLibrary/librarywidget.h similarity index 85% rename from src/onlineLibrary/librarywidget.h rename to src/ui/onlineLibrary/librarywidget.h index 7e565a4..7d3445d 100644 --- a/src/onlineLibrary/librarywidget.h +++ b/src/ui/onlineLibrary/librarywidget.h @@ -6,26 +6,26 @@ #include namespace Ui { -class libraryWidget; +class LibraryWidget; } -class libraryWidget : public QWidget +class LibraryWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit libraryWidget(QWidget *parent = nullptr); - ~libraryWidget(); + explicit LibraryWidget(QWidget *parent = nullptr); + ~LibraryWidget(); float sH; float sW; float stdIconHeight; float stdIconWidth; private: - Ui::libraryWidget * ui; + Ui::LibraryWidget * ui; toast * toastWindow; - bookInfoDialog * bookInfoDialogWindow; + BookInfoDialog * bookInfoDialogWindow; private slots: void syncCatalog(); diff --git a/src/onlineLibrary/librarywidget.ui b/src/ui/onlineLibrary/librarywidget.ui similarity index 99% rename from src/onlineLibrary/librarywidget.ui rename to src/ui/onlineLibrary/librarywidget.ui index dcd863c..a8c3982 100644 --- a/src/onlineLibrary/librarywidget.ui +++ b/src/ui/onlineLibrary/librarywidget.ui @@ -1,7 +1,7 @@ - libraryWidget - + LibraryWidget + 0 diff --git a/src/otaUpdate/otamanager.cpp b/src/ui/otaUpdate/otamanager.cpp similarity index 89% rename from src/otaUpdate/otamanager.cpp rename to src/ui/otaUpdate/otamanager.cpp index 80a47a6..d77505e 100644 --- a/src/otaUpdate/otamanager.cpp +++ b/src/ui/otaUpdate/otamanager.cpp @@ -6,9 +6,9 @@ #include #include -otaManager::otaManager(QWidget *parent) : +OTAUpdateManagerWidget::OTAUpdateManagerWidget(QWidget *parent) : QWidget(parent), - ui(new Ui::otaManager) + ui(new Ui::OTAUpdateManagerWidget) { ui->setupUi(this); QThread::msleep(500); @@ -30,7 +30,7 @@ otaManager::otaManager(QWidget *parent) : unsigned long currentEpoch = QDateTime::currentSecsSinceEpoch(); writeFile("/external_root/opt/storage/update/last_sync", QString::number(currentEpoch)); QFile::remove("/run/can_ota_update"); - otaManager::close(); + OTAUpdateManagerWidget::close(); } } ); otaCheckTimer->start(); @@ -54,14 +54,14 @@ otaManager::otaManager(QWidget *parent) : global::otaUpdate::downloadOta = false; } QFile::remove("/external_root/opt/storage/update/last_sync"); - otaManager::close(); + OTAUpdateManagerWidget::close(); } } ); otaDownloadTimer->start(); } } -otaManager::~otaManager() +OTAUpdateManagerWidget::~OTAUpdateManagerWidget() { delete ui; } diff --git a/src/otaUpdate/otamanager.h b/src/ui/otaUpdate/otamanager.h similarity index 59% rename from src/otaUpdate/otamanager.h rename to src/ui/otaUpdate/otamanager.h index 115dcdb..4806731 100644 --- a/src/otaUpdate/otamanager.h +++ b/src/ui/otaUpdate/otamanager.h @@ -4,20 +4,20 @@ #include namespace Ui { -class otaManager; +class OTAUpdateManagerWidget; } -class otaManager : public QWidget +class OTAUpdateManagerWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit otaManager(QWidget *parent = nullptr); - ~otaManager(); + explicit OTAUpdateManagerWidget(QWidget *parent = nullptr); + ~OTAUpdateManagerWidget(); private: - Ui::otaManager *ui; + Ui::OTAUpdateManagerWidget *ui; signals: void canOtaUpdate(bool yesno); diff --git a/src/otaUpdate/otamanager.ui b/src/ui/otaUpdate/otamanager.ui similarity index 88% rename from src/otaUpdate/otamanager.ui rename to src/ui/otaUpdate/otamanager.ui index 7de5c28..b710cb6 100644 --- a/src/otaUpdate/otamanager.ui +++ b/src/ui/otaUpdate/otamanager.ui @@ -1,7 +1,7 @@ - otaManager - + OTAUpdateManagerWidget + 0 diff --git a/src/ui/quit/quit.cpp b/src/ui/quit/quit.cpp new file mode 100644 index 0000000..eaae3ca --- /dev/null +++ b/src/ui/quit/quit.cpp @@ -0,0 +1,89 @@ +#include "quit.h" +#include "functions.h" +#include "ui.h" +#include "ui_quit.h" +#include +#include +#include +#include +#include +#include +#include + +QuitWidget::QuitWidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::QuitWidget) { + ui->setupUi(this); + ui->backBtn->setFont(QFont("u001")); + + ui->pushButton->setProperty("type", "borderless"); + ui->pushButton_2->setProperty("type", "borderless"); + ui->pushButton_3->setProperty("type", "borderless"); + ui->pushButton_4->setProperty("type", "borderless"); + ui->backBtn->setProperty("type", "borderless"); + + // Stylesheet + UI::applyStyle(*this, "eink"); + + // Getting the screen's size + float sW = QGuiApplication::screens()[0]->size().width(); + float sH = QGuiApplication::screens()[0]->size().height(); + // Defining what the "Quit" icon size will be + float stdIconWidth = sW / 1.25; + float stdIconHeight = sH / 1.25; + + QPixmap pixmap(":/resources/exit.png"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->label->setPixmap(scaledPixmap); + + if (checkconfig("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/9-deepSleep") == true) { + ui->pushButton_3->setText("Deep suspend"); + } +} + +QuitWidget::~QuitWidget() { + delete ui; +} + +void QuitWidget::on_pushButton_clicked() { + // Prevent strange "appearing from nowhere" low battery or critical battery alerts due to sysfs unmount + global::battery::showCriticalBatteryAlert = false; + global::battery::showLowBatteryDialog = false; + + // GUI apps + updateUserAppsMainJsonFile(); + + poweroff(true); + qApp->quit(); +} + +void QuitWidget::on_pushButton_2_clicked() { + global::battery::showCriticalBatteryAlert = false; + global::battery::showLowBatteryDialog = false; + + // GUI apps + updateUserAppsMainJsonFile(); + + reboot(true); + qApp->quit(); +} + +void QuitWidget::on_pushButton_4_clicked() { + log("Restarting InkBox", className); + QProcess process; + process.startDetached("inkbox", QStringList()); + qApp->quit(); +} + +void QuitWidget::on_backBtn_clicked() { + QuitWidget::close(); +} + +void QuitWidget::on_pushButton_3_clicked() { + log("Suspending", className); + if (checkconfig("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/9-deepSleep") == true) { + writeFile("/dev/ipd/sleepCall", "deepSleep"); + } else { + writeFile("/dev/ipd/sleepCall", "sleep"); + } +} diff --git a/src/quit/quit.h b/src/ui/quit/quit.h similarity index 72% rename from src/quit/quit.h rename to src/ui/quit/quit.h index 1e73f6e..21bdda9 100644 --- a/src/quit/quit.h +++ b/src/ui/quit/quit.h @@ -6,17 +6,17 @@ using namespace std; namespace Ui { -class quit; +class QuitWidget; } -class quit : public QWidget +class QuitWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit quit(QWidget *parent = nullptr); - ~quit(); + explicit QuitWidget(QWidget *parent = nullptr); + ~QuitWidget(); private slots: void on_pushButton_clicked(); @@ -26,7 +26,7 @@ private slots: void on_pushButton_3_clicked(); private: - Ui::quit *ui; + Ui::QuitWidget *ui; }; #endif // QUIT_H diff --git a/src/quit/quit.ui b/src/ui/quit/quit.ui similarity index 98% rename from src/quit/quit.ui rename to src/ui/quit/quit.ui index a1ce365..5777cb8 100644 --- a/src/quit/quit.ui +++ b/src/ui/quit/quit.ui @@ -1,7 +1,7 @@ - quit - + QuitWidget + 0 diff --git a/src/ui/reader/reader.cpp b/src/ui/reader/reader.cpp new file mode 100644 index 0000000..f6f7ad9 --- /dev/null +++ b/src/ui/reader/reader.cpp @@ -0,0 +1,2115 @@ +#include "reader.h" +#include "device.h" +#include "functions.h" +#include "ui.h" +#include "ui_reader.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +ReaderWidget::ReaderWidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::ReaderWidget) { + Device *device = Device::getSingleton(); + + // Elements + graphicsScene = new QGraphicsScene(this); + + // Variables + global::battery::showLowBatteryDialog = true; + global::battery::showCriticalBatteryAlert = true; + global::reader::highlightAlreadyDone = false; + if (global::reader::bookIsEpub == true) { + is_epub = true; + } + mupdf::convertRelativeValues = false; + wordwidgetLock = false; + textDialogLock = false; + goToSavedPageDone = false; + initialPdfRotationDone = false; + global::reader::textAlignment = 0; + global::reader::lineSpacing = 0; + global::reader::font = "Source Serif Pro"; + global::reader::fontSize = 10; + global::reader::margins = 1; + global::reader::currentViewportText = ""; + + ui->setupUi(this); + ui->fontLabel->setFont(QFont("u001")); + ui->sizeLabel->setFont(QFont("u001")); + ui->sizeValueLabel->setFont(QFont("Inter")); + ui->lineSpacingLabel->setFont(QFont("u001")); + ui->lineSpacingValueLabel->setFont(QFont("Inter")); + ui->marginsLabel->setFont(QFont("u001")); + ui->marginsValueLabel->setFont(QFont("Inter")); + ui->alignmentLabel->setFont(QFont("u001")); + ui->fontChooser->setFont(QFont("u001")); + ui->definitionStatusLabel->setFont(QFont("u001")); + ui->pageProgressBar->setFont(QFont("u001")); + + ui->previousBtn->setProperty("type", "borderless"); + ui->nextBtn->setProperty("type", "borderless"); + ui->optionsBtn->setProperty("type", "borderless"); + ui->homeBtn->setProperty("type", "borderless"); + ui->brightnessBtn->setProperty("type", "borderless"); + ui->alignLeftBtn->setProperty("type", "borderless"); + ui->alignRightBtn->setProperty("type", "borderless"); + ui->alignCenterBtn->setProperty("type", "borderless"); + ui->alignLeftBtn->setProperty("type", "borderless"); + ui->alignJustifyBtn->setProperty("type", "borderless"); + ui->infoCloseBtn->setProperty("type", "borderless"); + ui->saveWordBtn->setProperty("type", "borderless"); + ui->previousDefinitionBtn->setProperty("type", "borderless"); + ui->nextDefinitionBtn->setProperty("type", "borderless"); + ui->nightModeBtn->setProperty("type", "borderless"); + ui->searchBtn->setProperty("type", "borderless"); + ui->gotoBtn->setProperty("type", "borderless"); + ui->increaseScaleBtn->setProperty("type", "borderless"); + ui->decreaseScaleBtn->setProperty("type", "borderless"); + ui->quitBtn->setProperty("type", "borderless"); + ui->viewHighlightsBtn->setProperty("type", "borderless"); + + // Icons + ui->alignLeftBtn->setText(""); + ui->alignLeftBtn->setIcon(QIcon(":/resources/align-left.png")); + ui->alignRightBtn->setText(""); + ui->alignRightBtn->setIcon(QIcon(":/resources/align-right.png")); + ui->alignCenterBtn->setText(""); + ui->alignCenterBtn->setIcon(QIcon(":/resources/align-center.png")); + ui->alignJustifyBtn->setText(""); + ui->alignJustifyBtn->setIcon(QIcon(":/resources/align-justify.png")); + ui->infoCloseBtn->setText(""); + ui->infoCloseBtn->setIcon(QIcon(":/resources/close.png")); + ui->saveWordBtn->setText(""); + ui->saveWordBtn->setIcon(QIcon(":/resources/star.png")); + ui->previousDefinitionBtn->setText(""); + ui->previousDefinitionBtn->setIcon(QIcon(":/resources/chevron-left.png")); + ui->nextDefinitionBtn->setText(""); + ui->nextDefinitionBtn->setIcon(QIcon(":/resources/chevron-right.png")); + ui->homeBtn->setText(""); + ui->homeBtn->setIcon(QIcon(":/resources/home.png")); + ui->brightnessBtn->setText(""); + ui->brightnessBtn->setIcon(QIcon(":/resources/frontlight.png")); + ui->searchBtn->setText(""); + ui->searchBtn->setIcon(QIcon(":/resources/search.png")); + ui->increaseScaleBtn->setText(""); + ui->increaseScaleBtn->setIcon(QIcon(":/resources/zoom-in.png")); + ui->decreaseScaleBtn->setText(""); + ui->decreaseScaleBtn->setIcon(QIcon(":/resources/zoom-out.png")); + ui->quitBtn->setText(""); + ui->quitBtn->setIcon(QIcon(":/resources/power.png")); + ui->previousBtn->setText(""); + ui->previousBtn->setIcon(QIcon(":/resources/arrow-left.png")); + ui->optionsBtn->setText(""); + ui->optionsBtn->setIcon(QIcon(":/resources/settings.png")); + ui->nextBtn->setText(""); + ui->nextBtn->setIcon(QIcon(":/resources/arrow-right.png")); + ui->viewHighlightsBtn->setText(""); + ui->viewHighlightsBtn->setIcon(QIcon(":/resources/view-highlights.png")); + + // Style misc. + ui->bookInfoLabel->setStyleSheet("font-style: italic"); + + // Making text selectable + ui->text->setTextInteractionFlags(Qt::TextSelectableByMouse); + + // Font misc. + int id = QFontDatabase::addApplicationFont(":/resources/fonts/CrimsonPro-Italic.ttf"); + QString family = QFontDatabase::applicationFontFamilies(id).at(0); + QFont crimson(family); + + // Stylesheet + misc. + UI::applyStyle(*this, "eink"); + + // We have to get the file's path + if (global::reader::skipOpenDialog == true) { + if (checkconfig("/tmp/suspendBook") == true) { + wakeFromSleep = true; + // Prevent from opening the Reader framework next time unless the condition is reset + writeFile("/tmp/suspendBook", "false"); + book_file = "/inkbox/book/book.txt"; + } else if (global::reader::bookFile.isEmpty() == false) { + book_file = global::reader::bookFile; + global::reader::bookFile = ""; + } + } else { + if (checkconfig("/opt/inkbox_genuine") == true) { + if (checkconfig("/external_root/run/encfs_mounted") == true) { + QDir::setCurrent("/mnt/onboard/onboard/encfs-decrypted"); + } else { + QDir::setCurrent("/mnt/onboard/onboard"); + } + QFileDialog *dialog = new QFileDialog(this); + // https://forum.qt.io/topic/29471/solve-how-to-show-qfiledialog-at-center-position-screen/4 + QDesktopWidget desk; + QRect screenres = desk.screenGeometry(0); + dialog->setGeometry(QRect(screenres.width() / 4, screenres.height() / 4, screenres.width() / 2, screenres.height() / 2)); + + UI::applyStyle(*dialog, "eink"); + + book_file = dialog->getOpenFileName(dialog, tr("Open File"), QDir::currentPath()); + + if (!book_file.isEmpty()) { + setDefaultWorkDir(); + } else { + // User clicked "Cancel" button + // Restarting InkBox + setDefaultWorkDir(); + QProcess process; + process.startDetached("inkbox", QStringList()); + qApp->quit(); + } + } else { + if (checkconfig("/external_root/run/encfs_mounted") == true) { + QDir::setCurrent("/mnt/onboard/onboard/encfs-decrypted"); + } else { + QDir::setCurrent("/mnt/onboard/onboard"); + } + QDir::setCurrent("/mnt/onboard"); + QFileDialog *dialog = new QFileDialog(this); + // https://forum.qt.io/topic/29471/solve-how-to-show-qfiledialog-at-center-position-screen/4 + QDesktopWidget desk; + QRect screenres = desk.screenGeometry(0); + dialog->setGeometry(QRect(screenres.width() / 4, screenres.height() / 4, screenres.width() / 2, screenres.height() / 2)); + + UI::applyStyle(*dialog, "eink"); + + book_file = dialog->getOpenFileName(dialog, tr("Open File"), QDir::currentPath()); + + if (!book_file.isEmpty()) { + setDefaultWorkDir(); + } else { + // User clicked "Cancel" button + // Restarting InkBox + setDefaultWorkDir(); + QProcess process; + process.startDetached("inkbox", QStringList()); + qApp->quit(); + } + } + } + log("Opening file '" + book_file + "'", className); + + // Writing book path to file + writeFile("/tmp/inkboxBookPath", book_file); + + // Calling InkBox daemon (ibxd) via FIFO interface to run bookconfig_mount + if (!book_file.isEmpty()) { + if (checkconfig(".config/16-global_reading_settings/config") == false) { + global::reader::globalReadingSettings = false; + writeFile("/opt/ibxd", "bookconfig_mount\n"); + // Callback handler to wait until bookconfig_mount has finished execution + while (true) { + if (QFile::exists("/inkbox/bookConfigSetUp")) { + QFile::remove("/inkbox/bookConfigSetUp"); + setupLocalSettingsEnvironment(); + break; + } + } + } else { + global::reader::globalReadingSettings = true; + } + } + + // Custom settings + // Brightness + QTimer::singleShot(0, this, SLOT(setCinematicBrightnessWarmthSlot())); + // Font + global::reader::font = readFile(".config/04-book/font"); + if (global::reader::font == "u001") { + ui->fontChooser->setCurrentText("Univers (u001)"); + } else { + ui->fontChooser->setCurrentText(global::reader::font); + } + // Night mode + if (device->supportsNightmode()) { + if (checkconfig(".config/10-dark_mode/config") == true) { + log("Setting night mode to ON", className); + writeFile("/tmp/invertScreen", "y"); + ui->nightModeBtn->setText(""); + ui->nightModeBtn->setIcon(QIcon(":/resources/nightmode-full.png")); + isNightModeActive = true; + } else { + log("Setting night mode to OFF", className); + writeFile("/tmp/invertScreen", "n"); + ui->nightModeBtn->setText(""); + ui->nightModeBtn->setIcon(QIcon(":/resources/nightmode-empty.png")); + isNightModeActive = false; + } + } else { + log("Night mode disabled by software", className); + ui->line_7->hide(); + ui->line_7->deleteLater(); + ui->nightModeBtn->hide(); + ui->nightModeBtn->deleteLater(); + } + + Device::ScreenSize screenSize = device->getScreenSize(); + if (screenSize == Device::ScreenSize::VERY_LARGE) { + ui->nextBtn->setStyleSheet("padding: 13.5px"); + ui->previousBtn->setStyleSheet("padding: 13.5px"); + ui->optionsBtn->setStyleSheet("padding: 13.5px"); + } else if (screenSize == Device::ScreenSize::LARGE) { + ui->nextBtn->setStyleSheet("padding: 12.5px"); + ui->previousBtn->setStyleSheet("padding: 12.5px"); + ui->optionsBtn->setStyleSheet("padding: 12.5px"); + } else { + ui->nextBtn->setStyleSheet("padding: 10px"); + ui->previousBtn->setStyleSheet("padding: 10px"); + ui->optionsBtn->setStyleSheet("padding: 10px"); + } + ui->sizeValueLabel->setStyleSheet("font-size: 9pt; font-weight: bold"); + ui->lineSpacingValueLabel->setStyleSheet("font-size: 9pt; font-weight: bold"); + ui->marginsValueLabel->setStyleSheet("font-size: 9pt; font-weight: bold"); + ui->homeBtn->setStyleSheet("font-size: 9pt; padding: 5px"); + ui->brightnessBtn->setStyleSheet("font-size: 9pt; padding: 5px"); + ui->fontChooser->setStyleSheet("font-size: 9pt"); + ui->gotoBtn->setStyleSheet("font-size: 9pt; padding: 9px; font-weight: bold; background: lightGrey"); + ui->pageNumberLabel->setFont(QFont("Source Serif Pro")); + ui->viewHighlightsBtn->setStyleSheet("padding: 9px"); + + // Hiding the menubar + definition widget + brightness button + buttons bar widget + ui->menuWidget->setVisible(false); + if (device->supportsBrightness()) { + ui->brightnessBtn->setVisible(true); + ui->line_15->setVisible(true); + } else { + ui->brightnessBtn->setVisible(false); + ui->brightnessBtn->deleteLater(); + ui->line_15->setVisible(false); + ui->line_15->deleteLater(); + } + ui->menuBarWidget->setVisible(false); + ui->buttonsBarWidget->setVisible(false); + ui->pdfScaleWidget->setVisible(false); + ui->wordWidget->setVisible(false); + if (checkconfig(".config/11-menubar/sticky") == true) { + ui->menuWidget->setVisible(true); + ui->statusBarWidget->setVisible(true); + } else { + ui->menuWidget->setVisible(false); + ui->statusBarWidget->setVisible(false); + } + ui->pageWidget->hide(); + if (pdf_file_match(book_file) == true) { + ui->line_4->setLineWidth(2); + } + + // Topbar widget / book info + ui->topbarStackedWidget->setVisible(true); + showTopbarWidget = true; + ui->bookInfoLabel->setFont(crimson); + + // Defining pixmaps + // Getting the screen's size + float sW = QGuiApplication::screens()[0]->size().width(); + float sH = QGuiApplication::screens()[0]->size().height(); + // Defining what the icons' size will be + if (checkconfig("/opt/inkbox_genuine") == true) { + float stdIconHeight = sW / 16; + float stdIconWidth = sW / 16; + + if (screenSize == Device::ScreenSize::VERY_LARGE) { + stdIconWidth = sW / 19; + stdIconHeight = sH / 19; + } + QPixmap chargingPixmap(":/resources/battery_charging.png"); + scaledChargingPixmap = chargingPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + QPixmap fullPixmap(":/resources/battery_full.png"); + scaledFullPixmap = fullPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + QPixmap halfPixmap(":/resources/battery_half.png"); + scaledHalfPixmap = halfPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + QPixmap emptyPixmap(":/resources/battery_empty.png"); + scaledEmptyPixmap = emptyPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + } else { + float stdIconWidth = sW / 19; + float stdIconHeight = sH / 19; + QPixmap chargingPixmap(":/resources/battery_charging.png"); + scaledChargingPixmap = chargingPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + QPixmap fullPixmap(":/resources/battery_full.png"); + scaledFullPixmap = fullPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + QPixmap halfPixmap(":/resources/battery_half.png"); + scaledHalfPixmap = halfPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + QPixmap emptyPixmap(":/resources/battery_empty.png"); + scaledEmptyPixmap = emptyPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + } + + // Checking if there is a page refresh setting set + if (readFile(".config/04-book/refresh").isEmpty()) { + // Writing the default, refresh every 3 pages + writeFile(".config/04-book/refresh", "3"); + } + pageRefreshSetting = readFile(".config/04-book/refresh").toInt(); + // Checking if that config option was set to "Never refresh"... + if (pageRefreshSetting == -1) { + log("Setting page refresh to 'disabled'", className); + neverRefresh = true; + } else { + log("Setting page refresh to each " + QString::number(pageRefreshSetting) + " pages", className); + // Safety measure + neverRefresh = false; + } + + // Clock setting to show seconds + battery level + // TODO: we have similar codeblocks throughout the codebase. It would make sense to spin this off into a subfile that can be reused + if (checkconfig(".config/02-clock/config") == true) { + QTimer *t = new QTimer(this); + t->setInterval(500); + connect(t, &QTimer::timeout, [&]() { + QString time = QTime::currentTime().toString("hh:mm:ss"); + ui->batteryLabel->setText(QString(device->getBatteryLevel())); + ui->timeLabel->setText(time); + }); + t->start(); + } else { + QTimer *t = new QTimer(this); + t->setInterval(500); + connect(t, &QTimer::timeout, [&]() { + QString time = QTime::currentTime().toString("hh:mm"); + ui->batteryLabel->setText(QString(device->getBatteryLevel())); + ui->timeLabel->setText(time); + }); + t->start(); + } + + // Checking if we're waking from sleep and have lockscreen enabled; if so, do nothing there because the book should already have been parsed + if (wakeFromSleep != true) { + // Remount tmpfs + writeFile("/inkbox/remount", "true"); + + // Counting number of parsed files + split_total = setup_book(book_file, 0, true); + split_files_number = split_total; + split_total = split_total - 1; + + writeconfig_pagenumber(false); + } else { + // Retrieve split_total from tmpfs + split_total = readFile("/tmp/inkboxPageNumber").toInt(); + setup_book(book_file, 0, true); + } + + // Get text; no need to do it multiple times for ePUB books + if (is_epub == false && is_pdf == false && is_image == false) { + setDefaultWorkDir(); + if (global::reader::globalReadingSettings == false) { + QString splitTotalPageNumber = readFile(".config/A-page_number/config"); + if (!splitTotalPageNumber.isEmpty()) { + split_total = splitTotalPageNumber.toInt(); + } + } + setup_book(book_file, split_total, true); + } + + // Display text + // If needed, show scroll bar when rendering engine isn't doing its job properly + if (checkconfig(".config/14-reader_scrollbar/config") == true) { + ui->text->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + ui->text->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + } else { + ui->text->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + ui->text->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + } + + // Line spacing, margins and text alignment + QString lineSpacingString = readFile(".config/04-book/line_spacing"); + if (!lineSpacingString.isEmpty()) { + global::reader::lineSpacing = lineSpacingString.toInt(); + } + + QString marginsString = readFile(".config/04-book/margins"); + if (!marginsString.isEmpty()) { + global::reader::margins = marginsString.toInt(); + } + + QString alignment = readFile(".config/04-book/alignment"); + if (alignment == "Left") { + global::reader::textAlignment = 0; + } else if (alignment == "Center") { + global::reader::textAlignment = 1; + } else if (alignment == "Right") { + global::reader::textAlignment = 2; + } else if (alignment == "Justify") { + global::reader::textAlignment = 3; + } else { + alignment = "Left"; + global::reader::textAlignment = 0; + } + log("Setting text alignment to '" + alignment + "'", className); + + // Don't ask me why it doesn't work without that QTimer + QTimer::singleShot(0, this, SLOT(setInitialTextProperties())); + + // Wheeee! + if (is_epub == true) { + ui->graphicsView->hide(); + ui->graphicsView->deleteLater(); + ui->text->setText(epubPageContent); + global::reader::currentViewportText = ui->text->toHtml(); + } else if (is_pdf == true) { + ui->text->hide(); + ui->text->deleteLater(); + ui->line_20->hide(); + ui->line_20->deleteLater(); + ui->viewHighlightsBtn->hide(); + ui->viewHighlightsBtn->deleteLater(); + setupPng(); + } else if (is_image == true) { + ui->text->hide(); + ui->text->deleteLater(); + ui->line_20->hide(); + ui->line_20->deleteLater(); + ui->viewHighlightsBtn->hide(); + ui->viewHighlightsBtn->deleteLater(); + setupPng(); + } else { + ui->graphicsView->hide(); + ui->graphicsView->deleteLater(); + global::reader::currentViewportText = ui->text->toHtml(); + ui->text->setText(ittext); + } + + // Topbar info widget + if (is_epub == true) { + QString bookCreator = findEpubMetadata(book_file, "creator"); + QString bookTitle = findEpubMetadata(book_file, "title"); + bookCreator = bookCreator.trimmed(); + bookTitle = bookTitle.trimmed(); + + QString infoLabelContent = bookCreator; + infoLabelContent.append(" ― "); + infoLabelContent.append(bookTitle); + int infoLabelLength = infoLabelContent.length(); + int infoLabelDefinedLength; + if (screenSize == Device::ScreenSize::SMALL) { + infoLabelDefinedLength = 35; + } else { + infoLabelDefinedLength = 50; + } + + if (infoLabelLength <= infoLabelDefinedLength) { + ui->bookInfoLabel->setWordWrap(false); + } else { + ui->bookInfoLabel->setWordWrap(true); + } + ui->bookInfoLabel->setText(infoLabelContent); + } else { + QString bookReadRelativePath; + if (wakeFromSleep == true) { + bookReadRelativePath = readFile("/tmp/inkboxBookPath").split("/").last(); + } else { + bookReadRelativePath = book_file.split("/").last(); + } + + int infoLabelDefinedLength; + if (screenSize == Device::ScreenSize::SMALL) { + infoLabelDefinedLength = 35; + } else { + infoLabelDefinedLength = 50; + } + + if (bookReadRelativePath <= infoLabelDefinedLength) { + ui->bookInfoLabel->setWordWrap(false); + } else { + ui->bookInfoLabel->setWordWrap(true); + } + ui->bookInfoLabel->setText(bookReadRelativePath); + } + + // Clean up + writeFile("/inkbox/remount", "true"); + + // Way to tell shell scripts that we're in the Reader framework + writeFile("/tmp/inkboxReading", "true"); + + // Maintain a 'Recent books' list + QJsonObject recentBooksObject; + if (QFile::exists(global::localLibrary::recentBooksDatabasePath)) { + log("Reading recent books database", className); + QFile recentBooksDatabase(global::localLibrary::recentBooksDatabasePath); + QByteArray recentBooksData; + if (recentBooksDatabase.open(QIODevice::ReadOnly)) { + recentBooksData = recentBooksDatabase.readAll(); + recentBooksDatabase.close(); + } else { + QString function = __func__; + log(function + ": Failed to open recent books database file for reading at '" + recentBooksDatabase.fileName() + "'", className); + } + QJsonObject mainJsonObject = QJsonDocument::fromJson(qUncompress(QByteArray::fromBase64(recentBooksData))).object(); + for (int i = 1; i <= global::homePageWidget::recentBooksNumber; i++) { + QString objectName = "Book" + QString::number(i); + QJsonObject jsonObject = mainJsonObject[objectName].toObject(); + if (i == 1) { + if (jsonObject.value("BookPath").toString() != book_file) { + // Circular buffer + for (int i = global::homePageWidget::recentBooksNumber; i >= 2; i--) { + mainJsonObject["Book" + QString::number(i)] = mainJsonObject["Book" + QString::number(i - 1)]; + } + jsonObject.insert("BookPath", QJsonValue(book_file)); + mainJsonObject[objectName] = jsonObject; + } + } + } + recentBooksObject = mainJsonObject; + } else { + QJsonObject mainJsonObject; + QJsonObject firstJsonObject; + firstJsonObject.insert("BookPath", QJsonValue(book_file)); + mainJsonObject["Book1"] = firstJsonObject; + + for (int i = 2; i <= global::homePageWidget::recentBooksNumber; i++) { + QJsonObject jsonObject; + jsonObject.insert("BookPath", QJsonValue("")); + mainJsonObject["Book" + QString::number(i)] = jsonObject; + } + recentBooksObject = mainJsonObject; + } + QFile::remove(global::localLibrary::recentBooksDatabasePath); + writeFile(global::localLibrary::recentBooksDatabasePath, qCompress(QJsonDocument(recentBooksObject).toJson()).toBase64()); + + // USB mass storage prompt + if (global::reader::startUsbmsPrompt == true) { + QTimer *usbmsPrompt = new QTimer(this); + usbmsPrompt->setInterval(500); + connect(usbmsPrompt, &QTimer::timeout, [&]() { + if (checkconfig("/opt/inkbox_genuine") == true) { + if (global::usbms::showUsbmsDialog != true) { + if (device->isUSBPluggedIn() != usbmsStatus) { + global::usbms::showUsbmsDialog = true; + } + } else { + usbmsStatus = device->isUSBPluggedIn(); + if (usbmsStatus == false) { + // Loop again... + ; + } else { + // An USB cable is connected! + openUsbmsDialog(); + } + } + } else { + // Do nothing, we're running along with Nickel & friends... + ; + } + }); + usbmsPrompt->start(); + } + + // Battery watchdog + if (global::reader::startBatteryWatchdog == true) { + QTimer *t = new QTimer(this); + t->setInterval(2000); + connect(t, &QTimer::timeout, [&]() { + // Checking if battery level is low + if (global::battery::showCriticalBatteryAlert) { + if (device->isBatteryCritical() && !device->isUSBPluggedIn()) { + log("Warning! Battery is at a critical charge level!", className); + openCriticalBatteryAlertWindow(); + } + } + + if (global::battery::showLowBatteryDialog) { + if (device->isBatteryLow() && !device->isUSBPluggedIn()) { + if (global::battery::batteryAlertLock == true) { + ; + } else { + log("Warning! Battery is low!", className); + openLowBatteryDialog(); + } + } + } + }); + if (device->hasBattery()) { + t->start(); + } + } + + // Pages number info label + if (is_pdf == true) { + getTotalPdfPagesNumber(); + } + // The total pages number is already known for ePUBs at this point + setupPageWidget(); + + // Reading settings auto-save timer + if (global::reader::globalReadingSettings == false) { + QTimer *saveSettingsTimer = new QTimer(this); + saveSettingsTimer->setInterval(900000); // 15 minutes + connect(saveSettingsTimer, SIGNAL(timeout()), this, SLOT(saveReadingSettings())); + saveSettingsTimer->start(); + } +} + +ReaderWidget::~ReaderWidget() { + delete ui; +} + +int ReaderWidget::setup_book(QString book, int i, bool run_parser) { + // Parse eBook + if (remount == true) { + QString mount_prog("sh"); + QStringList mount_args; + mount_args << "split.sh"; + QProcess *mount_proc = new QProcess(); + mount_proc->start(mount_prog, mount_args); + mount_proc->waitForFinished(); + mount_proc->deleteLater(); + remount = false; + } else { + writeFile("/inkbox/remount", "false"); + QString mount_prog("sh"); + QStringList mount_args; + mount_args << "split.sh"; + QProcess *mount_proc = new QProcess(); + mount_proc->start(mount_prog, mount_args); + mount_proc->waitForFinished(); + mount_proc->deleteLater(); + } + + if (filematch_ran == false) { + if (epub_file_match(book) == true) { + QFile::remove("/run/book.epub"); + QFile::copy(book, "/run/book.epub"); + + getTotalEpubPagesNumber(); + + filematch_ran = true; + is_epub = true; + } else if (pdf_file_match(book) == true) { + getPdfOrientation(book); + QString pdfProg("/usr/local/bin/mutool"); + QStringList pdfArgs; + convertMuPdfVars(1, true); + pdfArgs << "convert" + << "-F" + << "png" + << "-O" + << "width=" + mupdf::pdf::width_qstr + ",height=" + mupdf::pdf::height_qstr << "-o" + << "/run/page.png" << book_file << mupdf::pdf::pdfPageNumber_qstr; + QProcess *pdfProc = new QProcess(); + pdfProc->start(pdfProg, pdfArgs); + pdfProc->waitForFinished(); + pdfProc->deleteLater(); + + filematch_ran = true; + is_pdf = true; + } else if (image_file_match(book) == true) { + ui->previousBtn->hide(); + ui->nextBtn->hide(); + ui->line->hide(); + ui->line_3->hide(); + ui->previousBtn->deleteLater(); + ui->nextBtn->deleteLater(); + ui->line->deleteLater(); + ui->line_3->deleteLater(); + + writeFile("/tmp/inkboxImagePath", book); + writeFile("/opt/ibxd", "inkbox_convert_image\n"); + + while (true) { + if (QFile::exists("/inkbox/convertImageDone")) { + if (checkconfig("/inkbox/convertImageDone") == true) { + filematch_ran = true; + is_image = true; + break; + } else { + showToast("Failed to display image"); + break; + } + QFile::remove("/inkbox/convertImageDone"); + } + } + + filematch_ran = true; + is_image = true; + } else { + // This is likely not an ePUB, a PDF or a picture. + // Copying book specified in the function call + QFile::copy(book, "/inkbox/book/book.txt"); + + filematch_ran = true; + is_epub = false; + } + } + + // Checking whether or not the user has defined an option for the number of words per page; if not, then setting the default. + // NOTE: This is only for plain text files. + setDefaultWorkDir(); + if (readFile(".config/07-words_number/config").isEmpty()) { + writeFile(".config/07-words_number/config", "100"); + } + QString wordsNumberConfig = readFile(".config/07-words_number/config"); + + // Parsing file + if (is_epub == true) { + if (run_parser == true) { + if (filematch_ran == true) { + QString epubProg("sh"); + QStringList epubArgs; + convertMuPdfVars(0, false); + epubArgs << "/mnt/onboard/.adds/inkbox/epub.sh" + << "0" + << "0" + << "0" << mupdf::epub::epubPageNumber_qstr; + QProcess *epubProc = new QProcess(); + epubProc->start(epubProg, epubArgs); + epubProc->waitForFinished(); + epubProc->deleteLater(); + } + } + } else if (is_pdf == true) { + if (run_parser == true) { + if (filematch_ran == true) { + QString pdfProg("/usr/local/bin/mutool"); + QStringList pdfArgs; + convertMuPdfVars(1, true); + pdfArgs << "convert" + << "-F" + << "png" + << "-O" + << "width=" + mupdf::pdf::width_qstr + ",height=" + mupdf::pdf::height_qstr << "-o" + << "/run/page.png" << book_file << mupdf::pdf::pdfPageNumber_qstr; + QProcess *pdfProc = new QProcess(); + pdfProc->start(pdfProg, pdfArgs); + pdfProc->waitForFinished(); + pdfProc->deleteLater(); + } + } + } else if (is_image == true) { + // Do nothing, since images won't have pages + ; + } else { + QString parse_prog("/mnt/onboard/.adds/inkbox/system/bin/split-txt"); + QStringList parse_args; + parse_args << wordsNumberConfig; + QProcess *parse_proc = new QProcess(); + parse_proc->start(parse_prog, parse_args); + parse_proc->waitForFinished(); + parse_proc->deleteLater(); + } + + // Reading files + if (is_epub == false && is_pdf == false && is_image == false) { + if (run_parser == true) { + QDirIterator it("/inkbox/book/split"); + while (it.hasNext()) { + QFile f(it.next()); + f.open(QIODevice::ReadOnly); + content << f.readAll(); + f.close(); + } + // These characters are replaced for consistency with ePUB text handling, highlighting and text alignment. + content[i].replace("\n", "
"); + content[i].replace("\t", "    "); + ittext = content[i]; + return content.size(); + } else { + content[i].replace("\n", "
"); + content[i].replace("\t", "    "); + ittext = content[i]; + } + } else { + QFile epubPage("/inkbox/book/page"); + epubPage.open(QIODevice::ReadOnly); + QTextStream in(&epubPage); + epubPageContent = in.readAll(); + epubPage.close(); + } + return 0; +} + +void ReaderWidget::checkwords() { + QFile words_list(".config/06-words/config"); + words_list.open(QIODevice::ReadWrite); + QTextStream in(&words_list); + words = in.readAll(); + words_list.close(); +} + +bool ReaderWidget::epub_file_match(QString file) { + QString fileExt = file.right(4); + + if (fileExt == "epub" or fileExt == "EPUB") { + log("Book file format: ePUB", className); + writeFile("/inkbox/bookIsEpub", "true"); + return true; + } else { + writeFile("/inkbox/bookIsEpub", "false"); + return false; + } +} + +void ReaderWidget::dictionary_lookup(string word, QString first_letter, int position) { + log("Dictionary lookup requested for word '" + QString::fromStdString(word) + "', position " + QString::number(position), className); + ofstream fhandler; + fhandler.open("/inkbox/dictionary/word"); + fhandler << word; + fhandler.close(); + + QDir::setCurrent("dictionary"); + QDir::setCurrent(first_letter); + QString lookup_prog("sh"); + QStringList lookup_args; + QString position_str = QString::number(position); + lookup_args << "../scripts/lookup.sh" << position_str; + QProcess *lookup_proc = new QProcess(); + lookup_proc->start(lookup_prog, lookup_args); + lookup_proc->waitForFinished(); + lookup_proc->deleteLater(); + + QFile definition_file("/inkbox/dictionary/definition"); + definition_file.open(QIODevice::ReadWrite); + QTextStream in(&definition_file); + definition = in.readAll(); + definition = definition.remove(QRegExp("[\n]")); + if (definition == "No definition found.") { + nextdefinition_lock = true; + } else { + nextdefinition_lock = false; + } + definition_file.close(); + + setDefaultWorkDir(); +} + +void ReaderWidget::save_word(string word, bool remove) { + if (remove == false) { + QFile words(".config/06-words/config"); + words.open(QIODevice::ReadWrite); + QTextStream in(&words); + QString words_list = in.readAll(); + string words_list_str = words_list.toStdString(); + words.close(); + + log("Saving word '" + QString::fromStdString(word) + "' in Saved Words list", className); + ofstream fhandler; + fhandler.open(".config/06-words/config"); + fhandler << words_list_str << word << "\n"; + fhandler.close(); + } else { + ofstream fhandler; + fhandler.open(".config/06-words/config"); + fhandler << word; + fhandler.close(); + } +} + +void ReaderWidget::on_nextBtn_clicked() { + // ui->nextBtn->setEnabled(false); + if (is_epub == false and is_pdf == false) { + if (split_total - 1 == 1 or split_total - 1 == 0) { + showToast("You've reached the end of the document"); + } else { + split_total = split_total - 1; + log("'Next' button clicked", className); + + setup_book(book_file, split_total, false); + ui->text->setText(""); + ui->text->setText(ittext); + global::reader::currentViewportText = ui->text->toHtml(); + + pagesTurned = pagesTurned + 1; + writeconfig_pagenumber(false); + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); + } + } else if (is_epub == true) { + if (mupdf::epub::epubPageNumber + 1 > totalPagesInt) { + showToast("You've reached the end of the document"); + } else { + mupdf::epub::epubPageNumber = mupdf::epub::epubPageNumber + 1; + log("'Next' button clicked: going to page " + QString::number(mupdf::epub::epubPageNumber), className); + setup_book(book_file, mupdf::epub::epubPageNumber, true); + ui->text->setText(""); + ui->text->setText(epubPageContent); + global::reader::currentViewportText = ui->text->toHtml(); + + pagesTurned = pagesTurned + 1; + writeconfig_pagenumber(false); + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); + } + } else if (is_pdf == true) { + if (mupdf::pdf::pdfPageNumber + 1 > totalPagesInt) { + showToast("You've reached the end of the document"); + } else { + mupdf::pdf::pdfPageNumber = mupdf::pdf::pdfPageNumber + 1; + log("'Next' button clicked: going to page " + QString::number(mupdf::pdf::pdfPageNumber), className); + if (ui->pdfScaleSlider->value() != 1) { + mupdf::convertRelativeValues = true; + } + setup_book(book_file, mupdf::pdf::pdfPageNumber, true); + setupPng(); + + pagesTurned = pagesTurned + 1; + writeconfig_pagenumber(false); + } + } + setupPageWidget(); + refreshScreen(); + // ui->nextBtn->setEnabled(true); +} + +void ReaderWidget::on_previousBtn_clicked() { + // ui->previousBtn->setEnabled(false); + if (is_epub == false and is_pdf == false) { + // Making sure we won't encounter a "List index out of range" error ;) + if (split_total >= split_files_number - 1) { + showToast("No previous page"); + } else { + split_total = split_total + 1; + log("'Previous' button clicked", className); + + setup_book(book_file, split_total, false); + ui->text->setText(""); + ui->text->setText(ittext); + global::reader::currentViewportText = ui->text->toHtml(); + + // We always increment pagesTurned regardless whether we press the Previous or Next button or not + pagesTurned = pagesTurned + 1; + writeconfig_pagenumber(false); + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); + } + } else if (is_pdf == true) { + if (mupdf::pdf::pdfPageNumber - 1 <= 0) { + showToast("No previous page"); + } else { + mupdf::pdf::pdfPageNumber = mupdf::pdf::pdfPageNumber - 1; + log("'Previous' button clicked: going to page " + QString::number(mupdf::pdf::pdfPageNumber), className); + if (ui->pdfScaleSlider->value() != 1) { + mupdf::convertRelativeValues = true; + } + setup_book(book_file, mupdf::pdf::pdfPageNumber, true); + setupPng(); + + // We always increment pagesTurned regardless whether we press the Previous or Next button or not + pagesTurned = pagesTurned + 1; + writeconfig_pagenumber(false); + } + } else { + if (mupdf::epub::epubPageNumber - 1 <= 0) { + showToast("No previous page"); + } else { + mupdf::epub::epubPageNumber = mupdf::epub::epubPageNumber - 1; + log("'Previous' button clicked: going to page " + QString::number(mupdf::epub::epubPageNumber), className); + setup_book(book_file, mupdf::epub::epubPageNumber, true); + ui->text->setText(""); + ui->text->setText(epubPageContent); + global::reader::currentViewportText = ui->text->toHtml(); + + // We always increment pagesTurned regardless whether we press the Previous or Next button or not + pagesTurned = pagesTurned + 1; + writeconfig_pagenumber(false); + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); + } + } + setupPageWidget(); + refreshScreen(); + // ui->previousBtn->setEnabled(true); +} + +void ReaderWidget::refreshScreen() { + if (neverRefresh == true) { + // Do nothing; "Never refresh" was set + ; + } else { + if (pagesTurned >= pageRefreshSetting) { + // Refreshing the screen + this->repaint(); + // Reset count + pagesTurned = 0; + } + } +} + +void ReaderWidget::on_optionsBtn_clicked() { + Device::ScreenSize screenSize = Device::getSingleton()->getScreenSize(); + log("'Options' button clicked", className); + if (menubar_shown == true) { + menubar_hide(); + if (screenSize == Device::ScreenSize::VERY_LARGE) { + ui->optionsBtn->setStyleSheet("background: white; color: black; padding: 13.5px"); + } else if (screenSize == Device::ScreenSize::LARGE) { + ui->optionsBtn->setStyleSheet("background: white; color: black; padding: 12.5px"); + } else { + ui->optionsBtn->setStyleSheet("background: white; color: black; padding: 10px"); + } + ui->optionsBtn->setIcon(QIcon(":/resources/settings.png")); + // The Glo HD (N437) has a newer platform plugin that doesn't need this + // TODO: figure out what this actually does + /*if(global::deviceID != "n437\n" or global::deviceID != "n306\n" or global::deviceID != "n249\n") { + QTimer::singleShot(500, this, SLOT(repaint())); + }*/ + menubar_shown = false; + } else { + menubar_show(); + if (screenSize == Device::ScreenSize::VERY_LARGE) { + ui->optionsBtn->setStyleSheet("background: black; color: white; padding: 13.5px"); + } else if (screenSize == Device::ScreenSize::LARGE) { + ui->optionsBtn->setStyleSheet("background: black; color: white; padding: 12.5px"); + } else { + ui->optionsBtn->setStyleSheet("background: black; color: white; padding: 10px"); + } + ui->optionsBtn->setIcon(QIcon(":/resources/settings-inverted.png")); + this->repaint(); + menubar_shown = true; + } +} + +void ReaderWidget::on_homeBtn_clicked() { + log("Returning to Home screen", className); + // We're leaving reading mode + writeFile("/tmp/inkboxReading", "false"); + // Remount tmpfs + writeFile("/inkbox/remount", "true"); + // Specify cinematic brightness mode + writeFile("/tmp/inkbox-cinematicBrightness_auto", "true"); + + // Relaunching process + quit_restart(); +} + +void ReaderWidget::on_fontChooser_currentIndexChanged(const QString &arg1) { + log("Setting font to '" + arg1 + "'", className); + global::reader::font = arg1; + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); +} + +void ReaderWidget::on_alignLeftBtn_clicked() { + log("Setting text alignment to 'Left'", className); + global::reader::textAlignment = 0; + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); + writeFile(".config/04-book/alignment", "Left"); +} + +void ReaderWidget::on_alignCenterBtn_clicked() { + log("Setting text alignment to 'Center'", className); + global::reader::textAlignment = 1; + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); + writeFile(".config/04-book/alignment", "Center"); +} + +void ReaderWidget::on_alignRightBtn_clicked() { + log("Setting text alignment to 'Right'", className); + global::reader::textAlignment = 2; + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); + writeFile(".config/04-book/alignment", "Right"); +} + +void ReaderWidget::on_alignJustifyBtn_clicked() { + log("Setting text alignment to 'Justify'", className); + global::reader::textAlignment = 3; + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); + writeFile(".config/04-book/alignment", "Justify"); +} + +void ReaderWidget::setTextProperties(int alignment, int lineSpacing, int margins, QString font, int fontSize) { + // Don't try to improve this + // I have spent more time on it than I would care to admit + + // Alignment + /* + * 0 - Left + * 1 - Center + * 2 - Right + * 3 - Justify + */ + + // Selection color + ui->text->setStyleSheet("QTextEdit { selection-background-color: white; color: white; }"); + // Font + { + if (font == "Crimson Pro") { + // As adding Crimson Pro to the default fonts bundled along with the Qt libs breaks the general u001/Inter homogeneity, it is incorporated on-demand here. + { + QString family; + { + int id = QFontDatabase::addApplicationFont(":/resources/fonts/CrimsonPro-Regular.ttf"); + family = QFontDatabase::applicationFontFamilies(id).at(0); + } + { + int id = QFontDatabase::addApplicationFont(":/resources/fonts/CrimsonPro-Italic.ttf"); + family = QFontDatabase::applicationFontFamilies(id).at(0); + } + { + int id = QFontDatabase::addApplicationFont(":/resources/fonts/CrimsonPro-Bold.ttf"); + family = QFontDatabase::applicationFontFamilies(id).at(0); + } + { + int id = QFontDatabase::addApplicationFont(":/resources/fonts/CrimsonPro-BoldItalic.ttf"); + family = QFontDatabase::applicationFontFamilies(id).at(0); + } + ui->text->setFont(QFont(family)); + } + writeFile(".config/04-book/font", "Crimson Pro"); + } else if (font == "Bitter") { + { + QString family; + { + int id = QFontDatabase::addApplicationFont(":/resources/fonts/Bitter-Medium.ttf"); + family = QFontDatabase::applicationFontFamilies(id).at(0); + } + { + int id = QFontDatabase::addApplicationFont(":/resources/fonts/Bitter-MediumItalic.ttf"); + family = QFontDatabase::applicationFontFamilies(id).at(0); + } + { + int id = QFontDatabase::addApplicationFont(":/resources/fonts/Bitter-Bold.ttf"); + family = QFontDatabase::applicationFontFamilies(id).at(0); + } + { + int id = QFontDatabase::addApplicationFont(":/resources/fonts/Bitter-BoldItalic.ttf"); + family = QFontDatabase::applicationFontFamilies(id).at(0); + } + ui->text->setFont(QFont(family)); + } + writeFile(".config/04-book/font", "Bitter"); + } else if (font == "Ibarra Real Nova") { + { + QString family; + { + int id = QFontDatabase::addApplicationFont(":/resources/fonts/IbarraRealNova-Medium.ttf"); + family = QFontDatabase::applicationFontFamilies(id).at(0); + } + { + int id = QFontDatabase::addApplicationFont(":/resources/fonts/IbarraRealNova-MediumItalic.ttf"); + family = QFontDatabase::applicationFontFamilies(id).at(0); + } + { + int id = QFontDatabase::addApplicationFont(":/resources/fonts/IbarraRealNova-Bold.ttf"); + family = QFontDatabase::applicationFontFamilies(id).at(0); + } + { + int id = QFontDatabase::addApplicationFont(":/resources/fonts/IbarraRealNova-BoldItalic.ttf"); + family = QFontDatabase::applicationFontFamilies(id).at(0); + } + ui->text->setFont(QFont(family)); + } + writeFile(".config/04-book/font", "Ibarra Real Nova"); + } else if (font == "Univers (u001)" or font == "u001") { + ui->text->setFont(QFont("u001")); + writeFile(".config/04-book/font", "Univers (u001)"); + } else { + ui->text->setFont(QFont(font)); + writeFile(".config/04-book/font", font); + } + } + + // Highlighting + QString htmlText = global::reader::currentViewportText; + QJsonObject jsonObject = getHighlightsForBook(book_file); + int keyCount = 1; + foreach (const QString &key, jsonObject.keys()) { + if (keyCount <= 1) { + keyCount++; + continue; + } else { + QString highlight = jsonObject.value(key).toString(); + if (htmlText.contains(highlight)) { + htmlText.replace(highlight, "" + highlight + ""); + } + } + keyCount++; + } + htmlText.replace(QRegExp("font-family:'.*';"), ""); + ui->text->setHtml(htmlText); + + // Line spacing, margins + setLineSpacing(lineSpacing, false); + ui->lineSpacingSlider->setValue(lineSpacing); + setMargins(margins, false); + ui->marginsSlider->setValue(margins); + + textDialogLock = true; + QTextCursor cursor = ui->text->textCursor(); + // Kudos to Qt for not implementing the opposite of the following function /)_-) + ui->text->selectAll(); + // Text alignment + if (alignment == 0) { + ui->text->setAlignment(Qt::AlignLeft); + } else if (alignment == 1) { + ui->text->setAlignment(Qt::AlignHCenter); + } else if (alignment == 2) { + ui->text->setAlignment(Qt::AlignRight); + } else if (alignment == 3) { + ui->text->setAlignment(Qt::AlignJustify); + } + // Font size + ui->text->setFontPointSize(fontSize); + ui->text->setTextCursor(cursor); + // Selection color + ui->text->setStyleSheet("QTextEdit { selection-background-color: black; color: black; }"); + textDialogLock = false; +} + +void ReaderWidget::menubar_show() { + log("Showing menu bar", className); + // Checking battery level and status, then displaying the relevant icon on batteryIconLabel + if (Device::getSingleton()->isUSBPluggedIn()) { + ui->batteryIconLabel->setPixmap(scaledChargingPixmap); + } else { + int batteryLevel = Device::getSingleton()->getBatteryLevel(); + if (batteryLevel >= 75 && batteryLevel <= 100) { + ui->batteryIconLabel->setPixmap(scaledFullPixmap); + } + if (batteryLevel >= 25 && batteryLevel <= 74) { + ui->batteryIconLabel->setPixmap(scaledHalfPixmap); + } + if (batteryLevel >= 0 && batteryLevel <= 24) { + ui->batteryIconLabel->setPixmap(scaledEmptyPixmap); + } + } + + ui->menuWidget->setVisible(true); + if (is_pdf == false && is_image == false) { + ui->menuBarWidget->setVisible(true); + } else { + if (is_pdf == true) { + ui->pdfScaleWidget->setVisible(true); + } + ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); + ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + } + ui->buttonsBarWidget->setVisible(true); + ui->statusBarWidget->setVisible(true); + if (is_image == true) { + ui->pageWidget->setVisible(false); + } else { + ui->pageWidget->setVisible(true); + } + + menubar_shown = true; +} + +void ReaderWidget::menubar_hide() { + log("Hiding menu bar", className); + + if (is_pdf == false && is_image == false) { + ui->menuBarWidget->setVisible(false); + } else { + ui->pdfScaleWidget->setVisible(false); + if (checkconfig(".config/14-reader_scrollbar/config") == true) { + ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); + ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + } else { + ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + } + } + ui->buttonsBarWidget->setVisible(false); + ui->pageWidget->setVisible(false); + if (checkconfig(".config/11-menubar/sticky") == true) { + ui->statusBarWidget->setVisible(true); + } else { + ui->statusBarWidget->setVisible(false); + ui->menuWidget->setVisible(false); + } + menubar_shown = false; +} + +void ReaderWidget::wordwidget_show() { + log("Showing word widget", className); + if (menubar_shown == true) { + menubar_hide(); + ui->optionsBtn->hide(); + ui->line->hide(); + ui->wordWidget->setVisible(true); + } else { + ui->optionsBtn->hide(); + ui->line->hide(); + ui->wordWidget->setVisible(true); + } +} + +void ReaderWidget::wordwidget_hide() { + log("Hiding word widget", className); + ui->wordWidget->setVisible(false); + ui->optionsBtn->setStyleSheet("background: white; color: black"); + ui->optionsBtn->show(); + ui->line->show(); + wordwidgetLock = false; +} + +void ReaderWidget::on_infoCloseBtn_clicked() { + wordwidget_hide(); + dictionary_position = 1; + QString dictionary_position_str = QString::number(dictionary_position); + ui->definitionStatusLabel->setText(dictionary_position_str); + + QTextCursor cursor = ui->text->textCursor(); + cursor.clearSelection(); + ui->text->setTextCursor(cursor); +} + +void ReaderWidget::on_previousDefinitionBtn_clicked() { + dictionary_position = dictionary_position - 1; + if (dictionary_position <= 0) { + dictionary_position = 1; + } else { + dictionary_lookup(selected_text_str, letter, dictionary_position); + ui->definitionLabel->setText(definition); + QString dictionary_position_str = QString::number(dictionary_position); + ui->definitionStatusLabel->setText(dictionary_position_str); + } +} + +void ReaderWidget::on_nextDefinitionBtn_clicked() { + dictionary_position = dictionary_position + 1; + dictionary_lookup(selected_text_str, letter, dictionary_position); + if (nextdefinition_lock == true) { + dictionary_position = dictionary_position - 1; + } else { + ui->definitionLabel->setText(definition); + QString dictionary_position_str = QString::number(dictionary_position); + ui->definitionStatusLabel->setText(dictionary_position_str); + } +} + +void ReaderWidget::on_saveWordBtn_clicked() { + if (checkconfig_match(".config/06-words/config", selected_text_str) == true) { + log("Removing word '" + QString::fromStdString(selected_text_str) + "' from Saved Words list", className); + checkwords(); + word = word.append("\n"); + words = words.replace(word, ""); + string words_std_string = words.toStdString(); + save_word(words_std_string, true); + ui->saveWordBtn->setText(""); + ui->saveWordBtn->setIcon(QIcon(":/resources/star.png")); + } else { + save_word(selected_text_str, false); + ui->saveWordBtn->setText(""); + ui->saveWordBtn->setIcon(QIcon(":/resources/starred_star.png")); + } +} + +void ReaderWidget::on_sizeSlider_valueChanged(int value) { + // Font size + log("Setting font size to " + QString::number(value + global::reader::initialFontSize + 1) + " points", className); + ui->sizeValueLabel->setText(QString::number(value + 1)); + + global::reader::fontSize = global::reader::initialFontSize + value + 1; + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); + + writeFile(".config/04-book/size", QString::number(value)); +} + +void ReaderWidget::writeconfig_pagenumber(bool persistent) { + // Saving the page number in tmpfs and in persistent storage if requested + if (is_epub == true) { + QString epubPageNumberStr = QString::number(mupdf::epub::epubPageNumber); + writeFile("/tmp/inkboxPageNumber", epubPageNumberStr); + if (persistent == true) { + log("Writing page number config for page '" + QString::number(mupdf::epub::epubPageNumber) + "'", className); + epubPageNumberStr.append("\n"); + writeFile(".config/A-page_number/config", epubPageNumberStr); + } + } else if (is_pdf == true) { + QString pdfPageNumberStr = QString::number(mupdf::pdf::pdfPageNumber); + writeFile("/tmp/inkboxPageNumber", pdfPageNumberStr); + if (persistent == true) { + log("Writing page number config for page '" + pdfPageNumberStr + "'", className); + pdfPageNumberStr.append("\n"); + writeFile(".config/A-page_number/config", pdfPageNumberStr); + } + } else { + QString splitTotalStr = QString::number(split_total); + writeFile("/tmp/inkboxPageNumber", splitTotalStr); + if (persistent == true) { + log("Writing page number config for split total '" + splitTotalStr + "'", className); + splitTotalStr.append("\n"); + writeFile(".config/A-page_number/config", splitTotalStr); + } + } +} + +void ReaderWidget::quit_restart() { + log("Restarting InkBox", className); + + // Saving current page number + saveReadingSettings(); + + // Cleaning bookconfig_mount mountpoint + writeFile("/opt/ibxd", "bookconfig_unmount\n"); + + // Restarting InkBox + QProcess process; + process.startDetached("inkbox", QStringList()); + qApp->quit(); +} + +void ReaderWidget::openLowBatteryDialog() { + log("Showing low battery dialog", className); + global::mainwindow::lowBatteryDialog = true; + global::battery::batteryAlertLock = true; + + generalDialogWindow = new GeneralDialog(this); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + QApplication::processEvents(); +} + +void ReaderWidget::openCriticalBatteryAlertWindow() { + log("Showing critical battery alert splash", className); + global::battery::showCriticalBatteryAlert = true; + global::battery::showLowBatteryDialog = false; + + alertWindow = new SplashAlertWidget(); + alertWindow->setAttribute(Qt::WA_DeleteOnClose); + alertWindow->setGeometry(QRect(QPoint(0, 0), screen()->geometry().size())); + alertWindow->show(); +} + +void ReaderWidget::convertMuPdfVars(int fileType, bool convertAll) { + /* fileType can be: + * 0: ePUB + * 1: PDF + * 2: Image + */ + if (fileType == 0) { + if (convertAll == 1) { + setPageStyle(0); + mupdf::epub::fontSize = 12; + mupdf::epub::fontSize_qstr = QString::number(mupdf::epub::fontSize); + mupdf::epub::width_qstr = QString::number(mupdf::epub::width); + mupdf::epub::height_qstr = QString::number(mupdf::epub::height); + } + if (global::reader::globalReadingSettings == false) { + if (goToSavedPageDone == false) { + mupdf::epub::epubPageNumber = readFile(".config/A-page_number/config").toInt(); + goToSavedPageDone = true; + } + } + if (mupdf::epub::epubPageNumber <= 0) { + mupdf::epub::epubPageNumber = 1; + } + mupdf::epub::epubPageNumber_qstr = QString::number(mupdf::epub::epubPageNumber); + } else if (fileType == 1) { + setPageStyle(1); + mupdf::pdf::width = defaultPdfPageWidth; + mupdf::pdf::height = defaultPdfPageHeight; + if (mupdf::convertRelativeValues == true) { + // For scaling + mupdf::pdf::width_qstr = QString::number(mupdf::pdf::relativeWidth); + mupdf::pdf::height_qstr = QString::number(mupdf::pdf::relativeHeight); + } else { + // Default + mupdf::pdf::width_qstr = QString::number(mupdf::pdf::width); + mupdf::pdf::height_qstr = QString::number(mupdf::pdf::height); + } + if (global::reader::globalReadingSettings == false) { + if (goToSavedPageDone == false) { + mupdf::pdf::pdfPageNumber = readFile(".config/A-page_number/config").toInt(); + goToSavedPageDone = true; + } + } + if (mupdf::pdf::pdfPageNumber <= 0) { + mupdf::pdf::pdfPageNumber = 1; + } + mupdf::pdf::pdfPageNumber_qstr = QString::number(mupdf::pdf::pdfPageNumber); + } else if (fileType == 2) { + ; + } + if (mupdf::convertRelativeValues == true) { + mupdf::convertRelativeValues = false; + } +} + +void ReaderWidget::setPageStyle(int fileType) { + /* fileType can be: + * 0: ePUB + * 1: PDF + * 2: Image + */ + if (fileType == 0) { + // General page size + defineDefaultPageSize(0); + + if (readFile(".config/13-epub_page_size/width").isEmpty()) { + QString pageWidth = QString::number(defaultEpubPageWidth); + writeFile(".config/13-epub_page_size/width", pageWidth); + writeFile(".config/13-epub_page_size/set", "true"); + } + mupdf::epub::width = readFile(".config/13-epub_page_size/width").toInt(); + + if (readFile(".config/13-epub_page_size/height").isEmpty()) { + QString pageHeight = QString::number(defaultEpubPageHeight); + writeFile(".config/13-epub_page_size/height", pageHeight); + writeFile(".config/13-epub_page_size/set", "true"); + } + mupdf::epub::height = readFile(".config/13-epub_page_size/height").toInt(); + } else if (fileType == 1) { + defineDefaultPageSize(1); + } +} + +void ReaderWidget::delay(int mseconds) { + // https://stackoverflow.com/questions/3752742/how-do-i-create-a-pause-wait-function-using-qt + QTime dieTime = QTime::currentTime().addMSecs(mseconds); + while (QTime::currentTime() < dieTime) + QCoreApplication::processEvents(QEventLoop::AllEvents, 100); +} + +void ReaderWidget::on_text_selectionChanged() { + delay(100); + if (wordwidgetLock == false and textDialogLock == false) { + QTextCursor cursor = ui->text->textCursor(); + selected_text = cursor.selectedText(); + if (!selected_text.isEmpty()) { + log("Text selection changed; selected text: '" + selected_text + "'", className); + if (!selected_text.contains(" ")) { + // Word selection + QString dictionary_position_str = QString::number(dictionary_position); + ui->definitionStatusLabel->setText(dictionary_position_str); + + selected_text = selected_text.toLower(); + QStringList parts = selected_text.split(' ', QString::SkipEmptyParts); + for (int i = 0; i < parts.size(); ++i) + parts[i].replace(0, 1, parts[i][0].toUpper()); + word = parts.join(" "); + letter = word.left(1); + selected_text_str = word.toStdString(); + dictionary_lookup(selected_text_str, letter, dictionary_position); + ui->wordLabel->setText(word); + ui->definitionLabel->setText(definition); + if (checkconfig_match(".config/06-words/config", selected_text_str) == true) { + ui->saveWordBtn->setText(""); + ui->saveWordBtn->setIcon(QIcon(":/resources/starred_star.png")); + } else { + ui->saveWordBtn->setText(""); + ui->saveWordBtn->setIcon(QIcon(":/resources/star.png")); + } + wordwidgetLock = true; + wordwidget_show(); + } else { + // Highlight + textDialogLock = true; + global::reader::highlightAlreadyDone = false; + QJsonObject jsonObject = getHighlightsForBook(book_file); + QString htmlText = ui->text->toHtml(); + if (htmlText.contains("" + selected_text + "") or htmlText.contains("" + selected_text + "")) { + log("Highlight already done", className); + global::reader::highlightAlreadyDone = true; + } + + TextDialog *textDialogWindow = new TextDialog(this); + QObject::connect(textDialogWindow, &TextDialog::destroyed, this, &ReaderWidget::unsetTextDialogLock); + QObject::connect(textDialogWindow, &TextDialog::highlightText, this, &ReaderWidget::highlightText); + QObject::connect(textDialogWindow, &TextDialog::unhighlightText, this, &ReaderWidget::unhighlightText); + textDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + textDialogWindow->setWindowFlags(Qt::FramelessWindowHint | Qt::Popup); + textDialogWindow->move(mapFromGlobal(ui->text->cursorRect().bottomRight())); + textDialogWindow->show(); + } + } else { + ; + } + } +} + +void ReaderWidget::on_nightModeBtn_clicked() { + if (isNightModeActive == true) { + // Disabling night/dark mode + log("Setting night mode to OFF", className); + writeFile("/tmp/invertScreen", "n"); + writeFile(".config/10-dark_mode/config", "false"); + ui->nightModeBtn->setIcon(QIcon(":/resources/nightmode-empty.png")); + isNightModeActive = false; + } else { + // Enabling night/dark mode + log("Setting night mode to ON", className); + writeFile("/tmp/invertScreen", "y"); + writeFile(".config/10-dark_mode/config", "true"); + ui->nightModeBtn->setIcon(QIcon(":/resources/nightmode-full.png")); + isNightModeActive = true; + } +} + +void ReaderWidget::openUsbmsDialog() { + log("Showing USBMS dialog", className); + global::usbms::showUsbmsDialog = false; + global::usbms::usbmsDialog = true; + + generalDialogWindow = new GeneralDialog(this); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + QApplication::processEvents(); +} + +QString ReaderWidget::setPageNumberLabelContent() { + QString content; + if (is_epub == true) { + QString pageNumber; + QString totalPages; + pageNumberInt = mupdf::epub::epubPageNumber; + pageNumber = QString::number(pageNumberInt); + totalPages = QString::number(totalPagesInt); + content.append(pageNumber); + content.append(" of "); + content.append(totalPages); + } else if (is_pdf == true) { + QString pageNumber; + QString totalPages; + pageNumberInt = mupdf::pdf::pdfPageNumber; + pageNumber = QString::number(pageNumberInt); + totalPages = QString::number(totalPagesInt); + content.append(pageNumber); + content.append(" of "); + content.append(totalPages); + } else { + QString pageNumber; + QString totalPages; + pageNumberInt = split_files_number - split_total; + totalPagesInt = split_files_number - 2; + pageNumber = QString::number(pageNumberInt); + totalPages = QString::number(totalPagesInt); + content.append(pageNumber); + content.append(" of "); + content.append(totalPages); + } + return content; +} + +void ReaderWidget::setupPageWidget() { + QString pageNumberInfoLabelContent = setPageNumberLabelContent(); + ui->pageNumberLabel->setText(pageNumberInfoLabelContent); + ui->pageProgressBar->setMaximum(totalPagesInt); + ui->pageProgressBar->setMinimum(1); + ui->pageProgressBar->setValue(pageNumberInt); +} + +void ReaderWidget::getTotalEpubPagesNumber() { + QString epubProg("sh"); + QStringList epubArgs; + convertMuPdfVars(0, true); + epubArgs << "/mnt/onboard/.adds/inkbox/epub.sh" << mupdf::epub::fontSize_qstr << mupdf::epub::width_qstr << mupdf::epub::height_qstr << mupdf::epub::epubPageNumber_qstr << "get_pages_number"; + QProcess *epubProc = new QProcess(); + epubProc->start(epubProg, epubArgs); + epubProc->waitForFinished(); + epubProc->deleteLater(); + + QString totalPages = readFile("/run/epub_total_pages_number"); + totalPagesInt = totalPages.toInt(); + log("ePUB total pages number: " + totalPages, className); + QFile::remove("/run/epub_total_pages_number"); +} + +void ReaderWidget::on_gotoBtn_clicked() { + log("Showing 'Go to page' dialog", className); + global::keyboard::keypadDialog = true; + generalDialogWindow = new GeneralDialog(); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + connect(generalDialogWindow, SIGNAL(gotoPageSelected(int)), SLOT(gotoPage(int))); +} + +void ReaderWidget::gotoPage(int pageNumber) { + log("Going to page " + QString::number(pageNumber), className); + if (is_epub == true) { + if (pageNumber > totalPagesInt or pageNumber < 1) { + showToast("Request is beyond page range"); + } else { + mupdf::epub::epubPageNumber = pageNumber; + setup_book(book_file, mupdf::epub::epubPageNumber, true); + ui->text->setText(""); + ui->text->setText(epubPageContent); + global::reader::currentViewportText = ui->text->toHtml(); + + pagesTurned = 0; + writeconfig_pagenumber(false); + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); + } + } else if (is_pdf == true) { + if (pageNumber > totalPagesInt or pageNumber < 1) { + showToast("Request is beyond page range"); + } else { + mupdf::pdf::pdfPageNumber = pageNumber; + setup_book(book_file, mupdf::pdf::pdfPageNumber, true); + setupPng(); + + pagesTurned = 0; + writeconfig_pagenumber(false); + } + } else { + if (split_files_number - pageNumber < 2 or split_files_number - pageNumber > split_files_number - 1) { + showToast("You've reached the end of the document"); + } else { + split_total = split_files_number - pageNumber; + + setup_book(book_file, split_total, false); + ui->text->setText(""); + ui->text->setText(ittext); + + pagesTurned = 0; + writeconfig_pagenumber(false); + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); + } + } + setupPageWidget(); + refreshScreen(); +} + +void ReaderWidget::on_searchBtn_clicked() { + global::forbidOpenSearchDialog = false; + setupSearchDialog(); +} + +void ReaderWidget::setupSearchDialog() { + if (global::forbidOpenSearchDialog == false) { + log("Launching Search dialog", className); + global::keyboard::keyboardDialog = true; + global::keyboard::searchDialog = true; + global::keyboard::keyboardText = ""; + generalDialogWindow = new GeneralDialog(); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + connect(generalDialogWindow, SIGNAL(refreshScreen()), SLOT(searchRefreshScreen())); + connect(generalDialogWindow, SIGNAL(destroyed(QObject *)), SLOT(setupSearchDialog())); + connect(generalDialogWindow, SIGNAL(openBookFile(QString, bool)), SLOT(openBookFileNative(QString, bool))); + connect(generalDialogWindow, SIGNAL(showToast(QString)), SLOT(showToast(QString))); + connect(generalDialogWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToast())); + generalDialogWindow->show(); + } else { + ; + } +} + +void ReaderWidget::searchRefreshScreen() { + this->repaint(); +} + +void ReaderWidget::showToast(QString messageToDisplay) { + global::toast::message = messageToDisplay; + toastWindow = new toast(this); + toastWindow->setAttribute(Qt::WA_DeleteOnClose); + toastWindow->show(); +} + +void ReaderWidget::saveReadingSettings() { + writeconfig_pagenumber(true); +} + +void ReaderWidget::setupLocalSettingsEnvironment() { + log("Setting local settings environment up", className); + QString pageNumberDirPath = ".config/A-page_number"; + QDir pageNumberDir; + pageNumberDir.mkpath(pageNumberDirPath); +} + +void ReaderWidget::setupPng() { + if (is_pdf == true) { + // Note: Output file is supposed to be '/run/page.png', but somehow mutool puts it in '/run/page1.png' + QPixmap pixmap("/run/page1.png"); + QFile::remove("/run/page1.png"); + // Initialized above + graphicsScene->clear(); + graphicsScene->addPixmap(pixmap); + // Shrinking scene if item is smaller than previous one + QRectF rect = graphicsScene->itemsBoundingRect(); + graphicsScene->setSceneRect(rect); + ui->graphicsView->items().clear(); + ui->graphicsView->setScene(graphicsScene); + if (global::reader::pdfOrientation == 1) { + if (!initialPdfRotationDone) { + ui->graphicsView->rotate(270); + initialPdfRotationDone = true; + } + } + } else if (is_image == true) { + QPixmap pixmap("/run/image.png"); + QFile::remove("/run/image.png"); + // Initialized above + graphicsScene->clear(); + graphicsScene->addPixmap(pixmap); + // Shrinking scene if item is smaller than previous one + QRectF rect = graphicsScene->itemsBoundingRect(); + graphicsScene->setSceneRect(rect); + ui->graphicsView->items().clear(); + ui->graphicsView->setScene(graphicsScene); + } +} + +bool ReaderWidget::pdf_file_match(QString file) { + QString fileExt = file.right(3); + + if (fileExt == "pdf" or fileExt == "PDF") { + log("Book file format: PDF", className); + writeFile("/inkbox/bookIsPdf", "true"); + return true; + } else { + writeFile("/inkbox/bookIsPdf", "false"); + return false; + } +} + +bool ReaderWidget::image_file_match(QString file) { + if (file.right(3) == "png" or file.right(3) == "PNG" or file.right(3) == "jpg" or file.right(3) == "JPG" or file.right(3) == "bmp" or file.right(3) == "BMP" or file.right(3) == "tif" or file.right(3) == "TIF") { + log("File format: image", className); + writeFile("/inkbox/bookIsImage", "true"); + return true; + } else if (file.right(4) == "jpeg" or file.right(4) == "JPEG" or file.right(4) == "tiff" or file.right(4) == "TIFF") { + log("File format: image", className); + writeFile("/inkbox/bookIsImage", "true"); + return true; + } else { + writeFile("/inkbox/bookIsImage", "false"); + return false; + } +} + +void ReaderWidget::getTotalPdfPagesNumber() { + QString epubProg("sh"); + QStringList epubArgs; + convertMuPdfVars(0, true); + epubArgs << "/mnt/onboard/.adds/inkbox/pdf_get_total_pages_number.sh" << book_file; + QProcess *epubProc = new QProcess(); + epubProc->start(epubProg, epubArgs); + epubProc->waitForFinished(); + epubProc->deleteLater(); + + QString totalPages = readFile("/run/pdf_total_pages_number"); + totalPagesInt = totalPages.toInt(); + log("Total PDF pages number: " + totalPages, className); + QFile::remove("/run/pdf_total_pages_number"); +} + +void ReaderWidget::on_pdfScaleSlider_valueChanged(int value) { + log("Setting PDF scale to " + QString::number(value), className); + if (value == 1) { + mupdf::pdf::relativeWidth = 1 * mupdf::pdf::width; + mupdf::pdf::relativeHeight = 1 * mupdf::pdf::height; + } else if (value == 2) { + mupdf::pdf::relativeWidth = 1.50 * mupdf::pdf::width; + mupdf::pdf::relativeHeight = 1.50 * mupdf::pdf::height; + } else if (value == 3) { + mupdf::pdf::relativeWidth = 2 * mupdf::pdf::width; + mupdf::pdf::relativeHeight = 2 * mupdf::pdf::height; + } else if (value == 4) { + mupdf::pdf::relativeWidth = 2.50 * mupdf::pdf::width; + mupdf::pdf::relativeHeight = 2.50 * mupdf::pdf::height; + } + + if (value != 1) { + ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); + ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + } else { + if (checkconfig(".config/14-reader_scrollbar/config") == true) { + ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); + ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + } else { + ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + } + } + + mupdf::convertRelativeValues = true; + setup_book(book_file, mupdf::pdf::pdfPageNumber, true); + setupPng(); +} + +void ReaderWidget::on_decreaseScaleBtn_clicked() { + int sliderCurrentValue; + int sliderWantedValue; + sliderCurrentValue = ui->pdfScaleSlider->value(); + sliderWantedValue = sliderCurrentValue - 1; + if (sliderWantedValue < ui->pdfScaleSlider->QAbstractSlider::minimum()) { + showToast("Minimum scale reached"); + } else { + ui->pdfScaleSlider->setValue(sliderWantedValue); + } +} + +void ReaderWidget::on_increaseScaleBtn_clicked() { + int sliderCurrentValue; + int sliderWantedValue; + sliderCurrentValue = ui->pdfScaleSlider->value(); + sliderWantedValue = sliderCurrentValue + 1; + if (sliderWantedValue > ui->pdfScaleSlider->QAbstractSlider::maximum()) { + showToast("Maximum scale reached"); + } else { + ui->pdfScaleSlider->setValue(sliderWantedValue); + } +} + +void ReaderWidget::openBookFileNative(QString book, bool relativePath) { + if (global::runningInstanceIsReaderOnly == false) { + emit openBookFile(book, relativePath); + } else { + showToast("Not supported"); + } +} + +void ReaderWidget::on_quitBtn_clicked() { + log("Showing Quit window", className); + writeconfig_pagenumber(true); + quitWindow = new QuitWidget(); + quitWindow->setAttribute(Qt::WA_DeleteOnClose); + quitWindow->showFullScreen(); +} + +void ReaderWidget::closeIndefiniteToast() { + // Warning: use with caution + toastWindow->close(); +} + +void ReaderWidget::getPdfOrientation(QString file) { + log("Getting viewport orientation for PDF file '" + file + "'", className); + writeFile("/inkbox/pdf_orientation_file_request", file); + writeFile("/opt/ibxd", "get_pdf_orientation\n"); + while (true) { + if (QFile::exists("/inkbox/pdf_orientation_result")) { + QString result = readFile("/inkbox/pdf_orientation_result").trimmed(); + if (result == "Portrait") { + QString function = __func__; + log(function + ": Orientation is portrait", className); + global::reader::pdfOrientation = 0; + } else { + QString function = __func__; + log(function + ": Orientation is landscape", className); + global::reader::pdfOrientation = 1; + } + break; + } + } +} + +void ReaderWidget::unsetTextDialogLock() { + QTextCursor cursor = ui->text->textCursor(); + cursor.clearSelection(); + ui->text->setTextCursor(cursor); + + textDialogLock = false; +} + +void ReaderWidget::highlightText() { + log("Highlighting text '" + selected_text + "'", className); + highlightBookText(selected_text, book_file, false); + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); +} + +void ReaderWidget::unhighlightText() { + log("Removing highlighted text '" + selected_text + "'", className); + highlightBookText(selected_text, book_file, true); + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); +} + +void ReaderWidget::on_viewHighlightsBtn_clicked() { + log("Launching highlights list dialog for book '" + book_file + "'", className); + QJsonObject jsonObject = getHighlightsForBook(book_file); + if (jsonObject.isEmpty() or jsonObject.length() <= 1) { + global::toast::delay = 3000; + showToast("No highlights for this book"); + } else { + global::highlightsListDialog::bookPath = book_file; + HighlightsListDialog *highlightsListDialogWindow = new HighlightsListDialog(this); + QObject::connect(highlightsListDialogWindow, &HighlightsListDialog::destroyed, this, &ReaderWidget::setTextPropertiesSlot); + QObject::connect(highlightsListDialogWindow, &HighlightsListDialog::showToast, this, &ReaderWidget::showToast); + highlightsListDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + } +} + +void ReaderWidget::setTextPropertiesSlot() { + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); +} + +void ReaderWidget::setInitialTextProperties() { + // Checking saved font size if any, and if there is, set it + QString fontSizeString = readFile(".config/04-book/size"); + if (!fontSizeString.isEmpty()) { + global::reader::fontSize = fontSizeString.toInt(); + ui->sizeSlider->setValue(global::reader::fontSize); + } else { + global::reader::fontSize = 4; + } +} + +void ReaderWidget::setLineSpacing(int spacing, bool write) { + global::reader::lineSpacing = spacing; + if (write == true and readFile(".config/04-book/line_spacing") != QString::number(global::reader::lineSpacing)) { + writeFile(".config/04-book/line_spacing", QString::number(global::reader::lineSpacing)); + } + + if (write == false) { + log("Setting line spacing to " + QString::number(global::reader::lineSpacing + 1), className); + QTextCursor textCursor = ui->text->textCursor(); + + QTextBlockFormat *newFormat = new QTextBlockFormat(); + textCursor.clearSelection(); + textCursor.select(QTextCursor::Document); + newFormat->setLineHeight((global::reader::lineSpacing * 10 + 100), QTextBlockFormat::ProportionalHeight); + newFormat->setLeftMargin(global::reader::margins * 10); + newFormat->setRightMargin(global::reader::margins * 10); + textCursor.setBlockFormat(*newFormat); + } +} + +void ReaderWidget::setMargins(int margins, bool write) { + global::reader::margins = margins; + if (write == true and readFile(".config/04-book/margins") != QString::number(global::reader::margins)) { + writeFile(".config/04-book/margins", QString::number(global::reader::margins)); + } + + if (write == false) { + log("Setting margins to " + QString::number(global::reader::margins), className); + QTextCursor textCursor = ui->text->textCursor(); + + QTextBlockFormat *newFormat = new QTextBlockFormat(); + textCursor.clearSelection(); + textCursor.select(QTextCursor::Document); + newFormat->setLineHeight((global::reader::lineSpacing * 10 + 100), QTextBlockFormat::ProportionalHeight); + newFormat->setLeftMargin(global::reader::margins * 10); + newFormat->setRightMargin(global::reader::margins * 10); + textCursor.setBlockFormat(*newFormat); + } +} + +void ReaderWidget::on_lineSpacingSlider_valueChanged(int value) { + global::reader::lineSpacing = value; + // Write setting once + setLineSpacing(global::reader::lineSpacing, true); + // Be consistent with other settings + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); + ui->lineSpacingValueLabel->setText(QString::number(value + 1)); +} + +void ReaderWidget::on_marginsSlider_valueChanged(int value) { + global::reader::margins = value; + // Write setting once + setMargins(global::reader::margins, true); + // Be consistent with other settings + setTextProperties(global::reader::textAlignment, global::reader::lineSpacing, global::reader::margins, global::reader::font, global::reader::fontSize); + ui->marginsValueLabel->setText(QString::number(value + 1)); +} + +void ReaderWidget::on_brightnessBtn_clicked() { + log("Showing Brightness Dialog", className); + brightnessDialogWindow = new BrightnessDialog(); + brightnessDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + brightnessDialogWindow->show(); +} + +void ReaderWidget::setCinematicBrightnessWarmthSlot() { + Device *device = Device::getSingleton(); + //FIXME: I have no clue what this is supposed to do, it sets the brightness value to itself? + if (global::reader::globalReadingSettings == false) { + if (device->supportsBrightness()) { + int brightness_value = device->getBrightness(); + log("Local Reading Settings: Setting brightness to " + QString::number(brightness_value), className); + UI::transitionBrightness(brightness_value); + } + if (device->supportsWarmLight()) { + int warmthValue = device->getWarmth(); + log("Local Reading Settings: Setting warmth to " + QString::number(warmthValue), className); + UI::transitionWarmth(warmthValue); + } + } +} diff --git a/src/reader/reader.h b/src/ui/reader/reader.h similarity index 92% rename from src/reader/reader.h rename to src/ui/reader/reader.h index d8d5a7b..35b385d 100644 --- a/src/reader/reader.h +++ b/src/ui/reader/reader.h @@ -2,7 +2,7 @@ #define READER_H #include "functions.h" -#include "alert.h" +#include "splashAlert.h" #include "generaldialog.h" #include "toast.h" #include "quit.h" @@ -41,17 +41,17 @@ namespace mupdf { } namespace Ui { -class reader; +class ReaderWidget; } -class reader : public QWidget +class ReaderWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit reader(QWidget *parent = nullptr); - ~reader(); + explicit ReaderWidget(QWidget *parent = nullptr); + ~ReaderWidget(); int split_total; int split_files_number; @@ -174,15 +174,15 @@ signals: void openBookFile(QString book, bool relativePath); private: - Ui::reader * ui; - alert * alertWindow; - generalDialog * generalDialogWindow; + Ui::ReaderWidget * ui; + SplashAlertWidget * alertWindow; + GeneralDialog * generalDialogWindow; toast * toastWindow; - quit * quitWindow; - textDialog * textDialogWindow; - highlightsListDialog * highlightsListDialogWindow; + QuitWidget * quitWindow; + TextDialog * textDialogWindow; + HighlightsListDialog * highlightsListDialogWindow; QGraphicsScene * graphicsScene; - brightnessDialog * brightnessDialogWindow; + BrightnessDialog * brightnessDialogWindow; }; #endif // READER_H diff --git a/src/reader/reader.ui b/src/ui/reader/reader.ui similarity index 99% rename from src/reader/reader.ui rename to src/ui/reader/reader.ui index c251fa5..8faea26 100644 --- a/src/reader/reader.ui +++ b/src/ui/reader/reader.ui @@ -1,7 +1,7 @@ - reader - + ReaderWidget + 0 diff --git a/src/ui/settings/koboxsettings.cpp b/src/ui/settings/koboxsettings.cpp new file mode 100644 index 0000000..bd038e6 --- /dev/null +++ b/src/ui/settings/koboxsettings.cpp @@ -0,0 +1,110 @@ +#include "koboxsettings.h" +#include "device.h" +#include "functions.h" +#include "ui.h" +#include "ui_koboxsettings.h" + +#include +#include + +KoboxSettingsWidget::KoboxSettingsWidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::KoboxSettingsWidget) { + ui->setupUi(this); + KoboxSettingsWidget::setFont(QFont("u001")); + ui->okBtn->setFont(QFont("Inter")); + + // UI tweaks + ui->okBtn->setProperty("type", "borderless"); + ui->pushButton->setProperty("type", "borderless"); + ui->resetKoboxBtn->setProperty("type", "borderless"); + ui->pushButton->setStyleSheet("font-weight: bold"); + ui->resetKoboxBtn->setStyleSheet("font-weight: bold"); + ui->okBtn->setStyleSheet("font-weight: bold"); + + // Stylesheet + UI::applyStyle(*this, "eink"); + + if (checkconfig("/external_root/boot/flags/X11_START") == true) { + ui->koboxStatusLabel->setText("KoBox is enabled"); + not_user_change = true; + ui->checkBox->click(); + ui->runtimeSettingsWidget->setVisible(true); + } else { + ui->koboxStatusLabel->setText("KoBox is disabled"); + ui->runtimeSettingsWidget->setVisible(false); + } + + // DPI setting + QString dpiSetting; + QString dpiSettingStr = readFile(".config/00-kobox/dpiSetting"); + int dpi = dpiSettingStr.toInt(); + if (dpiSettingStr.isEmpty()) { + dpi = Device::getSingleton()->getSingleton()->getBaseDPI(); + writeFile(".config/00-kobox/dpiSetting", QString(dpi)); + } + + ui->spinBox->setValue(dpi); +} + +KoboxSettingsWidget::~KoboxSettingsWidget() { + delete ui; +} + +void KoboxSettingsWidget::on_okBtn_clicked() { + KoboxSettingsWidget::close(); +} + +void KoboxSettingsWidget::on_checkBox_toggled(bool checked) { + if (checked == true) { + if (not_user_change != true) { + log("Enabling KoBox subsystem", className); + writeFile("/external_root/boot/flags/X11_START", "true\n"); + openSettingsRebootDialog(); + } else { + not_user_change = false; + } + } else { + log("Disabling KoBox subsystem", className); + writeFile("/external_root/boot/flags/X11_START", "false\n"); + openSettingsRebootDialog(); + } +} + +void KoboxSettingsWidget::openSettingsRebootDialog() { + log("Showing reboot dialog", className); + global::settings::settingsRebootDialog = true; + global::kobox::koboxSettingsRebootDialog = true; + generalDialogWindow = new GeneralDialog(this); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); +} +void KoboxSettingsWidget::openResetKoboxDialog() { + log("Showing KoBox reset dialog", className); + global::kobox::resetKoboxDialog = true; + generalDialogWindow = new GeneralDialog(this); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); +} + +void KoboxSettingsWidget::on_spinBox_valueChanged(int arg1) { + QString number = QString::number(arg1); + writeFile(".config/00-kobox/dpiSetting", number); + log("X11 DPI set to " + number, className); +} + +void KoboxSettingsWidget::on_pushButton_clicked() { + // Export Extensions disk image over USB with g_mass_storage/g_file_storage + global::usbms::usbmsDialog = false; + global::usbms::launchUsbms = true; + global::usbms::koboxExportExtensions = true; + + log("Exporting KoBox extensions onboard storage via USB", className); + log("Showing USBMS splash", className); + usbmsWindow = new USBMSSplashWidget(); + usbmsWindow->setAttribute(Qt::WA_DeleteOnClose); + usbmsWindow->setGeometry(QRect(QPoint(0, 0), screen()->geometry().size())); + usbmsWindow->show(); +} + +void KoboxSettingsWidget::on_resetKoboxBtn_clicked() { + openResetKoboxDialog(); +} diff --git a/src/settings/koboxsettings.h b/src/ui/settings/koboxsettings.h similarity index 68% rename from src/settings/koboxsettings.h rename to src/ui/settings/koboxsettings.h index fbced89..1ec7a6a 100644 --- a/src/settings/koboxsettings.h +++ b/src/ui/settings/koboxsettings.h @@ -7,17 +7,17 @@ #include "usbmsSplash.h" namespace Ui { -class koboxSettings; +class KoboxSettingsWidget; } -class koboxSettings : public QWidget +class KoboxSettingsWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit koboxSettings(QWidget *parent = nullptr); - ~koboxSettings(); + explicit KoboxSettingsWidget(QWidget *parent = nullptr); + ~KoboxSettingsWidget(); bool not_user_change = false; void openSettingsRebootDialog(); @@ -31,9 +31,9 @@ private slots: void on_resetKoboxBtn_clicked(); private: - Ui::koboxSettings *ui; - generalDialog *generalDialogWindow; - usbmsSplash *usbmsWindow; + Ui::KoboxSettingsWidget *ui; + GeneralDialog *generalDialogWindow; + USBMSSplashWidget *usbmsWindow; }; #endif // KOBOXSETTINGS_H diff --git a/src/settings/koboxsettings.ui b/src/ui/settings/koboxsettings.ui similarity index 99% rename from src/settings/koboxsettings.ui rename to src/ui/settings/koboxsettings.ui index 08f2689..7e8bae8 100644 --- a/src/settings/koboxsettings.ui +++ b/src/ui/settings/koboxsettings.ui @@ -1,7 +1,7 @@ - koboxSettings - + KoboxSettingsWidget + 0 diff --git a/src/ui/settings/powerdaemonsettings.cpp b/src/ui/settings/powerdaemonsettings.cpp new file mode 100644 index 0000000..9f9a3b3 --- /dev/null +++ b/src/ui/settings/powerdaemonsettings.cpp @@ -0,0 +1,399 @@ +#include "powerdaemonsettings.h" +#include "device.h" +#include "functions.h" +#include "ui_powerdaemonsettings.h" +#include "ui.h" +#include + +PowerDaemonSettingsWidget::PowerDaemonSettingsWidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::PowerDaemonSettingsWidget) { + ui->setupUi(this); + PowerDaemonSettingsWidget::setFont(QFont("u001")); + ui->mainLabel->setFont(QFont("Inter")); + + // Avoid some display issues (label moving because width of text would change with a proportional font) + ui->CBSLabel->setFont(QFont("Roboto Mono")); + ui->idleSleepLabel->setFont(QFont("Roboto Mono")); + + // Font tweaks + ui->label_2->setFont(QFont("Inter")); + ui->exitBtn->setFont(QFont("Inter")); + + // UI tweaks + ui->exitBtn->setProperty("type", "borderless"); + ui->expBtn->setProperty("type", "borderless"); + ui->hWhenChargerSleepBtn->setProperty("type", "borderless"); + ui->hChargerWakeUpBtn->setProperty("type", "borderless"); + ui->wifiReconnectBtn->setProperty("type", "borderless"); + ui->ledUsageBtn->setProperty("type", "borderless"); + ui->hCustomCaseBtn->setProperty("type", "borderless"); + ui->deepSleepBtn->setProperty("type", "borderless"); + + ui->mainLabel->setStyleSheet("font-weight: bold"); + ui->CBSLabel->setStyleSheet("font-weight: bold"); + ui->idleSleepLabel->setStyleSheet("font-weight: bold"); + ui->exitBtn->setStyleSheet("font-weight: bold"); + // Experimental features label + ui->label_2->setStyleSheet("font-weight: bold"); + + Device::ScreenSize screenSize = Device::getSingleton()->getScreenSize(); + + // Icons + int controlBtnFixedWidth; + if (screenSize == Device::ScreenSize::SMALL) { + controlBtnFixedWidth = 50; + } else { + controlBtnFixedWidth = 80; + } + + ui->CBSDecreaseBtn->setIcon(QIcon(":/resources/minus.png")); + ui->CBSDecreaseBtn->setFixedWidth(controlBtnFixedWidth); + ui->CBSIncreaseBtn->setIcon(QIcon(":/resources/plus.png")); + ui->CBSIncreaseBtn->setFixedWidth(controlBtnFixedWidth); + + int idleBtnsFixedWidth; + if (screenSize == Device::ScreenSize::SMALL) { + idleBtnsFixedWidth = 80; + } else { + idleBtnsFixedWidth = 100; + } + ui->idleSleepDecreaseBtn->setFixedWidth(idleBtnsFixedWidth); + ui->idleSleepIncreaseBtn->setFixedWidth(idleBtnsFixedWidth); + ui->idleSleepDecreaseMBtn->setFixedWidth(idleBtnsFixedWidth); + ui->idleSleepIncreaseMBtn->setFixedWidth(idleBtnsFixedWidth); + + // Padding + ui->CBSDecreaseBtn->setStyleSheet("padding: 10px; font-size: 10pt"); + ui->CBSIncreaseBtn->setStyleSheet("padding: 10px; font-size: 10pt"); + ui->idleSleepDecreaseBtn->setStyleSheet("font-family: 'Roboto Mono'; font-weight: bold; padding: 10px; font-size: 10pt"); + ui->idleSleepIncreaseBtn->setStyleSheet("font-family: 'Roboto Mono'; font-weight: bold; padding: 10px; font-size: 10pt"); + ui->idleSleepDecreaseMBtn->setStyleSheet("font-family: 'Roboto Mono'; font-weight: bold; padding: 10px; font-size: 10pt"); + ui->idleSleepIncreaseMBtn->setStyleSheet("font-family: 'Roboto Mono'; font-weight: bold; padding: 10px; font-size: 10pt"); + + // Stylesheet + UI::applyStyle(*this, "eink"); + + // Button tweaks + int autoRepeatDelay = 1250; + int autoRepeatInterval = 20; + + ui->CBSDecreaseBtn->setAutoRepeat(true); + ui->CBSDecreaseBtn->setAutoRepeatDelay(autoRepeatDelay); + ui->CBSDecreaseBtn->setAutoRepeatInterval(autoRepeatInterval); + + ui->CBSIncreaseBtn->setAutoRepeat(true); + ui->CBSIncreaseBtn->setAutoRepeatDelay(autoRepeatDelay); + ui->CBSIncreaseBtn->setAutoRepeatInterval(autoRepeatInterval); + + ui->idleSleepDecreaseBtn->setAutoRepeat(true); + ui->idleSleepDecreaseBtn->setAutoRepeatDelay(autoRepeatDelay); + ui->idleSleepDecreaseBtn->setAutoRepeatInterval(autoRepeatInterval); + + ui->idleSleepIncreaseBtn->setAutoRepeat(true); + ui->idleSleepIncreaseBtn->setAutoRepeatDelay(autoRepeatDelay); + ui->idleSleepIncreaseBtn->setAutoRepeatInterval(autoRepeatInterval); + + ui->idleSleepDecreaseMBtn->setAutoRepeat(true); + ui->idleSleepDecreaseMBtn->setAutoRepeatDelay(autoRepeatDelay); + ui->idleSleepDecreaseMBtn->setAutoRepeatInterval(autoRepeatInterval); + + ui->idleSleepIncreaseMBtn->setAutoRepeat(true); + ui->idleSleepIncreaseMBtn->setAutoRepeatDelay(autoRepeatDelay); + ui->idleSleepIncreaseMBtn->setAutoRepeatInterval(autoRepeatInterval); + + // Hide items + ui->hLabel_3->hide(); + ui->hCpuFreqComboBox->hide(); + + ui->hWhenChargerSleepBtn->hide(); + ui->hChargerWakeUpBtn->hide(); + ui->hCustomCaseBtn->hide(); + + // Prepare variables from system configuration (20-sleep_daemon) + log("Reading variables from power daemon configuration", className); + + // 1 - cinematicBrightnessDelayMs + QString cinematicBrightnessMs = readFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/1-cinematicBrightnessDelayMs"); + + cinematicBrightnessInt = cinematicBrightnessMs.toInt(); + convertCinematicInt(); + + // 2 - cpuGovernor + QString cpuGovernor = readFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/2-cpuGovernor"); + + QStringList cpuGovernorList = QStringList{ cpuGovernor }; + if (cpuGovernorList.contains("interactive") == false) { + cpuGovernorList.append("interactive"); + } + if (cpuGovernorList.contains("conservative") == false) { + cpuGovernorList.append("conservative"); + } + if (cpuGovernorList.contains("userspace") == false) { + cpuGovernorList.append("userspace"); + } + if (cpuGovernorList.contains("powersave") == false) { + cpuGovernorList.append("powersave"); + } + if (cpuGovernorList.contains("ondemand") == false) { + cpuGovernorList.append("ondemand"); + } + if (cpuGovernorList.contains("performance") == false) { + cpuGovernorList.append("performance"); + } + + ui->hCpuFreqComboBox->addItems(cpuGovernorList); + ui->hCpuFreqComboBox->setCurrentIndex(0); + + // 3 - whenChargerSleep + if (checkconfig("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/3-whenChargerSleep") == true) { + whenChargerSleepBool = true; + ui->hWhenChargerSleepBtn->click(); + } else { + whenChargerSleepBool = false; + } + + // 4 - chargerWakeUp + if (checkconfig("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/4-chargerWakeUp") == true) { + chargerWakeUpBool = true; + ui->hChargerWakeUpBtn->click(); + } else { + chargerWakeUpBool = false; + } + + // 5 - wifiReconnect + if (checkconfig("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/5-wifiReconnect") == true) { + ui->wifiReconnectBtn->click(); + wifiReconnectBool = true; + } else { + wifiReconnectBool = false; + } + + // 6 - ledUsage + if (checkconfig("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/6-ledUsage") == true) { + ui->ledUsageBtn->click(); + ledUsageBool = true; + } else { + ledUsageBool = false; + } + + // 7 - idleSleep + QString idleSleepString = readFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/7-idleSleep"); + idleSleepInt = idleSleepString.replace("\n", "").toInt(); + convertIdleSleepInt(); + + // 8 - customCase + if (checkconfig("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/8-customCase") == true) { + ui->hCustomCaseBtn->click(); + customCaseBool = true; + } else { + customCaseBool = false; + } + + // 9 - deepSleep + if (checkconfig("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/9-deepSleep") == true) { + ui->deepSleepBtn->click(); + deepSleepBool = true; + } else { + deepSleepBool = false; + } +} + +PowerDaemonSettingsWidget::~PowerDaemonSettingsWidget() { + delete ui; +} + +void PowerDaemonSettingsWidget::on_CBSIncreaseBtn_clicked() { + if (cinematicBrightnessInt < 500) { + cinematicBrightnessInt = cinematicBrightnessInt + 1; + convertCinematicInt(); + } +} + +void PowerDaemonSettingsWidget::on_CBSDecreaseBtn_clicked() { + if (cinematicBrightnessInt != 0) { + cinematicBrightnessInt = cinematicBrightnessInt - 1; + convertCinematicInt(); + } +} + +void PowerDaemonSettingsWidget::on_exitBtn_clicked() { + // Save all to files + // 1 - cinematicBrightnessdelayMs + writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/1-cinematicBrightnessDelayMs", QString::number(cinematicBrightnessInt)); + // 2 - cpuGovernor + writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/2-cpuGovernor", ui->hCpuFreqComboBox->currentText()); + // 3 - whenChargerSleep + writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/3-whenChargerSleep", QVariant(whenChargerSleepBool).toString()); + // 4 - chargerWakeUp + writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/4-chargerWakeUp", QVariant(chargerWakeUpBool).toString()); + // 5 - wifiReconnect + writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/5-wifiReconnect", QVariant(wifiReconnectBool).toString()); + // 6 - ledUsage + writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/6-ledUsage", QVariant(ledUsageBool).toString()); + // 7 - idleSleep + writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/7-idleSleep", QString::number(idleSleepInt)); + // 8 - customCase + writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/8-customCase", QVariant(customCaseBool).toString()); + // 9 - deepSleep + writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/9-deepSleep", QVariant(deepSleepBool).toString()); + + // Notify power daemon of configuration update + writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/updateConfig", "true"); + + PowerDaemonSettingsWidget::close(); +} + +void PowerDaemonSettingsWidget::on_expBtn_clicked() { + // TODO: Implement additional warning + ui->hLabel_3->show(); + ui->hCpuFreqComboBox->show(); + + ui->hWhenChargerSleepBtn->show(); + ui->hChargerWakeUpBtn->show(); + ui->hCustomCaseBtn->show(); + + ui->expBtn->hide(); +} + +void PowerDaemonSettingsWidget::on_hWhenChargerSleepBtn_clicked(bool checked) { + QString settingString = "suspend when charging"; + if (checked == true) { + logEnabled(settingString, className); + whenChargerSleepBool = true; + } else { + logDisabled(settingString, className); + whenChargerSleepBool = false; + } +} + +void PowerDaemonSettingsWidget::on_hChargerWakeUpBtn_clicked(bool checked) { + QString settingString = "ignore charger wake-up events"; + if (checked == true) { + logEnabled(settingString, className); + chargerWakeUpBool = true; + } else { + logDisabled(settingString, className); + chargerWakeUpBool = false; + } +} + +void PowerDaemonSettingsWidget::on_wifiReconnectBtn_clicked(bool checked) { + QString settingString = "Wi-Fi reconnection on wake-up"; + if (checked == true) { + logEnabled(settingString, className); + wifiReconnectBool = true; + } else { + logDisabled(settingString, className); + wifiReconnectBool = false; + } +} + +void PowerDaemonSettingsWidget::on_ledUsageBtn_clicked(bool checked) { + QString settingString = "use LED"; + if (checked == true) { + logEnabled(settingString, className); + ledUsageBool = true; + } else { + logDisabled(settingString, className); + ledUsageBool = false; + } +} + +void PowerDaemonSettingsWidget::on_idleSleepIncreaseBtn_clicked() { + if (idleSleepInt >= 15) { + idleSleepInt = idleSleepInt + 1; + } else { + idleSleepInt = 15; + } + convertIdleSleepInt(); +} + +void PowerDaemonSettingsWidget::on_idleSleepDecreaseBtn_clicked() { + if (idleSleepInt >= 15) { + idleSleepInt = idleSleepInt - 1; + if (idleSleepInt == 14) { + idleSleepInt = 0; + } + } else { + idleSleepInt = 0; + } + + convertIdleSleepInt(); +} + +void PowerDaemonSettingsWidget::convertIdleSleepInt() { + int copiedIdleSleepInt = idleSleepInt; + int minutes = 0; + int seconds = 0; + if (copiedIdleSleepInt == 0) { + ui->idleSleepLabel->setText("Never"); + return; + } + while (copiedIdleSleepInt >= 60) { + minutes = minutes + 1; + copiedIdleSleepInt = copiedIdleSleepInt - 60; + } + seconds = copiedIdleSleepInt; + + QString text; + if (minutes != 0) { + text.append(QString::number(minutes) + "m"); + } + if (seconds != 0) { + text.append(" "); + text.append(QString::number(seconds) + "s"); + } + ui->idleSleepLabel->setText(text); +} + +void PowerDaemonSettingsWidget::on_hCustomCaseBtn_clicked(bool checked) { + QString settingString = "custom case"; + if (checked == true) { + logEnabled(settingString, className); + customCaseBool = true; + } else { + logDisabled(settingString, className); + customCaseBool = false; + } +} + +void PowerDaemonSettingsWidget::on_deepSleepBtn_clicked(bool checked) { + QString settingString = "deep sleep"; + if (checked == true) { + logEnabled(settingString, className); + deepSleepBool = true; + } else { + logDisabled(settingString, className); + deepSleepBool = false; + } +} + +void PowerDaemonSettingsWidget::convertCinematicInt() { + QString text = QString::number(cinematicBrightnessInt); + // To avoid moving other widgets when the value changes + text.append(" ms"); + ui->CBSLabel->setText(text); +} + +void PowerDaemonSettingsWidget::on_idleSleepIncreaseMBtn_clicked() { + if (idleSleepInt >= 15) { + idleSleepInt = idleSleepInt + 60; + } else { + idleSleepInt = 60; + } + convertIdleSleepInt(); +} + +void PowerDaemonSettingsWidget::on_idleSleepDecreaseMBtn_clicked() { + if (idleSleepInt >= 60) { + idleSleepInt = idleSleepInt - 60; + if (idleSleepInt < 14) { + idleSleepInt = 0; + } + } else { + idleSleepInt = 0; + } + + convertIdleSleepInt(); +} diff --git a/src/settings/powerdaemonsettings.h b/src/ui/settings/powerdaemonsettings.h similarity index 84% rename from src/settings/powerdaemonsettings.h rename to src/ui/settings/powerdaemonsettings.h index e95ccff..d759885 100644 --- a/src/settings/powerdaemonsettings.h +++ b/src/ui/settings/powerdaemonsettings.h @@ -4,17 +4,17 @@ #include namespace Ui { -class powerDaemonSettings; +class PowerDaemonSettingsWidget; } -class powerDaemonSettings : public QWidget +class PowerDaemonSettingsWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit powerDaemonSettings(QWidget *parent = nullptr); - ~powerDaemonSettings(); + explicit PowerDaemonSettingsWidget(QWidget *parent = nullptr); + ~PowerDaemonSettingsWidget(); int cinematicBrightnessMs; private slots: @@ -39,7 +39,7 @@ private slots: void on_idleSleepDecreaseMBtn_clicked(); private: - Ui::powerDaemonSettings * ui; + Ui::PowerDaemonSettingsWidget * ui; bool whenChargerSleepBool; bool chargerWakeUpBool; bool wifiReconnectBool; diff --git a/src/settings/powerdaemonsettings.ui b/src/ui/settings/powerdaemonsettings.ui similarity index 99% rename from src/settings/powerdaemonsettings.ui rename to src/ui/settings/powerdaemonsettings.ui index b682d4b..04b2758 100644 --- a/src/settings/powerdaemonsettings.ui +++ b/src/ui/settings/powerdaemonsettings.ui @@ -1,7 +1,7 @@ - powerDaemonSettings - + PowerDaemonSettingsWidget + 0 diff --git a/src/ui/settings/settings.cpp b/src/ui/settings/settings.cpp new file mode 100644 index 0000000..99c2170 --- /dev/null +++ b/src/ui/settings/settings.cpp @@ -0,0 +1,944 @@ +#include "settings.h" +#include "device.h" +#include "functions.h" +#include "mainwindow.h" +#include "ui.h" +#include "ui_mainwindow.h" +#include "ui_settings.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +SettingsWidget::SettingsWidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::SettingsWidget) { + Device *device = Device::getSingleton(); + + ui->setupUi(this); + SettingsWidget::setFont(QFont("u001")); + ui->comboBox->setFont(QFont("u001")); + ui->tzComboBox->setFont(QFont("u001")); + ui->aboutBtn->setFont(QFont("u001")); + ui->headerBtn->setFont(QFont("Inter")); + ui->headerLabel->setFont(QFont("Chivo")); + ui->readingSettingsBtn->setFont(QFont("Chivo")); + ui->homeSettingsBtn->setFont(QFont("Chivo")); + ui->librarySettingsBtn->setFont(QFont("Chivo")); + ui->storageSettingsBtn->setFont(QFont("Chivo")); + ui->systemSettingsBtn->setFont(QFont("Chivo")); + ui->securitySettingsBtn->setFont(QFont("Chivo")); + ui->okBtn->setFont(QFont("Inter")); + + ui->setPasscodeBtn->setProperty("type", "borderless"); + ui->okBtn->setProperty("type", "borderless"); + ui->aboutBtn->setProperty("type", "borderless"); + ui->requestLeaseBtn->setProperty("type", "borderless"); + ui->usbmsBtn->setProperty("type", "borderless"); + ui->updateBtn->setProperty("type", "borderless"); + ui->resetBtn->setProperty("type", "borderless"); + ui->showSystemInfoBtn->setProperty("type", "borderless"); + ui->generateSystemReportBtn->setProperty("type", "borderless"); + ui->checkOtaUpdateBtn->setProperty("type", "borderless"); + ui->repackBtn->setProperty("type", "borderless"); + ui->exportHighlightsBtn->setProperty("type", "borderless"); + ui->label->setStyleSheet("font-size: 10.5pt; font-weight: bold"); + ui->okBtn->setStyleSheet("font-weight: bold"); + ui->aboutBtn->setStyleSheet("font-size: 9pt"); + ui->requestLeaseBtn->setStyleSheet("font-size: 9pt"); + ui->usbmsBtn->setStyleSheet("font-size: 9pt"); + ui->updateBtn->setStyleSheet("font-size: 9pt"); + ui->resetBtn->setStyleSheet("font-size: 9pt"); + ui->showSystemInfoBtn->setStyleSheet("font-size: 9pt"); + ui->generateSystemReportBtn->setStyleSheet("font-size: 9pt"); + ui->checkOtaUpdateBtn->setStyleSheet("font-size: 9pt"); + ui->comboBox->setStyleSheet("font-size: 9pt"); + ui->tzComboBox->setStyleSheet("font-size: 9pt"); + ui->setPasscodeBtn->setStyleSheet("font-size: 9pt"); + ui->repackBtn->setStyleSheet("font-size: 9pt"); + ui->exportHighlightsBtn->setStyleSheet("font-size: 9pt"); + + // Getting the screen's size + sW = QGuiApplication::screens()[0]->size().width(); + sH = QGuiApplication::screens()[0]->size().height(); + + // Defining what the default icon size will be + if (device->getScreenSize() == Device::ScreenSize::SMALL) { + homeIconWidth = sW / 18; + homeIconHeight = sW / 18; + } else { + homeIconWidth = sW / 20; + homeIconHeight = sW / 20; + } + + ui->headerStackedWidget->hide(); + + ui->headerBtn->setIcon(QIcon(":/resources/chevron-left.png")); + ui->headerBtn->setProperty("type", "borderless"); + ui->headerBtn->setStyleSheet("font-size: 9pt; font-weight: bold; padding: 15px"); + ui->headerLabel->setStyleSheet("padding: 15px"); + + ui->readingSettingsBtn->setText("\t\t\tReading"); + ui->readingSettingsBtn->setProperty("type", "borderless"); + ui->readingSettingsBtn->setStyleSheet("padding: 25px; Text-align: left"); + ui->readingSettingsBtn->setIcon(QIcon(":/resources/book.png")); + ui->readingSettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); + + ui->homeSettingsBtn->setText("\t\t\tHome"); + ui->homeSettingsBtn->setProperty("type", "borderless"); + ui->homeSettingsBtn->setStyleSheet("padding: 25px; Text-align:left"); + ui->homeSettingsBtn->setIcon(QIcon(":/resources/home.png")); + ui->homeSettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); + + ui->librarySettingsBtn->setText("\t\t\t Library"); + ui->librarySettingsBtn->setProperty("type", "borderless"); + ui->librarySettingsBtn->setStyleSheet("padding: 25px; Text-align:left"); + ui->librarySettingsBtn->setIcon(QIcon(":/resources/online-library.png")); + ui->storageSettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); + + ui->storageSettingsBtn->setText("\t\t\tStorage"); + ui->storageSettingsBtn->setProperty("type", "borderless"); + ui->storageSettingsBtn->setStyleSheet("padding: 25px; Text-align:left"); + ui->storageSettingsBtn->setIcon(QIcon(":/resources/usbms-inverted.png")); + ui->storageSettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); + + ui->systemSettingsBtn->setText("\t\t\tSystem"); + ui->systemSettingsBtn->setProperty("type", "borderless"); + ui->systemSettingsBtn->setStyleSheet("padding: 25px; Text-align:left"); + ui->systemSettingsBtn->setIcon(QIcon(":/resources/settings.png")); + ui->systemSettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); + + ui->securitySettingsBtn->setText("\t\t\tSecurity"); + ui->securitySettingsBtn->setProperty("type", "borderless"); + ui->securitySettingsBtn->setStyleSheet("padding: 25px; Text-align:left"); + ui->securitySettingsBtn->setIcon(QIcon(":/resources/lock.png")); + ui->securitySettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); + + ui->usbNetworkingCheckBox->hide(); + ui->requestLeaseBtn->hide(); + ui->usbmsBtn->hide(); + ui->label_4->hide(); + ui->label_6->hide(); + ui->updateBtn->hide(); + ui->updateLabel->hide(); + ui->enableLockscreenCheckBox->hide(); + ui->setPasscodeBtn->hide(); + ui->setPasscodeLabel->hide(); + + // Variables + defineDefaultPageSize(0); + defineDefaultPageSize(1); + + // Settings tweaking + enabling specific features whether it's running on the provided integrated OS or Kobo firmware + if (checkconfig(".config/01-demo/config") == true) { + ui->demoCheckBox->click(); + } + if (checkconfig(".config/02-clock/config") == true) { + ui->clockCheckBox->click(); + } + if (checkconfig(".config/05-quote/config") == true) { + ui->quoteCheckBox->click(); + } + + if (device->supportsNightmode()) { + if (checkconfig(".config/10-dark_mode/config") == true) { + ui->darkModeCheckBox->click(); + } + } else { + ui->darkModeCheckBox->hide(); + ui->darkModeCheckBox->deleteLater(); + } + + // Words number + QString wordsNumberConfigStr = readFile(".config/07-words_number/config"); + if (wordsNumberConfigStr.isEmpty()) { + Device::ScreenSize size = device->getScreenSize(); + if (size == Device::ScreenSize::SMALL) { + wordsNumberSaved = 120; + } else if (size == Device::ScreenSize::VERY_LARGE) { + wordsNumberSaved = 250; + } else { + wordsNumberSaved = 175; + } + } else { + QString words_number = wordsNumberConfigStr; + wordsNumberSaved = wordsNumberConfigStr.toInt(); + } + ui->wordsNumberValueLabel->setText(QString::number(wordsNumberSaved)); + + // ePUB page size + if (checkconfig(".config/13-epub_page_size/set") == true) { + QString epubPageWidthSettingStr = readFile(".config/13-epub_page_size/width"); + if (!epubPageWidthSettingStr.isEmpty()) { + QString pageWidth = epubPageWidthSettingStr; + ui->pageSizeWidthLabel->setText(pageWidth); + pageSizeWidthSaved = pageWidth.toInt(); + } else { + // Failsafe: setting default + ui->pageSizeWidthLabel->setText(QString::number(defaultEpubPageWidth)); + pageSizeWidthSaved = defaultEpubPageWidth; + } + QString epubPageHeightSettingStr = readFile(".config/13-epub_page_size/height"); + if (!epubPageHeightSettingStr.isEmpty()) { + QString pageHeight = epubPageHeightSettingStr; + ui->pageSizeHeightLabel->setText(pageHeight); + pageSizeHeightSaved = pageHeight.toInt(); + } else { + // Failsafe: setting default + ui->pageSizeHeightLabel->setText(QString::number(defaultEpubPageHeight)); + pageSizeHeightSaved = defaultEpubPageHeight; + } + } else { + ui->pageSizeWidthLabel->setText(QString::number(defaultEpubPageWidth)); + ui->pageSizeHeightLabel->setText(QString::number(defaultEpubPageHeight)); + pageSizeHeightSaved = defaultEpubPageHeight; + pageSizeWidthSaved = defaultEpubPageWidth; + } + + // QTextEdit scroll bar in Reader framework + if (checkconfig(".config/14-reader_scrollbar/config") == true) { + ui->readerScrollBarCheckBox->click(); + } + + // Sticky menubar + if (checkconfig(".config/11-menubar/sticky") == true) { + ui->menuBarCheckBox->click(); + } + + // Refresh + QString refreshSettingStr = readFile(".config/04-book/refresh"); + if (refreshSettingStr.isEmpty()) { + // Set default option, 3 + writeFile(".config/04-book/refresh", "3"); + ui->comboBox->setCurrentText("3 pages"); + } else { + int refreshInt = refreshSettingStr.toInt(); + if (refreshInt == -1) { + ui->comboBox->setCurrentText("Never refresh"); + } + if (refreshInt == 0) { + ui->comboBox->setCurrentText("Every page"); + } + if (refreshInt == 1) { + ui->comboBox->setCurrentText("1 page"); + } + if (refreshInt == 2) { + ui->comboBox->setCurrentText("2 pages"); + } + if (refreshInt == 3) { + ui->comboBox->setCurrentText("3 pages"); + } + if (refreshInt == 4) { + ui->comboBox->setCurrentText("4 pages"); + } + if (refreshInt == 5) { + ui->comboBox->setCurrentText("5 pages"); + } + if (refreshInt == 6) { + ui->comboBox->setCurrentText("6 pages"); + } + } + + // Lock screen + if (checkconfig(".config/12-lockscreen/config") == true) { + ui->enableLockscreenCheckBox->click(); + } + + // Global reading settings + if (checkconfig(".config/16-global_reading_settings/config") == true) { + ui->globalReadingSettingsCheckBox->click(); + } + + // Encrypted storage + if (checkconfig(".config/18-encrypted_storage/status") == true) { + ui->enableEncryptedStorageCheckBox->click(); + } else { + // Next interaction will be by the user + enableEncryptedStorageUserChange = true; + } + if (getEncFSStatus() == false) { + ui->repackLabel->hide(); + ui->repackBtn->hide(); + } + + // Timezone + ui->tzComboBox->addItems(QStringList(readFile(":/resources/tzlist").split("\n", Qt::SkipEmptyParts))); + timezone_not_user_change = true; + if (readFile(".config/19-timezone/config-name").isEmpty()) { + ui->tzComboBox->setCurrentText("UTC"); + } else { + ui->tzComboBox->setCurrentText(readFile(".config/19-timezone/config-name")); + } + + // Local library folders support + if (checkconfig(".config/21-local_library/folders") == true) { + ui->localLibraryShowFoldersCheckBox->click(); + } + + // USB show dialog + if (checkconfig(".config/22-usb/show-dialog") == true) { + ui->usbmsDialogBox->click(); + } + + // Automatic updates + if (checkconfig(".config/23-updates/check-updates") == true) { + ui->autoCheckUpdatesBox->click(); + } + + // 'Export highlights' button + if (!QFile::exists(global::localLibrary::highlightsDatabasePath) or readFile(global::localLibrary::highlightsDatabasePath).isEmpty()) { + ui->exportHighlightsBtn->setEnabled(false); + } + + if (readFile(".config/12-lockscreen/background") == "blank") { + ui->lockscreenBackgroundComboBox->setCurrentIndex(0); + } else if (readFile(".config/12-lockscreen/background") == "screenSaver") { + ui->lockscreenBackgroundComboBox->setCurrentIndex(1); + } else if (readFile(".config/12-lockscreen/background") == "background") { + ui->lockscreenBackgroundComboBox->setCurrentIndex(2); + } + + if (checkconfig("/opt/inkbox_genuine") == true) { + // Enforcing security policy if the user has not rooted the device + if (checkconfig("/external_root/opt/root/rooted") == true) { + ui->usbNetworkingCheckBox->show(); + if (checkconfig("/external_root/boot/flags/USBNET_ENABLE")) { + ui->usbNetworkingCheckBox->click(); + } + ui->requestLeaseBtn->show(); + ui->label_4->show(); + } else { + ui->usbNetworkingCheckBox->hide(); + ui->requestLeaseBtn->hide(); + ui->label_4->hide(); + } + ui->enableLockscreenCheckBox->show(); + ui->setPasscodeBtn->show(); + ui->setPasscodeLabel->show(); + ui->usbmsBtn->show(); + ui->label_6->show(); + } else { + ui->label_8->setText("Reset InkBox"); + } + + if (!device->supportsWifi()) { + ui->checkOtaUpdateLabel->hide(); + ui->checkOtaUpdateBtn->hide(); + ui->checkOtaUpdateLabel->deleteLater(); + ui->checkOtaUpdateBtn->deleteLater(); + ui->checkOtaUpdateGridLayout->deleteLater(); + } + + UI::applyStyle(*this, "eink"); +} + +SettingsWidget::~SettingsWidget() { + delete ui; +} + +void SettingsWidget::on_okBtn_clicked() { + saveDeferredSettings(); + + // Prevent potential unknown damage launching via shell script this could do + if (launch_sh == true) { + if (ui_enable_changed == true) { + ui_enable_changed = false; + global::settings::settingsRebootDialog = true; + generalDialogWindow = new GeneralDialog(); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + } else { + QProcess process; + process.startDetached("inkbox.sh", QStringList()); + qApp->quit(); + } + } else { + QProcess process; + process.startDetached("inkbox", QStringList()); + qApp->quit(); + } +} + +void SettingsWidget::saveDeferredSettings() { + // Save things + writeFile(".config/07-words_number/config", QString::number(wordsNumberSaved)); + log("Set text files words number to " + QString::number(wordsNumberSaved), className); + + writeFile(".config/13-epub_page_size/width", QString::number(pageSizeWidthSaved)); + writeFile(".config/13-epub_page_size/set", "true"); + + writeFile(".config/13-epub_page_size/height", QString::number(pageSizeHeightSaved)); + writeFile(".config/13-epub_page_size/set", "true"); + + // Notify power daemon of a potential configuration update + writeFile("/mnt/onboard/.adds/inkbox/.config/20-sleep_daemon/updateConfig", "true"); +} + +void SettingsWidget::on_aboutBtn_clicked() { + log("Showing About message box", className); + if (checkconfig("/opt/inkbox_genuine") == true) { + QString aboutmsg = "InkBox is an open-source, Qt-based eBook reader. It aims to bring you the latest Qt features while being also fast and responsive."; + aboutmsg.prepend(""); + aboutmsg.append("

InkBox "); + aboutmsg.append(readFile("/external_root/opt/isa/version")); + aboutmsg.append("
"); + QMessageBox::information(this, tr("Information"), aboutmsg); + } else { + QMessageBox::information(this, tr("About"), tr("InkBox is an open-source Qt-based eBook reader. It aims to bring you the latest Qt features while being also fast and responsive.")); + } +} + +void SettingsWidget::on_demoCheckBox_toggled(bool checked) { + QString settingString = "change MainWindow label demo"; + // Write to config file + if (checked == true) { + logEnabled(settingString, className); + checked_box = true; + writeconfig(".config/01-demo/config", "InkboxChangeLabel="); + } else { + logDisabled(settingString, className); + checked_box = false; + writeconfig(".config/01-demo/config", "InkboxChangeLabel="); + } +} + +void SettingsWidget::on_clockCheckBox_toggled(bool checked) { + QString settingString = "clock with seconds"; + // Write to config file + if (checked == true) { + logEnabled(settingString, className); + checked_box = true; + writeconfig(".config/02-clock/config", "ClockShowSeconds="); + } else { + logDisabled(settingString, className); + checked_box = false; + writeconfig(".config/02-clock/config", "ClockShowSeconds="); + } +} + +void SettingsWidget::on_quoteCheckBox_toggled(bool checked) { + QString settingString = "disable show quotes"; + if (checked == true) { + logEnabled(settingString, className); + checked_box = true; + writeconfig(".config/05-quote/config", "DisableQuote="); + } else { + logDisabled(settingString, className); + checked_box = false; + writeconfig(".config/05-quote/config", "DisableQuote="); + } +} + +void SettingsWidget::on_requestLeaseBtn_clicked() { + log("Requesting DHCP lease", className); + QString prog("chroot"); + QStringList args; + args << "/external_root" + << "/usr/sbin/dhclient"; + QProcess *proc = new QProcess(); + proc->start(prog, args); + proc->waitForFinished(); + proc->deleteLater(); +} + +void SettingsWidget::on_usbmsBtn_clicked() { + usbms_launch(); +} + +void SettingsWidget::on_updateBtn_clicked() { + log("'Update' button clicked", className); + writeFile("/mnt/onboard/onboard/.inkbox/can_really_update", "true\n"); + writeFile("/external_root/opt/update/will_update", "true\n"); + writeFile("/external_root/boot/flags/WILL_UPDATE", "true\n"); + QString prog("/sbin/reboot"); + QStringList args; + QProcess *proc = new QProcess(); + proc->start(prog, args); + proc->waitForFinished(); + proc->deleteLater(); +} + +void SettingsWidget::on_darkModeCheckBox_toggled(bool checked) { + QString settingString = "dark mode"; + if (checked == true) { + logEnabled(settingString, className); + writeFile(".config/10-dark_mode/config", "true"); + writeFile("/tmp/invertScreen", "y"); + } else { + logDisabled(settingString, className); + writeFile(".config/10-dark_mode/config", "false"); + writeFile("/tmp/invertScreen", "n"); + } +} + +void SettingsWidget::on_menuBarCheckBox_toggled(bool checked) { + QString settingString = "sticky menu bar"; + if (checked == true) { + logEnabled(settingString, className); + checked_box = true; + writeconfig(".config/11-menubar/sticky", "StickyMenuBar="); + } else { + logDisabled(settingString, className); + checked_box = false; + writeconfig(".config/11-menubar/sticky", "StickyMenuBar="); + } +} + +void SettingsWidget::on_comboBox_currentIndexChanged(const QString &arg1) { + log("Setting page refresh setting to " + arg1, className); + if (arg1 == "Every page") { + writeFile(".config/04-book/refresh", "0"); + } + if (arg1 == "1 page") { + writeFile(".config/04-book/refresh", "1"); + } + if (arg1 == "2 pages") { + writeFile(".config/04-book/refresh", "2"); + } + if (arg1 == "3 pages") { + writeFile(".config/04-book/refresh", "3"); + } + if (arg1 == "4 pages") { + writeFile(".config/04-book/refresh", "4"); + } + if (arg1 == "5 pages") { + writeFile(".config/04-book/refresh", "5"); + } + if (arg1 == "6 pages") { + writeFile(".config/04-book/refresh", "6"); + } + if (arg1 == "Never refresh") { + writeFile(".config/04-book/refresh", "-1"); + } +} + +void SettingsWidget::on_resetBtn_clicked() { + log("'Reset' button clicked", className); + // We write to a temporary file to show a "Reset" prompt + writeFile("/inkbox/resetDialog", "true"); + + // We setup the dialog + log("Showing reset dialog", className); + generalDialogWindow = new GeneralDialog(); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); +} + +void SettingsWidget::on_setPasscodeBtn_clicked() { + log("'Set passcode' button clicked", className); + log("Launching lockscreen binary", className); + saveDeferredSettings(); + writeFile("/tmp/setPasscode", "true"); + QProcess process; + process.startDetached("lockscreen", QStringList()); + qApp->quit(); +} + +void SettingsWidget::on_enableLockscreenCheckBox_toggled(bool checked) { + QString settingString = "lockscreen"; + if (checked == true) { + logEnabled(settingString, className); + writeFile(".config/12-lockscreen/config", "true"); + // Launching passcode setup wizard if none seems to be set at the moment + if (!(QFile::exists(".config/12-lockscreen/passcode") && QFile::exists(".config/12-lockscreen/salt"))) { + ui->setPasscodeBtn->click(); + } + } else { + logDisabled(settingString, className); + writeFile(".config/12-lockscreen/config", "false"); + } +} + +void SettingsWidget::on_showSystemInfoBtn_clicked() { + log("'Show system info' button clicked", className); + global::usbms::usbmsDialog = false; + + Device::SysInfo info = Device::getSingleton()->getSystemInfo(); + + QString text; + text = "InkBox OS version "; + text.append(readFile("/external_root/opt/isa/version")); + text.append("
Copyright © 2021-2024 Nicolas Mailloux and contributors
Special thanks to: Szybet, NiLuJe, akemnade, Rain92, Ansraer (GitHub)"); + text.append("
GUI Git commit: "); + text.append(info.inkGitVersion); + text.append("
Device UID: "); + text.append(info.uid); + text.append("
Kernel version: "); + text.append(info.kernelVersion); + text.append("
Kernel build: "); + text.append(info.kernelBuild); + text.append("
Kernel commit: "); + text.append(info.kernelCommit); + text.append("
Device: "); + QString device = Device::getSingleton()->getID(); + text.append(device); + text.append("
IP address: "); + text.append(info.ipAddress); + + global::text::textBrowserContents = text; + global::text::textBrowserDialog = true; + + // Show a system info dialog + log("Showing system info dialog", className); + generalDialogWindow = new GeneralDialog(); + generalDialogWindow->yIncrease = determineYIncrease(); + generalDialogWindow->increaseSize(); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); +} + +void SettingsWidget::on_readerScrollBarCheckBox_toggled(bool checked) { + QString settingString = "scrollbar display if necessary"; + if (checked == true) { + logEnabled(settingString, className); + writeFile(".config/14-reader_scrollbar/config", "true"); + } else { + logDisabled(settingString, className); + writeFile(".config/14-reader_scrollbar/config", "false"); + } +} + +void SettingsWidget::brightnessDown() { + UI::transitionBrightness(0); +} + +void SettingsWidget::on_globalReadingSettingsCheckBox_toggled(bool checked) { + QString settingString = "global reading settings"; + if (checked == true) { + logEnabled(settingString, className); + checked_box = true; + writeconfig(".config/16-global_reading_settings/config", "GlobalReadingSettings="); + } else { + logDisabled(settingString, className); + checked_box = false; + writeconfig(".config/16-global_reading_settings/config", "GlobalReadingSettings="); + } +} + +void SettingsWidget::on_checkOtaUpdateBtn_clicked() { + log("'Check for OTA update' button clicked", className); + if (testPing() == 0) { + launchOtaUpdater(); + } else { + emit showToast("Wi-Fi connection error"); + } +} + +void SettingsWidget::openUpdateDialog() { + log("Showing update dialog", className); + global::mainwindow::updateDialog = true; + // Write to a temporary file to show an "Update" prompt + writeFile("/inkbox/updateDialog", "true"); + + // Show the dialog + generalDialogWindow = new GeneralDialog(this); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + connect(generalDialogWindow, SIGNAL(showToast(QString)), SLOT(showToastNative(QString))); + connect(generalDialogWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToastNative())); + QApplication::processEvents(); +} + +void SettingsWidget::launchOtaUpdater() { + global::toast::modalToast = true; + global::toast::indefiniteToast = true; + emit showToast("Checking for updates"); + otaManagerWindow = new OTAUpdateManagerWidget(this); + connect(otaManagerWindow, SIGNAL(canOtaUpdate(bool)), SLOT(openUpdateDialogOTA(bool))); + otaManagerWindow->setAttribute(Qt::WA_DeleteOnClose); +} + +void SettingsWidget::openUpdateDialogOTA(bool open) { + emit closeIndefiniteToast(); + if (open == true) { + global::otaUpdate::isUpdateOta = true; + openUpdateDialog(); + } else { + emit showToast("No update available"); + } +} + +void SettingsWidget::showToastNative(QString messageToDisplay) { + emit showToast(messageToDisplay); +} + +void SettingsWidget::closeIndefiniteToastNative() { + emit closeIndefiniteToast(); +} + +void SettingsWidget::usbms_launch() { + log("Showing USBMS splash", className); + global::usbms::launchUsbms = true; + + usbmsWindow = new USBMSSplashWidget(); + usbmsWindow->setAttribute(Qt::WA_DeleteOnClose); + usbmsWindow->setGeometry(QRect(QPoint(0, 0), screen()->geometry().size())); + usbmsWindow->show(); +} + +void SettingsWidget::quit_restart() { + // If existing, cleaning bookconfig_mount mountpoint + writeFile("/opt/ibxd", "bookconfig_unmount\n"); + + // Restarting InkBox + QProcess process; + process.startDetached("inkbox", QStringList()); + qApp->quit(); +} + +void SettingsWidget::on_enableEncryptedStorageCheckBox_toggled(bool checked) { + QString settingString = "encrypted storage"; + if (checked == true) { + if (enableEncryptedStorageUserChange == true) { + logEnabled(settingString, className); + setDefaultWorkDir(); + writeFile(".config/18-encrypted_storage/initial_setup_done", "false"); + writeFile(".config/18-encrypted_storage/status", "true"); + if (QFile::exists(".config/18-encrypted_storage/storage_list")) { + QFile::remove(".config/18-encrypted_storage/storage_list"); + } + global::settings::settingsRebootDialog = true; + global::encfs::enableStorageEncryptionDialog = true; + generalDialogWindow = new GeneralDialog(this); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + } else { + enableEncryptedStorageUserChange = true; + } + } else { + logDisabled(settingString, className); + global::encfs::disableStorageEncryptionDialog = true; + generalDialogWindow = new GeneralDialog(this); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + connect(generalDialogWindow, SIGNAL(cancelDisableStorageEncryption()), SLOT(cancelDisableStorageEncryption())); + connect(generalDialogWindow, SIGNAL(disableStorageEncryption()), SLOT(disableStorageEncryption())); + } +} + +void SettingsWidget::disableStorageEncryption() { + log("Disabling encrypted storage", className); + setDefaultWorkDir(); + writeFile("/external_root/run/encfs_stop_cleanup", "true"); + writeFile("/opt/ibxd", "encfs_stop\n"); + QThread::msleep(5000); + + writeFile(".config/18-encrypted_storage/status", "false"); + QFile::remove(".config/18-encrypted_storage/initial_setup_done"); + QFile::remove(".config/18-encrypted_storage/storage_list"); + QFile::remove("/mnt/onboard/onboard/data.encfs"); + + QDir dumpDir("/mnt/onboard/onboard/encfs-dropbox"); + dumpDir.removeRecursively(); + QDir decDir("/mnt/onboard/onboard/encfs-decrypted"); + decDir.removeRecursively(); + + global::settings::settingsRebootDialog = true; + generalDialogWindow = new GeneralDialog(this); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); +} + +void SettingsWidget::cancelDisableStorageEncryption() { + enableEncryptedStorageUserChange = false; + ui->enableEncryptedStorageCheckBox->click(); +} + +void SettingsWidget::on_repackBtn_clicked() { + log("'Repack encrypted storage' button clicked", className); + QDir dir("/mnt/onboard/onboard/encfs-dropbox"); + if (dir.isEmpty()) { + log("Showing encrypted storage repack error dialog ('encfs-dropbox' directory is empty)", className); + global::encfs::errorNoBooksInDropboxDialog = true; + generalDialogWindow = new GeneralDialog(this); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + } else { + log("Showing encrypted storage repack dialog", className); + writeFile("/external_root/run/encfs_repack", "true"); + quit_restart(); + } +} + +void SettingsWidget::on_generateSystemReportBtn_clicked() { + log("'Generate system report' button clicked", className); + log("Generating system report", className); + writeFile("/opt/ibxd", "generate_system_report\n"); + while (true) { + if (QFile::exists("/inkbox/systemReportDone")) { + if (checkconfig("/inkbox/systemReportDone") == true) { + QFile::remove(global::localLibrary::databasePath); + emit showToast("System report generated successfully"); + } else { + emit showToast("Error in generating system report"); + } + QFile::remove("/inkbox/systemReportDone"); + break; + } + } +} + +void SettingsWidget::on_tzComboBox_currentTextChanged(const QString &arg1) { + if (timezone_not_user_change == true) { + timezone_not_user_change = false; + } else { + log("Setting timezone to " + arg1, className); + setDefaultWorkDir(); + // Preventing unnecessary (e)MMC writes + if (readFile(".config/19-timezone/config-name") != arg1) { + QProcess::execute("ln", QStringList() << "-sf" + << "/usr/share/zoneinfo/" + arg1 << ".config/19-timezone/config"); + writeFile(".config/19-timezone/config-name", arg1); + writeFile("/opt/ibxd", "gui_remount_localtime\n"); + QThread::msleep(500); + } + } +} + +void SettingsWidget::on_exportHighlightsBtn_clicked() { + QJsonObject jsonObject = readHighlightsDatabase(); + writeFile("/mnt/onboard/onboard/highlights-" + QDateTime::currentDateTime().toString("dd-MM-yy_hh.mm.ss") + ".json", QJsonDocument(jsonObject).toJson()); + showToast("Highlights exported successfully"); +} + +void SettingsWidget::on_wordsNumberIncBtn_clicked() { + wordsNumberSaved = wordsNumberSaved + 5; + ui->wordsNumberValueLabel->setText(QString::number(wordsNumberSaved)); +} + +void SettingsWidget::on_wordsNumberDecBtn_clicked() { + if (wordsNumberSaved > 10) { + wordsNumberSaved = wordsNumberSaved - 5; + ui->wordsNumberValueLabel->setText(QString::number(wordsNumberSaved)); + } +} + +void SettingsWidget::on_pageSizeHeightDecBtn_clicked() { + if (pageSizeHeightSaved > 100) { + pageSizeHeightSaved = pageSizeHeightSaved - 5; + ui->pageSizeHeightLabel->setText(QString::number(pageSizeHeightSaved)); + } +} + +void SettingsWidget::on_pageSizeHeightIncBtn_clicked() { + pageSizeHeightSaved = pageSizeHeightSaved + 5; + ui->pageSizeHeightLabel->setText(QString::number(pageSizeHeightSaved)); +} + +void SettingsWidget::on_pageSizeWidthDecBtn_clicked() { + if (pageSizeWidthSaved > 100) { + pageSizeWidthSaved = pageSizeWidthSaved - 5; + ui->pageSizeWidthLabel->setText(QString::number(pageSizeWidthSaved)); + } +} + +void SettingsWidget::on_pageSizeWidthIncBtn_clicked() { + pageSizeWidthSaved = pageSizeWidthSaved + 5; + ui->pageSizeWidthLabel->setText(QString::number(pageSizeWidthSaved)); +} + +void SettingsWidget::on_localLibraryShowFoldersCheckBox_toggled(bool checked) { + QString settingString = "local library folders support"; + if (checked == true) { + logEnabled(settingString, className); + checked_box = true; + writeconfig(".config/21-local_library/folders", "Folders="); + } else { + logDisabled(settingString, className); + checked_box = false; + writeconfig(".config/21-local_library/folders", "Folders="); + } +} + +void SettingsWidget::on_usbmsDialogBox_clicked(bool checked) { + QString settingString = "USB Mass Storage dialog display"; + if (checked == true) { + logEnabled(settingString, className); + writeFile(".config/22-usb/show-dialog", "true"); + } else { + logDisabled(settingString, className); + writeFile(".config/22-usb/show-dialog", "false"); + } +} + +void SettingsWidget::on_autoCheckUpdatesBox_clicked(bool checked) { + QString settingString = "automatic updates checking"; + if (checked == true) { + logEnabled(settingString, className); + writeFile(".config/23-updates/check-updates", "true"); + } else { + logDisabled(settingString, className); + writeFile(".config/23-updates/check-updates", "false"); + } +} + +void SettingsWidget::on_lockscreenBackgroundComboBox_currentTextChanged(const QString &arg1) { + if (arg1 == "Blank") { + writeFile(".config/12-lockscreen/background", "blank"); + log("Set lockscreen background to 'blank'", className); + } else if (arg1 == "Screensaver picture") { + writeFile(".config/12-lockscreen/background", "screenSaver"); + log("Set lockscreen background to 'screenSaver'", className); + } else if (arg1 == "Device's screen") { + writeFile(".config/12-lockscreen/background", "background"); + log("Set lockscreen background to 'background'", className); + } +} + +void SettingsWidget::on_settingsStackedWidget_currentChanged(int arg1) { + if (ui->settingsStackedWidget->currentIndex() != 0) { + ui->headerLabel->setText(ui->settingsStackedWidget->currentWidget()->objectName()); + ui->headerStackedWidget->show(); + } else { + ui->headerStackedWidget->hide(); + } +} + +void SettingsWidget::on_readingSettingsBtn_clicked() { + log("'Reading settings' button clicked", className); + ui->settingsStackedWidget->setCurrentIndex(1); +} + +void SettingsWidget::on_homeSettingsBtn_clicked() { + log("'Home settings' button clicked", className); + ui->settingsStackedWidget->setCurrentIndex(2); +} + +void SettingsWidget::on_librarySettingsBtn_clicked() { + log("'Library settings' button clicked", className); + ui->settingsStackedWidget->setCurrentIndex(3); +} + +void SettingsWidget::on_storageSettingsBtn_clicked() { + log("'Storage settings' button clicked", className); + ui->settingsStackedWidget->setCurrentIndex(4); +} + +void SettingsWidget::on_systemSettingsBtn_clicked() { + log("'System settings' button clicked", className); + ui->settingsStackedWidget->setCurrentIndex(5); +} + +void SettingsWidget::on_securitySettingsBtn_clicked() { + log("'Security settings' button clicked", className); + ui->settingsStackedWidget->setCurrentIndex(6); +} + +void SettingsWidget::on_headerBtn_clicked() { + // "Home" button + log("'Home' button clicked", className); + ui->settingsStackedWidget->setCurrentIndex(0); +} + +void SettingsWidget::on_usbNetworkingCheckBox_toggled(bool checked) { + if (checked) { + writeFile("/external_root/boot/flags/USBNET_ENABLE", "true"); + writeFile("/opt/ibxd", "usbnet_start\n"); + } else { + writeFile("/external_root/boot/flags/USBNET_ENABLE", "false"); + writeFile("/opt/ibxd", "usbnet_stop\n"); + } +} diff --git a/src/settings/settings.h b/src/ui/settings/settings.h similarity index 91% rename from src/settings/settings.h rename to src/ui/settings/settings.h index 29744fc..b9ef3be 100644 --- a/src/settings/settings.h +++ b/src/ui/settings/settings.h @@ -11,10 +11,10 @@ using namespace std; namespace Ui { -class settings; +class SettingsWidget; } -class settings : public QWidget +class SettingsWidget : public QWidget { Q_OBJECT @@ -33,8 +33,8 @@ public: float homeIconWidth; float homeIconHeight; - explicit settings(QWidget *parent = nullptr); - ~settings(); + explicit SettingsWidget(QWidget *parent = nullptr); + ~SettingsWidget(); private slots: void on_demoCheckBox_toggled(bool); @@ -46,7 +46,6 @@ private slots: void on_usbmsBtn_clicked(); void on_updateBtn_clicked(); void on_darkModeCheckBox_toggled(bool checked); - void on_uiScalingSlider_valueChanged(int value); void on_menuBarCheckBox_toggled(bool checked); void on_comboBox_currentIndexChanged(const QString &arg1); void on_resetBtn_clicked(); @@ -97,10 +96,10 @@ signals: void closeIndefiniteToast(); private: - Ui::settings * ui; - usbmsSplash * usbmsWindow; - generalDialog * generalDialogWindow; - otaManager * otaManagerWindow; + Ui::SettingsWidget * ui; + USBMSSplashWidget * usbmsWindow; + GeneralDialog * generalDialogWindow; + OTAUpdateManagerWidget * otaManagerWindow; toast * toastWindow; int pageSizeHeightSaved; diff --git a/src/settings/settings.ui b/src/ui/settings/settings.ui similarity index 96% rename from src/settings/settings.ui rename to src/ui/settings/settings.ui index c1eec0c..2aff0eb 100644 --- a/src/settings/settings.ui +++ b/src/ui/settings/settings.ui @@ -1,7 +1,7 @@ - settings - + SettingsWidget + 0 @@ -64,6 +64,7 @@ + 75 true @@ -169,7 +170,7 @@ - 0 + 5 @@ -200,8 +201,8 @@ 0 0 - 461 - 636 + 457 + 622 @@ -363,6 +364,7 @@ + 75 true @@ -407,8 +409,8 @@ Save && Quit 0 0 - 423 - 738 + 235 + 258
@@ -690,6 +692,7 @@ Save && Quit + 75 true @@ -868,6 +871,7 @@ Save && Quit + 75 true @@ -937,7 +941,7 @@ Save && Quit 0 - + 0 @@ -969,6 +973,7 @@ Save && Quit + 75 true @@ -979,7 +984,54 @@ Save && Quit - + + + + 0 + + + + + + 75 + true + + + + Generate + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Generate system report + + + + + + + + + Enable USB networking + + + + 0 @@ -988,6 +1040,7 @@ Save && Quit + 75 true @@ -1018,7 +1071,80 @@ Save && Quit - + + + + 0 + + + + + + 75 + true + + + + Update + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Update InkBox + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + + + + + + + 0 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + Timezone + + + + + + Qt::Vertical @@ -1060,6 +1186,7 @@ Save && Quit + 75 true @@ -1070,56 +1197,27 @@ Save && Quit - - - - 0 + + + + + 0 + 0 + - - - - - true - - - - Update - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Update InkBox - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - - + + Automatically check for updates + +
- + Enable night mode - + 0 @@ -1128,6 +1226,7 @@ Save && Quit + 75 true @@ -1158,146 +1257,6 @@ Save && Quit - - - - 0 - - - - - - true - - - - 1 - - - - - - - 0 - - - 2 - - - 1 - - - 1 - - - 0 - - - Qt::Horizontal - - - - - - - UI scaling factor - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - - - - - - - 0 - - - - - - true - - - - Generate - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Generate system report - - - - - - - - - - 0 - 0 - - - - Automatically check for updates - - - - - - - 0 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - Timezone - - - - - - - - - Enable USB networking - - - @@ -1350,6 +1309,7 @@ Save && Quit + 75 true @@ -1472,6 +1432,7 @@ Save && Quit + 75 true diff --git a/src/ui/settings/settingschooser.cpp b/src/ui/settings/settingschooser.cpp new file mode 100644 index 0000000..48b03c5 --- /dev/null +++ b/src/ui/settings/settingschooser.cpp @@ -0,0 +1,101 @@ +#include "settingschooser.h" +#include "device.h" +#include "functions.h" +#include "powerdaemonsettings.h" +#include "ui.h" +#include "ui_settingschooser.h" + +#include +#include + +SettingsChooserWidget::SettingsChooserWidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::SettingsChooserWidget) { + ui->setupUi(this); + + // Stylesheet + UI::applyStyle(*this, "eink"); + + // UI tweaks + if (checkconfig("/opt/inkbox_kobox_support") == false) { + ui->koboxSettingsBtn->hide(); + ui->line_3->hide(); + } + + // Getting the screen's size + sW = QGuiApplication::screens()[0]->size().width(); + sH = QGuiApplication::screens()[0]->size().height(); + + Device::ScreenSize screenSize = Device::getSingleton()->getScreenSize(); + QString padding = ""; + if (screenSize == Device::ScreenSize::SMALL) { + homeIconWidth = sW / 18; + homeIconHeight = sW / 18; + padding = "18px"; + } else if (screenSize == Device::ScreenSize::MEDIUM) { + homeIconWidth = sW / 20; + homeIconHeight = sW / 20; + padding = "20px"; + } else if (screenSize == Device::ScreenSize::LARGE) { + homeIconWidth = sW / 20; + homeIconHeight = sW / 20; + padding = "25px"; + } else if (screenSize == Device::ScreenSize::VERY_LARGE) { + homeIconWidth = sW / 20; + homeIconHeight = sW / 20; + padding = "40px"; + } + ui->inkboxSettingsBtn->setStyleSheet("padding: " + padding + "; Text-align: left"); + ui->koboxSettingsBtn->setStyleSheet("padding: " + padding + "; Text-align: left"); + ui->powerSettingsBtn->setStyleSheet("padding: " + padding + "; Text-align: left"); + + ui->inkboxSettingsBtn->setProperty("type", "borderless"); + ui->koboxSettingsBtn->setProperty("type", "borderless"); + ui->powerSettingsBtn->setProperty("type", "borderless"); + + ui->inkboxSettingsBtn->setText("\t\t\tInkBox settings"); + ui->koboxSettingsBtn->setText("\t\t\tKoBox settings"); + ui->powerSettingsBtn->setText("\t\t\tPower settings"); + + ui->inkboxSettingsBtn->setIcon(QIcon(":/resources/settings.png")); + ui->inkboxSettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); + ui->koboxSettingsBtn->setIcon(QIcon(":/resources/X11.png")); + ui->koboxSettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); + ui->powerSettingsBtn->setIcon(QIcon(":/resources/power.png")); + ui->powerSettingsBtn->setIconSize(QSize(homeIconWidth, homeIconHeight)); +} + +SettingsChooserWidget::~SettingsChooserWidget() { + delete ui; +} + +void SettingsChooserWidget::on_inkboxSettingsBtn_clicked() { + log("Launching InkBox Settings", className); + settingsWindow = new SettingsWidget(); + settingsWindow->setAttribute(Qt::WA_DeleteOnClose); + connect(settingsWindow, SIGNAL(showToast(QString)), SLOT(showToastNative(QString))); + connect(settingsWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToastNative())); + settingsWindow->showFullScreen(); +} + +void SettingsChooserWidget::on_koboxSettingsBtn_clicked() { + log("Launching KoBox Settings", className); + koboxSettingsWindow = new KoboxSettingsWidget(); + koboxSettingsWindow->setAttribute(Qt::WA_DeleteOnClose); + koboxSettingsWindow->showFullScreen(); +} + +void SettingsChooserWidget::on_powerSettingsBtn_clicked() { + log("Launching Power Daemon Settings", className); + PowerDaemonSettingsWidget *powerSettingsWindow = new PowerDaemonSettingsWidget(); + powerSettingsWindow->setAttribute(Qt::WA_DeleteOnClose); + powerSettingsWindow->showFullScreen(); +} + +void SettingsChooserWidget::showToastNative(QString messageToDisplay) { + emit showToast(messageToDisplay); +} + +void SettingsChooserWidget::closeIndefiniteToastNative() { + emit closeIndefiniteToast(); +} diff --git a/src/settings/settingschooser.h b/src/ui/settings/settingschooser.h similarity index 69% rename from src/settings/settingschooser.h rename to src/ui/settings/settingschooser.h index 1d796d9..b0418a8 100644 --- a/src/settings/settingschooser.h +++ b/src/ui/settings/settingschooser.h @@ -7,17 +7,17 @@ #include "koboxsettings.h" namespace Ui { -class settingsChooser; +class SettingsChooserWidget; } -class settingsChooser : public QWidget +class SettingsChooserWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit settingsChooser(QWidget *parent = nullptr); - ~settingsChooser(); + explicit SettingsChooserWidget(QWidget *parent = nullptr); + ~SettingsChooserWidget(); float sW; float sH; @@ -36,9 +36,9 @@ signals: void closeIndefiniteToast(); private: - Ui::settingsChooser *ui; - settings *settingsWindow; - koboxSettings *koboxSettingsWindow; + Ui::SettingsChooserWidget *ui; + SettingsWidget *settingsWindow; + KoboxSettingsWidget *koboxSettingsWindow; }; #endif // SETTINGSCHOOSER_H diff --git a/src/settings/settingschooser.ui b/src/ui/settings/settingschooser.ui similarity index 97% rename from src/settings/settingschooser.ui rename to src/ui/settings/settingschooser.ui index ae17d72..6be6080 100644 --- a/src/settings/settingschooser.ui +++ b/src/ui/settings/settingschooser.ui @@ -1,7 +1,7 @@ - settingsChooser - + SettingsChooserWidget + 0 diff --git a/src/ui/splash/splashAlert.cpp b/src/ui/splash/splashAlert.cpp new file mode 100644 index 0000000..591a2ca --- /dev/null +++ b/src/ui/splash/splashAlert.cpp @@ -0,0 +1,161 @@ +#include "splashAlert.h" +#include "device.h" +#include "functions.h" +#include "ui.h" +#include "ui_splashAlert.h" + +#include +#include +#include +#include + +SplashAlertWidget::SplashAlertWidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::SplashAlertWidget) { + ui->setupUi(this); + ui->messageLabel->setFont(QFont("u001")); + + // Getting the screen's size + float sW = QGuiApplication::screens()[0]->size().width(); + float sH = QGuiApplication::screens()[0]->size().height(); + // Defining what the "Alert" icon size will be + float stdIconWidth = sW / 1.7; + float stdIconHeight = sH / 1.7; + + // General stylesheet + UI::applyStyle(*this, ":/resources/eink-dark.qss"); + + // Default icon in case none of the conditions below are met + QPixmap pixmap(":/resources/alert.png"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->alertIconLabel->setPixmap(scaledPixmap); + + // Checking if the update's signature is untrusted. The signature error will always take precedence over the downgrade one (c.f. update.sh script) + if (checkconfig("/external_root/boot/flags/ALERT_SIGN") == true) { + QPixmap pixmap(":/resources/alert.png"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->alertIconLabel->setPixmap(scaledPixmap); + + signatureError = true; + log("Displaying signature error alert splash", className); + ui->securityLabel->setText("Failed to update InkBox."); + ui->messageLabel->setText("The digital signature of the update is untrusted.\nFor security reasons, it cannot be installed."); + ui->stackedWidget->setCurrentIndex(1); + } + if (checkconfig("/external_root/boot/flags/ALERT_DOWNGRADE") == true) { + QPixmap pixmap(":/resources/alert.png"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->alertIconLabel->setPixmap(scaledPixmap); + + log("Displaying downgrade error alert splash", className); + downgradeError = true; + ui->securityLabel->setText("Failed to update InkBox."); + ui->messageLabel->setText("An error occured during the update process.\nThe update package's version is lower than the actual installed version."); + ui->stackedWidget->setCurrentIndex(1); + } + if (global::encfs::lockdown == true) { + ui->stackedWidget->setVisible(false); + ui->stackedWidget->deleteLater(); + QPixmap pixmap(":/resources/alert.png"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->alertIconLabel->setPixmap(scaledPixmap); + + ui->warningLabel->setText("Fatal error"); + ui->securityLabel->setText("Device lockdown"); + log(global::encfs::lockdownMessage, className); + QString message = "Due to multiple incorrect passphrase attempts, this device is locked down until\n" + global::encfs::unlockTime + "\nand won't boot."; + ui->messageLabel->setText(message); + poweroff(false); + QTimer::singleShot(1000, this, SLOT(quit())); + } + if (global::battery::showCriticalBatteryAlert == true) { + global::battery::showCriticalBatteryAlert = false; + ui->stackedWidget->setVisible(false); + ui->stackedWidget->deleteLater(); + + QPixmap pixmap(":/resources/battery_alert.png"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->alertIconLabel->setPixmap(scaledPixmap); + + log("Displaying critical battery alert splash", className); + criticalBattery = true; + ui->warningLabel->setText("Please charge your eReader."); + ui->securityLabel->setText("The battery's charge level is critical."); + ui->messageLabel->setText("To prevent damage, your device has been turned off.\nPlease consider charging it."); + // The Mini (N705) has a higher DPI and otherwise the text doesn't fit + Device::ScreenSize screenSize = Device::getSingleton()->getScreenSize(); + if (screenSize == Device::ScreenSize::SMALL) { + ui->warningLabel->setStyleSheet("QLabel { background-color : black; color : white; font-size: 14pt }"); + } else { + ui->warningLabel->setStyleSheet("QLabel { background-color : black; color : white; font-size: 16pt }"); + } + poweroff(false); + QTimer::singleShot(1000, this, SLOT(quit())); + } + + ui->messageLabel->setStyleSheet("QLabel { background-color : black; color : white; font-size: 10pt }"); + ui->securityLabel->setStyleSheet("QLabel { background-color : black; color : white; font-size: 11pt }"); + ui->continueBtn->setProperty("type", "borderless"); + ui->resetBtn->setProperty("type", "borderless"); + ui->continueBtn->setStyleSheet("padding: 20px"); + ui->resetBtn->setStyleSheet("padding: 20px"); + ui->continue2Btn->setProperty("type", "borderless"); + ui->continue2Btn->setStyleSheet("padding: 20px"); +} + +SplashAlertWidget::~SplashAlertWidget() { + delete ui; +} + +void SplashAlertWidget::on_continueBtn_clicked() { + // We continue anyway and re-set the ALERT flag + writeFile("/external_root/boot/flags/ALERT", "false\n"); + writeFile("/external_root/boot/flags/ALERT_SIGN", "false\n"); + updateReset(); + QProcess process; + process.startDetached("inkbox", QStringList()); + qApp->quit(); +} + +void SplashAlertWidget::on_resetBtn_clicked() { + // We set the DO_FACTORY_RESET flag and we restart the device + log("Factory reset requested; setting required flags", className); + writeFile("/external_root/boot/flags/DO_FACTORY_RESET", "true\n"); + writeFile("/external_root/boot/flags/DIAGS_BOOT", "true\n"); + QString reboot_prog("/sbin/reboot"); + QStringList reboot_args; + reboot_args << "no_splash"; + QProcess *reboot_proc = new QProcess(); + reboot_proc->start(reboot_prog, reboot_args); + reboot_proc->waitForFinished(); + reboot_proc->deleteLater(); +} + +void SplashAlertWidget::on_continue2Btn_clicked() { + // We continue anyway and re-set the ALERT flag + writeFile("/external_root/boot/flags/ALERT", "false\n"); + updateReset(); + + log("Restarting InkBox", className); + if (signatureError == true) { + writeFile("/external_root/boot/flags/ALERT_SIGN", "false\n"); + QProcess process; + process.startDetached("inkbox", QStringList()); + qApp->quit(); + } + if (downgradeError == true) { + writeFile("/external_root/boot/flags/ALERT_DOWNGRADE", "false\n"); + QProcess process; + process.startDetached("inkbox", QStringList()); + qApp->quit(); + } +} + +void SplashAlertWidget::updateReset() { + writeFile("/mnt/onboard/onboard/.inkbox/can_really_update", "false\n"); + writeFile("/mnt/onboard/onboard/.inkbox/can_update", "false\n"); +} + +void SplashAlertWidget::quit() { + qApp->quit(); +} diff --git a/src/splash/alert.h b/src/ui/splash/splashAlert.h similarity index 62% rename from src/splash/alert.h rename to src/ui/splash/splashAlert.h index 7885aa7..2b05aab 100644 --- a/src/splash/alert.h +++ b/src/ui/splash/splashAlert.h @@ -1,22 +1,22 @@ -#ifndef ALERT_H -#define ALERT_H +#ifndef SPLASHALERT_H +#define SPLASHALERT_H #include namespace Ui { -class alert; +class SplashAlertWidget; } using namespace std; -class alert : public QWidget +class SplashAlertWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit alert(QWidget *parent = nullptr); - ~alert(); + explicit SplashAlertWidget(QWidget *parent = nullptr); + ~SplashAlertWidget(); bool signatureError = false; bool downgradeError = false; bool criticalBattery = false; @@ -29,7 +29,7 @@ private slots: void quit(); private: - Ui::alert *ui; + Ui::SplashAlertWidget *ui; }; -#endif // ALERT_H +#endif // SPLASHALERT_H diff --git a/src/splash/alert.ui b/src/ui/splash/splashAlert.ui similarity index 98% rename from src/splash/alert.ui rename to src/ui/splash/splashAlert.ui index cb60c4e..96f323a 100644 --- a/src/splash/alert.ui +++ b/src/ui/splash/splashAlert.ui @@ -1,7 +1,7 @@ - alert - + SplashAlertWidget + 0 diff --git a/src/ui/splash/usbmsSplash.cpp b/src/ui/splash/usbmsSplash.cpp new file mode 100644 index 0000000..6d92ca6 --- /dev/null +++ b/src/ui/splash/usbmsSplash.cpp @@ -0,0 +1,273 @@ +#include "usbmsSplash.h" +#include "device.h" +#include "ui.h" +#include "ui_usbmsSplash.h" + +#include +#include +#include + +#include "functions.h" + +USBMSSplashWidget::USBMSSplashWidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::USBMSSplashWidget) { + ui->setupUi(this); + USBMSSplashWidget::setFont(QFont("u001")); + ui->label->setFont(QFont("Inter")); + + // Getting the screen's size + sW = QGuiApplication::screens()[0]->size().width(); + sH = QGuiApplication::screens()[0]->size().height(); + + // Defining what the default icon size will be + if (global::kobox::showKoboxSplash == true) { + float stdIconWidth = sW / 1.30; + float stdIconHeight = sH / 1.30; + + // Stylesheet + UI::applyStyle(*this, "eink"); + + ui->label->setFont(QFont("Inter")); + ui->label->setText("Launching KoBox subsystem"); + ui->label->setStyleSheet("font-size: 14pt; font-weight: bold"); + ui->label_3->setText("Please wait, this could take a while."); + ui->label_3->setStyleSheet("font-size: 10pt"); + + QPixmap pixmap(":/resources/kobox-icon.png"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->label_2->setPixmap(scaledPixmap); + } else { + float stdIconWidth = sW / 1.15; + float stdIconHeight = sH / 1.15; + + this->setStyleSheet("background-color:black;"); + ui->label->setStyleSheet("QLabel { background-color : black; color : white; font-size: 15pt; font-weight: bold }"); + ui->label_3->setStyleSheet("QLabel { background-color : black; color : white; font-size: 10pt }"); + + QPixmap pixmap(":/resources/usbms.png"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->label_2->setPixmap(scaledPixmap); + } + + if (global::usbms::launchUsbms == true) { + global::usbms::launchUsbms = false; + usbmsLaunch(); + } +} + +void USBMSSplashWidget::usbmsLaunch() { + Device *device = Device::getSingleton(); + + log("Entering USBMS session", className); + writeFile("/tmp/in_usbms", "true"); + QTimer::singleShot(1500, this, SLOT(brightnessDown())); + QTimer::singleShot(1500, this, SLOT(warmthDown())); + + if (global::usbms::koboxExportExtensions == true) { + writeFile("/opt/ibxd", "kobox_extensions_storage_unmount\n"); + } + if (checkconfig("/external_root/run/encfs_mounted") == true) { + writeFile("/external_root/run/encfs_stop_cleanup", "true"); + writeFile("/opt/ibxd", "encfs_stop\n"); + while (true) { + if (QFile::exists("/tmp/encfs_stopped")) { + QFile::remove("/tmp/encfs_stopped"); + break; + } + QThread::msleep(500); + } + } + + writeFile("/opt/ibxd", "gui_apps_stop\n"); + while (true) { + if (QFile::exists("/tmp/gui_apps_stopped")) { + QFile::remove("/tmp/gui_apps_stopped"); + break; + } + QThread::msleep(500); + } + + writeFile("/opt/ibxd", "onboard_unmount\n"); + while (true) { + if (QFile::exists("/tmp/onboard_unmounted")) { + QFile::remove("/tmp/onboard_unmounted"); + break; + } + QThread::msleep(500); + } + + writeFile("/opt/ibxd", "usbnet_stop\n"); + while (true) { + if (QFile::exists("/tmp/usbnet_stopped")) { + QFile::remove("/tmp/usbnet_stopped"); + break; + } + QThread::msleep(500); + } + + device->loadUSBMassStorageModule(); + + QString prog_1("insmod"); + QStringList args_1; + + massStorageModule = device->getUSBMassStorageModule(); + + if (global::usbms::koboxExportExtensions == true) { + args_1 << massStorageModule << "file=/external_root/opt/storage/X11/extensions-user.img" + << "removable=y" + << "stall=0"; + } else { + args_1 << massStorageModule << "file=/external_root/opt/storage/onboard" + << "removable=y" + << "stall=0"; + } + + QProcess *proc_1 = new QProcess(); + proc_1->start(prog_1, args_1); + proc_1->waitForFinished(); + proc_1->deleteLater(); + + bool exitUsbMsDone = false; + QTimer *usbms_t = new QTimer(this); + usbms_t->setInterval(1000); + connect(usbms_t, &QTimer::timeout, [&]() { + if (exitUsbMsDone == false) { + if (!device->isUSBPluggedIn()) { + if (global::usbms::koboxExportExtensions == true) { + reboot(false); + qApp->quit(); + } else { + log("Exiting USBMS session", className); + // '' bit: because nothing else works ... + ui->label->setText("Processing content"); + ui->label->setFont(QFont("Inter")); + ui->label_3->setText("Please wait"); + ui->label_3->setFont(QFont("u001")); + ui->label->setStyleSheet("QLabel { background-color : black; color : white; font-size: 15pt; font-weight: bold }"); + ui->label_3->setStyleSheet("QLabel { background-color : black; color : white; font-size: 11pt }"); + ui->label->setFont(QFont("u001")); + + float stdIconWidth = sW / 2; + float stdIconHeight = sH / 2; + + QPixmap pixmap(":/resources/clock-inverted.png"); + QPixmap scaledPixmap = pixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->label_2->setPixmap(scaledPixmap); + + this->repaint(); + + QString prog("rmmod"); + QStringList args; + args << massStorageModule; + QProcess *proc = new QProcess(); + proc->start(prog, args); + proc->waitForFinished(); + proc->deleteLater(); + + QTimer::singleShot(500, this, SLOT(restartServices())); + } + exitUsbMsDone = true; + } else { + ; + } + } + }); + usbms_t->start(); +} + +USBMSSplashWidget::~USBMSSplashWidget() { + delete ui; +} + +void USBMSSplashWidget::brightnessDown() { + UI::transitionBrightness(0); + writeFile("/tmp/inkbox-cinematicBrightness_ran", "false"); +} + +void USBMSSplashWidget::warmthDown() { + if (Device::getSingleton()->supportsWarmLight()) { + UI::transitionWarmth(0); + } +} + +void USBMSSplashWidget::quit_restart() { + // If existing, cleaning bookconfig_mount mountpoint + writeFile("/opt/ibxd", "bookconfig_unmount\n"); + + // Restarting InkBox + QProcess process; + process.startDetached("inkbox", QStringList()); + qApp->quit(); +} + +void USBMSSplashWidget::restartServices() { + // Restarting USBNet + // NOTE: USBNet is only started if required conditions are met (see https://github.com/Kobo-InkBox/rootfs/blob/master/etc/init.d/usbnet) + writeFile("/opt/ibxd", "usbnet_start\n"); + while (true) { + if (QFile::exists("/tmp/usbnet_started")) { + QFile::remove("/tmp/usbnet_started"); + break; + } + QThread::msleep(500); + } + + // Mounting onboard storage + writeFile("/opt/ibxd", "onboard_mount\n"); + while (true) { + if (QFile::exists("/tmp/onboard_mounted")) { + QFile::remove("/tmp/onboard_mounted"); + break; + } + QThread::msleep(500); + } + + // Checking for updates + writeFile("/opt/ibxd", "update_inkbox_restart\n"); + while (true) { + if (QFile::exists("/tmp/update_inkbox_restarted")) { + QFile::remove("/tmp/update_inkbox_restarted"); + break; + } + QThread::msleep(500); + } + + QFile::remove("/tmp/in_usbms"); + // GUI apps: update main JSON file + writeFile("/opt/ibxd", "gui_apps_start\n"); + while (true) { + if (QFile::exists("/tmp/gui_apps_started")) { + if (checkconfig("/tmp/gui_apps_started") == true) { + QFile::remove("/tmp/gui_apps_started"); + updateUserAppsMainJsonFile(); + break; + } else { + log("GUI apps service failed to start", className); + QFile::remove("/tmp/gui_apps_started"); + break; + } + } + QThread::msleep(500); + } + // Remove macOS dotfiles + { + QString prog("busybox-initrd"); + QStringList args; + args << "find" + << "/mnt/onboard/onboard" + << "-type" + << "f" + << "-name" + << "._*" + << "-delete"; + QProcess *proc = new QProcess(); + proc->start(prog, args); + proc->waitForFinished(); + proc->deleteLater(); + } + // Re-generate local library on next launch + QFile::remove(global::localLibrary::databasePath); + + quit_restart(); +} diff --git a/src/splash/usbmsSplash.h b/src/ui/splash/usbmsSplash.h similarity index 69% rename from src/splash/usbmsSplash.h rename to src/ui/splash/usbmsSplash.h index ce90925..3cafda1 100644 --- a/src/splash/usbmsSplash.h +++ b/src/ui/splash/usbmsSplash.h @@ -4,17 +4,17 @@ #include namespace Ui { -class usbmsSplash; +class USBMSSplashWidget; } -class usbmsSplash : public QWidget +class USBMSSplashWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit usbmsSplash(QWidget *parent = nullptr); - ~usbmsSplash(); + explicit USBMSSplashWidget(QWidget *parent = nullptr); + ~USBMSSplashWidget(); float sW; float sH; QString massStorageModule; @@ -28,7 +28,7 @@ private slots: void restartServices(); private: - Ui::usbmsSplash *ui; + Ui::USBMSSplashWidget *ui; }; #endif // USBMS_SPLASH_H diff --git a/src/splash/usbmsSplash.ui b/src/ui/splash/usbmsSplash.ui similarity index 97% rename from src/splash/usbmsSplash.ui rename to src/ui/splash/usbmsSplash.ui index 57b7cda..4eda1ee 100644 --- a/src/splash/usbmsSplash.ui +++ b/src/ui/splash/usbmsSplash.ui @@ -1,7 +1,7 @@ - usbmsSplash - + USBMSSplashWidget + 0 diff --git a/src/ui/ui.cpp b/src/ui/ui.cpp new file mode 100644 index 0000000..4f5acb0 --- /dev/null +++ b/src/ui/ui.cpp @@ -0,0 +1,60 @@ +#include "ui.h" +#include "device.h" + +#include +#include + +UI::UI() { +} + +void UI::applyStyle(QWidget &widget, QString styleName) { + if(!styleName.startsWith(":") && !styleName.startsWith("/")) { + styleName = Device::getSingleton()->getStyleSheetPath() + styleName; + } + if(!styleName.endsWith(".qss")) { + styleName = styleName + "qss"; + } + + QFile stylesheetFile(styleName); + stylesheetFile.open(QFile::ReadOnly); + widget.setStyleSheet(stylesheetFile.readAll()); + stylesheetFile.close(); +} + + +void UI::transitionBrightness(int targetValue) { + Device* device = Device::getSingleton(); + + int currentBrightness = device->getBrightness(); + if(currentBrightness <= targetValue) { + while(currentBrightness < targetValue) { + currentBrightness++; + device->setBrightness(currentBrightness); + QThread::msleep(30); + } + } else { + while(currentBrightness > targetValue) { + currentBrightness--; + device->setBrightness(currentBrightness); + QThread::msleep(30); + } + } +} + +void UI::transitionWarmth(int targetValue) { + Device *device = Device::getSingleton(); + int currentWarmth = device->getWarmth(); + if (targetValue < currentWarmth) { + while (targetValue < currentWarmth) { + currentWarmth--; + device->setWarmth(currentWarmth); + QThread::msleep(30); + } + } else if (targetValue > currentWarmth) { + while (targetValue > currentWarmth) { + currentWarmth++; + device->setWarmth(currentWarmth); + QThread::msleep(30); + } + } +} diff --git a/src/ui/ui.h b/src/ui/ui.h new file mode 100644 index 0000000..823542c --- /dev/null +++ b/src/ui/ui.h @@ -0,0 +1,22 @@ +#ifndef UI_H +#define UI_H + +#include +#include + +/* + * Utility class for UI related stuff + */ + +class UI +{ +public: + UI(); + + static void applyStyle(QWidget &widget, QString styleName); + + static void transitionBrightness(int targetValue); + static void transitionWarmth(int targetValue); +}; + +#endif // UI_H diff --git a/src/widgets/dialogs/audio/audiodialog.cpp b/src/ui/widgets/dialogs/audio/audiodialog.cpp similarity index 91% rename from src/widgets/dialogs/audio/audiodialog.cpp rename to src/ui/widgets/dialogs/audio/audiodialog.cpp index d6ccda2..e1a4f93 100644 --- a/src/widgets/dialogs/audio/audiodialog.cpp +++ b/src/ui/widgets/dialogs/audio/audiodialog.cpp @@ -10,12 +10,12 @@ #include -audioDialog::audioDialog(QWidget *parent) : +AudioDialog::AudioDialog(QWidget *parent) : QDialog(parent), - ui(new Ui::audioDialog) + ui(new Ui::AudioDialog) { ui->setupUi(this); - audioDialog::setFont(QFont("u001")); + AudioDialog::setFont(QFont("u001")); ui->fileNameLabel->setFont(QFont("u001")); progress = new QTimer(this); @@ -102,12 +102,12 @@ audioDialog::audioDialog(QWidget *parent) : finishedStartingUp = true; } -audioDialog::~audioDialog() +AudioDialog::~AudioDialog() { delete ui; } -void audioDialog::changeMenu() { +void AudioDialog::changeMenu() { log("Menu change requested", className); if(currentMenu != Queue) { currentMenu = Queue; @@ -131,14 +131,14 @@ void audioDialog::changeMenu() { ui->scrollArea->verticalScrollBar()->setValue(ui->scrollArea->verticalScrollBar()->minimum()); } -void audioDialog::on_libraryBtn_clicked() +void AudioDialog::on_libraryBtn_clicked() { if(currentMenu != Library) { changeMenu(); } } -void audioDialog::on_queueBtn_clicked() +void AudioDialog::on_queueBtn_clicked() { if(currentMenu != Queue) { changeMenu(); @@ -146,7 +146,7 @@ void audioDialog::on_queueBtn_clicked() } // Only on launching dialog -void audioDialog::refreshFileList() { +void AudioDialog::refreshFileList() { log("Refreshing file list", className); if(QFile(".config/e-2-audio/path").exists() == false) { writeFile(".config/e-2-audio/path", "/mnt/onboard/onboard/music/"); @@ -230,24 +230,24 @@ void audioDialog::refreshFileList() { this->adjustSize(); } -void audioDialog::refreshAudioFileWidgets() { +void AudioDialog::refreshAudioFileWidgets() { global::audio::audioMutex.lock(); emit deleteItself(); // Doesn't work, freezes the app... // QCoreApplication::processEvents(); for(int i = 0; i < global::audio::fileList.size(); i++) { log("Adding new item number: " + QString::number(i), className); - audiofile* newAudioFile = new audiofile(this); + AudioFileWidget* newAudioFile = new AudioFileWidget(this); newAudioFile->provideData(global::audio::fileList[i]); - QObject::connect(this, &audioDialog::deleteItself, newAudioFile, &audiofile::die); - QObject::connect(newAudioFile, &audiofile::playFileChild, this, &audioDialog::playFile); + QObject::connect(this, &AudioDialog::deleteItself, newAudioFile, &AudioFileWidget::die); + QObject::connect(newAudioFile, &AudioFileWidget::playFileChild, this, &AudioDialog::playFile); ui->verticalLayout->addWidget(newAudioFile, Qt::AlignTop); } global::audio::audioMutex.unlock(); this->adjustSize(); } -void audioDialog::refreshAudioFileWidgetsQueue() { +void AudioDialog::refreshAudioFileWidgetsQueue() { global::audio::audioMutex.lock(); emit deleteItself(); // Doesn't work, freezes the app... @@ -257,21 +257,21 @@ void audioDialog::refreshAudioFileWidgetsQueue() { for(int i = 0; i < global::audio::queue.size(); i++) { log("Adding new item: " + QString::number(i), className); - audiofilequeue* newAudioFileQueue = new audiofilequeue(this); + AudioFileQueueWidget* newAudioFileQueue = new AudioFileQueueWidget(this); bool gray = false; if(global::audio::isSomethingCurrentlyPlaying == true && global::audio::itemCurrentlyPlaying == i) { gray = true; } global::audio::queue[i].id = i; // Give them invidual ID once more, because files can repeat newAudioFileQueue->provideData(global::audio::queue[i], gray); - QObject::connect(this, &audioDialog::deleteItself, newAudioFileQueue, &audiofilequeue::die); - QObject::connect(newAudioFileQueue, &audiofilequeue::playFileChild, this, &audioDialog::playFile); + QObject::connect(this, &AudioDialog::deleteItself, newAudioFileQueue, &AudioFileQueueWidget::die); + QObject::connect(newAudioFileQueue, &AudioFileQueueWidget::playFileChild, this, &AudioDialog::playFile); ui->verticalLayout->addWidget(newAudioFileQueue, Qt::AlignTop); } global::audio::audioMutex.unlock(); } -void audioDialog::on_refreshBtn_clicked() +void AudioDialog::on_refreshBtn_clicked() { global::audio::audioMutex.lock(); global::audio::currentAction.append(global::audio::Action::Stop); @@ -281,7 +281,7 @@ void audioDialog::on_refreshBtn_clicked() refreshAudioFileWidgetsQueue(); } -void audioDialog::playFile(int itemInQueue) { +void AudioDialog::playFile(int itemInQueue) { log("Called playFile", className); log("Calling stop to current actions to play a new file", className); @@ -304,7 +304,7 @@ void audioDialog::playFile(int itemInQueue) { } } -void audioDialog::progressFuncManage() { +void AudioDialog::progressFuncManage() { global::audio::audioMutex.lock(); // log("Called progress watcher", className); @@ -355,12 +355,12 @@ void audioDialog::progressFuncManage() { } } -void audioDialog::on_progressSlider_sliderPressed() +void AudioDialog::on_progressSlider_sliderPressed() { ui->progressSlider->releaseMouse(); } -void audioDialog::on_soundLevelSlider_valueChanged(int value) +void AudioDialog::on_soundLevelSlider_valueChanged(int value) { log("Setting volume level: " + QString::number(value), className); // It detects if volume changes @@ -371,17 +371,17 @@ void audioDialog::on_soundLevelSlider_valueChanged(int value) } } -void audioDialog::on_plusBtn_clicked() +void AudioDialog::on_plusBtn_clicked() { ui->soundLevelSlider->setValue(ui->soundLevelSlider->value() + 1); } -void audioDialog::on_minusBtn_clicked() +void AudioDialog::on_minusBtn_clicked() { ui->soundLevelSlider->setValue(ui->soundLevelSlider->value() - 1); } -void audioDialog::on_playBtn_clicked() +void AudioDialog::on_playBtn_clicked() { global::audio::audioMutex.lock(); if(global::audio::isSomethingCurrentlyPlaying == true) { @@ -412,7 +412,7 @@ void audioDialog::on_playBtn_clicked() global::audio::audioMutex.unlock(); } -void audioDialog::on_previousBtn_clicked() +void AudioDialog::on_previousBtn_clicked() { global::audio::audioMutex.lock(); int item = global::audio::itemCurrentlyPlaying; @@ -429,7 +429,7 @@ void audioDialog::on_previousBtn_clicked() global::audio::audioMutex.unlock(); } -void audioDialog::on_nextBtn_clicked() +void AudioDialog::on_nextBtn_clicked() { global::audio::audioMutex.lock(); int item = global::audio::itemCurrentlyPlaying; @@ -446,7 +446,7 @@ void audioDialog::on_nextBtn_clicked() global::audio::audioMutex.unlock(); } -void audioDialog::on_exitBtn_clicked() +void AudioDialog::on_exitBtn_clicked() { progress->stop(); progress->deleteLater(); diff --git a/src/widgets/dialogs/audio/audiodialog.h b/src/ui/widgets/dialogs/audio/audiodialog.h similarity index 87% rename from src/widgets/dialogs/audio/audiodialog.h rename to src/ui/widgets/dialogs/audio/audiodialog.h index ff07a40..a8fcdb9 100644 --- a/src/widgets/dialogs/audio/audiodialog.h +++ b/src/ui/widgets/dialogs/audio/audiodialog.h @@ -5,16 +5,16 @@ #include namespace Ui { -class audioDialog; +class AudioDialog; } -class audioDialog : public QDialog +class AudioDialog : public QDialog { Q_OBJECT public: - explicit audioDialog(QWidget *parent = nullptr); - ~audioDialog(); + explicit AudioDialog(QWidget *parent = nullptr); + ~AudioDialog(); QString className = this->metaObject()->className(); enum audioMenu { @@ -51,7 +51,7 @@ signals: void deleteItself(); private: - Ui::audioDialog *ui; + Ui::AudioDialog *ui; }; #endif // AUDIODIALOG_H diff --git a/src/widgets/dialogs/audio/audiodialog.ui b/src/ui/widgets/dialogs/audio/audiodialog.ui similarity index 99% rename from src/widgets/dialogs/audio/audiodialog.ui rename to src/ui/widgets/dialogs/audio/audiodialog.ui index 27ea7e4..96cd084 100644 --- a/src/widgets/dialogs/audio/audiodialog.ui +++ b/src/ui/widgets/dialogs/audio/audiodialog.ui @@ -1,7 +1,7 @@ - audioDialog - + AudioDialog + 0 diff --git a/src/widgets/dialogs/audio/audiofile.cpp b/src/ui/widgets/dialogs/audio/audiofile.cpp similarity index 79% rename from src/widgets/dialogs/audio/audiofile.cpp rename to src/ui/widgets/dialogs/audio/audiofile.cpp index a86a299..abb7984 100644 --- a/src/widgets/dialogs/audio/audiofile.cpp +++ b/src/ui/widgets/dialogs/audio/audiofile.cpp @@ -2,12 +2,12 @@ #include "ui_audiofile.h" #include "functions.h" -audiofile::audiofile(QWidget *parent) : +AudioFileWidget::AudioFileWidget(QWidget *parent) : QWidget(parent), - ui(new Ui::audiofile) + ui(new Ui::AudioFileWidget) { ui->setupUi(this); - audiofile::setFont(QFont("u001")); + AudioFileWidget::setFont(QFont("u001")); ui->nameLabel->setFont(QFont("u001")); ui->timeLabel->setFont(QFont("u001")); @@ -16,23 +16,23 @@ audiofile::audiofile(QWidget *parent) : ui->nameLabel->setWordWrap(true); } -audiofile::~audiofile() +AudioFileWidget::~AudioFileWidget() { delete ui; } -void audiofile::provideData(global::audio::musicFile fileProvided) { +void AudioFileWidget::provideData(global::audio::musicFile fileProvided) { file = fileProvided; ui->nameLabel->setText(file.name); ui->timeLabel->setText(file.length); } -void audiofile::die() { +void AudioFileWidget::die() { this->deleteLater(); this->close(); } -void audiofile::on_addBtn_clicked() +void AudioFileWidget::on_addBtn_clicked() { ui->addBtn->setDisabled(true); ui->addBtn->setStyleSheet("background: black;"); @@ -53,7 +53,7 @@ void audiofile::on_addBtn_clicked() QTimer::singleShot(700, this, SLOT(enableButton())); } -void audiofile::enableButton() { +void AudioFileWidget::enableButton() { log("Enabling 'Back' button", className); ui->addBtn->setEnabled(true); ui->addBtn->setStyleSheet("background: white;"); diff --git a/src/widgets/dialogs/audio/audiofile.h b/src/ui/widgets/dialogs/audio/audiofile.h similarity index 73% rename from src/widgets/dialogs/audio/audiofile.h rename to src/ui/widgets/dialogs/audio/audiofile.h index c993d1c..f92cbfd 100644 --- a/src/widgets/dialogs/audio/audiofile.h +++ b/src/ui/widgets/dialogs/audio/audiofile.h @@ -6,16 +6,16 @@ #include namespace Ui { -class audiofile; +class AudioFileWidget; } -class audiofile : public QWidget +class AudioFileWidget : public QWidget { Q_OBJECT public: - explicit audiofile(QWidget *parent = nullptr); - ~audiofile(); + explicit AudioFileWidget(QWidget *parent = nullptr); + ~AudioFileWidget(); QString className = this->metaObject()->className(); void provideData(global::audio::musicFile fileProvided); global::audio::musicFile file; @@ -32,7 +32,7 @@ signals: void playFileChild(int itemInQueue); private: - Ui::audiofile *ui; + Ui::AudioFileWidget *ui; }; #endif // AUDIOFILE_H diff --git a/src/widgets/dialogs/audio/audiofile.ui b/src/ui/widgets/dialogs/audio/audiofile.ui similarity index 97% rename from src/widgets/dialogs/audio/audiofile.ui rename to src/ui/widgets/dialogs/audio/audiofile.ui index f240a07..de18e6d 100644 --- a/src/widgets/dialogs/audio/audiofile.ui +++ b/src/ui/widgets/dialogs/audio/audiofile.ui @@ -1,7 +1,7 @@ - audiofile - + AudioFileWidget + 0 diff --git a/src/widgets/dialogs/audio/audiofilequeue.cpp b/src/ui/widgets/dialogs/audio/audiofilequeue.cpp similarity index 84% rename from src/widgets/dialogs/audio/audiofilequeue.cpp rename to src/ui/widgets/dialogs/audio/audiofilequeue.cpp index d0dd920..642cfad 100644 --- a/src/widgets/dialogs/audio/audiofilequeue.cpp +++ b/src/ui/widgets/dialogs/audio/audiofilequeue.cpp @@ -1,12 +1,12 @@ #include "audiofilequeue.h" #include "ui_audiofilequeue.h" -audiofilequeue::audiofilequeue(QWidget *parent) : +AudioFileQueueWidget::AudioFileQueueWidget(QWidget *parent) : QWidget(parent), - ui(new Ui::audiofilequeue) + ui(new Ui::AudioFileQueueWidget) { ui->setupUi(this); - audiofilequeue::setFont(QFont("u001")); + AudioFileQueueWidget::setFont(QFont("u001")); ui->nameLabel->setFont(QFont("u001")); ui->timeLabel->setFont(QFont("u001")); @@ -16,12 +16,12 @@ audiofilequeue::audiofilequeue(QWidget *parent) : ui->nameLabel->setWordWrap(true); } -audiofilequeue::~audiofilequeue() +AudioFileQueueWidget::~AudioFileQueueWidget() { delete ui; } -void audiofilequeue::provideData(global::audio::musicFile fileProvided, bool gray) { +void AudioFileQueueWidget::provideData(global::audio::musicFile fileProvided, bool gray) { file = fileProvided; ui->nameLabel->setText(file.name); ui->timeLabel->setText(file.length); @@ -33,12 +33,12 @@ void audiofilequeue::provideData(global::audio::musicFile fileProvided, bool gra } } -void audiofilequeue::die() { +void AudioFileQueueWidget::die() { this->deleteLater(); this->close(); } -void audiofilequeue::on_deleteBtn_clicked() +void AudioFileQueueWidget::on_deleteBtn_clicked() { int id = -1; log("global::audio::queue.size(): " + QString::number(global::audio::queue.size()), className); @@ -74,7 +74,7 @@ void audiofilequeue::on_deleteBtn_clicked() global::audio::audioMutex.unlock(); } -void audiofilequeue::on_playBtn_clicked() +void AudioFileQueueWidget::on_playBtn_clicked() { global::audio::audioMutex.lock(); for(int i = 0; i < global::audio::queue.size(); i++) { diff --git a/src/widgets/dialogs/audio/audiofilequeue.h b/src/ui/widgets/dialogs/audio/audiofilequeue.h similarity index 72% rename from src/widgets/dialogs/audio/audiofilequeue.h rename to src/ui/widgets/dialogs/audio/audiofilequeue.h index 50d46c3..10045a4 100644 --- a/src/widgets/dialogs/audio/audiofilequeue.h +++ b/src/ui/widgets/dialogs/audio/audiofilequeue.h @@ -5,16 +5,16 @@ #include "functions.h" namespace Ui { -class audiofilequeue; +class AudioFileQueueWidget; } -class audiofilequeue : public QWidget +class AudioFileQueueWidget : public QWidget { Q_OBJECT public: - explicit audiofilequeue(QWidget *parent = nullptr); - ~audiofilequeue(); + explicit AudioFileQueueWidget(QWidget *parent = nullptr); + ~AudioFileQueueWidget(); QString className = this->metaObject()->className(); bool isPlaying = false; @@ -25,7 +25,7 @@ public slots: void die(); private: - Ui::audiofilequeue *ui; + Ui::AudioFileQueueWidget *ui; signals: void playFileChild(int itemInQueue); diff --git a/src/widgets/dialogs/audio/audiofilequeue.ui b/src/ui/widgets/dialogs/audio/audiofilequeue.ui similarity index 97% rename from src/widgets/dialogs/audio/audiofilequeue.ui rename to src/ui/widgets/dialogs/audio/audiofilequeue.ui index 8ebf3c9..2b5d6b1 100644 --- a/src/widgets/dialogs/audio/audiofilequeue.ui +++ b/src/ui/widgets/dialogs/audio/audiofilequeue.ui @@ -1,7 +1,7 @@ - audiofilequeue - + AudioFileQueueWidget + 0 diff --git a/src/ui/widgets/dialogs/brightnessdialog.cpp b/src/ui/widgets/dialogs/brightnessdialog.cpp new file mode 100644 index 0000000..562312d --- /dev/null +++ b/src/ui/widgets/dialogs/brightnessdialog.cpp @@ -0,0 +1,157 @@ +#include "brightnessdialog.h" +#include "device.h" +#include "functions.h" +#include "ui.h" +#include "ui_brightnessdialog.h" + +#include +#include +#include +#include + +BrightnessDialog::BrightnessDialog(QWidget *parent) : + QDialog(parent), + ui(new Ui::BrightnessDialog) { + ui->setupUi(this); + BrightnessDialog::setFont(QFont("u001")); + + // Stylesheet, style & misc. + UI::applyStyle(*this, "eink"); + + ui->quitBtn->setProperty("type", "borderless"); + ui->quitBtn->setText(""); + ui->quitBtn->setIcon(QIcon(":/resources/close.png")); + ui->okBtn->setProperty("type", "borderless"); + ui->okBtn->setText(""); + ui->okBtn->setIcon(QIcon(":/resources/check.png")); + ui->decBtn->setProperty("type", "borderless"); + ui->decBtn->setText(""); + ui->decBtn->setIcon(QIcon(":/resources/minus.png")); + ui->incBtn->setProperty("type", "borderless"); + ui->incBtn->setText(""); + ui->incBtn->setIcon(QIcon(":/resources/plus.png")); + ui->brightnessLabel->setStyleSheet("padding-left: 125px; padding-right: 125px; font:bold"); + ui->valueLabel->setStyleSheet("font-size: 9pt"); + ui->warmthValueLabel->setStyleSheet("font-size: 9pt"); + + int value; + int warmthValue; + + Device *platform = Device::getSingleton(); + + if (platform->supportsWarmLight()) { + ui->warmthDecBtn->setProperty("type", "borderless"); + ui->warmthIncBtn->setProperty("type", "borderless"); + ui->warmthDecBtn->setText(""); + ui->warmthIncBtn->setText(""); + ui->warmthDecBtn->setIcon(QIcon(":/resources/nightmode-empty.png")); + ui->warmthIncBtn->setIcon(QIcon(":/resources/nightmode-full.png")); + ui->warmthSlider->setMaximum(Device::getSingleton()->getMaxWarmLightValue()); + + warmthValue = platform->getWarmth(); + ui->warmthSlider->setValue(warmthValue); + if (warmthValue == 0) { + ui->warmthValueLabel->setText("0"); + } + } else { + ui->warmthSlider->hide(); + ui->warmthDecBtn->hide(); + ui->warmthIncBtn->hide(); + ui->warmthValueLabel->hide(); + ui->warmthSlider->deleteLater(); + ui->warmthDecBtn->deleteLater(); + ui->warmthIncBtn->deleteLater(); + ui->gridLayout_5->deleteLater(); + ui->warmthValueLabel->deleteLater(); + this->adjustSize(); + } + + value = Device::getSingleton()->getBrightness(); + + // Setting the slider to the appropriate position + ui->horizontalSlider->setValue(value); + + // Showing brightness percentage on label + QString valueStr = QString::number(value); + valueStr = valueStr.append("%"); + ui->valueLabel->setText(valueStr); + + // Saving current brightness value in case we want to go backwards + oldValue = value; + if (Device::getSingleton()->supportsWarmLight()) { + oldWarmthValue = warmthValue; + } +} + +BrightnessDialog::~BrightnessDialog() { + delete ui; +} + +void BrightnessDialog::on_quitBtn_clicked() { + Device *platform = Device::getSingleton(); + // Reverting back to the old value + platform->setBrightness(oldValue); + if (platform->supportsWarmLight()) { + platform->setWarmth(oldWarmthValue); + } + + // Leaving + BrightnessDialog::close(); +} + +void BrightnessDialog::on_horizontalSlider_valueChanged(int value) { + Device::getSingleton()->setBrightness(value); + QString valueStr = QString::number(value); + valueStr = valueStr.append("%"); + ui->valueLabel->setText(valueStr); +} + +void BrightnessDialog::on_incBtn_clicked() { + int value = ui->horizontalSlider->value(); + value = value + 1; + ui->horizontalSlider->setValue(value); +} + +void BrightnessDialog::on_decBtn_clicked() { + int value = ui->horizontalSlider->value(); + value = value - 1; + ui->horizontalSlider->setValue(value); +} + +void BrightnessDialog::on_okBtn_clicked() { + Device *device = Device::getSingleton(); + + // Get set brightness value + int brightnessValue = ui->horizontalSlider->value(); + int warmthValue; + + // Write brightness config + log("Display brightness set to " + QString::number(brightnessValue), className); + device->setBrightness(brightnessValue); + if (device->supportsWarmLight()) { + warmthValue = ui->warmthSlider->value(); + log("Display warmth set to " + QString::number(warmthValue), className); + device->setWarmth(warmthValue); + } + + // Leaving + BrightnessDialog::close(); +} + +void BrightnessDialog::on_warmthSlider_valueChanged(int value) { + Device::getSingleton()->setWarmth(value); + QString valueStr = QString::number(value); + ui->warmthValueLabel->setText(valueStr); +} + +void BrightnessDialog::on_warmthDecBtn_clicked() { + int value = ui->warmthSlider->value(); + value = value - 1; + ui->warmthSlider->setValue(value); +} + +void BrightnessDialog::on_warmthIncBtn_clicked() { + int value = ui->warmthSlider->value(); + value = value + 1; + ui->warmthSlider->setValue(value); +} diff --git a/src/widgets/dialogs/brightnessdialog.h b/src/ui/widgets/dialogs/brightnessdialog.h similarity index 72% rename from src/widgets/dialogs/brightnessdialog.h rename to src/ui/widgets/dialogs/brightnessdialog.h index ed419c6..8faeab2 100644 --- a/src/widgets/dialogs/brightnessdialog.h +++ b/src/ui/widgets/dialogs/brightnessdialog.h @@ -6,10 +6,10 @@ using namespace std; namespace Ui { -class brightnessDialog; +class BrightnessDialog; } -class brightnessDialog : public QDialog +class BrightnessDialog : public QDialog { Q_OBJECT @@ -17,9 +17,8 @@ public: QString className = this->metaObject()->className(); int oldValue; int oldWarmthValue; - void preSetBrightness(int brightnessValue); - explicit brightnessDialog(QWidget *parent = nullptr); - ~brightnessDialog(); + explicit BrightnessDialog(QWidget *parent = nullptr); + ~BrightnessDialog(); private slots: void on_quitBtn_clicked(); @@ -32,7 +31,7 @@ private slots: void on_warmthIncBtn_clicked(); private: - Ui::brightnessDialog *ui; + Ui::BrightnessDialog *ui; }; #endif // BRIGHTNESSDIALOG_H diff --git a/src/widgets/dialogs/brightnessdialog.ui b/src/ui/widgets/dialogs/brightnessdialog.ui similarity index 98% rename from src/widgets/dialogs/brightnessdialog.ui rename to src/ui/widgets/dialogs/brightnessdialog.ui index 7c26fed..fd36fc6 100644 --- a/src/widgets/dialogs/brightnessdialog.ui +++ b/src/ui/widgets/dialogs/brightnessdialog.ui @@ -1,7 +1,7 @@ - brightnessDialog - + BrightnessDialog + 0 diff --git a/src/ui/widgets/dialogs/generaldialog.cpp b/src/ui/widgets/dialogs/generaldialog.cpp new file mode 100644 index 0000000..747b29b --- /dev/null +++ b/src/ui/widgets/dialogs/generaldialog.cpp @@ -0,0 +1,788 @@ +#include "generaldialog.h" +#include "device.h" +#include "functions.h" +#include "mainwindow.h" +#include "reader.h" +#include "ui.h" +#include "ui_generaldialog.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +GeneralDialog::GeneralDialog(QWidget *parent) : + QDialog(parent), + ui(new Ui::GeneralDialog) { + Device *device = Device::getSingleton(); + + ui->setupUi(this); + ui->bodyLabel->setFont(QFont("u001")); + ui->searchComboBox->setFont(QFont("u001")); + + // Preventing outside interaction + this->setModal(true); + + // Stylesheet, style & misc. + if (global::keyboard::encfsDialog == true) { + UI::applyStyle(*this, ":/resources/eink-square-encfs.qss"); + } else { + UI::applyStyle(*this, "eink"); + } + + ui->okBtn->setProperty("type", "borderless"); + ui->cancelBtn->setProperty("type", "borderless"); + ui->acceptBtn->setProperty("type", "borderless"); + + ui->okBtn->setStyleSheet("font-size: 9pt; padding: 10px; font-weight: bold; background: lightGrey"); + ui->cancelBtn->setStyleSheet("font-size: 9pt; padding: 10px; font-weight: bold; background: lightGrey"); + ui->acceptBtn->setStyleSheet("font-size: 9pt; padding: 10px; font-weight: bold; background: lightGrey"); + ui->headerLabel->setStyleSheet("font-weight: bold"); + ui->bodyLabel->setStyleSheet("font-size: 9.5pt"); + ui->searchComboBox->setStyleSheet("font-size: 9pt"); + + // Disabling "Online library" search if device doesn't have Wi-Fi + if (device->supportsWifi()) { + ui->searchComboBox->removeItem(2); + } + + if (QFile::exists("/inkbox/searchComboBoxFunction") == true) { + QString searchComboBoxFunction = readFile("/inkbox/searchComboBoxFunction"); + if (searchComboBoxFunction == "Dictionary") { + ui->searchComboBox->setCurrentIndex(0); + } else if (searchComboBoxFunction == "Local storage") { + ui->searchComboBox->setCurrentIndex(1); + } else if (searchComboBoxFunction == "Online library") { + ui->searchComboBox->setCurrentIndex(2); + } else { + ui->searchComboBox->setCurrentIndex(0); + } + } + + if (checkconfig("/inkbox/resetDialog") == true) { + if (checkconfig("/opt/inkbox_genuine") == true) { + resetDialog = true; + ui->okBtn->setText("Proceed"); + ui->cancelBtn->setText("Go back"); + ui->bodyLabel->setText("This will erase any books\nyou have stored on the device.\nSettings will be reset."); + + ui->headerLabel->setText("Warning"); + QTimer::singleShot(50, this, SLOT(adjust_size())); + writeFile("/inkbox/resetDialog", "false"); + } else { + resetDialog = true; + ui->okBtn->setText("Proceed"); + ui->cancelBtn->setText("Go back"); + ui->bodyLabel->setText("Settings will be reset."); + ui->headerLabel->setText("Warning"); + QTimer::singleShot(50, this, SLOT(adjust_size())); + writeFile("/inkbox/resetDialog", "false"); + } + } else if (checkconfig("/inkbox/updateDialog") == true) { + updateDialog = true; + ui->okBtn->setText("Update"); + ui->cancelBtn->setText("Not now"); + ui->bodyLabel->setText("Do you want to update InkBox now?"); // Because I hate Univers/U001's question mark ... + ui->headerLabel->setText("Update available"); + QTimer::singleShot(50, this, SLOT(adjust_size())); + writeFile("/inkbox/updateDialog", "false"); + } else if (global::settings::settingsRebootDialog == true) { + settingsRebootDialog = true; + ui->stackedWidget->setCurrentIndex(1); + if (global::kobox::koboxSettingsRebootDialog == true or global::encfs::enableStorageEncryptionDialog) { + koboxSettingsRebootDialog = true; + ui->bodyLabel->setText("The device will reboot now, since
the settings you defined require it to work properly."); + } else { + ui->bodyLabel->setText("The settings you defined might
require a complete reboot of the device for them to work properly."); + } + ui->headerLabel->setText("Information"); + QTimer::singleShot(50, this, SLOT(adjust_size())); + } else if (global::mainwindow::lowBatteryDialog == true) { + lowBatteryDialog = true; + ui->stackedWidget->setCurrentIndex(1); + QString message = "The battery's level is low.\nPlease charge your eReader.\nCurrent level: "; + message.append(device->getBatteryLevel()); + ui->bodyLabel->setText(message); + ui->headerLabel->setText("Low battery"); + QTimer::singleShot(50, this, SLOT(adjust_size())); + writeFile("/inkbox/lowBatteryDialog", "false"); + } else if (global::usbms::usbmsDialog == true) { + usbmsDialog = true; + ui->stackedWidget->setCurrentIndex(0); + ui->okBtn->setText("Connect"); + ui->cancelBtn->setText("Not now"); + ui->bodyLabel->setText("Do you want to connect your device to a computer to manage books?"); + ui->headerLabel->setText("USB cable connected"); + QTimer::singleShot(50, this, SLOT(adjust_size())); + } else if (global::text::textBrowserDialog == true) { + textBrowserDialog = true; + textwidgetWindow = new textwidget(); + + if (global::text::textBrowserTitle.isEmpty() == true) { + ui->headerLabel->setText("Information"); + } else { + ui->headerLabel->setText(global::text::textBrowserTitle); + } + // Important + ui->bodyLabel->setText(global::text::textBrowserContents); + + ui->stackedWidget->setCurrentIndex(1); + ui->mainStackedWidget->insertWidget(1, textwidgetWindow); + ui->mainStackedWidget->setCurrentIndex(1); + QTimer::singleShot(50, this, SLOT(adjust_size())); + } else if (global::kobox::resetKoboxDialog == true) { + resetKoboxDialog = true; + ui->headerLabel->setText("Warning"); + ui->okBtn->setText("Proceed"); + ui->cancelBtn->setText("Go back"); + ui->bodyLabel->setText("This will erase all KoBox user data. KoBox settings will be reset."); + QTimer::singleShot(50, this, SLOT(adjust_size())); + } else if (global::keyboard::keyboardDialog == true) { + setupKeyboardDialog(); + } else if (global::keyboard::keypadDialog == true) { + keypadDialog = true; + keypadWidget = new virtualkeypad(); + ui->headerLabel->setText("Enter a number"); + ui->okBtn->setText("OK"); + ui->cancelBtn->setText("Cancel"); + ui->mainStackedWidget->insertWidget(1, keypadWidget); + ui->mainStackedWidget->setCurrentIndex(1); + QTimer::singleShot(50, this, SLOT(adjust_size())); + } else if (global::encfs::disableStorageEncryptionDialog == true) { + ui->headerLabel->setText("Warning"); + ui->okBtn->setText("Proceed"); + ui->cancelBtn->setText("Go back"); + ui->bodyLabel->setText("This will delete all the files you have encrypted. Are you sure you want to continue?"); + QTimer::singleShot(50, this, SLOT(adjust_size())); + } else if (global::encfs::errorNoBooksInDropboxDialog == true) { + ui->stackedWidget->setCurrentIndex(1); + ui->headerLabel->setText("Error"); + ui->bodyLabel->setText("Please put books in the 'encfs-dropbox' folder to repack your encrypted storage."); + QTimer::singleShot(50, this, SLOT(adjust_size())); + } else if (global::encfs::repackDialog == true) { + ui->headerLabel->setText("Information"); + ui->okBtn->setText("Proceed"); + ui->cancelBtn->setText("Not now"); + ui->bodyLabel->setText("New files have been found in 'encfs-dropbox'. Would you want to repack your encrypted storage?"); + QTimer::singleShot(50, this, SLOT(adjust_size())); + } else if (global::userApps::appCompatibilityDialog == true) { + appCompatibilityDialog = true; + global::userApps::appCompatibilityLastContinueStatus = true; + ui->okBtn->setText("Continue"); + ui->cancelBtn->setText("Cancel"); + ui->bodyLabel->setText(global::userApps::appCompatibilityText); + ui->headerLabel->setText("Compatibility warning"); + QTimer::singleShot(50, this, SLOT(adjust_size())); + } else if (global::userApps::appInfoDialog == true) { + appInfoDialog = true; + textwidgetWindow = new textwidget(); + + ui->headerLabel->setText("App info"); + ui->stackedWidget->setCurrentIndex(1); + ui->mainStackedWidget->insertWidget(1, textwidgetWindow); + ui->mainStackedWidget->setCurrentIndex(1); + yIncrease = 1.8; + QTimer::singleShot(50, this, SLOT(increaseSize())); + } else if (global::library::librarySyncDialog == true) { + librarySyncDialog = true; + ui->okBtn->setText("Continue"); + ui->cancelBtn->setText("Not now"); + ui->bodyLabel->setText("Online library requires syncing. Do you want to continue?"); + ui->headerLabel->setText("Sync required"); + QTimer::singleShot(50, this, SLOT(adjust_size())); + } else if (global::telemetry::telemetryDialog == true) { + telemetryDialog = true; + ui->stackedWidget->setCurrentIndex(0); + ui->okBtn->setText("Send"); + ui->cancelBtn->setText("Don't send"); + ui->bodyLabel->setText("We, the InkBox OS developers, would like to know a bit more about our userbase.
We would be extremely grateful if you would allow us to collect some information about your device.
Would you like to send it to us
?
No personal data will be transmitted.
"); + ui->headerLabel->setText("Telemetry request"); + QTimer::singleShot(50, this, SLOT(adjust_size())); + } else { + // We shouldn't be there ;) + log("Launched without settings", className); + } +} + +GeneralDialog::~GeneralDialog() { + delete ui; +} + +void GeneralDialog::on_cancelBtn_clicked() { + log("Cancel button clicked", className); + if (updateDialog == true) { + writeFile("/tmp/cancelUpdateDialog", "true"); + GeneralDialog::close(); + } else if (usbmsDialog == true) { + global::usbms::usbmsDialog = false; + GeneralDialog::close(); + } else if (resetKoboxDialog == true) { + global::kobox::resetKoboxDialog = false; + GeneralDialog::close(); + } else if (keypadDialog == true) { + global::keyboard::keypadDialog = false; + GeneralDialog::close(); + } else if (global::encfs::disableStorageEncryptionDialog == true) { + emit cancelDisableStorageEncryption(); + global::encfs::disableStorageEncryptionDialog = false; + GeneralDialog::close(); + } else { + if (global::keyboard::searchDialog == true) { + global::keyboard::searchDialog = false; + global::forbidOpenSearchDialog = true; + global::keyboard::keyboardDialog = false; + global::keyboard::keyboardText = ""; + global::library::librarySearchDialog = false; + } else if (global::keyboard::vncDialog == true) { + global::keyboard::vncDialog = false; + global::keyboard::keyboardDialog = false; + global::keyboard::keyboardText = ""; + } else if (global::keyboard::encfsDialog == true) { + global::keyboard::encfsDialog = false; + global::encfs::cancelSetup = true; + global::keyboard::keyboardText = ""; + } else if (global::encfs::errorNoBooksInDropboxDialog == true) { + global::encfs::errorNoBooksInDropboxDialog = false; + } else if (global::encfs::repackDialog == true) { + global::encfs::repackDialog = false; + } else if (global::userApps::appCompatibilityDialog == true) { + global::userApps::launchApp = false; + global::userApps::appCompatibilityLastContinueStatus = false; + global::userApps::appCompatibilityText = ""; + global::userApps::appCompatibilityDialog = false; + } else if (global::library::librarySyncDialog == true) { + emit noSyncOnlineLibrary(); + global::library::librarySyncDialog = false; + } else if (global::telemetry::telemetryDialog == true) { + global::telemetry::telemetryDialog = false; + log("User declined telemetry request", className); + writeFile("/mnt/onboard/.adds/inkbox/.config/24-telemetry/asked", "true"); + } else if (global::keyboard::telemetryMessageDialog == true) { + global::keyboard::telemetryMessageDialog = false; + emit telemetryMessage(global::keyboard::keyboardText); + global::keyboard::keyboardText = ""; + log("No message to be sent along with collected data", className); + } + GeneralDialog::close(); + } +} + +void GeneralDialog::on_okBtn_clicked() { + log("OK button clicked", className); + if (resetDialog == true) { + if (checkconfig("/opt/inkbox_genuine") == true) { + // Soft-reset the device + // We set a custom boot flag and reboot silently in Diagnostics + log("Setting up the device for soft-reset", className); + writeFile("/external_root/boot/flags/DIAGS_BOOT", "true\n"); + writeFile("/external_root/boot/flags/DO_SOFT_RESET", "true\n"); + reboot(false); + qApp->quit(); + } else { + // Restore default settings, we're not on InkBox OS + log("Restoring default settings", className); + QString prog("sh"); + QStringList args; + args << "reset-config.sh"; + QProcess *proc = new QProcess(); + proc->start(prog, args); + proc->waitForFinished(); + proc->deleteLater(); + + // Relaunching InkBox + QProcess process; + process.startDetached("inkbox.sh", QStringList()); + qApp->quit(); + } + } + if (updateDialog == true) { + if (global::otaUpdate::isUpdateOta == true) { + this->hide(); + + global::otaUpdate::downloadOta = true; + otaManagerWindow = new OTAUpdateManagerWidget(this); + connect(otaManagerWindow, SIGNAL(downloadedOtaUpdate(bool)), SLOT(startOtaUpdate(bool))); + otaManagerWindow->setAttribute(Qt::WA_DeleteOnClose); + + global::toast::indefiniteToast = true; + global::toast::modalToast = true; + emit showToast("Downloading update"); + } else { + installUpdate(); + qApp->quit(); + } + } + if (usbmsDialog == true) { + log("Showing USBMS splash", className); + global::usbms::usbmsDialog = false; + global::usbms::launchUsbms = true; + + usbmsWindow = new USBMSSplashWidget(); + usbmsWindow->setAttribute(Qt::WA_DeleteOnClose); + usbmsWindow->setGeometry(QRect(QPoint(0, 0), screen()->geometry().size())); + usbmsWindow->show(); + } + if (resetKoboxDialog == true) { + resetKoboxUserData(); + } + if (keypadDialog == true) { + int number = global::keyboard::keypadText.toInt(); + emit gotoPageSelected(number); + global::keyboard::keypadDialog = false; + GeneralDialog::close(); + } + if (keyboardDialog == true) { + if (global::keyboard::searchDialog == true) { + if (!global::keyboard::keyboardText.isEmpty()) { + if (ui->searchComboBox->currentText() == "Dictionary") { + writeFile("/inkbox/searchComboBoxFunction", "Dictionary"); + for (int i = ui->mainStackedWidget->count(); i >= 0; i--) { + QWidget *widget = ui->mainStackedWidget->widget(i); + ui->mainStackedWidget->removeWidget(widget); + widget->deleteLater(); + } + ui->topStackedWidget->setVisible(false); + ui->stackedWidget->setVisible(false); + dictionaryWidgetWindow = new dictionaryWidget(); + dictionaryWidgetWindow->setAttribute(Qt::WA_DeleteOnClose); + connect(dictionaryWidgetWindow, SIGNAL(refreshScreen()), SLOT(refreshScreenNative())); + connect(dictionaryWidgetWindow, SIGNAL(destroyed(QObject *)), SLOT(restartSearchDialog())); + ui->mainStackedWidget->insertWidget(1, dictionaryWidgetWindow); + } else if (ui->searchComboBox->currentText() == "Local storage") { + writeFile("/inkbox/searchComboBoxFunction", "Local storage"); + QString onboardPath; + QStringList storageSearchResults; + if (checkconfig("/opt/inkbox_genuine") == true) { + onboardPath = "/mnt/onboard/onboard/"; + } else { + onboardPath = "/mnt/onboard/"; + } + QDirIterator dirIt(onboardPath, QDirIterator::Subdirectories); + log("Searching local storage for '" + global::keyboard::keyboardText + "'", className); + while (dirIt.hasNext()) { + dirIt.next(); + if (QFileInfo(dirIt.filePath()).isFile()) { + QString suffix = QFileInfo(dirIt.filePath()).suffix(); + if (suffix == "txt" or suffix == "TXT" or suffix == "epub" or suffix == "EPUB" or suffix == "pdf" or suffix == "PDF" or suffix == "png" or suffix == "PNG" or suffix == "tif" or suffix == "TIF" or suffix == "bmp" or suffix == "BMP" or suffix == "tiff" or suffix == "TIFF" or suffix == "jpg" or suffix == "JPG" or suffix == "jpeg" or suffix == "JPEG") { + if (dirIt.fileName().contains(global::keyboard::keyboardText) == true) { + storageSearchResults.append(dirIt.fileName()); + global::localStorage::searchResultsPaths.append(dirIt.filePath()); + } + } + } + } + if (!storageSearchResults.isEmpty()) { + log("Displaying search results", className); + for (int i = ui->mainStackedWidget->count(); i >= 0; i--) { + QWidget *widget = ui->mainStackedWidget->widget(i); + ui->mainStackedWidget->removeWidget(widget); + widget->deleteLater(); + } + ui->topStackedWidget->setVisible(false); + ui->stackedWidget->setVisible(false); + searchResultsWidgetWindow = new searchResultsWidget(this); + searchResultsWidgetWindow->setAttribute(Qt::WA_DeleteOnClose); + global::forbidOpenSearchDialog = true; + connect(searchResultsWidgetWindow, SIGNAL(destroyed(QObject *)), SLOT(restartSearchDialog())); + connect(searchResultsWidgetWindow, SIGNAL(openBookFile(QString, bool)), SLOT(openBookFileNative(QString, bool))); + searchResultsWidgetWindow->setListViewContents(storageSearchResults); + ui->mainStackedWidget->insertWidget(1, searchResultsWidgetWindow); + } else { + log("No search results found", className); + global::toast::delay = 3000; + emit showToast("No results found"); + keyboardWidget->clearLineEdit(); + global::keyboard::keyboardText = ""; + } + } else if (ui->searchComboBox->currentText() == "Online library") { + if (Device::getSingleton()->supportsWifi()) { + writeFile("/inkbox/searchComboBoxFunction", "Online library"); + log("Searching online library for '" + global::keyboard::keyboardText + "'", className); + + if (!readFile("/external_root/opt/storage/gutenberg/last_sync").isEmpty()) { + unsigned long currentEpoch = QDateTime::currentSecsSinceEpoch(); + unsigned long syncEpoch = readFile("/external_root/opt/storage/gutenberg/last_sync").toULong(); + unsigned long allowSyncEpoch = syncEpoch + 86400; + if (currentEpoch > allowSyncEpoch) { + syncGutenbergCatalog(); + } else { + noGutenbergSyncToDo = true; + } + } else { + syncGutenbergCatalog(); + } + + QTimer *searchTimer = new QTimer(this); + searchTimer->setInterval(100); + connect(searchTimer, &QTimer::timeout, [&]() { + if (noGutenbergSyncToDo == true or (gutenbergSyncDone == true && gutenbergSyncStatus == true)) { + if (searchTimerDone == false) { + searchTimerDone = true; + writeFile("/inkbox/gutenberg_search_request", global::keyboard::keyboardText); + writeFile("/opt/ibxd", "gutenberg_search\n"); + global::toast::modalToast = true; + global::toast::indefiniteToast = true; + emit showToast("Searching"); + QTimer::singleShot(100, this, SLOT(waitForGutenbergSearchDone())); + } + } + }); + searchTimer->start(); + } else { + emit showToast("Wi-Fi connection error"); + } + } + } else { + global::toast::delay = 3000; + emit showToast("Please type in a search term"); + } + } else if (global::keyboard::vncDialog == true) { + if (!global::keyboard::keyboardText.isEmpty()) { + log("Gathering VNC connection information", className); + if (vncServerSet != true) { + vncServerAddress = global::keyboard::keyboardText; + vncServerSet = true; + keyboardWidget->clearLineEdit(); + ui->headerLabel->setText("Enter the server's password"); + } else if (vncPasswordSet != true) { + vncServerPassword = global::keyboard::keyboardText; + vncPasswordSet = true; + keyboardWidget->clearLineEdit(); + ui->headerLabel->setText("Enter the server's port"); + } else { + vncServerPort = global::keyboard::keyboardText; + global::keyboard::vncDialog = false; + global::keyboard::keyboardDialog = false; + startVNC(vncServerAddress, vncServerPassword, vncServerPort); + GeneralDialog::close(); + } + } else { + global::toast::delay = 3000; + emit showToast("Please type in the required argument"); + } + } else if (global::keyboard::wifiPassphraseDialog == true) { + if (!global::keyboard::keyboardText.isEmpty()) { + if (global::keyboard::keyboardText.count() < 8) { + global::toast::delay = 3000; + showToast("Minimum passphrase length is 8 characters"); + } else { + GeneralDialog::close(); + } + } else { + global::toast::delay = 3000; + showToast("Please type in the required argument"); + } + } else if (global::keyboard::encfsDialog == true) { + if (!global::keyboard::keyboardText.isEmpty()) { + global::encfs::passphrase = global::keyboard::keyboardText; + global::keyboard::encfsDialog = false; + global::keyboard::keyboardText = ""; + global::keyboard::keyboardDialog = false; + this->close(); + } else { + global::toast::delay = 3000; + showToast("Please type in the required argument"); + } + } else if (global::keyboard::telemetryMessageDialog == true) { + if (!global::keyboard::keyboardText.isEmpty()) { + emit telemetryMessage(global::keyboard::keyboardText); + log("Message to be sent along with collected data is: " + global::keyboard::keyboardText, className); + global::keyboard::keyboardText = ""; + global::keyboard::telemetryMessageDialog = false; + global::keyboard::keyboardDialog = false; + this->close(); + } else { + global::toast::delay = 3000; + showToast("Please type in the required argument"); + } + } else { + global::keyboard::keyboardDialog = false; + GeneralDialog::close(); + } + } + if (global::encfs::disableStorageEncryptionDialog == true) { + global::encfs::disableStorageEncryptionDialog = false; + emit disableStorageEncryption(); + this->close(); + } + if (global::encfs::repackDialog == true) { + global::encfs::repackDialog = false; + log("Encrypted storage repack requested", className); + writeFile("/external_root/run/encfs_repack", "true"); + quit_restart(); + } else if (global::userApps::appCompatibilityDialog == true) { + global::userApps::launchApp = true; + global::userApps::appCompatibilityText = ""; + global::userApps::appCompatibilityLastContinueStatus = true; // Not really necessary, only needed if something fails horribly + global::userApps::appCompatibilityDialog = false; + GeneralDialog::close(); + } else if (global::library::librarySyncDialog == true) { + emit syncOnlineLibrary(); + global::library::librarySyncDialog = false; + GeneralDialog::close(); + } else if (global::telemetry::telemetryDialog == true) { + global::telemetry::telemetryDialog = false; + global::keyboard::telemetryMessageDialog = true; + GeneralDialog::close(); + } +} +void GeneralDialog::on_acceptBtn_clicked() { + log("OK button clicked", className); + if (lowBatteryDialog == true) { + global::mainwindow::lowBatteryDialog = false; + global::battery::batteryAlertLock = false; + global::battery::showLowBatteryDialog = false; + } + + if (settingsRebootDialog == true) { + if (koboxSettingsRebootDialog == true or global::encfs::enableStorageEncryptionDialog) { + reboot(true); + qApp->quit(); + } else { + QProcess process; + process.startDetached("inkbox.sh", QStringList()); + qApp->quit(); + } + } + if (textBrowserDialog == true) { + global::text::textBrowserContents = ""; + global::text::textBrowserTitle = ""; + global::text::textBrowserDialog = false; + } + + if (appInfoDialog == true) { + global::text::textBrowserContents = ""; + global::text::textBrowserTitle = ""; + global::userApps::appInfoDialog = false; + } + + // We don't have any other option ;p + GeneralDialog::close(); +} + +void GeneralDialog::adjust_size() { + float widthProportion = 2; + float heightProportion = 2; + if (telemetryDialog) { + Device::ScreenSize screenSize = Device::getSingleton()->getScreenSize(); + if (screenSize == Device::ScreenSize::SMALL) { + widthProportion = 3.3; + heightProportion = 2.6; + } else if (screenSize == Device::ScreenSize::MEDIUM) { + widthProportion = 3.4; + heightProportion = 2.6; + } else if (screenSize == Device::ScreenSize::LARGE) { + widthProportion = 3.4; + heightProportion = 2.6; + } else if (screenSize == Device::ScreenSize::VERY_LARGE) { + widthProportion = 3; + heightProportion = 2.6; + } + } + + this->adjustSize(); + QRect screenGeometry = QGuiApplication::screens()[0]->geometry(); + int x = (screenGeometry.width() - this->width()) / widthProportion; + int y = (screenGeometry.height() - this->height()) / heightProportion; + this->move(x, y); + this->show(); + emit refreshScreen(); +} + +void GeneralDialog::restartSearchDialog() { + GeneralDialog::close(); +} + +void GeneralDialog::setupKeyboardDialog() { + adjust_size(); + ui->stackedWidget->setCurrentIndex(0); + keyboardDialog = true; + ui->stackedWidget->setVisible(true); + if (global::keyboard::searchDialog == true) { + ui->topStackedWidget->setCurrentIndex(1); + ui->searchHeaderLabel->setText("Search"); + ui->okBtn->setText("Search"); + ui->cancelBtn->setText("Close"); + } else if (global::keyboard::vncDialog == true) { + ui->headerLabel->setText("Enter the server's IP address"); + ui->okBtn->setText("OK"); + ui->cancelBtn->setText("Cancel"); + } else if (global::keyboard::wifiPassphraseDialog == true) { + ui->headerLabel->setText("Enter the network's passphrase"); + ui->okBtn->setText("Enter"); + ui->cancelBtn->setText("Cancel"); + } else if (global::keyboard::encfsDialog == true) { + ui->headerLabel->setText("Enter your encrypted storage's passphrase"); + ui->okBtn->setText("OK"); + ui->cancelBtn->setText("Cancel"); + } else if (global::keyboard::telemetryMessageDialog == true) { + ui->headerLabel->setWordWrap(true); + ui->headerLabel->setText("If you'd like, feel free to send us a random message along with the collected data"); + ui->okBtn->setText("Continue"); + ui->cancelBtn->setText("No, thanks"); + } else { + ui->headerLabel->setText("Enter a string"); + ui->okBtn->setText("OK"); + ui->cancelBtn->setText("Cancel"); + } + keyboardWidget = new virtualkeyboard(); + connect(keyboardWidget, SIGNAL(adjust_size()), SLOT(adjust_size())); + ui->mainStackedWidget->insertWidget(1, keyboardWidget); + ui->mainStackedWidget->setCurrentIndex(1); + adjust_size(); + QTimer::singleShot(1000, this, SLOT(adjust_size())); +} + +void GeneralDialog::refreshScreenNative() { + emit refreshScreen(); +} + +void GeneralDialog::startVNC(QString server, QString password, QString port) { + log("Launching VNC viewer", className); + writeFile("/external_root/tmp/app_vnc_server", server); + writeFile("/external_root/tmp/app_vnc_password", password); + writeFile("/external_root/tmp/app_vnc_port", port); + writeFile("/opt/ibxd", "app_start_vnc\n"); + qApp->quit(); +} + +void GeneralDialog::startOtaUpdate(bool wasDownloadSuccessful) { + emit closeIndefiniteToast(); + if (wasDownloadSuccessful == true) { + global::otaUpdate::isUpdateOta = false; + installUpdate(); + qApp->quit(); + } else { + emit showToast("Download failed"); + global::otaUpdate::isUpdateOta = false; + } + GeneralDialog::close(); +} + +void GeneralDialog::openBookFileNative(QString book, bool relativePath) { + emit openBookFile(book, relativePath); +} + +void GeneralDialog::showToastNative(QString messageToDisplay) { + emit showToast(messageToDisplay); +} + +void GeneralDialog::closeIndefiniteToastNative() { + emit closeIndefiniteToast(); +} + +void GeneralDialog::quit_restart() { + log("Restarting InkBox", className); + // If existing, cleaning bookconfig_mount mountpoint + writeFile("/opt/ibxd", "bookconfig_unmount\n"); + + // Restarting InkBox + QProcess process; + process.startDetached("inkbox", QStringList()); + qApp->quit(); +} + +void GeneralDialog::syncGutenbergCatalog() { + log("Syncing Gutenberg catalog", className); + global::toast::modalToast = true; + global::toast::indefiniteToast = true; + emit showToast("Sync in progress"); + + writeFile("/opt/ibxd", "gutenberg_sync\n"); + QTimer *syncCheckTimer = new QTimer(this); + syncCheckTimer->setInterval(500); + connect(syncCheckTimer, &QTimer::timeout, [&]() { + if (QFile::exists("/inkbox/gutenbergSyncDone") == true) { + if (checkconfig("/inkbox/gutenbergSyncDone") == true) { + log("Gutenberg sync successfully completed", className); + gutenbergSyncDone = true; + gutenbergSyncStatus = true; + emit closeIndefiniteToast(); + } else { + log("Gutenberg sync encountered an error", className); + gutenbergSyncDone = true; + gutenbergSyncStatus = false; + emit closeIndefiniteToast(); + emit showToast("Error"); + global::keyboard::searchDialog = false; + global::forbidOpenSearchDialog = true; + global::keyboard::keyboardDialog = false; + global::keyboard::keyboardText = ""; + global::library::librarySearchDialog = false; + QTimer::singleShot(5000, this, SLOT(close())); + } + QFile::remove("/inkbox/gutenbergSyncDone"); + } + }); + syncCheckTimer->start(); +} + +void GeneralDialog::waitForGutenbergSearchDone() { + while (true) { + if (QFile::exists("/inkbox/gutenberg-search/search_done")) { + if (checkconfig("/inkbox/gutenberg-search/search_done") == true) { + QList searchResults = readFile("/inkbox/gutenberg-search/search_results_titles").split("\n"); + searchResults.takeLast(); + global::library::libraryResults = true; + + for (int i = ui->mainStackedWidget->count(); i >= 0; i--) { + QWidget *widget = ui->mainStackedWidget->widget(i); + ui->mainStackedWidget->removeWidget(widget); + widget->deleteLater(); + } + ui->topStackedWidget->setVisible(false); + ui->stackedWidget->setVisible(false); + searchResultsWidgetWindow = new searchResultsWidget(this); + searchResultsWidgetWindow->setAttribute(Qt::WA_DeleteOnClose); + global::forbidOpenSearchDialog = true; + connect(searchResultsWidgetWindow, SIGNAL(destroyed(QObject *)), SLOT(restartSearchDialog())); + connect(searchResultsWidgetWindow, SIGNAL(showToast(QString)), SLOT(showToastNative(QString))); + connect(searchResultsWidgetWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToastNative())); + connect(searchResultsWidgetWindow, SIGNAL(hideDialog()), SLOT(hide())); + searchResultsWidgetWindow->setListViewContents(searchResults); + ui->mainStackedWidget->insertWidget(1, searchResultsWidgetWindow); + QFile::remove("/inkbox/gutenberg-search/search_done"); + emit closeIndefiniteToast(); + break; + } else { + emit closeIndefiniteToast(); + global::toast::delay = 3000; + global::toast::modalToast = true; + emit showToast("No results found"); + keyboardWidget->clearLineEdit(); + global::keyboard::keyboardText = ""; + QFile::remove("/inkbox/gutenberg-search/search_done"); + QTimer::singleShot(3000, this, SLOT(close())); + break; + } + } + QThread::msleep(500); + } +} + +void GeneralDialog::increaseSize() { + log("Resizing", className); + + ui->topStackedWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + ui->mainStackedWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); + ui->stackedWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + + QRect screenGeometry = QGuiApplication::screens()[0]->geometry(); + int wx = screenGeometry.width(); + + int x = wx - 25; + int y = this->height() * yIncrease; + this->setFixedWidth(x); + this->setFixedHeight(y); + + ui->bodyLabel->sizePolicy().setVerticalPolicy(QSizePolicy::Expanding); + ui->bodyLabel->sizePolicy().setHorizontalPolicy(QSizePolicy::Expanding); + + adjust_size(); +} diff --git a/src/widgets/dialogs/generaldialog.h b/src/ui/widgets/dialogs/generaldialog.h similarity index 91% rename from src/widgets/dialogs/generaldialog.h rename to src/ui/widgets/dialogs/generaldialog.h index d2614aa..2fd3d83 100644 --- a/src/widgets/dialogs/generaldialog.h +++ b/src/ui/widgets/dialogs/generaldialog.h @@ -14,17 +14,17 @@ using namespace std; namespace Ui { -class generalDialog; +class GeneralDialog; } -class generalDialog : public QDialog +class GeneralDialog : public QDialog { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit generalDialog(QWidget *parent = nullptr); - ~generalDialog(); + explicit GeneralDialog(QWidget *parent = nullptr); + ~GeneralDialog(); bool resetDialog = false; bool updateDialog = false; bool settingsRebootDialog = false; @@ -74,13 +74,13 @@ private slots: void waitForGutenbergSearchDone(); private: - Ui::generalDialog *ui; - usbmsSplash *usbmsWindow; + Ui::GeneralDialog *ui; + USBMSSplashWidget *usbmsWindow; textwidget *textwidgetWindow; virtualkeyboard *keyboardWidget; virtualkeypad *keypadWidget; dictionaryWidget *dictionaryWidgetWindow; - otaManager *otaManagerWindow; + OTAUpdateManagerWidget *otaManagerWindow; searchResultsWidget * searchResultsWidgetWindow; signals: diff --git a/src/widgets/dialogs/generaldialog.ui b/src/ui/widgets/dialogs/generaldialog.ui similarity index 99% rename from src/widgets/dialogs/generaldialog.ui rename to src/ui/widgets/dialogs/generaldialog.ui index 1923556..71f8347 100644 --- a/src/widgets/dialogs/generaldialog.ui +++ b/src/ui/widgets/dialogs/generaldialog.ui @@ -1,7 +1,7 @@ - generalDialog - + GeneralDialog + 0 diff --git a/src/ui/widgets/dialogs/kobox/koboxappsdialog.cpp b/src/ui/widgets/dialogs/kobox/koboxappsdialog.cpp new file mode 100644 index 0000000..bc44eab --- /dev/null +++ b/src/ui/widgets/dialogs/kobox/koboxappsdialog.cpp @@ -0,0 +1,138 @@ +#include "koboxappsdialog.h" +#include "ui_koboxappsdialog.h" + +#include "device.h" +#include "functions.h" + +#include "ui.h" +#include +#include +#include +#include +#include +#include + +KoboxAppsDialog::KoboxAppsDialog(QWidget *parent) : + QDialog(parent), + ui(new Ui::KoboxAppsDialog) { + ui->setupUi(this); + ui->definitionLabel->setFont(QFont("u001")); + ui->appsList->setFont(QFont("u001")); + + // Preventing outside interaction + this->setModal(true); + + // Stylesheet, style & misc. + UI::applyStyle(*this, "eink"); + + ui->definitionLabel->setText("Please select an application.\nClick on 'Launch' to start it."); + + ui->launchBtn->setProperty("type", "borderless"); + ui->cancelBtn->setProperty("type", "borderless"); + ui->launchBtn->setStyleSheet("font-size: 9pt; padding: 10px; font-weight: bold; background: lightGrey"); + ui->cancelBtn->setStyleSheet("font-size: 9pt; padding: 10px; font-weight: bold; background: lightGrey"); + ui->appsList->setStyleSheet("font-size: 9pt"); + ui->definitionLabel->setStyleSheet("font-size: 9.5pt"); + ui->headerLabel->setStyleSheet("font-weight: bold"); + + this->adjustSize(); + + // Centering dialog + QRect screenGeometry = QGuiApplication::screens()[0]->geometry(); + int x = (screenGeometry.width() - this->width()) / 2; + int y = (screenGeometry.height() - this->height()) / 2; + this->move(x, y); + + checkApps(); + QStringListModel *model = new QStringListModel(this); + QStringList list = apps.split("\n", QString::SkipEmptyParts); + + // Apps that aren't extensions + list.prepend("Geany"); + + if (checkconfig("/external_root/opt/root/rooted") == true) { + list.prepend("KTerm"); + } + + model->setStringList(list); + ui->appsList->setModel(model); + ui->appsList->setEditTriggers(QAbstractItemView::NoEditTriggers); +} + +void KoboxAppsDialog::checkApps() { + QFile apps_list("/external_root/opt/X11/extensions_list"); + apps_list.open(QIODevice::ReadWrite); + QTextStream in(&apps_list); + apps = in.readAll(); + apps_list.close(); +} + +KoboxAppsDialog::~KoboxAppsDialog() { + delete ui; +} + +void KoboxAppsDialog::on_cancelBtn_clicked() { + KoboxAppsDialog::close(); +} + +void KoboxAppsDialog::on_launchBtn_clicked() { + index = ui->appsList->currentIndex(); + itemText = index.data(Qt::DisplayRole).toString(); + if (itemText.isEmpty()) { + emit showToast("Please select an application"); + } else { + // DPI setting + QString initialDpiSetting = readFile(".config/00-kobox/dpiSetting"); + int dpi; + if (initialDpiSetting.isEmpty()) { + dpi = Device::getSingleton()->getBaseDPI(); + } else { + dpi = initialDpiSetting.toInt(); + } + + // Fullscreen or windowed (i3) + // Mostly windowed except for apps like KTerm which ship their own OSK + dpModeSetting = "windowed"; + + if (itemText == "Netsurf") { + log("Launching KoBox app: NetSurf", className); + // Bypass standard shell script launch shenanigans + writeFile("/external_root/tmp/X_program", "!netsurf"); + } else if (itemText == "KTerm") { + log("Launching KoBox app: KTerm", className); + writeFile("/external_root/tmp/X_program", "/usr/local/bin/kterm -l /usr/local/share/kterm/layouts/keyboard-kt.xml -k 1"); + dpModeSetting = "fullscreen"; + dpi += 50; + } else if (itemText == "Geany") { + log("Launching KoBox app: Geany", className); + writeFile("/external_root/tmp/X_program", "geany"); + } else { + log("Launching KoBox app: " + itemText, className); + QString app = itemText.toLower(); + writeFile("/external_root/tmp/X_program", app); + } + + writeFile("/external_root/tmp/X_dpmode", dpModeSetting); + writeFile("/external_root/tmp/X_dpi", QString(dpi)); + + /* Wheeee! */ + global::kobox::showKoboxSplash = true; + + // Re-use USBMS splash window for KoBox splash, since it's pretty much the same layout + log("Showing KoBox splash", className); + usbmsSplashWindow = new USBMSSplashWidget(); + usbmsSplashWindow->setAttribute(Qt::WA_DeleteOnClose); + usbmsSplashWindow->setGeometry(QRect(QPoint(0, 0), screen()->geometry().size())); + usbmsSplashWindow->show(); + QApplication::processEvents(); + + // Stop EncFS/Encrypted storage + if (checkconfig("/external_root/run/encfs_mounted") == true) { + writeFile("/external_root/run/encfs_stop_cleanup", "true"); + writeFile("/opt/ibxd", "encfs_stop\n"); + } + + // Write to FIFO to start X11 + writeFile("/opt/ibxd", "x_start_gui\n"); + } +} diff --git a/src/widgets/dialogs/kobox/koboxappsdialog.h b/src/ui/widgets/dialogs/kobox/koboxappsdialog.h similarity index 71% rename from src/widgets/dialogs/kobox/koboxappsdialog.h rename to src/ui/widgets/dialogs/kobox/koboxappsdialog.h index fda20be..43ce5c4 100644 --- a/src/widgets/dialogs/kobox/koboxappsdialog.h +++ b/src/ui/widgets/dialogs/kobox/koboxappsdialog.h @@ -7,17 +7,17 @@ #include "usbmsSplash.h" namespace Ui { -class koboxAppsDialog; +class KoboxAppsDialog; } -class koboxAppsDialog : public QDialog +class KoboxAppsDialog : public QDialog { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit koboxAppsDialog(QWidget *parent = nullptr); - ~koboxAppsDialog(); + explicit KoboxAppsDialog(QWidget *parent = nullptr); + ~KoboxAppsDialog(); void checkApps(); @@ -35,8 +35,8 @@ signals: void showToast(QString messageToDisplay); private: - Ui::koboxAppsDialog *ui; - usbmsSplash *usbmsSplashWindow; + Ui::KoboxAppsDialog *ui; + USBMSSplashWidget *usbmsSplashWindow; }; #endif // KOBOXAPPSDIALOG_H diff --git a/src/widgets/dialogs/kobox/koboxappsdialog.ui b/src/ui/widgets/dialogs/kobox/koboxappsdialog.ui similarity index 96% rename from src/widgets/dialogs/kobox/koboxappsdialog.ui rename to src/ui/widgets/dialogs/kobox/koboxappsdialog.ui index 9699ea6..68c1b12 100644 --- a/src/widgets/dialogs/kobox/koboxappsdialog.ui +++ b/src/ui/widgets/dialogs/kobox/koboxappsdialog.ui @@ -1,7 +1,7 @@ - koboxAppsDialog - + KoboxAppsDialog + Qt::NonModal diff --git a/src/ui/widgets/dialogs/library/bookinfodialog.cpp b/src/ui/widgets/dialogs/library/bookinfodialog.cpp new file mode 100644 index 0000000..c6b906e --- /dev/null +++ b/src/ui/widgets/dialogs/library/bookinfodialog.cpp @@ -0,0 +1,174 @@ +#include "bookinfodialog.h" +#include "functions.h" +#include "ui.h" +#include "ui_bookinfodialog.h" + +#include + +BookInfoDialog::BookInfoDialog(QWidget *parent) : + QDialog(parent), + ui(new Ui::BookInfoDialog) { + ui->setupUi(this); + + // Preventing outside interaction + this->setModal(true); + + // Stylesheet + UI::applyStyle(*this, "eink"); + + ui->closeBtn->setProperty("type", "borderless"); + ui->closeBtn->setText(""); + ui->closeBtn->setIcon(QIcon(":/resources/close.png")); + ui->bookCoverLabel->setText(""); + ui->getBtn->setStyleSheet("background: lightGrey; font-size: 9pt; padding: 8px"); + + // Getting the screen's size + sW = QGuiApplication::screens()[0]->size().width(); + sH = QGuiApplication::screens()[0]->size().height(); + + // Setting icons up + stdIconWidth = sW / 4; + stdIconHeight = sH / 4; + + if (global::bookInfoDialog::localInfoDialog == false) { + if (global::library::isLatestBook == true) { + QString bookNumberQstr = QString::number(global::library::latestBookNumber); + + QString coverPath = "/mnt/onboard/onboard/.inkbox/gutenberg-data/latest-books/"; + coverPath = coverPath.append(bookNumberQstr); + coverPath = coverPath.append("/cover.jpg"); + + QString idPath = "/mnt/onboard/onboard/.inkbox/gutenberg-data/latest-books/"; + idPath = idPath.append(bookNumberQstr); + idPath = idPath.append("/id"); + global::library::bookId = readFile(idPath).toULong(); + + QPixmap coverPixmap(coverPath); + QPixmap scaledCoverPixmap = coverPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->bookCoverLabel->setPixmap(scaledCoverPixmap); + global::library::isLatestBook = false; + + ui->bookTitleLabel->setText(global::library::bookTitle); + } else { + ui->bookTitleLabel->setText(global::library::bookTitle); + + QDir gutenbergDir; + gutenbergDir.mkpath("/inkbox/gutenberg"); + writeFile("/inkbox/gutenberg/bookid", QString::number(global::library::bookId)); + writeFile("/opt/ibxd", "gutenberg_get_cover\n"); + while (true) { + if (QFile::exists("/inkbox/gutenberg/getCoverDone")) { + if (checkconfig("/inkbox/gutenberg/getCoverDone") == true) { + QPixmap coverPixmap("/inkbox/gutenberg/book_cover.jpg"); + QPixmap scaledCoverPixmap = coverPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->bookCoverLabel->setPixmap(scaledCoverPixmap); + QFile::remove("/inkbox/gutenberg/getCoverDone"); + break; + } else { + QPixmap coverPixmap(":/resources/cover_unavailable.png"); + QPixmap scaledCoverPixmap = coverPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); + ui->bookCoverLabel->setPixmap(scaledCoverPixmap); + QFile::remove("/inkbox/gutenberg/getCoverDone"); + break; + } + } + } + } + + log("Setting up book info dialog, ID: " + QString::number(global::library::bookId) + ", title: " + global::library::bookTitle, className); + } else { + if (global::localLibrary::bookOptionsDialog::bookID != global::localLibrary::folderID) { + QJsonObject bookJsonObject = getBookMetadata(global::localLibrary::bookOptionsDialog::bookID); + QString bookInfo; + QString title = bookJsonObject["Title"].toString(); + QString author = bookJsonObject["Author"].toString(); + QString publicationDate = bookJsonObject["PublicationDate"].toString(); + QString path = bookJsonObject["BookPath"].toString(); + if (!title.isEmpty()) { + bookInfo.append("Title: " + title + "
"); + } + if (!author.isEmpty()) { + bookInfo.append("Author: " + author + "
"); + } + if (!publicationDate.isEmpty()) { + bookInfo.append("Publication date: " + publicationDate + "
"); + } + if (!path.isEmpty()) { + bookInfo.append("Path: " + path + "
"); + } + global::text::textBrowserContents = bookInfo; + } else { + QString bookInfo = "Path: " + global::localLibrary::bookOptionsDialog::folderPath; + global::text::textBrowserContents = bookInfo; + } + textwidget *textwidgetWindow = new textwidget(this); + ui->stackedWidget->insertWidget(1, textwidgetWindow); + ui->stackedWidget->setCurrentIndex(1); + } + + QRect screenGeometry = QGuiApplication::screens()[0]->geometry(); + { + int wx = screenGeometry.width(); + + int x = wx - 25; + int y = this->height() * determineYIncrease(); + this->setFixedWidth(x); + this->setFixedHeight(y); + + this->adjustSize(); + } + + // Centering dialog + int x = (screenGeometry.width() - this->width()) / 2; + int y = (screenGeometry.height() - this->height()) / 2; + this->move(x, y); +} + +BookInfoDialog::~BookInfoDialog() { + delete ui; +} + +void BookInfoDialog::on_closeBtn_clicked() { + global::library::bookTitle = ""; + global::bookInfoDialog::localInfoDialog = false; + BookInfoDialog::close(); +} + +void BookInfoDialog::on_getBtn_clicked() { + QDir gutenbergDir; + gutenbergDir.mkpath("/inkbox/gutenberg"); + writeFile("/inkbox/gutenberg/bookid", QString::number(global::library::bookId)); + writeFile("/inkbox/gutenberg/booktitle", global::library::bookTitle); + writeFile("/opt/ibxd", "gutenberg_get_book\n"); + + global::toast::modalToast = true; + global::toast::indefiniteToast = true; + log("Downloading book, ID: " + QString::number(global::library::bookId) + ", title: " + global::library::bookTitle, className); + emit showToast("Downloading"); + + QTimer::singleShot(500, this, SLOT(waitForBookFetch())); +} + +void BookInfoDialog::waitForBookFetch() { + while (true) { + if (QFile::exists("/inkbox/gutenberg/getBookDone")) { + if (checkconfig("/inkbox/gutenberg/getBookDone") == true) { + emit closeIndefiniteToast(); + QString function = __func__; + log(function + ": Download successful", className); + emit showToast("Download successful"); + QFile::remove("/inkbox/gutenberg/getBookDone"); + QFile::remove(global::localLibrary::databasePath); + break; + } else { + emit closeIndefiniteToast(); + QString function = __func__; + log(function + ": Download failed", className); + emit showToast("Download failed"); + QFile::remove("/inkbox/gutenberg/getBookDone"); + break; + } + } + QThread::msleep(500); + } +} diff --git a/src/widgets/dialogs/library/bookinfodialog.h b/src/ui/widgets/dialogs/library/bookinfodialog.h similarity index 76% rename from src/widgets/dialogs/library/bookinfodialog.h rename to src/ui/widgets/dialogs/library/bookinfodialog.h index 2229354..690220e 100644 --- a/src/widgets/dialogs/library/bookinfodialog.h +++ b/src/ui/widgets/dialogs/library/bookinfodialog.h @@ -6,17 +6,17 @@ #include "textwidget.h" namespace Ui { -class bookInfoDialog; +class BookInfoDialog; } -class bookInfoDialog : public QDialog +class BookInfoDialog : public QDialog { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit bookInfoDialog(QWidget *parent = nullptr); - ~bookInfoDialog(); + explicit BookInfoDialog(QWidget *parent = nullptr); + ~BookInfoDialog(); float sH; float sW; float stdIconHeight; @@ -32,7 +32,7 @@ signals: void closeIndefiniteToast(); private: - Ui::bookInfoDialog * ui; + Ui::BookInfoDialog * ui; textwidget * textwidgetWindow; }; diff --git a/src/widgets/dialogs/library/bookinfodialog.ui b/src/ui/widgets/dialogs/library/bookinfodialog.ui similarity index 98% rename from src/widgets/dialogs/library/bookinfodialog.ui rename to src/ui/widgets/dialogs/library/bookinfodialog.ui index fc507fb..ee4f919 100644 --- a/src/widgets/dialogs/library/bookinfodialog.ui +++ b/src/ui/widgets/dialogs/library/bookinfodialog.ui @@ -1,7 +1,7 @@ - bookInfoDialog - + BookInfoDialog + 0 diff --git a/src/widgets/dialogs/library/bookoptionsdialog.cpp b/src/ui/widgets/dialogs/library/bookoptionsdialog.cpp similarity index 94% rename from src/widgets/dialogs/library/bookoptionsdialog.cpp rename to src/ui/widgets/dialogs/library/bookoptionsdialog.cpp index 9e061b3..37ee3ec 100644 --- a/src/widgets/dialogs/library/bookoptionsdialog.cpp +++ b/src/ui/widgets/dialogs/library/bookoptionsdialog.cpp @@ -3,9 +3,9 @@ #include "functions.h" -bookOptionsDialog::bookOptionsDialog(QWidget *parent) : +BookOptionsDialog::BookOptionsDialog(QWidget *parent) : QDialog(parent), - ui(new Ui::bookOptionsDialog) + ui(new Ui::BookOptionsDialog) { ui->setupUi(this); ui->pinBtn->setProperty("type", "borderless"); @@ -59,12 +59,12 @@ bookOptionsDialog::bookOptionsDialog(QWidget *parent) : this->adjustSize(); } -bookOptionsDialog::~bookOptionsDialog() +BookOptionsDialog::~BookOptionsDialog() { delete ui; } -void bookOptionsDialog::on_pinBtn_clicked() +void BookOptionsDialog::on_pinBtn_clicked() { if(bookPinned == false) { pinBook(global::localLibrary::bookOptionsDialog::bookID); @@ -74,7 +74,7 @@ void bookOptionsDialog::on_pinBtn_clicked() } } -void bookOptionsDialog::on_deleteBtn_clicked() +void BookOptionsDialog::on_deleteBtn_clicked() { if(isFolder == true) { deleteFolder(); @@ -84,7 +84,7 @@ void bookOptionsDialog::on_deleteBtn_clicked() } } -void bookOptionsDialog::deleteBook() { +void BookOptionsDialog::deleteBook() { log("Deleting book '" + bookPath + "'", className); global::toast::delay = 3000; if(QFile::remove(bookPath)) { @@ -97,7 +97,7 @@ void bookOptionsDialog::deleteBook() { } } -void bookOptionsDialog::deleteFolder() { +void BookOptionsDialog::deleteFolder() { log("Removing empty directory '" + global::localLibrary::bookOptionsDialog::folderPath + "'", className); if(QDir(global::localLibrary::bookOptionsDialog::folderPath).isEmpty() == true) { global::toast::delay = 3000; @@ -111,12 +111,12 @@ void bookOptionsDialog::deleteFolder() { } -void bookOptionsDialog::on_infoBtn_clicked() +void BookOptionsDialog::on_infoBtn_clicked() { emit openLocalBookInfoDialog(); } -void bookOptionsDialog::pinBook(int bookID) { +void BookOptionsDialog::pinBook(int bookID) { QJsonObject pinnedBooksObject; if(QFile::exists(global::localLibrary::pinnedBooksDatabasePath)) { QString function = __func__; log(function + ": Reading pinned books database", className); @@ -185,7 +185,7 @@ void bookOptionsDialog::pinBook(int bookID) { writeFile(global::localLibrary::pinnedBooksDatabasePath, qCompress(QJsonDocument(pinnedBooksObject).toJson()).toBase64()); } -void bookOptionsDialog::unpinBook(int bookID) { +void BookOptionsDialog::unpinBook(int bookID) { QJsonObject pinnedBooksObject; QString function = __func__; log(function + ": Reading pinned books database", className); QFile database(global::localLibrary::pinnedBooksDatabasePath); @@ -232,7 +232,7 @@ void bookOptionsDialog::unpinBook(int bookID) { writeFile(global::localLibrary::pinnedBooksDatabasePath, qCompress(QJsonDocument(pinnedBooksObject).toJson()).toBase64()); } -bool bookOptionsDialog::isBookPinned(int bookID) { +bool BookOptionsDialog::isBookPinned(int bookID) { QJsonObject pinnedBooksObject; if(QFile::exists(global::localLibrary::pinnedBooksDatabasePath)) { QString function = __func__; log(function + ": Reading pinned books database", className); @@ -260,7 +260,7 @@ bool bookOptionsDialog::isBookPinned(int bookID) { return bookPinned; } -void bookOptionsDialog::on_wipeLocalReadingSettingsBtn_clicked() +void BookOptionsDialog::on_wipeLocalReadingSettingsBtn_clicked() { log("Removing local reading settings directory for book '" + bookPath + "' at '/mnt/onboard/onboard/." + bookChecksum + "'", className); QDir dir("/mnt/onboard/onboard/." + bookChecksum); diff --git a/src/widgets/dialogs/library/bookoptionsdialog.h b/src/ui/widgets/dialogs/library/bookoptionsdialog.h similarity index 80% rename from src/widgets/dialogs/library/bookoptionsdialog.h rename to src/ui/widgets/dialogs/library/bookoptionsdialog.h index 725085f..69d78e8 100644 --- a/src/widgets/dialogs/library/bookoptionsdialog.h +++ b/src/ui/widgets/dialogs/library/bookoptionsdialog.h @@ -5,17 +5,17 @@ #include namespace Ui { -class bookOptionsDialog; +class BookOptionsDialog; } -class bookOptionsDialog : public QDialog +class BookOptionsDialog : public QDialog { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit bookOptionsDialog(QWidget *parent = nullptr); - ~bookOptionsDialog(); + explicit BookOptionsDialog(QWidget *parent = nullptr); + ~BookOptionsDialog(); QString bookPath; QString bookChecksum; bool bookPinned; @@ -38,7 +38,7 @@ signals: void removedFolder(); private: - Ui::bookOptionsDialog *ui; + Ui::BookOptionsDialog *ui; }; #endif // BOOKOPTIONSDIALOG_H diff --git a/src/widgets/dialogs/library/bookoptionsdialog.ui b/src/ui/widgets/dialogs/library/bookoptionsdialog.ui similarity index 97% rename from src/widgets/dialogs/library/bookoptionsdialog.ui rename to src/ui/widgets/dialogs/library/bookoptionsdialog.ui index 64172e5..5fad6b4 100644 --- a/src/widgets/dialogs/library/bookoptionsdialog.ui +++ b/src/ui/widgets/dialogs/library/bookoptionsdialog.ui @@ -1,7 +1,7 @@ - bookOptionsDialog - + BookOptionsDialog + 0 diff --git a/src/ui/widgets/dialogs/powerDaemon/sleepdialog.cpp b/src/ui/widgets/dialogs/powerDaemon/sleepdialog.cpp new file mode 100644 index 0000000..167d612 --- /dev/null +++ b/src/ui/widgets/dialogs/powerDaemon/sleepdialog.cpp @@ -0,0 +1,28 @@ +#include "sleepdialog.h" +#include "ui.h" +#include "ui_sleepdialog.h" + +#include "functions.h" + +SleepDialog::SleepDialog(QDialog *parent) : + QDialog(parent), + ui(new Ui::SleepDialog) { + ui->setupUi(this); + + // Stylesheet + UI::applyStyle(*this, "eink"); +} + +SleepDialog::~SleepDialog() { + delete ui; +} + +void SleepDialog::launchSleepDialog() { + log("Launching sleep dialog", className); + this->exec(); +} + +void SleepDialog::hideSleepDialog() { + log("Hiding sleep dialog", className); + this->hide(); +} diff --git a/src/widgets/dialogs/powerDaemon/sleepdialog.h b/src/ui/widgets/dialogs/powerDaemon/sleepdialog.h similarity index 64% rename from src/widgets/dialogs/powerDaemon/sleepdialog.h rename to src/ui/widgets/dialogs/powerDaemon/sleepdialog.h index 981e68f..8201868 100644 --- a/src/widgets/dialogs/powerDaemon/sleepdialog.h +++ b/src/ui/widgets/dialogs/powerDaemon/sleepdialog.h @@ -4,17 +4,17 @@ #include namespace Ui { -class sleepDialog; +class SleepDialog; } -class sleepDialog : public QDialog +class SleepDialog : public QDialog { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit sleepDialog(QDialog *parent = nullptr); - ~sleepDialog(); + explicit SleepDialog(QDialog *parent = nullptr); + ~SleepDialog(); public slots: void launchSleepDialog(); @@ -22,7 +22,7 @@ public slots: private: - Ui::sleepDialog * ui; + Ui::SleepDialog * ui; }; #endif // SLEEPDIALOG_H diff --git a/src/widgets/dialogs/powerDaemon/sleepdialog.ui b/src/ui/widgets/dialogs/powerDaemon/sleepdialog.ui similarity index 95% rename from src/widgets/dialogs/powerDaemon/sleepdialog.ui rename to src/ui/widgets/dialogs/powerDaemon/sleepdialog.ui index 14f5533..4a77675 100644 --- a/src/widgets/dialogs/powerDaemon/sleepdialog.ui +++ b/src/ui/widgets/dialogs/powerDaemon/sleepdialog.ui @@ -1,7 +1,7 @@ - sleepDialog - + SleepDialog + 0 diff --git a/src/widgets/dialogs/reader/highlightslistdialog.cpp b/src/ui/widgets/dialogs/reader/highlightslistdialog.cpp similarity index 86% rename from src/widgets/dialogs/reader/highlightslistdialog.cpp rename to src/ui/widgets/dialogs/reader/highlightslistdialog.cpp index 91579dd..8598a4f 100644 --- a/src/widgets/dialogs/reader/highlightslistdialog.cpp +++ b/src/ui/widgets/dialogs/reader/highlightslistdialog.cpp @@ -3,9 +3,9 @@ #include -highlightsListDialog::highlightsListDialog(QWidget *parent) : +HighlightsListDialog::HighlightsListDialog(QWidget *parent) : QDialog(parent), - ui(new Ui::highlightsListDialog) + ui(new Ui::HighlightsListDialog) { // Preventing outside interaction this->setModal(true); @@ -42,12 +42,12 @@ highlightsListDialog::highlightsListDialog(QWidget *parent) : QTimer::singleShot(150, this, SLOT(increaseSize())); } -highlightsListDialog::~highlightsListDialog() +HighlightsListDialog::~HighlightsListDialog() { delete ui; } -void highlightsListDialog::increaseSize() +void HighlightsListDialog::increaseSize() { log("Resizing", className); @@ -71,12 +71,12 @@ void highlightsListDialog::increaseSize() this->show(); } -void highlightsListDialog::on_cancelBtn_clicked() +void HighlightsListDialog::on_cancelBtn_clicked() { - highlightsListDialog::close(); + HighlightsListDialog::close(); } -void highlightsListDialog::on_okBtn_clicked() +void HighlightsListDialog::on_okBtn_clicked() { int itemsCount = 0; int range = ui->listWidget->count(); @@ -97,14 +97,14 @@ void highlightsListDialog::on_okBtn_clicked() else { emit showToast("Item deleted successfully"); } - highlightsListDialog::close(); + HighlightsListDialog::close(); } else { emit showToast("Please select items to delete"); } } -void highlightsListDialog::on_selectAllBtn_clicked() +void HighlightsListDialog::on_selectAllBtn_clicked() { int range = ui->listWidget->count(); for(int i = 0; i < range; i++) { @@ -112,7 +112,7 @@ void highlightsListDialog::on_selectAllBtn_clicked() } } -void highlightsListDialog::on_listWidget_itemClicked(QListWidgetItem *item) +void HighlightsListDialog::on_listWidget_itemClicked(QListWidgetItem *item) { if(item->checkState() == Qt::Unchecked) { item->setCheckState(Qt::Checked); diff --git a/src/widgets/dialogs/reader/highlightslistdialog.h b/src/ui/widgets/dialogs/reader/highlightslistdialog.h similarity index 73% rename from src/widgets/dialogs/reader/highlightslistdialog.h rename to src/ui/widgets/dialogs/reader/highlightslistdialog.h index 3831260..c43e2b5 100644 --- a/src/widgets/dialogs/reader/highlightslistdialog.h +++ b/src/ui/widgets/dialogs/reader/highlightslistdialog.h @@ -7,17 +7,17 @@ #include "functions.h" namespace Ui { -class highlightsListDialog; +class HighlightsListDialog; } -class highlightsListDialog : public QDialog +class HighlightsListDialog : public QDialog { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit highlightsListDialog(QWidget *parent = nullptr); - ~highlightsListDialog(); + explicit HighlightsListDialog(QWidget *parent = nullptr); + ~HighlightsListDialog(); private slots: void increaseSize(); @@ -30,7 +30,7 @@ signals: void showToast(QString messageToDisplay); private: - Ui::highlightsListDialog *ui; + Ui::HighlightsListDialog *ui; }; #endif // HIGHLIGHTSLISTDIALOG_H diff --git a/src/widgets/dialogs/reader/highlightslistdialog.ui b/src/ui/widgets/dialogs/reader/highlightslistdialog.ui similarity index 96% rename from src/widgets/dialogs/reader/highlightslistdialog.ui rename to src/ui/widgets/dialogs/reader/highlightslistdialog.ui index 1a6f601..bc14e38 100644 --- a/src/widgets/dialogs/reader/highlightslistdialog.ui +++ b/src/ui/widgets/dialogs/reader/highlightslistdialog.ui @@ -1,7 +1,7 @@ - highlightsListDialog - + HighlightsListDialog + 0 diff --git a/src/widgets/dialogs/reader/textdialog.cpp b/src/ui/widgets/dialogs/reader/textdialog.cpp similarity index 80% rename from src/widgets/dialogs/reader/textdialog.cpp rename to src/ui/widgets/dialogs/reader/textdialog.cpp index 140d452..151a9a4 100644 --- a/src/widgets/dialogs/reader/textdialog.cpp +++ b/src/ui/widgets/dialogs/reader/textdialog.cpp @@ -1,9 +1,9 @@ #include "textdialog.h" #include "ui_textdialog.h" -textDialog::textDialog(QWidget *parent) : +TextDialog::TextDialog(QWidget *parent) : QDialog(parent), - ui(new Ui::textDialog) + ui(new Ui::TextDialog) { ui->setupUi(this); ui->highlightBtn->setProperty("type", "borderless"); @@ -19,12 +19,12 @@ textDialog::textDialog(QWidget *parent) : this->adjustSize(); } -textDialog::~textDialog() +TextDialog::~TextDialog() { delete ui; } -void textDialog::on_highlightBtn_clicked() +void TextDialog::on_highlightBtn_clicked() { if(highlightAlreadyDone == true) { emit unhighlightText(); @@ -32,5 +32,5 @@ void textDialog::on_highlightBtn_clicked() else { emit highlightText(); } - textDialog::close(); + TextDialog::close(); } diff --git a/src/widgets/dialogs/reader/textdialog.h b/src/ui/widgets/dialogs/reader/textdialog.h similarity index 72% rename from src/widgets/dialogs/reader/textdialog.h rename to src/ui/widgets/dialogs/reader/textdialog.h index 58cdec7..a22b10b 100644 --- a/src/widgets/dialogs/reader/textdialog.h +++ b/src/ui/widgets/dialogs/reader/textdialog.h @@ -6,17 +6,17 @@ #include "functions.h" namespace Ui { -class textDialog; +class TextDialog; } -class textDialog : public QDialog +class TextDialog : public QDialog { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit textDialog(QWidget *parent = nullptr); - ~textDialog(); + explicit TextDialog(QWidget *parent = nullptr); + ~TextDialog(); bool highlightAlreadyDone = false; signals: @@ -27,7 +27,7 @@ private slots: void on_highlightBtn_clicked(); private: - Ui::textDialog *ui; + Ui::TextDialog *ui; }; #endif // TEXTDIALOG_H diff --git a/src/widgets/dialogs/reader/textdialog.ui b/src/ui/widgets/dialogs/reader/textdialog.ui similarity index 95% rename from src/widgets/dialogs/reader/textdialog.ui rename to src/ui/widgets/dialogs/reader/textdialog.ui index 1268753..b36eab5 100644 --- a/src/widgets/dialogs/reader/textdialog.ui +++ b/src/ui/widgets/dialogs/reader/textdialog.ui @@ -1,7 +1,7 @@ - textDialog - + TextDialog + 0 diff --git a/src/ui/widgets/dialogs/wifi/connectiondialog.cpp b/src/ui/widgets/dialogs/wifi/connectiondialog.cpp new file mode 100644 index 0000000..80a1da5 --- /dev/null +++ b/src/ui/widgets/dialogs/wifi/connectiondialog.cpp @@ -0,0 +1,370 @@ +#include +#include + +#include "connectiondialog.h" +#include "device.h" +#include "functions.h" +#include "generaldialog.h" +#include "ui.h" +#include "ui_connectiondialog.h" + +ConnectionDialog::ConnectionDialog(QWidget *parent) : + QDialog(parent), + ui(new Ui::ConnectionDialog) { + Device *device = Device::getSingleton(); + + ui->setupUi(this); + this->setFont(QFont("u001")); + ui->passphraseTextEdit->setFont(QFont("Roboto Mono")); + ui->label->setFont(QFont("Inter")); + ui->label_2->setFont(QFont("Inter")); + + // Stylesheet, style & misc. + UI::applyStyle(*this, "eink"); + + ui->cancelBtn->setProperty("type", "borderless"); + ui->connectBtn->setProperty("type", "borderless"); + ui->showPassphraseBtn->setProperty("type", "borderless"); + + ui->label->setStyleSheet("font-weight: bold"); + ui->label_2->setStyleSheet("font-weight: bold"); + + ui->cancelBtn->setIcon(QIcon(":/resources/close.png")); + ui->connectBtn->setIcon(QIcon(":/resources/arrow-right.png")); + + // Size + float widthScaleFactor = 1.0; + float heightScaleFactor = 1.0; + + Device::ScreenSize screenSize = device->getScreenSize(); + QString padding = ""; + if (screenSize == Device::ScreenSize::SMALL) { + widthScaleFactor = 1.2; + heightScaleFactor = 5.9; + } else if (screenSize == Device::ScreenSize::MEDIUM) { + widthScaleFactor = 1.5; + heightScaleFactor = 6.0; + } else if (screenSize == Device::ScreenSize::LARGE) { + widthScaleFactor = 1.5; + heightScaleFactor = 6.3; + } else if (screenSize == Device::ScreenSize::VERY_LARGE) { + widthScaleFactor = 1.5; + heightScaleFactor = 6.45; + } + + QRect screenGeometry = QGuiApplication::screens()[0]->geometry(); + int halfOfHalfHeight = ((screenGeometry.height() / 2) / 2) / 2; + this->setFixedWidth(screenGeometry.width() / widthScaleFactor); + this->setFixedHeight(screenGeometry.height() - halfOfHalfHeight * heightScaleFactor); + + // Centering dialog + int x = (screenGeometry.width() - this->width()) / 2; + int y = (screenGeometry.height() - this->height()) / 2; + this->move(x, y); +} + +ConnectionDialog::~ConnectionDialog() { + delete ui; +} + +void ConnectionDialog::applyVariables() { + // Limit name size + int truncateThreshold; + if (Device::getSingleton()->getScreenSize() == Device::ScreenSize::SMALL) { + truncateThreshold = 20; + } else { + truncateThreshold = 30; + } + int nameLength = connectedNetworkData.name.length(); + QString name = connectedNetworkData.name; + if (nameLength > truncateThreshold) { + name.chop(nameLength - truncateThreshold); + name.append("..."); + } + ui->nameLabel->setText(name); + ui->macLabel->setText(connectedNetworkData.mac); + ui->signalLabel->setText(QString::number(connectedNetworkData.signal) + "%"); + + if (connectedNetworkData.encryption == false) { + ui->showPassphraseBtn->hide(); + ui->passphraseTextEdit->setText("No passphrase required"); + ui->passphraseTextEdit->setDisabled(true); + } else { + if (passphraseDatabase.exists() == false) { + log("Creating empty database", className); + // https://forum.qt.io/topic/104791/how-i-can-create-json-format-in-qt/5 + QJsonObject root; + QJsonArray array; + QJsonDocument newJsonDocument; + root["list"] = array; + newJsonDocument.setObject(root); + + passphraseDatabase.open(QFile::WriteOnly | QFile::Text | QFile::Truncate); + passphraseDatabase.write(newJsonDocument.toJson()); + passphraseDatabase.flush(); + passphraseDatabase.close(); + } + QString passphrase = searchDatabase(connectedNetworkData.name); + if (passphrase.isEmpty() == false) { + log("Found passphrase: '" + passphrase + "'", className); + ui->showPassphraseBtn->setIcon(QIcon(":/resources/show.png")); + showedPassphrase = false; + savedPassphrase = passphrase; + + int passphraseLength = passphrase.length(); + QString hiddenPassphrase; + for (int i = 0; i < passphraseLength; i++) { + hiddenPassphrase.append("•"); + } + ui->passphraseTextEdit->setText(hiddenPassphrase); + } else { + log("No passphrase found", className); + ui->passphraseTextEdit->setText("No passphrase was saved"); + showedPassphrase = true; + ui->showPassphraseBtn->hide(); + } + } +} + +QString ConnectionDialog::searchDatabase(QString key) { + passphraseDatabase.open(QIODevice::ReadOnly | QIODevice::Text); + QString fileRead = passphraseDatabase.readAll(); + passphraseDatabase.close(); + QJsonDocument jsonDocument = QJsonDocument::fromJson(fileRead.toUtf8()); + + if (jsonDocument["list"].isArray() == true) { + QJsonArray jsonArray = jsonDocument["list"].toArray(); + for (QJsonValueRef refJsonObject : jsonArray) { + QJsonObject jsonMainObject = refJsonObject.toObject(); + QString searchedName = jsonMainObject.keys().first().toUtf8(); + log("Found in database: '" + searchedName + "'", className); + if (searchedName == key) { + QString returnedPassphrase = jsonMainObject.value(key).toString(); + log("Searched name '" + searchedName + "' matched '" + key + "' and the passphrase is: '" + returnedPassphrase + "'", className); + return returnedPassphrase; + } else { + log("Searched name '" + searchedName + "' doesn't match '" + key + "'", className); + } + } + return ""; + } else { + log("Something went horribly wrong", className); + } +} + +void ConnectionDialog::writeToDatabase(QString name, QString passphrase) { + if (searchDatabase(name).isEmpty() == false) { + removeFromDatabase(name); + } + + passphraseDatabase.open(QIODevice::ReadOnly | QIODevice::Text); + QString fileRead = passphraseDatabase.readAll(); + passphraseDatabase.close(); + QJsonDocument jsonDocument = QJsonDocument::fromJson(fileRead.toUtf8()); + + if (jsonDocument["list"].isArray() == true) { + QJsonArray jsonArray = jsonDocument["list"].toArray(); + QJsonValue newValue; + + // https://stackoverflow.com/questions/26804660/how-to-initialize-qjsonobject-from-qstring + // I hoped this would be easier + QJsonObject newObject = QJsonDocument::fromJson(QString("{\"" + name + "\" : \"" + passphrase + "\" }").toUtf8()).object(); + jsonArray.append(newObject); + + QJsonDocument newJsonDocument; + QJsonObject root; + root["list"] = jsonArray; + newJsonDocument.setObject(root); + + passphraseDatabase.open(QFile::WriteOnly | QFile::Text | QFile::Truncate); + passphraseDatabase.write(newJsonDocument.toJson()); + passphraseDatabase.flush(); + passphraseDatabase.close(); + } else { + log("Something went horribly wrong", className); + } +} + +void ConnectionDialog::removeFromDatabase(QString name) { + passphraseDatabase.open(QIODevice::ReadOnly | QIODevice::Text); + QString fileRead = passphraseDatabase.readAll(); + passphraseDatabase.close(); + QJsonDocument jsonDocument = QJsonDocument::fromJson(fileRead.toUtf8()); + + int counter = 0; + bool remove = false; + if (jsonDocument["list"].isArray() == true) { + QJsonArray jsonArray = jsonDocument["list"].toArray(); + for (QJsonValueRef refJsonObject : jsonArray) { + QJsonObject jsonMainObject = refJsonObject.toObject(); + QString searchedName = jsonMainObject.keys().first().toUtf8(); + log("Found in database: '" + searchedName + "'", className); + if (searchedName == name) { + remove = true; + } + if (remove == false) { + counter = counter + 1; + } + } + if (remove == true) { + jsonArray.removeAt(counter); + QJsonDocument newJsonDocument; + QJsonObject root; + root["list"] = jsonArray; + newJsonDocument.setObject(root); + + passphraseDatabase.open(QFile::WriteOnly | QFile::Text | QFile::Truncate); + passphraseDatabase.write(newJsonDocument.toJson()); + passphraseDatabase.flush(); + passphraseDatabase.close(); + } else { + log("ERROR: tried to remove from database, but couldn't find key", className); + } + } +} + +void ConnectionDialog::on_cancelBtn_clicked() { + this->deleteLater(); + this->close(); +} + +void ConnectionDialog::on_passphraseTextEdit_selectionChanged() { + ui->passphraseTextEdit->setSelection(0, 0); +} + +void ConnectionDialog::on_passphraseTextEdit_cursorPositionChanged(int oldpos, int newpos) { + log("Detected click on text edit widget", className); + if (cursorPositionIgnore == true) { + if (newpos != 0) { + if (showedPassphrase == true) { + ui->passphraseTextEdit->setCursorPosition(0); + global::keyboard::keyboardDialog = true; + global::keyboard::wifiPassphraseDialog = true; + global::keyboard::keyboardText = ""; + GeneralDialog *generalDialogWindow = new GeneralDialog(); + generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); + generalDialogWindow->wifiEssid = connectedNetworkData.name; + connect(generalDialogWindow, &GeneralDialog::showToast, this, &ConnectionDialog::showToastSlot); + connect(generalDialogWindow, &GeneralDialog::refreshScreen, this, &ConnectionDialog::refreshScreenSlot); + + generalDialogWindow->exec(); + + global::keyboard::keyboardDialog = false; + global::keyboard::wifiPassphraseDialog = false; + if (global::keyboard::keyboardText.isEmpty() == false) { + // A bit hacky: avoid summoning the keyboard back when the text is changing (and the cursor too) showedPassphrase shouldn't be used for this, but it works and adding another boolean would start being messy + showedPassphrase = false; + ui->passphraseTextEdit->setText(global::keyboard::keyboardText); + ui->showPassphraseBtn->setIcon(QIcon(":/resources/hide.png")); + ui->showPassphraseBtn->show(); + showedPassphrase = true; + savedPassphrase = global::keyboard::keyboardText; + ui->showPassphraseBtn->show(); + } + global::keyboard::keyboardText = ""; + } else { + log("Passphrase is not saved; ignoring text edit widget call", className); + } + } + } else { + log("Ignoring click on text edit widget", className); + cursorPositionIgnore = true; + } +} + +void ConnectionDialog::showToastSlot(QString message) { + emit showToastSignal(message); +} + +void ConnectionDialog::on_showPassphraseBtn_clicked() { + if (showedPassphrase == false) { + ui->showPassphraseBtn->setIcon(QIcon(":/resources/hide.png")); + ui->passphraseTextEdit->setText(savedPassphrase); + showedPassphrase = true; + } else { + showedPassphrase = false; + ui->showPassphraseBtn->setIcon(QIcon(":/resources/show.png")); + + int passphraseLength = searchDatabase(connectedNetworkData.name).length(); + if (passphraseLength != 0) { + QString hiddenPassphrase; + for (int i = 0; i < passphraseLength; i++) { + hiddenPassphrase.append("•"); + } + ui->passphraseTextEdit->setText(hiddenPassphrase); + } else { + // This is executed if the user asks to hide the passphrase but it isn't saved yet (upon first connection to a network) + QString hiddenPassphrase; + int passphraseLength = ui->passphraseTextEdit->text().length(); + for (int i = 0; i < passphraseLength; i++) { + hiddenPassphrase.append("•"); + } + ui->passphraseTextEdit->setText(hiddenPassphrase); + } + } +} + +void ConnectionDialog::refreshScreenSlot() { + this->repaint(); + emit refreshScreenSignal(); +} + +void ConnectionDialog::on_connectBtn_clicked() { + QString finalPassphrase; + if (connectedNetworkData.encryption == false) { + finalPassphrase = "NONE"; + } else { + if (savedPassphrase.isEmpty() == false) { + finalPassphrase = savedPassphrase; + writeToDatabase(connectedNetworkData.name, savedPassphrase); + } else { + showToastSlot("Provide a passphrase first"); + return void(); + } + } + passphraseForReconnecting = finalPassphrase; + + ui->cancelBtn->setEnabled(false); + if (checkWifiState() == global::wifi::wifiState::configured) { + writeFile("/opt/ibxd", "stop_wifi_operations\n"); + } + writeFile("/run/wifi_network_essid", connectedNetworkData.name); + writeFile("/run/wifi_network_passphrase", finalPassphrase); + finalConnectWait(); +} + +void ConnectionDialog::finalConnectWait() { + if (checkIfWifiBusy() == true) { + // To be sure + if (waitTry == 10) { + writeFile("/opt/ibxd", "stop_wifi_operations\n"); + } + // Wait for everything to shut down; 10 seconds timeout + if (waitTry == 20) { + writeFile("/opt/ibxd", "stop_wifi_operations\n"); + emit showToastSignal("Failed to stop other Wi-Fi processes"); + ui->cancelBtn->setEnabled(true); + } else { + QTimer::singleShot(500, this, SLOT(finalConnectWait())); + waitTry = waitTry + 1; + } + } else { + writeFile("/opt/ibxd", "connect_to_wifi_network\n"); + + // This will be deleted later in MainWindow's icon updater if it failed. It is also deleted in the Wi-Fi stop script. + log("Writing to configuration directory with connection information data", className); + writeFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/essid", connectedNetworkData.name); + writeFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/passphrase", passphraseForReconnecting); + + this->deleteLater(); + this->close(); + } +} + +bool ConnectionDialog::checkIfWifiBusy() { + if (checkProcessName("connect_to_network.sh") == true or checkProcessName("connection_manager.sh") == true or checkProcessName("prepare_changing_wifi.sh") == true) { + return true; + } else { + return false; + } +} diff --git a/src/widgets/dialogs/wifi/connectiondialog.h b/src/ui/widgets/dialogs/wifi/connectiondialog.h similarity index 88% rename from src/widgets/dialogs/wifi/connectiondialog.h rename to src/ui/widgets/dialogs/wifi/connectiondialog.h index ab4e1d0..361cb39 100644 --- a/src/widgets/dialogs/wifi/connectiondialog.h +++ b/src/ui/widgets/dialogs/wifi/connectiondialog.h @@ -5,17 +5,17 @@ #include "functions.h" namespace Ui { -class connectiondialog; +class ConnectionDialog; } -class connectiondialog : public QDialog +class ConnectionDialog : public QDialog { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit connectiondialog(QWidget *parent = nullptr); - ~connectiondialog(); + explicit ConnectionDialog(QWidget *parent = nullptr); + ~ConnectionDialog(); global::wifi::wifiNetworkData connectedNetworkData; QString currentlyConnectedNetworkName; QFile passphraseDatabase = QFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/passphrases.json"); @@ -47,7 +47,7 @@ private slots: void on_connectBtn_clicked(); private: - Ui::connectiondialog *ui; + Ui::ConnectionDialog *ui; bool cursorPositionIgnore = false; bool showedPassphrase; QString savedPassphrase; diff --git a/src/widgets/dialogs/wifi/connectiondialog.ui b/src/ui/widgets/dialogs/wifi/connectiondialog.ui similarity index 98% rename from src/widgets/dialogs/wifi/connectiondialog.ui rename to src/ui/widgets/dialogs/wifi/connectiondialog.ui index 7c97ade..d4d3166 100644 --- a/src/widgets/dialogs/wifi/connectiondialog.ui +++ b/src/ui/widgets/dialogs/wifi/connectiondialog.ui @@ -1,7 +1,7 @@ - connectiondialog - + ConnectionDialog + 0 diff --git a/src/ui/widgets/dialogs/wifi/network.cpp b/src/ui/widgets/dialogs/wifi/network.cpp new file mode 100644 index 0000000..cd1702f --- /dev/null +++ b/src/ui/widgets/dialogs/wifi/network.cpp @@ -0,0 +1,108 @@ +#include "network.h" +#include "connectiondialog.h" +#include "device.h" +#include "ui.h" +#include "ui_network.h" + +#include + +NetworkWidget::NetworkWidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::NetworkWidget) { + ui->setupUi(this); + this->setFont(QFont("u001")); + + // Stylesheet, style & misc. + UI::applyStyle(*this, "eink"); + + // Buttons + ui->encryptionIcon->setProperty("type", "borderless"); + ui->encryptionIcon->setStyleSheet("QPushButton[type='borderless']:pressed { background: white; color: white; border: none; }"); + ui->signalStrengthIcon->setProperty("type", "borderless"); + ui->signalStrengthIcon->setStyleSheet("QPushButton[type='borderless']:pressed { background: white; color: white; border: none; }"); + ui->enterButton->setProperty("type", "borderless"); +} + +NetworkWidget::~NetworkWidget() { + delete ui; +} + +void NetworkWidget::applyVariables() { + log("Applying variables for network", className); + + QString percent = "%"; + if (mainData.signal < 100) { + percent.append(" "); + } + ui->signalStrengthLabel->setText(QString::number(mainData.signal) + percent); + + // Limit name size + int truncateThreshold; + if (Device::getSingleton()->getScreenSize() == Device::SMALL) { + truncateThreshold = 12; + } else { + truncateThreshold = 20; + } + int nameLength = mainData.name.length(); + QString name = mainData.name; + if (nameLength > truncateThreshold) { + name.chop(nameLength - truncateThreshold); + name.append("..."); + } + ui->nameLabel->setText(name); + + if (mainData.encryption == true) { + ui->encryptionIcon->setIcon(QIcon(":/resources/lock.png")); + } else { + ui->encryptionIcon->setIcon(QIcon(":/resources/public.png")); + } + + if (currentlyConnectedNetwork == mainData.name) { + ui->frame->setStyleSheet(".QFrame{background-color: lightGray; border: 2px solid black; border-radius: 10px;}"); + ui->signalStrengthLabel->setStyleSheet("background-color: lightGray;"); + ui->nameLabel->setStyleSheet("background-color: lightGray;"); + ui->encryptionIcon->setStyleSheet("background-color: lightGray;"); + ui->enterButton->setStyleSheet("background-color: lightGray;"); + + ui->signalStrengthIcon->setStyleSheet("QPushButton {background-color: lightGray; border: none}; QPushButton[type='borderless']:pressed { background: lightGray; color: lightGray; border: none; }"); + ui->encryptionIcon->setStyleSheet("QPushButton {background-color: lightGray; border: none}; QPushButton[type='borderless']:pressed { background: lightGray; color: lightGray; border: none; }"); + ui->enterButton->setStyleSheet("QPushButton {background-color: lightGray; border: none}; QPushButton[type='borderless']:pressed { background: lightGray; color: lightGray; border: none; }"); + } else { + ui->frame->setStyleSheet(".QFrame{background-color: white; border: 2px solid black; border-radius: 10px;}"); + } + + if (mainData.signal >= 0 and mainData.signal <= 25) { + ui->signalStrengthIcon->setIcon(QIcon(":/resources/wifi-0.png")); + } else if (mainData.signal >= 25 and mainData.signal < 50) { + ui->signalStrengthIcon->setIcon(QIcon(":/resources/wifi-25.png")); + } else if (mainData.signal >= 50 and mainData.signal < 75) { + ui->signalStrengthIcon->setIcon(QIcon(":/resources/wifi-50.png")); + } else if (mainData.signal >= 75 and mainData.signal < 100) { + ui->signalStrengthIcon->setIcon(QIcon(":/resources/wifi-75.png")); + } else if (mainData.signal == 100) { + ui->signalStrengthIcon->setIcon(QIcon(":/resources/wifi-100.png")); + } +} + +void NetworkWidget::on_enterButton_clicked() { + ConnectionDialog *newConnectionDialog = new ConnectionDialog; + newConnectionDialog->connectedNetworkData = mainData; + newConnectionDialog->currentlyConnectedNetworkName = currentlyConnectedNetwork; + newConnectionDialog->applyVariables(); + connect(newConnectionDialog, &ConnectionDialog::showToastSignal, this, &NetworkWidget::showToastSlot); + connect(newConnectionDialog, &ConnectionDialog::refreshScreenSignal, this, &NetworkWidget::refreshScreenSlot); + newConnectionDialog->exec(); +} + +void NetworkWidget::closeWrapper() { + this->deleteLater(); + this->close(); +} + +void NetworkWidget::showToastSlot(QString message) { + emit showToastSignal(message); +} + +void NetworkWidget::refreshScreenSlot() { + emit refreshScreenSignal(); +} diff --git a/src/widgets/dialogs/wifi/network.h b/src/ui/widgets/dialogs/wifi/network.h similarity index 77% rename from src/widgets/dialogs/wifi/network.h rename to src/ui/widgets/dialogs/wifi/network.h index 2649b0d..af5ee30 100644 --- a/src/widgets/dialogs/wifi/network.h +++ b/src/ui/widgets/dialogs/wifi/network.h @@ -6,17 +6,17 @@ #include "functions.h" namespace Ui { -class network; +class NetworkWidget; } -class network : public QWidget +class NetworkWidget : public QWidget { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit network(QWidget *parent = nullptr); - ~network(); + explicit NetworkWidget(QWidget *parent = nullptr); + ~NetworkWidget(); global::wifi::wifiNetworkData mainData; QString currentlyConnectedNetwork; @@ -34,7 +34,7 @@ private slots: void on_enterButton_clicked(); private: - Ui::network *ui; + Ui::NetworkWidget *ui; }; #endif // NETWORK_H diff --git a/src/widgets/dialogs/wifi/network.ui b/src/ui/widgets/dialogs/wifi/network.ui similarity index 98% rename from src/widgets/dialogs/wifi/network.ui rename to src/ui/widgets/dialogs/wifi/network.ui index 3a44c2f..c6f5c14 100644 --- a/src/widgets/dialogs/wifi/network.ui +++ b/src/ui/widgets/dialogs/wifi/network.ui @@ -1,7 +1,7 @@ - network - + NetworkWidget + 0 diff --git a/src/ui/widgets/dialogs/wifi/wifidialog.cpp b/src/ui/widgets/dialogs/wifi/wifidialog.cpp new file mode 100644 index 0000000..45ca2b2 --- /dev/null +++ b/src/ui/widgets/dialogs/wifi/wifidialog.cpp @@ -0,0 +1,510 @@ +#include +#include +#include +#include +#include +#include + +#include "device.h" +#include "functions.h" +#include "mainwindow.h" +#include "network.h" +#include "ui.h" +#include "ui_wifidialog.h" +#include "wifidialog.h" +#include "wifilogger.h" + +WifiDialog::WifiDialog(QWidget *parent) : + QDialog(parent), + ui(new Ui::WifiDialog) { + Device *device = Device::getSingleton(); + ui->setupUi(this); + this->setFont(QFont("u001")); + + // Stylesheet, style & misc. + UI::applyStyle(*this, "eink"); + + this->setModal(true); + + ui->wifiCheckBox->setFont(QFont("Inter")); + ui->returnBtn->setFont(QFont("Inter")); + ui->returnBtn->setStyleSheet("font-weight: bold"); + + ui->refreshBtn->setProperty("type", "borderless"); + ui->stopBtn->setProperty("type", "borderless"); + ui->logBtn->setProperty("type", "borderless"); + ui->returnBtn->setProperty("type", "borderless"); + + ui->refreshBtn->setIcon(QIcon(":/resources/refresh.png")); + ui->stopBtn->setIcon(QIcon(":/resources/stop.png")); + ui->logBtn->setIcon(QIcon(":/resources/log.png")); + + // Size + QRect screenGeometry = QGuiApplication::screens()[0]->geometry(); + this->setFixedWidth(screenGeometry.width() / 1.1); + + int halfOfHalfHeight = ((screenGeometry.height() / 2) / 2) / 2; + int finalHeight = screenGeometry.height() - halfOfHalfHeight * 2; + + this->setFixedHeight(finalHeight); + + // Centering dialog + int x = (screenGeometry.width() - this->width()) / 2; + int y = (screenGeometry.height() - this->height()) / 2; + this->move(x, y); + + // Button sizes + if (device->getScreenSize() == Device::ScreenSize::SMALL) { + ui->refreshBtn->setStyleSheet("padding: 20px;"); + ui->stopBtn->setStyleSheet("padding: 20px;"); + ui->logBtn->setStyleSheet("padding: 20px;"); + } else { + ui->refreshBtn->setStyleSheet("padding: 25px;"); + ui->stopBtn->setStyleSheet("padding: 25px;"); + ui->logBtn->setStyleSheet("padding: 25px;"); + } + + // Set Wi-Fi checkbox state. Ignore the first call. + global::wifi::wifiState currentWifiState = checkWifiState(); + if (currentWifiState != global::wifi::wifiState::disabled and currentWifiState != global::wifi::wifiState::unknown) { + ui->wifiCheckBox->setChecked(true); + // To be sure nothing breaks + refreshFromWatcher = true; + ui->refreshBtn->click(); + } else { + wifiButtonEnabled = true; + ui->stopBtn->setStyleSheet(ui->stopBtn->styleSheet() + "background-color: lightGray;"); + ui->stopBtn->setEnabled(false); + } + + // To avoid confusion with reconnecting + QTimer::singleShot(0, this, SLOT(watcher())); +} + +WifiDialog::~WifiDialog() { + delete ui; +} + +void WifiDialog::on_refreshBtn_clicked() { + log("Clicked refresh button", className); + if (checkWifiState() == global::wifi::wifiState::disabled) { + if (refreshFromWatcher == true) { + refreshFromWatcher = false; + emit showToast("To scan, turn Wi-Fi on first"); + } + } else { + refreshFromWatcher = false; + launchRefresh(); + } +} + +void WifiDialog::launchRefresh() { + // Order is important + if (scanInProgress == false) { + scanInProgress = true; + ui->refreshBtn->setStyleSheet(ui->refreshBtn->styleSheet() + "background-color: lightGray;"); + ui->refreshBtn->setEnabled(false); + + elapsedSeconds = 0; + fullList.remove(); + formattedList.remove(); + writeFile("/opt/ibxd", "list_wifi_networks\n"); + QTimer::singleShot(0, this, SLOT(refreshWait())); + } else { + log("Scan is already in progress", className); + } +} + +void WifiDialog::refreshWait() { + if (fullList.exists() == false and formattedList.exists() == false) { + if (elapsedSeconds == 6) { + emit showToast("Failed to get networks list"); + ui->refreshBtn->setStyleSheet(ui->refreshBtn->styleSheet() + "background-color: white;"); + ui->refreshBtn->setEnabled(true); + scanInProgress = false; + } else { + elapsedSeconds = elapsedSeconds + 1; + QTimer::singleShot(1000, this, SLOT(refreshWait())); + } + } else { + log("Retrieved network list successfully", className); + refreshNetworksList(); + } +} + +void WifiDialog::refreshNetworksList() { + emit killNetworkWidgets(); + QStringList networkList = readFile("/external_root/run/wifi_list_format").split("%%==SPLIT==%%\n"); + QVector pureNetworkList; + for (QString network : networkList) { + QStringList data = network.split("\n"); + int count = 1; + global::wifi::wifiNetworkData singleNetwork; + if (data.count() < 4) { + log("Data lines count is below 4; skipping", className); + continue; + } + for (QString singleData : data) { + if (count == 1) { + singleNetwork.mac = singleData; + log("MAC is: " + singleData, className); + } + if (count == 2) { + if (singleData.isEmpty() == true) { + log("Network name is empty", className); + } else { + log("Network name is: '" + singleData + "'", className); + } + singleNetwork.name = singleData; + } + if (count == 3) { + log("Encryption type is: " + singleData, className); + singleNetwork.encryption = QVariant(singleData).toBool(); + } + if (count == 4) { + log("Signal strength is: " + singleData, className); + singleNetwork.signal = QVariant(singleData).toInt(); + } + if (count >= 5) { + log("Skipping additional items from network information", className); + } + count = count + 1; + } + // Filter out remaining empty networks + if (singleNetwork.name.isEmpty() == false) { + pureNetworkList.append(singleNetwork); + } + } + log("Found " + QString::number(pureNetworkList.count()) + " valid networks", className); + if (pureNetworkList.count() == 0) { + if (secondScanTry == false) { + secondScanTry = true; + if (checkWifiState() != global::wifi::wifiState::disabled) { + scanInProgress = false; + QTimer::singleShot(0, this, SLOT(launchRefresh())); + log("No networks found. Trying one more time"); + return void(); + } else { + return void(); + } + } else { + secondScanTry = false; + log("No networks found, skipping", className); + showToastSlot("No networks found"); + ui->refreshBtn->setEnabled(true); + ui->refreshBtn->setStyleSheet(ui->refreshBtn->styleSheet() + "background-color: white;"); + scanInProgress = false; + return void(); + } + } + QFile currentWifiNameFile = QFile("/external_root/run/current_wifi_name"); + currentWifiNameFile.remove(); + writeFile("/opt/ibxd", "get_current_wifi_name\n"); + usleep(300000); // 0.3s + // Here, it's looking for the currently connected network to put it on top of the list + QString currentNetwork = ""; + if (currentWifiNameFile.exists() == true) { + QString currentWifiNetwork = readFile(currentWifiNameFile.fileName()); + currentWifiNetwork = currentWifiNetwork.replace("\n", ""); + log("Current network name is: " + currentWifiNetwork, className); + int countVec = 0; + int vectorNetworkLocation = 9999; + for (global::wifi::wifiNetworkData wifiNetwork : pureNetworkList) { + if (currentWifiNetwork.isEmpty() == false and wifiNetwork.name == currentWifiNetwork) { + log("Found current network in vector", className); + vectorNetworkLocation = countVec; + currentNetwork = wifiNetwork.name; + NetworkWidget *connectedNetwork = new NetworkWidget; + connectedNetwork->mainData = wifiNetwork; + // To be really sure that the the info is put there + connectedNetwork->currentlyConnectedNetwork = currentNetwork; + connectedNetworkDataParent = wifiNetwork; + connectedNetworkDataParentSet = true; + + // This doesn't work, so a layout is needed + // ui->scrollArea->addScrollBarWidget(connectedNetwork, Qt::AlignTop); + connectedNetwork->applyVariables(); + connect(this, &WifiDialog::killNetworkWidgets, connectedNetwork, &NetworkWidget::closeWrapper); + connect(connectedNetwork, &NetworkWidget::showToastSignal, this, &WifiDialog::showToastSlot); + connect(connectedNetwork, &NetworkWidget::refreshScreenSignal, this, &WifiDialog::refreshScreenSlot); + ui->scrollBarLayout->addWidget(connectedNetwork, Qt::AlignTop); + } else { + countVec = countVec + 1; + } + } + if (vectorNetworkLocation != 9999) { + log("pureNetworkList size is: " + QString::number(pureNetworkList.count()) + ", entry at " + QString::number(vectorNetworkLocation) + " slated for removal", className); + pureNetworkList.removeAt(vectorNetworkLocation); + } + } + + if (pureNetworkList.count() >= 1) { + // Sort based on signal strength + QVector sortedPureNetworkList; + sortedPureNetworkList.append(pureNetworkList.first()); + pureNetworkList.removeFirst(); + // Possible fix for a segmentation fault + if (pureNetworkList.isEmpty() == false) { + for (global::wifi::wifiNetworkData wifiNetwork : pureNetworkList) { + bool stopIterating = false; + int counter = 0; + for (global::wifi::wifiNetworkData wifiNetworkToSort : sortedPureNetworkList) { + if (stopIterating == false) { + if (wifiNetwork.signal >= wifiNetworkToSort.signal) { + sortedPureNetworkList.insert(counter, wifiNetwork); + stopIterating = true; + } + counter = counter + 1; + } + } + // This happens if it's the smallest value, so insert it at the end + if (stopIterating == false) { + sortedPureNetworkList.append(wifiNetwork); + } + } + } + log("There are " + QString::number(sortedPureNetworkList.count()) + " sorted networks", className); + + for (global::wifi::wifiNetworkData wifiNetwork : sortedPureNetworkList) { + log("Signal strength with sorting: " + QString::number(wifiNetwork.signal), className); + } + + // And now, handle the remainder of the networks + for (global::wifi::wifiNetworkData wifiNetwork : sortedPureNetworkList) { + NetworkWidget *connectedNetwork = new NetworkWidget; + connectedNetwork->mainData = wifiNetwork; + connectedNetwork->currentlyConnectedNetwork = currentNetwork; + connectedNetwork->applyVariables(); + connect(this, &WifiDialog::killNetworkWidgets, connectedNetwork, &NetworkWidget::closeWrapper); + connect(connectedNetwork, &NetworkWidget::showToastSignal, this, &WifiDialog::showToastSlot); + connect(connectedNetwork, &NetworkWidget::refreshScreenSignal, this, &WifiDialog::refreshScreenSlot); + ui->scrollBarLayout->addWidget(connectedNetwork, Qt::AlignTop); + } + } + scannedAtLeastOnce = true; + ui->refreshBtn->setEnabled(true); + ui->refreshBtn->setStyleSheet(ui->refreshBtn->styleSheet() + "background-color: white;"); + scanInProgress = false; + secondScanTry = false; +} + +void WifiDialog::on_wifiCheckBox_stateChanged(int arg1) { + if (ignoreCheckBoxCall == false) { + connectedNetworkDataParentSet = false; + log("Wi-Fi dialog checkbox clicked: " + QString::number(arg1), className); + if (wifiButtonEnabled == true) { + if (arg1 == 2) { + log("Turning Wi-Fi on", className); + // The watcher will scan Wi-Fi + QTimer::singleShot(0, this, SLOT(turnOnWifi())); + ui->stopBtn->setStyleSheet(ui->stopBtn->styleSheet() + "background-color: white;"); + ui->stopBtn->setEnabled(true); + } else { + log("Turning Wi-Fi off", className); + QTimer::singleShot(0, this, SLOT(turnOffWifi())); + // To inform the Wi-Fi icon updater to not show the connected/failed to connect message + writeFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/stopped", "true"); + ui->stopBtn->setStyleSheet(ui->stopBtn->styleSheet() + "background-color: lightGray;"); + ui->stopBtn->setEnabled(false); + } + emit killNetworkWidgets(); + } + if (wifiButtonEnabled == false) { + wifiButtonEnabled = true; + } + } else { + ignoreCheckBoxCall = false; + if (checkWifiState() != global::wifi::wifiState::disabled) { + emit killNetworkWidgets(); + forceRefresh = true; + } else { + emit killNetworkWidgets(); + } + } +} + +void WifiDialog::turnOnWifi() { + writeFile("/opt/ibxd", "toggle_wifi_on\n"); + // No one will notice this freeze :> + waitToScan(); +} + +void WifiDialog::turnOffWifi() { + writeFile("/opt/ibxd", "toggle_wifi_off\n"); +} + +void WifiDialog::on_logBtn_clicked() { + // To avoid half of the information + if (scannedAtLeastOnce == false and checkWifiState() == global::wifi::wifiState::configured) { + log("Scanning at least once is needed"); + emit showToast("Scan at least once"); + } else { + WifiLoggerDialog *wifiLoggerDialog = new WifiLoggerDialog; + if (connectedNetworkDataParentSet == true) { + wifiLoggerDialog->connectedNetworkData = connectedNetworkDataParent; + wifiLoggerDialog->isThereData = true; + } + wifiLoggerDialog->exec(); + } +} + +void WifiDialog::showToastSlot(QString message) { + emit showToast(message); +} + +void WifiDialog::refreshScreenSlot() { + this->repaint(); +} + +/* + Some documentation used by the watcher + * connection_manager.sh - Manages all things, launches other processes + * connect_to_network.sh - All-in-one connection manager. Manages everything, used by IPD, should be used for Wi-Fi reconnections after sleeping/booting + * get_dhcp.sh - Gets dhcp addresses + * prepare_changing_wifi.sh - Kills everything, prepares to changing network + * timesync.sh - Syncs time + * toggle.sh - Turns Wi-Fi adapter on/off + * list_networks - Lists networks + * check_wifi_passphrase.sh - Checks Wi-Fi network passphrase + * watcher() first watches at processes that could kill other ones +*/ + +void WifiDialog::watcher() { + bool killing = checkProcessName("toggle.sh"); + bool changing = checkProcessName("prepare_changing_wifi.sh"); + if (killing == true) { + setStatusText("Changing Wi-Fi adapter status"); + isToggleRunning = true; + QTimer::singleShot(relaunchMs, this, SLOT(watcher())); + return void(); + } + + if (changing == true) { + setStatusText("Disconnecting or cleaning up"); + log("prepare_changing_wifi.sh is active", className); + QTimer::singleShot(relaunchMs, this, SLOT(watcher())); + return void(); + } + + bool reconnection = checkProcessName("connect_to_network.sh"); + if (reconnection == true) { + forceRefresh = true; + QFile recName = QFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/essid"); + if (recName.exists() == true) { + setStatusText("Reconnecting to '" + readFile(recName.fileName()).replace("\n", "") + "'"); + } else { + // Shouldn't be possible + setStatusText("Reconnecting after sleep"); + } + QTimer::singleShot(relaunchMs, this, SLOT(watcher())); + return void(); + } + + bool listing = checkProcessName("list_networks"); + if (listing == true) { + setStatusText("Scanning available networks"); + QTimer::singleShot(relaunchMs, this, SLOT(watcher())); + return void(); + } + + bool dhcp = checkProcessName("get_dhcp.sh"); + if (dhcp == true) { + forceRefresh = true; + setStatusText("Getting IP address"); + QTimer::singleShot(relaunchMs, this, SLOT(watcher())); + return void(); + } + + bool passphraseCheck = checkProcessName("check_wifi_passphrase.sh"); + if (passphraseCheck == true) { + forceRefresh = true; + setStatusText("Checking Wi-Fi network passphrase"); + QTimer::singleShot(relaunchMs, this, SLOT(watcher())); + return void(); + } + + bool time = checkProcessName("timesync.sh"); + if (time == true) { + forceRefresh = true; + setStatusText("Syncing time"); + QTimer::singleShot(relaunchMs, this, SLOT(watcher())); + return void(); + } + + bool connecting = checkProcessName("connection_manager.sh"); + if (connecting == true) { + forceRefresh = true; + setStatusText("Connecting to Wi-Fi network"); + QTimer::singleShot(relaunchMs, this, SLOT(watcher())); + return void(); + } + + if (ui->statusLabel->text() != "Idle") { + setStatusText("Idle"); + } + + if (unlockCheckBox == true) { + ui->wifiCheckBox->setEnabled(true); + unlockCheckBox = false; + } + + if (isToggleRunning == true) { + isToggleRunning = false; + // Make sure the checkbox is in the right state + if (checkWifiState() == global::wifi::wifiState::disabled) { + // In this state, ignore forceRefresh to avoid message + forceRefresh = false; + if (ui->wifiCheckBox->isChecked() == true) { + ignoreCheckBoxCall = true; + ui->wifiCheckBox->setChecked(false); + } + } else { + if (ui->wifiCheckBox->isChecked() == false) { + ignoreCheckBoxCall = true; + ui->wifiCheckBox->setChecked(true); + } + } + } + + if (forceRefresh == true) { + forceRefresh = false; + refreshFromWatcher = true; + QTimer::singleShot(1500, this, SLOT(waitToScan())); + } + + QTimer::singleShot(relaunchMs, this, SLOT(watcher())); +} + +void WifiDialog::setStatusText(QString message) { + ui->statusLabel->setText(message); +} + +void WifiDialog::on_stopBtn_clicked() { + log("Stop button was clicked", className); + connectedNetworkDataParentSet = false; + ui->wifiCheckBox->setEnabled(false); + unlockCheckBox = true; + + // To inform the wifi icon GUI to don't show the connected/failed to connect message + writeFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/stopped", "true"); + writeFile("/opt/ibxd", "stop_wifi_operations\n"); + + QFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/essid").remove(); + QFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/passphrase").remove(); + + // This variable just avoids showing the toast, so it is usable here too + waitToScan(); +} + +void WifiDialog::on_returnBtn_clicked() { + this->deleteLater(); + this->close(); +} + +void WifiDialog::waitToScan() { + if (checkWifiState() != global::wifi::wifiState::disabled) { + ui->refreshBtn->click(); + } else { + QTimer::singleShot(750, this, SLOT(waitToScan())); + } +} diff --git a/src/widgets/dialogs/wifi/wifidialog.h b/src/ui/widgets/dialogs/wifi/wifidialog.h similarity index 92% rename from src/widgets/dialogs/wifi/wifidialog.h rename to src/ui/widgets/dialogs/wifi/wifidialog.h index 92754c5..ce5d57e 100644 --- a/src/widgets/dialogs/wifi/wifidialog.h +++ b/src/ui/widgets/dialogs/wifi/wifidialog.h @@ -8,22 +8,22 @@ #include "wifilogger.h" namespace Ui { -class wifiDialog; +class WifiDialog; } -class wifiDialog : public QDialog +class WifiDialog : public QDialog { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit wifiDialog(QWidget *parent = nullptr); - ~wifiDialog(); + explicit WifiDialog(QWidget *parent = nullptr); + ~WifiDialog(); global::wifi::wifiNetworkData connectedNetworkDataParent; bool connectedNetworkDataParentSet = false; private: - Ui::wifiDialog *ui; + Ui::WifiDialog *ui; bool wifiButtonEnabled = false; bool scannedAtLeastOnce = false; diff --git a/src/widgets/dialogs/wifi/wifidialog.ui b/src/ui/widgets/dialogs/wifi/wifidialog.ui similarity index 99% rename from src/widgets/dialogs/wifi/wifidialog.ui rename to src/ui/widgets/dialogs/wifi/wifidialog.ui index 361f044..461d876 100644 --- a/src/widgets/dialogs/wifi/wifidialog.ui +++ b/src/ui/widgets/dialogs/wifi/wifidialog.ui @@ -1,7 +1,7 @@ - wifiDialog - + WifiDialog + 0 diff --git a/src/ui/widgets/dialogs/wifi/wifilogger.cpp b/src/ui/widgets/dialogs/wifi/wifilogger.cpp new file mode 100644 index 0000000..c86b489 --- /dev/null +++ b/src/ui/widgets/dialogs/wifi/wifilogger.cpp @@ -0,0 +1,192 @@ +#include "ui.h" +#include +#include +#include + +#include "functions.h" +#include "ui_wifilogger.h" +#include "wifilogger.h" + +WifiLoggerDialog::WifiLoggerDialog(QWidget *parent) : + QDialog(parent), + ui(new Ui::WifiLoggerDialog) { + ui->setupUi(this); + this->setFont(QFont("u001")); + // 'Not currently connected to a network' label + ui->label_8->setFont(QFont("Inter")); + ui->returnBtn->setFont(QFont("Inter")); + ui->nameLabel->setFont(QFont("Inter")); + ui->allLogsText->setFont(QFont("Roboto Mono")); + ui->fancyLogsText->setFont(QFont("Roboto Mono")); + ui->nameLabel->setStyleSheet("font-weight: bold"); + ui->returnBtn->setStyleSheet("font-weight: bold"); + ui->allLogsText->setStyleSheet("font-size: 7.5pt"); + ui->fancyLogsText->setStyleSheet("font-size: 7.5pt"); + + // Stylesheet, style & misc. + UI::applyStyle(*this, "eink"); + + this->setModal(true); + + // Scroll bar + // Needed for the nia. + // ui->allLogsText->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 50px; }"); + // ui->fancyLogsText->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 50px; }"); + + log("Entered wifilogger", className); + setWifiInfoPage(); + ui->previousBtn->setProperty("type", "borderless"); + ui->nextBtn->setProperty("type", "borderless"); + ui->returnBtn->setProperty("type", "borderless"); + ui->refreshBtn->setProperty("type", "borderless"); + + // Size + QRect screenGeometry = QGuiApplication::screens()[0]->geometry(); + this->setFixedWidth(screenGeometry.width() / 1.2); + + int halfOfHalfHeight = ((screenGeometry.height() / 2) / 2) / 2; + int finalHeight = screenGeometry.height() - halfOfHalfHeight * 2.4; + + this->setFixedHeight(finalHeight); + + // Centering dialog + int x = (screenGeometry.width() - this->width()) / 2; + int y = (screenGeometry.height() - this->height()) / 2; + this->move(x, y); +} + +WifiLoggerDialog::~WifiLoggerDialog() { + delete ui; +} + +void WifiLoggerDialog::setWifiInfoPage() { + if (checkWifiState() == global::wifi::wifiState::configured) { + getWifiInformationTimer.singleShot(0, this, SLOT(getWifiInformation())); + ui->stackedWidget->setCurrentIndex(0); + ui->nameLabel->setText("Network information"); + } else { + ui->stackedWidget->setCurrentIndex(1); + ui->nameLabel->setText("Not connected to a network"); + } +} + +void WifiLoggerDialog::setFancyLoggingPage() { + updateLogs(); + ui->stackedWidget->setCurrentIndex(2); + ui->nameLabel->setText("Important logs"); +} + +void WifiLoggerDialog::setAllLogsPage() { + updateLogs(); + ui->stackedWidget->setCurrentIndex(3); + ui->nameLabel->setText("All logs"); +} + +void WifiLoggerDialog::on_nextBtn_clicked() { + if (currentPage == 2) { + currentPage = 0; + } else { + currentPage = currentPage + 1; + } + changePage(); +} + +void WifiLoggerDialog::on_previousBtn_clicked() { + if (currentPage == 0) { + currentPage = 2; + } else { + currentPage = currentPage - 1; + } + changePage(); +} + +void WifiLoggerDialog::changePage() { + if (currentPage == 0) { + setWifiInfoPage(); + } else if (currentPage == 1) { + setFancyLoggingPage(); + } else if (currentPage == 2) { + setAllLogsPage(); + } else { + log("This shouldn't happen", className); + } +} + +void WifiLoggerDialog::getWifiInformation() { + log("Retrieving Wi-Fi information", className); + QFile wifiInformationPath = QFile("/external_root/run/wifi_information"); + if (waitingForFile == false) { + wifiInformationPath.remove(); + log("Sending get_wifi_information ibxd call", className); + writeFile("/opt/ibxd", "get_wifi_information\n"); + waitingForFile = true; + } + + if (waitingForFile == true) { + if (wifiInformationPath.exists() == false) { + getWifiInformationTimer.singleShot(1000, this, SLOT(getWifiInformation())); + return void(); + } + } + + waitingForFile = false; + log("Setting variables", className); + QString wifiInfo = readFile(wifiInformationPath.fileName()); + QStringList wifiInfoList = wifiInfo.split("\n"); + int counter = 0; + for (QString infomation : wifiInfoList) { + if (counter == 0) { + ui->netNameLabel->setText(infomation); + } + if (counter == 1) { + ui->ipLabel->setText(infomation); + } + if (counter == 2) { + ui->maskLabel->setText(infomation); + } + if (counter == 3) { + ui->gatewayLabel->setText(infomation); + } + counter = counter + 1; + } + + if (isThereData == true) { + ui->encryptionLabel->setText(QVariant(connectedNetworkData.encryption).toString()); + ui->signalLabel->setText(QString::number(connectedNetworkData.signal) + "%"); + ui->macLabel->setText(connectedNetworkData.mac); + } else { + // Shouldn't happen for 99%, but if anyway... it's designed to be non-blocking, so I can't really wait for this. + ui->encryptionLabel->setText("Rescan needed"); + ui->signalLabel->setText("Rescan needed"); + ui->macLabel->setText("Rescan needed"); + } +} + +void WifiLoggerDialog::on_returnBtn_clicked() { + log("Exiting wifilogger", className); + getWifiInformationTimer.stop(); + this->deleteLater(); + this->close(); +} + +void WifiLoggerDialog::updateLogs() { + if (fancyLogs.exists() == true and allLogs.exists() == true) { + QString fancyLogsText = readFile(fancyLogs.fileName()); + QString allLogsText = readFile(allLogs.fileName()); + + ui->fancyLogsText->setText(fancyLogsText); + ui->allLogsText->setText(allLogsText); + ui->fancyLogsText->verticalScrollBar()->setValue(ui->fancyLogsText->verticalScrollBar()->maximum()); + ui->allLogsText->verticalScrollBar()->setValue(ui->allLogsText->verticalScrollBar()->maximum()); + } +} + +void WifiLoggerDialog::on_refreshBtn_clicked() { + if (currentPage == 0) { + if (waitingForFile == false) { + setWifiInfoPage(); + } + } else { + updateLogs(); + } +} diff --git a/src/widgets/dialogs/wifi/wifilogger.h b/src/ui/widgets/dialogs/wifi/wifilogger.h similarity index 84% rename from src/widgets/dialogs/wifi/wifilogger.h rename to src/ui/widgets/dialogs/wifi/wifilogger.h index e10bd92..d6ce173 100644 --- a/src/widgets/dialogs/wifi/wifilogger.h +++ b/src/ui/widgets/dialogs/wifi/wifilogger.h @@ -5,23 +5,23 @@ #include "functions.h" namespace Ui { -class wifilogger; +class WifiLoggerDialog; } -class wifilogger : public QDialog +class WifiLoggerDialog : public QDialog { Q_OBJECT public: QString className = this->metaObject()->className(); - explicit wifilogger(QWidget *parent = nullptr); - ~wifilogger(); + explicit WifiLoggerDialog(QWidget *parent = nullptr); + ~WifiLoggerDialog(); global::wifi::wifiNetworkData connectedNetworkData; // To the above value bool isThereData = false; private: - Ui::wifilogger *ui; + Ui::WifiLoggerDialog *ui; /* * 0 Is Wi-Fi info/no Wi-Fi info page * 1 Is fancy logs page diff --git a/src/widgets/dialogs/wifi/wifilogger.ui b/src/ui/widgets/dialogs/wifi/wifilogger.ui similarity index 99% rename from src/widgets/dialogs/wifi/wifilogger.ui rename to src/ui/widgets/dialogs/wifi/wifilogger.ui index f58e5ae..c217485 100644 --- a/src/widgets/dialogs/wifi/wifilogger.ui +++ b/src/ui/widgets/dialogs/wifi/wifilogger.ui @@ -1,7 +1,7 @@ - wifilogger - + WifiLoggerDialog + 0 diff --git a/src/widgets/interfaceWidgets/qclickablelabel.cpp b/src/ui/widgets/interfaceWidgets/qclickablelabel.cpp similarity index 100% rename from src/widgets/interfaceWidgets/qclickablelabel.cpp rename to src/ui/widgets/interfaceWidgets/qclickablelabel.cpp diff --git a/src/widgets/interfaceWidgets/qclickablelabel.h b/src/ui/widgets/interfaceWidgets/qclickablelabel.h similarity index 100% rename from src/widgets/interfaceWidgets/qclickablelabel.h rename to src/ui/widgets/interfaceWidgets/qclickablelabel.h diff --git a/src/widgets/interfaceWidgets/qtooltiplabel.cpp b/src/ui/widgets/interfaceWidgets/qtooltiplabel.cpp similarity index 100% rename from src/widgets/interfaceWidgets/qtooltiplabel.cpp rename to src/ui/widgets/interfaceWidgets/qtooltiplabel.cpp diff --git a/src/widgets/interfaceWidgets/qtooltiplabel.h b/src/ui/widgets/interfaceWidgets/qtooltiplabel.h similarity index 100% rename from src/widgets/interfaceWidgets/qtooltiplabel.h rename to src/ui/widgets/interfaceWidgets/qtooltiplabel.h diff --git a/src/widgets/interfaceWidgets/toast.cpp b/src/ui/widgets/interfaceWidgets/toast.cpp similarity index 100% rename from src/widgets/interfaceWidgets/toast.cpp rename to src/ui/widgets/interfaceWidgets/toast.cpp diff --git a/src/widgets/interfaceWidgets/toast.h b/src/ui/widgets/interfaceWidgets/toast.h similarity index 100% rename from src/widgets/interfaceWidgets/toast.h rename to src/ui/widgets/interfaceWidgets/toast.h diff --git a/src/widgets/interfaceWidgets/toast.ui b/src/ui/widgets/interfaceWidgets/toast.ui similarity index 100% rename from src/widgets/interfaceWidgets/toast.ui rename to src/ui/widgets/interfaceWidgets/toast.ui diff --git a/src/widgets/misc/egg.cpp b/src/ui/widgets/misc/egg.cpp similarity index 82% rename from src/widgets/misc/egg.cpp rename to src/ui/widgets/misc/egg.cpp index 09684ee..c52dd3f 100644 --- a/src/widgets/misc/egg.cpp +++ b/src/ui/widgets/misc/egg.cpp @@ -1,10 +1,13 @@ #include "egg.h" #include "ui_egg.h" +#include "device.h" + egg::egg(QWidget *parent) : QDialog(parent), ui(new Ui::egg) { + Device* device = Device::getSingleton(); ui->setupUi(this); this->setStyleSheet(readFile("/mnt/onboard/.adds/inkbox/eink.qss")); ui->previousBtn->setProperty("type", "borderless"); @@ -21,19 +24,24 @@ egg::egg(QWidget *parent) : ui->infoBtn->setIcon(QIcon(":/resources/info.png")); ui->titleLabel->setFont(QFont("Inter")); ui->contributorName->setFont(QFont("Inter")); - if(global::deviceID == "n873\n") { - ui->nextBtn->setStyleSheet("padding: 13.5px"); - ui->previousBtn->setStyleSheet("padding: 13.5px"); - } - else if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { - ui->nextBtn->setStyleSheet("padding: 12.5px"); - ui->previousBtn->setStyleSheet("padding: 12.5px"); - } - else { - ui->nextBtn->setStyleSheet("padding: 10px"); - ui->previousBtn->setStyleSheet("padding: 10px"); + + Device::ScreenSize screenSize = device->getScreenSize(); + QString padding = ""; + if(screenSize == Device::ScreenSize::SMALL) { + padding = "10px"; + } else if(screenSize == Device::ScreenSize::MEDIUM) { + padding = "11px"; + } else if(screenSize == Device::ScreenSize::LARGE) { + padding = "12.5px"; + } else if(screenSize == Device::ScreenSize::VERY_LARGE) { + padding = "13.5px"; } + + ui->nextBtn->setStyleSheet("padding: " + padding); + ui->previousBtn->setStyleSheet("padding: " + padding); + + graphicsScene = new QGraphicsScene(this); // Set first contributor name ui->contributorName->setText("
Szybet
(Contributor)
"); diff --git a/src/widgets/misc/egg.h b/src/ui/widgets/misc/egg.h similarity index 100% rename from src/widgets/misc/egg.h rename to src/ui/widgets/misc/egg.h diff --git a/src/widgets/misc/egg.ui b/src/ui/widgets/misc/egg.ui similarity index 100% rename from src/widgets/misc/egg.ui rename to src/ui/widgets/misc/egg.ui diff --git a/src/widgets/misc/hourglassanimationwidget.cpp b/src/ui/widgets/misc/hourglassanimationwidget.cpp similarity index 100% rename from src/widgets/misc/hourglassanimationwidget.cpp rename to src/ui/widgets/misc/hourglassanimationwidget.cpp diff --git a/src/widgets/misc/hourglassanimationwidget.h b/src/ui/widgets/misc/hourglassanimationwidget.h similarity index 100% rename from src/widgets/misc/hourglassanimationwidget.h rename to src/ui/widgets/misc/hourglassanimationwidget.h diff --git a/src/widgets/misc/hourglassanimationwidget.ui b/src/ui/widgets/misc/hourglassanimationwidget.ui similarity index 100% rename from src/widgets/misc/hourglassanimationwidget.ui rename to src/ui/widgets/misc/hourglassanimationwidget.ui diff --git a/src/widgets/reader/dictionarywidget.cpp b/src/ui/widgets/reader/dictionarywidget.cpp similarity index 100% rename from src/widgets/reader/dictionarywidget.cpp rename to src/ui/widgets/reader/dictionarywidget.cpp diff --git a/src/widgets/reader/dictionarywidget.h b/src/ui/widgets/reader/dictionarywidget.h similarity index 100% rename from src/widgets/reader/dictionarywidget.h rename to src/ui/widgets/reader/dictionarywidget.h diff --git a/src/widgets/reader/dictionarywidget.ui b/src/ui/widgets/reader/dictionarywidget.ui similarity index 100% rename from src/widgets/reader/dictionarywidget.ui rename to src/ui/widgets/reader/dictionarywidget.ui diff --git a/src/widgets/text/searchresultswidget.cpp b/src/ui/widgets/text/searchresultswidget.cpp similarity index 98% rename from src/widgets/text/searchresultswidget.cpp rename to src/ui/widgets/text/searchresultswidget.cpp index 6bd9782..093d8e3 100644 --- a/src/widgets/text/searchresultswidget.cpp +++ b/src/ui/widgets/text/searchresultswidget.cpp @@ -66,7 +66,7 @@ void searchResultsWidget::on_openBtn_clicked() item = index.data(Qt::DisplayRole).toString(); global::library::bookTitle = item; - bookInfoDialog * bookInfoDialogWindow = new bookInfoDialog(); + BookInfoDialog * bookInfoDialogWindow = new BookInfoDialog(); connect(bookInfoDialogWindow, SIGNAL(showToast(QString)), SLOT(showToastNative(QString))); connect(bookInfoDialogWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToastNative())); connect(bookInfoDialogWindow, SIGNAL(destroyed(QObject*)), SLOT(close())); diff --git a/src/widgets/text/searchresultswidget.h b/src/ui/widgets/text/searchresultswidget.h similarity index 95% rename from src/widgets/text/searchresultswidget.h rename to src/ui/widgets/text/searchresultswidget.h index 34c6afe..5a3d0dc 100644 --- a/src/widgets/text/searchresultswidget.h +++ b/src/ui/widgets/text/searchresultswidget.h @@ -30,7 +30,7 @@ private slots: private: Ui::searchResultsWidget *ui; - bookInfoDialog * bookInfoDialogWindow; + BookInfoDialog * bookInfoDialogWindow; signals: void openBookFile(QString book, bool relativePath); diff --git a/src/widgets/text/searchresultswidget.ui b/src/ui/widgets/text/searchresultswidget.ui similarity index 100% rename from src/widgets/text/searchresultswidget.ui rename to src/ui/widgets/text/searchresultswidget.ui diff --git a/src/ui/widgets/text/textwidget.cpp b/src/ui/widgets/text/textwidget.cpp new file mode 100644 index 0000000..65d5940 --- /dev/null +++ b/src/ui/widgets/text/textwidget.cpp @@ -0,0 +1,26 @@ +#include "textwidget.h" +#include "functions.h" +#include "ui.h" +#include "ui_textwidget.h" + +#include +#include + +textwidget::textwidget(QWidget *parent) : + QWidget(parent), + ui(new Ui::textwidget) { + ui->setupUi(this); + ui->textBrowser->setFont(QFont("u001")); + + // Stylesheet + UI::applyStyle(*this, "eink"); + + if (global::text::textBrowserDialog == true) { + ui->textBrowser->setStyleSheet("font-size: 9pt"); + } + ui->textBrowser->setText(global::text::textBrowserContents); +} + +textwidget::~textwidget() { + delete ui; +} diff --git a/src/widgets/text/textwidget.h b/src/ui/widgets/text/textwidget.h similarity index 100% rename from src/widgets/text/textwidget.h rename to src/ui/widgets/text/textwidget.h diff --git a/src/widgets/text/textwidget.ui b/src/ui/widgets/text/textwidget.ui similarity index 100% rename from src/widgets/text/textwidget.ui rename to src/ui/widgets/text/textwidget.ui diff --git a/src/widgets/virtualKeyboard/virtualkeyboard.cpp b/src/ui/widgets/virtualKeyboard/virtualkeyboard.cpp similarity index 52% rename from src/widgets/virtualKeyboard/virtualkeyboard.cpp rename to src/ui/widgets/virtualKeyboard/virtualkeyboard.cpp index 114df10..3fb9b51 100644 --- a/src/widgets/virtualKeyboard/virtualkeyboard.cpp +++ b/src/ui/widgets/virtualKeyboard/virtualkeyboard.cpp @@ -1,5 +1,6 @@ #include "virtualkeyboard.h" #include "ui_virtualkeyboard.h" +#include "device.h" #include #include @@ -9,6 +10,20 @@ virtualkeyboard::virtualkeyboard(QWidget *parent) : QWidget(parent), ui(new Ui::virtualkeyboard) { + Device* device = Device::getSingleton(); + + Device::ScreenSize size = device->getScreenSize(); + QString padding = ""; + if(size == Device::ScreenSize::SMALL) { + padding = "11.45px"; + } else if(size == Device::ScreenSize::MEDIUM) { + padding = "13px"; + } else if(size == Device::ScreenSize::LARGE) { + padding = "20px"; + } else { + padding = "27px"; + } + ui->setupUi(this); this->setStyleSheet(readFile("/mnt/onboard/.adds/inkbox/eink.qss")); @@ -22,16 +37,9 @@ virtualkeyboard::virtualkeyboard(QWidget *parent) : ui->closeBtn->setProperty("type", "borderless"); ui->enterBtn->setProperty("type", "borderless"); { - int padding = 13; - if(global::deviceID == "n873\n") { - padding = 27; - } - else if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { - padding = 20; - } - ui->closeBtn->setStyleSheet("font-weight: bold; font-size: 9pt; padding: " + QString::number(padding) + "px"); + ui->closeBtn->setStyleSheet("font-weight: bold; font-size: 9pt; padding: " + padding); ui->closeBtn->setIcon(QIcon(":/resources/close.png")); - ui->enterBtn->setStyleSheet("font-weight: bold; font-size: 9pt; padding: " + QString::number(padding) + "px"); + ui->enterBtn->setStyleSheet("font-weight: bold; font-size: 9pt; padding: " + padding); ui->enterBtn->setIcon(QIcon(":/resources/arrow-right.png")); } } @@ -91,186 +99,50 @@ virtualkeyboard::virtualkeyboard(QWidget *parent) : ui->spt->setProperty("type", "borderless"); ui->sat->setProperty("type", "borderless"); - if(global::deviceID == "n873\n") { - ui->n1->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->n2->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->n3->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->n4->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->n5->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->n6->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->n7->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->n8->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->n9->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->n0->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); + ui->n1->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->n2->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->n3->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->n4->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->n5->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->n6->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->n7->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->n8->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->n9->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->n0->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); - ui->la->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lb->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lc->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->ld->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->le->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lf->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lg->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lh->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->li->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lj->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lk->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->ll->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lm->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->ln->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lo->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lp->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lq->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lr->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->ls->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lt->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lu->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lv->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lw->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lx->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->ly->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->lz->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); + ui->la->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lb->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lc->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->ld->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->le->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lf->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lg->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lh->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->li->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lj->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lk->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->ll->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lm->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->ln->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lo->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lp->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lq->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lr->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->ls->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lt->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lu->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lv->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lw->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lx->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->ly->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->lz->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); - ui->eraseBtn->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->shiftBtn->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->spt->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 27px"); - ui->sat->setStyleSheet("font-weight: bold; font-size: 7pt; padding: 27px"); - ui->spaceBtn->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 15px; border: 1px solid black"); - } - else if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { - ui->n1->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->n2->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->n3->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->n4->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->n5->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->n6->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->n7->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->n8->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->n9->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->n0->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); + ui->eraseBtn->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->shiftBtn->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->spt->setStyleSheet("font-weight: bold; font-size: 9pt; padding: "+padding); + ui->sat->setStyleSheet("font-weight: bold; font-size: 7pt; padding: "+padding); + ui->spaceBtn->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 10px; border: 1px solid black"); - ui->la->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lb->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lc->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->ld->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->le->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lf->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lg->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lh->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->li->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lj->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lk->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->ll->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lm->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->ln->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lo->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lp->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lq->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lr->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->ls->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lt->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lu->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lv->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lw->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lx->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->ly->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->lz->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - - ui->eraseBtn->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->shiftBtn->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->spt->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 20px"); - ui->sat->setStyleSheet("font-weight: bold; font-size: 7pt; padding: 20px"); - ui->spaceBtn->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 15px; border: 1px solid black"); - } - else if(global::deviceID == "n705\n") { - ui->n1->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->n2->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->n3->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->n4->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->n5->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->n6->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->n7->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->n8->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->n9->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->n0->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - - ui->la->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lb->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lc->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->ld->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->le->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lf->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lg->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lh->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->li->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lj->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lk->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->ll->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lm->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->ln->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lo->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lp->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lq->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lr->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->ls->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lt->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lu->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lv->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lw->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lx->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->ly->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->lz->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - - ui->eraseBtn->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->shiftBtn->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->spt->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 11.45px"); - ui->sat->setStyleSheet("font-weight: bold; font-size: 7pt; padding: 11.45px"); - ui->spaceBtn->setStyleSheet("font-weight: bold; font-size: 8pt; padding: 10px; border: 1px solid black"); - } - else { - ui->n1->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->n2->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->n3->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->n4->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->n5->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->n6->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->n7->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->n8->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->n9->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->n0->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - - ui->la->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lb->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lc->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->ld->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->le->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lf->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lg->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lh->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->li->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lj->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lk->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->ll->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lm->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->ln->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lo->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lp->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lq->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lr->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->ls->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lt->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lu->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lv->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lw->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lx->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->ly->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->lz->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - - ui->eraseBtn->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->shiftBtn->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->spt->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 13px"); - ui->sat->setStyleSheet("font-weight: bold; font-size: 7pt; padding: 13px"); - ui->spaceBtn->setStyleSheet("font-weight: bold; font-size: 9pt; padding: 10px; border: 1px solid black"); - } ui->lineEdit->setStyleSheet("border: 3px solid black"); if(global::keyboard::vncDialog == true or global::keyboard::wifiPassphraseDialog == true or global::keyboard::encfsDialog == true) { diff --git a/src/widgets/virtualKeyboard/virtualkeyboard.h b/src/ui/widgets/virtualKeyboard/virtualkeyboard.h similarity index 100% rename from src/widgets/virtualKeyboard/virtualkeyboard.h rename to src/ui/widgets/virtualKeyboard/virtualkeyboard.h diff --git a/src/widgets/virtualKeyboard/virtualkeyboard.ui b/src/ui/widgets/virtualKeyboard/virtualkeyboard.ui similarity index 100% rename from src/widgets/virtualKeyboard/virtualkeyboard.ui rename to src/ui/widgets/virtualKeyboard/virtualkeyboard.ui diff --git a/src/widgets/virtualKeyboard/virtualkeypad.cpp b/src/ui/widgets/virtualKeyboard/virtualkeypad.cpp similarity index 100% rename from src/widgets/virtualKeyboard/virtualkeypad.cpp rename to src/ui/widgets/virtualKeyboard/virtualkeypad.cpp diff --git a/src/widgets/virtualKeyboard/virtualkeypad.h b/src/ui/widgets/virtualKeyboard/virtualkeypad.h similarity index 100% rename from src/widgets/virtualKeyboard/virtualkeypad.h rename to src/ui/widgets/virtualKeyboard/virtualkeypad.h diff --git a/src/widgets/virtualKeyboard/virtualkeypad.ui b/src/ui/widgets/virtualKeyboard/virtualkeypad.ui similarity index 100% rename from src/widgets/virtualKeyboard/virtualkeypad.ui rename to src/ui/widgets/virtualKeyboard/virtualkeypad.ui diff --git a/src/widgets/dialogs/brightnessdialog.cpp b/src/widgets/dialogs/brightnessdialog.cpp deleted file mode 100644 index 607e6df..0000000 --- a/src/widgets/dialogs/brightnessdialog.cpp +++ /dev/null @@ -1,229 +0,0 @@ -#include "brightnessdialog.h" -#include "ui_brightnessdialog.h" -#include "functions.h" - -#include -#include -#include -#include - -brightnessDialog::brightnessDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::brightnessDialog) -{ - ui->setupUi(this); - brightnessDialog::setFont(QFont("u001")); - - // Stylesheet, style & misc. - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - ui->quitBtn->setProperty("type", "borderless"); - ui->quitBtn->setText(""); - ui->quitBtn->setIcon(QIcon(":/resources/close.png")); - ui->okBtn->setProperty("type", "borderless"); - ui->okBtn->setText(""); - ui->okBtn->setIcon(QIcon(":/resources/check.png")); - ui->decBtn->setProperty("type", "borderless"); - ui->decBtn->setText(""); - ui->decBtn->setIcon(QIcon(":/resources/minus.png")); - ui->incBtn->setProperty("type", "borderless"); - ui->incBtn->setText(""); - ui->incBtn->setIcon(QIcon(":/resources/plus.png")); - ui->brightnessLabel->setStyleSheet("padding-left: 125px; padding-right: 125px; font:bold"); - ui->valueLabel->setStyleSheet("font-size: 9pt"); - ui->warmthValueLabel->setStyleSheet("font-size: 9pt"); - - if(global::isN249 == false and global::isN873 == false) { - ui->warmthSlider->hide(); - ui->warmthDecBtn->hide(); - ui->warmthIncBtn->hide(); - ui->warmthValueLabel->hide(); - ui->warmthSlider->deleteLater(); - ui->warmthDecBtn->deleteLater(); - ui->warmthIncBtn->deleteLater(); - ui->gridLayout_5->deleteLater(); - ui->warmthValueLabel->deleteLater(); - this->adjustSize(); - } - else if(global::isN249 == true or global::isN873 == true) { - ui->warmthDecBtn->setProperty("type", "borderless"); - ui->warmthIncBtn->setProperty("type", "borderless"); - ui->warmthDecBtn->setText(""); - ui->warmthIncBtn->setText(""); - ui->warmthDecBtn->setIcon(QIcon(":/resources/nightmode-empty.png")); - ui->warmthIncBtn->setIcon(QIcon(":/resources/nightmode-full.png")); - } - else { - ui->warmthSlider->hide(); - ui->warmthDecBtn->hide(); - ui->warmthIncBtn->hide(); - ui->warmthValueLabel->hide(); - ui->warmthSlider->deleteLater(); - ui->warmthDecBtn->deleteLater(); - ui->warmthIncBtn->deleteLater(); - ui->gridLayout_5->deleteLater(); - ui->warmthValueLabel->deleteLater(); - this->adjustSize(); - } - - int value; - int warmthValue; - if(global::isN249 == true or global::isN873 == true) { - if(global::isN249 == true) { - ui->warmthSlider->setMaximum(100); - } - else if(global::isN873 == true) { - ui->warmthSlider->setMaximum(10); - } - } - if(global::isN249 or global::isN873 == true) { - value = getBrightness(); - if(global::isN249 == true or global::isN873 == true) { - warmthValue = getWarmth(); - if(warmthValue == 0) { - if(global::isN249 == true) { - ui->warmthValueLabel->setText("0%"); - } - else { - ui->warmthValueLabel->setText("0"); - } - } - else { - ui->warmthSlider->setValue(warmthValue); - } - } - } - else if(global::isN613 == true) { - setDefaultWorkDir(); - value = brightnessCheckconfig(".config/03-brightness/config"); - } - else { - value = getBrightness(); - } - - // Setting the slider to the appropriate position - ui->horizontalSlider->setValue(value); - - // Showing brightness percentage on label - QString valueStr = QString::number(value); - valueStr = valueStr.append("%"); - ui->valueLabel->setText(valueStr); - - // Saving current brightness value in case we want to go backwards - if(global::isN249 == true or global::isN873 == true) { - oldValue = getBrightness(); - if(global::isN249 == true or global::isN873 == true) { - oldWarmthValue = getWarmth(); - } - } - else if(global::isN613 == true) { - setDefaultWorkDir(); - oldValue = brightnessCheckconfig(".config/03-brightness/config"); - } - else { - oldValue = getBrightness(); - } -} - -brightnessDialog::~brightnessDialog() -{ - delete ui; -} - -void brightnessDialog::on_quitBtn_clicked() -{ - // Reverting back to the old value - brightnessDialog::preSetBrightness(oldValue); - if(global::isN249 == true or global::isN873 == true) { - setWarmth(oldWarmthValue); - } - - // Just in case ;) - brightnessWriteconfig(oldValue); - if(global::isN249 == true or global::isN873 == true) { - warmthWriteconfig(oldWarmthValue); - } - - // Leaving - brightnessDialog::close(); -} - -void brightnessDialog::on_horizontalSlider_valueChanged(int value) -{ - brightnessDialog::preSetBrightness(value); - QString valueStr = QString::number(value); - valueStr = valueStr.append("%"); - ui->valueLabel->setText(valueStr); -} - -void brightnessDialog::on_incBtn_clicked() -{ - int value = ui->horizontalSlider->value(); - value = value + 1; - ui->horizontalSlider->setValue(value); -} - -void brightnessDialog::on_decBtn_clicked() -{ - int value = ui->horizontalSlider->value(); - value = value - 1; - ui->horizontalSlider->setValue(value); -} - -void brightnessDialog::on_okBtn_clicked() -{ - // Get set brightness value - int brightnessValue = ui->horizontalSlider->value(); - int warmthValue; - - // Write brightness config - log("Display brightness set to " + QString::number(brightnessValue), className); - brightnessWriteconfig(brightnessValue); - if(global::isN249 == true or global::isN873 == true) { - warmthValue = ui->warmthSlider->value(); - log("Display warmth set to " + QString::number(warmthValue), className); - warmthWriteconfig(warmthValue); - } - - // Leaving - brightnessDialog::close(); -} - -void brightnessDialog::preSetBrightness(int brightnessValue) { - if(global::isN613 == true) { - setBrightness_ntxio(brightnessValue); - } - else { - setBrightness(brightnessValue); - } -} - -void brightnessDialog::on_warmthSlider_valueChanged(int value) -{ - setWarmth(value); - QString valueStr = QString::number(value); - if(global::isN249 == true) { - valueStr = valueStr + "%"; - } - ui->warmthValueLabel->setText(valueStr); -} - - -void brightnessDialog::on_warmthDecBtn_clicked() -{ - int value = ui->warmthSlider->value(); - value = value - 1; - ui->warmthSlider->setValue(value); -} - - -void brightnessDialog::on_warmthIncBtn_clicked() -{ - int value = ui->warmthSlider->value(); - value = value + 1; - ui->warmthSlider->setValue(value); -} - diff --git a/src/widgets/dialogs/generaldialog.cpp b/src/widgets/dialogs/generaldialog.cpp deleted file mode 100644 index e3a9299..0000000 --- a/src/widgets/dialogs/generaldialog.cpp +++ /dev/null @@ -1,869 +0,0 @@ -#include "generaldialog.h" -#include "ui_generaldialog.h" -#include "functions.h" -#include "reader.h" -#include "mainwindow.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -generalDialog::generalDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::generalDialog) -{ - ui->setupUi(this); - ui->bodyLabel->setFont(QFont("u001")); - ui->searchComboBox->setFont(QFont("u001")); - - // Preventing outside interaction - this->setModal(true); - - // Stylesheet, style & misc. - if(global::keyboard::encfsDialog == true) { - QFile stylesheetFile(":/resources/eink-square-encfs.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - } - else { - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - } - - ui->okBtn->setProperty("type", "borderless"); - ui->cancelBtn->setProperty("type", "borderless"); - ui->acceptBtn->setProperty("type", "borderless"); - - ui->okBtn->setStyleSheet("font-size: 9pt; padding: 10px; font-weight: bold; background: lightGrey"); - ui->cancelBtn->setStyleSheet("font-size: 9pt; padding: 10px; font-weight: bold; background: lightGrey"); - ui->acceptBtn->setStyleSheet("font-size: 9pt; padding: 10px; font-weight: bold; background: lightGrey"); - ui->headerLabel->setStyleSheet("font-weight: bold"); - ui->bodyLabel->setStyleSheet("font-size: 9.5pt"); - ui->searchComboBox->setStyleSheet("font-size: 9pt"); - - // Disabling "Online library" search if device doesn't have Wi-Fi - if(global::device::isWifiAble == false && global::deviceID != "emu\n") { - ui->searchComboBox->removeItem(2); - } - - if(QFile::exists("/inkbox/searchComboBoxFunction") == true) { - QString searchComboBoxFunction = readFile("/inkbox/searchComboBoxFunction"); - if(searchComboBoxFunction == "Dictionary") { - ui->searchComboBox->setCurrentIndex(0); - } - else if(searchComboBoxFunction == "Local storage") { - ui->searchComboBox->setCurrentIndex(1); - } - else if(searchComboBoxFunction == "Online library") { - ui->searchComboBox->setCurrentIndex(2); - } - else { - ui->searchComboBox->setCurrentIndex(0); - } - } - - if(checkconfig("/inkbox/resetDialog") == true) { - if(checkconfig("/opt/inkbox_genuine") == true) { - resetDialog = true; - ui->okBtn->setText("Proceed"); - ui->cancelBtn->setText("Go back"); - if(global::deviceID != "n705\n") { - ui->bodyLabel->setText("This will erase any books you have stored on the device.\nSettings will be reset."); - } - else { - ui->bodyLabel->setText("This will erase any books\nyou have stored on the device.\nSettings will be reset."); - } - ui->headerLabel->setText("Warning"); - QTimer::singleShot(50, this, SLOT(adjust_size())); - writeFile("/inkbox/resetDialog", "false"); - } - else { - resetDialog = true; - ui->okBtn->setText("Proceed"); - ui->cancelBtn->setText("Go back"); - ui->bodyLabel->setText("Settings will be reset."); - ui->headerLabel->setText("Warning"); - QTimer::singleShot(50, this, SLOT(adjust_size())); - writeFile("/inkbox/resetDialog", "false"); - } - } - else if(checkconfig("/inkbox/updateDialog") == true) { - updateDialog = true; - ui->okBtn->setText("Update"); - ui->cancelBtn->setText("Not now"); - ui->bodyLabel->setText("Do you want to update InkBox now?"); // Because I hate Univers/U001's question mark ... - ui->headerLabel->setText("Update available"); - QTimer::singleShot(50, this, SLOT(adjust_size())); - writeFile("/inkbox/updateDialog", "false"); - } - else if(global::settings::settingsRebootDialog == true) { - settingsRebootDialog = true; - ui->stackedWidget->setCurrentIndex(1); - if(global::kobox::koboxSettingsRebootDialog == true or global::encfs::enableStorageEncryptionDialog) { - koboxSettingsRebootDialog = true; - ui->bodyLabel->setText("The device will reboot now, since
the settings you defined require it to work properly."); - } - else { - ui->bodyLabel->setText("The settings you defined might
require a complete reboot of the device for them to work properly."); - } - ui->headerLabel->setText("Information"); - QTimer::singleShot(50, this, SLOT(adjust_size())); - } - else if(global::mainwindow::lowBatteryDialog == true) { - lowBatteryDialog = true; - ui->stackedWidget->setCurrentIndex(1); - getBatteryLevel(); - QString message = "The battery's level is low.\nPlease charge your eReader.\nCurrent level: "; - message.append(batteryLevel); - ui->bodyLabel->setText(message); - ui->headerLabel->setText("Low battery"); - QTimer::singleShot(50, this, SLOT(adjust_size())); - writeFile("/inkbox/lowBatteryDialog", "false"); - } - else if(global::usbms::usbmsDialog == true) { - usbmsDialog = true; - ui->stackedWidget->setCurrentIndex(0); - ui->okBtn->setText("Connect"); - ui->cancelBtn->setText("Not now"); - ui->bodyLabel->setText("Do you want to connect your device to a computer to manage books?"); - ui->headerLabel->setText("USB cable connected"); - QTimer::singleShot(50, this, SLOT(adjust_size())); - } - else if(global::text::textBrowserDialog == true) { - textBrowserDialog = true; - textwidgetWindow = new textwidget(); - - if(global::text::textBrowserTitle.isEmpty() == true) { - ui->headerLabel->setText("Information"); - } - else { - ui->headerLabel->setText(global::text::textBrowserTitle); - } - // Important - ui->bodyLabel->setText(global::text::textBrowserContents); - - ui->stackedWidget->setCurrentIndex(1); - ui->mainStackedWidget->insertWidget(1, textwidgetWindow); - ui->mainStackedWidget->setCurrentIndex(1); - QTimer::singleShot(50, this, SLOT(adjust_size())); - } - else if(global::kobox::resetKoboxDialog == true) { - resetKoboxDialog = true; - ui->headerLabel->setText("Warning"); - ui->okBtn->setText("Proceed"); - ui->cancelBtn->setText("Go back"); - ui->bodyLabel->setText("This will erase all KoBox user data. KoBox settings will be reset."); - QTimer::singleShot(50, this, SLOT(adjust_size())); - } - else if(global::keyboard::keyboardDialog == true) { - setupKeyboardDialog(); - } - else if(global::keyboard::keypadDialog == true) { - keypadDialog = true; - keypadWidget = new virtualkeypad(); - ui->headerLabel->setText("Enter a number"); - ui->okBtn->setText("OK"); - ui->cancelBtn->setText("Cancel"); - ui->mainStackedWidget->insertWidget(1, keypadWidget); - ui->mainStackedWidget->setCurrentIndex(1); - QTimer::singleShot(50, this, SLOT(adjust_size())); - } - else if(global::encfs::disableStorageEncryptionDialog == true) { - ui->headerLabel->setText("Warning"); - ui->okBtn->setText("Proceed"); - ui->cancelBtn->setText("Go back"); - ui->bodyLabel->setText("This will delete all the files you have encrypted. Are you sure you want to continue?"); - QTimer::singleShot(50, this, SLOT(adjust_size())); - } - else if(global::encfs::errorNoBooksInDropboxDialog == true) { - ui->stackedWidget->setCurrentIndex(1); - ui->headerLabel->setText("Error"); - ui->bodyLabel->setText("Please put books in the 'encfs-dropbox' folder to repack your encrypted storage."); - QTimer::singleShot(50, this, SLOT(adjust_size())); - } - else if(global::encfs::repackDialog == true) { - ui->headerLabel->setText("Information"); - ui->okBtn->setText("Proceed"); - ui->cancelBtn->setText("Not now"); - ui->bodyLabel->setText("New files have been found in 'encfs-dropbox'. Would you want to repack your encrypted storage?"); - QTimer::singleShot(50, this, SLOT(adjust_size())); - } - else if(global::userApps::appCompatibilityDialog == true) { - appCompatibilityDialog = true; - global::userApps::appCompatibilityLastContinueStatus = true; - ui->okBtn->setText("Continue"); - ui->cancelBtn->setText("Cancel"); - ui->bodyLabel->setText(global::userApps::appCompatibilityText); - ui->headerLabel->setText("Compatibility warning"); - QTimer::singleShot(50, this, SLOT(adjust_size())); - } - else if(global::userApps::appInfoDialog == true) { - appInfoDialog = true; - textwidgetWindow = new textwidget(); - - ui->headerLabel->setText("App info"); - ui->stackedWidget->setCurrentIndex(1); - ui->mainStackedWidget->insertWidget(1, textwidgetWindow); - ui->mainStackedWidget->setCurrentIndex(1); - yIncrease = 1.8; - QTimer::singleShot(50, this, SLOT(increaseSize())); - } - else if(global::library::librarySyncDialog == true) { - librarySyncDialog = true; - ui->okBtn->setText("Continue"); - ui->cancelBtn->setText("Not now"); - ui->bodyLabel->setText("Online library requires syncing. Do you want to continue?"); - ui->headerLabel->setText("Sync required"); - QTimer::singleShot(50, this, SLOT(adjust_size())); - } - else if(global::telemetry::telemetryDialog == true) { - telemetryDialog = true; - ui->stackedWidget->setCurrentIndex(0); - ui->okBtn->setText("Send"); - ui->cancelBtn->setText("Don't send"); - ui->bodyLabel->setText("We, the InkBox OS developers, would like to know a bit more about our userbase.
We would be extremely grateful if you would allow us to collect some information about your device.
Would you like to send it to us
?
No personal data will be transmitted.
"); - ui->headerLabel->setText("Telemetry request"); - QTimer::singleShot(50, this, SLOT(adjust_size())); - } - else { - // We shouldn't be there ;) - log("Launched without settings", className); - } -} - -generalDialog::~generalDialog() -{ - delete ui; -} - -void generalDialog::on_cancelBtn_clicked() -{ - log("Cancel button clicked", className); - if(updateDialog == true) { - writeFile("/tmp/cancelUpdateDialog", "true"); - generalDialog::close(); - } - else if(usbmsDialog == true) { - global::usbms::usbmsDialog = false; - generalDialog::close(); - } - else if(resetKoboxDialog == true) { - global::kobox::resetKoboxDialog = false; - generalDialog::close(); - } - else if(keypadDialog == true) { - global::keyboard::keypadDialog = false; - generalDialog::close(); - } - else if(global::encfs::disableStorageEncryptionDialog == true) { - emit cancelDisableStorageEncryption(); - global::encfs::disableStorageEncryptionDialog = false; - generalDialog::close(); - } - else { - if(global::keyboard::searchDialog == true) { - global::keyboard::searchDialog = false; - global::forbidOpenSearchDialog = true; - global::keyboard::keyboardDialog = false; - global::keyboard::keyboardText = ""; - global::library::librarySearchDialog = false; - } - else if(global::keyboard::vncDialog == true) { - global::keyboard::vncDialog = false; - global::keyboard::keyboardDialog = false; - global::keyboard::keyboardText = ""; - } - else if(global::keyboard::encfsDialog == true) { - global::keyboard::encfsDialog = false; - global::encfs::cancelSetup = true; - global::keyboard::keyboardText = ""; - } - else if(global::encfs::errorNoBooksInDropboxDialog == true) { - global::encfs::errorNoBooksInDropboxDialog = false; - } - else if(global::encfs::repackDialog == true) { - global::encfs::repackDialog = false; - } - else if(global::userApps::appCompatibilityDialog == true) { - global::userApps::launchApp = false; - global::userApps::appCompatibilityLastContinueStatus = false; - global::userApps::appCompatibilityText = ""; - global::userApps::appCompatibilityDialog = false; - } - else if(global::library::librarySyncDialog == true) { - emit noSyncOnlineLibrary(); - global::library::librarySyncDialog = false; - } - else if(global::telemetry::telemetryDialog == true) { - global::telemetry::telemetryDialog = false; - log("User declined telemetry request", className); - writeFile("/mnt/onboard/.adds/inkbox/.config/24-telemetry/asked", "true"); - } - else if(global::keyboard::telemetryMessageDialog == true) { - global::keyboard::telemetryMessageDialog = false; - emit telemetryMessage(global::keyboard::keyboardText); - global::keyboard::keyboardText = ""; - log("No message to be sent along with collected data", className); - } - generalDialog::close(); - } -} - -void generalDialog::on_okBtn_clicked() -{ - log("OK button clicked", className); - if(resetDialog == true) { - if(checkconfig("/opt/inkbox_genuine") == true) { - // Soft-reset the device - // We set a custom boot flag and reboot silently in Diagnostics - log("Setting up the device for soft-reset", className); - writeFile("/external_root/boot/flags/DIAGS_BOOT", "true\n"); - writeFile("/external_root/boot/flags/DO_SOFT_RESET", "true\n"); - reboot(false); - qApp->quit(); - } - else { - // Restore default settings, we're not on InkBox OS - log("Restoring default settings", className); - QString prog ("sh"); - QStringList args; - args << "reset-config.sh"; - QProcess *proc = new QProcess(); - proc->start(prog, args); - proc->waitForFinished(); - proc->deleteLater(); - - // Relaunching InkBox - QProcess process; - process.startDetached("inkbox.sh", QStringList()); - qApp->quit(); - } - } - if(updateDialog == true) { - if(global::otaUpdate::isUpdateOta == true) { - this->hide(); - - global::otaUpdate::downloadOta = true; - otaManagerWindow = new otaManager(this); - connect(otaManagerWindow, SIGNAL(downloadedOtaUpdate(bool)), SLOT(startOtaUpdate(bool))); - otaManagerWindow->setAttribute(Qt::WA_DeleteOnClose); - - global::toast::indefiniteToast = true; - global::toast::modalToast = true; - emit showToast("Downloading update"); - } - else { - installUpdate(); - qApp->quit(); - } - } - if(usbmsDialog == true) { - log("Showing USBMS splash", className); - global::usbms::usbmsDialog = false; - global::usbms::launchUsbms = true; - - usbmsWindow = new usbmsSplash(); - usbmsWindow->setAttribute(Qt::WA_DeleteOnClose); - usbmsWindow->setGeometry(QRect(QPoint(0,0), screen()->geometry ().size())); - usbmsWindow->show(); - } - if(resetKoboxDialog == true) { - resetKoboxUserData(); - } - if(keypadDialog == true) { - int number = global::keyboard::keypadText.toInt(); - emit gotoPageSelected(number); - global::keyboard::keypadDialog = false; - generalDialog::close(); - } - if(keyboardDialog == true) { - if(global::keyboard::searchDialog == true) { - if(!global::keyboard::keyboardText.isEmpty()) { - if(ui->searchComboBox->currentText() == "Dictionary") { - writeFile("/inkbox/searchComboBoxFunction", "Dictionary"); - for(int i = ui->mainStackedWidget->count(); i >= 0; i--) { - QWidget * widget = ui->mainStackedWidget->widget(i); - ui->mainStackedWidget->removeWidget(widget); - widget->deleteLater(); - } - ui->topStackedWidget->setVisible(false); - ui->stackedWidget->setVisible(false); - dictionaryWidgetWindow = new dictionaryWidget(); - dictionaryWidgetWindow->setAttribute(Qt::WA_DeleteOnClose); - connect(dictionaryWidgetWindow, SIGNAL(refreshScreen()), SLOT(refreshScreenNative())); - connect(dictionaryWidgetWindow, SIGNAL(destroyed(QObject*)), SLOT(restartSearchDialog())); - ui->mainStackedWidget->insertWidget(1, dictionaryWidgetWindow); - } - else if(ui->searchComboBox->currentText() == "Local storage") { - writeFile("/inkbox/searchComboBoxFunction", "Local storage"); - QString onboardPath; - QStringList storageSearchResults; - if(checkconfig("/opt/inkbox_genuine") == true) { - onboardPath = "/mnt/onboard/onboard/"; - } - else { - onboardPath = "/mnt/onboard/"; - } - QDirIterator dirIt(onboardPath, QDirIterator::Subdirectories); - log("Searching local storage for '" + global::keyboard::keyboardText + "'", className); - while(dirIt.hasNext()) { - dirIt.next(); - if(QFileInfo(dirIt.filePath()).isFile()) { - QString suffix = QFileInfo(dirIt.filePath()).suffix(); - if(suffix == "txt" or suffix == "TXT" or suffix == "epub" or suffix == "EPUB" or suffix == "pdf" or suffix == "PDF" or suffix == "png" or suffix == "PNG" or suffix == "tif" or suffix == "TIF" or suffix == "bmp" or suffix == "BMP" or suffix == "tiff" or suffix == "TIFF" or suffix == "jpg" or suffix == "JPG" or suffix == "jpeg" or suffix == "JPEG") { - if(dirIt.fileName().contains(global::keyboard::keyboardText) == true) { - storageSearchResults.append(dirIt.fileName()); - global::localStorage::searchResultsPaths.append(dirIt.filePath()); - } - } - } - } - if(!storageSearchResults.isEmpty()) { - log("Displaying search results", className); - for(int i = ui->mainStackedWidget->count(); i >= 0; i--) { - QWidget * widget = ui->mainStackedWidget->widget(i); - ui->mainStackedWidget->removeWidget(widget); - widget->deleteLater(); - } - ui->topStackedWidget->setVisible(false); - ui->stackedWidget->setVisible(false); - searchResultsWidgetWindow = new searchResultsWidget(this); - searchResultsWidgetWindow->setAttribute(Qt::WA_DeleteOnClose); - global::forbidOpenSearchDialog = true; - connect(searchResultsWidgetWindow, SIGNAL(destroyed(QObject*)), SLOT(restartSearchDialog())); - connect(searchResultsWidgetWindow, SIGNAL(openBookFile(QString, bool)), SLOT(openBookFileNative(QString, bool))); - searchResultsWidgetWindow->setListViewContents(storageSearchResults); - ui->mainStackedWidget->insertWidget(1, searchResultsWidgetWindow); - } - else { - log("No search results found", className); - global::toast::delay = 3000; - emit showToast("No results found"); - keyboardWidget->clearLineEdit(); - global::keyboard::keyboardText = ""; - } - } - else if(ui->searchComboBox->currentText() == "Online library") { - if(testPing() == 0 or global::deviceID == "emu\n") { - writeFile("/inkbox/searchComboBoxFunction", "Online library"); - log("Searching online library for '" + global::keyboard::keyboardText + "'", className); - - if(!readFile("/external_root/opt/storage/gutenberg/last_sync").isEmpty()) { - unsigned long currentEpoch = QDateTime::currentSecsSinceEpoch(); - unsigned long syncEpoch = readFile("/external_root/opt/storage/gutenberg/last_sync").toULong(); - unsigned long allowSyncEpoch = syncEpoch + 86400; - if(currentEpoch > allowSyncEpoch) { - syncGutenbergCatalog(); - } - else { - noGutenbergSyncToDo = true; - } - } - else { - syncGutenbergCatalog(); - } - - QTimer * searchTimer = new QTimer(this); - searchTimer->setInterval(100); - connect(searchTimer, &QTimer::timeout, [&]() { - if(noGutenbergSyncToDo == true or (gutenbergSyncDone == true && gutenbergSyncStatus == true)) { - if(searchTimerDone == false) { - searchTimerDone = true; - writeFile("/inkbox/gutenberg_search_request", global::keyboard::keyboardText); - writeFile("/opt/ibxd", "gutenberg_search\n"); - global::toast::modalToast = true; - global::toast::indefiniteToast = true; - emit showToast("Searching"); - QTimer::singleShot(100, this, SLOT(waitForGutenbergSearchDone())); - } - } - } ); - searchTimer->start(); - } - else { - emit showToast("Wi-Fi connection error"); - } - } - } - else { - global::toast::delay = 3000; - emit showToast("Please type in a search term"); - } - } - else if(global::keyboard::vncDialog == true) { - if(!global::keyboard::keyboardText.isEmpty()) { - log("Gathering VNC connection information", className); - if(vncServerSet != true) { - vncServerAddress = global::keyboard::keyboardText; - vncServerSet = true; - keyboardWidget->clearLineEdit(); - ui->headerLabel->setText("Enter the server's password"); - } - else if(vncPasswordSet != true) { - vncServerPassword = global::keyboard::keyboardText; - vncPasswordSet = true; - keyboardWidget->clearLineEdit(); - ui->headerLabel->setText("Enter the server's port"); - } - else { - vncServerPort = global::keyboard::keyboardText; - global::keyboard::vncDialog = false; - global::keyboard::keyboardDialog = false; - startVNC(vncServerAddress, vncServerPassword, vncServerPort); - generalDialog::close(); - } - } - else { - global::toast::delay = 3000; - emit showToast("Please type in the required argument"); - } - } - else if(global::keyboard::wifiPassphraseDialog == true) { - if(!global::keyboard::keyboardText.isEmpty()) { - if(global::keyboard::keyboardText.count() < 8) { - global::toast::delay = 3000; - showToast("Minimum passphrase length is 8 characters"); - } - else { - generalDialog::close(); - } - } - else { - global::toast::delay = 3000; - showToast("Please type in the required argument"); - } - } - else if(global::keyboard::encfsDialog == true) { - if(!global::keyboard::keyboardText.isEmpty()) { - global::encfs::passphrase = global::keyboard::keyboardText; - global::keyboard::encfsDialog = false; - global::keyboard::keyboardText = ""; - global::keyboard::keyboardDialog = false; - this->close(); - } - else { - global::toast::delay = 3000; - showToast("Please type in the required argument"); - } - } - else if(global::keyboard::telemetryMessageDialog == true) { - if(!global::keyboard::keyboardText.isEmpty()) { - emit telemetryMessage(global::keyboard::keyboardText); - log("Message to be sent along with collected data is: " + global::keyboard::keyboardText, className); - global::keyboard::keyboardText = ""; - global::keyboard::telemetryMessageDialog = false; - global::keyboard::keyboardDialog = false; - this->close(); - } - else { - global::toast::delay = 3000; - showToast("Please type in the required argument"); - } - } - else { - global::keyboard::keyboardDialog = false; - generalDialog::close(); - } - } - if(global::encfs::disableStorageEncryptionDialog == true) { - global::encfs::disableStorageEncryptionDialog = false; - emit disableStorageEncryption(); - this->close(); - } - if(global::encfs::repackDialog == true) { - global::encfs::repackDialog = false; - log("Encrypted storage repack requested", className); - writeFile("/external_root/run/encfs_repack", "true"); - quit_restart(); - } - else if(global::userApps::appCompatibilityDialog == true) { - global::userApps::launchApp = true; - global::userApps::appCompatibilityText = ""; - global::userApps::appCompatibilityLastContinueStatus = true; // Not really necessary, only needed if something fails horribly - global::userApps::appCompatibilityDialog = false; - generalDialog::close(); - } - else if(global::library::librarySyncDialog == true) { - emit syncOnlineLibrary(); - global::library::librarySyncDialog = false; - generalDialog::close(); - } - else if(global::telemetry::telemetryDialog == true) { - global::telemetry::telemetryDialog = false; - global::keyboard::telemetryMessageDialog = true; - generalDialog::close(); - } -} -void generalDialog::on_acceptBtn_clicked() -{ - log("OK button clicked", className); - if(lowBatteryDialog == true) { - global::mainwindow::lowBatteryDialog = false; - global::battery::batteryAlertLock = false; - global::battery::showLowBatteryDialog = false; - } - - if(settingsRebootDialog == true) { - if(koboxSettingsRebootDialog == true or global::encfs::enableStorageEncryptionDialog) { - reboot(true); - qApp->quit(); - } - else { - QProcess process; - process.startDetached("inkbox.sh", QStringList()); - qApp->quit(); - } - } - if(textBrowserDialog == true) { - global::text::textBrowserContents = ""; - global::text::textBrowserTitle = ""; - global::text::textBrowserDialog = false; - } - - if(appInfoDialog == true) { - global::text::textBrowserContents = ""; - global::text::textBrowserTitle = ""; - global::userApps::appInfoDialog = false; - } - - // We don't have any other option ;p - generalDialog::close(); -} - -void generalDialog::adjust_size() { - float widthProportion = 2; - float heightProportion = 2; - if(telemetryDialog) { - if(global::deviceID == "n705\n") { - widthProportion = 3.3; - heightProportion = 2.6; - } - else if(global::deviceID == "n873\n") { - widthProportion = 3; - heightProportion = 2.6; - } - else { - widthProportion = 3.4; - heightProportion = 2.6; - } - } - - this->adjustSize(); - QRect screenGeometry = QGuiApplication::screens()[0]->geometry(); - int x = (screenGeometry.width() - this->width()) / widthProportion; - int y = (screenGeometry.height() - this->height()) / heightProportion; - this->move(x, y); - this->show(); - emit refreshScreen(); -} - -void generalDialog::restartSearchDialog() { - generalDialog::close(); -} - -void generalDialog::setupKeyboardDialog() { - adjust_size(); - ui->stackedWidget->setCurrentIndex(0); - keyboardDialog = true; - ui->stackedWidget->setVisible(true); - if(global::keyboard::searchDialog == true) { - ui->topStackedWidget->setCurrentIndex(1); - ui->searchHeaderLabel->setText("Search"); - ui->okBtn->setText("Search"); - ui->cancelBtn->setText("Close"); - } - else if(global::keyboard::vncDialog == true) { - ui->headerLabel->setText("Enter the server's IP address"); - ui->okBtn->setText("OK"); - ui->cancelBtn->setText("Cancel"); - } - else if(global::keyboard::wifiPassphraseDialog == true) { - ui->headerLabel->setText("Enter the network's passphrase"); - ui->okBtn->setText("Enter"); - ui->cancelBtn->setText("Cancel"); - } - else if(global::keyboard::encfsDialog == true) { - ui->headerLabel->setText("Enter your encrypted storage's passphrase"); - ui->okBtn->setText("OK"); - ui->cancelBtn->setText("Cancel"); - } - else if(global::keyboard::telemetryMessageDialog == true) { - ui->headerLabel->setWordWrap(true); - ui->headerLabel->setText("If you'd like, feel free to send us a random message along with the collected data"); - ui->okBtn->setText("Continue"); - ui->cancelBtn->setText("No, thanks"); - } - else { - ui->headerLabel->setText("Enter a string"); - ui->okBtn->setText("OK"); - ui->cancelBtn->setText("Cancel"); - } - keyboardWidget = new virtualkeyboard(); - connect(keyboardWidget, SIGNAL(adjust_size()), SLOT(adjust_size())); - ui->mainStackedWidget->insertWidget(1, keyboardWidget); - ui->mainStackedWidget->setCurrentIndex(1); - adjust_size(); - QTimer::singleShot(1000, this, SLOT(adjust_size())); -} - -void generalDialog::refreshScreenNative() { - emit refreshScreen(); -} - -void generalDialog::startVNC(QString server, QString password, QString port) { - log("Launching VNC viewer", className); - writeFile("/external_root/tmp/app_vnc_server", server); - writeFile("/external_root/tmp/app_vnc_password", password); - writeFile("/external_root/tmp/app_vnc_port", port); - writeFile("/opt/ibxd", "app_start_vnc\n"); - qApp->quit(); -} - -void generalDialog::startOtaUpdate(bool wasDownloadSuccessful) { - emit closeIndefiniteToast(); - if(wasDownloadSuccessful == true) { - global::otaUpdate::isUpdateOta = false; - installUpdate(); - qApp->quit(); - } - else { - emit showToast("Download failed"); - global::otaUpdate::isUpdateOta = false; - } - generalDialog::close(); -} - -void generalDialog::openBookFileNative(QString book, bool relativePath) { - emit openBookFile(book, relativePath); -} - -void generalDialog::showToastNative(QString messageToDisplay) { - emit showToast(messageToDisplay); -} - -void generalDialog::closeIndefiniteToastNative() { - emit closeIndefiniteToast(); -} - -void generalDialog::quit_restart() { - log("Restarting InkBox", className); - // If existing, cleaning bookconfig_mount mountpoint - writeFile("/opt/ibxd", "bookconfig_unmount\n"); - - // Restarting InkBox - QProcess process; - process.startDetached("inkbox", QStringList()); - qApp->quit(); -} - -void generalDialog::syncGutenbergCatalog() { - log("Syncing Gutenberg catalog", className); - global::toast::modalToast = true; - global::toast::indefiniteToast = true; - emit showToast("Sync in progress"); - - writeFile("/opt/ibxd", "gutenberg_sync\n"); - QTimer * syncCheckTimer = new QTimer(this); - syncCheckTimer->setInterval(500); - connect(syncCheckTimer, &QTimer::timeout, [&]() { - if(QFile::exists("/inkbox/gutenbergSyncDone") == true) { - if(checkconfig("/inkbox/gutenbergSyncDone") == true) { - log("Gutenberg sync successfully completed", className); - gutenbergSyncDone = true; - gutenbergSyncStatus = true; - emit closeIndefiniteToast(); - } - else { - log("Gutenberg sync encountered an error", className); - gutenbergSyncDone = true; - gutenbergSyncStatus = false; - emit closeIndefiniteToast(); - emit showToast("Error"); - global::keyboard::searchDialog = false; - global::forbidOpenSearchDialog = true; - global::keyboard::keyboardDialog = false; - global::keyboard::keyboardText = ""; - global::library::librarySearchDialog = false; - QTimer::singleShot(5000, this, SLOT(close())); - } - QFile::remove("/inkbox/gutenbergSyncDone"); - } - } ); - syncCheckTimer->start(); -} - -void generalDialog::waitForGutenbergSearchDone() { - while(true) { - if(QFile::exists("/inkbox/gutenberg-search/search_done")) { - if(checkconfig("/inkbox/gutenberg-search/search_done") == true) { - QList searchResults = readFile("/inkbox/gutenberg-search/search_results_titles").split("\n"); - searchResults.takeLast(); - global::library::libraryResults = true; - - for(int i = ui->mainStackedWidget->count(); i >= 0; i--) { - QWidget * widget = ui->mainStackedWidget->widget(i); - ui->mainStackedWidget->removeWidget(widget); - widget->deleteLater(); - } - ui->topStackedWidget->setVisible(false); - ui->stackedWidget->setVisible(false); - searchResultsWidgetWindow = new searchResultsWidget(this); - searchResultsWidgetWindow->setAttribute(Qt::WA_DeleteOnClose); - global::forbidOpenSearchDialog = true; - connect(searchResultsWidgetWindow, SIGNAL(destroyed(QObject*)), SLOT(restartSearchDialog())); - connect(searchResultsWidgetWindow, SIGNAL(showToast(QString)), SLOT(showToastNative(QString))); - connect(searchResultsWidgetWindow, SIGNAL(closeIndefiniteToast()), SLOT(closeIndefiniteToastNative())); - connect(searchResultsWidgetWindow, SIGNAL(hideDialog()), SLOT(hide())); - searchResultsWidgetWindow->setListViewContents(searchResults); - ui->mainStackedWidget->insertWidget(1, searchResultsWidgetWindow); - QFile::remove("/inkbox/gutenberg-search/search_done"); - emit closeIndefiniteToast(); - break; - } - else { - emit closeIndefiniteToast(); - global::toast::delay = 3000; - global::toast::modalToast = true; - emit showToast("No results found"); - keyboardWidget->clearLineEdit(); - global::keyboard::keyboardText = ""; - QFile::remove("/inkbox/gutenberg-search/search_done"); - QTimer::singleShot(3000, this, SLOT(close())); - break; - } - } - QThread::msleep(500); - } -} - -void generalDialog::increaseSize() -{ - log("Resizing", className); - - ui->topStackedWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - ui->mainStackedWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding); - ui->stackedWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); - - QRect screenGeometry = QGuiApplication::screens()[0]->geometry(); - int wx = screenGeometry.width(); - - int x = wx - 25; - int y = this->height() * yIncrease; - this->setFixedWidth(x); - this->setFixedHeight(y); - - ui->bodyLabel->sizePolicy().setVerticalPolicy(QSizePolicy::Expanding); - ui->bodyLabel->sizePolicy().setHorizontalPolicy(QSizePolicy::Expanding); - - adjust_size(); -} diff --git a/src/widgets/dialogs/kobox/koboxappsdialog.cpp b/src/widgets/dialogs/kobox/koboxappsdialog.cpp deleted file mode 100644 index 2a48009..0000000 --- a/src/widgets/dialogs/kobox/koboxappsdialog.cpp +++ /dev/null @@ -1,176 +0,0 @@ -#include "koboxappsdialog.h" -#include "ui_koboxappsdialog.h" - -#include "functions.h" - -#include -#include -#include -#include -#include -#include - -koboxAppsDialog::koboxAppsDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::koboxAppsDialog) -{ - ui->setupUi(this); - ui->definitionLabel->setFont(QFont("u001")); - ui->appsList->setFont(QFont("u001")); - - // Preventing outside interaction - this->setModal(true); - - // Stylesheet, style & misc. - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - ui->definitionLabel->setText("Please select an application.\nClick on 'Launch' to start it."); - - ui->launchBtn->setProperty("type", "borderless"); - ui->cancelBtn->setProperty("type", "borderless"); - ui->launchBtn->setStyleSheet("font-size: 9pt; padding: 10px; font-weight: bold; background: lightGrey"); - ui->cancelBtn->setStyleSheet("font-size: 9pt; padding: 10px; font-weight: bold; background: lightGrey"); - ui->appsList->setStyleSheet("font-size: 9pt"); - ui->definitionLabel->setStyleSheet("font-size: 9.5pt"); - ui->headerLabel->setStyleSheet("font-weight: bold"); - - this->adjustSize(); - - // Centering dialog - QRect screenGeometry = QGuiApplication::screens()[0]->geometry(); - int x = (screenGeometry.width() - this->width()) / 2; - int y = (screenGeometry.height() - this->height()) / 2; - this->move(x, y); - - checkApps(); - QStringListModel * model = new QStringListModel(this); - QStringList list = apps.split("\n", QString::SkipEmptyParts); - - // Apps that aren't extensions - list.prepend("Geany"); - - if(checkconfig("/external_root/opt/root/rooted") == true) { - list.prepend("KTerm"); - } - - model->setStringList(list); - ui->appsList->setModel(model); - ui->appsList->setEditTriggers(QAbstractItemView::NoEditTriggers); -} - -void koboxAppsDialog::checkApps() { - QFile apps_list("/external_root/opt/X11/extensions_list"); - apps_list.open(QIODevice::ReadWrite); - QTextStream in (&apps_list); - apps = in.readAll(); - apps_list.close(); -} - -koboxAppsDialog::~koboxAppsDialog() -{ - delete ui; -} - -void koboxAppsDialog::on_cancelBtn_clicked() -{ - koboxAppsDialog::close(); -} - -void koboxAppsDialog::on_launchBtn_clicked() -{ - index = ui->appsList->currentIndex(); - itemText = index.data(Qt::DisplayRole).toString(); - if(itemText.isEmpty()) { - emit showToast("Please select an application"); - } - else { - // DPI setting - QString initialDpiSetting = readFile(".config/00-kobox/dpiSetting"); - if(initialDpiSetting.isEmpty()) { - if(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "kt\n") { - dpiSetting = "125"; - } - else if(global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n306\n" or global::deviceID == "emu\n") { - dpiSetting = "175"; - } - else if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { - dpiSetting = "225"; - } - else if(global::deviceID == "n873\n") { - dpiSetting = "250"; - } - else { - dpiSetting = "125"; - } - - } - else { - dpiSetting = initialDpiSetting; - } - - // Fullscreen or windowed (i3) - // Mostly windowed except for apps like KTerm which ship their own OSK - dpModeSetting = "windowed"; - - if(itemText == "Netsurf") { - log("Launching KoBox app: NetSurf", className); - // Bypass standard shell script launch shenanigans - writeFile("/external_root/tmp/X_program", "!netsurf"); - } - else if(itemText == "KTerm") { - log("Launching KoBox app: KTerm", className); - writeFile("/external_root/tmp/X_program", "/usr/local/bin/kterm -l /usr/local/share/kterm/layouts/keyboard-kt.xml -k 1"); - dpModeSetting = "fullscreen"; - if(global::deviceID == "n705\n" or global::deviceID == "n905\n" or global::deviceID == "kt\n") { - dpiSetting = "175"; - } - else if(global::deviceID == "n613\n" or global::deviceID == "n236\n" or global::deviceID == "n306\n" or global::deviceID == "emu\n") { - dpiSetting = "225"; - } - else if(global::deviceID == "n437\n" or global::deviceID == "n249\n") { - dpiSetting = "275"; - } - else if(global::deviceID == "n873\n") { - dpiSetting = "300"; - } - else { - dpiSetting = "175"; - } - } - else if(itemText == "Geany") { - log("Launching KoBox app: Geany", className); - writeFile("/external_root/tmp/X_program", "geany"); - } - else { - log("Launching KoBox app: " + itemText, className); - QString app = itemText.toLower(); - writeFile("/external_root/tmp/X_program", app); - } - - writeFile("/external_root/tmp/X_dpmode", dpModeSetting); - writeFile("/external_root/tmp/X_dpi", dpiSetting); - - /* Wheeee! */ - global::kobox::showKoboxSplash = true; - - // Re-use USBMS splash window for KoBox splash, since it's pretty much the same layout - log("Showing KoBox splash", className); - usbmsSplashWindow = new usbmsSplash(); - usbmsSplashWindow->setAttribute(Qt::WA_DeleteOnClose); - usbmsSplashWindow->setGeometry(QRect(QPoint(0,0), screen()->geometry().size())); - usbmsSplashWindow->show(); - QApplication::processEvents(); - - // Stop EncFS/Encrypted storage - if(checkconfig("/external_root/run/encfs_mounted") == true) { - writeFile("/external_root/run/encfs_stop_cleanup", "true"); - writeFile("/opt/ibxd", "encfs_stop\n"); - } - - // Write to FIFO to start X11 - writeFile("/opt/ibxd", "x_start_gui\n"); - } -} diff --git a/src/widgets/dialogs/library/bookinfodialog.cpp b/src/widgets/dialogs/library/bookinfodialog.cpp deleted file mode 100644 index a85cb0e..0000000 --- a/src/widgets/dialogs/library/bookinfodialog.cpp +++ /dev/null @@ -1,184 +0,0 @@ -#include "bookinfodialog.h" -#include "ui_bookinfodialog.h" -#include "functions.h" - -#include - -bookInfoDialog::bookInfoDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::bookInfoDialog) -{ - ui->setupUi(this); - - // Preventing outside interaction - this->setModal(true); - - // Stylesheet - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - ui->closeBtn->setProperty("type", "borderless"); - ui->closeBtn->setText(""); - ui->closeBtn->setIcon(QIcon(":/resources/close.png")); - ui->bookCoverLabel->setText(""); - ui->getBtn->setStyleSheet("background: lightGrey; font-size: 9pt; padding: 8px"); - - // Getting the screen's size - sW = QGuiApplication::screens()[0]->size().width(); - sH = QGuiApplication::screens()[0]->size().height(); - - // Setting icons up - stdIconWidth = sW / 4; - stdIconHeight = sH / 4; - - if(global::bookInfoDialog::localInfoDialog == false) { - if(global::library::isLatestBook == true) { - QString bookNumberQstr = QString::number(global::library::latestBookNumber); - - QString coverPath = "/mnt/onboard/onboard/.inkbox/gutenberg-data/latest-books/"; - coverPath = coverPath.append(bookNumberQstr); - coverPath = coverPath.append("/cover.jpg"); - - QString idPath = "/mnt/onboard/onboard/.inkbox/gutenberg-data/latest-books/"; - idPath = idPath.append(bookNumberQstr); - idPath = idPath.append("/id"); - global::library::bookId = readFile(idPath).toULong(); - - QPixmap coverPixmap(coverPath); - QPixmap scaledCoverPixmap = coverPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->bookCoverLabel->setPixmap(scaledCoverPixmap); - global::library::isLatestBook = false; - - ui->bookTitleLabel->setText(global::library::bookTitle); - } - else { - ui->bookTitleLabel->setText(global::library::bookTitle); - - QDir gutenbergDir; - gutenbergDir.mkpath("/inkbox/gutenberg"); - writeFile("/inkbox/gutenberg/bookid", QString::number(global::library::bookId)); - writeFile("/opt/ibxd", "gutenberg_get_cover\n"); - while(true) { - if(QFile::exists("/inkbox/gutenberg/getCoverDone")) { - if(checkconfig("/inkbox/gutenberg/getCoverDone") == true) { - QPixmap coverPixmap("/inkbox/gutenberg/book_cover.jpg"); - QPixmap scaledCoverPixmap = coverPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->bookCoverLabel->setPixmap(scaledCoverPixmap); - QFile::remove("/inkbox/gutenberg/getCoverDone"); - break; - } - else { - QPixmap coverPixmap(":/resources/cover_unavailable.png"); - QPixmap scaledCoverPixmap = coverPixmap.scaled(stdIconWidth, stdIconHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->bookCoverLabel->setPixmap(scaledCoverPixmap); - QFile::remove("/inkbox/gutenberg/getCoverDone"); - break; - } - } - } - } - - log("Setting up book info dialog, ID: " + QString::number(global::library::bookId) + ", title: " + global::library::bookTitle, className); - } - else { - if(global::localLibrary::bookOptionsDialog::bookID != global::localLibrary::folderID) { - QJsonObject bookJsonObject = getBookMetadata(global::localLibrary::bookOptionsDialog::bookID); - QString bookInfo; - QString title = bookJsonObject["Title"].toString(); - QString author = bookJsonObject["Author"].toString(); - QString publicationDate = bookJsonObject["PublicationDate"].toString(); - QString path = bookJsonObject["BookPath"].toString(); - if(!title.isEmpty()) { - bookInfo.append("Title: " + title + "
"); - } - if(!author.isEmpty()) { - bookInfo.append("Author: " + author + "
"); - } - if(!publicationDate.isEmpty()) { - bookInfo.append("Publication date: " + publicationDate + "
"); - } - if(!path.isEmpty()) { - bookInfo.append("Path: " + path + "
"); - } - global::text::textBrowserContents = bookInfo; - } - else { - QString bookInfo = "Path: " + global::localLibrary::bookOptionsDialog::folderPath; - global::text::textBrowserContents = bookInfo; - } - textwidget * textwidgetWindow = new textwidget(this); - ui->stackedWidget->insertWidget(1, textwidgetWindow); - ui->stackedWidget->setCurrentIndex(1); - } - - QRect screenGeometry = QGuiApplication::screens()[0]->geometry(); - { - int wx = screenGeometry.width(); - - int x = wx - 25; - int y = this->height() * determineYIncrease(); - this->setFixedWidth(x); - this->setFixedHeight(y); - - this->adjustSize(); - } - - // Centering dialog - int x = (screenGeometry.width() - this->width()) / 2; - int y = (screenGeometry.height() - this->height()) / 2; - this->move(x, y); -} - -bookInfoDialog::~bookInfoDialog() -{ - delete ui; -} - -void bookInfoDialog::on_closeBtn_clicked() -{ - global::library::bookTitle = ""; - global::bookInfoDialog::localInfoDialog = false; - bookInfoDialog::close(); -} - - -void bookInfoDialog::on_getBtn_clicked() -{ - QDir gutenbergDir; - gutenbergDir.mkpath("/inkbox/gutenberg"); - writeFile("/inkbox/gutenberg/bookid", QString::number(global::library::bookId)); - writeFile("/inkbox/gutenberg/booktitle", global::library::bookTitle); - writeFile("/opt/ibxd", "gutenberg_get_book\n"); - - global::toast::modalToast = true; - global::toast::indefiniteToast = true; - log("Downloading book, ID: " + QString::number(global::library::bookId) + ", title: " + global::library::bookTitle, className); - emit showToast("Downloading"); - - QTimer::singleShot(500, this, SLOT(waitForBookFetch())); -} - -void bookInfoDialog::waitForBookFetch() { - while(true) { - if(QFile::exists("/inkbox/gutenberg/getBookDone")) { - if(checkconfig("/inkbox/gutenberg/getBookDone") == true) { - emit closeIndefiniteToast(); - QString function = __func__; log(function + ": Download successful", className); - emit showToast("Download successful"); - QFile::remove("/inkbox/gutenberg/getBookDone"); - QFile::remove(global::localLibrary::databasePath); - break; - } - else { - emit closeIndefiniteToast(); - QString function = __func__; log(function + ": Download failed", className); - emit showToast("Download failed"); - QFile::remove("/inkbox/gutenberg/getBookDone"); - break; - } - } - QThread::msleep(500); - } -} diff --git a/src/widgets/dialogs/powerDaemon/sleepdialog.cpp b/src/widgets/dialogs/powerDaemon/sleepdialog.cpp deleted file mode 100644 index 6b5e806..0000000 --- a/src/widgets/dialogs/powerDaemon/sleepdialog.cpp +++ /dev/null @@ -1,34 +0,0 @@ -#include "sleepdialog.h" -#include "ui_sleepdialog.h" - -#include "functions.h" - -sleepDialog::sleepDialog(QDialog *parent) : - QDialog(parent), - ui(new Ui::sleepDialog) -{ - ui->setupUi(this); - - // Stylesheet - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); -} - -sleepDialog::~sleepDialog() -{ - delete ui; -} - -void sleepDialog::launchSleepDialog() -{ - log("Launching sleep dialog", className); - this->exec(); -} - -void sleepDialog::hideSleepDialog() -{ - log("Hiding sleep dialog", className); - this->hide(); -} diff --git a/src/widgets/dialogs/wifi/connectiondialog.cpp b/src/widgets/dialogs/wifi/connectiondialog.cpp deleted file mode 100644 index 0ec3966..0000000 --- a/src/widgets/dialogs/wifi/connectiondialog.cpp +++ /dev/null @@ -1,390 +0,0 @@ -#include -#include - -#include "connectiondialog.h" -#include "ui_connectiondialog.h" -#include "generaldialog.h" -#include "functions.h" - -connectiondialog::connectiondialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::connectiondialog) -{ - ui->setupUi(this); - this->setFont(QFont("u001")); - ui->passphraseTextEdit->setFont(QFont("Roboto Mono")); - ui->label->setFont(QFont("Inter")); - ui->label_2->setFont(QFont("Inter")); - - // Stylesheet, style & misc. - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - ui->cancelBtn->setProperty("type", "borderless"); - ui->connectBtn->setProperty("type", "borderless"); - ui->showPassphraseBtn->setProperty("type", "borderless"); - - ui->label->setStyleSheet("font-weight: bold"); - ui->label_2->setStyleSheet("font-weight: bold"); - - ui->cancelBtn->setIcon(QIcon(":/resources/close.png")); - ui->connectBtn->setIcon(QIcon(":/resources/arrow-right.png")); - - // Size - QRect screenGeometry = QGuiApplication::screens()[0]->geometry(); - if(global::deviceID == "n705\n") { - this->setFixedWidth(screenGeometry.width() / 1.2); - } - else { - this->setFixedWidth(screenGeometry.width() / 1.5); - } - - int halfOfHalfHeight = ((screenGeometry.height() / 2) / 2) / 2; - int finalHeight; - if(global::deviceID == "n705\n") { - finalHeight = screenGeometry.height() - halfOfHalfHeight * 5.9; - } - else if(global::deviceID == "n873\n") { - finalHeight = screenGeometry.height() - halfOfHalfHeight * 6.45; - } - else { - finalHeight = screenGeometry.height() - halfOfHalfHeight * 6.3; - } - - this->setFixedHeight(finalHeight); - - // Centering dialog - int x = (screenGeometry.width() - this->width()) / 2; - int y = (screenGeometry.height() - this->height()) / 2; - this->move(x, y); -} - -connectiondialog::~connectiondialog() -{ - delete ui; -} - -void connectiondialog::applyVariables() { - // Limit name size - int truncateThreshold; - if(global::deviceID == "n705\n") { - truncateThreshold = 20; - } - else { - truncateThreshold = 30; - } - int nameLength = connectedNetworkData.name.length(); - QString name = connectedNetworkData.name; - if(nameLength > truncateThreshold) { - name.chop(nameLength - truncateThreshold); - name.append("..."); - } - ui->nameLabel->setText(name); - ui->macLabel->setText(connectedNetworkData.mac); - ui->signalLabel->setText(QString::number(connectedNetworkData.signal) + "%"); - - if(connectedNetworkData.encryption == false) { - ui->showPassphraseBtn->hide(); - ui->passphraseTextEdit->setText("No passphrase required"); - ui->passphraseTextEdit->setDisabled(true); - } - else { - if(passphraseDatabase.exists() == false) { - log("Creating empty database", className); - // https://forum.qt.io/topic/104791/how-i-can-create-json-format-in-qt/5 - QJsonObject root; - QJsonArray array; - QJsonDocument newJsonDocument; - root["list"] = array; - newJsonDocument.setObject(root); - - passphraseDatabase.open(QFile::WriteOnly | QFile::Text | QFile::Truncate); - passphraseDatabase.write(newJsonDocument.toJson()); - passphraseDatabase.flush(); - passphraseDatabase.close(); - } - QString passphrase = searchDatabase(connectedNetworkData.name); - if(passphrase.isEmpty() == false) { - log("Found passphrase: '" + passphrase + "'", className); - ui->showPassphraseBtn->setIcon(QIcon(":/resources/show.png")); - showedPassphrase = false; - savedPassphrase = passphrase; - - int passphraseLength = passphrase.length(); - QString hiddenPassphrase; - for(int i = 0; i < passphraseLength; i++) { - hiddenPassphrase.append("•"); - } - ui->passphraseTextEdit->setText(hiddenPassphrase); - } - else { - log("No passphrase found", className); - ui->passphraseTextEdit->setText("No passphrase was saved"); - showedPassphrase = true; - ui->showPassphraseBtn->hide(); - } - } -} - -QString connectiondialog::searchDatabase(QString key) { - passphraseDatabase.open(QIODevice::ReadOnly | QIODevice::Text); - QString fileRead = passphraseDatabase.readAll(); - passphraseDatabase.close(); - QJsonDocument jsonDocument = QJsonDocument::fromJson(fileRead.toUtf8()); - - if(jsonDocument["list"].isArray() == true) { - QJsonArray jsonArray = jsonDocument["list"].toArray(); - for(QJsonValueRef refJsonObject: jsonArray) { - QJsonObject jsonMainObject = refJsonObject.toObject(); - QString searchedName = jsonMainObject.keys().first().toUtf8(); - log("Found in database: '" + searchedName + "'", className); - if(searchedName == key) { - QString returnedPassphrase = jsonMainObject.value(key).toString(); - log("Searched name '" + searchedName + "' matched '" + key + "' and the passphrase is: '" + returnedPassphrase + "'", className); - return returnedPassphrase; - } - else { - log("Searched name '" + searchedName + "' doesn't match '" + key + "'", className); - } - } - return ""; - } - else { - log("Something went horribly wrong", className); - } -} - -void connectiondialog::writeToDatabase(QString name, QString passphrase) { - if(searchDatabase(name).isEmpty() == false) { - removeFromDatabase(name); - } - - passphraseDatabase.open(QIODevice::ReadOnly | QIODevice::Text); - QString fileRead = passphraseDatabase.readAll(); - passphraseDatabase.close(); - QJsonDocument jsonDocument = QJsonDocument::fromJson(fileRead.toUtf8()); - - if(jsonDocument["list"].isArray() == true) { - QJsonArray jsonArray = jsonDocument["list"].toArray(); - QJsonValue newValue; - - // https://stackoverflow.com/questions/26804660/how-to-initialize-qjsonobject-from-qstring - // I hoped this would be easier - QJsonObject newObject = QJsonDocument::fromJson(QString("{\"" + name + "\" : \"" + passphrase + "\" }").toUtf8()).object(); - jsonArray.append(newObject); - - QJsonDocument newJsonDocument; - QJsonObject root; - root["list"] = jsonArray; - newJsonDocument.setObject(root); - - passphraseDatabase.open(QFile::WriteOnly | QFile::Text | QFile::Truncate); - passphraseDatabase.write(newJsonDocument.toJson()); - passphraseDatabase.flush(); - passphraseDatabase.close(); - } - else { - log("Something went horribly wrong", className); - } -} - -void connectiondialog::removeFromDatabase(QString name) { - passphraseDatabase.open(QIODevice::ReadOnly | QIODevice::Text); - QString fileRead = passphraseDatabase.readAll(); - passphraseDatabase.close(); - QJsonDocument jsonDocument = QJsonDocument::fromJson(fileRead.toUtf8()); - - int counter = 0; - bool remove = false; - if(jsonDocument["list"].isArray() == true) { - QJsonArray jsonArray = jsonDocument["list"].toArray(); - for(QJsonValueRef refJsonObject: jsonArray) { - QJsonObject jsonMainObject = refJsonObject.toObject(); - QString searchedName = jsonMainObject.keys().first().toUtf8(); - log("Found in database: '" + searchedName + "'", className); - if(searchedName == name) { - remove = true; - } - if(remove == false) { - counter = counter + 1; - } - } - if(remove == true) { - jsonArray.removeAt(counter); - QJsonDocument newJsonDocument; - QJsonObject root; - root["list"] = jsonArray; - newJsonDocument.setObject(root); - - passphraseDatabase.open(QFile::WriteOnly | QFile::Text | QFile::Truncate); - passphraseDatabase.write(newJsonDocument.toJson()); - passphraseDatabase.flush(); - passphraseDatabase.close(); - } - else { - log("ERROR: tried to remove from database, but couldn't find key", className); - } - } -} - -void connectiondialog::on_cancelBtn_clicked() -{ - this->deleteLater(); - this->close(); -} - -void connectiondialog::on_passphraseTextEdit_selectionChanged() -{ - ui->passphraseTextEdit->setSelection(0, 0); -} - -void connectiondialog::on_passphraseTextEdit_cursorPositionChanged(int oldpos, int newpos) -{ - log("Detected click on text edit widget", className); - if(cursorPositionIgnore == true) { - if(newpos != 0) { - if(showedPassphrase == true) { - ui->passphraseTextEdit->setCursorPosition(0); - global::keyboard::keyboardDialog = true; - global::keyboard::wifiPassphraseDialog = true; - global::keyboard::keyboardText = ""; - generalDialog* generalDialogWindow = new generalDialog(); - generalDialogWindow->setAttribute(Qt::WA_DeleteOnClose); - generalDialogWindow->wifiEssid = connectedNetworkData.name; - connect(generalDialogWindow, &generalDialog::showToast, this, &connectiondialog::showToastSlot); - connect(generalDialogWindow, &generalDialog::refreshScreen, this, &connectiondialog::refreshScreenSlot); - - generalDialogWindow->exec(); - - global::keyboard::keyboardDialog = false; - global::keyboard::wifiPassphraseDialog = false; - if(global::keyboard::keyboardText.isEmpty() == false) { - // A bit hacky: avoid summoning the keyboard back when the text is changing (and the cursor too) showedPassphrase shouldn't be used for this, but it works and adding another boolean would start being messy - showedPassphrase = false; - ui->passphraseTextEdit->setText(global::keyboard::keyboardText); - ui->showPassphraseBtn->setIcon(QIcon(":/resources/hide.png")); - ui->showPassphraseBtn->show(); - showedPassphrase = true; - savedPassphrase = global::keyboard::keyboardText; - ui->showPassphraseBtn->show(); - } - global::keyboard::keyboardText = ""; - } - else { - log("Passphrase is not saved; ignoring text edit widget call", className); - } - } - } - else { - log("Ignoring click on text edit widget", className); - cursorPositionIgnore = true; - } -} - -void connectiondialog::showToastSlot(QString message) { - emit showToastSignal(message); -} - -void connectiondialog::on_showPassphraseBtn_clicked() -{ - if(showedPassphrase == false) { - ui->showPassphraseBtn->setIcon(QIcon(":/resources/hide.png")); - ui->passphraseTextEdit->setText(savedPassphrase); - showedPassphrase = true; - } - else { - showedPassphrase = false; - ui->showPassphraseBtn->setIcon(QIcon(":/resources/show.png")); - - int passphraseLength = searchDatabase(connectedNetworkData.name).length(); - if(passphraseLength != 0) { - QString hiddenPassphrase; - for(int i = 0; i < passphraseLength; i++) { - hiddenPassphrase.append("•"); - } - ui->passphraseTextEdit->setText(hiddenPassphrase); - } - else { - // This is executed if the user asks to hide the passphrase but it isn't saved yet (upon first connection to a network) - QString hiddenPassphrase; - int passphraseLength = ui->passphraseTextEdit->text().length(); - for(int i = 0; i < passphraseLength; i++) { - hiddenPassphrase.append("•"); - } - ui->passphraseTextEdit->setText(hiddenPassphrase); - } - } -} - -void connectiondialog::refreshScreenSlot() { - this->repaint(); - emit refreshScreenSignal(); -} - -void connectiondialog::on_connectBtn_clicked() -{ - QString finalPassphrase; - if(connectedNetworkData.encryption == false) { - finalPassphrase = "NONE"; - } - else { - if(savedPassphrase.isEmpty() == false) { - finalPassphrase = savedPassphrase; - writeToDatabase(connectedNetworkData.name, savedPassphrase); - } - else { - showToastSlot("Provide a passphrase first"); - return void(); - } - } - passphraseForReconnecting = finalPassphrase; - - ui->cancelBtn->setEnabled(false); - if(checkWifiState() == global::wifi::wifiState::configured) { - writeFile("/opt/ibxd", "stop_wifi_operations\n"); - } - writeFile("/run/wifi_network_essid", connectedNetworkData.name); - writeFile("/run/wifi_network_passphrase", finalPassphrase); - finalConnectWait(); -} - -void connectiondialog::finalConnectWait() { - if(checkIfWifiBusy() == true) { - // To be sure - if(waitTry == 10) { - writeFile("/opt/ibxd", "stop_wifi_operations\n"); - } - // Wait for everything to shut down; 10 seconds timeout - if(waitTry == 20) { - writeFile("/opt/ibxd", "stop_wifi_operations\n"); - emit showToastSignal("Failed to stop other Wi-Fi processes"); - ui->cancelBtn->setEnabled(true); - } - else { - QTimer::singleShot(500, this, SLOT(finalConnectWait())); - waitTry = waitTry + 1; - } - } - else { - writeFile("/opt/ibxd", "connect_to_wifi_network\n"); - - // This will be deleted later in MainWindow's icon updater if it failed. It is also deleted in the Wi-Fi stop script. - log("Writing to configuration directory with connection information data", className); - writeFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/essid", connectedNetworkData.name); - writeFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/passphrase", passphraseForReconnecting); - - this->deleteLater(); - this->close(); - } -} - -bool connectiondialog::checkIfWifiBusy() { - if(checkProcessName("connect_to_network.sh") == true or checkProcessName("connection_manager.sh") == true or checkProcessName("prepare_changing_wifi.sh") == true) { - return true; - } - else { - return false; - } -} diff --git a/src/widgets/dialogs/wifi/network.cpp b/src/widgets/dialogs/wifi/network.cpp deleted file mode 100644 index cc50f43..0000000 --- a/src/widgets/dialogs/wifi/network.cpp +++ /dev/null @@ -1,119 +0,0 @@ -#include "network.h" -#include "ui_network.h" -#include "connectiondialog.h" - -#include - -network::network(QWidget *parent) : - QWidget(parent), - ui(new Ui::network) -{ - ui->setupUi(this); - this->setFont(QFont("u001")); - - // Stylesheet, style & misc. - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - // Buttons - ui->encryptionIcon->setProperty("type", "borderless"); - ui->encryptionIcon->setStyleSheet("QPushButton[type='borderless']:pressed { background: white; color: white; border: none; }"); - ui->signalStrengthIcon->setProperty("type", "borderless"); - ui->signalStrengthIcon->setStyleSheet("QPushButton[type='borderless']:pressed { background: white; color: white; border: none; }"); - ui->enterButton->setProperty("type", "borderless"); -} - -network::~network() -{ - delete ui; -} - -void network::applyVariables() { - log("Applying variables for network", className); - - QString percent = "%"; - if(mainData.signal < 100) { - percent.append(" "); - } - ui->signalStrengthLabel->setText(QString::number(mainData.signal) + percent); - - // Limit name size - int truncateThreshold; - if(global::deviceID == "n705\n") { - truncateThreshold = 12; - } - else { - truncateThreshold = 20; - } - int nameLength = mainData.name.length(); - QString name = mainData.name; - if(nameLength > truncateThreshold) { - name.chop(nameLength - truncateThreshold); - name.append("..."); - } - ui->nameLabel->setText(name); - - if(mainData.encryption == true) { - ui->encryptionIcon->setIcon(QIcon(":/resources/lock.png")); - } - else { - ui->encryptionIcon->setIcon(QIcon(":/resources/public.png")); - } - - if(currentlyConnectedNetwork == mainData.name) { - ui->frame->setStyleSheet(".QFrame{background-color: lightGray; border: 2px solid black; border-radius: 10px;}"); - ui->signalStrengthLabel->setStyleSheet("background-color: lightGray;"); - ui->nameLabel->setStyleSheet("background-color: lightGray;"); - ui->encryptionIcon->setStyleSheet("background-color: lightGray;"); - ui->enterButton->setStyleSheet("background-color: lightGray;"); - - ui->signalStrengthIcon->setStyleSheet("QPushButton {background-color: lightGray; border: none}; QPushButton[type='borderless']:pressed { background: lightGray; color: lightGray; border: none; }"); - ui->encryptionIcon->setStyleSheet("QPushButton {background-color: lightGray; border: none}; QPushButton[type='borderless']:pressed { background: lightGray; color: lightGray; border: none; }"); - ui->enterButton->setStyleSheet("QPushButton {background-color: lightGray; border: none}; QPushButton[type='borderless']:pressed { background: lightGray; color: lightGray; border: none; }"); - } - else { - ui->frame->setStyleSheet(".QFrame{background-color: white; border: 2px solid black; border-radius: 10px;}"); - } - - if(mainData.signal >= 0 and mainData.signal <= 25) { - ui->signalStrengthIcon->setIcon(QIcon(":/resources/wifi-0.png")); - } - else if(mainData.signal >= 25 and mainData.signal < 50) { - ui->signalStrengthIcon->setIcon(QIcon(":/resources/wifi-25.png")); - } - else if(mainData.signal >= 50 and mainData.signal < 75) { - ui->signalStrengthIcon->setIcon(QIcon(":/resources/wifi-50.png")); - } - else if(mainData.signal >= 75 and mainData.signal < 100) { - ui->signalStrengthIcon->setIcon(QIcon(":/resources/wifi-75.png")); - } - else if(mainData.signal == 100) { - ui->signalStrengthIcon->setIcon(QIcon(":/resources/wifi-100.png")); - } -} - -void network::on_enterButton_clicked() -{ - connectiondialog* newConnectionDialog = new connectiondialog; - newConnectionDialog->connectedNetworkData = mainData; - newConnectionDialog->currentlyConnectedNetworkName = currentlyConnectedNetwork; - newConnectionDialog->applyVariables(); - connect(newConnectionDialog, &connectiondialog::showToastSignal, this, &network::showToastSlot); - connect(newConnectionDialog, &connectiondialog::refreshScreenSignal, this, &network::refreshScreenSlot); - newConnectionDialog->exec(); -} - -void network::closeWrapper() { - this->deleteLater(); - this->close(); -} - -void network::showToastSlot(QString message) { - emit showToastSignal(message); -} - -void network::refreshScreenSlot() { - emit refreshScreenSignal(); -} diff --git a/src/widgets/dialogs/wifi/wifidialog.cpp b/src/widgets/dialogs/wifi/wifidialog.cpp deleted file mode 100644 index 0b8b05b..0000000 --- a/src/widgets/dialogs/wifi/wifidialog.cpp +++ /dev/null @@ -1,535 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "wifidialog.h" -#include "ui_wifidialog.h" -#include "functions.h" -#include "mainwindow.h" -#include "network.h" -#include "wifilogger.h" - -wifiDialog::wifiDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::wifiDialog) -{ - ui->setupUi(this); - this->setFont(QFont("u001")); - - // Stylesheet, style & misc. - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - this->setModal(true); - - ui->wifiCheckBox->setFont(QFont("Inter")); - ui->returnBtn->setFont(QFont("Inter")); - ui->returnBtn->setStyleSheet("font-weight: bold"); - - ui->refreshBtn->setProperty("type", "borderless"); - ui->stopBtn->setProperty("type", "borderless"); - ui->logBtn->setProperty("type", "borderless"); - ui->returnBtn->setProperty("type", "borderless"); - - ui->refreshBtn->setIcon(QIcon(":/resources/refresh.png")); - ui->stopBtn->setIcon(QIcon(":/resources/stop.png")); - ui->logBtn->setIcon(QIcon(":/resources/log.png")); - - // Size - QRect screenGeometry = QGuiApplication::screens()[0]->geometry(); - this->setFixedWidth(screenGeometry.width() / 1.1); - - int halfOfHalfHeight = ((screenGeometry.height() / 2) / 2) / 2; - int finalHeight = screenGeometry.height() - halfOfHalfHeight * 2; - - this->setFixedHeight(finalHeight); - - // Centering dialog - int x = (screenGeometry.width() - this->width()) / 2; - int y = (screenGeometry.height() - this->height()) / 2; - this->move(x, y); - - // Button sizes - if(global::deviceID == "n705\n") { - ui->refreshBtn->setStyleSheet("padding: 20px;"); - ui->stopBtn->setStyleSheet("padding: 20px;"); - ui->logBtn->setStyleSheet("padding: 20px;"); - } - else { - ui->refreshBtn->setStyleSheet("padding: 25px;"); - ui->stopBtn->setStyleSheet("padding: 25px;"); - ui->logBtn->setStyleSheet("padding: 25px;"); - } - - // Set Wi-Fi checkbox state. Ignore the first call. - global::wifi::wifiState currentWifiState = checkWifiState(); - if(currentWifiState != global::wifi::wifiState::disabled and currentWifiState != global::wifi::wifiState::unknown) { - ui->wifiCheckBox->setChecked(true); - // To be sure nothing breaks - refreshFromWatcher = true; - ui->refreshBtn->click(); - } else { - wifiButtonEnabled = true; - ui->stopBtn->setStyleSheet(ui->stopBtn->styleSheet() + "background-color: lightGray;"); - ui->stopBtn->setEnabled(false); - } - - // To avoid confusion with reconnecting - QTimer::singleShot(0, this, SLOT(watcher())); -} - -wifiDialog::~wifiDialog() -{ - delete ui; -} - -void wifiDialog::on_refreshBtn_clicked() -{ - log("Clicked refresh button", className); - if(checkWifiState() == global::wifi::wifiState::disabled) { - if(refreshFromWatcher == true) { - refreshFromWatcher = false; - emit showToast("To scan, turn Wi-Fi on first"); - } - } - else { - refreshFromWatcher = false; - launchRefresh(); - } -} - -void wifiDialog::launchRefresh() { - // Order is important - if(scanInProgress == false) { - scanInProgress = true; - ui->refreshBtn->setStyleSheet(ui->refreshBtn->styleSheet() + "background-color: lightGray;"); - ui->refreshBtn->setEnabled(false); - - elapsedSeconds = 0; - fullList.remove(); - formattedList.remove(); - writeFile("/opt/ibxd", "list_wifi_networks\n"); - QTimer::singleShot(0, this, SLOT(refreshWait())); - } - else { - log("Scan is already in progress", className); - } -} - -void wifiDialog::refreshWait() { - if(fullList.exists() == false and formattedList.exists() == false) { - if(elapsedSeconds == 6) { - emit showToast("Failed to get networks list"); - ui->refreshBtn->setStyleSheet(ui->refreshBtn->styleSheet() + "background-color: white;"); - ui->refreshBtn->setEnabled(true); - scanInProgress = false; - } - else { - elapsedSeconds = elapsedSeconds + 1; - QTimer::singleShot(1000, this, SLOT(refreshWait())); - } - } else { - log("Retrieved network list successfully", className); - refreshNetworksList(); - } -} - -void wifiDialog::refreshNetworksList() { - emit killNetworkWidgets(); - QStringList networkList = readFile("/external_root/run/wifi_list_format").split("%%==SPLIT==%%\n"); - QVector pureNetworkList; - for(QString network: networkList) { - QStringList data = network.split("\n"); - int count = 1; - global::wifi::wifiNetworkData singleNetwork; - if(data.count() < 4) { - log("Data lines count is below 4; skipping", className); - continue; - } - for(QString singleData: data) { - if(count == 1) { - singleNetwork.mac = singleData; - log("MAC is: " + singleData, className); - } - if(count == 2) { - if(singleData.isEmpty() == true) { - log("Network name is empty", className); - } - else { - log("Network name is: '" + singleData + "'", className); - } - singleNetwork.name = singleData; - } - if(count == 3) { - log("Encryption type is: " + singleData, className); - singleNetwork.encryption = QVariant(singleData).toBool(); - } - if(count == 4) { - log("Signal strength is: " + singleData, className); - singleNetwork.signal = QVariant(singleData).toInt(); - } - if(count >= 5) { - log("Skipping additional items from network information", className); - } - count = count + 1; - } - // Filter out remaining empty networks - if(singleNetwork.name.isEmpty() == false) { - pureNetworkList.append(singleNetwork); - } - } - log("Found " + QString::number(pureNetworkList.count()) + " valid networks", className); - if(pureNetworkList.count() == 0) { - if(secondScanTry == false) { - secondScanTry = true; - if(checkWifiState() != global::wifi::wifiState::disabled) { - scanInProgress = false; - QTimer::singleShot(0, this, SLOT(launchRefresh())); - log("No networks found. Trying one more time"); - return void(); - } - else { - return void(); - } - } - else { - secondScanTry = false; - log("No networks found, skipping", className); - showToastSlot("No networks found"); - ui->refreshBtn->setEnabled(true); - ui->refreshBtn->setStyleSheet(ui->refreshBtn->styleSheet() + "background-color: white;"); - scanInProgress = false; - return void(); - } - } - QFile currentWifiNameFile = QFile("/external_root/run/current_wifi_name"); - currentWifiNameFile.remove(); - writeFile("/opt/ibxd", "get_current_wifi_name\n"); - usleep(300000); // 0.3s - // Here, it's looking for the currently connected network to put it on top of the list - QString currentNetwork = ""; - if(currentWifiNameFile.exists() == true) { - QString currentWifiNetwork = readFile(currentWifiNameFile.fileName()); - currentWifiNetwork = currentWifiNetwork.replace("\n", ""); - log("Current network name is: " + currentWifiNetwork, className); - int countVec = 0; - int vectorNetworkLocation = 9999; - for(global::wifi::wifiNetworkData wifiNetwork: pureNetworkList) { - if(currentWifiNetwork.isEmpty() == false and wifiNetwork.name == currentWifiNetwork) { - log("Found current network in vector", className); - vectorNetworkLocation = countVec; - currentNetwork = wifiNetwork.name; - network* connectedNetwork = new network; - connectedNetwork->mainData = wifiNetwork; - // To be really sure that the the info is put there - connectedNetwork->currentlyConnectedNetwork = currentNetwork; - connectedNetworkDataParent = wifiNetwork; - connectedNetworkDataParentSet = true; - - // This doesn't work, so a layout is needed - // ui->scrollArea->addScrollBarWidget(connectedNetwork, Qt::AlignTop); - connectedNetwork->applyVariables(); - connect(this, &wifiDialog::killNetworkWidgets, connectedNetwork, &network::closeWrapper); - connect(connectedNetwork, &network::showToastSignal, this, &wifiDialog::showToastSlot); - connect(connectedNetwork, &network::refreshScreenSignal, this, &wifiDialog::refreshScreenSlot); - ui->scrollBarLayout->addWidget(connectedNetwork, Qt::AlignTop); - } - else { - countVec = countVec + 1; - } - } - if(vectorNetworkLocation != 9999) { - log("pureNetworkList size is: " + QString::number(pureNetworkList.count()) + ", entry at " + QString::number(vectorNetworkLocation) + " slated for removal", className); - pureNetworkList.removeAt(vectorNetworkLocation); - } - } - - if(pureNetworkList.count() >= 1) { - // Sort based on signal strength - QVector sortedPureNetworkList; - sortedPureNetworkList.append(pureNetworkList.first()); - pureNetworkList.removeFirst(); - // Possible fix for a segmentation fault - if(pureNetworkList.isEmpty() == false) { - for(global::wifi::wifiNetworkData wifiNetwork: pureNetworkList) { - bool stopIterating = false; - int counter = 0; - for(global::wifi::wifiNetworkData wifiNetworkToSort: sortedPureNetworkList) { - if(stopIterating == false) { - if(wifiNetwork.signal >= wifiNetworkToSort.signal) { - sortedPureNetworkList.insert(counter, wifiNetwork); - stopIterating = true; - } - counter = counter + 1; - } - } - // This happens if it's the smallest value, so insert it at the end - if(stopIterating == false) { - sortedPureNetworkList.append(wifiNetwork); - } - } - } - log("There are " + QString::number(sortedPureNetworkList.count()) + " sorted networks", className); - - for(global::wifi::wifiNetworkData wifiNetwork: sortedPureNetworkList) { - log("Signal strength with sorting: " + QString::number(wifiNetwork.signal), className); - } - - // And now, handle the remainder of the networks - for(global::wifi::wifiNetworkData wifiNetwork: sortedPureNetworkList) { - network* connectedNetwork = new network; - connectedNetwork->mainData = wifiNetwork; - connectedNetwork->currentlyConnectedNetwork = currentNetwork; - connectedNetwork->applyVariables(); - connect(this, &wifiDialog::killNetworkWidgets, connectedNetwork, &network::closeWrapper); - connect(connectedNetwork, &network::showToastSignal, this, &wifiDialog::showToastSlot); - connect(connectedNetwork, &network::refreshScreenSignal, this, &wifiDialog::refreshScreenSlot); - ui->scrollBarLayout->addWidget(connectedNetwork, Qt::AlignTop); - } - } - scannedAtLeastOnce = true; - ui->refreshBtn->setEnabled(true); - ui->refreshBtn->setStyleSheet(ui->refreshBtn->styleSheet() + "background-color: white;"); - scanInProgress = false; - secondScanTry = false; -} - -void wifiDialog::on_wifiCheckBox_stateChanged(int arg1) -{ - if(ignoreCheckBoxCall == false) { - connectedNetworkDataParentSet = false; - log("Wi-Fi dialog checkbox clicked: " + QString::number(arg1), className); - if(wifiButtonEnabled == true) { - if(arg1 == 2) { - log("Turning Wi-Fi on", className); - // The watcher will scan Wi-Fi - QTimer::singleShot(0, this, SLOT(turnOnWifi())); - ui->stopBtn->setStyleSheet(ui->stopBtn->styleSheet() + "background-color: white;"); - ui->stopBtn->setEnabled(true); - } else { - log("Turning Wi-Fi off", className); - QTimer::singleShot(0, this, SLOT(turnOffWifi())); - // To inform the Wi-Fi icon updater to not show the connected/failed to connect message - writeFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/stopped", "true"); - ui->stopBtn->setStyleSheet(ui->stopBtn->styleSheet() + "background-color: lightGray;"); - ui->stopBtn->setEnabled(false); - } - emit killNetworkWidgets(); - } - if(wifiButtonEnabled == false) { - wifiButtonEnabled = true; - } - } - else { - ignoreCheckBoxCall = false; - if(checkWifiState() != global::wifi::wifiState::disabled) { - emit killNetworkWidgets(); - forceRefresh = true; - } - else { - emit killNetworkWidgets(); - } - } - -} - -void wifiDialog::turnOnWifi() { - writeFile("/opt/ibxd", "toggle_wifi_on\n"); - // No one will notice this freeze :> - waitToScan(); -} - -void wifiDialog::turnOffWifi() { - writeFile("/opt/ibxd", "toggle_wifi_off\n"); -} - -void wifiDialog::on_logBtn_clicked() -{ - // To avoid half of the information - if(scannedAtLeastOnce == false and checkWifiState() == global::wifi::wifiState::configured) { - log("Scanning at least once is needed"); - emit showToast("Scan at least once"); - } else { - wifilogger* wifiLoggerDialog = new wifilogger; - if(connectedNetworkDataParentSet == true) { - wifiLoggerDialog->connectedNetworkData = connectedNetworkDataParent; - wifiLoggerDialog->isThereData = true; - } - wifiLoggerDialog->exec(); - } -} - -void wifiDialog::showToastSlot(QString message) { - emit showToast(message); -} - -void wifiDialog::refreshScreenSlot() { - this->repaint(); -} - -/* - Some documentation used by the watcher - * connection_manager.sh - Manages all things, launches other processes - * connect_to_network.sh - All-in-one connection manager. Manages everything, used by IPD, should be used for Wi-Fi reconnections after sleeping/booting - * get_dhcp.sh - Gets dhcp addresses - * prepare_changing_wifi.sh - Kills everything, prepares to changing network - * timesync.sh - Syncs time - * toggle.sh - Turns Wi-Fi adapter on/off - * list_networks - Lists networks - * check_wifi_passphrase.sh - Checks Wi-Fi network passphrase - * watcher() first watches at processes that could kill other ones -*/ - -void wifiDialog::watcher() { - bool killing = checkProcessName("toggle.sh"); - bool changing = checkProcessName("prepare_changing_wifi.sh"); - if(killing == true) { - setStatusText("Changing Wi-Fi adapter status"); - isToggleRunning = true; - QTimer::singleShot(relaunchMs, this, SLOT(watcher())); - return void(); - } - - if(changing == true) { - if(global::deviceID == "n705\n") { - setStatusText("Disconnecting or cleaning up"); - } - else { - setStatusText("Disconnecting from a network or cleaning up"); - } - log("prepare_changing_wifi.sh is active", className); - QTimer::singleShot(relaunchMs, this, SLOT(watcher())); - return void(); - } - - bool reconnection = checkProcessName("connect_to_network.sh"); - if(reconnection == true) { - forceRefresh = true; - QFile recName = QFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/essid"); - if(recName.exists() == true) { - setStatusText("Reconnecting to '" + readFile(recName.fileName()).replace("\n", "") + "'"); - } - else { - // Shouldn't be possible - setStatusText("Reconnecting after sleep"); - } - QTimer::singleShot(relaunchMs, this, SLOT(watcher())); - return void(); - } - - bool listing = checkProcessName("list_networks"); - if(listing == true) { - setStatusText("Scanning available networks"); - QTimer::singleShot(relaunchMs, this, SLOT(watcher())); - return void(); - } - - bool dhcp = checkProcessName("get_dhcp.sh"); - if(dhcp == true) { - forceRefresh = true; - setStatusText("Getting IP address"); - QTimer::singleShot(relaunchMs, this, SLOT(watcher())); - return void(); - } - - bool passphraseCheck = checkProcessName("check_wifi_passphrase.sh"); - if(passphraseCheck == true) { - forceRefresh = true; - setStatusText("Checking Wi-Fi network passphrase"); - QTimer::singleShot(relaunchMs, this, SLOT(watcher())); - return void(); - } - - bool time = checkProcessName("timesync.sh"); - if(time == true) { - forceRefresh = true; - setStatusText("Syncing time"); - QTimer::singleShot(relaunchMs, this, SLOT(watcher())); - return void(); - } - - bool connecting = checkProcessName("connection_manager.sh"); - if(connecting == true) { - forceRefresh = true; - setStatusText("Connecting to Wi-Fi network"); - QTimer::singleShot(relaunchMs, this, SLOT(watcher())); - return void(); - } - - if(ui->statusLabel->text() != "Idle") { - setStatusText("Idle"); - } - - if(unlockCheckBox == true) { - ui->wifiCheckBox->setEnabled(true); - unlockCheckBox = false; - } - - if(isToggleRunning == true) { - isToggleRunning = false; - // Make sure the checkbox is in the right state - if(checkWifiState() == global::wifi::wifiState::disabled) { - // In this state, ignore forceRefresh to avoid message - forceRefresh = false; - if(ui->wifiCheckBox->isChecked() == true) { - ignoreCheckBoxCall = true; - ui->wifiCheckBox->setChecked(false); - } - } - else { - if(ui->wifiCheckBox->isChecked() == false) { - ignoreCheckBoxCall = true; - ui->wifiCheckBox->setChecked(true); - } - } - } - - if(forceRefresh == true) { - forceRefresh = false; - refreshFromWatcher = true; - QTimer::singleShot(1500, this, SLOT(waitToScan())); - } - - QTimer::singleShot(relaunchMs, this, SLOT(watcher())); -} - -void wifiDialog::setStatusText(QString message) { - ui->statusLabel->setText(message); -} - -void wifiDialog::on_stopBtn_clicked() -{ - log("Stop button was clicked", className); - connectedNetworkDataParentSet = false; - ui->wifiCheckBox->setEnabled(false); - unlockCheckBox = true; - - // To inform the wifi icon GUI to don't show the connected/failed to connect message - writeFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/stopped", "true"); - writeFile("/opt/ibxd", "stop_wifi_operations\n"); - - QFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/essid").remove(); - QFile("/mnt/onboard/.adds/inkbox/.config/17-wifi_connection_information/passphrase").remove(); - - // This variable just avoids showing the toast, so it is usable here too - waitToScan(); -} - -void wifiDialog::on_returnBtn_clicked() -{ - this->deleteLater(); - this->close(); -} - -void wifiDialog::waitToScan() { - if(checkWifiState() != global::wifi::wifiState::disabled) { - ui->refreshBtn->click(); - } - else { - QTimer::singleShot(750, this, SLOT(waitToScan())); - } -} diff --git a/src/widgets/dialogs/wifi/wifilogger.cpp b/src/widgets/dialogs/wifi/wifilogger.cpp deleted file mode 100644 index fd57b5f..0000000 --- a/src/widgets/dialogs/wifi/wifilogger.cpp +++ /dev/null @@ -1,207 +0,0 @@ -#include -#include -#include - -#include "wifilogger.h" -#include "ui_wifilogger.h" -#include "functions.h" - -wifilogger::wifilogger(QWidget *parent) : - QDialog(parent), - ui(new Ui::wifilogger) -{ - ui->setupUi(this); - this->setFont(QFont("u001")); - // 'Not currently connected to a network' label - ui->label_8->setFont(QFont("Inter")); - ui->returnBtn->setFont(QFont("Inter")); - ui->nameLabel->setFont(QFont("Inter")); - ui->allLogsText->setFont(QFont("Roboto Mono")); - ui->fancyLogsText->setFont(QFont("Roboto Mono")); - ui->nameLabel->setStyleSheet("font-weight: bold"); - ui->returnBtn->setStyleSheet("font-weight: bold"); - ui->allLogsText->setStyleSheet("font-size: 7.5pt"); - ui->fancyLogsText->setStyleSheet("font-size: 7.5pt"); - - // Stylesheet, style & misc. - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - this->setModal(true); - - // Scroll bar - // Needed for the nia. - // ui->allLogsText->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 50px; }"); - // ui->fancyLogsText->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 50px; }"); - - log("Entered wifilogger", className); - setWifiInfoPage(); - ui->previousBtn->setProperty("type", "borderless"); - ui->nextBtn->setProperty("type", "borderless"); - ui->returnBtn->setProperty("type", "borderless"); - ui->refreshBtn->setProperty("type", "borderless"); - - // Size - QRect screenGeometry = QGuiApplication::screens()[0]->geometry(); - this->setFixedWidth(screenGeometry.width() / 1.2); - - int halfOfHalfHeight = ((screenGeometry.height() / 2) / 2) / 2; - int finalHeight = screenGeometry.height() - halfOfHalfHeight * 2.4; - - this->setFixedHeight(finalHeight); - - // Centering dialog - int x = (screenGeometry.width() - this->width()) / 2; - int y = (screenGeometry.height() - this->height()) / 2; - this->move(x, y); -} - -wifilogger::~wifilogger() -{ - delete ui; -} - -void wifilogger::setWifiInfoPage() { - if(checkWifiState() == global::wifi::wifiState::configured) { - getWifiInformationTimer.singleShot(0, this, SLOT(getWifiInformation())); - ui->stackedWidget->setCurrentIndex(0); - ui->nameLabel->setText("Network information"); - } - else { - ui->stackedWidget->setCurrentIndex(1); - ui->nameLabel->setText("Not connected to a network"); - } -} - -void wifilogger::setFancyLoggingPage() { - updateLogs(); - ui->stackedWidget->setCurrentIndex(2); - ui->nameLabel->setText("Important logs"); -} - -void wifilogger::setAllLogsPage() { - updateLogs(); - ui->stackedWidget->setCurrentIndex(3); - ui->nameLabel->setText("All logs"); -} - -void wifilogger::on_nextBtn_clicked() -{ - if(currentPage == 2) { - currentPage = 0; - } - else { - currentPage = currentPage + 1; - } - changePage(); -} - -void wifilogger::on_previousBtn_clicked() -{ - if(currentPage == 0) { - currentPage = 2; - } - else { - currentPage = currentPage - 1; - } - changePage(); -} - -void wifilogger::changePage() { - if(currentPage == 0) { - setWifiInfoPage(); - } - else if(currentPage == 1) { - setFancyLoggingPage(); - } - else if(currentPage == 2) { - setAllLogsPage(); - } - else { - log("This shouldn't happen", className); - } -} - -void wifilogger::getWifiInformation() { - log("Retrieving Wi-Fi information", className); - QFile wifiInformationPath = QFile("/external_root/run/wifi_information"); - if(waitingForFile == false) { - wifiInformationPath.remove(); - log("Sending get_wifi_information ibxd call", className); - writeFile("/opt/ibxd", "get_wifi_information\n"); - waitingForFile = true; - } - - if(waitingForFile == true) { - if(wifiInformationPath.exists() == false) { - getWifiInformationTimer.singleShot(1000, this, SLOT(getWifiInformation())); - return void(); - } - } - - waitingForFile = false; - log("Setting variables", className); - QString wifiInfo = readFile(wifiInformationPath.fileName()); - QStringList wifiInfoList = wifiInfo.split("\n"); - int counter = 0; - for(QString infomation: wifiInfoList) { - if(counter == 0) { - ui->netNameLabel->setText(infomation); - } - if(counter == 1) { - ui->ipLabel->setText(infomation); - } - if(counter == 2) { - ui->maskLabel->setText(infomation); - } - if(counter == 3) { - ui->gatewayLabel->setText(infomation); - } - counter = counter + 1; - } - - if(isThereData == true) { - ui->encryptionLabel->setText(QVariant(connectedNetworkData.encryption).toString()); - ui->signalLabel->setText(QString::number(connectedNetworkData.signal) + "%"); - ui->macLabel->setText(connectedNetworkData.mac); - } - else { - // Shouldn't happen for 99%, but if anyway... it's designed to be non-blocking, so I can't really wait for this. - ui->encryptionLabel->setText("Rescan needed"); - ui->signalLabel->setText("Rescan needed"); - ui->macLabel->setText("Rescan needed"); - } -} - -void wifilogger::on_returnBtn_clicked() -{ - log("Exiting wifilogger", className); - getWifiInformationTimer.stop(); - this->deleteLater(); - this->close(); -} - -void wifilogger::updateLogs() { - if(fancyLogs.exists() == true and allLogs.exists() == true) { - QString fancyLogsText = readFile(fancyLogs.fileName()); - QString allLogsText = readFile(allLogs.fileName()); - - ui->fancyLogsText->setText(fancyLogsText); - ui->allLogsText->setText(allLogsText); - ui->fancyLogsText->verticalScrollBar()->setValue(ui->fancyLogsText->verticalScrollBar()->maximum()); - ui->allLogsText->verticalScrollBar()->setValue(ui->allLogsText->verticalScrollBar()->maximum()); - } -} - -void wifilogger::on_refreshBtn_clicked() -{ - if(currentPage == 0) { - if(waitingForFile == false) { - setWifiInfoPage(); - } - } - else { - updateLogs(); - } -} diff --git a/src/widgets/text/textwidget.cpp b/src/widgets/text/textwidget.cpp deleted file mode 100644 index 8fb1d0a..0000000 --- a/src/widgets/text/textwidget.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "textwidget.h" -#include "ui_textwidget.h" -#include "functions.h" - -#include -#include - -textwidget::textwidget(QWidget *parent) : - QWidget(parent), - ui(new Ui::textwidget) -{ - ui->setupUi(this); - ui->textBrowser->setFont(QFont("u001")); - - // Stylesheet - QFile stylesheetFile("/mnt/onboard/.adds/inkbox/eink.qss"); - stylesheetFile.open(QFile::ReadOnly); - this->setStyleSheet(stylesheetFile.readAll()); - stylesheetFile.close(); - - if(global::text::textBrowserDialog == true) { - ui->textBrowser->setStyleSheet("font-size: 9pt"); - } - ui->textBrowser->setText(global::text::textBrowserContents); -} - -textwidget::~textwidget() -{ - delete ui; -}