commit 3beecdda38492bd33aa3cea7b7bb9fcdc2877b31 Author: iaom Date: Mon Jul 31 18:01:44 2023 +0800 Import Upstream version 4.0.0.0 diff --git a/3rd-parties/qtsingleapplication/INSTALL.TXT b/3rd-parties/qtsingleapplication/INSTALL.TXT new file mode 100644 index 0000000..bbb74a9 --- /dev/null +++ b/3rd-parties/qtsingleapplication/INSTALL.TXT @@ -0,0 +1,254 @@ +INSTALLATION INSTRUCTIONS + +These instructions refer to the package you are installing as +some-package.tar.gz or some-package.zip. The .zip file is intended for use +on Windows. + +The directory you choose for the installation will be referred to as +your-install-dir. + +Note to Qt Visual Studio Integration users: In the instructions below, +instead of building from command line with nmake, you can use the menu +command 'Qt->Open Solution from .pro file' on the .pro files in the +example and plugin directories, and then build from within Visual +Studio. + +Unpacking and installation +-------------------------- + +1. Unpacking the archive (if you have not done so already). + + On Unix and Mac OS X (in a terminal window): + + cd your-install-dir + gunzip some-package.tar.gz + tar xvf some-package.tar + + This creates the subdirectory some-package containing the files. + + On Windows: + + Unpack the .zip archive by right-clicking it in explorer and + choosing "Extract All...". If your version of Windows does not + have zip support, you can use the infozip tools available + from www.info-zip.org. + + If you are using the infozip tools (in a command prompt window): + cd your-install-dir + unzip some-package.zip + +2. Configuring the package. + + The configure script is called "configure" on unix/mac and + "configure.bat" on Windows. It should be run from a command line + after cd'ing to the package directory. + + You can choose whether you want to use the component by including + its source code directly into your project, or build the component + as a dynamic shared library (DLL) that is loaded into the + application at run-time. The latter may be preferable for + technical or licensing (LGPL) reasons. If you want to build a DLL, + run the configure script with the argument "-library". Also see + the note about usage below. + + (Components that are Qt plugins, e.g. styles and image formats, + are by default built as a plugin DLL.) + + The configure script will prompt you in some cases for further + information. Answer these questions and carefully read the license text + before accepting the license conditions. The package cannot be used if + you do not accept the license conditions. + +3. Building the component and examples (when required). + + If a DLL is to be built, or if you would like to build the + examples, next give the commands + + qmake + make [or nmake if your are using Microsoft Visual C++] + + The example program(s) can be found in the directory called + "examples" or "example". + + Components that are Qt plugins, e.g. styles and image formats, are + ready to be used as soon as they are built, so the rest of this + installation instruction can be skipped. + +4. Building the Qt Designer plugin (optional). + + Some of the widget components are provided with plugins for Qt + Designer. To build and install the plugin, cd into the + some-package/plugin directory and give the commands + + qmake + make [or nmake if your are using Microsoft Visual C++] + + Restart Qt Designer to make it load the new widget plugin. + + Note: If you are using the built-in Qt Designer from the Qt Visual + Studio Integration, you will need to manually copy the plugin DLL + file, i.e. copy + %QTDIR%\plugins\designer\some-component.dll + to the Qt Visual Studio Integration plugin path, typically: + C:\Program Files\Trolltech\Qt VS Integration\plugins + + Note: If you for some reason are using a Qt Designer that is built + in debug mode, you will need to build the plugin in debug mode + also. Edit the file plugin.pro in the plugin directory, changing + 'release' to 'debug' in the CONFIG line, before running qmake. + + + +Solutions components are intended to be used directly from the package +directory during development, so there is no 'make install' procedure. + + +Using a component in your project +--------------------------------- + +To use this component in your project, add the following line to the +project's .pro file (or do the equivalent in your IDE): + + include(your-install-dir/some-package/src/some-package.pri) + +This adds the package's sources and headers to the SOURCES and HEADERS +project variables respectively (or, if the component has been +configured as a DLL, it adds that library to the LIBS variable), and +updates INCLUDEPATH to contain the package's src +directory. Additionally, the .pri file may include some dependencies +needed by the package. + +To include a header file from the package in your sources, you can now +simply use: + + #include + +or alternatively, in pre-Qt 4 style: + + #include + +Refer to the documentation to see the classes and headers this +components provides. + + + +Install documentation (optional) +-------------------------------- + +The HTML documentation for the package's classes is located in the +your-install-dir/some-package/doc/html/index.html. You can open this +file and read the documentation with any web browser. + +To install the documentation into Qt Assistant (for Qt version 4.4 and +later): + +1. In Assistant, open the Edit->Preferences dialog and choose the + Documentation tab. Click the Add... button and select the file + your-install-dir/some-package/doc/html/some-package.qch + +For Qt versions prior to 4.4, do instead the following: + +1. The directory your-install-dir/some-package/doc/html contains a + file called some-package.dcf. Execute the following commands in a + shell, command prompt or terminal window: + + cd your-install-dir/some-package/doc/html/ + assistant -addContentFile some-package.dcf + +The next time you start Qt Assistant, you can access the package's +documentation. + + +Removing the documentation from assistant +----------------------------------------- + +If you have installed the documentation into Qt Assistant, and want to uninstall it, do as follows, for Qt version 4.4 and later: + +1. In Assistant, open the Edit->Preferences dialog and choose the + Documentation tab. In the list of Registered Documentation, select + the item com.nokia.qtsolutions.some-package_version, and click + the Remove button. + +For Qt versions prior to 4.4, do instead the following: + +1. The directory your-install-dir/some-package/doc/html contains a + file called some-package.dcf. Execute the following commands in a + shell, command prompt or terminal window: + + cd your-install-dir/some-package/doc/html/ + assistant -removeContentFile some-package.dcf + + + +Using the component as a DLL +---------------------------- + +1. Normal components + + The shared library (DLL) is built and placed in the + some-package/lib directory. It is intended to be used directly + from there during development. When appropriate, both debug and + release versions are built, since the run-time linker will in some + cases refuse to load a debug-built DLL into a release-built + application or vice versa. + + The following steps are taken by default to help the dynamic + linker to locate the DLL at run-time (during development): + + Unix: The some-package.pri file will add linker instructions to + add the some-package/lib directory to the rpath of the + executable. (When distributing, or if your system does not support + rpath, you can copy the shared library to another place that is + searched by the dynamic linker, e.g. the "lib" directory of your + Qt installation.) + + Mac: The full path to the library is hardcoded into the library + itself, from where it is copied into the executable at link time, + and ready by the dynamic linker at run-time. (When distributing, + you will want to edit these hardcoded paths in the same way as for + the Qt DLLs. Refer to the document "Deploying an Application on + Mac OS X" in the Qt Reference Documentation.) + + Windows: the .dll file(s) are copied into the "bin" directory of + your Qt installation. The Qt installation will already have set up + that directory to be searched by the dynamic linker. + + +2. Plugins + + For Qt Solutions plugins (e.g. image formats), both debug and + release versions of the plugin are built by default when + appropriate, since in some cases the release Qt library will not + load a debug plugin, and vice versa. The plugins are automatically + copied into the plugins directory of your Qt installation when + built, so no further setup is required. + + Plugins may also be built statically, i.e. as a library that will be + linked into your application executable, and so will not need to + be redistributed as a separate plugin DLL to end users. Static + building is required if Qt itself is built statically. To do it, + just add "static" to the CONFIG variable in the plugin/plugin.pro + file before building. Refer to the "Static Plugins" section in the + chapter "How to Create Qt Plugins" for explanation of how to use a + static plugin in your application. The source code of the example + program(s) will also typically contain the relevant instructions + as comments. + + + +Uninstalling +------------ + + The following command will remove any fils that have been + automatically placed outside the package directory itself during + installation and building + + make distclean [or nmake if your are using Microsoft Visual C++] + + If Qt Assistant documentation or Qt Designer plugins have been + installed, they can be uninstalled manually, ref. above. + + +Enjoy! :) + +- The Qt Solutions Team. diff --git a/3rd-parties/qtsingleapplication/README.TXT b/3rd-parties/qtsingleapplication/README.TXT new file mode 100644 index 0000000..06abb09 --- /dev/null +++ b/3rd-parties/qtsingleapplication/README.TXT @@ -0,0 +1,33 @@ +Qt Solutions Component: Single Application + +The QtSingleApplication component provides support for +applications that can be only started once per user. + + + +Version history: + +2.0: - Version 1.3 ported to Qt 4. + +2.1: - Fix compilation problem on Mac. + +2.2: - Really fix the Mac compilation problem. + - Mac: fix crash due to wrong object releasing. + - Mac: Fix memory leak. + +2.3: - Windows: Force creation of internal widget to make it work + with Qt 4.2. + +2.4: - Fix the system for automatic window raising on message + reception. NOTE: minor API change. + +2.5: - Mac: Fix isRunning() to work and report correctly. + +2.6: - - initialize() is now obsolete, no longer necessary to call + it + - - Fixed race condition where multiple instances migth be started + - - QtSingleCoreApplication variant provided for non-GUI (console) + usage + - Complete reimplementation. Visible changes: + - LGPL release. + diff --git a/3rd-parties/qtsingleapplication/buildlib/buildlib.pro b/3rd-parties/qtsingleapplication/buildlib/buildlib.pro new file mode 100644 index 0000000..37dddcd --- /dev/null +++ b/3rd-parties/qtsingleapplication/buildlib/buildlib.pro @@ -0,0 +1,13 @@ +TEMPLATE=lib +CONFIG += qt dll qtsingleapplication-buildlib +mac:CONFIG += absolute_library_soname +win32|mac:!wince*:!win32-msvc:!macx-xcode:CONFIG += debug_and_release build_all +include(../src/qtsingleapplication.pri) +TARGET = $$QTSINGLEAPPLICATION_LIBNAME +DESTDIR = $$QTSINGLEAPPLICATION_LIBDIR +win32 { + DLLDESTDIR = $$[QT_INSTALL_BINS] + QMAKE_DISTCLEAN += $$[QT_INSTALL_BINS]\\$${QTSINGLEAPPLICATION_LIBNAME}.dll +} +target.path = $$DESTDIR +INSTALLS += target diff --git a/3rd-parties/qtsingleapplication/common.pri b/3rd-parties/qtsingleapplication/common.pri new file mode 100644 index 0000000..924c57c --- /dev/null +++ b/3rd-parties/qtsingleapplication/common.pri @@ -0,0 +1,14 @@ +exists(config.pri):infile(config.pri, SOLUTIONS_LIBRARY, yes): CONFIG += qtsingleapplication-uselib + +TEMPLATE += fakelib +greaterThan(QT_MAJOR_VERSION, 5)|\ + if(equals(QT_MAJOR_VERSION, 5):greaterThan(QT_MINOR_VERSION, 4))|\ + if(equals(QT_MAJOR_VERSION, 5):equals(QT_MINOR_VERSION, 4):greaterThan(QT_PATCH_VERSION, 1)) { + QTSINGLEAPPLICATION_LIBNAME = $$qt5LibraryTarget(QtSolutions_SingleApplication-head) +} else { + QTSINGLEAPPLICATION_LIBNAME = $$qtLibraryTarget(QtSolutions_SingleApplication-head) +} +TEMPLATE -= fakelib + +QTSINGLEAPPLICATION_LIBDIR = $$PWD/lib +unix:qtsingleapplication-uselib:!qtsingleapplication-buildlib:QMAKE_RPATHDIR += $$QTSINGLEAPPLICATION_LIBDIR diff --git a/3rd-parties/qtsingleapplication/configure b/3rd-parties/qtsingleapplication/configure new file mode 100755 index 0000000..3c4edff --- /dev/null +++ b/3rd-parties/qtsingleapplication/configure @@ -0,0 +1,25 @@ +#!/bin/sh + +if [ "x$1" != "x" -a "x$1" != "x-library" ]; then + echo "Usage: $0 [-library]" + echo + echo "-library: Build the component as a dynamic library (DLL). Default is to" + echo " include the component source code directly in the application." + echo + exit 0 +fi + +rm -f config.pri +if [ "x$1" = "x-library" ]; then + echo "Configuring to build this component as a dynamic library." + echo "SOLUTIONS_LIBRARY = yes" > config.pri +fi + +echo +echo "This component is now configured." +echo +echo "To build the component library (if requested) and example(s)," +echo "run qmake and your make command." +echo +echo "To remove or reconfigure, run make distclean." +echo diff --git a/3rd-parties/qtsingleapplication/configure.bat b/3rd-parties/qtsingleapplication/configure.bat new file mode 100644 index 0000000..2927549 --- /dev/null +++ b/3rd-parties/qtsingleapplication/configure.bat @@ -0,0 +1,43 @@ +:: Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +:: SPDX-License-Identifier: BSD-3-Clause + +@echo off + +rem +rem "Main" +rem + +if not "%1"=="" ( + if not "%1"=="-library" ( + call :PrintUsage + goto EOF + ) +) + +if exist config.pri. del config.pri +if "%1"=="-library" ( + echo Configuring to build this component as a dynamic library. + echo SOLUTIONS_LIBRARY = yes > config.pri +) + +echo . +echo This component is now configured. +echo . +echo To build the component library (if requested) and example(s), +echo run qmake and your make or nmake command. +echo . +echo To remove or reconfigure, run make (nmake) distclean. +echo . +goto EOF + +:PrintUsage +echo Usage: configure.bat [-library] +echo . +echo -library: Build the component as a dynamic library (DLL). Default is to +echo include the component source directly in the application. +echo A DLL may be preferable for technical or licensing (LGPL) reasons. +echo . +goto EOF + + +:EOF diff --git a/3rd-parties/qtsingleapplication/doc/html/classic.css b/3rd-parties/qtsingleapplication/doc/html/classic.css new file mode 100644 index 0000000..b8cae8e --- /dev/null +++ b/3rd-parties/qtsingleapplication/doc/html/classic.css @@ -0,0 +1,284 @@ +BODY,H1,H2,H3,H4,H5,H6,P,CENTER,TD,TH,UL,DL,DIV { + font-family: Arial, Geneva, Helvetica, sans-serif; +} +H1 { + text-align: center; + font-size: 160%; +} +H2 { + font-size: 120%; +} +H3 { + font-size: 100%; +} + +h3.fn,span.fn +{ + background-color: #eee; + border-width: 1px; + border-style: solid; + border-color: #ddd; + font-weight: bold; + padding: 6px 0px 6px 10px; + margin: 42px 0px 0px 0px; +} + +hr { + border: 0; + color: #a0a0a0; + background-color: #ccc; + height: 1px; + width: 100%; + text-align: left; + margin: 34px 0px 34px 0px; +} + +table.valuelist { + border-width: 1px 1px 1px 1px; + border-style: solid; + border-color: #dddddd; + border-collapse: collapse; + background-color: #f0f0f0; +} + +table.indextable { + border-width: 1px 1px 1px 1px; + border-style: solid; + border-collapse: collapse; + background-color: #f0f0f0; + border-color:#555; + font-size: 100%; +} + +table td.largeindex { + border-width: 1px 1px 1px 1px; + border-collapse: collapse; + background-color: #f0f0f0; + border-color:#555; + font-size: 120%; +} + +table.valuelist th { + border-width: 1px 1px 1px 2px; + padding: 4px; + border-style: solid; + border-color: #666; + color:white; + background-color:#666; +} + +th.titleheader { + border-width: 1px 0px 1px 0px; + padding: 2px; + border-style: solid; + border-color: #666; + color:white; + background-color:#555; + background-image:url('images/gradient.png')}; + background-repeat: repeat-x; + font-size: 100%; +} + + +th.largeheader { + border-width: 1px 0px 1px 0px; + padding: 4px; + border-style: solid; + border-color: #444; + color:white; + background-color:#555555; + font-size: 120%; +} + +p { + + margin-left: 4px; + margin-top: 8px; + margin-bottom: 8px; +} + +a:link +{ + color: #0046ad; + text-decoration: none +} + +a:visited +{ + color: #672967; + text-decoration: none +} + +a.obsolete +{ + color: #661100; + text-decoration: none +} + +a.compat +{ + color: #661100; + text-decoration: none +} + +a.obsolete:visited +{ + color: #995500; + text-decoration: none +} + +a.compat:visited +{ + color: #995500; + text-decoration: none +} + +body +{ + background: #ffffff; + color: black +} + +table.generic, table.annotated +{ + border-width: 1px; + border-color:#bbb; + border-style:solid; + border-collapse:collapse; +} + +table td.memItemLeft { + width: 180px; + padding: 2px 0px 0px 8px; + margin: 4px; + border-width: 1px; + border-color: #E0E0E0; + border-style: none; + font-size: 100%; + white-space: nowrap +} + +table td.memItemRight { + padding: 2px 8px 0px 8px; + margin: 4px; + border-width: 1px; + border-color: #E0E0E0; + border-style: none; + font-size: 100%; +} + +table tr.odd { + background: #f0f0f0; + color: black; +} + +table tr.even { + background: #e4e4e4; + color: black; +} + +table.annotated th { + padding: 3px; + text-align: left +} + +table.annotated td { + padding: 3px; +} + +table tr pre +{ + padding-top: 0px; + padding-bottom: 0px; + padding-left: 0px; + padding-right: 0px; + border: none; + background: none +} + +tr.qt-style +{ + background: #96E066; + color: black +} + +body pre +{ + padding: 0.2em; + border: #e7e7e7 1px solid; + background: #f1f1f1; + color: black +} + +table tr.qt-code pre +{ + padding: 0.2em; + border: #e7e7e7 1px solid; + background: #f1f1f1; + color: black +} + +span.preprocessor, span.preprocessor a +{ + color: darkblue; +} + +span.comment +{ + color: darkred; + font-style: italic +} + +span.string,span.char +{ + color: darkgreen; +} + +.title +{ + text-align: center +} + +.subtitle +{ + font-size: 0.8em +} + +.small-subtitle +{ + font-size: 0.65em +} + +.qmlitem { + padding: 0; +} + +.qmlname { + white-space: nowrap; +} + +.qmltype { + text-align: center; + font-size: 160%; +} + +.qmlproto { + background-color: #eee; + border-width: 1px; + border-style: solid; + border-color: #ddd; + font-weight: bold; + padding: 6px 10px 6px 10px; + margin: 42px 0px 0px 0px; +} + +.qmlreadonly { + float: right; + color: red +} + +.qmldoc { +} + +*.qmlitem p { +} diff --git a/3rd-parties/qtsingleapplication/doc/html/images/qt-logo.png b/3rd-parties/qtsingleapplication/doc/html/images/qt-logo.png new file mode 100644 index 0000000..794162f Binary files /dev/null and b/3rd-parties/qtsingleapplication/doc/html/images/qt-logo.png differ diff --git a/3rd-parties/qtsingleapplication/doc/html/index.html b/3rd-parties/qtsingleapplication/doc/html/index.html new file mode 100644 index 0000000..af9dab1 --- /dev/null +++ b/3rd-parties/qtsingleapplication/doc/html/index.html @@ -0,0 +1,48 @@ + + + + + + Single Application + + + + + + + +
  Home

Single Application
+

+ +

Description

+

The QtSingleApplication component provides support for applications that can be only started once per user.

+

For some applications it is useful or even critical that they are started only once by any user. Future attempts to start the application should activate any already running instance, and possibly perform requested actions, e.g. loading a file, in that instance.

+

The QtSingleApplication class provides an interface to detect a running instance, and to send command strings to that instance. For console (non-GUI) applications, the QtSingleCoreApplication variant is provided, which avoids dependency on QtGui.

+ +

Classes

+ + +

Examples

+ + +

Tested platforms

+
    +
  • Qt 4.4, 4.5 / Windows XP / MSVC.NET 2005
  • +
  • Qt 4.4, 4.5 / Linux / gcc
  • +
  • Qt 4.4, 4.5 / MacOS X 10.5 / gcc
  • +
+


+ + + + +
Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies)Trademarks
Qt Solutions
+ diff --git a/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication-example-loader.html b/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication-example-loader.html new file mode 100644 index 0000000..6a36632 --- /dev/null +++ b/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication-example-loader.html @@ -0,0 +1,175 @@ + + + + + + Loading Documents + + + + + + + +
  Home

Loading Documents
+

+

The application in this example loads or prints the documents passed as commandline parameters to further instances of this application.

+
 /****************************************************************************
+ **
+ ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+ ** Contact: http://www.qt-project.org/legal
+ **
+ ** This file is part of the Qt Solutions component.
+ **
+ ** You may use this file under the terms of the BSD license as follows:
+ **
+ ** "Redistribution and use in source and binary forms, with or without
+ ** modification, are permitted provided that the following conditions are
+ ** met:
+ **   * Redistributions of source code must retain the above copyright
+ **     notice, this list of conditions and the following disclaimer.
+ **   * Redistributions in binary form must reproduce the above copyright
+ **     notice, this list of conditions and the following disclaimer in
+ **     the documentation and/or other materials provided with the
+ **     distribution.
+ **   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+ **     the names of its contributors may be used to endorse or promote
+ **     products derived from this software without specific prior written
+ **     permission.
+ **
+ ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+ **
+ ****************************************************************************/
+
+ #include <qtsingleapplication.h>
+ #include <QtCore/QFile>
+ #include <QtGui/QMainWindow>
+ #include <QtGui/QPrinter>
+ #include <QtGui/QPainter>
+ #include <QtGui/QTextEdit>
+ #include <QtGui/QMdiArea>
+ #include <QtCore/QTextStream>
+
+ class MainWindow : public QMainWindow
+ {
+     Q_OBJECT
+ public:
+     MainWindow();
+
+ public slots:
+     void handleMessage(const QString& message);
+
+ signals:
+     void needToShow();
+
+ private:
+     QMdiArea *workspace;
+ };
+

The user interface in this application is a QMainWindow subclass with a QMdiArea as the central widget. It implements a slot handleMessage() that will be connected to the messageReceived() signal of the QtSingleApplication class.

+
 MainWindow::MainWindow()
+ {
+     workspace = new QMdiArea(this);
+
+     setCentralWidget(workspace);
+ }
+

The MainWindow constructor creates a minimal user interface.

+
 void MainWindow::handleMessage(const QString& message)
+ {
+     enum Action {
+         Nothing,
+         Open,
+         Print
+     } action;
+
+     action = Nothing;
+     QString filename = message;
+     if (message.toLower().startsWith("/print ")) {
+         filename = filename.mid(7);
+         action = Print;
+     } else if (!message.isEmpty()) {
+         action = Open;
+     }
+     if (action == Nothing) {
+         emit needToShow();
+         return;
+     }
+
+     QFile file(filename);
+     QString contents;
+     if (file.open(QIODevice::ReadOnly))
+         contents = file.readAll();
+     else
+         contents = "[[Error: Could not load file " + filename + "]]";
+
+     QTextEdit *view = new QTextEdit;
+     view->setPlainText(contents);
+
+     switch(action) {
+

The handleMessage() slot interprets the message passed in as a filename that can be prepended with /print to indicate that the file should just be printed rather than loaded.

+
     case Print:
+         {
+             QPrinter printer;
+             view->print(&printer);
+             delete view;
+         }
+         break;
+
+     case Open:
+         {
+             workspace->addSubWindow(view);
+             view->setWindowTitle(message);
+             view->show();
+             emit needToShow();
+         }
+         break;
+     default:
+         break;
+     };
+ }
+

Loading the file will also activate the window.

+
 #include "main.moc"
+
+ int main(int argc, char **argv)
+ {
+     QtSingleApplication instance("File loader QtSingleApplication example", argc, argv);
+     QString message;
+     for (int a = 1; a < argc; ++a) {
+         message += argv[a];
+         if (a < argc-1)
+             message += " ";
+     }
+
+     if (instance.sendMessage(message))
+         return 0;
+

The main entry point function creates a QtSingleApplication object, and creates a message to send to a running instance of the application. If the message was sent successfully the process exits immediately.

+
     MainWindow mw;
+     mw.handleMessage(message);
+     mw.show();
+
+     QObject::connect(&instance, SIGNAL(messageReceived(const QString&)),
+                      &mw, SLOT(handleMessage(const QString&)));
+
+     instance.setActivationWindow(&mw, false);
+     QObject::connect(&mw, SIGNAL(needToShow()), &instance, SLOT(activateWindow()));
+
+     return instance.exec();
+ }
+

If the message could not be sent the application starts up. Note that false is passed to the call to setActivationWindow() to prevent automatic activation for every message received, e.g. when the application should just print a file. Instead, the message handling function determines whether activation is requested, and signals that by emitting the needToShow() signal. This is then simply connected directly to QtSingleApplication's activateWindow() slot.

+


+ + + + +
Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies)Trademarks
Qt Solutions
+ diff --git a/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication-example-trivial.html b/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication-example-trivial.html new file mode 100644 index 0000000..5e60cfa --- /dev/null +++ b/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication-example-trivial.html @@ -0,0 +1,101 @@ + + + + + + A Trivial Example + + + + + + + +
  Home

A Trivial Example
+

+

The application in this example has a log-view that displays messages sent by further instances of the same application.

+

The example demonstrates the use of the QtSingleApplication class to detect and communicate with a running instance of the application using the sendMessage() API. The messageReceived() signal is used to display received messages in a QTextEdit log.

+
 /****************************************************************************
+ **
+ ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+ ** Contact: http://www.qt-project.org/legal
+ **
+ ** This file is part of the Qt Solutions component.
+ **
+ ** You may use this file under the terms of the BSD license as follows:
+ **
+ ** "Redistribution and use in source and binary forms, with or without
+ ** modification, are permitted provided that the following conditions are
+ ** met:
+ **   * Redistributions of source code must retain the above copyright
+ **     notice, this list of conditions and the following disclaimer.
+ **   * Redistributions in binary form must reproduce the above copyright
+ **     notice, this list of conditions and the following disclaimer in
+ **     the documentation and/or other materials provided with the
+ **     distribution.
+ **   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+ **     the names of its contributors may be used to endorse or promote
+ **     products derived from this software without specific prior written
+ **     permission.
+ **
+ ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+ **
+ ****************************************************************************/
+
+ #include <qtsingleapplication.h>
+ #include <QtGui/QTextEdit>
+
+ class TextEdit : public QTextEdit
+ {
+     Q_OBJECT
+ public:
+     TextEdit(QWidget *parent = 0)
+         : QTextEdit(parent)
+     {}
+ public slots:
+     void append(const QString &str)
+     {
+         QTextEdit::append(str);
+     }
+ };
+
+ #include "main.moc"
+
+ int main(int argc, char **argv)
+ {
+     QtSingleApplication instance(argc, argv);
+

The example has only the main entry point function. A QtSingleApplication object is created immediately.

+
     if (instance.sendMessage("Wake up!"))
+         return 0;
+

If another instance of this application is already running, sendMessage() will succeed, and this instance just exits immediately.

+
     TextEdit logview;
+     logview.setReadOnly(true);
+     logview.show();
+

Otherwise the instance continues as normal and creates the user interface.

+
     instance.setActivationWindow(&logview);
+
+     QObject::connect(&instance, SIGNAL(messageReceived(const QString&)),
+                      &logview, SLOT(append(const QString&)));
+
+     return instance.exec();
+

The logview object is also set as the application's activation window. Every time a message is received, the window will be raised and activated automatically.

+

The messageReceived() signal is also connected to the QTextEdit's append() slot. Every message received from further instances of this application will be displayed in the log.

+

Finally the event loop is entered.

+


+ + + + +
Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies)Trademarks
Qt Solutions
+ diff --git a/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication-members.html b/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication-members.html new file mode 100644 index 0000000..c995ce3 --- /dev/null +++ b/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication-members.html @@ -0,0 +1,235 @@ + + + + + + List of All Members for QtSingleApplication + + + + + + + +
  Home

List of All Members for QtSingleApplication

+

This is the complete list of members for QtSingleApplication, including inherited members.

+

+ +
+

+


+ + + + +
Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies)Trademarks
Qt Solutions
+ diff --git a/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication-obsolete.html b/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication-obsolete.html new file mode 100644 index 0000000..0d07dfa --- /dev/null +++ b/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication-obsolete.html @@ -0,0 +1,31 @@ + + + + + + Obsolete Members for QtSingleApplication + + + + + + + +
  Home

Obsolete Members for QtSingleApplication

+

The following class members are obsolete. They are provided to keep old source code working. We strongly advise against using them in new code.

+

+

Public Functions

+ + +
void initialize ( bool dummy = true )   (obsolete)
+
+

Member Function Documentation

+

void QtSingleApplication::initialize ( bool dummy = true )

+


+ + + + +
Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies)Trademarks
Qt Solutions
+ diff --git a/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication.dcf b/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication.dcf new file mode 100644 index 0000000..d81f87f --- /dev/null +++ b/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication.dcf @@ -0,0 +1,40 @@ + + +
+
+ QtSingleApplication + activateWindow + activationWindow + id + isRunning + messageReceived + sendMessage + setActivationWindow +
+
+
+
+ QtSingleCoreApplication + id + isRunning + messageReceived + sendMessage +
+
+
+
+
+ A non-GUI example +
+
+ A Trivial Example +
+
+ Loading Documents +
+
+ Single Application +
+
+
+ diff --git a/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication.html b/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication.html new file mode 100644 index 0000000..2754a3b --- /dev/null +++ b/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication.html @@ -0,0 +1,162 @@ + + + + + + QtSingleApplication Class Reference + + + + + + + +
  Home

QtSingleApplication Class Reference

+

The QtSingleApplication class provides an API to detect and communicate with running instances of an application. More...

+
 #include <QtSingleApplication>

Inherits QApplication.

+ +
+ +

Public Functions

+ + + + + + + + + + + +
QtSingleApplication ( int & argc, char ** argv, bool GUIenabled = true )
QtSingleApplication ( const QString & appId, int & argc, char ** argv )
QtSingleApplication ( int & argc, char ** argv, Type type )
QtSingleApplication ( Display * dpy, Qt::HANDLE visual = 0, Qt::HANDLE cmap = 0 )
QtSingleApplication ( Display * dpy, int & argc, char ** argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap = 0 )
QtSingleApplication ( Display * dpy, const QString & appId, int argc, char ** argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap = 0 )
QWidget * activationWindow () const
QString id () const
bool isRunning ()
void setActivationWindow ( QWidget * aw, bool activateOnMessage = true )
+ +
+ +

Public Slots

+ + + +
void activateWindow ()
bool sendMessage ( const QString & message, int timeout = 5000 )
+ +
+ +

Signals

+ + +
void messageReceived ( const QString & message )
+ +

Additional Inherited Members

+ + +
+

Detailed Description

+

The QtSingleApplication class provides an API to detect and communicate with running instances of an application.

+

This class allows you to create applications where only one instance should be running at a time. I.e., if the user tries to launch another instance, the already running instance will be activated instead. Another usecase is a client-server system, where the first started instance will assume the role of server, and the later instances will act as clients of that server.

+

By default, the full path of the executable file is used to determine whether two processes are instances of the same application. You can also provide an explicit identifier string that will be compared instead.

+

The application should create the QtSingleApplication object early in the startup phase, and call isRunning() to find out if another instance of this application is already running. If isRunning() returns false, it means that no other instance is running, and this instance has assumed the role as the running instance. In this case, the application should continue with the initialization of the application user interface before entering the event loop with exec(), as normal.

+

The messageReceived() signal will be emitted when the running application receives messages from another instance of the same application. When a message is received it might be helpful to the user to raise the application so that it becomes visible. To facilitate this, QtSingleApplication provides the setActivationWindow() function and the activateWindow() slot.

+

If isRunning() returns true, another instance is already running. It may be alerted to the fact that another instance has started by using the sendMessage() function. Also data such as startup parameters (e.g. the name of the file the user wanted this new instance to open) can be passed to the running instance with this function. Then, the application should terminate (or enter client mode).

+

If isRunning() returns true, but sendMessage() fails, that is an indication that the running instance is frozen.

+

Here's an example that shows how to convert an existing application to use QtSingleApplication. It is very simple and does not make use of all QtSingleApplication's functionality (see the examples for that).

+
 // Original
+ int main(int argc, char **argv)
+ {
+     QApplication app(argc, argv);
+
+     MyMainWidget mmw;
+     mmw.show();
+     return app.exec();
+ }
+
+ // Single instance
+ int main(int argc, char **argv)
+ {
+     QtSingleApplication app(argc, argv);
+
+     if (app.isRunning())
+         return !app.sendMessage(someDataString);
+
+     MyMainWidget mmw;
+     app.setActivationWindow(&mmw);
+     mmw.show();
+     return app.exec();
+ }
+

Once this QtSingleApplication instance is destroyed (normally when the process exits or crashes), when the user next attempts to run the application this instance will not, of course, be encountered. The next instance to call isRunning() or sendMessage() will assume the role as the new running instance.

+

For console (non-GUI) applications, QtSingleCoreApplication may be used instead of this class, to avoid the dependency on the QtGui library.

+

See also QtSingleCoreApplication.

+
+

Member Function Documentation

+

QtSingleApplication::QtSingleApplication ( int & argc, char ** argv, bool GUIenabled = true )

+

Creates a QtSingleApplication object. The application identifier will be QCoreApplication::applicationFilePath(). argc, argv, and GUIenabled are passed on to the QAppliation constructor.

+

