diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 2daed62..0000000 --- a/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -CMakeLists.txt.user -build/ - -# translations files -*.qm -.vscode/ diff --git a/.tx/config b/.tx/config deleted file mode 100644 index 2d4dca1..0000000 --- a/.tx/config +++ /dev/null @@ -1,10 +0,0 @@ -[main] -host = https://www.transifex.com -minimum_perc = 80 -mode = developer - -[o:linuxdeepin:p:deepin-desktop-environment:r:dde-application-manager] -file_filter = translations/dde-application-manager_.ts -source_file = translations/dde-application-manager.ts -source_lang = en_US -type = QT diff --git a/.tx/deepin.conf b/.tx/deepin.conf deleted file mode 100644 index c230b4f..0000000 --- a/.tx/deepin.conf +++ /dev/null @@ -1,2 +0,0 @@ -[transifex] -branch = m20 diff --git a/CMakeLists.txt b/CMakeLists.txt deleted file mode 100644 index 5696487..0000000 --- a/CMakeLists.txt +++ /dev/null @@ -1,28 +0,0 @@ -cmake_minimum_required(VERSION 3.11) - -project(dde-application-manager) - -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) - -include(GNUInstallDirs) - -#install settings -if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - set(CMAKE_INSTALL_PREFIX /usr) -endif () - -add_subdirectory(src) -add_subdirectory(misc) - -if (NOT (${CMAKE_BUILD_TYPE} MATCHES "Debug")) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Ofast") - - # generate qm - execute_process(COMMAND bash "translate_generation.sh" - WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) -endif () - -# qm files -file(GLOB QM_FILES "translations/*.qm") -install(FILES ${QM_FILES} DESTINATION ${CMAKE_INSTALL_DATADIR}/dde-application-manager/translations) diff --git a/dbus/org.deepin.dde.Application1.Instance.xml b/dbus/org.deepin.dde.Application1.Instance.xml deleted file mode 100644 index a852d3f..0000000 --- a/dbus/org.deepin.dde.Application1.Instance.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/dbus/org.deepin.dde.Application1.Manager.xml b/dbus/org.deepin.dde.Application1.Manager.xml deleted file mode 100644 index 97ed555..0000000 --- a/dbus/org.deepin.dde.Application1.Manager.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/dbus/org.deepin.dde.Application1.xml b/dbus/org.deepin.dde.Application1.xml deleted file mode 100644 index b6e8898..0000000 --- a/dbus/org.deepin.dde.Application1.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/dbus/org.deepin.dde.Mime1.xml b/dbus/org.deepin.dde.Mime1.xml deleted file mode 100644 index 623366f..0000000 --- a/dbus/org.deepin.dde.Mime1.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/lupdate.sh b/lupdate.sh deleted file mode 100755 index 31b7334..0000000 --- a/lupdate.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash -cp ".transifexrc" ${HOME}/ - -cd ./translations - -#rm -f dde-launcher.ts -#根据源码生成翻译英文翻译文件 -lupdate ../src/ -ts -no-obsolete dde-application-manager.ts - -cd ../ - -lupdate ./ -ts -no-obsolete translations/dde-application-manager.ts - -tx push -s -b m23 diff --git a/misc/CMakeLists.txt b/misc/CMakeLists.txt deleted file mode 100644 index a60f6b4..0000000 --- a/misc/CMakeLists.txt +++ /dev/null @@ -1,2 +0,0 @@ -add_subdirectory(systemd) -add_subdirectory(dconf) diff --git a/misc/dconf/CMakeLists.txt b/misc/dconf/CMakeLists.txt deleted file mode 100644 index 5a5572c..0000000 --- a/misc/dconf/CMakeLists.txt +++ /dev/null @@ -1,9 +0,0 @@ -set(DCONFIG_FILES - com.deepin.dde.launcher.json - com.deepin.dde.dock.json - com.deepin.dde.appearance.json - com.deepin.dde.startdde.json - com.deepin.xsettings.json -) - -install(FILES ${DCONFIG_FILES} DESTINATION ${CMAKE_INSTALL_DATADIR}/dsg/configs/dde-application-manager) diff --git a/misc/dconf/com.deepin.dde.appearance.json b/misc/dconf/com.deepin.dde.appearance.json deleted file mode 100644 index c6e9186..0000000 --- a/misc/dconf/com.deepin.dde.appearance.json +++ /dev/null @@ -1,145 +0,0 @@ -{ - "magic": "dsg.config.meta", - "version": "1.0", - "contents": { - "Extra_Picture_Uris": { - "serial": 0, - "flags": [], - "name": "Extra_Picture_Uris", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Font_Standard": { - "value": "Noto Sans", - "serial": 0, - "flags": [], - "name": "Font_Standard", - "name[zh_CN]": "*****", - "description": "The standard font for desktop", - "permissions": "readwrite", - "visibility": "private" - }, - "Theme_Auto": { - "value": false, - "serial": 0, - "flags": [], - "name": "Theme_Auto", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Wallpaper_Slideshow": { - "value": "", - "serial": 0, - "flags": [], - "name": "Wallpaper_Slideshow", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Cursor_Theme": { - "value": "bloom", - "serial": 0, - "flags": [], - "name": "Cursor_Theme", - "name[zh_CN]": "*****", - "description": "Cursor theme name. Used only by Xservers that support the Xcursor extension.", - "permissions": "readwrite", - "visibility": "private" - }, - "Font_Size": { - "value": 10.5, - "serial": 0, - "flags": [], - "name": "Font_Size", - "name[zh_CN]": "*****", - "description": "The desktop font size", - "permissions": "readwrite", - "visibility": "private" - }, - "Wallpaper_Uris": { - "value": "", - "serial": 0, - "flags": [], - "name": "Wallpaper_Uris", - "name[zh_CN]": "*****", - "description": "wallpaper json string", - "permissions": "readwrite", - "visibility": "private" - }, - "Icon_Theme": { - "value": "bloom", - "serial": 0, - "flags": [], - "name": "Icon_Theme", - "name[zh_CN]": "*****", - "description": "Icon theme to use for the panel, nautilus etc.", - "permissions": "readwrite", - "visibility": "private" - }, - "Opacity": { - "value": 0.4, - "serial": 0, - "flags": [], - "name": "Opacity", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Font_Monospace": { - "value": "Noto Mono", - "serial": 0, - "flags": [], - "name": "Font_Monospace", - "name[zh_CN]": "*****", - "description": "The monospace font for desktop", - "permissions": "readwrite", - "visibility": "private" - }, - "Excluded_Icon_Themes": { - "value": ["hicolor", "gnome", "Adwaita"], - "serial": 0, - "flags": [], - "name": "Excluded_Icon_Themes", - "name[zh_CN]": "*****", - "description": "Icon theme black list.", - "permissions": "readwrite", - "visibility": "private" - }, - "Gtk_Theme": { - "value": "deepin", - "serial": 0, - "flags": [], - "name": "Gtk_Theme", - "name[zh_CN]": "*****", - "description": "Basename of the default theme used by gtk+.", - "permissions": "readwrite", - "visibility": "private" - }, - "Sound_Theme": { - "value": "deepin", - "serial": 0, - "flags": [], - "name": "Sound_Theme", - "name[zh_CN]": "*****", - "description": "Set the system sound theme", - "permissions": "readwrite", - "visibility": "private" - }, - "Background_Uris": { - "value": ["file:///usr/share/backgrounds/default_background.jpg"], - "serial": 0, - "flags": [], - "name": "Background_Uris", - "name[zh_CN]": "*****", - "description": "Note that the backend only supports local (file://) URIs.", - "permissions": "readwrite", - "visibility": "private" - } - } -} diff --git a/misc/dconf/com.deepin.dde.dock.json b/misc/dconf/com.deepin.dde.dock.json deleted file mode 100644 index 970177b..0000000 --- a/misc/dconf/com.deepin.dde.dock.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "magic": "dsg.config.meta", - "version": "1.0", - "contents": { - "Window_Size_Fashion": { - "value": 48, - "serial": 0, - "flags": [], - "name": "Window_Size_Fashion", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Icon_Size": { - "value": 36, - "serial": 0, - "flags": [], - "name": "Icon_Size", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Position": { - "value": "bottom", - "serial": 0, - "flags": [], - "name": "Position", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Wireless_Scan_Interval": { - "value": 5, - "serial": 0, - "flags": [], - "name": "Wireless_Scan_Interval", - "name[zh_CN]": "*****", - "description": "wireless scan interval", - "permissions": "readwrite", - "visibility": "private" - }, - "Hide_Timeout": { - "value": 0, - "serial": 0, - "flags": [], - "name": "Hide_Timeout", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Hide_Mode": { - "value": "keep-showing", - "serial": 0, - "flags": [], - "name": "Hide_Mode", - "name[zh_CN]": "*****", - "description": "The value will influence when the dock is shown or hidden.", - "permissions": "readwrite", - "visibility": "private" - }, - "Show_Timeout": { - "value": 100, - "serial": 0, - "flags": [], - "name": "Show_Timeout", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Window_Size_Efficient": { - "value": 40, - "serial": 0, - "flags": [], - "name": "Window_Size_Efficient", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Plugin_Settings": { - "value": "{}", - "serial": 0, - "flags": [], - "name": "Plugin_Settings", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Docked_Apps": { - "value": ["/usr/share/applications/dde-file-manager", "/usr/share/applications/uos-browser", "/usr/share/applications/org.deepin.browser", "/usr/share/applications/deepin-appstore", "/usr/share/applications/deepin-app-store", "/usr/share/applications/com.deepin.store.intranet", "/usr/share/applications/deepin-album", "/usr/share/applications/deepin-music", "/usr/share/applications/deepin-contacts", "/usr/share/applications/dde-calendar", "/usr/share/applications/dde-control-center"], - "serial": 0, - "flags": [], - "name": "Docked_Apps", - "name[zh_CN]": "*****", - "description": "The default apps which is docked when dock is started.", - "permissions": "readwrite", - "visibility": "private" - }, - "Win_Icon_Preferred_Apps": { - "value": ["apps.com.qq.im", "deepin.com.qq.im", "apps.com.qq.im.light", "apps.com.qq.b.eim", "apps.com.qq.rtxclient"], - "serial": 0, - "flags": [], - "name": "Win_Icon_Preferred_Apps", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Delay_Plugins_Time": { - "value": 0, - "serial": 0, - "flags": [], - "name": "Delay_Plugins_Time", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Force_Quit_App": { - "value": "enabled", - "serial": 0, - "flags": [], - "name": "Force_Quit_App", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Display_Mode": { - "value": "", - "serial": 0, - "flags": [], - "name": "Display_Mode", - "name[zh_CN]": "*****", - "description": "The dock gets different display mode, for instance, dock looks like win7 taskbar on classic mode.", - "permissions": "readwrite", - "visibility": "private" - }, - "Recent_App": { - "value": [], - "serial": 0, - "flags": [], - "name": "Recent_App", - "name[zh_CN]": "*****", - "description": "The apps which has been opened recently when dock is started", - "permissions": "readwrite", - "visibility": "private" - }, - "Show_Recent": { - "value": false, - "serial": 0, - "flags": [], - "name": "Show_Recent", - "name[zh_CN]": "*****", - "description": "show or hide recent app in dock", - "permissions": "readwrite", - "visibility": "private" - }, - "Show_MultiWindow": { - "value": false, - "serial": 0, - "flags": [], - "name": "Show_MultiWindow", - "name[zh_CN]": "*****", - "description": "show or hide Multi Window in dock when the Entry has subWindow", - "permissions": "readwrite", - "visibility": "private" - } - } -} diff --git a/misc/dconf/com.deepin.dde.launcher.json b/misc/dconf/com.deepin.dde.launcher.json deleted file mode 100644 index b853c96..0000000 --- a/misc/dconf/com.deepin.dde.launcher.json +++ /dev/null @@ -1,246 +0,0 @@ -{ - "magic": "dsg.config.meta", - "version": "1.0", - "contents": { - "Apps_Disable_AutoStart": { - "value": [], - "serial": 0, - "flags": [], - "name": "Apps_Disable_AutoStart", - "name[zh_CN]": "*****", - "description": "apps not allowed to start up", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Order_Zh_Cn": { - "value": ["uos-browser", "org.deepin.browser", "dde-file-manager", "deepin-app-store", "deepin-appstore", "deepin-music", "deepin-movie", "deepin-screen-recorder", "deepin-image-viewer", "deepin-album", "deepin-draw", "deepin-reader", "deepin-editor", "deepin-mail", "thunderbird", "deepin-terminal", "terminal", "org.gnome.Terminal", "deepin-contacts", "deepin-voice-note", "downloader", "deepin-manual", "org.deepin.scanner", "org.deepin.scaner", "dde-computer", "dde-trash", "deepin-defender", "dde-control-center", "chineseime-setting", "fcitx-config-gtk3", "chineseime-setting-wizard", "deepin-system-monitor", "deepin-boot-maker", "deepin-devicemanager", "deepin-log-viewer", "dde-printer", "dde-calendar", "deepin-calculator", "deepin-font-manager", "deepin-compressor", "deepin-deb-installer", "deepin-diskmanager", "dde-introduction", "uos-service-support", "uos-remote-assistance", "deepin-camera", "deepin-phone-master", "gparted", "org.gnome.Cheese", "Cheese", "gnome.Cheese"], - "serial": 0, - "flags": [], - "name": "Apps_Order_Zh_Cn", - "name[zh_CN]": "*****", - "description": "launcher apps order, ensure that all lowercase.", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Icon_Ratio": { - "value": 0.5, - "serial": 0, - "flags": [], - "name": "Apps_Icon_Ratio", - "name[zh_CN]": "*****", - "description": "(null)", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Disable_UseProxy": { - "value": [], - "serial": 0, - "flags": [], - "name": "Apps_Disable_UseProxy", - "name[zh_CN]": "*****", - "description": "apps disable use proxy menu", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Without_AutoStart": { - "value": [], - "serial": 0, - "flags": [], - "name": "Apps_Without_AutoStart", - "name[zh_CN]": "*****", - "description": "apps hide function start up", - "permissions": "readwrite", - "visibility": "private" - }, - "Fullscreen": { - "value": true, - "serial": 0, - "flags": [], - "name": "Fullscreen", - "name[zh_CN]": "*****", - "description": "(null)", - "permissions": "readwrite", - "visibility": "private" - }, - "Mini_Frame_Right_Bar_Hide_List": { - "value": [], - "serial": 0, - "flags": [], - "name": "Mini_Frame_Right_Bar_Hide_List", - "name[zh_CN]": "*****", - "description": "icons not allowed to show on mini frame right bar", - "permissions": "readwrite", - "visibility": "private" - }, - "Auto_Exit": { - "value": false, - "serial": 0, - "flags": [], - "name": "Auto_Exit", - "name[zh_CN]": "*****", - "description": "(null)", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Order_Zh_Tw": { - "value": ["uos-browser", "org.deepin.browser", "dde-file-manager", "deepin-app-store", "deepin-appstore", "deepin-music", "deepin-movie", "deepin-screen-recorder", "deepin-image-viewer", "deepin-album", "deepin-draw", "deepin-reader", "deepin-editor", "deepin-mail", "thunderbird", "deepin-terminal", "terminal", "org.gnome.Terminal", "deepin-contacts", "deepin-voice-note", "downloader", "deepin-manual", "org.deepin.scanner", "org.deepin.scaner", "dde-computer", "dde-trash", "deepin-defender", "dde-control-center", "chineseime-setting", "fcitx-config-gtk3", "chineseime-setting-wizard", "deepin-system-monitor", "deepin-boot-maker", "deepin-devicemanager", "deepin-log-viewer", "dde-printer", "dde-calendar", "deepin-calculator", "deepin-font-manager", "deepin-compressor", "deepin-deb-installer", "deepin-diskmanager", "dde-introduction", "uos-service-support", "uos-remote-assistance", "deepin-camera", "deepin-phone-master", "gparted", "org.gnome.Cheese", "Cheese", "gnome.Cheese"], - "serial": 0, - "flags": [], - "name": "Apps_Order_Zh_Tw", - "name[zh_CN]": "*****", - "description": "launcher apps order, ensure that all lowercase.", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Disable_SendDock": { - "value": [], - "serial": 0, - "flags": [], - "name": "Apps_Disable_SendDock", - "name[zh_CN]": "*****", - "description": "apps not allowed to send to Dock", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Disable_SendDesktop": { - "value": [], - "serial": 0, - "flags": [], - "name": "Apps_Disable_SendDesktop", - "name[zh_CN]": "*****", - "description": "apps not allowed to send to Desktop", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Without_SendDesktop": { - "value": [], - "serial": 0, - "flags": [], - "name": "Apps_Without_SendDesktop", - "name[zh_CN]": "*****", - "description": "apps hide function send to desktop", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Hold_List": { - "value": ["dde-introduction", "dde-file-manager", "deepin-appstore", "deepin-app-store", "deepin-terminal", "deepin-manual", "dde-computer", "dde-trash", "deepin-defender", "dde-control-center", "fcitx-config-gtk3", "fcitx-configtool", "deepin-system-monitor", "deepin-devicemanager", "dde-printer", "dde-calendar", "uos-service-support", "deepin-toggle-desktop", "deepin-wm-multitaskingview", "kwin-wm-multitaskingview", "com.deepin.store.intranet", "chineseime-setting"], - "serial": 0, - "flags": [], - "name": "Apps_Hold_List", - "name[zh_CN]": "*****", - "description": "apps not allowed to uninstall", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Without_Open": { - "value": [], - "serial": 0, - "flags": [], - "name": "Apps_Without_Open", - "name[zh_CN]": "*****", - "description": "apps hide function open", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Disable_Open": { - "value": [], - "serial": 0, - "flags": [], - "name": "Apps_Disable_Open", - "name[zh_CN]": "*****", - "description": "apps not allowed to open", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Use_Proxy": { - "value": [], - "serial": 0, - "flags": [], - "name": "Apps_Use_Proxy", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Search_Package_Name": { - "value": false, - "serial": 0, - "flags": [], - "name": "Search_Package_Name", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Order": { - "value": ["uos-browser", "org.deepin.browser", "dde-file-manager", "deepin-app-store", "deepin-appstore", "deepin-music", "deepin-movie", "deepin-screen-recorder", "deepin-image-viewer", "deepin-album", "deepin-draw", "deepin-reader", "deepin-editor", "deepin-mail", "thunderbird", "deepin-terminal", "terminal", "org.gnome.Terminal", "deepin-contacts", "deepin-voice-note", "downloader", "deepin-manual", "org.deepin.scanner", "org.deepin.scaner", "dde-computer", "dde-trash", "deepin-defender", "dde-control-center", "chineseime-setting", "fcitx-config-gtk3", "chineseime-setting-wizard", "deepin-system-monitor", "deepin-boot-maker", "deepin-devicemanager", "deepin-log-viewer", "dde-printer", "dde-calendar", "deepin-calculator", "deepin-font-manager", "deepin-compressor", "deepin-deb-installer", "deepin-diskmanager", "dde-introduction", "uos-service-support", "uos-remote-assistance", "deepin-camera", "deepin-phone-master", "gparted", "org.gnome.Cheese", "Cheese", "gnome.Cheese"], - "serial": 0, - "flags": [], - "name": "Apps_Order", - "name[zh_CN]": "*****", - "description": "launcher apps order, ensure that all lowercase.", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Without_UseProxy": { - "value": [], - "serial": 0, - "flags": [], - "name": "Apps_Without_UseProxy", - "name[zh_CN]": "*****", - "description": "apps hide use proxy menu", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Disable_Scaling": { - "value": [], - "serial": 0, - "flags": [], - "name": "Apps_Disable_Scaling", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Hidden": { - "value": [], - "serial": 0, - "flags": [], - "name": "Apps_Hidden", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Without_SendDock": { - "value": [], - "serial": 0, - "flags": [], - "name": "Apps_Without_SendDock", - "name[zh_CN]": "*****", - "description": "apps hide function send to dock", - "permissions": "readwrite", - "visibility": "private" - }, - "Apps_Without_Uninstall": { - "value": [], - "serial": 0, - "flags": [], - "name": "Apps_Without_Uninstall", - "name[zh_CN]": "*****", - "description": "apps hide function uninstall", - "permissions": "readwrite", - "visibility": "private" - }, - "Display_Mode": { - "value": "free", - "serial": 0, - "flags": [], - "name": "Display_Mode", - "name[zh_CN]": "*****", - "description": "Launcher display mode.", - "permissions": "readwrite", - "visibility": "private" - } - } -} diff --git a/misc/dconf/com.deepin.dde.startdde.json b/misc/dconf/com.deepin.dde.startdde.json deleted file mode 100644 index 11db86b..0000000 --- a/misc/dconf/com.deepin.dde.startdde.json +++ /dev/null @@ -1,96 +0,0 @@ -{ - "magic": "dsg.config.meta", - "version": "1.0", - "contents": { - "Wm_Cmd": { - "value": "", - "serial": 0, - "flags": [], - "name": "Wm_Cmd", - "name[zh_CN]": "*****", - "description": "This key will special window manager at startdde startup. If empty, using deepin-wm.", - "permissions": "readwrite", - "visibility": "private" - }, - "Quick_Black_Screen": { - "value": true, - "serial": 0, - "flags": [], - "name": "Quick_Black_Screen", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Swap_Sched_Enabled": { - "value": true, - "serial": 0, - "flags": [], - "name": "Swap_Sched_Enabled", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Launch_Welcome": { - "value": true, - "serial": 0, - "flags": [], - "name": "Launch_Welcome", - "name[zh_CN]": "*****", - "description": "This key will indicate whether showing dde-welcome.", - "permissions": "readwrite", - "visibility": "private" - }, - "Autostart_Delay": { - "value": 0, - "serial": 0, - "flags": [], - "name": "Autostart_Delay", - "name[zh_CN]": "*****", - "description": "The delay seconds for autostart", - "permissions": "readwrite", - "visibility": "private" - }, - "Turbo_Invoker_Enabled": { - "value": false, - "serial": 0, - "flags": [], - "name": "Turbo_Invoker_Enabled", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Login_Reminder": { - "value": false, - "serial": 0, - "flags": [], - "name": "Login_Reminder", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Iowait_Enabled": { - "value": false, - "serial": 0, - "flags": [], - "name": "Iowait_Enabled", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Memchecker_Enabled": { - "value": false, - "serial": 0, - "flags": [], - "name": "Memchecker_Enabled", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - } - } -} diff --git a/misc/dconf/com.deepin.xsettings.json b/misc/dconf/com.deepin.xsettings.json deleted file mode 100644 index ee4104a..0000000 --- a/misc/dconf/com.deepin.xsettings.json +++ /dev/null @@ -1,337 +0,0 @@ -{ - "magic": "dsg.config.meta", - "version": "1.0", - "contents": { - "Qt_Active_Color": { - "value": "0,33153,65535,65535", - "serial": 0, - "flags": [], - "name": "Qt_Active_Color", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Xft_Antialias": { - "value": true, - "serial": 0, - "flags": [], - "name": "Xft_Antialias", - "name[zh_CN]": "*****", - "description": "Whether to antialias Xft fonts; 0=no, 1=yes, -1=default.", - "permissions": "readwrite", - "visibility": "private" - }, - "Gtk_Cursor_Theme_Name": { - "value": "bloom", - "serial": 0, - "flags": [], - "name": "Gtk_Cursor_Theme_Name", - "name[zh_CN]": "*****", - "description": "Cursor theme name. Used only by Xservers that support the Xcursor extension.", - "permissions": "readwrite", - "visibility": "private" - }, - "Dtk_Window_Radius": { - "value": 18, - "serial": 0, - "flags": [], - "name": "Dtk_Window_Radius", - "name[zh_CN]": "*****", - "description": "The window radius last time", - "permissions": "readwrite", - "visibility": "private" - }, - "Gtk_Cursor_Blink_Timeout": { - "value": 10, - "serial": 0, - "flags": [], - "name": "Gtk_Cursor_Blink_Timeout", - "name[zh_CN]": "*****", - "description": "Time after which the cursor stops blinking, in seconds.", - "permissions": "readwrite", - "visibility": "private" - }, - "Scale_Factor": { - "value": 1.0, - "serial": 0, - "flags": [], - "name": "Scale_Factor", - "name[zh_CN]": "*****", - "description": "Text scale for Gdk.", - "permissions": "readwrite", - "visibility": "private" - }, - "Gtk_Key_Theme_Name": { - "value": "default", - "serial": 0, - "flags": [], - "name": "Gtk_Key_Theme_Name", - "name[zh_CN]": "*****", - "description": "Basename of the default keybinding theme used by gtk+.", - "permissions": "readwrite", - "visibility": "private" - }, - "Cursor_Blink_Time": { - "value": 1200, - "serial": 0, - "flags": [], - "name": "Cursor_Blink_Time", - "name[zh_CN]": "*****", - "description": "Length of the cursor blink cycle, in milliseconds.", - "permissions": "readwrite", - "visibility": "private" - }, - "Enable_Event_Sounds": { - "value": true, - "serial": 0, - "flags": [], - "name": "Enable_Event_Sounds", - "name[zh_CN]": "*****", - "description": "Whether to play any event sounds at all.", - "permissions": "readwrite", - "visibility": "private" - }, - "Qt_Font_Name": { - "value": "", - "serial": 0, - "flags": [], - "name": "Qt_Font_Name", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Gtk_Theme_Name": { - "value": "deepin", - "serial": 0, - "flags": [], - "name": "Gtk_Theme_Name", - "name[zh_CN]": "*****", - "description": "Basename of the default theme used by gtk+.", - "permissions": "readwrite", - "visibility": "private" - }, - "Double_Click_Time": { - "value": 250, - "serial": 0, - "flags": [], - "name": "Double_Click_Time", - "name[zh_CN]": "*****", - "description": "Maximum time allowed between two clicks for them to be considered a double click (in milliseconds).", - "permissions": "readwrite", - "visibility": "private" - }, - "Icon_Theme_Name": { - "value": "deepin", - "serial": 0, - "flags": [], - "name": "Icon_Theme_Name", - "name[zh_CN]": "*****", - "description": "Icon theme to use for the panel, nautilus etc.", - "permissions": "readwrite", - "visibility": "private" - }, - "Primary_Monitor_Name": { - "value": "eDP-1", - "serial": 0, - "flags": [], - "name": "Primary_Monitor_Name", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Dnd_Drag_Threshold": { - "value": 8, - "serial": 0, - "flags": [], - "name": "Dnd_Drag_Threshold", - "name[zh_CN]": "*****", - "description": "A palette of named colors for use in themes.", - "permissions": "readwrite", - "visibility": "private" - }, - "Sound_Theme_Name": { - "value": "deepin", - "serial": 0, - "flags": [], - "name": "Sound_Theme_Name", - "name[zh_CN]": "*****", - "description": "Set the system sound theme", - "permissions": "readwrite", - "visibility": "private" - }, - "Double_Click_Distance": { - "value": 5, - "serial": 0, - "flags": [], - "name": "Double_Click_Distance", - "name[zh_CN]": "*****", - "description": "Maximum distance allowed between two clicks for them to be considered a double click (in pixels).", - "permissions": "readwrite", - "visibility": "private" - }, - "Xft_Hinting": { - "value": true, - "serial": 0, - "flags": [], - "name": "Xft_Hinting", - "name[zh_CN]": "*****", - "description": "Whether to hint Xft fonts; 0=no, 1=yes, -1=default.", - "permissions": "readwrite", - "visibility": "private" - }, - "Theme_Name": { - "value": "deepin", - "serial": 0, - "flags": [], - "name": "Theme_Name", - "name[zh_CN]": "*****", - "description": "Theme to use for gtk+ and qt.", - "permissions": "readwrite", - "visibility": "private" - }, - "Gtk_Cursor_Theme_Size": { - "value": 24, - "serial": 0, - "flags": [], - "name": "Gtk_Cursor_Theme_Size", - "name[zh_CN]": "*****", - "description": "Timeout in milliseconds before a click starts repeating (onspinner buttons for example).", - "permissions": "readwrite", - "visibility": "private" - }, - "Icon_Theme_Fallback": { - "value": "default", - "serial": 0, - "flags": [], - "name": "Icon_Theme_Fallback", - "name[zh_CN]": "*****", - "description": "Name of a icon theme to fall back to.", - "permissions": "readwrite", - "visibility": "private" - }, - "Xft_Rgba": { - "value": "rgb", - "serial": 0, - "flags": [], - "name": "Xft_Rgba", - "name[zh_CN]": "*****", - "description": "Type of subpixel antialiasing; none, rgb, bgr, vrgb, vbgr.", - "permissions": "readwrite", - "visibility": "private" - }, - "Window_Scale": { - "value": 1, - "serial": 0, - "flags": [], - "name": "Window_Scale", - "name[zh_CN]": "*****", - "description": "Window scale for Gdk.", - "permissions": "readwrite", - "visibility": "private" - }, - "Gtk_Recent_Files_Enabled": { - "value": true, - "serial": 0, - "flags": [], - "name": "Gtk_Recent_Files_Enabled", - "name[zh_CN]": "*****", - "description": "Whether GTK+ should keep track of items inside the recently used resources list.", - "permissions": "readwrite", - "visibility": "private" - }, - "Qt_Mono_Font_Name": { - "value": "", - "serial": 0, - "flags": [], - "name": "Qt_Mono_Font_Name", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Cursor_Blink": { - "value": true, - "serial": 0, - "flags": [], - "name": "Cursor_Blink", - "name[zh_CN]": "*****", - "description": "Whether the cursor should blink.", - "permissions": "readwrite", - "visibility": "private" - }, - "Individual_Scaling": { - "value": "", - "serial": 0, - "flags": [], - "name": "Individual_Scaling", - "name[zh_CN]": "*****", - "description": "Semicolon-separated list of name=value pairs, as used in QT_SCREEN_SCALE_FACTORS.", - "permissions": "readwrite", - "visibility": "private" - }, - "Xft_Dpi": { - "value": -1, - "serial": 0, - "flags": [], - "name": "Xft_Dpi", - "name[zh_CN]": "*****", - "description": "Resolution for Xft, in 1024 * dots/inch. -1 to use default value. Do not modify it manually.", - "permissions": "readwrite", - "visibility": "private" - }, - "Enable_Input_Feedback_Sounds": { - "value": true, - "serial": 0, - "flags": [], - "name": "Enable_Input_Feedback_Sounds", - "name[zh_CN]": "*****", - "description": "Whether to play event sounds as feedback to user input.", - "permissions": "readwrite", - "visibility": "private" - }, - "Xft_Hintstyle": { - "value": "hintfull", - "serial": 0, - "flags": [], - "name": "Xft_Hintstyle", - "name[zh_CN]": "*****", - "description": "What degree of hinting to use; hintnone, hintslight, hintmedium, or hintfull.", - "permissions": "readwrite", - "visibility": "private" - }, - "Qt_Font_Point_Size": { - "value": 10.5, - "serial": 0, - "flags": [], - "name": "Qt_Font_Point_Size", - "name[zh_CN]": "*****", - "description": "", - "permissions": "readwrite", - "visibility": "private" - }, - "Gtk_Recent_Files_Max_Age": { - "value": 30, - "serial": 0, - "flags": [], - "name": "Gtk_Recent_Files_Max_Age", - "name[zh_CN]": "*****", - "description": "The maximum age, in days, of the items inside the recently used resources list. Items older than this setting will be excised from the list. If set to 0, the list will always be empty; if set to -1, no item will be removed.", - "permissions": "readwrite", - "visibility": "private" - }, - "Gtk_Font_Name": { - "value": "sans-serif 10.5", - "serial": 0, - "flags": [], - "name": "Gtk_Font_Name", - "name[zh_CN]": "*****", - "description": "Name of the default font used by gtk+.", - "permissions": "readwrite", - "visibility": "private" - } - } -} - diff --git a/misc/systemd/CMakeLists.txt b/misc/systemd/CMakeLists.txt deleted file mode 100644 index 7caef89..0000000 --- a/misc/systemd/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -set(SYSTEMD_FILES - org.deepin.dde.Application1.Instance@.service - org.deepin.dde.Application1.Manager.service -) - -install(FILES ${SYSTEMD_FILES} DESTINATION lib/systemd/user/) diff --git a/misc/systemd/org.deepin.dde.Application1.Instance@.service b/misc/systemd/org.deepin.dde.Application1.Instance@.service deleted file mode 100644 index f2919e8..0000000 --- a/misc/systemd/org.deepin.dde.Application1.Instance@.service +++ /dev/null @@ -1,9 +0,0 @@ -[Unit] -Description=DDE Application Loader is managing %I - -[Service] -Type=simple -Environment="DAM_TASK_HASH=%I" -Environment="DAM_TASK_TYPE=freedesktop" -ExecStart=/usr/bin/dde-application-loader -Slice=app.slice diff --git a/misc/systemd/org.deepin.dde.Application1.Manager.service b/misc/systemd/org.deepin.dde.Application1.Manager.service deleted file mode 100644 index a9d3eb3..0000000 --- a/misc/systemd/org.deepin.dde.Application1.Manager.service +++ /dev/null @@ -1,19 +0,0 @@ -[Unit] -Description=DDE Application Manager service -RefuseManualStart=no -RefuseManualStop=no -OnFailureJobMode=replace-irreversibly -CollectMode=inactive-or-failed -StartLimitIntervalSec=10s -StartLimitBurst=30 - -Requires=dde-session-pre.target -After=dde-session-pre.target - -[Service] -Type=dbus -BusName=org.deepin.dde.Application1.Manager -ExecStart=/usr/bin/dde-application-manager -Slice=app.slice -Restart=on-failure -RestartSec=300ms diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt deleted file mode 100644 index 07d217f..0000000 --- a/src/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -include(FindPkgConfig) -find_package(PkgConfig REQUIRED) -find_package(Qt5 REQUIRED COMPONENTS Core DBus Concurrent) - -if(CMAKE_BUILD_TYPE STREQUAL "Debug") - add_definitions(-DDEFINE_LOADER_PATH) - set(LOADER_PATH ${PROJECT_BINARY_DIR}/src/loader/deepin-application-loader) -endif() - -configure_file( - "${PROJECT_SOURCE_DIR}/src/define.h.in" - "${PROJECT_BINARY_DIR}/src/define.h" -) - -add_subdirectory("service") -add_subdirectory("loader") diff --git a/src/define.h.in b/src/define.h.in deleted file mode 100644 index f3b0638..0000000 --- a/src/define.h.in +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef DEFINE_H_IN -#define DEFINE_H_IN - -#define LOADER_PATH "@LOADER_PATH@" - -#endif // DEFINE_H_IN diff --git a/src/frameworkdbus/dbusbamfapplication.cpp b/src/frameworkdbus/dbusbamfapplication.cpp deleted file mode 100644 index 7cf33f5..0000000 --- a/src/frameworkdbus/dbusbamfapplication.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c BamfApplication -p BamfApplication Application.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * This file may have been hand-edited. Look for HAND-EDIT comments - * before re-generating it. - */ - -#include "dbusbamfapplication.h" - -/* - * Implementation of interface class __BamfApplication - */ - -class __BamfApplicationPrivate -{ -public: - __BamfApplicationPrivate() = default; - - // begin member variables - -public: - QMap m_processingCalls; - QMap> m_waittingCalls; -}; - -__BamfApplication::__BamfApplication(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent) - : DBusExtendedAbstractInterface(service, path, staticInterfaceName(), connection, parent) - , d_ptr(new __BamfApplicationPrivate) -{ - if (QMetaType::type("QList") == QMetaType::UnknownType) { - qRegisterMetaType< QList >("QList"); - qDBusRegisterMetaType< QList >(); - } -} - -__BamfApplication::~__BamfApplication() -{ - qDeleteAll(d_ptr->m_processingCalls.values()); - delete d_ptr; -} - -void __BamfApplication::CallQueued(const QString &callName, const QList &args) -{ - if (d_ptr->m_waittingCalls.contains(callName)) - { - d_ptr->m_waittingCalls[callName] = args; - return; - } - if (d_ptr->m_processingCalls.contains(callName)) - { - d_ptr->m_waittingCalls.insert(callName, args); - } else { - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(asyncCallWithArgumentList(callName, args)); - connect(watcher, &QDBusPendingCallWatcher::finished, this, &__BamfApplication::onPendingCallFinished); - d_ptr->m_processingCalls.insert(callName, watcher); - } -} - -void __BamfApplication::onPendingCallFinished(QDBusPendingCallWatcher *w) -{ - w->deleteLater(); - const auto callName = d_ptr->m_processingCalls.key(w); - Q_ASSERT(!callName.isEmpty()); - d_ptr->m_processingCalls.remove(callName); - if (!d_ptr->m_waittingCalls.contains(callName)) - return; - const auto args = d_ptr->m_waittingCalls.take(callName); - CallQueued(callName, args); -} diff --git a/src/frameworkdbus/dbusbamfapplication.h b/src/frameworkdbus/dbusbamfapplication.h deleted file mode 100644 index c6f2978..0000000 --- a/src/frameworkdbus/dbusbamfapplication.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c BamfApplication -p BamfApplication Application.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * Do not edit! All changes made to it will be lost. - */ - -#ifndef BAMFAPPLICATION_H -#define BAMFAPPLICATION_H - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - - -/* - * Proxy class for interface org.ayatana.bamf.application - */ -class __BamfApplicationPrivate; -class __BamfApplication : public DBusExtendedAbstractInterface -{ - Q_OBJECT - -public: - static inline const char *staticInterfaceName() - { return "org.ayatana.bamf.application"; } - -public: - explicit __BamfApplication(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent = 0); - - ~__BamfApplication(); - -public Q_SLOTS: // METHODS - inline Q_DECL_DEPRECATED QDBusPendingReply ApplicationMenu() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("ApplicationMenu"), argumentList); - } - - - inline Q_DECL_DEPRECATED QDBusReply ApplicationMenu(QString &objectpath) - { - QList argumentList; - QDBusMessage reply = callWithArgumentList(QDBus::Block, QStringLiteral("ApplicationMenu"), argumentList); - if (reply.type() == QDBusMessage::ReplyMessage && reply.arguments().count() == 2) { - objectpath = qdbus_cast(reply.arguments().at(1)); - } - return reply; - } - - inline QDBusPendingReply ApplicationType() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("ApplicationType"), argumentList); - } - - - - inline QDBusPendingReply DesktopFile() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("DesktopFile"), argumentList); - } - - - - inline QDBusPendingReply FocusableChild() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("FocusableChild"), argumentList); - } - - - - inline QDBusPendingReply ShowStubs() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("ShowStubs"), argumentList); - } - - - - inline QDBusPendingReply SupportedMimeTypes() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("SupportedMimeTypes"), argumentList); - } - - - - inline QDBusPendingReply > Xids() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("Xids"), argumentList); - } - - - - -Q_SIGNALS: // SIGNALS - void DesktopFileUpdated(const QString &desktop_file); - void SupportedMimeTypesChanged(const QStringList &dnd_mimes); - Q_DECL_DEPRECATED void WindowAdded(const QString &path); - Q_DECL_DEPRECATED void WindowRemoved(const QString &path); - // begin property changed signals - -public Q_SLOTS: - void CallQueued(const QString &callName, const QList &args); - -private Q_SLOTS: - void onPendingCallFinished(QDBusPendingCallWatcher *w); - -private: - __BamfApplicationPrivate *d_ptr; -}; - -namespace org { - namespace ayatana { - namespace bamf { - typedef ::__BamfApplication BamfApplication; - } - } -} -#endif diff --git a/src/frameworkdbus/dbusbamfmatcher.cpp b/src/frameworkdbus/dbusbamfmatcher.cpp deleted file mode 100644 index 10072c2..0000000 --- a/src/frameworkdbus/dbusbamfmatcher.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c BamfMatcher -p BamfMatcher Matcher.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * This file may have been hand-edited. Look for HAND-EDIT comments - * before re-generating it. - */ - -#include "dbusbamfmatcher.h" - -/* - * Implementation of interface class __BamfMatcher - */ - -class __BamfMatcherPrivate -{ -public: - __BamfMatcherPrivate() = default; - - // begin member variables - -public: - QMap m_processingCalls; - QMap> m_waittingCalls; -}; - -__BamfMatcher::__BamfMatcher(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent) - : DBusExtendedAbstractInterface(service, path, staticInterfaceName(), connection, parent) - , d_ptr(new __BamfMatcherPrivate) -{ - if (QMetaType::type("QList") == QMetaType::UnknownType) { - qRegisterMetaType< QList >("QList"); - qDBusRegisterMetaType< QList >(); - } -} - -__BamfMatcher::~__BamfMatcher() -{ - qDeleteAll(d_ptr->m_processingCalls.values()); - delete d_ptr; -} - -void __BamfMatcher::CallQueued(const QString &callName, const QList &args) -{ - if (d_ptr->m_waittingCalls.contains(callName)) - { - d_ptr->m_waittingCalls[callName] = args; - return; - } - if (d_ptr->m_processingCalls.contains(callName)) - { - d_ptr->m_waittingCalls.insert(callName, args); - } else { - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(asyncCallWithArgumentList(callName, args)); - connect(watcher, &QDBusPendingCallWatcher::finished, this, &__BamfMatcher::onPendingCallFinished); - d_ptr->m_processingCalls.insert(callName, watcher); - } -} - -void __BamfMatcher::onPendingCallFinished(QDBusPendingCallWatcher *w) -{ - w->deleteLater(); - const auto callName = d_ptr->m_processingCalls.key(w); - Q_ASSERT(!callName.isEmpty()); - if (callName.isEmpty()) - return; - d_ptr->m_processingCalls.remove(callName); - if (!d_ptr->m_waittingCalls.contains(callName)) - return; - const auto args = d_ptr->m_waittingCalls.take(callName); - CallQueued(callName, args); -} diff --git a/src/frameworkdbus/dbusbamfmatcher.h b/src/frameworkdbus/dbusbamfmatcher.h deleted file mode 100644 index 1c09efb..0000000 --- a/src/frameworkdbus/dbusbamfmatcher.h +++ /dev/null @@ -1,188 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c BamfMatcher -p BamfMatcher Matcher.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * Do not edit! All changes made to it will be lost. - */ - -#ifndef BAMFMATCHER_H -#define BAMFMATCHER_H - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - - -/* - * Proxy class for interface org.ayatana.bamf.matcher - */ -class __BamfMatcherPrivate; -class __BamfMatcher : public DBusExtendedAbstractInterface -{ - Q_OBJECT - -public: - static inline const char *staticInterfaceName() - { return "org.ayatana.bamf.matcher"; } - -public: - explicit __BamfMatcher(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent = 0); - - ~__BamfMatcher(); - -public Q_SLOTS: // METHODS - inline QDBusPendingReply ActiveApplication() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("ActiveApplication"), argumentList); - } - - - - inline QDBusPendingReply ActiveWindow() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("ActiveWindow"), argumentList); - } - - - - inline QDBusPendingReply ApplicationForXid(uint xid) - { - QList argumentList; - argumentList << QVariant::fromValue(xid); - return asyncCallWithArgumentList(QStringLiteral("ApplicationForXid"), argumentList); - } - - - - inline QDBusPendingReply ApplicationIsRunning(const QString &desktop_file) - { - QList argumentList; - argumentList << QVariant::fromValue(desktop_file); - return asyncCallWithArgumentList(QStringLiteral("ApplicationIsRunning"), argumentList); - } - - - - inline QDBusPendingReply ApplicationPaths() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("ApplicationPaths"), argumentList); - } - - - - inline QDBusPendingReply PathForApplication(const QString &desktop_file) - { - QList argumentList; - argumentList << QVariant::fromValue(desktop_file); - return asyncCallWithArgumentList(QStringLiteral("PathForApplication"), argumentList); - } - - - - inline QDBusPendingReply<> RegisterFavorites(const QStringList &favorites) - { - QList argumentList; - argumentList << QVariant::fromValue(favorites); - return asyncCallWithArgumentList(QStringLiteral("RegisterFavorites"), argumentList); - } - - inline void RegisterFavoritesQueued(const QStringList &favorites) - { - QList argumentList; - argumentList << QVariant::fromValue(favorites); - - CallQueued(QStringLiteral("RegisterFavorites"), argumentList); - } - - - inline QDBusPendingReply RunningApplications() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("RunningApplications"), argumentList); - } - - - - inline QDBusPendingReply RunningApplicationsDesktopFiles() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("RunningApplicationsDesktopFiles"), argumentList); - } - - - - inline QDBusPendingReply TabPaths() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("TabPaths"), argumentList); - } - - - - inline QDBusPendingReply WindowPaths() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("WindowPaths"), argumentList); - } - - - - inline QDBusPendingReply WindowStackForMonitor(int monitor_id) - { - QList argumentList; - argumentList << QVariant::fromValue(monitor_id); - return asyncCallWithArgumentList(QStringLiteral("WindowStackForMonitor"), argumentList); - } - - - - inline QDBusPendingReply > XidsForApplication(const QString &desktop_file) - { - QList argumentList; - argumentList << QVariant::fromValue(desktop_file); - return asyncCallWithArgumentList(QStringLiteral("XidsForApplication"), argumentList); - } - - - - -Q_SIGNALS: // SIGNALS - void ActiveApplicationChanged(const QString &old_app, const QString &new_app); - void ActiveWindowChanged(const QString &old_win, const QString &new_win); - void RunningApplicationsChanged(const QStringList &opened_desktop_files, const QStringList &closed_desktop_files); - void StackingOrderChanged(); - void ViewClosed(const QString &path, const QString &type); - void ViewOpened(const QString &path, const QString &type); - // begin property changed signals - -public Q_SLOTS: - void CallQueued(const QString &callName, const QList &args); - -private Q_SLOTS: - void onPendingCallFinished(QDBusPendingCallWatcher *w); - -private: - __BamfMatcherPrivate *d_ptr; -}; - -namespace org { - namespace ayatana { - namespace bamf { - typedef ::__BamfMatcher BamfMatcher; - } - } -} -#endif diff --git a/src/frameworkdbus/dbuskwaylandoutput.cpp b/src/frameworkdbus/dbuskwaylandoutput.cpp deleted file mode 100644 index 8b4f23d..0000000 --- a/src/frameworkdbus/dbuskwaylandoutput.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c OutputManagement -p generated/outputmanagement ../xml/OutputManagement.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * This file may have been hand-edited. Look for HAND-EDIT comments - * before re-generating it. - */ - -#include "dbuskwaylandoutput.h" - -/* - * Implementation of interface class __OutputManagement - */ - -class __OutputManagementPrivate -{ -public: - __OutputManagementPrivate() = default; - - // begin member variables - -public: - QMap m_processingCalls; - QMap> m_waittingCalls; -}; - -__OutputManagement::__OutputManagement(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent) - : DBusExtendedAbstractInterface(service, path, staticInterfaceName(), connection, parent) - , d_ptr(new __OutputManagementPrivate) -{ -} - -__OutputManagement::~__OutputManagement() -{ - qDeleteAll(d_ptr->m_processingCalls.values()); - delete d_ptr; -} - -void __OutputManagement::CallQueued(const QString &callName, const QList &args) -{ - if (d_ptr->m_waittingCalls.contains(callName)) - { - d_ptr->m_waittingCalls[callName] = args; - return; - } - if (d_ptr->m_processingCalls.contains(callName)) - { - d_ptr->m_waittingCalls.insert(callName, args); - } else { - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(asyncCallWithArgumentList(callName, args)); - connect(watcher, &QDBusPendingCallWatcher::finished, this, &__OutputManagement::onPendingCallFinished); - d_ptr->m_processingCalls.insert(callName, watcher); - } -} - -void __OutputManagement::onPendingCallFinished(QDBusPendingCallWatcher *w) -{ - w->deleteLater(); - const auto callName = d_ptr->m_processingCalls.key(w); - Q_ASSERT(!callName.isEmpty()); - if (callName.isEmpty()) - return; - d_ptr->m_processingCalls.remove(callName); - if (!d_ptr->m_waittingCalls.contains(callName)) - return; - const auto args = d_ptr->m_waittingCalls.take(callName); - CallQueued(callName, args); -} diff --git a/src/frameworkdbus/dbuskwaylandoutput.h b/src/frameworkdbus/dbuskwaylandoutput.h deleted file mode 100644 index b0df2e6..0000000 --- a/src/frameworkdbus/dbuskwaylandoutput.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c OutputManagement -p generated/outputmanagement ../xml/OutputManagement.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * Do not edit! All changes made to it will be lost. - */ - -#ifndef OUTPUTMANAGEMENT_H -#define OUTPUTMANAGEMENT_H - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - - -/* - * Proxy class for interface org.deepin.dde.KWayland1.Output - */ -class __OutputManagementPrivate; -class __OutputManagement : public DBusExtendedAbstractInterface -{ - Q_OBJECT - -public: - static inline const char *staticInterfaceName() - { return "org.deepin.dde.KWayland1.Output"; } - -public: - explicit __OutputManagement(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent = 0); - - ~__OutputManagement(); - -public Q_SLOTS: // METHODS - inline QDBusPendingReply<> Apply(const QString &outputs) - { - QList argumentList; - argumentList << QVariant::fromValue(outputs); - return asyncCallWithArgumentList(QStringLiteral("Apply"), argumentList); - } - - inline void ApplyQueued(const QString &outputs) - { - QList argumentList; - argumentList << QVariant::fromValue(outputs); - - CallQueued(QStringLiteral("Apply"), argumentList); - } - - - inline QDBusPendingReply GetOutput(const QString &uuid) - { - QList argumentList; - argumentList << QVariant::fromValue(uuid); - return asyncCallWithArgumentList(QStringLiteral("GetOutput"), argumentList); - } - - - - inline QDBusPendingReply ListOutput() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("ListOutput"), argumentList); - } - - - - inline QDBusPendingReply<> WlSimulateKey(int state) - { - QList argumentList; - argumentList << QVariant::fromValue(state); - return asyncCallWithArgumentList(QStringLiteral("WlSimulateKey"), argumentList); - } - - inline void WlSimulateKeyQueued(int state) - { - QList argumentList; - argumentList << QVariant::fromValue(state); - - CallQueued(QStringLiteral("WlSimulateKey"), argumentList); - } - - - -Q_SIGNALS: // SIGNALS - void OutputAdded(const QString &output); - void OutputChanged(const QString &output); - void OutputRemoved(const QString &output); - // begin property changed signals - -public Q_SLOTS: - void CallQueued(const QString &callName, const QList &args); - -private Q_SLOTS: - void onPendingCallFinished(QDBusPendingCallWatcher *w); - -private: - __OutputManagementPrivate *d_ptr; -}; - -namespace com { - namespace deepin { - namespace dde { - namespace kwayland1 { - typedef ::__OutputManagement Output; - } - } - } -} -#endif diff --git a/src/frameworkdbus/dbuskwaylandwindowmanager.cpp b/src/frameworkdbus/dbuskwaylandwindowmanager.cpp deleted file mode 100644 index 466e0a0..0000000 --- a/src/frameworkdbus/dbuskwaylandwindowmanager.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c kwaylandmanager -p kwaylandmanager org.deepin.dde.KWayland1.WindowManager.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * This file may have been hand-edited. Look for HAND-EDIT comments - * before re-generating it. - */ - -#include "dbuskwaylandwindowmanager.h" - -/* - * Implementation of interface class __kwaylandmanager - */ - -class __kwaylandmanagerPrivate -{ -public: - __kwaylandmanagerPrivate() = default; - - // begin member variables - -public: - QMap m_processingCalls; - QMap> m_waittingCalls; -}; - -__KwaylandManager::__KwaylandManager(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent) - : DBusExtendedAbstractInterface(service, path, staticInterfaceName(), connection, parent) - , d_ptr(new __kwaylandmanagerPrivate) -{ -} - -__KwaylandManager::~__KwaylandManager() -{ - qDeleteAll(d_ptr->m_processingCalls.values()); - delete d_ptr; -} - -void __KwaylandManager::CallQueued(const QString &callName, const QList &args) -{ - if (d_ptr->m_waittingCalls.contains(callName)) - { - d_ptr->m_waittingCalls[callName] = args; - return; - } - if (d_ptr->m_processingCalls.contains(callName)) - { - d_ptr->m_waittingCalls.insert(callName, args); - } else { - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(asyncCallWithArgumentList(callName, args)); - connect(watcher, &QDBusPendingCallWatcher::finished, this, &__KwaylandManager::onPendingCallFinished); - d_ptr->m_processingCalls.insert(callName, watcher); - } -} - -void __KwaylandManager::onPendingCallFinished(QDBusPendingCallWatcher *w) -{ - w->deleteLater(); - const auto callName = d_ptr->m_processingCalls.key(w); - Q_ASSERT(!callName.isEmpty()); - if (callName.isEmpty()) - return; - d_ptr->m_processingCalls.remove(callName); - if (!d_ptr->m_waittingCalls.contains(callName)) - return; - const auto args = d_ptr->m_waittingCalls.take(callName); - CallQueued(callName, args); -} diff --git a/src/frameworkdbus/dbuskwaylandwindowmanager.h b/src/frameworkdbus/dbuskwaylandwindowmanager.h deleted file mode 100644 index 1c018f0..0000000 --- a/src/frameworkdbus/dbuskwaylandwindowmanager.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c kwaylandmanager -p kwaylandmanager org.deepin.dde.KWayland1.WindowManager.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * Do not edit! All changes made to it will be lost. - */ - -#ifndef KWAYLANDMANAGER_H -#define KWAYLANDMANAGER_H - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - - -/* - * Proxy class for interface org.deepin.dde.KWayland1.WindowManager - */ -class __kwaylandmanagerPrivate; -class __KwaylandManager : public DBusExtendedAbstractInterface -{ - Q_OBJECT - -public: - static inline const char *staticInterfaceName() - { return "org.deepin.dde.KWayland1.WindowManager"; } - -public: - explicit __KwaylandManager(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent = 0); - - ~__KwaylandManager(); - -public Q_SLOTS: // METHODS - inline QDBusPendingReply ActiveWindow() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("ActiveWindow"), argumentList); - } - - - - inline QDBusPendingReply IsShowingDesktop() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsShowingDesktop"), argumentList); - } - - - - inline QDBusPendingReply Windows() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("Windows"), argumentList); - } - - - - -Q_SIGNALS: // SIGNALS - void ActiveWindowChanged(); - void WindowCreated(const QString &ObjPath); - void WindowRemove(const QString &ObjPath); - // begin property changed signals - -public Q_SLOTS: - void CallQueued(const QString &callName, const QList &args); - -private Q_SLOTS: - void onPendingCallFinished(QDBusPendingCallWatcher *w); - -private: - __kwaylandmanagerPrivate *d_ptr; -}; - -namespace org { - namespace deepin { - namespace dde { - namespace kwayland1 { - typedef ::__KwaylandManager WindowManager; - } - } - } -} -#endif diff --git a/src/frameworkdbus/dbuslauncher.cpp b/src/frameworkdbus/dbuslauncher.cpp deleted file mode 100644 index 0429fd6..0000000 --- a/src/frameworkdbus/dbuslauncher.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c Launcherd -p generated/org_deepin_dde_daemon_launcherd ../xml/org.deepin.dde.daemon.Launcherd.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * This file may have been hand-edited. Look for HAND-EDIT comments - * before re-generating it. - */ - -#include "dbuslauncher.h" - -/* - * Implementation of interface class __Launcherd - */ - -class __LauncherdPrivate -{ -public: - __LauncherdPrivate() = default; - - // begin member variables - int DisplayMode; - bool Fullscreen; - -public: - QMap m_processingCalls; - QMap> m_waittingCalls; -}; - -LauncherBackEnd::LauncherBackEnd(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent) - : DBusExtendedAbstractInterface(service, path, staticInterfaceName(), connection, parent) - , d_ptr(new __LauncherdPrivate) -{ - connect(this, &LauncherBackEnd::propertyChanged, this, &LauncherBackEnd::onPropertyChanged); - - if (QMetaType::type("LauncherItemInfo") == QMetaType::UnknownType) - registerLauncherItemInfoMetaType(); - if (QMetaType::type("LauncherItemInfoList") == QMetaType::UnknownType) - registerLauncherItemInfoListMetaType(); -} - -LauncherBackEnd::~LauncherBackEnd() -{ - qDeleteAll(d_ptr->m_processingCalls.values()); - delete d_ptr; -} - -void LauncherBackEnd::onPropertyChanged(const QString &propName, const QVariant &value) -{ - if (propName == QStringLiteral("DisplayMode")) - { - const int &DisplayMode = qvariant_cast(value); - if (d_ptr->DisplayMode != DisplayMode) - { - d_ptr->DisplayMode = DisplayMode; - Q_EMIT DisplayModeChanged(d_ptr->DisplayMode); - } - return; - } - - if (propName == QStringLiteral("Fullscreen")) - { - const bool &Fullscreen = qvariant_cast(value); - if (d_ptr->Fullscreen != Fullscreen) - { - d_ptr->Fullscreen = Fullscreen; - Q_EMIT FullscreenChanged(d_ptr->Fullscreen); - } - return; - } - - qWarning() << "property not handle: " << propName; - return; -} - -int LauncherBackEnd::displayMode() -{ - return qvariant_cast(internalPropGet("DisplayMode", &d_ptr->DisplayMode)); -} - -void LauncherBackEnd::setDisplayMode(int value) -{ - - internalPropSet("DisplayMode", QVariant::fromValue(value), &d_ptr->DisplayMode); -} - -bool LauncherBackEnd::fullscreen() -{ - return qvariant_cast(internalPropGet("Fullscreen", &d_ptr->Fullscreen)); -} - -void LauncherBackEnd::setFullscreen(bool value) -{ - - internalPropSet("Fullscreen", QVariant::fromValue(value), &d_ptr->Fullscreen); -} - -void LauncherBackEnd::CallQueued(const QString &callName, const QList &args) -{ - if (d_ptr->m_waittingCalls.contains(callName)) - { - d_ptr->m_waittingCalls[callName] = args; - return; - } - if (d_ptr->m_processingCalls.contains(callName)) - { - d_ptr->m_waittingCalls.insert(callName, args); - } else { - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(asyncCallWithArgumentList(callName, args)); - connect(watcher, &QDBusPendingCallWatcher::finished, this, &LauncherBackEnd::onPendingCallFinished); - d_ptr->m_processingCalls.insert(callName, watcher); - } -} - -void LauncherBackEnd::onPendingCallFinished(QDBusPendingCallWatcher *w) -{ - w->deleteLater(); - const auto callName = d_ptr->m_processingCalls.key(w); - Q_ASSERT(!callName.isEmpty()); - if (callName.isEmpty()) - return; - d_ptr->m_processingCalls.remove(callName); - if (!d_ptr->m_waittingCalls.contains(callName)) - return; - const auto args = d_ptr->m_waittingCalls.take(callName); - CallQueued(callName, args); -} diff --git a/src/frameworkdbus/dbuslauncher.h b/src/frameworkdbus/dbuslauncher.h deleted file mode 100644 index 4738c8d..0000000 --- a/src/frameworkdbus/dbuslauncher.h +++ /dev/null @@ -1,235 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c Launcherd -p generated/com_deepin_dde_daemon_launcher1 ../xml/org.deepin.dde.daemon.Launcher1.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * Do not edit! All changes made to it will be lost. - */ - -#ifndef ORG_DEEPIN_DDE_DAEMON_LAUNCHER1_H -#define ORG_DEEPIN_DDE_DAEMON_LAUNCHER1_H - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "types/launcheriteminfo.h" -#include "types/launcheriteminfolist.h" - -/* - * Proxy class for interface org.deepin.dde.daemon.Launcher1 - */ -class __LauncherdPrivate; -class LauncherBackEnd : public DBusExtendedAbstractInterface -{ - Q_OBJECT - -public: - static inline const char *staticInterfaceName() - { return "org.deepin.dde.daemon.Launcher1"; } - -public: - explicit LauncherBackEnd(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent = 0); - - ~LauncherBackEnd(); - - Q_PROPERTY(int DisplayMode READ displayMode WRITE setDisplayMode NOTIFY DisplayModeChanged) - int displayMode(); - void setDisplayMode(int value); - - Q_PROPERTY(bool Fullscreen READ fullscreen WRITE setFullscreen NOTIFY FullscreenChanged) - bool fullscreen(); - void setFullscreen(bool value); - -public Q_SLOTS: // METHODS - inline QDBusPendingReply GetAllItemInfos() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("GetAllItemInfos"), argumentList); - } - - - - inline QDBusPendingReply GetAllNewInstalledApps() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("GetAllNewInstalledApps"), argumentList); - } - - - - inline QDBusPendingReply GetDisableScaling(const QString &id) - { - QList argumentList; - argumentList << QVariant::fromValue(id); - return asyncCallWithArgumentList(QStringLiteral("GetDisableScaling"), argumentList); - } - - - - inline QDBusPendingReply GetItemInfo(const QString &id) - { - QList argumentList; - argumentList << QVariant::fromValue(id); - return asyncCallWithArgumentList(QStringLiteral("GetItemInfo"), argumentList); - } - - - - inline QDBusPendingReply GetUseProxy(const QString &id) - { - QList argumentList; - argumentList << QVariant::fromValue(id); - return asyncCallWithArgumentList(QStringLiteral("GetUseProxy"), argumentList); - } - - - - inline QDBusPendingReply IsItemOnDesktop(const QString &id) - { - QList argumentList; - argumentList << QVariant::fromValue(id); - return asyncCallWithArgumentList(QStringLiteral("IsItemOnDesktop"), argumentList); - } - - - - inline QDBusPendingReply<> MarkLaunched(const QString &id) - { - QList argumentList; - argumentList << QVariant::fromValue(id); - return asyncCallWithArgumentList(QStringLiteral("MarkLaunched"), argumentList); - } - - inline void MarkLaunchedQueued(const QString &id) - { - QList argumentList; - argumentList << QVariant::fromValue(id); - - CallQueued(QStringLiteral("MarkLaunched"), argumentList); - } - - - inline QDBusPendingReply RequestRemoveFromDesktop(const QString &id) - { - QList argumentList; - argumentList << QVariant::fromValue(id); - return asyncCallWithArgumentList(QStringLiteral("RequestRemoveFromDesktop"), argumentList); - } - - - - inline QDBusPendingReply RequestSendToDesktop(const QString &id) - { - QList argumentList; - argumentList << QVariant::fromValue(id); - return asyncCallWithArgumentList(QStringLiteral("RequestSendToDesktop"), argumentList); - } - - - - inline QDBusPendingReply<> RequestUninstall(const QString &id, bool purge) - { - QList argumentList; - argumentList << QVariant::fromValue(id) << QVariant::fromValue(purge); - return asyncCallWithArgumentList(QStringLiteral("RequestUninstall"), argumentList); - } - - inline void RequestUninstallQueued(const QString &id, bool purge) - { - QList argumentList; - argumentList << QVariant::fromValue(id) << QVariant::fromValue(purge); - - CallQueued(QStringLiteral("RequestUninstall"), argumentList); - } - - - inline QDBusPendingReply<> Search(const QString &key) - { - QList argumentList; - argumentList << QVariant::fromValue(key); - return asyncCallWithArgumentList(QStringLiteral("Search"), argumentList); - } - - inline void SearchQueued(const QString &key) - { - QList argumentList; - argumentList << QVariant::fromValue(key); - - CallQueued(QStringLiteral("Search"), argumentList); - } - - - inline QDBusPendingReply<> SetDisableScaling(const QString &id, bool value) - { - QList argumentList; - argumentList << QVariant::fromValue(id) << QVariant::fromValue(value); - return asyncCallWithArgumentList(QStringLiteral("SetDisableScaling"), argumentList); - } - - inline void SetDisableScalingQueued(const QString &id, bool value) - { - QList argumentList; - argumentList << QVariant::fromValue(id) << QVariant::fromValue(value); - - CallQueued(QStringLiteral("SetDisableScaling"), argumentList); - } - - - inline QDBusPendingReply<> SetUseProxy(const QString &id, bool value) - { - QList argumentList; - argumentList << QVariant::fromValue(id) << QVariant::fromValue(value); - return asyncCallWithArgumentList(QStringLiteral("SetUseProxy"), argumentList); - } - - inline void SetUseProxyQueued(const QString &id, bool value) - { - QList argumentList; - argumentList << QVariant::fromValue(id) << QVariant::fromValue(value); - - CallQueued(QStringLiteral("SetUseProxy"), argumentList); - } - - - -Q_SIGNALS: // SIGNALS - void ItemChanged(const QString &status, LauncherItemInfo itemInfo, qlonglong categoryID); - void NewAppLaunched(const QString &appID); - void SearchDone(const QStringList &apps); - void UninstallFailed(const QString &appId, const QString &errMsg); - void UninstallSuccess(const QString &appID); - // begin property changed signals - void DisplayModeChanged(int value) const; - void FullscreenChanged(bool value) const; - -public Q_SLOTS: - void CallQueued(const QString &callName, const QList &args); - -private Q_SLOTS: - void onPendingCallFinished(QDBusPendingCallWatcher *w); - void onPropertyChanged(const QString &propName, const QVariant &value); - -private: - __LauncherdPrivate *d_ptr; -}; - -namespace org { - namespace deepin { - namespace dde { - namespace daemon { - typedef ::LauncherBackEnd LauncherBackEnd; - } - } - } -} -#endif diff --git a/src/frameworkdbus/dbuslauncherfront.cpp b/src/frameworkdbus/dbuslauncherfront.cpp deleted file mode 100644 index 4d3ee85..0000000 --- a/src/frameworkdbus/dbuslauncherfront.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c Launcher -p generated/org_deepin_dde_launcher1 ../xml/org.deepin.dde.Launcher1.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * This file may have been hand-edited. Look for HAND-EDIT comments - * before re-generating it. - */ - -#include "dbuslauncherfront.h" - -/* - * Implementation of interface class __Launcher - */ - -class __LauncherPrivate -{ -public: - __LauncherPrivate() = default; - - // begin member variables - bool Visible; - -public: - QMap m_processingCalls; - QMap> m_waittingCalls; -}; - -LauncherFront::LauncherFront(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent) - : DBusExtendedAbstractInterface(service, path, staticInterfaceName(), connection, parent) - , d_ptr(new __LauncherPrivate) -{ - connect(this, &LauncherFront::propertyChanged, this, &LauncherFront::onPropertyChanged); - -} - -LauncherFront::~LauncherFront() -{ - qDeleteAll(d_ptr->m_processingCalls.values()); - delete d_ptr; -} - -void LauncherFront::onPropertyChanged(const QString &propName, const QVariant &value) -{ - if (propName == QStringLiteral("Visible")) - { - const bool &Visible = qvariant_cast(value); - if (d_ptr->Visible != Visible) - { - d_ptr->Visible = Visible; - Q_EMIT VisibleChanged(d_ptr->Visible); - } - return; - } - - qWarning() << "property not handle: " << propName; - return; -} - -bool LauncherFront::visible() -{ - return qvariant_cast(internalPropGet("Visible", &d_ptr->Visible)); -} - -void LauncherFront::CallQueued(const QString &callName, const QList &args) -{ - if (d_ptr->m_waittingCalls.contains(callName)) - { - d_ptr->m_waittingCalls[callName] = args; - return; - } - if (d_ptr->m_processingCalls.contains(callName)) - { - d_ptr->m_waittingCalls.insert(callName, args); - } else { - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(asyncCallWithArgumentList(callName, args)); - connect(watcher, &QDBusPendingCallWatcher::finished, this, &LauncherFront::onPendingCallFinished); - d_ptr->m_processingCalls.insert(callName, watcher); - } -} - -void LauncherFront::onPendingCallFinished(QDBusPendingCallWatcher *w) -{ - w->deleteLater(); - const auto callName = d_ptr->m_processingCalls.key(w); - Q_ASSERT(!callName.isEmpty()); - if (callName.isEmpty()) - return; - d_ptr->m_processingCalls.remove(callName); - if (!d_ptr->m_waittingCalls.contains(callName)) - return; - const auto args = d_ptr->m_waittingCalls.take(callName); - CallQueued(callName, args); -} diff --git a/src/frameworkdbus/dbuslauncherfront.h b/src/frameworkdbus/dbuslauncherfront.h deleted file mode 100644 index a15c441..0000000 --- a/src/frameworkdbus/dbuslauncherfront.h +++ /dev/null @@ -1,169 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c Launcher -p generated/org_deepin_dde_launcher1 ../xml/org.deepin.dde.Launcher1.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * Do not edit! All changes made to it will be lost. - */ - -#ifndef ORG_DEEPIN_DDE_LAUNCHER1_H -#define ORG_DEEPIN_DDE_LAUNCHER1_H - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - - -/* - * Proxy class for interface org.deepin.dde.Launcher1 - */ -class __LauncherPrivate; -class LauncherFront : public DBusExtendedAbstractInterface -{ - Q_OBJECT - -public: - static inline const char *staticInterfaceName() - { return "org.deepin.dde.Launcher1"; } - -public: - explicit LauncherFront(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent = 0); - - ~LauncherFront(); - - Q_PROPERTY(bool Visible READ visible NOTIFY VisibleChanged) - bool visible(); - -public Q_SLOTS: // METHODS - inline QDBusPendingReply<> Exit() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("Exit"), argumentList); - } - - inline void ExitQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("Exit"), argumentList); - } - - - inline QDBusPendingReply<> Hide() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("Hide"), argumentList); - } - - inline void HideQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("Hide"), argumentList); - } - - - inline QDBusPendingReply IsVisible() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsVisible"), argumentList); - } - - - - inline QDBusPendingReply<> Show() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("Show"), argumentList); - } - - inline void ShowQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("Show"), argumentList); - } - - - inline QDBusPendingReply<> ShowByMode(qlonglong in0) - { - QList argumentList; - argumentList << QVariant::fromValue(in0); - return asyncCallWithArgumentList(QStringLiteral("ShowByMode"), argumentList); - } - - inline void ShowByModeQueued(qlonglong in0) - { - QList argumentList; - argumentList << QVariant::fromValue(in0); - - CallQueued(QStringLiteral("ShowByMode"), argumentList); - } - - - inline QDBusPendingReply<> Toggle() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("Toggle"), argumentList); - } - - inline void ToggleQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("Toggle"), argumentList); - } - - - inline QDBusPendingReply<> UninstallApp(const QString &appKey) - { - QList argumentList; - argumentList << QVariant::fromValue(appKey); - return asyncCallWithArgumentList(QStringLiteral("UninstallApp"), argumentList); - } - - inline void UninstallAppQueued(const QString &appKey) - { - QList argumentList; - argumentList << QVariant::fromValue(appKey); - - CallQueued(QStringLiteral("UninstallApp"), argumentList); - } - - - -Q_SIGNALS: // SIGNALS - void Closed(); - void Shown(); - void VisibleChanged(bool visible); - // begin property changed signals - //void VisibleChanged(bool value) const; - -public Q_SLOTS: - void CallQueued(const QString &callName, const QList &args); - -private Q_SLOTS: - void onPendingCallFinished(QDBusPendingCallWatcher *w); - void onPropertyChanged(const QString &propName, const QVariant &value); - -private: - __LauncherPrivate *d_ptr; -}; - -namespace org { - namespace deepin { - namespace dde { - typedef ::LauncherFront LauncherFront; - } - } -} -#endif diff --git a/src/frameworkdbus/dbusplasmawindow.cpp b/src/frameworkdbus/dbusplasmawindow.cpp deleted file mode 100644 index 58a0499..0000000 --- a/src/frameworkdbus/dbusplasmawindow.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c Window -p generated/window ../xml/Window.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * This file may have been hand-edited. Look for HAND-EDIT comments - * before re-generating it. - */ - -#include "dbusplasmawindow.h" - -/* - * Implementation of interface class __Window - */ - -class __WindowPrivate -{ -public: - __WindowPrivate() = default; - - // begin member variables - -public: - QMap m_processingCalls; - QMap> m_waittingCalls; -}; - -__PlasmaWindow::__PlasmaWindow(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent) - : DBusExtendedAbstractInterface(service, path, staticInterfaceName(), connection, parent) - , d_ptr(new __WindowPrivate) -{ - if (QMetaType::type("DockRect") == QMetaType::UnknownType) - registerRectMetaType(); -} - -__PlasmaWindow::~__PlasmaWindow() -{ - qDeleteAll(d_ptr->m_processingCalls.values()); - delete d_ptr; -} - -void __PlasmaWindow::CallQueued(const QString &callName, const QList &args) -{ - if (d_ptr->m_waittingCalls.contains(callName)) - { - d_ptr->m_waittingCalls[callName] = args; - return; - } - if (d_ptr->m_processingCalls.contains(callName)) - { - d_ptr->m_waittingCalls.insert(callName, args); - } else { - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(asyncCallWithArgumentList(callName, args)); - connect(watcher, &QDBusPendingCallWatcher::finished, this, &__PlasmaWindow::onPendingCallFinished); - d_ptr->m_processingCalls.insert(callName, watcher); - } -} - -void __PlasmaWindow::onPendingCallFinished(QDBusPendingCallWatcher *w) -{ - w->deleteLater(); - const auto callName = d_ptr->m_processingCalls.key(w); - Q_ASSERT(!callName.isEmpty()); - if (callName.isEmpty()) - return; - d_ptr->m_processingCalls.remove(callName); - if (!d_ptr->m_waittingCalls.contains(callName)) - return; - const auto args = d_ptr->m_waittingCalls.take(callName); - CallQueued(callName, args); -} diff --git a/src/frameworkdbus/dbusplasmawindow.h b/src/frameworkdbus/dbusplasmawindow.h deleted file mode 100644 index 8829ce2..0000000 --- a/src/frameworkdbus/dbusplasmawindow.h +++ /dev/null @@ -1,437 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c Window -p generated/window ../xml/Window.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * Do not edit! All changes made to it will be lost. - */ - -#ifndef WINDOW_H -#define WINDOW_H - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "types/dockrect.h" - -/* - * Proxy class for interface org.deepin.dde.KWayland1.PlasmaWindow - */ -class __WindowPrivate; -class __PlasmaWindow : public DBusExtendedAbstractInterface -{ - Q_OBJECT - -public: - static inline const char *staticInterfaceName() - { return "org.deepin.dde.KWayland1.PlasmaWindow"; } - -public: - explicit __PlasmaWindow(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent = 0); - - ~__PlasmaWindow(); - -public Q_SLOTS: // METHODS - inline QDBusPendingReply AppId() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("AppId"), argumentList); - } - - inline QDBusPendingReply Geometry() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("Geometry"), argumentList); - } - - inline QDBusPendingReply Icon() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("Icon"), argumentList); - } - - inline QDBusPendingReply InternalId() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("InternalId"), argumentList); - } - - inline QDBusPendingReply IsActive() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsActive"), argumentList); - } - - inline QDBusPendingReply IsCloseable() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsCloseable"), argumentList); - } - - inline QDBusPendingReply IsDemandingAttention() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsDemandingAttention"), argumentList); - } - - inline QDBusPendingReply IsFullscreen() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsFullscreen"), argumentList); - } - - inline QDBusPendingReply IsFullscreenable() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsFullscreenable"), argumentList); - } - - inline QDBusPendingReply IsKeepAbove() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsKeepAbove"), argumentList); - } - - inline QDBusPendingReply IsMaximizeable() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsMaximizeable"), argumentList); - } - - inline QDBusPendingReply IsMaximized() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsMaximized"), argumentList); - } - - inline QDBusPendingReply IsMinimizeable() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsMinimizeable"), argumentList); - } - - inline QDBusPendingReply IsMinimized() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsMinimized"), argumentList); - } - - inline QDBusPendingReply IsMovable() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsMovable"), argumentList); - } - - inline QDBusPendingReply IsOnAllDesktops() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsOnAllDesktops"), argumentList); - } - - inline QDBusPendingReply IsResizable() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsResizable"), argumentList); - } - - inline QDBusPendingReply IsShadeable() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsShadeable"), argumentList); - } - - inline QDBusPendingReply IsShaded() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsShaded"), argumentList); - } - - inline QDBusPendingReply IsValid() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsValid"), argumentList); - } - - inline QDBusPendingReply IsVirtualDesktopChangeable() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("IsVirtualDesktopChangeable"), argumentList); - } - - inline QDBusPendingReply Pid() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("Pid"), argumentList); - } - - inline QDBusPendingReply<> RequestActivate() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("RequestActivate"), argumentList); - } - - inline void RequestActivateQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("RequestActivate"), argumentList); - } - - inline QDBusPendingReply<> RequestClose() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("RequestClose"), argumentList); - } - - inline void RequestCloseQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("RequestClose"), argumentList); - } - - inline QDBusPendingReply<> RequestEnterNewVirtualDesktop() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("RequestEnterNewVirtualDesktop"), argumentList); - } - - inline void RequestEnterNewVirtualDesktopQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("RequestEnterNewVirtualDesktop"), argumentList); - } - - inline QDBusPendingReply<> RequestEnterVirtualDesktop(const QString &argin0) - { - QList argumentList; - argumentList << QVariant::fromValue(argin0); - return asyncCallWithArgumentList(QStringLiteral("RequestEnterVirtualDesktop"), argumentList); - } - - inline void RequestEnterVirtualDesktopQueued(const QString &argin0) - { - QList argumentList; - argumentList << QVariant::fromValue(argin0); - - CallQueued(QStringLiteral("RequestEnterVirtualDesktop"), argumentList); - } - - inline QDBusPendingReply<> RequestLeaveVirtualDesktop(const QString &argin0) - { - QList argumentList; - argumentList << QVariant::fromValue(argin0); - return asyncCallWithArgumentList(QStringLiteral("RequestLeaveVirtualDesktop"), argumentList); - } - - inline void RequestLeaveVirtualDesktopQueued(const QString &argin0) - { - QList argumentList; - argumentList << QVariant::fromValue(argin0); - - CallQueued(QStringLiteral("RequestLeaveVirtualDesktop"), argumentList); - } - - inline QDBusPendingReply<> RequestMove() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("RequestMove"), argumentList); - } - - inline void RequestMoveQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("RequestMove"), argumentList); - } - - inline QDBusPendingReply<> RequestResize() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("RequestResize"), argumentList); - } - - inline void RequestResizeQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("RequestResize"), argumentList); - } - - inline QDBusPendingReply<> RequestToggleKeepAbove() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("RequestToggleKeepAbove"), argumentList); - } - - inline void RequestToggleKeepAboveQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("RequestToggleKeepAbove"), argumentList); - } - - inline QDBusPendingReply<> RequestToggleKeepBelow() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("RequestToggleKeepBelow"), argumentList); - } - - inline void RequestToggleKeepBelowQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("RequestToggleKeepBelow"), argumentList); - } - - inline QDBusPendingReply<> RequestToggleMaximized() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("RequestToggleMaximized"), argumentList); - } - - inline void RequestToggleMaximizedQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("RequestToggleMaximized"), argumentList); - } - - inline QDBusPendingReply<> RequestToggleMinimized() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("RequestToggleMinimized"), argumentList); - } - - inline void RequestToggleMinimizedQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("RequestToggleMinimized"), argumentList); - } - - inline QDBusPendingReply<> RequestToggleShaded() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("RequestToggleShaded"), argumentList); - } - - inline void RequestToggleShadedQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("RequestToggleShaded"), argumentList); - } - - inline QDBusPendingReply<> RequestVirtualDesktop(uint argin0) - { - QList argumentList; - argumentList << QVariant::fromValue(argin0); - return asyncCallWithArgumentList(QStringLiteral("RequestVirtualDesktop"), argumentList); - } - - inline void RequestVirtualDesktopQueued(uint argin0) - { - QList argumentList; - argumentList << QVariant::fromValue(argin0); - - CallQueued(QStringLiteral("RequestVirtualDesktop"), argumentList); - } - - inline QDBusPendingReply SkipSwitcher() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("SkipSwitcher"), argumentList); - } - - inline QDBusPendingReply SkipTaskbar() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("SkipTaskbar"), argumentList); - } - - inline QDBusPendingReply Title() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("Title"), argumentList); - } - - inline QDBusPendingReply VirtualDesktop() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("VirtualDesktop"), argumentList); - } - - inline QDBusPendingReply WindowId() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("WindowId"), argumentList); - } - - inline QDBusPendingReply Uuid() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("uuid"), argumentList);; - } - -Q_SIGNALS: // SIGNALS - void ActiveChanged(); - void AppIdChanged(); - void CloseableChanged(); - void DemandsAttentionChanged(); - void FullscreenChanged(); - void FullscreenableChanged(); - void GeometryChanged(); - void IconChanged(); - void KeepAboveChanged(); - void KeepBelowChanged(); - void MaximizeableChanged(); - void MaximizedChanged(); - void MinimizeableChanged(); - void MinimizedChanged(); - void MovableChanged(); - void OnAllDesktopsChanged(); - void ParentWindowChanged(); - void ResizableChanged(); - void ShadeableChanged(); - void ShadedChanged(); - void SkipSwitcherChanged(); - void SkipTaskbarChanged(); - void TitleChanged(); - void Unmapped(); - void VirtualDesktopChangeableChanged(); - void VirtualDesktopChanged(); - void WindowIdChanged(); - // begin property changed signals - -public Q_SLOTS: - void CallQueued(const QString &callName, const QList &args); - -private Q_SLOTS: - void onPendingCallFinished(QDBusPendingCallWatcher *w); - -private: - __WindowPrivate *d_ptr; -}; - -namespace org { - namespace deepin { - namespace dde { - namespace kwayland1 { - typedef ::__PlasmaWindow PlasmaWindow; - } - } - } -} -#endif diff --git a/src/frameworkdbus/dbuswm.cpp b/src/frameworkdbus/dbuswm.cpp deleted file mode 100644 index 008baee..0000000 --- a/src/frameworkdbus/dbuswm.cpp +++ /dev/null @@ -1,209 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c wm -p generated/com_deepin_wm ../xml/com.deepin.wm.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * This file may have been hand-edited. Look for HAND-EDIT comments - * before re-generating it. - */ - -#include "dbuswm.h" - -/* - * Implementation of interface class __wm - */ - -class __wmPrivate -{ -public: - __wmPrivate() = default; - - // begin member variables - bool compositingAllowSwitch; - bool compositingEnabled; - bool compositingPossible; - int cursorSize; - QString cursorTheme; - bool zoneEnabled; - -public: - QMap m_processingCalls; - QMap> m_waittingCalls; -}; - -__wm::__wm(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent) - : DBusExtendedAbstractInterface(service, path, staticInterfaceName(), connection, parent) - , d_ptr(new __wmPrivate) -{ - connect(this, &__wm::propertyChanged, this, &__wm::onPropertyChanged); - - if (QMetaType::type("QList") == QMetaType::UnknownType) { - qRegisterMetaType< QList >("QList"); - qDBusRegisterMetaType< QList >(); - } -} - -__wm::~__wm() -{ - qDeleteAll(d_ptr->m_processingCalls.values()); - delete d_ptr; -} - -void __wm::onPropertyChanged(const QString &propName, const QVariant &value) -{ - if (propName == QStringLiteral("compositingAllowSwitch")) - { - const bool &compositingAllowSwitch = qvariant_cast(value); - if (d_ptr->compositingAllowSwitch != compositingAllowSwitch) - { - d_ptr->compositingAllowSwitch = compositingAllowSwitch; - Q_EMIT CompositingAllowSwitchChanged(d_ptr->compositingAllowSwitch); - } - return; - } - - if (propName == QStringLiteral("compositingEnabled")) - { - const bool &compositingEnabled = qvariant_cast(value); - if (d_ptr->compositingEnabled != compositingEnabled) - { - d_ptr->compositingEnabled = compositingEnabled; - Q_EMIT CompositingEnabledChanged(d_ptr->compositingEnabled); - } - return; - } - - if (propName == QStringLiteral("compositingPossible")) - { - const bool &compositingPossible = qvariant_cast(value); - if (d_ptr->compositingPossible != compositingPossible) - { - d_ptr->compositingPossible = compositingPossible; - Q_EMIT CompositingPossibleChanged(d_ptr->compositingPossible); - } - return; - } - - if (propName == QStringLiteral("cursorSize")) - { - const int &cursorSize = qvariant_cast(value); - if (d_ptr->cursorSize != cursorSize) - { - d_ptr->cursorSize = cursorSize; - Q_EMIT CursorSizeChanged(d_ptr->cursorSize); - } - return; - } - - if (propName == QStringLiteral("cursorTheme")) - { - const QString &cursorTheme = qvariant_cast(value); - if (d_ptr->cursorTheme != cursorTheme) - { - d_ptr->cursorTheme = cursorTheme; - Q_EMIT CursorThemeChanged(d_ptr->cursorTheme); - } - return; - } - - if (propName == QStringLiteral("zoneEnabled")) - { - const bool &zoneEnabled = qvariant_cast(value); - if (d_ptr->zoneEnabled != zoneEnabled) - { - d_ptr->zoneEnabled = zoneEnabled; - Q_EMIT ZoneEnabledChanged(d_ptr->zoneEnabled); - } - return; - } - - qWarning() << "property not handle: " << propName; - return; -} - -bool __wm::compositingAllowSwitch() -{ - return qvariant_cast(internalPropGet("compositingAllowSwitch", &d_ptr->compositingAllowSwitch)); -} - -bool __wm::compositingEnabled() -{ - return qvariant_cast(internalPropGet("compositingEnabled", &d_ptr->compositingEnabled)); -} - -void __wm::setCompositingEnabled(bool value) -{ - - internalPropSet("compositingEnabled", QVariant::fromValue(value), &d_ptr->compositingEnabled); -} - -bool __wm::compositingPossible() -{ - return qvariant_cast(internalPropGet("compositingPossible", &d_ptr->compositingPossible)); -} - -int __wm::cursorSize() -{ - return qvariant_cast(internalPropGet("cursorSize", &d_ptr->cursorSize)); -} - -void __wm::setCursorSize(int value) -{ - - internalPropSet("cursorSize", QVariant::fromValue(value), &d_ptr->cursorSize); -} - -QString __wm::cursorTheme() -{ - return qvariant_cast(internalPropGet("cursorTheme", &d_ptr->cursorTheme)); -} - -void __wm::setCursorTheme(const QString &value) -{ - - internalPropSet("cursorTheme", QVariant::fromValue(value), &d_ptr->cursorTheme); -} - -bool __wm::zoneEnabled() -{ - return qvariant_cast(internalPropGet("zoneEnabled", &d_ptr->zoneEnabled)); -} - -void __wm::setZoneEnabled(bool value) -{ - - internalPropSet("zoneEnabled", QVariant::fromValue(value), &d_ptr->zoneEnabled); -} - -void __wm::CallQueued(const QString &callName, const QList &args) -{ - if (d_ptr->m_waittingCalls.contains(callName)) - { - d_ptr->m_waittingCalls[callName] = args; - return; - } - if (d_ptr->m_processingCalls.contains(callName)) - { - d_ptr->m_waittingCalls.insert(callName, args); - } else { - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(asyncCallWithArgumentList(callName, args)); - connect(watcher, &QDBusPendingCallWatcher::finished, this, &__wm::onPendingCallFinished); - d_ptr->m_processingCalls.insert(callName, watcher); - } -} - -void __wm::onPendingCallFinished(QDBusPendingCallWatcher *w) -{ - w->deleteLater(); - const auto callName = d_ptr->m_processingCalls.key(w); - Q_ASSERT(!callName.isEmpty()); - if (callName.isEmpty()) - return; - d_ptr->m_processingCalls.remove(callName); - if (!d_ptr->m_waittingCalls.contains(callName)) - return; - const auto args = d_ptr->m_waittingCalls.take(callName); - CallQueued(callName, args); -} diff --git a/src/frameworkdbus/dbuswm.h b/src/frameworkdbus/dbuswm.h deleted file mode 100644 index dd6f0e3..0000000 --- a/src/frameworkdbus/dbuswm.h +++ /dev/null @@ -1,708 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c wm -p generated/com_deepin_wm ../xml/com.deepin.wm.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * Do not edit! All changes made to it will be lost. - */ - -#ifndef COM_DEEPIN_WM_H -#define COM_DEEPIN_WM_H - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - - -/* - * Proxy class for interface com.deepin.wm - */ -class __wmPrivate; -class __wm : public DBusExtendedAbstractInterface -{ - Q_OBJECT - -public: - static inline const char *staticInterfaceName() - { return "com.deepin.wm"; } - -public: - explicit __wm(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent = 0); - - ~__wm(); - - Q_PROPERTY(bool compositingAllowSwitch READ compositingAllowSwitch NOTIFY CompositingAllowSwitchChanged) - bool compositingAllowSwitch(); - - Q_PROPERTY(bool compositingEnabled READ compositingEnabled WRITE setCompositingEnabled NOTIFY CompositingEnabledChanged) - bool compositingEnabled(); - void setCompositingEnabled(bool value); - - Q_PROPERTY(bool compositingPossible READ compositingPossible NOTIFY CompositingPossibleChanged) - bool compositingPossible(); - - Q_PROPERTY(int cursorSize READ cursorSize WRITE setCursorSize NOTIFY CursorSizeChanged) - int cursorSize(); - void setCursorSize(int value); - - Q_PROPERTY(QString cursorTheme READ cursorTheme WRITE setCursorTheme NOTIFY CursorThemeChanged) - QString cursorTheme(); - void setCursorTheme(const QString &value); - - Q_PROPERTY(bool zoneEnabled READ zoneEnabled WRITE setZoneEnabled NOTIFY ZoneEnabledChanged) - bool zoneEnabled(); - void setZoneEnabled(bool value); - -public Q_SLOTS: // METHODS - inline QDBusPendingReply<> BeginToMoveActiveWindow() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("BeginToMoveActiveWindow"), argumentList); - } - - inline void BeginToMoveActiveWindowQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("BeginToMoveActiveWindow"), argumentList); - } - - - inline QDBusPendingReply<> CancelPreviewWindow() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("CancelPreviewWindow"), argumentList); - } - - inline void CancelPreviewWindowQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("CancelPreviewWindow"), argumentList); - } - - - inline QDBusPendingReply<> ChangeCurrentWorkspaceBackground(const QString &uri) - { - QList argumentList; - argumentList << QVariant::fromValue(uri); - return asyncCallWithArgumentList(QStringLiteral("ChangeCurrentWorkspaceBackground"), argumentList); - } - - inline void ChangeCurrentWorkspaceBackgroundQueued(const QString &uri) - { - QList argumentList; - argumentList << QVariant::fromValue(uri); - - CallQueued(QStringLiteral("ChangeCurrentWorkspaceBackground"), argumentList); - } - - - inline QDBusPendingReply<> ClearMoveStatus() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("ClearMoveStatus"), argumentList); - } - - inline void ClearMoveStatusQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("ClearMoveStatus"), argumentList); - } - - - inline QDBusPendingReply<> EnableZoneDetected(bool enabled) - { - QList argumentList; - argumentList << QVariant::fromValue(enabled); - return asyncCallWithArgumentList(QStringLiteral("EnableZoneDetected"), argumentList); - } - - inline void EnableZoneDetectedQueued(bool enabled) - { - QList argumentList; - argumentList << QVariant::fromValue(enabled); - - CallQueued(QStringLiteral("EnableZoneDetected"), argumentList); - } - - - inline QDBusPendingReply GetAccel(const QString &id) - { - QList argumentList; - argumentList << QVariant::fromValue(id); - return asyncCallWithArgumentList(QStringLiteral("GetAccel"), argumentList); - } - - - - inline QDBusPendingReply GetAllAccels() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("GetAllAccels"), argumentList); - } - - - - inline QDBusPendingReply GetCurrentDesktopStatus() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("GetCurrentDesktopStatus"), argumentList); - } - - - - inline QDBusPendingReply GetCurrentWorkspace() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("GetCurrentWorkspace"), argumentList); - } - - - - inline QDBusPendingReply GetCurrentWorkspaceBackground() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("GetCurrentWorkspaceBackground"), argumentList); - } - - - - inline QDBusPendingReply GetCurrentWorkspaceBackgroundForMonitor(const QString &strMonitorName) - { - QList argumentList; - argumentList << QVariant::fromValue(strMonitorName); - return asyncCallWithArgumentList(QStringLiteral("GetCurrentWorkspaceBackgroundForMonitor"), argumentList); - } - - - - inline QDBusPendingReply GetDefaultAccel(const QString &id) - { - QList argumentList; - argumentList << QVariant::fromValue(id); - return asyncCallWithArgumentList(QStringLiteral("GetDefaultAccel"), argumentList); - } - - - - inline QDBusPendingReply GetIsShowDesktop() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("GetIsShowDesktop"), argumentList); - } - - - - inline QDBusPendingReply GetMultiTaskingStatus() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("GetMultiTaskingStatus"), argumentList); - } - - - - inline QDBusPendingReply GetTouchBorderInterval() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("GetTouchBorderInterval"), argumentList); - } - - - - inline QDBusPendingReply GetWorkspaceBackground(int index) - { - QList argumentList; - argumentList << QVariant::fromValue(index); - return asyncCallWithArgumentList(QStringLiteral("GetWorkspaceBackground"), argumentList); - } - - - - inline QDBusPendingReply GetWorkspaceBackgroundForMonitor(int index, const QString &strMonitorName) - { - QList argumentList; - argumentList << QVariant::fromValue(index) << QVariant::fromValue(strMonitorName); - return asyncCallWithArgumentList(QStringLiteral("GetWorkspaceBackgroundForMonitor"), argumentList); - } - - - - inline QDBusPendingReply<> MinimizeActiveWindow() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("MinimizeActiveWindow"), argumentList); - } - - inline void MinimizeActiveWindowQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("MinimizeActiveWindow"), argumentList); - } - - - inline QDBusPendingReply<> NextWorkspace() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("NextWorkspace"), argumentList); - } - - inline void NextWorkspaceQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("NextWorkspace"), argumentList); - } - - - inline QDBusPendingReply<> PerformAction(int type) - { - QList argumentList; - argumentList << QVariant::fromValue(type); - return asyncCallWithArgumentList(QStringLiteral("PerformAction"), argumentList); - } - - inline void PerformActionQueued(int type) - { - QList argumentList; - argumentList << QVariant::fromValue(type); - - CallQueued(QStringLiteral("PerformAction"), argumentList); - } - - - inline QDBusPendingReply<> PresentWindows(const QList &xids) - { - QList argumentList; - argumentList << QVariant::fromValue(xids); - return asyncCallWithArgumentList(QStringLiteral("PresentWindows"), argumentList); - } - - inline void PresentWindowsQueued(const QList &xids) - { - QList argumentList; - argumentList << QVariant::fromValue(xids); - - CallQueued(QStringLiteral("PresentWindows"), argumentList); - } - - - inline QDBusPendingReply<> PreviewWindow(uint xid) - { - QList argumentList; - argumentList << QVariant::fromValue(xid); - return asyncCallWithArgumentList(QStringLiteral("PreviewWindow"), argumentList); - } - - inline void PreviewWindowQueued(uint xid) - { - QList argumentList; - argumentList << QVariant::fromValue(xid); - - CallQueued(QStringLiteral("PreviewWindow"), argumentList); - } - - - inline QDBusPendingReply<> PreviousWorkspace() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("PreviousWorkspace"), argumentList); - } - - inline void PreviousWorkspaceQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("PreviousWorkspace"), argumentList); - } - - - inline QDBusPendingReply<> RemoveAccel(const QString &id) - { - QList argumentList; - argumentList << QVariant::fromValue(id); - return asyncCallWithArgumentList(QStringLiteral("RemoveAccel"), argumentList); - } - - inline void RemoveAccelQueued(const QString &id) - { - QList argumentList; - argumentList << QVariant::fromValue(id); - - CallQueued(QStringLiteral("RemoveAccel"), argumentList); - } - - - inline QDBusPendingReply SetAccel(const QString &data) - { - QList argumentList; - argumentList << QVariant::fromValue(data); - return asyncCallWithArgumentList(QStringLiteral("SetAccel"), argumentList); - } - - - - inline QDBusPendingReply<> SetCurrentWorkspace(int index) - { - QList argumentList; - argumentList << QVariant::fromValue(index); - return asyncCallWithArgumentList(QStringLiteral("SetCurrentWorkspace"), argumentList); - } - - inline void SetCurrentWorkspaceQueued(int index) - { - QList argumentList; - argumentList << QVariant::fromValue(index); - - CallQueued(QStringLiteral("SetCurrentWorkspace"), argumentList); - } - - - inline QDBusPendingReply<> SetCurrentWorkspaceBackground(const QString &uri) - { - QList argumentList; - argumentList << QVariant::fromValue(uri); - return asyncCallWithArgumentList(QStringLiteral("SetCurrentWorkspaceBackground"), argumentList); - } - - inline void SetCurrentWorkspaceBackgroundQueued(const QString &uri) - { - QList argumentList; - argumentList << QVariant::fromValue(uri); - - CallQueued(QStringLiteral("SetCurrentWorkspaceBackground"), argumentList); - } - - - inline QDBusPendingReply<> SetCurrentWorkspaceBackgroundForMonitor(const QString &uri, const QString &strMonitorName) - { - QList argumentList; - argumentList << QVariant::fromValue(uri) << QVariant::fromValue(strMonitorName); - return asyncCallWithArgumentList(QStringLiteral("SetCurrentWorkspaceBackgroundForMonitor"), argumentList); - } - - inline void SetCurrentWorkspaceBackgroundForMonitorQueued(const QString &uri, const QString &strMonitorName) - { - QList argumentList; - argumentList << QVariant::fromValue(uri) << QVariant::fromValue(strMonitorName); - - CallQueued(QStringLiteral("SetCurrentWorkspaceBackgroundForMonitor"), argumentList); - } - - - inline QDBusPendingReply<> SetDecorationDeepinTheme(const QString &deepinThemeName) - { - QList argumentList; - argumentList << QVariant::fromValue(deepinThemeName); - return asyncCallWithArgumentList(QStringLiteral("SetDecorationDeepinTheme"), argumentList); - } - - inline void SetDecorationDeepinThemeQueued(const QString &deepinThemeName) - { - QList argumentList; - argumentList << QVariant::fromValue(deepinThemeName); - - CallQueued(QStringLiteral("SetDecorationDeepinTheme"), argumentList); - } - - - inline QDBusPendingReply<> SetDecorationTheme(const QString &themeType, const QString &themeName) - { - QList argumentList; - argumentList << QVariant::fromValue(themeType) << QVariant::fromValue(themeName); - return asyncCallWithArgumentList(QStringLiteral("SetDecorationTheme"), argumentList); - } - - inline void SetDecorationThemeQueued(const QString &themeType, const QString &themeName) - { - QList argumentList; - argumentList << QVariant::fromValue(themeType) << QVariant::fromValue(themeName); - - CallQueued(QStringLiteral("SetDecorationTheme"), argumentList); - } - - - inline QDBusPendingReply<> SetMultiTaskingStatus(bool isActive) - { - QList argumentList; - argumentList << QVariant::fromValue(isActive); - return asyncCallWithArgumentList(QStringLiteral("SetMultiTaskingStatus"), argumentList); - } - - inline void SetMultiTaskingStatusQueued(bool isActive) - { - QList argumentList; - argumentList << QVariant::fromValue(isActive); - - CallQueued(QStringLiteral("SetMultiTaskingStatus"), argumentList); - } - - - inline QDBusPendingReply<> SetShowDesktop(bool isShowDesktop) - { - QList argumentList; - argumentList << QVariant::fromValue(isShowDesktop); - return asyncCallWithArgumentList(QStringLiteral("SetShowDesktop"), argumentList); - } - - inline void SetShowDesktopQueued(bool isShowDesktop) - { - QList argumentList; - argumentList << QVariant::fromValue(isShowDesktop); - - CallQueued(QStringLiteral("SetShowDesktop"), argumentList); - } - - - inline QDBusPendingReply<> SetTouchBorderInterval(double interval) - { - QList argumentList; - argumentList << QVariant::fromValue(interval); - return asyncCallWithArgumentList(QStringLiteral("SetTouchBorderInterval"), argumentList); - } - - inline void SetTouchBorderIntervalQueued(double interval) - { - QList argumentList; - argumentList << QVariant::fromValue(interval); - - CallQueued(QStringLiteral("SetTouchBorderInterval"), argumentList); - } - - - inline QDBusPendingReply<> SetTransientBackground(const QString &in0) - { - QList argumentList; - argumentList << QVariant::fromValue(in0); - return asyncCallWithArgumentList(QStringLiteral("SetTransientBackground"), argumentList); - } - - inline void SetTransientBackgroundQueued(const QString &in0) - { - QList argumentList; - argumentList << QVariant::fromValue(in0); - - CallQueued(QStringLiteral("SetTransientBackground"), argumentList); - } - - - inline QDBusPendingReply<> SetTransientBackgroundForMonitor(const QString &uri, const QString &strMonitorName) - { - QList argumentList; - argumentList << QVariant::fromValue(uri) << QVariant::fromValue(strMonitorName); - return asyncCallWithArgumentList(QStringLiteral("SetTransientBackgroundForMonitor"), argumentList); - } - - inline void SetTransientBackgroundForMonitorQueued(const QString &uri, const QString &strMonitorName) - { - QList argumentList; - argumentList << QVariant::fromValue(uri) << QVariant::fromValue(strMonitorName); - - CallQueued(QStringLiteral("SetTransientBackgroundForMonitor"), argumentList); - } - - - inline QDBusPendingReply<> SetWorkspaceBackground(int index, const QString &uri) - { - QList argumentList; - argumentList << QVariant::fromValue(index) << QVariant::fromValue(uri); - return asyncCallWithArgumentList(QStringLiteral("SetWorkspaceBackground"), argumentList); - } - - inline void SetWorkspaceBackgroundQueued(int index, const QString &uri) - { - QList argumentList; - argumentList << QVariant::fromValue(index) << QVariant::fromValue(uri); - - CallQueued(QStringLiteral("SetWorkspaceBackground"), argumentList); - } - - - inline QDBusPendingReply<> SetWorkspaceBackgroundForMonitor(int index, const QString &strMonitorName, const QString &uri) - { - QList argumentList; - argumentList << QVariant::fromValue(index) << QVariant::fromValue(strMonitorName) << QVariant::fromValue(uri); - return asyncCallWithArgumentList(QStringLiteral("SetWorkspaceBackgroundForMonitor"), argumentList); - } - - inline void SetWorkspaceBackgroundForMonitorQueued(int index, const QString &strMonitorName, const QString &uri) - { - QList argumentList; - argumentList << QVariant::fromValue(index) << QVariant::fromValue(strMonitorName) << QVariant::fromValue(uri); - - CallQueued(QStringLiteral("SetWorkspaceBackgroundForMonitor"), argumentList); - } - - - inline QDBusPendingReply<> ShowAllWindow() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("ShowAllWindow"), argumentList); - } - - inline void ShowAllWindowQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("ShowAllWindow"), argumentList); - } - - - inline QDBusPendingReply<> ShowWindow() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("ShowWindow"), argumentList); - } - - inline void ShowWindowQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("ShowWindow"), argumentList); - } - - - inline QDBusPendingReply<> ShowWorkspace() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("ShowWorkspace"), argumentList); - } - - inline void ShowWorkspaceQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("ShowWorkspace"), argumentList); - } - - - inline QDBusPendingReply<> SwitchApplication(bool backward) - { - QList argumentList; - argumentList << QVariant::fromValue(backward); - return asyncCallWithArgumentList(QStringLiteral("SwitchApplication"), argumentList); - } - - inline void SwitchApplicationQueued(bool backward) - { - QList argumentList; - argumentList << QVariant::fromValue(backward); - - CallQueued(QStringLiteral("SwitchApplication"), argumentList); - } - - - inline QDBusPendingReply<> SwitchToWorkspace(bool backward) - { - QList argumentList; - argumentList << QVariant::fromValue(backward); - return asyncCallWithArgumentList(QStringLiteral("SwitchToWorkspace"), argumentList); - } - - inline void SwitchToWorkspaceQueued(bool backward) - { - QList argumentList; - argumentList << QVariant::fromValue(backward); - - CallQueued(QStringLiteral("SwitchToWorkspace"), argumentList); - } - - - inline QDBusPendingReply<> TileActiveWindow(uint side) - { - QList argumentList; - argumentList << QVariant::fromValue(side); - return asyncCallWithArgumentList(QStringLiteral("TileActiveWindow"), argumentList); - } - - inline void TileActiveWindowQueued(uint side) - { - QList argumentList; - argumentList << QVariant::fromValue(side); - - CallQueued(QStringLiteral("TileActiveWindow"), argumentList); - } - - - inline QDBusPendingReply<> ToggleActiveWindowMaximize() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("ToggleActiveWindowMaximize"), argumentList); - } - - inline void ToggleActiveWindowMaximizeQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("ToggleActiveWindowMaximize"), argumentList); - } - - - inline QDBusPendingReply<> TouchToMove(int x, int y) - { - QList argumentList; - argumentList << QVariant::fromValue(x) << QVariant::fromValue(y); - return asyncCallWithArgumentList(QStringLiteral("TouchToMove"), argumentList); - } - - inline void TouchToMoveQueued(int x, int y) - { - QList argumentList; - argumentList << QVariant::fromValue(x) << QVariant::fromValue(y); - - CallQueued(QStringLiteral("TouchToMove"), argumentList); - } - - - inline QDBusPendingReply WorkspaceCount() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("WorkspaceCount"), argumentList); - } - - - - -Q_SIGNALS: // SIGNALS - void WorkspaceBackgroundChanged(int index, const QString &newUri); - void WorkspaceBackgroundChangedForMonitor(int index, const QString &strMonitorName, const QString &uri); - void WorkspaceSwitched(int from, int to); - void compositingEnabledChanged(bool enabled); - void wmCompositingEnabledChanged(bool enabled); - void workspaceCountChanged(int count); - // begin property changed signals - void CompositingAllowSwitchChanged(bool value) const; - void CompositingEnabledChanged(bool value) const; - void CompositingPossibleChanged(bool value) const; - void CursorSizeChanged(int value) const; - void CursorThemeChanged(const QString & value) const; - void ZoneEnabledChanged(bool value) const; - -public Q_SLOTS: - void CallQueued(const QString &callName, const QList &args); - -private Q_SLOTS: - void onPendingCallFinished(QDBusPendingCallWatcher *w); - void onPropertyChanged(const QString &propName, const QVariant &value); - -private: - __wmPrivate *d_ptr; -}; - -namespace com { - namespace deepin { - typedef ::__wm WM; - } -} -#endif diff --git a/src/frameworkdbus/dbuswmswitcher.cpp b/src/frameworkdbus/dbuswmswitcher.cpp deleted file mode 100644 index 9f59cd6..0000000 --- a/src/frameworkdbus/dbuswmswitcher.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c WMSwitcher -p generated/org_deepin_dde_wmswitcher1 ../xml/org.deepin.dde.WMSwitcher1.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * This file may have been hand-edited. Look for HAND-EDIT comments - * before re-generating it. - */ - -#include "dbuswmswitcher.h" - -/* - * Implementation of interface class __WMSwitcher - */ - -class __WMSwitcherPrivate -{ -public: - __WMSwitcherPrivate() = default; - - // begin member variables - -public: - QMap m_processingCalls; - QMap> m_waittingCalls; -}; - -__WMSwitcher::__WMSwitcher(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent) - : DBusExtendedAbstractInterface(service, path, staticInterfaceName(), connection, parent) - , d_ptr(new __WMSwitcherPrivate) -{ -} - -__WMSwitcher::~__WMSwitcher() -{ - qDeleteAll(d_ptr->m_processingCalls.values()); - delete d_ptr; -} - -void __WMSwitcher::CallQueued(const QString &callName, const QList &args) -{ - if (d_ptr->m_waittingCalls.contains(callName)) - { - d_ptr->m_waittingCalls[callName] = args; - return; - } - if (d_ptr->m_processingCalls.contains(callName)) - { - d_ptr->m_waittingCalls.insert(callName, args); - } else { - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(asyncCallWithArgumentList(callName, args)); - connect(watcher, &QDBusPendingCallWatcher::finished, this, &__WMSwitcher::onPendingCallFinished); - d_ptr->m_processingCalls.insert(callName, watcher); - } -} - -void __WMSwitcher::onPendingCallFinished(QDBusPendingCallWatcher *w) -{ - w->deleteLater(); - const auto callName = d_ptr->m_processingCalls.key(w); - Q_ASSERT(!callName.isEmpty()); - if (callName.isEmpty()) - return; - d_ptr->m_processingCalls.remove(callName); - if (!d_ptr->m_waittingCalls.contains(callName)) - return; - const auto args = d_ptr->m_waittingCalls.take(callName); - CallQueued(callName, args); -} diff --git a/src/frameworkdbus/dbuswmswitcher.h b/src/frameworkdbus/dbuswmswitcher.h deleted file mode 100644 index ec1578a..0000000 --- a/src/frameworkdbus/dbuswmswitcher.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c WMSwitcher -p generated/org_deepin_dde_wmswitcher1 ../xml/org.deepin.dde.WMSwitcher1.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * Do not edit! All changes made to it will be lost. - */ - -#ifndef ORG_DEEPIN_WMSWITCHER1_H -#define ORG_DEEPIN_WMSWITCHER1_H - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - - -/* - * Proxy class for interface org.deepin.dde.WMSwitcher1 - */ -class __WMSwitcherPrivate; -class __WMSwitcher : public DBusExtendedAbstractInterface -{ - Q_OBJECT - -public: - static inline const char *staticInterfaceName() - { return "org.deepin.dde.WMSwitcher1"; } - -public: - explicit __WMSwitcher(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent = 0); - - ~__WMSwitcher(); - -public Q_SLOTS: // METHODS - inline QDBusPendingReply AllowSwitch() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("AllowSwitch"), argumentList); - } - - - - inline QDBusPendingReply CurrentWM() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("CurrentWM"), argumentList); - } - - - - inline QDBusPendingReply<> RequestSwitchWM() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("RequestSwitchWM"), argumentList); - } - - inline void RequestSwitchWMQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("RequestSwitchWM"), argumentList); - } - - - inline QDBusPendingReply<> RestartWM() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("RestartWM"), argumentList); - } - - inline void RestartWMQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("RestartWM"), argumentList); - } - - - inline QDBusPendingReply<> Start2DWM() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("Start2DWM"), argumentList); - } - - inline void Start2DWMQueued() - { - QList argumentList; - - CallQueued(QStringLiteral("Start2DWM"), argumentList); - } - - - -Q_SIGNALS: // SIGNALS - void WMChanged(const QString &in0); - // begin property changed signals - -public Q_SLOTS: - void CallQueued(const QString &callName, const QList &args); - -private Q_SLOTS: - void onPendingCallFinished(QDBusPendingCallWatcher *w); - -private: - __WMSwitcherPrivate *d_ptr; -}; - -namespace org { - namespace deepin { - namespace dde { - typedef ::__WMSwitcher WMSwitcher1; - } - } -} -#endif diff --git a/src/frameworkdbus/dbusxeventmonitor.cpp b/src/frameworkdbus/dbusxeventmonitor.cpp deleted file mode 100644 index 90db842..0000000 --- a/src/frameworkdbus/dbusxeventmonitor.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c org_deepin_api_XEventMonitor -p /home/donghl/work/code/dde-dock/frame/dbusinterface/generation_dbus_interface/org_deepin_api_xeventmonitor /home/donghl/work/code/dde-dock/frame/dbusinterface/xml/org.deepin.api.XEventMonitor.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * This file may have been hand-edited. Look for HAND-EDIT comments - * before re-generating it. - */ - -#include "dbusxeventmonitor.h" - -/* - * Implementation of interface class __org_deepin_dde_XEventMonitor - */ - -class __org_deepin_dde_XEventMonitorPrivate -{ -public: - __org_deepin_dde_XEventMonitorPrivate() = default; - - // begin member variables - -public: - QMap m_processingCalls; - QMap> m_waittingCalls; -}; - -__org_deepin_dde_XEventMonitor::__org_deepin_dde_XEventMonitor(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent) - : DBusExtendedAbstractInterface(service, path, staticInterfaceName(), connection, parent) - , d_ptr(new __org_deepin_dde_XEventMonitorPrivate) -{ - if (QMetaType::type("AreaList") == QMetaType::UnknownType) - registerAreaListMetaType(); -} - -__org_deepin_dde_XEventMonitor::~__org_deepin_dde_XEventMonitor() -{ - qDeleteAll(d_ptr->m_processingCalls.values()); - delete d_ptr; -} - -void __org_deepin_dde_XEventMonitor::CallQueued(const QString &callName, const QList &args) -{ - if (d_ptr->m_waittingCalls.contains(callName)) { - d_ptr->m_waittingCalls[callName] = args; - return; - } - if (d_ptr->m_processingCalls.contains(callName)) { - d_ptr->m_waittingCalls.insert(callName, args); - } else { - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(asyncCallWithArgumentList(callName, args)); - connect(watcher, &QDBusPendingCallWatcher::finished, this, &__org_deepin_dde_XEventMonitor::onPendingCallFinished); - d_ptr->m_processingCalls.insert(callName, watcher); - } -} - -void __org_deepin_dde_XEventMonitor::onPendingCallFinished(QDBusPendingCallWatcher *w) -{ - w->deleteLater(); - const auto callName = d_ptr->m_processingCalls.key(w); - Q_ASSERT(!callName.isEmpty()); - if (callName.isEmpty()) - return; - - d_ptr->m_processingCalls.remove(callName); - if (!d_ptr->m_waittingCalls.contains(callName)) - return; - - const auto args = d_ptr->m_waittingCalls.take(callName); - CallQueued(callName, args); -} diff --git a/src/frameworkdbus/dbusxeventmonitor.h b/src/frameworkdbus/dbusxeventmonitor.h deleted file mode 100644 index d6b557d..0000000 --- a/src/frameworkdbus/dbusxeventmonitor.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * This file was generated by qdbusxml2cpp-fix version 0.8 - * Command line was: qdbusxml2cpp-fix -c org_deepin_api_XEventMonitor -p /home/donghl/work/code/dde-dock/frame/dbusinterface/generation_dbus_interface/org_deepin_api_xeventmonitor /home/donghl/work/code/dde-dock/frame/dbusinterface/xml/org.deepin.api.XEventMonitor.xml - * - * qdbusxml2cpp-fix is Copyright (C) 2016 Deepin Technology Co., Ltd. - * - * This is an auto-generated file. - * Do not edit! All changes made to it will be lost. - */ - -#ifndef ORG_DEEPIN_API_XEVENTMONITOR_H -#define ORG_DEEPIN_API_XEVENTMONITOR_H - -#include "types/arealist.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -/* - * Proxy class for interface org.deepin.dde.XEventMonitor1 - */ -class __org_deepin_dde_XEventMonitorPrivate; -class __org_deepin_dde_XEventMonitor : public DBusExtendedAbstractInterface -{ - Q_OBJECT - -public: - static inline const char *staticInterfaceName() - { return "org.deepin.dde.XEventMonitor1"; } - -public: - explicit __org_deepin_dde_XEventMonitor(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent = 0); - - ~__org_deepin_dde_XEventMonitor(); - -public Q_SLOTS: // METHODS - inline QDBusPendingReply RegisterArea(int in0, int in1, int in2, int in3, int in4) - { - QList argumentList; - argumentList << QVariant::fromValue(in0) << QVariant::fromValue(in1) << QVariant::fromValue(in2) << QVariant::fromValue(in3) << QVariant::fromValue(in4); - return asyncCallWithArgumentList(QStringLiteral("RegisterArea"), argumentList); - } - - inline QDBusPendingReply RegisterAreas(AreaList in0, int in1) - { - QList argumentList; - argumentList << QVariant::fromValue(in0) << QVariant::fromValue(in1); - return asyncCallWithArgumentList(QStringLiteral("RegisterAreas"), argumentList); - } - - inline QDBusPendingReply RegisterFullScreen() - { - QList argumentList; - return asyncCallWithArgumentList(QStringLiteral("RegisterFullScreen"), argumentList); - } - - inline QDBusPendingReply UnregisterArea(const QString &in0) - { - QList argumentList; - argumentList << QVariant::fromValue(in0); - return asyncCallWithArgumentList(QStringLiteral("UnregisterArea"), argumentList); - } - -Q_SIGNALS: // SIGNALS - void ButtonPress(int in0, int in1, int in2, const QString &in3); - void ButtonRelease(int in0, int in1, int in2, const QString &in3); - void CancelAllArea(); - void CursorInto(int in0, int in1, const QString &in2); - void CursorMove(int in0, int in1, const QString &in2); - void CursorOut(int in0, int in1, const QString &in2); - void KeyPress(const QString &in0, int in1, int in2, const QString &in3); - void KeyRelease(const QString &in0, int in1, int in2, const QString &in3); - // begin property changed signals - -public Q_SLOTS: - void CallQueued(const QString &callName, const QList &args); - -private Q_SLOTS: - void onPendingCallFinished(QDBusPendingCallWatcher *w); - -private: - __org_deepin_dde_XEventMonitorPrivate *d_ptr; -}; - -namespace org { - namespace deepin { - namespace dde { - typedef ::__org_deepin_dde_XEventMonitor XEventMonitor1; - } - } -} - -#endif diff --git a/src/frameworkdbus/qtdbusextended/DBusExtended b/src/frameworkdbus/qtdbusextended/DBusExtended deleted file mode 100644 index 719c49b..0000000 --- a/src/frameworkdbus/qtdbusextended/DBusExtended +++ /dev/null @@ -1 +0,0 @@ -#include "dbusextended.h" diff --git a/src/frameworkdbus/qtdbusextended/DBusExtendedAbstractInterface b/src/frameworkdbus/qtdbusextended/DBusExtendedAbstractInterface deleted file mode 100644 index 246af8a..0000000 --- a/src/frameworkdbus/qtdbusextended/DBusExtendedAbstractInterface +++ /dev/null @@ -1 +0,0 @@ -#include "dbusextendedabstractinterface.h" diff --git a/src/frameworkdbus/qtdbusextended/dbusextended.h b/src/frameworkdbus/qtdbusextended/dbusextended.h deleted file mode 100644 index ac29201..0000000 --- a/src/frameworkdbus/qtdbusextended/dbusextended.h +++ /dev/null @@ -1,15 +0,0 @@ -// SPDX-FileCopyrightText: 2015 Jolla Ltd. -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef QT_DBUS_EXTENDED_H -#define QT_DBUS_EXTENDED_H - -#if defined(QT_DBUS_EXTENDED_LIBRARY) -# define QT_DBUS_EXTENDED_EXPORT Q_DECL_EXPORT -#else -# define QT_DBUS_EXTENDED_EXPORT Q_DECL_IMPORT -#endif - -#endif /* QT_DBUS_EXTENDED_H */ diff --git a/src/frameworkdbus/qtdbusextended/dbusextendedabstractinterface.cpp b/src/frameworkdbus/qtdbusextended/dbusextendedabstractinterface.cpp deleted file mode 100644 index 0e6d6e0..0000000 --- a/src/frameworkdbus/qtdbusextended/dbusextendedabstractinterface.cpp +++ /dev/null @@ -1,505 +0,0 @@ -// SPDX-FileCopyrightText: 2015 Jolla Ltd. -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "dbusextendedpendingcallwatcher_p.h" - -#include - -#include -#include -#include -#include -#include - -#include -#include - - -Q_GLOBAL_STATIC_WITH_ARGS(QByteArray, dBusInterface, ("org.freedesktop.DBus")) -Q_GLOBAL_STATIC_WITH_ARGS(QByteArray, dBusPropertiesInterface, ("org.freedesktop.DBus.Properties")) -Q_GLOBAL_STATIC_WITH_ARGS(QByteArray, dBusPropertiesChangedSignal, ("PropertiesChanged")) -Q_GLOBAL_STATIC_WITH_ARGS(QByteArray, propertyChangedSignature, ("propertyChanged(QString,QVariant)")) -Q_GLOBAL_STATIC_WITH_ARGS(QByteArray, propertyInvalidatedSignature, ("propertyInvalidated(QString)")) - - -DBusExtendedAbstractInterface::DBusExtendedAbstractInterface(const QString &service, const QString &path, const char *interface, const QDBusConnection &connection, QObject *parent) - : QDBusAbstractInterface(service, path, interface, connection, parent) - , m_sync(true) - , m_useCache(false) - , m_getAllPendingCallWatcher(0) - , m_propertiesChangedConnected(false) -{ - const_cast(connection).connect(QString("org.freedesktop.DBus"), QString("/org/freedesktop/DBus"), QString("org.freedesktop.DBus"), QString("NameOwnerChanged"), this, SLOT(onDBusNameOwnerChanged(QString,QString,QString))); -} - -DBusExtendedAbstractInterface::~DBusExtendedAbstractInterface() -{ -} - -void DBusExtendedAbstractInterface::setSync(bool sync) { setSync(sync, true); } - -/* - * Note: After sync is set to false, it will always return a empty value - * if you call the property's get function directly. So you can only get it - * through the changed signal when you get an property, and it's also a good idea - * to save a cache yourself. - */ - -/* - * 注意: 如果设置 sync 为 false 那么在调用属性的 get 函数获取一个属性时会一直返回空值, - * 解决方法是监听属性的 changed 信号并自行保存一份缓存, 让 changed 信号修改这个缓存 - */ -void DBusExtendedAbstractInterface::setSync(bool sync, bool autoStart) -{ - m_sync = sync; - - // init all properties - if (autoStart && !m_sync && !isValid()) - startServiceProcess(); -} - -void DBusExtendedAbstractInterface::getAllProperties() -{ - m_lastExtendedError = QDBusError(); - - if (!isValid()) { - QString errorMessage = QStringLiteral("This Extended DBus interface is not valid yet."); - m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage); - qDebug() << Q_FUNC_INFO << errorMessage; - return; - } - - if (!m_sync && m_getAllPendingCallWatcher) { - // Call already in place, not repeating ... - return; - } - - QDBusMessage msg = QDBusMessage::createMethodCall(service(), path(), *dBusPropertiesInterface(), QStringLiteral("GetAll")); - msg << interface(); - - if (m_sync) { - QDBusMessage reply = connection().call(msg); - - if (reply.type() != QDBusMessage::ReplyMessage) { - m_lastExtendedError = QDBusError(reply); - qWarning() << Q_FUNC_INFO << m_lastExtendedError.message(); - return; - } - - if (reply.signature() != QLatin1String("a{sv}")) { - QString errorMessage = QStringLiteral("Invalid signature \"%1\" in return from call to %2") - .arg(reply.signature(), - QString(*dBusPropertiesInterface())); - qWarning() << Q_FUNC_INFO << errorMessage; - m_lastExtendedError = QDBusError(QDBusError::InvalidSignature, errorMessage); - return; - } - - QVariantMap value = reply.arguments().at(0).toMap(); - onPropertiesChanged(interface(), value, QStringList()); - } else { - QDBusPendingReply async = connection().asyncCall(msg); - m_getAllPendingCallWatcher = new QDBusPendingCallWatcher(async, this); - - connect(m_getAllPendingCallWatcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(onAsyncGetAllPropertiesFinished(QDBusPendingCallWatcher*))); - return; - } -} - -void DBusExtendedAbstractInterface::connectNotify(const QMetaMethod &signal) -{ - if (signal.methodType() == QMetaMethod::Signal - && (signal.methodSignature() == *propertyChangedSignature() - || signal.methodSignature() == *propertyInvalidatedSignature())) { - if (!m_propertiesChangedConnected) { - QStringList argumentMatch; - argumentMatch << interface(); - connection().connect(service(), path(), *dBusPropertiesInterface(), *dBusPropertiesChangedSignal(), - argumentMatch, QString(), - this, SLOT(onPropertiesChanged(QString, QVariantMap, QStringList))); - - m_propertiesChangedConnected = true; - return; - } - } else { - QDBusAbstractInterface::connectNotify(signal); - } -} - -void DBusExtendedAbstractInterface::disconnectNotify(const QMetaMethod &signal) -{ - if (signal.methodType() == QMetaMethod::Signal - && (signal.methodSignature() == *propertyChangedSignature() - || signal.methodSignature() == *propertyInvalidatedSignature())) { - if (m_propertiesChangedConnected - && 0 == receivers(propertyChangedSignature()->constData()) - && 0 == receivers(propertyInvalidatedSignature()->constData())) { - QStringList argumentMatch; - argumentMatch << interface(); - connection().disconnect(service(), path(), *dBusPropertiesInterface(), *dBusPropertiesChangedSignal(), - argumentMatch, QString(), - this, SLOT(onPropertiesChanged(QString, QVariantMap, QStringList))); - - m_propertiesChangedConnected = false; - return; - } - } else { - QDBusAbstractInterface::disconnectNotify(signal); - } -} - -QVariant DBusExtendedAbstractInterface::internalPropGet(const char *propname, void *propertyPtr) -{ - m_lastExtendedError = QDBusError(); - - if (m_useCache) { - int propertyIndex = metaObject()->indexOfProperty(propname); - QMetaProperty metaProperty = metaObject()->property(propertyIndex); - return QVariant(metaProperty.userType(), propertyPtr); - } - - if (m_sync) { - QVariant ret = property(propname); - - QMetaType::construct(ret.userType(), propertyPtr, ret.constData()); - - return ret; - } else { - if (!isValid()) { - QString errorMessage = QStringLiteral("This Extended DBus interface is not valid yet."); - m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage); - qDebug() << Q_FUNC_INFO << errorMessage; - return QVariant(); - } - - int propertyIndex = metaObject()->indexOfProperty(propname); - - if (-1 == propertyIndex) { - QString errorMessage = QStringLiteral("Got unknown property \"%1\" to read") - .arg(QString::fromLatin1(propname)); - m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage); - qWarning() << Q_FUNC_INFO << errorMessage; - return QVariant(); - } - - QMetaProperty metaProperty = metaObject()->property(propertyIndex); - - if (!metaProperty.isReadable()) { - QString errorMessage = QStringLiteral("Property \"%1\" is NOT readable") - .arg(QString::fromLatin1(propname)); - m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage); - qWarning() << Q_FUNC_INFO << errorMessage; - return QVariant(); - } - - // is this metatype registered? - const char *expectedSignature = ""; - if (int(metaProperty.type()) != QMetaType::QVariant) { - expectedSignature = QDBusMetaType::typeToSignature(metaProperty.userType()); - if (0 == expectedSignature) { - QString errorMessage = - QStringLiteral("Type %1 must be registered with Qt D-Bus " - "before it can be used to read property " - "%2.%3") - .arg(metaProperty.typeName(), - interface(), - propname); - m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage); - qWarning() << Q_FUNC_INFO << errorMessage; - return QVariant(); - } - } - - asyncProperty(propname); - return QVariant(metaProperty.userType(), propertyPtr); - } -} - -void DBusExtendedAbstractInterface::internalPropSet(const char *propname, const QVariant &value, void *propertyPtr) -{ - m_lastExtendedError = QDBusError(); - - if (m_sync) { - setProperty(propname, value); - } else { - if (!isValid()) { - QString errorMessage = QStringLiteral("This interface is not yet valid"); - m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage); - qDebug() << Q_FUNC_INFO << errorMessage; - return; - } - - int propertyIndex = metaObject()->indexOfProperty(propname); - - if (-1 == propertyIndex) { - QString errorMessage = QStringLiteral("Got unknown property \"%1\" to write") - .arg(QString::fromLatin1(propname)); - m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage); - qWarning() << Q_FUNC_INFO << errorMessage; - return; - } - - QMetaProperty metaProperty = metaObject()->property(propertyIndex); - - if (!metaProperty.isWritable()) { - QString errorMessage = QStringLiteral("Property \"%1\" is NOT writable") - .arg(QString::fromLatin1(propname)); - m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage); - qWarning() << Q_FUNC_INFO << errorMessage; - return; - } - - QVariant variant = QVariant(metaProperty.type(), propertyPtr); - variant = value; - - asyncSetProperty(propname, variant); - } -} - -QVariant DBusExtendedAbstractInterface::asyncProperty(const QString &propertyName) -{ - QDBusMessage msg = QDBusMessage::createMethodCall(service(), path(), *dBusPropertiesInterface(), QStringLiteral("Get")); - msg << interface() << propertyName; - QDBusPendingReply async = connection().asyncCall(msg); - DBusExtendedPendingCallWatcher *watcher = new DBusExtendedPendingCallWatcher(async, propertyName, QVariant(), this); - - connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(onAsyncPropertyFinished(QDBusPendingCallWatcher*))); - - return QVariant(); -} - -void DBusExtendedAbstractInterface::asyncSetProperty(const QString &propertyName, const QVariant &value) -{ - QDBusMessage msg = QDBusMessage::createMethodCall(service(), path(), *dBusPropertiesInterface(), QStringLiteral("Set")); - - msg << interface() << propertyName << QVariant::fromValue(QDBusVariant(value)); - QDBusPendingReply<> async = connection().asyncCall(msg); - DBusExtendedPendingCallWatcher *watcher = new DBusExtendedPendingCallWatcher(async, propertyName, value, this); - - connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(onAsyncSetPropertyFinished(QDBusPendingCallWatcher*))); -} - -void DBusExtendedAbstractInterface::startServiceProcess() -{ - const QString &servName = service(); - - if (isValid()) - { - qWarning() << "Service" << servName << "is already started."; - return; - } - - QDBusMessage msg = QDBusMessage::createMethodCall("org.freedesktop.DBus", "/", *dBusInterface(), QStringLiteral("StartServiceByName")); - msg << servName << quint32(0); - QDBusPendingReply async = connection().asyncCall(msg); - QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(async, this); - - connect(watcher, &QDBusPendingCallWatcher::finished, this, &DBusExtendedAbstractInterface::onStartServiceProcessFinished); -} - -void DBusExtendedAbstractInterface::onStartServiceProcessFinished(QDBusPendingCallWatcher *w) -{ - if (w->isError()) - { - m_lastExtendedError = w->error(); - } else { - m_lastExtendedError = QDBusError(); - } - - QDBusPendingReply reply = *w; - - Q_EMIT serviceStartFinished(reply.value()); - - w->deleteLater(); -} - -void DBusExtendedAbstractInterface::onAsyncPropertyFinished(QDBusPendingCallWatcher *w) -{ - DBusExtendedPendingCallWatcher *watcher = qobject_cast(w); - Q_ASSERT(watcher); - - QDBusPendingReply reply = *watcher; - - if (reply.isError()) { - m_lastExtendedError = reply.error(); - } else { - int propertyIndex = metaObject()->indexOfProperty(watcher->asyncProperty().toLatin1().constData()); - QVariant value = demarshall(interface(), - metaObject()->property(propertyIndex), - reply.value(), - &m_lastExtendedError); - - if (m_lastExtendedError.isValid()) { - Q_EMIT propertyInvalidated(watcher->asyncProperty()); - } else { - Q_EMIT propertyChanged(watcher->asyncProperty(), value); - } - } - - Q_EMIT asyncPropertyFinished(watcher->asyncProperty()); - watcher->deleteLater(); -} - -void DBusExtendedAbstractInterface::onAsyncSetPropertyFinished(QDBusPendingCallWatcher *w) -{ - DBusExtendedPendingCallWatcher *watcher = qobject_cast(w); - Q_ASSERT(watcher); - - QDBusPendingReply<> reply = *watcher; - - if (reply.isError()) { - m_lastExtendedError = reply.error(); - } else { - m_lastExtendedError = QDBusError(); - } - - Q_EMIT asyncSetPropertyFinished(watcher->asyncProperty()); - - // Resetting the property to its previous value after sending the - // finished signal - if (reply.isError()) { - m_lastExtendedError = QDBusError(); - Q_EMIT propertyChanged(watcher->asyncProperty(), watcher->previousValue()); - } - - watcher->deleteLater(); -} - -void DBusExtendedAbstractInterface::onAsyncGetAllPropertiesFinished(QDBusPendingCallWatcher *watcher) -{ - m_getAllPendingCallWatcher = 0; - - QDBusPendingReply reply = *watcher; - - if (reply.isError()) { - m_lastExtendedError = reply.error(); - } else { - m_lastExtendedError = QDBusError(); - } - - Q_EMIT asyncGetAllPropertiesFinished(); - - if (!reply.isError()) { - onPropertiesChanged(interface(), reply.value(), QStringList()); - } - - watcher->deleteLater(); -} - -void DBusExtendedAbstractInterface::onPropertiesChanged(const QString& interfaceName, - const QVariantMap& changedProperties, - const QStringList& invalidatedProperties) -{ - if (interfaceName == interface()) { - QVariantMap::const_iterator i = changedProperties.constBegin(); - while (i != changedProperties.constEnd()) { - int propertyIndex = metaObject()->indexOfProperty(i.key().toLatin1().constData()); - - if (-1 == propertyIndex) { - qDebug() << Q_FUNC_INFO << "Got unknown changed property" << i.key(); - } else { - QVariant value = demarshall(interface(), metaObject()->property(propertyIndex), i.value(), &m_lastExtendedError); - - if (m_lastExtendedError.isValid()) { - Q_EMIT propertyInvalidated(i.key()); - } else { - Q_EMIT propertyChanged(i.key(), value); - } - } - - ++i; - } - - QStringList::const_iterator j = invalidatedProperties.constBegin(); - while (j != invalidatedProperties.constEnd()) { - if (-1 == metaObject()->indexOfProperty(j->toLatin1().constData())) { - qDebug() << Q_FUNC_INFO << "Got unknown invalidated property" << *j; - } else { - m_lastExtendedError = QDBusError(); - Q_EMIT propertyInvalidated(*j); - } - - ++j; - } - } -} - -void DBusExtendedAbstractInterface::onDBusNameOwnerChanged(const QString &name, const QString &oldOwner, const QString &newOwner) -{ - if (name == service() && oldOwner.isEmpty()) - { - m_dbusOwner = newOwner; - Q_EMIT serviceValidChanged(true); - } - else if (name == m_dbusOwner && newOwner.isEmpty()) - { - m_dbusOwner.clear(); - Q_EMIT serviceValidChanged(false); - } -} - -QVariant DBusExtendedAbstractInterface::demarshall(const QString &interface, const QMetaProperty &metaProperty, const QVariant &value, QDBusError *error) -{ - Q_ASSERT(metaProperty.isValid()); - Q_ASSERT(error != 0); - - if (value.userType() == metaProperty.userType()) { - // No need demarshalling. Passing back straight away ... - *error = QDBusError(); - return value; - } - - QVariant result = QVariant(metaProperty.userType(), (void*)0); - QString errorMessage; - const char *expectedSignature = QDBusMetaType::typeToSignature(metaProperty.userType()); - - if (value.userType() == qMetaTypeId()) { - // demarshalling a DBus argument ... - QDBusArgument dbusArg = value.value(); - - if (expectedSignature == dbusArg.currentSignature().toLatin1()) { - QDBusMetaType::demarshall(dbusArg, metaProperty.userType(), result.data()); - if (!result.isValid()) { - errorMessage = QStringLiteral("Unexpected failure demarshalling " - "upon PropertiesChanged signal arrival " - "for property `%3.%4' (expected type `%5' (%6))") - .arg(interface, - QString::fromLatin1(metaProperty.name()), - QString::fromLatin1(metaProperty.typeName()), - expectedSignature); - } - } else { - errorMessage = QStringLiteral("Unexpected `user type' (%2) " - "upon PropertiesChanged signal arrival " - "for property `%3.%4' (expected type `%5' (%6))") - .arg(dbusArg.currentSignature(), - interface, - QString::fromLatin1(metaProperty.name()), - QString::fromLatin1(metaProperty.typeName()), - QString::fromLatin1(expectedSignature)); - } - } else { - const char *actualSignature = QDBusMetaType::typeToSignature(value.userType()); - - errorMessage = QStringLiteral("Unexpected `%1' (%2) " - "upon PropertiesChanged signal arrival " - "for property `%3.%4' (expected type `%5' (%6))") - .arg(QString::fromLatin1(value.typeName()), - QString::fromLatin1(actualSignature), - interface, - QString::fromLatin1(metaProperty.name()), - QString::fromLatin1(metaProperty.typeName()), - QString::fromLatin1(expectedSignature)); - } - - if (errorMessage.isEmpty()) { - *error = QDBusError(); - } else { - *error = QDBusMessage::createError(QDBusError::InvalidSignature, errorMessage); - qDebug() << Q_FUNC_INFO << errorMessage; - } - - return result; -} diff --git a/src/frameworkdbus/qtdbusextended/dbusextendedabstractinterface.h b/src/frameworkdbus/qtdbusextended/dbusextendedabstractinterface.h deleted file mode 100644 index 3113172..0000000 --- a/src/frameworkdbus/qtdbusextended/dbusextendedabstractinterface.h +++ /dev/null @@ -1,83 +0,0 @@ -// SPDX-FileCopyrightText: 2015 Jolla Ltd. -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef DBUSEXTENDEDABSTRACTINTERFACE_H -#define DBUSEXTENDEDABSTRACTINTERFACE_H - -#include - -#include -#include - -class QDBusPendingCallWatcher; -class DBusExtendedPendingCallWatcher; - -class QT_DBUS_EXTENDED_EXPORT DBusExtendedAbstractInterface: public QDBusAbstractInterface -{ - Q_OBJECT - -public: - virtual ~DBusExtendedAbstractInterface(); - - Q_PROPERTY(bool sync READ sync WRITE setSync) - inline bool sync() const { return m_sync; } - void setSync(bool sync); - void setSync(bool sync, bool autoStart); - - Q_PROPERTY(bool useCache READ useCache WRITE setUseCache) - inline bool useCache() const { return m_useCache; } - inline void setUseCache(bool useCache) { m_useCache = useCache; } - - void getAllProperties(); - inline QDBusError lastExtendedError() const { return m_lastExtendedError; } - -public Q_SLOTS: - void startServiceProcess(); - -protected: - DBusExtendedAbstractInterface(const QString &service, - const QString &path, - const char *interface, - const QDBusConnection &connection, - QObject *parent); - - void connectNotify(const QMetaMethod &signal); - void disconnectNotify(const QMetaMethod &signal); - QVariant internalPropGet(const char *propname, void *propertyPtr); - void internalPropSet(const char *propname, const QVariant &value, void *propertyPtr); - -Q_SIGNALS: - void serviceValidChanged(const bool valid) const; - void serviceStartFinished(const quint32 ret) const; - void propertyChanged(const QString &propertyName, const QVariant &value); - void propertyInvalidated(const QString &propertyName); - void asyncPropertyFinished(const QString &propertyName); - void asyncSetPropertyFinished(const QString &propertyName); - void asyncGetAllPropertiesFinished(); - -private Q_SLOTS: - void onPropertiesChanged(const QString& interfaceName, - const QVariantMap& changedProperties, - const QStringList& invalidatedProperties); - void onDBusNameOwnerChanged(const QString &name, const QString &oldOwner, const QString &newOwner); - void onAsyncPropertyFinished(QDBusPendingCallWatcher *w); - void onAsyncSetPropertyFinished(QDBusPendingCallWatcher *w); - void onAsyncGetAllPropertiesFinished(QDBusPendingCallWatcher *watcher); - void onStartServiceProcessFinished(QDBusPendingCallWatcher *w); - -private: - QVariant asyncProperty(const QString &propertyName); - void asyncSetProperty(const QString &propertyName, const QVariant &value); - static QVariant demarshall(const QString &interface, const QMetaProperty &metaProperty, const QVariant &value, QDBusError *error); - - bool m_sync; - bool m_useCache; - QDBusPendingCallWatcher *m_getAllPendingCallWatcher; - QDBusError m_lastExtendedError; - QString m_dbusOwner; - bool m_propertiesChangedConnected; -}; - -#endif /* DBUSEXTENDEDABSTRACTINTERFACE_H */ diff --git a/src/frameworkdbus/qtdbusextended/dbusextendedpendingcallwatcher.cpp b/src/frameworkdbus/qtdbusextended/dbusextendedpendingcallwatcher.cpp deleted file mode 100644 index 3ef6498..0000000 --- a/src/frameworkdbus/qtdbusextended/dbusextendedpendingcallwatcher.cpp +++ /dev/null @@ -1,18 +0,0 @@ -// SPDX-FileCopyrightText: 2015 Jolla Ltd. -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "dbusextendedpendingcallwatcher_p.h" - - -DBusExtendedPendingCallWatcher::DBusExtendedPendingCallWatcher(const QDBusPendingCall &call, const QString &asyncProperty, const QVariant &previousValue, QObject *parent) - : QDBusPendingCallWatcher(call, parent) - , m_asyncProperty(asyncProperty) - , m_previousValue(previousValue) -{ -} - -DBusExtendedPendingCallWatcher::~DBusExtendedPendingCallWatcher() -{ -} diff --git a/src/frameworkdbus/qtdbusextended/dbusextendedpendingcallwatcher_p.h b/src/frameworkdbus/qtdbusextended/dbusextendedpendingcallwatcher_p.h deleted file mode 100644 index d00210d..0000000 --- a/src/frameworkdbus/qtdbusextended/dbusextendedpendingcallwatcher_p.h +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-FileCopyrightText: 2015 Jolla Ltd. -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -// -// W A R N I N G -// ------------- -// -// This file is not part of the public API. This header file may -// change from version to version without notice, or even be -// removed. -// -// We mean it. -// -// - - -#ifndef DBUSEXTENDEDPENDINGCALLWATCHER_P_H -#define DBUSEXTENDEDPENDINGCALLWATCHER_P_H - -#include -#include - -class DBusExtendedPendingCallWatcher: public QDBusPendingCallWatcher -{ - Q_OBJECT - -public: - explicit DBusExtendedPendingCallWatcher(const QDBusPendingCall &call, - const QString &asyncProperty, - const QVariant &previousValue, - QObject *parent = 0); - ~DBusExtendedPendingCallWatcher(); - - Q_PROPERTY(QString AsyncProperty READ asyncProperty) - inline QString asyncProperty() const { return m_asyncProperty; } - - Q_PROPERTY(QVariant PreviousValue READ previousValue) - inline QVariant previousValue() const { return m_previousValue; } - -private: - QString m_asyncProperty; - QVariant m_previousValue; -}; - -#endif /* DBUSEXTENDEDPENDINGCALLWATCHER_P_H */ diff --git a/src/frameworkdbus/types/arealist.cpp b/src/frameworkdbus/types/arealist.cpp deleted file mode 100644 index 93eeadf..0000000 --- a/src/frameworkdbus/types/arealist.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-FileCopyrightText: 2011 ~ 2017 Deepin Technology Co., Ltd. -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "arealist.h" - -bool MonitRect::operator ==(const MonitRect &rect) -{ - return x1 == rect.x1 && y1 == rect.y1 && x2 == rect.x2 && y2 == rect.y2; -} - -QDBusArgument &operator<<(QDBusArgument &arg, const MonitRect &rect) -{ - arg.beginStructure(); - arg << rect.x1 << rect.y1 << rect.x2 << rect.y2; - arg.endStructure(); - - return arg; -} - -const QDBusArgument &operator>>(const QDBusArgument &arg, MonitRect &rect) -{ - arg.beginStructure(); - arg >> rect.x1 >> rect.y1 >> rect.x2 >> rect.y2; - arg.endStructure(); - - return arg; -} - -void registerAreaListMetaType() -{ - qRegisterMetaType("MonitRect"); - qDBusRegisterMetaType(); - - qRegisterMetaType("AreaList"); - qDBusRegisterMetaType(); -} diff --git a/src/frameworkdbus/types/arealist.h b/src/frameworkdbus/types/arealist.h deleted file mode 100644 index 0f426e4..0000000 --- a/src/frameworkdbus/types/arealist.h +++ /dev/null @@ -1,32 +0,0 @@ -// SPDX-FileCopyrightText: 2011 ~ 2017 Deepin Technology Co., Ltd. -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef AREALIST_H -#define AREALIST_H - -#include -#include -#include - -struct MonitRect { - int x1; - int y1; - int x2; - int y2; - - bool operator ==(const MonitRect& rect); -}; - -typedef QList AreaList; - -Q_DECLARE_METATYPE(MonitRect) -Q_DECLARE_METATYPE(AreaList) - -QDBusArgument &operator<<(QDBusArgument &arg, const MonitRect &rect); -const QDBusArgument &operator>>(const QDBusArgument &arg, MonitRect &rect); - -void registerAreaListMetaType(); - -#endif // AREALIST_H diff --git a/src/frameworkdbus/types/dockrect.cpp b/src/frameworkdbus/types/dockrect.cpp deleted file mode 100644 index a938a55..0000000 --- a/src/frameworkdbus/types/dockrect.cpp +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "dockrect.h" -#include - -DockRect::DockRect() - : X(0) - , Y(0) - , Width(0) - , Height(0) -{ - -} - -QDebug operator<<(QDebug debug, const DockRect &rect) -{ - debug << QString("DockRect(%1, %2, %3, %4)").arg(rect.X) - .arg(rect.Y) - .arg(rect.Width) - .arg(rect.Height); - - return debug; -} - -DockRect::operator QRect() const -{ - return QRect(X, Y, Width, Height); -} - -QDBusArgument &operator<<(QDBusArgument &arg, const DockRect &rect) -{ - arg.beginStructure(); - arg << rect.X << rect.Y << rect.Width << rect.Height; - arg.endStructure(); - - return arg; -} - -const QDBusArgument &operator>>(const QDBusArgument &arg, DockRect &rect) -{ - arg.beginStructure(); - arg >> rect.X >> rect.Y >> rect.Width >> rect.Height; - arg.endStructure(); - - return arg; -} - -void registerRectMetaType() -{ - qRegisterMetaType("DockRect"); - qDBusRegisterMetaType(); -} diff --git a/src/frameworkdbus/types/dockrect.h b/src/frameworkdbus/types/dockrect.h deleted file mode 100644 index a0a700e..0000000 --- a/src/frameworkdbus/types/dockrect.h +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef DOCKRECT_H -#define DOCKRECT_H - -#include -#include - -struct DockRect -{ -public: - DockRect(); - operator QRect() const; - - friend QDebug operator<<(QDebug debug, const DockRect &rect); - friend const QDBusArgument &operator>>(const QDBusArgument &arg, DockRect &rect); - friend QDBusArgument &operator<<(QDBusArgument &arg, const DockRect &rect); - - qint32 X, Y, Width, Height; -}; - -Q_DECLARE_METATYPE(DockRect) - -void registerRectMetaType(); - -#endif // DOCKRECT_H diff --git a/src/frameworkdbus/types/launcheriteminfo.cpp b/src/frameworkdbus/types/launcheriteminfo.cpp deleted file mode 100644 index 2eda6cb..0000000 --- a/src/frameworkdbus/types/launcheriteminfo.cpp +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-FileCopyrightText: 2017 ~ 2019 Deepin Technology Co., Ltd. -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "launcheriteminfo.h" - -bool LauncherItemInfo::operator!=(const LauncherItemInfo &itemInfo) -{ - return itemInfo.path != path; -} - -QDBusArgument &operator<<(QDBusArgument &argument, const LauncherItemInfo &itemInfo) -{ - argument.beginStructure(); - argument << itemInfo.path << itemInfo.name << itemInfo.id << itemInfo.icon << itemInfo.categoryId << itemInfo.timeInstalled << itemInfo.keywords; - argument.endStructure(); - return argument; -} - -const QDBusArgument &operator>>(const QDBusArgument &argument, LauncherItemInfo &itemInfo) -{ - argument.beginStructure(); - argument >> itemInfo.path >> itemInfo.name >> itemInfo.id >> itemInfo.icon >> itemInfo.categoryId >> itemInfo.timeInstalled >> itemInfo.keywords; - argument.endStructure(); - return argument; -} - -void registerLauncherItemInfoMetaType() -{ - qRegisterMetaType("ItemInfo"); - qDBusRegisterMetaType(); -} diff --git a/src/frameworkdbus/types/launcheriteminfo.h b/src/frameworkdbus/types/launcheriteminfo.h deleted file mode 100644 index df55ef3..0000000 --- a/src/frameworkdbus/types/launcheriteminfo.h +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-FileCopyrightText: 2017 ~ 2019 Deepin Technology Co., Ltd. -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#pragma once - -#include -#include -#include -#include -#include - -struct LauncherItemInfo { - QString path; - QString name; - QString id; - QString icon; - qint64 categoryId; - qint64 timeInstalled; - QStringList keywords; - bool operator!=(const LauncherItemInfo &versionInfo); - - friend QDebug operator<<(QDebug argument, const LauncherItemInfo &info) - { - argument << info.path << info.name << info.id; - argument << info.icon << info.categoryId << info.timeInstalled << info.keywords; - - return argument; - } -}; - -Q_DECLARE_METATYPE(LauncherItemInfo) - -QDBusArgument &operator<<(QDBusArgument &argument, const LauncherItemInfo &versionInfo); -const QDBusArgument &operator>>(const QDBusArgument &argument, LauncherItemInfo &versionInfo); -void registerLauncherItemInfoMetaType(); diff --git a/src/frameworkdbus/types/launcheriteminfolist.cpp b/src/frameworkdbus/types/launcheriteminfolist.cpp deleted file mode 100644 index 1c3d0de..0000000 --- a/src/frameworkdbus/types/launcheriteminfolist.cpp +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-FileCopyrightText: 2017 ~ 2019 Deepin Technology Co., Ltd. -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "launcheriteminfolist.h" - -void registerLauncherItemInfoListMetaType() -{ - qRegisterMetaType("ItemInfoList"); - qDBusRegisterMetaType(); -} diff --git a/src/frameworkdbus/types/launcheriteminfolist.h b/src/frameworkdbus/types/launcheriteminfolist.h deleted file mode 100644 index 51f327a..0000000 --- a/src/frameworkdbus/types/launcheriteminfolist.h +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-FileCopyrightText: 2017 ~ 2019 Deepin Technology Co., Ltd. -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#pragma once - -#include "launcheriteminfo.h" - -#include -#include - -typedef QList LauncherItemInfoList; - -Q_DECLARE_METATYPE(LauncherItemInfoList) - -void registerLauncherItemInfoListMetaType(); diff --git a/src/frameworkdbus/types/unlaunchedappmap.cpp b/src/frameworkdbus/types/unlaunchedappmap.cpp deleted file mode 100644 index 3489b85..0000000 --- a/src/frameworkdbus/types/unlaunchedappmap.cpp +++ /dev/null @@ -1,11 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "unlaunchedappmap.h" - -void registerUnLaunchedAppMapMetaType() -{ - qRegisterMetaType("UnLaunchedAppMap"); - qDBusRegisterMetaType(); -} diff --git a/src/frameworkdbus/types/unlaunchedappmap.h b/src/frameworkdbus/types/unlaunchedappmap.h deleted file mode 100644 index 187bafd..0000000 --- a/src/frameworkdbus/types/unlaunchedappmap.h +++ /dev/null @@ -1,18 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef TYPES_H -#define TYPES_H - -#include -#include -#include - -typedef QMap UnLaunchedAppMap; - -Q_DECLARE_METATYPE(UnLaunchedAppMap) - -void registerUnLaunchedAppMapMetaType(); - -#endif // TYPES_H diff --git a/src/frameworkdbus/types/windowinfomap.cpp b/src/frameworkdbus/types/windowinfomap.cpp deleted file mode 100644 index a2abbfe..0000000 --- a/src/frameworkdbus/types/windowinfomap.cpp +++ /dev/null @@ -1,53 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "windowinfomap.h" - -#include - -void registerWindowInfoMapMetaType() -{ - registerWindowInfoMetaType(); - - qRegisterMetaType("WindowInfoMap"); - qDBusRegisterMetaType(); -} - -void registerWindowInfoMetaType() -{ - qRegisterMetaType("WindowInfo"); - qDBusRegisterMetaType(); -} - -QDebug operator<<(QDebug argument, const WindowInfo &info) -{ - argument << '(' << info.title << ',' << info.attention << info.uuid << ')'; - - return argument; -} - -QDBusArgument &operator<<(QDBusArgument &argument, const WindowInfo &info) -{ - argument.beginStructure(); - argument << info.title << info.attention << info.uuid; - argument.endStructure(); - - return argument; -} - -const QDBusArgument &operator>>(const QDBusArgument &argument, WindowInfo &info) -{ - argument.beginStructure(); - argument >> info.title >> info.attention >> info.uuid; - argument.endStructure(); - - return argument; -} - -bool WindowInfo::operator==(const WindowInfo &rhs) const -{ - return attention == rhs.attention && - title == rhs.title && - uuid == rhs.uuid; -} diff --git a/src/frameworkdbus/types/windowinfomap.h b/src/frameworkdbus/types/windowinfomap.h deleted file mode 100644 index 8dbcc1a..0000000 --- a/src/frameworkdbus/types/windowinfomap.h +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef WINDOWINFOLIST_H -#define WINDOWINFOLIST_H - -#include -#include -#include - -class WindowInfo -{ -public: - friend QDebug operator<<(QDebug argument, const WindowInfo &info); - friend QDBusArgument &operator<<(QDBusArgument &argument, const WindowInfo &info); - friend const QDBusArgument &operator>>(const QDBusArgument &argument, WindowInfo &info); - - bool operator==(const WindowInfo &rhs) const; - -public: - bool attention; - QString title; - QString uuid; -}; -Q_DECLARE_METATYPE(WindowInfo) - -typedef QMap WindowInfoMap; -Q_DECLARE_METATYPE(WindowInfoMap) - -void registerWindowInfoMetaType(); -void registerWindowInfoMapMetaType(); - -#endif // WINDOWINFOLIST_H diff --git a/src/lib/appinfo.cpp b/src/lib/appinfo.cpp deleted file mode 100644 index 0c35798..0000000 --- a/src/lib/appinfo.cpp +++ /dev/null @@ -1,414 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "appinfo.h" -#include "utils.h" -#include "dlocale.h" -#include "appinfocommon.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -bool AppInfoManger::onceInit = false; -std::vector AppInfoManger::xdgDataDirs; -std::vector AppInfoManger::xdgAppDirs; - -AppInfoManger::AppInfoManger() -{ - canDelete = false; -} - -std::vector AppInfoManger::getStringList(std::string session, std::string key) -{ - return keyFile.getStrList(session, key); -} - -std::string AppInfoManger::toJson() -{ - QJsonDocument doc; - QJsonObject obj; - - obj["Id"] = desktopId.c_str(); - obj["Name"] = appName.c_str(); - obj["DisplayName"] = displayName.c_str(); - obj["Description"] = comment.c_str(); - obj["Icon"] = icon.c_str(); - obj["Exec"] = cmdline.c_str(); - obj["CanDelete"] = canDelete; - - if (!obj.isEmpty()) { - doc.setObject(obj); - } - - return doc.toJson(QJsonDocument::Compact).toStdString(); -} - -std::string AppInfoManger::getFileName() -{ - return fileName; -} - -std::shared_ptr AppInfoManger::loadByDesktopId(std::string desktopId) -{ - std::shared_ptr appInfo; - - if (!hasEnding(desktopId, AppinfoCommon::DesktopExt)) { - desktopId += AppinfoCommon::DesktopExt; - } - - if (QDir::isAbsolutePath(desktopId.c_str())) { - appInfo = AppInfoManger::initAppInfoByFile(desktopId); - if (appInfo) { - appInfo->desktopId = AppInfoManger::getDesktopIdFile(desktopId); - } - return appInfo; - } - - std::vector appDirs = AppInfoManger::getXdgAppsDirs(); - - for (auto iter : appDirs) { - appInfo = AppInfoManger::initAppInfoByFile(iter + "/" + desktopId); - if (appInfo) { - appInfo->desktopId = desktopId; - return appInfo; - } - } - - return appInfo; -} - -std::shared_ptr AppInfoManger::initAppInfoByFile(std::string fileName) -{ - std::shared_ptr appInfo; - KeyFile keyFile; - - bool bSuccess = keyFile.loadFile(fileName); - if (!bSuccess) { - return appInfo; - } - - std::string type = keyFile.getStr(AppinfoCommon::MainSection, AppinfoCommon::KeyType); - - if (type != AppinfoCommon::TypeApplication) { - return appInfo; - } - - appInfo = std::make_shared(); - - appInfo->appName = getAppName(keyFile); - appInfo->icon = AppInfoManger::getIconByKeyFile(keyFile); - appInfo->displayName = appInfo->appName; - appInfo->comment = keyFile.getLocaleStr(AppinfoCommon::MainSection, AppinfoCommon::KeyComment); - appInfo->cmdline = keyFile.getStr(AppinfoCommon::MainSection, AppinfoCommon::KeyExec); - appInfo->fileName = fileName; - appInfo->keyFile = keyFile; - - if (!appInfo->shouldShow()) { - return nullptr; - } - - return appInfo; -} - -std::string AppInfoManger::getIconByKeyFile(KeyFile& keyFile) -{ - std::string icon = keyFile.getStr(AppinfoCommon::MainSection, AppinfoCommon::KeyIcon); - - if (!QDir::isAbsolutePath(icon.c_str())) { - if (hasEnding(icon, ".png")) { - icon = icon.substr(0, icon.length() - strlen(".png")); - } - - if (hasEnding(icon, ".xpm")) { - icon = icon.substr(0, icon.length() - strlen(".xpm")); - } - - if (hasEnding(icon, ".svg")) { - icon = icon.substr(0, icon.length() - strlen(".svg")); - } - } - - return icon; -} - -std::string AppInfoManger::getDesktopIdFile(std::string fileName) -{ - if (hasEnding(fileName, AppinfoCommon::DesktopExt)) { - fileName = fileName.substr(0, fileName.size() - strlen(AppinfoCommon::DesktopExt.c_str()) + 1); - } - - auto index = fileName.find("/applications/"); - if (index == fileName.npos) { - return ""; - } - - std::string dir = fileName.substr(0, index); - - std::vector dataDIrs = AppInfoManger::getXdgDataDirs(); - - if (std::find(dataDIrs.begin(), dataDIrs.end(), dir) != dataDIrs.end()) { - - return fileName.substr(index + 14, fileName.size() - (index + 14 + 1)); - } - - return fileName; -} - -bool AppInfoManger::shouldShow() -{ - if (!keyFile.getStr(AppinfoCommon::MainSection, AppinfoCommon::KeyNoDisplay).empty()) { - return false; - } - - if (!keyFile.getStr(AppinfoCommon::MainSection, AppinfoCommon::KeyHidden).empty()) { - return false; - } - QString deskEnv = getenv("XDG_CURRENT_DESKTOP"); - - auto envList = deskEnv.split(":"); - - std::vector onlyShowIn = keyFile.getStrList(AppinfoCommon::MainSection, AppinfoCommon::KeyOnlyShowIn); - std::vector notShowIn = keyFile.getStrList(AppinfoCommon::MainSection, AppinfoCommon::KeyNotShowIn); - - for (auto iter : envList) { - if (std::find(onlyShowIn.begin(), onlyShowIn.end(), iter.toStdString()) != onlyShowIn.end()) { - return true; - } - if (std::find(notShowIn.begin(), notShowIn.end(), iter.toStdString()) != notShowIn.end()) { - return false; - } - } - - return onlyShowIn.empty(); -} - -std::string AppInfoManger::getDefaultApp(std::string mimeType, bool supportUri) -{ - GAppInfo* gAppInfo = g_app_info_get_default_for_type(mimeType.c_str(), supportUri); - - if (gAppInfo == nullptr) { - return ""; - } - - if (supportUri && !g_app_info_supports_uris(gAppInfo)) { - return ""; - } - - return g_app_info_get_id(gAppInfo); -} - -std::vector AppInfoManger::getAppList(std::string mimeType) -{ - std::vector retVector; - GList* appInfoList = g_app_info_get_all_for_type(mimeType.c_str()); - - while (appInfoList) { - GAppInfo* gAppInfo = static_cast(appInfoList->data); - - const char* appId = g_app_info_get_id(gAppInfo); - if (appId) { - retVector.push_back(appId); - } - appInfoList = appInfoList->next; - } - - return retVector; -} - - -bool AppInfoManger::setDefaultApp(std::string mimeType, std::string desktopId) -{ - GDesktopAppInfo* gDesktopAppInfo = g_desktop_app_info_new(desktopId.c_str()); - - if (gDesktopAppInfo == nullptr) { - return false; - } - - GAppInfo* gAppInfo = G_APP_INFO(gDesktopAppInfo); - - GError* err = nullptr; - g_app_info_set_as_default_for_type(gAppInfo, mimeType.c_str(), &err); - - if (err != nullptr) { - return false; - } - return true; -} - -std::string AppInfoManger::getAppName(KeyFile& keyFile) -{ - std::string name; - - std::string xDeepinVendor = keyFile.getStr(AppinfoCommon::MainSection, AppinfoCommon::DeepinVendor); - - if (xDeepinVendor == "deepin") { - name = keyFile.getLocaleStr(AppinfoCommon::MainSection, AppinfoCommon::KeyGenericName); - } else { - name = keyFile.getLocaleStr(AppinfoCommon::MainSection, AppinfoCommon::KeyName); - } - - if (name.empty()) { - name = AppInfoManger::getDesktopIdFile(keyFile.getFilePath()); - } - - return name; -} - -std::vector& AppInfoManger::getXdgDataDirs() -{ - if (!AppInfoManger::onceInit) { - AppInfoManger::onceInit = true; - - AppInfoManger::xdgDataDirs.push_back(getUserDataDir()); - for (auto iter : getSystemDataDirs()) { - xdgDataDirs.push_back(iter); - } - - for (auto dataDir : AppInfoManger::xdgDataDirs) { - AppInfoManger::xdgAppDirs.push_back(dataDir + "/applications"); - } - } - - return AppInfoManger::xdgDataDirs; -} - -std::vector& AppInfoManger::getXdgAppsDirs() -{ - if (!AppInfoManger::onceInit) { - AppInfoManger::onceInit = true; - - AppInfoManger::xdgDataDirs.push_back(getUserDataDir()); - - for (auto iter : getSystemDataDirs()) { - xdgDataDirs.push_back(iter); - } - - for (auto dataDir : AppInfoManger::xdgDataDirs) { - AppInfoManger::xdgAppDirs.push_back(dataDir + "/applications"); - } - } - - return AppInfoManger::xdgAppDirs; -} - -std::vector> AppInfoManger::getAll(std::map> skipDirs) -{ - std::vector> ret; - - std::vector xdgAppDirs = AppInfoManger::getXdgAppsDirs(); - - std::vector>> appPathNameInfos; - for (auto iter : xdgAppDirs) { - std::map tempMap; - if (skipDirs.count(iter) != 0) { - walk(iter, skipDirs[iter], tempMap); - } else { - std::vector temp; - walk(iter, temp, tempMap); - } - appPathNameInfos.push_back(std::make_pair(iter, tempMap)); - } - - std::map recordMap; - - for (auto appPathNameInfo : appPathNameInfos) { - for (auto appName : appPathNameInfo.second) { - std::string tempAppName = appName.first; - if (hasBeginWith(appName.first, "./")) { - tempAppName = appName.first.substr(appName.first.find_first_of("./") + 2, appName.first.size() - 2); - } - if (recordMap.count(tempAppName)) { - continue; - } - - std::shared_ptr appInfo = AppInfoManger::loadByDesktopId(appPathNameInfo.first + "/" + tempAppName); - if (!appInfo) { - continue; - } - - recordMap[tempAppName] = 0; - - if (appInfo->shouldShow()) { - ret.push_back(appInfo); - } - } - } - return ret; -} - - -std::string AppInfoManger::getDesktopId() -{ - return desktopId; -} - -std::string AppInfoManger::getAppName() -{ - return appName; -} -std::string AppInfoManger::getDisplayName() -{ - return displayName; -} -std::string AppInfoManger::getComment() -{ - return comment; -} -std::string AppInfoManger::getIcon() -{ - return icon; -} - -std::string AppInfoManger::getCmdline() -{ - return cmdline; -} - -bool AppInfoManger::getCanDelete() -{ - return canDelete; -} - -void AppInfoManger::setCanDelete(bool bCanDelete) -{ - canDelete = bCanDelete; -} -std::vector AppInfoManger::getCategories() -{ - return keyFile.getStrList(AppinfoCommon::MainSection, AppinfoCommon::KeyCategories); -} - -void AppInfoManger::setDesktopId(std::string desktopId) -{ - this->desktopId = desktopId; -} - -std::string AppInfoManger::toJson(std::vector> appInfos) -{ - QJsonDocument doc; - QJsonObject obj; - QJsonArray arr; - for (auto iter : appInfos) { - obj["Id"] = iter->getDesktopId().c_str(); - obj["Name"] = iter->getAppName().c_str(); - obj["DisplayName"] = iter->getDisplayName().c_str(); - obj["Description"] = iter->getComment().c_str(); - obj["Icon"] = iter->getIcon().c_str(); - obj["Exec"] = iter->getCmdline().c_str(); - obj["CanDelete"] = iter->getCanDelete(); - arr.push_back(obj); - } - - if (!arr.empty()) { - doc.setArray(arr); - } - - return doc.toJson(QJsonDocument::Compact).toStdString(); -} diff --git a/src/lib/appinfo.h b/src/lib/appinfo.h deleted file mode 100644 index e0f1446..0000000 --- a/src/lib/appinfo.h +++ /dev/null @@ -1,60 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef APPINFO_H -#define APPINFO_H - -#include "keyfile.h" - -#include -#include - -class AppInfoManger -{ -public: - AppInfoManger(); - std::vector getStringList(std::string session, std::string key); - std::string toJson(); - std::string getFileName(); - static std::shared_ptr loadByDesktopId(std::string desktopId); - static std::string getDefaultApp(std::string mimeType, bool supportUri); - static std::vector getAppList(std::string mimeType); - static bool setDefaultApp(std::string mimeType, std::string desktopId); - static std::vector& getXdgDataDirs(); - static std::vector& getXdgAppsDirs(); - static std::vector> getAll(std::map> skipDirs); - std::string getDesktopId(); - std::string getAppName(); - std::string getDisplayName(); - std::string getComment(); - std::string getIcon(); - std::string getCmdline(); - bool getCanDelete(); - void setCanDelete(bool bCanDelete); - std::vector getCategories(); - void setDesktopId(std::string desktopId); - static std::string toJson(std::vector> appInfos); - -private: - static std::shared_ptr initAppInfoByFile(std::string fileName); - static std::string getAppName(KeyFile& keyFile); - static std::string getIconByKeyFile(KeyFile& keyFile); - static std::string getDesktopIdFile(std::string fileName); - bool shouldShow(); -private: - std::string desktopId; - std::string appName; - std::string displayName; - std::string comment; - std::string icon; - std::string cmdline; - bool canDelete; - std::string fileName; - KeyFile keyFile; - static std::vector xdgDataDirs; - static std::vector xdgAppDirs; - static bool onceInit; -}; - -#endif // APPINFO_H diff --git a/src/lib/appinfocommon.cpp b/src/lib/appinfocommon.cpp deleted file mode 100644 index 8026bd4..0000000 --- a/src/lib/appinfocommon.cpp +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "appinfocommon.h" - -const std::string AppinfoCommon::MainSection = "Desktop Entry"; -const std::string AppinfoCommon::KeyType = "Type"; -const std::string AppinfoCommon::KeyVersion = "Version"; -const std::string AppinfoCommon::KeyName = "Name"; -const std::string AppinfoCommon::KeyGenericName = "GenericName"; -const std::string AppinfoCommon::KeyNoDisplay = "NoDisplay"; -const std::string AppinfoCommon::KeyComment = "Comment"; -const std::string AppinfoCommon::KeyIcon = "Icon"; -const std::string AppinfoCommon::KeyHidden = "Hidden"; -const std::string AppinfoCommon::KeyOnlyShowIn = "OnlyShowIn"; -const std::string AppinfoCommon::KeyNotShowIn = "NotShowIn"; -const std::string AppinfoCommon::KeyTryExec = "TryExec"; -const std::string AppinfoCommon::KeyExec = "Exec"; -const std::string AppinfoCommon::KeyPath = "Path"; -const std::string AppinfoCommon::KeyTerminal = "Terminal"; -const std::string AppinfoCommon::KeyMimeType = "MimeType"; -const std::string AppinfoCommon::KeyCategories = "Categories"; -const std::string AppinfoCommon::KeyKeywords = "Keywords"; -const std::string AppinfoCommon::KeyStartupNotify = "StartupNotify"; -const std::string AppinfoCommon::KeyStartupWMClass = "StartupWMClass"; -const std::string AppinfoCommon::KeyURL = "URL"; -const std::string AppinfoCommon::KeyActions = "Actions"; -const std::string AppinfoCommon::KeyDBusActivatable = "DBusActivatable"; - -const std::string AppinfoCommon::TypeApplication = "Application"; -const std::string AppinfoCommon::TypeLink = "Link"; -const std::string AppinfoCommon::TypeDirectory = "Directory"; - -const std::string AppinfoCommon::EnvDesktopEnv = "XDG_CURRENT_DESKTOP"; -const std::string AppinfoCommon::DesktopExt = ".desktop"; -const std::string AppinfoCommon::EnableInvoker = "ENABLE_TURBO_INVOKER"; -const std::string AppinfoCommon::TurboInvokerFailedMsg = "Failed to invoke: Booster:"; -const std::string AppinfoCommon::TurboInvokerErrMsg = "deepin-turbo-invoker: error"; -const std::string AppinfoCommon::SectionDefaultApps = "Default Applications"; -const std::string AppinfoCommon::SectionAddedAssociations = "Added Associations"; -const std::string AppinfoCommon::DeepinVendor = "X-Deepin-Vendor"; -const std::string AppinfoCommon::AppMimeTerminal = "application/x-terminal"; diff --git a/src/lib/appinfocommon.h b/src/lib/appinfocommon.h deleted file mode 100644 index ebef0b1..0000000 --- a/src/lib/appinfocommon.h +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef APPINFOCOMMON_H -#define APPINFOCOMMON_H -#include - -class AppinfoCommon -{ -public: - const static std::string MainSection; - const static std::string KeyType; - const static std::string KeyVersion; - const static std::string KeyName; - const static std::string KeyGenericName; - const static std::string KeyNoDisplay; - const static std::string KeyComment; - const static std::string KeyIcon; - const static std::string KeyHidden; - const static std::string KeyOnlyShowIn; - const static std::string KeyNotShowIn; - const static std::string KeyTryExec; - const static std::string KeyExec; - const static std::string KeyPath; - const static std::string KeyTerminal; - const static std::string KeyMimeType; - const static std::string KeyCategories; - const static std::string KeyKeywords; - const static std::string KeyStartupNotify; - const static std::string KeyStartupWMClass; - const static std::string KeyURL; - const static std::string KeyActions; - const static std::string KeyDBusActivatable; - - const static std::string TypeApplication; - const static std::string TypeLink; - const static std::string TypeDirectory; - - const static std::string EnvDesktopEnv; - const static std::string DesktopExt; - const static std::string EnableInvoker; - const static std::string TurboInvokerFailedMsg; - const static std::string TurboInvokerErrMsg; - const static std::string SectionDefaultApps; - const static std::string SectionAddedAssociations; - const static std::string DeepinVendor ; - const static std::string AppMimeTerminal; -}; - -#endif // APPINFOCOMMON_H diff --git a/src/lib/applaunchcontext.cpp b/src/lib/applaunchcontext.cpp deleted file mode 100644 index ccec399..0000000 --- a/src/lib/applaunchcontext.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "applaunchcontext.h" - -AppLaunchContext::AppLaunchContext() - : m_count(0) - , m_timestamp(0) -{ - -} - -// TODO -std::string AppLaunchContext::getStartupNotifyId(const DesktopInfo *info, std::vector files) -{ - -} - -// TODO -void AppLaunchContext::launchFailed(std::string startupNotifyId) -{ - -} diff --git a/src/lib/applaunchcontext.h b/src/lib/applaunchcontext.h deleted file mode 100644 index 4742329..0000000 --- a/src/lib/applaunchcontext.h +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef APPLAUNCHCONTEXT_H -#define APPLAUNCHCONTEXT_H - -#include -#include -#include - -class DesktopInfo; -class AppLaunchContext -{ -public: - AppLaunchContext(); - - void setEnv(const std::vector &value) {m_env = value;} - std::vector getEnv() {return m_env;} - - void setTimestamp(uint32_t value) {m_timestamp = value;} - uint32_t getTimestamp() {return m_timestamp;} - - void setCmdPrefixes(const std::vector &value) {m_cmdPrefixes = value;} - std::vector getCmdPrefixes() {return m_cmdPrefixes;} - - void setCmdSuffixes(const std::vector &value) {m_cmdSuffixes = value;} - std::vector getCmdSuffixes() {return m_cmdSuffixes;} - - std::string getStartupNotifyId(const DesktopInfo *info, std::vector files); - - void launchFailed(std::string startupNotifyId); - -private: - uint m_count; - uint32_t m_timestamp; - std::vector m_cmdPrefixes; - std::vector m_cmdSuffixes; - std::vector m_env; -}; - -#endif // APPLAUNCHCONTEXT_H diff --git a/src/lib/basedir.cpp b/src/lib/basedir.cpp deleted file mode 100644 index 213d5a4..0000000 --- a/src/lib/basedir.cpp +++ /dev/null @@ -1,157 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "basedir.h" -#include "dfile.h" -#include "dstring.h" - -#include - -BaseDir::BaseDir() -{ - -} - -std::string BaseDir::homeDir() -{ - char *home = getenv("HOME"); - if (!home) - return ""; - - return std::string(home) + "/"; -} - -std::string BaseDir::userDataDir() -{ - // default $HOME/.local/share - std::string home = homeDir(); - std::string defaultDir = (home.size() > 0) ? home + ".local/share/" : ""; - const char *xdgDataHomePtr = getenv("XDG_DATA_HOME"); - if (!xdgDataHomePtr) - return defaultDir; - - if (!DFile::isDir(xdgDataHomePtr)) - return defaultDir; - - return std::string(xdgDataHomePtr) + "/"; -} - -std::vector BaseDir::sysDataDirs() -{ - std::vector defaultDirs {"/usr/local/share/", "/usr/share/"}; - const char *xdgDataDirsPtr = getenv("XDG_DATA_DIRS"); - if (!xdgDataDirsPtr) - return defaultDirs; - - std::string xdgDataDirsStr(xdgDataDirsPtr); - std::vector xdgDataDirs = DString::splitStr(xdgDataDirsStr, ':'); - if (xdgDataDirs.size() == 0) - return defaultDirs; - - filterNotAbs(xdgDataDirs); - addSuffixSlash(xdgDataDirs); - return xdgDataDirs; -} - -std::string BaseDir::userConfigDir() -{ - // default $HOME/.config - std::string defaultDir = homeDir() + ".config/"; - const char *xdgConfigHomePtr = getenv("XDG_CONFIG_HOME"); - if (!xdgConfigHomePtr) - return defaultDir; - - std::string xdgConfigHome(xdgConfigHomePtr); - if (!DFile::isDir(xdgConfigHome)) - return defaultDir; - - return xdgConfigHome + "/"; -} - -std::vector BaseDir::sysConfigDirs() -{ - std::vector defaultDirs {"/etc/xdg/"}; - const char *xdgConfigDirsPtr = getenv("XDG_CONFIG_DIRS"); - if (!xdgConfigDirsPtr) - return defaultDirs; - - std::string xdgConfigDirsStr(xdgConfigDirsPtr); - std::vector xdgConfigDirs = DString::splitStr(xdgConfigDirsStr, ':'); - if (xdgConfigDirs.size() == 0) - return defaultDirs; - - filterNotAbs(xdgConfigDirs); - addSuffixSlash(xdgConfigDirs); - return xdgConfigDirs; -} - -std::string BaseDir::userCacheDir() -{ - std::string home = homeDir(); - std::string defaultDir = (home.size() > 0) ? home + ".cache/" : ""; - const char *xdgCacheHomePtr = getenv("XDG_CACHE_HOME"); - if (!xdgCacheHomePtr) - return defaultDir; - - std::string xdgCacheHome(xdgCacheHomePtr); - if (!DFile::isDir(xdgCacheHome)) - return defaultDir; - - return xdgCacheHome + "/"; -} - -std::string BaseDir::userAppDir() -{ - std::string dataDir = userDataDir(); - return (dataDir.size() > 0) ? dataDir + "applications/" : ""; -} - -std::vector BaseDir::sysAppDirs() -{ - auto dataDirs = sysDataDirs(); - std::vector sysAppDirs(dataDirs.size()); - std::transform(dataDirs.begin(), dataDirs.end(), sysAppDirs.begin(), - [](std::string dir) -> std::string {return dir + "applications/";}); - return sysAppDirs; -} - -std::vector BaseDir::appDirs() -{ - std::vector appDirs = sysAppDirs(); - appDirs.push_back(userAppDir()); - return appDirs; -} - -std::vector BaseDir::autoStartDirs() -{ - std::vector autoStartDirs = sysConfigDirs(); - autoStartDirs.push_back(userConfigDir()); - std::transform(autoStartDirs.begin(), autoStartDirs.end(), autoStartDirs.begin(), - [](std::string dir) -> std::string {return dir + "autostart/";}); - - return autoStartDirs; -} - -std::string BaseDir::userAutoStartDir() -{ - return userConfigDir() + "autostart/"; -} - -void BaseDir::filterNotAbs(std::vector &dirs) -{ - for (auto iter = dirs.begin(); iter != dirs.end();) { // erase element in vector - if (!DFile::isDir(*iter)) - iter = dirs.erase(iter); - else - iter++; - } -} - -void BaseDir::addSuffixSlash(std::vector &dirs) -{ - for (auto &dir : dirs) { - if (!DString::endWith(dir, "/")) - dir += "/"; - } -} diff --git a/src/lib/basedir.h b/src/lib/basedir.h deleted file mode 100644 index 4085ab3..0000000 --- a/src/lib/basedir.h +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef BASEDIR_H -#define BASEDIR_H - -#include -#include - -// 基础目录类, 目录结尾统一包含斜杠/ -class BaseDir -{ -public: - BaseDir(); - - static std::string homeDir(); - static std::string userDataDir(); - static std::vector sysDataDirs(); - static std::string userConfigDir(); - static std::vector sysConfigDirs(); - static std::string userCacheDir(); - static std::string userAppDir(); - static std::vector sysAppDirs(); - static std::vector appDirs(); - static std::vector autoStartDirs(); - static std::string userAutoStartDir(); - -private: - static void filterNotAbs(std::vector& dirs); - static void addSuffixSlash(std::vector& dirs); -}; - -#endif // BASEDIR_H diff --git a/src/lib/desktopfile.cpp b/src/lib/desktopfile.cpp deleted file mode 100644 index 361f979..0000000 --- a/src/lib/desktopfile.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "desktopfile.h" - -DesktopFile::DesktopFile(char separtor) - : KeyFile(separtor) -{ -} - -DesktopFile::~DesktopFile() = default; - -bool DesktopFile::saveToFile(const std::string &filePath){ - FILE *sfp = fopen(filePath.data(), "w+"); - if (!sfp) { - perror("open file failed..."); - return false; - } - - // NOTE(black_desk): XDG require the first section of desktop file - // is always "Desktop Entry" - - auto mainSection = m_mainKeyMap.find("Desktop Entry"); - if (mainSection != m_mainKeyMap.end()) { - // FIXME(black_desk): should handle write fail. - writeSectionToFile(mainSection->first, mainSection->second, sfp); - } else { - // FIXME(black_desk): should have some warning. - } - - for (const auto &im : m_mainKeyMap) { - if (im.first == "Desktop Entry") { - continue; - } - // FIXME(black_desk): should handle write fail. - writeSectionToFile(im.first, im.second, sfp); - } - - fclose(sfp); - return true; -} diff --git a/src/lib/desktopfile.h b/src/lib/desktopfile.h deleted file mode 100644 index f1ec748..0000000 --- a/src/lib/desktopfile.h +++ /dev/null @@ -1,24 +0,0 @@ -// SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef DESKTOPFILE_H -#define DESKTOPFILE_H - -#include "keyfile.h" - -#include -#include -#include - -// 解析desktop文件类 -class DesktopFile: public KeyFile -{ -public: - explicit DesktopFile(char separtor = ';'); - virtual ~DesktopFile(); - - virtual bool saveToFile(const std::string &filePath) override; -}; - -#endif // DESKTOPFILE_H diff --git a/src/lib/desktopinfo.cpp b/src/lib/desktopinfo.cpp deleted file mode 100644 index d9fc0d4..0000000 --- a/src/lib/desktopinfo.cpp +++ /dev/null @@ -1,411 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "desktopinfo.h" -#include "locale.h" -#include "unistd.h" -#include "dstring.h" -#include "dfile.h" -#include "basedir.h" - -#include - -#include -#include -#include -#include - -std::vector DesktopInfo::currentDesktops; - -DesktopInfo::DesktopInfo(const std::string &_fileName) - : m_isValid(true) - , m_desktopFile() -{ - std::string fileNameWithSuffix(_fileName); - if (!DString::endWith(_fileName, ".desktop")) - fileNameWithSuffix += ".desktop"; - - m_fileName = fileNameWithSuffix; - - if (DFile::dir(m_fileName).empty()) { - // fileName是文件名,增加目录 - bool isExisted = false; - for (const auto &dir : BaseDir::appDirs()) { - m_fileName = dir + fileNameWithSuffix; - if (DFile::isExisted(m_fileName)) { - isExisted = true; - break; - } - } - - if (!isExisted) { - m_isValid = false; - return; - } - } - - m_desktopFile.loadFile(m_fileName); - - // check DesktopInfo valid - std::vector mainKeys = m_desktopFile.getMainKeys(); - if (mainKeys.size() == 0) - m_isValid = false; - - bool found = std::any_of(mainKeys.begin(), mainKeys.end(), - [](const auto &key) {return key == MainSection;}); - - if (!found) - m_isValid = false; - - if (m_desktopFile.getStr(MainSection, KeyType) != TypeApplication) - m_isValid = false; - - m_name = m_desktopFile.getLocaleStr(MainSection, KeyName, ""); - m_icon = m_desktopFile.getStr(MainSection, KeyIcon); - m_id = getId(); -} - -DesktopInfo::~DesktopInfo() -{ - -} - -std::string DesktopInfo::getFileName() -{ - return m_fileName; -} - -bool DesktopInfo::isValidDesktop() -{ - return m_isValid; -} - -/** if return true, item is shown - * @brief DesktopInfo::shouldShow - * @return - */ -bool DesktopInfo::shouldShow() -{ - if (getNoDisplay() || getIsHidden()) { - qDebug() << "hidden desktop file path: " << QString::fromStdString(m_fileName); - return false; - } - - std::vector desktopEnvs; - return getShowIn(desktopEnvs); -} - -bool DesktopInfo::getNoDisplay() -{ - return m_desktopFile.getBool(MainSection, KeyNoDisplay); -} - -bool DesktopInfo::getIsHidden() -{ - return m_desktopFile.getBool(MainSection, KeyHidden); -} - -bool DesktopInfo::getShowIn(std::vector desktopEnvs) -{ -#ifdef QT_DEBUG - qDebug() << "desktop file path: " << QString::fromStdString(m_fileName); -#endif - - if (desktopEnvs.size() == 0) { - const char *env = getenv(envDesktopEnv.c_str()); - const auto &desktop = DString::splitChars(env, ':'); - currentDesktops.assign(desktop.begin(), desktop.end()); - desktopEnvs.assign(currentDesktops.begin(), currentDesktops.end()); - } - - std::vector onlyShowIn = m_desktopFile.getStrList(MainSection, KeyOnlyShowIn); - std::vector notShowIn = m_desktopFile.getStrList(MainSection, KeyNotShowIn); - -#ifdef QT_DEBUG - auto strVector2qstrVector = [](const std::vector &vector) { - QVector vectorString; - for (const std::string &str : vector) - vectorString.append(QString::fromStdString(str)); - - return vectorString; - }; - - qDebug() << "onlyShowIn:" << strVector2qstrVector(onlyShowIn) << - ", notShowIn:" << strVector2qstrVector(notShowIn) << - ", desktopEnvs:" << strVector2qstrVector(desktopEnvs); -#endif - - for (const auto &desktop : desktopEnvs) { - bool ret = std::any_of(onlyShowIn.begin(), onlyShowIn.end(), - [&desktop](const auto &d) {return d == desktop;}); -#ifdef QT_DEBUG - qInfo() << Q_FUNC_INFO << "onlyShowIn, result:" << ret; -#endif - if (ret) - return true; - - ret = std::any_of(notShowIn.begin(), notShowIn.end(), - [&desktop](const auto &d) {return d == desktop;}); -#ifdef QT_DEBUG - qInfo() << Q_FUNC_INFO << "notShowIn, result:" << ret; -#endif - if (ret) - return false; - } - - return onlyShowIn.size() == 0; -} - -std::string DesktopInfo::getExecutable() -{ - return m_desktopFile.getStr(MainSection, KeyExec); -} - -bool DesktopInfo::isExecutableOk() -{ - // 检查TryExec字段 - std::string value = getTryExec(); - std::vector parts = DString::splitStr(value, ' '); - if (parts.size() > 0 ) { - value.assign(parts[0]); - DString::delQuote(value); - if (strstr(value.c_str(), "/") && DFile::isExisted(value)) - return true; - else - return findExecutable(value); - } - - // 检查Exec字段 - value.assign(getExecutable()); - parts.clear(); - parts = DString::splitStr(value, ' '); - if (parts.size() > 0) { - value.assign(parts[0]); - DString::delQuote(value); - if (strstr(value.c_str(), "/") && DFile::isExisted(value)) - return true; - else - return findExecutable(value); - } - - return false; -} - -bool DesktopInfo::isInstalled() -{ - const char *name = m_fileName.c_str(); - const char *found = strstr(name, "/applications/"); - if (!found) - return false; - - auto appDirs = BaseDir::appDirs(); - return std::any_of(appDirs.begin(), appDirs.end(), - [&name, &found] (std::string dir) -> bool {return strneq(dir.c_str(), name, size_t(found - name));}); -} - -// [Desktop Action new-window] or [Full_Screenshot Shortcut Group] -bool DesktopInfo::isDesktopAction(std::string name) -{ - return DString::startWith(name.c_str(), "Desktop Action") || DString::endWith(name.c_str(), "Shortcut Group"); -} - -std::vector DesktopInfo::getActions() -{ - std::vector actions; - for (const auto &mainKey : m_desktopFile.getMainKeys()) { - if (DString::startWith(mainKey, "Desktop Action") - || DString::endWith(mainKey, "Shortcut Group")) { - DesktopAction action; - action.name = m_desktopFile.getLocaleStr(mainKey, KeyName, ""); - action.exec = m_desktopFile.getStr(mainKey, KeyExec); - action.section = mainKey; - actions.push_back(action); - } - } - - return actions; -} - -// 使用appId获取DesktopInfo需检查有效性 -DesktopInfo DesktopInfo::getDesktopInfoById(std::string appId) -{ - if (!DString::endWith(appId, ".desktop")) - appId += ".desktop"; - - for (const auto & dir : BaseDir::appDirs()) { - std::string filePath = dir + appId; - //检测文件有效性 - if (DFile::isExisted(filePath)) { - return DesktopInfo(filePath); - } - } - - return DesktopInfo(""); -} - -bool DesktopInfo::getTerminal() -{ - return m_desktopFile.getBool(MainSection, KeyTerminal); -} - -// TryExec is Path to an executable file on disk used to determine if the program is actually installed -std::string DesktopInfo::getTryExec() -{ - return m_desktopFile.getStr(MainSection, KeyTryExec); -} - -// 按$PATH路径查找执行文件 -bool DesktopInfo::findExecutable(std::string &exec) -{ - static const char *path = getenv("PATH"); - static std::vector paths = DString::splitChars(path, ':'); - return std::any_of(paths.begin(), paths.end(), [&exec](std::string path) {return DFile::isExisted(path + "/" +exec);}); -} - -/** - * @brief DesktopInfo::getId - * filename must has suffix desktopExt - * example: - * /usr/share/applications/a.desktop -> a - * /usr/share/applications/kde4/a.desktop -> kde4/a - * /xxxx/dir/a.desktop -> /xxxx/dir/a - * @return - */ -std::string DesktopInfo::getId() -{ - if (!m_id.empty()) - return m_id; - - std::string idStr; - auto const suffixPos = m_fileName.find(".desktop"); - if (suffixPos == std::string::npos) - return ""; - - idStr = m_fileName.substr(0, m_fileName.size() - 8); // trim suffix - size_t dirPos = idStr.find("/applications/"); - if (dirPos == std::string::npos) - return idStr; - - std::string baseDir(idStr.substr(0, dirPos + 14)); // length of "/applications/" is 14 - std::vector appDirs = BaseDir::appDirs(); - bool installed = std::any_of(appDirs.begin(), appDirs.end(), - [&baseDir](const auto &dir) {return dir == baseDir;}); - - if (installed) { - m_id = idStr.substr(baseDir.size(), idStr.size()); - } - - return m_id; -} - -std::string DesktopInfo::getGenericName() -{ - return m_desktopFile.getLocaleStr(MainSection, KeyGenericName, ""); -} - -std::string DesktopInfo::getName() -{ - return m_name; -} - -std::string DesktopInfo::getIcon() -{ - return m_icon; -} - -std::string DesktopInfo::getCommandLine() -{ - return m_desktopFile.getStr(MainSection, KeyExec); -} - -std::vector DesktopInfo::getKeywords() -{ - return m_desktopFile.getLocaleStrList(MainSection, KeyKeywords, ""); -} - -std::vector DesktopInfo::getCategories() -{ - return m_desktopFile.getStrList(MainSection, KeyCategories); -} - -void DesktopInfo::setDesktopOverrideExec(const std::string &execStr) -{ - m_overRideExec = execStr; -} - -DesktopFile *DesktopInfo::getDesktopFile() -{ - return &m_desktopFile; -} - -// class AppsDir -AppsDir::AppsDir(const std::string &dirPath) - : m_path(dirPath) -{ - -} - -AppsDir::~AppsDir() -{ - -} - -std::string AppsDir::getPath() -{ - return m_path; -} - - -// 获取目录对应的应用名称 -std::map AppsDir::getAppNames() -{ - DIR* dp; - struct dirent* ep; - - dp = opendir(m_path.c_str()); - if (!dp) { - std::cout << "Couldn't open directory " << m_path << std::endl; - return m_appNames; - } - - while ((ep = readdir(dp))) { - if (ep->d_type != DT_REG && ep->d_type != DT_LNK) - continue; - - if (!DString::endWith(ep->d_name, ".desktop")) - continue; - - m_appNames.insert({ep->d_name, true}); - } - closedir(dp); - - return m_appNames; -} - -// 获取所有应用信息 -std::vector AppsDir::getAllDesktopInfos() -{ - std::vector desktopInfos; - - for (auto dir : BaseDir::appDirs()) { - AppsDir appsDir(dir); - std::map appNames = appsDir.getAppNames(); - if (appNames.size() == 0) - continue; - - for (const auto &iter : appNames) { - std::string filePath = dir + iter.first; - - DesktopInfo desktopInfo(filePath); - if (!DFile::isExisted(filePath) || !desktopInfo.isValidDesktop() || !desktopInfo.shouldShow()) { - qDebug() << QString("app item %1 doesn't show in the list..").arg(QString::fromStdString(filePath)); - continue; - } - - desktopInfos.push_back(desktopInfo); - } - } - - return desktopInfos; -} diff --git a/src/lib/desktopinfo.h b/src/lib/desktopinfo.h deleted file mode 100644 index 98e58c4..0000000 --- a/src/lib/desktopinfo.h +++ /dev/null @@ -1,117 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef DESKTOPINFO_H -#define DESKTOPINFO_H - -#include "desktopfile.h" - -#include -#include - -const std::string MainSection = "Desktop Entry"; -const std::string KeyType = "Type"; -const std::string KeyVersion = "Version"; -const std::string KeyName = "Name"; -const std::string KeyGenericName = "GenericName"; -const std::string KeyNoDisplay = "NoDisplay"; -const std::string KeyComment = "Comment"; -const std::string KeyIcon = "Icon"; -const std::string KeyHidden = "Hidden"; -const std::string KeyOnlyShowIn = "OnlyShowIn"; -const std::string KeyNotShowIn = "NotShowIn"; -const std::string KeyTryExec = "TryExec"; -const std::string KeyExec = "Exec"; -const std::string KeyPath = "Path"; -const std::string KeyTerminal = "Terminal"; -const std::string KeyMimeType = "MimeType"; -const std::string KeyCategories = "Categories"; -const std::string KeyKeywords = "Keywords"; -const std::string KeyStartupNotify = "StartupNotify"; -const std::string KeyStartupWMClass = "StartupWMClass"; -const std::string KeyURL = "URL"; -const std::string KeyActions = "Actions"; -const std::string KeyDBusActivatable = "DBusActivatable"; - -const std::string TypeApplication = "Application"; -const std::string TypeLink = "Link"; -const std::string TypeDirectory = "Directory"; - -const std::string envDesktopEnv = "XDG_CURRENT_DESKTOP"; - -typedef struct DesktopAction -{ - DesktopAction() - : section("") - , name("") - , exec("") - { - } - std::string section; - std::string name; - std::string exec; -} DesktopAction; - -// 应用Desktop信息类 -class DesktopInfo { -public: - explicit DesktopInfo(const std::string &_fileName); - ~DesktopInfo(); - - std::string getFileName(); - std::string getExecutable(); - bool isValidDesktop(); - bool shouldShow(); - bool getNoDisplay(); - bool getIsHidden(); - bool getShowIn(std::vector desktopEnvs); - bool isExecutableOk(); - bool isInstalled(); - static bool isDesktopAction(std::string name); - std::vector getActions(); - static DesktopInfo getDesktopInfoById(std::string appId); - bool getTerminal(); - - std::string getId(); - std::string getGenericName(); - std::string getName(); - std::string getIcon(); - std::string getCommandLine(); - std::vector getKeywords(); - std::vector getCategories(); - void setDesktopOverrideExec(const std::string &execStr); - - DesktopFile *getDesktopFile(); - -private: - std::string getTryExec(); - bool findExecutable(std::string &exec); - - static std::vector currentDesktops; - - std::string m_fileName; - std::string m_id; - std::string m_name; - std::string m_icon; - std::string m_overRideExec; - bool m_isValid; - DesktopFile m_desktopFile; -}; - -// 应用目录类 -class AppsDir { -public: - explicit AppsDir(const std::string &dirPath); - ~AppsDir(); - - std::string getPath(); - std::map getAppNames(); - static std::vector getAllDesktopInfos(); - -private: - std::string m_path; - std::map m_appNames; -}; - -#endif // DESKTOPINFO_H diff --git a/src/lib/dfile.cpp b/src/lib/dfile.cpp deleted file mode 100644 index 1e1d933..0000000 --- a/src/lib/dfile.cpp +++ /dev/null @@ -1,91 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "dfile.h" -#include "macro.h" -#include "dstring.h" - -#include -#include -#include - -DFile::DFile() -{ - -} - -// 符号连接 -bool DFile::isLink(std::string file) -{ - if (file.empty()) - return false; - - struct stat fileStat; - if (!stat(file.c_str(), &fileStat)) - return S_ISLNK(fileStat.st_mode); - - return false; -} - -bool DFile::isRegularFile(std::string file) -{ - if (file.empty()) - return false; - - struct stat fileStat; - if (!stat(file.c_str(), &fileStat)) - return S_ISREG(fileStat.st_mode); - - return true; -} - -bool DFile::isDir(std::string dir) -{ - if (dir.empty()) - return false; - - struct stat fileStat; - if (!stat(dir.c_str(), &fileStat)) - return S_ISDIR(fileStat.st_mode); - - return false; -} - -bool DFile::isExisted(std::string file) -{ - return !access(file.c_str(), F_OK); -} - -std::string DFile::dir(std::string path) -{ - std::string ret; - if (isDir(path)) { - ret = path; - } else { - size_t pos = path.find_last_of("/"); - if (pos != std::string::npos) { - ret.assign(path, 0, pos + 1); // 包含结尾斜杠/ - } - } - - return ret; -} - -std::string DFile::base(std::string file) -{ - std::string ret; - if (strstr(file.c_str(), "/")) { // 包含路径 - size_t pos = file.find_last_of("/"); - if (pos != std::string::npos) { - ret.assign(file, pos + 1, file.size() - pos); // 去除路径 - } - } - - size_t pos = file.find_last_of("."); // 去除后缀 - if (pos != std::string::npos) { - ret.assign(file, 0, pos + 1); - } - - return ret; -} diff --git a/src/lib/dfile.h b/src/lib/dfile.h deleted file mode 100644 index 8d51aac..0000000 --- a/src/lib/dfile.h +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef DFILE_H -#define DFILE_H - -#include - -class DFile -{ -public: - explicit DFile(); - static bool isLink(std::string file); - static bool isRegularFile(std::string file); - static bool isDir(std::string dir); - static bool isExisted(std::string file); - static std::string dir(std::string path); - static std::string base(std::string file); -}; - -#endif // DFILE_H diff --git a/src/lib/dlocale.cpp b/src/lib/dlocale.cpp deleted file mode 100644 index f67a926..0000000 --- a/src/lib/dlocale.cpp +++ /dev/null @@ -1,193 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "dlocale.h" -#include "dstring.h" - -#include -#include - -#define ComponentCodeset 1 -#define ComponentTerritory 2 -#define ComponentModifier 4 - -#define MAXLINELEN 256 - -const char *aliasFile = "/usr/share/locale/locale.alias"; -const char charUscore = '_'; -const char charDot = '.'; -const char charAt = '@'; - -Locale::Locale() -{ - pthread_mutex_init(&m_languageNames.mutex, nullptr); - - // init aliases - FILE *fp = fopen(aliasFile, "r"); - if (fp) { - - char data[MAXLINELEN] = {0}; - std::string line; - std::vector parts; - while (fgets(data, MAXLINELEN, fp)) { - char *start = &data[0]; - char *end = start; - - // 移除行首 - while (strneq(start, " ", 1) || strneq(start, "\t", 1)) - start++; - - // 过滤注释行和空行 - if (strneq(start, "#", 1) || strneq(start, "\n", 1)) - continue; - - while (!strneq(end, "\n", 1)) - end++; - - // 移除行尾 - while (strneq(end, "\n", 1) || strneq(end, "\r", 1) - || strneq(end, " ", 1) || strneq(end, "\t", 1)) - end--; - - line.assign(start, ulong(end - start + 1)); - parts = DString::splitStr(line, ' '); - // 使用\t分割 - if (parts.size() != 2) - parts = DString::splitStr(line, '\t'); - - if (parts.size() == 2) { - m_aliases[parts[0]] = parts[1]; - } - } - fclose(fp); - } -} - -/** - * @brief Locale::explodeLocale 拆分locale - * @param locale - * @return - */ -Locale::Components Locale::explodeLocale(std::string locale) -{ - Components cmp; - std::vector parts; - if (locale.find(charAt) != std::string::npos) { - parts = DString::splitStr(locale, charAt); - if (parts.size() == 2) { - cmp.modifier = parts[1]; - locale = parts[0]; - cmp.mask |= ComponentModifier; - } - } - - if (locale.find(charDot) != std::string::npos) { - parts = DString::splitStr(locale, charDot); - if (parts.size() == 2) { - cmp.codeset = parts[1]; - locale = locale[0]; - cmp.mask |= ComponentCodeset; - } - } - - if (locale.find(charUscore) != std::string::npos) { - parts = DString::splitStr(locale, charUscore); - if (parts.size() == 2) { - cmp.territory = parts[1]; - locale = parts[0]; - cmp.mask |= ComponentTerritory; - } - } - - cmp.language = locale; - return cmp; -} - -std::string Locale::guessCategoryValue(std::string categoryName) -{ - // The highest priority value is the 'LANGUAGE' environment - // variable. This is a GNU extension. - const char *language = getenv("LANGUAGE"); - if (language) - return language; - - // Setting of LC_ALL overwrites all other. - const char *lcAll = getenv("LC_ALL"); - if (lcAll) - return lcAll; - - // Next comes the name of the desired category. - const char *name = getenv(categoryName.c_str()); - if (name) - return name; - - // Last possibility is the LANG environment variable. - const char *lang = getenv("LANG"); - if (lang) - return lang; - - return "C"; -} - -std::string Locale::unaliasLang(std::string lang) -{ - if (m_aliases.find(lang) != m_aliases.end()) - return m_aliases[lang]; - else - return lang; -} - -/** - * @brief Locale::getLocaleVariants - * @param locale - * @return - */ -std::vector Locale::getLocaleVariants(const std::string &locale) -{ - auto cmp = explodeLocale(locale); - uint mask = cmp.mask; - std::vector variants; - for (uint i = 0; i <= mask; i++) { - uint j = mask - i; - //if ((j & ^mask) == 0) { - std::string var(cmp.language); - if (j & ComponentTerritory) - var = var + charUscore + cmp.territory; - if (j & ComponentCodeset) - var = var + charDot + cmp.codeset; - if (j & ComponentModifier) - var = var + charAt + cmp.modifier; - - variants.push_back(var); - //} - } - - return variants; -} - -std::vector Locale::getLanguageNames() -{ - std::vector names; - std::string value(guessCategoryValue("LC_MESSAGES")); - if (value.empty()) { - names.push_back(value); - return names; - } - - pthread_mutex_lock(&m_languageNames.mutex); - if (m_languageNames.language != value) { - m_languageNames.language = value; - m_languageNames.names.clear(); - std::vector langs = DString::splitStr(value, ':'); - for (const auto & lang : langs) { - std::vector localeVariant = getLocaleVariants(unaliasLang(lang)); - for (const auto & var : localeVariant) - m_languageNames.names.push_back(var); - } - m_languageNames.names.push_back("C"); - } - pthread_mutex_unlock(&m_languageNames.mutex); - - return m_languageNames.names; -} diff --git a/src/lib/dlocale.h b/src/lib/dlocale.h deleted file mode 100644 index 50117b6..0000000 --- a/src/lib/dlocale.h +++ /dev/null @@ -1,49 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef LOCALE_H -#define LOCALE_H - -#include -#include -#include - -// 本地化类 -class Locale { - struct LanguageNameCache { - std::string language; - std::vector names; - pthread_mutex_t mutex; - }; - - struct Components { - Components() : mask(0) {} // 数字必须初始化 - std::string language; - std::string territory; - std::string codeset; - std::string modifier; - uint mask; - }; - -public: - std::vector getLocaleVariants(const std::string &locale); - std::vector getLanguageNames(); - static inline Locale *instance() { - static Locale instance; - return &instance; - } - -private: - Locale(); - Locale(const Locale &); - Locale& operator= (const Locale &); - - Components explodeLocale(std::string locale); - std::string guessCategoryValue(std::string categoryName); - std::string unaliasLang(std::string); - std::map m_aliases; - LanguageNameCache m_languageNames; -}; - -#endif diff --git a/src/lib/dstring.cpp b/src/lib/dstring.cpp deleted file mode 100644 index 1349d9d..0000000 --- a/src/lib/dstring.cpp +++ /dev/null @@ -1,122 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "dstring.h" - -DString::DString() -{ - -} - -DString::~DString() -{ - -} - -std::vector DString::splitChars(const char *cs, char c) -{ - std::vector ret; - if (!cs) { - return ret; - } - - unsigned long idx = 0; - unsigned long size = strlen(cs); - bool found = false; - std::string sub; - for (unsigned long i=0; i < size; i++) { - if (!strneq(&cs[i], &c, 1)) - continue; - - sub.assign(cs, found ? idx+1:idx, found ? i-idx-1:i-idx); - if (idx < i && !sub.empty()) { - ret.push_back(sub); - } - idx = i; - found = true; - } - sub.assign(cs, found ? idx+1:idx, found ? size-idx-1:size-idx); - if (idx < size && !sub.empty()) { - ret.push_back(sub); - } - - return ret; -} - -std::vector DString::splitStr(const std::string &str, char c) -{ - return splitChars(str.c_str(), c); -} - -bool DString::startWith(const char *chars, const char *prefix) -{ - if (!chars || !prefix) { - return false; - } - - size_t len; - len = strlen(prefix); - return strneq(chars, prefix, len); -} - -bool DString::startWith(const std::string &str, const std::string &prefix) -{ - return startWith(str.c_str(), prefix.c_str()); -} - -bool DString::endWith(const char *chars, const char *suffix) -{ - if (!chars || !suffix) { - return false; - } - - size_t charsLen = strlen(chars); - size_t suffixLen = strlen(suffix); - - if (charsLen == 0 || charsLen < suffixLen) - return false; - - return memcmp(chars + charsLen - suffixLen, suffix, suffixLen) == 0; -} - -bool DString::endWith(const std::string &str, const std::string &suffix) -{ - return endWith(str.c_str(), suffix.c_str()); -} - -char *DString::delQuote(const char *chars) -{ - char *data = nullptr; - if (!chars) - return data; - - if (strneq(chars, "\"", 1) && strneq(chars + strlen(chars) - 1, "\"", 1)) { - data = static_cast(calloc(1, strlen(chars) - 2)); - memcpy(data, chars + 1, strlen(chars) - 1); - } else { - data = static_cast(calloc(1, strlen(chars) + 1)); - memcpy(data, chars, strlen(chars) + 1); - } - - return data; -} - -void DString::delQuote(std::string &str) -{ - while (*str.begin() == '\"' && *str.rbegin() == '\"') - str.assign(str.substr(1, str.size() - 2)); -} - -std::string DString::join(std::vector strs, std::string joinStr) -{ - std::string ret; - for (uint i = 0; i < strs.size(); i++) { - if (i < strs.size() - 1) { - ret += strs[i] + joinStr; - } else { - ret += strs[i]; - } - } - return ret; -} diff --git a/src/lib/dstring.h b/src/lib/dstring.h deleted file mode 100644 index 63a4b03..0000000 --- a/src/lib/dstring.h +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef DSTRING_H -#define DSTRING_H - -#include -#include -#include - -#define streq(a,b) (strcmp((a),(b)) == 0) -#define strneq(a, b, n) (strncmp((a), (b), (n)) == 0) -#define strcaseeq(a,b) (strcasecmp((a),(b)) == 0) -#define strncaseeq(a, b, n) (strncasecmp((a), (b), (n)) == 0) - -// 字符串操作 -class DString -{ -public: - DString(); - ~DString(); - - // 字符串拆分 - static std::vector splitChars(const char *cs, char c); - static std::vector splitStr(const std::string &str, char c); - // 字符串前缀判断 - static bool startWith(const char *chars, const char *prefix); - static bool startWith(const std::string &str, const std::string &prefix); - // 字符后缀判断 - static bool endWith(const char *chars, const char *suffix); - static bool endWith(const std::string &str, const std::string &suffix); - // 去除首尾引用 - static char *delQuote(const char *chars); - static void delQuote(std::string &str); - // 连接字符串 - static std::string join(std::vector strs, std::string joinStr); -}; - -#endif // DSTRING_H diff --git a/src/lib/gsetting.cpp b/src/lib/gsetting.cpp deleted file mode 100644 index 45b5d15..0000000 --- a/src/lib/gsetting.cpp +++ /dev/null @@ -1,89 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "gsetting.h" - -#include - -GSetting::GSetting(std::string settings) - : m_gs(nullptr) - , m_settings(settings) -{ - m_gs = g_settings_new(m_settings.c_str()); - if (!m_gs) { - std::cout << "GSetting: g_settings_new error" << std::endl; - } -} - -GSetting::~GSetting() -{ - if (m_gs) { - g_object_unref(m_gs); - m_gs = nullptr; - } -} - -std::string GSetting::getString(std::string key) -{ - std::string ret; - if (m_gs) { - ret = g_settings_get_string(m_gs, key.c_str()); - } - return ret; -} - -void GSetting::setString(std::string key, std::string value) -{ - if (m_gs) { - g_settings_set_string(m_gs, key.c_str(), value.c_str()); - } -} - -int GSetting::getInt(std::string key) -{ - int ret = 0; - if (m_gs) { - ret = g_settings_get_int(m_gs, key.c_str()); - } - return ret; -} - -void GSetting::setInt(std::string key, int value) -{ - if (m_gs) { - g_settings_set_int(m_gs, key.c_str(), value); - } -} - -double GSetting::getDouble(std::string key) -{ - double ret = 0; - if (m_gs) { - ret = g_settings_get_double(m_gs, key.c_str()); - } - return ret; -} - -void GSetting::setDouble(std::string key, double value) -{ - if (m_gs) { - g_settings_set_double(m_gs, key.c_str(), value); - } -} - -bool GSetting::getBool(std::string key) -{ - bool ret = false; - if (m_gs) { - ret = g_settings_get_boolean(m_gs, key.c_str()); - } - return ret; -} - -void GSetting::setBool(std::string key, bool value) -{ - if (m_gs) { - g_settings_set_double(m_gs, key.c_str(), value); - } -} diff --git a/src/lib/gsetting.h b/src/lib/gsetting.h deleted file mode 100644 index 8087fed..0000000 --- a/src/lib/gsetting.h +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef GSETTING_H -#define GSETTING_H - -#include -#include - -class GSetting -{ -public: - explicit GSetting(std::string settings); - ~GSetting(); - - std::string getString(std::string key); - void setString(std::string key, std::string value); - - int getInt(std::string key); - void setInt(std::string key, int value); - - double getDouble(std::string key); - void setDouble(std::string key, double value); - - bool getBool(std::string key); - void setBool(std::string key, bool value); - -private: - GSettings *m_gs; - std::string m_settings; -}; - -#endif // GSETTING_H diff --git a/src/lib/keyfile.cpp b/src/lib/keyfile.cpp deleted file mode 100644 index 69c52c2..0000000 --- a/src/lib/keyfile.cpp +++ /dev/null @@ -1,306 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "keyfile.h" -#include "dlocale.h" -#include "dstring.h" -#include "macro.h" - -#include -#include -#include -#include -#include - -KeyFile::KeyFile(char separtor) - : m_modified(false) - , m_listSeparator(separtor) -{ -} - -KeyFile::~KeyFile() -{ -} - -bool KeyFile::getBool(const std::string §ion, const std::string &key, bool defaultValue) -{ - if (m_mainKeyMap.find(section) == m_mainKeyMap.end()) - return false; - - std::string valueStr = m_mainKeyMap[section][key]; - bool value = defaultValue; - if (valueStr == "true") - value = true; - else if (valueStr == "false") - value = false; - - return value; -} - -void KeyFile::setBool(const std::string §ion, const std::string &key, const std::string &defaultValue) -{ - if (m_mainKeyMap.find(section) == m_mainKeyMap.end()) - m_mainKeyMap.insert({section, KeyMap()}); - - m_mainKeyMap[section][key] = defaultValue; -} - -// TODO -std::vector KeyFile::getBoolList(const std::string §ion, const std::string &key, bool defaultValue) -{ - std::vector tmp; - return tmp; -} - -int KeyFile::getInt(const std::string §ion, const std::string &key, int defaultValue) -{ - if (m_mainKeyMap.find(section) == m_mainKeyMap.end()) - return defaultValue; - - std::string valueStr = m_mainKeyMap[section][key]; - int value; - try { - value = std::stoi(valueStr); - } catch (std::invalid_argument&) { - value = defaultValue; - } - - return value; -} - -// TODO -std::vector KeyFile::getIntList(const std::string §ion, const std::string &key, int defaultValue) -{ - std::vector tmp; - return tmp; -} - -// TODO -int64_t KeyFile::getInt64(const std::string §ion, const std::string &key, int64_t defaultValue) -{ - return int64_t(0); -} - -// TODO -uint64_t KeyFile::getUint64(const std::string §ion, const std::string &key, int64_t defaultValue) -{ - return uint64_t(0); -} - -// TODO -float KeyFile::getFloat(const std::string §ion, const std::string &key, float defaultValue) -{ - return 1.0; -} - -std::string KeyFile::getStr(const std::string §ion, const std::string &key, std::string defaultValue) -{ - if (m_mainKeyMap.find(section) == m_mainKeyMap.end()) - return defaultValue; - - std::string valueStr = m_mainKeyMap[section][key]; - if (valueStr.empty()) - valueStr = defaultValue; - - return valueStr; -} - -bool KeyFile::containKey(const std::string §ion, const std::string &key) -{ - if (m_mainKeyMap.find(section) == m_mainKeyMap.end()) - return false; - - return m_mainKeyMap[section].find(key) != m_mainKeyMap[section].end(); -} - -std::string KeyFile::getLocaleStr(const std::string §ion, const std::string &key, std::string defaultLocale) -{ - std::vector languages = defaultLocale.empty() - ? Locale::instance()->getLanguageNames() - : Locale::instance()->getLocaleVariants(defaultLocale); - - std::string translated; - for (const auto &lang : languages) { - translated.assign(getStr(section, key + "[" + lang + "]")); - if (!translated.empty()) - return translated; - } - - // NOTE: not support key Gettext-Domain - // fallback to default key - return getStr(section, key); -} - -std::vector KeyFile::getStrList(const std::string §ion, const std::string &key) -{ - std::string value = getStr(section, key); - return DString::splitStr(value, m_listSeparator); -} - -std::vector KeyFile::getLocaleStrList(const std::string §ion, const std::string &key, std::string defaultLocale) -{ - std::vector languages = defaultLocale.empty() - ? Locale::instance()->getLanguageNames() - : Locale::instance()->getLocaleVariants(defaultLocale); - - std::vector translated; - for (const auto &lang : languages) { - translated = getStrList(section, key + "[" + lang + "]"); - if (translated.size() > 0) - return translated; - } - - //fallback to default key - return getStrList(section, key); -} - -// 修改keyfile内容 -void KeyFile::setKey(const std::string §ion, const std::string &key, const std::string &value) -{ - if (m_mainKeyMap.find(section) == m_mainKeyMap.end()) - m_mainKeyMap.insert({section, KeyMap()}); - - m_mainKeyMap[section][key] = value; -} - -// 写入文件 -bool KeyFile::saveToFile(const std::string &filePath) -{ - FILE *sfp = fopen(filePath.data(), "w+"); - if (!sfp) { - perror("open file failed..."); - return false; - } - - for (const auto &im : m_mainKeyMap) { - if (!writeSectionToFile(im.first, im.second,sfp)){ - return false; - } - } - - fclose(sfp); - return true; -} - -bool KeyFile::writeSectionToFile(const std::string& sectionName, const KeyMap& keyMap, FILE * file){ - if (file == nullptr) { - return false; - } - - std::string section = "[" + sectionName + "]\n"; - fputs(section.c_str(), file); - for (const auto &ik : keyMap) { - std::string kv = ik.first + "=" + ik.second + "\n"; - fputs(kv.c_str(), file); - } - - // FIXME(black_desk): should handle fputs error - return true; -} - -bool KeyFile::loadFile(const std::string &filePath) -{ - m_mainKeyMap.clear(); - - std::string lastSection; - std::ifstream fs(filePath); - if (!fs.is_open()) { - perror("open file failed: "); - return false; - } - - std::string line; - while (std::getline(fs, line)) { - line.erase( - line.begin(), - std::find_if( - line.begin(), line.end(), - std::not1(std::ptr_fun(std::isspace)) - ) - ); - - if (line.front() == '#') { - continue; - } - - line.erase( - std::find_if( - line.rbegin(), line.rend(), - std::not1(std::ptr_fun(std::isspace)) - ).base(), - line.end() - ); - - if (line.front() == '[') { - auto rPos = line.find_first_of(']'); - if ( rPos != std::string::npos && 0 < rPos ) { - // TODO(black_desk): lastSection might be empty string here. - // I cannot found a spec for the space before groupname in - // freedesktop.org - lastSection = line.substr(1, rPos-1); - - m_mainKeyMap.insert({ - lastSection, - KeyMap() - }); - - } - continue; - } - - - auto equalPos = line.find_first_of('='); - - if (equalPos == std::string::npos) { - continue; - } - - // 文件格式错误 - if (lastSection.empty()) { - std::cout << "failed to load file " << filePath << std::endl; - return false; - } - - // 子键 - - // TODO(black_desk): we should check chars in key here, as spec says - // that it can only contain a-z0-9A-Z - std::string key = line.substr(0, equalPos); - std::string value = equalPos + 1 < line.length() ? - line.substr(equalPos + 1) : - ""; - - // TODO(black_desk): space after value is removed before. But I cannot - // find a spec about this behavior. - m_mainKeyMap[lastSection][key] = value; - } - - m_filePath = filePath; - - return true; -} - -std::vector KeyFile::getMainKeys() -{ - std::vector mainKeys; - for (const auto &iter : m_mainKeyMap) - mainKeys.push_back(iter.first); - - return mainKeys; -} - -void KeyFile::print() -{ - std::cout << "sectionMap: " << std::endl; - for (auto sectionMap : m_mainKeyMap) { - std::cout << "section=" << sectionMap.first << std::endl; - KeyMap keyMap = sectionMap.second; - - for (auto iter : keyMap) { - std::cout << iter.first << "=" << iter.second << std::endl; - } - - std::cout << std::endl; - } -} diff --git a/src/lib/keyfile.h b/src/lib/keyfile.h deleted file mode 100644 index 01d72b8..0000000 --- a/src/lib/keyfile.h +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef KEYFILE_H -#define KEYFILE_H - -#include -#include -#include -#include - -typedef std::map KeyMap; -typedef std::map MainKeyMap; - -// 解析ini文件类 -class KeyFile -{ -public: - explicit KeyFile(char separtor = ';'); - virtual ~KeyFile(); - - bool getBool(const std::string §ion, const std::string &key, bool defaultValue = false); - void setBool(const std::string §ion, const std::string &key, const std::string &defaultValue = "false"); - std::vector getBoolList(const std::string §ion, const std::string &key, bool defaultValue = false); - int getInt(const std::string §ion, const std::string &key, int defaultValue = 0); - std::vector getIntList(const std::string §ion, const std::string &key, int defaultValue = 0); - int64_t getInt64(const std::string §ion, const std::string &key, int64_t defaultValue = 0); - uint64_t getUint64(const std::string §ion, const std::string &key, int64_t defaultValue = 0); - float getFloat(const std::string §ion, const std::string &key, float defaultValue = 0); - std::string getStr(const std::string §ion, const std::string &key, std::string defaultValue = ""); - bool containKey(const std::string §ion, const std::string &key); - std::string getLocaleStr(const std::string §ion, const std::string &key, std::string defaultLocale = ""); - std::vector getStrList(const std::string §ion, const std::string &key); - std::vector getLocaleStrList(const std::string §ion, const std::string &key, std::string defaultLocale = ""); - - void setKey(const std::string §ion, const std::string &key, const std::string &value); - virtual bool saveToFile(const std::string &filePath); - bool loadFile(const std::string &filePath); - std::vector getMainKeys(); - std::string getFilePath() - { - return m_filePath; - } - - // for test - void print(); - -protected: - MainKeyMap m_mainKeyMap; // section -> key : value - std::string m_filePath; - bool m_modified; - char m_listSeparator; - - static bool writeSectionToFile(const std::string& sectionName, const KeyMap& keyMap, FILE * file); -}; - -#endif // KEYFILE_H diff --git a/src/lib/lang.h b/src/lib/lang.h deleted file mode 100644 index f398d2d..0000000 --- a/src/lib/lang.h +++ /dev/null @@ -1,55 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef LANG_H -#define LANG_H - -#include "dstring.h" - -#include -#include -#include -#include -#include - -// 返回用户语言,参见man gettext -inline std::vector queryLangs() { - std::vector ret; - const char *lcAll = getenv("LC_ALL"); - const char *lcMessage = getenv("LC_MESSAGE"); - const char *language = getenv("LANGUAGE"); - const char *lang = getenv("LANG"); - - auto cutOff = [](std::string str)->std::string { - size_t idx = str.find("."); - if (idx == std::string::npos) - return str; - - return std::string(str).substr(0, idx); - }; - - if (lcAll && std::string(lcAll) != "C" - && language && std::string(language) != "") - { - std::vector splits = DString::splitChars(language, ':'); - for (const auto &l : splits) { - ret.push_back(cutOff(l)); - } - return ret; - } - - if (lcAll && std::string(lcAll) != "") - ret.push_back(cutOff(lcAll)); - - if (lcMessage && std::string(lcMessage) != "") - ret.push_back(cutOff(lcMessage)); - - if (lang && std::string(lang) != "") - ret.push_back(cutOff(lang)); - - return ret; -} - - -#endif // LANG_H diff --git a/src/lib/macro.h b/src/lib/macro.h deleted file mode 100644 index 30e678f..0000000 --- a/src/lib/macro.h +++ /dev/null @@ -1,18 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef MACRO_H -#define MACRO_H - -#define _likely_(x) (__builtin_expect(!!(x), 1)) -#define _unlikely_(x) (__builtin_expect(!!(x), 0)) - -#define MAX(x, y) (x) > (y) ? (x) : (y) -#define MIN(x, y) (x) < (y) ? (x) : (y) - -#define MAX_FILEPATH_LEN 256 -#define MAX_LINE_LEN 256 - - -#endif // MACRO_H diff --git a/src/lib/meminfo.cpp b/src/lib/meminfo.cpp deleted file mode 100644 index 80f81a8..0000000 --- a/src/lib/meminfo.cpp +++ /dev/null @@ -1,72 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "meminfo.h" -#include "macro.h" -#include "dstring.h" - -#include -#include -#include - -MemInfo::MemInfo() -{ - -} - -MemoryInfo MemInfo::getMemoryInfo() -{ - MemoryInfo ret; - FILE *fp = fopen("/proc/meminfo", "r"); - if (!fp) - return ret; - - char line[MAX_LINE_LEN] = {0}; - while (fgets(line, MAX_LINE_LEN, fp)) { - std::string info(line); - std::vector parts = DString::splitStr(info, ':'); - if (parts.size() != 2) - continue; - - uint64_t num = std::stoll(parts[1]); - if (parts[0] == "MemTotal") { - ret.memTotal = num; - } else if (parts[0] == "MemFree") { - ret.memFree = num; - } else if (parts[0] == "MemAvailable") { - ret.memAvailable = num; - } else if (parts[0] == "Buffers") { - ret.buffers = num; - } else if (parts[0] == "Cached") { - ret.cached = num; - } else if (parts[0] == "SwapTotal") { - ret.swapTotal = num; - } else if (parts[0] == "SwapFree") { - ret.swapFree = num; - } else if (parts[0] == "SwapCached") { - ret.swapCached = num; - } - } - fclose(fp); - - return ret; -} - -// IsSufficient check the memory whether reaches the qualified value -bool MemInfo::isSufficient(uint64_t minMemAvail, uint64_t maxSwapUsed) -{ - if (minMemAvail == 0) - return true; - - MemoryInfo info = getMemoryInfo(); - uint64_t used = info.swapTotal - info.swapFree - info.swapCached; - - if (info.memAvailable < minMemAvail) - return false; - - if (maxSwapUsed == 0 || info.memAvailable > used) - return true; - - return used < maxSwapUsed; -} diff --git a/src/lib/meminfo.h b/src/lib/meminfo.h deleted file mode 100644 index 7db610e..0000000 --- a/src/lib/meminfo.h +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef MEMINFO_H -#define MEMINFO_H - -#include - -// MemoryInfo show the current memory stat, sum by kb -struct MemoryInfo -{ - uint64_t memTotal; - uint64_t memFree; - uint64_t memAvailable; - uint64_t buffers; - uint64_t cached; - uint64_t swapTotal; - uint64_t swapFree; - uint64_t swapCached; -}; - -class MemInfo -{ -public: - MemInfo(); - - static MemoryInfo getMemoryInfo(); - - static bool isSufficient(uint64_t minMemAvail, uint64_t maxSwapUsed); -}; - -#endif // MEMINFO_H diff --git a/src/lib/process.cpp b/src/lib/process.cpp deleted file mode 100644 index 8a4d207..0000000 --- a/src/lib/process.cpp +++ /dev/null @@ -1,183 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "process.h" -#include "macro.h" -#include "dstring.h" -#include "dfile.h" - -#include -#include -#include -#include - -#define FILECONTENLEN 2048 - -Process::Process() - : m_pid(0) - , m_ppid(0) -{ - -} - -Process::Process(int _pid) - : m_pid(_pid) - , m_ppid(0) -{ - -} - -bool Process::isExist() -{ - std::string procDir = "/proc/" + std::to_string(m_pid); - return DFile::isExisted(procDir); -} - -std::vector Process::getCmdLine() -{ - if (m_cmdLine.size() == 0) { - std::string cmdlineFile = getFile("cmdline"); - m_cmdLine = readFile(cmdlineFile); - } - - return m_cmdLine; -} - -std::string Process::getCwd() -{ - if (m_cwd.empty()) { - std::string cwdFile = getFile("cwd"); - char path[MAX_FILEPATH_LEN] = {}; - ssize_t len = readlink(cwdFile.c_str(), path, MAX_FILEPATH_LEN); - if (len > 0 && len < MAX_FILEPATH_LEN) { - m_cwd = std::string(path) + "/"; - } - } - - return m_cwd; -} - -std::string Process::getExe() -{ - if (m_exe.empty()) { - std::string cmdLineFile = getFile("exe"); - char path[MAX_FILEPATH_LEN] = {}; - ssize_t len = readlink(cmdLineFile.c_str(), path, MAX_FILEPATH_LEN); - if (len > 0 && len < MAX_FILEPATH_LEN) { - m_exe = std::string(path); - } - } - - return m_exe; -} - -std::vector Process::getEnviron() -{ - if (m_environ.size() == 0) { - std::string envFile = getFile("environ"); - m_environ = readFile(envFile); - } - - return m_environ; -} - -std::string Process::getEnv(const std::string &key) -{ - if (m_environ.size() == 0) - m_environ = getEnviron(); - - std::string keyPrefix = key + "="; - for (auto & env : m_environ) { - if (DString::startWith(env, keyPrefix)) { - ulong len = keyPrefix.size(); - return env.substr(len, env.size() - len); - } - } - - return ""; -} - -Status Process::getStatus() -{ - if (!m_status.empty()){ - return m_status; - } - - std::string statusFile = getFile("status"); - - std::ifstream fs(statusFile); - if (!fs.is_open()) { - return m_status; - } - - std::string tmp = ""; - while (std::getline(fs, tmp)) { - auto pos = tmp.find_first_of(':'); - if (pos == std::string::npos) { - continue; - } - - std::string value; - if (pos + 1 < tmp.length()) { - value = tmp.substr(pos + 1); - } - - m_status[tmp.substr(0, pos)] = value; - } - - return m_status; -} - -std::vector Process::getUids() -{ - if (m_uids.size() == 0) { - if (m_status.find("Uid") != m_status.end()) { - std::string uidGroup = m_status["Uid"]; - std::vector parts = DString::splitStr(uidGroup, '\t'); - m_uids.reserve(parts.size()); - std::transform(parts.begin(), parts.end(), m_uids.begin(), - [](std::string idStr) -> int {return std::stoi(idStr);}); - } - } - - return m_uids; -} - -int Process::getPid() -{ - return m_pid; -} - -int Process::getPpid() -{ - if (m_ppid == 0) { - if (m_status.find("PPid") != m_status.end()) { - m_ppid = std::stoi(m_status["PPid"]); - } - } - - return m_ppid; -} - -std::string Process::getFile(const std::string &name) -{ - return "/proc/" + std::to_string(m_pid) + "/" + name; -} - -// This funciton only can used to read `environ` and `cmdline` -std::vector Process::readFile(std::string fileName) -{ - std::vector ret; - std::ifstream fs(fileName); - if (!fs.is_open()) { - return ret; - } - - std::string tmp; - while (std::getline(fs, tmp, '\0')) { - ret.push_back(tmp); - } - - return ret; -} diff --git a/src/lib/process.h b/src/lib/process.h deleted file mode 100644 index 0549076..0000000 --- a/src/lib/process.h +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef PROCESS_H -#define PROCESS_H - -#include -#include -#include - -typedef std::map Status; - -class Process -{ -public: - explicit Process(); - explicit Process(int _pid); - - bool isExist(); - std::vector getCmdLine(); - std::string getCwd(); - std::string getExe(); - std::vector getEnviron(); - std::string getEnv(const std::string &key); - Status getStatus(); - std::vector getUids(); - int getPid(); - int getPpid(); - -private: - std::string getFile(const std::string &name); - std::vector readFile(std::string fileName); - - int m_pid; - std::vector m_cmdLine; - std::string m_cwd; - std::string m_exe; - std::vector m_environ; - Status m_status; - std::vector m_uids; - int m_ppid; -}; - -#endif // PROCESS_H diff --git a/src/lib/terminalinfo.cpp b/src/lib/terminalinfo.cpp deleted file mode 100644 index ea3a608..0000000 --- a/src/lib/terminalinfo.cpp +++ /dev/null @@ -1,164 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "terminalinfo.h" -#include "utils.h" -#include "appinfocommon.h" - -#include - -TerminalInfo& TerminalInfo::getInstanceTerminal() -{ - static TerminalInfo terminal; - - return terminal; -} - -TerminalInfo::TerminalInfo() - : gsSchemaDefaultTerminal("com.deepin.desktop.default-applications.terminal") - , gsKeyExec("exec") - , gsKeyExecArg("exec-arg") - , gsKeyAppId("app-id") - , categoryTerminalEmulator("TerminalEmulator") - , execXTerminalEmulator("x-terminal-emulator") - , defaultTerminal(new QGSettings(gsSchemaDefaultTerminal.c_str())) -{ - init(); -} - -void TerminalInfo::resetTerminal() -{ - defaultTerminal->reset(gsKeyExec.c_str()); - defaultTerminal->reset(gsKeyExecArg.c_str()); - defaultTerminal->reset(gsKeyExecArg.c_str()); -} - -std::string TerminalInfo::getPresetTerminalPath() -{ - std::string path; - - for (auto term : terms) { - path = lookPath(term); - if (!path.empty()) { - return path; - } - } - - return ""; -} - -void TerminalInfo::init() -{ - termBlackList = {"guake", - "tilda", - "org.kde.yakuake", - "qterminal_drop", - "Terminal" - }; - - execArgMap = {{"gnome-terminal", "-x"}, - {"mate-terminal", "-x"}, - {"terminator", "-x"}, - {"xfce4-terminal", "-x"} - }; - - terms = {"deepin-terminal", - "gnome-terminal", - "terminator", - "xfce4-terminal", - "rxvt", - "xterm" - }; -} -std::shared_ptr TerminalInfo::getDefaultTerminal() -{ - - std::string appId = defaultTerminal->get(gsKeyAppId.c_str()).toString().toStdString(); - - if (!hasEnding(appId, AppinfoCommon::DesktopExt)) { - appId += AppinfoCommon::DesktopExt; - } - - std::vector> appInfos = getTerminalInfos(); - - for (auto iter : appInfos) { - if (iter->getDesktopId() == appId) { - return iter; - } - } - - for (auto appInfo : appInfos) { - for (auto term : terms) { - if (appInfo->getCmdline() == term) { - return appInfo; - } - } - } - - return nullptr; -} - -bool TerminalInfo::setDefaultTerminal(std::string id) -{ - std::vector> appInfos = getTerminalInfos(); - - for (auto iter : appInfos) { - if (iter->getDesktopId() == id) { - std::string cmdline = iter->getCmdline(); - std::string exec = cmdline.substr(0, cmdline.find(" ")); - defaultTerminal->set(gsKeyExec.c_str(), exec.c_str()); - - std::string arg = "-e"; - if (execArgMap.count(exec) != 0) { - arg = execArgMap[exec]; - } - defaultTerminal->set(gsKeyExecArg.c_str(), arg.c_str()); - - if (hasEnding(id, AppinfoCommon::DesktopExt)) { - id = id.substr(0, id.find(AppinfoCommon::DesktopExt)); - } - defaultTerminal->set(gsKeyAppId.c_str(), id.c_str()); - return true; - } - } - return false; -} - -std::vector> TerminalInfo::getTerminalInfos() -{ - std::map> skipDirs; - std::vector> appInfos = AppInfoManger::getAll(skipDirs); - - std::vector>::iterator iter = appInfos.begin(); - - while (iter != appInfos.end()) { - if (isTerminalApp(*iter)) { - (*iter)->setDesktopId((*iter)->getDesktopId() + AppinfoCommon::DesktopExt); - iter++; - } else { - iter = appInfos.erase(iter); - } - } - - return appInfos; -} - -bool TerminalInfo::isTerminalApp(std::shared_ptr appInfo) -{ - if (std::find(termBlackList.begin(), termBlackList.end(), appInfo->getDesktopId()) != termBlackList.end()) { - return false; - } - - std::vector categories = appInfo->getCategories(); - if (std::find(categories.begin(), categories.end(), categoryTerminalEmulator) == categories.end()) { - return false; - } - - std::string cmdline = appInfo->getCmdline(); - if (cmdline.find(execXTerminalEmulator) != std::string::npos) { - return false; - } - - return true; -} diff --git a/src/lib/terminalinfo.h b/src/lib/terminalinfo.h deleted file mode 100644 index 7165a18..0000000 --- a/src/lib/terminalinfo.h +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef TERMINALINFO_H -#define TERMINALINFO_H - -#include "appinfo.h" - -#include -#include -#include -#include - -class TerminalInfo -{ -public: - static TerminalInfo& getInstanceTerminal(); - void resetTerminal(); - std::string getPresetTerminalPath(); - bool setDefaultTerminal(std::string id); - std::shared_ptr getDefaultTerminal(); - std::vector> getTerminalInfos(); - TerminalInfo(const TerminalInfo& term) = delete; - TerminalInfo& operator=(const TerminalInfo& term) = delete; - -private: - TerminalInfo(); - void init(); - - bool isTerminalApp(std::shared_ptr appInfo); - -private: - - std::vector termBlackList; - std::map execArgMap; - std::vector terms; - const std::string gsSchemaDefaultTerminal; - const std::string gsKeyExec; - const std::string gsKeyExecArg; - const std::string gsKeyAppId; - const std::string categoryTerminalEmulator; - const std::string execXTerminalEmulator; - std::shared_ptr defaultTerminal; -}; - -#endif // TERMINALINFO_H diff --git a/src/lib/utils.cpp b/src/lib/utils.cpp deleted file mode 100644 index bb1d1e2..0000000 --- a/src/lib/utils.cpp +++ /dev/null @@ -1,199 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "utils.h" - -#define HOME "HOME" - -#include -#include - -std::string getUserDir(const char* envName); -std::vector getSystemDirs(const char* envName); - -std::string getUserHomeDir() -{ - const char* dir = getenv(HOME); - - if (dir) { - return dir; - } - - struct passwd* user = getpwent(); - if (user) { - return user->pw_dir; - } - - return ""; -} - -std::string getUserDataDir() -{ - // default $HOME/.local/share - std::string userDataDir = getUserDir("XDG_DATA_HOME"); - - if (userDataDir.empty()) { - userDataDir = getUserHomeDir(); - if (!userDataDir.empty()) { - userDataDir += "/.local/share"; - } - } - return userDataDir; -} - -std::string getUserConfigDir() -{ - // default $HOME/.config - std::string userConfigDir = getUserDir("XDG_CONFIG_HOME"); - - if (userConfigDir.empty()) { - userConfigDir = getUserHomeDir(); - if (!userConfigDir.empty()) { - userConfigDir += "/.config"; - } - - } - return userConfigDir; -} - -std::string getUserDir(const char* envName) -{ - const char* envDir = getenv(envName); - if (!envDir) { - return ""; - } - - if (!QDir::isAbsolutePath(envDir)) { - return ""; - } - - return envDir; -} - -std::vector getSystemDataDirs() -{ - std::vector systemDir = getSystemDirs("XDG_DATA_DIRS"); - - if (systemDir.empty()) { - systemDir.push_back({"/usr/local/share", "/usr/share"}); - } - - return systemDir; -} - -std::vector getSystemConfigDirs() -{ - std::vector systemDir = getSystemDirs("XDG_CONFIG_DIRS"); - - if (systemDir.empty()) { - systemDir.push_back("/etc/xdg"); - } - - return systemDir; -} - -std::vector getSystemDirs(const char* envName) -{ - std::vector dirVector; - const char* envDir = getenv(envName); - if (envDir == nullptr) { - return dirVector; - } - - QString tempDirs(envDir); - auto tempList = tempDirs.split(":"); - - for (auto iter : tempList) { - if (QDir::isAbsolutePath(iter)) { - dirVector.push_back(iter.toStdString()); - } - } - - - return dirVector; -} - -std::string lookPath(std::string file) -{ - std::string path; - - if (file.find("/") != std::string::npos) { - if (access(path.c_str(), X_OK) != -1) { - return file; - } else { - return path; - } - } - - char* pathEnv = getenv("PATH"); - - char* temp = strtok(pathEnv, ";"); - - while (temp) { - path = std::string(temp) + "/" + file; - - if (access(path.c_str(), X_OK) != -1) { - return path; - } else { - path = ""; - temp = strtok(nullptr, "/"); - } - } - - return path; -} - -void walk(std::string root, std::vector& skipdir, std::map& retMap) -{ - walk(root, ".", skipdir, retMap); -} - -void walk(std::string root, std::string name, std::vector& skipdir, std::map& retMap) -{ - QDir dir(root.c_str()); - - if (dir.exists()) { - if (std::find(skipdir.begin(), skipdir.end(), name) != skipdir.end()) { - return; - } - } else { - return; - } - - if (hasEnding(name, ".desktop")) { - retMap[name] = 0; - } - - std::string path = root + "/" + name; - QDir temp(path.c_str()); - - QStringList entryList = temp.entryList(); - for (auto iter : entryList) { - QFile file(iter); - - if (file.exists()) { - continue; - } - walk(root, name + "/" + iter.toStdString(), skipdir, retMap); - } - -} - -bool hasEnding(std::string const& fullString, std::string const& ending) -{ - if (fullString.length() >= ending.length()) { - return fullString.compare(fullString.length() - ending.length(), ending.length(), ending) == 0; - } else { - return false; - } -} - -bool hasBeginWith(std::string const& fullString, std::string const& ending) -{ - if (fullString.length() >= ending.length()) { - return (0 == fullString.compare(0, ending.length(), ending)); - } else { - return false; - } -} diff --git a/src/lib/utils.h b/src/lib/utils.h deleted file mode 100644 index 7d5b27a..0000000 --- a/src/lib/utils.h +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef UTILS_H -#define UTILS_H -#include -#include -#include -#include - -std::string getUserHomeDir(); - -std::string getUserDataDir(); - -std::string getUserConfigDir(); - -std::string getUserDir(const char* envName); - -std::vector getSystemDataDirs(); - -std::vector getSystemConfigDirs(); - -std::vector getSystemDirs(const char* envName); - -std::string lookPath(std::string file); - -void walk(std::string root, std::vector& skipdir, std::map& retMap); - -void walk(std::string root, std::string name, std::vector& skipdir, std::map& retMap); - -bool hasEnding(std::string const& fullString, std::string const& ending); - -bool hasBeginWith(std::string const& fullString, std::string const& ending); -#endif // UTILS_H - diff --git a/src/lib/xcbutils.cpp b/src/lib/xcbutils.cpp deleted file mode 100644 index 6b302dc..0000000 --- a/src/lib/xcbutils.cpp +++ /dev/null @@ -1,762 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "xcbutils.h" - -#include -#include -#include -#include - -#include -#include - -XCBUtils::XCBUtils() -{ - m_connect = xcb_connect(nullptr, &m_screenNum); // nullptr表示默认使用环境变量$DISPLAY获取屏幕 - if (xcb_connection_has_error(m_connect)) { - std::cout << "XCBUtils: init xcb_connect error" << std::endl; - return; - } - - if (!xcb_ewmh_init_atoms_replies(&m_ewmh, - xcb_ewmh_init_atoms(m_connect, &m_ewmh), // 初始化Atom - nullptr)) - std::cout << "XCBUtils: init ewmh error" << std::endl; -} - -XCBUtils::~XCBUtils() -{ - if (m_connect) { - xcb_disconnect(m_connect); // 关闭连接并释放 - m_connect = nullptr; - } -} - -XWindow XCBUtils::allocId() -{ - return xcb_generate_id(m_connect); -} - -void XCBUtils::flush() -{ - xcb_flush(m_connect); -} - -void XCBUtils::killClientChecked(XWindow xid) -{ - xcb_kill_client_checked(m_connect, xid); -} - -xcb_get_property_reply_t *XCBUtils::getPropertyValueReply(XWindow xid, XCBAtom property, XCBAtom type) -{ - xcb_get_property_cookie_t cookie = xcb_get_property(m_connect, - 0, - xid, - property, - type, - 0, - MAXLEN); - return xcb_get_property_reply(m_connect, cookie, nullptr); -} - -void *XCBUtils::getPropertyValue(XWindow xid, XCBAtom property, XCBAtom type) -{ - void *value = nullptr; - xcb_get_property_reply_t *reply = getPropertyValueReply(xid, property, type); - if (reply) { - if (xcb_get_property_value_length(reply) > 0) { - value = xcb_get_property_value(reply); - } - free(reply); - } - return value; -} - -std::string XCBUtils::getUTF8PropertyStr(XWindow xid, XCBAtom property) -{ - std::string ret; - xcb_get_property_reply_t *reply = getPropertyValueReply(xid, property, m_ewmh.UTF8_STRING); - if (reply) { - ret = getUTF8StrFromReply(reply); - - free(reply); - } - return ret; -} - -XCBAtom XCBUtils::getAtom(const char *name) -{ - XCBAtom ret = m_atomCache.getVal(name); - if (ret == ATOMNONE) { - xcb_intern_atom_cookie_t cookie = xcb_intern_atom(m_connect, false, strlen(name), name); - xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply (m_connect, - cookie, - nullptr); - if (reply) { - m_atomCache.store(name, reply->atom); - ret = reply->atom; - - free(reply); - } - } - - return ret; -} - -std::string XCBUtils::getAtomName(XCBAtom atom) -{ - std::string ret = m_atomCache.getName(atom); - if (ret.empty()) { - xcb_get_atom_name_cookie_t cookie = xcb_get_atom_name(m_connect, atom); - xcb_get_atom_name_reply_t *reply = xcb_get_atom_name_reply(m_connect, - cookie, - nullptr); - if (reply) { - char *name = xcb_get_atom_name_name(reply); - if (name) { - m_atomCache.store(name, atom); - ret = name; - } - - free(reply); - } - } - - return ret; -} - -Geometry XCBUtils::getWindowGeometry(XWindow xid) -{ - xcb_get_geometry_cookie_t cookie = xcb_get_geometry(m_connect, xcb_drawable_t(xid)); - xcb_get_geometry_reply_t *reply = xcb_get_geometry_reply(m_connect, cookie, nullptr); - if (!reply) { - std::cout << xid << " getWindowGeometry err" << std::endl; - return Geometry(); - } - - Geometry ret; - ret.x = reply->x; - ret.y = reply->y; - ret.width = reply->width; - ret.height = reply->height; - - free(reply); - - const xcb_setup_t *xcbSetup = xcb_get_setup(m_connect); - if (!xcbSetup) - return Geometry(); - - xcb_screen_iterator_t xcbScreenIterator = xcb_setup_roots_iterator(xcbSetup); - xcb_translate_coordinates_reply_t *translateReply = - xcb_translate_coordinates_reply(m_connect, - xcb_translate_coordinates(m_connect, xid, xcbScreenIterator.data->root, 0, 0), - nullptr); - - if (translateReply) { - ret.x = translateReply->dst_x; - ret.y = translateReply->dst_y; - free(translateReply); - } - - XWindow dWin = getDecorativeWindow(xid); - reply = xcb_get_geometry_reply(m_connect, xcb_get_geometry(m_connect, xcb_drawable_t(dWin)), nullptr); - if (!reply) - return ret; - - if (reply->x == ret.x && reply->y == ret.y) { - // 无标题的窗口,比如deepin-editor, dconf-editor等 - WindowFrameExtents windowFrameRect = getWindowFrameExtents(xid); - if (!windowFrameRect.isNull()) { - int x = ret.x + windowFrameRect.Left; - int y = ret.y + windowFrameRect.Top; - int width = ret.width - (windowFrameRect.Left + windowFrameRect.Right); - int height = ret.height - (windowFrameRect.Top + windowFrameRect.Bottom); - ret.x = x; - ret.y = y; - ret.width = width; - ret.height = height; - } - } - - free(reply); - return ret; -} - -XWindow XCBUtils::getDecorativeWindow(XWindow xid) -{ - XWindow winId = xid; - for (int i = 0; i < 10; i++) { - xcb_query_tree_cookie_t cookie = xcb_query_tree(m_connect, winId); - xcb_query_tree_reply_t *reply = xcb_query_tree_reply(m_connect, cookie, nullptr); - if (!reply) - return 0; - - if (reply->root == reply->parent) - return winId; - - winId = reply->parent; - } - - return 0; -} - -WindowFrameExtents XCBUtils::getWindowFrameExtents(XWindow xid) -{ - xcb_atom_t perp = getAtom("_NET_FRAME_EXTENTS"); - xcb_get_property_cookie_t cookie = xcb_get_property(m_connect, false, xid, perp, XCB_ATOM_CARDINAL, 0, 4); - std::shared_ptr reply( - xcb_get_property_reply(m_connect, cookie, nullptr), - [](xcb_get_property_reply_t* ptr) { free(ptr); } - ); - if (!reply || reply->format == 0) { - perp = getAtom("_GTK_FRAME_EXTENTS"); - cookie = xcb_get_property(m_connect, false, xid, perp, XCB_ATOM_CARDINAL, 0, 4); - reply.reset( - xcb_get_property_reply(m_connect, cookie, nullptr), - [](xcb_get_property_reply_t* ptr) { free(ptr); } - ); - if (!reply) - return WindowFrameExtents(); - } - - if (reply->format != 32 || reply->value_len != 4) { - return WindowFrameExtents(); - } - uint32_t *data = static_cast(xcb_get_property_value(reply.get())); - - if (!data) - return WindowFrameExtents(); - - WindowFrameExtents winFrame(data[0], data[1], data[2], data[3]); - return winFrame; -} - -XWindow XCBUtils::getActiveWindow() -{ - XWindow ret; - xcb_get_property_cookie_t cookie = xcb_ewmh_get_active_window(&m_ewmh, m_screenNum); - if (!xcb_ewmh_get_active_window_reply(&m_ewmh, cookie, &ret, nullptr)) { - std::cout << "getActiveWindow error" << std::endl; - } - - return ret; -} - -void XCBUtils::setActiveWindow(XWindow xid) -{ - xcb_ewmh_set_active_window(&m_ewmh, m_screenNum, xid); -} - -void XCBUtils::changeActiveWindow(XWindow newActiveXid) -{ - xcb_ewmh_request_change_active_window(&m_ewmh, m_screenNum, newActiveXid, XCB_EWMH_CLIENT_SOURCE_TYPE_OTHER, XCB_CURRENT_TIME, XCB_WINDOW_NONE); - flush(); -} - -void XCBUtils::restackWindow(XWindow xid) -{ - xcb_ewmh_request_restack_window(&m_ewmh, m_screenNum, xid, 0, XCB_STACK_MODE_ABOVE); -} - -std::list XCBUtils::getClientList() -{ - std::list ret; - xcb_get_property_cookie_t cookie = xcb_ewmh_get_client_list(&m_ewmh, m_screenNum); - xcb_ewmh_get_windows_reply_t reply; - if (xcb_ewmh_get_client_list_reply(&m_ewmh, cookie, &reply, nullptr)) { - for (uint32_t i = 0; i < reply.windows_len; i++) { - ret.push_back(reply.windows[i]); - } - - xcb_ewmh_get_windows_reply_wipe(&reply); - } else { - std::cout << "getClientList error" << std::endl; - } - - return ret; -} - -std::list XCBUtils::getClientListStacking() -{ - std::list ret; - xcb_get_property_cookie_t cookie = xcb_ewmh_get_client_list_stacking(&m_ewmh, m_screenNum); - xcb_ewmh_get_windows_reply_t reply; - if (xcb_ewmh_get_client_list_stacking_reply(&m_ewmh, cookie, &reply, nullptr)) { - for (uint32_t i = 0; i < reply.windows_len; i++) { - ret.push_back(reply.windows[i]); - } - - xcb_ewmh_get_windows_reply_wipe(&reply); - } else { - std::cout << "getClientListStacking error" << std::endl; - } - - return ret; -} - -std::vector XCBUtils::getWMState(XWindow xid) -{ - std::vector ret; - xcb_get_property_cookie_t cookie = xcb_ewmh_get_wm_state(&m_ewmh, xid); - xcb_ewmh_get_atoms_reply_t reply; // a list of Atom - if (xcb_ewmh_get_wm_state_reply(&m_ewmh, cookie, &reply, nullptr)) { - for (uint32_t i = 0; i < reply.atoms_len; i++) { - ret.push_back(reply.atoms[i]); - } - - xcb_ewmh_get_atoms_reply_wipe(&reply); - } else { - std::cout << xid << " getWMState error" << std::endl; - } - - return ret; -} - -std::vector XCBUtils::getWMWindoType(XWindow xid) -{ - std::vector ret; - xcb_get_property_cookie_t cookie = xcb_ewmh_get_wm_window_type(&m_ewmh, xid); - xcb_ewmh_get_atoms_reply_t reply; // a list of Atom - if (xcb_ewmh_get_wm_window_type_reply(&m_ewmh, cookie, &reply, nullptr)) { - for (uint32_t i = 0; i < reply.atoms_len; i++) { - ret.push_back(reply.atoms[i]); - } - - xcb_ewmh_get_atoms_reply_wipe(&reply); - } else { - std::cout << xid << " getWMWindoType error" << std::endl; - } - - return ret; -} - -std::vector XCBUtils::getWMAllowedActions(XWindow xid) -{ - std::vector ret; - xcb_get_property_cookie_t cookie = xcb_ewmh_get_wm_allowed_actions(&m_ewmh, xid); - xcb_ewmh_get_atoms_reply_t reply; // a list of Atoms - if (xcb_ewmh_get_wm_allowed_actions_reply(&m_ewmh, cookie, &reply, nullptr)) { - for (uint32_t i = 0; i < reply.atoms_len; i++) { - ret.push_back(reply.atoms[i]); - } - - xcb_ewmh_get_atoms_reply_wipe(&reply); - } else { - std::cout << xid << " getWMAllowedActions error" << std::endl; - } - - return ret; -} - -void XCBUtils::setWMAllowedActions(XWindow xid, std::vector actions) -{ - XCBAtom list[MAXALLOWEDACTIONLEN] {0}; - for (size_t i = 0; i < actions.size(); i++) { - list[i] = actions[i]; - } - - xcb_ewmh_set_wm_allowed_actions(&m_ewmh, xid, actions.size(), list); -} - -std::string XCBUtils::getWMName(XWindow xid) -{ - std::string ret; - xcb_get_property_cookie_t cookie = xcb_ewmh_get_wm_name(&m_ewmh, xid); - xcb_ewmh_get_utf8_strings_reply_t reply; - if (xcb_ewmh_get_wm_name_reply(&m_ewmh, cookie, &reply, nullptr)) { - ret.assign(reply.strings, reply.strings_len); - // 释放utf8_strings_reply分配的内存 - xcb_ewmh_get_utf8_strings_reply_wipe(&reply); - } else { - std::cout << xid << " getWMName error" << std::endl; - } - - return ret; -} - -uint32_t XCBUtils::getWMPid(XWindow xid) -{ - // NOTE(black_desk): code copy from https://gitlab.gnome.org/GNOME/metacity/-/merge_requests/13/diffs - - XResClientIdSpec spec = { - .client = xid, - .mask = XRES_CLIENT_ID_PID_MASK, - }; - - std::shared_ptr dpy = { - XOpenDisplay(nullptr), - [](Display *p){ XCloseDisplay(p); }, - }; - - long num_ids; - XResClientIdValue *client_ids; - XResQueryClientIds(dpy.get(), - 1, - &spec, - &num_ids, - &client_ids); - - pid_t pid = -1; - for (long i = 0; i < num_ids; i++) { - if (client_ids[i].spec.mask == XRES_CLIENT_ID_PID_MASK) { - pid = XResGetClientPid(&client_ids[i]); - break; - } - } - - XResClientIdsDestroy(num_ids, client_ids); - return pid; -} - -std::string XCBUtils::getWMIconName(XWindow xid) -{ - std::string ret; - xcb_get_property_cookie_t cookie = xcb_ewmh_get_wm_icon_name(&m_ewmh, xid); - xcb_ewmh_get_utf8_strings_reply_t reply; - if (!xcb_ewmh_get_wm_icon_name_reply(&m_ewmh, cookie, &reply, nullptr)) { - std::cout << xid << " getWMIconName error" << std::endl; - } - - ret.assign(reply.strings); - - return ret; -} - -WMIcon XCBUtils::getWMIcon(XWindow xid) -{ - WMIcon wmIcon{}; - xcb_get_property_cookie_t cookie = xcb_ewmh_get_wm_icon(&m_ewmh, xid); - xcb_ewmh_get_wm_icon_reply_t reply; - xcb_generic_error_t *error; - - auto ret = xcb_ewmh_get_wm_icon_reply(&m_ewmh, cookie, &reply, &error); - - if (error) { - std::cout << "failed to get wm icon" << error->error_code; - std::free(error); - return wmIcon; - } - - if (ret) { - auto fcn = [](xcb_ewmh_wm_icon_iterator_t it) { - // 根据宽高获取每个位置的数据,每行前有两个位置offset - const auto size = 2 + it.width * it.height; - std::vector ret(size); - // data数据是按行从左至右,从上至下排列 - uint32_t *data = it.data; - if (!data) { - return ret; - } - - std::copy_n(data, size, ret.begin()); - return ret; - }; - - // 获取icon中size最大的图标 - xcb_ewmh_wm_icon_iterator_t iter = xcb_ewmh_get_wm_icon_iterator(&reply); - xcb_ewmh_wm_icon_iterator_t wmIconIt{0, 0, nullptr}; - for (; iter.rem; xcb_ewmh_get_wm_icon_next(&iter)) { - const int size = iter.width * iter.height; - if (size > 0 && size > wmIconIt.width * wmIconIt.height) { - wmIconIt = iter; - } - } - - wmIcon = WMIcon{wmIconIt.width, wmIconIt.height, fcn(wmIconIt)}; - - xcb_ewmh_get_wm_icon_reply_wipe(&reply); // clear - } - - return wmIcon; -} - -XWindow XCBUtils::getWMClientLeader(XWindow xid) -{ - XWindow ret; - XCBAtom atom = getAtom("WM_CLIENT_LEADER"); - void *value = getPropertyValue(xid, atom, XCB_ATOM_INTEGER); - std::cout << "getWMClientLeader:" << (char*)value << std::endl; - - return ret; -} - -void XCBUtils::requestCloseWindow(XWindow xid, uint32_t timestamp) -{ - xcb_ewmh_request_close_window(&m_ewmh, m_screenNum, xid, timestamp, XCB_EWMH_CLIENT_SOURCE_TYPE_OTHER); -} - -uint32_t XCBUtils::getWMDesktop(XWindow xid) -{ - uint32_t ret; - xcb_get_property_cookie_t cookie = xcb_ewmh_get_wm_desktop(&m_ewmh, xid); - if (!xcb_ewmh_get_wm_desktop_reply(&m_ewmh, cookie, &ret, nullptr)) { - std::cout << xid << " getWMDesktop error" << std::endl; - } - - return ret; -} - -void XCBUtils::setWMDesktop(XWindow xid, uint32_t desktop) -{ - xcb_ewmh_set_wm_desktop(&m_ewmh, xid, desktop); -} - -void XCBUtils::setCurrentWMDesktop(uint32_t desktop) -{ - xcb_ewmh_set_current_desktop(&m_ewmh, m_screenNum, desktop); -} - -void XCBUtils::changeCurrentDesktop(uint32_t newDesktop, uint32_t timestamp) -{ - xcb_ewmh_request_change_current_desktop(&m_ewmh, m_screenNum, newDesktop, timestamp); -} - -uint32_t XCBUtils::getCurrentWMDesktop() -{ - uint32_t ret; - xcb_get_property_cookie_t cookie = xcb_ewmh_get_current_desktop(&m_ewmh, m_screenNum); - if (!xcb_ewmh_get_current_desktop_reply(&m_ewmh, cookie, &ret, nullptr)) { - std::cout << "getCurrentWMDesktop error" << std::endl; - } - - return ret; -} - -bool XCBUtils::isGoodWindow(XWindow xid) -{ - bool ret = false; - xcb_get_geometry_cookie_t cookie = xcb_get_geometry(m_connect, xid); - xcb_generic_error_t **errStore = nullptr; - xcb_get_geometry_reply_t *reply = xcb_get_geometry_reply(m_connect, cookie, errStore); - if (reply) { - // 正常获取窗口geometry则判定为good - if (!errStore) { - ret = true; - } else { - free(errStore); - } - - free(reply); - } - return ret; -} - -// TODO XCB下无_MOTIF_WM_HINTS属性 -MotifWMHints XCBUtils::getWindowMotifWMHints(XWindow xid) -{ - XCBAtom atomWmHints = getAtom("_MOTIF_WM_HINTS"); - xcb_get_property_cookie_t cookie = xcb_get_property(m_connect, false, xid, atomWmHints, atomWmHints, 0, 5); - xcb_get_property_reply_t *reply = xcb_get_property_reply(m_connect, cookie, nullptr); - if (!reply || reply->format != 32 || reply->value_len != 5) - return MotifWMHints{0, 0, 0, 0, 0}; - - uint32_t *data = static_cast(xcb_get_property_value(reply)); - MotifWMHints ret; - ret.flags = data[0]; - ret.functions = data[1]; - ret.decorations = data[2]; - ret.inputMode = data[3]; - ret.status = data[4]; - return ret; -} - -bool XCBUtils::hasXEmbedInfo(XWindow xid) -{ - //XCBAtom atom = getAtom("_XEMBED_INFO"); - - return false; -} - -XWindow XCBUtils::getWMTransientFor(XWindow xid) -{ - XWindow ret; - xcb_get_property_cookie_t cookie = xcb_icccm_get_wm_transient_for(m_connect, xid); - if (!xcb_icccm_get_wm_transient_for_reply(m_connect, cookie, &ret, nullptr)) { - std::cout << xid << " getWMTransientFor error" << std::endl; - } - - return ret; -} - -uint32_t XCBUtils::getWMUserTime(XWindow xid) -{ - uint32_t ret; - xcb_get_property_cookie_t cookie = xcb_ewmh_get_wm_user_time(&m_ewmh, xid); - if (!xcb_ewmh_get_wm_user_time_reply(&m_ewmh, cookie, &ret, nullptr)) { - std::cout << xid << " getWMUserTime error" << std::endl; - } - - return ret; -} - -int XCBUtils::getWMUserTimeWindow(XWindow xid) -{ - XCBAtom ret; - xcb_get_property_cookie_t cookie = xcb_ewmh_get_wm_user_time_window(&m_ewmh, xid); - if (!xcb_ewmh_get_wm_user_time_window_reply(&m_ewmh, cookie, &ret, nullptr)) { - std::cout << xid << " getWMUserTimeWindow error" << std::endl; - } - - return ret; -} - -WMClass XCBUtils::getWMClass(XWindow xid) -{ - WMClass ret; - xcb_get_property_cookie_t cookie = xcb_icccm_get_wm_class(m_connect, xid); - xcb_icccm_get_wm_class_reply_t reply; - reply.instance_name = nullptr; - reply.class_name = nullptr; - xcb_icccm_get_wm_class_reply(m_connect, cookie, &reply, nullptr); // 返回值为0不一定表示失败, 故不做返回值判断 - if (reply.class_name) - ret.className.assign(reply.class_name); - - if (reply.instance_name) - ret.instanceName.assign(reply.instance_name); - - if (reply.class_name || reply.instance_name) { - xcb_icccm_get_wm_class_reply_wipe(&reply); - } - - return ret; -} - -void XCBUtils::minimizeWindow(XWindow xid) -{ - uint32_t data[2]; - data[0] = XCB_ICCCM_WM_STATE_ICONIC; - data[1] = XCB_NONE; - xcb_ewmh_send_client_message(m_connect, xid, getRootWindow(),getAtom("WM_CHANGE_STATE"), 2, data); - flush(); -} - -void XCBUtils::maxmizeWindow(XWindow xid) -{ - xcb_ewmh_request_change_wm_state(&m_ewmh - , m_screenNum - , xid - , XCB_EWMH_WM_STATE_ADD - , getAtom("_NET_WM_STATE_MAXIMIZED_VERT") - , getAtom("_NET_WM_STATE_MAXIMIZED_HORZ") - , XCB_EWMH_CLIENT_SOURCE_TYPE_OTHER); -} - -// TODO -std::vector XCBUtils::getWMCommand(XWindow xid) -{ - std::vector ret; - xcb_get_property_reply_t *reply = getPropertyValueReply(xid, XCB_ATOM_WM_COMMAND, m_ewmh.UTF8_STRING); - if (reply) { - ret = getUTF8StrsFromReply(reply); - free(reply); - } - - return ret; -} - -std::string XCBUtils::getUTF8StrFromReply(xcb_get_property_reply_t *reply) -{ - std::string ret; - if (!reply || reply->format != 8) { - return ret; - } - - char data[12] = {0}; - for (uint32_t i=0; i < reply->value_len; i++) { - data[i] = char(reply->pad0[i]); - } - ret.assign(data); - return ret; -} - -std::vector XCBUtils::getUTF8StrsFromReply(xcb_get_property_reply_t *reply) -{ - std::vector ret; - if (!reply) { - return ret; - } - - if (reply->format != 8) { - return ret; - } - - - // 字符串拆分 - uint32_t start = 0; - for (uint32_t i=0; i < reply->value_len; i++) { - if (reply->pad0[i] == 0) { - char data[12] = {0}; - int count = 0; - for (uint32_t j=start; j < i; j++) - data[count++] = char(reply->pad0[j]); - - data[count] = 0; - ret.push_back(data); - } - } - - return ret; -} - -XWindow XCBUtils::getRootWindow() -{ - XWindow rootWindow = 0; - /* Get the first screen */ - xcb_screen_t *screen = xcb_setup_roots_iterator(xcb_get_setup(m_connect)).data; - if (screen) { - rootWindow = screen->root; - } - - std::cout << "getRootWinodw: " << rootWindow << std::endl; - return rootWindow; -} - -void XCBUtils::registerEvents(XWindow xid, uint32_t eventMask) -{ - uint32_t value[1] = {eventMask}; - xcb_void_cookie_t cookie = xcb_change_window_attributes_checked(m_connect, - xid, - XCB_CW_EVENT_MASK, - &value); - flush(); - - xcb_generic_error_t *error = xcb_request_check(m_connect, cookie); - if (error != nullptr) { - std::cout << "window " << xid << "registerEvents error" << std::endl; - } -} - - -AtomCache::AtomCache() -{ -} - -XCBAtom AtomCache::getVal(std::string name) -{ - XCBAtom atom = ATOMNONE; - auto search = m_atoms.find(name); - if (search != m_atoms.end()) { - atom = search->second; - } - - return atom; -} - -std::string AtomCache::getName(XCBAtom atom) -{ - std::string ret; - auto search = m_atomNames.find(atom); - if (search != m_atomNames.end()) { - ret = search->second; - } - - return ret; -} - -void AtomCache::store(std::string name, XCBAtom value) -{ - m_atoms[name] = value; - m_atomNames[value] = name; -} diff --git a/src/lib/xcbutils.h b/src/lib/xcbutils.h deleted file mode 100644 index f069dc3..0000000 --- a/src/lib/xcbutils.h +++ /dev/null @@ -1,276 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef XCBUTILS_H -#define XCBUTILS_H - -#include -#include -#include - -#include -#include -#include -#include - -#define MAXLEN 0xffff -#define MAXALLOWEDACTIONLEN 256 -#define ATOMNONE 0 - -typedef xcb_window_t XWindow ; -typedef xcb_atom_t XCBAtom; -typedef xcb_destroy_notify_event_t DestroyEvent; -typedef xcb_map_notify_event_t MapEvent; -typedef xcb_configure_notify_event_t ConfigureEvent; -typedef xcb_property_notify_event_t PropertyEvent; -typedef xcb_event_mask_t EventMask; - -typedef struct { - std::string instanceName; - std::string className; -} WMClass; - -typedef struct { - int16_t x, y; - uint16_t width, height; -} Geometry; - -typedef struct { - uint32_t flags; - uint32_t functions; - uint32_t decorations; - int32_t inputMode; - uint32_t status; -} MotifWMHints; - -typedef struct { - uint32_t width; /** Icon width */ - uint32_t height; /** Icon height */ - std::vector data; /** Rows, left to right and top to bottom of the CARDINAL ARGB */ -} WMIcon; - -typedef struct WindowFrameExtents { - uint32_t Left; - uint32_t Right; - uint32_t Top; - uint32_t Bottom; - WindowFrameExtents(int left = 0, int right = 0, int top = 0, int bottom = 0): Left(left), Right(right), Top(top), Bottom(bottom) {} - bool isNull() { return Left == 0 && Right == 0 && Top == 0 && Bottom == 0;} -} WindowFrameExtents; - -// 缓存atom,减少X访问 TODO 加读写锁 -class AtomCache { -public: - AtomCache(); - - XCBAtom getVal(std::string name); - std::string getName(XCBAtom atom); - void store(std::string name, XCBAtom value); - -public: - std::map m_atoms; - std::map m_atomNames; -}; - -// XCB接口封装, 参考getCurrentWMDesktop -class XCBUtils -{ - XCBUtils(); - XCBUtils(const XCBUtils &other); - XCBUtils & operator= (const XCBUtils &other); - ~XCBUtils(); - -public: - static XCBUtils *instance() { - static XCBUtils instance; - return &instance; - } - - /************************* xcb method ***************************/ - // 分配XID - XWindow allocId(); - - // 刷新 - void flush(); - - /************************* xpropto method ***************************/ - // 杀掉进程 - void killClientChecked(XWindow xid); - - // 获取属性reply, 返回值必须free - xcb_get_property_reply_t *getPropertyValueReply(XWindow xid, XCBAtom property, XCBAtom type = XCB_ATOM_ATOM); - - // 获取属性 - void *getPropertyValue(XWindow xid, XCBAtom property, XCBAtom type = XCB_ATOM_ATOM); - - // 获取字符串属性 - std::string getUTF8PropertyStr(XWindow xid, XCBAtom property); - - // 获取名称对应的Atom - XCBAtom getAtom(const char *name); - - // 获取Atom对应的名称 - std::string getAtomName(XCBAtom atom); - - // 获取窗口矩形 - Geometry getWindowGeometry(XWindow xid); - - // 判断当前窗口是否正常 - bool isGoodWindow(XWindow xid); - - // 获取窗口 - MotifWMHints getWindowMotifWMHints(XWindow xid); - - bool hasXEmbedInfo(XWindow xid); - - /************************* ewmh method ***************************/ - - // 获取活动窗口 _NET_ACTIVE_WINDOW - XWindow getActiveWindow(); - - // 设置活动窗口 _NET_ACTIVE_WINDOW 属性 - void setActiveWindow(XWindow xid); - - // 改变活动窗口 - void changeActiveWindow(XWindow newActiveXid); - - // 重新排列窗口 - void restackWindow(XWindow xid); - - // 获取窗口列表 _NET_CLIENT_LIST - std::list getClientList(); - - // 获取窗口列表 _NET_CLIENT_LIST_STACKING - std::list getClientListStacking(); - - // 获取窗口状态 _NET_WM_STATE - /* - _NET_WM_STATE_MODAL, ATOM - _NET_WM_STATE_STICKY, ATOM - _NET_WM_STATE_MAXIMIZED_VERT, ATOM - _NET_WM_STATE_MAXIMIZED_HORZ, ATOM - _NET_WM_STATE_SHADED, ATOM - _NET_WM_STATE_SKIP_TASKBAR, ATOM - _NET_WM_STATE_SKIP_PAGER, ATOM - _NET_WM_STATE_HIDDEN, ATOM - _NET_WM_STATE_FULLSCREEN, ATOM - _NET_WM_STATE_ABOVE, ATOM - _NET_WM_STATE_BELOW, ATOM - _NET_WM_STATE_DEMANDS_ATTENTION, ATOM - */ - std::vector getWMState(XWindow xid); - - // 获取窗口类型 _NET_WM_WINDOW_TYPE - // Rationale: This hint is intended to replace the MOTIF hints. - // One of the objections to the MOTIF hints is that they are a purely visual description of the window decoration. - // By describing the function of the window, the Window Manager can apply consistent decoration and behavior to windows of the same type. - // Possible examples of behavior include keeping dock/panels on top or allowing pinnable menus / toolbars to only be hidden - // when another window has focus - /* - _NET_WM_WINDOW_TYPE_DESKTOP, ATOM - _NET_WM_WINDOW_TYPE_DOCK, ATOM - _NET_WM_WINDOW_TYPE_TOOLBAR, ATOM - _NET_WM_WINDOW_TYPE_MENU, ATOM - _NET_WM_WINDOW_TYPE_UTILITY, ATOM - _NET_WM_WINDOW_TYPE_SPLASH, ATOM - _NET_WM_WINDOW_TYPE_DIALOG, ATOM - _NET_WM_WINDOW_TYPE_DROPDOWN_MENU, ATOM - _NET_WM_WINDOW_TYPE_POPUP_MENU, ATOM - _NET_WM_WINDOW_TYPE_TOOLTIP, ATOM - _NET_WM_WINDOW_TYPE_NOTIFICATION, ATOM - _NET_WM_WINDOW_TYPE_COMBO, ATOM - _NET_WM_WINDOW_TYPE_DND, ATOM - _NET_WM_WINDOW_TYPE_NORMAL, ATOM - * */ - std::vector getWMWindoType(XWindow xid); - - // 获取窗口许可动作 _NET_WM_ALLOWED_ACTIONS - std::vector getWMAllowedActions(XWindow xid); - - // 设置窗口许可动作 - void setWMAllowedActions(XWindow xid, std::vector actions); - - // 获取窗口名称 _NET_WM_NAME - std::string getWMName(XWindow xid); - - // 获取窗口所属进程 _NET_WM_PID - uint32_t getWMPid(XWindow xid); - - // 获取窗口图标 _NET_WM_ICON_NAME - std::string getWMIconName(XWindow xid); - - // 获取窗口图标信息 _NET_WM_ICON - WMIcon getWMIcon(XWindow xid); - - // WM_CLIENT_LEADER - XWindow getWMClientLeader(XWindow xid); - - // 关闭窗口 _NET_CLOSE_WINDOW - void requestCloseWindow(XWindow xid, uint32_t timestamp); - - // 获取窗口对应桌面 _NET_WM_DESKTOP - uint32_t getWMDesktop(XWindow xid); - - // 设置窗口当前桌面 - void setWMDesktop(XWindow xid, uint32_t desktop); - - // 设置当前桌面属性 - void setCurrentWMDesktop(uint32_t desktop); - - // 请求改变当前桌面 - void changeCurrentDesktop(uint32_t newDesktop, uint32_t timestamp); - - // 获取当前桌面 _NET_CURRENT_DESKTOP - uint32_t getCurrentWMDesktop(); - - - /************************* icccm method ***************************/ - // The WM_TRANSIENT_FOR hint of the ICCCM allows clients to specify that a toplevel window may be closed before the client finishes. - // A typical example of a transient window is a dialog. - // Some dialogs can be open for a long time, while the user continues to work in the main window. - // Other dialogs have to be closed before the user can continue to work in the main window - XWindow getWMTransientFor(XWindow xid); - - uint32_t getWMUserTime(XWindow xid); - - int getWMUserTimeWindow(XWindow xid); - - // 获取窗口类型 - WMClass getWMClass(XWindow xid); - - // 最小化窗口 - void minimizeWindow(XWindow xid); - - // 最大化窗口 - void maxmizeWindow(XWindow xid); - - /************************* other method ***************************/ - // 获取窗口command - std::vector getWMCommand(XWindow xid); - - // 解析属性为UTF8格式字符串 - std::string getUTF8StrFromReply(xcb_get_property_reply_t *reply); - - // 解析属性为UTF8格式字符串字符数组 - std::vector getUTF8StrsFromReply(xcb_get_property_reply_t *reply); - - // 获取根窗口 - XWindow getRootWindow(); - - // 注册事件 - void registerEvents(XWindow xid, uint32_t eventMask); - -private: - XWindow getDecorativeWindow(XWindow xid); - WindowFrameExtents getWindowFrameExtents(XWindow xid); - -private: - xcb_connection_t *m_connect; - int m_screenNum; - - xcb_ewmh_connection_t m_ewmh; - AtomCache m_atomCache; // 和ewmh中Atom类型存在重复部分,扩张了自定义类型 -}; - -#endif // XCBUTILS_H diff --git a/src/loader/CMakeLists.txt b/src/loader/CMakeLists.txt deleted file mode 100644 index a96a9d3..0000000 --- a/src/loader/CMakeLists.txt +++ /dev/null @@ -1,42 +0,0 @@ -set(BIN_NAME dde-application-loader) - -pkg_check_modules(LIBCAP REQUIRED IMPORTED_TARGET libcap) - -set(SRCS - ./main.cpp - ../modules/tools/desktop_deconstruction.hpp - ../modules/socket/client.h - ../modules/socket/client.cpp - ../modules/methods/task.hpp - ../modules/methods/basic.h - ../modules/methods/instance.hpp - ../modules/methods/process_status.hpp - ../modules/methods/registe.hpp - ../modules/methods/use_mime_app_info.h - ../modules/util/common.cpp - ../modules/util/common.h - ../modules/util/filesystem.cpp - ../modules/util/filesystem.h - ../modules/util/json.h - ../modules/util/logger.cpp - ../modules/util/logger.h - ../modules/util/macro.h - ../modules/util/oci_runtime.h - ../modules/util/platform.cpp - ../modules/util/platform.h - ../modules/util/semaphore.cpp - ../modules/util/semaphore.h - ../modules/util/util.h - ../modules/util/debug/debug.h - ../modules/util/debug/debug.cpp -) - -add_executable(${BIN_NAME} ${SRCS}) - -target_link_libraries(${BIN_NAME} - pthread - PkgConfig::LIBCAP - stdc++fs - Qt5::Core -) -install(TARGETS ${BIN_NAME} DESTINATION ${CMAKE_INSTALL_BINDIR}) diff --git a/src/loader/main.cpp b/src/loader/main.cpp deleted file mode 100644 index ee7240c..0000000 --- a/src/loader/main.cpp +++ /dev/null @@ -1,356 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include - -#include "../modules/methods/basic.h" -#include "../modules/methods/instance.hpp" -#include "../modules/methods/process_status.hpp" -#include "../modules/methods/registe.hpp" -#include "../modules/methods/task.hpp" -#include "../modules/socket/client.h" -#include "../modules/tools/desktop_deconstruction.hpp" -#include "../modules/util/oci_runtime.h" - -extern char** environ; - -// from linglong -#define LINGLONG 118 -#define LL_VAL(str) #str -#define LL_TOSTRING(str) LL_VAL(str) - -struct App { - std::string type; - std::string prefix; - std::string id; -}; - -static App parseApp(const QString& app) -{ - QStringList values = app.split('/', QString::SkipEmptyParts); - qInfo() << "app:" << app << ", values size:" << values.size(); - App result; - if (values.size() == 3) { - result.prefix = values.at(0).toStdString(); - result.type = values.at(1).toStdString(); - result.id = values.at(2).toStdString(); - } - return result; -} - -void quit() {} - -void sig_handler(int num) -{ - int status; - pid_t pid; - /* 由于该信号不能叠加,所以可能同时有多个子进程已经结束 所以循环wait */ - while ((pid = waitpid(0, &status, WNOHANG)) > 0) { - if (WIFEXITED(status)) // 判断子进程的退出状态 是否是正常退出 - printf("-----child %d exit with %d\n", pid, WEXITSTATUS(status)); - else if (WIFSIGNALED(status)) // 判断子进程是否是 通过信号退出 - printf("child %d killed by the %dth signal\n", pid, WTERMSIG(status)); - } -} - -// TODO: startManager合并流程? -int childFreedesktop(Methods::Task* task, std::string path) -{ - prctl(PR_SET_PDEATHSIG, SIGKILL); - prctl(PR_SET_PDEATHSIG, SIGTERM); - prctl(PR_SET_PDEATHSIG, SIGHUP); - - DesktopDeconstruction dd(path); - dd.beginGroup("Desktop Entry"); - std::cout << dd.value("Exec") << std::endl; - - QStringList envs; - for (auto it = task->environments.begin(); it != task->environments.end(); ++it) { - envs.append(it.key() + "=" + it.value()); - } - - QStringList exeArgs; - exeArgs << QString::fromStdString(dd.value("Exec")).split(" "); - - QString exec = exeArgs[0]; - exeArgs.removeAt(0); - - pid_t pid = fork(); - if (pid == -1) { - perror("fork()"); - return -1; - } - - if (pid == 0) { - // 子进程 - QProcess process; - qInfo() << "exec:" << exec; - qInfo() << "exeArgs:" << exeArgs; - process.setWorkingDirectory(QDir::homePath()); - process.setEnvironment(envs); - process.start(exec, exeArgs); - process.waitForFinished(-1); - process.close(); - qInfo() << "process finish"; - exit(0); - } - return pid; -} - -int childLinglong(Methods::Task* task, std::string path) -{ - prctl(PR_SET_PDEATHSIG, SIGKILL); - prctl(PR_SET_PDEATHSIG, SIGTERM); - prctl(PR_SET_PDEATHSIG, SIGHUP); - - DesktopDeconstruction dd(path); - dd.beginGroup("Desktop Entry"); - std::cout << dd.value("Exec") << std::endl; - - linglong::Runtime runtime; - linglong::Annotations annotations; - linglong::Root root; - linglong::Mount mount; - annotations.container_root_path = "/run/user/1000/DAM/" + task->id; - annotations.native = { { mount } }; - root.path = annotations.container_root_path + "/root"; - mount.destination = "/"; - mount.source = "/"; - mount.type = "bind"; - mount.data = { "ro" }; - runtime.hostname = "hostname"; - runtime.process.cwd = "/"; - std::filesystem::path container_root_path(annotations.container_root_path.toStdString()); - if (!std::filesystem::exists(container_root_path)) { - if (!std::filesystem::create_directories(container_root_path)) { - std::cout << "[Loader] [Warning] cannot create container root path." << std::endl; - return -1; - } - } - - for (auto it = task->environments.begin(); it != task->environments.end(); ++it) { - runtime.process.env.append(it.key() + "=" + it.value()); - } - - std::istringstream stream(dd.value("Exec")); - std::string s; - while (getline(stream, s, ' ')) { - if (s.empty()) { - continue; - } - - // TODO: %U - if (s.length() == 2 && s[0] == '%') { - continue; - } - runtime.process.args.push_back(QString::fromStdString(s)); - } - - // 应用运行信息 - QByteArray runtimeArray; - toJson(runtimeArray, runtime); - qWarning() << "runtimeArray: " << runtimeArray; - - // 使用Pipe进行父子进程通信 - int pipeEnds[2]; - if (pipe(pipeEnds) != 0) { - return EXIT_FAILURE; - } - - pid_t pid = fork(); - if (pid == -1) { - perror("fork()"); - return -1; - } - - if (pid == 0) { - // 子进程 - (void) close(pipeEnds[1]); - - // 重定向到LINGLONG - if (dup2(pipeEnds[0], LINGLONG) == -1) { - return EXIT_FAILURE; - } - (void) close(pipeEnds[0]); - - // 初始化运行命令和参数,并执行 - char const* const args[] = { "/usr/bin/ll-box", LL_TOSTRING(LINGLONG), nullptr }; - int ret = execvp(args[0], (char**) args); - std::cout << "[Loader] [Fork] " << ret << std::endl; - //std::filesystem::remove(container_root_path); - exit(ret); - } else { - // 父进程 - QByteArray runtimeArray; - linglong::toJson(runtimeArray, runtime); - const std::string data = runtimeArray.data(); - close(pipeEnds[0]); - - // 将运行时信息通过pipe传递给子进程 - write(pipeEnds[1], data.c_str(), data.size()); - close(pipeEnds[1]); - } - - return pid; -} - -int childAndroid(Methods::Task* task, std::string path) -{ - // TODO - return 0; -} - -#define DAM_TASK_HASH "DAM_TASK_HASH" -#define DAM_TASK_TYPE "DAM_TASK_TYPE" - -int main(int argc, char* argv[]) -{ - const char* dam_task_hash = getenv(DAM_TASK_HASH); - if (!dam_task_hash) { - return -1; - } - const char* dam_task_type = getenv(DAM_TASK_TYPE); - if (!dam_task_type) { - return -2; - } - - char socketPath[50]; - sprintf(socketPath, "/run/user/%d/dde-application-manager.socket", getuid()); - - // register client and run quitConnect - Socket::Client client; - client.connect(socketPath); - - // 初始化应用注册信息 - QByteArray registerArray; - Methods::Registe registe; - registe.id = dam_task_type; - registe.hash = dam_task_hash; - Methods::toJson(registerArray, registe); - - // 向AM注册应用信息进行校验 - Methods::Registe registe_result; - registe_result.state = false; - QByteArray result = client.get(registerArray); - if (!result.isEmpty()) { - Methods::fromJson(result, registe_result); - } - if (!registe_result.state) { - return -3; - } - - // 初始化应用实例信息 - Methods::Instance instance; - instance.hash = registe_result.hash; - QByteArray instanceArray; - Methods::toJson(instanceArray, instance); - - // 向AM注册应用实例信息进行校验 - result = client.get(instanceArray); - Methods::Task task; - Methods::fromJson(result, task); // fromJson TODO 数据解析异常 - qInfo() << "[Task] " << result; - - // 校验task内容 - App app = parseApp(task.runId); - qInfo() << "[App] " - << "prefix:" << QString::fromStdString(app.prefix) - << "type:" << QString::fromStdString(app.type) - << "id:" << QString::fromStdString(app.id); - if (task.id.isEmpty() || app.id.empty() || app.type.empty() || app.prefix.empty()) { - std::cout << "get task error" << std::endl; - return -4; - } - if (app.prefix != "freedesktop" - && app.prefix != "linglong" - && app.prefix != "android") { - qWarning() << "error app prefix :" << QString::fromStdString(app.type); - return -1; - } - - pthread_attr_t attr; - size_t stack_size; - pthread_attr_init(&attr); - pthread_attr_getstacksize(&attr, &stack_size); - pthread_attr_destroy(&attr); - - /* 先将SIGCHLD信号阻塞 保证在子进程结束前设置父进程的捕捉函数 */ - sigset_t nmask, omask; - // sigemptyset(&nmask); - // sigaddset(&nmask, SIGCHLD); - // sigprocmask(SIG_BLOCK, &nmask, &omask); - - //char* stack = (char*) malloc(stack_size); - //pid_t pid = clone(child, stack + stack_size, CLONE_NEWPID | SIGCHLD, static_cast(&task)); - pid_t pid = -1; - if (app.prefix == "freedesktop") { - pid = childFreedesktop(&task, task.filePath.toStdString()); - } else if (app.prefix == "linglong") { - pid = childLinglong(&task, task.filePath.toStdString()); - } else if (app.prefix == "android") { - pid = childAndroid(&task, task.filePath.toStdString()); - } else { - qWarning() << "error app prefix:" << QString::fromStdString(app.prefix); - } - - if(pid != -1) { - Methods::ProcessStatus processSuccess; - processSuccess.code = 0; - processSuccess.id = task.id; - processSuccess.type = "success"; - processSuccess.data = QString::number(pid); - QByteArray processArray; - Methods::toJson(processArray, processSuccess); - client.send(processArray); - } - - // TODO: 启动线程,创建新的连接去接受服务器的消息 - - // TODO:信号处理有问题 - /* 设置捕捉函数 */ - // struct sigaction sig; - // sig.sa_handler = sig_handler; - // sigemptyset(&sig.sa_mask); - // sig.sa_flags = 0; - // sigaction(SIGCHLD, &sig, NULL); - /* 然后再unblock */ - // sigdelset(&omask, SIGCHLD); - // sigprocmask(SIG_SETMASK, &omask, NULL); - - int exitCode; - waitpid(pid, &exitCode, 0); - qInfo() << "app exitCode:" << exitCode; - - Methods::ProcessStatus quit; - quit.code = exitCode; - quit.id = task.id; - quit.type = "quit"; - QByteArray quitArray; - Methods::toJson(quitArray, quit); - client.send(quitArray); - - return exitCode; -} diff --git a/src/modules/apps/alrecorder.cpp b/src/modules/apps/alrecorder.cpp deleted file mode 100644 index ffa9769..0000000 --- a/src/modules/apps/alrecorder.cpp +++ /dev/null @@ -1,247 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "alrecorder.h" -#include "dfwatcher.h" - -#include -#include -#include -#include -#include - -const QString userAppsCfgDir = QDir::homePath() + "/.config/deepin/dde-daemon/apps/"; - -AlRecorder::AlRecorder(DFWatcher *_watcher, QObject *parent) - : QObject (parent) - , watcher(_watcher) - , mutex(QMutex(QMutex::NonRecursive)) -{ - connect(watcher, &DFWatcher::Event, this, &AlRecorder::onDFChanged, Qt::QueuedConnection); - Q_EMIT serviceRestarted(); -} - -AlRecorder::~AlRecorder() -{ -} - -/** - * @brief AlRecorder::getNew 获取未启动应用列表 - * @return - */ -QMap AlRecorder::getNew() -{ - QMap ret; - QMutexLocker locker(&mutex); - for (auto is = subRecoders.begin(); is != subRecoders.end(); is++) { - QStringList apps; - for (auto il = is.value().launchedMap.begin(); il != is.value().launchedMap.end(); il++) { - if (!il.value()) // 未启动应用 - apps.push_back(il.key()); - } - - if (apps.size() > 0) - ret[is.key()] = apps; - } - - return ret; -} - -/** - * @brief AlRecorder::markLaunched 标记应用已启动状态 - * @param filePath - */ -void AlRecorder::markLaunched(const QString &filePath) -{ - if (!filePath.endsWith(".desktop")) - return; - - QFileInfo info; - QMutexLocker locker(&mutex); - for (auto sri = subRecoders.begin(); sri != subRecoders.end(); sri++) { - if (!filePath.startsWith(sri.key())) - continue; - - info.setFile(filePath); - QString name = info.completeBaseName(); - for (auto li = sri.value().launchedMap.begin(); li != sri.value().launchedMap.end(); li++) { - // 查找同名且未启动过的应用 - if (li.key() == name && !li.value()) { - li.value() = true; - Q_EMIT launched(filePath); - - // 记录启动状态 - saveStatusFile(info.absolutePath() + "/"); - } - } - } -} - -/** - * @brief AlRecorder::uninstallHints 记录Launcher服务卸载应用信息, 终端卸载不会调用该函数, desktopFiles为绝对路径 - * @param desktopFiles - */ -void AlRecorder::uninstallHints(const QStringList &desktopFiles) -{ - QMutexLocker locker(&mutex); - for (auto desktop : desktopFiles) { - for (auto sri = subRecoders.begin(); sri != subRecoders.end(); sri++) { - if (!desktop.contains(sri.key())) - continue; - - QFileInfo info(desktop); - sri.value().uninstallMap[info.completeBaseName()] = true; - } - } -} - -/** - * @brief AlRecorder::watchDirs 监控目录 - * @param dataDirs - */ -void AlRecorder::watchDirs(const QStringList &dataDirs) -{ - for (auto dirPath : dataDirs) { - if (subRecoders.contains(dirPath)) - continue; - - QDir dir(dirPath); - QStringList files = dir.entryList(QDir::Files); - for (auto &file : files) - file = dirPath + file; - - // 监听目录和文件 - watcher->addDir(dirPath); - if (files.size() > 0) - watcher->addPaths(files); - - // 初始化对应目录和应用信息 - initSubRecoder(dirPath); - } -} - -/** - * @brief AlRecorder::initSubRecoder 初始化应用目录记录 - * @param dirPath - */ -void AlRecorder::initSubRecoder(const QString &dirPath) -{ - subRecorder sub; - QByteArray encryText = QCryptographicHash::hash(dirPath.toLatin1(), QCryptographicHash::Md5); - QString statusFile = userAppsCfgDir + "launched-" + encryText.toHex() + ".csv"; - - // 读取App状态记录 - QMap launchedApp; - QFile file(statusFile); - if (file.exists() && file.open(QIODevice::ReadWrite | QIODevice::Text)) { - while (!file.atEnd()){ - QString line(file.readLine()); - QStringList strs = line.split(","); - if (strs.length() != 2) - continue; - - if (strs[1].size() > 0 && strs[1][0] == 't') - launchedApp[strs[0]] = true; - else - launchedApp[strs[0]] = false; - } - - file.close(); - } else { - // 读取app desktop - QDir dir(dirPath); - QStringList files = dir.entryList(QDir::Files); - QStringList apps; - for (QString file : files) { - if (!file.endsWith(".desktop")) - continue; - - int index = file.lastIndexOf("."); - file.truncate(index); - qInfo() << "entry =" << file; - apps.push_back(file); - } - - // fallback 都打开过 - for (auto app : apps) - launchedApp[app] = true; - } - - sub.statusFile = statusFile; - sub.launchedMap = launchedApp; - subRecoders[dirPath] = sub; -} - -/** - * @brief AlRecorder::onDFChanged 处理desktopFile文件改变事件 - * @param filePath - * @param op - */ -void AlRecorder::onDFChanged(const QString &filePath, uint32_t op) -{ - QFileInfo info(filePath); - QString dirPath = info.absolutePath() + "/"; - QString name = info.completeBaseName(); - subRecorder &sub = subRecoders[dirPath]; - QMap &launchedMap = sub.launchedMap; - - // 过滤文件, 仅保留.desktop类型 - if (!filePath.endsWith(".desktop")) - return; - - switch (op) { - case DFWatcher::event::Add: - qInfo() << "AlRecorder: Add " << filePath; - if (!launchedMap.contains(name)) { - bool launched = false; - if (sub.removedLaunchedMap.find(name) != sub.removedLaunchedMap.end()) { - launched = sub.removedLaunchedMap[name]; - sub.removedLaunchedMap.remove(name); - } - launchedMap[name] = launched; - } - sub.uninstallMap.remove(name); - saveStatusFile(dirPath); // 刷新状态文件 - break; - case DFWatcher::event::Del: - qInfo() << "AlRecorder: Del" << filePath; - if (launchedMap.contains(name)) { - if (!sub.uninstallMap.contains(name)) - sub.removedLaunchedMap[name] = launchedMap[name]; - - launchedMap.remove(name); - } - saveStatusFile(dirPath); //刷新状态文件 - break; - case DFWatcher::event::Mod: - break; - } -} - -/** - * @brief AlRecorder::saveStatusFile 保存状态文件 - * @param dirPath - */ -void AlRecorder::saveStatusFile(const QString &dirPath) -{ - subRecorder sub = subRecoders[dirPath]; - QString tmpFile = sub.statusFile + "_tmp"; - QFile fp(tmpFile); - bool ok = false; - qInfo() << "saveStatusFile=" << dirPath << "create file=" << tmpFile; - if (fp.open(QIODevice::ReadWrite | QIODevice::Text)) { - QTextStream out(&fp); - out << "# " << dirPath << endl; - for (auto rl = sub.launchedMap.begin(); rl != sub.launchedMap.end(); rl++) { - out << rl.key() << "," << ((rl.value() == true) ? "t" : "f") << endl; - } - ok = true; - fp.close(); - } - - // 覆盖原文件 - QFile::remove(sub.statusFile); - QFile::rename(tmpFile, sub.statusFile); - Q_EMIT statusSaved(dirPath, sub.statusFile, ok); -} diff --git a/src/modules/apps/alrecorder.h b/src/modules/apps/alrecorder.h deleted file mode 100644 index 2989eb5..0000000 --- a/src/modules/apps/alrecorder.h +++ /dev/null @@ -1,55 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef ALRECORDER_H -#define ALRECORDER_H - -#include -#include -#include - -class DFWatcher; - -// 记录当前用户应用状态信息 -class AlRecorder: public QObject -{ - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "org.deepin.dde.AlRecorder1") - -public: - // 各个应用目录中应用的启动记录 - struct subRecorder { - QString statusFile; // 应用目录状态文件 - QMap launchedMap; // 应用启动记录 - QMap removedLaunchedMap; // desktop文件卸载记录 - QMap uninstallMap; // 记录应用将被卸载状态 - }; - - AlRecorder(DFWatcher *_watcher, QObject *parent = nullptr); - ~AlRecorder(); - -Q_SIGNALS: - void launched(const QString &file); - void statusSaved(const QString &root, const QString &file, bool ok); - void serviceRestarted(); - -private Q_SLOTS: - void onDFChanged(const QString &filePath, uint32_t op); - -public Q_SLOTS: - QMap getNew(); - void markLaunched(const QString &filePath); - void uninstallHints(const QStringList &desktopFiles); - void watchDirs(const QStringList &dataDirs); - -private: - void initSubRecoder(const QString &dirPath); - void saveStatusFile(const QString &dirPath); - - QMap subRecoders; // 记录不同应用目录的文件状态 - DFWatcher *watcher; - QMutex mutex; -}; - -#endif // ALRECODER_H diff --git a/src/modules/apps/appmanager.cpp b/src/modules/apps/appmanager.cpp deleted file mode 100644 index c05a389..0000000 --- a/src/modules/apps/appmanager.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "appmanager.h" -#include "dfwatcher.h" -#include "alrecorder.h" -#include "basedir.h" -#include "dbusalrecorderadaptor.h" - -#include -#include - -AppManager::AppManager(QObject *parent) - : QObject(parent) - , watcher(new DFWatcher(this)) - , recorder(new AlRecorder(watcher, this)) -{ - qInfo() << "AppManager"; - new DBusAdaptorRecorder(recorder); - QDBusConnection con = QDBusConnection::sessionBus(); - if (!con.registerService("org.deepin.dde.AlRecorder1")) - { - qWarning() << "register service AlRecorder1 error:" << con.lastError().message(); - return; - } - - if (!con.registerObject("/org/deepin/dde/AlRecorder1", recorder)) - { - qWarning() << "register object AlRecorder1 error:" << con.lastError().message(); - return; - } - - - QStringList dataDirs; - dataDirs << BaseDir::userAppDir().c_str(); - for (auto &dir : BaseDir::sysAppDirs()) - dataDirs << dir.c_str(); - - qInfo() << "get dataDirs: " << dataDirs; - recorder->watchDirs(dataDirs); // 监控应用desktop -} - -AppManager::~AppManager() -{ - -} diff --git a/src/modules/apps/appmanager.h b/src/modules/apps/appmanager.h deleted file mode 100644 index f08eb98..0000000 --- a/src/modules/apps/appmanager.h +++ /dev/null @@ -1,24 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef APPMANAGER_H -#define APPMANAGER_H - -#include - -class DFWatcher; -class AlRecorder; -class AppManager: public QObject -{ - Q_OBJECT -public: - explicit AppManager(QObject *parent = nullptr); - ~AppManager(); - -private: - DFWatcher *watcher; - AlRecorder *recorder; -}; - -#endif // APPMANAGER_H diff --git a/src/modules/apps/dbusalrecorderadaptor.cpp b/src/modules/apps/dbusalrecorderadaptor.cpp deleted file mode 100644 index e636046..0000000 --- a/src/modules/apps/dbusalrecorderadaptor.cpp +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "dbusalrecorderadaptor.h" - -DBusAdaptorRecorder::DBusAdaptorRecorder(QObject *parent) - : QDBusAbstractAdaptor(parent) -{ - setAutoRelaySignals(true); - if (QMetaType::type("UnlaunchedAppMap") == QMetaType::UnknownType) - registerUnLaunchedAppMapMetaType(); - - AlRecorder *recorder = static_cast(QObject::parent()); - if (recorder) { - connect(recorder, &AlRecorder::launched, this, &DBusAdaptorRecorder::Launched); - connect(recorder, &AlRecorder::serviceRestarted, this, &DBusAdaptorRecorder::ServiceRestarted); - connect(recorder, &AlRecorder::statusSaved, this, &DBusAdaptorRecorder::StatusSaved); - } -} - -DBusAdaptorRecorder::~DBusAdaptorRecorder() -{ -} - -AlRecorder *DBusAdaptorRecorder::parent() const -{ - return static_cast(QObject::parent()); -} - -UnLaunchedAppMap DBusAdaptorRecorder::GetNew() -{ - return parent()->getNew(); -} - -void DBusAdaptorRecorder::MarkLaunched(const QString &desktopFile) -{ - parent()->markLaunched(desktopFile); -} - -void DBusAdaptorRecorder::UninstallHints(const QStringList &desktopFiles) -{ - parent()->uninstallHints(desktopFiles); -} - -void DBusAdaptorRecorder::WatchDirs(const QStringList &dirs) -{ - parent()->watchDirs(dirs); -} - diff --git a/src/modules/apps/dbusalrecorderadaptor.h b/src/modules/apps/dbusalrecorderadaptor.h deleted file mode 100644 index 8a1d189..0000000 --- a/src/modules/apps/dbusalrecorderadaptor.h +++ /dev/null @@ -1,71 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef DBUSALRECORDERADAPTOR_H -#define DBUSALRECORDERADAPTOR_H - -#include "alrecorder.h" -#include "unlaunchedappmap.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class DBusAdaptorRecorder: public QDBusAbstractAdaptor -{ - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "org.deepin.dde.AlRecorder1") - Q_CLASSINFO("D-Bus Introspection", "" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - "") - - AlRecorder *parent() const; - -public: - explicit DBusAdaptorRecorder(QObject *parent); - virtual ~DBusAdaptorRecorder(); - -public: // PROPERTIES -public Q_SLOTS: // METHODS - UnLaunchedAppMap GetNew(); - void MarkLaunched(const QString &desktopFile); - void UninstallHints(const QStringList &desktopFiles); - void WatchDirs(const QStringList &dirs); -Q_SIGNALS: // SIGNALS - void Launched(const QString &file); - void ServiceRestarted(); - void StatusSaved(const QString &root, const QString &file, bool ok); -}; - -#endif diff --git a/src/modules/apps/desktopfilereader.cpp b/src/modules/apps/desktopfilereader.cpp deleted file mode 100644 index c46711b..0000000 --- a/src/modules/apps/desktopfilereader.cpp +++ /dev/null @@ -1,89 +0,0 @@ -// SPDX-FileCopyrightText: 2022 ~ 2022 Deepin Technology Co., Ltd. -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "desktopfilereader.h" -#include "basedir.h" - -#include - -#define BAMF_INDEX_NAME "bamf-2.index" - -DesktopFileReader *DesktopFileReader::instance() -{ - static DesktopFileReader instance; - return &instance; -} - -QString DesktopFileReader::fileName(const QString &instanceName) const -{ - for (const BamfData &lineData: m_bamfLineData) { - if (lineData.instanceName.toLower() == instanceName.toLower()) { - QString name = lineData.lineData.split("\t").first(); - return QString("%1%2").arg(lineData.directory).arg(name); - } - } - - // 如果根据instanceName没有找到,则根据空格来进行分隔 - for (const BamfData &lineData: m_bamfLineData) { - QStringList lines = lineData.lineData.split("\t"); - if (lines.size() < 2) - continue; - - QStringList cmds = lines[2].split(" "); - if (cmds.size() > 1 && cmds[1].toLower() == instanceName.toLower()) - return QString("%1%2").arg(lineData.directory).arg(lines.first()); - } - - return instanceName; -} - -DesktopFileReader::DesktopFileReader() -{ - loadDesktopFiles(); -} - -DesktopFileReader::~DesktopFileReader() -{ -} - -QStringList DesktopFileReader::applicationDirs() const -{ - std::vector appDirs = BaseDir::appDirs(); - QStringList directions; - for (std::string appDir : appDirs) - directions << appDir.c_str(); - - return directions; -} - -void DesktopFileReader::loadDesktopFiles() -{ - QStringList directions = applicationDirs(); - for (const QString &direction : directions) { - // 读取后缀名为 - QDir dir(direction); - dir.setNameFilters(QStringList() << BAMF_INDEX_NAME); - QFileInfoList fileList = dir.entryInfoList(); - if (fileList.size() == 0) - continue; - - QFileInfo fileInfo = fileList.at(0); - QFile file(fileInfo.absoluteFilePath()); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) - continue; - - QList> bamfLine; - while (!file.atEnd()) { - QString line = file.readLine(); - QStringList part = line.split("\t"); - BamfData bamf; - bamf.directory = direction; - if (part.size() > 2) - bamf.instanceName = part[2].trimmed(); - bamf.lineData = line; - m_bamfLineData << bamf; - } - } -} diff --git a/src/modules/apps/desktopfilereader.h b/src/modules/apps/desktopfilereader.h deleted file mode 100644 index 0babaa4..0000000 --- a/src/modules/apps/desktopfilereader.h +++ /dev/null @@ -1,36 +0,0 @@ -// SPDX-FileCopyrightText: 2022 ~ 2022 Deepin Technology Co., Ltd. -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef DESKTOPFILEREADER_H -#define DESKTOPFILEREADER_H - -#include -#include - -struct BamfData { - QString directory; - QString instanceName; - QString lineData; -}; - -class DesktopFileReader -{ -public: - static DesktopFileReader *instance(); - QString fileName(const QString &instanceName) const; - -protected: - DesktopFileReader(); - ~DesktopFileReader(); - -private: - QStringList applicationDirs() const; - void loadDesktopFiles(); - -private: - QList m_bamfLineData; -}; - -#endif // DESKTOPFILEREADER_H diff --git a/src/modules/apps/dfwatcher.cpp b/src/modules/apps/dfwatcher.cpp deleted file mode 100644 index 733add9..0000000 --- a/src/modules/apps/dfwatcher.cpp +++ /dev/null @@ -1,113 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "dfwatcher.h" - -#include -#include -#include -#include - -const QString dfSuffix = ".desktop"; -const QString configSuffix = ".json"; - - DFWatcher::DFWatcher(QObject *parent) - : QObject (parent) - , watcher(new QFileSystemWatcher(this)) - { - QDBusConnection con = QDBusConnection::sessionBus(); - if (!con.registerService("org.deepin.dde.DFWatcher1")) - { - qInfo() << "register service DFWatcher error:" << con.lastError().message(); - return; - } - - if (!con.registerObject("/org/deepin/dde/DFWatcher1", this, QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals)) - { - qInfo() << "register object DFWatcher error:" << con.lastError().message(); - return; - } - - connect(watcher, &QFileSystemWatcher::fileChanged, this, &DFWatcher::fileUpdated, Qt::QueuedConnection); - connect(watcher, &QFileSystemWatcher::directoryChanged, this, &DFWatcher::directoryUpdated, Qt::QueuedConnection); - } - - DFWatcher::~DFWatcher() - { - QDBusConnection::sessionBus().unregisterObject("/org/deepin/dde/DFWatcher1"); - } - - void DFWatcher::addDir(const QString &path) - { - // 记录当前目录内容 - qInfo() << "addDir :" << path; - const QDir dir(path); - dirContentMap[path] = dir.entryList(QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Files, QDir::DirsFirst); - - watcher->addPath(path); - } - - void DFWatcher::addPaths(const QStringList &paths) - { - watcher->addPaths(paths); - } - - QStringList DFWatcher::files() - { - return watcher->files(); - } - - void DFWatcher::removePath(const QString &filepath) - { - watcher->removePath(filepath); - } - - void DFWatcher::fileUpdated(const QString &filePath) - { - qInfo() << "event: modify filepath=" << filePath; - if (filePath.endsWith(dfSuffix) || filePath.endsWith(configSuffix)) - Q_EMIT Event(filePath, int(event::Mod)); - } - - void DFWatcher::directoryUpdated(const QString &dirPath) - { - QStringList recoderedContent = dirContentMap[dirPath]; - - const QDir dir(dirPath); - QStringList newEntries = dir.entryList(QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Files, QDir::DirsFirst); - - QSet newDirSet = QSet::fromList(newEntries); - QSet currentDirSet = QSet::fromList(recoderedContent); - - // 添加的文件 - QSet newFiles = newDirSet - currentDirSet; - QStringList newFile = newFiles.toList(); - - // 移除的文件 - QSet deletedFiles = currentDirSet - newDirSet; - QStringList deleteFile = deletedFiles.toList(); - - // 更新目录记录 - dirContentMap[dirPath] = newEntries; - - // 新增文件 - if (newFile.size() > 0) { - for (auto &file : newFile) { - //qInfo() << "event: add filepath=" << file; - if (file.endsWith(dfSuffix)) { - Q_EMIT Event(dirPath + file, event::Add); - } - } - } - - // 移除文件 - if (deleteFile.size() > 0) { - for (auto &file : deleteFile) { - //qInfo() << "event: del filepath=" << file; - if (file.endsWith(dfSuffix)) { - Q_EMIT Event(dirPath + file, event::Del); - } - } - } - } diff --git a/src/modules/apps/dfwatcher.h b/src/modules/apps/dfwatcher.h deleted file mode 100644 index 5301806..0000000 --- a/src/modules/apps/dfwatcher.h +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef DFWATCHER_H -#define DFWATCHER_H - -#include -#include -#include - -class DFWatcher: public QObject { - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "org.deepin.dde.DFWatcher1") - -public: - enum event{ - Add, - Del, - Mod, - }; - - explicit DFWatcher(QObject *parent = nullptr); - ~DFWatcher(); - - void addDir(const QString & path); - void addPaths(const QStringList &paths); - QStringList files(); - void removePath(const QString &filepath); -Q_SIGNALS: - void Event(const QString &filepath, int op); - -private Q_SLOTS: - void fileUpdated(const QString &filePath); - void directoryUpdated(const QString &dirPath); - -private: - QFileSystemWatcher *watcher; - QMap dirContentMap; // 监控的目录内容列表 -}; - -#endif diff --git a/src/modules/dock/appinfo.cpp b/src/modules/dock/appinfo.cpp deleted file mode 100644 index 0e90b28..0000000 --- a/src/modules/dock/appinfo.cpp +++ /dev/null @@ -1,58 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "appinfo.h" -#include "common.h" - -#include -#include -#include - -AppInfo::AppInfo(DesktopInfo &info) - : m_isValid(true) -{ - init(info); -} - -AppInfo::AppInfo(const QString &_fileName) - : m_isValid(true) -{ - DesktopInfo info(_fileName.toStdString()); - init(info); -} - -void AppInfo::init(DesktopInfo &info) -{ - if (!info.isValidDesktop()) { - m_isValid = false; - return; - } - - std::string xDeepinVendor= info.getDesktopFile()->getStr(MainSection, "X-Deepin-Vendor"); - if (xDeepinVendor == "deepin") { - m_name = info.getGenericName().c_str(); - if (m_name.isEmpty()) - m_name = info.getName().c_str(); - } else { - m_name = info.getName().c_str(); - } - - m_innerId = genInnerIdWithDesktopInfo(info); - m_fileName = info.getFileName().c_str(); - m_id = info.getId().c_str(); - m_icon = info.getIcon().c_str(); - m_installed = info.isInstalled(); - for (const auto & action : info.getActions()) { - m_actions.push_back(action); - } -} - -QString AppInfo::genInnerIdWithDesktopInfo(DesktopInfo &info) -{ - std::string cmdline = info.getCommandLine(); - QByteArray encryText = QCryptographicHash::hash(QString(cmdline.c_str()).toLatin1(), QCryptographicHash::Md5); - QString innerId = desktopHashPrefix + encryText.toHex(); - qInfo() << "app " << info.getId().c_str() << " generate innerId :" << innerId; - return innerId; -} diff --git a/src/modules/dock/appinfo.h b/src/modules/dock/appinfo.h deleted file mode 100644 index f3a77ff..0000000 --- a/src/modules/dock/appinfo.h +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef APPINFO_H -#define APPINFO_H - -#include "desktopinfo.h" - -#include - -// 应用信息类 -class AppInfo -{ -public: - explicit AppInfo(DesktopInfo &info); - explicit AppInfo(const QString &_fileName); - - void init(DesktopInfo &info); - QString getFileName() {return m_fileName;} - QString getIcon() {return m_icon;} - QString getId() {return m_id;} - QString getInnerId() {return m_innerId;} - QString getName() {return m_name;} - QVector getActions() {return m_actions;} - QString getIdentifyMethod() {return m_identifyMethod;} - void setIdentifyMethod(QString method) {m_identifyMethod = method;} - bool isInstalled() {return m_installed;} - bool isValidApp() {return m_isValid;} - -private: - QString genInnerIdWithDesktopInfo(DesktopInfo &info); - - QString m_fileName; - QString m_id; - QString m_icon; - QString m_identifyMethod; - QString m_innerId; - QString m_name; - QVector m_actions; - bool m_installed; - bool m_isValid; -}; - -#endif // APPINFO_H diff --git a/src/modules/dock/appmenu.cpp b/src/modules/dock/appmenu.cpp deleted file mode 100644 index 27355e8..0000000 --- a/src/modules/dock/appmenu.cpp +++ /dev/null @@ -1,80 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "appmenu.h" - -#include -#include - -AppMenu::AppMenu() - : m_checkableMenu(false) - , m_singleCheck(false) - , m_itemCount(0) - , m_dirty(false) -{ - -} - -/** - * @brief AppMenu::appendItem 增加菜单选项 - * @param item - */ -void AppMenu::appendItem(AppMenuItem item) -{ - if (!item.text.isEmpty()) { - item.id = allocateId(); - m_items.push_back(item); - } -} - -/** - * @brief AppMenu::handleAction 响应应用菜单项 - * @param timestamp - * @param itemId - */ -void AppMenu::handleAction(uint32_t timestamp, QString itemId) -{ - for (auto &item : m_items) { - if (item.id == itemId) { - item.action(timestamp); - break; - } - } -} - -void AppMenu::setDirtyStatus(bool isDirty) -{ - m_dirty = isDirty; -} - -QString AppMenu::getMenuJsonStr() -{ - QJsonObject obj; - QJsonArray array; - for (auto item : m_items) { - QJsonObject objItem; - objItem["itemId"] = item.id; - objItem["itemText"] = item.text; - objItem["isActive"] = item.isActive; - objItem["isCheckable"] = item.isCheckable; - objItem["checked"] = item.checked; - objItem["itemIcon"] = item.icon; - objItem["itemIconHover"] = item.iconHover; - objItem["itemIconInactive"] = item.iconInactive; - objItem["showCheckMark"] = item.showCheckMark; - objItem["itemSubMenu"] = item.subMenu ? item.subMenu->getMenuJsonStr() : ""; - array.push_back(objItem); - } - obj["items"] = QJsonValue(array); - obj["checkableMenu"] = m_checkableMenu; - obj["singleCheck"] = m_singleCheck; - - QString ret = QJsonDocument(obj).toJson(); - return ret; -} - -QString AppMenu::allocateId() -{ - return QString::number(m_itemCount++); -} diff --git a/src/modules/dock/appmenu.h b/src/modules/dock/appmenu.h deleted file mode 100644 index 708eca5..0000000 --- a/src/modules/dock/appmenu.h +++ /dev/null @@ -1,67 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef APPMENU_H -#define APPMENU_H - -#include -#include -#include - -#include -#include -#include - -typedef std::function AppMenuAction; - -class AppMenu; - -// 应用菜单选项 -struct AppMenuItem -{ - AppMenuItem() - : isActive(true) - , hint(0) - { - } - - QString id; - QString text; - QString isCheckable; - QString checked; - QString icon; - QString iconHover; - QString iconInactive; - QString showCheckMark; - std::shared_ptr subMenu; - - bool isActive; - int hint; - AppMenuAction action; -}; - -// 应用菜单类 -class AppMenu -{ -public: - AppMenu(); - - void appendItem(AppMenuItem item); - void handleAction(uint32_t timestamp, QString itemId); - void setDirtyStatus(bool isDirty); - QString getMenuJsonStr(); - -private: - QString allocateId(); - -private: - QVector m_items; // json:"items" - bool m_checkableMenu; // json:"checkableMenu" - bool m_singleCheck; // json:"singleCheck" - - int m_itemCount; - bool m_dirty; -}; - -#endif // APPMENU_H diff --git a/src/modules/dock/common.h b/src/modules/dock/common.h deleted file mode 100644 index 902b1f9..0000000 --- a/src/modules/dock/common.h +++ /dev/null @@ -1,90 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef COMMON_H -#define COMMON_H - -#include -#include -#include - -const QString configDock = "com.deepin.dde.dock"; -const QString configAppearance = "com.deepin.dde.appearance"; -const QString keyHideMode = "Hide_Mode"; -const QString keyDisplayMode = "Display_Mode"; -const QString keyPosition = "Position"; -const QString keyIconSize = "Icon_Size"; -const QString keyDockedApps = "Docked_Apps"; -const QString keyShowTimeout = "Show_Timeout"; -const QString keyHideTimeout = "Hide_Timeout"; -const QString keyWindowSizeFashion = "Window_Size_Fashion"; -const QString keyWindowSizeEfficient = "Window_Size_Efficient"; -const QString keyWinIconPreferredApps = "Win_Icon_Preferred_Apps"; -const QString keyOpacity = "Opacity"; -const QString keyPluginSettings = "Plugin_Settings"; -const QString keyForceQuitApp = "Force_Quit_App"; -const QString keyRecentApp = "Recent_App"; -const QString keyShowRecent = "Show_Recent"; -const QString keyShowMultiWindow = "Show_MultiWindow"; - -const QString scratchDir = QDir::homePath() + "/.local/dock/scratch/"; - -// DBus服务、路径 -const QString dbusService = "org.deepin.dde.daemon.Dock1"; -const QString dbusPath = "/org/deepin/dde/daemon/Dock1"; -const QString dbusInterface = dbusService; - -const QString windowPatternsFile = "/usr/share/dde/data/window_patterns.json"; -const QString desktopHashPrefix = "d:"; -const QString windowHashPrefix = "w:"; - -const QString entryDBusObjPathPrefix = dbusPath + "/entries/"; -const QString entryDBusInterface = dbusInterface + ".Entry"; - -// 驻留应用desktop file模板 -const QString dockedItemTemplate = R"([Desktop Entry] -Name=%1 -Exec=%2 -Icon=%3 -Type=Application -Terminal=false -StartupNotify=false -)"; - -const QString frontendWindowWmClass = "dde-dock"; -const int configureNotifyDelay = 100; -const int smartHideTimerDelay = 400; - -const int bestIconSize = 48; -const int menuItemHintShowAllWindows = 1; - -const int MotifHintFunctions = 1; -const int MotifHintDecorations = 2; -const int MotifHintInputMode = 4; -const int MotifHintStatus = 8; - -const int MotifFunctionNone = 0; -const int MotifFunctionAll = 1; -const int MotifFunctionResize = 2; -const int MotifFunctionMove = 4; -const int MotifFunctionMinimize = 8; -const int MotifFunctionMaximize = 16; -const int MotifFunctionClose = 32; - -const QString ddeLauncherWMClass = "dde-launcher"; - -static inline QByteArray sessionType() { - static QByteArray type = qgetenv("XDG_SESSION_TYPE"); - return type; -} - -static inline bool isWaylandSession() { - return sessionType().compare("wayland") == 0; -} - -static inline bool isX11Session() { - return sessionType().compare("x11") == 0; -} - -#endif // COMMON_H diff --git a/src/modules/dock/dbusadaptordock.cpp b/src/modules/dock/dbusadaptordock.cpp deleted file mode 100644 index 17e23a8..0000000 --- a/src/modules/dock/dbusadaptordock.cpp +++ /dev/null @@ -1,256 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "dbusadaptordock.h" - -DBusAdaptorDock::DBusAdaptorDock(QObject *parent) - : QDBusAbstractAdaptor(parent) -{ - // constructor - setAutoRelaySignals(true); - - Dock *dock = static_cast(QObject::parent()); - if (dock) { - connect(dock, &Dock::serviceRestarted, this, &DBusAdaptorDock::ServiceRestarted); - connect(dock, &Dock::entryAdded, this, &DBusAdaptorDock::EntryAdded); - connect(dock, &Dock::entryRemoved, this, &DBusAdaptorDock::EntryRemoved); - connect(dock, &Dock::hideStateChanged, this, &DBusAdaptorDock::HideStateChanged); - connect(dock, &Dock::frontendWindowRectChanged, this, &DBusAdaptorDock::FrontendWindowRectChanged); - connect(dock, &Dock::showRecentChanged, this, &DBusAdaptorDock::showRecentChanged); - connect(dock, &Dock::showMultiWindowChanged, this, &DBusAdaptorDock::ShowMultiWindowChanged); - } -} - -DBusAdaptorDock::~DBusAdaptorDock() -{ - // destructor -} - -int DBusAdaptorDock::displayMode() const -{ - return parent()->getDisplayMode(); -} - -void DBusAdaptorDock::setDisplayMode(int value) -{ - if (displayMode() != value) { - parent()->setDisplayMode(value); - Q_EMIT DisplayModeChanged(value); - } -} - -QStringList DBusAdaptorDock::dockedApps() const -{ - return parent()->getDockedApps(); -} - -QList DBusAdaptorDock::entries() const -{ - QList ret; - for (auto path : parent()->getEntryPaths()) - ret.push_back(QDBusObjectPath(path)); - return ret; -} - -int DBusAdaptorDock::hideMode() const -{ - return int(parent()->getHideMode()); -} - -void DBusAdaptorDock::setHideMode(int value) -{ - if (hideMode() != value) { - parent()->setHideMode(static_cast(value)); - Q_EMIT HideModeChanged(value); - } -} - -int DBusAdaptorDock::hideState() const -{ - return int(parent()->getHideState()); -} - -uint DBusAdaptorDock::hideTimeout() const -{ - return parent()->getHideTimeout(); -} - -void DBusAdaptorDock::setHideTimeout(uint value) -{ - if (hideTimeout() != value) { - parent()->setHideTimeout(value); - Q_EMIT HideTimeoutChanged(value); - } -} - -uint DBusAdaptorDock::windowSizeEfficient() const -{ - return parent()->getWindowSizeEfficient(); -} - -void DBusAdaptorDock::setWindowSizeEfficient(uint value) -{ - if (windowSizeEfficient() != value) { - parent()->setWindowSizeEfficient(value); - Q_EMIT WindowSizeEfficientChanged(value); - } -} - -uint DBusAdaptorDock::windowSizeFashion() const -{ - return parent()->getWindowSizeFashion(); -} - -void DBusAdaptorDock::setWindowSizeFashion(uint value) -{ - if (windowSizeFashion() != value) { - parent()->setWindowSizeFashion(value); - Q_EMIT WindowSizeFashionChanged(value); - } -} - -QRect DBusAdaptorDock::frontendWindowRect() const -{ - return parent()->getFrontendWindowRect(); -} - -double DBusAdaptorDock::opacity() const -{ - return parent()->getOpacity(); -} - -uint DBusAdaptorDock::iconSize() const -{ - return parent()->getIconSize(); -} - -void DBusAdaptorDock::setIconSize(uint value) -{ - if (iconSize() != value) { - parent()->setIconSize(value); - Q_EMIT IconSizeChanged(value); - } -} - -int DBusAdaptorDock::position() const -{ - return parent()->getPosition(); -} - -void DBusAdaptorDock::setPosition(int value) -{ - if (position() != value) { - parent()->setPosition(value); - Q_EMIT PositionChanged(value); - } -} - -uint DBusAdaptorDock::showTimeout() const -{ - return parent()->getShowTimeout(); -} - -void DBusAdaptorDock::setShowTimeout(uint value) -{ - if (showTimeout() != value) { - parent()->setShowTimeout(value); - Q_EMIT ShowTimeoutChanged(value); - } -} - -bool DBusAdaptorDock::showRecent() const -{ - return parent()->showRecent(); -} - -bool DBusAdaptorDock::showMultiWindow() const -{ - return parent()->showMultiWindow(); -} - -Dock *DBusAdaptorDock::parent() const -{ - return static_cast(QObject::parent()); -} - -void DBusAdaptorDock::CloseWindow(uint win) -{ - parent()->closeWindow(win); -} - -// for debug -QStringList DBusAdaptorDock::GetEntryIDs() -{ - return parent()->getEntryIDs(); -} - -bool DBusAdaptorDock::IsDocked(const QString &desktopFile) -{ - return parent()->isDocked(desktopFile); -} - -bool DBusAdaptorDock::IsOnDock(const QString &desktopFile) -{ - return parent()->isOnDock(desktopFile); -} - -void DBusAdaptorDock::MoveEntry(int index, int newIndex) -{ - parent()->moveEntry(index, newIndex); -} - -QString DBusAdaptorDock::QueryWindowIdentifyMethod(uint win) -{ - return parent()->queryWindowIdentifyMethod(win); -} - -QStringList DBusAdaptorDock::GetDockedAppsDesktopFiles() -{ - return parent()->getDockedAppsDesktopFiles(); -} - -QString DBusAdaptorDock::GetPluginSettings() -{ - return parent()->getPluginSettings(); -} - -void DBusAdaptorDock::SetPluginSettings(QString jsonStr) -{ - parent()->setPluginSettings(jsonStr); -} - -void DBusAdaptorDock::MergePluginSettings(QString jsonStr) -{ - parent()->mergePluginSettings(jsonStr); -} - -void DBusAdaptorDock::RemovePluginSettings(QString key1, QStringList key2List) -{ - parent()->removePluginSettings(key1, key2List); -} - -bool DBusAdaptorDock::RequestDock(const QString &desktopFile, int index) -{ - return parent()->requestDock(desktopFile, index); -} - -bool DBusAdaptorDock::RequestUndock(const QString &desktopFile) -{ - return parent()->requestUndock(desktopFile); -} - -void DBusAdaptorDock::SetShowRecent(bool visible) -{ - parent()->setShowRecent(visible); -} - -void DBusAdaptorDock::SetShowMultiWindow(bool showMultiWindow) -{ - parent()->setShowMultiWindow(showMultiWindow); -} - -void DBusAdaptorDock::SetFrontendWindowRect(int x, int y, uint width, uint height) -{ - parent()->setFrontendWindowRect(x, y, width, height); -} diff --git a/src/modules/dock/dbusadaptordock.h b/src/modules/dock/dbusadaptordock.h deleted file mode 100644 index ee3f6e2..0000000 --- a/src/modules/dock/dbusadaptordock.h +++ /dev/null @@ -1,216 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef DBUSADAPTORDOCK_H -#define DBUSADAPTORDOCK_H - -#include "dock.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/* - * Adaptor class for interface org.deepin.dde.daemon.Dock1 - */ -class DBusAdaptorDock: public QDBusAbstractAdaptor -{ - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "org.deepin.dde.daemon.Dock1") - Q_CLASSINFO("D-Bus Introspection", "" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - "") -public: - DBusAdaptorDock(QObject *parent); - virtual ~DBusAdaptorDock(); - -public: // PROPERTIES - Q_PROPERTY(int DisplayMode READ displayMode WRITE setDisplayMode NOTIFY DisplayModeChanged) - int displayMode() const; - void setDisplayMode(int value); - - Q_PROPERTY(QStringList DockedApps READ dockedApps NOTIFY DockedAppsChanged) - QStringList dockedApps() const; - - Q_PROPERTY(QList Entries READ entries NOTIFY EntriesChanged) - QList entries() const; - - Q_PROPERTY(int HideMode READ hideMode WRITE setHideMode NOTIFY HideModeChanged) - int hideMode() const; - void setHideMode(int value); - - Q_PROPERTY(int HideState READ hideState NOTIFY HideStateChanged) - int hideState() const; - - Q_PROPERTY(uint HideTimeout READ hideTimeout WRITE setHideTimeout NOTIFY HideTimeoutChanged) - uint hideTimeout() const; - void setHideTimeout(uint value); - - Q_PROPERTY(uint WindowSizeEfficient READ windowSizeEfficient WRITE setWindowSizeEfficient NOTIFY WindowSizeEfficientChanged) - uint windowSizeEfficient() const; - void setWindowSizeEfficient(uint value); - - Q_PROPERTY(uint WindowSizeFashion READ windowSizeFashion WRITE setWindowSizeFashion NOTIFY WindowSizeFashionChanged) - uint windowSizeFashion() const; - void setWindowSizeFashion(uint value); - - Q_PROPERTY(QRect FrontendWindowRect READ frontendWindowRect NOTIFY FrontendWindowRectChanged) - QRect frontendWindowRect() const; - - Q_PROPERTY(double Opacity READ opacity NOTIFY OpacityChanged) - double opacity() const; - - Q_PROPERTY(uint IconSize READ iconSize WRITE setIconSize NOTIFY IconSizeChanged) - uint iconSize() const; - void setIconSize(uint value); - - Q_PROPERTY(int Position READ position WRITE setPosition NOTIFY PositionChanged) - int position() const; - void setPosition(int value); - - Q_PROPERTY(uint ShowTimeout READ showTimeout WRITE setShowTimeout NOTIFY ShowTimeoutChanged) - uint showTimeout() const; - void setShowTimeout(uint value); - - Q_PROPERTY(bool ShowRecent READ showRecent NOTIFY showRecentChanged) - bool showRecent() const; - - Q_PROPERTY(bool ShowMultiWindow READ showMultiWindow NOTIFY ShowMultiWindowChanged) - bool showMultiWindow() const; - - Dock *parent() const; - -public Q_SLOTS: // METHODS - void CloseWindow(uint win); - QStringList GetEntryIDs(); - bool IsDocked(const QString &desktopFile); - bool IsOnDock(const QString &desktopFile); - void MoveEntry(int index, int newIndex); - QString QueryWindowIdentifyMethod(uint win); - QStringList GetDockedAppsDesktopFiles(); - QString GetPluginSettings(); - void SetPluginSettings(QString jsonStr); - void MergePluginSettings(QString jsonStr); - void RemovePluginSettings(QString key1, QStringList key2List); - bool RequestDock(const QString &desktopFile, int index); - bool RequestUndock(const QString &desktopFile); - void SetShowRecent(bool visible); - void SetShowMultiWindow(bool showMultiWindow); - void SetFrontendWindowRect(int x, int y, uint width, uint height); - -Q_SIGNALS: // SIGNALS - void ServiceRestarted(); - void EntryAdded(const QDBusObjectPath &path, int index); - void EntryRemoved(const QString &entryId); - - void DisplayModeChanged(int value) const; - void DockedAppsChanged(const QStringList &value) const; - void EntriesChanged(const QList &value) const; - void FrontendWindowRectChanged(const QRect &dockRect) const; - void HideModeChanged(int value) const; - void HideStateChanged(int value) const; - void HideTimeoutChanged(uint value) const; - void IconSizeChanged(uint value) const; - void OpacityChanged(double value) const; - void PositionChanged(int value) const; - void ShowTimeoutChanged(uint value) const; - void WindowSizeEfficientChanged(uint value) const; - void WindowSizeFashionChanged(uint value) const; - void showRecentChanged(bool) const; - void ShowMultiWindowChanged(bool) const; -}; - -#endif diff --git a/src/modules/dock/dbusadaptorentry.cpp b/src/modules/dock/dbusadaptorentry.cpp deleted file mode 100644 index be780ec..0000000 --- a/src/modules/dock/dbusadaptorentry.cpp +++ /dev/null @@ -1,151 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "dbusadaptorentry.h" - -DBusAdaptorEntry::DBusAdaptorEntry(QObject *parent) - : QDBusAbstractAdaptor(parent) -{ - - // constructor - setAutoRelaySignals(true); - - if (QMetaType::type("WindowInfo") == QMetaType::UnknownType) - registerWindowInfoMetaType(); - - if (QMetaType::type("WindowInfoMap") == QMetaType::UnknownType) - registerWindowInfoMapMetaType(); - - Entry *entry = static_cast(QObject::parent()); - if (entry) { - connect(entry, &Entry::isActiveChanged, this, &DBusAdaptorEntry::IsActiveChanged); - connect(entry, &Entry::isDockedChanged, this, &DBusAdaptorEntry::IsDockedChanged); - connect(entry, &Entry::menuChanged, this, &DBusAdaptorEntry::MenuChanged); - connect(entry, &Entry::iconChanged, this, &DBusAdaptorEntry::IconChanged); - connect(entry, &Entry::nameChanged, this, &DBusAdaptorEntry::NameChanged); - connect(entry, &Entry::desktopFileChanged, this, &DBusAdaptorEntry::DesktopFileChanged); - connect(entry, &Entry::currentWindowChanged, this, &DBusAdaptorEntry::CurrentWindowChanged); - connect(entry, &Entry::windowInfosChanged, this, &DBusAdaptorEntry::WindowInfosChanged); - connect(entry, &Entry::modeChanged, this, &DBusAdaptorEntry::ModeChanged); - } -} - -DBusAdaptorEntry::~DBusAdaptorEntry() -{ -} - -uint DBusAdaptorEntry::currentWindow() const -{ - return parent()->getCurrentWindow(); -} - -QString DBusAdaptorEntry::desktopFile() const -{ - return parent()->getDesktopFile(); -} - -QString DBusAdaptorEntry::icon() const -{ - return parent()->getIcon(); -} - -QString DBusAdaptorEntry::id() const -{ - return parent()->getId(); -} - -bool DBusAdaptorEntry::isActive() const -{ - return parent()->getIsActive(); -} - -bool DBusAdaptorEntry::isDocked() const -{ - return parent()->getIsDocked(); -} - -int DBusAdaptorEntry::mode() const -{ - return parent()->mode(); -} - -QString DBusAdaptorEntry::menu() const -{ - return parent()->getMenu(); -} - -QString DBusAdaptorEntry::name() const -{ - return parent()->getName(); -} - -WindowInfoMap DBusAdaptorEntry::windowInfos() -{ - return parent()->getExportWindowInfos(); -} - -Entry *DBusAdaptorEntry::parent() const -{ - return static_cast(QObject::parent()); -} - -void DBusAdaptorEntry::Activate(uint timestamp) -{ - parent()->active(timestamp); -} - -void DBusAdaptorEntry::Check() -{ - parent()->check(); -} - -void DBusAdaptorEntry::ForceQuit() -{ - parent()->forceQuit(); -} - -void DBusAdaptorEntry::ActiveWindow(quint32 winId) -{ - parent()->activeWindow(winId); -} - -QList DBusAdaptorEntry::GetAllowedCloseWindows() -{ - auto ids = parent()->getAllowedClosedWindowIds(); - QList ret; - for (auto id : ids) - ret.push_back(id); - - return ret; -} - -void DBusAdaptorEntry::HandleDragDrop(uint timestamp, const QStringList &files) -{ - parent()->handleDragDrop(timestamp, files); -} - -void DBusAdaptorEntry::HandleMenuItem(uint timestamp, const QString &id) -{ - parent()->handleMenuItem(timestamp, id); -} - -void DBusAdaptorEntry::NewInstance(uint timestamp) -{ - parent()->newInstance(timestamp); -} - -void DBusAdaptorEntry::PresentWindows() -{ - parent()->presentWindows(); -} - -void DBusAdaptorEntry::RequestDock() -{ - parent()->requestDock(); -} - -void DBusAdaptorEntry::RequestUndock() -{ - parent()->requestUndock(); -} diff --git a/src/modules/dock/dbusadaptorentry.h b/src/modules/dock/dbusadaptorentry.h deleted file mode 100644 index 240d468..0000000 --- a/src/modules/dock/dbusadaptorentry.h +++ /dev/null @@ -1,134 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef DBUSADAPTORENTRY_H -#define DBUSADAPTORENTRY_H - -#include "entry.h" -#include "windowinfomap.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -/* - * Adaptor class for interface org.deepin.dde.daemon.Dock1.Entry - */ -class DBusAdaptorEntry: public QDBusAbstractAdaptor -{ - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "org.deepin.dde.daemon.Dock1.Entry") - Q_CLASSINFO("D-Bus Introspection", "" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - "") - -public: - explicit DBusAdaptorEntry(QObject *parent); - virtual ~DBusAdaptorEntry(); - -public: // PROPERTIES - Q_PROPERTY(uint CurrentWindow READ currentWindow NOTIFY CurrentWindowChanged) - uint currentWindow() const; - - Q_PROPERTY(QString DesktopFile READ desktopFile NOTIFY DesktopFileChanged) - QString desktopFile() const; - - Q_PROPERTY(QString Icon READ icon NOTIFY IconChanged) - QString icon() const; - - Q_PROPERTY(QString Id READ id) - QString id() const; - - Q_PROPERTY(bool IsActive READ isActive NOTIFY IsActiveChanged) - bool isActive() const; - - Q_PROPERTY(bool IsDocked READ isDocked NOTIFY IsDockedChanged) - bool isDocked() const; - - Q_PROPERTY(QString Menu READ menu NOTIFY MenuChanged) - QString menu() const; - - Q_PROPERTY(QString Name READ name NOTIFY NameChanged) - QString name() const; - - Q_PROPERTY(WindowInfoMap WindowInfos READ windowInfos NOTIFY WindowInfosChanged) - WindowInfoMap windowInfos(); - - Q_PROPERTY(int Mode READ mode NOTIFY ModeChanged) - int mode() const; - - Entry *parent() const; - -public Q_SLOTS: // METHODS - void Activate(uint timestamp); - void Check(); - void ForceQuit(); - void ActiveWindow(quint32 winId); - QList GetAllowedCloseWindows(); - void HandleDragDrop(uint timestamp, const QStringList &files); - void HandleMenuItem(uint timestamp, const QString &id); - void NewInstance(uint timestamp); - void PresentWindows(); - void RequestDock(); - void RequestUndock(); - -Q_SIGNALS: // SIGNALS - void IsActiveChanged(bool value) const; - void IsDockedChanged(bool value) const; - void MenuChanged(const QString &value) const; - void IconChanged(const QString &value) const; - void NameChanged(const QString &value) const; - void DesktopFileChanged(const QString &value) const; - void CurrentWindowChanged(uint32_t value) const; - void WindowInfosChanged(WindowInfoMap value) const; - void ModeChanged(int value) const; -}; - -#endif diff --git a/src/modules/dock/dbushandler.cpp b/src/modules/dock/dbushandler.cpp deleted file mode 100644 index d225c6f..0000000 --- a/src/modules/dock/dbushandler.cpp +++ /dev/null @@ -1,246 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "dbushandler.h" -#include "dock.h" -#include "windowinfok.h" -#include "dbusbamfapplication.h" - -DBusHandler::DBusHandler(Dock *_dock, QObject *parent) - : QObject(parent) - , m_dock(_dock) - , m_session(QDBusConnection::sessionBus()) - , m_launcherEnd(new LauncherBackEnd("org.deepin.dde.daemon.Launcher1", "/org/deepin/dde/daemon/Launcher1", m_session, this)) - , m_launcherFront(new LauncherFront("org.deepin.dde.Launcher1", "/org/deepin/dde/Launcher1", m_session, this)) - , m_wm(new com::deepin::WM("com.deepin.wm", "/com/deepin/wm", m_session, this)) - , m_wmSwitcher(new org::deepin::dde::WMSwitcher1("org.deepin.dde.WMSwitcher1", "/org/deepin/dde/WMSwitcher1", m_session, this)) - , m_kwaylandManager(nullptr) - , m_xEventMonitor(nullptr) -{ - // 关联org.deepin.dde.daemon.Launcher1事件 ItemChanged - connect(m_launcherEnd, &LauncherBackEnd::ItemChanged, this, &DBusHandler::handleLauncherItemChanged); - - // 关联org.deepin.dde.Launcher1事件 VisibleChanged - connect(m_launcherFront, &LauncherFront::VisibleChanged, this, [&](bool visible) { - m_dock->setDdeLauncherVisible(visible); - m_dock->updateHideState(false); - }); - - // 关联org.deepin.dde.WMSwitcher1事件 WMChanged - connect(m_wmSwitcher, &__WMSwitcher::WMChanged, this, [&](QString name) {m_dock->setWMName(name);}); - - if (isWaylandSession()) { - m_xEventMonitor = new org::deepin::dde::XEventMonitor1("org.deepin.dde.XEventMonitor1", "/org/deepin/dde/XEventMonitor1", m_session, this); - // 注册XEventMonitor区域为整个屏幕的区域 - m_activeWindowMonitorKey = m_xEventMonitor->RegisterFullScreen(); - // 关联XEventMonitor的ButtonRelease事件 - connect(m_xEventMonitor, &org::deepin::dde::XEventMonitor1::ButtonRelease, this, &DBusHandler::onActiveWindowButtonRelease); - } -} - -// 关联org.deepin.dde.KWayland.WindowManager事件 -void DBusHandler::listenWaylandWMSignals() -{ - m_kwaylandManager = new org::deepin::dde::kwayland1::WindowManager("org.deepin.dde.KWayland1", "/org/deepin/dde/KWayland1/WindowManager", m_session, this); - - // ActiveWindowchanged - connect(m_kwaylandManager, &__KwaylandManager::ActiveWindowChanged, this, &DBusHandler::handleWlActiveWindowChange); - // WindowCreated - connect(m_kwaylandManager, &__KwaylandManager::WindowCreated, this, [&] (const QString &ObjPath) { - m_dock->registerWindowWayland(ObjPath); - }); - // WindowRemove - connect(m_kwaylandManager, &__KwaylandManager::WindowRemove, this, [&] (const QString &ObjPath) { - m_dock->unRegisterWindowWayland(ObjPath); - }); -} - -void DBusHandler::loadClientList() -{ - if (!m_kwaylandManager) - return; - - // 加载已存在的窗口 - QDBusPendingReply windowList = m_kwaylandManager->Windows(); - QVariantList windows = windowList.value(); - for (QVariant windowPath : windows) - m_dock->registerWindowWayland(windowPath.toString()); -} - -void DBusHandler::handleLauncherItemChanged(const QString &status, LauncherItemInfo itemInfo, qlonglong categoryID) -{ - qInfo() << "handleLauncherItemChanged status:" << status << " Name:" << itemInfo.name << " ID:" << itemInfo.id; - if (status == "deleted") { - m_dock->handleLauncherItemDeleted(itemInfo.path); - } else if (status == "created") { - // don't need to download to dock when app reinstall - } else if (status == "updated") { - m_dock->handleLauncherItemUpdated(itemInfo.path); - } -} - -QString DBusHandler::getCurrentWM() -{ - return m_wmSwitcher->CurrentWM().value(); -} - -// TODO 扩展Application Manager Launch接口,允许带参数启动应用,暂时调用StartManager接口 -void DBusHandler::launchApp(QString desktopFile, uint32_t timestamp, QStringList files) -{ - QDBusInterface interface = QDBusInterface("org.deepin.dde.Application1.Manager", "/org/deepin/dde/Application1/Manager", "org.deepin.dde.Application1.Manager"); - interface.call("LaunchApp", desktopFile, timestamp, files); -} - -void DBusHandler::launchAppAction(QString desktopFile, QString action, uint32_t timestamp) -{ - QDBusInterface interface = QDBusInterface("org.deepin.dde.Application1.Manager", "/org/deepin/dde/Application1/Manager", "org.deepin.dde.Application1.Manager"); - interface.call("LaunchAppAction", desktopFile, action, timestamp); -} - -void DBusHandler::markAppLaunched(const QString &filePath) -{ - QDBusInterface interface = QDBusInterface("org.deepin.dde.AlRecorder1", "/org/deepin/dde/AlRecorder1", "org.deepin.dde.AlRecorder1"); - interface.call("MarkLaunched", filePath); -} - -bool DBusHandler::wlShowingDesktop() -{ - bool ret = false; - if (m_kwaylandManager) - ret = m_kwaylandManager->IsShowingDesktop().value(); - - return ret; -} - -uint DBusHandler::wlActiveWindow() -{ - uint ret = 0; - if (m_kwaylandManager) - ret = m_kwaylandManager->ActiveWindow().value(); - - return ret; -} - -void DBusHandler::handleWlActiveWindowChange() -{ - uint activeWinInternalId = wlActiveWindow(); - if (activeWinInternalId == 0) - return; - - WindowInfoK *info = m_dock->handleActiveWindowChangedK(activeWinInternalId); - if (info && info->getXid() != 0) { - m_dock->handleActiveWindowChanged(info); - } else { - m_dock->updateHideState(false); - } -} - -void DBusHandler::onActiveWindowButtonRelease(int type, int x, int y, const QString &key) -{ - // 当鼠标松开区域事件的时候,取消注册,同时调用激活窗口的方法来触发智能隐藏的相关信号 - if (key != m_activeWindowMonitorKey) - return; - - uint activeWinInternalId = wlActiveWindow(); - if (activeWinInternalId == 0) - return; - - WindowInfoK *info = m_dock->handleActiveWindowChangedK(activeWinInternalId); - if (!info) - return; - - // 如果是在当前激活窗口区域内释放的,则触发检测智能隐藏的方法 - DockRect dockRect = info->getGeometry(); - if (dockRect.X <= x && x <= dockRect.X + dockRect.Width && dockRect.Y <= y && y <= dockRect.Y + dockRect.Height) { - // 取消智能隐藏 - m_dock->updateHideState(false); - } -} - -void DBusHandler::listenKWindowSignals(WindowInfoK *windowInfo) -{ - PlasmaWindow *window = windowInfo->getPlasmaWindow(); - if (!window) - return; - - // Title changed - connect(window, &PlasmaWindow::TitleChanged, this, [=] { - windowInfo->updateTitle(); - auto entry = m_dock->getEntryByWindowId(windowInfo->getXid()); - if (!entry) - return; - - if (entry->getCurrentWindowInfo() == windowInfo) - entry->updateName(); - - entry->updateExportWindowInfos(); - }); - - // Icon changed - connect(window, &PlasmaWindow::IconChanged, this, [=] { - windowInfo->updateIcon(); - auto entry = m_dock->getEntryByWindowId(windowInfo->getXid()); - if (!entry) - return; - - entry->updateIcon(); - }); - - // DemandingAttention changed - connect(window, &PlasmaWindow::DemandsAttentionChanged, this, [=] { - windowInfo->updateDemandingAttention(); - auto entry = m_dock->getEntryByWindowId(windowInfo->getXid()); - if (!entry) - return; - - entry->updateExportWindowInfos(); - }); - - // Geometry changed - connect(window, &PlasmaWindow::GeometryChanged, this, [=] { - if (!windowInfo->updateGeometry()) - return; - - m_dock->handleWindowGeometryChanged(); - }); -} - -PlasmaWindow *DBusHandler::createPlasmaWindow(QString objPath) -{ - return new PlasmaWindow("org.deepin.dde.KWayland1", objPath, m_session, this); -} - -/** - * @brief DBusHandler::removePlasmaWindowHandler 取消关联信号 TODO - * @param window - */ -void DBusHandler::removePlasmaWindowHandler(PlasmaWindow *window) -{ - -} - -void DBusHandler::presentWindows(QList windows) -{ - m_wm->PresentWindows(windows); -} - -// TODO: 待优化点, 查看Bamf根据windowId获取对应应用desktopFile路径实现方式, 移除bamf依赖 -QString DBusHandler::getDesktopFromWindowByBamf(XWindow windowId) -{ - QDBusInterface interface0 = QDBusInterface("org.ayatana.bamf", "/org/ayatana/bamf/matcher", "org.ayatana.bamf.matcher"); - QDBusReply replyApplication = interface0.call("ApplicationForXid", windowId); - QString appObjPath = replyApplication.value(); - if (!replyApplication.isValid() || appObjPath.isEmpty()) - return ""; - - - QDBusInterface interface = QDBusInterface("org.ayatana.bamf", appObjPath, "org.ayatana.bamf.application"); - QDBusReply replyDesktopFile = interface.call("DesktopFile"); - - if (replyDesktopFile.isValid()) - return replyDesktopFile.value(); - - - return ""; -} diff --git a/src/modules/dock/dbushandler.h b/src/modules/dock/dbushandler.h deleted file mode 100644 index ff700ac..0000000 --- a/src/modules/dock/dbushandler.h +++ /dev/null @@ -1,79 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef DBUSHANDLER_H -#define DBUSHANDLER_H - -#include "dbuslauncher.h" -#include "dbuslauncherfront.h" -#include "dbuswm.h" -#include "dbuswmswitcher.h" -#include "dbuskwaylandwindowmanager.h" -#include "windowinfok.h" -#include "dbusplasmawindow.h" -#include "dbusxeventmonitor.h" - -#include -#include -#include - -class Dock; - -// 处理DBus交互 -class DBusHandler : public QObject -{ - Q_OBJECT -public: - explicit DBusHandler(Dock *_dock, QObject *parent = nullptr); - - /************************* KWayland/WindowManager ***************************/ - void listenWaylandWMSignals(); - void loadClientList(); - bool wlShowingDesktop(); - uint wlActiveWindow(); - - /************************* daemon.Launcher1 ***************************/ - void handleLauncherItemChanged(const QString &status, LauncherItemInfo itemInfo, qlonglong categoryID); - - /************************* WMSwitcher ***************************/ - QString getCurrentWM(); - - /************************* StartManager ***************************/ - void launchApp(QString desktopFile, uint32_t timestamp, QStringList files); - void launchAppAction(QString desktopFile, QString action, uint32_t timestamp); - - /************************* AlRecorder1 ***************************/ - void markAppLaunched(const QString &filePath); - - /************************* KWayland.PlasmaWindow ***************************/ - void listenKWindowSignals(WindowInfoK *windowInfo); - PlasmaWindow *createPlasmaWindow(QString objPath); - void removePlasmaWindowHandler(PlasmaWindow *window); - - /************************* WM ***************************/ - void presentWindows(QList windows); - - /************************* bamf ***************************/ - // XWindow -> desktopFile - QString getDesktopFromWindowByBamf(XWindow windowId); - -private Q_SLOTS: - void handleWlActiveWindowChange(); - void onActiveWindowButtonRelease(int type, int x, int y, const QString &key); - -private: - Dock *m_dock; - QDBusConnection m_session; - - LauncherBackEnd *m_launcherEnd; - LauncherFront *m_launcherFront; - com::deepin::WM *m_wm; - org::deepin::dde::WMSwitcher1 *m_wmSwitcher; - org::deepin::dde::kwayland1::WindowManager *m_kwaylandManager; - - org::deepin::dde::XEventMonitor1 *m_xEventMonitor; - QString m_activeWindowMonitorKey; -}; - -#endif // DBUSHANDLER_H diff --git a/src/modules/dock/dock.cpp b/src/modules/dock/dock.cpp deleted file mode 100644 index 2638b70..0000000 --- a/src/modules/dock/dock.cpp +++ /dev/null @@ -1,1642 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "dock.h" -#include "windowidentify.h" -#include "windowinfok.h" -#include "xcbutils.h" -#include "dbushandler.h" -#include "appinfo.h" -#include "waylandmanager.h" -#include "x11manager.h" -#include "windowinfobase.h" -#include "dbusplasmawindow.h" -#include "impl/application_manager.h" - -#include "macro.h" - -#include -#include -#include - -#define SETTING DockSettings::instance() -#define XCB XCBUtils::instance() - -bool shouldShowEntry(Entry *entry) -{ - auto app = entry->getApp(); - if (app && app->isValidApp()) { - QString path = entry->getApp()->getFileName(); - DesktopInfo desktopInfo(path.toStdString()); - return desktopInfo.shouldShow(); - } - return false; -} - -Dock::Dock(ApplicationManager *applicationManager, QObject *parent) - : SynModule(parent) - , m_entriesSum(0) - , m_windowIdentify(new WindowIdentify(this)) - , m_entries(new Entries(this)) - , m_ddeLauncherVisible(false) - , m_hideState(HideState::Unknown) - , m_activeWindow(nullptr) - , m_activeWindowOld(nullptr) - , m_dbusHandler(new DBusHandler(this)) - , m_windowOperateMutex(QMutex(QMutex::NonRecursive)) - , m_showRecent(false) - , m_showMultiWindow(false) - , m_applicationManager(applicationManager) -{ - registeModule("dock"); - - if (isWaylandSession()) { - // wayland env - m_isWayland = true; - m_waylandManager = new WaylandManager(this); - m_dbusHandler->listenWaylandWMSignals(); - } else if (isX11Session()) { - // x11 env - m_isWayland = false; - m_x11Manager = new X11Manager(this); - } else { - qFatal("Unknown XDG_SESSION_TYPE '%s'", sessionType().constData()); - } - - initSettings(); - initEntries(); - - // 初始化智能隐藏定时器 - m_smartHideTimer = new QTimer(this); - m_smartHideTimer->setSingleShot(true); - connect(m_smartHideTimer, &QTimer::timeout, this, &Dock::smartHideModeTimerExpired); - - if (!m_isWayland) { - std::thread thread([&] { - // Xlib方式 - m_x11Manager->listenXEventUseXlib(); - // XCB方式 - //listenXEventUseXCB(); - }); - thread.detach(); - m_x11Manager->listenRootWindowXEvent(); - connect(m_x11Manager, &X11Manager::requestUpdateHideState, this, &Dock::updateHideState); - connect(m_x11Manager, &X11Manager::requestHandleActiveWindowChange, this, &Dock::handleActiveWindowChanged); - connect(m_x11Manager, &X11Manager::requestAttachOrDetachWindow, this, &Dock::attachOrDetachWindow); - } -} - -Dock::~Dock() -{ - -} - -/** - * @brief Dock::dockEntry 驻留应用 - * @param entry 应用实例 - * @return - */ -bool Dock::dockEntry(Entry *entry, bool moveToEnd) -{ - if (entry->getIsDocked()) - return false; - - AppInfo *app = entry->getApp(); - auto needScratchDesktop = [&]{ - if (!app) { - qInfo() << "needScratchDesktop: yes, appInfo is nil"; - return true; - } - - if (app->isInstalled()) { - qInfo() << "needScratchDesktop: no, desktop is installed"; - return false; - } - - if (app->getFileName().contains(scratchDir)) { - qInfo() << "needScratchDesktop: no, desktop in scratchDir"; - return false; - } - - return true; - }; - - - if (needScratchDesktop()) { - // 创建scratch Desktop file - QDir dir; - if (!dir.mkpath(scratchDir)) { - qWarning() << "create scratch Desktopfile failed"; - return false; - } - - QFile file; - QString newDesktopFile; - if (app) { - QString newFile = scratchDir + app->getInnerId() + ".desktop"; - // 在目标文件存在的情况下,先删除,防止出现驻留不成功的情况 - if (QFile::exists(newFile)) - QFile::remove(newFile); - if (file.copy(app->getFileName(), newFile)) - newDesktopFile = newFile; - } else { - WindowInfoBase *current = entry->getCurrentWindowInfo(); - if (current) { - QString appId = current->getInnerId(); - QString title = current->getDisplayName(); - QString icon = current->getIcon(); - if (icon.isEmpty()) - icon = "application-default-icon"; - - QString scriptContent = entry->getExec(false); - QString scriptFile = scratchDir + appId + ".sh"; - file.setFileName(scriptFile); - if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { - file.write(scriptContent.toStdString().c_str(), scriptContent.size()); - file.close(); - } - - // createScratchDesktopFile - QString cmd = scriptFile + " %U"; - QString fileNmae = scratchDir + appId + ".desktop"; - QString desktopContent = QString(dockedItemTemplate).arg(title).arg(cmd).arg(icon); - file.setFileName(fileNmae); - if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { - file.write(desktopContent.toStdString().c_str(), desktopContent.size()); - file.close(); - newDesktopFile = fileNmae; - } - } - } - - if (newDesktopFile.isEmpty()) - return false; - - app = new AppInfo(newDesktopFile); - entry->setApp(app); - entry->updateIcon(); - entry->setInnerId(app->getInnerId()); - } - - // 如果是最近打开应用,通过右键菜单的方式驻留,且当前是时尚模式,那么就让entry驻留到末尾 - if (moveToEnd && SETTING->getDisplayMode() == DisplayMode::Fashion) - m_entries->moveEntryToLast(entry); - - entry->setIsDocked(true); - entry->updateMenu(); - entry->updateMode(); - return true; -} - -/** - * @brief Dock::undockEntry 取消驻留 - * @param entry 应用实例 - */ -void Dock::undockEntry(Entry *entry, bool moveToEnd) -{ - if (!entry->getIsDocked()) { - qInfo() << "undockEntry: " << entry->getId() << " is not docked"; - // 当应用图标在最近打开区域的时候,此时该应用是未驻留的应用,如果该最近打开应用没有打开窗口,将这个图标 - // 拖动到回收站了,此时调用的是undock方法,根据需求,需要将该图标删除 - if (!entry->hasWindow()) { - // 没有子窗口的情况下,从列表中移除 - removeAppEntry(entry); - saveDockedApps(); - } - return; - } - - if (!entry->getApp()) { - qInfo() << "undockEntry: entry appInfo is nullptr"; - return; - } - - // 移除scratchDir目录下相关文件 - QString desktopFile = entry->getFileName(); - QString filebase(desktopFile.data(), desktopFile.size() - 9); - if (desktopFile.contains(scratchDir)) { - QStringList suffixs {".desktop", ".sh", ".png"}; - for (auto &ext : suffixs) { - QString fileName = filebase + ext; - QFile file(fileName); - if (file.exists()) { - file.remove(); - } - } - } - - if (entry->hasWindow()) { - // 移除驻留后,如果当前应用存在子窗口,那么会将移除最近使用应用中最后一个没有子窗口的窗口 - m_entries->removeLastRecent(); - if (desktopFile.contains(scratchDir) && entry->getCurrentWindowInfo()) { - QFileInfo info(desktopFile); - QString baseName = info.completeBaseName(); - if (baseName.startsWith(windowHashPrefix)) { - // desktop base starts with w: - // 由于有 Pid 识别方法在,在这里不能用 m.identifyWindow 再次识别 - entry->setInnerId(entry->getCurrentWindowInfo()->getInnerId()); - entry->setApp(nullptr); // 此处设置Entry的app为空, 在Entry中调用app相关信息前判断指针是否为空 - } else { - // desktop base starts with d: - QString innerId; - AppInfo *app = m_windowIdentify->identifyWindow(entry->getCurrentWindowInfo(), innerId); - // TODO update entry's innerId - entry->setApp(app); - entry->setInnerId(innerId); - } - } - // 如果存在窗口,在时尚模式下,就会移动到最近打开区域,此时让它移动到最后 - if (moveToEnd && SETTING->getDisplayMode() == DisplayMode::Fashion) - m_entries->moveEntryToLast(entry); - - entry->updateIcon(); - entry->setIsDocked(false); - entry->updateName(); - entry->updateMenu(); - // 更新模式, 是在应用区域还是在最近打开区域 - entry->updateMode(); - } else { - // 直接移除 - removeAppEntry(entry); - } - - saveDockedApps(); -} - -/** - * @brief Dock::allocEntryId 分配应用实例id - * @return - */ -QString Dock::allocEntryId() -{ - return QString("e%1T%2").arg(++m_entriesSum).arg(QString::number(QDateTime::currentSecsSinceEpoch(), 16)); -} - -/** - * @brief Dock::shouldShowOnDock 判断是否应该显示到任务栏 - * @param info - * @return - */ -bool Dock::shouldShowOnDock(WindowInfoBase *info) -{ - if (info->getWindowType() == "X11") { - XWindow winId = info->getXid(); - bool isReg = m_x11Manager->findWindowByXid(winId); - bool isContainedInClientList = m_clientList.indexOf(winId) != -1; - bool shouldSkip = info->shouldSkip(); - bool isGood = XCB->isGoodWindow(winId); - qInfo() << "shouldShowOnDock X11: isReg:" << isReg << " isContainedInClientList:" << isContainedInClientList << " shouldSkip:" << shouldSkip << " isGood:" << isGood; - - return isReg && isContainedInClientList && isGood && !shouldSkip; - } else if (info->getWindowType() == "Wayland") { - return !info->shouldSkip(); - } - - return false; -} - -/** - * @brief Dock::setDdeLauncherVisible 记录当前启动器是否可见 - * @param visible - */ -void Dock::setDdeLauncherVisible(bool visible) -{ - m_ddeLauncherVisible = visible; -} - -/** - * @brief Dock::getWMName 获取窗管名称 - * @return - */ -QString Dock::getWMName() -{ - return m_wmName; -} - -/** - * @brief Dock::setWMName 设置窗管名称 - * @param name 窗管名称 - */ -void Dock::setWMName(QString name) -{ - m_wmName = name; -} - -/** - * @brief Dock::setSyncConfig 同步配置 TODO - * @param ba 配置数据 - */ -void Dock::setSyncConfig(QByteArray ba) -{ - -} - -/** - * @brief Dock::getSyncConfig 获取配置 TODO - * @return 配置数据 - */ -QByteArray Dock::getSyncConfig() -{ - return QByteArray(); -} - -/** - * @brief Dock::createPlasmaWindow 创建wayland下窗口 - * @param objPath - * @return - */ -PlasmaWindow *Dock::createPlasmaWindow(QString objPath) -{ - return m_dbusHandler->createPlasmaWindow(objPath); -} - -/** - * @brief Dock::listenKWindowSignals - * @param windowInfo - */ -void Dock::listenKWindowSignals(WindowInfoK *windowInfo) -{ - m_dbusHandler->listenKWindowSignals(windowInfo); -} - -/** - * @brief Dock::removePlasmaWindowHandler 关闭窗口后需求对应的connect - * @param window - */ -void Dock::removePlasmaWindowHandler(PlasmaWindow *window) -{ - m_dbusHandler->removePlasmaWindowHandler(window); -} - -/** - * @brief Dock::presentWindows 显示窗口 - * @param windows 窗口id - */ -void Dock::presentWindows(QList windows) -{ - m_dbusHandler->presentWindows(windows); -} - -/** - * @brief Dock::getDockHideMode 获取任务栏隐藏模式 一直显示/一直隐藏/智能隐藏 - * @return - */ -HideMode Dock::getDockHideMode() -{ - return SETTING->getHideMode(); -} - -/** - * @brief Dock::isActiveWindow 判断是否为活动窗口 - * @param win - * @return - */ -bool Dock::isActiveWindow(const WindowInfoBase *win) -{ - if (!win) - return false; - - return win == getActiveWindow(); -} - -/** - * @brief Dock::getActiveWindow 获取当前活跃窗口 - * @return - */ -WindowInfoBase *Dock::getActiveWindow() -{ - if (!m_activeWindow) - return m_activeWindowOld; - - return m_activeWindow; - -} - -void Dock::doActiveWindow(XWindow xid) -{ - // 修改当前工作区为指定窗口的工作区 - XWindow winWorkspace = XCB->getWMDesktop(xid); - XWindow currentWorkspace = XCB->getCurrentWMDesktop(); - if (winWorkspace != currentWorkspace) { - qInfo() << "doActiveWindow: change currentWorkspace " << currentWorkspace << " to winWorkspace " << winWorkspace; - - // 获取窗口时间 - uint32_t timestamp = XCB->getWMUserTime(xid); - // 修改当前桌面工作区 - XCB->changeCurrentDesktop(winWorkspace, timestamp); - } - - XCB->changeActiveWindow(xid); - QTimer::singleShot(50, [&] { - XCB->restackWindow(xid); - }); -} - -/** - * @brief Dock::getClientList 获取窗口client列表 - * @return - */ -QList Dock::getClientList() -{ - return QList(m_clientList); -} - -/** - * @brief Dock::setClientList 设置窗口client列表 - */ -void Dock::setClientList(QList value) -{ - m_clientList = value; -} - -/** - * @brief Dock::closeWindow 关闭窗口 - * @param windowId 窗口id - */ -void Dock::closeWindow(uint32_t windowId) -{ - qInfo() << "Close Window " << windowId; - if (m_isWayland) { - WindowInfoK *info = m_waylandManager->findWindowByXid(windowId); - if (info) - info->close(0); - } else { - XCB->requestCloseWindow(windowId, 0); - } -} - -/** - * @brief Dock::getEntryIDs 获取所有应用Id - * @return - */ -QStringList Dock::getEntryIDs() -{ - return m_entries->getEntryIDs(); -} - -/** - * @brief Dock::setFrontendWindowRect 设置任务栏Rect - * @param x - * @param y - * @param width - * @param height - */ -void Dock::setFrontendWindowRect(int32_t x, int32_t y, uint width, uint height) -{ - if (m_frontendWindowRect == QRect(x, y, width, height)) { - qInfo() << "SetFrontendWindowRect: no changed"; - return; - } - - m_frontendWindowRect.setX(x); - m_frontendWindowRect.setY(y); - m_frontendWindowRect.setWidth(width); - m_frontendWindowRect.setHeight(height); - updateHideState(false); - - Q_EMIT frontendWindowRectChanged(m_frontendWindowRect); -} - -/** - * @brief Dock::isDocked 应用是否驻留 - * @param desktopFile - * @return - */ -bool Dock::isDocked(const QString desktopFile) -{ - auto entry = getDockedEntryByDesktopFile(desktopFile); - return !!entry; -} - -/** - * @brief Dock::requestDock 驻留应用 - * @param desktopFile desktopFile全路径 - * @param index - * @return - */ -bool Dock::requestDock(QString desktopFile, int index) -{ - qInfo() << "RequestDock: " << desktopFile; - AppInfo *app = new AppInfo(desktopFile); - if (!app || !app->isValidApp()) { - qInfo() << "RequestDock: invalid desktopFile"; - return false; - } - - Entry *entry = m_entries->getByInnerId(app->getInnerId()); - if (!entry) - entry = new Entry(this, app, app->getInnerId()); - - if (!dockEntry(entry)) - return false; - - entry->startExport(); - m_entries->insert(entry, index); - - saveDockedApps(); - return true; -} - -/** - * @brief Dock::requestUndock 取消驻留应用 - * @param desktopFile desktopFile文件全路径 - * @return - */ -bool Dock::requestUndock(QString desktopFile) -{ - auto entry = getDockedEntryByDesktopFile(desktopFile); - if (!entry) - return false; - - undockEntry(entry); - return true; -} - -void Dock::setShowRecent(bool visible) -{ - if (visible == m_showRecent) - return; - - SETTING->setShowRecent(visible); - onShowRecentChanged(visible); -} - -bool Dock::showRecent() const -{ - return m_showRecent; -} - -void Dock::setShowMultiWindow(bool visible) -{ - if (m_showMultiWindow == visible) - return; - - SETTING->setShowMultiWindow(visible); - onShowMultiWindowChanged(visible); -} - -bool Dock::showMultiWindow() const -{ - return m_showMultiWindow; -} - -/** - * @brief Dock::moveEntry 移动驻留程序顺序 - * @param oldIndex - * @param newIndex - */ -void Dock::moveEntry(int oldIndex, int newIndex) -{ - m_entries->move(oldIndex, newIndex); - saveDockedApps(); -} - -/** - * @brief Dock::isOnDock 是否在任务栏 - * @param desktopFile desktopFile文件全路径 - * @return - */ -bool Dock::isOnDock(QString desktopFile) -{ - return m_entries->getByDesktopFilePath(desktopFile); -} - -/** - * @brief Dock::queryWindowIdentifyMethod 查询窗口识别方式 - * @param windowId 窗口id - * @return - */ -QString Dock::queryWindowIdentifyMethod(XWindow windowId) -{ - return m_entries->queryWindowIdentifyMethod(windowId); -} - -/** - * @brief Dock::getDockedAppsDesktopFiles 获取驻留应用desktop文件 - * @return - */ -QStringList Dock::getDockedAppsDesktopFiles() -{ - QStringList ret; - for (auto entry: m_entries->filterDockedEntries()) { - ret << entry->getFileName(); - } - - return ret; -} - -/** - * @brief Dock::getPluginSettings 获取任务栏插件配置 - * @return - */ -QString Dock::getPluginSettings() -{ - return SETTING->getPluginSettings(); -} - -/** - * @brief Dock::setPluginSettings 设置任务栏插件配置 - * @param jsonStr - */ -void Dock::setPluginSettings(QString jsonStr) -{ - SETTING->setPluginSettings(jsonStr); -} - -/** - * @brief Dock::mergePluginSettings 合并任务栏插件配置 - * @param jsonStr - */ -void Dock::mergePluginSettings(QString jsonStr) -{ - SETTING->mergePluginSettings(jsonStr); -} - -/** - * @brief Dock::removePluginSettings 移除任务栏插件配置 - * @param pluginName - * @param settingkeys - */ -void Dock::removePluginSettings(QString pluginName, QStringList settingkeys) -{ - SETTING->removePluginSettings(pluginName, settingkeys); -} - -/** - * @brief Dock::smartHideModeTimerExpired 设置智能隐藏 - */ -void Dock::smartHideModeTimerExpired() -{ - HideState state = shouldHideOnSmartHideMode() ? HideState::Hide : HideState::Show; - qInfo() << "smartHideModeTimerExpired, should hide ? " << int(state); - setPropHideState(state); -} - -/** - * @brief Dock::initSettings 初始化配置 - */ -void Dock::initSettings() -{ - qInfo() << "init dock settings"; - m_forceQuitAppStatus = SETTING->getForceQuitAppMode(); - connect(SETTING, &DockSettings::hideModeChanged, this, [ this ](HideMode mode) { - this->updateHideState(false); - }); - connect(SETTING, &DockSettings::displayModeChanged, this, [](DisplayMode mode) { - qInfo() << "display mode change to " << static_cast(mode); - }); - connect(SETTING, &DockSettings::positionModeChanged, this, [](PositionMode mode) { - qInfo() << "position mode change to " << static_cast(mode); - }); - connect(SETTING, &DockSettings::forceQuitAppChanged, this, [ this ](ForceQuitAppMode mode) { - qInfo() << "forceQuitApp change to " << int(mode); - m_forceQuitAppStatus = mode; - m_entries->updateEntriesMenu(); - }); - connect(SETTING, &DockSettings::showRecentChanged, this, &Dock::onShowRecentChanged); - connect(SETTING, &DockSettings::showMultiWindowChanged, this, &Dock::onShowMultiWindowChanged); -} - -/** - * @brief Dock::initEntries 初始化应用 - */ -void Dock::initEntries() -{ - loadAppInfos(); - initClientList(); -} - -/** - * @brief Dock::loadAppInfos 加载本地驻留和最近使用的应用信息 - */ -void Dock::loadAppInfos() -{ - // 读取是否显示最近打开应用 - m_showRecent = SETTING->showRecent(); - // 读取是否显示多开窗口拆分 - m_showMultiWindow = SETTING->showMultiWindow(); - // 初始化驻留应用信息和最近使用的应用的信息 - auto loadApps = [ this ](const QStringList &apps, bool isDocked) { - for (const QString &app : apps) { - QString path = app; - DesktopInfo info(path.toStdString()); - if (!info.isValidDesktop()) - continue; - - AppInfo *appInfo = new AppInfo(info); - Entry *entryObj = new Entry(this, appInfo, appInfo->getInnerId()); - entryObj->setIsDocked(isDocked); - entryObj->updateMode(); - entryObj->updateMenu(); - entryObj->startExport(); - m_entries->append(entryObj); - } - }; - - loadApps(SETTING->getDockedApps(), true); - QStringList recentApps = SETTING->getRecentApps(); - if (recentApps.size() > MAX_UNOPEN_RECENT_COUNT) { - QStringList tempApps = recentApps; - recentApps.clear(); - for (int i = 0; i < MAX_UNOPEN_RECENT_COUNT; i++) - recentApps << tempApps[i]; - } - loadApps(recentApps, false); - saveDockedApps(); -} - -/** - * @brief Dock::initClientList 初始化窗口列表,关联到对应应用 - */ -void Dock::initClientList() -{ - if (m_isWayland) { - m_dbusHandler->loadClientList(); - } else { - QList clients; - for (auto c : XCB->instance()->getClientList()) - clients.push_back(c); - - // 依次注册窗口 - qSort(clients.begin(), clients.end()); - m_clientList = clients; - for (auto winId : m_clientList) { - WindowInfoX *winInfo = m_x11Manager->registerWindow(winId); - attachOrDetachWindow(static_cast(winInfo)); - } - } -} - -/** - * @brief Dock::findWindowByXidX 通过id获取窗口信息 - * @param xid - * @return - */ -WindowInfoX *Dock::findWindowByXidX(XWindow xid) -{ - return m_x11Manager->findWindowByXid(xid); -} - -/** - * @brief Dock::findWindowByXidK 通过xid获取窗口 TODO wayland和x11下窗口尽量完全剥离, 不应该存在通过xid查询wayland窗口的情况 - * @param xid - * @return - */ -WindowInfoK *Dock::findWindowByXidK(XWindow xid) -{ - return m_waylandManager->findWindowByXid(xid); -} - -/** - * @brief Dock::isWindowDockOverlapX 判断X环境下窗口和任务栏是否重叠 - * @param xid - * @return - * 计算重叠条件: - * 1 窗口类型非桌面desktop - * 2 窗口透明度非0 - * 3 窗口显示在当前工作区域 - * 4 窗口和任务栏rect存在重叠区域 - */ -bool Dock::isWindowDockOverlapX(XWindow xid) -{ - // 检查窗口类型 - auto desktopType = XCB->getAtom("_NET_WM_WINDOW_TYPE_DESKTOP"); - for (auto ty : XCB->getWMWindoType(xid)) { - if (ty == desktopType) { - // 不处理桌面窗口属性 - return false; - } - } - - // TODO 检查窗口透明度 - // 检查窗口是否显示 - auto wmHiddenType = XCB->getAtom("_NET_WM_STATE_HIDDEN"); - for (auto ty : XCB->getWMState(xid)) { - if (ty == wmHiddenType) { - // 不处理隐藏的窗口属性 - return false; - } - } - - // 检查窗口是否在当前工作区 - uint32_t wmDesktop = XCB->getWMDesktop(xid); - uint32_t currentDesktop = XCB->getCurrentWMDesktop(); - if (wmDesktop != currentDesktop) { - qInfo() << "isWindowDockOverlapX: wmDesktop:" << wmDesktop << " is not equal to currentDesktop:" << currentDesktop; - return false; - } - - // 检查窗口和任务栏窗口是否存在重叠 - auto winRect = XCB->getWindowGeometry(xid); - return hasInterSectionX(winRect, m_frontendWindowRect); -} - -/** - * @brief Dock::hasInterSectionX 检查窗口重叠区域 - * @param windowRect 活动窗口 - * @param dockRect 任务栏窗口 - * @return - */ -bool Dock::hasInterSectionX(const Geometry &windowRect, QRect dockRect) -{ - int ltX = MAX(windowRect.x, dockRect.x()); - int ltY = MAX(windowRect.y, dockRect.y()); - int rbX = MIN(windowRect.x + windowRect.width, dockRect.x() + dockRect.width()); - int rbY = MIN(windowRect.y + windowRect.height, dockRect.y() + dockRect.height()); - - return (ltX < rbX) && (ltY < rbY); -} - -/** - * @brief Dock::isWindowDockOverlapK 判断Wayland环境下窗口和任务栏是否重叠 - * @param info - * @return - */ -bool Dock::isWindowDockOverlapK(WindowInfoBase *info) -{ - WindowInfoK *infoK = static_cast(info); - if (!infoK) { - qInfo() << "isWindowDockOverlapK: infoK is nullptr"; - return false; - } - - DockRect rect = infoK->getGeometry(); - bool isActiveWin = infoK->getPlasmaWindow()->IsActive(); - QString appId = infoK->getAppId(); - if (!isActiveWin) { - qInfo() << "isWindowDockOverlapK: check window " << appId << " is not active"; - return false; - } - - QStringList appList = {"dde-desktop", "dde-lock", "dde-shutdown"}; - if (appList.contains(appId)) { - qInfo() << "isWindowDockOverlapK: appId in white list"; - return false; - } - - return hasInterSectionK(rect, m_frontendWindowRect); -} - -/** - * @brief Dock::hasInterSectionK Wayland环境下判断活动窗口和任务栏区域是否重叠 - * @param windowRect 活动窗口 - * @param dockRect 任务栏窗口 - * @return - */ -bool Dock::hasInterSectionK(const DockRect &windowRect, QRect dockRect) -{ - int position = getPosition(); - int ltX = MAX(windowRect.X, dockRect.x()); - int ltY = MAX(windowRect.Y, dockRect.y()); - int rbX = MIN(windowRect.X + windowRect.Width, dockRect.x() + dockRect.width()); - int rbY = MIN(windowRect.Y + windowRect.Height, dockRect.y() + dockRect.height()); - - if (position == int(PositionMode::Left) || position == int(PositionMode::Right)) - return ltX <= rbX && ltY < rbY; - - if (position == int(PositionMode::Top) || position == int(PositionMode::Bottom)) - return ltX < rbX && ltY <= rbY; - - return ltX < rbX && ltY < rbY; -} - -/** - * @brief Dock::getDockedEntryByDesktopFile 获取应用实例 - * @param desktopFile desktopFile文件全路径 - * @return - */ -Entry *Dock::getDockedEntryByDesktopFile(const QString &desktopFile) -{ - return m_entries->getDockedEntryByDesktopFile(desktopFile); -} - -/** - * @brief Dock::shouldHideOnSmartHideMode 判断智能隐藏模式下当前任务栏是否应该隐藏 - * @return - */ -bool Dock::shouldHideOnSmartHideMode() -{ - if (!m_activeWindow || m_ddeLauncherVisible) - return false; - - if (!m_isWayland) { - XWindow activeWinId = m_activeWindow->getXid(); - - // dde launcher is invisible, but it is still active window - WMClass winClass = XCB->getWMClass(activeWinId); - if (winClass.instanceName.size() > 0 && winClass.instanceName.c_str() == ddeLauncherWMClass) { - qInfo() << "shouldHideOnSmartHideMode: active window is dde launcher"; - return false; - } - - QVector list = getActiveWinGroup(activeWinId); - for (XWindow xid : list) { - if (isWindowDockOverlapX(xid)) { - qInfo() << "shouldHideOnSmartHideMode: window has overlap"; - return true; - } - } - return false; - } - - return isWindowDockOverlapK(m_activeWindow); -} - -/** - * @brief Dock::getActiveWinGroup - * @param xid - * @return - */ -QVector Dock::getActiveWinGroup(XWindow xid) -{ - QVector ret; - ret.push_back(xid); - - std::list winList = XCB->getClientListStacking(); - if (winList.empty() - || !std::any_of(winList.begin(), winList.end(), [&](XWindow id) { return id == xid;}) // not found active window in clientListStacking" - || *winList.begin() == 0) // root window - return ret; - - uint32_t apid = XCB->getWMPid(xid); - XWindow aleaderWin = XCB->getWMClientLeader(xid); - for (auto winId : winList) { - if (winId == xid) - break; - - uint32_t pid = XCB->getWMPid(winId); - // same pid - if (apid != 0 && pid == apid) { - // ok - ret.push_back(winId); - continue; - } - - WMClass wmClass = XCB->getWMClass(winId); - // same wmclass - if (wmClass.className.size() > 0 && wmClass.className.c_str() == frontendWindowWmClass) { - // skip over fronted window - continue; - } - - uint32_t leaderWin = XCB->getWMClientLeader(winId); - // same leaderWin - if (aleaderWin != 0 && aleaderWin == leaderWin) { - // ok - ret.push_back(winId); - continue; - } - - // above window - XWindow aboveWinId = 0; - for (auto iter = winList.begin(); iter != winList.end(); iter++) { - if (*iter == winId) { - aboveWinId = *++iter; - break; - } - } - - if (aboveWinId == 0) - continue; - - XWindow aboveWinTransientFor = XCB->getWMTransientFor(aboveWinId); - if (aboveWinTransientFor != 0 && aboveWinTransientFor == winId) { - // ok - ret.push_back(winId); - continue; - } - } - - return ret; -} - -/** - * @brief Dock::updateHideState 更新任务栏隐藏状态 - * @param delay - */ -void Dock::updateHideState(bool delay) -{ - if (m_ddeLauncherVisible) { - qInfo() << "updateHideState: dde launcher is visible, show dock"; - setPropHideState(HideState::Show); - } - - HideMode mode = SETTING->getHideMode(); - switch (mode) { - case HideMode::KeepShowing: - setPropHideState(HideState::Show); - break; - case HideMode::KeepHidden: - setPropHideState(HideState::Hide); - break; - case HideMode::SmartHide: - qInfo() << "reset smart hide mode timer " << delay; - m_smartHideTimer->start(delay ? smartHideTimerDelay : 0); - break; - } -} - -/** - * @brief Dock::setPropHideMode 设置隐藏属性 - * @param state - */ -void Dock::setPropHideState(HideState state) -{ - if (state == HideState::Unknown) { - qInfo() << "setPropHideState: unknown mode"; - return; - } - - if (state != m_hideState) { - m_hideState = state; - Q_EMIT hideStateChanged(static_cast(m_hideState)); - } -} - -/** - * @brief Dock::attachOrDetachWindow 关联或分离窗口 - * @param info - */ -void Dock::attachOrDetachWindow(WindowInfoBase *info) -{ - if (!info) - return; - - XWindow winId = info->getXid(); - bool shouldDock = shouldShowOnDock(info); - qInfo() << "attachOrDetachWindow: shouldDock " << shouldDock; - - // 顺序解析窗口合并或分离操作 - QMutexLocker locker(&m_windowOperateMutex); - Entry *entry = info->getEntry(); - if (entry) { - // detach - if (!shouldDock) - detachWindow(info); - else - qInfo() << "detach operate: window " << winId << "don't need to detach"; - } else { - // attach - if (info->getEntryInnerId().isEmpty()) { - // 窗口entryInnerId为空表示未识别,需要识别窗口并创建entryInnerId - qInfo() << "attach operate: window " << winId << " entryInnerId is empty, now call IdentifyWindow"; - QString innerId; - AppInfo *appInfo = m_windowIdentify->identifyWindow(info, innerId); - // 窗口entryInnerId即AppInfo的innerId, 用来将窗口和应用绑定关系 - info->setEntryInnerId(innerId); - info->setAppInfo(appInfo); - markAppLaunched(appInfo); - } else { - qInfo() << "attach operate: window " << winId << "has been identified"; - } - - // winInfo初始化后影响判断是否在任务栏显示图标,需判断 - if (shouldShowOnDock(info)) - attachWindow(info); - } - - // 在新增窗口后,同步最近打开应用到com.deepin.dde.dock.json的DConfig配置文件中 - updateRecentApps(); -} - -/** - * @brief Dock::attachWindow 关联窗口 - * @param info 窗口信息 - */ -void Dock::attachWindow(WindowInfoBase *info) -{ - // TODO: entries中存在innerid为空的entry, 导致后续新应用通过innerid获取应用一直能获取到 - Entry *entry = m_entries->getByInnerId(info->getEntryInnerId()); - if (entry) { - // entry existed - entry->attachWindow(info); - } else { - m_entries->removeLastRecent(); - entry = new Entry(this, info->getAppInfo(), info->getEntryInnerId()); - if (entry->attachWindow(info)) { - entry->startExport(); - m_entries->append(entry); - } - } -} - -/** - * @brief Dock::detachWindow 分离窗口 - * @param info 窗口信息 - */ -void Dock::detachWindow(WindowInfoBase *info) -{ - Entry *entry = m_entries->getByWindowId(info->getXid()); - if (!entry) - return; - - if (entry->detachWindow(info)) - removeEntryFromDock(entry); -} - -/** - * @brief Dock::launchApp 启动应用 - * @param timestamp 时间 - * @param files 应用打开文件 - */ -void Dock::launchApp(const QString desktopFile, uint32_t timestamp, QStringList files) -{ - m_applicationManager->LaunchApp(desktopFile, timestamp, files, false); -} - -/** - * @brief Dock::launchAppAction 启动应用响应 - * @param timestamp - * @param file - * @param section - */ -void Dock::launchAppAction(const QString desktopFile, QString action, uint32_t timestamp) -{ - m_applicationManager->LaunchAppAction(desktopFile, action ,timestamp, false); -} - -/** - * @brief Dock::is3DWM 当前窗口模式 2D/3D - * @return - */ -bool Dock::is3DWM() -{ - bool ret = false; - if (m_wmName.isEmpty()) - m_wmName = m_dbusHandler->getCurrentWM(); - - if (m_wmName == "deepin wm") - ret = true; - - return ret; -} - -/** - * @brief Dock::isWaylandEnv 当前环境 - * @return - */ -bool Dock::isWaylandEnv() -{ - return m_isWayland; -} - -/** - * @brief Dock::handleActiveWindowChangedK 处理活动窗口改变事件 wayland环境 - * @param activeWin - * @return - */ -WindowInfoK *Dock::handleActiveWindowChangedK(uint activeWin) -{ - return m_waylandManager->findWindowById(activeWin); -} - -/** - * @brief Dock::handleActiveWindowChanged 处理活动窗口改变事件 X11环境 - * @param info - */ -void Dock::handleActiveWindowChanged(WindowInfoBase *info) -{ - qInfo() << "handleActiveWindowChanged"; - if (!info) { - m_activeWindowOld = info; - m_activeWindow = nullptr; - return; - } - - m_activeWindow = info; - XWindow winId = m_activeWindow->getXid(); - m_entries->handleActiveWindowChanged(winId); - updateHideState(true); -} - -/** - * @brief Dock::saveDockedApps 保存驻留应用信息 - */ -void Dock::saveDockedApps() -{ - QStringList dockedApps; - for (auto entry : m_entries->filterDockedEntries()) { - QString path = entry->getApp()->getFileName(); - dockedApps << path; - } - - SETTING->setDockedApps(dockedApps); - - // 在驻留任务栏的时候,同时更新最近打开应用的信息 - updateRecentApps(); -} - -void Dock::updateRecentApps() -{ - QStringList unDockedApps; - QList recentEntrys = m_entries->unDockedEntries(); - for (Entry *entry : recentEntrys) { - if (shouldShowEntry(entry)) { - unDockedApps << entry->getApp()->getFileName(); - } - } - - // 保存未驻留的应用作为最近打开的应用 - SETTING->setRecentApps(unDockedApps); -} - -void Dock::removeEntryFromDock(Entry *entry) -{ - // 如果是最近打开应用 - if (m_entries->shouldInRecent()) { - // 更新entry的导出窗口信息 - entry->updateExportWindowInfos(); - // 更新entry的右键菜单的信息 - entry->updateMenu(); - // 更新entry的当前窗口的信息 - entry->setCurrentWindowInfo(nullptr); - // 移除应用后,同时更新最近打开的应用 - updateRecentApps(); - // 如果是高效模式,则发送消息或者关闭了显示最近应用的功能,则从任务栏移除 - // 或者时尚模式显示最近应用时,当前应用不应该驻留最近应用时,需要移除 - if ((SETTING->getDisplayMode() == DisplayMode::Efficient - || !m_showRecent) && !entry->getIsDocked()) { - Q_EMIT entryRemoved(entry->getId()); - } else if (SETTING->getDisplayMode() == DisplayMode::Fashion && m_showRecent && !entry->getIsDocked()) { - if (shouldShowEntry(entry)) { - return; - } - removeAppEntry(entry); - // 移除应用后,同时更新最近打开的应用 - updateRecentApps(); - } - } else { - removeAppEntry(entry); - // 移除应用后,同时更新最近打开的应用 - updateRecentApps(); - } -} - -void Dock::onShowRecentChanged(bool visible) -{ - if (m_showRecent == visible) - return; - - m_showRecent = visible; - m_entries->updateShowRecent(); - Q_EMIT showRecentChanged(visible); -} - -void Dock::onShowMultiWindowChanged(bool visible) -{ - if (m_showMultiWindow == visible) - return; - - m_showMultiWindow = visible; - Q_EMIT showMultiWindowChanged(visible); -} - -/** 移除应用实例 - * @brief Dock::removeAppEntry - * @param entry - */ -void Dock::removeAppEntry(Entry *entry) -{ - if (entry) { - m_entries->remove(entry); - } -} - -/** - * @brief Dock::handleWindowGeometryChanged 智能隐藏模式下窗口矩形变化,同步更新任务栏隐藏状态 - */ -void Dock::handleWindowGeometryChanged() -{ - if (SETTING->getHideMode() == HideMode::SmartHide) - return; - - updateHideState(false); -} - -/** - * @brief Dock::getEntryByWindowId 根据窗口id获取应用实例 - * @param windowId - * @return - */ -Entry *Dock::getEntryByWindowId(XWindow windowId) -{ - return m_entries->getByWindowId(windowId); -} - -/** - * @brief Dock::getDesktopFromWindowByBamf 通过bamf软件服务获取指定窗口的desktop文件 - * @param windowId - * @return - */ -QString Dock::getDesktopFromWindowByBamf(XWindow windowId) -{ - return m_dbusHandler->getDesktopFromWindowByBamf(windowId); -} - -/** - * @brief Dock::registerWindowWayland 注册wayland窗口 - * @param objPath - */ -void Dock::registerWindowWayland(const QString &objPath) -{ - return m_waylandManager->registerWindow(objPath); -} - -/** - * @brief Dock::unRegisterWindowWayland 取消注册wayland窗口 - * @param objPath - */ -void Dock::unRegisterWindowWayland(const QString &objPath) -{ - return m_waylandManager->unRegisterWindow(objPath); -} - -/** - * @brief Dock::isShowingDesktop - * @return - */ -bool Dock::isShowingDesktop() -{ - return m_dbusHandler->wlShowingDesktop(); -} - -/** - * @brief Dock::identifyWindow 识别窗口 - * @param winInfo - * @param innerId - * @return - */ -AppInfo *Dock::identifyWindow(WindowInfoBase *winInfo, QString &innerId) -{ - return m_windowIdentify->identifyWindow(winInfo, innerId); -} - -/** - * @brief Dock::markAppLaunched 标识应用已启动 - * @param appInfo - */ -void Dock::markAppLaunched(AppInfo *appInfo) -{ - if (!appInfo || !appInfo->isValidApp()) - return; - - QString desktopFile = appInfo->getFileName(); - qInfo() << "markAppLaunched: desktopFile is " << desktopFile; - m_dbusHandler->markAppLaunched(desktopFile); -} - -/** - * @brief Dock::getForceQuitAppStatus 获取强制关闭应用状态 - * @return - */ -ForceQuitAppMode Dock::getForceQuitAppStatus() -{ - return m_forceQuitAppStatus; -} - -/** - * @brief Dock::getWinIconPreferredApps 获取推荐的应用窗口图标 - * @return - */ -QVector Dock::getWinIconPreferredApps() -{ - return SETTING->getWinIconPreferredApps(); -} - -/** - * @brief Dock::handleLauncherItemDeleted 处理launcher item被删除信号 - * @param itemPath - */ -void Dock::handleLauncherItemDeleted(QString itemPath) -{ - for (auto entry : m_entries->filterDockedEntries()) { - if (entry->getFileName() == itemPath) { - undockEntry(entry); - break; - } - } -} - -/** - * @brief Dock::handleLauncherItemUpdated 在收到 launcher item 更新的信号后,需要更新相关信息,包括 appInfo、innerId、名称、图标、菜单。 - * @param itemPath - */ -void Dock::handleLauncherItemUpdated(QString itemPath) -{ - Entry *entry = m_entries->getByDesktopFilePath(itemPath); - if (!entry) - return; - - AppInfo *app = new AppInfo(itemPath); - entry->setApp(app); - entry->setInnerId(app->getInnerId()); - entry->updateName(); - entry->updateMenu(); - entry->forceUpdateIcon(); // 可能存在Icon图片改变,但Icon名称未改变的情况,因此强制发Icon的属性改变信号 -} - -/** - * @brief Dock::getOpacity 获取透明度 - * @return - */ -double Dock::getOpacity() -{ - return SETTING->getOpacity(); -} - -/** - * @brief Dock::getFrontendWindowRect 获取任务栏rect - * @return - */ -QRect Dock::getFrontendWindowRect() -{ - return m_frontendWindowRect; -} - -/** - * @brief Dock::getDisplayMode 获取显示模式 - * @return - */ -int Dock::getDisplayMode() -{ - return int(SETTING->getDisplayMode()); -} - -/** - * @brief Dock::setDisplayMode 设置显示模式 - * @param mode - */ -void Dock::setDisplayMode(int mode) -{ - DisplayMode displayMode = static_cast(mode); - SETTING->setDisplayMode(displayMode); - m_entries->setDisplayMode(displayMode); -} - -/** - * @brief Dock::getDockedApps 获取驻留应用 - * @return - */ -QStringList Dock::getDockedApps() -{ - return SETTING->getDockedApps(); -} - -/** - * @brief Dock::getEntryPaths 获取应用实例路径 - * @return - */ -QStringList Dock::getEntryPaths() -{ - QStringList ret; - for (auto id : m_entries->getEntryIDs()) { - ret.push_back(entryDBusObjPathPrefix + id); - } - - return ret; -} - -/** - * @brief Dock::getHideMode 获取隐藏模式 - * @return - */ -HideMode Dock::getHideMode() -{ - return SETTING->getHideMode(); -} - -/** - * @brief Dock::setHideMode 设置隐藏模式 - * @param mode - */ -void Dock::setHideMode(HideMode mode) -{ - SETTING->setHideMode(mode); -} - -/** - * @brief Dock::getHideState 获取隐藏状态 - * @return - */ -HideState Dock::getHideState() -{ - return m_hideState; -} - -/** - * @brief Dock::setHideState 设置任务栏隐藏状态 - * @param state - */ -void Dock::setHideState(HideState state) -{ - m_hideState = state; -} - -/** - * @brief Dock::getHideTimeout 获取执行隐藏动作超时时间 - * @return - */ -uint Dock::getHideTimeout() -{ - return SETTING->getHideTimeout(); -} - -/** - * @brief Dock::setHideTimeout 设置执行隐藏动作超时时间 - * @param timeout - */ -void Dock::setHideTimeout(uint timeout) -{ - SETTING->setHideTimeout(timeout); -} - -/** - * @brief Dock::getIconSize 获取应用图标大小 - * @return - */ -uint Dock::getIconSize() -{ - return SETTING->getIconSize(); -} - -/** - * @brief Dock::setIconSize 设置应用图标大小 - * @param size - */ -void Dock::setIconSize(uint size) -{ - SETTING->setIconSize(size); -} - -/** - * @brief Dock::getPosition 获取当前任务栏位置 - * @return - */ -int Dock::getPosition() -{ - return int(SETTING->getPositionMode()); -} - -/** - * @brief Dock::setPosition 设置任务栏位置 - * @param position - */ -void Dock::setPosition(int position) -{ - SETTING->setPositionMode(PositionMode(position)); -} - -/** - * @brief Dock::getShowTimeout 获取显示超时接口 - * @return - */ -uint Dock::getShowTimeout() -{ - return SETTING->getShowTimeout(); -} - -/** - * @brief Dock::setShowTimeout 设置显示超时 - * @param timeout - */ -void Dock::setShowTimeout(uint timeout) -{ - return SETTING->setShowTimeout(timeout); -} - -/** - * @brief Dock::getWindowSizeEfficient 获取任务栏高效模式大小 - * @return - */ -uint Dock::getWindowSizeEfficient() -{ - return SETTING->getWindowSizeEfficient(); -} - -/** - * @brief Dock::setWindowSizeEfficient 设置任务栏高效模式大小 - * @param size - */ -void Dock::setWindowSizeEfficient(uint size) -{ - SETTING->setWindowSizeEfficient(size); -} - -/** - * @brief Dock::getWindowSizeFashion 获取任务栏时尚模式大小 - * @return - */ -uint Dock::getWindowSizeFashion() -{ - return SETTING->getWindowSizeFashion(); -} - -/** - * @brief Dock::setWindowSizeFashion 设置任务栏时尚模式大小 - * @param size - */ -void Dock::setWindowSizeFashion(uint size) -{ - SETTING->setWindowSizeFashion(size); -} diff --git a/src/modules/dock/dock.h b/src/modules/dock/dock.h deleted file mode 100644 index 0005e03..0000000 --- a/src/modules/dock/dock.h +++ /dev/null @@ -1,194 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef DOCK_H -#define DOCK_H - -#include "synmodule.h" -#include "docksettings.h" -#include "entries.h" -#include "dbusplasmawindow.h" -#include "dockrect.h" - -#include -#include -#include - -class WindowIdentify; -class DBusHandler; -class WaylandManager; -class X11Manager; -class WindowInfoK; -class WindowInfoX; -class ApplicationManager; - -using PlasmaWindow = org::deepin::dde::kwayland1::PlasmaWindow; - -enum class HideState -{ - Unknown, - Show, - Hide, -}; - -// 任务栏 -class Dock : public SynModule -{ - Q_OBJECT -public: - explicit Dock(ApplicationManager *applicationManager, QObject *parent = nullptr); - ~Dock(); - - bool dockEntry(Entry *entry, bool moveToEnd = false); - void undockEntry(Entry *entry, bool moveToEnd = false); - QString allocEntryId(); - bool shouldShowOnDock(WindowInfoBase *info); - void setDdeLauncherVisible(bool visible); - QString getWMName(); - void setWMName(QString name); - void setPropHideState(HideState state); - void attachWindow(WindowInfoBase *info); - void detachWindow(WindowInfoBase *info); - void launchApp(const QString desktopFile, uint32_t timestamp, QStringList files); - void launchAppAction(const QString desktopFile, QString action, uint32_t timestamp); - bool is3DWM(); - bool isWaylandEnv(); - WindowInfoK *handleActiveWindowChangedK(uint activeWin); - void saveDockedApps(); - void removeAppEntry(Entry *entry); - void handleWindowGeometryChanged(); - Entry *getEntryByWindowId(XWindow windowId); - QString getDesktopFromWindowByBamf(XWindow windowId); - - void registerWindowWayland(const QString &objPath); - void unRegisterWindowWayland(const QString &objPath); - bool isShowingDesktop(); - - AppInfo *identifyWindow(WindowInfoBase *winInfo, QString &innerId); - void markAppLaunched(AppInfo *appInfo); - - ForceQuitAppMode getForceQuitAppStatus(); - QVector getWinIconPreferredApps(); - void handleLauncherItemDeleted(QString itemPath); - void handleLauncherItemUpdated(QString itemPath); - - double getOpacity(); - QRect getFrontendWindowRect(); - int getDisplayMode(); - void setDisplayMode(int mode); - QStringList getDockedApps(); - QStringList getEntryPaths(); - HideMode getHideMode(); - void setHideMode(HideMode mode); - HideState getHideState(); - void setHideState(HideState state); - uint getHideTimeout(); - void setHideTimeout(uint timeout); - uint getIconSize(); - void setIconSize(uint size); - int getPosition(); - void setPosition(int position); - uint getShowTimeout(); - void setShowTimeout(uint timeout); - uint getWindowSizeEfficient(); - void setWindowSizeEfficient(uint size); - uint getWindowSizeFashion(); - void setWindowSizeFashion(uint size); - - // 设置配置 - void setSyncConfig(QByteArray ba); - QByteArray getSyncConfig(); - - /******************************** dbus handler ****************************/ - PlasmaWindow *createPlasmaWindow(QString objPath); - void listenKWindowSignals(WindowInfoK *windowInfo); - void removePlasmaWindowHandler(PlasmaWindow *window); - void presentWindows(QList windows); - - HideMode getDockHideMode(); - bool isActiveWindow(const WindowInfoBase *win); - WindowInfoBase *getActiveWindow(); - void doActiveWindow(XWindow xid); - QList getClientList(); - void setClientList(QList value); - - void closeWindow(XWindow windowId); - QStringList getEntryIDs(); - void setFrontendWindowRect(int32_t x, int32_t y, uint width, uint height); - bool isDocked(const QString desktopFile); - bool requestDock(QString desktopFile, int index); - bool requestUndock(QString desktopFile); - void setShowRecent(bool visible); - bool showRecent() const; - void setShowMultiWindow(bool visible); - bool showMultiWindow() const; - void moveEntry(int oldIndex, int newIndex); - bool isOnDock(QString desktopFile); - QString queryWindowIdentifyMethod(XWindow windowId); - QStringList getDockedAppsDesktopFiles(); - QString getPluginSettings(); - void setPluginSettings(QString jsonStr); - void mergePluginSettings(QString jsonStr); - void removePluginSettings(QString pluginName, QStringList settingkeys); - void removeEntryFromDock(Entry *entry); - -Q_SIGNALS: - void serviceRestarted(); - void entryAdded(QDBusObjectPath entryObjPath, int index); - void entryRemoved(QString id); - void hideStateChanged(int); - void frontendWindowRectChanged(const QRect &dockRect); - void showRecentChanged(bool); - void showMultiWindowChanged(bool); - -public Q_SLOTS: - void updateHideState(bool delay); - void handleActiveWindowChanged(WindowInfoBase *info); - void smartHideModeTimerExpired(); - void attachOrDetachWindow(WindowInfoBase *info); - -private: - void initSettings(); - void initEntries(); - void loadAppInfos(); - void initClientList(); - WindowInfoX *findWindowByXidX(XWindow xid); - WindowInfoK *findWindowByXidK(XWindow xid); - bool isWindowDockOverlapX(XWindow xid); - bool hasInterSectionX(const Geometry &windowRect, QRect dockRect); - bool isWindowDockOverlapK(WindowInfoBase *info); - bool hasInterSectionK(const DockRect &windowRect, QRect dockRect); - Entry *getDockedEntryByDesktopFile(const QString &desktopFile); - bool shouldHideOnSmartHideMode(); - QVector getActiveWinGroup(XWindow xid); - void updateRecentApps(); - -private: - void onShowRecentChanged(bool visible); - void onShowMultiWindowChanged(bool visible); - -private: - WindowIdentify *m_windowIdentify; // 窗口识别 - Entries *m_entries; // 所有应用实例 - int m_entriesSum; // 累计打开的应用数量 - bool m_ddeLauncherVisible; // 前端启动器是否可见 - QString m_wmName; // 窗管名称 - WaylandManager *m_waylandManager; // wayland窗口管理 - X11Manager *m_x11Manager; // X11窗口管理 - QList m_clientList; // 所有窗口 - QRect m_frontendWindowRect; // 前端任务栏大小, 用于智能隐藏时判断窗口是否重合 - HideState m_hideState; // 记录任务栏隐藏状态 - QTimer *m_smartHideTimer; // 任务栏智能隐藏定时器 - WindowInfoBase *m_activeWindow;// 记录当前活跃窗口信息 - WindowInfoBase *m_activeWindowOld;// 记录前一个活跃窗口信息 - bool m_isWayland; // 判断是否为wayland环境 - ForceQuitAppMode m_forceQuitAppStatus; // 强制退出应用状态 - DBusHandler *m_dbusHandler; // 处理dbus交互 - QMutex m_windowOperateMutex; // 窗口合并或拆分锁 - bool m_showRecent; - bool m_showMultiWindow; - ApplicationManager *m_applicationManager; -}; - -#endif // DOCK_H diff --git a/src/modules/dock/dockmanager.cpp b/src/modules/dock/dockmanager.cpp deleted file mode 100644 index 6feca34..0000000 --- a/src/modules/dock/dockmanager.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "dockmanager.h" -#include "dock.h" -#include "impl/application_manager.h" - -#include -#include -#include - -DockManager::DockManager(ApplicationManager *parent) - : QObject(parent) - , m_dock(new Dock(parent, this)) -{ - qInfo() << "DockManager"; - m_adaptor = new DBusAdaptorDock(m_dock); - QDBusConnection con = QDBusConnection::sessionBus(); - if (!con.registerService(dbusService)) { - qWarning() << "register service Dock1 error:" << con.lastError().message(); - return; - } - - if (!con.registerObject(dbusPath, m_dock, QDBusConnection::ExportAdaptors)) { - qWarning() << "register object Dock1 error:" << con.lastError().message(); - } - - m_dock->serviceRestarted(); -} - -DockManager::~DockManager() -{ - -} diff --git a/src/modules/dock/dockmanager.h b/src/modules/dock/dockmanager.h deleted file mode 100644 index 9750508..0000000 --- a/src/modules/dock/dockmanager.h +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef DOCKMANAGER_H -#define DOCKMANAGER_H - -#include "dbusadaptordock.h" - -#include - -class Dock; -class ApplicationManager; - -// 任务栏管理类 -class DockManager : public QObject -{ - Q_OBJECT -public: - explicit DockManager(ApplicationManager *parent = nullptr); - ~DockManager(); - -private: - Dock *m_dock; - DBusAdaptorDock *m_adaptor; -}; - -#endif // DOCKMANAGER_H diff --git a/src/modules/dock/docksettings.cpp b/src/modules/dock/docksettings.cpp deleted file mode 100644 index 37e3ce0..0000000 --- a/src/modules/dock/docksettings.cpp +++ /dev/null @@ -1,387 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "docksettings.h" -#include "settings.h" - -#include - -#include -#include -#include - -DCORE_USE_NAMESPACE - -DockSettings::DockSettings(QObject *parent) - : QObject (parent) - , m_dockSettings(Settings::ConfigPtr(configDock)) - , m_appearanceSettings(Settings::ConfigPtr(configAppearance)) -{ - init(); -} - -void DockSettings::init() -{ - // 绑定属性 - if (m_dockSettings) { - connect(m_dockSettings, &DConfig::valueChanged, this, [&] (const QString &key) { - if (key == keyHideMode) { - Q_EMIT hideModeChanged(HideMode(m_dockSettings->value(key).toInt())); - } else if(key == keyDisplayMode) { - Q_EMIT displayModeChanged(DisplayMode(m_dockSettings->value(key).toInt())); - } else if (key == keyPosition) { - Q_EMIT positionModeChanged(PositionMode(m_dockSettings->value(key).toInt())); - } else if (key == keyForceQuitApp){ - QString mode = m_dockSettings->value(key).toString(); - Q_EMIT forceQuitAppChanged(ForceQuitAppModeHandler(mode).toEnum()); - } else if (key == keyShowRecent) { - Q_EMIT showRecentChanged(m_dockSettings->value(key).toBool()); - } else if (key == keyShowMultiWindow) { - Q_EMIT showMultiWindowChanged(m_dockSettings->value(key).toBool()); - } - }); - } -} - -HideMode DockSettings::getHideMode() -{ - HideMode ret = HideMode::KeepShowing; - if (m_dockSettings) { - QString mode = m_dockSettings->value(keyHideMode).toString(); - HideModeHandler handler(mode); - return handler.toEnum(); - } - return HideMode::KeepShowing; -} - -void DockSettings::setHideMode(HideMode mode) -{ - if (m_dockSettings) { - m_dockSettings->setValue(keyHideMode, HideModeHandler(mode).toString()); - } -} - -DisplayMode DockSettings::getDisplayMode() -{ - DisplayMode ret = DisplayMode::Efficient; - if (m_dockSettings) { - QString mode = m_dockSettings->value(keyDisplayMode).toString(); - DisplayModeHandler handler(mode); - return handler.toEnum(); - } - return DisplayMode::Efficient; -} - -void DockSettings::setDisplayMode(DisplayMode mode) -{ - if (m_dockSettings) { - m_dockSettings->setValue(keyDisplayMode, DisplayModeHandler(mode).toString()); - } -} - -PositionMode DockSettings::getPositionMode() -{ - PositionMode ret = PositionMode::Bottom; - if (m_dockSettings) { - QString mode = m_dockSettings->value(keyPosition).toString(); - PositionModeHandler handler(mode); - ret = handler.toEnum(); - } - return ret; -} - -void DockSettings::setPositionMode(PositionMode mode) -{ - if (m_dockSettings) { - m_dockSettings->setValue(keyPosition, PositionModeHandler(mode).toString()); - } -} - -ForceQuitAppMode DockSettings::getForceQuitAppMode() -{ - ForceQuitAppMode ret = ForceQuitAppMode::Enabled; - if (m_dockSettings) { - QString mode = m_dockSettings->value(keyForceQuitApp).toString(); - ForceQuitAppModeHandler handler(mode); - ret = handler.toEnum(); - } - return ret; -} - -void DockSettings::setForceQuitAppMode(ForceQuitAppMode mode) -{ - if (m_dockSettings) { - m_dockSettings->setValue(keyForceQuitApp, ForceQuitAppModeHandler(mode).toString()); - } -} - -uint DockSettings::getIconSize() -{ - uint size = 36; - if (m_dockSettings) { - size = m_dockSettings->value(keyIconSize).toUInt(); - } - return size; -} - -void DockSettings::setIconSize(uint size) -{ - if (m_dockSettings) { - m_dockSettings->setValue(keyIconSize, size); - } -} - -uint DockSettings::getShowTimeout() -{ - uint time = 100; - if (m_dockSettings) { - time = m_dockSettings->value(keyShowTimeout).toUInt(); - } - return time; -} - -void DockSettings::setShowTimeout(uint time) -{ - if (m_dockSettings) { - m_dockSettings->setValue(keyShowTimeout, time); - } -} - -uint DockSettings::getHideTimeout() -{ - uint time = 0; - if (m_dockSettings) { - time = m_dockSettings->value(keyHideTimeout).toUInt(); - } - return time; -} - -void DockSettings::setHideTimeout(uint time) -{ - if (m_dockSettings) { - m_dockSettings->setValue(keyHideTimeout, time); - } -} - -uint DockSettings::getWindowSizeEfficient() -{ - uint size = 40; - if (m_dockSettings) { - size = m_dockSettings->value(keyWindowSizeEfficient).toUInt(); - } - return size; -} - -void DockSettings::setWindowSizeEfficient(uint size) -{ - if (m_dockSettings) { - m_dockSettings->setValue(keyWindowSizeEfficient, size); - } -} - -uint DockSettings::getWindowSizeFashion() -{ - uint size = 48; - if (m_dockSettings) { - size = m_dockSettings->value(keyWindowSizeFashion).toUInt(); - } - return size; -} - -void DockSettings::setWindowSizeFashion(uint size) -{ - if (m_dockSettings) { - m_dockSettings->setValue(keyWindowSizeFashion, size); - } -} - -void DockSettings::saveStringList(const QString &key, const QStringList &values) -{ - if (!m_dockSettings) - return; - - m_dockSettings->setValue(key, values); -} - -QStringList DockSettings::loadStringList(const QString &key) const -{ - QStringList ret; - if (!m_dockSettings) - return ret; - - for(const auto &var : m_dockSettings->value(key).toList()) { - if (var.isValid()) - ret.push_back(var.toString()); - } - - return ret; -} - -QStringList DockSettings::getDockedApps() -{ - return loadStringList(keyDockedApps); -} - -void DockSettings::setDockedApps(const QStringList &apps) -{ - saveStringList(keyDockedApps, apps); -} - -QStringList DockSettings::getRecentApps() const -{ - return loadStringList(keyRecentApp); -} - -void DockSettings::setRecentApps(const QStringList &apps) -{ - saveStringList(keyRecentApp, apps); -} - -double DockSettings::getOpacity() -{ - double opacity = 0.4; - if (m_appearanceSettings) { - opacity = m_appearanceSettings->value(keyOpacity).toDouble(); - } - return opacity; -} - -QVector DockSettings::getWinIconPreferredApps() -{ - QVector ret; - if (m_dockSettings) { - for(const auto &var : m_dockSettings->value(keyWinIconPreferredApps).toList()) { - if (var.isValid()) - ret.push_back(var.toString()); - } - } - - return ret; -} - -void DockSettings::setShowRecent(bool visible) -{ - if (!m_dockSettings) - return; - - m_dockSettings->setValue(keyShowRecent, visible); -} - -bool DockSettings::showRecent() const -{ - if (!m_dockSettings) - return false; - - return m_dockSettings->value(keyShowRecent).toBool(); -} - -void DockSettings::setShowMultiWindow(bool showMultiWindow) -{ - if (!m_dockSettings) - return; - - m_dockSettings->setValue(keyShowMultiWindow, showMultiWindow); -} - -bool DockSettings::showMultiWindow() const -{ - if (!m_dockSettings) - return false; - - return m_dockSettings->value(keyShowMultiWindow).toBool(); -} - -QString DockSettings::getPluginSettings() -{ - QString ret; - if (m_dockSettings) { - ret = m_dockSettings->value(keyPluginSettings).toString(); - } - - qInfo() << "getpluginsettings:" << ret; - return ret; -} - -void DockSettings::setPluginSettings(QString jsonStr) -{ - if (jsonStr.isEmpty()) - return; - - if (m_dockSettings) { - m_dockSettings->setValue(keyPluginSettings, jsonStr); - } -} - -void DockSettings::mergePluginSettings(QString jsonStr) -{ - QString origin = getPluginSettings(); - QJsonObject originSettings = plguinSettingsStrToObj(origin); - QJsonObject needMergeSettings = plguinSettingsStrToObj(jsonStr); - for (auto pluginsIt = needMergeSettings.begin(); pluginsIt != needMergeSettings.end(); pluginsIt++) { - const QString &pluginName = pluginsIt.key(); - const QJsonObject &needMergeSettingsObj = pluginsIt.value().toObject(); - QJsonObject originSettingsObj = originSettings.value(pluginName).toObject(); - for (auto settingsIt = needMergeSettingsObj.begin(); settingsIt != needMergeSettingsObj.end(); settingsIt++) { - originSettingsObj.insert(settingsIt.key(), settingsIt.value()); - } - - // 重写plugin对应的设置 - originSettings.remove(pluginName); - originSettings.insert(pluginName, originSettingsObj); - } - - setPluginSettings(QJsonDocument(originSettings).toJson(QJsonDocument::JsonFormat::Compact)); -} - -void DockSettings::removePluginSettings(QString pluginName, QStringList settingkeys) -{ - if (pluginName.isEmpty()) - return; - - QString origin = getPluginSettings(); - QJsonObject originSettings = plguinSettingsStrToObj(origin); - if (settingkeys.size() == 0) { - originSettings.remove(pluginName); - } else { - for (auto pluginsIt = originSettings.begin(); pluginsIt != originSettings.end(); pluginsIt++) { - const QString &pluginName = pluginsIt.key(); - if (pluginName != pluginName) - continue; - - QJsonObject originSettingsObj = originSettings.value(pluginName).toObject(); - for (const auto &key : settingkeys) { - originSettingsObj.remove(key); - } - - // 重写plugin对应的设置 - originSettings.remove(pluginName); - originSettings.insert(pluginName, originSettingsObj); - } - } - - setPluginSettings(QJsonDocument(originSettings).toJson(QJsonDocument::JsonFormat::Compact)); -} - -// 借鉴自dde-dock -QJsonObject DockSettings::plguinSettingsStrToObj(QString jsonStr) -{ - QJsonObject ret; - const QJsonObject &pluginSettingsObject = QJsonDocument::fromJson(jsonStr.toLocal8Bit()).object(); - if (pluginSettingsObject.isEmpty()) { - return ret; - } - - for (auto pluginsIt = pluginSettingsObject.constBegin(); pluginsIt != pluginSettingsObject.constEnd(); ++pluginsIt) { - const QString &pluginName = pluginsIt.key(); - const QJsonObject &settingsObject = pluginsIt.value().toObject(); - QJsonObject newSettingsObject = ret.value(pluginName).toObject(); - for (auto settingsIt = settingsObject.constBegin(); settingsIt != settingsObject.constEnd(); ++settingsIt) { - newSettingsObject.insert(settingsIt.key(), settingsIt.value()); - } - // TODO: remove not exists key-values - ret.insert(pluginName, newSettingsObject); - } - - return ret; -} diff --git a/src/modules/dock/docksettings.h b/src/modules/dock/docksettings.h deleted file mode 100644 index e2452b5..0000000 --- a/src/modules/dock/docksettings.h +++ /dev/null @@ -1,260 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef DOCKSETTINGS_H -#define DOCKSETTINGS_H - -#include "common.h" - -#include - -// 隐藏模式 -enum class HideMode { - KeepShowing, - KeepHidden, - SmartHide -}; - -class HideModeHandler { - HideMode modeEnum; - QString modeStr; - -public: - HideModeHandler(HideMode mode) : modeEnum(mode), modeStr("") {} - HideModeHandler(QString mode) : modeEnum(HideMode::KeepShowing), modeStr(mode) {} - - bool equal(HideModeHandler hideMode) { - return toString() == hideMode.toString() || toEnum() == hideMode.toEnum(); - } - - QString toString() { - switch (modeEnum) { - case HideMode::KeepShowing: - return "keep-showing"; - case HideMode::KeepHidden: - return "keep-hidden"; - case HideMode::SmartHide: - return "smart-hide"; - } - // 默认保持始终显示 - return "keep-showing"; - } - - HideMode toEnum() { - if (modeStr == "keep-hidden") - return HideMode::KeepHidden; - if (modeStr == "smart-hide") - return HideMode::SmartHide; - - return HideMode::KeepShowing; - } -}; - -// 显示样式 -enum class DisplayMode { - Fashion, - Efficient -}; - -class DisplayModeHandler { - DisplayMode modeEnum; - QString modeStr; - -public: - DisplayModeHandler(DisplayMode mode) : modeEnum(mode), modeStr("") {} - DisplayModeHandler(QString mode) : modeEnum(DisplayMode::Efficient), modeStr(mode) {} - - bool equal(DisplayModeHandler displayMode) { - return toString() == displayMode.toString() || toEnum() == displayMode.toEnum(); - } - - QString toString() { - switch (modeEnum) { - case DisplayMode::Fashion: - return "fashion"; - case DisplayMode::Efficient: - return "efficient"; - } - } - - DisplayMode toEnum() { - if (modeStr == "fashion") - return DisplayMode::Fashion; - - return DisplayMode::Efficient; - } -}; - -// 显示位置 -enum class PositionMode { - Top, // 上 - Right, // 右 - Bottom, // 下 - Left // 左 -}; - -class PositionModeHandler { - PositionMode modeEnum; - QString modeStr; - -public: - PositionModeHandler(PositionMode mode) : modeEnum(mode), modeStr("") {} - PositionModeHandler(QString mode) : modeEnum(PositionMode::Bottom), modeStr(mode) {} - - bool equal(PositionModeHandler displayMode) { - return toString() == displayMode.toString() || toEnum() == displayMode.toEnum(); - } - - QString toString() { - switch (modeEnum) { - case PositionMode::Top: - return "top"; - case PositionMode::Right: - return "right"; - case PositionMode::Left: - return "left"; - case PositionMode::Bottom: - return "bottom"; - } - } - - PositionMode toEnum() { - if (modeStr == "top") - return PositionMode::Top; - if (modeStr == "right") - return PositionMode::Right; - if (modeStr == "bottom") - return PositionMode::Bottom; - if (modeStr == "left") - return PositionMode::Left; - - return PositionMode::Bottom; - } -}; - -// 强制退出应用菜单状态 -enum class ForceQuitAppMode { - Enabled, // 开启 - Disabled, // 关闭 - Deactivated, // 置灰 -}; - -class ForceQuitAppModeHandler { - ForceQuitAppMode modeEnum; - QString modeStr; - -public: - ForceQuitAppModeHandler(ForceQuitAppMode mode) : modeEnum(mode), modeStr("") {} - ForceQuitAppModeHandler(QString mode) : modeEnum(ForceQuitAppMode::Enabled), modeStr(mode) {} - - bool equal(ForceQuitAppModeHandler displayMode) { - return toString() == displayMode.toString() || toEnum() == displayMode.toEnum(); - } - - QString toString() { - switch (modeEnum) { - case ForceQuitAppMode::Enabled: - return "enabled"; - case ForceQuitAppMode::Disabled: - return "disabled"; - case ForceQuitAppMode::Deactivated: - return "deactivated"; - } - } - - ForceQuitAppMode toEnum() { - if (modeStr == "disabled") - return ForceQuitAppMode::Disabled; - if (modeStr == "deactivated") - return ForceQuitAppMode::Deactivated; - - return ForceQuitAppMode::Enabled; - } -}; - -class Settings; -namespace Dtk { -namespace Core { -class DConfig; -} -} - -using namespace Dtk::Core; - -// 任务栏组策略配置类 -class DockSettings: public QObject -{ - Q_OBJECT - -public: - static inline DockSettings *instance() { - static DockSettings instance; - return &instance; - } - void init(); - - HideMode getHideMode(); - void setHideMode(HideMode mode); - DisplayMode getDisplayMode(); - void setDisplayMode(DisplayMode mode); - PositionMode getPositionMode(); - void setPositionMode(PositionMode mode); - ForceQuitAppMode getForceQuitAppMode(); - void setForceQuitAppMode(ForceQuitAppMode mode); - uint getIconSize(); - void setIconSize(uint size); - uint getShowTimeout(); - void setShowTimeout(uint time); - uint getHideTimeout(); - void setHideTimeout(uint time); - uint getWindowSizeEfficient(); - void setWindowSizeEfficient(uint size); - uint getWindowSizeFashion(); - void setWindowSizeFashion(uint size); - QStringList getDockedApps(); - void setDockedApps(const QStringList &apps); - QStringList getRecentApps() const; - void setRecentApps(const QStringList &apps); - double getOpacity(); - QVector getWinIconPreferredApps(); - void setShowRecent(bool visible); - bool showRecent() const; - - void setShowMultiWindow(bool showMultiWindow); - bool showMultiWindow() const; - - // plugin settings - QString getPluginSettings(); - void setPluginSettings(QString jsonStr); - void mergePluginSettings(QString jsonStr); - void removePluginSettings(QString pluginName, QStringList settingkeys); - QJsonObject plguinSettingsStrToObj(QString jsonStr); - -Q_SIGNALS: - // 隐藏模式改变 - void hideModeChanged(HideMode mode); - // 显示样式改变 - void displayModeChanged(DisplayMode mode); - // 显示位置改变 - void positionModeChanged(PositionMode mode); - // 强制退出应用开关改变 - void forceQuitAppChanged(ForceQuitAppMode mode); - // 是否显示最近打开应用改变 - void showRecentChanged(bool); - // 是否显示多开应用改变 - void showMultiWindowChanged(bool); - -private: - DockSettings(QObject *paret = nullptr); - DockSettings(const DockSettings &); - DockSettings& operator= (const DockSettings &); - void saveStringList(const QString &key, const QStringList &values); - QStringList loadStringList(const QString &key) const; - -private: - DConfig *m_dockSettings; - DConfig *m_appearanceSettings; -}; - -#endif // DOCKSETTINGS_H diff --git a/src/modules/dock/entries.cpp b/src/modules/dock/entries.cpp deleted file mode 100644 index 938d36f..0000000 --- a/src/modules/dock/entries.cpp +++ /dev/null @@ -1,331 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "entries.h" -#include "dock.h" - -Entries::Entries(Dock *_dock) - : m_dock(_dock) -{ - -} - -QVector Entries::filterDockedEntries() -{ - QVector ret; - for (auto &entry : m_items) { - if (entry->isValid() && entry->getIsDocked()) - ret.push_back(entry); - } - - return ret; -} - -Entry *Entries::getByInnerId(QString innerId) -{ - Entry *ret = nullptr; - for (auto &entry : m_items) { - if (entry->getInnerId() == innerId) - ret = entry; - } - - return ret; -} - -void Entries::append(Entry *entry) -{ - insert(entry, -1); -} - -void Entries::insert(Entry *entry, int index) -{ - // 如果当前应用在列表中存在(通常是该应用为最近打开应用但是关闭了最近打开应用的接口或者当前为高效模式) - if (m_items.contains(entry)) - m_items.removeOne(entry); - - if (index < 0 || index >= m_items.size()) { - // append - index = m_items.size(); - m_items.push_back(entry); - } else { - // insert - m_items.insert(index, entry); - } - - insertCb(entry, index); -} - -void Entries::remove(Entry *entry) -{ - for (auto iter = m_items.begin(); iter != m_items.end();) { - if ((*iter)->getId() == entry->getId()) { - iter = m_items.erase(iter); - } else { - iter++; - } - } - - removeCb(entry); - delete entry; -} - -void Entries::move(int oldIndex, int newIndex) -{ - if (oldIndex == newIndex || oldIndex < 0 || newIndex < 0 || oldIndex >= m_items.size() || newIndex >= m_items.size()) - return; - - m_items.swap(oldIndex, newIndex); -} - -Entry *Entries::getByWindowPid(int pid) -{ - Entry *ret = nullptr; - for (auto &entry : m_items) { - if (entry->getWindowInfoByPid(pid)) { - ret = entry; - break; - } - } - - return ret; -} - -Entry *Entries::getByWindowId(XWindow windowId) -{ - Entry *ret = nullptr; - for (auto &entry : m_items) { - if (entry->getWindowInfoByWinId(windowId)) { - ret = entry; - break; - } - } - - return ret; -} - -Entry *Entries::getByDesktopFilePath(QString filePath) -{ - Entry *ret = nullptr; - for (auto &entry : m_items) { - if (entry->getFileName() == filePath) { - ret = entry; - break; - } - } - - return ret; -} - -QStringList Entries::getEntryIDs() -{ - QStringList list; - if (static_cast(m_dock->getDisplayMode()) == DisplayMode::Fashion - && m_dock->showRecent()) { - for (Entry *item : m_items) - list.push_back(item->getId()); - } else { - // 如果是高效模式或者没有开启显示最近应用的功能,那么未驻留并且没有子窗口的就不显示 - // 换句话说,只显示已经驻留或者有子窗口的应用 - for (Entry *item : m_items) { - if (!item->getIsDocked() && !item->hasWindow()) - continue; - list << item->getId(); - } - } - - return list; -} - -Entry *Entries::getDockedEntryByDesktopFile(const QString &desktopFile) -{ - Entry *ret = nullptr; - for (auto entry : filterDockedEntries()) { - if (!entry->isValid()) - continue; - - if (desktopFile == entry->getFileName()) { - ret = entry; - break; - } - } - - return ret; -} - -QString Entries::queryWindowIdentifyMethod(XWindow windowId) -{ - QString ret; - for (auto entry : m_items) { - auto window = entry->getWindowInfoByWinId(windowId); - if (window) { - auto app = window->getAppInfo(); - if (app) { - ret = app->getIdentifyMethod(); - } else { - ret = "Failed"; - } - break; - } - } - - return ret; -} - -void Entries::handleActiveWindowChanged(XWindow activeWindId) -{ - for (auto entry : m_items) { - auto windowInfo = entry->getWindowInfoByWinId(activeWindId); - if (windowInfo) { - entry->setPropIsActive(true); - entry->setCurrentWindowInfo(windowInfo); - entry->updateName(); - entry->updateIcon(); - } else { - entry->setPropIsActive(false); - } - } -} - -void Entries::updateEntriesMenu() -{ - for (auto entry : m_items) { - entry->updateMenu(); - } -} - -const QList Entries::unDockedEntries() const -{ - QList entrys; - for (Entry *entry : m_items) { - if (!entry->isValid() || entry->getIsDocked()) - continue; - - entrys << entry; - } - - return entrys; -} - -void Entries::moveEntryToLast(Entry *entry) -{ - if (m_items.contains(entry)) { - m_items.removeOne(entry); - m_items << entry; - } -} - -void Entries::insertCb(Entry *entry, int index) -{ - if (entry->getIsDocked() || entry->hasWindow() || - (static_cast(m_dock->getDisplayMode()) == DisplayMode::Fashion) && m_dock->showRecent()) - Q_EMIT m_dock->entryAdded(QDBusObjectPath(entry->path()), index); -} - -void Entries::removeCb(Entry *entry) -{ - Q_EMIT m_dock->entryRemoved(entry->getId()); - entry->stopExport(); -} - -bool Entries::shouldInRecent() -{ - // 如果当前移除的应用是未驻留应用,则判断未驻留应用的数量是否小于等于3,则让其始终显示 - QList unDocktrys; - for (Entry *entry : m_items) { - if (entry->isValid() && !entry->getIsDocked()) - unDocktrys << entry; - } - - // 如果当前未驻留应用的数量小于3个,则认为后续的应用应该显示到最近打开应用 - return (unDocktrys.size() <= MAX_UNOPEN_RECENT_COUNT); -} - -void Entries::removeLastRecent() -{ - // 先查找最近使用的应用,删除没有使用的 - int unDockCount = 0; - QList unDockEntrys; - QList removeEntrys; - for (Entry *entry : m_items) { - if (entry->getIsDocked()) - continue; - - // 此处只移除没有子窗口的图标 - if (!entry->hasWindow()) { - if (!entry->isValid()) - removeEntrys << entry; // 如果应用已经被卸载,那么需要删除 - else - unDockEntrys << entry; - } - - unDockCount++; - } - if (unDockCount >= MAX_UNOPEN_RECENT_COUNT && unDockEntrys.size() > 0) { - // 只有当最近使用区域的图标大于等于某个数值(3)的时候,并且存在没有子窗口的Entry,那么就移除该Entry - Entry *entry = unDockEntrys[0]; - removeEntrys << entry; - } - for (Entry *entry : removeEntrys) { - m_items.removeOne(entry); - removeCb(entry); - delete entry; - } -} - -void Entries::setDisplayMode(DisplayMode displayMode) -{ - if (!m_dock->showRecent()) - return; - - // 如果从时尚模式变成高效模式,对列表中所有的没有打开窗口的应用发送移除信号 - if (displayMode == DisplayMode::Efficient) { - for (Entry *entry : m_items) { - entry->updateMode(); - if (!entry->getIsDocked() && !entry->hasWindow()) - Q_EMIT m_dock->entryRemoved(entry->getId()); - } - } else { - // 如果从高效模式变成时尚模式,列表中所有的未驻留且不存在打开窗口的应用认为是最近打开应用,发送新增信号 - for (Entry *entry : m_items) { - entry->updateMode(); - if (!entry->getIsDocked() && !entry->hasWindow()) { - QString objPath = entry->path(); - int index = m_items.indexOf(entry); - Q_EMIT m_dock->entryAdded(QDBusObjectPath(objPath), index); - } - } - } -} - -void Entries::updateShowRecent() -{ - // 高效模式无需做任何操作 - if (static_cast(m_dock->getDisplayMode()) != DisplayMode::Fashion) - return; - - bool showRecent = m_dock->showRecent(); - if (showRecent) { - // 如果显示最近打开应用,则发送新增信号 - for (Entry *entry : m_items) { - // 已经驻留的或者有子窗口的本来就在任务栏上面,无需发送信号 - entry->updateMode(); - if (entry->getIsDocked() || entry->hasWindow()) - continue; - - QString objPath = entry->path(); - int index = m_items.indexOf(entry); - Q_EMIT m_dock->entryAdded(QDBusObjectPath(objPath), index); - } - } else { - // 如果是隐藏最近打开的应用,则发送移除的信号 - for (Entry *entry : m_items) { - // 已经驻留的或者有子窗口的本来就在任务栏上面,无需发送信号 - entry->updateMode(); - if (entry->getIsDocked() || entry->hasWindow()) - continue; - - Q_EMIT m_dock->entryRemoved(entry->getId()); - } - } -} diff --git a/src/modules/dock/entries.h b/src/modules/dock/entries.h deleted file mode 100644 index 955fc1d..0000000 --- a/src/modules/dock/entries.h +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef ENTRIES_H -#define ENTRIES_H - -#include "entry.h" -#include "docksettings.h" - -#include -#include - -#define MAX_UNOPEN_RECENT_COUNT 3 - -class Dock; - -// 所有应用管理类 -class Entries -{ -public: - Entries(Dock *_dock); - - QVector filterDockedEntries(); - Entry *getByInnerId(QString innerId); - void append(Entry *entry); - void insert(Entry *entry, int index); - void remove(Entry *entry); - void move(int oldIndex, int newIndex); - Entry *getByWindowPid(int pid); - Entry *getByWindowId(XWindow windowId); - Entry *getByDesktopFilePath(QString filePath); - QStringList getEntryIDs(); - Entry *getDockedEntryByDesktopFile(const QString &desktopFile); - QString queryWindowIdentifyMethod(XWindow windowId); - void handleActiveWindowChanged(XWindow activeWindId); - void updateEntriesMenu(); - const QList unDockedEntries() const; - void moveEntryToLast(Entry *entry); - bool shouldInRecent(); - void removeLastRecent(); - void setDisplayMode(DisplayMode displayMode); - void updateShowRecent(); - -private: - void insertCb(Entry *entry, int index); - void removeCb(Entry *entry); - -private: - QList m_items; - Dock *m_dock; -}; - -#endif // ENTRIES_H diff --git a/src/modules/dock/entry.cpp b/src/modules/dock/entry.cpp deleted file mode 100644 index 1a54066..0000000 --- a/src/modules/dock/entry.cpp +++ /dev/null @@ -1,974 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "entry.h" -#include "dock.h" -#include "processinfo.h" -#include "dbusadaptorentry.h" -#include "xcbutils.h" - -#include -#include - -#include - -#define XCB XCBUtils::instance() - -Entry::Entry(Dock *_dock, AppInfo *_app, QString _innerId, QObject *parent) - : QObject(parent) - , m_dock(_dock) - , m_app(nullptr) - , m_menu(nullptr) - , m_isActive(false) - , m_isDocked(false) - , m_innerId(_innerId) - , m_adapterEntry(nullptr) - , m_current(nullptr) - , m_currentWindow(0) - , m_winIconPreferred(false) - , m_mode(getCurrentMode()) -{ - setApp(_app); - m_id = m_dock->allocEntryId(); - m_name = getName(); - m_icon = getIcon(); -} - -Entry::~Entry() -{ - for (auto winInfo : m_windowInfoMap) { - if (winInfo) - delete winInfo; - } - m_windowInfoMap.clear(); - - if (m_app) { - delete m_app; - m_app = nullptr; - } - - if (m_menu) { - delete m_menu; - m_menu = nullptr; - } -} - -bool Entry::isValid() -{ - return m_app ? m_app->isValidApp() : false; -} - -QString Entry::getId() const -{ - return m_id; -} - -QString Entry::path() const -{ - return entryDBusObjPathPrefix + getId(); -} - -QString Entry::getName() -{ - QString ret; - if (m_app) { - ret = m_app->getName(); - } - - if (ret.isEmpty() && m_current) { - ret = m_current->getDisplayName(); - } - - return ret; -} - -void Entry::updateName() -{ - setPropName(getName()); -} - -QString Entry::getIcon() -{ - QString ret; - if (hasWindow()) { - if (!m_current) { - return ret; - } - - // has window && current not nullptr - if (m_winIconPreferred) { - // try current window icon first - ret = m_current->getIcon(); - if (ret.size() > 0) { - return ret; - } - } - - if (m_app) { - m_icon = m_app->getIcon(); - if (m_icon.size() > 0) { - return m_icon; - } - } - - return m_current->getIcon(); - } - - if (m_app) { - // no window - return m_app->getIcon(); - } - - return ret; -} - -QString Entry::getInnerId() -{ - return m_innerId; -} - -void Entry::setInnerId(QString _innerId) -{ - m_innerId = _innerId; -} - -QString Entry::getFileName() -{ - return m_app ? m_app->getFileName() : QString(); -} - -AppInfo *Entry::getApp() -{ - return m_app; -} - -void Entry::setApp(AppInfo *appinfo) -{ - if (m_app == appinfo) { - return; - } - - if (m_app) { - delete m_app; - } - - m_app = appinfo; - if (!appinfo) { - m_winIconPreferred = true; - setPropDesktopFile(""); - } else { - m_winIconPreferred = false; - setPropDesktopFile(appinfo->getFileName()); - QString id = m_app->getId(); - auto perferredApps = m_dock->getWinIconPreferredApps(); - if (perferredApps.contains(id)) { - m_winIconPreferred = true; - return; - } - - if (appinfo->getIcon().size() == 0) { - m_winIconPreferred = true; - } - } -} - -bool Entry::getIsDocked() const -{ - return m_isDocked; -} - -void Entry::setIsDocked(bool value) -{ - if (value != m_isDocked) { - m_isDocked = value; - Q_EMIT isDockedChanged(value); - } -} - -// 导出DBus服务 -void Entry::startExport() -{ - if (getId().isEmpty()) { - qWarning() << "startExport Entry " << getName() << " id is Empty"; - return; - } - - if (m_adapterEntry) { - qWarning() << "service " << getName() << " is running"; - return; - } - - m_adapterEntry = new DBusAdaptorEntry(this); // export dbus by Adaptor - QDBusConnection con = QDBusConnection::sessionBus(); - if (!con.registerService(dbusService)) { - qWarning() << "register service Dock1 error:" << con.lastError().message(); - return; - } - - if (!con.registerObject(path(), this)) { - qWarning() << "register object Dock1 error:" << con.lastError().message(); - } -} - -// 停止导出DBus服务 -void Entry::stopExport() -{ - if (getId().isEmpty()) { - qWarning() << "stopExport Entry " << getName() << " id is Empty"; - return; - } - - if (!m_adapterEntry) { - qWarning() << "serice " << getName() << "is not running"; - return; - } - - QDBusConnection con = QDBusConnection::sessionBus(); - con.unregisterObject(path()); - - m_adapterEntry->deleteLater(); - m_adapterEntry = nullptr; -} - -void Entry::setMenu(AppMenu *_menu) -{ - _menu->setDirtyStatus(true); - if (m_menu) - delete m_menu; - - m_menu = _menu; - Q_EMIT menuChanged(m_menu->getMenuJsonStr()); -} - -void Entry::updateMenu() -{ - qInfo() <<"Entry: updateMenu"; - AppMenu *appMenu = new AppMenu(); - appMenu->appendItem(getMenuItemLaunch()); - - for (auto &item :getMenuItemDesktopActions()) - appMenu->appendItem(item); - - if (hasWindow()) - appMenu->appendItem(getMenuItemAllWindows()); - - // menu item dock or undock - qInfo() << "entry " << m_id << " docked? " << m_isDocked; - if (m_isDocked) - appMenu->appendItem(getMenuItemUndock()); - else - appMenu->appendItem(getMenuItemDock()); - - if (hasWindow()) { - if (m_dock->getForceQuitAppStatus() != ForceQuitAppMode::Disabled) { - if (m_app && m_app->getIdentifyMethod() == "Andriod") - appMenu->appendItem(getMenuItemForceQuitAndroid()); - else - appMenu->appendItem(getMenuItemForceQuit()); - } - - if (getAllowedCloseWindows().size() > 0) - appMenu->appendItem(getMenuItemCloseAll()); - } - - setMenu(appMenu); -} - -void Entry::updateIcon() -{ - setPropIcon(getIcon()); -} - -int Entry::getCurrentMode() -{ - // 只要当前应用是已经驻留的应用,则让其显示为Normal - if (getIsDocked()) - return ENTRY_NORMAL; - - // 对于未驻留的应用则做如下处理 - if (static_cast(m_dock->getDisplayMode()) == DisplayMode::Efficient) { - // 高效模式下,只有存在子窗口的,则让其为nornal,没有子窗口的,一般不让其显示 - return hasWindow() ? ENTRY_NORMAL : ENTRY_NONE; - } - // 时尚模式下对未驻留应用做如下处理 - // 如果开启了最近打开应用的功能,则显示到最近打开区域(ENTRY_RECENT) - if (m_dock->showRecent()) - return ENTRY_RECENT; - - // 未开启最近使用应用的功能,如果有子窗口,则显示成通用的(ENTRY_NORMAL),如果没有子窗口,则不显示(ENTRY_NONE) - return hasWindow() ? ENTRY_NORMAL : ENTRY_NONE; -} - -void Entry::updateMode() -{ - int currentMode = getCurrentMode(); - if (m_mode != currentMode) { - m_mode = currentMode; - Q_EMIT modeChanged(m_mode); - } -} - -void Entry::forceUpdateIcon() -{ - m_icon = getIcon(); - Q_EMIT iconChanged(m_icon); -} - -void Entry::updateIsActive() -{ - bool isActive = false; - auto activeWin = m_dock->getActiveWindow(); - if (activeWin) { - // 判断活跃窗口是否属于当前应用 - isActive = m_windowInfoMap.find(activeWin->getXid()) != m_windowInfoMap.end(); - } - - setPropIsActive(isActive); -} - -WindowInfoBase *Entry::getWindowInfoByPid(int pid) -{ - for (const auto &windowInfo : m_windowInfoMap) { - if (windowInfo->getPid() == pid) - return windowInfo; - } - - return nullptr; -} - -WindowInfoBase *Entry::getWindowInfoByWinId(XWindow windowId) -{ - if (m_windowInfoMap.find(windowId) != m_windowInfoMap.end()) - return m_windowInfoMap[windowId]; - - return nullptr; -} - -void Entry::setPropIcon(QString value) -{ - if (value != m_icon) { - m_icon = value; - Q_EMIT iconChanged(value); - } -} - -void Entry::setPropName(QString value) -{ - if (value != m_name) { - m_name = value; - Q_EMIT nameChanged(value); - } -} - -void Entry::setPropIsActive(bool active) -{ - if (m_isActive != active) { - m_isActive = active; - Q_EMIT isActiveChanged(active); - } -} - -void Entry::setCurrentWindowInfo(WindowInfoBase *windowInfo) -{ - m_current = windowInfo; - setPropCurrentWindow(m_current ? m_current->getXid() : 0); -} - -void Entry::setPropCurrentWindow(XWindow value) -{ - if (value != m_currentWindow) { - m_currentWindow = value; - Q_EMIT currentWindowChanged(value); - } -} - -WindowInfoBase *Entry::getCurrentWindowInfo() -{ - return m_current; -} - -/** - * @brief Entry::findNextLeader - * @return - */ -WindowInfoBase *Entry::findNextLeader() -{ - auto xids = m_windowInfoMap.keys(); - qSort(xids); - XWindow curWinId = m_current->getXid(); - int index = xids.indexOf(curWinId); - if (index < 0) - return nullptr; - - // 如果当前窗口是最大, 返回xids[0], 否则返回xids[index + 1] - int nextIndex = 0; - if (index < xids.size() - 1) - nextIndex = index + 1; - - return m_windowInfoMap[xids[nextIndex]]; -} - -QString Entry::getExec(bool oneLine) -{ - if (!m_current) - return ""; - - ProcessInfo *process = m_current->getProcess(); - if (process) { - if (oneLine) - return process->getOneCommandLine().c_str(); - - return process->getShellScriptLines().c_str(); - } - - return ""; -} - -bool Entry::hasWindow() -{ - return m_windowInfoMap.size() > 0; -} - -/** - * @brief Entry::updateExportWindowInfos 同步更新导出窗口信息 - */ -void Entry::updateExportWindowInfos() -{ - WindowInfoMap infos; - for (auto info : m_windowInfoMap) { - WindowInfo winInfo; - XWindow xid = info->getXid(); - winInfo.title = info->getTitle(); - winInfo.attention = info->isDemandingAttention(); - winInfo.uuid = info->uuid(); - infos[xid] = winInfo; - } - - bool changed = true; - if (infos.size() == m_exportWindowInfos.size()) { - changed = false; - for (auto iter = infos.begin(); iter != infos.end(); iter++) { - XWindow xid = iter.key(); - if (infos[xid].title != m_exportWindowInfos[xid].title || - infos[xid].attention != m_exportWindowInfos[xid].attention || - infos[xid].uuid != m_exportWindowInfos[xid].uuid) { - changed = true; - break; - } - } - } - - if (changed) { - Q_EMIT windowInfosChanged(infos); - } - - // 更新导出的窗口信息 - m_exportWindowInfos = infos; -} - -// 分离窗口, 返回是否需要从任务栏remove -bool Entry::detachWindow(WindowInfoBase *info) -{ - info->setEntry(nullptr); - XWindow winId = info->getXid(); - if (m_windowInfoMap.contains(winId)) { - // WARN(black_desk): Address sanitizer report Dock::m_activeWindow use - // this pointer after free here. - // After comment out the delete, leak sanitizer report nothing. So I - // believe this pointer is free somewhere else. - - // WindowInfoBase *info = m_windowInfoMap[winId]; - m_windowInfoMap.remove(winId); - // delete info; - - } - - if (m_windowInfoMap.isEmpty()) { - if (!m_isDocked) { - // 既无窗口也非驻留应用,并且不是最近打开,无需在任务栏显示 - return true; - } - - Q_EMIT windowInfosChanged(WindowInfoMap()); - setCurrentWindowInfo(nullptr); - } else { - for (auto window : m_windowInfoMap) { - if (window) { // 选择第一个窗口作为当前窗口 - setCurrentWindowInfo(window); - break; - } - } - } - - updateExportWindowInfos(); - updateIcon(); - updateIsActive(); - updateMenu(); - - return false; -} - -bool Entry::isShowOnDock() const -{ - // 当前应用显示图标的条件是 - // 如果该图标已经固定在任务栏上,则始终显示 - if (getIsDocked()) - return true; - - // 1.时尚模式下,如果开启了显示最近使用,则不管是否有子窗口,都在任务栏上显示 - // 如果没有开启显示最近使用,则只显示有子窗口的 - if (static_cast(m_dock->getDisplayMode()) == DisplayMode::Fashion) - return (m_dock->showRecent() || m_exportWindowInfos.size() > 0); - - // 2.高效模式下,只有该应用有打开窗口才显示 - return m_exportWindowInfos.size() > 0; -} - -bool Entry::attachWindow(WindowInfoBase *info) -{ - XWindow winId = info->getXid(); - qInfo() << "attatchWindow: window id:" << winId; - info->setEntry(this); - - if (m_windowInfoMap.find(winId) != m_windowInfoMap.end()) { - qInfo() << "attachWindow: window " << winId << " is already attached"; - return false; - } - - bool lastShowOnDock = isShowOnDock(); - m_windowInfoMap[winId] = info; - updateExportWindowInfos(); - updateIsActive(); - - if (!m_current) { - // from no window to has window - setCurrentWindowInfo(info); - } - - updateIcon(); - updateMenu(); - - if (!lastShowOnDock && isShowOnDock()) { - // 新打开的窗口始终显示到最后 - Q_EMIT m_dock->entryAdded(QDBusObjectPath(path()), -1); - } - - return true; -} - -void Entry::launchApp(uint32_t timestamp) -{ - if (m_app) - m_dock->launchApp(m_app->getFileName(), timestamp, QStringList()); -} - -bool Entry::containsWindow(XWindow xid) -{ - return m_windowInfoMap.find(xid) != m_windowInfoMap.end(); -} - -// 处理菜单项 -void Entry::handleMenuItem(uint32_t timestamp, QString itemId) -{ - m_menu->handleAction(timestamp, itemId); -} - -// 处理拖拽事件 -void Entry::handleDragDrop(uint32_t timestamp, QStringList files) -{ - m_dock->launchApp(m_app->getFileName(), timestamp, files); -} - -// 驻留 -void Entry::requestDock(bool dockToEnd) -{ - if (m_dock->dockEntry(this, dockToEnd)) { - m_dock->saveDockedApps(); - } -} - -// 取消驻留 -void Entry::requestUndock(bool dockToEnd) -{ - m_dock->undockEntry(this, dockToEnd); -} - -void Entry::newInstance(uint32_t timestamp) -{ - QStringList files; - m_dock->launchApp(m_app->getFileName(), timestamp, files); -} - -// 检查应用窗口分离、合并状态 -void Entry::check() -{ - QList windows = m_windowInfoMap.values(); - for (WindowInfoBase *window : windows) { - m_dock->attachOrDetachWindow(window); - } -} - -// 强制退出 -void Entry::forceQuit() -{ - QMap> pidWinInfoMap; - QList windows = m_windowInfoMap.values(); - for (WindowInfoBase *window : windows) { - int pid = window->getPid(); - if (pid != 0) { - pidWinInfoMap[pid].push_back(window); - } else { - window->killClient(); - } - } - - for (auto iter = pidWinInfoMap.begin(); iter != pidWinInfoMap.end(); iter++) { - if (!killProcess(iter.key())) { // kill pid - for (auto &info : iter.value()) { // kill window - info->killClient(); - } - } - } - // 所有的窗口已经退出后,清空m_windowInfoMap内容 - m_windowInfoMap.clear(); - // 退出所有的进程后,及时更新当前剩余的窗口数量 - updateExportWindowInfos(); - m_dock->removeEntryFromDock(this); -} - -void Entry::presentWindows() -{ - QList windows = m_windowInfoMap.keys(); - m_dock->presentWindows(windows); -} - -/** - * @brief Entry::active 激活窗口 - * @param timestamp - */ -void Entry::active(uint32_t timestamp) -{ - if (m_dock->getHideMode() == HideMode::SmartHide) { - m_dock->setPropHideState(HideState::Show); - m_dock->updateHideState(false); - } - - // 无窗口则直接启动 - if (!hasWindow()) { - launchApp(timestamp); - return; - } - - if (!m_current) { - qWarning() << "active: current window is nullptr"; - return; - } - - WindowInfoBase *winInfo = m_current; - if (m_dock->isWaylandEnv()) { - // wayland环境 - if (!m_dock->isActiveWindow(winInfo)) { - winInfo->activate(); - } else { - bool showing = m_dock->isShowingDesktop(); - if (showing || winInfo->isMinimized()) { - winInfo->activate(); - } else if (m_windowInfoMap.size() == 1) { - winInfo->minimize(); - } else { - WindowInfoBase *nextWin = findNextLeader(); - if (nextWin) { - nextWin->activate(); - } - } - } - } else { - // X11环境 - XWindow xid = winInfo->getXid(); - WindowInfoBase *activeWin = m_dock->getActiveWindow(); - if (activeWin && xid != activeWin->getXid()) { - m_dock->doActiveWindow(xid); - } else { - bool found = false; - XWindow hiddenAtom = XCB->getAtom("_NET_WM_STATE_HIDDEN"); - for (auto state : XCB->getWMState(xid)) { - if (hiddenAtom == state) { - found = true; - break; - } - } - - if (found) { - // 激活隐藏窗口 - m_dock->doActiveWindow(xid); - } else if (m_windowInfoMap.size() == 1) { - // 窗口图标化 - XCB->minimizeWindow(xid); - } else if (m_dock->getActiveWindow() && m_dock->getActiveWindow()->getXid() == xid) { - WindowInfoBase *nextWin = findNextLeader(); - if (nextWin) { - nextWin->activate(); - } - } - } - } -} - -void Entry::activeWindow(quint32 winId) -{ - if (m_dock->isWaylandEnv()) { - if (!m_windowInfoMap.contains(winId)) - return; - - WindowInfoBase *winInfo = m_windowInfoMap[winId]; - if (m_dock->isActiveWindow(winInfo)) { - bool showing = m_dock->isShowingDesktop(); - if (showing || winInfo->isMinimized()) { - winInfo->activate(); - } else if (m_windowInfoMap.size() == 1) { - winInfo->minimize(); - } else { - WindowInfoBase *nextWin = findNextLeader(); - if (nextWin) { - nextWin->activate(); - } - } - } else { - winInfo->activate(); - } - } else { - m_dock->doActiveWindow(winId); - } -} - -int Entry::mode() -{ - return m_mode; -} - -XWindow Entry::getCurrentWindow() -{ - return m_currentWindow; -} - -QString Entry::getDesktopFile() -{ - return m_desktopFile; -} - -bool Entry::getIsActive() -{ - return m_isActive; -} - -QString Entry::getMenu() -{ - return m_menu->getMenuJsonStr(); -} - -QVector Entry::getAllowedClosedWindowIds() -{ - QVector ret; - for (auto iter = m_windowInfoMap.begin(); iter != m_windowInfoMap.end(); iter++) { - WindowInfoBase *info = iter.value(); - if (info && info->allowClose()) - ret.push_back(iter.key()); - } - - return ret; -} - -WindowInfoMap Entry::getExportWindowInfos() -{ - return m_exportWindowInfos; -} - -QVector Entry::getAllowedCloseWindows() -{ - QVector ret; - for (auto iter = m_windowInfoMap.begin(); iter != m_windowInfoMap.end(); iter++) { - WindowInfoBase *info = iter.value(); - if (info && info->allowClose()) { - ret.push_back(info); - } - } - - return ret; -} - -QVector Entry::getMenuItemDesktopActions() -{ - QVector ret; - if (!m_app) { - return ret; - } - - for (auto action : m_app->getActions()) { - AppMenuAction fn = [=](uint32_t timestamp) { - qInfo() << "do MenuItem: " << action.name.c_str(); - m_dock->launchAppAction(m_app->getFileName(), action.section.c_str(), timestamp); - }; - - AppMenuItem item; - item.text = action.name.c_str(); - item.action = fn; - item.isActive = true; - ret.push_back(item); - } - - return ret; -} - -AppMenuItem Entry::getMenuItemLaunch() -{ - QString itemName; - if (hasWindow()) { - itemName = getName(); - } else { - itemName = tr("Open"); - } - - AppMenuAction fn = [this](uint32_t timestamp) { - qInfo() << "do MenuItem: Open"; - this->launchApp(timestamp); - }; - - AppMenuItem item; - item.text = itemName; - item.action = fn; - item.isActive = true; - return item; -} - -AppMenuItem Entry::getMenuItemCloseAll() -{ - AppMenuAction fn = [this](uint32_t timestamp) { - qInfo() << "do MenuItem: Close All"; - auto winInfos = getAllowedCloseWindows(); - - // 根据创建时间从大到小排序, 方便后续关闭窗口 - for (int i = 0; i < winInfos.size() - 1; i++) { - for (int j = i + 1; j < winInfos.size(); j++) { - if (winInfos[i]->getCreatedTime() < winInfos[j]->getCreatedTime()) { - auto info = winInfos[i]; - winInfos[i] = winInfos[j]; - winInfos[j] = info; - } - } - } - - for (auto info : winInfos) { - qInfo() << "close WindowId " << info->getXid(); - info->close(timestamp); - } - - // 关闭窗口后,主动刷新事件 - XCB->flush(); - }; - - AppMenuItem item; - item.text = tr("Close All"); - item.action = fn; - item.isActive = true; - return item; -} - -AppMenuItem Entry::getMenuItemForceQuit() -{ - bool active = m_dock->getForceQuitAppStatus() != ForceQuitAppMode::Deactivated; - AppMenuAction fn = [this](uint32_t) { - qInfo() << "do MenuItem: Force Quit"; - forceQuit(); - }; - - AppMenuItem item; - item.text = tr("Force Quit"); - item.action = fn; - item.isActive = active; - return item; -} - -//dock栏上Android程序的Force Quit功能 -AppMenuItem Entry::getMenuItemForceQuitAndroid() -{ - bool active = m_dock->getForceQuitAppStatus() != ForceQuitAppMode::Deactivated; - auto allowedCloseWindows = getAllowedCloseWindows(); - AppMenuAction fn = [](uint32_t){}; - if (allowedCloseWindows.size() > 0) { - qInfo() << "do MenuItem: Force Quit"; - AppMenuAction fn = [&](uint32_t timestamp) { - for (auto info : allowedCloseWindows) { - info->close(timestamp); - } - }; - } - - AppMenuItem item; - item.text = tr("Force Quit"); - item.action = fn; - item.isActive = active; - return item; -} - -AppMenuItem Entry::getMenuItemDock() -{ - AppMenuItem item; - item.text = tr("Dock"); - item.action = [this](uint32_t) { - qInfo() << "do MenuItem: Dock"; - requestDock(true); - }; - - item.isActive = true; - return item; -} - -AppMenuItem Entry::getMenuItemUndock() -{ - AppMenuItem item; - item.text = tr("Undock"); - item.action = [this](uint32_t) { - qInfo() << "do MenuItem: Undock"; - requestUndock(true); - }; - - item.isActive = true; - return item; -} - -AppMenuItem Entry::getMenuItemAllWindows() -{ - AppMenuItem item; - item.text = tr("All Windows"); - item.action = [this](uint32_t) { - qInfo() << "do MenuItem: All Windows"; - presentWindows(); - }; - - item.isActive = true; - item.hint = menuItemHintShowAllWindows; - return item; -} - -bool Entry::killProcess(int pid) -{ - bool ret = true; - Process p(pid); - if (p.isExist()) { - ret = !kill(pid, SIGTERM); - } - - return ret; -} - -bool Entry::setPropDesktopFile(QString value) -{ - if (value != m_desktopFile) { - m_desktopFile = value; - Q_EMIT desktopFileChanged(value); - return true; - } - - return false; -} diff --git a/src/modules/dock/entry.h b/src/modules/dock/entry.h deleted file mode 100644 index fb610df..0000000 --- a/src/modules/dock/entry.h +++ /dev/null @@ -1,143 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef ENTRY_H -#define ENTRY_H - -#include "appinfo.h" -#include "appmenu.h" -#include "windowinfobase.h" -#include "windowinfomap.h" - -#include -#include -#include - -#define ENTRY_NONE 0 -#define ENTRY_NORMAL 1 -#define ENTRY_RECENT 2 - -// 单个应用类 -class Dock; -class DBusAdaptorEntry; - -class Entry: public QObject -{ - Q_OBJECT -public: - Entry(Dock *_dock, AppInfo *_app, QString _innerId, QObject *parent = nullptr); - ~Entry(); - - bool isValid(); - QString getId() const; - QString path() const; - QString getName(); - void updateName(); - QString getIcon(); - QString getInnerId(); - void setInnerId(QString _innerId); - QString getFileName(); - AppInfo *getApp(); - void setApp(AppInfo *appinfo); - bool getIsDocked() const; - void setIsDocked(bool value); - void startExport(); - void stopExport(); - void setMenu(AppMenu *_menu); - void updateMenu(); - void updateIcon(); - void updateMode(); - void forceUpdateIcon(); - void updateIsActive(); - WindowInfoBase *getWindowInfoByPid(int pid); - WindowInfoBase *getWindowInfoByWinId(XWindow windowId); - void setPropIcon(QString value); - void setPropName(QString value); - void setPropIsActive(bool active); - void setPropCurrentWindow(XWindow value); - void setCurrentWindowInfo(WindowInfoBase *windowInfo); - WindowInfoBase *getCurrentWindowInfo(); - WindowInfoBase *findNextLeader(); - QString getExec(bool oneLine); - bool hasWindow(); - void updateExportWindowInfos(); - bool detachWindow(WindowInfoBase *info); - bool attachWindow(WindowInfoBase *info); - void launchApp(uint32_t timestamp); - bool containsWindow(XWindow xid); - - void handleMenuItem(uint32_t timestamp, QString itemId); - void handleDragDrop(uint32_t timestamp, QStringList files); - void requestDock(bool dockToEnd = false); - void requestUndock(bool dockToEnd = false); - void newInstance(uint32_t timestamp); - void check(); - void forceQuit(); - void presentWindows(); - void active(uint32_t timestamp); - void activeWindow(quint32 winId); - int mode(); - - XWindow getCurrentWindow(); - QString getDesktopFile(); - bool getIsActive(); - QString getMenu(); - QVector getAllowedClosedWindowIds(); - WindowInfoMap getExportWindowInfos(); - -public Q_SLOTS: - QVector getAllowedCloseWindows(); - -Q_SIGNALS: - void isActiveChanged(bool value); - void isDockedChanged(bool value); - void menuChanged(QString value); - void iconChanged(QString value); - void nameChanged(QString value); - void desktopFileChanged(QString value); - void currentWindowChanged(uint32_t value); - void windowInfosChanged(const WindowInfoMap &value); - void modeChanged(int); - -private: - // 右键菜单项 - QVector getMenuItemDesktopActions(); - AppMenuItem getMenuItemLaunch(); - AppMenuItem getMenuItemCloseAll(); - AppMenuItem getMenuItemForceQuit(); - AppMenuItem getMenuItemForceQuitAndroid(); - AppMenuItem getMenuItemDock(); - AppMenuItem getMenuItemUndock(); - AppMenuItem getMenuItemAllWindows(); - bool killProcess(int pid); - bool setPropDesktopFile(QString value); - bool isShowOnDock() const; - int getCurrentMode(); - -private: - Dock *m_dock; - AppInfo *m_app; - AppMenu *m_menu; - - bool m_isActive; - bool m_isDocked; - - QString m_id; - QString m_name; - QString m_icon; - QString m_innerId; - QString m_desktopFile; - - DBusAdaptorEntry *m_adapterEntry; - - // Dbus属性直接放到interface上 - QMap m_windowInfoMap; // 该应用所有窗口 - WindowInfoMap m_exportWindowInfos; // 该应用导出的窗口属性 - WindowInfoBase *m_current; // 当前窗口 - XWindow m_currentWindow; //当前窗口Id - bool m_winIconPreferred; - int m_mode; -}; - -#endif // ENTRY_H diff --git a/src/modules/dock/processinfo.cpp b/src/modules/dock/processinfo.cpp deleted file mode 100644 index 245fcae..0000000 --- a/src/modules/dock/processinfo.cpp +++ /dev/null @@ -1,158 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "processinfo.h" -#include "dstring.h" - -#include -#include -#include - -ProcessInfo::ProcessInfo(int pid) - : m_hasPid(true) - , m_process(Process(pid)) - , m_isValid(true) -{ - if (pid == 0) - return; - - // exe - m_exe = m_process.getExe(); - // cwd - m_cwd = m_process.getCwd(); - // cmdline - m_cmdLine = m_process.getCmdLine(); - // 部分root进程在/proc文件系统查找不到exe、cwd、cmdline信息 - if (m_exe.empty() || m_cwd.empty() || m_cmdLine.size() == 0) { - m_isValid = false; - return; - } - - // ppid - Status pstatus = m_process.getStatus(); - if (pstatus.size() > 0) { - int ppid = m_process.getPpid(); - } - - // args - qInfo() << "ProcessInfo: exe=" << m_exe.c_str() << " cwd=" << m_cwd.c_str() << " cmdLine=" << (m_cmdLine[0].empty() ? " " : m_cmdLine[0].c_str()); - auto verifyExe = [](std::string exe, std::string cwd, std::string firstArg){ - if (firstArg.size() == 0) - return false; - - QFileInfo info(firstArg.c_str()); - if (info.completeBaseName() == firstArg.c_str()) - return true; - - if (!QDir::isAbsolutePath(firstArg.c_str())) - firstArg = cwd + firstArg; - - return exe == firstArg; - }; - - if (!m_cmdLine[0].empty()) { - if (!verifyExe(m_exe, m_cwd, m_cmdLine[0])) { - auto parts = DString::splitStr(m_cmdLine[0], ' '); - // try again - if (verifyExe(m_exe, m_cwd, parts[0])) { - for (int j = 1; j < parts.size(); j++) { - m_args.push_back(parts[j]); - } - for (int i = 1; i < m_cmdLine.size(); i++) { - m_args.push_back(m_cmdLine[i]); - } - } - } else { - for (int i = 1; i < m_cmdLine.size(); i++) { - m_args.push_back(m_cmdLine[i]); - } - } - } -} - -ProcessInfo::ProcessInfo(std::vector &cmd) - : m_hasPid(false) - , m_isValid(true) - , m_process(Process()) -{ - if (cmd.size() == 0) { - m_isValid = false; - return; - } - - m_cmdLine = cmd; - m_exe = cmd[0]; - for (ulong i=0; i < cmd.size(); i++) { - if (i > 0) { - m_args.push_back(cmd[i]); - } - } -} - -ProcessInfo::~ProcessInfo() -{ -} - -std::string ProcessInfo::getEnv(std::string key) -{ - return m_process.getEnv(key); -} - -std::vector ProcessInfo::getCmdLine() -{ - return m_cmdLine; -} - -std::vector ProcessInfo::getArgs() -{ - return m_args; -} - -int ProcessInfo::getPid() -{ - return m_process.getPid(); -} - -int ProcessInfo::getPpid() -{ - return m_process.getPpid(); -} - -bool ProcessInfo::initWithPid() -{ - return m_hasPid; -} - -bool ProcessInfo::isValid() -{ - return m_isValid; -} - -std::string ProcessInfo::getExe() -{ - return m_exe; -} - -std::string ProcessInfo::getOneCommandLine() -{ - std::string cmdline = getJoinedExeArgs(); - return "sh -c 'cd " + m_cwd + "; exec " + cmdline + ";'"; -} - -std::string ProcessInfo::getShellScriptLines() -{ - std::string cmdline = getJoinedExeArgs(); - return "#!/bin/sh\n cd " + m_cwd + "\n exec " + cmdline + "\n"; -} - -std::string ProcessInfo::getJoinedExeArgs() -{ - std::string ret = "\"" + m_exe + "\""; - for (auto arg : m_args) { - ret += " \"" + arg + "\""; - } - - ret += " $@"; - return ret; -} diff --git a/src/modules/dock/processinfo.h b/src/modules/dock/processinfo.h deleted file mode 100644 index 38788f3..0000000 --- a/src/modules/dock/processinfo.h +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef PROCESSINFO_H -#define PROCESSINFO_H - -#include "process.h" - -#include -#include - -// 进程信息 -class ProcessInfo -{ -public: - explicit ProcessInfo(int pid); - explicit ProcessInfo(std::vector &cmd); - virtual ~ProcessInfo(); - - std::string getEnv(std::string key); - std::vector getCmdLine(); - std::vector getArgs(); - int getPid(); - int getPpid(); - bool initWithPid(); - bool isValid(); - std::string getExe(); - std::string getOneCommandLine(); - std::string getShellScriptLines(); - -private: - std::string getJoinedExeArgs(); - - std::vector m_cmdLine; - std::vector m_args; - std::string m_exe; - std::string m_cwd; - - bool m_hasPid; - bool m_isValid; - Process m_process; -}; - -#endif // PROCESSINFO_H diff --git a/src/modules/dock/waylandmanager.cpp b/src/modules/dock/waylandmanager.cpp deleted file mode 100644 index 29b9bb1..0000000 --- a/src/modules/dock/waylandmanager.cpp +++ /dev/null @@ -1,118 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "waylandmanager.h" -#include "dock.h" -#include "xcbutils.h" - -#define XCB XCBUtils::instance() - -WaylandManager::WaylandManager(Dock *_dock, QObject *parent) - : QObject(parent) - , m_dock(_dock) - , m_mutex(QMutex(QMutex::NonRecursive)) -{ - -} - - -/** - * @brief WaylandManager::registerWindow 注册窗口 - * @param objPath - */ -void WaylandManager::registerWindow(const QString &objPath) -{ - qInfo() << "registerWindow: " << objPath; - if (findWindowByObjPath(objPath)) - return; - - PlasmaWindow *plasmaWindow = m_dock->createPlasmaWindow(objPath); - if (!plasmaWindow) { - qWarning() << "registerWindowWayland: createPlasmaWindow failed"; - return; - } - - if (!plasmaWindow->IsValid() || !plasmaWindow->isValid()) { - qWarning() << "PlasmaWindow is not valid:" << objPath; - delete plasmaWindow; - return; - } - - QString appId = plasmaWindow->AppId(); - QStringList list {"dde-dock", "dde-launcher", "dde-clipboard", "dde-osd", "dde-polkit-agent", "dde-simple-egl", "dmcs", "dde-lock"}; - if (list.indexOf(appId) >= 0 || appId.startsWith("No such object path")) { - delete plasmaWindow; - return; - } - - XWindow winId = XCB->allocId(); // XCB中未发现释放XID接口 - XWindow realId = plasmaWindow->WindowId(); - if (realId) - winId = realId; - - WindowInfoK *winInfo = new WindowInfoK(plasmaWindow, winId); - m_dock->listenKWindowSignals(winInfo); - insertWindow(objPath, winInfo); - m_dock->attachOrDetachWindow(winInfo); - if (winId) { - m_windowInfoMap[winId] = winInfo; - } -} - -// 取消注册窗口 -void WaylandManager::unRegisterWindow(const QString &objPath) -{ - qInfo() << "unRegisterWindow: " << objPath; - WindowInfoK *winInfo = findWindowByObjPath(objPath); - if (!winInfo) - return; - - m_dock->removePlasmaWindowHandler(winInfo->getPlasmaWindow()); - m_dock->detachWindow(winInfo); - deleteWindow(objPath); -} - -WindowInfoK *WaylandManager::findWindowById(uint activeWin) -{ - QMutexLocker locker(&m_mutex); - for (auto iter = m_kWinInfos.begin(); iter != m_kWinInfos.end(); iter++) { - if (iter.value()->getInnerId() == QString::number(activeWin)) { - return iter.value(); - } - } - - return nullptr; -} - -WindowInfoK *WaylandManager::findWindowByXid(XWindow xid) -{ - WindowInfoK *winInfo = nullptr; - for (auto iter = m_kWinInfos.begin(); iter != m_kWinInfos.end(); iter++) { - if (iter.value()->getXid() == xid) { - winInfo = iter.value(); - break; - } - } - - return winInfo; -} - -WindowInfoK *WaylandManager::findWindowByObjPath(QString objPath) -{ - if (m_kWinInfos.find(objPath) == m_kWinInfos.end()) - return nullptr; - - return m_kWinInfos[objPath]; -} - -void WaylandManager::insertWindow(QString objPath, WindowInfoK *windowInfo) -{ - QMutexLocker locker(&m_mutex); - m_kWinInfos[objPath] = windowInfo; -} - -void WaylandManager::deleteWindow(QString objPath) -{ - m_kWinInfos.remove(objPath); -} diff --git a/src/modules/dock/waylandmanager.h b/src/modules/dock/waylandmanager.h deleted file mode 100644 index 47b06a0..0000000 --- a/src/modules/dock/waylandmanager.h +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef WAYLANDMANAGER_H -#define WAYLANDMANAGER_H - -#include "windowinfok.h" - -#include -#include -#include - -class Dock; - -// 管理wayland窗口 -class WaylandManager : public QObject -{ - Q_OBJECT -public: - explicit WaylandManager(Dock *_dock, QObject *parent = nullptr); - - void registerWindow(const QString &objPath); - void unRegisterWindow(const QString &objPath); - - WindowInfoK *findWindowById(uint activeWin); - WindowInfoK *findWindowByXid(XWindow xid); - WindowInfoK *findWindowByObjPath(QString objPath); - void insertWindow(QString objPath, WindowInfoK *windowInfo); - void deleteWindow(QString objPath); - -private: - Dock *m_dock; - QMap m_kWinInfos; // dbusObjectPath -> kwayland window Info - QMap m_windowInfoMap; - QMutex m_mutex; -}; - -#endif // WAYLANDMANAGER_H diff --git a/src/modules/dock/windowidentify.cpp b/src/modules/dock/windowidentify.cpp deleted file mode 100644 index 969c3dd..0000000 --- a/src/modules/dock/windowidentify.cpp +++ /dev/null @@ -1,532 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "windowidentify.h" -#include "common.h" -#include "appinfo.h" -#include "dock.h" -#include "processinfo.h" -#include "dstring.h" -#include "basedir.h" -#include "dfile.h" -#include "xcbutils.h" -#include "../apps/desktopfilereader.h" - -#include -#include - -#define XCB XCBUtils::instance() - -static QMap crxAppIdMap = { - {"crx_onfalgmmmaighfmjgegnamdjmhpjpgpi", "apps.com.aiqiyi"}, - {"crx_gfhkopakpiiaeocgofdpcpjpdiglpkjl", "apps.cn.kugou.hd"}, - {"crx_gaoopbnflngfkoobibfgbhobdeiipcgh", "apps.cn.kuwo.kwmusic"}, - {"crx_jajaphleehpmpblokgighfjneejapnok", "apps.com.evernote"}, - {"crx_ebhffdbfjilfhahiinoijchmlceailfn", "apps.com.letv"}, - {"crx_almpoflgiciaanepplakjdkiaijmklld", "apps.com.tongyong.xxbox"}, - {"crx_heaphplipeblmpflpdcedfllmbehonfo", "apps.com.peashooter"}, - {"crx_dbngidmdhcooejaggjiochbafiaefndn", "apps.com.rovio.angrybirdsseasons"}, - {"crx_chfeacahlaknlmjhiagghobhkollfhip", "apps.com.sina.weibo"}, - {"crx_cpbmecbkmjjfemjiekledmejoakfkpec", "apps.com.openapp"}, - {"crx_lalomppgkdieklbppclocckjpibnlpjc", "apps.com.baidutieba"}, - {"crx_gejbkhjjmicgnhcdpgpggboldigfhgli", "apps.com.zhuishushenqi"}, - {"crx_gglenfcpioacendmikabbkecnfpanegk", "apps.com.duokan"}, - {"crx_nkmmgdfgabhefacpfdabadjfnpffhpio", "apps.com.zhihu.daily"}, - {"crx_ajkogonhhcighbinfgcgnjiadodpdicb", "apps.com.netease.newsreader"}, - {"crx_hgggjnaaklhemplabjhgpodlcnndhppo", "apps.com.baidu.music.pad"}, - {"crx_ebmgfebnlgilhandilnbmgadajhkkmob", "apps.cn.ibuka"}, - {"crx_nolebplcbgieabkblgiaacdpgehlopag", "apps.com.tianqitong"}, - {"crx_maghncnmccfbmkekccpmkjjfcmdnnlip", "apps.com.youjoy.strugglelandlord"}, - {"crx_heliimhfjgfabpgfecgdhackhelmocic", "apps.cn.emoney"}, - {"crx_jkgmneeafmgjillhgmjbaipnakfiidpm", "apps.com.instagram"}, - {"crx_cdbkhmfmikobpndfhiphdbkjklbmnakg", "apps.com.easymindmap"}, - {"crx_djflcciklfljleibeinjmjdnmenkciab", "apps.com.lgj.thunderbattle"}, - {"crx_ffdgbolnndgeflkapnmoefhjhkeilfff", "apps.com.qianlong"}, - {"crx_fmpniepgiofckbfgahajldgoelogdoap", "apps.com.windhd"}, - {"crx_dokjmallmkihbgefmladclcdcinjlnpj", "apps.com.youdao.hanyu"}, - {"crx_dicimeimfmbfcklbjdpnlmjgegcfilhm", "apps.com.ibookstar"}, - {"crx_cokkcjnpjfffianjbpjbcgjefningkjm", "apps.com.yidianzixun"}, - {"crx_ehflkacdpmeehailmcknlnkmjalehdah", "apps.com.xplane"}, - {"crx_iedokjbbjejfinokgifgecmboncmkbhb", "apps.com.wedevote"}, - {"crx_eaefcagiihjpndconigdpdmcbpcamaok", "apps.com.tongwei.blockbreaker"}, - {"crx_mkjjfibpccammnliaalefmlekiiikikj", "apps.com.dayima"}, - {"crx_gflkpppiigdigkemnjlonilmglokliol", "apps.com.cookpad"}, - {"crx_jfhpkchgedddadekfeganigbenbfaohe", "apps.com.issuu"}, - {"crx_ggkmfnbkldhmkehabgcbnmlccfbnoldo", "apps.bible.cbol"}, - {"crx_phlhkholfcljapmcidanddmhpcphlfng", "apps.com.kanjian.radio"}, - {"crx_bjgfcighhaahojkibojkdmpdihhcehfm", "apps.de.danoeh.antennapod"}, - {"crx_kldipknjommdfkifomkmcpbcnpmcnbfi", "apps.com.asoftmurmur"}, - {"crx_jfhlegimcipljdcionjbipealofoncmd", "apps.com.tencentnews"}, - {"crx_aikgmfkpmmclmpooohngmcdimgcocoaj", "apps.com.tonghuashun"}, - {"crx_ifimglalpdeoaffjmmihoofapmpflkad", "apps.com.letv.lecloud.disk"}, - {"crx_pllcekmbablpiogkinogefpdjkmgicbp", "apps.com.hwadzanebook"}, - {"crx_ohcknkkbjmgdfcejpbmhjbohnepcagkc", "apps.com.douban.radio"}, -}; - -WindowIdentify::WindowIdentify(Dock *_dock, QObject *parent) - : QObject(parent) - , m_dock(_dock) -{ - m_identifyWindowFuns << qMakePair(QString("Android") , &identifyWindowAndroid); - m_identifyWindowFuns << qMakePair(QString("PidEnv"), &identifyWindowByPidEnv); - m_identifyWindowFuns << qMakePair(QString("CmdlineTurboBooster"), &identifyWindowByCmdlineTurboBooster); - m_identifyWindowFuns << qMakePair(QString("Cmdline-XWalk"), &identifyWindowByCmdlineXWalk); - m_identifyWindowFuns << qMakePair(QString("FlatpakAppID"), &identifyWindowByFlatpakAppID); - m_identifyWindowFuns << qMakePair(QString("CrxId"), &identifyWindowByCrxId); - m_identifyWindowFuns << qMakePair(QString("Rule"), &identifyWindowByRule); - m_identifyWindowFuns << qMakePair(QString("Bamf"), &identifyWindowByBamf); - m_identifyWindowFuns << qMakePair(QString("Pid"), &identifyWindowByPid); - m_identifyWindowFuns << qMakePair(QString("Scratch"), &identifyWindowByScratch); - m_identifyWindowFuns << qMakePair(QString("GtkAppId"), &identifyWindowByGtkAppId); - m_identifyWindowFuns << qMakePair(QString("WmClass"), &identifyWindowByWmClass); -} - -AppInfo *WindowIdentify::identifyWindow(WindowInfoBase *winInfo, QString &innerId) -{ - if (!winInfo) - return nullptr; - - qInfo() << "identifyWindow: window id " << winInfo->getXid() << " innerId " << winInfo->getInnerId(); - if (winInfo->getWindowType() == "X11") - return identifyWindowX11(static_cast(winInfo), innerId); - if (winInfo->getWindowType() == "Wayland") - return identifyWindowWayland(static_cast(winInfo), innerId); - - return nullptr; -} - -AppInfo *WindowIdentify::identifyWindowX11(WindowInfoX *winInfo, QString &innerId) -{ - AppInfo *appInfo = nullptr; - if (winInfo->getInnerId().isEmpty()) { - qInfo() << "identifyWindowX11: window innerId is empty"; - return appInfo; - } - - for (auto iter = m_identifyWindowFuns.begin(); iter != m_identifyWindowFuns.end(); iter++) { - QString name = iter->first; - IdentifyFunc func = iter->second; - qInfo() << "identifyWindowX11: try " << name; - appInfo = func(m_dock, winInfo, innerId); - if (appInfo) { // TODO: if name == "Pid", appInfo may by nullptr - // 识别成功 - qInfo() << "identify Window by " << name << " innerId " << appInfo->getInnerId() << " success!"; - AppInfo *fixedAppInfo = fixAutostartAppInfo(appInfo->getFileName()); - if (fixedAppInfo) { - delete appInfo; - appInfo = fixedAppInfo; - appInfo->setIdentifyMethod(name + "+FixAutostart"); - innerId = appInfo->getInnerId(); - } else { - appInfo->setIdentifyMethod(name); - } - return appInfo; - } - } - - qInfo() << "identifyWindowX11: failed"; - // 如果识别窗口失败,则该app的entryInnerId使用当前窗口的innerId - innerId = winInfo->getInnerId(); - return appInfo; -} - -AppInfo *WindowIdentify::identifyWindowWayland(WindowInfoK *winInfo, QString &innerId) -{ - // TODO: 对桌面调起的文管应用做规避处理,需要在此处添加,因为初始化时appId和title为空 - if (winInfo->getAppId() == "dde-desktop" && m_dock->shouldShowOnDock(winInfo)) { - winInfo->setAppId("dde-file-manager"); - } - - QString appId = winInfo->getAppId(); - if (appId.isEmpty()) { - QString title = winInfo->getTitle(); - // TODO: 对于appId为空的情况,使用title过滤,此项修改针对浏览器下载窗口 - - } - - // 先使用appId获取appInfo,如果不能成功获取再使用GIO_LAUNCHED_DESKTOP_FILE环境变量获取 - AppInfo *appInfo = new AppInfo(appId); - if (!appInfo->isValidApp() && winInfo->getProcess()) { - ProcessInfo *process = winInfo->getProcess(); - std::string desktopFilePath = process->getEnv("GIO_LAUNCHED_DESKTOP_FILE"); - if (DString::endWith(desktopFilePath, ".desktop")) { - appInfo = new AppInfo(desktopFilePath.c_str()); - } - } - - // autoStart - if (appInfo->isValidApp()) { - AppInfo *fixedAppInfo = fixAutostartAppInfo(appInfo->getFileName()); - if (fixedAppInfo) { - delete appInfo; - appInfo = fixedAppInfo; - appInfo->setIdentifyMethod("FixAutostart"); - } - } - - if (appInfo) - innerId = appInfo->getInnerId(); - - return appInfo; -} - -AppInfo *WindowIdentify::identifyWindowAndroid(Dock *_dock, WindowInfoX *winInfo, QString &innerId) -{ - AppInfo *ret = nullptr; - int32_t androidId = getAndroidUengineId(winInfo->getXid()); - QString androidName = getAndroidUengineName(winInfo->getXid()); - if (androidId != -1 && androidName != "") { - QString desktopPath = "/usr/share/applications/uengine." + androidName + ".desktop"; - DesktopInfo desktopInfo(desktopPath.toStdString()); - if (!desktopInfo.isValidDesktop()) { - qInfo() << "identifyWindowAndroid: not exist DesktopFile " << desktopPath; - return ret; - } - - ret = new AppInfo(desktopInfo); - ret->setIdentifyMethod("Android"); - innerId = ret->getInnerId(); - } - - return ret; -} - -AppInfo *WindowIdentify::identifyWindowByPidEnv(Dock *_dock, WindowInfoX *winInfo, QString &innerId) -{ - AppInfo *ret = nullptr; - int pid = winInfo->getPid(); - auto process = winInfo->getProcess(); - qInfo() << "identifyWindowByPidEnv: pid=" << pid << " WindowId=" << winInfo->getXid(); - - if (pid == 0 || !process) { - return ret; - } - - QString launchedDesktopFile = process->getEnv("GIO_LAUNCHED_DESKTOP_FILE").c_str(); - QString launchedDesktopFilePidStr = process->getEnv("GIO_LAUNCHED_DESKTOP_FILE_PID").c_str(); - int launchedDesktopFilePid = launchedDesktopFilePidStr.toInt(); - qInfo() << "launchedDesktopFilePid=" << launchedDesktopFilePid << " launchedDesktopFile=" << launchedDesktopFile; - - if (launchedDesktopFile.isEmpty()) { - return ret; - } - - auto pidIsSh = [](int pid) -> bool { - Process parentProcess(pid); - auto parentCmdLine = parentProcess.getCmdLine(); - if (parentCmdLine.size() <= 0) { - return false; - } - - qInfo() << "ppid equal" << "parentCmdLine[0]:" << parentCmdLine[0].c_str(); - QString cmd0 = parentCmdLine[0].c_str(); - int pos = cmd0.lastIndexOf('/'); - if (pos > 0) - cmd0 = cmd0.remove(0, pos + 1); - - if (cmd0 == "sh" || cmd0 == "bash"){ - return true; - } - - return false; - }; - - auto processInLinglong = [](ProcessInfo* const process) -> bool { - for (Process p(process->getPpid()); p.getPid() != 0; p = Process(p.getPpid())) { - if (!p.getCmdLine().size()){ - qWarning() << "Failed to get command line of" << p.getPid() << " SKIP it."; - continue; - } - if (p.getCmdLine()[0].find("ll-box") != std::string::npos) { - qDebug() << "process ID" << process->getPid() << "is in linglong container," - <<"ll-box PID" << p.getPid(); - return true; - } - } - return false; - }; - - // 以下几种情况下,才能信任环境变量 GIO_LAUNCHED_DESKTOP_FILE。 - if (pid == launchedDesktopFilePid || // 当窗口pid和launchedDesktopFilePid相同时 - ( process->getPpid() && - process->getPpid() == launchedDesktopFilePid && - pidIsSh(process->getPpid()) - ) || // 当窗口的进程的父进程id(即ppid)和launchedDesktopFilePid相同,并且该父进程是sh或bash时。 - processInLinglong(process) // 当窗口pid在玲珑容器中 - ) { - - ret = new AppInfo(launchedDesktopFile); - innerId = ret->getInnerId(); - } - - return ret; -} - -AppInfo *WindowIdentify::identifyWindowByCmdlineTurboBooster(Dock *_dock, WindowInfoX *winInfo, QString &innerId) -{ - AppInfo *ret = nullptr; - int pid = winInfo->getPid(); - ProcessInfo *process = winInfo->getProcess(); - if (pid != 0 && process) { - auto cmdline = process->getCmdLine(); - if (cmdline.size() > 0) { - QString desktopFile; - if (DString::endWith(cmdline[0], ".desktop")) { - desktopFile = cmdline[0].c_str(); - } else if (QString(cmdline[0].c_str()).contains("/applications/")) { - QFileInfo fileInfo(cmdline[0].c_str()); - QString path = fileInfo.path(); - QString base = fileInfo.completeBaseName(); - QDir dir(path); - QStringList files = dir.entryList(QDir::Files); - for (auto f : files) { - if (f.contains(path + "/" + base + ".desktop")) { - desktopFile = f; - break; - } - } - - qInfo() << "identifyWindowByCmdlineTurboBooster: desktopFile is " << desktopFile; - if (!desktopFile.isEmpty()) { - ret = new AppInfo(desktopFile); - innerId = ret->getInnerId(); - } - } - } - } - - return ret; -} - -AppInfo *WindowIdentify::identifyWindowByCmdlineXWalk(Dock *_dock, WindowInfoX *winInfo, QString &innerId) -{ - qInfo() << "identifyWindowByCmdlineXWalk: windowId=" << winInfo->getXid(); - AppInfo *ret = nullptr; - do { - auto process = winInfo->getProcess(); - if (!process || !winInfo->getPid()) - break; - - QString exe = process->getExe().c_str(); - QFileInfo file(exe); - QString exeBase = file.completeBaseName(); - auto args = process->getArgs(); - if (exe != "xwalk" || args.size() == 0) - break; - - QString lastArg = args[args.size() - 1].c_str(); - file.setFile(lastArg); - if (file.completeBaseName() == "manifest.json") { - auto strs = lastArg.split("/"); - if (strs.size() > 3 && strs[strs.size() - 2].size() > 0) { // appId为 strs倒数第二个字符串 - ret = new AppInfo(strs[strs.size() - 2]); - innerId = ret->getInnerId(); - break; - } - } - - qInfo() << "identifyWindowByCmdlineXWalk: failed"; - } while (0); - - return ret; -} - -AppInfo *WindowIdentify::identifyWindowByFlatpakAppID(Dock *_dock, WindowInfoX *winInfo, QString &innerId) -{ - AppInfo *ret = nullptr; - QString flatpak = winInfo->getFlatpakAppId(); - qInfo() << "identifyWindowByFlatpakAppID: flatpak:" << flatpak; - if (flatpak.startsWith("app/")) { - auto parts = flatpak.split("/"); - if (parts.size() > 0) { - QString appId = parts[1]; - ret = new AppInfo(appId); - innerId = ret->getInnerId(); - } - } - - return ret; -} - -AppInfo *WindowIdentify::identifyWindowByCrxId(Dock *_dock, WindowInfoX *winInfo, QString &innerId) -{ - AppInfo *ret = nullptr; - WMClass wmClass = XCB->getWMClass(winInfo->getXid()); - QString className, instanceName; - className.append(wmClass.className.c_str()); - instanceName.append(wmClass.instanceName.c_str()); - - if (className.toLower() == "chromium-browser" && instanceName.toLower().startsWith("crx_")) { - if (crxAppIdMap.find(instanceName.toLower()) != crxAppIdMap.end()) { - QString appId = crxAppIdMap[instanceName.toLower()]; - qInfo() << "identifyWindowByCrxId: appId " << appId; - ret = new AppInfo(appId); - innerId = ret->getInnerId(); - } - } - - return ret; -} - -AppInfo *WindowIdentify::identifyWindowByRule(Dock *_dock, WindowInfoX *winInfo, QString &innerId) -{ - static WindowPatterns patterns; - qInfo() << "identifyWindowByRule: windowId=" << winInfo->getXid(); - AppInfo *ret = nullptr; - QString matchStr = patterns.match(winInfo); - if (matchStr.isEmpty()) - return ret; - - if (matchStr.size() > 4 && matchStr.startsWith("id=")) { - matchStr.remove(0, 3); - ret = new AppInfo(matchStr); - } else if (matchStr == "env") { - auto process = winInfo->getProcess(); - if (process) { - QString launchedDesktopFile = process->getEnv("GIO_LAUNCHED_DESKTOP_FILE").c_str(); - if (!launchedDesktopFile.isEmpty()) - ret = new AppInfo(launchedDesktopFile); - } - } else { - qInfo() << "patterns match bad result"; - } - - if (ret) - innerId = ret->getInnerId(); - - return ret; -} - -AppInfo *WindowIdentify::identifyWindowByBamf(Dock *_dock, WindowInfoX *winInfo, QString &innerId) -{ - if (_dock->isWaylandEnv()) { - return nullptr; - } - - AppInfo *ret = nullptr; - XWindow xid = winInfo->getXid(); - qInfo() << "identifyWindowByBamf: windowId=" << xid; - QString desktopFile; - // 重试 bamf 识别,部分的窗口经常要多次调用才能识别到。 - for (int i = 0; i < 3; i++) { - desktopFile = _dock->getDesktopFromWindowByBamf(xid); - if (!desktopFile.isEmpty()) - break; - } - - if (!desktopFile.isEmpty()) { - ret = new AppInfo(desktopFile); - innerId = ret->getInnerId(); - } - - return ret; -} - -AppInfo *WindowIdentify::identifyWindowByPid(Dock *_dock, WindowInfoX *winInfo, QString &innerId) -{ - AppInfo *ret = nullptr; - if (winInfo->getPid() > 10) { - auto entry = _dock->getEntryByWindowId(winInfo->getPid()); - if (entry) { - ret = entry->getApp(); - innerId = ret->getInnerId(); - } - } - - return ret; -} - -AppInfo *WindowIdentify::identifyWindowByScratch(Dock *_dock, WindowInfoX *winInfo, QString &innerId) -{ - AppInfo *ret = nullptr; - QString desktopFile = scratchDir + winInfo->getInnerId() + ".desktop"; - qInfo() << "identifyWindowByScratch: xid " << winInfo->getXid() << " desktopFile" << desktopFile; - QFile file(desktopFile); - - if (file.exists()) { - ret = new AppInfo(desktopFile); - innerId = ret->getInnerId(); - } - return ret; -} - -AppInfo *WindowIdentify::identifyWindowByGtkAppId(Dock *_dock, WindowInfoX *winInfo, QString &innerId) -{ - AppInfo *ret = nullptr; - QString gtkAppId = winInfo->getGtkAppId(); - if (!gtkAppId.isEmpty()) { - ret = new AppInfo(gtkAppId); - innerId = ret->getInnerId(); - } - - qInfo() << "identifyWindowByGtkAppId: gtkAppId:" << gtkAppId; - return ret; -} - -AppInfo *WindowIdentify::identifyWindowByWmClass(Dock *_dock, WindowInfoX *winInfo, QString &innerId) -{ - WMClass wmClass = winInfo->getWMClass(); - if (wmClass.instanceName.size() > 0) { - // example: - // WM_CLASS(STRING) = "Brackets", "Brackets" - // wm class instance is Brackets - // try app id org.deepin.flatdeb.brackets - //ret = new AppInfo("org.deepin.flatdeb." + QString(wmClass.instanceName.c_str()).toLower()); - if (DesktopInfo("org.deepin.flatdeb." + QString(wmClass.instanceName.c_str()).toLower().toStdString()).isValidDesktop()) { - AppInfo *appInfo = new AppInfo("org.deepin.flatdeb." + QString(wmClass.instanceName.c_str()).toLower()); - innerId = appInfo->getInnerId(); - return appInfo; - } - - if (DesktopInfo(wmClass.instanceName).isValidDesktop()) { - AppInfo *appInfo = new AppInfo(wmClass.instanceName.c_str()); - innerId = appInfo->getInnerId(); - return appInfo; - } - } - - if (wmClass.className.size() > 0) { - std::string filename = wmClass.className; - bool isValid = DesktopInfo(filename).isValidDesktop(); - if (!isValid) { - filename = DesktopFileReader::instance()->fileName(wmClass.instanceName.c_str()).toStdString(); - isValid = DesktopInfo(filename).isValidDesktop(); - } - - if (isValid) { - AppInfo *appInfo = new AppInfo(filename.c_str()); - innerId = appInfo->getInnerId(); - return appInfo; - } - } - - return nullptr; -} - -AppInfo *WindowIdentify::fixAutostartAppInfo(QString fileName) -{ - QFileInfo file(fileName); - QString filePath = file.absolutePath(); - bool isAutoStart = false; - for (auto &dir : BaseDir::autoStartDirs()) { - if (QString(dir.c_str()).contains(filePath)) { - isAutoStart = true; - break; - } - } - - return isAutoStart ? new AppInfo(file.completeBaseName()) : nullptr; -} - -int32_t WindowIdentify::getAndroidUengineId(XWindow winId) -{ - // TODO 获取AndroidUengineId - return 0; -} - -QString WindowIdentify::getAndroidUengineName(XWindow winId) -{ - // TODO 获取AndroidUengineName - return ""; -} diff --git a/src/modules/dock/windowidentify.h b/src/modules/dock/windowidentify.h deleted file mode 100644 index 5b386cb..0000000 --- a/src/modules/dock/windowidentify.h +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef WINDOWIDENTIFY_H -#define WINDOWIDENTIFY_H - -#include "windowpatterns.h" -#include "windowinfok.h" -#include "windowinfox.h" - -#include -#include -#include - -class AppInfo; -class Dock; - -typedef AppInfo *(*IdentifyFunc)(Dock *, WindowInfoX*, QString &innerId); - -// 应用窗口识别类 -class WindowIdentify : public QObject -{ - Q_OBJECT - -public: - explicit WindowIdentify(Dock *_dock, QObject *parent = nullptr); - - AppInfo *identifyWindow(WindowInfoBase *winInfo, QString &innerId); - AppInfo *identifyWindowX11(WindowInfoX *winInfo, QString &innerId); - AppInfo *identifyWindowWayland(WindowInfoK *winInfo, QString &innerId); - - static AppInfo *identifyWindowAndroid(Dock *_dock, WindowInfoX *winInfo, QString &innerId); - static AppInfo *identifyWindowByPidEnv(Dock *_dock, WindowInfoX *winInfo, QString &innerId); - static AppInfo *identifyWindowByCmdlineTurboBooster(Dock *_dock, WindowInfoX *winInfo, QString &innerId); - static AppInfo *identifyWindowByCmdlineXWalk(Dock *_dock, WindowInfoX *winInfo, QString &innerId); - static AppInfo *identifyWindowByFlatpakAppID(Dock *_dock, WindowInfoX *winInfo, QString &innerId); - static AppInfo *identifyWindowByCrxId(Dock *_dock, WindowInfoX *winInfo, QString &innerId); - static AppInfo *identifyWindowByRule(Dock *_dock, WindowInfoX *winInfo, QString &innerId); - static AppInfo *identifyWindowByBamf(Dock *_dock, WindowInfoX *winInfo, QString &innerId); - static AppInfo *identifyWindowByPid(Dock *_dock, WindowInfoX *winInfo, QString &innerId); - static AppInfo *identifyWindowByScratch(Dock *_dock, WindowInfoX *winInfo, QString &innerId); - static AppInfo *identifyWindowByGtkAppId(Dock *_dock, WindowInfoX *winInfo, QString &innerId); - static AppInfo *identifyWindowByWmClass(Dock *_dock, WindowInfoX *winInfo, QString &innerId); - -private: - AppInfo *fixAutostartAppInfo(QString fileName); - static int32_t getAndroidUengineId(XWindow winId); - static QString getAndroidUengineName(XWindow winId); - -private: - Dock *m_dock; - QList> m_identifyWindowFuns; -}; - -#endif // IDENTIFYWINDOW_H diff --git a/src/modules/dock/windowinfobase.h b/src/modules/dock/windowinfobase.h deleted file mode 100644 index 33aba72..0000000 --- a/src/modules/dock/windowinfobase.h +++ /dev/null @@ -1,68 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef WINDOWINFOBASE_H -#define WINDOWINFOBASE_H - -#include "processinfo.h" -#include "xcbutils.h" - -#include -#include - -class Entry; -class AppInfo; - -class WindowInfoBase -{ -public: - WindowInfoBase() : entry(nullptr), app(nullptr), processInfo(nullptr) {} - virtual ~WindowInfoBase() { - if (processInfo) { - delete processInfo; - } - } - - virtual bool shouldSkip() = 0; - virtual QString getIcon() = 0; - virtual QString getTitle() = 0; - virtual bool isDemandingAttention() = 0; - virtual void close(uint32_t timestamp) = 0; - virtual void activate() = 0; - virtual void minimize() = 0; - virtual bool isMinimized() = 0; - virtual int64_t getCreatedTime() = 0; - virtual QString getWindowType() = 0; - virtual QString getDisplayName() = 0; - virtual bool allowClose() = 0; - virtual void update() = 0; - virtual void killClient() = 0; - virtual QString uuid() = 0; - virtual QString getInnerId() { return innerId; } - - XWindow getXid() {return xid;} - void setEntry(Entry *value) { entry = value; } - Entry *getEntry() { return entry; } - QString getEntryInnerId() { return entryInnerId; } - void setEntryInnerId(QString value) { entryInnerId = value; } - AppInfo *getAppInfo() { return app; } - void setAppInfo(AppInfo *value) { app = value; } - int getPid() { return pid; } - ProcessInfo *getProcess() { return processInfo; } - bool containAtom(QVector supports, XCBAtom ty) {return supports.indexOf(ty) != -1;} - -protected: - XWindow xid; // 窗口id - QString title; // 窗口标题 - QString icon; // 窗口图标 - int pid; // 窗口所属应用进程 - QString entryInnerId; // 窗口所属应用对应的innerId - QString innerId; // 窗口对应的innerId - Entry *entry; // 窗口所属应用 - AppInfo *app; // 窗口所属应用对应的desktopFile信息 - ProcessInfo *processInfo; // 窗口所属应用的进程信息 - int64_t createdTime; // 创建时间 -}; - -#endif // WINDOWINFOBASE_H diff --git a/src/modules/dock/windowinfok.cpp b/src/modules/dock/windowinfok.cpp deleted file mode 100644 index a782c5b..0000000 --- a/src/modules/dock/windowinfok.cpp +++ /dev/null @@ -1,210 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "windowinfok.h" -#include "entry.h" -#include "processinfo.h" -#include "appinfo.h" - -#include - -WindowInfoK::WindowInfoK(PlasmaWindow *window, XWindow _xid) - : WindowInfoBase () - , m_updateCalled(false) - , m_internalId(0) - , m_demaningAttention(false) - , m_closeable(true) - , m_plasmaWindow(window) -{ - xid = _xid; - createdTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); // 获取当前时间,精确到纳秒 -} - -WindowInfoK::~WindowInfoK() -{ - delete m_plasmaWindow; -} - -bool WindowInfoK::shouldSkip() -{ - if (!m_updateCalled) { - update(); - m_updateCalled = true; - } - - bool skip = m_plasmaWindow->SkipTaskbar(); - - // 添加窗口能否最小化判断, 如果窗口不能最小化则隐藏任务栏图标 - bool canMinimize = false; - canMinimize = m_plasmaWindow->IsMinimizeable(); - if (!canMinimize) - skip = true; - - if (skip) { - // 白名单, 过滤类似“欢迎应用”, 没有最小化窗口但是需要在任务栏显示图标 - QStringList list { "dde-introduction"}; - if (list.indexOf(m_appId) != -1) - skip = false; - } - - return skip; -} - -QString WindowInfoK::getIcon() -{ - return icon; -} - -QString WindowInfoK::getTitle() -{ - return title; -} - -bool WindowInfoK::isDemandingAttention() -{ - return m_demaningAttention; -} - -bool WindowInfoK::allowClose() -{ - return m_closeable; -} - -void WindowInfoK::close(uint32_t timestamp) -{ - m_plasmaWindow->RequestClose(); -} - -QString WindowInfoK::getAppId() -{ - return m_appId; -} - -void WindowInfoK::setAppId(QString _appId) -{ - m_appId = _appId; -} - -void WindowInfoK::activate() -{ - m_plasmaWindow->RequestActivate(); -} - -void WindowInfoK::minimize() -{ - m_plasmaWindow->RequestToggleMinimized(); -} - -bool WindowInfoK::isMinimized() -{ - return m_plasmaWindow->IsMinimized(); -} - -bool WindowInfoK::changeXid(XWindow _xid) -{ - xid = _xid; - return true; -} - -PlasmaWindow *WindowInfoK::getPlasmaWindow() -{ - return m_plasmaWindow; -} - -bool WindowInfoK::updateGeometry() -{ - DockRect rect = m_plasmaWindow->Geometry(); - if (m_geometry == rect) - return false; - - m_geometry = rect; - return true; -} - -void WindowInfoK::updateTitle() -{ - title = m_plasmaWindow->Title(); -} - -void WindowInfoK::updateDemandingAttention() -{ - m_demaningAttention = m_plasmaWindow->IsDemandingAttention(); -} - -void WindowInfoK::updateIcon() -{ - icon = m_plasmaWindow->Icon(); -} - -void WindowInfoK::updateAppId() -{ - m_appId = m_plasmaWindow->AppId(); -} - -void WindowInfoK::updateInternalId() -{ - m_internalId = m_plasmaWindow->InternalId(); -} - -void WindowInfoK::updateCloseable() -{ - m_closeable = m_plasmaWindow->IsCloseable(); -} - -void WindowInfoK::updateProcessInfo() -{ - pid = m_plasmaWindow->Pid(); - processInfo = new ProcessInfo(pid); -} - -/** - * @brief WindowInfoK::getGeometry 获取窗口大小 - * @return - */ -DockRect WindowInfoK::getGeometry() -{ - return m_geometry; -} - -int64_t WindowInfoK::getCreatedTime() -{ - return createdTime; -} - -// 主要是为兼容X11 -QString WindowInfoK::getDisplayName() -{ - return ""; -} - -QString WindowInfoK::getWindowType() -{ - return "Wayland"; -} - -void WindowInfoK::update() -{ - updateInternalId(); - updateAppId(); - updateIcon(); - updateTitle(); - updateGeometry(); - updateDemandingAttention(); - updateCloseable(); - updateProcessInfo(); -} - -void WindowInfoK::killClient() -{ -} - -QString WindowInfoK::uuid() -{ - return QString(m_plasmaWindow->Uuid()); -} - -QString WindowInfoK::getInnerId() -{ - return QString::number(m_internalId); -} diff --git a/src/modules/dock/windowinfok.h b/src/modules/dock/windowinfok.h deleted file mode 100644 index dff044b..0000000 --- a/src/modules/dock/windowinfok.h +++ /dev/null @@ -1,66 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef WINDOWINFOK_H -#define WINDOWINFOK_H - -#include "windowinfobase.h" -#include "dbusplasmawindow.h" - -#include - -using PlasmaWindow = org::deepin::dde::kwayland1::PlasmaWindow; - -class Entry; -class ProcessInfo; - -// wayland下窗口信息 -class WindowInfoK: public WindowInfoBase -{ -public: - explicit WindowInfoK(PlasmaWindow *window, XWindow _xid = 0); - virtual ~WindowInfoK() override; - - virtual bool shouldSkip() override; - virtual QString getIcon() override; - virtual QString getTitle() override; - virtual bool isDemandingAttention() override; - virtual bool allowClose() override; - virtual void close(uint32_t timestamp) override; - virtual void activate() override; - virtual void minimize() override; - virtual bool isMinimized() override; - virtual int64_t getCreatedTime() override; - virtual QString getDisplayName() override; - virtual QString getWindowType() override; - virtual void update() override; - virtual void killClient() override; - virtual QString uuid() override; - QString getInnerId() override; - - QString getAppId(); - void setAppId(QString _appId); - bool changeXid(XWindow _xid); - PlasmaWindow *getPlasmaWindow(); - bool updateGeometry(); - void updateTitle(); - void updateDemandingAttention(); - void updateIcon(); - void updateAppId(); - void updateInternalId(); - void updateCloseable(); - void updateProcessInfo(); - DockRect getGeometry(); - -private: - bool m_updateCalled; - QString m_appId; - uint32_t m_internalId; - bool m_demaningAttention; - bool m_closeable; - PlasmaWindow *m_plasmaWindow; - DockRect m_geometry; -}; - -#endif // WINDOWINFOK_H diff --git a/src/modules/dock/windowinfox.cpp b/src/modules/dock/windowinfox.cpp deleted file mode 100644 index be4ab5c..0000000 --- a/src/modules/dock/windowinfox.cpp +++ /dev/null @@ -1,471 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "windowinfox.h" -#include "appinfo.h" -#include "xcbutils.h" -#include "dstring.h" -#include "common.h" -#include "processinfo.h" - -#include -#include -#include -#include -#include -#include - -#include - -#define XCB XCBUtils::instance() - -WindowInfoX::WindowInfoX(XWindow _xid) - : WindowInfoBase () - , m_x(0) - , m_y(0) - , m_width(0) - , m_height(0) - , m_hasWMTransientFor(false) - , m_hasXEmbedInfo(false) - , m_updateCalled(false) -{ - xid = _xid; - createdTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); // 获取当前时间,精确到纳秒 -} - -WindowInfoX::~WindowInfoX() -{ - -} - -bool WindowInfoX::shouldSkip() -{ - qInfo() << "window " << xid << " shouldSkip?"; - if (!m_updateCalled) { - update(); - m_updateCalled = true; - } - - if (hasWmStateSkipTaskBar() || isValidModal() || shouldSkipWithWMClass()) - return true; - - for (auto atom : m_wmWindowType) { - if (atom == XCB->getAtom("_NET_WM_WINDOW_TYPE_DIALOG") && !isActionMinimizeAllowed()) - return true; - - if (atom == XCB->getAtom("_NET_WM_WINDOW_TYPE_UTILITY") - || atom == XCB->getAtom("_NET_WM_WINDOW_TYPE_COMBO") - || atom == XCB->getAtom("_NET_WM_WINDOW_TYPE_DESKTOP") // 桌面属性窗口 - || atom == XCB->getAtom("_NET_WM_WINDOW_TYPE_DND") - || atom == XCB->getAtom("_NET_WM_WINDOW_TYPE_DOCK") // 任务栏属性窗口 - || atom == XCB->getAtom("_NET_WM_WINDOW_TYPE_DROPDOWN_MENU") - || atom == XCB->getAtom("_NET_WM_WINDOW_TYPE_MENU") - || atom == XCB->getAtom("_NET_WM_WINDOW_TYPE_NOTIFICATION") - || atom == XCB->getAtom("_NET_WM_WINDOW_TYPE_POPUP_MENU") - || atom == XCB->getAtom("_NET_WM_WINDOW_TYPE_SPLASH") - || atom == XCB->getAtom("_NET_WM_WINDOW_TYPE_TOOLBAR") - || atom == XCB->getAtom("_NET_WM_WINDOW_TYPE_TOOLTIP")) - return true; - } - - return false; -} - -QString WindowInfoX::getIcon() -{ - if (icon.isEmpty()) - icon = getIconFromWindow(); - - return icon; -} - -void WindowInfoX::activate() -{ - XCB->changeActiveWindow(xid); - QTimer::singleShot(50, [&] { - XCB->restackWindow(xid); - }); -} - -void WindowInfoX::minimize() -{ - XCB->minimizeWindow(xid); -} - -bool WindowInfoX::isMinimized() -{ - return containAtom(m_wmState, XCB->getAtom("_NET_WM_STATE_HIDDEN")); -} - -int64_t WindowInfoX::getCreatedTime() -{ - return createdTime; -} - -QString WindowInfoX::getWindowType() -{ - return "X11"; -} - -bool WindowInfoX::allowClose() -{ - // 允许关闭的条件: - // 1. 不设置 functions 字段,即MotifHintFunctions 标志位; - // 2. 或者设置了 functions 字段并且 设置了 MotifFunctionAll 标志位; - // 3. 或者设置了 functions 字段并且 设置了 MotifFunctionClose 标志位。 - // 相关定义在 motif-2.3.8/lib/Xm/MwmUtil.h 。 - if ((m_motifWmHints.flags & MotifHintFunctions) == 0 - || (m_motifWmHints.functions & MotifFunctionAll) != 0 - || (m_motifWmHints.functions & MotifFunctionClose) != 0) - return true; - - for (auto action : m_wmAllowedActions) { - if (action == XCB->getAtom("_NET_WM_ACTION_CLOSE")) { - return true; - } - } - - return false; -} - -QString WindowInfoX::getDisplayName() -{ - XWindow winId = xid; - //QString role = wmRole; - QString className(m_wmClass.className.c_str()); - QString instance; - if (m_wmClass.instanceName.size() > 0) { - int pos = QString(m_wmClass.instanceName.c_str()).lastIndexOf('/'); - if (pos != -1) - instance.remove(0, pos + 1); - } - qInfo() << "getDisplayName class:" << className << " ,instance:" << instance; - - //if (!role.isEmpty() && !className.isEmpty()) - // return className + " " + role; - - if (!className.isEmpty()) - return className; - - if (!instance.isEmpty()) - return instance; - - - QString _wmName = m_wmName; - if (!_wmName.isEmpty()) { - int pos = _wmName.lastIndexOf('-'); - if (pos != -1 && !_wmName.startsWith("-")) { - _wmName.truncate(pos); - return _wmName; - } - } - - if (processInfo) { - QString exe {processInfo->getEnv("exe").c_str()}; - if (!exe.isEmpty()) - return exe; - } - - return QString("window:%1").arg(winId); -} - -void WindowInfoX::killClient() -{ - XCB->killClientChecked(xid); -} - -QString WindowInfoX::uuid() -{ - return QString(); -} - -QString WindowInfoX::getGtkAppId() -{ - return m_gtkAppId; -} - -QString WindowInfoX::getFlatpakAppId() -{ - return m_flatpakAppId; -} - -QString WindowInfoX::getWmRole() -{ - return m_wmRole; -} - -WMClass WindowInfoX::getWMClass() -{ - return m_wmClass; -} - -QString WindowInfoX::getWMName() -{ - return m_wmName; -} - -ConfigureEvent *WindowInfoX::getLastConfigureEvent() -{ - return m_lastConfigureNotifyEvent; -} - -void WindowInfoX::setLastConfigureEvent(ConfigureEvent *event) -{ - m_lastConfigureNotifyEvent = event; -} - -bool WindowInfoX::isGeometryChanged(int _x, int _y, int _width, int _height) -{ - return !(_x == m_x && _y == m_y && _width == m_width && _height == m_height); -} - -void WindowInfoX::setGtkAppId(QString _gtkAppId) -{ - m_gtkAppId = _gtkAppId; -} - -void WindowInfoX::updateMotifWmHints() -{ - // get from XCB - m_motifWmHints = XCB->getWindowMotifWMHints(xid); -} - -// XEmbed info -// 一般 tray icon 会带有 _XEMBED_INFO 属性 -void WindowInfoX::updateHasXEmbedInfo() -{ - m_hasXEmbedInfo = XCB->hasXEmbedInfo(xid); -} - -/** - * @brief WindowInfoX::genInnerId 生成innerId - * @param winInfo - * @return - */ -QString WindowInfoX::genInnerId(WindowInfoX *winInfo) -{ - XWindow winId = winInfo->getXid(); - QString wmClassName, wmInstance; - WMClass wmClass = winInfo->getWMClass(); - if (wmClass.className.size() > 0) - wmClassName = wmClass.className.c_str(); - - if (wmClass.instanceName.size() > 0) { - QString instanceName(wmClass.instanceName.c_str()); - instanceName.remove(0, instanceName.lastIndexOf('/') + 1); - wmInstance = instanceName; - } - - QString exe, args; - if (winInfo->getProcess()) { - exe = winInfo->getProcess()->getExe().c_str(); - for (auto arg : winInfo->getProcess()->getArgs()) { - QString argStr(arg.c_str()); - if (argStr.contains("/") || argStr == "." || argStr == "..") { - args += "%F "; - } else { - args += argStr + " "; - } - } - - if (args.size() > 0) - args.remove(args.size() - 2, 1); - } - - bool hasPid = winInfo->getPid() != 0; - QString str; - // NOTE: 不要使用 wmRole,有些程序总会改变这个值比如 GVim - if (wmInstance.isEmpty() && wmClassName.isEmpty() && exe.isEmpty() && winInfo->getGtkAppId().isEmpty()) { - if (!winInfo->getWMName().isEmpty()) - str = QString("wmName:%1").arg(winInfo->getWMName()); - else - str = QString("windowId:%1").arg(winInfo->getXid()); - } else { - str = QString("wmInstance:%1,wmClass:%2,exe:%3,args:%4,hasPid:%5,gtkAppId:%6").arg(wmInstance).arg(wmClassName).arg(exe).arg(args).arg(hasPid).arg(winInfo->getGtkAppId()); - } - - QByteArray encryText = QCryptographicHash::hash(str.toLatin1(), QCryptographicHash::Md5); - QString innerId = windowHashPrefix + encryText.toHex(); - qInfo() << "genInnerId window " << winId << " innerId :" << innerId; - return innerId; -} - -// 更新窗口类型 -void WindowInfoX::updateWmWindowType() -{ - m_wmWindowType.clear(); - for (auto ty : XCB->getWMWindoType(xid)) { - m_wmWindowType.push_back(ty); - } -} - -// 更新窗口许可动作 -void WindowInfoX::updateWmAllowedActions() -{ - m_wmAllowedActions.clear(); - for (auto action : XCB->getWMAllowedActions(xid)) { - m_wmAllowedActions.push_back(action); - } -} - -void WindowInfoX::updateWmState() -{ - m_wmState.clear(); - for (auto a : XCB->getWMState(xid)) { - m_wmState.push_back(a); - } -} - -void WindowInfoX::updateWmClass() -{ - m_wmClass = XCB->getWMClass(xid); -} - -void WindowInfoX::updateWmName() -{ - auto name = XCB->getWMName(xid); - if (!name.empty()) - m_wmName = name.c_str(); - - title = getTitle(); -} - -void WindowInfoX::updateIcon() -{ - icon = getIconFromWindow(); -} - -void WindowInfoX::updateHasWmTransientFor() -{ - if (XCB->getWMTransientFor(xid) == 1) - m_hasWMTransientFor = true; -} - -/** - * @brief WindowInfoX::update 更新窗口信息(在识别窗口时执行一次) - */ -void WindowInfoX::update() -{ - updateWmClass(); - updateWmState(); - updateWmWindowType(); - updateWmAllowedActions(); - updateHasWmTransientFor(); - updateProcessInfo(); - updateWmName(); - innerId = genInnerId(this); -} - -QString WindowInfoX::getIconFromWindow() -{ - WMIcon icon = XCB->getWMIcon(xid); - - // invalid icon - if (icon.width == 0) { - return QString(); - } - - QImage img = QImage((uchar *)icon.data.data(), icon.width, icon.width, QImage::Format_ARGB32); - QBuffer buffer; - buffer.open(QIODevice::WriteOnly); - img.scaled(48, 48, Qt::KeepAspectRatio, Qt::SmoothTransformation); - img.save(&buffer, "PNG"); - - // convert to base64 - QString encode = buffer.data().toBase64(); - QString iconPath = QString("%1,%2").arg("data:image/png:base64").arg(encode); - buffer.close(); - - return iconPath; -} - -bool WindowInfoX::isActionMinimizeAllowed() -{ - return containAtom(m_wmAllowedActions, XCB->getAtom("_NET_WM_ACTION_MINIMIZE")); -} - -bool WindowInfoX::hasWmStateDemandsAttention() -{ - return containAtom(m_wmState, XCB->getAtom("_NET_WM_STATE_DEMANDS_ATTENTION")); -} - -bool WindowInfoX::hasWmStateSkipTaskBar() -{ - return containAtom(m_wmState, XCB->getAtom("_NET_WM_STATE_SKIP_TASKBAR")); -} - -bool WindowInfoX::hasWmStateModal() -{ - return containAtom(m_wmState, XCB->getAtom("_NET_WM_STATE_MODAL")); -} - -bool WindowInfoX::isValidModal() -{ - return hasWmStateModal() && hasWmStateModal(); -} - -// 通过WMClass判断是否需要隐藏此窗口 -bool WindowInfoX::shouldSkipWithWMClass() -{ - bool ret = false; - if (m_wmClass.instanceName == "explorer.exe" && m_wmClass.className == "Wine") - ret = true; - else if (m_wmClass.className == "dde-launcher" || - m_wmClass.className == "dde-dock" || - m_wmClass.className == "dde-lock") { - ret = true; - } - - return ret; -} - -void WindowInfoX::updateProcessInfo() -{ - XWindow winId = xid; - pid = XCB->getWMPid(winId); - if (processInfo) - delete processInfo; - - qInfo() << "updateProcessInfo: pid=" << pid; - processInfo = new ProcessInfo(pid); - if (!processInfo->isValid()) { - // try WM_COMMAND - auto wmComand = XCB->getWMCommand(winId); - if (wmComand.size() > 0) { - delete processInfo; - processInfo = new ProcessInfo(wmComand); - } - } - - qInfo() << "updateProcessInfo: pid is " << pid; -} - -bool WindowInfoX::getUpdateCalled() -{ - return m_updateCalled; -} - -void WindowInfoX::setInnerId(QString _innerId) -{ - innerId = _innerId; -} - -QString WindowInfoX::getTitle() -{ - QString name = m_wmName; - if (name.isEmpty()) - name = getDisplayName(); - - return name; -} - -bool WindowInfoX::isDemandingAttention() -{ - return hasWmStateDemandsAttention(); -} - -void WindowInfoX::close(uint32_t timestamp) -{ - XCB->requestCloseWindow(xid, timestamp); -} diff --git a/src/modules/dock/windowinfox.h b/src/modules/dock/windowinfox.h deleted file mode 100644 index b024337..0000000 --- a/src/modules/dock/windowinfox.h +++ /dev/null @@ -1,95 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef WINDOWINFOX_H -#define WINDOWINFOX_H - -#include "windowinfobase.h" -#include "xcbutils.h" - -#include - -class AppInfo; - -// X11下窗口信息 在明确X11环境下使用 -class WindowInfoX: public WindowInfoBase -{ -public: - WindowInfoX(XWindow _xid = 0); - virtual ~WindowInfoX() override; - - virtual bool shouldSkip() override; - virtual QString getIcon() override; - virtual QString getTitle() override; - virtual bool isDemandingAttention() override; - virtual void close(uint32_t timestamp) override; - virtual void activate() override; - virtual void minimize() override; - virtual bool isMinimized() override; - virtual int64_t getCreatedTime() override; - virtual QString getDisplayName() override; - virtual QString getWindowType() override; - virtual bool allowClose() override; - virtual void update() override; - virtual void killClient() override; - virtual QString uuid() override; - - QString genInnerId(WindowInfoX *winInfo); - QString getGtkAppId(); - QString getFlatpakAppId(); - QString getWmRole(); - WMClass getWMClass(); - QString getWMName(); - void updateProcessInfo(); - bool getUpdateCalled(); - void setInnerId(QString _innerId); - ConfigureEvent *getLastConfigureEvent(); - void setLastConfigureEvent(ConfigureEvent *event); - bool isGeometryChanged(int _x, int _y, int _width, int _height); - void setGtkAppId(QString _gtkAppId); - - /************************更新XCB窗口属性*********************/ - void updateWmWindowType(); - void updateWmAllowedActions(); - void updateWmState(); - void updateWmClass(); - void updateMotifWmHints(); - void updateWmName(); - void updateIcon(); - void updateHasXEmbedInfo(); - void updateHasWmTransientFor(); - -private: - QString getIconFromWindow(); - bool isActionMinimizeAllowed(); - bool hasWmStateDemandsAttention(); - bool hasWmStateSkipTaskBar(); - bool hasWmStateModal(); - bool isValidModal(); - bool shouldSkipWithWMClass(); - -private: - int16_t m_x; - int16_t m_y; - uint16_t m_width; - uint16_t m_height; - QVector m_wmState; - QVector m_wmWindowType; - QVector m_wmAllowedActions; - bool m_hasWMTransientFor; - WMClass m_wmClass; - QString m_wmName; - bool m_hasXEmbedInfo; - - // 自定义atom属性 - QString m_gtkAppId; - QString m_flatpakAppId; - QString m_wmRole; - MotifWMHints m_motifWmHints; - - bool m_updateCalled; - ConfigureEvent *m_lastConfigureNotifyEvent; -}; - -#endif // WINDOWINFOX_H diff --git a/src/modules/dock/windowpatterns.cpp b/src/modules/dock/windowpatterns.cpp deleted file mode 100644 index 6184161..0000000 --- a/src/modules/dock/windowpatterns.cpp +++ /dev/null @@ -1,292 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "windowpatterns.h" -#include "common.h" -#include "processinfo.h" -#include "dfile.h" -#include "dstring.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -const int parsedFlagNegative = 0x001; -const int parsedFlagIgnoreCase = 0x010; - -bool contains(QString key, QString value) { - return key.contains(value); -} - -bool containsIgnoreCase(QString key, QString value) { - QString _key = key.toLower(); - QString _value = value.toLower(); - return _key.contains(_value); -} - -bool equal(QString key, QString value) { - return key == value; -} - -bool equalIgnoreCase(QString key, QString value) { - return key.toLower() == value.toLower(); -} - -bool regexMatch(QString key, QString value) { - QRegExp ruleRegex(value); - bool ret = ruleRegex.exactMatch(key); - - // 配置中\.exe$ 在V20中go代码可以匹配以.exe结尾的字符串, Qt中使用\.*exe$匹配以.exe结尾字符串失败,暂时做兼容处理 - if (!ret && value == "\\.exe$") { - ret = key.endsWith(".exe"); - } - return ret; -} - -bool regexMatchIgnoreCase(QString key, QString value) { - QRegExp ruleRegex(value, Qt::CaseInsensitive); - bool ret = ruleRegex.exactMatch(key); - - // 配置中\.exe$ 在V20中go代码可以匹配以.exe结尾的字符串, Qt中使用\.*exe$匹配以.exe结尾字符串失败,暂时做兼容处理 - if (!ret && value == "\\.exe$") { - QString _key = key.toLower(); - ret = _key.endsWith(".exe"); - } - return ret; -} - -RuleValueParse::RuleValueParse() - : negative(false) - , type(0) - , flags(0) -{ -} - -bool RuleValueParse::match(const WindowInfoX *winInfo) -{ - QString parsedKey = parseRuleKey(const_cast(winInfo), key); - if (!fn) - return false; - - bool ret = fn(parsedKey, value); - return negative ? !ret : ret; -} - -QString RuleValueParse::parseRuleKey(WindowInfoX *winInfo, const QString &ruleKey) -{ - ProcessInfo * process = winInfo->getProcess(); - if (ruleKey == "hasPid") { - if (process && process->initWithPid()) { - return "t"; - } - return "f"; - } else if (ruleKey == "exec") { - if (process) { - // 返回执行文件baseName - auto baseName = DFile::base(process->getExe()); - return baseName.empty() ? "" : baseName.c_str(); - } - } else if (ruleKey == "arg") { - if (process) { - // 返回命令行参数 - auto ret = DString::join(process->getArgs(), ""); - return ret.empty() ? "" : ret.c_str(); - } - } else if (ruleKey == "wmi") { - // 窗口实例 - auto wmClass = winInfo->getWMClass(); - if (!wmClass.instanceName.empty()) - return wmClass.instanceName.c_str(); - } else if (ruleKey == "wmc") { - // 窗口类型 - auto wmClass = winInfo->getWMClass(); - if (!wmClass.className.empty()) - return wmClass.className.c_str(); - } else if (ruleKey == "wmn") { - // 窗口名称 - return winInfo->getWMName(); - } else if (ruleKey == "wmrole") { - // 窗口角色 - return winInfo->getWmRole(); - } else { - const QString envPrefix = "env."; - if (ruleKey.startsWith(envPrefix)) { - QString envName = ruleKey.mid(envPrefix.size()); - if (winInfo->getProcess()) { - auto ret = process->getEnv(envName.toStdString()); - return ret.empty() ? "" : ret.c_str(); - } - } - } - - return ""; -} - - -WindowPatterns::WindowPatterns() -{ - loadWindowPatterns(); -} - -/** - * @brief WindowPatterns::match 匹配窗口类型 - * @param winInfo - * @return - */ -QString WindowPatterns::match(WindowInfoX *winInfo) -{ - for (auto pattern : m_patterns) { - bool patternOk = true; - for (auto rule : pattern.parseRules) { - if (!rule.match(winInfo)) { - patternOk = false; - break; - } - } - - if (patternOk) { - // 匹配成功 - return pattern.result; - } - } - - // 匹配失败 - return ""; -} - -void WindowPatterns::loadWindowPatterns() -{ - qInfo() << "---loadWindowPatterns"; - QFile file(windowPatternsFile); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) - return; - - QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); - file.close(); - if (!doc.isArray()) - return; - - QJsonArray arr = doc.array(); - if (arr.size() == 0) - return; - - m_patterns.clear(); - for (auto iterp = arr.begin(); iterp != arr.end(); iterp++) { - // 过滤非Object - if (!(*iterp).isObject()) - continue; - - QJsonObject patternObj = (*iterp).toObject(); - QVariantMap patternMap = patternObj.toVariantMap(); - WindowPattern pattern; - for (auto infoIter = patternMap.begin(); infoIter != patternMap.end(); infoIter++) { - QString ret = infoIter.key(); - QVariant value = infoIter.value(); - - if (ret == "ret") { - pattern.result = value.toString(); - } else if (ret == "rules") { - for (auto &item : value.toList()) { - if (!item.isValid()) - continue; - - if (item.toList().size() != 2) - continue; - - pattern.rules.push_back({item.toList()[0].toString(), item.toList()[1].toString()}); - } - } - } - qInfo() << pattern.result; - for (const auto &item : pattern.rules) { - qInfo() << item[0] << " " << item[1]; - } - m_patterns.push_back(pattern); - } - - // 解析patterns - for (auto &pattern : m_patterns) { - for (int i=0; i < pattern.rules.size(); i++) { - RuleValueParse ruleValue = parseRule(pattern.rules[i]); - pattern.parseRules.push_back(ruleValue); - } - } -} - -// "=:XXX" equal XXX -// "=!XXX" not equal XXX - -// "c:XXX" contains XXX -// "c!XXX" not contains XXX - -// "r:XXX" match regexp XXX -// "r!XXX" not match regexp XXX - -// e c r ignore case -// = E C R not ignore case -// 解析窗口类型规则 -RuleValueParse WindowPatterns::parseRule(QVector rule) -{ - RuleValueParse ret; - ret.key = rule[0]; - ret.original = rule[1]; - if (rule[1].size() < 2) - return ret; - - int len = ret.original.size() + 1; - char *orig = static_cast(calloc(1, size_t(len))); - if (!orig) - return ret; - - strncpy(orig, ret.original.toStdString().c_str(), size_t(len)); - switch (orig[1]) { - case ':': - break; - case '!': - ret.flags |= parsedFlagNegative; - ret.negative = true; - break; - default: - return ret; - } - - ret.value = QString(&orig[2]); - ret.type = uint8_t(orig[0]); - switch (orig[0]) { - case 'C': - ret.fn = contains; - break; - case 'c': - ret.flags |= parsedFlagIgnoreCase; - ret.fn = containsIgnoreCase; - break; - case '=': - case 'E': - ret.fn = equal; - break; - case 'e': - ret.flags |= parsedFlagIgnoreCase; - ret.fn = equalIgnoreCase; - break; - case 'R': - ret.fn = regexMatch; - break; - case 'r': - ret.flags |= parsedFlagIgnoreCase; - ret.fn = regexMatchIgnoreCase; - break; - default: - break; - } - - free(orig); - return ret; -} diff --git a/src/modules/dock/windowpatterns.h b/src/modules/dock/windowpatterns.h deleted file mode 100644 index d9d396d..0000000 --- a/src/modules/dock/windowpatterns.h +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef WINDOWPATTERNS_H -#define WINDOWPATTERNS_H - -#include "windowinfox.h" - -#include -#include - - -struct RuleValueParse { - RuleValueParse(); - bool match(const WindowInfoX *winInfo); - static QString parseRuleKey(WindowInfoX *winInfo, const QString &ruleKey); - QString key; - bool negative; - bool (*fn)(QString, QString); - uint8_t type; - uint flags; - QString original; - QString value; -}; - -class WindowPatterns -{ - // 窗口类型匹配 - struct WindowPattern { - QVector> rules; // rules - QString result; // ret - QVector parseRules; - }; - -public: - WindowPatterns(); - - QString match(WindowInfoX *winInfo); - -private: - void loadWindowPatterns(); - RuleValueParse parseRule(QVector rule); - -private: - QVector m_patterns; - -}; - -#endif // WINDOWPATTERNS_H diff --git a/src/modules/dock/x11manager.cpp b/src/modules/dock/x11manager.cpp deleted file mode 100644 index bb6856a..0000000 --- a/src/modules/dock/x11manager.cpp +++ /dev/null @@ -1,455 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "x11manager.h" -#include "dock.h" -#include "common.h" - -#include -#include - -/* - * 使用Xlib监听X Events - * 使用XCB接口与X进行交互 - * */ - -#include -#include -#include -#include -#include - -#define XCB XCBUtils::instance() - -X11Manager::X11Manager(Dock *_dock, QObject *parent) - : QObject(parent) - , m_dock(_dock) - , m_mutex(QMutex(QMutex::NonRecursive)) - , m_listenXEvent(true) -{ - m_rootWindow = XCB->getRootWindow(); -} - -void X11Manager::listenXEventUseXlib() -{ - - Display *dpy; - int screen; - char *displayname = nullptr; - Window w; - XSetWindowAttributes attr; - XWindowAttributes wattr; - - dpy = XOpenDisplay (displayname); - if (!dpy) { - exit (1); - } - - screen = DefaultScreen (dpy); - w = RootWindow(dpy, screen); - - const struct { - const char *name; - long mask; - } events[] = { - { "keyboard", KeyPressMask | KeyReleaseMask | KeymapStateMask }, - { "mouse", ButtonPressMask | ButtonReleaseMask | EnterWindowMask | - LeaveWindowMask | PointerMotionMask | Button1MotionMask | - Button2MotionMask | Button3MotionMask | Button4MotionMask | - Button5MotionMask | ButtonMotionMask }, - { "button", ButtonPressMask | ButtonReleaseMask }, - { "expose", ExposureMask }, - { "visibility", VisibilityChangeMask }, - { "structure", StructureNotifyMask }, - { "substructure", SubstructureNotifyMask | SubstructureRedirectMask }, - { "focus", FocusChangeMask }, - { "property", PropertyChangeMask }, - { "colormap", ColormapChangeMask }, - { "owner_grab_button", OwnerGrabButtonMask }, - { nullptr, 0 } -}; - - long mask = 0; - for (int i = 0; events[i].name; i++) - mask |= events[i].mask; - - attr.event_mask = mask; - - XGetWindowAttributes(dpy, w, &wattr); - - attr.event_mask &= ~SubstructureRedirectMask; - XSelectInput(dpy, w, attr.event_mask); - - while (m_listenXEvent) { - XEvent event; - XNextEvent (dpy, &event); - - switch (event.type) { - case DestroyNotify: { - XDestroyWindowEvent *eD = (XDestroyWindowEvent *)(&event); - qDebug() << "DestroyNotify windowId=" << eD->window; - - handleDestroyNotifyEvent(XWindow(eD->window)); - break; - } - case MapNotify: { - XMapEvent *eM = (XMapEvent *)(&event); - qDebug() << "MapNotify windowId=" << eM->window; - - handleMapNotifyEvent(XWindow(eM->window)); - break; - } - case ConfigureNotify: { - XConfigureEvent *eC = (XConfigureEvent *)(&event); - qDebug() << "ConfigureNotify windowId=" << eC->window; - - handleConfigureNotifyEvent(XWindow(eC->window), eC->x, eC->y, eC->width, eC->height); - break; - } - case PropertyNotify: { - XPropertyEvent *eP = (XPropertyEvent *)(&event); - qDebug() << "PropertyNotify windowId=" << eP->window; - - handlePropertyNotifyEvent(XWindow(eP->window), XCBAtom(eP->atom)); - break; - } - case UnmapNotify: { - // 当松开鼠标的时候会触发该事件,在松开鼠标的时候,需要检测当前窗口是否符合智能隐藏的条件,因此在此处加上该功能 - // 如果不加上该处理,那么就会出现将窗口从任务栏下方移动到屏幕中央的时候,任务栏不隐藏 - handleActiveWindowChangedX(); - break; - } - default: - qDebug() << "Unknown event type " << event.type; - break; - } - } - - XCloseDisplay (dpy); -} - -void X11Manager::listenXEventUseXCB() -{ - /* - xcb_get_window_attributes_cookie_t cookie = xcb_get_window_attributes(XCB->getConnect(), XCB->getRootWindow()); - xcb_get_window_attributes_reply_t *reply = xcb_get_window_attributes_reply(XCB->getConnect(), cookie, NULL); - if (reply) { - uint32_t valueMask = reply->your_event_mask; - valueMask &= ~XCB_CW_OVERRIDE_REDIRECT; - uint32_t mask[2] = {0}; - mask[0] = valueMask; - //xcb_change_window_attributes(XCB->getConnect(), XCB->getRootWindow(), valueMask, mask); - - free(reply); - } - - xcb_generic_event_t *event; - while ( (event = xcb_wait_for_event (XCB->getConnect())) ) { - eventHandler(event->response_type & ~0x80, event); - } - */ -} - -/** - * @brief X11Manager::registerWindow 注册X11窗口 - * @param xid - * @return - */ -WindowInfoX *X11Manager::registerWindow(XWindow xid) -{ - qInfo() << "registWindow: windowId=" << xid; - WindowInfoX *ret = nullptr; - do { - if (m_windowInfoMap.find(xid) != m_windowInfoMap.end()) { - ret = m_windowInfoMap[xid]; - break; - } - - WindowInfoX *winInfo = new WindowInfoX(xid); - if (!winInfo) - break; - - listenWindowXEvent(winInfo); - m_windowInfoMap[xid] = winInfo; - ret = winInfo; - } while (0); - - return ret; -} - -// 取消注册X11窗口 -void X11Manager::unregisterWindow(XWindow xid) -{ - qInfo() << "unregisterWindow: windowId=" << xid; - if (m_windowInfoMap.find(xid) != m_windowInfoMap.end()) { - m_windowInfoMap.remove(xid); - } -} - -WindowInfoX *X11Manager::findWindowByXid(XWindow xid) -{ - WindowInfoX *ret = nullptr; - if (m_windowInfoMap.find(xid) != m_windowInfoMap.end()) - ret = m_windowInfoMap[xid]; - - return ret; -} - -void X11Manager::handleClientListChanged() -{ - QSet newClientList, oldClientList, addClientList, rmClientList; - for (auto atom : XCB->getClientList()) - newClientList.insert(atom); - - for (auto atom : m_dock->getClientList()) - oldClientList.insert(atom); - - addClientList = newClientList - oldClientList; - rmClientList = oldClientList - newClientList; - m_dock->setClientList(newClientList.toList()); - - // 处理新增窗口 - for (auto xid : addClientList) { - WindowInfoX *info = registerWindow(xid); - if (!XCB->isGoodWindow(xid)) - continue; - - uint32_t pid = XCB->getWMPid(xid); - WMClass wmClass = XCB->getWMClass(xid); - QString wmName(XCB->getWMName(xid).c_str()); - if (pid != 0 || (wmClass.className.size() > 0 && wmClass.instanceName.size() > 0) - || wmName.size() > 0 || XCB->getWMCommand(xid).size() > 0) { - - if (info) { - Q_EMIT requestAttachOrDetachWindow(info); - } - } - } - - // 处理需要移除的窗口 - for (auto xid : rmClientList) { - WindowInfoX *info = m_windowInfoMap[xid]; - if (info) { - m_dock->detachWindow(info); - unregisterWindow(xid); - } else { - // no window - auto entry = m_dock->getEntryByWindowId(xid); - if (entry && !m_dock->isDocked(entry->getFileName())) { - m_dock->removeAppEntry(entry); - } - } - } -} - -void X11Manager::handleActiveWindowChangedX() -{ - XWindow active = XCB->getActiveWindow(); - WindowInfoX *info = findWindowByXid(active); - if (info) { - Q_EMIT requestHandleActiveWindowChange(info); - } -} - -void X11Manager::listenRootWindowXEvent() -{ - uint32_t eventMask = EventMask::XCB_EVENT_MASK_PROPERTY_CHANGE | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY; - XCB->registerEvents(m_rootWindow, eventMask); - handleActiveWindowChangedX(); - handleClientListChanged(); -} - -/** - * @brief X11Manager::listenWindowXEvent 监听窗口事件 - * @param winInfo - */ -void X11Manager::listenWindowXEvent(WindowInfoX *winInfo) -{ - uint32_t eventMask = EventMask::XCB_EVENT_MASK_PROPERTY_CHANGE | EventMask::XCB_EVENT_MASK_STRUCTURE_NOTIFY | EventMask::XCB_EVENT_MASK_VISIBILITY_CHANGE; - XCB->registerEvents(winInfo->getXid(), eventMask); -} - -void X11Manager::handleRootWindowPropertyNotifyEvent(XCBAtom atom) -{ - if (atom == XCB->getAtom("_NET_CLIENT_LIST")) { - // 窗口列表改变 - handleClientListChanged(); - } else if (atom == XCB->getAtom("_NET_ACTIVE_WINDOW")) { - // 活动窗口改变 - handleActiveWindowChangedX(); - } else if (atom == XCB->getAtom("_NET_SHOWING_DESKTOP")) { - // 更新任务栏隐藏状态 - Q_EMIT requestUpdateHideState(false); - } -} - -// destory event -void X11Manager::handleDestroyNotifyEvent(XWindow xid) -{ - WindowInfoX *winInfo = findWindowByXid(xid); - if (!winInfo) - return; - - m_dock->detachWindow(winInfo); - unregisterWindow(xid); -} - -// map event -void X11Manager::handleMapNotifyEvent(XWindow xid) -{ - WindowInfoX *winInfo = registerWindow(xid); - if (!winInfo) - return; - - // TODO QTimer不能在非主线程执行,使用单独线程开发定时器处理非主线程类似定时任务 - //QTimer::singleShot(2 * 1000, this, [=] { - qInfo() << "handleMapNotifyEvent: pass 2s, now call idnetifyWindow, windowId=" << winInfo->getXid(); - QString innerId; - AppInfo *appInfo = m_dock->identifyWindow(winInfo, innerId); - m_dock->markAppLaunched(appInfo); - //}); -} - -// config changed event 检测窗口大小调整和重绘应用,触发智能隐藏更新 -void X11Manager::handleConfigureNotifyEvent(XWindow xid, int x, int y, int width, int height) -{ - WindowInfoX *winInfo = findWindowByXid(xid); - if (!winInfo || m_dock->getDockHideMode() != HideMode::SmartHide) - return; - - WMClass wmClass = winInfo->getWMClass(); - if (wmClass.className.c_str() == frontendWindowWmClass) - return; // ignore frontend window ConfigureNotify event - - Q_EMIT requestUpdateHideState(winInfo->isGeometryChanged(x, y, width, height)); -} - -// property changed event -void X11Manager::handlePropertyNotifyEvent(XWindow xid, XCBAtom atom) -{ - if (xid == m_rootWindow) { - handleRootWindowPropertyNotifyEvent(atom); - return; - } - - WindowInfoX *winInfo = findWindowByXid(xid); - if (!winInfo) - return; - - QString newInnerId; - bool needAttachOrDetach = false; - if (atom == XCB->getAtom("_NET_WM_STATE")) { - winInfo->updateWmState(); - needAttachOrDetach = true; - } else if (atom == XCB->getAtom("_GTK_APPLICATION_ID")) { - QString gtkAppId; - winInfo->setGtkAppId(gtkAppId); - newInnerId = winInfo->genInnerId(winInfo); - } else if (atom == XCB->getAtom("_NET_WM_PID")) { - winInfo->updateProcessInfo(); - newInnerId = winInfo->genInnerId(winInfo); - } else if (atom == XCB->getAtom("_NET_WM_NAME")) { - winInfo->updateWmName(); - newInnerId = winInfo->genInnerId(winInfo); - } else if (atom == XCB->getAtom("_NET_WM_ICON")) { - winInfo->updateIcon(); - } else if (atom == XCB->getAtom("_NET_WM_ALLOWED_ACTIONS")) { - winInfo->updateWmAllowedActions(); - } else if (atom == XCB->getAtom("_MOTIF_WM_HINTS")) { - winInfo->updateMotifWmHints(); - } else if (atom == XCB_ATOM_WM_CLASS) { - winInfo->updateWmClass(); - newInnerId = winInfo->genInnerId(winInfo); - needAttachOrDetach = true; - } else if (atom == XCB->getAtom("_XEMBED_INFO")) { - winInfo->updateHasXEmbedInfo(); - needAttachOrDetach = true; - } else if (atom == XCB->getAtom("_NET_WM_WINDOW_TYPE")) { - winInfo->updateWmWindowType(); - needAttachOrDetach = true; - } else if (atom == XCB_ATOM_WM_TRANSIENT_FOR) { - winInfo->updateHasWmTransientFor(); - needAttachOrDetach = true; - } - - if (!newInnerId.isEmpty() && winInfo->getUpdateCalled() && winInfo->getInnerId() != newInnerId) { - // winInfo.innerId changed - m_dock->detachWindow(winInfo); - winInfo->setInnerId(newInnerId); - needAttachOrDetach = true; - } - - if (needAttachOrDetach && winInfo) { - Q_EMIT requestAttachOrDetachWindow(winInfo); - } - - Entry *entry = m_dock->getEntryByWindowId(xid); - if (!entry) - return; - - if (atom == XCB->getAtom("_NET_WM_STATE")) { - entry->updateExportWindowInfos(); - } else if (atom == XCB->getAtom("_NET_WM_ICON")) { - if (entry->getCurrentWindowInfo() == winInfo) { - entry->updateIcon(); - } - } else if (atom == XCB->getAtom("_NET_WM_NAME")) { - if (entry->getCurrentWindowInfo() == winInfo) { - entry->updateName(); - } - entry->updateExportWindowInfos(); - } else if (atom == XCB->getAtom("_NET_WM_ALLOWED_ACTIONS")) { - entry->updateMenu(); - } -} - -void X11Manager::eventHandler(uint8_t type, void *event) -{ - qInfo() << "eventHandler" << "type = " << type; - switch (type) { - case XCB_MAP_NOTIFY: // 17 注册新窗口 - qInfo() << "eventHandler: XCB_MAP_NOTIFY"; - break; - case XCB_DESTROY_NOTIFY: // 19 销毁窗口 - qInfo() << "eventHandler: XCB_DESTROY_NOTIFY"; - break; - case XCB_CONFIGURE_NOTIFY: // 22 窗口变化 - qInfo() << "eventHandler: XCB_CONFIGURE_NOTIFY"; - break; - case XCB_PROPERTY_NOTIFY: // 28 窗口属性改变 - qInfo() << "eventHandler: XCB_PROPERTY_NOTIFY"; - break; - } -} - -void X11Manager::addWindowLastConfigureEvent(XWindow xid, ConfigureEvent *event) -{ - delWindowLastConfigureEvent(xid); - - QMutexLocker locker(&m_mutex); - QTimer *timer = new QTimer(); - timer->setInterval(configureNotifyDelay); - m_windowLastConfigureEventMap[xid] = QPair(event, timer); -} - -QPair X11Manager::getWindowLastConfigureEvent(XWindow xid) -{ - QPair ret; - QMutexLocker locker(&m_mutex); - if (m_windowLastConfigureEventMap.find(xid) != m_windowLastConfigureEventMap.end()) - ret = m_windowLastConfigureEventMap[xid]; - - return ret; -} - -void X11Manager::delWindowLastConfigureEvent(XWindow xid) -{ - QMutexLocker locker(&m_mutex); - if (m_windowLastConfigureEventMap.find(xid) != m_windowLastConfigureEventMap.end()) { - QPair item = m_windowLastConfigureEventMap[xid]; - m_windowLastConfigureEventMap.remove(xid); - delete item.first; - item.second->deleteLater(); - } -} diff --git a/src/modules/dock/x11manager.h b/src/modules/dock/x11manager.h deleted file mode 100644 index 1c19eed..0000000 --- a/src/modules/dock/x11manager.h +++ /dev/null @@ -1,63 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef X11MANAGER_H -#define X11MANAGER_H - -#include "windowinfox.h" -#include "xcbutils.h" - -#include -#include -#include -#include - -class Dock; - -class X11Manager : public QObject -{ - Q_OBJECT -public: - explicit X11Manager(Dock *_dock, QObject *parent = nullptr); - - WindowInfoX *findWindowByXid(XWindow xid); - WindowInfoX *registerWindow(XWindow xid); - void unregisterWindow(XWindow xid); - - void handleClientListChanged(); - void handleActiveWindowChangedX(); - void listenRootWindowXEvent(); - void listenWindowXEvent(WindowInfoX *winInfo); - - void handleRootWindowPropertyNotifyEvent(XCBAtom atom); - void handleDestroyNotifyEvent(XWindow xid); - void handleMapNotifyEvent(XWindow xid); - void handleConfigureNotifyEvent(XWindow xid, int x, int y, int width, int height); - void handlePropertyNotifyEvent(XWindow xid, XCBAtom atom); - - void eventHandler(uint8_t type, void *event); - void listenWindowEvent(WindowInfoX *winInfo); - void listenXEventUseXlib(); - void listenXEventUseXCB(); - -Q_SIGNALS: - void requestUpdateHideState(bool delay); - void requestHandleActiveWindowChange(WindowInfoBase *info); - void requestAttachOrDetachWindow(WindowInfoBase *info); - -private: - void addWindowLastConfigureEvent(XWindow xid, ConfigureEvent* event); - QPair getWindowLastConfigureEvent(XWindow xid); - void delWindowLastConfigureEvent(XWindow xid); - -private: - QMap m_windowInfoMap; - Dock *m_dock; - QMap> m_windowLastConfigureEventMap; // 手动回收ConfigureEvent和QTimer - QMutex m_mutex; - XWindow m_rootWindow; // 根窗口 - bool m_listenXEvent; // 监听X事件 -}; - -#endif // X11MANAGER_H diff --git a/src/modules/launcher/category.cpp b/src/modules/launcher/category.cpp deleted file mode 100644 index e6d6d92..0000000 --- a/src/modules/launcher/category.cpp +++ /dev/null @@ -1,274 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "category.h" - -Category::Category() -{ - -} - -Category::~Category() -{ - -} - -QString Category::getStr(Categorytype ty) { - QMap ty2str = { - {Categorytype::CategoryInternet, "Internet"}, - {Categorytype::CategoryChat, "Chat"}, - {Categorytype::CategoryMusic, "Music"}, - {Categorytype::CategoryVideo, "Video"}, - {Categorytype::CategoryGraphics, "Graphics"}, - {Categorytype::CategoryOffice, "Office"}, - {Categorytype::CategoryGame, "Game"}, - {Categorytype::CategoryReading, "Reading"}, - {Categorytype::CategoryDevelopment, "Development"}, - {Categorytype::CategorySystem, "System"}, - {Categorytype::CategoryOthers, "Others"}, - }; - return ty2str.find(ty) != ty2str.end() ? ty2str[ty] : "Others"; -} - -QString Category::pinYin(Categorytype ty) { - QMap ty2py = { - {Categorytype::CategoryInternet, "wangluo"}, - {Categorytype::CategoryChat, "shejiaogoutong"}, - {Categorytype::CategoryMusic, "yinyuexinshang"}, - {Categorytype::CategoryVideo, "shipinbofang"}, - {Categorytype::CategoryGraphics, "tuxintuxiang"}, - {Categorytype::CategoryOffice, "bangongxuexi"}, - {Categorytype::CategoryGame, "youxiyule"}, - {Categorytype::CategoryReading, "yuedufanyi"}, - {Categorytype::CategoryDevelopment, "bianchengkaifai"}, - {Categorytype::CategorySystem, "xitongguanli"}, - {Categorytype::CategoryOthers, "qita"}, - }; - return ty2py.find(ty) != ty2py.end() ? ty2py[ty] : "qita"; -} - -Categorytype Category::parseCategoryString(QString str) { - QMap name2ty { - {"internet", Categorytype::CategoryInternet}, - {"chat", Categorytype::CategoryChat}, - {"music", Categorytype::CategoryMusic}, - {"video", Categorytype::CategoryVideo}, - {"graphics", Categorytype::CategoryGraphics}, - {"office", Categorytype::CategoryOffice}, - {"game", Categorytype::CategoryGame}, - {"reading", Categorytype::CategoryReading}, - {"development", Categorytype::CategoryDevelopment}, - {"system", Categorytype::CategorySystem}, - {"others", Categorytype::CategoryOthers}, - }; - return name2ty.find(str) != name2ty.end() ? name2ty[str] : Categorytype::CategoryErr; -} - -QList Category::parseXCategoryString(QString str) { - QMultiMap xname2ty { - {"2dgraphics", Categorytype::CategoryGraphics}, - {"3dgraphics", Categorytype::CategoryGraphics}, - {"accessibility", Categorytype::CategorySystem}, - {"accessories", Categorytype::CategoryOthers}, - {"actiongame", Categorytype::CategoryGame}, - {"advancedsettings", Categorytype::CategorySystem}, - {"adventuregame", Categorytype::CategoryGame}, - {"amusement", Categorytype::CategoryGame}, - {"applet", Categorytype::CategoryOthers}, - {"arcadegame", Categorytype::CategoryGame}, - {"archiving", Categorytype::CategorySystem}, - {"art", Categorytype::CategoryOffice}, - {"artificialintelligence", Categorytype::CategoryOffice}, - {"astronomy", Categorytype::CategoryOffice}, - {"audio", Categorytype::CategoryMusic}, - {"audiovideo", Categorytype::CategoryMusic}, - {"audiovideo", Categorytype::CategoryVideo}, - {"audiovideoediting", Categorytype::CategoryMusic}, - {"audiovideoediting", Categorytype::CategoryVideo}, - {"biology", Categorytype::CategoryOffice}, - {"blocksgame", Categorytype::CategoryGame}, - {"boardgame", Categorytype::CategoryGame}, - {"building", Categorytype::CategoryDevelopment}, - {"calculator", Categorytype::CategorySystem}, - {"calendar", Categorytype::CategorySystem}, - {"cardgame", Categorytype::CategoryGame}, - {"cd", Categorytype::CategoryMusic}, - {"chart", Categorytype::CategoryOffice}, - {"chat", Categorytype::CategoryChat}, - {"chemistry", Categorytype::CategoryOffice}, - {"clock", Categorytype::CategorySystem}, - {"compiz", Categorytype::CategorySystem}, - {"compression", Categorytype::CategorySystem}, - {"computerscience", Categorytype::CategoryOffice}, - {"consoleonly", Categorytype::CategoryOthers}, - {"contactmanagement", Categorytype::CategoryChat}, - {"core", Categorytype::CategoryOthers}, - {"debugger", Categorytype::CategoryDevelopment}, - {"desktopsettings", Categorytype::CategorySystem}, - {"desktoputility", Categorytype::CategorySystem}, - {"development", Categorytype::CategoryDevelopment}, - {"dialup", Categorytype::CategorySystem}, - {"dictionary", Categorytype::CategoryOffice}, - {"discburning", Categorytype::CategorySystem}, - {"documentation", Categorytype::CategoryOffice}, - {"editors", Categorytype::CategoryOthers}, - {"education", Categorytype::CategoryOffice}, - {"electricity", Categorytype::CategoryOffice}, - {"electronics", Categorytype::CategoryOffice}, - {"email", Categorytype::CategoryInternet}, - {"emulator", Categorytype::CategoryGame}, - {"engineering", Categorytype::CategorySystem}, - {"favorites", Categorytype::CategoryOthers}, - {"filemanager", Categorytype::CategorySystem}, - {"filesystem", Categorytype::CategorySystem}, - {"filetools", Categorytype::CategorySystem}, - {"filetransfer", Categorytype::CategoryInternet}, - {"finance", Categorytype::CategoryOffice}, - {"game", Categorytype::CategoryGame}, - {"geography", Categorytype::CategoryOffice}, - {"geology", Categorytype::CategoryOffice}, - {"geoscience", Categorytype::CategoryOthers}, - {"gnome", Categorytype::CategorySystem}, - {"gpe", Categorytype::CategoryOthers}, - {"graphics", Categorytype::CategoryGraphics}, - {"guidesigner", Categorytype::CategoryDevelopment}, - {"hamradio", Categorytype::CategoryOffice}, - {"hardwaresettings", Categorytype::CategorySystem}, - {"ide", Categorytype::CategoryDevelopment}, - {"imageprocessing", Categorytype::CategoryGraphics}, - {"instantmessaging", Categorytype::CategoryChat}, - {"internet", Categorytype::CategoryInternet}, - {"ircclient", Categorytype::CategoryChat}, - {"kde", Categorytype::CategorySystem}, - {"kidsgame", Categorytype::CategoryGame}, - {"literature", Categorytype::CategoryOffice}, - {"logicgame", Categorytype::CategoryGame}, - {"math", Categorytype::CategoryOffice}, - {"medicalsoftware", Categorytype::CategoryOffice}, - {"meteorology", Categorytype::CategoryOthers}, - {"midi", Categorytype::CategoryMusic}, - {"mixer", Categorytype::CategoryMusic}, - {"monitor", Categorytype::CategorySystem}, - {"motif", Categorytype::CategoryOthers}, - {"multimedia", Categorytype::CategoryVideo}, - {"music", Categorytype::CategoryMusic}, - {"network", Categorytype::CategoryInternet}, - {"news", Categorytype::CategoryReading}, - {"numericalanalysis", Categorytype::CategoryOffice}, - {"ocr", Categorytype::CategoryGraphics}, - {"office", Categorytype::CategoryOffice}, - {"p2p", Categorytype::CategoryInternet}, - {"packagemanager", Categorytype::CategorySystem}, - {"panel", Categorytype::CategorySystem}, - {"pda", Categorytype::CategorySystem}, - {"photography", Categorytype::CategoryGraphics}, - {"physics", Categorytype::CategoryOffice}, - {"pim", Categorytype::CategoryOthers}, - {"player", Categorytype::CategoryMusic}, - {"player", Categorytype::CategoryVideo}, - {"playonlinux", Categorytype::CategoryOthers}, - {"presentation", Categorytype::CategoryOffice}, - {"printing", Categorytype::CategoryOffice}, - {"profiling", Categorytype::CategoryDevelopment}, - {"projectmanagement", Categorytype::CategoryOffice}, - {"publishing", Categorytype::CategoryOffice}, - {"puzzlegame", Categorytype::CategoryGame}, - {"rastergraphics", Categorytype::CategoryGraphics}, - {"recorder", Categorytype::CategoryMusic}, - {"recorder", Categorytype::CategoryVideo}, - {"remoteaccess", Categorytype::CategorySystem}, - {"revisioncontrol", Categorytype::CategoryDevelopment}, - {"robotics", Categorytype::CategoryOffice}, - {"roleplaying", Categorytype::CategoryGame}, - {"scanning", Categorytype::CategoryOffice}, - {"science", Categorytype::CategoryOffice}, - {"screensaver", Categorytype::CategoryOthers}, - {"sequencer", Categorytype::CategoryMusic}, - {"settings", Categorytype::CategorySystem}, - {"security", Categorytype::CategorySystem}, - {"simulation", Categorytype::CategoryGame}, - {"sportsgame", Categorytype::CategoryGame}, - {"spreadsheet", Categorytype::CategoryOffice}, - {"strategygame", Categorytype::CategoryGame}, - {"system", Categorytype::CategorySystem}, - {"systemsettings", Categorytype::CategorySystem}, - {"technical", Categorytype::CategoryOthers}, - {"telephony", Categorytype::CategorySystem}, - {"telephonytools", Categorytype::CategorySystem}, - {"terminalemulator", Categorytype::CategorySystem}, - {"texteditor", Categorytype::CategoryOffice}, - {"texttools", Categorytype::CategoryOffice}, - {"transiation", Categorytype::CategoryDevelopment}, - {"translation", Categorytype::CategoryReading}, - {"trayicon", Categorytype::CategorySystem}, - {"tuner", Categorytype::CategoryMusic}, - {"tv", Categorytype::CategoryVideo}, - {"utility", Categorytype::CategorySystem}, - {"vectorgraphics", Categorytype::CategoryGraphics}, - {"video", Categorytype::CategoryVideo}, - {"videoconference", Categorytype::CategoryInternet}, - {"viewer", Categorytype::CategoryGraphics}, - {"webbrowser", Categorytype::CategoryInternet}, - {"webdevelopment", Categorytype::CategoryDevelopment}, - {"wine", Categorytype::CategoryOthers}, - {"wine-programs-accessories", Categorytype::CategoryOthers}, - {"wordprocessor", Categorytype::CategoryOffice}, - {"x-alsa", Categorytype::CategoryMusic}, - {"x-bible", Categorytype::CategoryReading}, - {"x-bluetooth", Categorytype::CategorySystem}, - {"x-debian-applications-emulators", Categorytype::CategoryGame}, - {"x-digital_processing", Categorytype::CategorySystem}, - {"x-enlightenment", Categorytype::CategorySystem}, - {"x-geeqie", Categorytype::CategoryGraphics}, - {"x-gnome-networksettings", Categorytype::CategorySystem}, - {"x-gnome-personalsettings", Categorytype::CategorySystem}, - {"x-gnome-settings-panel", Categorytype::CategorySystem}, - {"x-gnome-systemsettings", Categorytype::CategorySystem}, - {"x-gnustep", Categorytype::CategorySystem}, - {"x-islamic-software", Categorytype::CategoryReading}, - {"x-jack", Categorytype::CategoryMusic}, - {"x-kde-edu-misc", Categorytype::CategoryReading}, - {"x-kde-internet", Categorytype::CategorySystem}, - {"x-kde-more", Categorytype::CategorySystem}, - {"x-kde-utilities-desktop", Categorytype::CategorySystem}, - {"x-kde-utilities-file", Categorytype::CategorySystem}, - {"x-kde-utilities-peripherals", Categorytype::CategorySystem}, - {"x-kde-utilities-pim", Categorytype::CategorySystem}, - {"x-lxde-settings", Categorytype::CategorySystem}, - {"x-mandriva-office-publishing", Categorytype::CategoryOthers}, - {"x-mandrivalinux-internet-other", Categorytype::CategorySystem}, - {"x-mandrivalinux-office-other", Categorytype::CategoryOffice}, - {"x-mandrivalinux-system-archiving-backup", Categorytype::CategorySystem}, - {"x-midi", Categorytype::CategoryMusic}, - {"x-misc", Categorytype::CategorySystem}, - {"x-multitrack", Categorytype::CategoryMusic}, - {"x-novell-main", Categorytype::CategorySystem}, - {"x-quran", Categorytype::CategoryReading}, - {"x-red-hat-base", Categorytype::CategorySystem}, - {"x-red-hat-base-only", Categorytype::CategorySystem}, - {"x-red-hat-extra", Categorytype::CategorySystem}, - {"x-red-hat-serverconfig", Categorytype::CategorySystem}, - {"x-religion", Categorytype::CategoryReading}, - {"x-sequencers", Categorytype::CategoryMusic}, - {"x-sound", Categorytype::CategoryMusic}, - {"x-sun-supported", Categorytype::CategorySystem}, - {"x-suse-backup", Categorytype::CategorySystem}, - {"x-suse-controlcenter-lookandfeel", Categorytype::CategorySystem}, - {"x-suse-controlcenter-system", Categorytype::CategorySystem}, - {"x-suse-core", Categorytype::CategorySystem}, - {"x-suse-core-game", Categorytype::CategoryGame}, - {"x-suse-core-office", Categorytype::CategoryOffice}, - {"x-suse-sequencer", Categorytype::CategoryMusic}, - {"x-suse-yast", Categorytype::CategorySystem}, - {"x-suse-yast-high_availability", Categorytype::CategorySystem}, - {"x-synthesis", Categorytype::CategorySystem}, - {"x-turbolinux-office", Categorytype::CategoryOffice}, - {"x-xfce", Categorytype::CategorySystem}, - {"x-xfce-toplevel", Categorytype::CategorySystem}, - {"x-xfcesettingsdialog", Categorytype::CategorySystem}, - {"x-ximian-main", Categorytype::CategorySystem}, - }; - - return {xname2ty.values(str)}; -} diff --git a/src/modules/launcher/category.h b/src/modules/launcher/category.h deleted file mode 100644 index 36f89d9..0000000 --- a/src/modules/launcher/category.h +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef CATEGORY_H -#define CATEGORY_H - -#include "common.h" - -#include -#include - -// 应用类型 -enum class Categorytype { - CategoryInternet, - CategoryChat, - CategoryMusic, - CategoryVideo, - CategoryGraphics, - CategoryGame, - CategoryOffice, - CategoryReading, - CategoryDevelopment, - CategorySystem, - CategoryOthers, - CategoryErr, -}; - -class Category -{ -public: - Category(); - ~Category(); - - // 类型转字符串 - static QString getStr(Categorytype ty); - // 类型转拼音 - static QString pinYin(Categorytype ty); - // 字符串转类型 - static Categorytype parseCategoryString(QString str); - // Xorg类型字符串转类型列表 - static QList parseXCategoryString(QString str); -}; - -#endif // CATEGORY_H diff --git a/src/modules/launcher/common.h b/src/modules/launcher/common.h deleted file mode 100644 index 4849028..0000000 --- a/src/modules/launcher/common.h +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef COMMON_H -#define COMMON_H - -#include -#include - -// DBus服务、路径名 -const QString dbusService = "org.deepin.dde.daemon.Launcher1"; -const QString dbusPath = "/org/deepin/dde/daemon/Launcher1"; - -// 组策略配置 -const QString configLauncher = "com.deepin.dde.launcher"; -const QString keyDisplayMode = "Display_Mode"; -const QString keyFullscreen = "Fullscreen"; -const QString keyAppsUseProxy = "Apps_Use_Proxy"; -const QString keyAppsDisableScaling = "Apps_Disable_Scaling"; -const QString keyAppsHidden = "Apps_Hidden"; -const QString keyPackageNameSearch = "Search_Package_Name"; - -// 应用配置 -const QString lastoreDataDir = "/var/lib/lastore"; -const QString desktopPkgMapFile = lastoreDataDir + "/desktop_package.json"; -const QString applicationsFile = lastoreDataDir + "/applications.json"; - -const QString ddeDataDir = "/usr/share/dde/data/"; -const QString appNameTranslationsFile = ddeDataDir + "app_name_translations.json"; - -// 应用状态 -const QString appStatusCreated = "created"; -const QString appStatusModified = "updated"; -const QString appStatusDeleted = "deleted"; - -// flatpak应用 -const QString flatpakBin = "flatpak"; - -// 启动器执行程序 -const QString launcherExe = "/usr/bin/dde-launcher"; -#endif // COMMON_H diff --git a/src/modules/launcher/dbusadaptorlauncher.cpp b/src/modules/launcher/dbusadaptorlauncher.cpp deleted file mode 100644 index 81276c7..0000000 --- a/src/modules/launcher/dbusadaptorlauncher.cpp +++ /dev/null @@ -1,109 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "dbusadaptorlauncher.h" - -DBusAdaptorLauncher::DBusAdaptorLauncher(QObject *parent) - : QDBusAbstractAdaptor(parent) -{ - setAutoRelaySignals(true); - - Launcher *launcher = static_cast(QObject::parent()); - if (launcher) { - connect(launcher, &Launcher::itemChanged, this, &DBusAdaptorLauncher::ItemChanged); - connect(launcher, &Launcher::newAppLaunched, this, &DBusAdaptorLauncher::NewAppLaunched); - connect(launcher, &Launcher::uninstallFailed, this, &DBusAdaptorLauncher::UninstallFailed); - connect(launcher, &Launcher::uninstallSuccess, this, &DBusAdaptorLauncher::UninstallSuccess); - connect(launcher, &Launcher::displayModeChanged, this, &DBusAdaptorLauncher::DisplayModeChanged); - connect(launcher, &Launcher::fullScreenChanged, this, &DBusAdaptorLauncher::FullscreenChanged); - } -} - -DBusAdaptorLauncher::~DBusAdaptorLauncher() -{ - -} - -Launcher *DBusAdaptorLauncher::parent() const -{ - return static_cast(QObject::parent()); -} - -int DBusAdaptorLauncher::displayMode() const -{ - return parent()->getDisplayMode(); -} - -void DBusAdaptorLauncher::setDisplayMode(int value) -{ - parent()->setDisplayMode(value); -} - -bool DBusAdaptorLauncher::fullscreen() const -{ - return parent()->getFullScreen(); -} - -void DBusAdaptorLauncher::setFullscreen(bool value) -{ - parent()->setFullscreen(value); -} - -LauncherItemInfoList DBusAdaptorLauncher::GetAllItemInfos() -{ - parent()->initItems(); - return parent()->getAllItemInfos(); -} - -QStringList DBusAdaptorLauncher::GetAllNewInstalledApps() -{ - return parent()->getAllNewInstalledApps(); -} - -bool DBusAdaptorLauncher::GetDisableScaling(const QString &id) -{ - return parent()->getDisableScaling(id); -} - -LauncherItemInfo DBusAdaptorLauncher::GetItemInfo(const QString &id) -{ - return parent()->getItemInfo(id); -} - -bool DBusAdaptorLauncher::GetUseProxy(const QString &id) -{ - return parent()->getUseProxy(id); -} - -bool DBusAdaptorLauncher::IsItemOnDesktop(const QString &id) -{ - return parent()->isItemOnDesktop(id); -} - -bool DBusAdaptorLauncher::RequestRemoveFromDesktop(const QString &id) -{ - return parent()->requestRemoveFromDesktop(id); -} - -bool DBusAdaptorLauncher::RequestSendToDesktop(const QString &id) -{ - return parent()->requestSendToDesktop(id); -} - -void DBusAdaptorLauncher::RequestUninstall(const QString &desktop, bool unused) -{ - Q_UNUSED(unused); - - parent()->requestUninstall(desktop); -} - -void DBusAdaptorLauncher::SetDisableScaling(const QString &id, bool value) -{ - parent()->setDisableScaling(id, value); -} - -void DBusAdaptorLauncher::SetUseProxy(const QString &id, bool value) -{ - parent()->setUseProxy(id, value); -} diff --git a/src/modules/launcher/dbusadaptorlauncher.h b/src/modules/launcher/dbusadaptorlauncher.h deleted file mode 100644 index 036e6a7..0000000 --- a/src/modules/launcher/dbusadaptorlauncher.h +++ /dev/null @@ -1,135 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef DBUSADAPTORLAUNCHER_H -#define DBUSADAPTORLAUNCHER_H - -#include "launcher.h" -#include "launcheriteminfolist.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/* - * Adaptor class for interface org.deepin.dde.daemon.Launcher1 - */ -class DBusAdaptorLauncher: public QDBusAbstractAdaptor -{ - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "org.deepin.dde.daemon.Launcher1") - Q_CLASSINFO("D-Bus Introspection", "" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - " \n" - "") -public: - explicit DBusAdaptorLauncher(QObject *parent); - virtual ~DBusAdaptorLauncher(); - - Launcher *parent() const; - -public: // PROPERTIES - Q_PROPERTY(int DisplayMode READ displayMode WRITE setDisplayMode NOTIFY DisplayModeChanged) - Q_PROPERTY(bool Fullscreen READ fullscreen WRITE setFullscreen NOTIFY FullscreenChanged) - - int displayMode() const; - void setDisplayMode(int value); - - bool fullscreen() const; - void setFullscreen(bool value); - -public Q_SLOTS: // METHODS - LauncherItemInfoList GetAllItemInfos(); - QStringList GetAllNewInstalledApps(); - bool GetDisableScaling(const QString &id); - LauncherItemInfo GetItemInfo(const QString &id); - bool GetUseProxy(const QString &id); - bool IsItemOnDesktop(const QString &id); - bool RequestRemoveFromDesktop(const QString &id); - bool RequestSendToDesktop(const QString &id); - void RequestUninstall(const QString &desktop, bool unused); - void SetDisableScaling(const QString &id, bool value); - void SetUseProxy(const QString &id, bool value); - -Q_SIGNALS: // SIGNALS - void ItemChanged(const QString &status, const LauncherItemInfo &itemInfo, qlonglong categoryID); - void NewAppLaunched(const QString &appID); - void UninstallFailed(const QString &appId, const QString &errMsg); - void UninstallSuccess(const QString &appID); - - void DisplayModeChanged(int mode); - // 该接口与1050 dbus服务接口签名保持一致 - void FullscreenChanged(); -}; - -#endif diff --git a/src/modules/launcher/launcher.cpp b/src/modules/launcher/launcher.cpp deleted file mode 100644 index 9d7ed72..0000000 --- a/src/modules/launcher/launcher.cpp +++ /dev/null @@ -1,1250 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "launcher.h" -#include "lang.h" -#include "desktopinfo.h" -#include "settings.h" -#include "basedir.h" -#include "launchersettings.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include - -DCORE_USE_NAMESPACE -DWIDGET_USE_NAMESPACE - -#define SETTING LauncherSettings::instance() - -const QString LASTORE_SERVICE = "org.deepin.dde.Lastore1"; -const QString LASTORE_PATH = "/org/deepin/dde/Lastore1"; -const QString LASTORE_INTERFACE = "org.deepin.dde.Lastore1.Manager"; - -Launcher::Launcher(QObject *parent) - : SynModule(parent) - , m_appInfo(DesktopInfo("")) -{ - registeModule("launcher"); - appsHidden = SETTING->getHiddenApps(); - initSettings(); - - for (auto dir : BaseDir::appDirs()) { - appDirs.push_back(dir.c_str()); - } - - loadDesktopPkgMap(); - loadPkgCategoryMap(); - loadNameMap(); - initItems(); - - initConnection(); -} - -Launcher::~Launcher() -{ - QDBusConnection::sessionBus().unregisterObject(dbusPath); -} - -void Launcher::setSyncConfig(QByteArray ba) -{ - if (!SETTING) - return; - - QJsonDocument doc = QJsonDocument::fromJson(ba); - QJsonObject obj = doc.object(); - SETTING->setDisplayMode(obj["display_mode"].toInt() == 1 ? "category" : "free"); - SETTING->setFullscreenMode(obj["fullscreen"].toBool()); -} - -QByteArray Launcher::getSyncConfig() -{ - QJsonObject obj; - obj["version"] = "1.0"; - obj["display_mode"] = SETTING->getDisplayMode(); - obj["fullscreen"] = SETTING->getFullscreenMode(); - QJsonDocument doc(obj); - return doc.toJson(); -} - -const QMap *Launcher::getItems() -{ - return &itemsMap; -} - -int Launcher::getDisplayMode() -{ - return SETTING->getDisplayMode() == "category" ? 1 : 0; -} - -bool Launcher::getFullScreen() -{ - return SETTING->getFullscreenMode(); -} - -void Launcher::setDisplayMode(int value) -{ - SETTING->setDisplayMode(value == 1 ? "category" : "free"); -} - -void Launcher::setFullscreen(bool isFull) -{ - SETTING->setFullscreenMode(isFull); -} - -/** - * @brief Launcher::getAllItemInfos 获取所有应用信息 - * @return - */ -LauncherItemInfoList Launcher::getAllItemInfos() -{ - LauncherItemInfoList allItemList; - for (auto &item : m_desktopAndItemMap) - allItemList.push_back(item.info); - - return allItemList; -} - -/** - * @brief Launcher::getAllNewInstalledApps 获取所有新安装且未打开的应用 - * @return - */ -QStringList Launcher::getAllNewInstalledApps() -{ - QStringList ret; - QMap newApps; - QDBusInterface interface = QDBusInterface("org.deepin.dde.AlRecorder1", "/org/deepin/dde/AlRecorder1", "org.deepin.dde.AlRecorder1"); - QDBusReply> reply = interface.call("GetNew"); - if (reply.isValid()) - newApps = reply; - - for (auto iter = newApps.begin(); iter != newApps.end(); iter++) { - for (QString name : iter.value()) { - QString path = iter.key() + name + ".desktop"; - Item item = getItemByPath(path); - if (item.isValid()) { - ret << item.info.id; - } - } - } - return ret; -} - -/** - * @brief Launcher::getDisableScaling 获取应用是否禁用缩放 - * @param appId - * @return - */ -bool Launcher::getDisableScaling(QString appId) -{ - if (itemsMap.find(appId) == itemsMap.end()) - return false; - - for (const auto &app : SETTING->getDisableScalingApps()) { - if (app == appId) - return true; - } - return false; -} - -/** - * @brief Launcher::getItemInfo 获取应用信息 - * @param appId - * @return - */ -LauncherItemInfo Launcher::getItemInfo(QString appId) -{ - LauncherItemInfo info; - if (itemsMap.find(appId) == itemsMap.end()) - return info; - - info = itemsMap[appId].info; - return info; -} - -/** - * @brief Launcher::getUseProxy 获取应用是否代理 - * @param appId - * @return - */ -bool Launcher::getUseProxy(QString appId) -{ - if (itemsMap.find(appId) == itemsMap.end()) - return false; - - for (const auto &app : SETTING->getUseProxyApps()) { - if (app == appId) - return true; - } - return false; -} - -/** - * @brief Launcher::isItemOnDesktop 桌面是否存在应用desktop文件 - * @param appId - * @return - */ -bool Launcher::isItemOnDesktop(QString appId) -{ - if (itemsMap.find(appId) == itemsMap.end()) - return false; - - QString filePath(QDir::homePath() + "/Desktop/" + appId + ".desktop"); - QFileInfo info(filePath); - return info.exists(); -} - -/** - * @brief Launcher::requestRemoveFromDesktop 移除桌面快捷方式 - * @param appId - * @return - */ -bool Launcher::requestRemoveFromDesktop(QString appId) -{ - if (itemsMap.find(appId) == itemsMap.end()) - return false; - - QString filePath(QDir::homePath() + "/Desktop/" + appId + ".desktop"); - QFileInfo info(filePath); - if (!info.exists()) - return true; - - QFile file(filePath); - return file.remove(); -} - -/** - * @brief Launcher::requestSendToDesktop 发送应用到桌面 - * @param appId - * @return - */ -bool Launcher::requestSendToDesktop(QString appId) -{ - if (itemsMap.find(appId) == itemsMap.end()) - return false; - - QString filePath(QDir::homePath() + "/Desktop/" + appId + ".desktop"); - QFileInfo info(filePath); - if (info.exists()) // 已经存在 - return false; - - // 创建桌面快捷方式文件 - DesktopInfo dinfo(itemsMap[appId].info.path.toStdString()); - dinfo.getDesktopFile()->setKey(MainSection, "X-Deepin-CreatedBy", dbusService.toStdString()); - dinfo.getDesktopFile()->setKey(MainSection, "X-Deepin-AppID", appId.toStdString()); - if (!dinfo.getDesktopFile()->saveToFile(filePath.toStdString())) - return false; - - // 播放音频 - DDesktopServices::playSystemSoundEffect(DDesktopServices::SSE_SendFileComplete); - - return true; -} - -/** - * @brief Launcher::requestUninstall 卸载应用 - * @param appId - */ -void Launcher::requestUninstall(const QString &desktop) -{ - QString appDesktopPath = desktop; - - bool exist = false; - for (const Item &item : m_desktopAndItemMap.values()) { - if (item.info.path == appDesktopPath) { - exist = true; - break; - } - } - - if (!exist) { - qWarning() << QString(" %1 uninstall faill ...").arg(appDesktopPath); - return; - } - - // 限制调用方 - QString servicePid = QString::number(QDBusConnection::sessionBus().interface()->servicePid(message().service())); - QString cmd = QString("cat /proc/%1/cmdline").arg(servicePid); - QProcess process; - QStringList args {"-c", cmd}; - process.start("sh", args); - process.waitForReadyRead(); - QString result = QString::fromUtf8(process.readAllStandardOutput()); - process.close(); - if (result != launcherExe) { - qWarning() << result << " has no right to uninstall " << appDesktopPath; - return; - } - - if (!m_desktopAndItemMap.keys().contains(appDesktopPath)) { - QFileInfo fileInfo(appDesktopPath); - if (!fileInfo.isSymLink()) { - qWarning() << QString("can't find desktopPath: %1").arg(appDesktopPath); - return; - } - - appDesktopPath = fileInfo.symLinkTarget(); - } - - const Item &item = m_desktopAndItemMap[appDesktopPath]; - DesktopInfo info(item.info.path.toStdString()); - if (!info.isValidDesktop()) { - qWarning() << QString("%1 desktop file is invalid...").arg(item.info.name); - return; - } - - m_appInfo = info; - doUninstall(info, item); -} - -/** - * @brief Launcher::setDisableScaling 设置应用是否禁用缩放 - * @param appId - * @param value - */ -void Launcher::setDisableScaling(QString appId, bool value) -{ - if (itemsMap.find(appId) == itemsMap.end()) - return; - - QVector apps = SETTING->getDisableScalingApps(); - if (value) { - for (const auto &app : apps) { - if (app == appId) { - return; - } - } - apps.append(appId); - } else { - bool found = false; - for (auto iter = apps.begin(); iter != apps.end(); iter++) { - if (*iter == appId) { - found = true; - apps.erase(iter); - break; - } - } - if (!found) - return; - } - - SETTING->setDisableScalingApps(apps); -} - -/** - * @brief Launcher::setUseProxy 设置用户代理 - * @param appId - * @param value - */ -void Launcher::setUseProxy(QString appId, bool value) -{ - if (itemsMap.find(appId) == itemsMap.end()) - return; - - - QVector apps = SETTING->getUseProxyApps(); - if (value) { - for (const auto &app : apps) { - if (app == appId) { - return; - } - } - apps.append(appId); - } else { - bool found = false; - for (auto iter = apps.begin(); iter != apps.end(); iter++) { - if (*iter == appId) { - found = true; - apps.erase(iter); - break; - } - } - if (!found) - return; - } - SETTING->setUseProxy(apps); -} - -/** - * @brief Launcher::handleFSWatcherEvents 处理文件改变事件 - * @param msg - */ -void Launcher::handleFSWatcherEvents(QDBusMessage msg) -{ - QList ret = msg.arguments(); - if (ret.size() != 2) - return; - - QString filePath = ret[0].toString(); - int op = ret[0].toInt(); - - // desktop包文件变化 - if (filePath == desktopPkgMapFile) { - loadDesktopPkgMap(); - - // retry queryPkgName for m.noPkgItemIDs - for (auto iter = noPkgItemIds.begin(); iter != noPkgItemIds.end(); iter++) { - QString id = iter.key(); - QString pkg = queryPkgName(id, ""); - if (pkg.isEmpty()) - continue; - - Item &item = itemsMap[id]; - Categorytype ty = queryCategoryId(&item); - if (qint64(ty) != item.info.categoryId) { - item.info.categoryId = qint64(ty); - emitItemChanged(&item, appStatusModified); - } - noPkgItemIds.remove(id); - } - } else if (filePath == applicationsFile) { // 应用信息文件变化 - loadPkgCategoryMap(); - } else if (filePath.endsWith(".desktop")){ // desktop文件变化 - onCheckDesktopFile(filePath); - } -} - -void Launcher::onHandleUninstall(const QDBusMessage &message) -{ - QList arguments = message.arguments(); - - if (3 != arguments.count()) - return; - - QVariantMap changedProps = qdbus_cast(arguments.at(1).value()); - const QStringList keys = changedProps.keys(); - - QString status; - if (keys.contains("Status")) { - status = changedProps["Status"].toString(); - } - -#ifdef QT_DEBUG - qInfo() << "changedProps: " << changedProps << ", status: " << status; -#endif - const QString &desktop = QString::fromStdString(m_appInfo.getFileName()); - if (status == "succeed" || status == "end") { - removeDesktop(desktop); - removeAutoStart(desktop); - Q_EMIT uninstallSuccess(desktop); - } else if (status == "failed") { - Q_EMIT uninstallFailed(desktop, QString()); - } -} - -/** - * @brief Launcher::initSettings 初始化启动器配置 - */ -void Launcher::initSettings() -{ - connect(SETTING, &LauncherSettings::displayModeChanged, this, [&](QString mode) { - Q_EMIT displayModeChanged(mode == "category" ? 1 : 0); - }); - connect(SETTING, &LauncherSettings::fullscreenChanged, this, &Launcher::fullScreenChanged); - connect(SETTING, &LauncherSettings::hiddenAppsChanged, this, &Launcher::handleAppHiddenChanged); -} - -/** - * @brief Launcher::loadDesktopPkgMap 加载应用包信息 - */ -void Launcher::loadDesktopPkgMap() -{ - QFile file(desktopPkgMapFile); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) - return; - - QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); - file.close(); - if (!doc.isObject()) - return; - - QJsonObject obj = doc.object(); - QVariantMap varMap = obj.toVariantMap(); - desktopPkgMap.clear(); - for (auto iter = varMap.begin(); iter != varMap.end(); iter++) { - if (!QDir::isAbsolutePath(iter.key())) - continue; - - QString appId = getAppIdByFilePath(iter.key(), appDirs); - if (appId == "") - continue; - - desktopPkgMap[appId] = iter.value().toString(); - } -} - -/** - * @brief Launcher::loadPkgCategoryMap 加载应用类型信息 - */ -void Launcher::loadPkgCategoryMap() -{ - QFile file(applicationsFile); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) - return; - - QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); - file.close(); - if (!doc.isObject()) - return; - - QJsonObject obj = doc.object(); - QVariantMap varMap = obj.toVariantMap(); - pkgCategoryMap.clear(); - for (auto iter = varMap.begin(); iter != varMap.end(); iter++) { - if (!iter.value().toJsonValue().isObject()) - continue; - - QJsonObject infoObj = iter.value().toJsonObject(); - QVariantMap infoMap = infoObj.toVariantMap(); - QString category = infoMap["category"].toString(); - pkgCategoryMap[iter.key()] = Category::parseCategoryString(category); - } -} - -void Launcher::onCheckDesktopFile(const QString &filePath, int type) -{ - Q_UNUSED(type); - - if (filePath.isEmpty()) { - qWarning() << "Desktop path is empty. "; - return; - } - - DesktopInfo info(filePath.toStdString()); - if (info.isValidDesktop()) { - Item newItem = NewItemWithDesktopInfo(info); - bool shouldShow = info.shouldShow() && - !isDeepinCustomDesktopFile(newItem.info.path) && - !appsHidden.contains(newItem.info.id); - - if (m_desktopAndItemMap.find(filePath) != m_desktopAndItemMap.end()) { - if (shouldShow) { - // update item - addItem(newItem); - emitItemChanged(&newItem, appStatusModified); - } else { - // hide item - emitItemChanged(&newItem, appStatusDeleted); - } - } else if (shouldShow) { - if (info.isExecutableOk()) { - // add item - addItem(newItem); - emitItemChanged(&newItem, appStatusCreated); - } - } - } else { - if (m_desktopAndItemMap.find(filePath) != m_desktopAndItemMap.end()) { - // remove item - const Item &item = itemsMap[filePath]; - removeDesktop(filePath); - - emitItemChanged(&item, appStatusDeleted); - } - } -} - -void Launcher::onNewAppLaunched(const QString &filePath) -{ - Item item = getItemByPath(filePath); - - if (item.isValid()) - Q_EMIT newAppLaunched(item.info.id); -} - -void Launcher::initConnection() -{ - QDBusConnection::sessionBus().connect("org.deepin.dde.DFWatcher1", - "/org/deepin/dde/DFWatcher1", - "org.deepin.dde.DFWatcher1", - "Event", - this, - SLOT(onCheckDesktopFile(const QString &, int))); - - QDBusConnection::sessionBus().connect("org.deepin.dde.AlRecorder1", - "/org/deepin/dde/AlRecorder1", - "org.deepin.dde.AlRecorder1", - "Launched", - this, - SLOT(onNewAppLaunched(const QString &))); -} - -/** - * @brief Launcher::handleAppHiddenChanged 响应DConfig中隐藏应用配置变化 - */ -void Launcher::handleAppHiddenChanged() -{ - auto hiddenApps = SETTING->getHiddenApps(); - QSet newSet, oldSet; - for (const auto &app : hiddenApps) - newSet.insert(app); - - for (const auto &app : appsHidden) - oldSet.insert(app); - - // 处理新增隐藏应用 - for (const auto &app : newSet - oldSet) { - if (itemsMap.find(app) == itemsMap.end()) - continue; - - emitItemChanged(&itemsMap[app], appStatusDeleted); - itemsMap.remove(app); - } - - // 处理显示应用 - for (const auto &appId : oldSet - newSet) { - if (itemsMap.find(appId) == itemsMap.end()) - continue; - - DesktopInfo info = DesktopInfo(itemsMap[appId].info.path.toStdString()); - if (!info.isValidDesktop()) { - qWarning() << "invalid Desktop Path"; - continue; - } - - Item item = NewItemWithDesktopInfo(info); - - if (!(info.shouldShow() && !isDeepinCustomDesktopFile(info.getFileName().c_str()))) - continue; - - addItem(item); - emitItemChanged(&item, appStatusCreated); - } - - appsHidden.clear(); - for (const auto &appId : hiddenApps) { - appsHidden.push_back(appId); - } -} - -/** - * @brief Launcher::loadNameMap 加载翻译应用信息 - */ -void Launcher::loadNameMap() -{ - QFile file(appNameTranslationsFile); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) - return; - - QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); - file.close(); - if (!doc.isObject()) - return; - - QJsonObject obj = doc.object(); - QVariantMap varMap = obj.toVariantMap(); - nameMap.clear(); - - QString lang(queryLangs()[0].data()); - for (auto iter = varMap.begin(); iter != varMap.end(); iter++) { - // 过滤非Object - if (!iter.value().toJsonValue().isObject()) - continue; - - // 过滤非本地语言 - if (iter.key() != lang) - continue; - - QJsonObject infoObj = iter.value().toJsonObject(); - QVariantMap infoMap = infoObj.toVariantMap(); - for (auto infoIter = infoMap.begin(); infoIter != infoMap.end(); infoIter++) { - // 过滤Object - if (infoIter.value().toJsonValue().isObject()) - continue; - - nameMap[infoIter.key()] = infoIter.value().toString(); - } - } -} - -/** - * @brief Launcher::initItems 初始化应用信息 - */ -void Launcher::initItems() -{ - itemsMap.clear(); - m_desktopAndItemMap.clear(); - std::vector infos = AppsDir::getAllDesktopInfos(); - for (auto &app : infos) { - if (!app.isExecutableOk() - || app.getId().empty() - || isDeepinCustomDesktopFile(app.getFileName().c_str())) - { - continue; - } - - Item item = NewItemWithDesktopInfo(app); - if (appsHidden.contains(item.info.id)) - continue; - - addItem(item); - } -} - -void Launcher::addItem(Item &item) -{ - if (!item.isValid()) { - qDebug() << "item is invalid, item info:" << item.info.path; - return; - } - - if (nameMap.size() > 0 && nameMap.find(item.info.id) != nameMap.end()) { - QString name = nameMap[item.info.id]; - if (!name.isEmpty()) - item.info.name = name; - } - - item.info.categoryId = qint64(queryCategoryId(&item)); - itemsMap[item.info.id] = item; - - QFileInfo desktopInfo(item.info.path); - m_desktopAndItemMap[item.info.path] = item; -} - -Categorytype Launcher::queryCategoryId(const Item *item) -{ - QString pkg = queryPkgName(item->info.id, item->info.path); - if (pkg.isEmpty()) { - noPkgItemIds[item->info.id] = 1; - - if (pkgCategoryMap.find(pkg) != pkgCategoryMap.end()) - return pkgCategoryMap[pkg]; - } - - Categorytype category = Category::parseCategoryString(item->xDeepinCategory); - if (category != Categorytype::CategoryErr) - return category; - - return getXCategory(item); -} - -/** - * @brief Launcher::getXCategory 获取应用类型 - * @param item - * @return - */ -Categorytype Launcher::getXCategory(const Item *item) -{ - // 统计应用类型 - QMap categoriesMap; - for (const auto &category : item->categories) { - QString lCategory = category.toLower(); - QList tys; - Categorytype ty = Category::parseCategoryString(lCategory); - if (ty != Categorytype::CategoryErr) - tys.push_back(ty); - else if (Category::parseXCategoryString(lCategory).size() > 0) { - tys.append(Category::parseXCategoryString(lCategory)); - } - - for (const auto & ty : tys) - categoriesMap[ty]++; - } - - categoriesMap.remove(Categorytype::CategoryOthers); - if (categoriesMap.size() == 0) - return Categorytype::CategoryOthers; - - // 计算最多的类型 - int max = 0; - Categorytype ty {Categorytype::CategoryOthers}; - for (auto iter = categoriesMap.begin(); iter != categoriesMap.end(); iter++) { - if (iter.value() > max) { - max = iter.value(); - ty = iter.key(); - } - } - - QList maxCatogories {ty}; - for (auto iter = categoriesMap.begin(); iter != categoriesMap.end(); iter++) { - if (iter.key() != ty && iter.value() == max) { - maxCatogories.push_back(iter.key()); - } - } - - if (maxCatogories.size() == 1) - return maxCatogories[0]; - - std::sort(maxCatogories.begin(), maxCatogories.end()); - - // 检查是否同时存在音乐和视频播放器 - QPair found; - for (auto iter = maxCatogories.begin(); iter != maxCatogories.end(); iter++) { - if (*iter == Categorytype::CategoryMusic) - found.first = true; - else if (*iter == Categorytype::CategoryVideo) - found.second = true; - } - - if (found.first && found.second) - return Categorytype::CategoryVideo; - - return maxCatogories[0]; -} - -/** - * @brief Launcher::queryPkgNameWithDpkg 使用dpkg -S,通过文件路径查包 - * @param itemPath - * @return - */ -QString Launcher::queryPkgNameWithDpkg(const QString &itemPath) -{ - QProcess process; - QStringList args {"-S", itemPath}; - process.start("dpkg", args); - if (!process.waitForFinished()) - return QString(); - - QByteArray output = process.readAllStandardOutput(); - if (output.size() == 0) - return QString(); - - std::vector splits = DString::splitChars(output.data(), '\n'); - if (splits.size() > 0) { - std::vector parts = DString::splitStr(splits[0], ':'); - if (parts.size() == 2) - return parts[0].c_str(); - } - return QString(); -} - -/** - * @brief Launcher::queryPkgName 通过id、path查询包名 - * @param itemID - * @param itemPath - * @return - */ -QString Launcher::queryPkgName(const QString &itemID, const QString &itemPath) -{ - QFileInfo itemInfo(itemPath); - if (itemPath.isEmpty() || !itemInfo.isFile()) - return QString(); - - // 处理desktop文件是软连接的情况 - if (itemInfo.isSymLink()) { - std::string path = itemInfo.symLinkTarget().toStdString(); - std::smatch result; - const std::regex e("^/opt/apps/([^/]+)/entries/applications/.*"); - if (std::regex_match(path, result, e) && result.size() == 2) { - // dpkg命令检查通过路径匹配的包是否存在 - QString pkgName(result[1].str().c_str()); - QProcess process; - QStringList args0 {"-s", pkgName}; - process.start("dpkg", args0); - if (process.waitForFinished()) - return pkgName; - - // 当包不存在则使用dpkg -S来查找包 - QStringList args1 {"-S", pkgName}; - process.start("dpkg", args1); - if (!process.waitForFinished()) - return QString(); - - QByteArray output = process.readAllStandardOutput(); - if (output.size() == 0) - return QString(); - - std::vector splits = DString::splitChars(output.data(), ':'); - if (splits.size() < 2) - return QString(); - - return splits[0].c_str(); - } - } - - if (DString::startWith(itemID.toStdString(), "org.deepin.flatdeb.")) - return QString("deepin-fpapp-") + itemID; - - if (desktopPkgMap.find(itemID) != desktopPkgMap.end()) - return desktopPkgMap[itemID]; - - return QString(); -} - -/** - * @brief Launcher::getItemByPath 根据desktop路径获取Item信息 - * @param itemPath - * @return - */ -Item Launcher::getItemByPath(QString itemPath) -{ - QString appId = getAppIdByFilePath(itemPath, appDirs); - if (itemsMap.find(appId) == itemsMap.end()) - return Item(); - - if (itemsMap[appId].info.path == itemPath) - return itemsMap[appId]; - - return Item(); -} - -void Launcher::emitItemChanged(const Item *item, QString status) -{ - LauncherItemInfo info(item->info); - Q_EMIT itemChanged(status, info, info.categoryId); -} - -AppType Launcher::getAppType(DesktopInfo &info, const Item &item) -{ - AppType ty = AppType::Default; - QFileInfo fileInfo; - // 判断是否为flatpak应用 - do { - if (!info.getDesktopFile()->containKey(MainSection, "X-Flatpak")) - break; - - std::vector parts = DString::splitStr(info.getCommandLine(), ' '); - if (parts.size() == 0) - break; - - fileInfo.setFile(parts[0].c_str()); - if (flatpakBin != fileInfo.completeBaseName()) - break; - - ty = AppType::Flatpak; - goto end; - } while (0); - - // 判断是否为ChromeShortcut - do { - if (!DString::startWith(item.info.id.toStdString(), "chrome-")) - break; - - if (!std::regex_match(item.exec.toStdString(), std::regex("google-chrome.*--app-id="))) - break; - - ty = AppType::ChromeShortcut; - goto end; - } while (0); - - // 判断是否为CrossOver - do { - fileInfo.setFile(info.getExecutable().c_str()); - QString execBase(fileInfo.completeBaseName()); - if (execBase.contains("CrossOver") && (execBase.contains("crossover") || execBase.contains("cxuninstall"))) { - ty = AppType::CrossOver; - goto end; - } - } while (0); - - // 判断是否为wineApp - do { - std::string createdBy = info.getDesktopFile()->getStr(MainSection, "X-Created-By"); - if (DString::startWith(createdBy, "cxoffice-") || strstr(info.getCommandLine().c_str(), "env WINEPREFIX=")) { - ty = AppType::WineApp; - goto end; - } - } while (0); - - -end: - return ty; -} - -bool Launcher::isLingLongApp(const QString &filePath) -{ - return filePath.contains("/persistent/linglong"); -} - -/** - * @brief Launcher::doUninstall 执行卸载操作 - * @param info - * @param item - * @return - */ -void Launcher::doUninstall(DesktopInfo &info, const Item &item) -{ - if (isLingLongApp(QString::fromStdString(info.getFileName()))) { - QProcess process; - // 获取 appId - QStringList args; - QString appId = item.exec.section(' ', 2, 2); - args.append("uninstall"); - args.append(appId); - - int retCode = QProcess::execute("ll-cli", args); - if (retCode != 0) { - Q_EMIT uninstallFailed(item.info.path, QString()); - notifyUninstallDone(item, false); - qWarning() << QString("uninstall %1 failed...").arg(info.getFileName().c_str()); - return; - } - - removeDesktop(item.info.path); - - Q_EMIT uninstallSuccess(item.info.path); - - // 浮窗通知 - notifyUninstallDone(item, true); - } else { - // 查询包名 - QString pkg = queryPkgName(item.info.id, item.info.path); - if (pkg.isEmpty()) - pkg = queryPkgNameWithDpkg(item.info.path); - - if (pkg.isEmpty()) { - qWarning() << "uninstall failed, becase package name is Empty"; - return; - } - - // 检测包是否安装 - QDBusInterface lastoreDbus = QDBusInterface(LASTORE_SERVICE, LASTORE_PATH, LASTORE_INTERFACE, QDBusConnection::systemBus()); - QDBusReply reply = lastoreDbus.call("PackageExists", pkg); - - // 包未安装时 - if (!(reply.isValid() && reply.value())) - return; - - // 卸载系统应用 - uninstallApp(item.info.name, pkg); - } -} - -/** - * @brief Launcher::uninstallFlatpak 卸载flatpak应用 - * @param info - * @param item - */ -void Launcher::uninstallFlatpak(DesktopInfo &info, const Item &item) -{ - struct FlatpakApp { - std::string name; - std::string arch; - std::string branch; - } flat; - std::vector parts = DString::splitStr(info.getCommandLine(), ' '); - for (unsigned long idx = 0; idx < parts.size(); idx++) { - if (flat.branch.empty() && DString::startWith(parts[idx], "--branch=")) - flat.branch.assign(parts[idx].c_str() + strlen("--branch=")); - - if (flat.arch.empty() && DString::startWith(parts[idx], "--arch=")) - flat.arch.assign(parts[idx].c_str() + strlen("--arch=")); - - if (flat.name.empty() && idx != 0 && !DString::startWith(parts[idx], "--") && strstr(parts[idx].c_str(), ".")) - flat.name.assign(parts[idx]); - - if (!flat.branch.empty() && !flat.arch.empty() && !flat.name.empty()) - break; - } - - if (flat.branch.empty() || flat.arch.empty() || flat.name.empty()) { - qInfo() << "uninstall Flatpak failed"; - return; - } - - bool userApp = item.info.path.startsWith(QDir::homePath()); - QString sysOrUser = "--user"; - if (!userApp) { - sysOrUser = "--system"; - QString pkgFile = QString("/usr/share/deepin-flatpak/app/%1/%2/%3/pkg").arg(flat.name.c_str()).arg(flat.arch.c_str()).arg(flat.branch.c_str()); - QFile file(pkgFile); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) - return; - - QString content(file.readAll()); - QString pkgName = content.trimmed(); - uninstallApp(item.info.name, pkgName); - } else { - QString ref = QString("app/%1/%2/%3").arg(flat.name.c_str()).arg(flat.arch.c_str()).arg(flat.branch.c_str()); - qInfo() << "uninstall flatpak ref= " << ref; - QProcess process; - QStringList args {sysOrUser, "uninstall", ref}; - process.start("flatpak", args); - bool res = process.waitForFinished(); - std::thread thread([&] { - notifyUninstallDone(item, res); - }); - thread.detach(); - } -} - -/** - * @brief Launcher::uninstallWineApp 卸载wine应用 - * @param item - * @return - */ -bool Launcher::uninstallWineApp(const Item &item) -{ - QProcess process; - QStringList args {item.info.path}; - process.start("/opt/deepinwine/tools/uninstall.sh", args); - bool res = process.waitForFinished(); - std::thread thread([&] { - notifyUninstallDone(item, res); - }); - return res; -} - -void Launcher::uninstallApp(const QString &name, const QString &pkg) -{ - QDBusInterface lastoreDbus = QDBusInterface(LASTORE_SERVICE, LASTORE_PATH, LASTORE_INTERFACE, QDBusConnection::systemBus()); - QDBusReply reply = lastoreDbus.call(QDBus::Block, "RemovePackage", name, pkg); - - if (!reply.isValid() || reply.value().path().isEmpty()) { - qWarning() << "RemovePackage failed: " << reply.error(); - return; - } - - QString servicePath = reply.value().path(); - - QDBusConnection::systemBus().disconnect(LASTORE_SERVICE, servicePath, "org.freedesktop.DBus.Properties", - "PropertiesChanged","sa{sv}as", this, SLOT(onHandleUninstall(const QDBusMessage &))); - QDBusConnection::systemBus().connect(LASTORE_SERVICE, servicePath, "org.freedesktop.DBus.Properties", - "PropertiesChanged","sa{sv}as", this, SLOT(onHandleUninstall(const QDBusMessage &))); -} - -/** 移除desktop文件 - * @brief Launcher::removeDesktop - * @param desktop - */ -void Launcher::removeDesktop(const QString &desktop) -{ - QFileInfo fileInfo(desktop); - const QString &curDesktop = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); - const QString &appDesktopPath = curDesktop + "/" + fileInfo.fileName(); - - QFile file(appDesktopPath); - if (!file.exists()) { - qDebug() << "file not exist...item info: " << desktop; - return; - } - - // 删除应用列表中的数据 - m_desktopAndItemMap.remove(desktop); - - // 删除发送到桌面的应用 - file.remove(); -} - -/** - * @brief Launcher::notifyUninstallDone 发送卸载结果 - * @param item - * @param result - */ -void Launcher::notifyUninstallDone(const Item &item, bool result) -{ - QString msg; - if (result) - msg = QString(tr("Removed successfully")); - else - msg = QString(tr("Failed to remove the app")); - - QList argList; - argList << QString("deepin-app-store") - << quint32(0) - << QString("deepin-app-store") - << msg - << QString("") - << QStringList("") - << QVariantMap() - << qint32(-1); - - QDBusInterface interface = QDBusInterface("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications"); - interface.callWithArgumentList(QDBus::Block, "Notify", argList); -} - -void Launcher::removeAutoStart(const QString &desktop) -{ - QFileInfo fileInfo(desktop); - const QString &autostartPath = BaseDir::userAutoStartDir().c_str() + fileInfo.fileName(); - - QFile file(autostartPath); - if (!file.exists()) { - qDebug() << QString("desktop file %1 doesn't exist...").arg(autostartPath); - return; - } - - file.remove(); -} - -/** - * @brief Launcher::isDeepinCustomDesktopFile 检测是否为Deepin定制应用 - * @param fileName - * @return - */ -bool Launcher::isDeepinCustomDesktopFile(QString fileName) -{ - QFileInfo fileInfo(fileName); - return fileInfo.dir() == QDir::homePath() + ".local/share/applications" - && fileInfo.completeBaseName().startsWith("deepin-custom-"); -} - -Item Launcher::NewItemWithDesktopInfo(DesktopInfo &info) -{ - QString enName(info.getDesktopFile()->getStr(MainSection, KeyName).c_str()); - QString enComment(info.getDesktopFile()->getStr(MainSection, KeyComment).c_str()); - QString xDeepinCategory(info.getDesktopFile()->getStr(MainSection, "X-Deepin-Category").c_str()); - QString xDeepinVendor(info.getDesktopFile()->getStr(MainSection, "X-Deepin-Vendor").c_str()); - - QString appName; - if (xDeepinVendor == "deepin") - appName = info.getGenericName().c_str(); - - if (appName.isEmpty()) - appName = info.getName().c_str(); - - if (appName.isEmpty()) - appName = info.getId().c_str(); - - QString appFileName(info.getFileName().c_str()); - QFileInfo fileInfo(appFileName); - int64_t ctime = fileInfo.birthTime().toSecsSinceEpoch(); - - Item item; - item.info.path = appFileName; - item.info.name = appName; - item.info.keywords << enName << appName; - item.info.id = getAppIdByFilePath(item.info.path, appDirs); - item.info.timeInstalled = ctime; - item.exec = info.getCommandLine().c_str(); - item.genericName = info.getGenericName().c_str(); - item.comment = enComment; - if (!info.getIcon().empty()) { - item.info.icon = info.getIcon().c_str(); - } - - xDeepinCategory = xDeepinCategory.toLower(); - - for (auto &keyWord : info.getKeywords()) { - item.desktopKeywords.push_back(QString(keyWord.c_str()).toLower()); - } - - for (auto &category : info.getCategories()) { - item.categories.push_back(QString(category.c_str()).toLower()); - } - return item; -} - -QString Launcher::getAppIdByFilePath(QString filePath, QStringList dirs) -{ - QString path = QDir::cleanPath(filePath); - QString appId; - for (auto dir : dirs) { - if (path.startsWith(dir)) { - appId = QDir(dir).relativeFilePath(path); - break; - } - } - - if (appId.isEmpty()) - return QString(); - - return appId.remove(".desktop"); -} diff --git a/src/modules/launcher/launcher.h b/src/modules/launcher/launcher.h deleted file mode 100644 index cca5459..0000000 --- a/src/modules/launcher/launcher.h +++ /dev/null @@ -1,151 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef LAUNCHER_H -#define LAUNCHER_H - -#include "common.h" -#include "synmodule.h" -#include "category.h" -#include "launcheriteminfolist.h" -#include "desktopinfo.h" - -#include -#include -#include -#include -#include - -// 同步数据 -struct SyncData { - QString version; - QString display_mode; - bool fullscreen; -}; - -// 应用类型 -enum class AppType { - Flatpak, - ChromeShortcut, - CrossOver, - WineApp, - Default -}; - -// 应用基本信息 -struct ItemInfo -{ - QString path; - QString name; - QString id; - QString icon; - Categorytype categoryId; - int64_t timeInstalled; - //QStringList keywords; // 存放前端搜索关键字 name enName -}; - -// 应用信息类 -struct Item { - inline bool isValid() {return !info.path.isEmpty();} - - LauncherItemInfo info; - QStringList desktopKeywords; //desktop file keywords - QStringList categories; - QString xDeepinCategory; - QString exec; - QString genericName; - QString comment; - std::map searchTargets; -}; - -class Launcher : public SynModule, public QDBusContext -{ - Q_OBJECT -public: - explicit Launcher(QObject *parent); - ~Launcher(); - - // 设置配置 - void setSyncConfig(QByteArray ba); - QByteArray getSyncConfig(); - - void initItems(); - const QMap *getItems(); - - int getDisplayMode(); - bool getFullScreen(); - void setDisplayMode(int value); - void setFullscreen(bool isFull); - - LauncherItemInfoList getAllItemInfos(); - QStringList getAllNewInstalledApps(); - bool getDisableScaling(QString appId); - LauncherItemInfo getItemInfo(QString appId); - bool getUseProxy(QString appId); - bool isItemOnDesktop(QString appId); - bool requestRemoveFromDesktop(QString appId); - bool requestSendToDesktop(QString appId); - void requestUninstall(const QString &desktop); - void setDisableScaling(QString appId, bool value); - void setUseProxy(QString appId, bool value); - -Q_SIGNALS: - void itemChanged(QString status, LauncherItemInfo itemInfo, qint64 ty); - void newAppLaunched(QString appId); - void uninstallSuccess(const QString &desktop); - void uninstallFailed(const QString &desktop, QString errMsg); - - void displayModeChanged(int mode); - void fullScreenChanged(bool isFull); - - void uninstallStatusChanged(const bool status); - -private Q_SLOTS: - void handleFSWatcherEvents(QDBusMessage msg); - void onCheckDesktopFile(const QString &filePath, int type = 0); - void onNewAppLaunched(const QString &filePath); - void onHandleUninstall(const QDBusMessage &message); - -private: - void initConnection(); - void initSettings(); - void loadDesktopPkgMap(); - void loadPkgCategoryMap(); - void handleAppHiddenChanged(); - void loadNameMap(); - QString getAppIdByFilePath(QString filePath, QStringList dirs); - bool isDeepinCustomDesktopFile(QString fileName); - Item NewItemWithDesktopInfo(DesktopInfo &info); - void addItem(Item &item); - Categorytype queryCategoryId(const Item *item); - Categorytype getXCategory(const Item *item); - QString queryPkgName(const QString &itemID, const QString &itemPath); - QString queryPkgNameWithDpkg(const QString &itemPath); - Item getItemByPath(QString itemPath); - void emitItemChanged(const Item *item, QString status); - AppType getAppType(DesktopInfo &info, const Item &item); - bool isLingLongApp(const QString &filePath); - void doUninstall(DesktopInfo &info, const Item &item); - void uninstallFlatpak(DesktopInfo &info, const Item &item); - bool uninstallWineApp(const Item &item); - void uninstallApp(const QString &name, const QString &pkg); - void removeDesktop(const QString &desktop); - void notifyUninstallDone(const Item &item, bool result); - void removeAutoStart(const QString &desktop); - -private: - QMap itemsMap; // appId, Item - QMap desktopPkgMap; - QMap pkgCategoryMap; - QMap nameMap; // appId, Name - QMap noPkgItemIds; - QVector appsHidden; - - QStringList appDirs; - - QMap m_desktopAndItemMap; // desktoppath,Item - DesktopInfo m_appInfo; // 卸载应用 -}; - -#endif // LAUNCHER_H diff --git a/src/modules/launcher/launchermanager.cpp b/src/modules/launcher/launchermanager.cpp deleted file mode 100644 index c30e320..0000000 --- a/src/modules/launcher/launchermanager.cpp +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "launchermanager.h" -#include "launcher.h" -#include "dbusadaptorlauncher.h" - -LauncherManager::LauncherManager(QObject *parent) - : QObject(parent) - , launcher(new Launcher(this)) -{ - qInfo() << "LauncherManager"; - new DBusAdaptorLauncher(launcher); - QDBusConnection con = QDBusConnection::sessionBus(); - if (!con.registerService(dbusService)) - { - qInfo() << "register service Launcher1 error:" << con.lastError().message(); - } - - if (!con.registerObject(dbusPath, launcher)) - { - qInfo() << "register object Launcher1 error:" << con.lastError().message(); - } - -} - -LauncherManager::~LauncherManager() -{ - -} diff --git a/src/modules/launcher/launchermanager.h b/src/modules/launcher/launchermanager.h deleted file mode 100644 index eafbc04..0000000 --- a/src/modules/launcher/launchermanager.h +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef LAUNCHERMANAGER_H -#define LAUNCHERMANAGER_H - -#include - -class Launcher; -class LauncherManager : public QObject -{ - Q_OBJECT -public: - explicit LauncherManager(QObject *parent = nullptr); - ~LauncherManager(); - -private: - Launcher *launcher; -}; - -#endif // LAUNCHERMANAGER_H diff --git a/src/modules/launcher/launchersettings.cpp b/src/modules/launcher/launchersettings.cpp deleted file mode 100644 index 872f21b..0000000 --- a/src/modules/launcher/launchersettings.cpp +++ /dev/null @@ -1,148 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "launchersettings.h" -#include "settings.h" - -#include - -#include -#include -#include - -DCORE_USE_NAMESPACE - -LauncherSettings::LauncherSettings(QObject *parent) - : QObject(parent) - , m_dconfig(Settings::ConfigPtr(configLauncher)) -{ - // 绑定属性 - connect(m_dconfig, &DConfig::valueChanged, this, [&] (const QString &key) { - if (key == keyDisplayMode) { - Q_EMIT displayModeChanged(m_dconfig->value(key).toString()); - } else if (key == keyFullscreen) { - Q_EMIT fullscreenChanged(m_dconfig->value(key).toBool()); - } else if (key == keyAppsHidden) { - Q_EMIT hiddenAppsChanged(); - } - }); -} - -/** - * @brief LauncherSettings::getDisplayMode 获取配置显示模式 - * @return - */ -QString LauncherSettings::getDisplayMode() -{ - return m_dconfig ? m_dconfig->value(keyDisplayMode).toString() : ""; -} - -/** - * @brief LauncherSettings::setDisplayMode 设置配置显示模式 - * @param value - */ -void LauncherSettings::setDisplayMode(QString value) -{ - if (m_dconfig) { - m_dconfig->setValue(keyDisplayMode, value); - } -} - -/** - * @brief LauncherSettings::getFullscreenMode 获取配置全屏模式 - * @return - */ -int LauncherSettings::getFullscreenMode() -{ - return m_dconfig ? m_dconfig->value(keyFullscreen).toBool() : false; -} - -/** - * @brief LauncherSettings::setFullscreenMode 设置配置全屏模式 - * @param value 全屏模式 - */ -void LauncherSettings::setFullscreenMode(int value) -{ - if (m_dconfig) { - m_dconfig->setValue(keyFullscreen, value); - } -} - -/** - * @brief LauncherSettings::getDisableScalingApps 获取配置禁用缩放应用 - * @return - */ -QVector LauncherSettings::getDisableScalingApps() -{ - QVector ret; - if (m_dconfig) { - QList apps = m_dconfig->value(keyAppsDisableScaling).toList(); - for (auto app : apps) { - ret.push_back(app.toString()); - } - } - return ret; -} - -/** - * @brief LauncherSettings::setDisableScalingApps 设置配置禁用缩放应用 - * @param value 应用禁用缩放应用 - */ -void LauncherSettings::setDisableScalingApps(const QVector &value) -{ - if (m_dconfig) { - QList apps; - for (const auto &app : value) - apps.push_back(app); - - m_dconfig->setValue(keyAppsDisableScaling, apps); - } -} - -/** - * @brief LauncherSettings::getUseProxyApps 获取配置代理应用 - * @return - */ -QVector LauncherSettings::getUseProxyApps() -{ - QVector ret; - if (m_dconfig) { - QList apps = m_dconfig->value(keyAppsUseProxy).toList(); - for (auto app : apps) { - ret.push_back(app.toString()); - } - } - return ret; -} - -/** - * @brief LauncherSettings::setUseProxy 设置配置代理应用 - * @param value 代理应用 - */ -void LauncherSettings::setUseProxy(const QVector &value) -{ - if (m_dconfig) { - QList apps; - for (const auto &app : value) - apps.push_back(app); - - m_dconfig->setValue(keyAppsUseProxy, apps); - } -} - -/** - * @brief LauncherSettings::getHiddenApps 获取配置隐藏应用 - * @return - */ -QVector LauncherSettings::getHiddenApps() -{ - QVector ret; - if (m_dconfig) { - QList hiddenApps = m_dconfig->value(keyAppsHidden).toList(); - for (auto app : hiddenApps) { - ret.push_back(app.toString()); - } - } - return ret; -} diff --git a/src/modules/launcher/launchersettings.h b/src/modules/launcher/launchersettings.h deleted file mode 100644 index cfa9a16..0000000 --- a/src/modules/launcher/launchersettings.h +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef LAUNCHERSETTINGS_H -#define LAUNCHERSETTINGS_H - -#include "common.h" - -#include -#include - -namespace Dtk { -namespace Core { -class DConfig; -} -} - -using namespace Dtk::Core; - -// 启动器相关配置 -class LauncherSettings : public QObject -{ - Q_OBJECT - LauncherSettings(QObject *paret = nullptr); - LauncherSettings(const LauncherSettings &); - LauncherSettings& operator= (const LauncherSettings &); - DConfig *m_dconfig; - -public: - static inline LauncherSettings *instance() { - static LauncherSettings instance; - return &instance; - } - - QString getDisplayMode(); - void setDisplayMode(QString value); - - int getFullscreenMode(); - void setFullscreenMode(int value); - - QVector getDisableScalingApps(); - void setDisableScalingApps(const QVector &value); - - QVector getUseProxyApps(); - void setUseProxy(const QVector &value); - - QVector getHiddenApps(); - -Q_SIGNALS: - void displayModeChanged(QString mode); - void fullscreenChanged(bool isFull); - void hiddenAppsChanged(); -}; - -#endif // LAUNCHERSETTINGS_H diff --git a/src/modules/methods/basic.h b/src/modules/methods/basic.h deleted file mode 100644 index 1781896..0000000 --- a/src/modules/methods/basic.h +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef BASIC_H_ -#define BASIC_H_ -#include -#include -#include - -namespace Methods -{ - struct Basic - { - QString type; - }; - - inline void fromJson(const QByteArray &array, Basic &basic) - { - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson basic failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("type")) { - qWarning() << "type not exist in basic array"; - return; - } - - basic.type = obj.value("type").toString(); - } - -} // namespace Methods - -#endif // BASIC_H_ diff --git a/src/modules/methods/instance.hpp b/src/modules/methods/instance.hpp deleted file mode 100644 index ea4ac20..0000000 --- a/src/modules/methods/instance.hpp +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef C664E26D_6517_412B_950F_07E20963349E -#define C664E26D_6517_412B_950F_07E20963349E - -#include -#include -#include - -namespace Methods { -struct Instance { - QString hash; - QString type{ "instance" }; -}; - -inline void toJson(QByteArray &array, const Instance &instance) { - QJsonObject obj { - { "type", instance.type }, - { "hash", instance.hash } - }; - - array = QJsonDocument(obj).toJson(); -} - -inline void fromJson(const QByteArray &array, Instance &instance) { - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson instance failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("hash")) { - qWarning() << "hash not exist in instance array"; - return; - } - - instance.hash = obj.value("hash").toString(); -} - -} // namespace Methods - -#endif /* C664E26D_6517_412B_950F_07E20963349E */ diff --git a/src/modules/methods/process_status.hpp b/src/modules/methods/process_status.hpp deleted file mode 100644 index cb145a3..0000000 --- a/src/modules/methods/process_status.hpp +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef PROCESS_STATUS_H_ -#define PROCESS_STATUS_H_ - -#include -#include -#include - -namespace Methods { -struct ProcessStatus { - QString data; - QString type; - QString id; - int code; -}; - -inline void toJson(QByteArray& array, const ProcessStatus& processStatus) -{ - QJsonObject obj { - { "type", processStatus.type }, - { "data", processStatus.data }, - { "id", processStatus.id }, - { "code", processStatus.code } - }; - - array = QJsonDocument(obj).toJson(); -} -inline void fromJson(const QByteArray& array, ProcessStatus& quit) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson quit failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("id") || !obj.contains("data") || !obj.contains("code")) { - qWarning() << "id data code not exist in quit array"; - return; - } - - quit.id = obj.value("id").toString(); - quit.data = obj.value("data").toString(); - quit.code = obj.value("code").toInt(); - quit.type = obj.value("type").toString(); -} -} // namespace Methods - -#endif // PROCESS_STATUS_H_ diff --git a/src/modules/methods/quit.hpp b/src/modules/methods/quit.hpp deleted file mode 100644 index f4984b3..0000000 --- a/src/modules/methods/quit.hpp +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef QUIT_H_ -#define QUIT_H_ -#include -#include -#include - -namespace Methods { -struct Quit { - QString date; - QString type{ "quit" }; - QString id; - int code; -}; - -inline void toJson(QByteArray &array, const Quit &quit) { - QJsonObject obj { - { "type", quit.type }, - { "date", quit.date }, - { "id", quit.id }, - { "code", quit.code } - }; - - array = QJsonDocument(obj).toJson(); -} - -inline void fromJson(const QByteArray &array, Quit &quit) { - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson quit failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("id") || !obj.contains("date") || !obj.contains("code")) { - qWarning() << "id date code not exist in quit array"; - return; - } - - quit.id = obj.value("id").toString(); - quit.date = obj.value("date").toString(); - quit.code = obj.value("code").toInt(); -} - -} // namespace Methods - -#endif // QUIT_H_ diff --git a/src/modules/methods/registe.hpp b/src/modules/methods/registe.hpp deleted file mode 100644 index 832f12f..0000000 --- a/src/modules/methods/registe.hpp +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef REGISTER_H_ -#define REGISTER_H_ -#include -#include -#include - -namespace Methods { -struct Registe { - QString date; - QString id; - QString type{ "registe" }; - QString hash; - bool state; -}; - -inline void toJson(QByteArray &array, const Registe ®iste) { - QJsonObject obj = { - { "type", registe.type }, - { "id", registe.id }, - { "hash", registe.hash }, - { "state", registe.state }, - { "date", registe.date } - }; - - array = QJsonDocument(obj).toJson(); -} - -inline void fromJson(const QByteArray &array, Registe ®iste) { - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson registe failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("id") || !obj.contains("date") || !obj.contains("hash")\ - || !obj.contains("state")) { - qWarning() << "id date code state not exist in registe array"; - return; - } - - registe.id = obj.value("id").toString(); - registe.date = obj.value("date").toString(); - registe.hash = obj.value("hash").toString(); - registe.state = obj.value("state").toBool(); -} - -} // namespace Methods - -#endif // REGISTER_H_ diff --git a/src/modules/methods/task.hpp b/src/modules/methods/task.hpp deleted file mode 100644 index f404cc5..0000000 --- a/src/modules/methods/task.hpp +++ /dev/null @@ -1,88 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef B0B88BD6_CF1E_4E87_926A_E6DBE6B9B19C -#define B0B88BD6_CF1E_4E87_926A_E6DBE6B9B19C - - -#include -#include -#include -#include -#include -#include -#include - -namespace Methods -{ - struct Task - { - QString id; - QString runId; - QString type{"task"}; - QString date; - QString filePath; - QList arguments; - QMap environments; - }; - - inline void toJson(QByteArray &array, const Task &task) { - QJsonArray argArray; - for (auto arg : task.arguments) { - argArray.append(arg); - } - - QVariantMap envsMap; - for (auto it = task.environments.constBegin(); it != task.environments.constEnd(); ++it) { - envsMap.insert(it.key(), it.value()); - } - - QJsonObject obj = { - {"type", task.type}, - {"id", task.id}, - {"runId", task.runId}, - {"filePath", task.filePath}, - {"date", task.date}, - {"arguments", argArray}, - {"environments", QJsonObject::fromVariantMap(envsMap)} - }; - - array = QJsonDocument(obj).toJson(); - } - - inline void fromJson(const QByteArray &array, Task &task) { - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson task failed"; - return; - } - QJsonObject obj = doc.object(); - if (obj.contains("id")) { - task.id = obj.value("id").toString(); - } - if (obj.contains("runId")) { - task.runId = obj.value("runId").toString(); - } - if (obj.contains("filePath")) { - task.filePath = obj.value("filePath").toString(); - } - if (obj.contains("date")) { - task.date = obj.value("date").toString(); - } - - if (obj.contains("arguments")) { - for (auto arg : obj.value("arguments").toArray()) { - task.arguments.append(arg.toString()); - } - } - if (obj.contains("environments")) { - QVariantMap envsMap = obj.value("environments").toObject().toVariantMap(); - for (auto it = envsMap.constBegin(); it != envsMap.constEnd(); ++it) { - task.environments.insert(it.key(), it.value().toString()); - } - } - } -} // namespace Methods - -#endif /* B0B88BD6_CF1E_4E87_926A_E6DBE6B9B19C */ diff --git a/src/modules/methods/use_default_app_info.h b/src/modules/methods/use_default_app_info.h deleted file mode 100644 index 9424883..0000000 --- a/src/modules/methods/use_default_app_info.h +++ /dev/null @@ -1,74 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef USE_DEFAULT_APP_INFO_H -#define USE_DEFAULT_APP_INFO_H - -#include -#include -#include -#include - -namespace Methods { -struct DefaultUserAppInfo { - QVariantList appId; - std::string appType; - QVariantList supportedType; -}; - -struct DefaultUserAppInfos { - std::vector appInfos; -}; - -inline void toJson(QJsonObject& j, const DefaultUserAppInfo& userAppInfo) -{ - j = QJsonObject{ { "AppId", QJsonArray::fromVariantList(userAppInfo.appId) }, { "AppType", userAppInfo.appType.c_str() }, { "SupportedType", QJsonArray::fromVariantList(userAppInfo.supportedType) }}; -} - -inline void fromJson(const QJsonObject& j, DefaultUserAppInfo& userAppInfo) -{ - - if (j.contains("AppId")) { - userAppInfo.appId = j.value("AppId").toArray().toVariantList(); - } - - if (j.contains("AppType")) { - userAppInfo.appType = j.value("AppType").toString().toStdString(); - } - - if (j.contains("SupportedType")) { - userAppInfo.supportedType = j.value("SupportedType").toArray().toVariantList(); - } -} - -inline void toJson(QJsonObject& j, const DefaultUserAppInfos& userAppInfos) -{ - QJsonObject tmpObj; - QJsonArray appInfoArray; - - for (auto appInfo : userAppInfos.appInfos) { - toJson(tmpObj, appInfo); - appInfoArray.append(tmpObj); - } - - j = QJsonObject { - {"DefaultApps", appInfoArray} - }; -} - -inline void fromJson(const QJsonObject& j, DefaultUserAppInfos& userAppInfos) -{ - QJsonObject tmpObj = j; - - if (j.contains("DefaultApps")) { - DefaultUserAppInfo userAppInfo; - for (auto appInfo : tmpObj.take("DefaultApps").toArray()) { - fromJson(appInfo.toObject(), userAppInfo); - userAppInfos.appInfos.push_back(userAppInfo); - } - } -} -} // namespace Methods - -#endif // USE_DEFAULT_APP_INFO_H diff --git a/src/modules/methods/use_mime_app_info.h b/src/modules/methods/use_mime_app_info.h deleted file mode 100644 index 12f1803..0000000 --- a/src/modules/methods/use_mime_app_info.h +++ /dev/null @@ -1,63 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef USE_MIME_APP_INFO_H -#define USE_MIME_APP_INFO_H - -#include -#include -#include -#include - -namespace Methods { -struct UserAppInfo { - std::string deskopid; - QVariantList supportedMime; -}; - -struct UserAppInfos { - std::vector appInfos; -}; - -inline void toJson(QJsonObject& j, const UserAppInfo& userAppInfo) -{ - j = QJsonObject{ { "DesktopId", userAppInfo.deskopid.c_str() }, { "SupportedMime", QJsonArray::fromVariantList(userAppInfo.supportedMime) } }; -} - -inline void fromJson(const QJsonObject& j, UserAppInfo& userAppInfo) -{ - if (j.contains("DesktopId")) { - userAppInfo.deskopid = j.value("DesktopId").toString().toStdString(); - } - - if (j.contains("SupportedMime")) { - userAppInfo.supportedMime = j.value("SupportedMime").toArray().toVariantList(); - } -} -inline void toJson(QJsonArray& j, const UserAppInfos& userAppInfos) -{ - QJsonObject tmpObj; - QJsonArray appInfoArray; - - for (auto appInfo : userAppInfos.appInfos) { - toJson(tmpObj, appInfo); - appInfoArray.append(tmpObj); - } - - j = appInfoArray; -} - -inline void fromJson(const QJsonArray& j, UserAppInfos& userAppInfos) -{ - QJsonArray tmpObj = j; - - for (auto iter : tmpObj) { - UserAppInfo userAppInfo; - fromJson(iter.toObject(), userAppInfo); - userAppInfos.appInfos.push_back(userAppInfo); - } -} -} // namespace Methods - -#endif // USE_MIME_APP_INFO_H diff --git a/src/modules/mimeapp/mime_app.cpp b/src/modules/mimeapp/mime_app.cpp deleted file mode 100644 index e0470b0..0000000 --- a/src/modules/mimeapp/mime_app.cpp +++ /dev/null @@ -1,385 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "mime_app.h" -#include "utils.h" -#include "../methods/use_mime_app_info.h" -#include "../methods/use_default_app_info.h" -#include "appinfo.h" -#include "terminalinfo.h" -#include "appinfocommon.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -class MimeAppPrivate : public QObject -{ - MimeApp *q_ptr = nullptr; - Q_DECLARE_PUBLIC(MimeApp) - -private: - Methods::UserAppInfos userAppInfos; - std::string filename; - QMutex mutex; -public: - MimeAppPrivate(MimeApp *parent) : QObject(parent), q_ptr(parent) - { - std::string homeDir = getUserHomeDir(); - if (!homeDir.empty()) { - homeDir += "/.config/deepin/dde-daemon/user_mime.json"; - filename = homeDir; - } - } - void Init() - { - QFile file(filename.c_str()); - if (!file.exists()) { - return; - } - - if (!file.open(QIODevice::ReadOnly)) { - return; - } - - QJsonParseError *error = new QJsonParseError; - QJsonDocument jdc = QJsonDocument::fromJson(file.readAll(), error); - - Methods::fromJson(jdc.array(), userAppInfos); - - file.close(); - } - - void Write() - { - QFile file(filename.c_str()); - if (!file.exists()) { - return; - } - - if (!file.open(QIODevice::WriteOnly)) { - return; - } - - QJsonArray jsonArr; - Methods::toJson(jsonArr, userAppInfos); - - QJsonDocument jdc; - jdc.setArray(jsonArr); - file.write(jdc.toJson(QJsonDocument::Compact)); //Indented:表示自动添加/n回车符 - file.close(); - } - - bool Add(const std::string &desktopId, QStringList mimeTypes) - { - bool bAdd = false; - - std::vector::iterator iter = userAppInfos.appInfos.begin(); - while (iter != userAppInfos.appInfos.end()) { - if (iter->deskopid == desktopId) { - for (auto mimeType : mimeTypes) { - if (std::find(iter->supportedMime.begin(), iter->supportedMime.end(), mimeType) != iter->supportedMime.end()) { - bAdd = true; - iter->supportedMime.push_back(mimeType); - } - } - return bAdd; - } - iter++; - } - - bAdd = true; - Methods::UserAppInfo appInfo; - for (auto mimeType : mimeTypes) { - - appInfo.supportedMime.push_back(mimeType); - } - - userAppInfos.appInfos.push_back(appInfo); - - return bAdd; - } - - bool Delete(const std::string &desktopId) - { - std::vector::iterator iter = userAppInfos.appInfos.begin(); - - while (iter != userAppInfos.appInfos.end()) { - if (iter->deskopid == desktopId) { - iter = userAppInfos.appInfos.erase(iter); - return true; - } else { - iter++; - } - } - - return false; - } - - bool DeleteMimeTypes(const std::string &desktopId, QStringList mimeTypes) - { - bool bDelete = false; - std::vector::iterator iter = userAppInfos.appInfos.begin(); - - while (iter != userAppInfos.appInfos.end()) { - if (iter->deskopid == desktopId) { - for (auto mimeType : mimeTypes) { - if (std::find(iter->supportedMime.begin(), iter->supportedMime.end(), mimeType) == iter->supportedMime.end()) { - bDelete = true; - iter->supportedMime.push_back(mimeType); - } - } - } - iter++; - } - - return bDelete; - } - - std::vector GetUserAppInfosByMimeType(std::string mimeType) - { - std::vector retVector; - - for (auto iter : userAppInfos.appInfos) { - if (std::find(iter.supportedMime.begin(), iter.supportedMime.end(), mimeType.c_str()) != iter.supportedMime.end()) { - retVector.push_back(iter); - } - } - - return retVector; - } - ~MimeAppPrivate() {} - -}; - -MimeApp::MimeApp(QObject *parent) : QObject(parent), dd_ptr(new MimeAppPrivate(this)) -{ - Q_D(MimeApp); - d->Init(); -} - -MimeApp::~MimeApp() -{ - -} - -void MimeApp::deleteMimeAssociation(std::string mimeType, std::string desktopId) -{ - Q_D(MimeApp); - - KeyFile keyFile; - keyFile.loadFile(d->filename); - - std::vector sessions{AppinfoCommon::SectionDefaultApps, AppinfoCommon::SectionAddedAssociations}; - - for (auto iter : sessions) { - std::vector apps = keyFile.getStrList(iter, mimeType); - std::vector::iterator app = apps.begin(); - while (app != apps.end()) { - if ((*app) == desktopId) { - app = apps.erase(app); - } else { - app++; - } - } - if (apps.empty()) { - //keyFile.DeleteKey(section, mimeType); - } else { - //keyFile.SetStringList(iter,mimeType,apps); - } - } - - keyFile.saveToFile(d->filename); -} - -std::string MimeApp::findFilePath(std::string fileName) -{ - std::string homeDir = getUserHomeDir(); - std::string path = homeDir + "/.local/share" + fileName; - - QFileInfo file(path.c_str()); - if (file.isFile()) { - return path; - } - - path = "/usr/local/share" + fileName; - - file.setFile(path.c_str()); - if (file.isFile()) { - return path; - } - - return "/usr/share" + fileName; -} - -void MimeApp::AddUserApp(QStringList mimeTypes, const QString &desktopId) -{ - qInfo() << "AddUserApp mimeTypes: " << mimeTypes << ", desktopId: " << desktopId; - Q_D(MimeApp); - - std::shared_ptr appInfo = AppInfoManger::loadByDesktopId(desktopId.toStdString()); - if (!appInfo) { - return; - } - - bool bAdd = d->Add(desktopId.toStdString(), mimeTypes); - - if (bAdd) { - d->Write(); - } - - return; -} - -bool MimeApp::setDefaultApp(const std::string &mimeType, const std::string &desktopId) -{ - qInfo() << "setDefaultApp mimeType: " << mimeType.c_str() << ", desktopId: " << desktopId.c_str(); - Q_D(MimeApp); - - KeyFile keyFile; - keyFile.loadFile(d->filename); - - std::string curDeskTopId = keyFile.getStr(AppinfoCommon::SectionDefaultApps, mimeType); - if (curDeskTopId == desktopId) { - return true; - } - - return AppInfoManger::setDefaultApp(mimeType, desktopId); -} - -void MimeApp::DeleteApp(QStringList mimeTypes, const QString &desktopId) -{ - qInfo() << "DeleteApp mimeTypes: " << mimeTypes << ", desktopId: " << desktopId; - Q_D(MimeApp); - - if (d->DeleteMimeTypes(desktopId.toStdString(), mimeTypes)) { - d->Write(); - return; - } - - std::shared_ptr appInfo = AppInfoManger::loadByDesktopId(desktopId.toStdString()); - if (!appInfo) { - return; - } - - std::vector originMimeTypes = appInfo->getStringList(AppinfoCommon::MainSection, AppinfoCommon::KeyMimeType); - - for (auto iter : mimeTypes) { - if (std::find(originMimeTypes.begin(), originMimeTypes.end(), iter.toStdString()) == originMimeTypes.end()) { - deleteMimeAssociation(iter.toStdString(), desktopId.toStdString()); - } - } -} - -void MimeApp::DeleteUserApp(const QString &desktopId) -{ - qInfo() << "DeleteUserApp desktopId: " << desktopId; - Q_D(MimeApp); - - bool bDelete = d->Delete(desktopId.toStdString()); - - if (bDelete) { - d->Write(); - } -} - -QString MimeApp::GetDefaultApp(const QString &mimeType) -{ - qInfo() << "GetDefaultApp mimeType: " << mimeType; - std::shared_ptr appInfo; - - if (mimeType.toStdString().compare(AppinfoCommon::AppMimeTerminal) == 0) { - appInfo = TerminalInfo::getInstanceTerminal().getDefaultTerminal(); - } else { - std::string appId = AppInfoManger::getDefaultApp(mimeType.toStdString(), false); - appInfo = AppInfoManger::loadByDesktopId(appId); - } - - if (!appInfo) { - return ""; - } - - return appInfo->toJson().c_str(); -} - -QString MimeApp::ListApps(const QString &mimeType) -{ - qInfo() << "ListApps mimeType: " << mimeType; - std::vector> appInfos; - - if (mimeType.toStdString().compare(AppinfoCommon::AppMimeTerminal) == 0) { - appInfos = TerminalInfo::getInstanceTerminal().getTerminalInfos(); - } else { - std::vector appList = AppInfoManger::getAppList(mimeType.toStdString()); - - for (auto iter : appList) { - std::shared_ptr appInfo = AppInfoManger::loadByDesktopId(iter); - if (appInfo) { - appInfos.push_back(appInfo); - } - } - } - - - std::string userAppDir = getUserDataDir() + "/applications"; - std::vector>::iterator iter = appInfos.begin(); - - while (iter != appInfos.end()) { - QDir dir((*iter)->getFileName().c_str()); - - if (dir.path().toStdString() == userAppDir && hasBeginWith(dir.path().toStdString(), "deepin-custom-")) { - iter = appInfos.erase(iter); - } else { - iter++; - } - } - - return AppInfoManger::toJson(appInfos).c_str(); -} - -QString MimeApp::ListUserApps(const QString &mimeType) -{ - qInfo() << "ListUserApps mimeType: " << mimeType; - Q_D(MimeApp); - - std::vector> retAppInfos; - - std::vector userAppInfos = d->GetUserAppInfosByMimeType(mimeType.toStdString()); - std::vector::iterator iter = userAppInfos.begin(); - - while (iter != userAppInfos.end()) { - std::shared_ptr appInfo = AppInfoManger::loadByDesktopId(iter->deskopid); - if (appInfo) { - appInfo->setCanDelete(true); - retAppInfos.push_back(appInfo); - } - iter++; - } - - return AppInfoManger::toJson(retAppInfos).c_str(); -} - -void MimeApp::SetDefaultApp(const QStringList &mimeTypes, const QString &desktopId) -{ - qInfo() << "SetDefaultApp mimeTypes: " << mimeTypes << ", desktopId: " << desktopId; - - bool bSuccess = false; - for (auto mime : mimeTypes) { - if (mime.toStdString().compare(AppinfoCommon::AppMimeTerminal) == 0) { - bSuccess = TerminalInfo::getInstanceTerminal().setDefaultTerminal(desktopId.toStdString()); - } else { - bSuccess = AppInfoManger::setDefaultApp(mime.toStdString(), desktopId.toStdString()); - } - - if (!bSuccess) { - qWarning() << "SetDefaultApp faile"; - break; - } - } -} diff --git a/src/modules/mimeapp/mime_app.h b/src/modules/mimeapp/mime_app.h deleted file mode 100644 index cab39a0..0000000 --- a/src/modules/mimeapp/mime_app.h +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef MIME_APP_H -#define MIME_APP_H - -#include "../../lib/dfile.h" - -#include - - -class MimeAppPrivate; -class MimeApp : public QObject -{ - Q_OBJECT - QScopedPointer dd_ptr; - Q_DECLARE_PRIVATE_D(qGetPtrHelper(dd_ptr), MimeApp) -public: - explicit MimeApp(QObject *parent = nullptr); - void deleteMimeAssociation(std::string mimeType, std::string desktopId); - bool setDefaultApp(const std::string &mimeType, const std::string &desktopId); - std::string findFilePath(std::string fileName); - ~MimeApp() override; - -Q_SIGNALS: - // Standard Notifications dbus implementation - void Change(); -public: // PROPERTIES - -public Q_SLOTS: // METHODS - void AddUserApp(QStringList mimeTypes, const QString &desktopId); - void DeleteApp(QStringList mimeTypes, const QString &desktopId); - void DeleteUserApp(const QString &desktopId); - QString GetDefaultApp(const QString &mimeType); - QString ListApps(const QString &mimeType); - QString ListUserApps(const QString &mimeType); - void SetDefaultApp(const QStringList &mimeTypes, const QString &desktopId); -private: - -}; - -#endif // MIME_APP_H diff --git a/src/modules/socket/client.cpp b/src/modules/socket/client.cpp deleted file mode 100644 index 5dbd55b..0000000 --- a/src/modules/socket/client.cpp +++ /dev/null @@ -1,131 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "client.h" - -#include -#include -#include - -#include - -namespace Socket { -struct ClientPrivate { - Client* q_ptr; - int socket_fd; - std::function&)> readFunc; - std::thread* readThread; - - ClientPrivate(Client* client) : q_ptr(client), readThread(nullptr) {} - ~ClientPrivate() - { - if (readThread) { - close(socket_fd); - readThread->join(); - delete readThread; - } - } - bool connect(const std::string& host) - { - sockaddr_un address; - - if ((socket_fd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0) { - printf("socket() failed\n"); - return false; - } - - memset(&address, 0, sizeof(struct sockaddr_un)); - - address.sun_family = AF_LOCAL; - snprintf(address.sun_path, host.size() + 1, "%s", host.c_str()); - if (::connect(socket_fd, (struct sockaddr*) &address, sizeof(struct sockaddr_un)) != 0) { - printf("connect() failed\n"); - return false; - } - - if (readThread) { - return false; - } - - // TODO readFunc function? - if (readFunc) { - readThread = new std::thread([=] { - char buf[512]; - std::vector result; - int bytesRead; - while ((bytesRead = recv(socket_fd, buf, 512, 0)) > 0) { - if (bytesRead == -1) { - return; - } - for (int i = 0; i < bytesRead; i++) { - result.push_back(buf[i]); - } - if (buf[bytesRead - 1] == '\0') { - readFunc(result); - result.clear(); - } - }; - }); - readThread->detach(); - } - - return true; - } - - QByteArray get(const QByteArray &call) { - send(call); - - char buf[512]; - std::vector data; - int bytesRead; - while ((bytesRead = recv(socket_fd, buf, 512, 0)) > 0) { - for (int i = 0; i < bytesRead; ++i) { - data.push_back(buf[i]); - } - - if (buf[bytesRead - 1] == '\0') { - break; - } - } - - return data.data(); - } - - size_t send(const QByteArray &call) { - std::string data = call.data(); - // \0 作为结尾标记 - data += '\0'; - return write(socket_fd, data.c_str(), data.length()); - } -}; - -Client::Client() : d_ptr(new ClientPrivate(this)) {} - -Client::~Client() {} - -bool Client::connect(const std::string& host) -{ - return d_ptr->connect(host); -} - -QByteArray Client::get(const QByteArray &call) -{ - return d_ptr->get(call); -} - -size_t Client::send(const QByteArray &call) -{ - return d_ptr->send(call); -} - -void Client::onReadyRead(std::function&)> func) -{ - d_ptr->readFunc = func; -} - -void Client::waitForFinished() -{ - d_ptr->readThread->join(); -} -} // namespace Socket diff --git a/src/modules/socket/client.h b/src/modules/socket/client.h deleted file mode 100644 index ce3fb2f..0000000 --- a/src/modules/socket/client.h +++ /dev/null @@ -1,32 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef B1D5EB4F_7645_4BDA_87D6_6B80A4910014 -#define B1D5EB4F_7645_4BDA_87D6_6B80A4910014 - -#include -#include -#include - -#include - -namespace Socket -{ - class ClientPrivate; - class Client - { - std::unique_ptr d_ptr; - - public: - Client(); - ~Client(); - bool connect(const std::string &host); - QByteArray get(const QByteArray &call); - size_t send(const QByteArray &call); - void onReadyRead(std::function &)> func); - void waitForFinished(); - }; -} // namespace Socket - -#endif /* B1D5EB4F_7645_4BDA_87D6_6B80A4910014 */ diff --git a/src/modules/socket/server.cpp b/src/modules/socket/server.cpp deleted file mode 100644 index 988dbef..0000000 --- a/src/modules/socket/server.cpp +++ /dev/null @@ -1,162 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "server.h" - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace Socket { - -ServerPrivate::ServerPrivate(Server *server) - : QObject() - , q_ptr(server) - , socket_fd(-1) - , workThread(nullptr) -{ - if ((socket_fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { - std::cout << "socket() failed" << std::endl; - return; - } - - connect(this, &ServerPrivate::requestStart, this, &ServerPrivate::work, Qt::QueuedConnection); -} - -ServerPrivate::~ServerPrivate() -{ - -} - -void ServerPrivate::work() -{ - // 处理客户端数据 - while (true) { - // 阻塞等待客户端连接 - int socket = accept(socket_fd, nullptr, nullptr); - if (socket == -1) { - std::cout << "accept() failed" << std::endl; - return; - } - QtConcurrent::run([=] { - int readBytes = 0; - char buffer[1024]; - std::vector data; - while (true) { - readBytes = recv(socket, buffer, 1024, 0); - if (readBytes == -1) { - std::cout << "client connect closed" << std::endl; - break; - } - - if (readBytes == 0) { - break; - } - - for (int i = 0; i != readBytes; i++) { - data.push_back(buffer[i]); - } - - if (buffer[readBytes - 1] == '\0') { - Q_EMIT q_ptr->onReadyRead(socket, data); - data.clear(); - } - } - }); - } -} - -bool ServerPrivate::listen(const std::string &host) -{ - if (socket_fd < 0) { - return false; - } - - struct sockaddr_un addr; - memset(&addr, 0, sizeof(struct sockaddr_un)); - addr.sun_family = AF_UNIX; - snprintf(addr.sun_path, host.size() + 1, "%s", host.c_str()); - - // 移除原有套接字文件 - if (remove(host.c_str()) == -1 && errno != ENOENT) { - std::cout << "remove() failed" << std::endl; - return false; - } - - // 绑定套接字文件 - if (bind(socket_fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) { - std::cout << "bind() failed" << std::endl; - return false; - } - - // 监听客户端连接 - if (::listen(socket_fd, 20) < 0) { - std::cout << "listen() failed" << std::endl; - return false; - } - - return true; -} - -void ServerPrivate::write(int socket, const std::vector &data) -{ - ::write(socket, data.data(), data.size()); -} - -void ServerPrivate::closeClient(int socket) -{ - ::close(socket); -} - - -Server::Server() - : QObject(nullptr) - , d_ptr(new ServerPrivate(this)) -{ - qRegisterMetaType>("VectorChar"); -} - -Server::~Server() -{ - -} - -bool Server::listen(const std::string &host) -{ - if (d_ptr->workThread) { - return false; - } - - const bool result = d_ptr->listen(host); - if (!result) { - return result; - } - - d_ptr->workThread = new QThread; - d_ptr->moveToThread(d_ptr->workThread); - d_ptr->workThread->start(); - Q_EMIT d_ptr->requestStart(); - return result; -} - -void Server::write(int socket, const std::vector &data) -{ - d_ptr->write(socket, data); -} - -void Server::close(int socket) -{ - d_ptr->closeClient(socket); -} - -} // namespace Socket - -#include "server.moc" diff --git a/src/modules/socket/server.h b/src/modules/socket/server.h deleted file mode 100644 index fd5b8bd..0000000 --- a/src/modules/socket/server.h +++ /dev/null @@ -1,53 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef F358257E_94E5_4A6C_91A8_4B6E57999E7B -#define F358257E_94E5_4A6C_91A8_4B6E57999E7B - -#include -#include -#include -#include -#include - -namespace Socket { - -class Server; -class ServerPrivate : public QObject { - Q_OBJECT -public: - Server *q_ptr; - int socket_fd; - QThread *workThread; - -Q_SIGNALS: - void requestStart(); - -public: - ServerPrivate(Server *server); - ~ServerPrivate(); - - void work(); - bool listen(const std::string &host); - void write(int socket, const std::vector &data); - void closeClient(int socket); -}; - - -class Server : public QObject { - Q_OBJECT - std::unique_ptr d_ptr; - -public: - Server(); - ~Server(); - bool listen(const std::string& host); - void write(int socket, const std::vector& data); - void close(int socket); -Q_SIGNALS: - void onReadyRead(int socket, const std::vector& data) const; -}; -} // namespace Socket - -#endif /* F358257E_94E5_4A6C_91A8_4B6E57999E7B */ diff --git a/src/modules/startmanager/common.h b/src/modules/startmanager/common.h deleted file mode 100644 index 9e32260..0000000 --- a/src/modules/startmanager/common.h +++ /dev/null @@ -1,47 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef COMMON_H -#define COMMON_H - -#include - -const QString AMServiceName = "/org/deepin/dde/Application1/Manager"; -const QString autostartDir = "autostart"; -const QString proxychainsBinary = "proxychains4"; - -const QString configLauncher = "com.deepin.dde.launcher"; -const QString keyAppsUseProxy = "Apps_Use_Proxy"; -const QString keyAppsDisableScaling = "Apps_Disable_Scaling"; - -const QString KeyXGnomeAutostartDelay = "X-GNOME-Autostart-Delay"; -const QString KeyXGnomeAutoRestart = "X-GNOME-AutoRestart"; -const QString KeyXDeepinCreatedBy = "X-Deepin-CreatedBy"; -const QString KeyXDeepinAppID = "X-Deepin-AppID"; - -const QString configStartdde = "com.deepin.dde.startdde"; -const QString keyAutostartDelay = "Autostart_Delay"; -const QString keyMemCheckerEnabled = "Memchecker_Enabled"; -const QString keySwapSchedEnabled = "swap-sched-enabled"; - -const QString configXsettings = "com.deepin.xsettings"; -const QString keyScaleFactor = "Scale_Factor"; - -const QString uiAppSchedHooksDir = "/usr/lib/UIAppSched.hooks"; -const QString launchedHookDir = uiAppSchedHooksDir + "/launched"; - -const QString cpuFreqAdjustFile = "/usr/share/startdde/app_startup.conf"; -const QString performanceGovernor = "performance"; - -const int restartRateLimitSeconds = 60; - -const QString sysMemLimitConfig = "/usr/share/startdde/memchecker.json"; - -const int defaultMinMemAvail = 300; // 300M -const int defaultMaxSwapUsed = 1200; // 1200M - -const QString autostartAdded = "added"; -const QString autostartDeleted = "deleted"; - -#endif // COMMON_H diff --git a/src/modules/startmanager/startmanager.cpp b/src/modules/startmanager/startmanager.cpp deleted file mode 100644 index 3f56ceb..0000000 --- a/src/modules/startmanager/startmanager.cpp +++ /dev/null @@ -1,696 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "startmanager.h" -#include "basedir.h" -#include "dfile.h" -#include "common.h" -#include "desktopinfo.h" -#include "startmanagersettings.h" -#include "startmanagerdbushandler.h" -#include "meminfo.h" -#include "../../service/impl/application_manager.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define DESKTOPEXT ".desktop" -#define SETTING StartManagerSettings::instance() - -StartManager::StartManager(QObject *parent) - : QObject(parent) - , minMemAvail(0) - , maxSwapUsed(0) - , dbusHandler(new StartManagerDBusHandler(this)) - , m_autostartFileWatcher(new QFileSystemWatcher(this)) - , m_autostartFiles(getAutostartList()) - , m_isDBusCalled(false) -{ - waitForDeadChild(); - loadSysMemLimitConfig(); - getDesktopToAutostartMap(); - listenAutostartFileEvents(); - startAutostartProgram(); -} - -static void sig_child(int signo) -{ - int stat; - int pid; - while((pid = waitpid(-1, &stat, WNOHANG)) > 0); -} - -void StartManager::waitForDeadChild() -{ - signal(SIGCHLD, sig_child); -} - -bool StartManager::addAutostart(const QString &desktop) -{ - setIsDBusCalled(true); - return setAutostart(desktop, true); -} - -bool StartManager::removeAutostart(const QString &desktop) -{ - setIsDBusCalled(true); - return setAutostart(desktop, false); -} - -QStringList StartManager::autostartList() -{ - if (m_autostartFiles.isEmpty()) { - m_autostartFiles = getAutostartList(); - } - - return m_autostartFiles; -} - -/**desktop为全路径或者相对路径都应该返回true - * 其他情况返回false - * @brief StartManager::isAutostart - * @param desktop - * @return - */ -bool StartManager::isAutostart(const QString &desktop) -{ - if (!desktop.endsWith(DESKTOPEXT)) { - qWarning() << "invalid desktop path"; - return false; - } - - QFileInfo file(desktop); - for (auto autostartDir : BaseDir::autoStartDirs()) { - std::string filePath = autostartDir + file.completeBaseName().toStdString(); - QDir dir(autostartDir.c_str()); - if (dir.exists(file.fileName())) { - DesktopInfo info(desktop.toStdString()); - if (info.isValidDesktop() && !info.getIsHidden()) { - return true; - } - } - } - - return false; -} - -bool StartManager::isMemSufficient() -{ - return SETTING->getMemCheckerEnabled() ? MemInfo::isSufficient(minMemAvail, maxSwapUsed) : true; -} - -bool StartManager::launchApp(const QString &desktopFile) -{ - return doLaunchAppWithOptions(desktopFile); -} - -bool StartManager::launchApp(QString desktopFile, uint32_t timestamp, QStringList files) -{ - return doLaunchAppWithOptions(desktopFile, timestamp, files, QVariantMap()); -} - -bool StartManager::launchAppAction(QString desktopFile, QString actionSection, uint32_t timestamp) -{ - DesktopInfo info(desktopFile.toStdString()); - if (!info.isValidDesktop()) { - qWarning() << "invalid arguments"; - return false; - } - - DesktopAction targetAction; - for (auto action : info.getActions()) { - if (!action.section.empty() && action.section.c_str() == actionSection) { - targetAction = action; - break; - } - } - - if (targetAction.section.empty()) { - qWarning() << "launchAppAction: targetAction section is empty"; - return false; - } - - if (targetAction.exec.empty()) { - qInfo() << "launchAppAction: targetAction exe is empty"; - return false; - } - - launch(&info, targetAction.exec.c_str(), timestamp, QStringList()); - - // mark app launched - dbusHandler->markLaunched(desktopFile); - return true; -} - -bool StartManager::launchAppWithOptions(QString desktopFile, uint32_t timestamp, QStringList files, QVariantMap options) -{ - return doLaunchAppWithOptions(desktopFile, timestamp, files, options); -} - -bool StartManager::runCommand(QString exe, QStringList args) -{ - return doRunCommandWithOptions(exe, args, QVariantMap()); -} - -bool StartManager::runCommandWithOptions(QString exe, QStringList args, QVariantMap options) -{ - return doRunCommandWithOptions(exe, args, options); -} - -void StartManager::onAutoStartupPathChange(const QString &path) -{ - const QStringList &autostartFilesList = getAutostartList(); - const QSet newAutostartFiles = QSet(autostartFilesList.begin(), autostartFilesList.end()); - const QSet oldAutostartFiles = QSet(m_autostartFiles.begin(), m_autostartFiles.end()); - - const QSet newFiles = newAutostartFiles - oldAutostartFiles; - const QSet deletedFiles = oldAutostartFiles - newAutostartFiles; - - QString desktopFullPath; - QDir autostartDir(BaseDir::userAutoStartDir().c_str()); - if (deletedFiles.size() && !isDBusCalled()) { - for (const QString &path : deletedFiles) { - QFileInfo info(path); - const QString &autostartDesktopPath = autostartDir.path() + QString("/") + info.fileName(); - - for (const std::string &appDir : BaseDir::appDirs()) { - QDir dir(appDir.c_str()); - dir.setFilter(QDir::Files); - dir.setNameFilters({ "*.desktop" }); - for (const auto &entry : dir.entryInfoList()) { - const QString &desktopPath = entry.absoluteFilePath(); - if (desktopPath.contains(info.completeBaseName())) { - desktopFullPath = desktopPath; - break; - } - } - - if (!desktopFullPath.isEmpty()) - break; - } - - m_autostartFiles.removeAll(autostartDesktopPath); - autostartDir.remove(info.fileName()); - - if (m_desktopDirToAutostartDirMap.keys().contains(desktopFullPath)) { - m_desktopDirToAutostartDirMap.remove(desktopFullPath); - Q_EMIT autostartChanged(autostartDeleted, desktopFullPath); - } - } - } else if (newFiles.size() && !isDBusCalled()) { - for (const QString &path : newFiles) { - QFileInfo info(path); - const QString &autostartDesktopPath = autostartDir.path() + QString("/") + info.fileName(); - m_autostartFiles.push_back(autostartDesktopPath); - const bool ret = QFile::copy(info.filePath(), autostartDesktopPath); - if (!ret) - qWarning() << "add to autostart list failed..."; - - /* 设置为自启动时,手动将Hidden字段写入到自启动目录的desktop文件中,并设置为false,只有这样, - * 安全中心才不会弹出自启动确认窗口, 这种操作是沿用V20阶段的约定规范,这块已经与安全中心研发对接过 */ - KeyFile kf; - kf.loadFile(autostartDesktopPath.toStdString()); - kf.setKey(MainSection, KeyXDeepinCreatedBy.toStdString(), AMServiceName.toStdString()); - kf.setKey(MainSection, KeyXDeepinAppID.toStdString(), info.completeBaseName().toStdString()); - kf.setBool(MainSection, KeyHidden, "false"); - kf.saveToFile(autostartDesktopPath.toStdString()); - - for (const std::string &appDir : BaseDir::appDirs()) { - QDir dir(appDir.c_str()); - dir.setFilter(QDir::Files); - dir.setNameFilters({ "*.desktop" }); - for (const auto &entry : dir.entryInfoList()) { - const QString &desktopPath = entry.absoluteFilePath(); - if (desktopPath.contains(info.completeBaseName())) { - desktopFullPath = desktopPath; - break; - } - } - - if (!desktopFullPath.isEmpty()) - break; - } - - if (!m_desktopDirToAutostartDirMap.keys().contains(desktopFullPath)) { - m_desktopDirToAutostartDirMap[desktopFullPath] = autostartDesktopPath; - Q_EMIT autostartChanged(autostartAdded, desktopFullPath); - } - } - } - - // 如果是用户通过启动器或者使用dbus接口调用方式添加或者删除自启动,则文件监控的不发送信号 - // 如果是用户直接删除自启动目录下的文件就发送信号 - m_autostartFiles = autostartFilesList; -} - -bool StartManager::setAutostart(const QString &desktop, const bool value) -{ - QFileInfo fileInfo(desktop); - if (!desktop.endsWith(".desktop") && !fileInfo.isAbsolute()) { - qWarning() << "invalid desktop path"; - return false; - } - - bool exist = false; - for (const std::string &appDir : BaseDir::appDirs()) { - QDir dir(appDir.c_str()); - dir.setFilter(QDir::Files); - dir.setNameFilters({ "*.desktop" }); - for (const auto &entry : dir.entryInfoList()) { - const QString &desktopPath = entry.absoluteFilePath(); - if (desktopPath == desktop) { - exist = true; - break; - } - } - - if (exist) - break; - } - - // 本地没有找到该应用就直接返回 - if (!exist) { - qWarning() << "no such file or directory"; - return false; - } - - QDir autostartDir(BaseDir::userAutoStartDir().c_str()); - const QString &appId = fileInfo.completeBaseName(); - - if (value && isAutostart(desktop)) { - qWarning() << "invalid path or item is already in the autostart list."; - return false; - } - - if (!value && !isAutostart(desktop)) { - qWarning() << "invalid path or item is not in the autostart list."; - return false; - } - - const QString &autostartDesktopPath = autostartDir.path() + QString("/") + fileInfo.fileName(); - if (value && !m_autostartFiles.contains(autostartDesktopPath)) { - m_autostartFiles.push_back(autostartDesktopPath); - - // 建立映射关系 - if (!m_desktopDirToAutostartDirMap.keys().contains(desktop)) - m_desktopDirToAutostartDirMap[desktop] = autostartDesktopPath; - - const bool ret = QFile::copy(fileInfo.filePath(), autostartDesktopPath); - if (!ret) - qWarning() << "add to autostart list failed."; - - /* 设置为自启动时,手动将Hidden字段写入到自启动目录的desktop文件中,并设置为false,只有这样, - * 安全中心才不会弹出自启动确认窗口, 这种操作是沿用V20阶段的约定规范,这块已经与安全中心研发对接过 */ - KeyFile kf; - kf.loadFile(autostartDesktopPath.toStdString()); - kf.setKey(MainSection, KeyXDeepinCreatedBy.toStdString(), AMServiceName.toStdString()); - kf.setKey(MainSection, KeyXDeepinAppID.toStdString(), appId.toStdString()); - kf.setBool(MainSection, KeyHidden, "false"); - kf.saveToFile(autostartDesktopPath.toStdString()); - } else if (!value && m_autostartFiles.contains(autostartDesktopPath)) { - // 删除映射关系 - if (m_desktopDirToAutostartDirMap.keys().contains(desktop)) - m_desktopDirToAutostartDirMap.remove(desktop); - - m_autostartFiles.removeAll(autostartDesktopPath); - autostartDir.remove(fileInfo.fileName()); - } else { - qWarning() << "invalid path or item is not in the autostart list."; - return false; - } - - Q_EMIT autostartChanged(value ? autostartAdded : autostartDeleted, desktop); - setIsDBusCalled(false); - return true; -} - -bool StartManager::doLaunchAppWithOptions(const QString &desktopFile) -{ - DesktopInfo info(desktopFile.toStdString()); - if (!info.isValidDesktop()) { - qWarning() << "invalid desktop path"; - return false; - } - - launch(&info, QString::fromStdString(info.getCommandLine()), 0, QStringList()); - - dbusHandler->markLaunched(desktopFile); - - return true; -} - -bool StartManager::doLaunchAppWithOptions(QString desktopFile, uint32_t timestamp, QStringList files, QVariantMap options) -{ - // launchApp - DesktopInfo info(desktopFile.toStdString()); - if (!info.isValidDesktop()) { - qWarning() << "invalid desktop path"; - return false; - } - - if (options.find("path") != options.end()) { - info.getDesktopFile()->setKey(MainSection, KeyPath, options["path"].toString().toStdString()); - } - - if (options.find("desktop-override-exec") != options.end()) { - info.setDesktopOverrideExec(options["desktop-override-exec"].toString().toStdString()); - } - - if (info.getCommandLine().empty()) { - qWarning() << "command line is empty"; - return false; - } - - launch(&info, QString::fromStdString(info.getCommandLine()), timestamp, files); - - // mark app launched - dbusHandler->markLaunched(desktopFile); - - return true; -} - -bool StartManager::launch(DesktopInfo *info, QString cmdLine, uint32_t timestamp, QStringList files) -{ - QProcess process; // NOTE(black_desk): this QProcess not used to start, we - // have to manually fork and exec to set - // GIO_LAUNCHED_DESKTOP_FILE_PID. - QStringList cmdPrefixesEnvs; - QProcessEnvironment envs = QProcessEnvironment::systemEnvironment(); - QString appId(QString::fromStdString(info->getId())); - - bool useProxy = shouldUseProxy(appId); - if (useProxy) { - envs.remove("auto_proxy"); - envs.remove("AUTO_PROXY"); - envs.remove("http_proxy"); - envs.remove("HTTP_PROXY"); - envs.remove("https_proxy"); - envs.remove("HTTPS_PROXY"); - envs.remove("ftp_proxy"); - envs.remove("FTP_PROXY"); - envs.remove("SOCKS_SERVER"); - envs.remove("no_proxy"); - envs.remove("NO_PROXY"); - } - - // FIXME: Don't using env to control the window scale factor, this function - // should via using graphisc server(Wayland Compositor/Xorg Xft) in deepin wine. - if (!appId.isEmpty() && !shouldDisableScaling(appId)) { - auto dbus = QDBusConnection::sessionBus(); - QDBusMessage reply = dbus.call(QDBusMessage::createMethodCall("org.deepin.dde.XSettings1", - "/org/deepin/dde/XSettings1", - "org.deepin.dde.XSettings1", - "GetScaleFactor"), QDBus::Block, 2); - - if (reply.type() == QDBusMessage::ReplyMessage) { - QDBusReply ret(reply); - double scale = ret.isValid() ? ret.value() : 1.0; - scale = scale > 0 ? scale : 1; - const QString scaleStr = QString::number(scale, 'f', -1); - envs.insert("DEEPIN_WINE_SCALE", scaleStr); - } - } - - QStringList exeArgs; - - auto stdCmdLine = cmdLine.toStdString(); - wordexp_t words; - auto ret = wordexp(stdCmdLine.c_str(), &words, 0); - if (ret != 0) { - qCritical() << "wordexp failed, error code:" << ret; - wordfree(&words); - return false; - } - - for (int i = 0; i < (int)words.we_wordc; i++) { - exeArgs << words.we_wordv[i]; - } - - wordfree(&words); - - handleRecognizeArgs(exeArgs, files); - - if (info->getTerminal()) { - exeArgs.insert(0, SETTING->getDefaultTerminalExecArg()); - exeArgs.insert(0, SETTING->getDefaultTerminalExec()); - } - - std::string workingDir = info->getDesktopFile()->getStr(MainSection, KeyPath); - if (workingDir.empty()) { - workingDir = BaseDir::homeDir(); - } - - QString exec = exeArgs[0]; - exeArgs.removeAt(0); - - qDebug() << "Launching app, desktop:" << QString::fromStdString(info->getFileName()) << "exec:" << exec - << "args:" << exeArgs << "useProxy:" << useProxy << "appid:" << appId << "envs:" << envs.toStringList(); - - process.setProgram(exec); - process.setArguments(exeArgs); - process.setWorkingDirectory(workingDir.c_str()); - - // NOTE(black_desk): This have to be done after load system environment. - // Set same env twice in qt make the first one gone. - envs.insert("GIO_LAUNCHED_DESKTOP_FILE", QString::fromStdString(info->getDesktopFile()->getFilePath())); - - qint64 pid = fork(); - if (pid == 0) { - envs.insert("GIO_LAUNCHED_DESKTOP_FILE_PID", QByteArray::number(getpid()).constData()); - auto argList = process.arguments(); - char const * args[argList.length() + 2]; - std::transform(argList.constBegin(), argList.constEnd(), args + 1, [](const QString& str){ - auto byte = new QByteArray; - *byte = str.toUtf8(); - auto tmp_buf = byte->data(); - return tmp_buf; - }); - auto arg0 = process.program().toLocal8Bit(); - args[0] = arg0.constData(); - args[process.arguments().length() + 1] = 0; - auto envStringList = envs.toStringList(); - char const * envs[envStringList.length() + 1]; - std::transform(envStringList.constBegin(), envStringList.constEnd(), envs, [](const QString& str){ - auto byte = new QByteArray; - *byte = str.toUtf8(); - auto tmp_buf = byte->data(); - return tmp_buf; - }); - envs[envStringList.length()] = 0; - execvpe(arg0.constData(), (char**)args, (char**)envs); - exit(-1); - } else { - if (useProxy) { - qDebug() << "Launch the process[" << pid << "] by app proxy."; - dbusHandler->addProxyProc(pid); - } - return true; - } - return false; -} - -bool StartManager::doRunCommandWithOptions(QString exe, QStringList args, QVariantMap options) -{ - if (options.find("dir") != options.end()) { - qDebug() << options["dir"].toString(); - return QProcess::startDetached(exe, args, options["dir"].toString()); - } - - return QProcess::startDetached(exe, args); -} - -void StartManager::waitCmd(DesktopInfo *info, QProcess *process, QString cmdName) -{ - -} - -bool StartManager::shouldUseProxy(QString appId) -{ - auto useProxyApps = SETTING->getUseProxyApps(); - if (!useProxyApps.contains(appId)) - return false; - - if (dbusHandler->getProxyMsg().isEmpty()) - return false; - - return true; -} - -bool StartManager::shouldDisableScaling(QString appId) -{ - auto disableScalingApps = SETTING->getDisableScalingApps(); - return disableScalingApps.contains(appId); -} - -void StartManager::loadSysMemLimitConfig() -{ - std::string configPath = BaseDir::userConfigDir() + "deepin/startdde/memchecker.json"; - QFile file(configPath.c_str()); - if (!file.exists()) - file.setFileName(sysMemLimitConfig); - - do { - if (!file.exists()) - break; - - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) - break; - - QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); - file.close(); - if (!doc.isObject()) - break; - - minMemAvail = uint64_t(doc.object()["min-mem-available"].toInt()); - maxSwapUsed = uint64_t(doc.object()["max-swap-used"].toInt()); - return; - } while (0); - - minMemAvail = defaultMinMemAvail; - maxSwapUsed = defaultMaxSwapUsed; -} - -void StartManager::listenAutostartFileEvents() -{ - m_autostartFileWatcher->addPath(BaseDir::userAutoStartDir().c_str()); - connect(m_autostartFileWatcher, &QFileSystemWatcher::directoryChanged, this, &StartManager::onAutoStartupPathChange, Qt::QueuedConnection); -} - -void StartManager::startAutostartProgram() -{ - for (const QString &desktopFile : autostartList()) { - DesktopInfo info(desktopFile.toStdString()); - if (!info.isValidDesktop()) - continue; - - launchApp(desktopFile); - } -} - -QStringList StartManager::getAutostartList() -{ - QStringList autostartList; - for (const std::string &autostartDir : BaseDir::autoStartDirs()) { - QDir dir(autostartDir.c_str()); - if (!dir.exists()) - continue; - - dir.setFilter(QDir::Files); - dir.setNameFilters({ "*.desktop" }); - for (const auto &entry : dir.entryInfoList()) { - if (autostartList.contains(entry.absoluteFilePath())) - continue; - - // 需要检查desktop文件中的Hidden,OnlyShowIn和NotShowIn字段,再决定是否需要自启动 - auto isNeedAutoStart = [ ](const std::string &_fileName){ - DesktopInfo info(_fileName); - if (!info.isValidDesktop()) - return false; - - if (info.getIsHidden()) - return false; - - return info.getShowIn(std::vector()); - }; - - if (isNeedAutoStart(entry.absoluteFilePath().toStdString())) - autostartList.push_back(entry.absoluteFilePath()); - } - } - - return autostartList; -} - -QMap StartManager::getDesktopToAutostartMap() -{ - // 获取已加入到自启动列表应用的desktop全路径 - QDir autostartDir(BaseDir::userAutoStartDir().c_str()); - autostartDir.setFilter(QDir::Files); - autostartDir.setNameFilters({ "*.desktop" }); - for (const auto &entry : autostartDir.entryInfoList()) { - const QFileInfo &fileInfo(entry.absoluteFilePath()); - for (const std::string &appDir : BaseDir::appDirs()) { - QDir dir(appDir.c_str()); - dir.setFilter(QDir::Files); - dir.setNameFilters({ "*.desktop" }); - for (const auto &entry : dir.entryInfoList()) { - const QString &desktopPath = entry.absoluteFilePath(); - if (desktopPath.contains(fileInfo.completeBaseName()) && - m_desktopDirToAutostartDirMap.find(desktopPath) == m_desktopDirToAutostartDirMap.end()) { - m_desktopDirToAutostartDirMap.insert(desktopPath, entry.absoluteFilePath()); - } - } - } - } - - return m_desktopDirToAutostartDirMap; -} - -void StartManager::setIsDBusCalled(const bool state) -{ - m_isDBusCalled = state; -} - -bool StartManager::isDBusCalled() const -{ - return m_isDBusCalled; -} - -/**遵循 freedesktop 规范,添加识别的字段处理 - * @brief StartManager::hangleRecognizeArgs - * @param exeArgs desktop文件中 exec 字段对应的内容 - * @param files 启动应用的路径列表 - */ -void StartManager::handleRecognizeArgs(QStringList &exeArgs, QStringList files) -{ - QStringList argList; - argList << "%f" << "%F" << "%u" << "%U" << "%i" << "%c" << "%k"; - - // https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#exec-variables - - // > If the application should not open any file the %f, %u, %F and %U field - // > codes must be removed from the command line and ignored. - - if (files.isEmpty()) { - for (const QString &arg : argList) { - exeArgs.removeAll(arg); - } - return; - } - - // 若 Recognized field codes 并非单独出现, 而是出现在引号中, 应该如何对其进行替换. - // 这一点在XDG spec中似乎并没有详细的说明. - - if (!exeArgs.filter("%f").isEmpty()) { - // > A single file name (including the path), even if multiple files are selected. - exeArgs.replaceInStrings("%f", files.at(0)); - } else if (!exeArgs.filter("%F").isEmpty()) { - exeArgs.removeOne("%F"); - for (const QString &file : files) { - QUrl url(file); - exeArgs << url.toLocalFile(); - } - } else if (!exeArgs.filter("%u").isEmpty()) { - exeArgs.replaceInStrings("%u", files.at(0)); - } else if (!exeArgs.filter("%U").isEmpty()) { - exeArgs.replaceInStrings("%U", files.join(" ")); - } else if (!exeArgs.filter("%i").isEmpty()) { - // TODO: 待出现这个类型的问题时再行适配,优先解决阻塞问题 - } else if (!exeArgs.filter("%c").isEmpty()) { - // TODO: 待出现这个类型的问题时再行适配,优先解决阻塞问题 - } else if (!exeArgs.filter("%k").isEmpty()) { - // TODO: 待出现这个类型的问题时再行适配,优先解决阻塞问题 - } -} diff --git a/src/modules/startmanager/startmanager.h b/src/modules/startmanager/startmanager.h deleted file mode 100644 index 9770a5d..0000000 --- a/src/modules/startmanager/startmanager.h +++ /dev/null @@ -1,71 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef STARTMANAGER_H -#define STARTMANAGER_H - -#include -#include - -class AppLaunchContext; -class StartManagerDBusHandler; -class DesktopInfo; -class QProcess; -class QFileSystemWatcher; -class ApplicationManager; - -class StartManager : public QObject -{ - Q_OBJECT -public: - explicit StartManager(QObject *parent = nullptr); - - bool addAutostart(const QString &desktop); - bool removeAutostart(const QString &desktop); - QStringList autostartList(); - bool isAutostart(const QString &desktop); - bool isMemSufficient(); - bool launchApp(const QString &desktopFile); - bool launchApp(QString desktopFile, uint32_t timestamp, QStringList files); - bool launchAppAction(QString desktopFile, QString actionSection, uint32_t timestamp); - bool launchAppWithOptions(QString desktopFile, uint32_t timestamp, QStringList files, QVariantMap options); - bool runCommand(QString exe, QStringList args); - bool runCommandWithOptions(QString exe, QStringList args, QVariantMap options); - -Q_SIGNALS: - void autostartChanged(const QString &status, const QString &fileName); - -public Q_SLOTS: - void onAutoStartupPathChange(const QString &dirPath); - -private: - void waitForDeadChild(); - bool setAutostart(const QString &fileName, const bool value); - bool doLaunchAppWithOptions(const QString &desktopFile); - bool doLaunchAppWithOptions(QString desktopFile, uint32_t timestamp, QStringList files, QVariantMap options); - bool launch(DesktopInfo *info, QString cmdLine, uint32_t timestamp, QStringList files); - bool doRunCommandWithOptions(QString exe, QStringList args, QVariantMap options); - void waitCmd(DesktopInfo *info, QProcess *process, QString cmdName); - bool shouldUseProxy(QString appId); - bool shouldDisableScaling(QString appId); - void loadSysMemLimitConfig(); - QStringList getDefaultTerminal(); - void listenAutostartFileEvents(); - void startAutostartProgram(); - QStringList getAutostartList(); - QMap getDesktopToAutostartMap(); - void setIsDBusCalled(const bool state); - bool isDBusCalled() const; - void handleRecognizeArgs(QStringList &exeArgs, QStringList files); - - uint64_t minMemAvail; - uint64_t maxSwapUsed; - StartManagerDBusHandler *dbusHandler; - QStringList m_autostartFiles; - QMap m_desktopDirToAutostartDirMap; // Desktop全路径和自启动目录 - QFileSystemWatcher *m_autostartFileWatcher; - bool m_isDBusCalled; -}; - -#endif // STARTMANAGER_H diff --git a/src/modules/startmanager/startmanagerdbushandler.cpp b/src/modules/startmanager/startmanagerdbushandler.cpp deleted file mode 100644 index fb99b79..0000000 --- a/src/modules/startmanager/startmanagerdbushandler.cpp +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "startmanagerdbushandler.h" - -#include -#include - -StartManagerDBusHandler::StartManagerDBusHandler(QObject *parent) - : QObject(parent) -{ - -} - -void StartManagerDBusHandler::markLaunched(QString desktopFile) -{ - QDBusInterface interface = QDBusInterface("org.deepin.dde.AlRecorder1", "/org/deepin/dde/AlRecorder1", "org.deepin.dde.AlRecorder1"); - interface.call("MarkLaunched", desktopFile); -} - -QString StartManagerDBusHandler::getProxyMsg() -{ - QString ret; - QDBusInterface interface = QDBusInterface("org.deepin.dde.NetworkProxy1", "/org/deepin/dde/NetworkProxy1/App", "org.deepin.dde.NetworkProxy1.App", QDBusConnection::systemBus()); - QDBusReply reply = interface.call("GetProxy"); - if (reply.isValid()) - ret = reply.value(); - - return ret; -} - -void StartManagerDBusHandler::addProxyProc(int32_t pid) -{ - QDBusInterface interface = QDBusInterface("org.deepin.dde.NetworkProxy1", "/org/deepin/dde/NetworkProxy1/App", "org.deepin.dde.NetworkProxy1.App", QDBusConnection::systemBus()); - interface.call("AddProc", pid); -} diff --git a/src/modules/startmanager/startmanagerdbushandler.h b/src/modules/startmanager/startmanagerdbushandler.h deleted file mode 100644 index 657484e..0000000 --- a/src/modules/startmanager/startmanagerdbushandler.h +++ /dev/null @@ -1,26 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef STARTMANAGERDBUSHANDLER_H -#define STARTMANAGERDBUSHANDLER_H - -#include - -class StartManagerDBusHandler : public QObject -{ - Q_OBJECT -public: - explicit StartManagerDBusHandler(QObject *parent = nullptr); - - void markLaunched(QString desktopFile); - - QString getProxyMsg(); - void addProxyProc(int32_t pid); - -Q_SIGNALS: - -public Q_SLOTS: -}; - -#endif // STARTMANAGERDBUSHANDLER_H diff --git a/src/modules/startmanager/startmanagersettings.cpp b/src/modules/startmanager/startmanagersettings.cpp deleted file mode 100644 index d082320..0000000 --- a/src/modules/startmanager/startmanagersettings.cpp +++ /dev/null @@ -1,92 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "startmanagersettings.h" -#include "settings.h" -#include "gsetting.h" - -#include - -#include -#include -#include - -DCORE_USE_NAMESPACE - -StartManagerSettings::StartManagerSettings(QObject *parent) - : QObject (parent) - , m_launchConfig(Settings::ConfigPtr(configLauncher)) - , m_startConfig(Settings::ConfigPtr(configStartdde)) - , m_xsettingsConfig(Settings::ConfigPtr(configXsettings)) -{ - -} - -QVector StartManagerSettings::getUseProxyApps() -{ - QVector ret; - if (!m_launchConfig) - return ret; - - QList apps = m_launchConfig->value(keyAppsUseProxy).toList(); - for (auto app : apps) { - ret.push_back(app.toString()); - } - - return ret; -} - -QVector StartManagerSettings::getDisableScalingApps() -{ - QVector ret; - if (!m_launchConfig) - return ret; - - QList apps = m_launchConfig->value(keyAppsDisableScaling).toList(); - for (auto app : apps) { - ret.push_back(app.toString()); - } - - return ret; -} - -bool StartManagerSettings::getMemCheckerEnabled() -{ - bool ret = false; - if (m_startConfig) { - ret = m_startConfig->value(keyMemCheckerEnabled).toBool(); - } - return ret; -} - -double StartManagerSettings::getScaleFactor() -{ - double ret = 0; - if (m_xsettingsConfig) { - m_xsettingsConfig->value(keyScaleFactor).toDouble(); - } - return ret; -} - -QString StartManagerSettings::getDefaultTerminalExec() -{ - QString ret; - GSetting settings("com.deepin.desktop.default-applications.terminal"); - auto exec = settings.getString("exec"); - if (!exec.empty()) { - ret = exec.c_str(); - } - return ret; -} - -QString StartManagerSettings::getDefaultTerminalExecArg() -{ - QString ret; - GSetting settings("com.deepin.desktop.default-applications.terminal"); - auto execArg = settings.getString("exec-arg"); - if (!execArg.empty()) { - ret = execArg.c_str(); - } - return ret; -} diff --git a/src/modules/startmanager/startmanagersettings.h b/src/modules/startmanager/startmanagersettings.h deleted file mode 100644 index 3a08cbe..0000000 --- a/src/modules/startmanager/startmanagersettings.h +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef STARTMANAGERSETTINGS_H -#define STARTMANAGERSETTINGS_H -#ifdef signals -#undef signals -#endif - -#include "common.h" -#include "gsetting.h" - -#include -#include - -namespace Dtk { -namespace Core { -class DConfig; -} -} - -using namespace Dtk::Core; - -class StartManagerSettings : public QObject -{ - Q_OBJECT -public: - static inline StartManagerSettings *instance() { - static StartManagerSettings instance; - return &instance; - } - - QVector getUseProxyApps(); - QVector getDisableScalingApps(); - - bool getMemCheckerEnabled(); - - double getScaleFactor(); - - QString getDefaultTerminalExec(); - QString getDefaultTerminalExecArg(); - -Q_SIGNALS: - -private: - StartManagerSettings(QObject *parent = nullptr); - StartManagerSettings(const StartManagerSettings &); - StartManagerSettings& operator= (const StartManagerSettings &); - - DConfig *m_launchConfig; - DConfig *m_startConfig; - DConfig *m_xsettingsConfig; -}; - -#endif // STARTMANAGERSETTINGS_H diff --git a/src/modules/tools/desktop_deconstruction.hpp b/src/modules/tools/desktop_deconstruction.hpp deleted file mode 100644 index a49cf33..0000000 --- a/src/modules/tools/desktop_deconstruction.hpp +++ /dev/null @@ -1,161 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef BB9B5BB3_BEAF_4D25_B4F6_55273B263973 -#define BB9B5BB3_BEAF_4D25_B4F6_55273B263973 - -#ifdef USE_QT - -#include -#include - -static QSettings DesktopDeconstruction(const QString &desktop) -{ - auto IniReadFunc = [](QIODevice &device, QSettings::SettingsMap &settingsMap) -> bool { - QTextStream stream(&device); - QString group; - while (!stream.atEnd()) { - QString line = stream.readLine(); - if (group.isEmpty()) { - if (line.front() == '[' && line.back() == ']') { - group = line.mid(1, line.size() - 2); - } - } - else { - if (line.isEmpty()) { - group.clear(); - } - else { - int index = line.indexOf("="); - if (index != -1) { - QString name = group + "/" + line.mid(0, index); - QVariant value = QVariant(line.mid(index + 1)); - settingsMap.insert(name, value); - } - } - } - } - return true; - }; - - return QSettings(desktop, QSettings::registerFormat("ini", IniReadFunc, nullptr)); -} - -#else - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class DesktopDeconstruction -{ - std::string m_path; - std::string m_group; - - struct Entry { - typedef std::string Key; - typedef std::any Value; - std::string name; - std::vector> pairs; - }; - - std::vector> _parse() - { - std::ifstream file(m_path); - if (!file) { - return {}; - } - - std::string line; - std::regex group_regex("\\[(.*?)\\]"); - std::vector> entrys; - std::shared_ptr currentEntry; - while (std::getline(file, line)) { - // 匹配 group,如果是,就进入判断 - if (std::regex_match(line, group_regex)) { - std::smatch result; - if (std::regex_search(line, result, group_regex)) { - currentEntry = std::make_shared(); - currentEntry.get()->name = result.str(); - entrys.push_back(currentEntry); - } - continue; - } - if (!currentEntry) { - continue; - } - - // 跳过 # 开头的注释 - if (!line.empty() && line[0] == '#') { - continue; - } - - const size_t index = line.find('='); - const std::string key = line.substr(0, index); - const std::any value = line.substr(index + 1, line.size()); - currentEntry.get()->pairs.push_back({key, value}); - } - file.close(); - - return entrys; - } - -public: - DesktopDeconstruction(const std::string &path) - : m_path(path) - { - } - ~DesktopDeconstruction() - { - } - - void beginGroup(const std::string group) - { - m_group = group; - } - - void endGroup() - { - m_group.clear(); - } - - std::vector listKeys() - { - std::vector> entrys{ _parse() }; - std::vector result; - for (const std::shared_ptr entry : entrys) { - for (const auto pair : entry.get()->pairs) { - result.push_back(pair.first); - } - } - return result; - } - - template - T value(const std::string key) - { - std::vector> entrys{ _parse() }; - for (const std::shared_ptr entry : entrys) { - if (entry.get()->name == "[" + m_group + "]") { - for (const auto pair : entry.get()->pairs) { - if (pair.first == key) { - return std::any_cast(pair.second); - } - } - } - } - return {}; - } -}; - -#endif - -#endif /* BB9B5BB3_BEAF_4D25_B4F6_55273B263973 */ diff --git a/src/modules/tools/query.h b/src/modules/tools/query.h deleted file mode 100644 index 7a56078..0000000 --- a/src/modules/tools/query.h +++ /dev/null @@ -1,15 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef QUERY_H -#define QUERY_H - -#include - -namespace Tools { - - -} - -#endif // QUERY_H diff --git a/src/modules/util/common.cpp b/src/modules/util/common.cpp deleted file mode 100644 index 9de07d2..0000000 --- a/src/modules/util/common.cpp +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "common.h" - -namespace linglong { -namespace util { - -std::string str_vec_join(const str_vec &vec, char sep) -{ - if (vec.empty()) { - return ""; - } - - std::string s; - for (auto iterator = vec.begin(); iterator != std::prev(vec.end()); ++iterator) { - s += *iterator + sep; - } - s += vec.back(); - return s; -} - -str_vec str_spilt(const std::string &s, const std::string &sep) -{ - str_vec vec; - size_t pos_begin = 0; - size_t pos_end = 0; - while ((pos_end = s.find(sep, pos_begin)) != std::string::npos) { - auto t = s.substr(pos_begin, pos_end - pos_begin); - if (!t.empty()) { - vec.push_back(t); - } - pos_begin = pos_end + sep.size(); - } - auto t = s.substr(pos_begin, s.size() - pos_begin); - if (!t.empty()) { - vec.push_back(t); - } - return vec; -} - -} // namespace util -} // namespace linglong \ No newline at end of file diff --git a/src/modules/util/common.h b/src/modules/util/common.h deleted file mode 100644 index bac1172..0000000 --- a/src/modules/util/common.h +++ /dev/null @@ -1,59 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef LINGLONG_BOX_SRC_UTIL_COMMON_H_ -#define LINGLONG_BOX_SRC_UTIL_COMMON_H_ - -#include -#include -#include - -#include -#include -#include - - -namespace linglong { -namespace util { - -typedef std::vector str_vec; - -str_vec str_spilt(const std::string &s, const std::string &sep); - -std::string str_vec_join(const str_vec &vec, char sep); - -inline std::string format(const std::string fmt, ...) -{ - int n = ((int)fmt.size()) * 2; - std::unique_ptr formatted; - va_list ap; - while (true) { - formatted.reset(new char[n]); - strcpy(&formatted[0], fmt.c_str()); - va_start(ap, fmt); - int final_n = vsnprintf(&formatted[0], n, fmt.c_str(), ap); - va_end(ap); - if (final_n < 0 || final_n >= n) - n += abs(final_n - n + 1); - else - break; - } - return std::string {formatted.get()}; -} - -} // namespace util -} // namespace linglong - -template -std::ostream &operator<<(std::ostream &out, const std::vector &v) -{ - if (!v.empty()) { - out << '['; - std::copy(v.begin(), v.end(), std::ostream_iterator(out, ", ")); - out << "\b\b]"; - } - return out; -} - -#endif /* LINGLONG_BOX_SRC_UTIL_COMMON_H_ */ diff --git a/src/modules/util/debug/debug.cpp b/src/modules/util/debug/debug.cpp deleted file mode 100644 index f0940fe..0000000 --- a/src/modules/util/debug/debug.cpp +++ /dev/null @@ -1,120 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include -#include -#include -#include -#include - -#include "../logger.h" -#include "debug.h" - -namespace linglong { - -#define DUMP_DBG(func, line) (linglong::util::Logger(linglong::util::Logger::Debug, func, line)) - -void DumpIDMap() -{ - logDbg() << "DumpIDMap Start -----------"; - std::ifstream uidMap("/proc/self/uid_map"); - for (std::string line; getline(uidMap, line);) { - logDbg() << "uid_map of pid:" << getpid() << line; - } - - std::ifstream gidMap("/proc/self/gid_map"); - for (std::string line; getline(gidMap, line);) { - logDbg() << "gid_map of pid:" << getpid() << line; - } - - auto setgroupsPath = util::format("/proc/self/setgroups"); - std::ifstream setgroupsFileRead(setgroupsPath); - std::string line; - std::getline(setgroupsFileRead, line); - logDbg() << "setgroups of pid:" << getpid() << line; - logDbg() << "DumpIDMap end -----------"; -} - -void DumpUidGidGroup() -{ - logDbg() << "DumpUidGidGroup Start -----------"; - // __uid_t uid = getuid(); // you can change this to be the uid that you want - // - // struct passwd *pw = getpwuid(uid); - // if (pw == NULL) { - // perror("getpwuid error: "); - // } - // - // int ngroups = 0; - // - // // this call is just to get the correct ngroups - // getgrouplist(pw->pw_name, pw->pw_gid, NULL, &ngroups); - // __gid_t groups[ngroups]; - // - // // here we actually get the groups - // getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups); - // - // // example to print the groups name - // for (int i = 0; i < ngroups; i++) { - // struct group *gr = getgrgid(groups[i]); - // if (gr == NULL) { - // perror("getgrgid error: "); - // } - // printf("%s\n", gr->gr_name); - // } - - logDbg() << "getuid" << getuid() << "geteuid" << geteuid(); - logDbg() << "getgid" << getgid() << "getegid" << getegid(); - const int groupSize = getgroups(0, NULL); - __gid_t list[groupSize + 1]; - getgroups(groupSize, list); - - std::string groupListStr; - for (int i = 0; i < groupSize; ++i) { - groupListStr += util::format("%d ", list[i]); - } - logDbg() << "getgroups size " << groupSize << ", list:" << groupListStr; - logDbg() << "DumpUidGidGroup end -----------"; -} - -void DumpFilesystem(const std::string &path, const char *func, int line) -{ - if (nullptr == func) { - func = const_cast(__FUNCTION__); - } - DUMP_DBG(func, line) << "DumpFilesystem begin -----------" << path; - DIR *dir; - if ((dir = opendir(path.c_str())) != NULL) { - struct dirent *ent; - /* print all the files and directories within directory */ - while ((ent = readdir(dir)) != NULL) { - DUMP_DBG(func, line) << path + "/" + ent->d_name; - } - closedir(dir); - } else { - /* could not open directory */ - logErr() << linglong::util::errnoString() << errno; - return; - } - DUMP_DBG(func, line) << "DumpFilesystem end -----------" << path; -} - -void DumpFileInfo(const std::string &path) -{ - DumpFileInfo1(path, __FUNCTION__, __LINE__); -} - -void DumpFileInfo1(const std::string &path, const char *func, int line) -{ - struct stat st { - }; - auto ret = lstat(path.c_str(), &st); - if (0 != ret) { - DUMP_DBG(func, line) << path << util::RetErrString(ret); - } else { - DUMP_DBG(func, line) << path << st.st_uid << st.st_gid << ((st.st_mode & S_IFMT) == S_IFDIR); - } -} - -} // namespace linglong diff --git a/src/modules/util/debug/debug.h b/src/modules/util/debug/debug.h deleted file mode 100644 index 08a61c9..0000000 --- a/src/modules/util/debug/debug.h +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef LINGLONG_BOX_SRC_UTIL_DEBUG_DEBUG_H_ -#define LINGLONG_BOX_SRC_UTIL_DEBUG_DEBUG_H_ - -#include - -namespace linglong { - -#define DUMP_FILESYSTEM(path) DumpFilesystem(path, __FUNCTION__, __LINE__) - -#define DUMP_FILE_INFO(path) DumpFileInfo1(path, __FUNCTION__, __LINE__) - -void DumpIDMap(); - -void DumpUidGidGroup(); - -void DumpFilesystem(const std::string &path, const char *func = nullptr, int line = -1); - -void DumpFileInfo(const std::string &path); - -void DumpFileInfo1(const std::string &path, const char *func = nullptr, int line = -1); - -} // namespace linglong - -#endif /* LINGLONG_BOX_SRC_UTIL_DEBUG_DEBUG_H_ */ diff --git a/src/modules/util/filesystem.cpp b/src/modules/util/filesystem.cpp deleted file mode 100644 index 9cd92cc..0000000 --- a/src/modules/util/filesystem.cpp +++ /dev/null @@ -1,176 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include -#include -#include -#include - -#include "filesystem.h" -#include "logger.h" - -namespace linglong { -namespace util { -namespace fs { - -using namespace std; - -bool create_directory(const path &p, __mode_t mode) -{ - return mkdir(p.string().c_str(), mode); -} - -bool create_directories(const path &p, __mode_t mode) -{ - std::string fullPath; - for (const auto &e : p.components()) { - fullPath += "/" + e; - if (is_dir(fullPath)) { - continue; - } - - auto ret = mkdir(fullPath.c_str(), mode); - if (0 != ret) { - logErr() << util::RetErrString(ret) << fullPath << mode; - return false; - } - } - return true; -} - -bool is_dir(const std::string &s) -{ - struct stat st { - }; - - if (0 != lstat(s.c_str(), &st)) { - return false; - } - - switch (st.st_mode & S_IFMT) { - case S_IFDIR: - return true; - default: - return false; - } -} - -bool exists(const std::string &s) -{ - struct stat st { - }; - - if (0 != lstat(s.c_str(), &st)) { - return false; - } - return true; -} - -path read_symlink(const path &p) -{ - char buf[PATH_MAX]; - if (readlink(p.string().c_str(), buf, sizeof(buf)) < 0) { - return p; - } else { - return path(string(buf)); - } -} - -file_status status(const path &p, std::error_code &ec) -{ - file_type ft; - perms perm = no_perms; - - struct stat st { - }; - - if (0 != lstat(p.string().c_str(), &st)) { - if (errno == ENOENT) { - ft = file_not_found; - } else { - ft = status_error; - } - return file_status(ft, perm); - } - - // FIXME: perms - // https://www.boost.org/doc/libs/1_75_0/libs/filesystem/doc/reference.html#file_status - // int st_perm = st.st_mode & 0xFFFF; - - // switch (st_perm) { - // case S_IRUSR: - // perm = owner_read; - // break; - // case S_IWUSR: - // case S_IXUSR: - // case S_IRWXU: - // case S_IRGRP: - // } - - switch (st.st_mode & S_IFMT) { - case S_IFREG: - ft = regular_file; - break; - case S_IFDIR: - ft = directory_file; - break; - case S_IFLNK: - ft = symlink_file; - break; - case S_IFBLK: - ft = block_file; - break; - case S_IFCHR: - ft = character_file; - break; - case S_IFIFO: - ft = fifo_file; - case S_IFSOCK: - break; - default: - ft = type_unknown; - break; - } - - return file_status(ft, perm); -} - -file_status::file_status() noexcept -{ -} - -file_status::file_status(file_type ft, perms perms) noexcept - : ft(ft) - , p(perms) -{ -} - -file_status::file_status(const file_status &fs) noexcept -{ - ft = fs.ft; - p = fs.p; -} - -file_status &file_status::operator=(const file_status &fs) noexcept -{ - ft = fs.ft; - p = fs.p; - return *this; -} - -file_status::~file_status() noexcept = default; - -file_type file_status::type() const noexcept -{ - return ft; -} - -perms file_status::permissions() const noexcept -{ - return p; -} - -} // namespace fs -} // namespace util -} // namespace linglong \ No newline at end of file diff --git a/src/modules/util/filesystem.h b/src/modules/util/filesystem.h deleted file mode 100644 index 7c87aeb..0000000 --- a/src/modules/util/filesystem.h +++ /dev/null @@ -1,145 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef LINGLONG_BOX_SRC_UTIL_FILESYSTEM_H_ -#define LINGLONG_BOX_SRC_UTIL_FILESYSTEM_H_ - -#include -#include -#include - -#include "common.h" - -namespace linglong { -namespace util { -namespace fs { - -class path : public std::basic_string -{ -public: - explicit path(const std::string &s) - : p(util::str_spilt(s, "/")) - { - } - - path &operator=(const std::string &s) - { - p = util::str_spilt(s, "/"); - return *this; - } - - path &operator=(const path &p1) = default; - - bool operator==(const path &s) const { return this->p == s.p; } - - bool operator!=(const path &s) const { return this->p != s.p; } - - path operator/(const path &p1) const - { - auto np = *this; - std::copy(p1.p.begin(), p1.p.end(), back_inserter(np.p)); - return np; - } - - path operator/(const std::string &str) const { return operator/(path(str)); } - - path parent_path() const - { - path pn(*this); - pn.p.pop_back(); - return pn; - } - - std::string string() const { return "/" + str_vec_join(p, '/'); } - - str_vec components() const { return p; } - -private: - friend std::ostream &operator<<(std::ostream &cout, path obj); - std::vector p; -}; - -inline std::ostream &operator<<(std::ostream &cout, path obj) -{ - for (auto const &s : obj.p) { - cout << "/" << s; - } - return cout; -} - -bool create_directories(const path &p, __mode_t mode); - -enum file_type { - status_error, - file_not_found, - regular_file, - directory_file, - symlink_file, - block_file, - character_file, - fifo_file, - socket_file, - reparse_file, - type_unknown -}; - -enum perms { - no_perms, - owner_read, - owner_write, - owner_exe, - owner_all, - group_read, - group_write, - group_exe, - group_all, - others_read, - others_write, - others_exe, - others_all, - all_all, - set_uid_on_exe, - set_gid_on_exe, - sticky_bit, - perms_mask, - perms_not_known, - add_perms, - remove_perms, - symlink_perms -}; - -class file_status -{ -public: - // constructors - file_status() noexcept; - explicit file_status(file_type ft, perms p = perms_not_known) noexcept; - - // compiler generated - file_status(const file_status &) noexcept; - file_status &operator=(const file_status &) noexcept; - ~file_status() noexcept; - - // observers - file_type type() const noexcept; - perms permissions() const noexcept; - -private: - file_type ft; - perms p; -}; - -bool is_dir(const std::string &s); - -bool exists(const std::string &s); - -file_status status(const path &p, std::error_code &ec); - -path read_symlink(const path &p); - -} // namespace fs -} // namespace util -} // namespace linglong - -#endif /* LINGLONG_BOX_SRC_UTIL_FILESYSTEM_H_ */ diff --git a/src/modules/util/json.h b/src/modules/util/json.h deleted file mode 100644 index 3ffbcd9..0000000 --- a/src/modules/util/json.h +++ /dev/null @@ -1,62 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef LINGLONG_BOX_SRC_UTIL_JSON_H_ -#define LINGLONG_BOX_SRC_UTIL_JSON_H_ - -#define JSON_USE_IMPLICIT_CONVERSIONS 0 - -#include - -#define tl std - -// namespace nlohmann { - -// template -// inline void from_json(const J &j, tl::optional &v) -// { -// if (j.is_null()) { -// v = tl::nullopt; -// } else { -// v = j.template get(); -// } -// } - -// template -// inline void to_json(J &j, const tl::optional &o) -// { -// if (o.has_value()) { -// j = o.value(); -// } -// } - -// } // namespace nlohmann - -// namespace linglong { - -// template -// tl::optional optional(const QJsonObject &j, const char *key) -// { -// tl::optional o; -// auto iter = j.template find(key); -// if (iter != j.end()) { -// o = iter->template get>(); -// } -// return o; -// } - -// template -// tl::optional optional(const nlohmann::json &j, const char *key) -// { -// tl::optional o; -// auto iter = j.template find(key); -// if (iter != j.end()) { -// o = iter->template get>(); -// } -// return o; -// } - -// } // namespace linglong - -#endif /* LINGLONG_BOX_SRC_UTIL_JSON_H_ */ diff --git a/src/modules/util/logger.cpp b/src/modules/util/logger.cpp deleted file mode 100644 index 34e4ede..0000000 --- a/src/modules/util/logger.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "logger.h" - -namespace linglong { -namespace util { - -std::string errnoString() -{ - return util::format("errno(%d): %s", errno, strerror(errno)); -} - -std::string RetErrString(int ret) -{ - return util::format("ret(%d),errno(%d): %s", ret, errno, strerror(errno)); -} - -static Logger::Level getLogLevelFromStr(std::string str) -{ - if (str == "Debug") { - return Logger::Debug; - } else if (str == "Info") { - return Logger::Info; - } else if (str == "Warning") { - return Logger::Warring; - } else if (str == "Error") { - return Logger::Error; - } else if (str == "Fatal") { - return Logger::Fatal; - } else { - return Logger::Info; - } -} - -static Logger::Level initLogLevel() -{ - auto env = getenv("LINGLONG_LOG_LEVEL"); - return getLogLevelFromStr(env ? env : ""); -} - -Logger::Level Logger::LOGLEVEL = initLogLevel(); - -} // namespace util -} // namespace linglong diff --git a/src/modules/util/logger.h b/src/modules/util/logger.h deleted file mode 100644 index f6a6587..0000000 --- a/src/modules/util/logger.h +++ /dev/null @@ -1,101 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef LINGLONG_BOX_SRC_UTIL_LOGGER_H_ -#define LINGLONG_BOX_SRC_UTIL_LOGGER_H_ - -#include "util.h" - -#include - -#include -#include -#include -#include -#include - -namespace linglong { -namespace util { -std::string errnoString(); -std::string RetErrString(int); - -class Logger -{ -public: - enum Level { - Debug, - Info, - Warring, - Error, - Fatal, - }; - - explicit Logger(Level l, const char *fn, int line) - : level(l) - , function(fn) - , line(line) {}; - - ~Logger() - { - std::string prefix; - if (level < LOGLEVEL) { - return; - } - switch (level) { - case Debug: - prefix = "[DBG |"; - std::cout << prefix << getpid() << " | " << function << ":" << line << " ] " << ss.str() << std::endl; - break; - case Info: - prefix = "[IFO |"; - std::cout << "\033[1;96m"; - std::cout << prefix << getpid() << " | " << function << ":" << line << " ] " << ss.str(); - std::cout << "\033[0m" << std::endl; - break; - case Warring: - prefix = "[WAN |"; - std::cout << "\033[1;93m"; - std::cout << prefix << getpid() << " | " << function << ":" << line << " ] " << ss.str(); - std::cout << "\033[0m" << std::endl; - break; - case Error: - prefix = "[ERR |"; - std::cout << "\033[1;31m"; - std::cout << prefix << getpid() << " | " << function << ":" << line << " ] " << ss.str(); - std::cout << "\033[0m" << std::endl; - break; - case Fatal: - prefix = "[FAL |"; - std::cout << "\033[1;91m"; - std::cout << prefix << getpid() << " | " << function << ":" << line << " ] " << ss.str(); - std::cout << "\033[0m" << std::endl; - exit(-1); - break; - } - } - - template - Logger &operator<<(const T &x) - { - ss << x << " "; - return *this; - } - -private: - static Level LOGLEVEL; - Level level = Debug; - const char *function; - int line; - std::ostringstream ss; -}; -} // namespace util -} // namespace linglong - -#define logDbg() (linglong::util::Logger(linglong::util::Logger::Debug, __FUNCTION__, __LINE__)) -#define logWan() (linglong::util::Logger(linglong::util::Logger::Warring, __FUNCTION__, __LINE__)) -#define logInf() (linglong::util::Logger(linglong::util::Logger::Info, __FUNCTION__, __LINE__)) -#define logErr() (linglong::util::Logger(linglong::util::Logger::Error, __FUNCTION__, __LINE__)) -#define logFal() (linglong::util::Logger(linglong::util::Logger::Fatal, __FUNCTION__, __LINE__)) - -#endif /* LINGLONG_BOX_SRC_UTIL_LOGGER_H_ */ diff --git a/src/modules/util/macro.h b/src/modules/util/macro.h deleted file mode 100644 index df86cd9..0000000 --- a/src/modules/util/macro.h +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef LINGLONG_BOX_SRC_UTIL_MACRO_H_ -#define LINGLONG_BOX_SRC_UTIL_MACRO_H_ - -#define LINGLONG 118 - -#define LL_VAL(str) #str -#define LL_TOSTRING(str) LL_VAL(str) - -#endif /* LINGLONG_BOX_SRC_UTIL_MACRO_H_ */ diff --git a/src/modules/util/oci_runtime.h b/src/modules/util/oci_runtime.h deleted file mode 100644 index e13428f..0000000 --- a/src/modules/util/oci_runtime.h +++ /dev/null @@ -1,1052 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef LINGLONG_BOX_SRC_UTIL_OCI_RUNTIME_H_ -#define LINGLONG_BOX_SRC_UTIL_OCI_RUNTIME_H_ - -#include - -#include -#include -#include -#include - -#include -#include -#include - -#include "util.h" - -namespace linglong { - -#undef linux - -struct Root { - QString path; - // 删除 std::optional 和 宏定义 - bool readonly; -}; - -inline void fromJson(const QByteArray &array, Root &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson root failed"; - return; - } - - QJsonObject obj = doc.object(); - // readonly 可以不存在 - if (!obj.contains("path")) { - return; - } - - o.path = obj.value("path").toString(); - if (obj.contains("readonly")) { - o.readonly = obj.value("readonly").toBool(); - } -} - -inline void toJson(QByteArray &array, const Root &o) -{ - QJsonObject obj { - {"path", o.path}, - {"readonly", o.readonly} - }; - - array = QJsonDocument(obj).toJson(); -} - -struct Process { - QList args; - QList env; - QString cwd; -}; - -inline void fromJson(const QByteArray &array, Process &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson process failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("args") || !obj.contains("env") || !obj.contains("cwd")) { - std::cout << "process json invalid format" << std::endl; - return; - } - - for (auto arg : obj.value("args").toArray()) { - o.args.append(arg.toString()); - } - for (auto env : obj.value("env").toArray()) { - o.env.append(env.toString()); - } - o.cwd = obj.value("cwd").toString(); -} - - -inline void toJson(QByteArray &array, const Process &o) -{ - QJsonArray argsArray; - for (auto arg : o.args) { - argsArray.append(arg); - } - QJsonArray envsArray; - for (auto env : o.env) { - envsArray.append(env); - } - - QJsonObject obj = { - {"args", argsArray}, - {"env", envsArray}, - {"cwd", o.cwd} - }; - - array = QJsonDocument(obj).toJson(); -} - -struct Mount { - enum Type { - Unknown, - Bind, - Proc, - Sysfs, - Devpts, - Mqueue, - Tmpfs, - Cgroup, - Cgroup2, - }; - QString destination; - QString type; - QString source; - QList data; - - Type fsType; - uint32_t flags = 0u; -}; - -inline void fromJson(const QByteArray &array, Mount &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson mount failed"; - return; - } - - QJsonObject obj = doc.object(); - static QMap fsTypes = { - {"bind", Mount::Bind}, {"proc", Mount::Proc}, {"devpts", Mount::Devpts}, {"mqueue", Mount::Mqueue}, - {"tmpfs", Mount::Tmpfs}, {"sysfs", Mount::Sysfs}, {"cgroup", Mount::Cgroup}, {"cgroup2", Mount::Cgroup2}, - }; - - struct mountFlag { - bool clear; - uint32_t flag; - }; - - static QMap optionFlags = { - {"acl", {false, MS_POSIXACL}}, - {"async", {true, MS_SYNCHRONOUS}}, - {"atime", {true, MS_NOATIME}}, - {"bind", {false, MS_BIND}}, - {"defaults", {false, 0}}, - {"dev", {true, MS_NODEV}}, - {"diratime", {true, MS_NODIRATIME}}, - {"dirsync", {false, MS_DIRSYNC}}, - {"exec", {true, MS_NOEXEC}}, - {"iversion", {false, MS_I_VERSION}}, - {"lazytime", {false, MS_LAZYTIME}}, - {"loud", {true, MS_SILENT}}, - {"mand", {false, MS_MANDLOCK}}, - {"noacl", {true, MS_POSIXACL}}, - {"noatime", {false, MS_NOATIME}}, - {"nodev", {false, MS_NODEV}}, - {"nodiratime", {false, MS_NODIRATIME}}, - {"noexec", {false, MS_NOEXEC}}, - {"noiversion", {true, MS_I_VERSION}}, - {"nolazytime", {true, MS_LAZYTIME}}, - {"nomand", {true, MS_MANDLOCK}}, - {"norelatime", {true, MS_RELATIME}}, - {"nostrictatime", {true, MS_STRICTATIME}}, - {"nosuid", {false, MS_NOSUID}}, - // {"nosymfollow",{false, MS_NOSYMFOLLOW}}, // since kernel 5.10 - {"rbind", {false, MS_BIND | MS_REC}}, - {"relatime", {false, MS_RELATIME}}, - {"remount", {false, MS_REMOUNT}}, - {"ro", {false, MS_RDONLY}}, - {"rw", {true, MS_RDONLY}}, - {"silent", {false, MS_SILENT}}, - {"strictatime", {false, MS_STRICTATIME}}, - {"suid", {true, MS_NOSUID}}, - {"sync", {false, MS_SYNCHRONOUS}}, - // {"symfollow",{true, MS_NOSYMFOLLOW}}, // since kernel 5.10 - }; - - if (!obj.contains("destination") || !obj.contains("type") || !obj.contains("source") \ - || !obj.contains("options")) { - std::cout << "mount json invalid format" << std::endl; - return; - } - - o.destination = obj.value("destination").toString(); - o.type = obj.value("type").toString(); - o.fsType = fsTypes.find(o.type).value(); - if (o.fsType == Mount::Bind) { - o.flags = MS_BIND; - } - o.source = obj.value("source").toString(); - o.data = {}; - - // Parse options to data and flags. - // FIXME: support "propagation flags" and "recursive mount attrs" - // https://github.com/opencontainers/runc/blob/c83abc503de7e8b3017276e92e7510064eee02a8/libcontainer/specconv/spec_linux.go#L958 - auto options = obj.value("options").toArray().toVariantList(); - for (auto const &opt : options) { - auto it = optionFlags.find(opt); - if (it != optionFlags.end()) { - if (it.value().clear) { - o.flags &= ~it.value().flag; - } else - o.flags |= it.value().flag; - } else { - o.data.push_back(opt.toString()); - } - } -} - -inline void toJson(QByteArray &array, const Mount &o) -{ - QJsonArray dataArray; - for (auto const &data : o.data) { - dataArray.append(data); - } - - QJsonObject obj = { - {"destination", o.destination}, - {"source", o.source}, - {"type", o.type}, - {"options", dataArray},// FIXME: this data is not original options, some of them have been prased to flags. - }; - - array = QJsonDocument(obj).toJson(); -} - -struct Namespace { - int type; -}; - -static std::map namespaceType = { - {"pid", CLONE_NEWPID}, {"uts", CLONE_NEWUTS}, {"mount", CLONE_NEWNS}, {"cgroup", CLONE_NEWCGROUP}, - {"network", CLONE_NEWNET}, {"ipc", CLONE_NEWIPC}, {"user", CLONE_NEWUSER}, -}; - -inline void fromJson(const QByteArray &array, Namespace &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson namespace failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("type")) { - std::cout << "namespace json invalid format" << std::endl; - return; - } - - o.type = namespaceType.find(obj.value("type").toString().toStdString())->second; -} - -inline void toJson(QByteArray &array, const Namespace &o) -{ - auto matchPair = std::find_if(std::begin(namespaceType), std::end(namespaceType), - [&](const std::pair &pair) { return pair.second == o.type; }); - - QJsonObject obj = { - {"type", matchPair->second}, - }; - - array = QJsonDocument(obj).toJson(); -} - -struct IDMap { - uint64_t containerID = 0u; - uint64_t hostID = 0u; - uint64_t size = 0u; -}; - -inline void fromJson(const QByteArray &array, IDMap &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson idmap failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("hostID") || !obj.contains("containerID") || !obj.contains("size")) { - std::cout << "idmap json invalid format" << std::endl; - return; - } - - o.hostID = obj.value("hostID").toVariant().ULongLong; - o.containerID = obj.value("containerID").toVariant().ULongLong; - o.size = obj.value("size").toVariant().ULongLong; -} - -inline void toJson(QByteArray &array, const IDMap &o) -{ - QJsonObject obj = { - {"hostID", QString::number(o.hostID, 10)}, - {"containerID", QString::number(o.containerID, 10)}, - {"size", QString::number(o.size, 10)}, - }; - - array = QJsonDocument(obj).toJson(); -} - -typedef QString SeccompAction; -typedef QString SeccompArch; - -struct SyscallArg { - u_int index; // require - u_int64_t value; // require - u_int64_t valueTwo; // optional - QString op; // require -}; - -inline void fromJson(const QByteArray &array, SyscallArg &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson SyscallArg failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("index") || !obj.contains("value") \ - || !obj.contains("valueTwo") || !obj.contains("op")) { - qWarning() << "syscallarg json invalid format"; - return; - } - - o.index = obj.value("index").toVariant().UInt; - o.value = obj.value("value").toVariant().ULongLong; - o.valueTwo = obj.value("valueTwo").toVariant().ULongLong; - o.op = obj.value("op").toString(); -} - -inline void toJson(QByteArray &array, const SyscallArg &o) -{ - QJsonObject obj = { - {"index", QString::number(o.index, 10)}, - {"value", QString::number(o.value, 10)}, - {"valueTwo", QString::number(o.valueTwo, 10)}, - {"op", o.op}, - }; - - array = QJsonDocument(obj).toJson(); -} - -struct Syscall { - QList names; - SeccompAction action; - QList args; -}; - -inline void fromJson(const QByteArray &array, Syscall &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson Syscall failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("names") || !obj.contains("action") || !obj.contains("args")) { - std::cout << "syscall json invalid format" << std::endl; - return; - } - - o.action = obj.value("action").toString(); - for (auto const &name : obj.value("names").toArray()) { - o.names.append(name.toString()); - } - - QJsonValue argsValue = obj.take("args"); - SyscallArg tmpArgs; - for (const auto &arg : argsValue.toArray()) { - fromJson(QJsonDocument(arg.toObject()).toJson(), tmpArgs); - o.args.append(tmpArgs); - } -} - -inline void toJson(QByteArray &array, const Syscall &o) -{ - QByteArray argsArray; - QJsonArray argsJsonArray; - for (const auto &arg : o.args) { - toJson(argsArray, arg); - argsJsonArray.append(QJsonDocument::fromJson(argsArray).array()); - } - - QByteArray namesArray; - QJsonArray namesJsonArray; - for (const auto &name : o.names) { - namesJsonArray.append(name); - } - - QJsonObject obj = { - { "names", namesJsonArray }, - { "action", o.action }, - { "args", argsJsonArray }, - }; - - array = QJsonDocument(obj).toJson(); -} - -struct Seccomp { - SeccompAction defaultAction = "INVALID_ACTION"; - QList architectures; - QList syscalls; -}; - -inline void fromJson(const QByteArray &array, Seccomp &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson Seccomp failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("defaultAction") || !obj.contains("architectures") \ - || !obj.contains("syscalls")) { - qWarning() << "seccomp json invalid format"; - return; - } - - o.defaultAction = obj.value("defaultAction").toString(); - for (auto const &arch : obj.value("architectures").toArray()) { - o.architectures.append(arch.toString()); - } - - Syscall syscallsArray; - for (auto const &syscall : obj.value("syscalls").toArray()) { - fromJson(QJsonDocument(syscall.toObject()).toJson(), syscallsArray); - o.syscalls.append(syscallsArray); - } -} - -inline void toJson(QByteArray &array, const Seccomp &o) -{ - QJsonArray syscallsJsonArray; - QByteArray syscallsByteArray; - for (auto const &syscall : o.syscalls) { - toJson(syscallsByteArray, syscall); - syscallsJsonArray.append(QJsonDocument::fromJson(syscallsByteArray).array()); - } - - QJsonArray archArray; - for (auto const &arch : o.architectures) { - archArray.append(arch); - } - - QJsonObject obj = { - { "defaultAction", o.defaultAction }, - { "architectures", archArray }, - { "syscalls", syscallsJsonArray }, - }; - - array = QJsonDocument(obj).toJson(); -} - -// https://github.com/containers/crun/blob/main/crun.1.md#memory-controller -struct ResourceMemory { - int64_t limit = -1; - int64_t reservation = -1; - int64_t swap = -1; -}; - -inline void fromJson(const QByteArray &array, ResourceMemory &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson ResourceMemory failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("limit") || !obj.contains("reservation") || !obj.contains("swap")) { - qWarning() << "resourceMemory json invalid format"; - return; - } - - o.limit = obj.value("limit").toVariant().toLongLong(); - o.reservation = obj.value("reservation").toVariant().toLongLong(); - o.swap = obj.value("swap").toVariant().toLongLong(); -} - -inline void toJson(QByteArray &array, const ResourceMemory &o) -{ - QJsonObject obj = { - {"limit", static_cast(o.limit)}, - {"reservation", static_cast(o.reservation)}, - {"swap", static_cast(o.swap)}, - }; - - array = QJsonDocument(obj).toJson(); -} - -// https://github.com/containers/crun/blob/main/crun.1.md#cpu-controller -// support v1 and v2 with conversion -struct ResourceCPU { - u_int64_t shares = 1024; - int64_t quota = 100000; - u_int64_t period = 100000; - // int64_t realtimeRuntime; - // int64_t realtimePeriod; - // std::string cpus; - // std::string mems; -}; - -inline void fromJson(const QByteArray &array, ResourceCPU &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson ResourceCPU failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("shares") || !obj.contains("quota") || !obj.contains("period")) { - qWarning() << "resourcecpu json invalid format"; - return; - } - - o.shares = obj.value("shares").toVariant().toULongLong(); - o.quota = obj.value("quota").toVariant().toLongLong(); - o.period = obj.value("period").toVariant().toULongLong(); -} - -inline void toJson(QByteArray &array, const ResourceCPU &o) -{ - QJsonObject obj = { - {"shares", QString::number(o.shares, 10)}, - {"quota", static_cast(o.quota)}, - {"period", QString::number(o.period, 10)}, - }; - - array = QJsonDocument(obj).toJson(); -} - -struct Resources { - ResourceMemory memory; - ResourceCPU cpu; -}; - -inline void fromJson(const QByteArray &array, Resources &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson Resources failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("cpu") || !obj.contains("memory")) { - qWarning() << "resources json invalid format"; - return; - } - - fromJson(QJsonDocument(obj.value("cpu").toObject()).toJson(), o.cpu); - fromJson(QJsonDocument(obj.value("memory").toObject()).toJson(), o.cpu); -} - -inline void toJson(QByteArray &array, const Resources &o) -{ - QByteArray cpuArray; - toJson(cpuArray, o.cpu); - QByteArray memoryArray; - toJson(memoryArray, o.memory); - QJsonObject obj = { - {"cpu", QJsonDocument::fromJson(cpuArray).array()}, - {"memory", QJsonDocument::fromJson(memoryArray).array()}, - }; - - array = QJsonDocument(obj).toJson(); -} - -struct Linux { - QList namespaces; - QList uidMappings; - QList gidMappings; - Seccomp seccomp; - QString cgroupsPath; - Resources resources; -}; - -inline void fromJson(const QByteArray &array, Linux &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson Linux failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("namespaces") || !obj.contains("uidMappings") || !obj.contains("gidMappings") \ - || !obj.contains("cgroupsPath") || !obj.contains("resources")) { - qWarning() << "linux json invalid format"; - return; - } - - Namespace nameArray; - for (auto name : obj.take("namespaces").toArray()) { - fromJson(QJsonDocument(name.toObject()).toJson(), nameArray); - o.namespaces.append(nameArray); - } - - { - IDMap uidMap; - for (auto uid : obj.take("uidMappings").toArray()) { - fromJson(QJsonDocument(uid.toObject()).toJson(), uidMap); - o.uidMappings.append(uidMap); - } - } - - { - IDMap gidMap; - for (auto gid : obj.take("gidMappings").toArray()) { - fromJson(QJsonDocument(gid.toObject()).toJson(), gidMap); - o.gidMappings.append(gidMap); - } - } - - o.cgroupsPath = obj.value("cgroupsPath").toString(); - fromJson(QJsonDocument(obj.value("resources").toObject()).toJson(), o.resources); - - if (obj.contains("seccomp")) { - fromJson(QJsonDocument(obj.value("seccomp").toObject()).toJson(), o.seccomp); - } -} - -inline void toJson(QByteArray &array, const Linux &o) -{ - QJsonArray nameSpacesJsonArray; - QByteArray nameSpacesByteArray; - for (auto const &nameSpace : o.namespaces) { - toJson(nameSpacesByteArray, nameSpace); - nameSpacesJsonArray.append(QJsonDocument::fromJson(nameSpacesByteArray).array()); - } - - QJsonArray uidMapsJsonArray; - QByteArray uidMapsByteArray; - for (auto const &uid : o.uidMappings) { - toJson(uidMapsByteArray, uid); - uidMapsJsonArray.append(QJsonDocument::fromJson(uidMapsByteArray).array()); - } - - QJsonArray gidMapsJsonArray; - QByteArray gidMapsByteArray; - for (auto const &gid : o.gidMappings) { - toJson(gidMapsByteArray, gid); - gidMapsJsonArray.append(QJsonDocument::fromJson(gidMapsByteArray).array()); - } - - QByteArray seccompArray; - toJson(seccompArray, o.seccomp); - - QByteArray resourcesArray; - toJson(resourcesArray, o.resources); - - QJsonObject obj = { - {"namespaces", nameSpacesJsonArray}, - {"uidMappings", uidMapsJsonArray}, - {"gidMappings", gidMapsJsonArray}, - {"seccomp", QJsonDocument::fromJson(seccompArray).array()}, - {"cgroupsPath", o.cgroupsPath}, - {"resources", QJsonDocument::fromJson(resourcesArray).array()}, - }; - - array = QJsonDocument(obj).toJson(); -} - -/* - "hooks": { - "prestart": [ - { - "path": "/usr/bin/fix-mounts", - "args": ["fix-mounts", "arg1", "arg2"], - "env": [ "key1=value1"] - }, - { - "path": "/usr/bin/setup-network" - } - ], - "poststart": [ - { - "path": "/usr/bin/notify-start", - "timeout": 5 - } - ], - "poststop": [ - { - "path": "/usr/sbin/cleanup.sh", - "args": ["cleanup.sh", "-f"] - } - ] - } - */ - -struct Hook { - QString path; - QList args; - QList env; -}; - -inline void fromJson(const QByteArray &array, Hook &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson Hook failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("path")) { - qWarning() << "hook json invalid format"; - return; - } - - o.path = obj.value("path").toString(); - - if (obj.contains("args")) { - for (auto const &arg : obj.value("args").toArray()) { - o.args.append(arg.toString()); - } - } - - if (obj.contains("env")) { - for (auto const &env : obj.value("env").toArray()) { - o.env.append(env.toString()); - } - } -} - -inline void toJson(QByteArray &array, const Hook &o) -{ - QJsonArray argsArray; - for (auto const &arg : o.args) { - argsArray.append(arg); - } - - QJsonArray envArray; - for (auto const &env : o.env) { - envArray.append(env); - } - - QJsonObject obj = { - {"path", o.path}, - {"args", argsArray}, - {"env", envArray}, - }; - - array = QJsonDocument(obj).toJson(); -} - -struct Hooks { - QList prestart; - QList poststart; - QList poststop; -}; - -inline void fromJson(const QByteArray &array, Hooks &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson Hooks failed"; - return; - } - - QJsonObject obj = doc.object(); - Hook hook; - if (obj.contains("prestart")) { - for (auto prestart : obj.take("prestart").toArray()) { - fromJson(QJsonDocument(prestart.toObject()).toJson(), hook); - o.prestart.append(hook); - } - } - - if (obj.contains("poststart")) { - for (auto poststart : obj.take("poststart").toArray()) { - fromJson(QJsonDocument(poststart.toObject()).toJson(), hook); - o.poststart.append(hook); - } - } - - if (obj.contains("poststop")) { - for (auto poststop : obj.take("poststop").toArray()) { - fromJson(QJsonDocument(poststop.toObject()).toJson(), hook); - o.poststop.append(hook); - } - } -} - -inline void toJson(QByteArray &array, const Hooks &o) -{ - QJsonArray poststartJsonArray; - QByteArray poststartByteArray; - for (auto const &poststart : o.poststart) { - toJson(poststartByteArray, poststart); - poststartJsonArray.append(QJsonDocument::fromJson(poststartByteArray).array()); - } - - QJsonArray poststopJsonArray; - QByteArray poststopByteArray; - for (auto const &poststop : o.poststop) { - toJson(poststopByteArray, poststop); - poststopJsonArray.append(QJsonDocument::fromJson(poststopByteArray).array()); - } - - QJsonArray prestartJsonArray; - QByteArray prestartByteArray; - for (auto const &prestart : o.prestart) { - toJson(prestartByteArray, prestart); - prestartJsonArray.append(QJsonDocument::fromJson(prestartByteArray).array()); - } - - QJsonObject obj = { - {"prestart", prestartJsonArray}, - {"poststart", poststartJsonArray}, - {"poststop", poststopJsonArray}, - }; - - array = QJsonDocument(obj).toJson(); -} - -struct AnnotationsOverlayfs { - QString lower_parent; - QString upper; - QString workdir; - QList mounts; -}; - -inline void fromJson(const QByteArray &array, AnnotationsOverlayfs &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson AnnotationsOverlayfs failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("lower_parent") || !obj.contains("upper") \ - || !obj.contains("workdir") || !obj.contains("mounts")) { - qWarning() << "annotationsOverlayfs json invalid format"; - return; - } - - o.lower_parent = obj.value("lower_parent").toString(); - o.upper = obj.value("upper").toString(); - o.workdir = obj.value("workdir").toString(); - - Mount mount; - for (auto mountArray : obj.take("mounts").toArray()) { - fromJson(QJsonDocument(mountArray.toObject()).toJson(), mount); - o.mounts.append(mount); - } -} - - -inline void toJson(QByteArray &array, const AnnotationsOverlayfs &o) -{ - QJsonArray MountsJsonArray; - QByteArray MountsByteArray; - for (auto const &mount : o.mounts) { - toJson(MountsByteArray, mount); - MountsJsonArray.append(QJsonDocument::fromJson(MountsByteArray).array()); - } - - QJsonObject obj = { - {"lower_parent", o.lower_parent}, - {"upper", o.upper}, - {"workdir", o.workdir}, - {"mounts", MountsJsonArray}, - }; - - array = QJsonDocument(obj).toJson(); -} - -struct AnnotationsNativeRootfs { - QList mounts; -}; - -inline void fromJson(const QByteArray &array, AnnotationsNativeRootfs &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson AnnotationsNativeRootfs failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("mounts")) { - qWarning() << "annotationsNativeRootfs json invalid format"; - return; - } - - Mount mount; - for (auto uid : obj.take("mounts").toArray()) { - fromJson(QJsonDocument(uid.toObject()).toJson(), mount); - o.mounts.append(mount); - } -} - -inline void toJson(QByteArray &array, const AnnotationsNativeRootfs &o) -{ - QJsonArray mountsJsonArray; - QByteArray mountsByteArray; - for (auto const &mount : o.mounts) { - toJson(mountsByteArray, mount); - mountsJsonArray.append(QJsonDocument::fromJson(mountsByteArray).array()); - } - - QJsonObject obj = { - {"mounts", mountsJsonArray}, - }; - - array = QJsonDocument(obj).toJson(); -} - -struct Annotations { - QString container_root_path; - AnnotationsOverlayfs overlayfs; - AnnotationsNativeRootfs native; -}; - -inline void fromJson(const QByteArray &array, Annotations &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson Linux failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("container_root_path")) { - qWarning() << "annotations json invalid format"; - return; - } - - o.container_root_path = obj.value("container_root_path").toString(); - if (obj.contains("overlayfs")) { - fromJson(QJsonDocument(obj.value("overlayfs").toObject()).toJson(), o.overlayfs); - } - if (obj.contains("native")) { - fromJson(QJsonDocument(obj.value("native").toObject()).toJson(), o.native); - } -} - -inline void toJson(QByteArray &array, const Annotations &o) -{ - QByteArray overlayfsArray; - toJson(overlayfsArray, o.overlayfs); - QByteArray nativeArray; - toJson(nativeArray, o.native); - - QJsonObject obj = { - {"overlayfs", QJsonDocument::fromJson(overlayfsArray).array()}, - {"native", QJsonDocument::fromJson(nativeArray).array()}, - {"container_root_path", o.container_root_path} - }; - - array = QJsonDocument(obj).toJson(); -} - -struct Runtime { - QString version; - Root root; - Process process; - QString hostname; - Linux linux; - QList mounts; - Hooks hooks; - Annotations annotations; -}; - -inline void fromJson(const QByteArray &array, Runtime &o) -{ - QJsonDocument doc = QJsonDocument::fromJson(array); - if (!doc.isObject()) { - qWarning() << "fromJson Runtime failed"; - return; - } - - QJsonObject obj = doc.object(); - if (!obj.contains("version") || !obj.contains("root") || !obj.contains("process") \ - || !obj.contains("hostname") || !obj.contains("linux")) { - qWarning() << "runtime json invalid format"; - return; - } - - o.version = obj.value("version").toString(); - o.hostname = obj.value("hostname").toString(); - fromJson(QJsonDocument(obj.value("root").toObject()).toJson(), o.root); - fromJson(QJsonDocument(obj.value("process").toObject()).toJson(), o.process); - fromJson(QJsonDocument(obj.value("linux").toObject()).toJson(), o.linux); - - // mounts hooks annotations 可不存在 - if (!obj.contains("mounts") || !obj.contains("hooks") || !obj.contains("annotations")) { - return; - } - fromJson(QJsonDocument(obj.value("hooks").toObject()).toJson(), o.hooks); - fromJson(QJsonDocument(obj.value("annotations").toObject()).toJson(), o.annotations); - Mount mount; - for (auto uid : obj.take("mounts").toArray()) { - fromJson(QJsonDocument(uid.toObject()).toJson(), mount); - o.mounts.append(mount); - } -} - -inline void toJson(QByteArray &array, const Runtime &o) -{ - QByteArray rootArray; - QByteArray processArray; - QByteArray linuxArray; - QByteArray hooksArray; - QByteArray annotationsArray; - toJson(rootArray, o.root); - toJson(processArray, o.process); - toJson(linuxArray, o.linux); - toJson(hooksArray, o.hooks); - toJson(annotationsArray, o.annotations); - - QJsonArray MountsJsonArray; - QByteArray MountsByteArray; - for (auto const &mount : o.mounts) { - toJson(MountsByteArray, mount); - MountsJsonArray.append(QJsonDocument::fromJson(MountsByteArray).array()); - } - - QJsonObject obj = { - {"version", o.version}, - {"root", QJsonDocument::fromJson(rootArray).array()}, - {"process", QJsonDocument::fromJson(processArray).array()}, - {"hostname", o.hostname}, - {"linux", QJsonDocument::fromJson(linuxArray).array()}, - {"hooks", QJsonDocument::fromJson(hooksArray).array()}, - {"annotations", QJsonDocument::fromJson(annotationsArray).array()}, - {"mounts", MountsJsonArray}, - }; - - array = QJsonDocument(obj).toJson(); -} - -} // namespace linglong - -#endif /* LINGLONG_BOX_SRC_UTIL_OCI_RUNTIME_H_ */ diff --git a/src/modules/util/platform.cpp b/src/modules/util/platform.cpp deleted file mode 100644 index 4fc6c73..0000000 --- a/src/modules/util/platform.cpp +++ /dev/null @@ -1,64 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "platform.h" -#include "logger.h" -#include "debug/debug.h" - -#include -#include -#include -#include - -namespace linglong { - -const int kStackSize = (1024 * 1024); - -namespace util { - -int PlatformClone(int (*callback)(void *), int flags, void *arg, ...) -{ - char *stack; - char *stackTop; - - stack = reinterpret_cast( - mmap(nullptr, kStackSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0)); - if (stack == MAP_FAILED) { - return EXIT_FAILURE; - } - - stackTop = stack + kStackSize; - - return clone(callback, stackTop, flags, arg); -} - -int Exec(const util::str_vec &args, tl::optional> env_list) -{ - auto targetArgc = args.size(); - const char *targetArgv[targetArgc + 1]; - for (decltype(targetArgc) i = 0; i < targetArgc; i++) { - targetArgv[i] = args[i].c_str(); - } - targetArgv[targetArgc] = nullptr; - - auto targetEnvc = env_list.has_value() ? env_list->size() : 0; - const char **targetEnvv = targetEnvc ? new const char *[targetEnvc + 1] : nullptr; - if (targetEnvv) { - for (decltype(targetEnvc) i = 0; i < targetEnvc; i++) { - targetEnvv[i] = env_list.value().at(i).c_str(); - } - targetEnvv[targetEnvc] = nullptr; - } - - logDbg() << "execve" << targetArgv[0] << " in pid:" << getpid(); - - int ret = execvpe(targetArgv[0], const_cast(targetArgv), const_cast(targetEnvv)); - - delete[] targetEnvv; - - return ret; -} - -} // namespace util -} // namespace linglong diff --git a/src/modules/util/platform.h b/src/modules/util/platform.h deleted file mode 100644 index c54b38c..0000000 --- a/src/modules/util/platform.h +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef LINGLONG_BOX_SRC_UTIL_PLATFORM_H_ -#define LINGLONG_BOX_SRC_UTIL_PLATFORM_H_ - -#include "common.h" -#include - -#define tl std - -namespace linglong { - -namespace util { - -int PlatformClone(int (*callback)(void *), int flags, void *arg, ...); - -int Exec(const util::str_vec &args, tl::optional> env_list); - -} // namespace util - -} // namespace linglong - -#endif /* LINGLONG_BOX_SRC_UTIL_PLATFORM_H_ */ diff --git a/src/modules/util/semaphore.cpp b/src/modules/util/semaphore.cpp deleted file mode 100644 index c42c9af..0000000 --- a/src/modules/util/semaphore.cpp +++ /dev/null @@ -1,67 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "semaphore.h" - -#include - -#include "logger.h" - -namespace linglong { - -union semun { - int val; - struct semid_ds *buf; - ushort *array; -}; - -struct Semaphore::SemaphorePrivate { - explicit SemaphorePrivate(Semaphore *parent = nullptr) - : q_ptr(parent) - { - (void)q_ptr; - } - - struct sembuf sem_lock = {0, -1, SEM_UNDO}; - - struct sembuf sem_unlock = {0, 1, SEM_UNDO}; - - int sem_id = -1; - - Semaphore *q_ptr; -}; - -Semaphore::Semaphore(int key) - : dd_ptr(new SemaphorePrivate(this)) -{ - dd_ptr->sem_id = semget(key, 1, IPC_CREAT | 0666); - if (dd_ptr->sem_id < 0) { - logErr() << "semget failed" << util::RetErrString(dd_ptr->sem_id); - } -} - -Semaphore::~Semaphore() = default; - -int Semaphore::init() -{ - union semun sem_union = {0}; - sem_union.val = 0; - logDbg() << "semctl " << dd_ptr->sem_id; - if (semctl(dd_ptr->sem_id, 0, SETVAL, sem_union) == -1) { - logErr() << "semctl failed" << util::RetErrString(-1); - } - return 0; -} - -int Semaphore::passeren() -{ - return semop(dd_ptr->sem_id, &dd_ptr->sem_lock, 1); -} - -int Semaphore::vrijgeven() -{ - return semop(dd_ptr->sem_id, &dd_ptr->sem_unlock, 1); -} - -} // namespace linglong diff --git a/src/modules/util/semaphore.h b/src/modules/util/semaphore.h deleted file mode 100644 index 9d5725f..0000000 --- a/src/modules/util/semaphore.h +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef LINGLONG_BOX_SRC_UTIL_SEMAPHORE_H_ -#define LINGLONG_BOX_SRC_UTIL_SEMAPHORE_H_ - -#include - -namespace linglong { - -class Semaphore -{ -public: - explicit Semaphore(int key); - ~Semaphore(); - - int init(); - - //! passeren -1 to value - //! if value < 0, block - //! \return - int passeren(); - - //! passeren +1 to value - //! if value <= 0, release process in queue - //! \return - int vrijgeven(); - -private: - struct SemaphorePrivate; - std::unique_ptr dd_ptr; -}; - -} // namespace linglong - -#endif /* LINGLONG_BOX_SRC_UTIL_SEMAPHORE_H_ */ diff --git a/src/modules/util/util.h b/src/modules/util/util.h deleted file mode 100644 index b043647..0000000 --- a/src/modules/util/util.h +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef LINGLONG_BOX_SRC_UTIL_UTIL_H_ -#define LINGLONG_BOX_SRC_UTIL_UTIL_H_ - -#include "macro.h" -#include "common.h" -#include "logger.h" -#include "semaphore.h" -#include "filesystem.h" -#include "json.h" - -#include - -// namespace linglong { -// namespace util { -// namespace json { - -// inline nlohmann::json fromByteArray(const std::string &content) -// { -// return nlohmann::json::parse(content); -// } - -// inline nlohmann::json fromFile(const std::string &filepath) -// { -// std::ifstream f(filepath); -// std::string str((std::istreambuf_iterator(f)), std::istreambuf_iterator()); -// auto j = fromByteArray(str); -// return j; -// } - -// } // namespace json -// } // namespace util -// } // namespace linglong - -#endif /* LINGLONG_BOX_SRC_UTIL_UTIL_H_ */ diff --git a/src/service/CMakeLists.txt b/src/service/CMakeLists.txt deleted file mode 100644 index d0d2030..0000000 --- a/src/service/CMakeLists.txt +++ /dev/null @@ -1,86 +0,0 @@ -set(CMAKE_INCLUDE_CURRENT_DIR ON) -set(CMAKE_AUTOMOC ON) -set(CMAKE_AUTORCC ON) - -set(BIN_NAME dde-application-manager) - -find_package(PkgConfig REQUIRED) -find_package(Qt5 REQUIRED COMPONENTS Core DBus Concurrent Gui) -find_package(DtkCore REQUIRED) -find_package(DtkWidget REQUIRED) - -pkg_check_modules(XCB REQUIRED IMPORTED_TARGET xcb-icccm xcb-ewmh xcb) -pkg_check_modules(X11 REQUIRED IMPORTED_TARGET x11) -pkg_check_modules(XRes REQUIRED IMPORTED_TARGET xres) -pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0 gio-unix-2.0) -pkg_check_modules(GLib REQUIRED IMPORTED_TARGET glib-2.0) -pkg_check_modules(QGSettings REQUIRED IMPORTED_TARGET gsettings-qt) - -qt5_add_dbus_adaptor(ADAPTER_SOURCES - ../../dbus/org.deepin.dde.Application1.Manager.xml - impl/application_manager.h - ApplicationManager) - -qt5_add_dbus_adaptor(ADAPTER_SOURCES - ../../dbus/org.deepin.dde.Application1.xml - impl/application.h - Application) - -qt5_add_dbus_adaptor(ADAPTER_SOURCES - ../../dbus/org.deepin.dde.Application1.Instance.xml - impl/application_instance.h - ApplicationInstance) - -qt5_add_dbus_adaptor(ADAPTER_SOURCES - ../../dbus/org.deepin.dde.Mime1.xml - ../modules/mimeapp/mime_app.h - MimeApp) - - -add_definitions(-DUSE_QT) - -file(GLOB_RECURSE SRCS "*.h" "*.cpp" "../frameworkdbus/*.h" "../frameworkdbus/*.cpp" - "../lib/*.h" "../lib/*.cpp" "../lib/*.hpp" - "../modules/*.h" "../modules/*.cpp" "../modules/*.hpp" - "../utils.h" "../utils/*.cpp") - -add_executable(${BIN_NAME} - ${SRCS} - ${ADAPTER_SOURCES} -) - -target_link_libraries(${BIN_NAME} - Qt5::Core - Qt5::DBus - Qt5::Concurrent - Qt5::Gui - Dtk::Core - pthread - PkgConfig::XCB - PkgConfig::X11 - PkgConfig::XRes - PkgConfig::GIO - PkgConfig::GLib - PkgConfig::QGSettings - ${DtkWidget_LIBRARIES} -) - -target_include_directories(${BIN_NAME} PUBLIC - PkgConfig::XCB - PkgConfig::X11 - PkgConfig::XRes - PkgConfig::GIO - PkgConfig::GLib - PkgConfig::QGSettings - ../lib - ../utils - ../frameworkdbus - ../frameworkdbus/qtdbusextended - ../frameworkdbus/types - ${Qt5Gui_PRIVATE_INCLUDE_DIRS} -) - -# binary file -install(TARGETS ${BIN_NAME} DESTINATION ${CMAKE_INSTALL_BINDIR}) - -add_definitions(-DQT_NO_KEYWORDS) diff --git a/src/service/applicationhelper.h b/src/service/applicationhelper.h deleted file mode 100644 index 1f53620..0000000 --- a/src/service/applicationhelper.h +++ /dev/null @@ -1,80 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "../modules/tools/desktop_deconstruction.hpp" - -#include - -namespace modules { -namespace ApplicationHelper { -class Helper { - QString m_file; - -public: - Helper(const QString &desktop) - : m_file(desktop) - { - - } - - inline QString desktop() const { return m_file; } - - template - T value(const QString &key) const - { - QSettings settings = DesktopDeconstruction(m_file); - settings.beginGroup("Desktop Entry"); - return settings.value(key).value(); - } - - QStringList categories() const - { - QStringList result; - QStringList tmp{ value("Categories").split(";") }; - for (auto t : tmp) { - if (t.isEmpty()) { - continue; - } - result << t; - } - return result; - } - - QString icon() const - { - return value("Icon"); - } - - // appId - QString id() const - { - return m_file.split("/").last().split(".").first(); - } - - QStringList mimetypes() const - { - QStringList result; - QStringList tmp{ value("MimeType").split(";") }; - for (auto t : tmp) { - if (t.isEmpty()) { - continue; - } - result << t; - } - return result; - } - - QString comment(const QString &locale) const - { - return value(QString("Comment[%1]").arg(locale)); - } - - QString name(const QString &name) const - { - return value(QString("Name[%1]").arg(name)); - } -}; -} // namespace ApplicationHelper -} // namespace modules - diff --git a/src/service/impl/application.cpp b/src/service/impl/application.cpp deleted file mode 100644 index 21079e6..0000000 --- a/src/service/impl/application.cpp +++ /dev/null @@ -1,178 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "application.h" - -#include -#include -#include -#include -#include - -#include "../applicationhelper.h" -#include "../modules/tools/desktop_deconstruction.hpp" -#include "application_instance.h" - -class ApplicationPrivate { - Application *q_ptr = nullptr; - Q_DECLARE_PUBLIC(Application); - - QList> instances; - QSharedPointer helper; - QString m_prefix; - Application::Type m_type; - -public: - ApplicationPrivate(Application *parent) : q_ptr(parent) {} - - ~ApplicationPrivate() {} - - QStringList categories() const - { - return helper->categories(); - } - - QString icon() const - { - return helper->icon(); - } - - QString id() const - { - return helper->id(); - } - - QStringList mimetypes() const - { - return helper->mimetypes(); - } - - QString comment(const QString &locale) const - { - return helper->comment(locale); - } - - QString name(const QString &name) const - { - return helper->name(name); - } -}; - -Application::Application(const QString &prefix, Type type, QSharedPointer helper) : QObject(nullptr), dd_ptr(new ApplicationPrivate(this)) -{ - Q_D(Application); - - d->helper = helper; - d->m_type = type; - d->m_prefix = prefix; -} - -Application::~Application() {} - -QStringList Application::categories() const -{ - Q_D(const Application); - - return d->categories(); -} - -QString Application::icon() const -{ - Q_D(const Application); - - return d->icon(); -} - -QString Application::id() const -{ - Q_D(const Application); - - const QString id{ d->id() }; - return QString("/%1/%2/%3").arg(d->m_prefix).arg(d->m_type == Application::Type::System ? "system" : "user").arg(id); -} - -QList Application::instances() const -{ - Q_D(const Application); - - QList result; - - for (const auto &ins : d->instances) { - result << ins->path(); - } - - return result; -} - -QStringList Application::mimetypes() const -{ - Q_D(const Application); - - return d->mimetypes(); -} - -QString Application::Comment(const QString &locale) -{ - Q_D(const Application); - - return d->comment(locale); -} - -QString Application::Name(const QString &locale) -{ - Q_D(const Application); - - return d->name(locale); -} - -QDBusObjectPath Application::path() const -{ - return QDBusObjectPath(QString("/org/deepin/dde/Application1/%1").arg(QString(QCryptographicHash::hash(id().toUtf8(), QCryptographicHash::Md5).toHex()))); -} - -Application::Type Application::type() const -{ - Q_D(const Application); - - return d->m_type; -} - -QString Application::filePath() const -{ - Q_D(const Application); - - return d->helper->desktop(); -} - -QSharedPointer Application::createInstance(QStringList files) -{ - Q_D(Application); - - d->instances << QSharedPointer(new ApplicationInstance(this, d->helper, files)); - - connect(d->instances.last().get(), &ApplicationInstance::taskFinished, this, [=] { - for (auto it = d->instances.begin(); it != d->instances.end(); ++it) { - if ((*it).data() == sender()) { - d->instances.erase(it); - return; - } - } - qWarning() << "The instance should not be found!"; - }); - - return d->instances.last(); -} - -QString Application::prefix() const -{ - Q_D(const Application); - - return d->m_prefix; -} - -QList>& Application::getAllInstances(){ - Q_D(Application); - - return d->instances; -} diff --git a/src/service/impl/application.h b/src/service/impl/application.h deleted file mode 100644 index f6650c7..0000000 --- a/src/service/impl/application.h +++ /dev/null @@ -1,66 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef A216803F_06DD_4F40_8FD1_5BAED85905BE -#define A216803F_06DD_4F40_8FD1_5BAED85905BE - -#include -#include -#include - -namespace modules { - namespace ApplicationHelper { - class Helper; - } -} - -class ApplicationPrivate; -class ApplicationInstance; -class Application : public QObject { - Q_OBJECT - QScopedPointer dd_ptr; - Q_DECLARE_PRIVATE_D(qGetPtrHelper(dd_ptr), Application) -public: - enum class Type { - System, - User, - }; - - Application(const QString& prefix, Type type, QSharedPointer helper); - ~Application() override; - -public: // PROPERTIES - Q_PROPERTY(QStringList categories READ categories) - QStringList categories() const; - - Q_PROPERTY(QString icon READ icon) - QString icon() const; - - Q_PROPERTY(QString id READ id) - QString id() const; - - Q_PROPERTY(QList instances READ instances) - QList instances() const; - - Q_PROPERTY(QStringList mimetypes READ mimetypes) - QStringList mimetypes() const; - - QDBusObjectPath path() const; - - QString prefix() const; - - Type type() const; - - QString filePath() const; - - QSharedPointer createInstance(QStringList files); - QList>& getAllInstances(); - bool destoryInstance(QString hashId); - -public Q_SLOTS: // METHODS - QString Comment(const QString &locale); - QString Name(const QString &locale); -}; - -#endif /* A216803F_06DD_4F40_8FD1_5BAED85905BE */ diff --git a/src/service/impl/application_instance.cpp b/src/service/impl/application_instance.cpp deleted file mode 100644 index b5cf725..0000000 --- a/src/service/impl/application_instance.cpp +++ /dev/null @@ -1,205 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "application_instance.h" -#include "../applicationhelper.h" -#include "application.h" -#include "instanceadaptor.h" - -#include -#include -#include -#include -#include -#include -#include - -#ifdef DEFINE_LOADER_PATH -#include "../../src/define.h" -#endif - -class ApplicationInstancePrivate -{ - ApplicationInstance* q_ptr = nullptr; - Q_DECLARE_PUBLIC(ApplicationInstance); - - Application* application; - InstanceAdaptor* adapter; - QString m_path; - QSharedPointer helper; - QDateTime startupTime; - QString m_id; - uint32_t pid; - -public: - ApplicationInstancePrivate(ApplicationInstance* parent) : q_ptr(parent) - { - startupTime = QDateTime::currentDateTime(); - m_id = QString(QCryptographicHash::hash(QUuid::createUuid().toByteArray(), QCryptographicHash::Md5).toHex()); - m_path = QString("/org/deepin/dde/Application1/Instance/%1").arg(m_id); - adapter = new InstanceAdaptor(q_ptr); - } - - ~ApplicationInstancePrivate() - { - // disconnect dbus - QDBusConnection::sessionBus().unregisterObject(m_path); - } - - void run() - { -#ifdef DEFINE_LOADER_PATH - - const QString task_hash{QString("DAM_TASK_HASH=%1").arg(m_id)}; - const QString task_type{"DAM_TASK_TYPE=freedesktop "}; - QProcess* p = new QProcess(q_ptr); - p->connect(p, static_cast(&QProcess::finished), p, [ = ] { - qInfo().noquote() << p->readAllStandardOutput(); - qWarning().noquote() << p->readAllStandardError(); - }); - p->connect(p, static_cast(&QProcess::finished), q_ptr, &ApplicationInstance::taskFinished); - p->connect(p, &QProcess::readyReadStandardOutput, p, [ = ] - { qInfo() << p->readAllStandardOutput(); }); - p->connect(p, &QProcess::readyReadStandardError, p, [ = ] - { qWarning() << p->readAllStandardError(); }); - p->setProgram(LOADER_PATH); - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - env.insert("DAM_TASK_HASH", m_id); - env.insert("DAM_TASK_TYPE", "freedesktop"); - p->setEnvironment(env.toStringList()); - p->start(); - p->waitForStarted(); - if (p->state() == QProcess::ProcessState::NotRunning) { - Q_EMIT q_ptr->taskFinished(p->exitCode()); - } -#else - qInfo() << "app manager load service:" << QString("org.deepin.dde.Application1.Instance@%1.service").arg(m_id); - QDBusInterface systemd("org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager"); - QDBusReply reply = systemd.call("StartUnit", QString("org.deepin.dde.Application1.Instance@%1.service").arg(m_id), "replace-irreversibly"); - if (!reply.isValid()) { - qInfo() << reply.error(); - q_ptr->deleteLater(); - } -#endif - } - - void _exit() - { -#ifdef LOADER_PATH -#else - QDBusInterface systemd("org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager"); - qInfo() << systemd.call("StopUnit", QString("org.deepin.dde.Application1.Instance@%1.service").arg(m_id), "replace-irreversibly"); -#endif - } - - void _kill() {} - uint32_t _getPid() - { - return pid; - } - - void _success(const QString& data) - { - pid = data.toUInt(); - } -}; - -ApplicationInstance::ApplicationInstance(Application* parent, QSharedPointer helper, QStringList files) - : QObject(nullptr) - , dd_ptr(new ApplicationInstancePrivate(this)) - , m_files(files) -{ - Q_D(ApplicationInstance); - - d->application = parent; - d->helper = helper; - - QTimer::singleShot(0, this, [ = ] { - QDBusConnection::sessionBus().registerObject(d->m_path, "org.deepin.dde.Application1.Instance", this); - d->run(); - }); -} - -ApplicationInstance::~ApplicationInstance() -{ - Q_D(ApplicationInstance); - qDebug() << "instance quit " << d->helper->desktop(); -} - -QDBusObjectPath ApplicationInstance::id() const -{ - Q_D(const ApplicationInstance); - - return d->application->path(); -} - -QString ApplicationInstance::hash() const -{ - Q_D(const ApplicationInstance); - - return d->m_id; -} - -quint64 ApplicationInstance::startuptime() const -{ - Q_D(const ApplicationInstance); - - return d->startupTime.toSecsSinceEpoch(); -} - -QDBusObjectPath ApplicationInstance::path() const -{ - Q_D(const ApplicationInstance); - - return QDBusObjectPath(d->m_path); -} - -Methods::Task ApplicationInstance::taskInfo() const -{ - Q_D(const ApplicationInstance); - - Methods::Task task; - task.id = d->m_id; - task.runId = d->application->id(); - task.filePath = d->application->filePath(); - task.date = QString::number(startuptime()); - task.arguments = m_files; - - // TODO: debug to display environment - task.environments.insert("DISPLAY", ":0"); - auto sysEnv = QProcessEnvironment::systemEnvironment(); - for (const auto& key : sysEnv.keys()) { - task.environments.insert(key, sysEnv.value(key)); - } - - return task; -} - -void ApplicationInstance::Exit() -{ - Q_D(ApplicationInstance); - - return d->_exit(); -} - -void ApplicationInstance::Kill() -{ - Q_D(ApplicationInstance); - - return d->_kill(); -} - -uint32_t ApplicationInstance::getPid() -{ - Q_D(ApplicationInstance); - - return d->_getPid(); -} - -void ApplicationInstance::Success(const QString& data) -{ - Q_D(ApplicationInstance); - QDBusConnection::sessionBus().registerObject(d->m_path, "org.deepin.dde.Application1.Instance", this); - return d->_success(data); -} diff --git a/src/service/impl/application_instance.h b/src/service/impl/application_instance.h deleted file mode 100644 index 60c4918..0000000 --- a/src/service/impl/application_instance.h +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef D6D05668_8A58_43AA_91C5_C6278643A1AF -#define D6D05668_8A58_43AA_91C5_C6278643A1AF - -#include -#include - -#include "../../modules/methods/task.hpp" - -namespace modules { -namespace ApplicationHelper { -class Helper; -} -} // namespace modules - -class Application; -class ApplicationInstancePrivate; -class ApplicationInstance : public QObject { - Q_OBJECT - QScopedPointer dd_ptr; - Q_DECLARE_PRIVATE_D(qGetPtrHelper(dd_ptr), ApplicationInstance) - - QStringList m_files; // 实例打开的文件 -public: - ApplicationInstance(Application* parent, QSharedPointer helper, QStringList files); - ~ApplicationInstance() override; - -public: // PROPERTIES - Q_PROPERTY(QDBusObjectPath id READ id) - QDBusObjectPath id() const; - - Q_PROPERTY(quint64 startuptime READ startuptime) - quint64 startuptime() const; - - QDBusObjectPath path() const; - QString hash() const; - Methods::Task taskInfo() const; - -Q_SIGNALS: - void taskFinished(int exitCode) const; - -public Q_SLOTS: // METHODS - void Exit(); - void Kill(); - void Success(const QString& data); - uint32_t getPid(); -}; - -#endif /* D6D05668_8A58_43AA_91C5_C6278643A1AF */ diff --git a/src/service/impl/application_manager.cpp b/src/service/impl/application_manager.cpp deleted file mode 100644 index 8c71f5a..0000000 --- a/src/service/impl/application_manager.cpp +++ /dev/null @@ -1,488 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "application_manager.h" - -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "../../modules/methods/basic.h" -#include "../../modules/methods/instance.hpp" -#include "../../modules/methods/quit.hpp" -#include "../../modules/methods/registe.hpp" -#include "../../modules/methods/task.hpp" -#include "../../modules/startmanager/startmanager.h" -#include "application.h" -#include "application_instance.h" -#include "instanceadaptor.h" -#include "../lib/keyfile.h" - -ApplicationManagerPrivate::ApplicationManagerPrivate(ApplicationManager* parent) - : QObject(parent) - , q_ptr(parent) - , startManager(new StartManager(this)) - , virtualMachePath("/usr/share/dde-daemon/supportVirsConf.ini") - , section("AppName") - , key("support") -{ - const QString socketPath{QString("/run/user/%1/dde-application-manager.socket").arg(getuid())}; - connect(&server, &Socket::Server::onReadyRead, this, &ApplicationManagerPrivate::recvClientData, Qt::QueuedConnection); - server.listen(socketPath.toStdString()); -} - -ApplicationManagerPrivate::~ApplicationManagerPrivate() -{ -} - -bool ApplicationManagerPrivate::checkDMsgUid() -{ - QDBusReply reply = q_ptr->connection().interface()->serviceUid(q_ptr->message().service()); - return reply.isValid() && (reply.value() == getuid()); -} - -/** - * @brief ApplicationManagerPrivate::recvClientData 接受客户端数据,进行校验 - * @param socket 客户端套接字 - * @param data 接受到客户端数据 - */ -void ApplicationManagerPrivate::recvClientData(int socket, const std::vector& data) -{ - QByteArray jsonArray = data.data(); - Methods::Basic basic; - Methods::fromJson(jsonArray, basic); - QByteArray tmpArray; - do { - // 运行实例 - if (basic.type == "instance") { - Methods::Instance instance; - Methods::fromJson(jsonArray, instance); - - // 校验实例信息 - auto find = tasks.find(instance.hash.toStdString()); - if (find != tasks.end()) { - Methods::Task task = find->second->taskInfo(); - Methods::toJson(tmpArray, task); - - // 通过校验,传入应用启动信息 - write(socket, tmpArray.toStdString()); - tasks.erase(find); - break; - } - } - - // 退出 - if (basic.type == "quit") { - Methods::ProcessStatus quit; - Methods::fromJson(jsonArray, quit); - processInstanceStatus(quit); - server.close(socket); - std::cout << "client quit" << std::endl; - break; - } - - // 注册应用 - if (basic.type == "registe") { - Methods::Registe registe; - Methods::fromJson(jsonArray, registe); - Methods::Registe result; - result.state = false; - // std::lock_guard lock(task_mutex); - for (auto it = tasks.begin(); it != tasks.end(); ++it) { - if (registe.hash == QString::fromStdString(it->first)) { - result.state = true; - result.hash = registe.hash; - break; - } - } - Methods::toJson(tmpArray, result); - write(socket, tmpArray.toStdString()); - break; - } - - if (basic.type == "success") { - Methods::ProcessStatus processSuccess; - Methods::fromJson(jsonArray, processSuccess); - processInstanceStatus(processSuccess); - std::cout << "client success" << std::endl; - break; - } - write(socket, jsonArray.toStdString()); - } while (false); -} - -void ApplicationManagerPrivate::write(int socket, const std::vector& data) -{ - std::vector tmp = data; - tmp.push_back('\0'); - server.write(socket, tmp); -} - -void ApplicationManagerPrivate::write(int socket, const std::string& data) -{ - std::vector result; - std::copy(data.cbegin(), data.cend(), std::back_inserter(result)); - return write(socket, result); -} - -void ApplicationManagerPrivate::write(int socket, const char c) -{ - return write(socket, std::vector(c)); -} - -void ApplicationManagerPrivate::init() -{ - KeyFile keyFile; - keyFile.loadFile(virtualMachePath); - virtualMachines = keyFile.getStrList(section, key); - if (virtualMachines.empty()) { - virtualMachines = {"hvm", "bochs", "virt", "vmware", "kvm", "cloud", "invented"}; - } -} - -void ApplicationManagerPrivate::processInstanceStatus(Methods::ProcessStatus instanceStatus) -{ - bool bFound = false; - - auto application = applications.begin(); - while (application != applications.end()) { - - auto instance = (*application)->getAllInstances().begin(); - while (instance != (*application)->getAllInstances().end()) { - if ((*instance)->hash() == instanceStatus.id) { - bFound = true; - } - if (bFound) { - if (instanceStatus.type == "success") { - (*instance)->Success(instanceStatus.data); - } else if (instanceStatus.type == "quit") { - (*instance)->Exit(); - (*application)->getAllInstances().erase(instance); - } else { - qWarning() << "instance tyep : " << instanceStatus.type << "not found"; - } - return; - } - instance++; - } - application++; - } -} - -ApplicationManager* ApplicationManager::instance() -{ - static ApplicationManager manager; - return &manager; -} - -ApplicationManager::ApplicationManager(QObject* parent) - : QObject(parent) - , dd_ptr(new ApplicationManagerPrivate(this)) -{ - Q_D(ApplicationManager); - - connect(d->startManager, &StartManager::autostartChanged, this, &ApplicationManager::AutostartChanged); -} - -ApplicationManager::~ApplicationManager() {} - -void ApplicationManager::addApplication(const QList>& list) -{ - Q_D(ApplicationManager); - - d->applications = list; -} - -/** - * @brief ApplicationManager::launchAutostartApps 加载自启动应用 - * TODO 待优化点: 多个loader使用同一个套接字通信,串行执行,效率低 - */ -void ApplicationManager::launchAutostartApps() -{ - /* - Launch("/freedesktop/system/seahorse", QStringList()); - QTimer::singleShot(1000, [&] { - for (auto app : startManager->autostartList()) { - QString id = app.split("/").last().split(".").first(); - Launch(id, QStringList()); - } - }); - */ -} - -QDBusObjectPath ApplicationManager::GetInformation(const QString& id) -{ - Q_D(ApplicationManager); - - if (!d->checkDMsgUid()) - return {}; - - for (const QSharedPointer& app : d->applications) { - if (app->id() == id) { - return app->path(); - } - } - return {}; -} - -QList ApplicationManager::GetInstances(const QString& id) -{ - Q_D(ApplicationManager); - if (!d->checkDMsgUid()) - return {}; - - for (const auto& app : d->applications) { - if (app->id() == id) { - return app->instances(); - } - } - - return {}; -} - -bool ApplicationManager::AddAutostart(const QString &desktop) -{ - Q_D(ApplicationManager); - if (!d->checkDMsgUid()) { - if (calledFromDBus()) - sendErrorReply(QDBusError::Failed, "The call failed"); - - qWarning() << "check msg failed..."; - return false; - } - - if (!d->startManager->addAutostart(desktop)) { - if (calledFromDBus()) - sendErrorReply(QDBusError::InvalidArgs, "invalid arguments"); - - qWarning() << "invalid arguments"; - return false; - } - - return true; -} - -bool ApplicationManager::RemoveAutostart(const QString &fileName) -{ - Q_D(ApplicationManager); - if (!d->checkDMsgUid()) { - if (calledFromDBus()) - sendErrorReply(QDBusError::Failed, "The call failed"); - - qWarning() << "check msg failed..."; - return false; - } - - if (!d->startManager->removeAutostart(fileName)) { - if (calledFromDBus()) - sendErrorReply(QDBusError::InvalidArgs, "invalid arguments"); - - qWarning() << "invalid arguments"; - return false; - } - - return true; -} - -QStringList ApplicationManager::AutostartList() -{ - Q_D(ApplicationManager); - if (!d->checkDMsgUid()) { - if (calledFromDBus()) - sendErrorReply(QDBusError::Failed, "The call failed"); - - qWarning() << "check msg failed..."; - return QStringList(); - } - - return d->startManager->autostartList(); -} - -bool ApplicationManager::IsAutostart(const QString &fileName) -{ - Q_D(ApplicationManager); - if (!d->checkDMsgUid()) { - if (calledFromDBus()) - sendErrorReply(QDBusError::Failed, "The call failed"); - - qWarning() << "check msg failed..."; - return false; - } - - if (!d->startManager->isAutostart(fileName)) { - if (calledFromDBus()) - sendErrorReply(QDBusError::InvalidArgs, "invalid arguments"); - - qWarning() << "invalid arguments"; - return false; - } - - return true; -} - -void ApplicationManager::Launch(const QString &desktopFile, bool withMsgCheck) -{ - Q_D(ApplicationManager); - if (withMsgCheck && !d->checkDMsgUid()) { - if (calledFromDBus()) - sendErrorReply(QDBusError::Failed, "The call failed"); - - qWarning() << "check msg failed..."; - return; - } - - if (!d->startManager->launchApp(desktopFile)) { - if (calledFromDBus()) - sendErrorReply(QDBusError::InvalidArgs, "invalid arguments"); - - qWarning() << "invalid arguments"; - } -} - - -void ApplicationManager::LaunchApp(const QString &desktopFile, uint32_t timestamp, const QStringList &files, bool withMsgCheck) -{ - Q_D(ApplicationManager); - if (withMsgCheck && !d->checkDMsgUid()) { - if (calledFromDBus()) - sendErrorReply(QDBusError::Failed, "The call failed"); - - qWarning() << "check msg failed..."; - return; - } - - if (!d->startManager->launchApp(desktopFile, timestamp, files)) { - if (calledFromDBus()) - sendErrorReply(QDBusError::InvalidArgs, "invalid arguments"); - - qWarning() << "invalid arguments"; - } -} - -void ApplicationManager::LaunchAppAction(const QString &desktopFile, const QString &action, uint32_t timestamp, bool withMsgCheck) -{ - Q_D(ApplicationManager); - if (withMsgCheck && !d->checkDMsgUid()) { - if (calledFromDBus()) - sendErrorReply(QDBusError::Failed, "The call failed"); - - qWarning() << "check msg failed..."; - return; - } - - if (!d->startManager->launchAppAction(desktopFile, action, timestamp)) { - if (calledFromDBus()) - sendErrorReply(QDBusError::InvalidArgs, "invalid arguments"); - - qWarning() << "invalid arguments"; - } -} - -void ApplicationManager::LaunchAppWithOptions(const QString &desktopFile, uint32_t timestamp, const QStringList &files, QVariantMap options) -{ - Q_D(ApplicationManager); - if (!d->checkDMsgUid()) { - if (calledFromDBus()) - sendErrorReply(QDBusError::Failed, "The call failed"); - - qWarning() << "check msg failed..."; - return; - } - - if (!d->startManager->launchAppWithOptions(desktopFile, timestamp, files, options)) { - if (calledFromDBus()) - sendErrorReply(QDBusError::InvalidArgs, "invalid arguments"); - - qWarning() << "invalid arguments"; - } -} - -void ApplicationManager::RunCommand(const QString &exe, const QStringList &args) -{ - Q_D(ApplicationManager); - if (!d->checkDMsgUid()) { - if (calledFromDBus()) - sendErrorReply(QDBusError::Failed, "The call failed"); - - qWarning() << "check msg failed..."; - return; - } - - if (!d->startManager->runCommand(exe, args)) { - if (calledFromDBus()) - sendErrorReply(QDBusError::InvalidArgs, "invalid arguments"); - - qWarning() << "invalid arguments"; - } -} - -void ApplicationManager::RunCommandWithOptions(const QString &exe, const QStringList &args, const QVariantMap &options) -{ - Q_D(ApplicationManager); - if (!d->checkDMsgUid()) { - if (calledFromDBus()) - sendErrorReply(QDBusError::Failed, "The call failed"); - - qWarning() << "check msg failed..."; - return; - } - - if (!d->startManager->runCommandWithOptions(exe, args, options)) { - if (calledFromDBus()) - sendErrorReply(QDBusError::InvalidArgs, "invalid arguments"); - - qWarning() << "invalid arguments"; - } -} - -QList ApplicationManager::instances() const -{ - Q_D(const ApplicationManager); - - QList result; - - for (const auto& app : d->applications) { - result += app->instances(); - } - - return result; -} - -QList ApplicationManager::list() const -{ - Q_D(const ApplicationManager); - - QList result; - for (const QSharedPointer& app : d->applications) { - result << app->path(); - } - - return result; -} - -bool ApplicationManager::IsProcessExist(uint32_t pid) -{ - Q_D(const ApplicationManager); - - for (auto app : d->applications) { - for (auto instance : app->getAllInstances()) { - if (instance->getPid() == pid) { - return true; - } - } - } - - return false; -} - -#include "application_manager.moc" diff --git a/src/service/impl/application_manager.h b/src/service/impl/application_manager.h deleted file mode 100644 index 9bc788b..0000000 --- a/src/service/impl/application_manager.h +++ /dev/null @@ -1,96 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef A2862DC7_5DA3_4129_9796_671D88015BED -#define A2862DC7_5DA3_4129_9796_671D88015BED - -#include "../../modules/startmanager/startmanager.h" -#include "../../modules/socket/server.h" -#include "../../modules/methods/process_status.hpp" - -#include -#include -#include -#include -#include - -class Application; -class ApplicationInstance; -class ApplicationManagerPrivate : public QObject -{ - Q_OBJECT - ApplicationManager *q_ptr = nullptr; - Q_DECLARE_PUBLIC(ApplicationManager); - - QList> applications; - Socket::Server server; - std::multimap> tasks; - StartManager *startManager; - std::vector virtualMachines; - const std::string virtualMachePath; - const std::string section; - const std::string key; - -public: - ApplicationManagerPrivate(ApplicationManager *parent); - ~ApplicationManagerPrivate(); - - // 检测调用方身份 - bool checkDMsgUid(); - void init(); - -private: - void recvClientData(int socket, const std::vector &data); - - void write(int socket, const std::vector &data); - - void write(int socket, const std::string &data); - - void write(int socket, const char c); - - void processInstanceStatus(Methods::ProcessStatus instanceStatus); -}; - -class ApplicationManager : public QObject, public QDBusContext -{ - Q_OBJECT - Q_PROPERTY(QList instances READ instances) - Q_PROPERTY(QList list READ list) - QScopedPointer dd_ptr; - Q_DECLARE_PRIVATE_D(qGetPtrHelper(dd_ptr), ApplicationManager) - -public: - static ApplicationManager* instance(); - - void addApplication(const QList> &list); - void launchAutostartApps(); - void processInstanceStatus(Methods::ProcessStatus instanceStatus); - -Q_SIGNALS: - void AutostartChanged(const QString &status, const QString &filePath); - -public Q_SLOTS: - bool AddAutostart(const QString &desktop); - QStringList AutostartList(); - bool IsAutostart(const QString &fileName); - bool RemoveAutostart(const QString &fileName); - void Launch(const QString &desktopFile, bool withMsgCheck = true); - void LaunchApp(const QString &desktopFile, uint32_t timestamp, const QStringList &files, bool withMsgCheck = true); - void LaunchAppAction(const QString &desktopFile, const QString &action, uint32_t timestamp, bool withMsgCheck = true); - void LaunchAppWithOptions(const QString &desktopFile, uint32_t timestamp, const QStringList &files, QVariantMap options); - void RunCommand(const QString &exe, const QStringList &args); - void RunCommandWithOptions(const QString &exe, const QStringList &args, const QVariantMap &options); - -protected: - ApplicationManager(QObject *parent = nullptr); - ~ApplicationManager() override; - - QList instances() const; - QList list() const; - QDBusObjectPath GetInformation(const QString &id); - QList GetInstances(const QString &id); - bool IsProcessExist(uint32_t pid); -}; - -#endif /* A2862DC7_5DA3_4129_9796_671D88015BED */ diff --git a/src/service/main.cpp b/src/service/main.cpp deleted file mode 100644 index 33f4bbf..0000000 --- a/src/service/main.cpp +++ /dev/null @@ -1,156 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include - -#include "impl/application_manager.h" -#include "impl/application.h" -#include "manageradaptor.h" -#include "application1adaptor.h" -#include "applicationhelper.h" -#include "mime1adaptor.h" -#include "settings.h" -#include "dsysinfo.h" -#include "../modules/apps/appmanager.h" -#include "../modules/launcher/launchermanager.h" -#include "../modules/dock/dockmanager.h" -#include "../modules/startmanager/startmanager.h" -#include "../modules/mimeapp/mime_app.h" - -#include -#include -#include - -DCORE_USE_NAMESPACE - -#define ApplicationManagerServiceName "org.deepin.dde.Application1.Manager" -#define ApplicationManagerServicePath "/org/deepin/dde/Application1/Manager" -#define ApplicationManagerInterface "org.deepin.dde.Application1.Manager" - -QFileInfoList scan(const QString &path) -{ - QDir dir(path); - dir.setFilter(QDir::Files); - dir.setNameFilters({ "*.desktop" }); - return dir.entryInfoList(); -} - -// 扫描系统目录 -// 扫描用户目录 -QList> scanFiles() -{ - QList> applications; - auto apps = scan("/usr/share/applications/"); - for (const QFileInfo &info : apps) { - applications << QSharedPointer(new Application( - "freedesktop", - Application::Type::System, - QSharedPointer(new modules::ApplicationHelper::Helper(info.filePath())) - )); - } - - struct passwd *user = getpwent(); - while (user) { - auto userApps = scan(QString("%1/.local/share/applications/").arg(user->pw_dir)); - for (const QFileInfo &info : userApps) { - applications << QSharedPointer(new Application( - "freedesktop", - Application::Type::System, - QSharedPointer(new modules::ApplicationHelper::Helper(info.filePath())) - )); - } - user = getpwent(); - } - endpwent(); - auto linglong = scan("/persistent/linglong/entries/share/applications/"); - for (const QFileInfo &info : linglong) { - applications << QSharedPointer(new Application( - "linglong", - Application::Type::System, - QSharedPointer(new modules::ApplicationHelper::Helper(info.filePath())) - )); - } - - return applications; -} - -void init() -{ - // 从DConfig中读取当前的显示模式,如果为空,则认为是第一次进入(新安装的系统),否则,就认为系统之前已经进入设置过,直接返回即可 - QSharedPointer config(Settings::ConfigPtr("com.deepin.dde.dock")); - if (config.isNull() || !config->value("Display_Mode").toString().isEmpty()) - return; - - // 然后判断当前系统是否为社区版,社区版默认任务栏模式为时尚模式,其他版本默认为高效模式 - QString displayMode = DSysInfo::isCommunityEdition() ? QString("fashion") : QString("efficient"); - config->setValue("Display_Mode", displayMode); -} - -int main(int argc, char *argv[]) -{ - QCoreApplication app(argc, argv); - app.setOrganizationName("deepin"); - app.setApplicationName("dde-application-manager"); - - DLogManager::registerConsoleAppender(); - DLogManager::registerFileAppender(); - - QTranslator *translator = new QTranslator(); - translator->load(QString("/usr/share/dde-application-manager/translations/dde-application-manager_%1.qm").arg(QLocale::system().name())); - QCoreApplication::installTranslator(translator); - - // 初始化 - init(); - - new AppManager(ApplicationManager::instance()); - new LauncherManager(ApplicationManager::instance()); - new DockManager(ApplicationManager::instance()); - new ManagerAdaptor(ApplicationManager::instance()); - - QDBusConnection connection = QDBusConnection::sessionBus(); - if (!connection.registerService("org.deepin.dde.Application1")) { - qWarning() << "error: " << connection.lastError().message(); - return -1; - } - - if (!connection.registerService(ApplicationManagerServiceName)) { - qWarning() << "error: " << connection.lastError().message(); - return -1; - } - - if (!connection.registerObject(ApplicationManagerServicePath, ApplicationManagerInterface, ApplicationManager::instance())) { - qWarning() << "error: " << connection.lastError().message(); - return -1; - } - - QList> apps{ scanFiles() }; - QList> appAdapters; - for (const QSharedPointer app : apps) { - QSharedPointer adapter = QSharedPointer(new Application1Adaptor(app.get())); - appAdapters << adapter; - if (!connection.registerObject(app->path().path(), "org.deepin.dde.Application1", app.get())) { - qWarning() << "error: " << connection.lastError().message(); - continue; - } - } - - ApplicationManager::instance()->addApplication(apps); - - ApplicationManager::instance()->launchAutostartApps(); - - MimeApp* mimeApp = new MimeApp; - - new Mime1Adaptor(mimeApp); - if (!connection.registerService("org.deepin.dde.Mime1")) { - qWarning() << "error: " << connection.lastError().message(); - return -1; - } - - if (!connection.registerObject("/org/deepin/dde/Mime1", "org.deepin.dde.Mime1", mimeApp)) { - qWarning() << "error: " << connection.lastError().message(); - return -1; - } - - return app.exec(); -} diff --git a/src/utils/settings.cpp b/src/utils/settings.cpp deleted file mode 100644 index d683345..0000000 --- a/src/utils/settings.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "settings.h" - -#include -#include - -Settings::Settings() -{ - -} - -Settings::~Settings() -{ - -} - -DConfig *Settings::ConfigPtr(const QString &name, const QString &subpath, QObject *parent) -{ - DConfig *config = DConfig::create("dde-application-manager", name, subpath, parent); - if (!config) - return nullptr; - - if (config->isValid()) - return config; - - delete config; - qDebug() << "Cannot find dconfigs, name:" << name; - return nullptr; -} - -const QVariant Settings::ConfigValue(const QString &name, const QString &subPath, const QString &key, const QVariant &fallback) -{ - QSharedPointer config(ConfigPtr(name, subPath)); - if (config && config->isValid() && config->keyList().contains(key)) { - QVariant v = config->value(key); - return v; - } - - qDebug() << "Cannot find dconfigs, name:" << name - << " subPath:" << subPath << " key:" << key - << "Use fallback value:" << fallback; - return fallback; -} - -bool Settings::ConfigSaveValue(const QString &name, const QString &subPath, const QString &key, const QVariant &value) -{ - QSharedPointer config(ConfigPtr(name, subPath)); - if (config && config->isValid() && config->keyList().contains(key)) { - config->setValue(key, value); - return true; - } - - qDebug() << "Cannot find dconfigs, name:" << name - << " subPath:" << subPath << " key:" << key; - return false; -} diff --git a/src/utils/settings.h b/src/utils/settings.h deleted file mode 100644 index 2b80d3e..0000000 --- a/src/utils/settings.h +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef SETTINGS_H -#define SETTINGS_H - -#include - -#include -#include - -DCORE_USE_NAMESPACE - -// Dconfig 配置类 -class Settings -{ -public: - Settings(); - ~Settings(); - - static DConfig *ConfigPtr(const QString &name, const QString &subpath = QString(), QObject *parent = nullptr); - static const QVariant ConfigValue(const QString &name, const QString &subPath = QString(), const QString &key = QString(), const QVariant &fallback = QVariant()); - static bool ConfigSaveValue(const QString &name, const QString &subPath, const QString &key, const QVariant &value); -}; - -#endif // SETTINGS_H diff --git a/src/utils/synconfig.cpp b/src/utils/synconfig.cpp deleted file mode 100644 index 58d37b5..0000000 --- a/src/utils/synconfig.cpp +++ /dev/null @@ -1,100 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#include "synconfig.h" - -#include -#include -#include -#include -#include - -const QString syncDBusService = "org.deepin.dde.Sync1.Config"; -const QString syncDBusObject = "/org/deepin/dde/Sync1/Config"; -const QString syncDBusDaemonService = "com.deepin.sync.Daemon"; -const QString syncDBusDaemonObject = "/com/deepin/sync/Daemon"; -const QString syncDBusDaemonInterface = syncDBusDaemonService; - -QMap SynConfig::synModulesMap; - -SynConfig *SynConfig::instance(QObject *parent) -{ - static SynConfig synConfig(parent); - - return &synConfig; -} - -bool SynConfig::registe(QString moduleName, SynModuleBase *module) -{ - bool registed = false; - if (moduleName.size() > 0 && module) { - synModulesMap[moduleName] = module; - registed = true; - } - - return registed; -} - -QByteArray SynConfig::GetSyncConfig(QString moduleName) -{ - if (synModulesMap.find(moduleName) == synModulesMap.end()) - return {}; - - SynModuleBase *module = synModulesMap[moduleName]; - if (module) - return module->getSyncConfig(); - else - return {}; -} - -void SynConfig::SetSyncConfig(QString moduleName, QByteArray ba) -{ - if (synModulesMap.find(moduleName) == synModulesMap.end()) - return; - - SynModuleBase *module = synModulesMap[moduleName]; - if (module) { - module->setSyncConfig(ba); - } -} - -SynConfig::SynConfig(QObject *parent) - : QObject(parent) -{ - QDBusConnection con = QDBusConnection::sessionBus(); - if (!con.registerService(syncDBusService)) - { - qCritical() << "register service org.deepin.dde.Sync1.Config error:" << con.lastError().message(); - return; - } - - if (!con.registerObject(syncDBusObject, this, QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals)) - { - qCritical() << "register object /org/deepin/dde/Sync1/Config error:" << con.lastError().message(); - return; - } - - // 只注册一次 - registerOnSyncDaemon(); - // 关联com.deepin.sync.Daemon所有者变化 - QDBusConnectionInterface *ifc = QDBusConnection::sessionBus().interface(); - connect(ifc, &QDBusConnectionInterface::serviceOwnerChanged, this, [ & ](const QString & name, const QString & oldOwner, const QString & newOwner) { - Q_UNUSED(oldOwner) - if (name == syncDBusDaemonService && !newOwner.isEmpty()) { - this->registerOnSyncDaemon(); - } - }); -} - -SynConfig::~SynConfig() -{ - -} - -void SynConfig::registerOnSyncDaemon() -{ - QDBusInterface interface = QDBusInterface(syncDBusDaemonService, syncDBusDaemonObject, syncDBusDaemonInterface); - // 修改V20注册方式,需同步到deepin-deepinid-daemon - interface.call("Register", syncDBusService, syncDBusObject); -} diff --git a/src/utils/synconfig.h b/src/utils/synconfig.h deleted file mode 100644 index 066cfba..0000000 --- a/src/utils/synconfig.h +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef SYNCONFIG_H -#define SYNCONFIG_H - -#include "synmodulebase.h" - -#include -#include - -class SynConfig final : public QObject -{ - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "org.deepin.dde.Sync1.Config") -public: - // 实例 - static SynConfig *instance(QObject *parent = nullptr); - // 记录模块对应类信息 - static bool registe(QString moduleName, SynModuleBase *module); - -public Q_SLOTS: - // 获取配置信息 - QByteArray GetSyncConfig(QString moduleName); - // 设置配置信息 - void SetSyncConfig(QString moduleName, QByteArray ba); - -private: - explicit SynConfig(QObject *parent = nullptr); - ~SynConfig(); - - // 将本服务注册到com.deepin.sync.Daemon - void registerOnSyncDaemon(); - - static QMap synModulesMap; // 记录模块对应类 -}; - -#endif // SYNCONFIG_H diff --git a/src/utils/synmodule.h b/src/utils/synmodule.h deleted file mode 100644 index e9c0f47..0000000 --- a/src/utils/synmodule.h +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef SYNMODULE_H -#define SYNMODULE_H - -#include "synconfig.h" -#include - -class SynModule : public SynModuleBase, public QObject -{ -public: - explicit SynModule(QObject *parent = nullptr) : QObject(parent) {} - virtual ~SynModule() {} - - // 获取配置信息 - virtual QByteArray getSyncConfig() = 0; - // 设置配置信息 - virtual void setSyncConfig(QByteArray ba) = 0; - // 注册配置模块 - virtual bool registeModule(QString moduleName) final {return SynConfig::instance(this)->registe(moduleName, this);} -}; - -#endif // SYNMODULE_H diff --git a/src/utils/synmodulebase.h b/src/utils/synmodulebase.h deleted file mode 100644 index 424f54f..0000000 --- a/src/utils/synmodulebase.h +++ /dev/null @@ -1,27 +0,0 @@ -// SPDX-FileCopyrightText: 2018 - 2023 UnionTech Software Technology Co., Ltd. -// -// SPDX-License-Identifier: GPL-3.0-or-later - -#ifndef SYNMODULEBASE_H -#define SYNMODULEBASE_H - -#include -#include -#include - -// 同步配置基类 -class SynModuleBase -{ -public: - SynModuleBase() {} - virtual ~SynModuleBase() {} - - // 获取配置信息 - virtual QByteArray getSyncConfig() = 0; - // 设置配置信息 - virtual void setSyncConfig(QByteArray ba) = 0; -}; - - - -#endif // SYNCONFIGBASE_H diff --git a/translate_generation.sh b/translate_generation.sh deleted file mode 100755 index c908092..0000000 --- a/translate_generation.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash -# this file is used to auto-generate .qm file from .ts file. -# author: shibowen at linuxdeepin.com - -ts_list=(`ls translations/*.ts`) - -for ts in "${ts_list[@]}" -do - printf "\nprocess ${ts}\n" - lrelease "${ts}" -done diff --git a/translations/dde-application-manager.ts b/translations/dde-application-manager.ts deleted file mode 100644 index ea0e41b..0000000 --- a/translations/dde-application-manager.ts +++ /dev/null @@ -1,42 +0,0 @@ - - - - - Entry - - Open - Open - - - Close All - Close All - - - Force Quit - Force Quit - - - Dock - Dock - - - Undock - Undock - - - All Windows - All Windows - - - - Launcher - - Removed successfully - - - - Failed to remove the app - - - - diff --git a/translations/dde-application-manager_ar.ts b/translations/dde-application-manager_ar.ts deleted file mode 100644 index 4dddbbf..0000000 --- a/translations/dde-application-manager_ar.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - فتح - - - Close All - إغلاق الكل - - - Force Quit - الخروج بالقوة - - - Dock - الرف - - - Undock - إلغاء الإرساء - - - All Windows - كل النوافذ - - - \ No newline at end of file diff --git a/translations/dde-application-manager_az.ts b/translations/dde-application-manager_az.ts deleted file mode 100644 index ae11983..0000000 --- a/translations/dde-application-manager_az.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Açın - - - Close All - Hamısını bağlamaq - - - Force Quit - Məcburi çıxış - - - Dock - Dok panel - - - Undock - Ayırmaq - - - All Windows - Bütün Pəncərələr - - - \ No newline at end of file diff --git a/translations/dde-application-manager_bo.ts b/translations/dde-application-manager_bo.ts deleted file mode 100644 index 9823f31..0000000 --- a/translations/dde-application-manager_bo.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - ཁ་ཕྱེ་བ། - - - Close All - ཆ་ཚང་སྒོ་རྒྱོབ། - - - Force Quit - བཙན་ཤེད་ཀྱིས་དོན་དུ་བཅུག་པ། - - - Dock - སྡོད་པ། - - - Undock - བསྡད་པ་གཙང་སེལ། - - - All Windows - སྒེའུ་ཁུང་ཆ་ཚང་། - - - \ No newline at end of file diff --git a/translations/dde-application-manager_ca.ts b/translations/dde-application-manager_ca.ts deleted file mode 100644 index d981c9a..0000000 --- a/translations/dde-application-manager_ca.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Obre - - - Close All - Tanca-ho tot - - - Force Quit - Força'n la sortida - - - Dock - Acoblador - - - Undock - Treu de l'acoblador - - - All Windows - Totes les finestres - - - \ No newline at end of file diff --git a/translations/dde-application-manager_cs.ts b/translations/dde-application-manager_cs.ts deleted file mode 100644 index 74f4861..0000000 --- a/translations/dde-application-manager_cs.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Otevřít - - - Close All - Zavřít vše - - - Force Quit - Vynutit ukončení - - - Dock - Panel - - - Undock - Zrušit ukotvení - - - All Windows - Všechna okna - - - \ No newline at end of file diff --git a/translations/dde-application-manager_da.ts b/translations/dde-application-manager_da.ts deleted file mode 100644 index 0ebf0f5..0000000 --- a/translations/dde-application-manager_da.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Åbn - - - Close All - Luk alle - - - Force Quit - Gennemtving afslut - - - Dock - Dok - - - Undock - Fjern fra dok - - - All Windows - Alle vinduer - - - \ No newline at end of file diff --git a/translations/dde-application-manager_de.ts b/translations/dde-application-manager_de.ts deleted file mode 100644 index f39cd0b..0000000 --- a/translations/dde-application-manager_de.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Öffnen - - - Close All - Alle schließen - - - Force Quit - Beenden erzwingen - - - Dock - Dock - - - Undock - Abdocken - - - All Windows - Alle Fenster - - - \ No newline at end of file diff --git a/translations/dde-application-manager_el.ts b/translations/dde-application-manager_el.ts deleted file mode 100644 index 9186f01..0000000 --- a/translations/dde-application-manager_el.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Άνοιγμα - - - Close All - Κλείσιμο Όλων - - - Force Quit - Δυναμικό Κλείσιμο - - - Dock - Προσθήκη στην γραμμή εργασιών - - - Undock - Αφαίρεση από την γραμμή εργασιών - - - All Windows - Όλα τα Παράθυρα - - - \ No newline at end of file diff --git a/translations/dde-application-manager_en.ts b/translations/dde-application-manager_en.ts deleted file mode 100644 index 0432da0..0000000 --- a/translations/dde-application-manager_en.ts +++ /dev/null @@ -1,40 +0,0 @@ - - - Entry - - Open - Open - - - Close All - Close All - - - Force Quit - Force Quit - - - Dock - Dock - - - Undock - Undock - - - All Windows - All Windows - - - - Launcher - - Removed successfully - Removed successfully - - - Failed to remove the app - Failed to remove the app - - - \ No newline at end of file diff --git a/translations/dde-application-manager_en_AU.ts b/translations/dde-application-manager_en_AU.ts deleted file mode 100644 index b890d06..0000000 --- a/translations/dde-application-manager_en_AU.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Open - - - Close All - Close All - - - Force Quit - Force Quit - - - Dock - Dock - - - Undock - Undock - - - All Windows - All Windows - - - \ No newline at end of file diff --git a/translations/dde-application-manager_en_US.ts b/translations/dde-application-manager_en_US.ts deleted file mode 100644 index cfd0107..0000000 --- a/translations/dde-application-manager_en_US.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Open - - - Close All - Close All - - - Force Quit - Force Quit - - - Dock - Dock - - - Undock - Undock - - - All Windows - All Windows - - - \ No newline at end of file diff --git a/translations/dde-application-manager_es.ts b/translations/dde-application-manager_es.ts deleted file mode 100644 index e181f9e..0000000 --- a/translations/dde-application-manager_es.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Abrir - - - Close All - Cerrar todo - - - Force Quit - Forzar cierre - - - Dock - Anclar - - - Undock - Desanclar - - - All Windows - Todas las ventanas - - - \ No newline at end of file diff --git a/translations/dde-application-manager_fa.ts b/translations/dde-application-manager_fa.ts deleted file mode 100644 index d9e38a0..0000000 --- a/translations/dde-application-manager_fa.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - باز کردن - - - Close All - بستن همه - - - Force Quit - خروج اجباری - - - Dock - داک - - - Undock - باز کردن از داک - - - All Windows - همه پنجره ها - - - \ No newline at end of file diff --git a/translations/dde-application-manager_fi.ts b/translations/dde-application-manager_fi.ts deleted file mode 100644 index 9ebcbab..0000000 --- a/translations/dde-application-manager_fi.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Avaa - - - Close All - Sulje kaikki - - - Force Quit - Pakota lopetus - - - Dock - Telakka - - - Undock - Poista - - - All Windows - Kaikki ikkunat - - - \ No newline at end of file diff --git a/translations/dde-application-manager_fr.ts b/translations/dde-application-manager_fr.ts deleted file mode 100644 index bc28ddd..0000000 --- a/translations/dde-application-manager_fr.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Ouvrir - - - Close All - Fermer tout - - - Force Quit - Forcer à quitter - - - Dock - Dock - - - Undock - Détacher du dock - - - All Windows - Toutes les fenêtres - - - \ No newline at end of file diff --git a/translations/dde-application-manager_gl_ES.ts b/translations/dde-application-manager_gl_ES.ts deleted file mode 100644 index 2a3111b..0000000 --- a/translations/dde-application-manager_gl_ES.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Abrir - - - Close All - Pechar todo - - - Force Quit - Forzar a saída - - - Dock - Doca - - - Undock - Quitar da doca - - - All Windows - Todas as xanelas - - - \ No newline at end of file diff --git a/translations/dde-application-manager_hu.ts b/translations/dde-application-manager_hu.ts deleted file mode 100644 index 0601f4b..0000000 --- a/translations/dde-application-manager_hu.ts +++ /dev/null @@ -1,40 +0,0 @@ - - - Entry - - Open - Megnyitás - - - Close All - Összes bezárása - - - Force Quit - Kényszerített kilépés - - - Dock - Kitűzés a Dokkolóra - - - Undock - Eltávolítás a Dokkolóról - - - All Windows - Összes ablak - - - - Launcher - - Removed successfully - Sikeresen eltávolítva - - - Failed to remove the app - Az alkalmazás eltávolítása sikertelen - - - \ No newline at end of file diff --git a/translations/dde-application-manager_it.ts b/translations/dde-application-manager_it.ts deleted file mode 100644 index 69ed1a8..0000000 --- a/translations/dde-application-manager_it.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Apri - - - Close All - Chiudi tutto - - - Force Quit - Forza chiusura - - - Dock - Dock - - - Undock - Sgancia - - - All Windows - Tutte le finestre - - - \ No newline at end of file diff --git a/translations/dde-application-manager_ja.ts b/translations/dde-application-manager_ja.ts deleted file mode 100644 index 89b421d..0000000 --- a/translations/dde-application-manager_ja.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - 開く - - - Close All - すべて閉じる - - - Force Quit - 強制終了 - - - Dock - ドック - - - Undock - ドックから外す - - - All Windows - すべてのウィンドウ - - - \ No newline at end of file diff --git a/translations/dde-application-manager_kab.ts b/translations/dde-application-manager_kab.ts deleted file mode 100644 index c31e2c4..0000000 --- a/translations/dde-application-manager_kab.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Ldi - - - Close All - Mdel akk - - - Force Quit - Ḥettem tuffɣa - - - Dock - - - - Undock - Kkes asekkeṛ - - - All Windows - Akk isfuyla - - - \ No newline at end of file diff --git a/translations/dde-application-manager_ko.ts b/translations/dde-application-manager_ko.ts deleted file mode 100644 index 01a2b74..0000000 --- a/translations/dde-application-manager_ko.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - 열기 - - - Close All - 모두 닫기 - - - Force Quit - 강제 종료 - - - Dock - 도구집 - - - Undock - 도구집 해제 - - - All Windows - 모든 창 - - - \ No newline at end of file diff --git a/translations/dde-application-manager_lt.ts b/translations/dde-application-manager_lt.ts deleted file mode 100644 index 5219a37..0000000 --- a/translations/dde-application-manager_lt.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Atverti - - - Close All - Užverti visus - - - Force Quit - Priverstinai išjungti - - - Dock - Dokas - - - Undock - Atskirti nuo doko - - - All Windows - Visi langai - - - \ No newline at end of file diff --git a/translations/dde-application-manager_ms.ts b/translations/dde-application-manager_ms.ts deleted file mode 100644 index e26c13a..0000000 --- a/translations/dde-application-manager_ms.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Buka - - - Close All - Tutup Semua - - - Force Quit - Paksa Keluar - - - Dock - Labuh - - - Undock - Tanggal - - - All Windows - Semua Tetingkap - - - \ No newline at end of file diff --git a/translations/dde-application-manager_nl.ts b/translations/dde-application-manager_nl.ts deleted file mode 100644 index b481ab3..0000000 --- a/translations/dde-application-manager_nl.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Openen - - - Close All - Alles sluiten - - - Force Quit - Afsluiten forceren - - - Dock - Vastmaken - - - Undock - Losmaken - - - All Windows - Alle vensters - - - \ No newline at end of file diff --git a/translations/dde-application-manager_pl.ts b/translations/dde-application-manager_pl.ts deleted file mode 100644 index 9840058..0000000 --- a/translations/dde-application-manager_pl.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Otwórz - - - Close All - Zamknij wszystkie - - - Force Quit - Wymuś zakończenie - - - Dock - Dodaj do doku - - - Undock - Odepnij - - - All Windows - Wszystkie okna - - - \ No newline at end of file diff --git a/translations/dde-application-manager_pt.ts b/translations/dde-application-manager_pt.ts deleted file mode 100644 index fa65c3e..0000000 --- a/translations/dde-application-manager_pt.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Abrir - - - Close All - Fechar tudo - - - Force Quit - Forçar fecho - - - Dock - Afixar na doca - - - Undock - Remover da doca - - - All Windows - Todas as janelas - - - \ No newline at end of file diff --git a/translations/dde-application-manager_pt_BR.ts b/translations/dde-application-manager_pt_BR.ts deleted file mode 100644 index c215fd1..0000000 --- a/translations/dde-application-manager_pt_BR.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Abrir - - - Close All - Fechar Tudo - - - Force Quit - Forçar Saída - - - Dock - Dock - - - Undock - Remover da Dock - - - All Windows - Todas as Janelas - - - \ No newline at end of file diff --git a/translations/dde-application-manager_ro.ts b/translations/dde-application-manager_ro.ts deleted file mode 100644 index 98280d7..0000000 --- a/translations/dde-application-manager_ro.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Deschide - - - Close All - Închide Tot - - - Force Quit - Închidere forţată - - - Dock - Dock - - - Undock - Detaşaţi - - - All Windows - Toate Ferestrele - - - \ No newline at end of file diff --git a/translations/dde-application-manager_ru.ts b/translations/dde-application-manager_ru.ts deleted file mode 100644 index 1a44146..0000000 --- a/translations/dde-application-manager_ru.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Открыть - - - Close All - Закрыть Всё - - - Force Quit - Принудительный Выход - - - Dock - Закрепить - - - Undock - Открепить - - - All Windows - Все Окна - - - \ No newline at end of file diff --git a/translations/dde-application-manager_si.ts b/translations/dde-application-manager_si.ts deleted file mode 100644 index 171c5a6..0000000 --- a/translations/dde-application-manager_si.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - විවෘත කරන්න - - - Close All - සියල්ල වසා දමන්න - - - Force Quit - බලෙන් ඉවත් වන්න - - - Dock - ඩොක් එක - - - Undock - අහෝසි කරන්න - - - All Windows - සියලුම කවුළු - - - \ No newline at end of file diff --git a/translations/dde-application-manager_sk.ts b/translations/dde-application-manager_sk.ts deleted file mode 100644 index 7c94245..0000000 --- a/translations/dde-application-manager_sk.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Otvoriť - - - Close All - Zavrieť všetko - - - Force Quit - Nútené ukončenie - - - Dock - Panel - - - Undock - Odopnúť z panela - - - All Windows - Všetky okná - - - \ No newline at end of file diff --git a/translations/dde-application-manager_sl.ts b/translations/dde-application-manager_sl.ts deleted file mode 100644 index ad8b3a0..0000000 --- a/translations/dde-application-manager_sl.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Odpri - - - Close All - Zapri vse - - - Force Quit - Prisili zapiranje - - - Dock - Zasidraj - - - Undock - Odsidraj - - - All Windows - Vsa okna - - - \ No newline at end of file diff --git a/translations/dde-application-manager_sq.ts b/translations/dde-application-manager_sq.ts deleted file mode 100644 index 8c714e4..0000000 --- a/translations/dde-application-manager_sq.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Hape - - - Close All - Mbylli Krejt - - - Force Quit - Detyro Dalje - - - Dock - Vëre në panel - - - Undock - Hiqe nga paneli - - - All Windows - Tërë Dritaret - - - \ No newline at end of file diff --git a/translations/dde-application-manager_sr.ts b/translations/dde-application-manager_sr.ts deleted file mode 100644 index dea14cc..0000000 --- a/translations/dde-application-manager_sr.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Покрени - - - Close All - Затвори све - - - Force Quit - Принудно изађи - - - Dock - Закачи - - - Undock - Откачи - - - All Windows - Сви прозори - - - \ No newline at end of file diff --git a/translations/dde-application-manager_tr.ts b/translations/dde-application-manager_tr.ts deleted file mode 100644 index b7b9aeb..0000000 --- a/translations/dde-application-manager_tr.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - - - - Close All - Tümünü Kapat - - - Force Quit - Zorla Çık - - - Dock - Rıhtım - - - Undock - Ayır - - - All Windows - Tüm Pencereler - - - \ No newline at end of file diff --git a/translations/dde-application-manager_ug.ts b/translations/dde-application-manager_ug.ts deleted file mode 100644 index 6ba3bd6..0000000 --- a/translations/dde-application-manager_ug.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - ئېچىش - - - Close All - ھەممىسىنى ئۆچۈرۈش - - - Force Quit - مەجبۇرىي چېكىنىش - - - Dock - ۋەزىپە ئىستونى - - - Undock - قالدۇقلىرىنى چىقىرىۋېتىش - - - All Windows - بارلىق كۆزنەكلەر - - - \ No newline at end of file diff --git a/translations/dde-application-manager_uk.ts b/translations/dde-application-manager_uk.ts deleted file mode 100644 index 01c2f04..0000000 --- a/translations/dde-application-manager_uk.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Відкрити - - - Close All - Закрити всі - - - Force Quit - Примусово Вийти - - - Dock - Док - - - Undock - Розстикуватись - - - All Windows - Усі вікна - - - \ No newline at end of file diff --git a/translations/dde-application-manager_vi.ts b/translations/dde-application-manager_vi.ts deleted file mode 100644 index 204e90a..0000000 --- a/translations/dde-application-manager_vi.ts +++ /dev/null @@ -1,29 +0,0 @@ - - - Entry - - Open - Mở - - - Close All - Đóng tất cả - - - Force Quit - Buộc đóng - - - Dock - Dock - - - Undock - Gỡ khỏi dock - - - All Windows - Tất cả Cửa sổ - - - \ No newline at end of file diff --git a/translations/dde-application-manager_zh_CN.ts b/translations/dde-application-manager_zh_CN.ts deleted file mode 100644 index 41134d0..0000000 --- a/translations/dde-application-manager_zh_CN.ts +++ /dev/null @@ -1,40 +0,0 @@ - - - Entry - - Open - 打开 - - - Close All - 关闭所有 - - - Force Quit - 强制退出 - - - Dock - 驻留 - - - Undock - 移除驻留 - - - All Windows - 所有窗口 - - - - Launcher - - Removed successfully - 卸载成功 - - - Failed to remove the app - 卸载失败 - - - \ No newline at end of file diff --git a/translations/dde-application-manager_zh_HK.ts b/translations/dde-application-manager_zh_HK.ts deleted file mode 100644 index 58af47f..0000000 --- a/translations/dde-application-manager_zh_HK.ts +++ /dev/null @@ -1,40 +0,0 @@ - - - Entry - - Open - 打開 - - - Close All - 關閉所有 - - - Force Quit - 強制退出 - - - Dock - 駐留 - - - Undock - 移除駐留 - - - All Windows - 所有窗口 - - - - Launcher - - Removed successfully - 卸載成功 - - - Failed to remove the app - 卸載失敗 - - - \ No newline at end of file diff --git a/translations/dde-application-manager_zh_TW.ts b/translations/dde-application-manager_zh_TW.ts deleted file mode 100644 index aef9acc..0000000 --- a/translations/dde-application-manager_zh_TW.ts +++ /dev/null @@ -1,40 +0,0 @@ - - - Entry - - Open - 打開 - - - Close All - 關閉所有 - - - Force Quit - 強制退出 - - - Dock - 駐留 - - - Undock - 移除駐留 - - - All Windows - 所有視窗 - - - - Launcher - - Removed successfully - 移除成功 - - - Failed to remove the app - 移除失敗 - - - \ No newline at end of file