If you are creating a console application (i.e. setting GUIenabled to false), you may consider using QtSingleCoreApplication instead.

+

QtSingleApplication::QtSingleApplication ( const QString & appId, int & argc, char ** argv )

+

Creates a QtSingleApplication object with the application identifier appId. argc and argv are passed on to the QAppliation constructor.

+

QtSingleApplication::QtSingleApplication ( int & argc, char ** argv, Type type )

+

Creates a QtSingleApplication object. The application identifier will be QCoreApplication::applicationFilePath(). argc, argv, and type are passed on to the QAppliation constructor.

+

QtSingleApplication::QtSingleApplication ( Display * dpy, Qt::HANDLE visual = 0, Qt::HANDLE cmap = 0 )

+

Special constructor for X11, ref. the documentation of QApplication's corresponding constructor. The application identifier will be QCoreApplication::applicationFilePath(). dpy, visual, and cmap are passed on to the QApplication constructor.

+

QtSingleApplication::QtSingleApplication ( Display * dpy, int & argc, char ** argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap = 0 )

+

Special constructor for X11, ref. the documentation of QApplication's corresponding constructor. The application identifier will be QCoreApplication::applicationFilePath(). dpy, argc, argv, visual, and cmap are passed on to the QApplication constructor.

+

QtSingleApplication::QtSingleApplication ( Display * dpy, const QString & appId, int argc, char ** argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap = 0 )

+

Special constructor for X11, ref. the documentation of QApplication's corresponding constructor. The application identifier will be appId. dpy, argc, argv, visual, and cmap are passed on to the QApplication constructor.

+

void QtSingleApplication::activateWindow ()   [slot]

+

De-minimizes, raises, and activates this application's activation window. This function does nothing if no activation window has been set.

+

This is a convenience function to show the user that this application instance has been activated when he has tried to start another instance.

+

This function should typically be called in response to the messageReceived() signal. By default, that will happen automatically, if an activation window has been set.

+

See also setActivationWindow(), messageReceived(), and initialize().

+

QWidget * QtSingleApplication::activationWindow () const

+

Returns the applications activation window if one has been set by calling setActivationWindow(), otherwise returns 0.

+

See also setActivationWindow().

+

QString QtSingleApplication::id () const

+

Returns the application identifier. Two processes with the same identifier will be regarded as instances of the same application.

+

bool QtSingleApplication::isRunning ()

+

Returns true if another instance of this application is running; otherwise false.

+

This function does not find instances of this application that are being run by a different user (on Windows: that are running in another session).

+

See also sendMessage().

+

void QtSingleApplication::messageReceived ( const QString & message )   [signal]

+

This signal is emitted when the current instance receives a message from another instance of this application.

+

See also sendMessage(), setActivationWindow(), and activateWindow().

+

bool QtSingleApplication::sendMessage ( const QString & message, int timeout = 5000 )   [slot]

+

Tries to send the text message to the currently running instance. The QtSingleApplication object in the running instance will emit the messageReceived() signal when it receives the message.

+

This function returns true if the message has been sent to, and processed by, the current instance. If there is no instance currently running, or if the running instance fails to process the message within timeout milliseconds, this function return false.

+

See also isRunning() and messageReceived().

+

void QtSingleApplication::setActivationWindow ( QWidget * aw, bool activateOnMessage = true )

+

Sets the activation window of this application to aw. The activation window is the widget that will be activated by activateWindow(). This is typically the application's main window.

+

If activateOnMessage is true (the default), the window will be activated automatically every time a message is received, just prior to the messageReceived() signal being emitted.

+

See also activationWindow(), activateWindow(), and messageReceived().

+


+ + + + +
Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies)Trademarks
Qt Solutions
+ diff --git a/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication.index b/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication.index new file mode 100644 index 0000000..56052c2 --- /dev/null +++ b/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication.index @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication.qhp b/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication.qhp new file mode 100644 index 0000000..ff42d9d --- /dev/null +++ b/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication.qhp @@ -0,0 +1,53 @@ + + + com.nokia.qtsolutions.qtsingleapplication_head + qdoc + + qt + solutions + qtsingleapplication + + + qt + solutions + qtsingleapplication + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + qtsingleapplication.html + index.html + qtsingleapplication-example-trivial.html + qtsinglecoreapplication.html + qtsingleapplication-example-loader.html + qtsinglecoreapplication-example-console.html + classic.css + images/qt-logo.png + + + diff --git a/3rd-parties/qtsingleapplication/doc/html/qtsinglecoreapplication-example-console.html b/3rd-parties/qtsingleapplication/doc/html/qtsinglecoreapplication-example-console.html new file mode 100644 index 0000000..18a9ae8 --- /dev/null +++ b/3rd-parties/qtsingleapplication/doc/html/qtsinglecoreapplication-example-console.html @@ -0,0 +1,118 @@ + + + + + + A non-GUI example + + + + + + + +
  Home

A non-GUI example
+

+

This example shows how to use the single-application functionality in a console application. It does not require the QtGui library at all.

+

The only differences from the GUI application usage demonstrated in the other examples are:

+

1) The .pro file should include qtsinglecoreapplication.pri instead of qtsingleapplication.pri

+

2) The class name is QtSingleCoreApplication instead of QtSingleApplication.

+

3) No calls are made regarding window activation, for obvious reasons.

+

console.pro:

+
 TEMPLATE   = app
+ CONFIG    += console
+ SOURCES   += main.cpp
+ include(../../src/qtsinglecoreapplication.pri)
+ QT -= gui
+

main.cpp:

+
 /****************************************************************************
+ **
+ ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+ ** Contact: http://www.qt-project.org/legal
+ **
+ ** This file is part of the Qt Solutions component.
+ **
+ ** You may use this file under the terms of the BSD license as follows:
+ **
+ ** "Redistribution and use in source and binary forms, with or without
+ ** modification, are permitted provided that the following conditions are
+ ** met:
+ **   * Redistributions of source code must retain the above copyright
+ **     notice, this list of conditions and the following disclaimer.
+ **   * Redistributions in binary form must reproduce the above copyright
+ **     notice, this list of conditions and the following disclaimer in
+ **     the documentation and/or other materials provided with the
+ **     distribution.
+ **   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
+ **     the names of its contributors may be used to endorse or promote
+ **     products derived from this software without specific prior written
+ **     permission.
+ **
+ ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
+ **
+ ****************************************************************************/
+
+ #include "qtsinglecoreapplication.h"
+ #include <QtCore/QDebug>
+
+ void report(const QString& msg)
+ {
+     qDebug("[%i] %s", (int)QCoreApplication::applicationPid(), qPrintable(msg));
+ }
+
+ class MainClass : public QObject
+ {
+     Q_OBJECT
+ public:
+     MainClass()
+         : QObject()
+         {}
+
+ public slots:
+     void handleMessage(const QString& message)
+         {
+             report( "Message received: \"" + message + "\"");
+         }
+ };
+
+ int main(int argc, char **argv)
+ {
+     report("Starting up");
+
+     QtSingleCoreApplication app(argc, argv);
+
+     if (app.isRunning()) {
+         QString msg(QString("Hi master, I am %1.").arg(QCoreApplication::applicationPid()));
+         bool sentok = app.sendMessage(msg, 2000);
+         QString rep("Another instance is running, so I will exit.");
+         rep += sentok ? " Message sent ok." : " Message sending failed; the other instance may be frozen.";
+         report(rep);
+         return 0;
+     } else {
+         report("No other instance is running; so I will.");
+         MainClass mainObj;
+         QObject::connect(&app, SIGNAL(messageReceived(const QString&)),
+                          &mainObj, SLOT(handleMessage(const QString&)));
+         return app.exec();
+     }
+ }
+
+ #include "main.moc"
+


+ + + + +
Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies)Trademarks
Qt Solutions
+ diff --git a/3rd-parties/qtsingleapplication/doc/html/qtsinglecoreapplication-members.html b/3rd-parties/qtsingleapplication/doc/html/qtsinglecoreapplication-members.html new file mode 100644 index 0000000..69fb858 --- /dev/null +++ b/3rd-parties/qtsingleapplication/doc/html/qtsinglecoreapplication-members.html @@ -0,0 +1,126 @@ + + + + + + List of All Members for QtSingleCoreApplication + + + + + + + +
  Home

List of All Members for QtSingleCoreApplication

+

This is the complete list of members for QtSingleCoreApplication, including inherited members.

+

+ +
+

+


+ + + + +
Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies)Trademarks
Qt Solutions
+ diff --git a/3rd-parties/qtsingleapplication/doc/html/qtsinglecoreapplication.html b/3rd-parties/qtsingleapplication/doc/html/qtsinglecoreapplication.html new file mode 100644 index 0000000..a20cf2f --- /dev/null +++ b/3rd-parties/qtsingleapplication/doc/html/qtsinglecoreapplication.html @@ -0,0 +1,98 @@ + + + + + + QtSingleCoreApplication Class Reference + + + + + + + +
  Home

QtSingleCoreApplication Class Reference

+

A variant of the QtSingleApplication class for non-GUI applications. More...

+
 #include <QtSingleCoreApplication>

Inherits QCoreApplication.

+ +
+ +

Public Functions

+ + + + + +
QtSingleCoreApplication ( int & argc, char ** argv )
QtSingleCoreApplication ( const QString & appId, int & argc, char ** argv )
QString id () const
bool isRunning ()
+ +
+ +

Public Slots

+ + +
bool sendMessage ( const QString & message, int timeout = 5000 )
+ +
+ +

Signals

+ + +
void messageReceived ( const QString & message )
+ +

Additional Inherited Members

+ + +
+

Detailed Description

+

A variant of the QtSingleApplication class for non-GUI applications.

+

This class is a variant of QtSingleApplication suited for use in console (non-GUI) applications. It is an extension of QCoreApplication (instead of QApplication). It does not require the QtGui library.

+

The API and usage is identical to QtSingleApplication, except that functions relating to the "activation window" are not present, for obvious reasons. Please refer to the QtSingleApplication documentation for explanation of the usage.

+

A QtSingleCoreApplication instance can communicate to a QtSingleApplication instance if they share the same application id. Hence, this class can be used to create a light-weight command-line tool that sends commands to a GUI application.

+

See also QtSingleApplication.

+
+

Member Function Documentation

+

QtSingleCoreApplication::QtSingleCoreApplication ( int & argc, char ** argv )

+

Creates a QtSingleCoreApplication object. The application identifier will be QCoreApplication::applicationFilePath(). argc and argv are passed on to the QCoreAppliation constructor.

+

QtSingleCoreApplication::QtSingleCoreApplication ( const QString & appId, int & argc, char ** argv )

+

Creates a QtSingleCoreApplication object with the application identifier appId. argc and argv are passed on to the QCoreAppliation constructor.

+

QString QtSingleCoreApplication::id () const

+

Returns the application identifier. Two processes with the same identifier will be regarded as instances of the same application.

+

bool QtSingleCoreApplication::isRunning ()

+

Returns true if another instance of this application is running; otherwise false.

+

This function does not find instances of this application that are being run by a different user (on Windows: that are running in another session).

+

See also sendMessage().

+

void QtSingleCoreApplication::messageReceived ( const QString & message )   [signal]

+

This signal is emitted when the current instance receives a message from another instance of this application.

+

See also sendMessage().

+

bool QtSingleCoreApplication::sendMessage ( const QString & message, int timeout = 5000 )   [slot]

+

Tries to send the text message to the currently running instance. The QtSingleCoreApplication object in the running instance will emit the messageReceived() signal when it receives the message.

+

This function returns true if the message has been sent to, and processed by, the current instance. If there is no instance currently running, or if the running instance fails to process the message within timeout milliseconds, this function return false.

+

See also isRunning() and messageReceived().

+


+ + + + +
Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies)Trademarks
Qt Solutions
+ diff --git a/3rd-parties/qtsingleapplication/doc/images/qt-logo.png b/3rd-parties/qtsingleapplication/doc/images/qt-logo.png new file mode 100644 index 0000000..794162f Binary files /dev/null and b/3rd-parties/qtsingleapplication/doc/images/qt-logo.png differ diff --git a/3rd-parties/qtsingleapplication/doc/index.qdoc b/3rd-parties/qtsingleapplication/doc/index.qdoc new file mode 100644 index 0000000..796dffe --- /dev/null +++ b/3rd-parties/qtsingleapplication/doc/index.qdoc @@ -0,0 +1,50 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + +/*! + \page index.html + \title Single Application + + \section1 Description + + The QtSingleApplication component provides support + for applications that can be only started once per user. + + + + For some applications it is useful or even critical that they are started + only once by any user. Future attempts to start the application should + activate any already running instance, and possibly perform requested + actions, e.g. loading a file, in that instance. + + The QtSingleApplication class provides an interface to detect a running + instance, and to send command strings to that instance. + For console (non-GUI) applications, the QtSingleCoreApplication variant is provided, which avoids dependency on QtGui. + + + + + \section1 Classes + \list + \i QtSingleApplication \i QtSingleCoreApplication\endlist + + \section1 Examples + \list + \i \link qtsingleapplication-example-trivial.html A Trivial Example \endlink \i \link qtsingleapplication-example-loader.html Loading Documents \endlink \i \link qtsinglecoreapplication-example-console.html A Non-GUI Example \endlink \endlist + + + + + + + \section1 Tested platforms + \list + \i Qt 4.4, 4.5 / Windows XP / MSVC.NET 2005 + \i Qt 4.4, 4.5 / Linux / gcc + \i Qt 4.4, 4.5 / MacOS X 10.5 / gcc + \endlist + + + + +*/ diff --git a/3rd-parties/qtsingleapplication/examples/console/console.pro b/3rd-parties/qtsingleapplication/examples/console/console.pro new file mode 100644 index 0000000..e0390e2 --- /dev/null +++ b/3rd-parties/qtsingleapplication/examples/console/console.pro @@ -0,0 +1,5 @@ +TEMPLATE = app +CONFIG += console +SOURCES += main.cpp +include(../../src/qtsinglecoreapplication.pri) +QT -= gui diff --git a/3rd-parties/qtsingleapplication/examples/console/console.qdoc b/3rd-parties/qtsingleapplication/examples/console/console.qdoc new file mode 100644 index 0000000..2706e26 --- /dev/null +++ b/3rd-parties/qtsingleapplication/examples/console/console.qdoc @@ -0,0 +1,28 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + +/*! \page qtsinglecoreapplication-example-console.html + \title A non-GUI example + + This example shows how to use the single-application functionality + in a console application. It does not require the \c QtGui library + at all. + + The only differences from the GUI application usage demonstrated + in the other examples are: + + 1) The \c.pro file should include \c qtsinglecoreapplication.pri + instead of \c qtsingleapplication.pri + + 2) The class name is \c QtSingleCoreApplication instead of \c + QtSingleApplication. + + 3) No calls are made regarding window activation, for obvious reasons. + + console.pro: + \quotefile console/console.pro + + main.cpp: + \quotefile console/main.cpp + +*/ diff --git a/3rd-parties/qtsingleapplication/examples/console/main.cpp b/3rd-parties/qtsingleapplication/examples/console/main.cpp new file mode 100644 index 0000000..13fd00e --- /dev/null +++ b/3rd-parties/qtsingleapplication/examples/console/main.cpp @@ -0,0 +1,52 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + + +#include "qtsinglecoreapplication.h" +#include + + +void report(const QString& msg) +{ + qDebug("[%i] %s", (int)QCoreApplication::applicationPid(), qPrintable(msg)); +} + +class MainClass : public QObject +{ + Q_OBJECT +public: + MainClass() + : QObject() + {} + +public slots: + void handleMessage(const QString& message) + { + report( "Message received: \"" + message + "\""); + } +}; + +int main(int argc, char **argv) +{ + report("Starting up"); + + QtSingleCoreApplication app(argc, argv); + + if (app.isRunning()) { + QString msg(QString("Hi master, I am %1.").arg(QCoreApplication::applicationPid())); + bool sentok = app.sendMessage(msg, 2000); + QString rep("Another instance is running, so I will exit."); + rep += sentok ? " Message sent ok." : " Message sending failed; the other instance may be frozen."; + report(rep); + return 0; + } else { + report("No other instance is running; so I will."); + MainClass mainObj; + QObject::connect(&app, SIGNAL(messageReceived(const QString&)), + &mainObj, SLOT(handleMessage(const QString&))); + return app.exec(); + } +} + + +#include "main.moc" diff --git a/3rd-parties/qtsingleapplication/examples/examples.pro b/3rd-parties/qtsingleapplication/examples/examples.pro new file mode 100644 index 0000000..36b8fd3 --- /dev/null +++ b/3rd-parties/qtsingleapplication/examples/examples.pro @@ -0,0 +1,4 @@ +TEMPLATE = subdirs +SUBDIRS = trivial \ + loader \ + console diff --git a/3rd-parties/qtsingleapplication/examples/loader/file1.qsl b/3rd-parties/qtsingleapplication/examples/loader/file1.qsl new file mode 100644 index 0000000..50fcd26 --- /dev/null +++ b/3rd-parties/qtsingleapplication/examples/loader/file1.qsl @@ -0,0 +1 @@ +File 1 diff --git a/3rd-parties/qtsingleapplication/examples/loader/file2.qsl b/3rd-parties/qtsingleapplication/examples/loader/file2.qsl new file mode 100644 index 0000000..4475433 --- /dev/null +++ b/3rd-parties/qtsingleapplication/examples/loader/file2.qsl @@ -0,0 +1 @@ +File 2 diff --git a/3rd-parties/qtsingleapplication/examples/loader/loader.pro b/3rd-parties/qtsingleapplication/examples/loader/loader.pro new file mode 100644 index 0000000..3e52586 --- /dev/null +++ b/3rd-parties/qtsingleapplication/examples/loader/loader.pro @@ -0,0 +1,6 @@ +greaterThan(QT_MAJOR_VERSION, 4): QT += printsupport +TEMPLATE = app + +include(../../src/qtsingleapplication.pri) + +SOURCES += main.cpp diff --git a/3rd-parties/qtsingleapplication/examples/loader/loader.qdoc b/3rd-parties/qtsingleapplication/examples/loader/loader.qdoc new file mode 100644 index 0000000..1f55026 --- /dev/null +++ b/3rd-parties/qtsingleapplication/examples/loader/loader.qdoc @@ -0,0 +1,44 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + +/*! \page qtsingleapplication-example-loader.html + \title Loading Documents + + The application in this example loads or prints the documents + passed as commandline parameters to further instances of this + application. + + \quotefromfile loader/main.cpp + \printuntil }; + The user interface in this application is a QMainWindow subclass + with a QMdiArea as the central widget. It implements a slot + \c handleMessage() that will be connected to the messageReceived() + signal of the QtSingleApplication class. + + \printuntil } + The MainWindow constructor creates a minimal user interface. + + \printto case Print: + The handleMessage() slot interprets the message passed in as a + filename that can be prepended with \e /print to indicate that + the file should just be printed rather than loaded. + + \printto #include + Loading the file will also activate the window. + + \printto mw + The \c main entry point function creates a QtSingleApplication + object, and creates a message to send to a running instance + of the application. If the message was sent successfully the + process exits immediately. + + \printuntil } + If the message could not be sent the application starts up. Note + that \c false is passed to the call to setActivationWindow() to + prevent automatic activation for every message received, e.g. when + the application should just print a file. Instead, the message + handling function determines whether activation is requested, and + signals that by emitting the needToShow() signal. This is then + simply connected directly to QtSingleApplication's + activateWindow() slot. +*/ diff --git a/3rd-parties/qtsingleapplication/examples/loader/main.cpp b/3rd-parties/qtsingleapplication/examples/loader/main.cpp new file mode 100644 index 0000000..5078490 --- /dev/null +++ b/3rd-parties/qtsingleapplication/examples/loader/main.cpp @@ -0,0 +1,115 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + +#include +#include +#include +#include +#include +#include +#include +#include + +class MainWindow : public QMainWindow +{ + Q_OBJECT +public: + MainWindow(); + +public slots: + void handleMessage(const QString& message); + +signals: + void needToShow(); + +private: + QMdiArea *workspace; +}; + +MainWindow::MainWindow() +{ + workspace = new QMdiArea(this); + + setCentralWidget(workspace); +} + +void MainWindow::handleMessage(const QString& message) +{ + enum Action { + Nothing, + Open, + Print + } action; + + action = Nothing; + QString filename = message; + if (message.toLower().startsWith("/print ")) { + filename = filename.mid(7); + action = Print; + } else if (!message.isEmpty()) { + action = Open; + } + if (action == Nothing) { + emit needToShow(); + return; + } + + QFile file(filename); + QString contents; + if (file.open(QIODevice::ReadOnly)) + contents = file.readAll(); + else + contents = "[[Error: Could not load file " + filename + "]]"; + + QTextEdit *view = new QTextEdit; + view->setPlainText(contents); + + switch(action) { + case Print: + { + QPrinter printer; + view->print(&printer); + delete view; + } + break; + + case Open: + { + workspace->addSubWindow(view); + view->setWindowTitle(message); + view->show(); + emit needToShow(); + } + break; + default: + break; + }; +} + +#include "main.moc" + +int main(int argc, char **argv) +{ + QtSingleApplication instance("File loader QtSingleApplication example", argc, argv); + QString message; + for (int a = 1; a < argc; ++a) { + message += argv[a]; + if (a < argc-1) + message += " "; + } + + if (instance.sendMessage(message)) + return 0; + + MainWindow mw; + mw.handleMessage(message); + mw.show(); + + QObject::connect(&instance, SIGNAL(messageReceived(const QString&)), + &mw, SLOT(handleMessage(const QString&))); + + instance.setActivationWindow(&mw, false); + QObject::connect(&mw, SIGNAL(needToShow()), &instance, SLOT(activateWindow())); + + return instance.exec(); +} diff --git a/3rd-parties/qtsingleapplication/examples/trivial/main.cpp b/3rd-parties/qtsingleapplication/examples/trivial/main.cpp new file mode 100644 index 0000000..d243cc5 --- /dev/null +++ b/3rd-parties/qtsingleapplication/examples/trivial/main.cpp @@ -0,0 +1,41 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + +#include +#include + +class TextEdit : public QTextEdit +{ + Q_OBJECT +public: + TextEdit(QWidget *parent = 0) + : QTextEdit(parent) + {} +public slots: + void append(const QString &str) + { + QTextEdit::append(str); + } +}; + +#include "main.moc" + + + +int main(int argc, char **argv) +{ + QtSingleApplication instance(argc, argv); + if (instance.sendMessage("Wake up!")) + return 0; + + TextEdit logview; + logview.setReadOnly(true); + logview.show(); + + instance.setActivationWindow(&logview); + + QObject::connect(&instance, SIGNAL(messageReceived(const QString&)), + &logview, SLOT(append(const QString&))); + + return instance.exec(); +} diff --git a/3rd-parties/qtsingleapplication/examples/trivial/trivial.pro b/3rd-parties/qtsingleapplication/examples/trivial/trivial.pro new file mode 100644 index 0000000..673497a --- /dev/null +++ b/3rd-parties/qtsingleapplication/examples/trivial/trivial.pro @@ -0,0 +1,5 @@ +TEMPLATE = app + +include(../../src/qtsingleapplication.pri) + +SOURCES += main.cpp diff --git a/3rd-parties/qtsingleapplication/examples/trivial/trivial.qdoc b/3rd-parties/qtsingleapplication/examples/trivial/trivial.qdoc new file mode 100644 index 0000000..4a8640e --- /dev/null +++ b/3rd-parties/qtsingleapplication/examples/trivial/trivial.qdoc @@ -0,0 +1,39 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + +/*! \page qtsingleapplication-example-trivial.html + \title A Trivial Example + + The application in this example has a log-view that displays + messages sent by further instances of the same application. + + The example demonstrates the use of the QtSingleApplication + class to detect and communicate with a running instance of + the application using the sendMessage() API. The messageReceived() + signal is used to display received messages in a QTextEdit log. + + \quotefromfile trivial/main.cpp + \printuntil instance + The example has only the \c main entry point function. + A QtSingleApplication object is created immediately. + + \printuntil return + If another instance of this application is already running, + sendMessage() will succeed, and this instance just exits + immediately. + + \printuntil show() + Otherwise the instance continues as normal and creates the + user interface. + + \printuntil return instance.exec(); + The \c logview object is also set as the application's activation + window. Every time a message is received, the window will be raised + and activated automatically. + + The messageReceived() signal is also connected to the QTextEdit's + append() slot. Every message received from further instances of + this application will be displayed in the log. + + Finally the event loop is entered. +*/ diff --git a/3rd-parties/qtsingleapplication/qtsingleapplication.pro b/3rd-parties/qtsingleapplication/qtsingleapplication.pro new file mode 100644 index 0000000..07257c5 --- /dev/null +++ b/3rd-parties/qtsingleapplication/qtsingleapplication.pro @@ -0,0 +1,5 @@ +TEMPLATE=subdirs +CONFIG += ordered +include(common.pri) +qtsingleapplication-uselib:SUBDIRS=buildlib +SUBDIRS+=examples diff --git a/3rd-parties/qtsingleapplication/src/CMakeLists.txt b/3rd-parties/qtsingleapplication/src/CMakeLists.txt new file mode 100644 index 0000000..b730eb9 --- /dev/null +++ b/3rd-parties/qtsingleapplication/src/CMakeLists.txt @@ -0,0 +1 @@ +target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) \ No newline at end of file diff --git a/3rd-parties/qtsingleapplication/src/QtLockedFile b/3rd-parties/qtsingleapplication/src/QtLockedFile new file mode 100644 index 0000000..16b48ba --- /dev/null +++ b/3rd-parties/qtsingleapplication/src/QtLockedFile @@ -0,0 +1 @@ +#include "qtlockedfile.h" diff --git a/3rd-parties/qtsingleapplication/src/QtSingleApplication b/3rd-parties/qtsingleapplication/src/QtSingleApplication new file mode 100644 index 0000000..d111bf7 --- /dev/null +++ b/3rd-parties/qtsingleapplication/src/QtSingleApplication @@ -0,0 +1 @@ +#include "qtsingleapplication.h" diff --git a/3rd-parties/qtsingleapplication/src/qtlocalpeer.cpp b/3rd-parties/qtsingleapplication/src/qtlocalpeer.cpp new file mode 100644 index 0000000..7e99171 --- /dev/null +++ b/3rd-parties/qtsingleapplication/src/qtlocalpeer.cpp @@ -0,0 +1,177 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + + +#include "qtlocalpeer.h" +#include +#include +#include +#include + +#if defined(Q_OS_WIN) +#include +#include +typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*); +static PProcessIdToSessionId pProcessIdToSessionId = 0; +#endif +#if defined(Q_OS_UNIX) +#include +#include +#include +#endif + +namespace QtLP_Private { +#include "qtlockedfile.cpp" +#if defined(Q_OS_WIN) +#include "qtlockedfile_win.cpp" +#else +#include "qtlockedfile_unix.cpp" +#endif +} + +const char* QtLocalPeer::ack = "ack"; + +QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId) + : QObject(parent), id(appId) +{ + QString prefix = id; + if (id.isEmpty()) { + id = QCoreApplication::applicationFilePath(); +#if defined(Q_OS_WIN) + id = id.toLower(); +#endif + prefix = id.section(QLatin1Char('/'), -1); + } + prefix.remove(QRegularExpression("[^a-zA-Z]")); + prefix.truncate(6); + + QByteArray idc = id.toUtf8(); + quint16 idNum = qChecksum(idc.constData(), idc.size()); + socketName = QLatin1String("qtsingleapp-") + prefix + + QLatin1Char('-') + QString::number(idNum, 16); + +#if defined(Q_OS_WIN) + if (!pProcessIdToSessionId) { + QLibrary lib("kernel32"); + pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId"); + } + if (pProcessIdToSessionId) { + DWORD sessionId = 0; + pProcessIdToSessionId(GetCurrentProcessId(), &sessionId); + socketName += QLatin1Char('-') + QString::number(sessionId, 16); + } +#else + socketName += QLatin1Char('-') + QString::number(::getuid(), 16); +#endif + + server = new QLocalServer(this); + QString lockName = QDir(QDir::tempPath()).absolutePath() + + QLatin1Char('/') + socketName + + QLatin1String("-lockfile"); + lockFile.setFileName(lockName); + lockFile.open(QIODevice::ReadWrite); +} + + + +bool QtLocalPeer::isClient() +{ + if (lockFile.isLocked()) + return false; + + if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false)) + return true; + + bool res = server->listen(socketName); +#if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0)) + // ### Workaround + if (!res && server->serverError() == QAbstractSocket::AddressInUseError) { + QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName); + res = server->listen(socketName); + } +#endif + if (!res) + qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString())); + QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection())); + return false; +} + + +bool QtLocalPeer::sendMessage(const QString &message, int timeout) +{ + if (!isClient()) + return false; + + QLocalSocket socket; + bool connOk = false; + for(int i = 0; i < 2; i++) { + // Try twice, in case the other instance is just starting up + socket.connectToServer(socketName); + connOk = socket.waitForConnected(timeout/2); + if (connOk || i) + break; + int ms = 250; +#if defined(Q_OS_WIN) + Sleep(DWORD(ms)); +#else + struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 }; + nanosleep(&ts, NULL); +#endif + } + if (!connOk) + return false; + + QByteArray uMsg(message.toUtf8()); + QDataStream ds(&socket); + ds.writeBytes(uMsg.constData(), uMsg.size()); + bool res = socket.waitForBytesWritten(timeout); + if (res) { + res &= socket.waitForReadyRead(timeout); // wait for ack + if (res) + res &= (socket.read(qstrlen(ack)) == ack); + } + return res; +} + + +void QtLocalPeer::receiveConnection() +{ + QLocalSocket* socket = server->nextPendingConnection(); + if (!socket) + return; + + while (true) { + if (socket->state() == QLocalSocket::UnconnectedState) { + qWarning("QtLocalPeer: Peer disconnected"); + delete socket; + return; + } + if (socket->bytesAvailable() >= qint64(sizeof(quint32))) + break; + socket->waitForReadyRead(); + } + + QDataStream ds(socket); + QByteArray uMsg; + quint32 remaining; + ds >> remaining; + uMsg.resize(remaining); + int got = 0; + char* uMsgBuf = uMsg.data(); + do { + got = ds.readRawData(uMsgBuf, remaining); + remaining -= got; + uMsgBuf += got; + } while (remaining && got >= 0 && socket->waitForReadyRead(2000)); + if (got < 0) { + qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData()); + delete socket; + return; + } + QString message(QString::fromUtf8(uMsg)); + socket->write(ack, qstrlen(ack)); + socket->waitForBytesWritten(1000); + socket->waitForDisconnected(1000); // make sure client reads ack + delete socket; + emit messageReceived(message); //### (might take a long time to return) +} diff --git a/3rd-parties/qtsingleapplication/src/qtlocalpeer.h b/3rd-parties/qtsingleapplication/src/qtlocalpeer.h new file mode 100644 index 0000000..5e6db56 --- /dev/null +++ b/3rd-parties/qtsingleapplication/src/qtlocalpeer.h @@ -0,0 +1,40 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + +#ifndef QTLOCALPEER_H +#define QTLOCALPEER_H + +#include +#include +#include + +#include "qtlockedfile.h" + +class QtLocalPeer : public QObject +{ + Q_OBJECT + +public: + QtLocalPeer(QObject *parent = 0, const QString &appId = QString()); + bool isClient(); + bool sendMessage(const QString &message, int timeout); + QString applicationId() const + { return id; } + +Q_SIGNALS: + void messageReceived(const QString &message); + +protected Q_SLOTS: + void receiveConnection(); + +protected: + QString id; + QString socketName; + QLocalServer* server; + QtLP_Private::QtLockedFile lockFile; + +private: + static const char* ack; +}; + +#endif // QTLOCALPEER_H diff --git a/3rd-parties/qtsingleapplication/src/qtlockedfile.cpp b/3rd-parties/qtsingleapplication/src/qtlockedfile.cpp new file mode 100644 index 0000000..78f20bc --- /dev/null +++ b/3rd-parties/qtsingleapplication/src/qtlockedfile.cpp @@ -0,0 +1,156 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + +#include "qtlockedfile.h" + +/*! + \class QtLockedFile + + \brief The QtLockedFile class extends QFile with advisory locking + functions. + + A file may be locked in read or write mode. Multiple instances of + \e QtLockedFile, created in multiple processes running on the same + machine, may have a file locked in read mode. Exactly one instance + may have it locked in write mode. A read and a write lock cannot + exist simultaneously on the same file. + + The file locks are advisory. This means that nothing prevents + another process from manipulating a locked file using QFile or + file system functions offered by the OS. Serialization is only + guaranteed if all processes that access the file use + QLockedFile. Also, while holding a lock on a file, a process + must not open the same file again (through any API), or locks + can be unexpectedly lost. + + The lock provided by an instance of \e QtLockedFile is released + whenever the program terminates. This is true even when the + program crashes and no destructors are called. +*/ + +/*! \enum QtLockedFile::LockMode + + This enum describes the available lock modes. + + \value ReadLock A read lock. + \value WriteLock A write lock. + \value NoLock Neither a read lock nor a write lock. +*/ + +/*! + Constructs an unlocked \e QtLockedFile object. This constructor + behaves in the same way as \e QFile::QFile(). + + \sa QFile::QFile() +*/ +QtLockedFile::QtLockedFile() + : QFile() +{ +#ifdef Q_OS_WIN + wmutex = 0; + rmutex = 0; +#endif + m_lock_mode = NoLock; +} + +/*! + Constructs an unlocked QtLockedFile object with file \a name. This + constructor behaves in the same way as \e QFile::QFile(const + QString&). + + \sa QFile::QFile() +*/ +QtLockedFile::QtLockedFile(const QString &name) + : QFile(name) +{ +#ifdef Q_OS_WIN + wmutex = 0; + rmutex = 0; +#endif + m_lock_mode = NoLock; +} + +/*! + Opens the file in OpenMode \a mode. + + This is identical to QFile::open(), with the one exception that the + Truncate mode flag is disallowed. Truncation would conflict with the + advisory file locking, since the file would be modified before the + write lock is obtained. If truncation is required, use resize(0) + after obtaining the write lock. + + Returns true if successful; otherwise false. + + \sa QFile::open(), QFile::resize() +*/ +bool QtLockedFile::open(OpenMode mode) +{ + if (mode & QIODevice::Truncate) { + qWarning("QtLockedFile::open(): Truncate mode not allowed."); + return false; + } + return QFile::open(mode); +} + +/*! + Returns \e true if this object has a in read or write lock; + otherwise returns \e false. + + \sa lockMode() +*/ +bool QtLockedFile::isLocked() const +{ + return m_lock_mode != NoLock; +} + +/*! + Returns the type of lock currently held by this object, or \e + QtLockedFile::NoLock. + + \sa isLocked() +*/ +QtLockedFile::LockMode QtLockedFile::lockMode() const +{ + return m_lock_mode; +} + +/*! + \fn bool QtLockedFile::lock(LockMode mode, bool block = true) + + Obtains a lock of type \a mode. The file must be opened before it + can be locked. + + If \a block is true, this function will block until the lock is + aquired. If \a block is false, this function returns \e false + immediately if the lock cannot be aquired. + + If this object already has a lock of type \a mode, this function + returns \e true immediately. If this object has a lock of a + different type than \a mode, the lock is first released and then a + new lock is obtained. + + This function returns \e true if, after it executes, the file is + locked by this object, and \e false otherwise. + + \sa unlock(), isLocked(), lockMode() +*/ + +/*! + \fn bool QtLockedFile::unlock() + + Releases a lock. + + If the object has no lock, this function returns immediately. + + This function returns \e true if, after it executes, the file is + not locked by this object, and \e false otherwise. + + \sa lock(), isLocked(), lockMode() +*/ + +/*! + \fn QtLockedFile::~QtLockedFile() + + Destroys the \e QtLockedFile object. If any locks were held, they + are released. +*/ diff --git a/3rd-parties/qtsingleapplication/src/qtlockedfile.h b/3rd-parties/qtsingleapplication/src/qtlockedfile.h new file mode 100644 index 0000000..c729bf2 --- /dev/null +++ b/3rd-parties/qtsingleapplication/src/qtlockedfile.h @@ -0,0 +1,60 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + +#ifndef QTLOCKEDFILE_H +#define QTLOCKEDFILE_H + +#include +#ifdef Q_OS_WIN +#include +#endif + +#if defined(Q_OS_WIN) +# if !defined(QT_QTLOCKEDFILE_EXPORT) && !defined(QT_QTLOCKEDFILE_IMPORT) +# define QT_QTLOCKEDFILE_EXPORT +# elif defined(QT_QTLOCKEDFILE_IMPORT) +# if defined(QT_QTLOCKEDFILE_EXPORT) +# undef QT_QTLOCKEDFILE_EXPORT +# endif +# define QT_QTLOCKEDFILE_EXPORT __declspec(dllimport) +# elif defined(QT_QTLOCKEDFILE_EXPORT) +# undef QT_QTLOCKEDFILE_EXPORT +# define QT_QTLOCKEDFILE_EXPORT __declspec(dllexport) +# endif +#else +# define QT_QTLOCKEDFILE_EXPORT +#endif + +namespace QtLP_Private { + +class QT_QTLOCKEDFILE_EXPORT QtLockedFile : public QFile +{ +public: + enum LockMode { NoLock = 0, ReadLock, WriteLock }; + + QtLockedFile(); + QtLockedFile(const QString &name); + ~QtLockedFile(); + + bool open(OpenMode mode); + + bool lock(LockMode mode, bool block = true); + bool unlock(); + bool isLocked() const; + LockMode lockMode() const; + +private: +#ifdef Q_OS_WIN + Qt::HANDLE wmutex; + Qt::HANDLE rmutex; + QVector rmutexes; + QString mutexname; + + Qt::HANDLE getMutexHandle(int idx, bool doCreate); + bool waitMutex(Qt::HANDLE mutex, bool doBlock); + +#endif + LockMode m_lock_mode; +}; +} +#endif diff --git a/3rd-parties/qtsingleapplication/src/qtlockedfile_unix.cpp b/3rd-parties/qtsingleapplication/src/qtlockedfile_unix.cpp new file mode 100644 index 0000000..8385d8b --- /dev/null +++ b/3rd-parties/qtsingleapplication/src/qtlockedfile_unix.cpp @@ -0,0 +1,78 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + +#include +#include +#include +#include + +#include "qtlockedfile.h" + +bool QtLockedFile::lock(LockMode mode, bool block) +{ + if (!isOpen()) { + qWarning("QtLockedFile::lock(): file is not opened"); + return false; + } + + if (mode == NoLock) + return unlock(); + + if (mode == m_lock_mode) + return true; + + if (m_lock_mode != NoLock) + unlock(); + + struct flock fl; + fl.l_whence = SEEK_SET; + fl.l_start = 0; + fl.l_len = 0; + fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK; + int cmd = block ? F_SETLKW : F_SETLK; + int ret = fcntl(handle(), cmd, &fl); + + if (ret == -1) { + if (errno != EINTR && errno != EAGAIN) + qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); + return false; + } + + + m_lock_mode = mode; + return true; +} + + +bool QtLockedFile::unlock() +{ + if (!isOpen()) { + qWarning("QtLockedFile::unlock(): file is not opened"); + return false; + } + + if (!isLocked()) + return true; + + struct flock fl; + fl.l_whence = SEEK_SET; + fl.l_start = 0; + fl.l_len = 0; + fl.l_type = F_UNLCK; + int ret = fcntl(handle(), F_SETLKW, &fl); + + if (ret == -1) { + qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); + return false; + } + + m_lock_mode = NoLock; + return true; +} + +QtLockedFile::~QtLockedFile() +{ + if (isOpen()) + unlock(); +} + diff --git a/3rd-parties/qtsingleapplication/src/qtlockedfile_win.cpp b/3rd-parties/qtsingleapplication/src/qtlockedfile_win.cpp new file mode 100644 index 0000000..28cf072 --- /dev/null +++ b/3rd-parties/qtsingleapplication/src/qtlockedfile_win.cpp @@ -0,0 +1,174 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + +#include "qtlockedfile.h" +#include +#include + +#define MUTEX_PREFIX "QtLockedFile mutex " +// Maximum number of concurrent read locks. Must not be greater than MAXIMUM_WAIT_OBJECTS +#define MAX_READERS MAXIMUM_WAIT_OBJECTS + +#if QT_VERSION >= 0x050000 +#define QT_WA(unicode, ansi) unicode +#endif + +Qt::HANDLE QtLockedFile::getMutexHandle(int idx, bool doCreate) +{ + if (mutexname.isEmpty()) { + QFileInfo fi(*this); + mutexname = QString::fromLatin1(MUTEX_PREFIX) + + fi.absoluteFilePath().toLower(); + } + QString mname(mutexname); + if (idx >= 0) + mname += QString::number(idx); + + Qt::HANDLE mutex; + if (doCreate) { + QT_WA( { mutex = CreateMutexW(NULL, FALSE, (TCHAR*)mname.utf16()); }, + { mutex = CreateMutexA(NULL, FALSE, mname.toLocal8Bit().constData()); } ); + if (!mutex) { + qErrnoWarning("QtLockedFile::lock(): CreateMutex failed"); + return 0; + } + } + else { + QT_WA( { mutex = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, (TCHAR*)mname.utf16()); }, + { mutex = OpenMutexA(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, mname.toLocal8Bit().constData()); } ); + if (!mutex) { + if (GetLastError() != ERROR_FILE_NOT_FOUND) + qErrnoWarning("QtLockedFile::lock(): OpenMutex failed"); + return 0; + } + } + return mutex; +} + +bool QtLockedFile::waitMutex(Qt::HANDLE mutex, bool doBlock) +{ + Q_ASSERT(mutex); + DWORD res = WaitForSingleObject(mutex, doBlock ? INFINITE : 0); + switch (res) { + case WAIT_OBJECT_0: + case WAIT_ABANDONED: + return true; + break; + case WAIT_TIMEOUT: + break; + default: + qErrnoWarning("QtLockedFile::lock(): WaitForSingleObject failed"); + } + return false; +} + + + +bool QtLockedFile::lock(LockMode mode, bool block) +{ + if (!isOpen()) { + qWarning("QtLockedFile::lock(): file is not opened"); + return false; + } + + if (mode == NoLock) + return unlock(); + + if (mode == m_lock_mode) + return true; + + if (m_lock_mode != NoLock) + unlock(); + + if (!wmutex && !(wmutex = getMutexHandle(-1, true))) + return false; + + if (!waitMutex(wmutex, block)) + return false; + + if (mode == ReadLock) { + int idx = 0; + for (; idx < MAX_READERS; idx++) { + rmutex = getMutexHandle(idx, false); + if (!rmutex || waitMutex(rmutex, false)) + break; + CloseHandle(rmutex); + } + bool ok = true; + if (idx >= MAX_READERS) { + qWarning("QtLockedFile::lock(): too many readers"); + rmutex = 0; + ok = false; + } + else if (!rmutex) { + rmutex = getMutexHandle(idx, true); + if (!rmutex || !waitMutex(rmutex, false)) + ok = false; + } + if (!ok && rmutex) { + CloseHandle(rmutex); + rmutex = 0; + } + ReleaseMutex(wmutex); + if (!ok) + return false; + } + else { + Q_ASSERT(rmutexes.isEmpty()); + for (int i = 0; i < MAX_READERS; i++) { + Qt::HANDLE mutex = getMutexHandle(i, false); + if (mutex) + rmutexes.append(mutex); + } + if (rmutexes.size()) { + DWORD res = WaitForMultipleObjects(rmutexes.size(), rmutexes.constData(), + TRUE, block ? INFINITE : 0); + if (res != WAIT_OBJECT_0 && res != WAIT_ABANDONED) { + if (res != WAIT_TIMEOUT) + qErrnoWarning("QtLockedFile::lock(): WaitForMultipleObjects failed"); + m_lock_mode = WriteLock; // trick unlock() to clean up - semiyucky + unlock(); + return false; + } + } + } + + m_lock_mode = mode; + return true; +} + +bool QtLockedFile::unlock() +{ + if (!isOpen()) { + qWarning("QtLockedFile::unlock(): file is not opened"); + return false; + } + + if (!isLocked()) + return true; + + if (m_lock_mode == ReadLock) { + ReleaseMutex(rmutex); + CloseHandle(rmutex); + rmutex = 0; + } + else { + foreach(Qt::HANDLE mutex, rmutexes) { + ReleaseMutex(mutex); + CloseHandle(mutex); + } + rmutexes.clear(); + ReleaseMutex(wmutex); + } + + m_lock_mode = QtLockedFile::NoLock; + return true; +} + +QtLockedFile::~QtLockedFile() +{ + if (isOpen()) + unlock(); + if (wmutex) + CloseHandle(wmutex); +} diff --git a/3rd-parties/qtsingleapplication/src/qtsingleapplication.cpp b/3rd-parties/qtsingleapplication/src/qtsingleapplication.cpp new file mode 100644 index 0000000..a6f4516 --- /dev/null +++ b/3rd-parties/qtsingleapplication/src/qtsingleapplication.cpp @@ -0,0 +1,310 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + + +#include "qtsingleapplication.h" +#include "qtlocalpeer.h" +#include + + +/*! + \class QtSingleApplication qtsingleapplication.h + \brief The QtSingleApplication class provides an API to detect and + communicate with running instances of an application. + + This class allows you to create applications where only one + instance should be running at a time. I.e., if the user tries to + launch another instance, the already running instance will be + activated instead. Another usecase is a client-server system, + where the first started instance will assume the role of server, + and the later instances will act as clients of that server. + + By default, the full path of the executable file is used to + determine whether two processes are instances of the same + application. You can also provide an explicit identifier string + that will be compared instead. + + The application should create the QtSingleApplication object early + in the startup phase, and call isRunning() to find out if another + instance of this application is already running. If isRunning() + returns false, it means that no other instance is running, and + this instance has assumed the role as the running instance. In + this case, the application should continue with the initialization + of the application user interface before entering the event loop + with exec(), as normal. + + The messageReceived() signal will be emitted when the running + application receives messages from another instance of the same + application. When a message is received it might be helpful to the + user to raise the application so that it becomes visible. To + facilitate this, QtSingleApplication provides the + setActivationWindow() function and the activateWindow() slot. + + If isRunning() returns true, another instance is already + running. It may be alerted to the fact that another instance has + started by using the sendMessage() function. Also data such as + startup parameters (e.g. the name of the file the user wanted this + new instance to open) can be passed to the running instance with + this function. Then, the application should terminate (or enter + client mode). + + If isRunning() returns true, but sendMessage() fails, that is an + indication that the running instance is frozen. + + Here's an example that shows how to convert an existing + application to use QtSingleApplication. It is very simple and does + not make use of all QtSingleApplication's functionality (see the + examples for that). + + \code + // Original + int main(int argc, char **argv) + { + QApplication app(argc, argv); + + MyMainWidget mmw; + mmw.show(); + return app.exec(); + } + + // Single instance + int main(int argc, char **argv) + { + QtSingleApplication app(argc, argv); + + if (app.isRunning()) + return !app.sendMessage(someDataString); + + MyMainWidget mmw; + app.setActivationWindow(&mmw); + mmw.show(); + return app.exec(); + } + \endcode + + Once this QtSingleApplication instance is destroyed (normally when + the process exits or crashes), when the user next attempts to run the + application this instance will not, of course, be encountered. The + next instance to call isRunning() or sendMessage() will assume the + role as the new running instance. + + For console (non-GUI) applications, QtSingleCoreApplication may be + used instead of this class, to avoid the dependency on the QtGui + library. + + \sa QtSingleCoreApplication +*/ + + +void QtSingleApplication::sysInit(const QString &appId) +{ + actWin = 0; + peer = new QtLocalPeer(this, appId); + connect(peer, SIGNAL(messageReceived(const QString&)), SIGNAL(messageReceived(const QString&))); +} + + +/*! + Creates a QtSingleApplication object. The application identifier + will be QCoreApplication::applicationFilePath(). \a argc, \a + argv, and \a GUIenabled are passed on to the QAppliation constructor. + + If you are creating a console application (i.e. setting \a + GUIenabled to false), you may consider using + QtSingleCoreApplication instead. +*/ + +QtSingleApplication::QtSingleApplication(int &argc, char **argv, bool GUIenabled) + : QApplication(argc, argv, GUIenabled) +{ + sysInit(); +} + + +/*! + Creates a QtSingleApplication object with the application + identifier \a appId. \a argc and \a argv are passed on to the + QAppliation constructor. +*/ + +QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char **argv) + : QApplication(argc, argv) +{ + sysInit(appId); +} + +#if QT_VERSION < 0x050000 + +/*! + Creates a QtSingleApplication object. The application identifier + will be QCoreApplication::applicationFilePath(). \a argc, \a + argv, and \a type are passed on to the QAppliation constructor. +*/ +QtSingleApplication::QtSingleApplication(int &argc, char **argv, Type type) + : QApplication(argc, argv, type) +{ + sysInit(); +} + + +# if defined(Q_WS_X11) +/*! + Special constructor for X11, ref. the documentation of + QApplication's corresponding constructor. The application identifier + will be QCoreApplication::applicationFilePath(). \a dpy, \a visual, + and \a cmap are passed on to the QApplication constructor. +*/ +QtSingleApplication::QtSingleApplication(Display* dpy, Qt::HANDLE visual, Qt::HANDLE cmap) + : QApplication(dpy, visual, cmap) +{ + sysInit(); +} + +/*! + Special constructor for X11, ref. the documentation of + QApplication's corresponding constructor. The application identifier + will be QCoreApplication::applicationFilePath(). \a dpy, \a argc, \a + argv, \a visual, and \a cmap are passed on to the QApplication + constructor. +*/ +QtSingleApplication::QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap) + : QApplication(dpy, argc, argv, visual, cmap) +{ + sysInit(); +} + +/*! + Special constructor for X11, ref. the documentation of + QApplication's corresponding constructor. The application identifier + will be \a appId. \a dpy, \a argc, \a + argv, \a visual, and \a cmap are passed on to the QApplication + constructor. +*/ +QtSingleApplication::QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap) + : QApplication(dpy, argc, argv, visual, cmap) +{ + sysInit(appId); +} +# endif // Q_WS_X11 +#endif // QT_VERSION < 0x050000 + + +/*! + Returns true if another instance of this application is running; + otherwise false. + + This function does not find instances of this application that are + being run by a different user (on Windows: that are running in + another session). + + \sa sendMessage() +*/ + +bool QtSingleApplication::isRunning() +{ + return peer->isClient(); +} + + +/*! + Tries to send the text \a message to the currently running + instance. The QtSingleApplication object in the running instance + will emit the messageReceived() signal when it receives the + message. + + This function returns true if the message has been sent to, and + processed by, the current instance. If there is no instance + currently running, or if the running instance fails to process the + message within \a timeout milliseconds, this function return false. + + \sa isRunning(), messageReceived() +*/ +bool QtSingleApplication::sendMessage(const QString &message, int timeout) +{ + return peer->sendMessage(message, timeout); +} + + +/*! + Returns the application identifier. Two processes with the same + identifier will be regarded as instances of the same application. +*/ +QString QtSingleApplication::id() const +{ + return peer->applicationId(); +} + + +/*! + Sets the activation window of this application to \a aw. The + activation window is the widget that will be activated by + activateWindow(). This is typically the application's main window. + + If \a activateOnMessage is true (the default), the window will be + activated automatically every time a message is received, just prior + to the messageReceived() signal being emitted. + + \sa activateWindow(), messageReceived() +*/ + +void QtSingleApplication::setActivationWindow(QWidget* aw, bool activateOnMessage) +{ + actWin = aw; + if (activateOnMessage) + connect(peer, SIGNAL(messageReceived(const QString&)), this, SLOT(activateWindow())); + else + disconnect(peer, SIGNAL(messageReceived(const QString&)), this, SLOT(activateWindow())); +} + + +/*! + Returns the applications activation window if one has been set by + calling setActivationWindow(), otherwise returns 0. + + \sa setActivationWindow() +*/ +QWidget* QtSingleApplication::activationWindow() const +{ + return actWin; +} + + +/*! + De-minimizes, raises, and activates this application's activation window. + This function does nothing if no activation window has been set. + + This is a convenience function to show the user that this + application instance has been activated when he has tried to start + another instance. + + This function should typically be called in response to the + messageReceived() signal. By default, that will happen + automatically, if an activation window has been set. + + \sa setActivationWindow(), messageReceived(), initialize() +*/ +void QtSingleApplication::activateWindow() +{ + if (actWin) { + actWin->setWindowState(actWin->windowState() & ~Qt::WindowMinimized); + actWin->raise(); + actWin->activateWindow(); + } +} + + +/*! + \fn void QtSingleApplication::messageReceived(const QString& message) + + This signal is emitted when the current instance receives a \a + message from another instance of this application. + + \sa sendMessage(), setActivationWindow(), activateWindow() +*/ + + +/*! + \fn void QtSingleApplication::initialize(bool dummy = true) + + \obsolete +*/ diff --git a/3rd-parties/qtsingleapplication/src/qtsingleapplication.h b/3rd-parties/qtsingleapplication/src/qtsingleapplication.h new file mode 100644 index 0000000..f8f6e88 --- /dev/null +++ b/3rd-parties/qtsingleapplication/src/qtsingleapplication.h @@ -0,0 +1,68 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + +#ifndef QTSINGLEAPPLICATION_H +#define QTSINGLEAPPLICATION_H + +#include + +class QtLocalPeer; + +#if defined(Q_OS_WIN) +# if !defined(QT_QTSINGLEAPPLICATION_EXPORT) && !defined(QT_QTSINGLEAPPLICATION_IMPORT) +# define QT_QTSINGLEAPPLICATION_EXPORT +# elif defined(QT_QTSINGLEAPPLICATION_IMPORT) +# if defined(QT_QTSINGLEAPPLICATION_EXPORT) +# undef QT_QTSINGLEAPPLICATION_EXPORT +# endif +# define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllimport) +# elif defined(QT_QTSINGLEAPPLICATION_EXPORT) +# undef QT_QTSINGLEAPPLICATION_EXPORT +# define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllexport) +# endif +#else +# define QT_QTSINGLEAPPLICATION_EXPORT +#endif + +class QT_QTSINGLEAPPLICATION_EXPORT QtSingleApplication : public QApplication +{ + Q_OBJECT + +public: + QtSingleApplication(int &argc, char **argv, bool GUIenabled = true); + QtSingleApplication(const QString &id, int &argc, char **argv); +#if QT_VERSION < 0x050000 + QtSingleApplication(int &argc, char **argv, Type type); +# if defined(Q_WS_X11) + QtSingleApplication(Display* dpy, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0); + QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap= 0); + QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0); +# endif // Q_WS_X11 +#endif // QT_VERSION < 0x050000 + + bool isRunning(); + QString id() const; + + void setActivationWindow(QWidget* aw, bool activateOnMessage = true); + QWidget* activationWindow() const; + + // Obsolete: + void initialize(bool dummy = true) + { isRunning(); Q_UNUSED(dummy) } + +public Q_SLOTS: + bool sendMessage(const QString &message, int timeout = 5000); + void activateWindow(); + + +Q_SIGNALS: + void messageReceived(const QString &message); + + +private: + void sysInit(const QString &appId = QString()); + QtLocalPeer *peer; + QWidget *actWin; +}; + +#endif // QTSINGLEAPPLICATION_H diff --git a/3rd-parties/qtsingleapplication/src/qtsingleapplication.pri b/3rd-parties/qtsingleapplication/src/qtsingleapplication.pri new file mode 100644 index 0000000..6f2bced --- /dev/null +++ b/3rd-parties/qtsingleapplication/src/qtsingleapplication.pri @@ -0,0 +1,17 @@ +include(../common.pri) +INCLUDEPATH += $$PWD +DEPENDPATH += $$PWD +QT *= network +greaterThan(QT_MAJOR_VERSION, 4): QT *= widgets + +qtsingleapplication-uselib:!qtsingleapplication-buildlib { + LIBS += -L$$QTSINGLEAPPLICATION_LIBDIR -l$$QTSINGLEAPPLICATION_LIBNAME +} else { + SOURCES += $$PWD/qtsingleapplication.cpp $$PWD/qtlocalpeer.cpp + HEADERS += $$PWD/qtsingleapplication.h $$PWD/qtlocalpeer.h +} + +win32 { + contains(TEMPLATE, lib):contains(CONFIG, shared):DEFINES += QT_QTSINGLEAPPLICATION_EXPORT + else:qtsingleapplication-uselib:DEFINES += QT_QTSINGLEAPPLICATION_IMPORT +} diff --git a/3rd-parties/qtsingleapplication/src/qtsinglecoreapplication.cpp b/3rd-parties/qtsingleapplication/src/qtsinglecoreapplication.cpp new file mode 100644 index 0000000..a3e2b3a --- /dev/null +++ b/3rd-parties/qtsingleapplication/src/qtsinglecoreapplication.cpp @@ -0,0 +1,112 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + + +#include "qtsinglecoreapplication.h" +#include "qtlocalpeer.h" + +/*! + \class QtSingleCoreApplication qtsinglecoreapplication.h + \brief A variant of the QtSingleApplication class for non-GUI applications. + + This class is a variant of QtSingleApplication suited for use in + console (non-GUI) applications. It is an extension of + QCoreApplication (instead of QApplication). It does not require + the QtGui library. + + The API and usage is identical to QtSingleApplication, except that + functions relating to the "activation window" are not present, for + obvious reasons. Please refer to the QtSingleApplication + documentation for explanation of the usage. + + A QtSingleCoreApplication instance can communicate to a + QtSingleApplication instance if they share the same application + id. Hence, this class can be used to create a light-weight + command-line tool that sends commands to a GUI application. + + \sa QtSingleApplication +*/ + +/*! + Creates a QtSingleCoreApplication object. The application identifier + will be QCoreApplication::applicationFilePath(). \a argc and \a + argv are passed on to the QCoreAppliation constructor. +*/ + +QtSingleCoreApplication::QtSingleCoreApplication(int &argc, char **argv) + : QCoreApplication(argc, argv) +{ + peer = new QtLocalPeer(this); + connect(peer, SIGNAL(messageReceived(const QString&)), SIGNAL(messageReceived(const QString&))); +} + + +/*! + Creates a QtSingleCoreApplication object with the application + identifier \a appId. \a argc and \a argv are passed on to the + QCoreAppliation constructor. +*/ +QtSingleCoreApplication::QtSingleCoreApplication(const QString &appId, int &argc, char **argv) + : QCoreApplication(argc, argv) +{ + peer = new QtLocalPeer(this, appId); + connect(peer, SIGNAL(messageReceived(const QString&)), SIGNAL(messageReceived(const QString&))); +} + + +/*! + Returns true if another instance of this application is running; + otherwise false. + + This function does not find instances of this application that are + being run by a different user (on Windows: that are running in + another session). + + \sa sendMessage() +*/ + +bool QtSingleCoreApplication::isRunning() +{ + return peer->isClient(); +} + + +/*! + Tries to send the text \a message to the currently running + instance. The QtSingleCoreApplication object in the running instance + will emit the messageReceived() signal when it receives the + message. + + This function returns true if the message has been sent to, and + processed by, the current instance. If there is no instance + currently running, or if the running instance fails to process the + message within \a timeout milliseconds, this function return false. + + \sa isRunning(), messageReceived() +*/ + +bool QtSingleCoreApplication::sendMessage(const QString &message, int timeout) +{ + return peer->sendMessage(message, timeout); +} + + +/*! + Returns the application identifier. Two processes with the same + identifier will be regarded as instances of the same application. +*/ + +QString QtSingleCoreApplication::id() const +{ + return peer->applicationId(); +} + + +/*! + \fn void QtSingleCoreApplication::messageReceived(const QString& message) + + This signal is emitted when the current instance receives a \a + message from another instance of this application. + + \sa sendMessage() +*/ diff --git a/3rd-parties/qtsingleapplication/src/qtsinglecoreapplication.h b/3rd-parties/qtsingleapplication/src/qtsinglecoreapplication.h new file mode 100644 index 0000000..1272589 --- /dev/null +++ b/3rd-parties/qtsingleapplication/src/qtsinglecoreapplication.h @@ -0,0 +1,34 @@ +// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +// SPDX-License-Identifier: BSD-3-Clause + +#ifndef QTSINGLECOREAPPLICATION_H +#define QTSINGLECOREAPPLICATION_H + +#include + +class QtLocalPeer; + +class QtSingleCoreApplication : public QCoreApplication +{ + Q_OBJECT + +public: + QtSingleCoreApplication(int &argc, char **argv); + QtSingleCoreApplication(const QString &id, int &argc, char **argv); + + bool isRunning(); + QString id() const; + +public Q_SLOTS: + bool sendMessage(const QString &message, int timeout = 5000); + + +Q_SIGNALS: + void messageReceived(const QString &message); + + +private: + QtLocalPeer* peer; +}; + +#endif // QTSINGLECOREAPPLICATION_H diff --git a/3rd-parties/qtsingleapplication/src/qtsinglecoreapplication.pri b/3rd-parties/qtsingleapplication/src/qtsinglecoreapplication.pri new file mode 100644 index 0000000..d2d6cc3 --- /dev/null +++ b/3rd-parties/qtsingleapplication/src/qtsinglecoreapplication.pri @@ -0,0 +1,10 @@ +INCLUDEPATH += $$PWD +DEPENDPATH += $$PWD +HEADERS += $$PWD/qtsinglecoreapplication.h $$PWD/qtlocalpeer.h +SOURCES += $$PWD/qtsinglecoreapplication.cpp $$PWD/qtlocalpeer.cpp + +QT *= network + +win32:contains(TEMPLATE, lib):contains(CONFIG, shared) { + DEFINES += QT_QTSINGLECOREAPPLICATION_EXPORT=__declspec(dllexport) +} diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..3ae0c56 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,23 @@ +cmake_minimum_required(VERSION 3.14) + +project(ukui-notification LANGUAGES CXX) +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +set(CMAKE_AUTOUIC ON) +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTORCC ON) + +set(CMAKE_CXX_STANDARD 11) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +include(GNUInstallDirs) +find_package(QT NAMES Qt6 Qt5 COMPONENTS Core LinguistTools DBus Network Gui Qml REQUIRED) +find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core LinguistTools DBus Network Gui Qml REQUIRED) +set(REQUIRED_QT_VERSION 5.12.8) + +add_subdirectory(notification-server) +add_subdirectory(libukui-notification) +add_subdirectory(notification-ukcc-plugin) +if(BUILD_TEST) + add_subdirectory(test) +endif() + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..818433e --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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, either version 3 of the License, or + (at your option) any later version. + + 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 . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.en.md b/README.en.md new file mode 100644 index 0000000..73dba88 --- /dev/null +++ b/README.en.md @@ -0,0 +1,4 @@ +# ukui-notification + +#### Description +ukui-notification diff --git a/README.md b/README.md new file mode 100644 index 0000000..5409b81 --- /dev/null +++ b/README.md @@ -0,0 +1,58 @@ +# ukui-notification + +# 介绍 +ukui-notificaton包含UKUI桌面环境的通知服务(ukui-notification-server)和通知开发接口(libukui-notifiaction)。 +## 通知服务 +ukui-notifiaction-server提供了遵循freedesktop[通知协议](https://specifications.freedesktop.org/notification-spec/notification-spec-latest.html)的通知服务接口。 +目前支持的Capabilities: + +actions; + +body; + +body-hyperlinks; + +persistence; + +sound. +### 扩展hints +目前ukui-notification-server的通知接口支持的扩展hints: + +1.x-ukui-display 用于标识通知弹窗应该被显示在哪个DISPLAY上。 + +### 扩展接口 +除协议规定的接口外,通知服务提供的额外接口: + +1.org.ukui.NotificationServer.UpdateUnreadMessagesNumber (String desktop_entry, UInt32 number) ↦ () + + 用于发送应用当前未读消息数量 + +## 通知开发接口 +#### 使用cmake: +```cmake +find_package(ukui-notification) +target_link_libraries(yourapp ukui-notification) +``` +#### 使用qmake: +```qmake +CONFIG += link_pkgconfig +PKGCONFIG += ukui-notification +``` +#### 关键接口: +notification-client.h 通知中心客户端注册、消息同步与action执行等功能。 + +popup-notification.h 单条通知的所有信息 + +notification-global-settings.h 全局通知设置 + +application-settings.h 应用通知行为设置 + +single-application-settings.h 单个应用的通知设置 +#### 代码编译: +mkdir build + +cd build + +cmake .. + +make \ No newline at end of file diff --git a/dbus/org.freedesktop.Notifications.xml b/dbus/org.freedesktop.Notifications.xml new file mode 100644 index 0000000..55fe73c --- /dev/null +++ b/dbus/org.freedesktop.Notifications.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dbus/org.ukui.NotificationClient.xml b/dbus/org.ukui.NotificationClient.xml new file mode 100644 index 0000000..caecb8c --- /dev/null +++ b/dbus/org.ukui.NotificationClient.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dbus/org.ukui.NotificationServer.xml b/dbus/org.ukui.NotificationServer.xml new file mode 100644 index 0000000..ff3dbeb --- /dev/null +++ b/dbus/org.ukui.NotificationServer.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/libukui-notification/CMakeLists.txt b/libukui-notification/CMakeLists.txt new file mode 100644 index 0000000..2ac6999 --- /dev/null +++ b/libukui-notification/CMakeLists.txt @@ -0,0 +1,109 @@ +set(VERSION_MAJOR 1) +set(VERSION_MINOR 0) +set(VERSION_MICRO 0) +set(UKUI_NOTIFICATION_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_MICRO}) + +find_package(KF5WindowSystem) +find_package(PkgConfig REQUIRED) +set(UKUI_NOTIFICATION_EXTERNAL_LIBS "") +set(UKUI_NOTIFICATION_PC_PKGS ukui-search) + +foreach(PC_LIB IN ITEMS ${UKUI_NOTIFICATION_PC_PKGS}) + pkg_check_modules(${PC_LIB} REQUIRED ${PC_LIB}) + if(${${PC_LIB}_FOUND}) + include_directories(${${PC_LIB}_INCLUDE_DIRS}) + link_directories(${${PC_LIB}_LIBRARY_DIRS}) + list(APPEND UKUI_NOTIFICATION_EXTERNAL_LIBS ${${PC_LIB}_LIBRARIES}) + endif() +endforeach() +include_directories(notification-settings) +set(ukui-notification_LIB_SRCS + notification-client.cpp + notification-client.h + popup-notification.h + popup-notification.cpp + ukui-notification_global.h + notification-client-private.h + utils.h + utils.cpp + notification-close-reason.h + notification-settings/settings-properties.h + notification-settings/settings-properties-info.h + notification-settings/settings-properties-info.cpp + notification-settings/settings-manager-private.h + notification-settings/settings-manager.h + notification-settings/settings-manager.cpp + notification-settings/notification-global-settings.cpp + notification-settings/notification-global-settings.h + notification-settings/single-application-settings.cpp + notification-settings/single-application-settings.h + notification-settings/applications-settings.cpp + notification-settings/applications-settings.h) +set(HEADERS + notification-client.h + popup-notification.h + notification-close-reason.h + notification-settings/settings-properties.h + notification-settings/settings-properties-info.h + notification-settings/notification-global-settings.h + notification-settings/single-application-settings.h + notification-settings/applications-settings.h + ukui-notification_global.h + utils.h) +if(COMMAND qt_add_dbus_interface) + qt_add_dbus_interface(ukui-notification_LIB_SRCS ../dbus/org.freedesktop.Notifications.xml notifications_interface) + qt_add_dbus_adaptor(ukui-notification_LIB_SRCS ../dbus/org.ukui.NotificationClient.xml notification-client-private.h UkuiNotification::NotificationClientPrivate) +else() + qt5_add_dbus_interface(ukui-notification_LIB_SRCS ../dbus/org.freedesktop.Notifications.xml notifications_interface) + qt5_add_dbus_adaptor(ukui-notification_LIB_SRCS ../dbus/org.ukui.NotificationClient.xml notification-client-private.h UkuiNotification::NotificationClientPrivate) +endif() +add_library(ukui-notification SHARED ${ukui-notification_LIB_SRCS}) +target_link_libraries(ukui-notification + PRIVATE + Qt${QT_VERSION_MAJOR}::Core + Qt${QT_VERSION_MAJOR}::DBus + Qt${QT_VERSION_MAJOR}::Gui + Qt${QT_VERSION_MAJOR}::Qml + KF5::WindowSystem + ${UKUI_NOTIFICATION_EXTERNAL_LIBS} + ) + +include(CMakePackageConfigHelpers) +set(CMAKE_CONFIG_INSTALL_DIR "/usr/share/cmake/ukui-notification") +set(HEADERS_INSTALL_DIR /usr/include/ukui-notification) +set(PC_INSTALL_DIR "/usr/lib/pkgconfig") + +target_include_directories(ukui-notification PUBLIC $) +configure_package_config_file( + "${CMAKE_CURRENT_SOURCE_DIR}/ukui-notification-config.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/ukui-notification-config.cmake" + INSTALL_DESTINATION ${CMAKE_CONFIG_INSTALL_DIR}) +write_basic_package_version_file( + ${CMAKE_CURRENT_BINARY_DIR}/ukui-notification-config-version.cmake + VERSION ${UKUI_NOTIFICATION_VERSION} + COMPATIBILITY SameMajorVersion +) + +configure_package_config_file( + "${CMAKE_CURRENT_SOURCE_DIR}/ukui-notification.pc.in" + "${CMAKE_CURRENT_BINARY_DIR}/ukui-notification.pc" + INSTALL_DESTINATION ${PC_INSTALL_DIR}) +set_target_properties(ukui-notification PROPERTIES + VERSION ${UKUI_NOTIFICATION_VERSION} + SOVERSION ${VERSION_MAJOR} + OUTPUT_NAME ukui-notification + ) +install(TARGETS ukui-notification + EXPORT ukui-notification + PUBLIC_HEADER DESTINATION ${HEADERS_INSTALL_DIR} + LIBRARY DESTINATION /usr/lib/${CMAKE_LIBRARY_ARCHITECTURE} + ) +install(EXPORT ukui-notification + FILE ukui-notification-targets.cmake + DESTINATION ${CMAKE_CONFIG_INSTALL_DIR}) + +install(FILES ${HEADERS} DESTINATION ${HEADERS_INSTALL_DIR}) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/ukui-notification.pc DESTINATION ${PC_INSTALL_DIR}) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/ukui-notification-config.cmake + ${CMAKE_CURRENT_BINARY_DIR}/ukui-notification-config-version.cmake + DESTINATION ${CMAKE_CONFIG_INSTALL_DIR}) diff --git a/libukui-notification/notification-client-private.h b/libukui-notification/notification-client-private.h new file mode 100644 index 0000000..5e4e668 --- /dev/null +++ b/libukui-notification/notification-client-private.h @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef UKUI_NOTIFICATION_NOTIFICATION_CLIENT_PRIVATE_H +#define UKUI_NOTIFICATION_NOTIFICATION_CLIENT_PRIVATE_H +#include +#include +#include +#include "notifications_interface.h" +#include "notification-client.h" +namespace UkuiNotification { +class NotificationClientPrivate : public QObject +{ + Q_OBJECT +public: + explicit NotificationClientPrivate(NotificationClient *q); + ~NotificationClientPrivate() override; + /** + * 初始化客户端dbus服务并注册成为客户端 + * @return + */ + bool init(); + /** + * 注销 + */ + void unregisterClient(); + static QString clientServicePath(); + static QString clientServiceInterface(); + + void Notify(const QString &app_name, + uint replaces_id, + const QString &app_icon, + const QString &summary, + const QString &body, + const QStringList &actions, + const QVariantMap &hints, + int timeout); + bool closeNotification(uint id, NotificationCloseReason::CloseReason reason); + bool invokeAction(uint id, const QString &action_key); + +private Q_SLOTS: + void notificationClosed(uint id, uint reason); + void serviceChange(const QString &service, const QString &oldOwner, const QString &newOwner); + /** + * 用于注册客户端,或在服务发生变化(重启)后重新注册客户端 + * @return true 成功 false 失败 + */ + bool registerClient(); + +private: + OrgFreedesktopNotificationsInterface* m_notificationsInterface = nullptr; + QDBusInterface *m_serverInterface = nullptr; + QDBusServiceWatcher *m_watcher = nullptr; + bool m_registered = false; + NotificationClient *q; +}; +} +#endif //UKUI_NOTIFICATION_NOTIFICATION_CLIENT_PRIVATE_H diff --git a/libukui-notification/notification-client.cpp b/libukui-notification/notification-client.cpp new file mode 100644 index 0000000..070b8ce --- /dev/null +++ b/libukui-notification/notification-client.cpp @@ -0,0 +1,221 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#include "notification-client.h" +#include "notification-client-private.h" +#include +#include +#include "notificationclientadaptor.h" + +using namespace UkuiNotification; + +NotificationClientPrivate::NotificationClientPrivate(NotificationClient *q) : QObject(q), q(q) +{ +} + +NotificationClientPrivate::~NotificationClientPrivate() +{ + if(m_notificationsInterface) { + m_notificationsInterface->call(QDBus::NoBlock, QStringLiteral("UnRegisterClient")); + delete m_notificationsInterface; + m_notificationsInterface = nullptr; + } +} + +bool NotificationClientPrivate::init() +{ + if(m_registered) { + return false; + } + m_registered = true; + new NotificationClientAdaptor(this); + QDBusConnection conn = QDBusConnection::sessionBus(); + + if(!conn.registerObject(clientServicePath(), clientServiceInterface(), this)) { + qWarning() << "Failed to register NotificationClient DBus object!" << conn.lastError(); + return false; + } + m_watcher = new QDBusServiceWatcher(QStringLiteral("org.freedesktop.Notifications"), + conn, + QDBusServiceWatcher::WatchForOwnerChange, + this); + connect(m_watcher, &QDBusServiceWatcher::serviceOwnerChanged, this, &NotificationClientPrivate::serviceChange); + return registerClient(); +} + +bool NotificationClientPrivate::registerClient() +{ + QDBusConnection conn = QDBusConnection::sessionBus(); + if(!m_notificationsInterface) { + m_notificationsInterface = new OrgFreedesktopNotificationsInterface(QStringLiteral("org.freedesktop.Notifications"), + QStringLiteral("/org/freedesktop/Notifications"), + conn); + + connect(m_notificationsInterface, &OrgFreedesktopNotificationsInterface::NotificationClosed, + this, &NotificationClientPrivate::notificationClosed); + } + + if(!m_serverInterface) { + m_serverInterface = new QDBusInterface(QStringLiteral("org.freedesktop.Notifications"), + QStringLiteral("/org/freedesktop/Notifications"), + QStringLiteral("org.ukui.NotificationServer"), + conn, + this); + if(!m_serverInterface->isValid()) { + qWarning() << "Failed to create notification server interface! " << conn.lastError(); + return false; + } + } + QDBusMessage reply = m_serverInterface->call(QStringLiteral("RegisterClient")); + if (reply.type() == QDBusMessage::ErrorMessage || reply.type() == QDBusMessage::InvalidMessage) { + qWarning() << "Failed to call RegisterClient!" << conn.lastError() << reply.type(); + return false; + } + return true; +} + +void NotificationClientPrivate::unregisterClient() +{ + if(m_notificationsInterface) { + disconnect(m_notificationsInterface, &OrgFreedesktopNotificationsInterface::NotificationClosed, + this, &NotificationClientPrivate::notificationClosed); + delete m_notificationsInterface; + m_notificationsInterface = nullptr; + } + QDBusConnection conn = QDBusConnection::sessionBus(); + if(m_serverInterface) { + QDBusMessage reply = m_serverInterface->call(QStringLiteral("UnRegisterClient")); + if (reply.type() == QDBusMessage::ErrorMessage || reply.type() == QDBusMessage::InvalidMessage) { + qWarning() << "Failed to call UnRegisterClient!" << conn.lastError() << reply.type(); + return; + } + } + conn.unregisterObject(clientServicePath(), QDBusConnection::UnregisterTree); + + m_registered = false; +} + +QString NotificationClientPrivate::clientServicePath() +{ + return QStringLiteral("/NotificationClient"); +} + +QString NotificationClientPrivate::clientServiceInterface() +{ + return QStringLiteral("org.ukui.NotificationClient"); +} + +void NotificationClientPrivate::Notify(const QString &app_name, uint replaces_id, const QString &app_icon, + const QString &summary, const QString &body, const QStringList &actions, + const QVariantMap &hints, int timeout) +{ + PopupNotification notification(replaces_id); + notification.setSummary(summary); + notification.setBody(body); + notification.setApplicationName(app_name); + notification.setApplicationIconName(app_icon); + notification.setActions(actions); + notification.setTimeout(timeout); + notification.setHints(hints); + Q_EMIT q->newNotification(notification); +} + +void NotificationClientPrivate::notificationClosed(uint id, uint reason) +{ + auto closeReason = NotificationCloseReason::CloseReason::Undefined; + switch (reason) { + case 1: + closeReason = NotificationCloseReason::CloseReason::Expired; + break; + case 2: + closeReason = NotificationCloseReason::CloseReason::DismissedByUser; + break; + case 3: + closeReason = NotificationCloseReason::CloseReason::Revoked; + break; + } + Q_EMIT q->notificationClosed(id, closeReason); +} + +bool NotificationClientPrivate::closeNotification(uint id, NotificationCloseReason::CloseReason reason) +{ + if(!m_serverInterface) { + return false; + } + QDBusMessage reply = m_serverInterface->callWithArgumentList(QDBus::NoBlock, QStringLiteral("CloseNotification"), {id, reason}); + if (reply.type() == QDBusMessage::ErrorMessage) { + qWarning() << "Failed to call CloseNotification!" << QDBusConnection::sessionBus().lastError(); + return false; + } + return true; +} + +void NotificationClientPrivate::serviceChange(const QString &service, const QString &oldOwner, const QString &newOwner) +{ + qDebug() << "Notification Service" << service << "status change, old owner:" << oldOwner << "new:" << newOwner; + if(oldOwner.isEmpty() && m_registered) { + registerClient(); + } +} + +bool NotificationClientPrivate::invokeAction(uint id, const QString &action_key) +{ + if(!m_serverInterface) { + return false; + } + qDebug() << "invokeAction" << id << action_key; + QDBusMessage reply = m_serverInterface->callWithArgumentList(QDBus::NoBlock, + QStringLiteral("InvokeAction"), + {id, action_key}); + if (reply.type() == QDBusMessage::ErrorMessage) { + qWarning() << "Failed to call InvokedAction!" << QDBusConnection::sessionBus().lastError(); + return false; + } + return true; +} + +NotificationClient::NotificationClient(QObject *parent) : QObject(parent), d(new NotificationClientPrivate(this)) +{ + qRegisterMetaType("PopupNotification"); + qRegisterMetaType("const UkuiNotification::PopupNotification&"); + qRegisterMetaType("ActionList"); + qmlRegisterUncreatableType("org.ukui.notification.client", 1, 0, "NotificationCloseReason", ""); +} + +NotificationClient::~NotificationClient() = default; + +bool NotificationClient::registerClient() +{ + return d->init(); +} + +bool NotificationClient::closeNotification(uint id, NotificationCloseReason::CloseReason reason) +{ + return d->closeNotification(id, reason); +} + +bool NotificationClient::invokeAction(uint id, const QString &action_key) +{ + return d->invokeAction(id, action_key); +} + +void NotificationClient::unregisterClient() +{ + d->unregisterClient(); +} diff --git a/libukui-notification/notification-client.h b/libukui-notification/notification-client.h new file mode 100644 index 0000000..f9f5f92 --- /dev/null +++ b/libukui-notification/notification-client.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef UKUI_NOTIFICATION_NOTIFICATION_CLIENT_H +#define UKUI_NOTIFICATION_NOTIFICATION_CLIENT_H +#include "ukui-notification_global.h" +#include +#include "popup-notification.h" +#include "notification-close-reason.h" +namespace UkuiNotification { +class NotificationClientPrivate; +class UKUINOTIFICATION_EXPORT NotificationClient : public QObject +{ + Q_OBJECT +public: + explicit NotificationClient(QObject *parent = nullptr); + ~NotificationClient(); + /** + * 注册成为弹窗通知客户端 + * @return ture-成功 false 失败 + */ + bool registerClient(); + void unregisterClient(); + bool closeNotification(uint id, NotificationCloseReason::CloseReason reason); + bool invokeAction(uint id, const QString &action_key); +Q_SIGNALS: + void newNotification(const UkuiNotification::PopupNotification ¬ification); + void notificationClosed(uint id, UkuiNotification::NotificationCloseReason::CloseReason closeReason); +private: + NotificationClientPrivate *d = nullptr; +}; + +} // UkuiNotification + +#endif //UKUI_NOTIFICATION_NOTIFICATION_CLIENT_H diff --git a/libukui-notification/notification-close-reason.h b/libukui-notification/notification-close-reason.h new file mode 100644 index 0000000..189731b --- /dev/null +++ b/libukui-notification/notification-close-reason.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef UKUI_NOTIFICATION_NOTIFICATIONCLOSEREASON_H +#define UKUI_NOTIFICATION_NOTIFICATIONCLOSEREASON_H + + +#include +#include "ukui-notification_global.h" + +namespace UkuiNotification { +class UKUINOTIFICATION_EXPORT NotificationCloseReason +{ + Q_GADGET +public: + /** + * The reason a notification was closed + */ + enum CloseReason { + Expired = 1, // The notification expired(timed out). + DismissedByUser = 2, // The notification was dismissed by the user. + Revoked = 3, //< The notification was closed by sender by a call to CloseNotification. + Undefined = 4, //Undefined/reserved reasons. + }; + Q_ENUM(CloseReason) +}; +} +#endif //UKUI_NOTIFICATION_NOTIFICATIONCLOSEREASON_H \ No newline at end of file diff --git a/libukui-notification/notification-settings/applications-settings.cpp b/libukui-notification/notification-settings/applications-settings.cpp new file mode 100644 index 0000000..f807c28 --- /dev/null +++ b/libukui-notification/notification-settings/applications-settings.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#include "applications-settings.h" +#include +#include +#include +#include "settings-manager.h" +#include + +using namespace UkuiNotification; +static std::once_flag flag; +static ApplicationsSettings *s_self; +namespace UkuiNotification{ +class ApplicationsSettingsPrivate +{ + friend class ApplicationsSettings; +private: + ApplicationsSettingsMap m_cache; + QJsonObject m_settingsData; +}; +} + +ApplicationsSettings *UkuiNotification::ApplicationsSettings::self() +{ + std::call_once(flag, [ & ] { + s_self = new ApplicationsSettings(); + }); + return s_self; +} + +ApplicationsSettings::ApplicationsSettings(QObject *parent) : QObject(parent), d(new ApplicationsSettingsPrivate) +{ + d->m_settingsData = SettingsManager::self()->getAllAppSettings(); + connect(SettingsManager::self(), &SettingsManager::appUninstalled, this, &ApplicationsSettings::applicationUninstalled); + connect(SettingsManager::self(), &SettingsManager::settingsDataChanged, this, &ApplicationsSettings::settingsDataChanged); + qmlRegisterUncreatableType("org.ukui.notification.client", 1, 0, "SingleApplicationSettings", ""); +} + +ApplicationsSettings::~ApplicationsSettings() +{ + if(d) { + delete d; + d = nullptr; + } +} + +SingleApplicationSettings *ApplicationsSettings::creatSettings(const PopupNotification ¬ification) +{ + QString desktopEntry = notification.desktopEntry(); + if(desktopEntry.isEmpty()) { + desktopEntry = QStringLiteral("default"); + } + if(d->m_cache.contains(desktopEntry)) { + return d->m_cache[desktopEntry]; + } + return d->m_cache.insert(desktopEntry, new SingleApplicationSettings(desktopEntry)).value(); +} + +ApplicationsSettingsMap &ApplicationsSettings::getAllApplicationsSettings() +{ + for(const QString &desktopEntry : d->m_settingsData.keys()) { + if(!d->m_cache.contains(desktopEntry)) { + d->m_cache.insert(desktopEntry, new SingleApplicationSettings(desktopEntry)); + } + } + return d->m_cache; +} + +QJsonObject ApplicationsSettings::getAppSettings(const QString &appDesktopName) +{ + if(appDesktopName == QStringLiteral("default") || appDesktopName.isEmpty()) { + return SettingsManager::self()->getAppDefaultSettings(); + } + QJsonValue value = d->m_settingsData.value(appDesktopName); + if(value.isUndefined()) { + return SettingsManager::self()->getAppDefaultSettings();; + } + return value.toObject(); +} + +bool ApplicationsSettings::setAppSetting(const QString &appDesktopName, SettingsProperty::Property key, + const QVariant &value) +{ + return SettingsManager::self()->setAppSettings(appDesktopName, key, value); +} + +void ApplicationsSettings::clearCache() +{ + ApplicationsSettingsMap::const_iterator i = d->m_cache.constBegin(); + while(i != d->m_cache.constEnd()) { + ++i; + delete i.value(); + } + d->m_cache.clear(); +} + +void ApplicationsSettings::settingsDataChanged() +{ + QJsonObject data = SettingsManager::self()->getAllAppSettings(); + if(d->m_settingsData == data) { + return; + } + for(const QString &desktopEntry : data.keys()) { + bool newInstalled = !d->m_settingsData.contains(desktopEntry); + d->m_settingsData.insert(desktopEntry, data.value(desktopEntry)); + if(newInstalled) { + Q_EMIT applicationInstalled(desktopEntry); + } + } + Q_EMIT settingsUpdated(); +} + + diff --git a/libukui-notification/notification-settings/applications-settings.h b/libukui-notification/notification-settings/applications-settings.h new file mode 100644 index 0000000..578fef6 --- /dev/null +++ b/libukui-notification/notification-settings/applications-settings.h @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef UKUI_NOTIFICATION_APPLICATIONS_SETTINGS_H +#define UKUI_NOTIFICATION_APPLICATIONS_SETTINGS_H +#include +#include +#include "single-application-settings.h" +#include "popup-notification.h" +namespace UkuiNotification{ +typedef QMap ApplicationsSettingsMap; +class ApplicationsSettingsPrivate; +/** + * SingleApplicationSettings 工厂 + */ +class ApplicationsSettings : public QObject +{ + Q_OBJECT +public: + static ApplicationsSettings *self(); + ~ApplicationsSettings(); + + /** + * 获取某条通知的配置 + * @param notification 表示一条通知 + * @return 返回的指针不需要使用者回收 + */ + SingleApplicationSettings *creatSettings(const PopupNotification ¬ification); + ApplicationsSettingsMap &getAllApplicationsSettings(); + /** + * @brief getAppSettings + * 获取当前用户某个应用通知相关配置信息。 + * @param appDesktopName 传"default"获取配置默认值 + */ + QJsonObject getAppSettings(const QString &appDesktopName); + bool setAppSetting(const QString &appDesktopName, SettingsProperty::Property key, const QVariant &value); + void clearCache(); +Q_SIGNALS: + void applicationUninstalled(const QString &desktopEntry); + void settingsUpdated(); + void applicationInstalled(const QString &desktopEntry); +private Q_SLOTS: + +private: + ApplicationsSettings(QObject *parent = nullptr); + void settingsDataChanged(); + ApplicationsSettingsPrivate *d = nullptr; +}; +} + +#endif //UKUI_NOTIFICATION_APPLICATIONS_SETTINGS_H diff --git a/libukui-notification/notification-settings/notification-global-settings.cpp b/libukui-notification/notification-settings/notification-global-settings.cpp new file mode 100644 index 0000000..ca97466 --- /dev/null +++ b/libukui-notification/notification-settings/notification-global-settings.cpp @@ -0,0 +1,213 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#include "notification-global-settings.h" +#include +#include +#include +#include +#include +#include +#include "settings-manager.h" +#include "settings-properties.h" +#include "settings-properties-info.h" + +namespace UkuiNotification{ +class NotificationGlobalSettingsPrivate +{ + friend class NotificationGlobalSettings; +private: + QJsonObject m_settings; + QDBusInterface *m_usdInterface = nullptr; + int m_currentScreenMode = 0; //0-仅主屏;1-镜像;2-扩展;3-仅副屏 +}; +} + +using namespace UkuiNotification;// UkuiNotification + +NotificationGlobalSettings::NotificationGlobalSettings(QObject *parent) : QObject(parent), d(new NotificationGlobalSettingsPrivate()) +{ + qmlRegisterUncreatableType("org.ukui.notification.client", 1, 0, "NotificationGlobalSettings", ""); + connect(SettingsManager::self(), &SettingsManager::settingsDataChanged, this, &NotificationGlobalSettings::settingsDataChanged); + d->m_settings = SettingsManager::self()->getGlobalSettings(); + d->m_usdInterface = new QDBusInterface("org.ukui.SettingsDaemon", + "/org/ukui/SettingsDaemon/xrandr", + "org.ukui.SettingsDaemon.xrandr"); + if(!d->m_usdInterface->isValid()) { + qWarning() << "NotificationGlobalSettings: Fail to creat org.ukui.SettingsDaemon dbus interface!"; + return; + } + QDBusReply reply = d->m_usdInterface->call("getScreenMode", "ukui-notification-server"); + if (reply.isValid()) { + d->m_currentScreenMode = reply.value(); + } else { + qWarning()<<"NotificationGlobalSettings: Call getScreenMode failed!"; + } + connect(d->m_usdInterface, SIGNAL(screenModeChanged(int)), this, SLOT(screenModeChanged(int))); +} + +NotificationGlobalSettings::~NotificationGlobalSettings() +{ + if(d) { + delete d; + d = nullptr; + } +} + +bool NotificationGlobalSettings::scheduleTurnOnDND() +{ + return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::ScheduleTurnOnDND).name()).toVariant().toBool(); +} + +QTime NotificationGlobalSettings::scheduleTurnOnDNDTime() +{ + return QTime::fromString(d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::ScheduleTurnOnDNDTime).name()).toString(), "HHmm"); +} + +QTime NotificationGlobalSettings::scheduleTurnOffDNDTime() +{ + return QTime::fromString(d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::ScheduleTurnOffDNDTime).name()).toString(), "HHmm"); +} + +bool NotificationGlobalSettings::DNDWhileMultiScreen() +{ + return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::DNDWhileMultiScreen).name()).toVariant().toBool(); +} + +bool NotificationGlobalSettings::DNDWhileFullScreen() +{ + return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::DNDWhileFullScreen).name()).toVariant().toBool(); +} + +bool NotificationGlobalSettings::notifyAlarmWhileDND() +{ + return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::NotifyAlarmWhileDND).name()).toVariant().toBool(); +} + +bool NotificationGlobalSettings::receiveNotificationsFromApps() +{ + return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::ReceiveNotificationsFromApps).name()).toVariant().toBool(); +} + +void NotificationGlobalSettings::settingsDataChanged() +{ + QJsonObject data = SettingsManager::self()->getGlobalSettings(); + for(SettingsProperty::Property property : GLOBAL_SETTINGS) { + QString name = SettingsPropertiesInfo(property).name(); + QJsonValue value = data.value(name); + if(d->m_settings.value(name) != value) { + d->m_settings.insert(name, value); + switch (property) { + case SettingsProperty::ScheduleTurnOnDND: + Q_EMIT scheduleTurnOnDNDChanged(value.toVariant().toBool()); + break; + case SettingsProperty::ScheduleTurnOnDNDTime: + Q_EMIT scheduleTurnOnDNDTimeChanged(QTime::fromString(value.toString(), "HHmm")); + break; + case SettingsProperty::ScheduleTurnOffDNDTime: + Q_EMIT scheduleTurnOffDNDTimeChanged(QTime::fromString(value.toString(), "HHmm")); + break; + case SettingsProperty::DNDWhileMultiScreen: + Q_EMIT DNDWhileMultiScreenChanged(value.toVariant().toBool()); + break; + case SettingsProperty::DNDWhileFullScreen: + Q_EMIT DNDWhileFullScreenChanged(value.toVariant().toBool()); + break; + case SettingsProperty::NotifyAlarmWhileDND: + Q_EMIT notifyAlarmWhileDNDChanged(value.toVariant().toBool()); + break; + case SettingsProperty::ReceiveNotificationsFromApps: + Q_EMIT receiveNotificationsFromAppsChanged(value.toVariant().toBool()); + break; + default: + break; + } + } + } +} + +void NotificationGlobalSettings::setScheduleTurnOnDND(bool enable) +{ + SettingsManager::self()->setGlobalSettings(SettingsProperty::ScheduleTurnOnDND, enable); +} + +void NotificationGlobalSettings::setScheduleTurnOnDNDTime(const QTime &time) +{ + SettingsManager::self()->setGlobalSettings(SettingsProperty::ScheduleTurnOnDNDTime, time); +} + +void NotificationGlobalSettings::setScheduleTurnOffDNDTime(const QTime &time) +{ + SettingsManager::self()->setGlobalSettings(SettingsProperty::ScheduleTurnOffDNDTime, time); +} + +void NotificationGlobalSettings::setDNDWhileMultiScreen(bool enable) +{ + SettingsManager::self()->setGlobalSettings(SettingsProperty::DNDWhileMultiScreen, enable); +} + +void NotificationGlobalSettings::setDNDWhileFullScreen(bool enable) +{ + SettingsManager::self()->setGlobalSettings(SettingsProperty::DNDWhileFullScreen, enable); +} + +void NotificationGlobalSettings::setNotifyAlarmWhileDND(bool enable) +{ + SettingsManager::self()->setGlobalSettings(SettingsProperty::NotifyAlarmWhileDND, enable); +} + +void NotificationGlobalSettings::setReceiveNotificationsFromApps(bool enable) +{ + SettingsManager::self()->setGlobalSettings(SettingsProperty::ReceiveNotificationsFromApps, enable); +} + +bool NotificationGlobalSettings::isDND() { + bool dnd = false; + if(scheduleTurnOnDND()) { + QTime currentTime = QTime::currentTime(); + if( currentTime >= scheduleTurnOnDNDTime() && currentTime < scheduleTurnOffDNDTime()) { + dnd = true; + } + } + if(!dnd) { + if(DNDWhileMultiScreen()) { + if(d->m_currentScreenMode == 1 || d->m_currentScreenMode == 2) { + dnd = true; + } + } + } + if(!dnd) { + if(DNDWhileFullScreen()) { + QDBusMessage msg = QDBusMessage::createMethodCall(QStringLiteral("org.kde.KWin"), + QStringLiteral("/KWin"), + QStringLiteral("org.kde.KWin"), + QStringLiteral("haveFullScreenActiveWindow")); + QDBusReply reply = QDBusConnection::sessionBus().call(msg); + if(reply.isValid()) { + dnd = reply.value(); + } + } + } + return dnd; +} + +void NotificationGlobalSettings::screenModeChanged(int mode) { + d->m_currentScreenMode = mode; +} + diff --git a/libukui-notification/notification-settings/notification-global-settings.h b/libukui-notification/notification-settings/notification-global-settings.h new file mode 100644 index 0000000..6981694 --- /dev/null +++ b/libukui-notification/notification-settings/notification-global-settings.h @@ -0,0 +1,108 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef UKUI_NOTIFICATION_NOTIFICATION_GLOBAL_SETTINGS_H +#define UKUI_NOTIFICATION_NOTIFICATION_GLOBAL_SETTINGS_H +#include +#include +#include "settings-properties.h" +namespace UkuiNotification { +class NotificationGlobalSettingsPrivate; +class NotificationGlobalSettings : public QObject +{ + Q_OBJECT + Q_PROPERTY(bool scheduleTurnOnDND READ scheduleTurnOnDND WRITE setScheduleTurnOnDND NOTIFY scheduleTurnOnDNDChanged) + Q_PROPERTY(QTime scheduleTurnOnDNDTime READ scheduleTurnOnDNDTime WRITE setScheduleTurnOnDNDTime NOTIFY scheduleTurnOnDNDTimeChanged) + Q_PROPERTY(QTime scheduleTurnOffDNDTime READ scheduleTurnOffDNDTime WRITE setScheduleTurnOffDNDTime NOTIFY scheduleTurnOffDNDTimeChanged) + Q_PROPERTY(bool DNDWhileMultiScreen READ DNDWhileMultiScreen WRITE setDNDWhileMultiScreen NOTIFY DNDWhileMultiScreenChanged) + Q_PROPERTY(bool DNDWhileFullScreen READ DNDWhileFullScreen WRITE setDNDWhileFullScreen NOTIFY DNDWhileFullScreenChanged) + Q_PROPERTY(bool notifyAlarmWhileDND READ notifyAlarmWhileDND WRITE setNotifyAlarmWhileDND NOTIFY notifyAlarmWhileDNDChanged) + Q_PROPERTY(bool receiveNotificationsFromApps READ receiveNotificationsFromApps WRITE setReceiveNotificationsFromApps NOTIFY receiveNotificationsFromAppsChanged) + Q_PROPERTY(bool isDND READ isDND) + +public: + NotificationGlobalSettings(QObject *parent = nullptr); + ~NotificationGlobalSettings(); + /** + * 自动开启勿扰模式 + * @return true 自动开启 false 关闭 + */ + bool scheduleTurnOnDND(); + void setScheduleTurnOnDND(bool enable); + /** + * 自动开启勿扰模式时间 + * @return + */ + QTime scheduleTurnOnDNDTime(); + void setScheduleTurnOnDNDTime(const QTime &time); + /** + * 自动关闭勿扰模式时间 + * @return + */ + QTime scheduleTurnOffDNDTime(); + void setScheduleTurnOffDNDTime(const QTime &time); + /** + * 多屏连接时自动开启勿扰模式 + * @return + */ + bool DNDWhileMultiScreen(); + void setDNDWhileMultiScreen(bool enable); + /** + * 全屏模式下自动开启勿扰模式 + * @return + */ + bool DNDWhileFullScreen(); + void setDNDWhileFullScreen(bool enable); + /** + * 勿扰模式下允许闹钟提示 + * @return + */ + bool notifyAlarmWhileDND(); + void setNotifyAlarmWhileDND(bool enable); + /** + * 获取来自应用的通知 + * @return + */ + bool receiveNotificationsFromApps(); + void setReceiveNotificationsFromApps(bool enable); + + /** + * 当前是否处于勿扰模式 + * @return + */ + bool isDND(); +Q_SIGNALS: + void scheduleTurnOnDNDChanged(bool); + void scheduleTurnOnDNDTimeChanged(QTime); + void scheduleTurnOffDNDTimeChanged(QTime); + void DNDWhileMultiScreenChanged(bool); + void DNDWhileFullScreenChanged(bool); + void notifyAlarmWhileDNDChanged(bool); + void receiveNotificationsFromAppsChanged(bool); + +private Q_SLOTS: + void settingsDataChanged(); + void screenModeChanged(int mode); +private: + NotificationGlobalSettingsPrivate *d = nullptr; +}; + +} // UkuiNotification + +#endif //UKUI_NOTIFICATION_NOTIFICATION_GLOBAL_SETTINGS_H diff --git a/libukui-notification/notification-settings/settings-manager-private.h b/libukui-notification/notification-settings/settings-manager-private.h new file mode 100644 index 0000000..c669ab1 --- /dev/null +++ b/libukui-notification/notification-settings/settings-manager-private.h @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef NotificationSettingsPrivate_H +#define NotificationSettingsPrivate_H + +#include "settings-manager.h" +#include +#include +#include +#include +#include "settings-properties.h" + +namespace UkuiNotification { + + +#define NOTIFICATION_SETTINGS_VERSION "1.0" + +class SettingsManagerPrivate : public QObject +{ + friend class SettingsManager; + Q_OBJECT +public: + explicit SettingsManagerPrivate(QObject* parent = nullptr); + ~SettingsManagerPrivate(); + void init(); + +private Q_SLOTS: + /** + * @brief checkAndLoad + * 检查通知配置文件,不存在则初始化生成默认配置文件,存在则根据配置文件版本判断是否更新配置文件。 + */ + void checkAndLoad(); +private: + /** + * @brief createSettingsFile + * 初始化创建通知配置文件。 + */ + void createSettingsFile(); + + /** + * @brief updateSettingsFile + * 更新通知配置文件。 + */ + void updateSettingsFile(); + + /** + * @brief getAppInfo + * 从搜索应用数据库服务中获取desktop信息。 + */ + QStringList getAppInfo(); + + void initSettingsData(QJsonObject &data); + void checkApplicationList(QJsonObject &data); + +public Q_SLOTS: + void desktopFileAdd(const QStringList &data); + void desktopFileDelete(const QStringList &data); +Q_SIGNALS: + void settingsUpdateFinished(); + void appUninstalled(const QString &desktopEntry); + +private: + void save2SettingsFile(const QJsonObject &jsonDocData); + QJsonObject m_settingsData; + QFileSystemWatcher *m_watcher = nullptr; + UkuiSearch::ApplicationInfo * m_applicationInfo = nullptr; + QJsonObject m_applicationDefaultSettings; + bool m_needCheckApplist = true; +}; + +} +#endif // NotificationSettingsPrivate_H diff --git a/libukui-notification/notification-settings/settings-manager.cpp b/libukui-notification/notification-settings/settings-manager.cpp new file mode 100644 index 0000000..a991777 --- /dev/null +++ b/libukui-notification/notification-settings/settings-manager.cpp @@ -0,0 +1,368 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#include "settings-manager.h" +#include "settings-manager-private.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "settings-properties-info.h" + +using namespace UkuiNotification; + +static const QString SETTINGS_FILE_PATH = QDir::homePath() + QStringLiteral("/.config/org.ukui/ukui-notification"); +static const QString SETTINGS_FILE_PATH_NAME = SETTINGS_FILE_PATH + QStringLiteral("/ukui-notification-settings.json"); +static std::once_flag flag; +static SettingsManager *s_self; +SettingsManagerPrivate::SettingsManagerPrivate(QObject* parent) : QObject(parent) +{ + for(SettingsProperty::Property property : SINGLE_APPLICATION_SETTINGS) { + SettingsPropertiesInfo info(property); + m_applicationDefaultSettings.insert(info.name(), info.defaultValue()); + } +} + +SettingsManagerPrivate::~SettingsManagerPrivate() +{ +} + +void SettingsManagerPrivate::init() +{ + m_watcher = new QFileSystemWatcher(this); + connect(m_watcher, &QFileSystemWatcher::fileChanged, this, &SettingsManagerPrivate::checkAndLoad); + //TODO 应用数据服务接口更新中 + m_applicationInfo = new UkuiSearch::ApplicationInfo(this); + if (qApp->property("IS_UKUI_NOTIFICATION_SERVICE").toBool()) { + connect(m_applicationInfo, &UkuiSearch::ApplicationInfo::appDBItems2BAdd, this,&SettingsManagerPrivate::desktopFileAdd); + } + connect(m_applicationInfo, &UkuiSearch::ApplicationInfo::appDBItems2BDelete, this, &SettingsManagerPrivate::desktopFileDelete); + checkAndLoad(); +} +void SettingsManagerPrivate::checkAndLoad() +{ + QLockFile lockFile(SETTINGS_FILE_PATH + QStringLiteral("ukui-notification-settings.json.lock")); + lockFile.lock(); + QFile settingsFile(SETTINGS_FILE_PATH_NAME); + if (!settingsFile.exists()) { + qDebug() << SETTINGS_FILE_PATH_NAME << " is not exist, start create settings file."; + createSettingsFile(); + lockFile.unlock(); + return; + } + + if (!settingsFile.open(QFile::ReadOnly)) { + qWarning() << "SettingsManagerPrivate: configuration file " << settingsFile.fileName() << "open failed !"; + m_watcher->addPath(SETTINGS_FILE_PATH_NAME); + lockFile.unlock(); + return; + } + // 读取json数据 + QByteArray byteArray = settingsFile.readAll(); + settingsFile.close(); + QJsonParseError errRpt; + QJsonDocument jsonDocument(QJsonDocument::fromJson(byteArray, &errRpt)); + if (errRpt.error != QJsonParseError::NoError) { + qWarning() << "SettingsManagerPrivate: Incorrect configuration files. JSON parse error"; + createSettingsFile(); + lockFile.unlock(); + return; + } + + // 读取配置文件 + QJsonObject settingsData = jsonDocument.object(); + QString version = settingsData.value("VERSION").toString(); + if (version != QString(NOTIFICATION_SETTINGS_VERSION)) { + qDebug() << "Notification settings version is different, need update! configFile:" << version << " new:" << NOTIFICATION_SETTINGS_VERSION; + updateSettingsFile(); + } else { + if(m_needCheckApplist) { + checkApplicationList(settingsData); + m_needCheckApplist = false; + } + m_settingsData.swap(settingsData); + Q_EMIT settingsUpdateFinished(); + m_watcher->addPath(SETTINGS_FILE_PATH_NAME); + } + lockFile.unlock(); +} + +void SettingsManagerPrivate::createSettingsFile() +{ + initSettingsData(m_settingsData); + save2SettingsFile(m_settingsData); + Q_EMIT settingsUpdateFinished(); + m_watcher->addPath(SETTINGS_FILE_PATH_NAME); +} + +void SettingsManagerPrivate::updateSettingsFile() +{ + m_watcher->removePath(SETTINGS_FILE_PATH_NAME); + //初始化当前版本默认值 + QJsonObject newData; + initSettingsData(newData); + //同步全局配置 + QJsonObject newGlobalData = newData.value(QStringLiteral("Global")).toObject(); + QJsonObject oldGlobalData = m_settingsData.value(QStringLiteral("Global")).toObject(); + for(const QString &key : newGlobalData.keys()) { + QJsonValue oldValue = oldGlobalData.value(key); + if(!oldValue.isUndefined()) { + newGlobalData.insert(key, oldValue); + } + } + newData.insert(QStringLiteral("Global"), newGlobalData); + //同步所有应用配置 + QJsonObject newApplicationsData = newData.value(QStringLiteral("Applications")).toObject(); + QJsonObject oldApplicationsData = m_settingsData.value(QStringLiteral("Applications")).toObject(); + for(const QString &desktopEntry : newApplicationsData.keys()) { + if(oldApplicationsData.contains(desktopEntry)) { + QJsonObject oldSingleAppData = oldApplicationsData.value(desktopEntry).toObject(); + QJsonObject newSingleAppData = newApplicationsData.value(desktopEntry).toObject(); + for(const QString &key : newSingleAppData.keys()) { + QJsonValue oldValue = oldSingleAppData.value(key); + if(!oldValue.isUndefined()) { + newSingleAppData.insert(key, oldValue); + } + } + newApplicationsData.insert(desktopEntry, newSingleAppData); + } + } + newData.insert(QStringLiteral("Applications"), newApplicationsData); + //写入数据 + m_settingsData.swap(newData); + save2SettingsFile(m_settingsData); + m_watcher->addPath(SETTINGS_FILE_PATH_NAME); + Q_EMIT settingsUpdateFinished(); +} + +QStringList SettingsManagerPrivate::getAppInfo() +{ + + return m_applicationInfo->getInfo(UkuiSearch::ApplicationProperties{}, + UkuiSearch::ApplicationPropertyMap{{UkuiSearch::ApplicationProperty::AutoStart, 0}}).keys(); +} + +void SettingsManagerPrivate::initSettingsData(QJsonObject &data) +{ + data.insert("VERSION", QString(NOTIFICATION_SETTINGS_VERSION)); + + //全局设置 + QJsonObject globalSettings; + for(SettingsProperty::Property property : GLOBAL_SETTINGS) { + SettingsPropertiesInfo info(property); + globalSettings.insert(info.name(), info.defaultValue()); + } + data.insert(QStringLiteral("Global"), globalSettings); + + //应用设置 + QJsonObject applicationsSettings; + for (const QString &desktopFile : getAppInfo()) { + applicationsSettings.insert(desktopFile, m_applicationDefaultSettings); + } + data.insert(QStringLiteral("Applications"), applicationsSettings); +} + +void SettingsManagerPrivate::desktopFileAdd(const QStringList &data) +{ + QJsonObject applicationsSettings = m_settingsData.value(QStringLiteral("Applications")).toObject(); + bool needUpdate = false; + for (const QString &desktopPath : data) { + if(m_applicationInfo->getInfo(desktopPath, UkuiSearch::ApplicationProperty::AutoStart).toInt() == 0) { + applicationsSettings.insert(desktopPath, m_applicationDefaultSettings); + needUpdate = true; + } + } + if(!needUpdate) { + return; + } + + m_settingsData.insert(QStringLiteral("Applications"), applicationsSettings); + + QLockFile lockFile(SETTINGS_FILE_PATH + QStringLiteral("ukui-notification-settings.json.lock")); + lockFile.lock(); + m_watcher->removePath(SETTINGS_FILE_PATH_NAME); + save2SettingsFile(m_settingsData); + m_watcher->addPath(SETTINGS_FILE_PATH_NAME); + lockFile.unlock(); + Q_EMIT settingsUpdateFinished(); +} + +void SettingsManagerPrivate::desktopFileDelete(const QStringList &data) +{ + if (data.isEmpty()) { + return; + } + if (qApp->property("IS_UKUI_NOTIFICATION_SERVER").toBool()) { + QJsonObject applicationsSettings = m_settingsData.value(QStringLiteral("Applications")).toObject(); + for (const QString &app : data) { + applicationsSettings.remove(app); + } + m_settingsData.insert(QStringLiteral("Applications"), applicationsSettings); + QLockFile lockFile(SETTINGS_FILE_PATH + QStringLiteral("ukui-notification-settings.json.lock")); + lockFile.lock(); + m_watcher->removePath(SETTINGS_FILE_PATH_NAME); + save2SettingsFile(m_settingsData); + m_watcher->addPath(SETTINGS_FILE_PATH_NAME); + lockFile.unlock(); + Q_EMIT settingsUpdateFinished(); + } + for(const QString &app : data) { + Q_EMIT appUninstalled(app); + } +} + +void SettingsManagerPrivate::save2SettingsFile(const QJsonObject &jsonDocData) +{ + QDir dir; + QString configFileDir(SETTINGS_FILE_PATH); + if (!dir.exists(configFileDir)) { + if (!dir.mkdir(configFileDir)) { + qWarning() << "Unable to create notification settings config file."; + return; + } + } + + QFile settingsFile(SETTINGS_FILE_PATH_NAME); + settingsFile.open(QIODevice::WriteOnly | QIODevice::Truncate); + + if (settingsFile.write(QJsonDocument(jsonDocData).toJson()) == -1) { + qWarning() << "SettingsManagerPrivate: Error saving configuration file."; + } + settingsFile.flush(); + settingsFile.close(); +} + +void SettingsManagerPrivate::checkApplicationList(QJsonObject &data) +{ + QStringList appList = getAppInfo(); + QStringList appNeedRemoved; + QJsonObject applicationSettings = data.value(QStringLiteral("Applications")).toObject(); + for(const QString &desktopFile : applicationSettings.keys()) { + if(appList.contains(desktopFile)) { + appList.removeAll(desktopFile); + } else { + appNeedRemoved.append(desktopFile); + } + } + //移除应用列表里已经不存在的应用 + for(const QString &desktopFile : appNeedRemoved) { + applicationSettings.remove(desktopFile); + } + //将配置文件中没有的应用插入 + for(const QString &desktopFile : appList) { + applicationSettings.insert(desktopFile, m_applicationDefaultSettings); + } + data.insert(QStringLiteral("Applications"), applicationSettings); + save2SettingsFile(data); +} + +SettingsManager::SettingsManager(QObject *parent) : QObject(parent), d(new SettingsManagerPrivate(this)) +{ + connect(d, &SettingsManagerPrivate::settingsUpdateFinished, this, &SettingsManager::settingsDataChanged); + connect(d, &SettingsManagerPrivate::appUninstalled, this, &SettingsManager::appUninstalled); + d->init(); +} + +QJsonObject SettingsManager::getGlobalSettings() +{ + return d->m_settingsData.value(QStringLiteral("Global")).toObject(); +} + +QJsonObject SettingsManager::getAllAppSettings() +{ + return d->m_settingsData.value(QStringLiteral("Applications")).toObject(); +} + +QJsonObject SettingsManager::getAppSettings(const QString &appDesktopName) +{ + if(appDesktopName == QStringLiteral("default") || appDesktopName.isEmpty()) { + return d->m_applicationDefaultSettings; + } + QJsonValue value = d->m_settingsData.value(QStringLiteral("Applications")).toObject().value(appDesktopName); + if(value.isUndefined()) { + return {}; + } + return value.toObject(); +} + + +QJsonObject SettingsManager::getAppDefaultSettings() +{ + return d->m_applicationDefaultSettings; +} + +SettingsManager *SettingsManager::self() +{ + std::call_once(flag, [ & ] { + s_self = new SettingsManager(); + }); + return s_self; +} + +bool SettingsManager::setGlobalSettings(SettingsProperty::Property key, const QVariant &value) +{ + if(!GLOBAL_SETTINGS.contains(key)) { + return false; + } + auto info = SettingsPropertiesInfo(key); + QString valueToSet = info.valueToString(value); + + QJsonObject data = d->m_settingsData.value(QStringLiteral("Global")).toObject(); + data.insert(info.name(), valueToSet); + d->m_settingsData.insert(QStringLiteral("Global"), data); + QLockFile lockFile(SETTINGS_FILE_PATH + QStringLiteral("ukui-notification-settings.json.lock")); + lockFile.lock(); + d->save2SettingsFile(d->m_settingsData); + lockFile.unlock(); + return true; +} + +bool SettingsManager::setAppSettings(const QString &appDesktopName, SettingsProperty::Property key, const QVariant &value) +{ + if(!SINGLE_APPLICATION_SETTINGS.contains(key)) { + return false; + } + + QJsonObject appsData = d->m_settingsData.value(QStringLiteral("Applications")).toObject(); + QJsonValue dataValue = appsData.value(appDesktopName); + if(dataValue.isUndefined()) { + return false; + } + QJsonObject oneAppData = dataValue.toObject(); + auto info = SettingsPropertiesInfo(key); + QString valueToSet = info.valueToString(value); + oneAppData.insert(info.name(), valueToSet); + appsData.insert(appDesktopName, oneAppData); + d->m_settingsData.insert(QStringLiteral("Applications"), appsData); + + QLockFile lockFile(SETTINGS_FILE_PATH + QStringLiteral("ukui-notification-settings.json.lock")); + lockFile.lock(); + d->save2SettingsFile(d->m_settingsData); + lockFile.unlock(); + return true; +} + + + diff --git a/libukui-notification/notification-settings/settings-manager.h b/libukui-notification/notification-settings/settings-manager.h new file mode 100644 index 0000000..e6b45f8 --- /dev/null +++ b/libukui-notification/notification-settings/settings-manager.h @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + + +#ifndef SETTINGS_MANAGER_H +#define SETTINGS_MANAGER_H + +#include +#include "settings-properties.h" + +namespace UkuiNotification { + +class SettingsManagerPrivate; +class SettingsManager : public QObject +{ + Q_OBJECT +public: + static SettingsManager *self(); + + ~SettingsManager() = default; + + /** + * 获取全局配置 + */ + QJsonObject getGlobalSettings(); + + /** + * @brief getAllAppSettings + * 获取当前用户全部应用通知相关配置信息。 + */ + QJsonObject getAllAppSettings(); + + /** + * @brief getAppSettings + * 获取当前用户某个应用通知相关配置信息。 + * @param appDesktopName 传"default"获取配置默认值 + */ + QJsonObject getAppSettings(const QString &appDesktopName); + + /** + * 获取应用通知设置默认值 + * @return + */ + QJsonObject getAppDefaultSettings(); + + bool setGlobalSettings(SettingsProperty::Property key, const QVariant &value); + bool setAppSettings(const QString &appDesktopName, SettingsProperty::Property key, const QVariant &value); + +Q_SIGNALS: + void settingsDataChanged(); + void newAppInstalled(const QString &desktopEntry); + void appUninstalled(const QString &desktopEntry); + +private: + SettingsManager(QObject *parent = nullptr); + SettingsManagerPrivate * d = nullptr; + +}; +} + +#endif diff --git a/libukui-notification/notification-settings/settings-properties-info.cpp b/libukui-notification/notification-settings/settings-properties-info.cpp new file mode 100644 index 0000000..e8e47ec --- /dev/null +++ b/libukui-notification/notification-settings/settings-properties-info.cpp @@ -0,0 +1,237 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#include "settings-properties-info.h" +#include +#include + +using namespace UkuiNotification; + +class UkuiNotification::SettingsPropertiesInfoPrivate +{ +public: + SettingsProperty::Property m_property; + QString m_name; + QString m_displayName; + QMetaType::Type m_valueType; + QString m_defaultValue; + QMetaType::Type m_settingsPropertyMetaType; +}; + +SettingsPropertiesInfo::SettingsPropertiesInfo(): d(new SettingsPropertiesInfoPrivate) +{ + d->m_property = SettingsProperty::Invalid; + d->m_name = QStringLiteral("Invalid"); + d->m_valueType = QMetaType::UnknownType; + d->m_settingsPropertyMetaType = static_cast(QMetaType::type("UkuiNotification::SettingsProperty::Property")); +} + +SettingsPropertiesInfo::SettingsPropertiesInfo(SettingsProperty::Property property) + : d(new SettingsPropertiesInfoPrivate) +{ + d->m_property = property; + + switch (property) { + case SettingsProperty::ScheduleTurnOnDND: + d->m_name = QStringLiteral("ScheduleTurnOnDND"); + d->m_displayName = tr("Schedule turn on"); + d->m_valueType = QMetaType::Bool; + d->m_defaultValue = "false"; + break; + + case SettingsProperty::ScheduleTurnOnDNDTime: + d->m_name = QStringLiteral("ScheduleTurnOnDNDTime"); + d->m_displayName = tr("Schedule turn on time"); + d->m_valueType = QMetaType::QTime; + d->m_defaultValue = "00:00"; + break; + + case SettingsProperty::ScheduleTurnOffDNDTime: + d->m_name = QStringLiteral("ScheduleTurnOffDNDTime"); + d->m_displayName = tr("Schedule turn off time"); + d->m_valueType = QMetaType::QTime; + d->m_defaultValue = "00:00"; + break; + + case SettingsProperty::DNDWhileMultiScreen: + d->m_name = QStringLiteral("DNDWhileMultiScreen"); + d->m_displayName = tr("Turn on while multi-screen connected"); + d->m_valueType = QMetaType::Bool; + d->m_defaultValue = "false"; + break; + + case SettingsProperty::DNDWhileFullScreen: + d->m_name = QStringLiteral("DNDWhileFullScreen"); + d->m_displayName = tr("Turn on in full screen mode"); + d->m_valueType = QMetaType::Bool; + d->m_defaultValue = "false"; + break; + + case SettingsProperty::NotifyAlarmWhileDND: + d->m_name = QStringLiteral("NotifyAlarmWhileDND"); + d->m_displayName = tr("Allow alarm to notify in do not disturb mode"); + d->m_valueType = QMetaType::Bool; + d->m_defaultValue = "false"; + break; + + case SettingsProperty::ReceiveNotificationsFromApps: + d->m_name = QStringLiteral("ReceiveNotificationsFromApps"); + d->m_displayName = tr("Get notifications from applications"); + d->m_valueType = QMetaType::Bool; + d->m_defaultValue = "false"; + break; + + case SettingsProperty::AllowNotify: + d->m_name = QStringLiteral("AllowNotify"); + d->m_displayName = tr("Allow notify"); + d->m_valueType = QMetaType::Bool; + d->m_defaultValue = "true"; + break; + + case SettingsProperty::AllowSound: + d->m_name = QStringLiteral("AllowSound"); + d->m_displayName = tr("Allow sound for notifications"); + d->m_valueType = QMetaType::Bool; + d->m_defaultValue = "true"; + break; + + case SettingsProperty::ShowContentOnLockScreen: + d->m_name = QStringLiteral("ShowContentOnLockScreen"); + d->m_displayName = tr("Show notification content on lock screen"); + d->m_valueType = QMetaType::Bool; + d->m_defaultValue = "false"; + break; + + case SettingsProperty::ShowNotificationOnLockScreen: + d->m_name = QStringLiteral("ShowNotificationOnLockScreen"); + d->m_displayName = tr("Show notifications on lock screen"); + d->m_valueType = QMetaType::Bool; + d->m_defaultValue = "false"; + break; + +// case SettingsProperty::PopupStyle: +// d->m_name = QStringLiteral("popupStyle"); +// d->m_displayName = tr("Style of popup notification"); +// d->m_valueType = d->m_settingsPropertyMetaType; +// d->m_defaultValue = "TransientPopup"; +// break; +// +// case SettingsProperty::TransientPopup: +// d->m_name = QStringLiteral("TransientPopup"); +// d->m_displayName = tr("Popup: displayed in the upper right corner of the screen, will automatically disappear"); +// d->m_valueType = QMetaType::Int; +// break; +// +// case SettingsProperty::ResidentPopup: +// d->m_name = QStringLiteral("ResidentPopup"); +// d->m_displayName = tr("Notice: will remain on the screen until it is closed"); +// d->m_valueType = QMetaType::Int; +// break; +// +// case SettingsProperty::NoPopup: +// d->m_name = QStringLiteral("NoPopup"); +// d->m_displayName = tr("None: notifications will not be displayed on the screen, only be put into notification center"); +// d->m_valueType = QMetaType::Int; +// break; + + case SettingsProperty::Invalid: + d->m_name = QStringLiteral("Invalid"); + d->m_valueType = QMetaType::UnknownType; + break; + // NOTE: new properties must also be added to ::fromName() + } +} + +SettingsPropertiesInfo::SettingsPropertiesInfo(const SettingsPropertiesInfo& pi) + : d(new SettingsPropertiesInfoPrivate(*pi.d)) +{ +} + +SettingsPropertiesInfo::~SettingsPropertiesInfo() = default; + +SettingsPropertiesInfo& SettingsPropertiesInfo::operator=(const SettingsPropertiesInfo& rhs) +{ + *d = *rhs.d; + return *this; +} + +bool SettingsPropertiesInfo::operator==(const SettingsPropertiesInfo& rhs) const +{ + return d->m_name == rhs.d->m_name && d->m_displayName == rhs.d->m_displayName && + d->m_property == rhs.d->m_property && d->m_valueType == rhs.d->m_valueType; +} + +QString SettingsPropertiesInfo::displayName() const +{ + return d->m_displayName; +} + +QString SettingsPropertiesInfo::name() const +{ + return d->m_name; +} + +SettingsProperty::Property SettingsPropertiesInfo::property() const +{ + return d->m_property; +} + +QMetaType::Type SettingsPropertiesInfo::valueType() const +{ + return d->m_valueType; +} + +SettingsPropertiesInfo SettingsPropertiesInfo::fromName(const QString& name) +{ + static QHash propertyHash = { + { QStringLiteral("ScheduleTurnOnDND"), SettingsProperty::ScheduleTurnOnDND }, + { QStringLiteral("ScheduleTurnOnDNDTime"), SettingsProperty::ScheduleTurnOnDNDTime }, + { QStringLiteral("ScheduleTurnOffDNDTime"), SettingsProperty::ScheduleTurnOffDNDTime }, + { QStringLiteral("DNDWhileMultiScreen"), SettingsProperty::DNDWhileMultiScreen }, + { QStringLiteral("DNDWhileFullScreen"), SettingsProperty::DNDWhileFullScreen }, + { QStringLiteral("NotifyAlarmWhileDND"), SettingsProperty::NotifyAlarmWhileDND }, + { QStringLiteral("ReceiveNotificationsFromApps"), SettingsProperty::ReceiveNotificationsFromApps }, + { QStringLiteral("AllowNotify"), SettingsProperty::AllowNotify }, + { QStringLiteral("AllowSound"), SettingsProperty::AllowSound }, + { QStringLiteral("ShowContentOnLockScreen"), SettingsProperty::ShowContentOnLockScreen }, + { QStringLiteral("ShowNotificationOnLockScreen"), SettingsProperty::ShowNotificationOnLockScreen }, +// { QStringLiteral("popupStyle"), SettingsProperty::PopupStyle }, +// { QStringLiteral("TransientPopup"), SettingsProperty::TransientPopup }, +// { QStringLiteral("ResidentPopup"), SettingsProperty::ResidentPopup }, +// { QStringLiteral("NoPopup"), SettingsProperty::NoPopup } + }; + + return {propertyHash.value(name)}; +} + +QString SettingsPropertiesInfo::defaultValue() const +{ + return d->m_defaultValue; +} + +QString SettingsPropertiesInfo::valueToString(const QVariant &value) const +{ + if(d->m_valueType == d->m_settingsPropertyMetaType) { + return SettingsPropertiesInfo(static_cast(value.toInt())).name(); + } else if(d->m_valueType == QMetaType::QTime) { + return value.toTime().toString("HHmm"); + } else { + return value.toString(); + } +} diff --git a/libukui-notification/notification-settings/settings-properties-info.h b/libukui-notification/notification-settings/settings-properties-info.h new file mode 100644 index 0000000..2f78544 --- /dev/null +++ b/libukui-notification/notification-settings/settings-properties-info.h @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef SETTINGS_PROPERTIES_INFO_H +#define SETTINGS_PROPERTIES_INFO_H + +#include +#include +#include +#include "settings-properties.h" + +#include + +namespace UkuiNotification { + +class SettingsPropertiesInfoPrivate; +/** + * \class SettingsPropertiesInfo SettingsPropertiesInfo.h + */ +class Q_DECL_IMPORT SettingsPropertiesInfo : public QObject +{ + Q_OBJECT +public: + SettingsPropertiesInfo(); + SettingsPropertiesInfo(SettingsProperty::Property property); + SettingsPropertiesInfo(const SettingsPropertiesInfo& pi); + ~SettingsPropertiesInfo(); + + SettingsPropertiesInfo& operator=(const SettingsPropertiesInfo& rhs); + bool operator==(const SettingsPropertiesInfo& rhs) const; + + /** + * The enumeration which represents this property + */ + SettingsProperty::Property property() const; + + /** + * The internal unique name used to refer to the property + */ + QString name() const; + + /** + * A user visible name of the property + */ + QString displayName() const; + + /** + * The type the value of this property should be. + * Eg - Property::Height should be an integer + */ + QMetaType::Type valueType() const; + QString defaultValue() const; + QString valueToString(const QVariant &value) const; + + /** + * Construct a SettingsPropertiesInfo from the internal property name. + * The internal property name is case insensitive + */ + static SettingsPropertiesInfo fromName(const QString& name); + +private: + const std::unique_ptr d; +}; + +} // namespace +Q_DECLARE_METATYPE(UkuiNotification::SettingsPropertiesInfo) + + +#endif // SETTINGS_PROPERTIES_INFO_H diff --git a/libukui-notification/notification-settings/settings-properties.h b/libukui-notification/notification-settings/settings-properties.h new file mode 100644 index 0000000..6b49fd0 --- /dev/null +++ b/libukui-notification/notification-settings/settings-properties.h @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef SETTINGS_PROPERTIES +#define SETTINGS_PROPERTIES +#include +#include + +namespace UkuiNotification { +namespace SettingsProperty { +Q_NAMESPACE +/** + * @brief The Property enum contains all settings property types + * + */ +enum Property { + Invalid = 0, + + //Global settings about DND mode + ScheduleTurnOnDND, //是否在时间段内自动开启勿扰模式,bool类型,默认值false + ScheduleTurnOnDNDTime, //勿扰模式开启时间,QDateTime类型,默认值00:00 + ScheduleTurnOffDNDTime, //勿扰模式结束时间,QDateTime类型,默认值00:00 + DNDWhileMultiScreen, //多屏启动时是否启动勿扰模式,bool类型,默认值false + DNDWhileFullScreen, //全屏状态下是否启动勿扰模式,bool类型,默认值false + NotifyAlarmWhileDND, //勿扰模式下是否允许闹钟提示,bool类型,默认值false + + //Show notifications from applications + ReceiveNotificationsFromApps, //是否获取来自应用程序的通知,bool类型,默认值true + + //single app notification settings + AllowNotify = ReceiveNotificationsFromApps + 1, //是否接收当前应用通知,bool类型,默认值true + AllowSound, //是否打开通知提示声,bool类型,默认值true + ShowContentOnLockScreen, //锁屏界面是否显示通知内容信息,bool类型,默认值false + ShowNotificationOnLockScreen //锁屏界面是否显示通知,bool类型,默认值false +// PopupStyle, //通知样式,appNotificationStyle类型,默认值Mutative +// +// //single app notification settings中的 popupStyle 类型取值范围 +// TransientPopup = PopupStyle +1, //横幅模式,显示在右上角,会自动消失 +// ResidentPopup, //提示模式,会保留在屏幕上,直到被关闭 +// NoPopup //无,通知不会显示在屏幕上,但是会进入通知中心 +}; +typedef QMap PropertyMap; +} + +static const QList GLOBAL_SETTINGS { + SettingsProperty::ScheduleTurnOnDND, + SettingsProperty::ScheduleTurnOnDNDTime, + SettingsProperty::ScheduleTurnOffDNDTime, + SettingsProperty::DNDWhileMultiScreen, + SettingsProperty::DNDWhileFullScreen, + SettingsProperty::NotifyAlarmWhileDND, + SettingsProperty::ReceiveNotificationsFromApps +}; +static const QList SINGLE_APPLICATION_SETTINGS { + SettingsProperty::AllowNotify, + SettingsProperty::AllowSound, + SettingsProperty::ShowContentOnLockScreen, + SettingsProperty::ShowNotificationOnLockScreen +// SettingsProperty::PopupStyle, +}; +} // namespace UkuiNotification + +Q_DECLARE_METATYPE(UkuiNotification::SettingsProperty::Property) + +#endif diff --git a/libukui-notification/notification-settings/single-application-settings.cpp b/libukui-notification/notification-settings/single-application-settings.cpp new file mode 100644 index 0000000..d80978c --- /dev/null +++ b/libukui-notification/notification-settings/single-application-settings.cpp @@ -0,0 +1,200 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#include "single-application-settings.h" +#include +#include +#include "settings-properties-info.h" +#include "applications-settings.h" + + +namespace UkuiNotification{ +class SingleApplicationSettingsPrivate +{ + friend class SingleApplicationSettings; +public: + SingleApplicationSettingsPrivate(); + SingleApplicationSettingsPrivate(const SingleApplicationSettingsPrivate &other); + ~SingleApplicationSettingsPrivate(); +private: + QJsonObject m_settings; + QString m_desktopEntry; +}; +} +using namespace UkuiNotification; + +SingleApplicationSettingsPrivate::SingleApplicationSettingsPrivate() +{ +} + +SingleApplicationSettingsPrivate::SingleApplicationSettingsPrivate(const SingleApplicationSettingsPrivate &other) +{ + m_settings = other.m_settings; + m_desktopEntry = other.m_desktopEntry; +} + +SingleApplicationSettingsPrivate::~SingleApplicationSettingsPrivate() +{ + +} + +SingleApplicationSettings::SingleApplicationSettings(const QString &desktopEntry, QObject *parent) + : QObject(parent) + , d(new SingleApplicationSettingsPrivate) +{ + d->m_desktopEntry = desktopEntry; + init(); +} + +SingleApplicationSettings::SingleApplicationSettings(const SingleApplicationSettings &other) + : d(new SingleApplicationSettingsPrivate(*other.d)) +{ + init(); +} + +SingleApplicationSettings &SingleApplicationSettings::operator=(const SingleApplicationSettings &other) +{ + *d = *other.d; + init(); + return *this; +} +SingleApplicationSettings &SingleApplicationSettings::operator=(SingleApplicationSettings &&other) Q_DECL_NOEXCEPT +{ + d = other.d; + other.d = nullptr; + init(); + return *this; +} + +SingleApplicationSettings::~SingleApplicationSettings() +{ + if(d) { + delete d; + d = nullptr; + } +} + +void SingleApplicationSettings::init() +{ + d->m_settings = ApplicationsSettings::self()->getAppSettings(d->m_desktopEntry); + if(d->m_desktopEntry != QStringLiteral("default") && !d->m_desktopEntry.isEmpty()) { + connect(ApplicationsSettings::self(), &ApplicationsSettings::applicationUninstalled, this, &SingleApplicationSettings::appUninstalled); + connect(ApplicationsSettings::self(), &ApplicationsSettings::settingsUpdated, this, &SingleApplicationSettings::settingsDataChanged); + } +} + +bool SingleApplicationSettings::allowNotify() const +{ + return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::AllowNotify).name()).toVariant().toBool(); +} + +bool SingleApplicationSettings::allowSound() const +{ + return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::AllowSound).name()).toVariant().toBool(); +} + +bool SingleApplicationSettings::showContentOnLockScreen() const +{ + return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::ShowContentOnLockScreen).name()).toVariant().toBool(); +} + +bool SingleApplicationSettings::showNotificationOnLockScreen() const +{ + return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::ShowNotificationOnLockScreen).name()).toVariant().toBool(); +} + +//SettingsProperty::Property UkuiNotification::SingleApplicationSettings::popupStyle() const +//{ +// return SettingsPropertiesInfo::fromName(d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::PopupStyle).name()).toString()).property(); +//} + +void SingleApplicationSettings::settingsDataChanged() +{ + QJsonObject data = ApplicationsSettings::self()->getAppSettings(d->m_desktopEntry); + if(data.isEmpty()) { + return; + } + for(SettingsProperty::Property property : SINGLE_APPLICATION_SETTINGS) { + QString name = SettingsPropertiesInfo(property).name(); + QJsonValue value = data.value(name); + if(d->m_settings.value(name) != value) { + d->m_settings.insert(name, value); + switch (property) { + case SettingsProperty::AllowNotify: + Q_EMIT allowNotifyChanged(value.toVariant().toBool()); + break; + case SettingsProperty::AllowSound: + Q_EMIT allowSoundChanged(value.toVariant().toBool()); + break; + case SettingsProperty::ShowContentOnLockScreen: + Q_EMIT showContentOnLockScreenChanged(value.toVariant().toBool()); + break; + case SettingsProperty::ShowNotificationOnLockScreen: + Q_EMIT showNotificationOnLockScreenChanged(value.toVariant().toBool()); + break; +// case SettingsProperty::PopupStyle: +// Q_EMIT popupStyleChanged(SettingsPropertiesInfo::fromName(value.toString()).property()); +// break; + default: + break; + } + } + } +} + +void SingleApplicationSettings::appUninstalled(const QString &desktopEntry) +{ + if(d->m_desktopEntry == desktopEntry) { + Q_EMIT uninstalled(); + } +} + +void SingleApplicationSettings::setAllowNotify(bool enable) +{ + qWarning() << d->m_desktopEntry << enable; + ApplicationsSettings::self()->setAppSetting(d->m_desktopEntry, SettingsProperty::AllowNotify, enable); +} + +void SingleApplicationSettings::setAllowSound(bool enable) +{ + ApplicationsSettings::self()->setAppSetting(d->m_desktopEntry, SettingsProperty::AllowSound, enable); +} + +void SingleApplicationSettings::setShowContentOnLockScreen(bool enable) +{ + ApplicationsSettings::self()->setAppSetting(d->m_desktopEntry, SettingsProperty::ShowContentOnLockScreen, enable); +} + +void SingleApplicationSettings::setShowNotificationOnLockScreen(bool enable) +{ + ApplicationsSettings::self()->setAppSetting(d->m_desktopEntry, SettingsProperty::ShowNotificationOnLockScreen, enable); +} + +//void SingleApplicationSettings::setPopupStyle(SettingsProperty::Property style) +//{ +// ApplicationsSettings::self()->setAppSetting(d->m_desktopEntry, SettingsProperty::PopupStyle, style); +//} + +QString SingleApplicationSettings::desktopEntry() const +{ + return d->m_desktopEntry; +} + + + diff --git a/libukui-notification/notification-settings/single-application-settings.h b/libukui-notification/notification-settings/single-application-settings.h new file mode 100644 index 0000000..44662a0 --- /dev/null +++ b/libukui-notification/notification-settings/single-application-settings.h @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef UKUI_NOTIFICATION_SINGLE_APPLICATION_SETTINGS_H +#define UKUI_NOTIFICATION_SINGLE_APPLICATION_SETTINGS_H +#include +#include "settings-properties.h" +#include +namespace UkuiNotification { +class SingleApplicationSettingsPrivate; +/** + * 一个应用的设置項 + */ +class SingleApplicationSettings : public QObject +{ + Q_OBJECT + Q_PROPERTY(bool allowNotify READ allowNotify WRITE setAllowNotify NOTIFY allowNotifyChanged) + Q_PROPERTY(bool allowSound READ allowSound WRITE setAllowSound NOTIFY allowSoundChanged) + Q_PROPERTY(bool showContentOnLockScreen READ showContentOnLockScreen WRITE setShowContentOnLockScreen NOTIFY showContentOnLockScreenChanged) + Q_PROPERTY(bool showNotificationOnLockScreen READ showNotificationOnLockScreen WRITE setShowNotificationOnLockScreen NOTIFY showNotificationOnLockScreenChanged) +// Q_PROPERTY(SettingsProperty::Property PopupStyle READ popupStyle WRITE setPopupStyle NOTIFY popupStyleChanged) +public: + explicit SingleApplicationSettings(const QString &desktopEntry = QString(), QObject *parent = nullptr); + SingleApplicationSettings(const SingleApplicationSettings &other); + SingleApplicationSettings &operator=(const SingleApplicationSettings &other); + SingleApplicationSettings &operator=(SingleApplicationSettings &&other) Q_DECL_NOEXCEPT; + ~SingleApplicationSettings(); + + bool allowNotify() const; + void setAllowNotify(bool enable); + + bool allowSound() const ; + void setAllowSound(bool enable); + + bool showContentOnLockScreen() const ; + void setShowContentOnLockScreen(bool enable); + + bool showNotificationOnLockScreen() const; + void setShowNotificationOnLockScreen(bool enable); + +// SettingsProperty::Property popupStyle() const; +// void setPopupStyle(SettingsProperty::Property style); + + QString desktopEntry() const; + +Q_SIGNALS: + void allowNotifyChanged(bool); + void allowSoundChanged(bool); + void showContentOnLockScreenChanged(bool); + void showNotificationOnLockScreenChanged(bool); + void popupStyleChanged(SettingsProperty::Property); + void uninstalled(); + +private Q_SLOTS: + void init(); + void settingsDataChanged(); + void appUninstalled(const QString &desktopEntry); + +private: + SingleApplicationSettingsPrivate *d = nullptr; +}; +} + +#endif //UKUI_NOTIFICATION_SINGLE_APPLICATION_SETTINGS_H diff --git a/libukui-notification/popup-notification.cpp b/libukui-notification/popup-notification.cpp new file mode 100644 index 0000000..c8cf8a4 --- /dev/null +++ b/libukui-notification/popup-notification.cpp @@ -0,0 +1,432 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#include "popup-notification.h" +#include +#include +#include +namespace UkuiNotification { +class PopupNotificationPrivate +{ +public: + PopupNotificationPrivate(); + ~PopupNotificationPrivate(); + QImage parseImageHint(const QDBusArgument &arg); + void loadImageFromPath(const QString &path); + QSize maximumImageSize(); + + uint m_id = 0; + QString m_applicationName; + QString m_applicationIconName; + QString m_summary; + QString m_body; + QList> m_actions; + bool m_hasDefaultAction = false; + QString m_defaultActionLabel; + QVariantMap m_hints = QVariantMap(); + QString m_category; + QImage m_image; + QString m_icon; + QDateTime m_createdTime; + QString m_desktopEntry; + PopupNotification::Urgency m_urgency = PopupNotification::NormalUrgency; + int m_timeout = -1; + bool m_resident = false; + bool m_transient = false; + QString m_soundFile; + QString m_soundName; + bool m_suppressSound = false; + QString m_display; + QStringList m_actionState; + bool m_noFold = false; + int m_popupTimeout = 6; +}; +} +using namespace UkuiNotification; + +PopupNotificationPrivate::PopupNotificationPrivate() +{ +} + +PopupNotificationPrivate::~PopupNotificationPrivate() = default; + +QImage PopupNotificationPrivate::parseImageHint(const QDBusArgument &arg) +{ + //copy from plasma-workspace + int width, height, rowStride, hasAlpha, bitsPerSample, channels; + QByteArray pixels; + char *ptr; + char *end; + + arg.beginStructure(); + arg >> width >> height >> rowStride >> hasAlpha >> bitsPerSample >> channels >> pixels; + arg.endStructure(); + + auto copyLineRGB32 = [](QRgb *dst, const char *src, int width) { + const char *end = src + width * 3; + for (; src != end; ++dst, src += 3) { + *dst = qRgb(src[0], src[1], src[2]); + } + }; + + auto copyLineARGB32 = [](QRgb *dst, const char *src, int width) { + const char *end = src + width * 4; + for (; src != end; ++dst, src += 4) { + *dst = qRgba(src[0], src[1], src[2], src[3]); + } + }; + + QImage::Format format = QImage::Format_Invalid; + void (*fcn)(QRgb *, const char *, int) = nullptr; + if (bitsPerSample == 8) { + if (channels == 4) { + format = QImage::Format_ARGB32; + fcn = copyLineARGB32; + } else if (channels == 3) { + format = QImage::Format_RGB32; + fcn = copyLineRGB32; + } + } + if (format == QImage::Format_Invalid) { + qWarning() << "Unsupported image format (hasAlpha:" << hasAlpha << "bitsPerSample:" << bitsPerSample + << "channels:" << channels << ")"; + return QImage(); + } + + QImage image(width, height, format); + ptr = pixels.data(); + end = ptr + pixels.length(); + for (int y = 0; y < height; ++y, ptr += rowStride) { + if (ptr + channels * width > end) { + qWarning() << "Image data is incomplete. y:" << y << "height:" << height; + break; + } + fcn((QRgb *)image.scanLine(y), ptr, width); + } + + return image; +} + +void PopupNotificationPrivate::loadImageFromPath(const QString &path) +{ + //copy from plasma-workspace + QUrl imageUrl; + if (path.startsWith(QLatin1Char('/'))) { + imageUrl = QUrl::fromLocalFile(path); + } else if (path.contains(QLatin1Char('/'))) { + imageUrl = QUrl(path); + + if (!imageUrl.isLocalFile()) { + qDebug() << "Refused to load image from" << path << "which isn't a valid local location."; + return; + } + } + + if (!imageUrl.isValid()) { + m_icon = path; + return; + } + + QImageReader reader(imageUrl.toLocalFile()); + reader.setAutoTransform(true); + + const QSize imageSize = reader.size(); + if (imageSize.isValid() && (imageSize.width() > maximumImageSize().width() || imageSize.height() > maximumImageSize().height())) { + const QSize thumbnailSize = imageSize.scaled(maximumImageSize(), Qt::KeepAspectRatio); + reader.setScaledSize(thumbnailSize); + } + + m_image = reader.read(); +} + +QSize PopupNotificationPrivate::maximumImageSize() +{ + return QSize(256, 256); +} + +PopupNotification::PopupNotification(uint id) : d(new PopupNotificationPrivate()) +{ + d->m_id = id; +} + +PopupNotification::PopupNotification(const PopupNotification &other) : d(new PopupNotificationPrivate(*other.d)) +{ +} + +PopupNotification &PopupNotification::operator=( const PopupNotification &other) +{ + *d = *other.d; + return *this; +} + +PopupNotification &PopupNotification::operator=(PopupNotification &&other) Q_DECL_NOEXCEPT +{ + d = other.d; + other.d = nullptr; + return *this; +} +PopupNotification::~PopupNotification() +{ + if(d) { + delete d; + d = nullptr; + } +} + +uint PopupNotification::id() const +{ + return d->m_id; +} + +QString PopupNotification::applicationName() const +{ + return d->m_applicationName; +} + +void PopupNotification::setApplicationName(const QString &applicationName) +{ + d->m_applicationName = applicationName; +} + +QString PopupNotification::applicationIconName() const +{ + return d->m_applicationIconName; +} + +void PopupNotification::setApplicationIconName(const QString &applicationIconName) +{ + d->m_applicationIconName = applicationIconName; +} + +QString PopupNotification::summary() const +{ + return d->m_summary; +} + +void PopupNotification::setSummary(const QString &summary) +{ + d->m_summary = summary; +} + +QString PopupNotification::body() const +{ + return d->m_body; +} + +void PopupNotification::setBody(const QString &body) +{ + d->m_body = body; +} + +bool PopupNotification::hasDefaultAction() const +{ + return d->m_hasDefaultAction; +} + +QString PopupNotification::defaultActionLabel() +{ + return d->m_defaultActionLabel; +} + +void PopupNotification::setActions(const QStringList &actions) +{ + if (actions.count() % 2 != 0) { + qWarning() << "List of actions must contain an even number of items, tried to set actions to" << actions; + return; + } + + d->m_hasDefaultAction = false; + + for (int i = 0; i < actions.count(); i += 2) { + const QString &key = actions.at(i); + const QString &label = actions.at(i + 1); + + if (!d->m_hasDefaultAction && key == QLatin1String("default")) { + d->m_hasDefaultAction = true; + d->m_defaultActionLabel = label; + } + d->m_actions.append({key, label}); + } +} + +QList> PopupNotification::actions() const +{ + return d->m_actions; +} + +QVariantMap PopupNotification::hints() const +{ + return d->m_hints; +} + +void PopupNotification::setHints(const QVariantMap &hints) +{ + d->m_hints = hints; + d->m_desktopEntry = hints.value(QStringLiteral("desktop-entry")).toString(); + bool ok; + int urgency = hints.value(QStringLiteral("urgency")).toInt(&ok); + if(ok) { + switch (urgency) { + default: + case 0: //低等级,不弹窗 + setUrgency(Urgency::LowUrgency); + d->m_popupTimeout = 0; + break; + case 1: //中等级,弹窗时间默认6秒 + setUrgency(Urgency::NormalUrgency); + d->m_popupTimeout = 6; + break; + case 2: //高等级,默认弹窗常驻,不可折叠 + setUrgency(Urgency::CriticalUrgency); + d->m_popupTimeout = -1; + d->m_noFold = true; + break; + } + } + d->m_createdTime = QDateTime::fromString(hints.value(QStringLiteral("x-ukui-createdTime")).toString()); + d->m_resident = hints.value(QStringLiteral("resident")).toBool(); + d->m_transient = hints.value(QStringLiteral("transient")).toBool(); + d->m_category = hints.value(QStringLiteral("category")).toString(); + + auto end = hints.end(); + auto it = hints.find(QStringLiteral("image-data")); + if (it != end) { + d->m_image = d->parseImageHint(it->value()); + if (!d->m_image.isNull()) { + const QSize max = d->maximumImageSize(); + if (d->m_image.size().width() > max.width() || d->m_image.size().height() > max.height()) { + d->m_image = d->m_image.scaled(max, Qt::KeepAspectRatio, Qt::SmoothTransformation); + } + } + } + if (d->m_image.isNull()) { + it = hints.find(QStringLiteral("image-path")); + + if (it != end) { + d->loadImageFromPath(it->toString()); + } + } + + d->m_soundFile = hints.value(QStringLiteral("sound-file")).toString(); + d->m_soundName = hints.value(QStringLiteral("sound-name")).toString(); + d->m_suppressSound = hints.value(QStringLiteral("suppress-sound")).toBool(); + d->m_display = hints.value(QStringLiteral("x-ukui-display")).toString(); + d->m_actionState = hints.value(QStringLiteral("x-ukui-action-state")).toStringList(); + + QVariant tmp = hints.value(QStringLiteral("x-ukui-no-fold")); + if(!tmp.isNull()) { + d->m_noFold = tmp.toBool(); + } + tmp = hints.value(QStringLiteral("x-ukui-popup-timeout")); + if(!tmp.isNull()) { + d->m_popupTimeout = tmp.toInt(); + } +} + +int PopupNotification::timeout() const +{ + return d->m_timeout; +} + +void PopupNotification::setTimeout(int timeout) +{ + d->m_timeout = timeout; +} + +QDateTime PopupNotification::createdTime() const +{ + return d->m_createdTime; +} + +bool PopupNotification::enableActionIcons() const +{ + //TODO 可以支持action-icon + return false; +} + +QString PopupNotification::category() const +{ + return d->m_category; +} + +QString PopupNotification::desktopEntry() const +{ + return d->m_desktopEntry; +} + +QImage PopupNotification::image() const +{ + return d->m_image; +} + +QString PopupNotification::icon() const +{ + return d->m_icon; +} + +bool PopupNotification::resident() const +{ + return d->m_resident; +} + +QString PopupNotification::soundFile() const +{ + return d->m_soundFile; +} +QString PopupNotification::soundName() const +{ + return d->m_soundName; +} + +bool PopupNotification::suppressSound() const +{ + return d->m_suppressSound; +} + +bool PopupNotification::transient() const +{ + return d->m_transient; +} + +QString PopupNotification::display() const +{ + return d->m_display; +} + +void PopupNotification::setUrgency(PopupNotification::Urgency urgency) +{ + d->m_urgency = urgency; +} + +PopupNotification::Urgency PopupNotification::urgency() const +{ + return d->m_urgency; +} + +QStringList PopupNotification::actionState() const { + return d->m_actionState; +} + +bool PopupNotification::noFold() const { + return d->m_noFold; +} + +int PopupNotification::popupTimeout() const { + return d->m_popupTimeout; +} diff --git a/libukui-notification/popup-notification.h b/libukui-notification/popup-notification.h new file mode 100644 index 0000000..de21d2a --- /dev/null +++ b/libukui-notification/popup-notification.h @@ -0,0 +1,181 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef UKUI_NOTIFICATION_POPUP_NOTIFICATION_H +#define UKUI_NOTIFICATION_POPUP_NOTIFICATION_H +#include "ukui-notification_global.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace UkuiNotification { +class PopupNotificationPrivate; +typedef QList> ActionList; +class UKUINOTIFICATION_EXPORT PopupNotification +{ + friend class NotificationSettingsTest; + Q_GADGET + Q_PROPERTY(uint id READ id) + Q_PROPERTY(QString applicationName READ applicationName WRITE setApplicationName) + Q_PROPERTY(QString applicationIconName READ applicationIconName WRITE setApplicationIconName) + Q_PROPERTY(QString summary READ summary WRITE setSummary) + Q_PROPERTY(QString body READ body WRITE setBody) + Q_PROPERTY(QDateTime createdTime READ createdTime) + Q_PROPERTY(bool hasDefaultAction READ hasDefaultAction) + Q_PROPERTY(ActionList actions READ actions) + Q_PROPERTY(int timeout READ timeout WRITE setTimeout) + Q_PROPERTY(bool enableActionIcons READ enableActionIcons) + Q_PROPERTY(QImage image READ image) + Q_PROPERTY(QString icon READ icon) + Q_PROPERTY(bool resident READ resident) + Q_PROPERTY(bool transient READ transient) + Q_PROPERTY(QString soundFile READ soundFile) + Q_PROPERTY(QString soundName READ soundName) + Q_PROPERTY(bool suppressSound READ suppressSound) + Q_PROPERTY(QString category READ category) + Q_PROPERTY(Urgency urgency READ urgency WRITE setUrgency) + Q_PROPERTY(QString display READ display) + Q_PROPERTY(QStringList actionState READ actionState) + Q_PROPERTY(bool noFold READ noFold) + Q_PROPERTY(int popupTimeout READ popupTimeout) + +public: +/** + * The notification urgency. + */ + enum Urgency { + LowUrgency = 0, + NormalUrgency = 1, + CriticalUrgency = 2, + }; + Q_ENUM(Urgency) + + explicit PopupNotification(uint id = 0); + PopupNotification(const PopupNotification &other); + PopupNotification &operator=(const PopupNotification &other); + PopupNotification &operator=(PopupNotification &&other) Q_DECL_NOEXCEPT; + ~PopupNotification(); + + uint id() const; + QString applicationName() const; + void setApplicationName(const QString &applicationName); + + QString applicationIconName() const; + void setApplicationIconName(const QString &applicationIconName); + + QString summary() const; + void setSummary(const QString &summary); + + QString body() const; + void setBody(const QString &body); + + bool hasDefaultAction() const; + QString defaultActionLabel(); + void setActions(const QStringList &actions); + ActionList actions() const; + QStringList actionState() const; + + QVariantMap hints() const; + void setHints(const QVariantMap &hints); + + int timeout() const; + void setTimeout(int timeout); + + QDateTime createdTime() const; + //m_hints + /** + * 使用图标显示action + * @return + */ + bool enableActionIcons() const; + /** + * 分类 + * @return + */ + QString category() const; + /** + * desktop名称(不带.desktop后缀) + * @return + */ + QString desktopEntry() const; + /** + * 对应image-data字段 + * @return + */ + QImage image() const; + /** + * 当加载image-data失败,或通过image-path加载image失败时(image-path不是URL),icon会被设置为image-path数据 + * @return + */ + QString icon() const; + /** + * 是否持续显示,不会自动移除,直到被用户手动或发送者删除 + * @return + */ + bool resident() const; + /** + * 通知发送时播放的声音文件路径 + * @return + */ + QString soundFile() const; + /** + * 声音主题中的声音名称 + * @return + */ + QString soundName() const; + /** + * 是否静音 + * @return + */ + bool suppressSound() const; + /** + * 暂时通知(会自动移除) + * @return + */ + bool transient() const; + + Urgency urgency() const; + void setUrgency(Urgency urgency); + /** + * 通知发送者所在的display + * @return + */ + QString display() const; + /** + * 是否不折叠 + * @return + */ + bool noFold() const; + /** + * 弹窗持续时间 + * @return + */ + int popupTimeout() const; + +private: + PopupNotificationPrivate *d = nullptr; +}; +} + +#endif //UKUI_NOTIFICATION_POPUP_NOTIFICATION_H diff --git a/libukui-notification/ukui-notification-config.cmake.in b/libukui-notification/ukui-notification-config.cmake.in new file mode 100644 index 0000000..62b2ea1 --- /dev/null +++ b/libukui-notification/ukui-notification-config.cmake.in @@ -0,0 +1,9 @@ +@PACKAGE_INIT@ + +include(CMakeFindDependencyMacro) +find_dependency(Qt@QT_VERSION_MAJOR@Core "@REQUIRED_QT_VERSION@") +if(TARGET Qt6::Core) + find_dependency(Qt6Core5Compat @REQUIRED_QT_VERSION@) +endif() + +include("${CMAKE_CURRENT_LIST_DIR}/ukui-notification-targets.cmake") \ No newline at end of file diff --git a/libukui-notification/ukui-notification.pc.in b/libukui-notification/ukui-notification.pc.in new file mode 100644 index 0000000..548e76e --- /dev/null +++ b/libukui-notification/ukui-notification.pc.in @@ -0,0 +1,11 @@ +prefix=/usr +exec_prefix=${prefix} +libdir=${prefix}/lib/@CMAKE_LIBRARY_ARCHITECTURE@ +includedir=${prefix}/include/ukui-notification + +Name: ukui-notification +Description: ukui-notification header files +URL: https://www.ukui.org/ +Version: @VERSION@ +Cflags: -I${includedir} +Libs: -L${libdir} -lukui-notification \ No newline at end of file diff --git a/libukui-notification/ukui-notification_global.h b/libukui-notification/ukui-notification_global.h new file mode 100644 index 0000000..be0e9f3 --- /dev/null +++ b/libukui-notification/ukui-notification_global.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef UKUINOTIFICATION_GLOBAL_H +#define UKUINOTIFICATION_GLOBAL_H + +#include + +#if defined(UKUINOTIFICATION_LIBRARY) +# define UKUINOTIFICATION_EXPORT Q_DECL_EXPORT +#else +# define UKUINOTIFICATION_EXPORT Q_DECL_IMPORT +#endif + +#endif // UKUINOTIFICATION_GLOBAL_H diff --git a/libukui-notification/utils.cpp b/libukui-notification/utils.cpp new file mode 100644 index 0000000..73bada9 --- /dev/null +++ b/libukui-notification/utils.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#include "utils.h" +#include +#include +#include +#include +using namespace UkuiNotification; +static UkuiSearch::ApplicationInfo s_applicationInfo; +QString Utils::desktopEntryFromPid(uint pid) +{ + QString desktop; + if(s_applicationInfo.tranPidToDesktopFp(pid, desktop)) { + return desktop; + } + return {}; +} + +QString Utils::displayFromPid(uint pid) +{ + QFile environFile(QStringLiteral("/proc/%1/environ").arg(QString::number(pid))); + if (environFile.open(QIODevice::ReadOnly | QIODevice::Text)) { + const QByteArray DISPLAY = KWindowSystem::isPlatformWayland() ? QByteArrayLiteral("WAYLAND_DISPLAY") : QByteArrayLiteral("DISPLAY"); + const auto lines = environFile.readAll().split('\0'); + for (const QByteArray &line : lines) { + const int equalsIdx = line.indexOf('='); + if (equalsIdx <= 0) { + continue; + } + const QByteArray key = line.left(equalsIdx); + if (key == DISPLAY) { + const QByteArray value = line.mid(equalsIdx + 1); + return value; + } + } + } + return {}; +} + +QString Utils::desktopEntryFromName(const QString& desktopFileName) +{ + QString desktopFilePathName; + s_applicationInfo.desktopFilePathFromName(desktopFileName, desktopFilePathName); + return desktopFilePathName; +} \ No newline at end of file diff --git a/libukui-notification/utils.h b/libukui-notification/utils.h new file mode 100644 index 0000000..d248884 --- /dev/null +++ b/libukui-notification/utils.h @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef UKUI_NOTIFICATION_UTILS_H +#define UKUI_NOTIFICATION_UTILS_H +#include +namespace UkuiNotification { +namespace Utils { + QString desktopEntryFromPid(uint pid); + QString displayFromPid(uint pid); + QString desktopEntryFromName(const QString& desktopFileName); +} +} +#endif //UKUI_NOTIFICATION_UTILS_H diff --git a/notification-server/CMakeLists.txt b/notification-server/CMakeLists.txt new file mode 100644 index 0000000..51aa61e --- /dev/null +++ b/notification-server/CMakeLists.txt @@ -0,0 +1,46 @@ +set(VERSION_MAJOR 1) +set(VERSION_MINOR 0) +set(VERSION_MICRO 0) +set(NOTIFICATION_SERVER_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_MICRO}) + +configure_file (notification-server-config.h.in notification-server-config.h @ONLY) +set(3rdParties_DIR ../3rd-parties/qtsingleapplication/src/) +set(notificationServer_SRCS + server.h + server-private.h + server.cpp + main.cpp + ${3rdParties_DIR}qtsinglecoreapplication.h + ${3rdParties_DIR}qtsinglecoreapplication.cpp + ${3rdParties_DIR}qtlocalpeer.h + ${3rdParties_DIR}qtlocalpeer.cpp + notification-server-application.cpp + notification-server-application.h + ) +if(COMMAND qt_add_dbus_adaptor) + qt_add_dbus_adaptor(notificationServer_SRCS ../dbus/org.freedesktop.Notifications.xml server-private.h NotificationServer::ServerPrivate) + qt_add_dbus_adaptor(notificationServer_SRCS ../dbus/org.ukui.NotificationServer.xml server-private.h NotificationServer::ServerPrivate) +else() + qt5_add_dbus_adaptor(notificationServer_SRCS ../dbus/org.freedesktop.Notifications.xml server-private.h NotificationServer::ServerPrivate) + qt5_add_dbus_adaptor(notificationServer_SRCS ../dbus/org.ukui.NotificationServer.xml server-private.h NotificationServer::ServerPrivate) +endif() +add_executable(ukui-notification-server ${notificationServer_SRCS}) +include_directories(../libukui-notification) +target_include_directories(ukui-notification-server PUBLIC ${3rdParties_DIR}) + +target_link_libraries(ukui-notification-server + PRIVATE + Qt${QT_VERSION_MAJOR}::Core + Qt${QT_VERSION_MAJOR}::DBus + Qt${QT_VERSION_MAJOR}::Network + ukui-notification + ) +set(TS_FILES ukui-notification_zh_CN.ts) +if(COMMAND qt_create_translation) + qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR}/translations ${TS_FILES}) +else() + qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR}/translations ${TS_FILES}) +endif() +set(DBUS_SERVICE_FILE data/org.freedesktop.Notifications.service) +install(TARGETS ukui-notification-server DESTINATION /usr/bin) +install(FILES ${DBUS_SERVICE_FILE} DESTINATION /usr/share/dbus-1/services) diff --git a/notification-server/data/org.freedesktop.Notifications.service b/notification-server/data/org.freedesktop.Notifications.service new file mode 100644 index 0000000..42ef202 --- /dev/null +++ b/notification-server/data/org.freedesktop.Notifications.service @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=org.freedesktop.Notifications +Exec=/usr/bin/ukui-notification-server \ No newline at end of file diff --git a/notification-server/main.cpp b/notification-server/main.cpp new file mode 100644 index 0000000..4aecda6 --- /dev/null +++ b/notification-server/main.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#include +#include +#include +#include "notification-server-application.h" + +int main(int argc, char *argv[]) +{ + +// QTranslator translator; +// const QStringList uiLanguages = QLocale::system().uiLanguages(); +// for (const QString &locale : uiLanguages) { +// const QString baseName = "ukui-notification_" + QLocale(locale).name(); +// if (translator.load(":/i18n/" + baseName)) { +// a.installTranslator(&translator); +// break; +// } +// } + NotificationServer::NotificationServerApplication app(argc, argv); + if(app.isRunning()) { + return 0; + } + return app.exec(); +} diff --git a/notification-server/notification-server-application.cpp b/notification-server/notification-server-application.cpp new file mode 100644 index 0000000..1ee2ed1 --- /dev/null +++ b/notification-server/notification-server-application.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#include +#include +#include "notification-server-application.h" +#include "notification-server-config.h" +#include "server.h" +using namespace NotificationServer; +NotificationServerApplication::NotificationServerApplication(int &argc, char **argv, const QString &applicationName) + : QtSingleCoreApplication(applicationName, argc, argv) +{ + setApplicationVersion(NOTIFICATION_SERVER_VERSION); + qApp->setProperty("IS_UKUI_NOTIFICATION_SERVER", true); + if (!this->isRunning()) { + connect(this, &QtSingleCoreApplication::messageReceived, [=](QString msg) { + this->parseCmd(msg, true); + }); + Server::self().init(); + } + parseCmd(arguments().join(" ").toUtf8(), !isRunning()); +} + +NotificationServerApplication::~NotificationServerApplication() +{ +} + +void NotificationServerApplication::parseCmd(QString msg, bool isPrimary) +{ + QCommandLineParser parser; + + parser.addHelpOption(); + parser.addVersionOption(); + + QCommandLineOption quitOption(QStringList()<<"q"<<"quit", tr("Quit notification server")); + parser.addOption(quitOption); + + if (isPrimary) { + const QStringList args = QString(msg).split(' '); + parser.process(args); + if (parser.isSet(quitOption)) { + qApp->quit(); + return; + } + } + else { + if (arguments().count() < 2) { + parser.showHelp(); + } + parser.process(arguments()); + sendMessage(msg); + } +} diff --git a/notification-server/notification-server-application.h b/notification-server/notification-server-application.h new file mode 100644 index 0000000..33f7295 --- /dev/null +++ b/notification-server/notification-server-application.h @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef UKUI_NOTIFICATION_NOTIFICATION_SERVER_APPLICATION_H +#define UKUI_NOTIFICATION_NOTIFICATION_SERVER_APPLICATION_H + +#include +#include "qtsinglecoreapplication.h" +namespace NotificationServer { +class NotificationServerApplication : public QtSingleCoreApplication +{ + Q_OBJECT +public: + NotificationServerApplication(int &argc, char *argv[], const QString &applicationName = "ukui-notification-server"); + ~NotificationServerApplication(); + +protected Q_SLOTS: + void parseCmd(QString msg, bool isPrimary); +}; +} + +#endif //UKUI_NOTIFICATION_NOTIFICATION_SERVER_APPLICATION_H diff --git a/notification-server/notification-server-config.h.in b/notification-server/notification-server-config.h.in new file mode 100644 index 0000000..610fa0b --- /dev/null +++ b/notification-server/notification-server-config.h.in @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef NOTIFICATION_SERVER_CONFIG_H_IN +#define NOTIFICATION_SERVER_CONFIG_H_IN + +#define VERSION_MAJOR "@VERSION_MAJOR@" +#define VERSION_MINOR "@VERSION_MINOR@" +#define VERSION_MICRO "@VERSION_MICRO@" +#define NOTIFICATION_SERVER_VERSION "@NOTIFICATION_SERVER_VERSION@" + +#endif // NOTIFICATION_SERVER_CONFIG_H_INNOTIFICATION_SERVER_VERSION \ No newline at end of file diff --git a/notification-server/server-private.h b/notification-server/server-private.h new file mode 100644 index 0000000..6b24283 --- /dev/null +++ b/notification-server/server-private.h @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef UKUI_NOTIFICATION_SERVER_PRIVATE_H +#define UKUI_NOTIFICATION_SERVER_PRIVATE_H +#include +#include +#include +class QDBusServiceWatcher; +namespace NotificationServer { +class Notification { + friend class ServerPrivate; + QString m_appName; + uint m_id = 0; + QString m_appIcon; + QString m_summary; + QString m_body; + QStringList m_actions; + QVariantMap m_hints; + int m_timeout; +}; +class ServerPrivate : public QObject, protected QDBusContext +{ + Q_OBJECT +//dbus interface +public: + QStringList GetCapabilities() const; + uint Notify(const QString &app_name, + uint replaces_id, + const QString &app_icon, + const QString &summary, + const QString &body, + const QStringList &actions, + const QVariantMap &hints, + int timeout); + void CloseNotification(uint id); + QString GetServerInformation(QString &vendor, QString &version, QString &spec_version) const; + + /** + * 注册成为通知中心客户端 + */ + void RegisterClient(); + /** + * 注销 + */ + void UnRegisterClient(); + /** + * 通知中心关闭通知 + * @param id 通知id + * @param reason 关闭原因 + */ + void CloseNotification(uint id, uint); + void InvokeAction(uint id, const QString &action_key); + void UpdateUnreadMessagesNumber(const QString &desktopEntry, uint number); +Q_SIGNALS: + void NotificationClosed(uint id, uint reason); + void ActionInvoked(uint id, const QString &actionKey); + void ActivationToken(uint id, const QString &ActivationToken); + void UnreadMessageNumberUpdated(const QString &desktopEntry, uint number); +public: + explicit ServerPrivate(QObject *parent = nullptr); + ~ServerPrivate() override; + bool init(); + + static QString notificationServiceName(); + static QString notificationServicePath(); + static QString notificationServiceInterface(); +private: + void sendCache(); + QDBusServiceWatcher *m_notificationWatchers = nullptr; + uint m_increasedNotificationId = 1; + QMap m_notificationsCache; +}; + + + +} // NotificationServer + +#endif //UKUI_NOTIFICATION_SERVER_PRIVATE_H diff --git a/notification-server/server.cpp b/notification-server/server.cpp new file mode 100644 index 0000000..0e672bb --- /dev/null +++ b/notification-server/server.cpp @@ -0,0 +1,222 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#include +#include +#include "server.h" +#include "server-private.h" +#include "notificationsadaptor.h" +#include "notificationserveradaptor.h" +#include "notification-server-config.h" +#include "utils.h" +#include "notification-close-reason.h" +#include "notification-settings/settings-manager.h" + +using namespace NotificationServer; + +ServerPrivate::ServerPrivate(QObject *parent) : QObject(parent), m_notificationWatchers(new QDBusServiceWatcher(this)) +{ + m_notificationWatchers->setConnection(QDBusConnection::sessionBus()); + m_notificationWatchers->setWatchMode(QDBusServiceWatcher::WatchForUnregistration); + connect(m_notificationWatchers, &QDBusServiceWatcher::serviceUnregistered, + m_notificationWatchers, &QDBusServiceWatcher::removeWatchedService); +} + +ServerPrivate::~ServerPrivate() = default; + +QStringList ServerPrivate::GetCapabilities() const +{ + return QStringList(); +} + +uint ServerPrivate::Notify(const QString &app_name, uint replaces_id, const QString &app_icon, const QString &summary, + const QString &body, const QStringList &actions, const QVariantMap &hints, int timeout) +{ + uint id = 0; + if(replaces_id > 0) { + id = replaces_id; + } else { + id = m_increasedNotificationId++; + } + + QVariantMap newHints = hints; + newHints.insert(QStringLiteral("x-ukui-createdTime"), QDateTime::currentDateTime().toString()); + + uint pid = 0; + QDBusReply pidReply = connection().interface()->servicePid(message().service()); + if(pidReply.isValid()) { + pid = pidReply.value(); + } + + if(newHints.value(QStringLiteral("x-ukui-display")).toString().isEmpty() && pid > 0) { + newHints.insert(QStringLiteral("x-ukui-display"), UkuiNotification::Utils::displayFromPid(pid)); + } + //如果desktop-entry只有文件名,需要获取全路径 + QString desktopEntry = newHints.value(QStringLiteral("desktop-entry")).toString(); + if(!desktopEntry.isEmpty()) { + desktopEntry = UkuiNotification::Utils::desktopEntryFromName(desktopEntry); + } + if(desktopEntry.isEmpty() && pid > 0) { + desktopEntry = UkuiNotification::Utils::desktopEntryFromPid(pid); + } + newHints.insert(QStringLiteral("desktop-entry"), desktopEntry); + + qDebug() << "New message received:" << app_name << id << app_icon << summary << body + << actions << hints << timeout << "new hints" << newHints; + if(m_notificationWatchers->watchedServices().isEmpty()) { + Notification notification; + notification.m_appName = app_name; + notification.m_id = id; + notification.m_appIcon = app_icon; + notification.m_summary = summary; + notification.m_body = body; + notification.m_actions = actions; + notification.m_hints = newHints; + m_notificationsCache.insert(id, notification); + return id; + } + for(const QString &service : m_notificationWatchers->watchedServices()) { + QDBusMessage msg = QDBusMessage::createMethodCall(service, + QStringLiteral("/NotificationClient"), + QStringLiteral("org.ukui.NotificationClient"), + QStringLiteral("Notify")); + msg.setArguments({app_name, id, app_icon, summary, body, actions, newHints, timeout}); + QDBusConnection::sessionBus().call(msg, QDBus::NoBlock); + } + return id; +} + +QString ServerPrivate::GetServerInformation(QString &vendor, QString &version, QString &spec_version) const +{ + vendor = QStringLiteral("Kylin"); + version = QLatin1String(NOTIFICATION_SERVER_VERSION); + spec_version = QStringLiteral("1.2"); + return QStringLiteral("UKUI"); +} + +void ServerPrivate::CloseNotification(uint id) +{ + for(const QString &service : m_notificationWatchers->watchedServices()) { + QDBusMessage msg = QDBusMessage::createMethodCall(service, + QStringLiteral("/NotificationClient"), + QStringLiteral("org.ukui.NotificationClient"), + QStringLiteral("CloseNotification")); + msg.setArguments({id, UkuiNotification::NotificationCloseReason::Revoked}); + QDBusConnection::sessionBus().call(msg, QDBus::NoBlock); + } +} + +bool ServerPrivate::init() +{ + new NotificationsAdaptor(this); + new NotificationServerAdaptor(this); + QDBusConnection conn = QDBusConnection::sessionBus(); + auto registration = conn.interface()->registerService(notificationServiceName(), + QDBusConnectionInterface::ReplaceExistingService, + QDBusConnectionInterface::DontAllowReplacement); + if (registration.value() != QDBusConnectionInterface::ServiceRegistered) { + qWarning() << "Failed to register Notification service on DBus!"; + return false; + } + if(!conn.registerObject(notificationServicePath(), this)) { + qWarning() << "Failed to register Notification DBus object!" << conn.lastError().message(); + return false; + } + UkuiNotification::SettingsManager::self(); + return true; +} + +QString ServerPrivate::notificationServiceName() +{ + return QStringLiteral("org.freedesktop.Notifications"); +} + +QString ServerPrivate::notificationServicePath() +{ + return QStringLiteral("/org/freedesktop/Notifications"); +} + +QString ServerPrivate::notificationServiceInterface() +{ + return QStringLiteral("org.freedesktop.Notifications");; +} + +void ServerPrivate::RegisterClient() +{ + m_notificationWatchers->addWatchedService(message().service()); + qDebug() << "Watched services:" << m_notificationWatchers->watchedServices(); + sendCache(); +} + +void ServerPrivate::UnRegisterClient() +{ + m_notificationWatchers->removeWatchedService(message().service()); +} + +void ServerPrivate::CloseNotification(uint id, uint reason) +{ + if(m_notificationsCache.contains(id)) { + m_notificationsCache.remove(id); + } + Q_EMIT NotificationClosed(id, reason); +} + +void ServerPrivate::InvokeAction(uint id, const QString &action_key) +{ + qDebug() << "InvokeAction" << id << action_key; + Q_EMIT ActionInvoked(id, action_key); +} + +void ServerPrivate::sendCache() +{ + for(const uint &id : m_notificationsCache.keys()) { + auto notification = m_notificationsCache.take(id); + for(const QString &service : m_notificationWatchers->watchedServices()) { + QDBusMessage msg = QDBusMessage::createMethodCall(service, + QStringLiteral("/NotificationClient"), + QStringLiteral("org.ukui.NotificationClient"), + QStringLiteral("Notify")); + msg.setArguments({notification.m_appName, notification.m_id, notification.m_appIcon, notification.m_summary, + notification.m_body, notification.m_actions, notification.m_hints, notification.m_timeout}); + QDBusConnection::sessionBus().call(msg, QDBus::NoBlock); + } + } +} + +void ServerPrivate::UpdateUnreadMessagesNumber(const QString &desktopEntry, uint number) +{ + Q_EMIT UnreadMessageNumberUpdated(desktopEntry, number); +} + +Server::Server(QObject *parent): QObject(parent), d(new ServerPrivate(this)) +{ +} + +Server &Server::self() +{ + static Server self; + return self; +} + +bool Server::init() +{ + return d->init(); +} + +Server::~Server() = default; diff --git a/notification-server/server.h b/notification-server/server.h new file mode 100644 index 0000000..716f221 --- /dev/null +++ b/notification-server/server.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef UKUI_NOTIFICATION_SERVER_H +#define UKUI_NOTIFICATION_SERVER_H +#include +namespace NotificationServer { +class ServerPrivate; +class Server : public QObject +{ + Q_OBJECT +public: + static Server &self(); + ~Server(); + bool init(); +private: + explicit Server(QObject *parent = nullptr); + Q_DISABLE_COPY(Server) + ServerPrivate *d = nullptr; +}; + +} // NotificationServer + +#endif //UKUI_NOTIFICATION_SERVER_H diff --git a/notification-server/translations/ukui-notification_zh_CN.ts b/notification-server/translations/ukui-notification_zh_CN.ts new file mode 100644 index 0000000..e5ca8aa --- /dev/null +++ b/notification-server/translations/ukui-notification_zh_CN.ts @@ -0,0 +1,4 @@ + + + + diff --git a/notification-ukcc-plugin/CMakeLists.txt b/notification-ukcc-plugin/CMakeLists.txt new file mode 100644 index 0000000..34d8367 --- /dev/null +++ b/notification-ukcc-plugin/CMakeLists.txt @@ -0,0 +1,49 @@ + +set(notification-ukcc-plugin_LIB_SRCS + notification-ukcc-plugin.cpp + notification-ukcc-plugin.h + notice-menu.cpp + notice-menu.h) + +find_package(QT NAMES Qt6 Qt5 COMPONENTS Core Widgets LinguistTools REQUIRED) +find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core Widgets LinguistTools REQUIRED) +find_package(PkgConfig REQUIRED) +set(UKUI_NOTIFICATION_EXTERNAL_LIBS "") +set(UKUI_NOTIFICATION_PC_PKGS kysdk-qtwidgets) + +foreach(PC_LIB IN ITEMS ${UKUI_NOTIFICATION_PC_PKGS}) + pkg_check_modules(${PC_LIB} REQUIRED ${PC_LIB}) + if(${${PC_LIB}_FOUND}) + include_directories(${${PC_LIB}_INCLUDE_DIRS}) + link_directories(${${PC_LIB}_LIBRARY_DIRS}) + list(APPEND UKUI_NOTIFICATION_EXTERNAL_LIBS ${${PC_LIB}_LIBRARIES}) + endif() +endforeach() + +include_directories(${Qt5Core_INCLUDE_DIRS} ${Qt5Widgets_INCLUDE_DIRS}) +include_directories(../libukui-notification/notification-settings) +include_directories(../libukui-notification) + + +file(GLOB TS_FILES "${PROJECT_SOURCE_DIR}/notification-ukcc-plugin/translations/*.ts") +qt5_add_translation(QM_FILES ${TS_FILES}) +#set(QM_FILES ${QM_FILES} PARENT_SCOPE) +add_custom_target(translations ALL DEPENDS ${QM_FILES}) + +add_library(notification-ukcc-plugin SHARED + ${notification-ukcc-plugin_LIB_SRCS} + ${QM_FILES} + ) + +target_link_libraries(notification-ukcc-plugin + PRIVATE + Qt${QT_VERSION_MAJOR}::Core + Qt${QT_VERSION_MAJOR}::DBus + Qt${QT_VERSION_MAJOR}::Network + ukui-notification + ukcc + ) + +install(TARGETS notification-ukcc-plugin DESTINATION /usr/lib/${CMAKE_LIBRARY_ARCHITECTURE}/ukui-control-center) +install(FILES ${TS_FILES} ${QM_FILES} DESTINATION /usr/share/ukui-notification/notification-ukcc-plugin/translations) + diff --git a/notification-ukcc-plugin/notice-menu.cpp b/notification-ukcc-plugin/notice-menu.cpp new file mode 100644 index 0000000..699e539 --- /dev/null +++ b/notification-ukcc-plugin/notice-menu.cpp @@ -0,0 +1,222 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 "notice-menu.h" +#include +#include +#include + +NoticeMenu::NoticeMenu(QWidget *parent) : + QMenu(parent) +{ + setFixedSize(380, 380); + initUi(); + setConnect(); +} + +void NoticeMenu::initStatus(UkuiNotification::SingleApplicationSettings *settings) +{ + m_voiceBtn->blockSignals(true); + m_showBtn->blockSignals(true); + m_detailBtn->blockSignals(true); + m_styleGroup->blockSignals(true); + + m_voiceBtn->setChecked(settings->allowSound()); + m_detailBtn->setChecked(settings->showContentOnLockScreen()); + m_showBtn->setChecked(settings->showNotificationOnLockScreen()); + +// int styleId = 0; +// UkuiNotification::SettingsProperty::Property style = settings->popupStyle(); +// if (style == UkuiNotification::SettingsProperty::TransientPopup) { +// styleId = 0; +// } else if (style == UkuiNotification::SettingsProperty::ResidentPopup) { +// styleId = 1; +// } else if (style == UkuiNotification::SettingsProperty::NoPopup) { +// styleId = 2; +// } +// m_styleGroup->button(styleId)->setChecked(true); + + m_voiceBtn->blockSignals(false); + m_showBtn->blockSignals(false); + m_detailBtn->blockSignals(false); + m_styleGroup->blockSignals(false); +} + +void NoticeMenu::setVoiceEnable(bool state) +{ + m_voiceBtn->blockSignals(true); + m_voiceBtn->setChecked(state); + m_voiceBtn->blockSignals(false); +} + +void NoticeMenu::setDetailShowOnLockScreenEnable(bool state) +{ + m_detailBtn->blockSignals(true); + m_detailBtn->setChecked(state); + m_detailBtn->blockSignals(false); +} + +void NoticeMenu::setShowOnLockScreenEnable(bool state) +{ + m_showBtn->blockSignals(true); + m_showBtn->setChecked(state); + m_showBtn->blockSignals(false); +} + +//void NoticeMenu::setPopupStyle(UkuiNotification::SettingsProperty::Property style) +//{ +// int styleId = 0; +// if (style == UkuiNotification::SettingsProperty::TransientPopup) { +// styleId = 0; +// } else if (style == UkuiNotification::SettingsProperty::ResidentPopup) { +// styleId = 1; +// } else if (style == UkuiNotification::SettingsProperty::NoPopup) { +// styleId = 2; +// } +// m_styleGroup->blockSignals(true); +// m_styleGroup->button(styleId)->setChecked(true); +// m_styleGroup->blockSignals(false); +//} + +void NoticeMenu::initUi() +{ + QVBoxLayout *menuLyt = new QVBoxLayout(this); + menuLyt->setSpacing(0); + menuLyt->setContentsMargins(8, 0, 8, 0); + + QFrame *voiceFrame = new QFrame(this); + m_voiceBtn = new KSwitchButton; + setFrame(voiceFrame, tr("Beep sound when notified"), m_voiceBtn); + + QFrame *line_1 = setLine(); + + QFrame *detailFrame = new QFrame(this); + m_detailBtn = new KSwitchButton; + setFrame(detailFrame, tr("Show message on screenlock"), m_detailBtn); + + QFrame *line_2 = setLine(); + + QFrame *showFrame = new QFrame(this); + m_showBtn = new KSwitchButton; + setFrame(showFrame, tr("Show noticfication on screenlock"), m_showBtn); + + QFrame *line_3 = setLine(); + +// QLabel *styletitleLabel = new QLabel(tr("Notification Style"), this); +// styletitleLabel->setContentsMargins(24, 0, 0, 0); +// +// m_styleGroup = new QButtonGroup(this); +// +// QFrame *mutativeFrame = new QFrame(this); +// m_mutativeBtn = new QRadioButton; +// m_styleGroup->addButton(m_mutativeBtn, 0); +// setFrame(mutativeFrame, tr("Banner: Appears in the upper right corner of the screen, and disappears automatically"), m_mutativeBtn); +// +// QFrame *alwaysFrame = new QFrame(this); +// m_alwaysBtn = new QRadioButton; +// m_styleGroup->addButton(m_alwaysBtn, 1); +// setFrame(alwaysFrame, tr("Tip:It will be kept on the screen until it is closed"), m_alwaysBtn); +// +// QFrame *noneFrame = new QFrame(this); +// m_noneBtn = new QRadioButton; +// m_styleGroup->addButton(m_noneBtn, 2); +// setFrame(noneFrame, tr("None:Notifications will not be displayed on the screen, but will go to the notification center"), m_noneBtn); + + menuLyt->addWidget(voiceFrame); + menuLyt->addWidget(line_1); + menuLyt->addWidget(detailFrame); + menuLyt->addWidget(line_2); + menuLyt->addWidget(showFrame); + menuLyt->addWidget(line_3); + menuLyt->addSpacing(16); +// menuLyt->addWidget(styletitleLabel); +// menuLyt->addWidget(mutativeFrame); +// menuLyt->addWidget(alwaysFrame); +// menuLyt->addWidget(noneFrame); + menuLyt->addStretch(); + + // 隐藏未实现模块 +// voiceFrame->hide(); +// line_1->hide(); +// detailFrame->hide(); +// line_2->hide(); +// line_3->hide(); +// styletitleLabel->hide(); +// mutativeFrame->hide(); +// alwaysFrame->hide(); +// noneFrame->hide(); +// setFixedHeight(60); + +} + +void NoticeMenu::setFrame(QFrame *frame, QString str, KSwitchButton *btn) +{ + frame->setFixedHeight(60); + frame->setFrameShape(QFrame::NoFrame); + QHBoxLayout *hLyt = new QHBoxLayout(frame); + hLyt->setContentsMargins(24, 0, 24, 0); + hLyt->setSpacing(8); + FixLabel *label = new FixLabel(str, frame); + label->setFixedWidth(250); + hLyt->addWidget(label); + hLyt->addStretch(); + hLyt->addWidget(btn); +} + +void NoticeMenu::setFrame(QFrame *frame, QString str, QRadioButton *btn) +{ + frame->setFixedHeight(48); + frame->setFrameShape(QFrame::NoFrame); + QHBoxLayout *hLyt = new QHBoxLayout(frame); + hLyt->setContentsMargins(24, 0, 24, 0); + FixLabel *label = new FixLabel(str, frame); + label->setFixedWidth(288); + hLyt->addWidget(btn); + hLyt->addWidget(label); + hLyt->addStretch(); +} + +QFrame *NoticeMenu::setLine() +{ + QFrame *line = new QFrame(); + line->setMinimumSize(QSize(0, 1)); + line->setMaximumSize(QSize(16777215, 1)); + line->setLineWidth(0); + line->setFrameShape(QFrame::HLine); + line->setFrameShadow(QFrame::Sunken); + return line; +} + +void NoticeMenu::setConnect() +{ + connect(m_voiceBtn, &KSwitchButton::stateChanged, this, &NoticeMenu::voiceSignals); + connect(m_detailBtn, &KSwitchButton::stateChanged, this, &NoticeMenu::detailSignals); + connect(m_showBtn, &KSwitchButton::stateChanged, this, &NoticeMenu::showSignals); + connect(m_styleGroup, QOverload::of(&QButtonGroup::buttonClicked), this, &NoticeMenu::styleBtnSignals); +} + +void NoticeMenu::showEvent(QShowEvent *event) +{ + int menuXPos = this->pos().x(); + int menuWidth = this->size().width()-4; + int buttonWidth = 36; + QPoint pos = QPoint(menuXPos - menuWidth + buttonWidth, + this->pos().y()); + this->move(pos); + QMenu::showEvent(event); +} diff --git a/notification-ukcc-plugin/notice-menu.h b/notification-ukcc-plugin/notice-menu.h new file mode 100644 index 0000000..27ce6a9 --- /dev/null +++ b/notification-ukcc-plugin/notice-menu.h @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + */ + +#ifndef NOTICEMENU_H +#define NOTICEMENU_H + +#include +#include +#include +#include +#include + +#include +#include "applications-settings.h" + +using namespace kdk; + +class NoticeMenu : public QMenu +{ + Q_OBJECT +public: + explicit NoticeMenu(QWidget *parent = nullptr); + + void initStatus(UkuiNotification::SingleApplicationSettings *settings); + void setVoiceEnable(bool state); + void setDetailShowOnLockScreenEnable(bool state); + void setShowOnLockScreenEnable(bool state); + void setPopupStyle(UkuiNotification::SettingsProperty::Property style); + + static QFrame *setLine(); + +private: + void initUi(); + void setFrame(QFrame *frame, QString str, KSwitchButton *btn); + void setFrame(QFrame *frame, QString str, QRadioButton *btn); + void setConnect(); + +private: + KSwitchButton *m_voiceBtn = nullptr; + KSwitchButton *m_detailBtn = nullptr; + KSwitchButton *m_showBtn = nullptr; + QButtonGroup *m_styleGroup = nullptr; + QRadioButton *m_noneBtn = nullptr; + QRadioButton *m_mutativeBtn = nullptr; + QRadioButton *m_alwaysBtn = nullptr; + +protected: + void showEvent(QShowEvent *event) override; + +Q_SIGNALS: + void voiceSignals(bool checked); + void detailSignals(bool checked); + void showSignals(bool checked); + void styleBtnSignals(int id); +}; + +#endif // NOTICEMENU_H diff --git a/notification-ukcc-plugin/notification-ukcc-plugin.cpp b/notification-ukcc-plugin/notification-ukcc-plugin.cpp new file mode 100644 index 0000000..2d024d0 --- /dev/null +++ b/notification-ukcc-plugin/notification-ukcc-plugin.cpp @@ -0,0 +1,633 @@ + +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 "notification-ukcc-plugin.h" +#include "notice-menu.h" +#include +#include +#include +#include +#include +#include +#include + +#define THEME_QT_SCHEMA "org.ukui.style" + +class ToolButton : public QToolButton +{ +public: + explicit ToolButton(QWidget *parent = nullptr): + QToolButton(parent) + { + } + +protected: + void paintEvent(QPaintEvent *event) override; +}; + +Notice::Notice() +{ + QTranslator* translator = new QTranslator(this); + if(!translator->load("/usr/share/ukui-notification/notification-ukcc-plugin/translations/" + QLocale::system().name())) { + qWarning() << "/usr/share/ukui-notification/notification-ukcc-plugin/translations/" + QLocale::system().name() << "load failed"; + } + QApplication::installTranslator(translator); + + m_pluginName = tr("Notice"); + m_pluginType = SYSTEM; + + if (QGSettings::isSchemaInstalled(THEME_QT_SCHEMA)) { + QByteArray id(THEME_QT_SCHEMA); + m_themeSetting = new QGSettings(id, QByteArray(), this); + } + if (!m_globalSettings) { + m_globalSettings = new UkuiNotification::NotificationGlobalSettings(); + } + if (!m_appInfo) { + m_appInfo = new UkuiSearch::ApplicationInfo(); + } + + m_pluginWidget = new QWidget; + m_pluginWidget->setAttribute(Qt::WA_DeleteOnClose); + + initUi(m_pluginWidget); + initSearchText(); + initNoticeStatus(); + initConnection(); + initListUI(); +} + +Notice::~Notice() +{ + if (m_globalSettings) { + delete m_globalSettings; + m_globalSettings = nullptr; + } + if (m_appInfo) { + delete m_appInfo; + m_appInfo = nullptr; + } + +} + +QString Notice::plugini18nName() +{ + return m_pluginName; +} + +int Notice::pluginTypes() +{ + return m_pluginType; +} + +QWidget *Notice::pluginUi() +{ + return m_pluginWidget; +} + +const QString Notice::name() const +{ + return QStringLiteral("Notice"); +} + +QString Notice::translationPath() const +{ + return QStringLiteral("/usr/share/ukui-notification/notification-ukcc-plugin/translations/%1.ts"); +} + +bool Notice::isShowOnHomePage() const +{ + return false; +} + +QIcon Notice::icon() const +{ + return QIcon::fromTheme("ukui-tool-symbolic"); +} + +bool Notice::isEnable() const +{ + return true; +} + +void Notice::initUi(QWidget *widget) +{ + QVBoxLayout *mverticalLayout = new QVBoxLayout(widget); + mverticalLayout->setSpacing(0); + mverticalLayout->setContentsMargins(0, 0, 0, 0); + + QFrame *notFazeFrame = new QFrame(widget); + initNotFaze(notFazeFrame); + + QWidget *Noticewidget = new QWidget(widget); + Noticewidget->setMinimumSize(QSize(550, 0)); + Noticewidget->setMaximumSize(QSize(16777215, 16777215)); + + QVBoxLayout *NoticeLayout = new QVBoxLayout(Noticewidget); + NoticeLayout->setContentsMargins(0, 0, 0, 0); + NoticeLayout->setSpacing(8); + + m_noticeLabel = new TitleLabel(Noticewidget); + m_notFazeLabel = new TitleLabel(); + m_notFazeLabel->setText(tr("NotFaze Mode")); + + LightLabel *notFazeLabel = new LightLabel(tr("(Notification banners, prompts will be hidden, and notification sounds will be muted)")); + QFrame *distrubFrame = new QFrame(widget); + distrubFrame->setMinimumWidth(550); + distrubFrame->setMaximumWidth(16777215); + + QHBoxLayout *distrubLyt = new QHBoxLayout(distrubFrame); + distrubLyt->setContentsMargins(0, 0, 0, 0); + distrubLyt->addWidget(m_notFazeLabel); + distrubLyt->addSpacing(4); + distrubLyt->addWidget(notFazeLabel, Qt::AlignLeft); + + m_getNoticeFrame = new QFrame(Noticewidget); + m_getNoticeFrame->setMinimumSize(QSize(550, 60)); + m_getNoticeFrame->setMaximumSize(QSize(16777215, 60)); + m_getNoticeFrame->setFrameShape(QFrame::Box); + + QHBoxLayout *mGetNoticeLayout = new QHBoxLayout(m_getNoticeFrame); + mGetNoticeLayout->setContentsMargins(16,0,16,0); + + m_getNoticeLabel = new QLabel(m_getNoticeFrame); + m_getNoticeLabel->setFixedWidth(550); + m_enableSwitchBtn = new KSwitchButton(m_getNoticeFrame); + m_enableSwitchBtn->setObjectName("getnoticeinfo"); + + mGetNoticeLayout->addWidget(m_getNoticeLabel,Qt::AlignLeft); + mGetNoticeLayout->addStretch(); + mGetNoticeLayout->addWidget(m_enableSwitchBtn); + + m_noticeAppFrame = new QFrame(Noticewidget); + m_noticeAppFrame->setMinimumSize(QSize(550, 0)); + m_noticeAppFrame->setMaximumSize(QSize(16777215, 16777215)); + m_noticeAppFrame->setFrameShape(QFrame::Box); + + m_appListVerticalLayout = new QVBoxLayout(m_noticeAppFrame); + m_appListVerticalLayout->setContentsMargins(0, 0, 0, 0); + m_appListVerticalLayout->setSpacing(0); + + NoticeLayout->addWidget(m_noticeLabel); + NoticeLayout->addWidget(m_getNoticeFrame); + NoticeLayout->addWidget(m_noticeAppFrame); + + if (1) { + mverticalLayout->addWidget(distrubFrame); + mverticalLayout->addSpacing(8); + mverticalLayout->addWidget(notFazeFrame); + mverticalLayout->addSpacing(32); + } else { + distrubFrame->hide(); + notFazeFrame->hide(); + } + mverticalLayout->addWidget(Noticewidget); + mverticalLayout->addStretch(); + +} + +void Notice::initNotFaze(QFrame *frame) +{ + frame->setMinimumSize(QSize(550, 0)); + frame->setMaximumSize(QSize(16777215, 16777215)); + frame->setFrameShape(QFrame::Box); + + QVBoxLayout *notFazeLyt = new QVBoxLayout(frame); + notFazeLyt->setContentsMargins(0, 0, 0, 0); + notFazeLyt->setSpacing(0); + + QFrame *line_1 = NoticeMenu::setLine(); + QFrame *line_2 = NoticeMenu::setLine(); + QFrame *line_3 = NoticeMenu::setLine(); + + QFrame *autoOpenFrame = new QFrame(frame); + autoOpenFrame->setMinimumSize(550, 60); + autoOpenFrame->setMaximumSize(16777215, 60); + QHBoxLayout *autoLyt = new QHBoxLayout(autoOpenFrame); + autoLyt->setContentsMargins(16, 0, 16, 0); + QLabel *autoOpenLabel = new QLabel(tr("Automatically turn on"), autoOpenFrame); + m_openTimeHComboBox = new QComboBox(autoOpenFrame); + m_openTimeHComboBox->setObjectName("opentimehour"); + m_openTimeHComboBox->setFixedWidth(64); + m_openTimeMComboBox = new QComboBox(autoOpenFrame); + m_openTimeMComboBox->setObjectName("opentimeminute"); + m_openTimeMComboBox->setFixedWidth(64); + m_closeTimeHComboBox = new QComboBox(autoOpenFrame); + m_closeTimeHComboBox->setObjectName("closetimehour"); + m_closeTimeHComboBox->setFixedWidth(64); + m_closeTimeMComboBox = new QComboBox(autoOpenFrame); + m_closeTimeMComboBox->setObjectName("closetimeminute"); + m_closeTimeMComboBox->setFixedWidth(64); + for (int i = 0; i < 24; i++) { + m_openTimeHComboBox->addItem(QStringLiteral("%1").arg(i, 2, 10, QLatin1Char('0'))); + m_closeTimeHComboBox->addItem(QStringLiteral("%1").arg(i, 2, 10, QLatin1Char('0'))); + } + + for (int i = 0; i < 60; i++) { + m_openTimeMComboBox->addItem(QStringLiteral("%1").arg(i, 2, 10, QLatin1Char('0'))); + m_closeTimeMComboBox->addItem(QStringLiteral("%1").arg(i, 2, 10, QLatin1Char('0'))); + } + + QLabel * label_1 = new QLabel(autoOpenFrame); + label_1->setFixedWidth(20); + label_1->setText(tr("to")); + QLabel *label_2 = new QLabel(autoOpenFrame); + label_2->setFixedWidth(4); + label_2->setText(":"); + QLabel *label_3 = new QLabel(autoOpenFrame); + label_3->setFixedWidth(4); + label_3->setText(":"); + m_autoOpenSwitchBtn = new KSwitchButton(autoOpenFrame); + m_autoOpenSwitchBtn->setObjectName("autoopen"); + + autoLyt->addWidget(autoOpenLabel); + autoLyt->addStretch(); + autoLyt->addWidget(m_openTimeHComboBox); + autoLyt->addWidget(label_2); + autoLyt->addWidget(m_openTimeMComboBox); + autoLyt->addWidget(label_1); + autoLyt->addWidget(m_closeTimeHComboBox); + autoLyt->addWidget(label_3); + autoLyt->addWidget(m_closeTimeMComboBox); + autoLyt->addSpacing(24); + autoLyt->addWidget(m_autoOpenSwitchBtn); + + QFrame *multiScreenFrame = new QFrame(frame); + m_multiScreenSwitchBtn= new KSwitchButton(); + m_multiScreenSwitchBtn->setObjectName("multiscreen"); + setFrame(multiScreenFrame, m_multiScreenSwitchBtn, tr("Automatically turn on when multiple screens are connected")); + + QFrame *fullScreenFrame = new QFrame(frame); + m_fullScreenSwitchBtn= new KSwitchButton(); + m_fullScreenSwitchBtn->setObjectName("fullscreen"); + setFrame(fullScreenFrame, m_fullScreenSwitchBtn, tr("Automatically open in full screen mode")); + + QFrame *allowAlarmrRemindersFrame = new QFrame(frame); + m_allowAlarmSwitchBtn= new KSwitchButton(); + m_allowAlarmSwitchBtn->setObjectName("allowAlarmr"); + setFrame(allowAlarmrRemindersFrame, m_allowAlarmSwitchBtn, tr("Allow automatic alarm reminders in Do Not Disturb mode")); + + notFazeLyt->addWidget(autoOpenFrame); + notFazeLyt->addWidget(line_1); + notFazeLyt->addWidget(multiScreenFrame); + notFazeLyt->addWidget(line_2); + notFazeLyt->addWidget(fullScreenFrame); + notFazeLyt->addWidget(line_3); + notFazeLyt->addWidget(allowAlarmrRemindersFrame); +} + +void Notice::setFrame(QFrame *frame, KSwitchButton *btn, QString str) +{ + frame->setMinimumSize(QSize(550, 60)); + frame->setMaximumSize(QSize(16777215, 60)); + frame->setFrameShape(QFrame::NoFrame); + + QHBoxLayout *hLyt = new QHBoxLayout(frame); + hLyt->setContentsMargins(16, 0, 16, 0); + QLabel *label = new QLabel(str, frame); + + hLyt->addWidget(label); + hLyt->addStretch(); + hLyt->addWidget(btn); +} + + +void Notice::initSearchText() +{ + m_noticeLabel->setText(tr("Notice Settings")); + //~ contents_path /notice/Get notifications from the app + m_getNoticeLabel->setText(tr("Get notifications from the app")); +} + +void Notice::initConnection() +{ + if (m_globalSettings) { + connect(m_openTimeHComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, [&](const QString &text){ + //Utils::buriedSettings(name(), "open time(hour) when auto turn on do not disturb mode", QString("settings"), text); + m_globalSettings->setScheduleTurnOnDNDTime(QTime::fromString(text + ":" + m_openTimeMComboBox->currentText(), "hh:mm")); + }); + + connect(m_openTimeMComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, [&](const QString &text){ + //Utils::buriedSettings(name(), "open time(minute) when auto turn on do not disturb mode", QString("settings"), m_openTimeMCombox->currentText()); + m_globalSettings->setScheduleTurnOnDNDTime(QTime::fromString(text + m_openTimeHComboBox->currentText(), "mm:hh")); + }); + + connect(m_closeTimeHComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, [&](const QString &text){ + //Utils::buriedSettings(name(), "close time(hour) when auto turn on do not disturb mode", QString("settings"), m_closeTimeMCombox->currentText()); + m_globalSettings->setScheduleTurnOffDNDTime(QTime::fromString(text + ":" + m_closeTimeMComboBox->currentText(), "hh:mm")); + }); + + connect(m_closeTimeMComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, [&](const QString &text){ + //Utils::buriedSettings(name(), "close time(minute) when auto turn on do not disturb mode", QString("settings"), m_closeTimeMCombox->currentText()); + m_globalSettings->setScheduleTurnOffDNDTime(QTime::fromString(text + ":" + m_closeTimeHComboBox->currentText(), "mm:hh")); + }); + + connect(m_autoOpenSwitchBtn, &KSwitchButton::stateChanged, [&](bool state) { + //Utils::buriedSettings(name(), "whether auto turn on do not disturb mode", QString("settings"), state ? "true" : "false"); + m_globalSettings->setScheduleTurnOnDND(state); + setComBoxStatus(state); + }); + connect(m_multiScreenSwitchBtn, &KSwitchButton::stateChanged, [&](bool state) { + //Utils::buriedSettings(name(), "whether auto turn on do not disturb mode", QString("settings"), state ? "true" : "false"); + m_globalSettings->setDNDWhileMultiScreen(state); + }); + connect(m_fullScreenSwitchBtn, &KSwitchButton::stateChanged, [&](bool state) { + //Utils::buriedSettings(name(), "whether auto turn on do not disturb mode", QString("settings"), state ? "true" : "false"); + m_globalSettings->setDNDWhileFullScreen(state); + }); + connect(m_allowAlarmSwitchBtn, &KSwitchButton::stateChanged, [&](bool state) { + //Utils::buriedSettings(name(), "whether auto turn on do not disturb mode", QString("settings"), state ? "true" : "false"); + m_globalSettings->setNotifyAlarmWhileDND(state); + }); + connect(m_enableSwitchBtn, &KSwitchButton::stateChanged, [&](bool state){ + //Utils::buriedSettings(name(), "whether to get the notification from the app", QString("settings"), state ? "true" : "false"); + m_globalSettings->setReceiveNotificationsFromApps(state); + setHiddenNoticeApp(state); + }); + + + connect(m_globalSettings, &UkuiNotification::NotificationGlobalSettings::scheduleTurnOnDNDChanged, this, [&](bool state) { + m_autoOpenSwitchBtn->blockSignals(true); + m_autoOpenSwitchBtn->setChecked(state); + m_autoOpenSwitchBtn->blockSignals(false); + setComBoxStatus(state); + }); + connect(m_globalSettings, &UkuiNotification::NotificationGlobalSettings::scheduleTurnOnDNDTimeChanged, this, [&](QTime time) { + m_openTimeHComboBox->blockSignals(true); + m_openTimeHComboBox->setCurrentText(time.toString("hh")); + m_openTimeHComboBox->blockSignals(false); + + m_openTimeMComboBox->blockSignals(true); + m_openTimeMComboBox->setCurrentText(time.toString("mm")); + m_openTimeMComboBox->blockSignals(false); + }); + connect(m_globalSettings, &UkuiNotification::NotificationGlobalSettings::scheduleTurnOffDNDTimeChanged, this, [&](QTime time) { + m_closeTimeHComboBox->blockSignals(true); + m_closeTimeHComboBox->setCurrentText(time.toString("hh")); + m_closeTimeHComboBox->blockSignals(false); + + m_closeTimeMComboBox->blockSignals(true); + m_closeTimeMComboBox->setCurrentText(time.toString("mm")); + m_closeTimeMComboBox->blockSignals(false); + }); + connect(m_globalSettings, &UkuiNotification::NotificationGlobalSettings::DNDWhileMultiScreenChanged, this, [&](bool state) { + m_multiScreenSwitchBtn->blockSignals(true); + m_multiScreenSwitchBtn->setChecked(state); + m_multiScreenSwitchBtn->blockSignals(false); + }); + connect(m_globalSettings, &UkuiNotification::NotificationGlobalSettings::DNDWhileFullScreenChanged, this, [&](bool state) { + m_fullScreenSwitchBtn->blockSignals(true); + m_fullScreenSwitchBtn->setChecked(state); + m_fullScreenSwitchBtn->blockSignals(false); + }); + connect(m_globalSettings, &UkuiNotification::NotificationGlobalSettings::notifyAlarmWhileDNDChanged, this, [&](bool state) { + m_allowAlarmSwitchBtn->blockSignals(true); + m_allowAlarmSwitchBtn->setChecked(state); + m_allowAlarmSwitchBtn->blockSignals(false); + }); + connect(m_globalSettings, &UkuiNotification::NotificationGlobalSettings::receiveNotificationsFromAppsChanged, this, [&](bool state) { + m_enableSwitchBtn->blockSignals(true); + m_enableSwitchBtn->setChecked(state); + m_enableSwitchBtn->blockSignals(false); + setHiddenNoticeApp(state); + }); + } + +} + +void Notice::initNoticeStatus() +{ + if (m_globalSettings) { + m_autoOpenSwitchBtn->blockSignals(true); + m_autoOpenSwitchBtn->setChecked(m_globalSettings->scheduleTurnOnDND()); + setComBoxStatus(m_autoOpenSwitchBtn->isChecked()); + m_autoOpenSwitchBtn->blockSignals(false); + + QTime openTime = m_globalSettings->scheduleTurnOnDNDTime(); + m_openTimeHComboBox->blockSignals(true); + m_openTimeHComboBox->setCurrentText(openTime.toString("hh")); + m_openTimeHComboBox->blockSignals(false); + m_openTimeMComboBox->blockSignals(true); + m_openTimeMComboBox->setCurrentText(openTime.toString("mm")); + m_openTimeMComboBox->blockSignals(false); + + QTime closeTime = m_globalSettings->scheduleTurnOffDNDTime(); + m_closeTimeHComboBox->blockSignals(true); + m_closeTimeHComboBox->setCurrentText(closeTime.toString("hh")); + m_closeTimeHComboBox->blockSignals(false); + m_closeTimeMComboBox->blockSignals(true); + m_closeTimeMComboBox->setCurrentText(closeTime.toString("mm")); + m_closeTimeMComboBox->blockSignals(false); + + m_multiScreenSwitchBtn->blockSignals(true); + m_multiScreenSwitchBtn->setChecked(m_globalSettings->DNDWhileMultiScreen()); + m_multiScreenSwitchBtn->blockSignals(false); + m_fullScreenSwitchBtn->blockSignals(true); + m_fullScreenSwitchBtn->setChecked(m_globalSettings->DNDWhileFullScreen()); + m_fullScreenSwitchBtn->blockSignals(false); + m_allowAlarmSwitchBtn->blockSignals(true); + m_allowAlarmSwitchBtn->setChecked(m_globalSettings->notifyAlarmWhileDND()); + m_allowAlarmSwitchBtn->blockSignals(false); + m_enableSwitchBtn->blockSignals(true); + m_enableSwitchBtn->setChecked(m_globalSettings->receiveNotificationsFromApps()); + m_enableSwitchBtn->blockSignals(false); + } + + setHiddenNoticeApp(m_enableSwitchBtn->isChecked()); +} + +void Notice::initListUI() +{ + UkuiNotification::ApplicationsSettingsMap appDataMap = UkuiNotification::ApplicationsSettings::self()->getAllApplicationsSettings(); + UkuiNotification::ApplicationsSettingsMap::const_iterator i = appDataMap.constBegin(); + while(i != appDataMap.constEnd()) { + initItemUi(i.key(), i.value()); + ++i; + } +} + +void Notice::initItemUi(const QString &desktopPath, UkuiNotification::SingleApplicationSettings *settings) +{ + QString localName = m_appInfo->getInfo(desktopPath, UkuiSearch::ApplicationProperty::LocalName).toString(); + QString iconName = m_appInfo->getInfo(desktopPath, UkuiSearch::ApplicationProperty::Icon).toString(); + QString fileName = desktopPath.left(desktopPath.indexOf(QLatin1Char('.'))); + + QFrame *baseWidget = new QFrame(m_noticeAppFrame); + baseWidget->setMinimumWidth(550); + baseWidget->setMaximumWidth(16777215); + baseWidget->setFixedHeight(60); + baseWidget->setFrameShape(QFrame::Shape::NoFrame); + baseWidget->setAttribute(Qt::WA_DeleteOnClose); + + QLabel *iconLabel = new QLabel(baseWidget); + iconLabel->setFixedSize(32, 32); + + setAppIcon(iconLabel, iconName); + connect(m_themeSetting, &QGSettings::changed, [&](const QString &key){ + if (key == "iconThemeName") + setAppIcon(iconLabel, iconName); + }); + + QHBoxLayout *devHorLayout = new QHBoxLayout(baseWidget); + devHorLayout->setSpacing(8); + devHorLayout->setContentsMargins(16, 0, 16, 0); + + QLabel *nameLabel = new QLabel(baseWidget); + nameLabel->setText(localName); + + ToolButton *setBtn = new ToolButton(baseWidget); + setBtn->setProperty("useButtonPalette", true); + setBtn->setPopupMode(QToolButton::InstantPopup); + setBtn->setFixedSize(QSize(36, 36)); + setBtn->setIcon(QIcon::fromTheme("view-more-horizontal-symbolic")); + + NoticeMenu *menu = new NoticeMenu(setBtn); + setBtn->setMenu(menu); + + KSwitchButton *appSwitch = new KSwitchButton(baseWidget); + + devHorLayout->addWidget(iconLabel); + devHorLayout->addWidget(nameLabel); + devHorLayout->addStretch(); + devHorLayout->addWidget(setBtn); + devHorLayout->addWidget(appSwitch); + + m_appListVerticalLayout->addWidget(baseWidget); + if (m_appListVerticalLayout->count() >= 2) { + QFrame *line = new QFrame(m_pluginWidget); + line->setMinimumSize(QSize(0, 1)); + line->setMaximumSize(QSize(16777215, 1)); + line->setLineWidth(0); + line->setFrameShape(QFrame::HLine); + line->setFrameShadow(QFrame::Sunken); + m_appListVerticalLayout->insertWidget(m_appListVerticalLayout->count() - 1, line); + } + + + appSwitch->blockSignals(true); + appSwitch->setChecked(settings->allowNotify()); + appSwitch->blockSignals(false); + + menu->blockSignals(true); + menu->initStatus(settings); + menu->blockSignals(false); + + connect(appSwitch, &KSwitchButton::stateChanged, [=](bool state) { + //Utils::buriedSettings(name(), "whether auto turn on do not disturb mode", QString("settings"), state ? "true" : "false"); + UkuiNotification::ApplicationsSettings::self()->setAppSetting(desktopPath, UkuiNotification::SettingsProperty::AllowNotify, state); + }); + + connect(settings, &UkuiNotification::SingleApplicationSettings::allowNotifyChanged, [=](bool state) { + appSwitch->blockSignals(true); + appSwitch->setChecked(state); + appSwitch->blockSignals(false); + }); + connect(settings, &UkuiNotification::SingleApplicationSettings::allowSoundChanged, [=](bool state) { + menu->blockSignals(true); + menu->setVoiceEnable(state); + menu->blockSignals(false); + }); + connect(settings, &UkuiNotification::SingleApplicationSettings::showContentOnLockScreenChanged, [=](bool state) { + menu->blockSignals(true); + menu->setDetailShowOnLockScreenEnable(state); + menu->blockSignals(false); + }); + connect(settings, &UkuiNotification::SingleApplicationSettings::showNotificationOnLockScreenChanged, [=](bool state) { + menu->blockSignals(true); + menu->setShowOnLockScreenEnable(state); + menu->blockSignals(false); + }); + connect(settings, &UkuiNotification::SingleApplicationSettings::popupStyleChanged, [=](UkuiNotification::SettingsProperty::Property style) { + menu->blockSignals(true); + menu->setPopupStyle(style); + menu->blockSignals(false); + }); + connect(settings, &UkuiNotification::SingleApplicationSettings::uninstalled, [=]() { + baseWidget->hide(); + }); + + + connect(menu, &NoticeMenu::voiceSignals, [=](bool checked) { + //Common::buriedSettings(name(), "whether prompt sound during notification", QString("settings"), checked ? "true" : "false"); + UkuiNotification::ApplicationsSettings::self()->setAppSetting(desktopPath, UkuiNotification::SettingsProperty::AllowSound, checked); + }); + + connect(menu, &NoticeMenu::detailSignals, [=](bool checked) { + //Common::buriedSettings(name(), "whether to show the message content in the lock screen interface", QString("settings"), checked ? "true" : "false"); + UkuiNotification::ApplicationsSettings::self()->setAppSetting(desktopPath, UkuiNotification::SettingsProperty::ShowContentOnLockScreen, checked); + }); + + connect(menu, &NoticeMenu::showSignals, [=](bool checked) { + //Common::buriedSettings(name(), "whether to show the notice in the lock screen interface", QString("settings"), checked ? "true" : "false"); + UkuiNotification::ApplicationsSettings::self()->setAppSetting(desktopPath, UkuiNotification::SettingsProperty::ShowNotificationOnLockScreen, checked); + }); + +// connect(menu, &NoticeMenu::styleBtnSignals, [=](int id) { +// QString str("mutative"); +// UkuiNotification::SettingsProperty::Property style = UkuiNotification::SettingsProperty::TransientPopup; +// if (id == 0) { +// str = "mutative"; +// style = UkuiNotification::SettingsProperty::TransientPopup; +// } else if (id == 1) { +// str = "always"; +// style = UkuiNotification::SettingsProperty::ResidentPopup; +// } else if (id == 2) { +// str = "none"; +// style = UkuiNotification::SettingsProperty::NoPopup; +// } +// //Common::buriedSettings(name(), "set notice style", QString("settings"), str); +// UkuiNotification::ApplicationsSettings::self()->setAppSetting(desktopPath, UkuiNotification::SettingsProperty::PopupStyle, style); +// }); +} + +void Notice::setAppIcon(QLabel *iconlabel, const QString &icon) +{ + QFileInfo iconFile(QString("/usr/share/pixmaps/" + icon + ".png")); + QPixmap pixmap; + QIcon currentIcon = QIcon::fromTheme(icon); + if (!currentIcon.isNull()) { + pixmap = currentIcon.pixmap(QSize(32, 32)); + } else if (iconFile.exists()) { + pixmap = QPixmap(iconFile.filePath()).scaled(32, 32); + } else { + pixmap = QPixmap(QString(":/img/plugins/autoboot/desktop.png")); + } + iconlabel->setPixmap(pixmap); +} + +void Notice::setHiddenNoticeApp(bool status) +{ + m_noticeAppFrame->setVisible(status); +} + +void Notice::setComBoxStatus(bool status) +{ + m_openTimeHComboBox->setEnabled(status); + m_closeTimeHComboBox->setEnabled(status); + m_openTimeMComboBox->setEnabled(status); + m_closeTimeMComboBox->setEnabled(status); +} + +void ToolButton::paintEvent(QPaintEvent *event) +{ + QPalette palette; + palette.setColor(QPalette::Button, palette.base().color()); + this->setPalette(palette); + QToolButton::paintEvent(event); +} diff --git a/notification-ukcc-plugin/notification-ukcc-plugin.h b/notification-ukcc-plugin/notification-ukcc-plugin.h new file mode 100644 index 0000000..1b4fa8f --- /dev/null +++ b/notification-ukcc-plugin/notification-ukcc-plugin.h @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + */ + +#ifndef NOTIFICATION_UKCC_PLUGIN_H +#define NOTIFICATION_UKCC_PLUGIN_H + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include "applications-settings.h" +#include "notification-global-settings.h" + +using namespace kdk; + +class Notice : public QObject, CommonInterface +{ + Q_OBJECT + Q_PLUGIN_METADATA(IID "org.ukcc.CommonInterface") + Q_INTERFACES(CommonInterface) + +public: + Notice(); + ~Notice(); + + QString plugini18nName() Q_DECL_OVERRIDE; + int pluginTypes() Q_DECL_OVERRIDE; + QWidget * pluginUi() Q_DECL_OVERRIDE; + const QString name() const Q_DECL_OVERRIDE; + QString translationPath() const override; + bool isShowOnHomePage() const Q_DECL_OVERRIDE; + QIcon icon() const Q_DECL_OVERRIDE; + bool isEnable() const Q_DECL_OVERRIDE; + + void initUi(QWidget *widget); + void initNotFaze(QFrame *frame); + void setFrame(QFrame *frame, KSwitchButton *btn, QString str); + void initSearchText(); + void initConnection(); + void initNoticeStatus(); + void initListUI(); + void initItemUi(const QString &desktopPath, UkuiNotification::SingleApplicationSettings *settings); + void setAppIcon(QLabel *iconlabel, const QString &icon); + +private: + void setHiddenNoticeApp(bool status); + void setComBoxStatus(bool status); + +private: + QString m_pluginName; + int m_pluginType; + + QWidget *m_pluginWidget = nullptr; + + TitleLabel *m_noticeLabel = nullptr; + TitleLabel *m_notFazeLabel = nullptr; + QLabel *m_getNoticeLabel = nullptr; + + QFrame *m_noticeAppFrame = nullptr; + QFrame *m_getNoticeFrame = nullptr; + + KSwitchButton *m_autoOpenSwitchBtn = nullptr; + KSwitchButton *m_multiScreenSwitchBtn = nullptr; + KSwitchButton *m_fullScreenSwitchBtn = nullptr; + KSwitchButton *m_allowAlarmSwitchBtn = nullptr; + KSwitchButton *m_enableSwitchBtn = nullptr; + + QComboBox *m_openTimeHComboBox = nullptr; + QComboBox *m_openTimeMComboBox = nullptr; + QComboBox *m_closeTimeHComboBox = nullptr; + QComboBox *m_closeTimeMComboBox = nullptr; + + QGSettings *m_themeSetting = nullptr; + + QVBoxLayout *m_appListVerticalLayout = nullptr; + + UkuiNotification::NotificationGlobalSettings *m_globalSettings = nullptr; + + UkuiSearch::ApplicationInfo *m_appInfo = nullptr; +}; + +#endif // NOTIFICATION_UKCC_PLUGIN_H diff --git a/notification-ukcc-plugin/translations/bo_CN.ts b/notification-ukcc-plugin/translations/bo_CN.ts new file mode 100644 index 0000000..be1a4e5 --- /dev/null +++ b/notification-ukcc-plugin/translations/bo_CN.ts @@ -0,0 +1,96 @@ + + + + + Notice + + + Notice + བརྡ་ཐོ། + + + + NotFaze Mode + མི་དམངས་ཀྱི་དཔེ་དབྱིབས་མིན་པ། + + + + (Notification banners, prompts will be hidden, and notification sounds will be muted) + (བརྡ་ཐོ་གཏོང་བའི་འཕྲེད་འགེལ་སྦྱར་ཡིག་དང་། བརྡ་གཏོང་ཡི་གེ་སྦས་སྐུང་བྱས་ནས་བརྡ་ཁྱབ་ཀྱི་སྒྲ་གྲགས་ཡོང་། ) + + + + Automatically turn on + རང་འགུལ་གྱིས་ཁ་ཕྱེ་བ། + + + + to + དེ་ལྟར་བྱས་ན་ + + + + Automatically turn on when multiple screens are connected + བརྙན་ཤེལ་མང་པོ་སྦྲེལ་མཐུད་བྱེད་སྐབས་རང་འགུལ་གྱིས་ཁ་ཕྱེ་བ། + + + + Automatically open in full screen mode + བརྙན་ཤེལ་ཧྲིལ་པོའི་རྣམ་པའི་ཐོག་ནས་རང་འགུལ་གྱིས་སྒོ་ + + + + Allow automatic alarm reminders in Do Not Disturb mode + རང་འགུལ་གྱིས་ཉེན་བརྡ་གཏོང་བའི་དྲན་སྐུལ་བྱེད་སྟངས་ལ་སུན་པོ་བཟོ་མི་རུང་། + + + + Notice Settings + བརྡ་ཐོའི་སྒྲིག་བཀོད། + + + + Get notifications from the app + ཉེར་སྤྱོད་གོ་རིམ་ཁྲོད་ནས་བརྡ་ཐོ་གཏོང་དགོས། + /notice/Get notifications from the app + + + + NoticeMenu + + + Beep sound when notified + བརྡ་ཐོ་གཏོང་སྐབས་སྐད་ཅོར་རྒྱག་པ། + + + + Show message on screenlock + བརྙན་ཤེལ་སྟེང་ནས་ཆ་འཕྲིན་མངོན་པ། + + + + Show noticfication on screenlock + བརྙན་ཤེལ་སྟེང་ནས་དོ་སྣང་བྱེད་པ། + + + + Notification Style + བརྡ་ཐོ་གཏོང་སྟངས། + + + + Banner: Appears in the upper right corner of the screen, and disappears automatically + འཕྲེད་འགེལ་ཡི་གེ། བརྙན་ཤེལ་གྱི་གཡས་ཟུར་དུ་མངོན་པ་མ་ཟད། རང་འགུལ་གྱིས་མེད་པར་གྱུར་པ། + + + + Tip:It will be kept on the screen until it is closed + རྩེ་མོ། འཆར་ངོས་སུ་ཉར་ཚགས་བྱས་ནས་སྒོ་མ་བརྒྱབ་གོང་ལ་ཉར་ཚགས་བྱེད་དགོས། + + + + None:Notifications will not be displayed on the screen, but will go to the notification center + གཅིག་ཀྱང་མ་ལུས་པར་འཆར་ངོས་སུ་བརྡ་ཐོ་མི་མངོན་པར་བརྡ་ཁྱབ་ལྟེ་གནས་སུ་འགྲོ་རྒྱུ་རེད། + + + diff --git a/notification-ukcc-plugin/translations/en_US.ts b/notification-ukcc-plugin/translations/en_US.ts new file mode 100644 index 0000000..eee95e1 --- /dev/null +++ b/notification-ukcc-plugin/translations/en_US.ts @@ -0,0 +1,96 @@ + + + + + Notice + + + Notice + Notice + + + + NotFaze Mode + NotFaze Mode + + + + (Notification banners, prompts will be hidden, and notification sounds will be muted) + (Notification banners, prompts will be hidden, and notification sounds will be muted) + + + + Automatically turn on + Automatically turn on + + + + to + to + + + + Automatically turn on when multiple screens are connected + Automatically turn on when multiple screens are connected + + + + Automatically open in full screen mode + Automatically open in full screen mode + + + + Allow automatic alarm reminders in Do Not Disturb mode + Allow automatic alarm reminders in Do Not Disturb mode + + + + Notice Settings + Notice Settings + + + + Get notifications from the app + Get notifications from the app + /notice/Get notifications from the app + + + + NoticeMenu + + + Beep sound when notified + Beep sound when notified + + + + Show message on screenlock + Show message on screenlock + + + + Show noticfication on screenlock + Show noticfication on screenlock + + + + Notification Style + Notification Style + + + + Banner: Appears in the upper right corner of the screen, and disappears automatically + Banner: Appears in the upper right corner of the screen, and disappears automatically + + + + Tip:It will be kept on the screen until it is closed + Tip:It will be kept on the screen until it is closed + + + + None:Notifications will not be displayed on the screen, but will go to the notification center + None:Notifications will not be displayed on the screen, but will go to the notification center + + + diff --git a/notification-ukcc-plugin/translations/zh_CN.ts b/notification-ukcc-plugin/translations/zh_CN.ts new file mode 100644 index 0000000..e4dcd86 --- /dev/null +++ b/notification-ukcc-plugin/translations/zh_CN.ts @@ -0,0 +1,96 @@ + + + + + Notice + + + Notice + 通知 + + + + NotFaze Mode + 勿扰模式 + + + + (Notification banners, prompts will be hidden, and notification sounds will be muted) + (通知横幅、提示将会隐藏,通知声音将会静音) + + + + Automatically turn on + 自动开启 + + + + to + + + + + Automatically turn on when multiple screens are connected + 多屏连接时自动开启 + + + + Automatically open in full screen mode + 全屏模式下自动开启 + + + + Allow automatic alarm reminders in Do Not Disturb mode + 勿扰模式下允许闹钟提示 + + + + Notice Settings + 通知 + + + + Get notifications from the app + 获取来自应用的通知 + /notice/Get notifications from the app + + + + NoticeMenu + + + Beep sound when notified + 通知时提示声音 + + + + Show message on screenlock + 在锁屏界面显示消息内容 + + + + Show noticfication on screenlock + 在锁屏界面显示通知 + + + + Notification Style + 通知样式 + + + + Banner: Appears in the upper right corner of the screen, and disappears automatically + 横幅:显示在屏幕右上角,会自动消失 + + + + Tip:It will be kept on the screen until it is closed + 提示:会保留在屏幕上,直到被关闭 + + + + None:Notifications will not be displayed on the screen, but will go to the notification center + 无:通知不会显示在屏幕上,但会进入通知中心 + + + diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt new file mode 100644 index 0000000..4b54e32 --- /dev/null +++ b/test/CMakeLists.txt @@ -0,0 +1,14 @@ +set(notificationClientTest_SRCS + notification-client-test.cpp + notification-client-test.h + main.cpp notification-settings-test.cpp notification-settings-test.h) +include_directories(${CMAKE_SOURCE_DIR}/libukui-notification ${CMAKE_SOURCE_DIR}/libukui-notification/notification-settings) + +message(${notificationClientTest_SRCS}, "123123") +add_executable(ukui-notification-test ${notificationClientTest_SRCS}) + +target_link_libraries(ukui-notification-test PRIVATE + Qt${QT_MAJOR_VERSION}::Core + Qt${QT_MAJOR_VERSION}::Gui + ukui-notification + ) \ No newline at end of file diff --git a/test/main.cpp b/test/main.cpp new file mode 100644 index 0000000..e86dcb3 --- /dev/null +++ b/test/main.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#include +#include +#include "notification-client-test.h" +#include "notification-settings-test.h" + +int main(int argc, char *argv[]) +{ + QCoreApplication app(argc, argv); +// NotificationClientTest ct; + NotificationSettingsTest setting; + return app.exec(); +} \ No newline at end of file diff --git a/test/notification-client-test.cpp b/test/notification-client-test.cpp new file mode 100644 index 0000000..2896aad --- /dev/null +++ b/test/notification-client-test.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#include "notification-client-test.h" +#include + +NotificationClientTest::NotificationClientTest(QObject *parent) : QObject(parent) +{ + m_client = new UkuiNotification::NotificationClient(this); + connect(m_client, &UkuiNotification::NotificationClient::newNotification, + [&](const UkuiNotification::PopupNotification ¬ification){ + qDebug() << notification.applicationName() + << notification.applicationIconName() + << notification.summary() + << notification.body() + << notification.actions() + << notification.hints() + << notification.timeout(); + }); + qDebug() << "Register client" << m_client->registerClient(); +} + +NotificationClientTest::~NotificationClientTest() +{ + +} diff --git a/test/notification-client-test.h b/test/notification-client-test.h new file mode 100644 index 0000000..85cb87a --- /dev/null +++ b/test/notification-client-test.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef UKUI_NOTIFICATION_NOTIFICATION_CLIENT_TEST_H +#define UKUI_NOTIFICATION_NOTIFICATION_CLIENT_TEST_H +#include "notification-client.h" +#include + +class NotificationClientTest : public QObject +{ + Q_OBJECT +public: + explicit NotificationClientTest(QObject *parent = nullptr); + ~NotificationClientTest(); +private: + UkuiNotification::NotificationClient *m_client = nullptr; +}; + + +#endif //UKUI_NOTIFICATION_NOTIFICATION_CLIENT_TEST_H diff --git a/test/notification-settings-test.cpp b/test/notification-settings-test.cpp new file mode 100644 index 0000000..1e79eb1 --- /dev/null +++ b/test/notification-settings-test.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#include "notification-settings-test.h" +#include "popup-notification.h" + +NotificationSettingsTest::NotificationSettingsTest(QObject *parent) : QObject(parent) +{ + UkuiNotification::ApplicationsSettingsMap &map = UkuiNotification::ApplicationsSettings::self()->getAllApplicationsSettings(); + for(const QString &key : map.keys()) { + initConnection(map.value(key)); + } + m_globalSettings = new UkuiNotification::NotificationGlobalSettings(this); + connect(m_globalSettings, &UkuiNotification::NotificationGlobalSettings::scheduleTurnOnDNDChanged, this, [&](bool value){ + qDebug() << "scheduleTurnOnDNDChanged" << value; + }); + connect(m_globalSettings, &UkuiNotification::NotificationGlobalSettings::scheduleTurnOnDNDTimeChanged, this, [&](QTime value){ + qDebug() << "scheduleTurnOnDNDTimeChanged" << value; + }); + connect(m_globalSettings, &UkuiNotification::NotificationGlobalSettings::scheduleTurnOffDNDTimeChanged, this, [&](QTime value){ + qDebug() << "scheduleTurnOffDNDTimeChanged" << value; + }); + connect(m_globalSettings, &UkuiNotification::NotificationGlobalSettings::DNDWhileMultiScreenChanged, this, [&](bool value){ + qDebug() << "DNDWhileMultiScreenChanged" << value; + }); + connect(m_globalSettings, &UkuiNotification::NotificationGlobalSettings::DNDWhileFullScreenChanged, this, [&](bool value){ + qDebug() << "DNDWhileFullScreenChanged" << value; + }); + connect(m_globalSettings, &UkuiNotification::NotificationGlobalSettings::notifyAlarmWhileDNDChanged, this, [&](bool value){ + qDebug() << "notifyAlarmWhileDNDChanged" << value; + }); + connect(m_globalSettings, &UkuiNotification::NotificationGlobalSettings::receiveNotificationsFromAppsChanged, this, [&](bool value){ + qDebug() << "receiveNotificationsFromAppsChanged" << value; + }); +} + +NotificationSettingsTest::~NotificationSettingsTest() +{ + +} + +void NotificationSettingsTest::initConnection(UkuiNotification::SingleApplicationSettings *setting) +{ + connect(setting, &UkuiNotification::SingleApplicationSettings::allowNotifyChanged, this, [&](bool value){ + qDebug() << "allowNotifyChanged" << value; + }); + connect(setting, &UkuiNotification::SingleApplicationSettings::allowSoundChanged, this, [&](bool value){ + qDebug() << "allowSoundChanged" << value; + }); + connect(setting, &UkuiNotification::SingleApplicationSettings::showContentOnLockScreenChanged, this, [&](bool value){ + qDebug() << "showContentOnLockScreenChanged" << value; + }); + connect(setting, &UkuiNotification::SingleApplicationSettings::showNotificationOnLockScreenChanged, this, [&](bool value){ + qDebug() << "showNotificationOnLockScreenChanged" << value; + }); + connect(setting, &UkuiNotification::SingleApplicationSettings::popupStyleChanged, this, [&](UkuiNotification::SettingsProperty::Property value){ + qDebug() << "popupStyleChanged" << value; + }); + connect(setting, &UkuiNotification::SingleApplicationSettings::uninstalled, this, [&](){ + qDebug() << "uninstalled"; + }); +} diff --git a/test/notification-settings-test.h b/test/notification-settings-test.h new file mode 100644 index 0000000..e7a9960 --- /dev/null +++ b/test/notification-settings-test.h @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2023, KylinSoft Co., Ltd. + * + * 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, either version 3 of the License, or + * (at your option) any later version. + * + * 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 . + * + * Authors: iaom + */ + +#ifndef UKUI_NOTIFICATION_NOTIFICATION_SETTINGS_TEST_H +#define UKUI_NOTIFICATION_NOTIFICATION_SETTINGS_TEST_H +#include +#include "applications-settings.h" +#include "notification-global-settings.h" + +class NotificationSettingsTest : public QObject +{ +Q_OBJECT +public: + explicit NotificationSettingsTest(QObject *parent = nullptr); + ~NotificationSettingsTest(); + + void initConnection(UkuiNotification::SingleApplicationSettings *setting); +private: + UkuiNotification::NotificationGlobalSettings *m_globalSettings = nullptr; +}; + + +#endif //UKUI_NOTIFICATION_NOTIFICATION_SETTINGS_TEST_H