pax_global_header00006660000000000000000000000064152236367560014531gustar00rootroot0000000000000052 comment=a5fe4da66943c599023fc90407c545c08a6f5a7d ukui-window-switch-4.21.1.0/000077500000000000000000000000001522363675600155355ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/.gitignore000066400000000000000000000002311522363675600175210ustar00rootroot00000000000000# Ignore the following files .vscode /build*/ /cmake-build* *.user *.qm CMakeLists.txt.user* windowsview/globalconfig.h # debian files obj-*-linux-gnu/ ukui-window-switch-4.21.1.0/.vscode/000077500000000000000000000000001522363675600170765ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/.vscode/settings.json000066400000000000000000000002141522363675600216260ustar00rootroot00000000000000{ "files.associations": { "*.tcc": "cpp", "fstream": "cpp", "thread": "cpp", "qgsettings": "cpp" } }ukui-window-switch-4.21.1.0/CMakeLists.txt000066400000000000000000000013111522363675600202710ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.16) project(ukui-window-switch) find_package(PkgConfig) find_package(QT NAMES Qt6 Qt5 COMPONENTS Core Gui REQUIRED) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core Gui REQUIRED) if (QT_VERSION_MAJOR EQUAL "5") set(KF_VERSION_MAJOR "5") find_package(KF5CoreAddons REQUIRED) find_package(KF5WindowSystem REQUIRED) pkg_check_modules(QGSettings REQUIRED gsettings-qt) elseif (QT_VERSION_MAJOR EQUAL "6") set(KF_VERSION_MAJOR "6") find_package(KF6CoreAddons REQUIRED) find_package(KF6WindowSystem REQUIRED) pkg_check_modules(QGSettings REQUIRED gsettings-qt6) endif() include_directories(${QGSettings_INCLUDE_DIRS}) add_subdirectory(windowsview)ukui-window-switch-4.21.1.0/COPYING000066400000000000000000000614471522363675600166040ustar00rootroot00000000000000 GNU LIBRARY GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the library GPL. It is numbered 2 because it goes with version 2 of the ordinary GPL.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Library General Public License, applies to some specially designated Free Software Foundation software, and to any other libraries whose authors decide to use it. You can use it for your libraries, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library, or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link a program with the library, you must provide complete object files to the recipients so that they can relink them with the library, after making changes to the library and recompiling it. And you must show them these terms so they know their rights. Our method of protecting your rights has two steps: (1) copyright the library, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the library. Also, for each distributor's protection, we want to make certain that everyone understands that there is no warranty for this free library. If the library is modified by someone else and passed on, we want its recipients to know that what they have is not the original version, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that companies distributing free software will individually obtain patent licenses, thus in effect transforming the program into proprietary software. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License, which was designed for utility programs. This license, the GNU Library General Public License, applies to certain designated libraries. This license is quite different from the ordinary one; be sure to read it in full, and don't assume that anything in it is the same as in the ordinary license. The reason we have a separate public license for some libraries is that they blur the distinction we usually make between modifying or adding to a program and simply using it. Linking a program with a library, without changing the library, is in some sense simply using the library, and is analogous to running a utility program or application program. However, in a textual and legal sense, the linked executable is a combined work, a derivative of the original library, and the ordinary General Public License treats it as such. Because of this blurred distinction, using the ordinary General Public License for libraries did not effectively promote software sharing, because most developers did not use the libraries. We concluded that weaker conditions might promote sharing better. However, unrestricted linking of non-free programs would deprive the users of those programs of all benefit from the free status of the libraries themselves. This Library General Public License is intended to permit developers of non-free programs to use free libraries, while preserving your freedom as a user of such programs to change the free libraries that are incorporated in them. (We have not seen how to achieve this as regards changes in header files, but we have achieved it as regards changes in the actual functions of the Library.) The hope is that this will lead to faster development of free libraries. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, while the latter only works together with the library. Note that it is possible for a library to be covered by the ordinary General Public License rather than by this special one. GNU LIBRARY GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Library General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also compile or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. c) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. d) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Library General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! ukui-window-switch-4.21.1.0/README.md000066400000000000000000000072611522363675600170220ustar00rootroot00000000000000# ukui-window-switch ukui-window-switch is a MultitaskView runs in Kylin Operating System. ## Introduction MultitaskView supports both PC and Pad. - PC MultitaskView provides a convenient and fast interactive interface, which makes it convenient to switch between virtual desktops and locate the window you want, so as to improve your production efficiency and working efficiency. - Pad MultitaskView is convenient to manage the opened windows, it also improves interactive experience through different animations. In Pad mode, you can choose to wake up or close any windows shown in MultitaskView. ## Features Common features of multitaskView: 1. Loaded as a plugin of kwin; 2. Run with compositor; - PC The following are the features of the MultitaskView in PC mode: 1. Add the functions of creating, deleting, exchanging virtual desktop and managing window content in virtual desktop; 2. The window is of equal height and slides up and down, and one line places the window with the greatest possibility; 3. Support small window dragging to different virtual desktops; 4. Dual screen mode adaptation; - Pad 1. Display the contents of the window with equal height and width, and can only slide left and right; 2. Add all clear function; 3. Support sliding up, closing, arousing, closing, arousing and other dynamic effects; 4. Adapt to different system modes and desktop states; ## Requirements Please use the version after 0430 for ukui panel and kwin. ## Installation Obtain the package (ukui-window-switch) of MultitaskView from the warehouse source and execute "sudo apt install ukui-window-switch". Please ensure that the installed version meets the installation conditions of the new version!!!! ## Usage [Open operation mode] 1. Slide from the bottom of the screen to bring up the MultitaskView; 2. Click the second button on the left side of the taskbar to evoke the MultitaskView; 3. Win + Tab shortcut key evokes MultitaskView; [Close operation mode] 1. When the MultitaskView is open, click ESC to close the MultitaskView; 2. When the MultitaskView is open, click the blank space of the MultitaskView to close the MultitaskView; 3. When the MultitaskView is open, use the shortcut key "menu + Tab" to close the MultitaskView; 4. In PC mode only and MultitaskView is on, click virtual desktop to close MultitaskView; 5. When the MultitaskView is open, click the thumbnail window to close the MultitaskView; 6. Passively trigger to close the MultitaskView. When a new window is activated, the MultitaskView will be closed automatically; ## Development The MultitaskView is divided into two parts: the view module is developed with QML language and the backend is developed with C++ language. The view module is divided into PC mode and Pad mode. The development and commissioning shall be carried out according to the following steps: 1. cd ukui-window-switch 2. mkdir build 3. cd build 4. cmake .. 5. sudo make install 6. kwin --replace & ## Debuglog The log is stored in the log of kwin. The viewing method is as follows: 1. cd ~/.log (or cd .config/kwin/log) 2. tail -f kwin_0.log ## Changelog You can view the record of each change in the changelog in Debian directory. ## FAQ 1. The MultitaskView always shows no application window? Please ensure that the current version of kwin is installed correctly 2. Shortcut keys cannot evoke MultitaskView? rm -rf ~/.config/kglobalshortcutsrc reboot 3. Does the MultitaskView provide a DBUS interface and how to use it? Please use d-feet In the session, find "org.kde.kwin" -> "/MultitaskView" -> org.kde.kWin.MultitaskView->show() Please ensure that the installed versions of kwin and ukui panel support the new version of multitask ukui-window-switch-4.21.1.0/man/000077500000000000000000000000001522363675600163105ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/man/ukui-window-switch-wlcom.1000066400000000000000000000013511522363675600232720ustar00rootroot00000000000000.\" Man Page for ukui-window-switch-wlcom .TH ukui-window-switch-wlcom 1 "15 Oct 2025" "UKUI Desktop Environment" .SH "NAME" ukui-window-switch-wlcom - use it to switch windows on Wayland compositor .SH "SYNOPSIS" Open the multitaskView. .SH "DESCRIPTION" The user can press the win+tab key to open the multitaskView. User can used it to delete or activate other windows, and it can also be used to control the workspace. .TP \fB --show-workspace\fR Open the multitaskView. .SH "BUGS" .SS Should you encounter any bugs, they may be reported at: https://gitee.com/openkylin/ukui-window-switch/issues .SH "AUTHORS" .SS This Manual Page has been written for the UKUI Desktop Environment by: zy (2025) ukui-window-switch-4.21.1.0/man/ukui-window-switch.1000066400000000000000000000013041522363675600221510ustar00rootroot00000000000000.\" Man Page for ukui-window-switch .TH ukui-window-switch 1 "26 July 2023" "UKUI Desktop Environment" .SH "NAME" ukui-window-switch - use it to switch windows .SH "SYNOPSIS" Open the multitaskView. .SH "DESCRIPTION" The user can press the win+tab key to open the multitaskView. User can used it to delete or activate other windows, and it can also be used to control the workspace. .TP \fB --show-workspace\fR Open the multitaskView. .SH "BUGS" .SS Should you encounter any bugs, they may be reported at: https://gitee.com/openkylin/ukui-window-switch/issues .SH "AUTHORS" .SS This Manual Page has been written for the UKUI Desktop Environment by: Dian Jiao (2023) ukui-window-switch-4.21.1.0/windowsview/000077500000000000000000000000001522363675600201225ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/CMakeLists.txt000066400000000000000000000022671522363675600226710ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.16) find_package(QT NAMES Qt6 Qt5 COMPONENTS LinguistTools REQUIRED) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS LinguistTools REQUIRED) file(GLOB TS_FILES translations/*.ts) set_source_files_properties(${TS_FILES} PROPERTIES OUTPUT_LOCATION ${CMAKE_CURRENT_BINARY_DIR}/translations) if (QT_VERSION_MAJOR EQUAL "5") qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/ukui-window-switch-wlcom ${CMAKE_CURRENT_SOURCE_DIR}/qml ${TS_FILES} OPTIONS -no-obsolete -no-ui-lines) elseif (QT_VERSION_MAJOR EQUAL "6") qt_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/ukui-window-switch-wlcom ${CMAKE_CURRENT_SOURCE_DIR}/qml ${TS_FILES} OPTIONS -no-obsolete -no-ui-lines) endif() add_custom_target(generate_qm ALL DEPENDS ${QM_FILES}) set(TRANSLATION_DIR "/usr/share/ukui-window-switch/translations/") add_compile_definitions(TRANSLATION_DIR="${TRANSLATION_DIR}") add_subdirectory(ukui-window-switch-wlcom) install(FILES ukui-window-switch DESTINATION /usr/bin/) install(FILES ukui-window-switch.desktop DESTINATION /etc/xdg/autostart/) install(FILES ${QM_FILES} DESTINATION ${TRANSLATION_DIR}) ukui-window-switch-4.21.1.0/windowsview/appwindowfiltermodel.cpp000066400000000000000000000044711522363675600250730ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: zy-yuan1 * */ #include "appwindowfiltermodel.h" #include AppWindowFilterModel::AppWindowFilterModel(QObject *parent) : QSortFilterProxyModel(parent) { setFilterRole(AppWindowListModel::DesktopsId); } void AppWindowFilterModel::setSourceModel(QAbstractItemModel *sourceModel) { m_sourceModel = qobject_cast(sourceModel); QSortFilterProxyModel::setSourceModel(sourceModel); connect(sourceModel, &QAbstractItemModel::dataChanged, this, &AppWindowFilterModel::onDataChanged); } int AppWindowFilterModel::desktopId() const { return m_desktopId; } void AppWindowFilterModel::setDesktopId(const int id) { if (m_desktopId == id) { return; } m_desktopId = id; invalidate(); } int AppWindowFilterModel::screenId() const { return m_screenId; } void AppWindowFilterModel::setScreenId(const int id) { if (m_screenId == id) { return; } m_screenId = id; invalidate(); } bool AppWindowFilterModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { QList desktopsId = m_sourceModel->index(source_row, 0, source_parent).data(AppWindowListModel::Role::DesktopsId).value >(); int screenId = m_sourceModel->index(source_row, 0, source_parent).data(AppWindowListModel::Role::ScreenId).toUInt(); return desktopsId.contains(m_desktopId) && screenId == m_screenId; } void AppWindowFilterModel::onDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles) { Q_EMIT dataChanged(mapFromSource(topLeft), mapFromSource(bottomRight), roles); } ukui-window-switch-4.21.1.0/windowsview/appwindowfiltermodel.h000066400000000000000000000034031522363675600245320ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: zy-yuan1 * */ #ifndef APPWINDOWFILTERMODEL_H #define APPWINDOWFILTERMODEL_H #include #include #include "appwindowlistmodel.h" class AppWindowFilterModel : public QSortFilterProxyModel { Q_OBJECT Q_PROPERTY(int desktopId READ desktopId WRITE setDesktopId) Q_PROPERTY(int screenId READ screenId WRITE setScreenId) public: explicit AppWindowFilterModel(QObject *parent = nullptr); ~AppWindowFilterModel() = default; Q_INVOKABLE void setSourceModel(QAbstractItemModel *sourceModel) override; int desktopId() const; void setDesktopId(const int id); int screenId() const; void setScreenId(const int id); protected: bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; private: void onDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles = QVector()); AppWindowListModel *m_sourceModel = nullptr; int m_desktopId = 1; int m_screenId = 0; }; #endif // APPWINDOWFILTERMODEL_H ukui-window-switch-4.21.1.0/windowsview/appwindowlistmodel.cpp000066400000000000000000000211431522363675600245540ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: zy-yuan1 * */ #include "appwindowlistmodel.h" #include "windowmanagerinterface.h" #include #include AppWindowListModel::AppWindowListModel(QObject *parent) : QAbstractListModel(parent) { connectSignals(); loadWindows(); } void AppWindowListModel::connectSignals() { QObject::connect(WindowManagerInterface::getInstance(), &WindowManagerInterface::appWindowRemoved, this, &AppWindowListModel::onAppWindowRemoved); QObject::connect(WindowManagerInterface::getInstance(), &WindowManagerInterface::appWindowDesktopChanged, this, &AppWindowListModel::onAppWindowDesktopChanged); QObject::connect(WindowManagerInterface::getInstance(), &WindowManagerInterface::desktopMoved, this, &AppWindowListModel::onDesktopMoved); QObject::connect(WindowManagerInterface::getInstance(), &WindowManagerInterface::desktopRemoved, this, &AppWindowListModel::onDesktopRemoved); QObject::connect(WindowManagerInterface::getInstance(), &WindowManagerInterface::appWindowAdd, this, &AppWindowListModel::onAppWindowAdd); QObject::connect(WindowManagerInterface::getInstance(), &WindowManagerInterface::appWindowActivated, this, &AppWindowListModel::onAppWindowActived); QObject::connect(WindowManagerInterface::getInstance(), &WindowManagerInterface::appWindowUpdated, this, &AppWindowListModel::onAppWindowUpdated); } int AppWindowListModel::rowCount(const QModelIndex &parent) const { return m_windowList.count(); } QVariant AppWindowListModel::data(const QModelIndex &index, int role) const { int i = index.row(); if (i < 0 || i >= m_windowList.count()) { return QVariant(); } Window window = m_windowList.at(i); switch (static_cast(role)) { case Role::Id: return window.id(); case Role::Uuid: return window.uuid(); case Role::Caption: return window.caption(); case Role::X: return window.x(); case Role::Y: return window.y(); case Role::Width: return window.width(); case Role::Height: return window.height(); case Role::Minimized: return window.minimized(); case Role::DesktopsId: return QVariant::fromValue >(window.desktopsId()); case Role::ScreenId: return window.screenId(); case Role::Icon: return window.icon(); default: return {}; } } bool AppWindowListModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (!index.isValid()) { return false; } if (role == Role::DesktopsId) { m_windowList[index.row()].setDesktopsId(value.value >()); Q_EMIT dataChanged(index, index, QVector{Role::DesktopsId}); return true; } else if (role == Role::ScreenId) { m_windowList[index.row()].setScreenId(Desktop::DesktopType(value.toInt())); Q_EMIT dataChanged(index, index, QVector{Role::ScreenId}); return true; } return false; } QHash AppWindowListModel::roleNames() const { QHash roles = QAbstractItemModel::roleNames(); QMetaEnum e = metaObject()->enumerator(metaObject()->indexOfEnumerator("Role")); for (int i = 0; i < e.keyCount(); ++i) { roles.insert(e.value(i), e.key(i)); } return roles; } void AppWindowListModel::loadWindows() { m_windowList.clear(); beginResetModel(); for (const Window &appwindow : getAllAppWindowList()) { m_windowList.append(appwindow); } endResetModel(); } void AppWindowListModel::addItem(Window window) { beginInsertRows(QModelIndex(), 0, 0); m_windowList.prepend(window); endInsertRows(); } void AppWindowListModel::onAppWindowRemoved(QString windowId) { for (int index = 0; index < m_windowList.size(); ++index) { auto item = m_windowList.at(index); if (item.uuid() == windowId) { beginRemoveRows(QModelIndex(), index, index); m_windowList.removeAt(index); endRemoveRows(); break; } } } void AppWindowListModel::onAppWindowDesktopChanged(QString windowId, int oldDesktopIndex, int newDesktopIndex) { for (int i = 0; i < m_windowList.size(); ++i) { auto &item = m_windowList.at(i); if (item.uuid() == windowId) { m_windowList[i].setDesktopsId(QList{ newDesktopIndex }); Q_EMIT dataChanged(index(i, 0), index(i, 0), QVector{Role::DesktopsId}); break; } } } void AppWindowListModel::onDesktopMoved(int oldDesktopIndex, int newDesktopIndex) { for (int i = 0; i < m_windowList.size(); ++i) { auto &item = m_windowList.at(i); QList desktops = item.desktopsId(); if (desktops.contains(oldDesktopIndex)) { int ind = desktops.indexOf(oldDesktopIndex); desktops.replace(ind, newDesktopIndex); } else if (desktops.contains(newDesktopIndex)) { int ind = desktops.indexOf(newDesktopIndex); desktops.replace(ind, oldDesktopIndex); } else { continue; } m_windowList[i].setDesktopsId(desktops); Q_EMIT dataChanged(index(i, 0), index(i, 0), QVector{Role::DesktopsId}); } } void AppWindowListModel::onDesktopRemoved(int desktopIndex) { //只需要处理desktopId > desktopIndex的情况, //desktopId < desktopIndex时,不影响窗口所在工作区的索引值 //desktopId = desktopIndex时,在onAppWindowDesktopChanged中处理 bool changeFlag; for (int i = 0; i < m_windowList.size(); ++i) { changeFlag = false; auto &item = m_windowList.at(i); QList desktops = item.desktopsId(); for (int i = 0; i < desktops.size(); ++i) { if (desktops.at(i) > desktopIndex) { changeFlag = true; desktops[i] -=1; } } if (changeFlag) { m_windowList[i].setDesktopsId(desktops); Q_EMIT dataChanged(index(i, 0), index(i, 0), QVector{Role::DesktopsId}); } } } void AppWindowListModel::onAppWindowAdd(const Window &window) { qDebug() << "onAppWindowAdd window.caption" << window.caption(); addItem(window); } void AppWindowListModel::onAppWindowActived() { loadWindows(); } void AppWindowListModel::onAppWindowUpdated(const Window &window) { for (int i = 0; i < m_windowList.size(); ++i) { auto &item = m_windowList.at(i); if (item.uuid() == window.uuid()) { m_windowList.replace(i, window); Q_EMIT dataChanged(index(i, 0), index(i, 0)); break; } } } // TODO: remove? QVariant AppWindowListModel::getItemData(const QModelIndex &index) { int i = index.row(); if (i >= 0 && i < m_windowList.count()) { return QVariant::fromValue(m_windowList.at(i)); } else { return QVariant(); } } QList AppWindowListModel::getAllAppWindowList() const { QList allAppWindowList; for(int desktopIndex = 1; desktopIndex <= WindowManagerInterface::getInstance()->getNumberOfDesktops(); desktopIndex++) { for (int screenIndex = 0; screenIndex < WindowManagerInterface::getInstance()->logicalScreenCount(); screenIndex++) { QList windowList; windowList = WindowManagerInterface::getInstance()->createWindowList(desktopIndex, screenIndex); for (int i = windowList.size() - 1; i >= 0; --i) { for (const auto &wind : allAppWindowList) { if (wind.uuid() == windowList[i].uuid()) { windowList.removeAt(i); break; } } } std::reverse(windowList.begin(), windowList.end()); allAppWindowList += windowList; } } return allAppWindowList; } ukui-window-switch-4.21.1.0/windowsview/appwindowlistmodel.h000066400000000000000000000047401522363675600242250ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: zy-yuan1 * */ #ifndef APPWINDOWLISTMODEL_H #define APPWINDOWLISTMODEL_H #include #include #include #include "multitaskviewabstractmodelhandler.h" class Window; class AppWindowListModel : public QAbstractListModel { Q_OBJECT public: enum Role { Id = Qt::UserRole + 1, Uuid, Caption, X, Y, Width, Height, Minimized, DesktopsId, ScreenId, Icon }; Q_ENUM(Role) explicit AppWindowListModel(QObject *parent = nullptr); ~AppWindowListModel() = default; int rowCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; QHash roleNames() const override; /* for TabletView * qml里无法直接读取QMap,需要使用iterator,因此使用QVariant::fromValve(window) * TODO: TabletView 加载动画优化 */ Q_INVOKABLE QVariant getItemData(const QModelIndex &index); private: void connectSignals(); void loadWindows(); void addItem(Window window); QList getAllAppWindowList() const; QList m_windowList; private Q_SLOTS: void onAppWindowRemoved(QString windowId); void onAppWindowDesktopChanged(QString windowId, int oldDesktopIndex, int newDesktopIndex); void onDesktopMoved(int oldDesktopIndex, int newDesktopIndex); void onDesktopRemoved(int desktopIndex); void onAppWindowAdd(const Window &window); void onAppWindowActived(); void onAppWindowUpdated(const Window &window); }; #endif // APPWINDOWLISTMODEL_H ukui-window-switch-4.21.1.0/windowsview/data.qrc000066400000000000000000000025441522363675600215470ustar00rootroot00000000000000 qml/Controller.js images/all-clean-click.svg images/all-clean-default.svg images/all-clean-hover.svg images/ukui-taskview-close-click.svg images/ukui-taskview-close-default.svg images/ukui-taskview-close-hover.svg qml/AppPreviewWindow.qml qml/MasterDesktopArea.qml qml/MultitaskView.qml qml/AppArea.qml qml/DesktopArea.qml qml/TabletPreviewWindow.qml images/tablet_delete.svg qml/TabletViewMain.qml qml/TabletViewCloseButton.qml qml/CloseButton.qml qml/ArrowButton.qml images/icon-arrow-white.svg images/icon-arrow-black.svg qml/VirtualDesktopWindow.qml qml/NewDesktopButton.qml qml/ThumbnailWithKwin.qml qml/Tabbox.qml qml/ThumbnailWithWlcom.qml qml/WorkSpaceThumbnailWithWlcom.qml qml/WorkSpaceThumbnailWithKwin.qml qml/LineEdit.qml ukui-window-switch-4.21.1.0/windowsview/desktopbackground.cpp000066400000000000000000000512111522363675600243370ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "desktopbackground.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include //! 默认的最大虚化程度 #define MAX_BLUR_ALPHA 20 static const QString backgroundSchemaUrl = "org.mate.background"; static const QString fillStyleKeyName = "pictureOptions"; static const QString fileNameKeyName = "pictureFilename"; QImage DesktopBackground::m_blurBackground; QImage DesktopBackground::m_nonBlurBackground; quint32 DesktopBackground::m_blurRadius = 0; static int backgroundNum = 0; DesktopBackground::DesktopBackground(QQuickPaintedItem *parent) : QQuickPaintedItem(parent) , m_blurAlpha(0) { backgroundNum++; QElapsedTimer timer; timer.start(); setFlag(ItemHasContents); init(); qDebug() << "The DesktopBackground Constructor took" << timer.elapsed() << "milliseconds"; } DesktopBackground::~DesktopBackground() { backgroundNum --; m_blurRadius = 0; } void DesktopBackground::init() { connect(this, &DesktopBackground::blurAlphaChanged, this, &DesktopBackground::onBlurAlphaChanged); m_backgroundFile = getBackgroundFile(); m_backgroundFillStyle = getBackgroundFillStyle(); if (m_backgroundFile == "") { // no background file, use pure color qWarning() << "[Multitask]: 未获取到背景图片!"; m_usePureColor = true; m_pureColor = getBackgroundPrimaryColor(); return; } m_scalingFactor = getSystemScalingFactor(); if (m_nonBlurBackground.isNull()) { QImage image(m_backgroundFile); m_nonBlurBackground = image; if (m_backgroundFillStyle == "centered" || m_backgroundFillStyle == "wallpaper") { // 居中 或 平铺 m_nonBlurBackground = m_nonBlurBackground.scaled(m_nonBlurBackground.width() * m_scalingFactor, m_nonBlurBackground.height() * m_scalingFactor); } } } void DesktopBackground::setBlurAlpha(qreal alpha) { if(alpha < 0 || alpha > 1) { return; } m_blurAlpha = alpha; quint32 blur_radius = qRound(m_blurAlpha * MAX_BLUR_ALPHA); if (blur_radius != 0 && m_blurRadius != blur_radius) { m_blurRadius = qRound(m_blurAlpha * MAX_BLUR_ALPHA); emit blurAlphaChanged(); } } QRect DesktopBackground::scaledRect(const QImage &image) { qreal scaledAspectRatio = qreal(boundingRect().width()) / qreal(boundingRect().height()); qreal width = image.width(); qreal height = image.height(); if ((width / height) == scaledAspectRatio) { return image.rect(); } bool widthShorter = (width <= height); // scaledAspectRatio是一个必大于1的实数 // 值为qMax(boundingRect().height(), boundingRect().width()) / qMax(boundingRect().width(), boundingRect().height()) if (widthShorter) { scaledAspectRatio = qreal(boundingRect().height()) / qreal(boundingRect().width()); } qreal shorterEdge = widthShorter ? width : height; qreal longerEdge = widthShorter ? height : width; while (shorterEdge > 1) { qint32 temp = qFloor(shorterEdge * scaledAspectRatio); if (temp <= longerEdge) { longerEdge = temp; break; } qint32 spacing = qRound(shorterEdge / 20); if (spacing <= 0) { spacing = 1; } shorterEdge -= spacing; } QSize scaledSize = image.size(); if (shorterEdge > 1 && longerEdge > 1) { scaledSize.setWidth(widthShorter ? shorterEdge : longerEdge); scaledSize.setHeight(widthShorter ? longerEdge : shorterEdge); } qint32 offsetX = 0; qint32 offsetY = 0; if (image.width() > scaledSize.width()) { offsetX = (image.width() - scaledSize.width()) / 2; } if (image.height() > scaledSize.height()) { offsetY = (image.height() - scaledSize.height()) / 2; } QPoint offsetPoint = image.rect().topLeft(); offsetPoint += QPoint(offsetX, offsetY); return QRect(offsetPoint, scaledSize); } QRect DesktopBackground::getDestRect(const QImage &image, const QRectF &desktopRect) { qreal screenScale = qreal(desktopRect.width()) / desktopRect.height(); qreal pixmapScale = qreal(image.width() / image.height()); qreal width = image.width(); qreal height = image.height(); if (qFuzzyCompare(pixmapScale, screenScale)) { return QRect(0, 0, desktopRect.width(), desktopRect.height()); } qreal scaleWidth = desktopRect.width() / width; qreal scaleHeight = desktopRect.height() / height; qreal realPixmapWidth = 0; qreal realPixmapHeight = 0; if (pixmapScale < screenScale) { //图片比例小于屏幕比例时,按照图片和屏幕高度比进行缩放 realPixmapWidth = width * scaleHeight; realPixmapHeight = desktopRect.height(); } else { //图片比例大于屏幕比例时,按照图片与屏幕宽度比进行缩放 realPixmapWidth = desktopRect.width(); realPixmapHeight = height * scaleWidth; } QSize sourceSize(desktopRect.width(), desktopRect.height()); qint32 offsetX = 0; qint32 offsetY = 0; if (desktopRect.width() == realPixmapWidth) { offsetY = (desktopRect.height() - realPixmapHeight) / 2; sourceSize.setHeight(realPixmapHeight); } else if (desktopRect.height() == realPixmapHeight) { offsetX = (desktopRect.width() - realPixmapWidth) / 2; sourceSize.setWidth(realPixmapWidth); } // 规避xcb下闪线的问题 sourceSize = sourceSize - QSize(1, 1); QPoint offsetPoint(0, 0); offsetPoint += QPoint(offsetX, offsetY); return QRect(offsetPoint, sourceSize); } void DesktopBackground::setNonBlurBackground(const QImage &image) { m_nonBlurBackground = image; } void DesktopBackground::setBlurBackground(const QImage &originImage, qreal blurAlpha) { m_blurBackground = BackgroundImageHandler::blurImage(blurAlpha * MAX_BLUR_ALPHA, originImage); } QString DesktopBackground::getBackgroundFile() { if (!QGSettings::isSchemaInstalled(backgroundSchemaUrl.toUtf8())) { return QString(); } QString filePath; QGSettings gsettings(backgroundSchemaUrl.toUtf8()); const QStringList keyList = gsettings.keys(); if (keyList.contains(fileNameKeyName)) { filePath = gsettings.get(fileNameKeyName).toString(); } else { qWarning() << "[Multitask]: inValid key name" << fileNameKeyName; filePath = ""; } if (!QFile::exists(filePath)) { // maybe desktop background picture was deleted, try AccountsService filePath = getBackgroundFileFromAccount(); } return filePath; } QString DesktopBackground::getBackgroundFileFromAccount() { uid_t uid = getuid(); QDBusInterface iface("org.freedesktop.Accounts", "/org/freedesktop/Accounts", "org.freedesktop.Accounts", QDBusConnection::systemBus()); QDBusReply userPath = iface.call("FindUserById", (qint64)uid); if(!userPath.isValid()) { qWarning() << "[Multitask]: UserPath error" << userPath.error(); } else { QDBusInterface userIface("org.freedesktop.Accounts", userPath.value().path(), "org.freedesktop.DBus.Properties", QDBusConnection::systemBus()); QDBusReply backgroundReply = userIface.call("Get", "org.freedesktop.Accounts.User", "BackgroundFile"); if(backgroundReply.isValid()) { return backgroundReply.value().variant().toString(); } } return ""; } QString DesktopBackground::getBackgroundFillStyle() { if (!QGSettings::isSchemaInstalled(backgroundSchemaUrl.toUtf8())) { return QString(); } QString fillStyle; QGSettings gsettings(backgroundSchemaUrl.toUtf8()); const QStringList keyList = gsettings.keys(); if (keyList.contains(fillStyleKeyName)) { fillStyle = gsettings.get(fillStyleKeyName).toString(); } else { qWarning() << "[Multitask]: inValid key name" << fillStyleKeyName; fillStyle = "scaled"; } return fillStyle; } QColor DesktopBackground::getBackgroundPrimaryColor() { if (!QGSettings::isSchemaInstalled(backgroundSchemaUrl.toUtf8())) { return QColor(); } QGSettings gsettings(backgroundSchemaUrl.toUtf8()); const QStringList keyList = gsettings.keys(); if (keyList.contains("primaryColor")) { auto color = gsettings.get("primaryColor").toString(); return QColor(color); } else { qWarning() << "[Multitask]: inValid key name primaryColor"; return QColor(Qt::color1) ; } } void DesktopBackground::updateBlurBackground() { QElapsedTimer timer; timer.start(); if (m_nonBlurBackground.isNull()) { return; } if (m_blurRadius > 0 && m_blurBackground.isNull()) { // 重新模糊背景图片 m_blurBackground = BackgroundImageHandler::blurImage(m_blurAlpha * MAX_BLUR_ALPHA, m_nonBlurBackground); } qDebug() << "The DesktopBackground blur took" << timer.elapsed() << "milliseconds"; // m_blurBackground.save("/home/pangyi/backgroundImage.png", "PNG"); } double DesktopBackground::getSystemScalingFactor() { double scalingFactor = 1.5; QString schemaUrl = "org.ukui.SettingsDaemon.plugins.xsettings"; QString keyName = "scalingFactor"; if (QGSettings::isSchemaInstalled(schemaUrl.toUtf8())) { QGSettings gsettings(schemaUrl.toUtf8()); const QStringList keyList = gsettings.keys(); if (keyList.contains(keyName)) { scalingFactor = gsettings.get(keyName).toDouble(); // qDebug() << "MMMMMM scalingFactor = " << scalingFactor; } else { qWarning() << QString("未获取到Gesetting的键值(%1) value").arg(keyName); // default return scalingFactor; } } return scalingFactor; } void DesktopBackground::onBlurAlphaChanged() { if(m_nonBlurBackground.isNull()) { return; } updateBlurBackground(); update(); } void DesktopBackground::paint(QPainter *painter) { if (m_usePureColor) { painter->fillRect(boundingRect(), m_pureColor); return; } QImage tmpImage; if (qRound(m_blurAlpha * MAX_BLUR_ALPHA) > 0) { tmpImage = m_blurBackground; } else { tmpImage = m_nonBlurBackground; } if (m_backgroundFillStyle == "centered") { //居中 // scale tmpImage to fitin Desktop Preview Window tmpImage = tmpImage.scaled(tmpImage.width() * boundingRect().width() / qApp->screenAt(QPoint(boundingRect().center().x(), boundingRect().center().y()))->geometry().width(), tmpImage.height() * boundingRect().height() / qApp->screenAt(QPoint(boundingRect().center().x(), boundingRect().center().y()))->geometry().height(), Qt::KeepAspectRatioByExpanding); painter->drawImage((boundingRect().width() - tmpImage.width()) / 2, (boundingRect().height() - tmpImage.height()) / 2, tmpImage); } else if (m_backgroundFillStyle == "wallpaper") { //平铺 // scale tmpImage to fitin Desktop Preview Window tmpImage = tmpImage.scaled(tmpImage.width() * boundingRect().width() / qApp->screenAt(QPoint(boundingRect().center().x(), boundingRect().center().y()))->geometry().width(), tmpImage.height() * boundingRect().height() / qApp->screenAt(QPoint(boundingRect().center().x(), boundingRect().center().y()))->geometry().height(), Qt::KeepAspectRatioByExpanding); int drewWidth = 0; int drewHeight = 0; while (drewHeight < boundingRect().height()) { // draw background on x-direction while (drewWidth < boundingRect().width()) { painter->drawImage(drewWidth, drewHeight, tmpImage); drewWidth += tmpImage.width(); } // set drewWidth to 0 to start next line of drawing drewWidth = 0; // draw background on y-direction drewHeight += tmpImage.height(); } } else if (m_backgroundFillStyle == "scaled") { //填充 painter->drawImage(boundingRect(), tmpImage, scaledRect(tmpImage)); } else if (m_backgroundFillStyle == "stretched") { //拉伸 painter->drawImage(boundingRect(), tmpImage); } else if (m_backgroundFillStyle == "zoom") { //适应 painter->drawImage(getDestRect(tmpImage, boundingRect()), tmpImage, tmpImage.rect()); } else if (m_backgroundFillStyle == "spanned") { //跨区 painter->drawImage(boundingRect(), tmpImage, tmpImage.rect()); } else { // default to scaled painter->drawImage(boundingRect(), tmpImage, scaledRect(tmpImage)); } } int BackgroundImageHandler::edge(int x, int i, int w) { // x 为中心位置, i 为偏移量, w 为图片的宽度/高度 int inx = x + i; if(inx < 0 || inx >= w) { return x - i; } else { return inx; } } // 一维高斯函数 float BackgroundImageHandler::gaussFunc1D(int x, float sigma) { float A = 1.0f / (sigma * sqrt(2 * 3.1415f)); float index = -1.0 * (x * x) / (2 * sigma * sigma); return A * qExp(index); } // 获取线性的权值空间 void BackgroundImageHandler::getKernal(int radius, float* weight) { float sigma = radius / 3.0f; float sum = 0.0f; // 获取权值空间weight[] for(int i = 0; i < 2 * radius + 1; i++) { weight[i] = gaussFunc1D(i - radius, sigma); sum += weight[i]; } // 归一化 for(int i = 0; i < 2 * radius + 1; i++) { weight[i] /= sum; } } // 获取最终的模糊图像 QImage BackgroundImageHandler::blurImage(int blur_radius, const QImage &image) { QImage blurImage = image; int imgOriginWidth = blurImage.width(); int imgOriginHeight = blurImage.height(); // 模糊算法优化点:对原图进行缩放 int maxImgWidth = 1920; if (blurImage.width() > maxImgWidth) { int scaleRatio = qRound((qreal)blurImage.width()/maxImgWidth * 2); blurImage = blurImage.scaled(blurImage.width()/scaleRatio, blurImage.height()/scaleRatio, Qt::KeepAspectRatio, Qt::FastTransformation); } // 保证图片格式可用 if (blurImage.format() == QImage::Format::Format_Mono || blurImage.format() == QImage::Format::Format_MonoLSB) { blurImage.setColorCount(256); // set the color count to 256, which is 8-bit blurImage = blurImage.convertToFormat(QImage::Format_RGB32); } // 原图为 originImg // 第一个方向处理的图像为tmpImg int originWidth = blurImage.width(); int originHeight = blurImage.height(); int divisor = std::__gcd(originWidth, originHeight); int blurWidth = originWidth / divisor; int blurHeight = originHeight / divisor; int value = 1; if (blurWidth < 300) { while (true) { if ( ( value + 1 ) * blurWidth > 300 ) { break; } else { ++value; } } blurImage = blurImage.scaled(blurWidth * value, blurHeight * value, Qt::KeepAspectRatio); } else { // 说明背景图没有找到足够大的最大公约数 blurImage = blurImage.scaledToWidth(300); } // qDebug() << __func__ << originWidth << originHeight << blurImage.width() << blurImage.height() << value << divisor; QImage tmpImg = blurImage; // 经过第二次处理的最终结果bluredImage float weight[2 * blur_radius + 1]; getKernal(blur_radius, weight); int height = blurImage.height(); int width = blurImage.width(); float rgb[3]; unsigned char *p, *p1, *ptmp; // 在横向进行一次相加 for(int y = 0; y < height; y++) { p = blurImage.scanLine(y); for(int x = 0; x < width; x++) { rgb[0] = rgb[1] = rgb[2] = 0.0f; for(int i = -blur_radius; i <= blur_radius; i++) { // 边界处理后的对应的权值矩阵实际值 int inx = edge(x, i, width); p1 = p + inx * 4; rgb[0] += p1[0] * weight[blur_radius + i]; rgb[1] += p1[1] * weight[blur_radius + i]; rgb[2] += p1[2] * weight[blur_radius + i]; } ptmp = tmpImg.scanLine(y) + 4 * x; ptmp[0] = rgb[0]; ptmp[1] = rgb[1]; ptmp[2] = rgb[2]; } } // 在纵方向对第一次的结果重新进行一次,先进行逆时针旋转90度进行高斯模糊,减少 scanLine() 函数的计算量 QTransform matrix; matrix.rotate(-90.0); tmpImg = tmpImg.transformed(matrix, Qt::FastTransformation); blurImage = blurImage.transformed(matrix, Qt::FastTransformation); int height_rotate = blurImage.height(); int width_rotate = blurImage.width(); for(int y = 0; y < height_rotate; y++) { p = tmpImg.scanLine(y); for(int x = 0; x < width_rotate; x++) { rgb[0] = rgb[1] = rgb[2] = 0.0f; for(int i = -blur_radius; i <= blur_radius; i++) { // 边界处理后的对应的权值矩阵实际值 int inx = edge(x, i, width_rotate); p1 = p + inx * 4; rgb[0] += p1[0] * weight[blur_radius + i]; rgb[1] += p1[1] * weight[blur_radius + i]; rgb[2] += p1[2] * weight[blur_radius + i]; } ptmp = blurImage.scanLine(y) + 4 * x; ptmp[0] = rgb[0]; ptmp[1] = rgb[1]; ptmp[2] = rgb[2]; } } matrix.rotate(180.0); blurImage = blurImage.transformed(matrix, Qt::FastTransformation); // smooth scale是耗时大户啊(将近90ms),暂时没想到优化方法! blurImage = blurImage.scaled(originWidth, originHeight, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); // 将模糊图片缩放回原图尺寸 blurImage = blurImage.scaled(imgOriginWidth, imgOriginHeight, Qt::IgnoreAspectRatio, Qt::FastTransformation); return blurImage; } void BackgroundImageHandler::loadBackgroundImageAsync(const QString filePath, double scalingFactor, const QString fillStyle, QObject *context, ImageTaskCallBack loadFinishedCallback) { auto taskFunc = [filePath, scalingFactor, fillStyle]() { return loadBackgroundImage(filePath, scalingFactor, fillStyle); }; new BackgroundImageHandler(taskFunc, context, loadFinishedCallback); } void BackgroundImageHandler::blurImageAsync(const QImage &image, qreal radius, QObject *context, ImageTaskCallBack blurFinishedCallback) { auto taskFunc = [radius, image]() { return blurImage(radius, image); }; new BackgroundImageHandler(taskFunc, context, blurFinishedCallback); } BackgroundImageHandler::BackgroundImageHandler(ImageTask taskFunc, QObject *context, ImageTaskCallBack callback) { auto* thread = QThread::create([this, taskFunc](){ auto image = taskFunc(); Q_EMIT taskFinished(image); }); moveToThread(thread); connect(thread, &QThread::finished, thread, &QObject::deleteLater); connect(thread, &QThread::finished, this, &QObject::deleteLater); connect(this, &BackgroundImageHandler::taskFinished, context, [callback, thread](const QImage image) { callback(image); if (thread->isRunning()) { thread->quit(); thread->wait(); } }); thread->start(); } QImage BackgroundImageHandler::loadBackgroundImage(const QString& filePath, double scalingFactor, const QString& fillStyle) { QImage image(filePath); if (scalingFactor != 1.0) { if (fillStyle == "centered" || fillStyle == "wallpaper") { // 居中 或 平铺 image = image.scaled(image.width() * scalingFactor, image.height() * scalingFactor); } } return image; } ukui-window-switch-4.21.1.0/windowsview/desktopbackground.h000066400000000000000000000071021522363675600240040ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef DESKTOPBACKGROUND_H #define DESKTOPBACKGROUND_H #include #include #include #include class QGSettings; class QColor; /*! * \brief 背景绘制的Item,导出由QML使用进行背景的绘制 * \details 方便前端进行背景绘制,并提供虚化、背景图片拉伸的能力 */ using ImageTask = std::function; using ImageTaskCallBack = std::function; class BackgroundImageHandler : public QObject { Q_OBJECT public: ~BackgroundImageHandler() = default; static void loadBackgroundImageAsync(const QString filePath, double scalingFactor, const QString fillStyle, QObject* context, ImageTaskCallBack loadFinishedCallback); static void blurImageAsync(const QImage &image, qreal radius, QObject* context, ImageTaskCallBack blurFinishedCallback); static QImage blurImage(int blur_radius, const QImage &blurImage); private: BackgroundImageHandler(ImageTask taskFunc, QObject* context, ImageTaskCallBack callback); static QImage loadBackgroundImage(const QString &filePath, double scalingFactor, const QString &fillStyle); static int edge(int x, int i, int w); static float gaussFunc1D(int x, float sigma); static void getKernal(int radius, float* weight); Q_SIGNALS: void taskFinished(const QImage &image); }; class DesktopBackground : public QQuickPaintedItem { Q_OBJECT Q_PROPERTY(qreal blurAlpha READ blurAlpha WRITE setBlurAlpha NOTIFY blurAlphaChanged) public: explicit DesktopBackground(QQuickPaintedItem *parent = nullptr); ~DesktopBackground(); void paint(QPainter *painter); qreal blurAlpha() { return m_blurAlpha; } void setBlurAlpha(qreal alpha); QRect scaledRect(const QImage &image); QRect getDestRect(const QImage &image, const QRectF &desktopRect); static void setNonBlurBackground(const QImage &image); static void setBlurBackground(const QImage &originImage, qreal blurAlpha); static double getSystemScalingFactor(); static QString getBackgroundFile(); static QString getBackgroundFillStyle(); signals: void loadPicture(const QString &fileName); void blurAlphaChanged(); void blurImage(int radius, const QImage &blurImage); private slots: void onBlurAlphaChanged(); private: void init(); static QString getBackgroundFileFromAccount(); QColor getBackgroundPrimaryColor(); void updateBlurBackground(); private: QString m_backgroundFile; QString m_backgroundFillStyle = "scaled"; double m_scalingFactor = 1.5; static QImage m_blurBackground; static QImage m_nonBlurBackground; qreal m_blurAlpha; static quint32 m_blurRadius; bool m_usePureColor = false; QColor m_pureColor = Qt::black; }; #endif // DESKTOPBACKGROUND_H ukui-window-switch-4.21.1.0/windowsview/desktoplistmodel.cpp000066400000000000000000000173161522363675600242240ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: zy-yuan1 * */ #include "desktoplistmodel.h" #include #include #include #include #include #include #include #include "windowmanagerinterface.h" DesktopListModel::DesktopListModel(QObject *parent) : QAbstractListModel(parent) { connectSignals(); init(); } int DesktopListModel::rowCount(const QModelIndex &parent) const { return m_desktopList.count(); } QVariant DesktopListModel::data(const QModelIndex &index, int role) const { int i = index.row(); if (i < 0 || i >= m_desktopList.count()) { return QVariant(); } Desktop desktop = m_desktopList.at(i); switch (static_cast(role)) { case Role::Id: return i + 1; case Role::Uuid: return desktop.uuid(); case Role::CustomName: return desktop.customName(); case Role::ItemType: return desktop.type() == Desktop::DesktopType::NewDesktop ? QString("newDesktop") : QString("workSpace"); default: return {}; } } bool DesktopListModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (!index.isValid()) { return false; } if (role == Role::CustomName) { m_desktopList[index.row()].setCustomName(value.toString()); Q_EMIT dataChanged(index, index, QVector{Role::CustomName}); WindowManagerInterface::getInstance()->setDesktopName(index.row() + 1, value.toString()); WindowManagerInterface::getInstance()->saveDesktopNames(getDesktopNames()); return true; } else if (role == Role::ItemType) { m_desktopList[index.row()].setDesktopType(Desktop::DesktopType(value.toInt())); Q_EMIT dataChanged(index, index, QVector{Role::ItemType}); } return false; } QHash DesktopListModel::roleNames() const { QHash roles = QAbstractItemModel::roleNames(); QMetaEnum e = metaObject()->enumerator(metaObject()->indexOfEnumerator("Role")); for (int i = 0; i < e.keyCount(); ++i) { roles.insert(e.value(i), e.key(i)); } return roles; } bool DesktopListModel::insertRows(int row, int count, const QModelIndex &parent) { if (row < 0 || row > m_desktopList.count() || m_desktopList.count() > MAX_DESKTOP_COUNT) { return false; } beginInsertRows(parent, row, row); Desktop desktop; desktop.setDesktopType(Desktop::DesktopType::WorkSpace); m_desktopList.insert(m_desktopList.count() - 1, desktop); endInsertRows(); return true; } bool DesktopListModel::removeRows(int row, int count, const QModelIndex &parent) { if (!rowIsValid(row)) { return false; } beginRemoveRows(parent, row, row); m_desktopList.removeAt(row); endRemoveRows(); return true; } bool DesktopListModel::moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destinationParent, int destinationChild) { if (!rowIsValid(sourceRow) || !rowIsValid(destinationChild)) { return false; } // only support count == 1 // 需要注意 beginMoveRows 单个节点移动时,上移差是1,下移差是2 if (sourceRow < destinationChild) { // 右移/下移 beginMoveRows(sourceParent,sourceRow, sourceRow, destinationParent, destinationChild + 1); } else { // 左移/上移 beginMoveRows(sourceParent,sourceRow, sourceRow, destinationParent, destinationChild); } m_desktopList.move(sourceRow, destinationChild); endMoveRows(); return true; } bool DesktopListModel::rowIsValid(int row) const { return row >= 0 && row < m_desktopList.count(); } void DesktopListModel::connectSignals() { QObject::connect(WindowManagerInterface::getInstance(), &WindowManagerInterface::desktopAppended, this, &DesktopListModel::onDesktopAppend); QObject::connect(WindowManagerInterface::getInstance(), &WindowManagerInterface::desktopRemoved, this, &DesktopListModel::onDesktopRemoved); QObject::connect(WindowManagerInterface::getInstance(), &WindowManagerInterface::desktopMoved, this, &DesktopListModel::onDesktopMoved); } void DesktopListModel::init() { beginResetModel(); m_desktopList.clear(); const auto desktopCount = WindowManagerInterface::getInstance()->getNumberOfDesktops(); QStringList desktopNameList = WindowManagerInterface::getInstance()->getDesktopNames(); for (int desktopIndex = 1; desktopIndex <= desktopCount; desktopIndex++) { Desktop desktop; desktop.setDesktopType(Desktop::DesktopType::WorkSpace); if (desktopIndex < desktopNameList.size()) { desktop.setCustomName(desktopNameList.at(desktopIndex - 1)); } m_desktopList.append(desktop); } // 在末尾添加空的Desktop,指代“newDesktop” if (desktopCount < MAX_DESKTOP_COUNT) { Desktop desktop; desktop.setDesktopType(Desktop::DesktopType::NewDesktop); m_desktopList.append(desktop); } endResetModel(); } QStringList DesktopListModel::getDesktopNames() { QStringList nameList; for (const auto &desktop : m_desktopList) { nameList.append(desktop.customName()); } return nameList; } void DesktopListModel::onDesktopAppend(int desktopIndex) { //当工作区数量达到最大时,再点击“新建工作区”不需要model新增item,只需将model最后一项的属性ItemType由“newDesktop”改为“workSpace”,并修改其他必须修改的属性 //其他情况下则新增item if (desktopIndex == MAX_DESKTOP_COUNT) { setData(index(desktopIndex - 1, 0), Desktop::DesktopType::WorkSpace, Role::ItemType); setData(index(desktopIndex - 1, 0), "", Role::CustomName); } else { insertRows(desktopIndex - 1, 1, QModelIndex()); emit desktopAppended(rowCount() + 1); } WindowManagerInterface::getInstance()->saveDesktopNames(getDesktopNames()); } void DesktopListModel::onDesktopRemoved(int desktopIndex) { //当工作区数量是最大时,且最后一项为“workSpace”,由于要播放删除动画,需要先添加“newDesktop”,再删除desktopIndex对应工作区 if (rowCount() == MAX_DESKTOP_COUNT && index(MAX_DESKTOP_COUNT - 1, 0).data(Role::ItemType).toString() == QString("workSpace")) { insertRows(MAX_DESKTOP_COUNT, 1, QModelIndex()); setData(index(MAX_DESKTOP_COUNT, 0), Desktop::DesktopType::NewDesktop, Role::ItemType); setData(index(MAX_DESKTOP_COUNT, 0), "", Role::CustomName); } removeRows(desktopIndex - 1, 1, QModelIndex()); WindowManagerInterface::getInstance()->saveDesktopNames(getDesktopNames()); } void DesktopListModel::onDesktopMoved(int srcDesktopIndex, int destDesktopIndex) { moveRows(QModelIndex(), srcDesktopIndex - 1, 1, QModelIndex(), destDesktopIndex - 1); WindowManagerInterface::getInstance()->saveDesktopNames(getDesktopNames()); } ukui-window-switch-4.21.1.0/windowsview/desktoplistmodel.h000066400000000000000000000054561522363675600236730ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: zy-yuan1 * */ #ifndef DESKTOPLISTMODEL_H #define DESKTOPLISTMODEL_H #include #include #include #include #include #include #include #include "multitaskviewabstractmodelhandler.h" class Window; class Desktop; class DesktopListModel : public QAbstractListModel { Q_OBJECT public: enum Role { Id = Qt::UserRole + 1, /* desktop index, 从 1 开始计数,易于和界面显示对应 */ Uuid, /* desktop uuid */ CustomName, /* 用户自定义名称 */ ItemType /*DesktopType*/ }; Q_ENUM(Role) explicit DesktopListModel(QObject *parent = nullptr); ~DesktopListModel() = default; int rowCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; QHash roleNames() const override; bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; bool moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destinationParent, int destinationChild) override; bool rowIsValid(int row) const; void connectSignals(); void init(); private: QStringList getDesktopNames(); QList m_desktopList; /* 最大虚拟桌面数量为15: 15个工作区 或 14个工作区+新建工作区*/ static constexpr int MAX_DESKTOP_COUNT = 15; signals: /* 用户手动添加工作区时,需要额外执行动画使最后一个工作区(或新建工作区)显示完整;删除工作区则不需要 */ void desktopAppended(int desktopIndex); private slots: void onDesktopAppend(int desktopIndex); void onDesktopRemoved(int desktopIndex); void onDesktopMoved(int srcDesktopIndex, int destDesktopIndex); }; #endif // DESKTOPLISTMODEL_H ukui-window-switch-4.21.1.0/windowsview/globalconfig.h.in000066400000000000000000000001511522363675600233230ustar00rootroot00000000000000#cmakedefine01 HAVE_X11 #cmakedefine01 HAVE_XCB_COMPOSITE #cmakedefine01 HAVE_GLX #cmakedefine01 HAVE_EGLukui-window-switch-4.21.1.0/windowsview/icontheme.cpp000066400000000000000000000024551522363675600226070ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "icontheme.h" IconTheme::IconTheme(QQuickPaintedItem *parent) : QQuickPaintedItem(parent) { } void IconTheme::setIcon(const QIcon &icon) { m_icon = icon; } void IconTheme::setIconName(const QString &iconName) { if(!QIcon::hasThemeIcon(iconName)) { qWarning() << "未找到名为 " << iconName << " 的图标!"; return; } m_icon = QIcon::fromTheme(iconName, m_icon); } void IconTheme::paint(QPainter *painter) { if(m_icon.isNull()) return; m_icon.paint(painter, boundingRect().toRect()); } ukui-window-switch-4.21.1.0/windowsview/icontheme.h000066400000000000000000000033241522363675600222500ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef ICONTHEME_H #define ICONTHEME_H #include #include /*! * \brief 封装QIcon,并导出为QML类型 * \details 在QML中不能直接使用QIcon类,常见的比如在Button中设置icon属性为QIcon类会提示Unable to assign QIcon to QQuickIcon。 * 子类化QQuickImageProvider来实现在QML中访问C++提供的图片感觉即繁琐又复杂。 * 通过继承QQuickPaintedItem,封装一层QIcon直接导出为QML可以使用的类,使用QIcon无疑会方便许多。 */ class IconTheme : public QQuickPaintedItem { Q_OBJECT Q_PROPERTY(QString iconName WRITE setIconName) Q_PROPERTY(QIcon icon READ icon WRITE setIcon) public: IconTheme(QQuickPaintedItem *parent = nullptr); QIcon icon() { return m_icon; } void setIcon(const QIcon &icon); void setIconName(const QString &iconName); void paint(QPainter *painter); private: QIcon m_icon; }; #endif // ICONTHEME_H ukui-window-switch-4.21.1.0/windowsview/images/000077500000000000000000000000001522363675600213675ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/images/all-clean-click.svg000066400000000000000000000125161522363675600250300ustar00rootroot00000000000000 ukui-window-switch-4.21.1.0/windowsview/images/all-clean-default.svg000066400000000000000000000125161522363675600253670ustar00rootroot00000000000000 ukui-window-switch-4.21.1.0/windowsview/images/all-clean-hover.svg000066400000000000000000000125161522363675600250660ustar00rootroot00000000000000 ukui-window-switch-4.21.1.0/windowsview/images/icon-arrow-black.svg000066400000000000000000000007551522363675600252510ustar00rootroot00000000000000 icon-arrow-深 ukui-window-switch-4.21.1.0/windowsview/images/icon-arrow-white.svg000066400000000000000000000007611522363675600253120ustar00rootroot00000000000000 icon-arrow-浅 ukui-window-switch-4.21.1.0/windowsview/images/tablet_delete.svg000066400000000000000000000032631522363675600247110ustar00rootroot00000000000000 切片 ukui-window-switch-4.21.1.0/windowsview/images/ukui-taskview-close-click.svg000066400000000000000000000015471522363675600271150ustar00rootroot00000000000000 ukui-window-switch-4.21.1.0/windowsview/images/ukui-taskview-close-default.svg000066400000000000000000000015651522363675600274540ustar00rootroot00000000000000 ukui-window-switch-4.21.1.0/windowsview/images/ukui-taskview-close-hover.svg000066400000000000000000000015451522363675600271510ustar00rootroot00000000000000 ukui-window-switch-4.21.1.0/windowsview/multitaskviewabstractmodelhandler.h000066400000000000000000000126131522363675600273110ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef MultitaskViewAbstractModelHandler_H #define MultitaskViewAbstractModelHandler_H #include #include class Window { Q_GADGET Q_PROPERTY(int id READ id) Q_PROPERTY(QString caption READ caption) Q_PROPERTY(int x READ x) Q_PROPERTY(int y READ y) Q_PROPERTY(int width READ width) Q_PROPERTY(int height READ height) Q_PROPERTY(bool minimized READ minimized) Q_PROPERTY(QString uuid READ uuid) Q_PROPERTY(QList desktopsId READ desktopsId) Q_PROPERTY(int screenId READ screenId) Q_PROPERTY(QVariant icon READ icon WRITE setIcon) public: Window() = default; Window(int id, QString uuid, const QString& caption, int x, int y, int width, int height, bool minimized) : m_id(id), m_uuid(uuid), m_caption(caption), m_x(x), m_y(y), m_width(width), m_height(height), m_isMinimized(minimized) {} int id() const { return m_id; } QString uuid() const { return m_uuid; } const QString& caption() const { return m_caption; } int x() const { return m_x; } int y() const { return m_y; } int width() const { return m_width; } int height() const { return m_height; } bool minimized() const { return m_isMinimized; } QList desktopsId() const { return m_desktopsId; } int screenId() const { return m_screenId; } void setDesktopsId(const QList desktopsId) { m_desktopsId = desktopsId; } void setScreenId(const int screenId) { m_screenId = screenId; } const QVariant& icon() { return m_icon; } void setIcon(const QVariant& icon) { m_icon = icon; } private: int m_id = 0; QString m_uuid; QString m_caption; int m_x = 0; int m_y = 0; int m_width = 0; int m_height = 0; bool m_isMinimized = false; QList m_desktopsId; int m_screenId = 0; QVariant m_icon; }; Q_DECLARE_METATYPE(Window) class Desktop { Q_GADGET Q_PROPERTY(QString uuid READ uuid) public: enum DesktopType { WorkSpace = 0, NewDesktop }; Desktop() = default; QString uuid() const { return m_uuid; } DesktopType type() const { return m_type; }; void setUuid(const QString uuid) { m_uuid = uuid; } void setDesktopType(DesktopType type) { m_type = type; } QString customName() const { return m_customName; } void setCustomName(const QString name) { m_customName = name; } private: QString m_uuid; QString m_customName; DesktopType m_type = DesktopType::WorkSpace; }; Q_DECLARE_METATYPE(Desktop) class MultitaskViewAbstractModelHandler : public QObject { Q_OBJECT Q_DISABLE_COPY(MultitaskViewAbstractModelHandler) public: explicit MultitaskViewAbstractModelHandler() = default; ~MultitaskViewAbstractModelHandler() = default; virtual void removeAppWindow(QString windowId) = 0; virtual void moveAppWindowToDesktop(QString windowId, int srcDesktopInex, int destDesktopInex) = 0; virtual void activateAppWindow(QString windowId) = 0; virtual QVariant getWindowIcon(QString windowId) = 0; virtual void removeDesktop(int desktopIndex) = 0; virtual void appendDesktop() = 0; virtual void moveDesktop(int srcDesktopIndex, int destDesktopIndex) = 0; virtual int getCurrentDesktop() = 0; virtual bool isCurrentDesktopShowingDesktop() = 0; virtual void setCurrentDesktop(int desktopIndex) = 0; virtual QRect getFullScreenGeometry(int desktopIndex, int screenIndex) =0; virtual bool hasModalChildWindow(QString windowId) = 0; virtual bool isExtensionMode() = 0; virtual int logicalScreenCount() = 0; virtual QList createWindowList(int desktopIndex, int screenIndex) = 0; virtual int getNumberOfDesktops() = 0; virtual QString getDesktopUuid(int desktopIndex) = 0; virtual QString getOutputUuid(int outputIndex) = 0; virtual void setDesktopName(const int desktopIndex, const QString name) = 0; signals: void appWindowCreated(); void appWindowAdd(const Window &window); void appWindowRemoved(QString windowId); void appWindowActivated(); void appWindowUpdated(const Window &window); void appWindowDesktopChanged(QString windowId, int oldDesktopIndex,int newDesktopIndex); void desktopRemoved(int desktopIndex); void desktopAppended(int desktopIndex); void desktopMoved(int oldDesktopIndex, int newDesktopIndex); void currentDesktopChanged(int oldCurrentDesktopIndex, int newCurrentDesktopIndex); void screenCountChanged(); void screenSizeChanged(); void desktopNumberChanged(); }; #endif // MultitaskViewAbstractModelHandler_H ukui-window-switch-4.21.1.0/windowsview/qml/000077500000000000000000000000001522363675600207135ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/qml/AppArea.qml000066400000000000000000000342531522363675600227460ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import QtQuick 2.12 import QtQuick.Layouts 1.3 import "Controller.js" as Controller import org.ukui.positioner 1.0 import org.ukui.quick.items 1.0 as UkuiItem FocusScope { id : root property var appAreaController : new Controller.AppController(multitaskViewModel, root, multitaskViewManager, ["none"]) property int currentTabIndex: 0 Flickable { id : scrollArea anchors.fill : parent // 预览图布局区域 y 轴起始高度 property int scrollViewYStartPoint : 32 * scaleFactor // 预览图布局区域距离左侧和右侧的间距 property int scrollViewLeftSpace : isVerticalLayout ? 32 : 0 anchors.leftMargin: scrollViewLeftSpace //注意:间距为0则无法显示滚动条 anchors.rightMargin: scrollViewLeftSpace anchors.topMargin: 0 anchors.bottomMargin: 0 property ListModel windowPosInfoModel: ListModel{} property var rowSpacing : isVerticalLayout ? Math.floor(16 * scaleFactor) : Math.floor(10 * scaleFactor) property var columnSpacing : isVerticalLayout ? Math.floor(16 * scaleFactor) : Math.floor(10 * scaleFactor) height: parent.height width: parent.width contentWidth : parent.width - scrollViewLeftSpace * 2 contentHeight : Math.max(flow.height, height) clip : true UkuiItem.DtThemeScrollBar.vertical: UkuiItem.DtThemeScrollBar { id: vScrollBar parent: scrollArea.parent anchors.top: scrollArea.top anchors.left: scrollArea.right anchors.bottom: scrollArea.bottom visual : flow.height > scrollArea.height } MouseArea{ anchors.fill : parent onClicked : { appAreaController.closeMultitaskView() } } NumberAnimation { id : scrollMoveAnimation target : vScrollBar property : "position" from : vScrollBar.position duration : 300 easing.type : Easing.InOutQuart } UkuiFlow { id : flow property bool needFlowYAnimation : false spacing : scrollArea.rowSpacing topPadding: scrollArea.scrollViewYStartPoint width : parent.width flow : Flow.LeftToRight layoutDirection: isLayoutLeftToRight ? Qt.LeftToRight : Qt.RightToLeft lineHorizontalCenterAlignment: true move :Transition { //子项增加时或者减少时的过度,也就是子项的visible变化的过度 NumberAnimation { properties : "x,y"; easing.type : Easing.InOutQuad; duration : isVerticalLayout ? 500 : 300 } } onHeightChanged: { y = Math.max((scrollArea.height - flow.height) / 2, 0) } // flow 垂直居中动画 Behavior on y { enabled: flow.needFlowYAnimation NumberAnimation { duration : isVerticalLayout ? 500 : 300 easing.type : Easing.InOutQuart } } onPositioningComplete: { updateWindowPosInfo() } function updateWindowPosInfo() { var rowWindowNum = 0 //窗口区域每行的窗口数 var leftX = 0 var rightX = 0 var rowY = flow.topPadding var itemCount = 0 var winModel = [] scrollArea.windowPosInfoModel.clear() for (let i = 0; i < flow.children.length; ++i) { if (flow.children[i].width === 0) { continue } // 根据预览窗 Y 坐标判断是否到下一行 if (flow.children[i].y !== rowY) { if (winModel.length > 0) { scrollArea.windowPosInfoModel.append({model : winModel, rowWindowCount : rowWindowNum}) winModel = [] rowWindowNum = 0 } rowY += flow.children[i].height + flow.spacing } // 更新预览窗在 Flow 布局中的 X 坐标并存入局部 model itemCount++ leftX = flow.children[i].x rightX = leftX + flow.children[i].width winModel.push({index: itemCount - 1, leftX: leftX, rightX: rightX}) rowWindowNum++ } if (winModel.length > 0) { scrollArea.windowPosInfoModel.append({model : winModel, rowWindowCount : rowWindowNum}) } } Repeater { id : previewWindowRepeater model : appAreaModel activeFocusOnTab: count !== 0 ? true : false focus : true delegate: Rectangle { id : thumbnailitem width: appWindow.width height: appWindow.height focus: true color : "transparent" property var thumbWidth : getThumbnailSize()[0] property var thumbHeight : getThumbnailSize()[1] property string uuid: model.Uuid states: [ State { name : "tabActive" when: previewWindowRepeater.activeFocus && index === currentTabIndex && (multitaskViewManager.shouldShowTabBorder) PropertyChanges { target: appWindow.borderRectangle borderColor : tabFocusBorderColor } } ] function getThumbnailSize() { var thumbHeight = thumbRectangleHeight var max_width = parent.width / 3 var clientWidth = model.Width var clientHeight = model.Height var thumbWidth = Math.floor(thumbHeight * clientWidth / clientHeight) if (thumbWidth > max_width) { thumbWidth = max_width thumbHeight = Math.floor(thumbWidth * clientHeight / clientWidth) } return [thumbWidth, thumbHeight] } AppPreviewWindow { id : appWindow // Warning: 因为 appWindow 的 parent 会改变,所以不要使用 parent 获取宽高 minWidth: Math.floor(root.width / 10) thumbHeight : thumbnailitem.thumbHeight thumbWidth : thumbnailitem.thumbWidth windowType : "app" x_wid : model.Id wid : model.Uuid icon : model.Icon caption : model.Caption parent: thumbnailitem Drag.onActiveChanged : { if (!Drag.active) { var fromPos = mapToItem(thumbnailitem, 0, 0) posX = fromPos.x posY = fromPos.y appAreaController.onSourceDropped(appWindow, rootWindow.highlightDesktop, rootWindow.highlightDesktop) } else { //拖拽动画开始前,修改 appWindow 父对象 appWindow.parent = allroot zoomOutAnimation() } } } }//Rectangle onActiveFocusChanged: { if (previewWindowRepeater.activeFocus) { currentTabIndex = 0 if (vScrollBar.position > 0) { scrollMoveAnimation.to = 0 scrollMoveAnimation.start() } multitaskViewManager.activeAreaChangeDataCollect("Windows Preview Area") } } onItemAdded : { if (flow.needFlowYAnimation !== false) { flow.needFlowYAnimation = false } } onItemRemoved : { if (flow.needFlowYAnimation !== true) { flow.needFlowYAnimation = true } } Keys.onPressed: { if (rootWindow.isWlcom) { multitaskViewManager.keyNavigationDataCollect(event.key) } if (event.key === Qt.Key_Left) { if (currentTabIndex > 0) { currentTabIndex = currentTabIndex - 1 } else if (currentTabIndex === 0) { currentTabIndex = previewWindowRepeater.count - 1 } event.accepted = true } else if (event.key === Qt.Key_Right ) { if (currentTabIndex < previewWindowRepeater.count - 1) { currentTabIndex = currentTabIndex + 1 } else if (currentTabIndex === previewWindowRepeater.count - 1) { currentTabIndex = 0 } event.accepted = true } else if (event.key === Qt.Key_Up || event.key === Qt.Key_Down) { var isKeyUp = event.key === Qt.Key_Up currentTabIndex = appAreaController.keyUpDownSelectWindow(isKeyUp, scrollArea.windowPosInfoModel, currentTabIndex) event.accepted = true } else if (event.key === Qt.Key_Tab) { if (event.modifiers & Qt.MetaModifier) { appAreaController.closeMultitaskView() return } currentTabIndex = 0 event.accepted = false } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) { appAreaController.onWindowClicked(previewWindowRepeater.itemAt(currentTabIndex).uuid); event.accepted = true } else if (event.key === Qt.Key_End) { currentTabIndex = previewWindowRepeater.count - 1 event.accepted = true } else if (event.key === Qt.Key_Home) { currentTabIndex = 0 event.accepted = true } else if (event.key === Qt.Key_PageUp || event.key === Qt.Key_PageDown) { var isKeyPageUp = event.key === Qt.Key_PageUp currentTabIndex = appAreaController.keyPageUpDownSelectWindow(isKeyPageUp, scrollArea.windowPosInfoModel, currentTabIndex) event.accepted = true } else if (event.key === Qt.Key_Escape) { appAreaController.closeMultitaskView() } if (event.key === Qt.Key_Tab || event.key === Qt.Key_Left || event.key === Qt.Key_Right || event.key === Qt.Key_Up || event.key === Qt.Key_Down || event.key === Qt.Key_Home || event.key === Qt.Key_End || event.key === Qt.Key_PageUp || event.key === Qt.Key_PageDown) { multitaskViewManager.setShouldShowTabBorder(true) } if (event.accepted) { scrollToTabItem() } } function scrollToTabItem() { var currentNextY = itemAt(currentTabIndex).mapToItem(scrollArea, 0, 0).y var previewWindowHeight = itemAt(currentTabIndex).height if (currentNextY < 0) { scrollMoveAnimation.to = vScrollBar.position - (-currentNextY) / scrollArea.contentHeight scrollMoveAnimation.start() } else if (currentNextY + previewWindowHeight > scrollArea.height) { scrollMoveAnimation.to = vScrollBar.position + (currentNextY + previewWindowHeight - scrollArea.height) / scrollArea.contentHeight scrollMoveAnimation.start() } } }//Repeater Component.onCompleted: { if (appAreaModel.rowCount() !== 0) { previewWindowRepeater.forceActiveFocus() } // 无应用窗口时不获取tab焦点 } Connections { target: multitaskViewManager function onTaskViewShowed() { if (appAreaModel.rowCount() !== 0) { previewWindowRepeater.forceActiveFocus() } } } }//Flow }//ScrollView } ukui-window-switch-4.21.1.0/windowsview/qml/AppPreviewWindow.qml000066400000000000000000000254261522363675600247110ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* 每个预览窗口的UI设计 */ import QtQuick 2.12 import QtQuick.Layouts 1.3 import QtQuick.Effects import "Controller.js" as Controller //ukui-quick import org.ukui.quick.items 1.0 as UkuiItem import org.ukui.quick.platform 1.0 as UkuiPlatform Rectangle { id : root color : "transparent" /** windowType is the type of PreviewWindow, * the options are : none, app, desktop, creation. * Default to none. */ property string windowType : "none" /** stateList is the list of state, * the options are : default, hover, drag, receive. * Default to default. */ property var stateList : ["default", "hover", "drag", "receive"]; state : "default" property string wid : "" property int x_wid : -1 property var thumbHeight property var thumbWidth property real posX : 0 property real posY : 0 property double titleOpacity : 1 property var controller : new Controller.AppController(multitaskViewModel, root, multitaskViewManager, ["none"]); property var icon Drag.active : previewMouseArea.drag.active Drag.source : root Drag.hotSpot.x : root.width / 2 Drag.hotSpot.y : root.height / 2 property alias borderRectangle : previewArea property alias caption : caption.text // 定义缩放比例系数变量 property double scaleValue : 0.0 property double windowDragX : 0.0 property double windowDragY : 0.0 property double windowOriginalX : 0.0 property double windowOriginalY : 0.0 // 定义应用预览窗各间距、宽高 property int spacingWidth: 2 * scaleFactor // focus边框与预览图间距 property int appThumbnailMargin: appBorderWidth + spacingWidth property int minWidth: thumbWidth + 2 * appThumbnailMargin width: Math.max(thumbWidth + 2 * appThumbnailMargin, minWidth) height: captionRow.height + previewArea.height + mainColumnLayout.spacing + 2 * appThumbnailMargin states : [ State { name : "default" PropertyChanges { target : previewArea borderColor : root.parent.state == "tabActive" ? tabFocusBorderColor : defaultBorderColor } PropertyChanges { target : previewWindowCloseButton; visible : rootWindow.isTouchState ? true : false } }, State { name : "hover" PropertyChanges { target : previewArea borderColor : root.parent.state == "tabActive" ? tabFocusBorderColor : hoverBorderColor } PropertyChanges { target : previewWindowCloseButton; visible : true } } ] MouseArea { id : previewMouseArea anchors.fill : parent hoverEnabled : true preventStealing : true drag.axis : Drag.XAndYAxis drag.target : root Accessible.role: Accessible.Button Accessible.name: "active-window-" + root.caption Accessible.description: "preview-window, click to active the app window" onEntered : { root.state = "hover" } onExited : { root.state = "default" } onPressed : { windowDragX = mouseX windowDragY = mouseY //拖拽开始时相对于 mainView 的初始位置 var originalPos = mapToItem(allroot, 0, 0) windowOriginalX = originalPos.x windowOriginalY = originalPos.y } onClicked : { controller.onWindowClicked(wid); } onReleased : { root.Drag.drop(); } ColumnLayout { id: mainColumnLayout anchors.fill: parent anchors.centerIn : parent spacing : 10 * scaleFactor // 标题栏与预览图外边框间距 RowLayout { id : captionRow spacing : Math.floor(8 * scaleFactor) Layout.fillHeight : true Layout.preferredHeight : iconAndCloseButtonHeight Layout.leftMargin : appBorderWidth + spacingWidth Layout.rightMargin: appBorderWidth opacity : titleOpacity layoutDirection: isLayoutLeftToRight ? Qt.LeftToRight : Qt.RightToLeft UkuiItem.Icon { id: iconItem width: iconAndCloseButtonHeight height: width source: icon } UkuiItem.DtThemeText { id : caption verticalAlignment: Qt.AlignVCenter horizontalAlignment: isLayoutLeftToRight ? Qt.AlignLeft : Qt.AlignRight elide : isLayoutLeftToRight ? Text.ElideRight : Text.ElideLeft Layout.fillWidth : true text : "" textColor : UkuiPlatform.GlobalTheme.kFontWhite } CloseButton { id : previewWindowCloseButton width : iconAndCloseButtonHeight height : width radius : width / 2 windowType : "app" Accessible.name: "close-window-" + caption.text Accessible.description: "close-button, click to close the app window" onExited: { if (!previewMouseArea.containsMouse) { root.state = "default" } } onClicked: { controller.removePreviewWindow(root.wid) } } }//RowLayout UkuiItem.DtThemeBackground { id : previewArea Layout.fillWidth: true Layout.fillHeight: false Layout.preferredHeight : thumbRectangleHeight + 2 * appThumbnailMargin color : "transparent" borderColor : tabFocusBorderColor border.width : appBorderWidth radius : UkuiPlatform.GlobalTheme.kRadiusWindow * scaleFactor Rectangle { id : appWindowBack anchors.centerIn: parent height : thumbHeight width : thumbWidth radius : UkuiPlatform.GlobalTheme.kRadiusMenu * scaleFactor color : Qt.rgba(1, 1, 1, 0.5) clip : true layer.enabled : appWindowBack.radius !== 0 layer.effect: MultiEffect { maskEnabled: true maskSource: ShaderEffectSource { sourceItem: Rectangle { id: roundMask width: thumbWidth height: thumbHeight radius: appWindowBack.radius color: "white" // 必须设置颜色以启用 alpha 通道 visible: false // 遮罩不可见,仅用于裁剪 } hideSource: true // 隐藏原始遮罩源 } } Loader { id : appWindowLoader property string thumbnailId : wid height : thumbHeight width : thumbWidth anchors.centerIn: parent source: isWlcom ? "ThumbnailWithWlcom.qml" : "ThumbnailWithKwin.qml" } } } }//culumnLayout } function returnOriginal(x, y) { zoomInAnimation() } function zoomOutAnimation() { transformId.origin.x = windowDragX transformId.origin.y = windowDragY scaleValue = 0.38 titleOpacity = 0 scaleDownAnimation.restart() } function zoomInAnimation() { transformId.origin.x = windowDragX transformId.origin.y = windowDragY scaleValue = 1 titleOpacity = 1 scaleUpAnimation.restart() } transform : Scale{ id : transformId } ParallelAnimation{ id : scaleDownAnimation NumberAnimation { target : transformId property : "xScale" to : scaleValue duration : 300 easing.type : Easing.InOutQuart } NumberAnimation{ target : transformId property : "yScale" to : scaleValue duration : 300 easing.type : Easing.InOutQuart } NumberAnimation{ target : captionRow property : "opacity" to : titleOpacity duration : 300 easing.type : Easing.InOutQuart } } ParallelAnimation{ id : scaleUpAnimation NumberAnimation { target : transformId property : "xScale" to : scaleValue duration : 300 easing.type : Easing.InOutQuart } NumberAnimation{ target : transformId property : "yScale" to : scaleValue duration : 300 easing.type : Easing.InOutQuart } NumberAnimation{ target : captionRow property : "opacity" to : titleOpacity duration : 300 easing.type : Easing.InOutQuart } NumberAnimation { target: root property: "x" duration: 300 to: windowOriginalX easing.type: Easing.InOutQuad } NumberAnimation { target: root property: "y" duration: 300 to: windowOriginalY easing.type: Easing.InOutQuad } onFinished: { //拖拽还原动画结束后,将 appWindow 的父对象改回 thumbnailitem,并重新设置坐标 appWindow.parent = thumbnailitem appWindow.x = 0 appWindow.y = 0 } } } ukui-window-switch-4.21.1.0/windowsview/qml/ArrowButton.qml000066400000000000000000000056661522363675600237310ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import QtQuick 2.12 //ukui-quick import org.ukui.quick.items 1.0 as UkuiItem import org.ukui.quick.platform 1.0 as UkuiPlatform UkuiItem.DtThemeBackground { id : arrowButton width : Math.floor(48 * scaleFactor) height : width radius : UkuiPlatform.GlobalTheme.kRadiusNormal backgroundColor: buttonMouseArea.containsPress ? UkuiPlatform.GlobalTheme.kContainClick : buttonMouseArea.containsMouse ? UkuiPlatform.GlobalTheme.kContainHover : UkuiPlatform.GlobalTheme.kContainGeneralNormal property var direction : "right" Accessible.role: Accessible.Button Accessible.name: "arrow button" + direction Accessible.description: "a push button, click to move the parent view "+ direction UkuiItem.Icon { id: arrowIcon anchors.centerIn: parent width: parent.width / 2 height: width source: direction == "right" ? "ukui-end-symbolic" : "ukui-start-symbolic" mode: UkuiItem.Icon.AutoHighlight } MouseArea { id: buttonMouseArea anchors.fill: parent hoverEnabled: true onClicked : { if (direction == "left") { if (desktopListView.contentX + desktopListView.contentXoffset - desktopMoveDistance > 0) { contentMoveAnimation.to = desktopListView.contentX - desktopMoveDistance contentMoveAnimation.start() } else { contentMoveAnimation.to = 0 - desktopListView.contentXoffset contentMoveAnimation.start() } } if (direction == "right") { if (desktopListView.contentX + desktopListView.contentXoffset + desktopMoveDistance < desktopListView.contentWidth-desktopListView.width) { contentMoveAnimation.to = desktopListView.contentX + desktopMoveDistance contentMoveAnimation.start() } else { contentMoveAnimation.to = desktopListView.contentWidth - desktopListView.width - desktopListView.contentXoffset contentMoveAnimation.start() } } } } } ukui-window-switch-4.21.1.0/windowsview/qml/CloseButton.qml000066400000000000000000000060641522363675600236750ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import QtQuick 2.12 import org.ukui.quick.items 1.0 import org.ukui.quick.platform 1.0 DtThemeBackground { id : root visible : false state : "default" border.width: 1 border.color: "transparent" property string windowType : "none" property var buttonStateList : ["default", "hover", "click"]; property alias closeButtonContainMouse: closeButtonMouseArea.containsMouse signal entered() signal exited() signal pressed() signal clicked() Accessible.role: Accessible.Button Accessible.name: "close button" Accessible.description: "a push button, click to close the preview window or desktop" Accessible.onPressAction: { root.clicked() } states : [ State { name : "default" PropertyChanges { target : root backgroundColor: GlobalTheme.kContainGeneralAlphaNormal } }, State { name : "hover" PropertyChanges { target : root backgroundColor: windowType == "desktop" ? GlobalTheme.kComponentAlphaHover : GlobalTheme.kComponentHover } }, State { name : "click" PropertyChanges { target : root backgroundColor: windowType == "desktop" ? GlobalTheme.kComponentAlphaClick : GlobalTheme.kComponentClick } } ] Icon { id: closeIcon anchors.centerIn: parent width: parent.width / 2 height: parent.height / 2 source: "window-close-symbolic" mode: parent.closeButtonContainMouse ? Icon.AutoHighlight : windowType == "desktop" ? Icon.AutoHighlight : Icon.Highlight } MouseArea { id : closeButtonMouseArea anchors.fill : parent hoverEnabled : true preventStealing: true onEntered: { root.state = "hover" root.entered() } onExited: { root.exited() root.state = "default" } onPressed: { root.state = "press" root.pressed() } onReleased: { root.state = containsMouse ? "hover" : "default" } onClicked: { root.clicked() } } } ukui-window-switch-4.21.1.0/windowsview/qml/Controller.js000066400000000000000000000236721522363675600234060ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // 控制器基类 class Controller { constructor(model, view, manager, acceptedTypeSet) { this.model = model; this.view = view; this.manager = manager; this.acceptedTypeSet = acceptedTypeSet; } // 关闭多任务视图 closeMultitaskView() { this.manager.close(); } // 窗口点击事件处理 onWindowClicked(windowId) {} // 删除预览窗口 removePreviewWindow(windowId) {} // 设置默认态 setDefaultStatus() { this.view.setDefaultStatus(); } // 设置 Hover 态 setHoverStatus() { this.view.setHoverStatus(); } //设置点击状态 setClickStatus() { this.view.setClickStatus(); } // 设置拖拽态 setDragStatus() {} // 设置拖拽接收态 setReceiveStatus() {} // 自己进入目标 onEnterTarget(srcDesktopIndex, destDesktopIndex) {} // 自己离开目标 onExitTarget() {} // 来源进入自己 onSourceEntered(source) {} // 来源离开自己 onSourceExited(source) {} // 自己被释放 onDropSource(source, srcDesktopIndex, destDesktopIndex) {} // 接收来源对象 acceptSource(source, srcDesktopIndex, destDesktopIndex) {} // 拒绝来源对象 rejectSource(source) { source.returnOriginal(source.posX,source.posY); } // 是否合法来源 validateSource(source) { return this.acceptedTypeSet.indexOf(source.windowType) > -1; } // 来源释放在自己区域 onSourceDropped(source, srcDesktopIndex, destDesktopIndex) { if (this.validateSource(source)) { this.acceptSource(source, srcDesktopIndex, destDesktopIndex); } else { this.rejectSource(source); } } } class AppController extends Controller { constructor(model, view, manager, acceptedTypeSet) { super(model, view, manager, acceptedTypeSet); } // 窗口点击事件处理 onWindowClicked(windowId) { this.model.activateAppWindow(windowId); this.manager.close(); } // 删除预览窗口 removePreviewWindow(windowId) { if (this.model.hasModalChildWindow(windowId)) { this.onWindowClicked(windowId); } else { this.model.removeAppWindow(windowId); } } // 自己被释放 onDropSource(source, srcDesktopIndex, destDesktopIndex) { this.model.moveAppWindowToDesktop(source.wid, srcDesktopIndex, destDesktopIndex); } // Up与Down键的走焦目标 keyUpDownSelectWindow(keyStatus,windowPosInfoModel,currentTabIndex) { var currentRow = 0 var currentRowWindowNum = 0 var windowNum = 0 //计算当前获取键盘焦点的窗口位于第几行 for(var i = 0; i < windowPosInfoModel.count; i++) { windowNum += windowPosInfoModel.get(i).rowWindowCount if (currentTabIndex < windowNum) { currentRow = i currentRowWindowNum = windowPosInfoModel.get(i).rowWindowCount break } } //计算当前获取键盘焦点窗口的leftX rightX var currentRowModel = windowPosInfoModel.get(currentRow).model var currentIndexLeftX = 0 var currentIndexRightX = 0 for (var i = 0; i < currentRowWindowNum; i++) { if (currentTabIndex === currentRowModel.get(i).index) { currentIndexLeftX = currentRowModel.get(i).leftX currentIndexRightX = currentRowModel.get(i).rightX break } } //判断应该跳转到上/下一行的哪个窗口 var lastRowModel if (currentRow === 0 && keyStatus) { lastRowModel = windowPosInfoModel.get(windowPosInfoModel.count - 1).model } else if (currentRow === windowPosInfoModel.count - 1 && !keyStatus) { lastRowModel = windowPosInfoModel.get(0).model } else { lastRowModel = keyStatus ? windowPosInfoModel.get(currentRow - 1).model : windowPosInfoModel.get(currentRow + 1).model } var lastIndex = 0 var resultIndex = 0 var result = 0 for (var i = 0; i < lastRowModel.count; i++) { var temp = 0 if (lastRowModel.get(i).rightX < currentIndexLeftX) { lastIndex = i continue; } if (lastRowModel.get(i).leftX > currentIndexRightX) { break; } if (lastRowModel.get(i).leftX <= currentIndexLeftX) { if (lastRowModel.get(i).rightX <= currentIndexRightX) { temp = lastRowModel.get(i).rightX - currentIndexLeftX } else { temp = currentIndexRightX - currentIndexLeftX } } else { if (lastRowModel.get(i).rightX <= currentIndexRightX) { temp = lastRowModel.get(i).rightX - lastRowModel.get(i).leftX } else { temp = currentIndexRightX - lastRowModel.get(i).leftX } } if (temp > result) { result = temp; lastIndex = i } } resultIndex = lastRowModel.get(lastIndex).index return resultIndex } // PageUp与PageDown键的走焦目标 keyPageUpDownSelectWindow(keyStatus,windowPosInfoModel,currentTabIndex) { var currentRow = 0 var lastRowWindowNum = 0 var currentRowWindowNum = 0 var windowNum = 0 for(var i = 0; i < windowPosInfoModel.count; i++) { windowNum += windowPosInfoModel.get(i).rowWindowCount if (currentTabIndex < windowNum) { if (i === 0 && keyStatus) { return currentTabIndex } else if (i === windowPosInfoModel.count - 1 && !keyStatus) { return currentTabIndex } currentRow = i currentRowWindowNum = windowPosInfoModel.get(i).rowWindowCount lastRowWindowNum = keyStatus ? windowPosInfoModel.get(i - 1).rowWindowCount : windowPosInfoModel.get(i + 1).rowWindowCount break } } //判断应该跳转到上一行的哪个窗口 if (keyStatus) { var lastRowModel = windowPosInfoModel.get(currentRow - 1).model var resultIndex = lastRowModel.get(0).index return resultIndex } else{ var lastRowModel = windowPosInfoModel.get(currentRow + 1).model var resultIndex = lastRowModel.get(lastRowWindowNum - 1).index return resultIndex } } } class DesktopController extends Controller { constructor(model, view, manager, acceptedTypeSet) { super(model, view, manager, acceptedTypeSet); } // 窗口点击事件处理 onWindowClicked(desktopIndex) { this.manager.close(); } // 删除预览窗口 removePreviewWindow(desktopIndex) { this.model.removeDesktop(desktopIndex); } // 设置 Hover 态 setHoverStatus() { this.view.setHoverStatus(); this.model.setCurrentDesktop(this.view.wid); } setCurrentDesktop(wid) { this.model.setCurrentDesktop(wid); } // 自己进入目标 onEnterTarget(srcDesktopIndex, destDesktopIndex) { // 进入动画靠 虚拟桌面预览区域的 ListView 自带提供,不需调用 this.model.moveDesktop(srcDesktopIndex, destDesktopIndex); } // 来源进入自己 onSourceEntered(source, srcDesktopIndex, destDesktopIndex) { source.controller.onEnterTarget(srcDesktopIndex, destDesktopIndex); } // 来源离开自己 onSourceExited(source) { source.controller.onExitTarget(); this.setDefaultStatus(); } // 接收来源对象 acceptSource(source, srcDesktopIndex, destDesktopIndex) { source.controller.onDropSource(source, srcDesktopIndex, destDesktopIndex); } } class CloseButtonController extends Controller { constructor(model, view, manager, acceptedTypeSet) { super(model, view, manager, acceptedTypeSet); } } class CreationController extends Controller { constructor(model, view, manager, acceptedTypeSet) { super(model, view, manager, acceptedTypeSet); } // 窗口点击事件处理 onWindowClicked(/*unused*/) { this.model.appendDesktop(); } // 来源进入自己 onSourceEntered(source) { if (!validateSource(source)) { return; } source.controller.onEnterTarget(srcDesktopIndex, destDesktopIndex); } // 来源离开自己 onSourceExited(source) { if (!validateSource(source)) { return; } source.controller.onExitTarget(); } // 接收来源对象 acceptSource(source, srcDesktopIndex, destDesktopIndex) { this.model.appendDesktop(); source.controller.onDropSource(source, srcDesktopIndex, destDesktopIndex); // 设置新建的虚拟桌面为当前虚拟桌面。 } } ukui-window-switch-4.21.1.0/windowsview/qml/DesktopArea.qml000066400000000000000000000303601522363675600236320ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import QtQuick 2.12 import QtQuick.Layouts 1.3 import QtQuick.Window 2.12 import DesktopListModel 1.0 //ukui-quick import org.ukui.quick.items 1.0 as UkuiItem import org.ukui.quick.platform 1.0 as UkuiPlatform FocusScope { id : root //虚拟桌面的各个参数 property bool desktopHoverStatus : false //虚拟桌面标题栏高度 property int desktopCaptionHeight : Math.floor(32 * scaleFactor) property int spacing : Math.floor(24 * scaleFactor) property int desktopRectWidth : desktopThumbnailWidth + 2 * workspaceBorderWidth property int desktopRectHeight : desktopRect.height property int desktopMoveDistance : desktopRectWidth / 2 UkuiItem.DtThemeBackground { id : desktopRect anchors.fill : parent useStyleTransparency : true backgroundColor : UkuiPlatform.GlobalTheme.kContainGeneralNormal MouseArea { id : desktopMouseArea anchors.fill : parent hoverEnabled : true onEntered: { desktopHoverStatus = true } onExited: { desktopHoverStatus = false } onClicked: { focus = true } onWheel: { if (!hScrollBar.visible) { return; } // 鼠标滚轮操作滚动条 if (wheel.angleDelta.y > 0) { hScrollBar.decrease(); } else if (wheel.angleDelta.y < 0) { hScrollBar.increase(); } } ListView { id : desktopListView anchors.fill : parent property bool initMultitask : true orientation : ListView.Horizontal layoutDirection: isLayoutLeftToRight ? Qt.LeftToRight : Qt.RightToLeft property int contentXoffset : isLayoutLeftToRight ? 0 : contentWidth model : desktopListModel spacing : root.spacing activeFocusOnTab: false clip : true keyNavigationEnabled: true interactive: true UkuiItem.DtThemeScrollBar.horizontal: UkuiItem.DtThemeScrollBar { id: hScrollBar policy: UkuiItem.DtThemeScrollBar.AsNeeded visual: parent.contentWidth > parent.width } onActiveFocusChanged: { if (desktopListView.activeFocus) { currentIndex = 0 } // interactive == false,透传鼠标事件,使desktopMouseArea clicked事件得以触发,退出工作区名称编辑状态 // interactive == true,截获鼠标事件,ListView交互生效 interactive = !activeFocus } Keys.onPressed: { if (rootWindow.isWlcom) { multitaskViewManager.keyNavigationDataCollect(event.key) } if (event.key === Qt.Key_PageUp || event.key === Qt.Key_Home) { if (currentIndex === 0) { return } currentIndex = 0 if (isLayoutLeftToRight && desktopListView.contentX > 0) { contentMoveAnimation.to = 0 contentMoveAnimation.start() } else if (!isLayoutLeftToRight && desktopListView.contentX + desktopListView.width < 0) { contentMoveAnimation.to = - desktopListView.width contentMoveAnimation.start() } } else if (event.key === Qt.Key_PageDown || event.key === Qt.Key_End) { if (currentIndex === desktopListModel.rowCount() - 2) { return } currentIndex = desktopListModel.rowCount() - 2 if (isLayoutLeftToRight && desktopListView.contentX < desktopListView.contentWidth - desktopListView.width) { contentMoveAnimation.to = desktopListView.contentWidth - desktopListView.width contentMoveAnimation.start() } else if (!isLayoutLeftToRight && desktopListView.contentX + desktopListView.contentWidth > 0) { contentMoveAnimation.to = - desktopListView.contentWidth contentMoveAnimation.start() } } else if (event.key === Qt.Key_Left && currentIndex === 0) { // 当焦点在第一个工作区,不响应左键;在其他工作区则正常响应左键 return } if (event.key === Qt.Key_Tab || event.key === Qt.Key_Left || event.key === Qt.Key_Right || event.key === Qt.Key_Home || event.key === Qt.Key_End || event.key === Qt.Key_PageUp || event.key === Qt.Key_PageDown) { multitaskViewManager.setShouldShowTabBorder(true); event.accepted = false; } } //这里实现了虚拟桌面listview的居中 NumberAnimation { id : desktopListViewLeftMarginAni target : desktopListView property : isLayoutLeftToRight ? "leftMargin" : "rightMargin" duration : 300 easing.type : Easing.InOutQuad } populate: Transition { NumberAnimation { properties : "scale,opacity" from : 0 to : 1 duration : 300 easing.type : Easing.InOutQuad } } add : Transition { NumberAnimation { properties : "scale,opacity" from : 0 to : 1 duration : 400 easing.type : Easing.InOutQuad } } remove : Transition { NumberAnimation { properties : "scale,opacity" from : 1 to : 0 duration : 400 easing.type : Easing.InOutQuad } } removeDisplaced : Transition { NumberAnimation { properties : "x,y" duration : 400 } } move : Transition { NumberAnimation { property : "x" duration : 200 easing.type : Easing.InOutQuad } } moveDisplaced : Transition { NumberAnimation { property : "x" duration : 200 easing.type : Easing.InOutQuad } } onCountChanged : { if (initMultitask || count <= 0) { if (count === desktopListModel.rowCount()) { initMultitask = false; } return; } var newWidth = desktopRectWidth * count + desktopListView.spacing * (count - 1) desktopListViewLeftMarginAni.to = (rootWindow.width - newWidth) / 2 < 0 ? 0 : (rootWindow.width - newWidth) / 2 desktopListViewLeftMarginAni.start() } Connections { target: multitaskViewManager function onDesktopDataUpdated() { desktopListView.model = {} desktopListView.model = desktopListModel } } function getWorkspaceItemOrNewWorkspaceItem(type) { if(type === "newDesktop") { return "NewDesktopButton.qml" } return "VirtualDesktopWindow.qml" } NumberAnimation { id : moveToScrollEndAnimation target : desktopListView property : "contentX" from : desktopListView.contentX to : isLayoutLeftToRight ? desktopListView.contentWidth + desktopRectWidth + root.spacing - desktopListView.width : - desktopListView.contentWidth - desktopRectWidth - root.spacing duration : 300 easing.type : Easing.InOutQuart } function moveToScrollEnd() { if (desktopListView.contentWidth + desktopRectWidth + root.spacing > desktopListView.width && desktopListView.count < 16) { moveToScrollEndAnimation.restart() } } Connections { target: desktopListModel function onDesktopAppended(desktopIndex) { desktopListView.moveToScrollEnd(desktopIndex) } } delegate: Loader { source : desktopListView.getWorkspaceItemOrNewWorkspaceItem(model.ItemType) onLoaded: { if ("customName" in item) { item.customName = model.CustomName } } Connections { target: item function onCustomNameChanged() { if (model.CustomName !== item.customName) { desktopListModel.setData(desktopListModel.index(index, 0), item.customName, DesktopListModel.CustomName) } } } } } // desktopListView NumberAnimation { id : contentMoveAnimation target : desktopListView property : "contentX" from : desktopListView.contentX duration : 300 easing.type : Easing.InOutQuart } ArrowButton { id : leftButton visible : desktopHoverStatus && desktopListView.contentX + desktopListView.contentXoffset > 0 x : Math.floor(48 * scaleFactor) y : (parent.height-leftButton.height)/2 direction: "left" } ArrowButton { id : rightButton visible : desktopHoverStatus && desktopListView.contentX + desktopListView.contentXoffset < desktopListView.contentWidth-desktopListView.width x : parent.width - Math.floor(48 * scaleFactor) - rightButton.width y : (parent.height-rightButton.height)/2 direction: "right" } } } } ukui-window-switch-4.21.1.0/windowsview/qml/LineEdit.qml000066400000000000000000000074751522363675600231400ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: zy-yuan1 * */ import QtQuick 2.15 //ukui-quick import org.ukui.quick.items 1.0 as UkuiItem import org.ukui.quick.platform 1.0 as UkuiPlatform UkuiItem.DtThemeBackground { id: rootItem property bool editable: false property bool enableLayoutMirroring: false property string defaultText: "" property string itemDisplayText: defaultText property int contentTextWidth: textDisplay.contentWidth property bool isDefaultText : false signal textEditingFinished() implicitWidth: 100 implicitHeight: 32 color: "transparent" borderColor: editable ? UkuiPlatform.GlobalTheme.kBrandNormal : UkuiPlatform.GlobalTheme.kGrayAlpha0 border.width : 2 radius: 4 Accessible.role: Accessible.Button Accessible.name: "edit-text-" + itemDisplayText Accessible.description: "push-button, click to modify the text" MouseArea { id: rootMouseArea anchors.fill: parent hoverEnabled: true preventStealing: true cursorShape: editable ? Qt.IBeamCursor : Qt.ArrowCursor onClicked: { if (!editable) { // 点击进入编辑状态 editable = true; } } } onEditableChanged: { if (editable) { // 单击进入textInput可输入状态,需要将焦点强制转移给textInput textInput.forceActiveFocus(); textInput.selectAll(); } // 更新Text显示文本 updateItemDisplayText(); textInput.text = itemDisplayText } TextInput { id: textInput anchors.fill: parent anchors.centerIn : parent anchors.leftMargin : 4 anchors.rightMargin : 4 horizontalAlignment: TextInput.AlignLeft verticalAlignment: TextInput.AlignVCenter LayoutMirroring.enabled: enableLayoutMirroring clip: true maximumLength : 32 focus: true selectByMouse: true color: UkuiPlatform.GlobalTheme.kFontPrimary.pureColor selectionColor: UkuiPlatform.GlobalTheme.kBrandNormal.pureColor visible: editable text: itemDisplayText onEditingFinished: { editable = false; textEditingFinished() } Keys.priority: Keys.AfterItem Keys.onPressed: { event.accepted = true } } UkuiItem.DtThemeText { id: textDisplay anchors.fill: parent anchors.centerIn: parent horizontalAlignment: Text.AlignLeft LayoutMirroring.enabled: enableLayoutMirroring verticalAlignment: Text.AlignVCenter text: itemDisplayText elide: enableLayoutMirroring ? Text.ElideLeft : Text.ElideRight visible: !editable UkuiItem.Tooltip { anchors.fill: parent mainText: textDisplay.text posFollowCursor: true active: !editable && textDisplay.truncated } } function updateItemDisplayText() { itemDisplayText = textInput.length > 0 ? textInput.displayText : rootItem.defaultText isDefaultText = textInput.length > 0 ? false : true } } ukui-window-switch-4.21.1.0/windowsview/qml/MasterDesktopArea.qml000066400000000000000000000175101522363675600250100ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* 虚拟桌面的UI和功能的处理,也是加载创建预览窗口 虚拟桌面区域的窗口和窗口区域的窗口都来自一个"类” */ import QtQuick 2.12 import QtQuick.Controls 2.5 import QtQuick.Layouts 1.3 import QtQuick.Window 2.12 //ukui-quick import org.ukui.quick.items 1.0 as UkuiItem import org.ukui.quick.platform 1.0 as UkuiPlatform FocusScope { id : root //虚拟桌面的各个参数 property bool desktopHoverStatus : false //虚拟桌面标题栏高度 property int desktopCaptionHeight : Math.floor(32 * scaleFactor) property int spacing : Math.floor(24 * scaleFactor) property int desktopRectWidth : desktopRect.height property int desktopRectHeight : desktopThumbnailHeight + 2 * workspaceBorderWidth + spacingWidth + desktopCaptionHeight property int listviewTopMargin : Math.floor(24 * scaleFactor) UkuiItem.DtThemeBackground { id : desktopRect anchors.fill : parent useStyleTransparency : true backgroundColor : UkuiPlatform.GlobalTheme.kContainGeneralNormal MouseArea { id : desktopMouseArea anchors.fill : parent hoverEnabled : true onEntered: { desktopHoverStatus = true } onExited: { desktopHoverStatus = false } ListView { id : desktopListView anchors.fill : parent anchors.topMargin : root.listviewTopMargin property bool initMultitask : true orientation : ListView.Vertical model : desktopListModel spacing : root.spacing activeFocusOnTab: false clip : true onActiveFocusChanged: { if (desktopListView.activeFocus) { currentIndex = 0 } } Keys.onPressed: { if (event.key === Qt.Key_PageUp || event.key === Qt.Key_Home) { if (currentIndex === 0) { return } currentIndex = 0 if (desktopListView.contentY > 0){ contentMoveAnimation.to = 0 contentMoveAnimation.start() } } else if (event.key === Qt.Key_PageDown || event.key === Qt.Key_End) { if (currentIndex === desktopListModel.rowCount() - 2) { return } currentIndex = desktopListModel.rowCount() - 2 if (desktopListView.contentY < desktopListView.contentHeight - desktopListView.height) { contentMoveAnimation.to = desktopListView.contentHeight - desktopListView.height contentMoveAnimation.start() } } } ScrollBar.vertical: ScrollBar { id : deskVbar hoverEnabled : true active : hovered || pressed //定义样式 contentItem : Rectangle { implicitWidth : Math.floor(8 * scaleFactor) radius : Math.floor(4 * scaleFactor) visible : desktopHoverStatus && desktopListView.contentHeight > desktopListView.height color : deskVbar.hovered || deskVbar.pressed ? UkuiPlatform.GlobalTheme.kComponentAlphaHover : UkuiPlatform.GlobalTheme.kComponentAlphaNormal } } populate: Transition { NumberAnimation { properties : "scale,opacity" from : 0 to : 1 duration : 400 easing.type : Easing.InOutQuad } } add : Transition { NumberAnimation { properties : "scale,opacity" from : 0 to : 1 duration : 300 easing.type : Easing.InOutQuad } } remove : Transition { NumberAnimation { properties : "scale,opacity" from : 1 to : 0 duration : 300 easing.type : Easing.InOutQuad } } removeDisplaced : Transition { NumberAnimation { properties : "x,y" duration : 300 } } move : Transition { NumberAnimation { property : "y" duration : 200 easing.type : Easing.InOutQuad } } moveDisplaced : Transition { NumberAnimation { property : "y" duration : 200 easing.type : Easing.InOutQuad } } function getWorkspaceItemOrNewWorkspaceItem(type) { if(type === "newDesktop") { return "NewDesktopButton.qml" } return "VirtualDesktopWindow.qml" } NumberAnimation { id : moveToScrollEndAnimation target : desktopListView property : "contentY" from : desktopListView.contentY to : desktopListView.contentHeight + desktopRectHeight + root.spacing - desktopListView.height duration : 300 easing.type : Easing.InOutQuart } function moveToScrollEnd() { if (desktopListView.contentHeight + desktopRectHeight + root.spacing > desktopListView.height && desktopListView.count < 16) { moveToScrollEndAnimation.restart() } } Connections { target: desktopListModel function onDesktopAppended(desktopIndex) { desktopListView.moveToScrollEnd(desktopIndex) } } delegate: Loader { source : desktopListView.getWorkspaceItemOrNewWorkspaceItem(model.ItemType) } } // desktopListView } NumberAnimation { id : contentMoveAnimation target : desktopListView property : "contentY" from : desktopListView.contentY to : desktopListView.contentY duration : 300 easing.type : Easing.InOutQuart } } } ukui-window-switch-4.21.1.0/windowsview/qml/MultitaskView.qml000066400000000000000000000145201522363675600242400ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import QtQuick 2.12 import QtQuick.Layouts 1.3 import QtQuick.Window 2.12 import org.kylin.background 3.0 as KWin //ukui-quick import org.ukui.quick.platform 1.0 as UkuiPlatform import AppWindowFilterModel 1.0 Repeater { id : allroot model : screencnt focus: true Keys.enabled: true property int screencnt : multitaskViewModel.logicalScreenCount function closeMultitaskView() { console.log("closeMultitaskView() !") multitaskViewManager.close() } Keys.onPressed : { if (event.key === Qt.Key_Escape) { closeMultitaskView(); return; } if (event.modifiers & Qt.MetaModifier) { if (event.key === Qt.Key_Tab) { closeMultitaskView(); return; } } } Rectangle { id : rootWindow visible: allroot.visible x : rootWindow.screenRect.x y : rootWindow.screenRect.y width : rootWindow.screenRect.width height : rootWindow.screenRect.height property var isWlcom : multitaskViewManager.isWlcom() property var isVerticalLayout : multitaskViewManager.isMultitaskViewVerticalLayout() property int highlightDesktop : multitaskViewModel.highlightDesktop property var screenRect : multitaskViewModel.screenRectList[index] //getFullScreenGeometry(highlightDesktop, index) property var scaleFactor : devicePixelRatio property bool isTouchState : multitaskViewModel.isTouchState // focus border color property var hoverBorderColor : UkuiPlatform.GlobalTheme.kWhite property var tabFocusBorderColor : UkuiPlatform.GlobalTheme.kBrandNormal property var defaultBorderColor : UkuiPlatform.GlobalTheme.kGrayAlpha0 // focus border width property int iconAndCloseButtonHeight : 32 * scaleFactor property int appBorderWidth : 4 * scaleFactor property int workspaceBorderWidth : 3 * scaleFactor property int spacingWidth : 2 * scaleFactor property int thumbRectangleHeight : isVerticalLayout ? Math.floor(screenRect.height * 5 / 22) : Math.floor(screenRect.height * 5 / 23) // 工作区窗口缩放比 property double desktopScale : isVerticalLayout ? 16 / 135 : 57 / 480 // 工作区窗口的高度和宽度 property int desktopThumbnailWidth : screenRect.width * desktopScale property int desktopThumbnailHeight : screenRect.height * desktopScale //水平布局方向 property bool isLayoutLeftToRight: multitaskViewManager.isLayoutLeftToRight() KWin.DesktopBackground { id : wholeDesktopBackground width : rootWindow.width height : rootWindow.height blurAlpha : 0.7 } FocusScope { id: mainView anchors.fill: parent focus: true width: parent.width height: parent.height property var screenIndex : index AppWindowFilterModel { id: appAreaModel desktopId: rootWindow.highlightDesktop screenId: mainView.screenIndex sourceModel: appWindowListModel } Loader { id: viewLoader sourceComponent: isVerticalLayout ? verticalLayoutView : horizontalLayoutView anchors.fill: parent } Component { id: verticalLayoutView Rectangle { color: "transparent" AppArea { id : appArea1 anchors.left : parent.left anchors.right : parent.right anchors.top : parent.top height : Math.floor(mainView.height * 111 / 135) width: parent.width Component.onCompleted : { console.log("AppArea end! ! !") } } DesktopArea { id : desktopArea1 anchors.left : parent.left anchors.right : parent.right anchors.top : appArea1.bottom anchors.bottom : parent.bottom } Component.onCompleted : { console.log("verticalLayoutView end! ! !") } } } Component { id: horizontalLayoutView Rectangle { color: "transparent" AppArea { id : appArea2 anchors.left : parent.left anchors.bottom : parent.bottom anchors.top : parent.top height: parent.height width : Math.floor(mainView.width * 410 / 480) Component.onCompleted : { console.log("MasterAppArea end! ! !") } } MasterDesktopArea { id : desktopArea2 anchors.left : appArea2.right anchors.right : parent.right anchors.top : parent.top anchors.bottom : parent.bottom } Component.onCompleted : { console.log("horizontalLayoutView end! ! !") } } } } } } ukui-window-switch-4.21.1.0/windowsview/qml/NewDesktopButton.qml000066400000000000000000000150341522363675600247100ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import QtQuick 2.12 import QtQuick.Layouts 1.3 import QtQuick.Window 2.12 import "Controller.js" as Controller //ukui-quick import org.ukui.quick.items 1.0 as UkuiItem import org.ukui.quick.platform 1.0 as UkuiPlatform Item { id : root width : isVerticalLayout ? desktopRectWidth : desktopRect.width height : isVerticalLayout ? desktopRect.height - 8 : desktopRectHeight activeFocusOnTab: true focus : true property string windowType : "creation" property var newWorkspaceController : new Controller.CreationController(multitaskViewModel, root, multitaskViewManager, ["app","desktop"]); // 用户自定义工作区名称 property string customName: "" onActiveFocusChanged: { if (root.activeFocus) { desktopListView.currentIndex = desktopListView.count - 1 if (isVerticalLayout && desktopListView.contentX + desktopListView.contentXoffset < desktopListView.contentWidth - desktopListView.width) { contentMoveAnimation.to = isLayoutLeftToRight ? desktopListView.contentWidth - desktopListView.width : -desktopListView.contentWidth contentMoveAnimation.start() } if (!isVerticalLayout && desktopListView.contentY < desktopListView.contentHeight - desktopListView.height) { contentMoveAnimation.to = desktopListView.contentHeight + listviewTopMargin - desktopListView.height contentMoveAnimation.start() } multitaskViewManager.activeAreaChangeDataCollect("New Workspace Button Area") } } Keys.onPressed: { if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) { newWorkspaceController.onWindowClicked() event.accepted = true } else if (event.key === Qt.Key_Escape) { newWorkspaceController.closeMultitaskView() } else if (event.modifiers & Qt.MetaModifier) { if (event.key === Qt.Key_Tab) { newWorkspaceController.closeMultitaskView() } } else if (event.key === Qt.Key_Tab) { if (appAreaModel.rowCount() === 0) { desktopListView.currentIndex = 0 multitaskViewManager.setShouldShowTabBorder(true) } } } states: State { name: "active" when: root.activeFocus && (multitaskViewManager.shouldShowTabBorder) PropertyChanges { target: createDesktopButtonBorder; borderColor : tabFocusBorderColor} } Item { anchors.fill: parent anchors.centerIn : parent MouseArea { id : previewMouseArea anchors.fill : parent preventStealing : true Accessible.role: Accessible.Button Accessible.name: "new-desktop" Accessible.description: "push-button, click to create a new desktop" onClicked : { newWorkspaceController.onWindowClicked() } } ColumnLayout { id : mainVerticalLayout anchors.fill: parent anchors.centerIn : parent spacing : spacingWidth UkuiItem.DtThemeText { id : caption verticalAlignment: Qt.AlignVCenter horizontalAlignment: isLayoutLeftToRight ? Qt.AlignLeft : Qt.AlignRight elide : isLayoutLeftToRight ? Text.ElideRight : Text.ElideLeft Layout.fillWidth : true Layout.fillHeight : true Layout.preferredHeight: desktopCaptionHeight Layout.maximumHeight: root.height - mainVerticalLayout.spacing - createDesktopButtonBorder.height Layout.leftMargin : workspaceBorderWidth text : qsTr("New Desktop") UkuiItem.Tooltip { anchors.fill: parent mainText: caption.text posFollowCursor: true active: caption.truncated } MouseArea { id: captionArea anchors.fill: parent hoverEnabled: true } } UkuiItem.DtThemeBackground { id : createDesktopButtonBorder Layout.fillWidth: true Layout.fillHeight: false Layout.preferredHeight: desktopThumbnailHeight + 2 * border.width color : "transparent" border.width : workspaceBorderWidth borderColor : defaultBorderColor radius : UkuiPlatform.GlobalTheme.kRadiusWindow * scaleFactor UkuiItem.DtThemeBackground { id : createDesktopButton width : desktopThumbnailWidth height : desktopThumbnailHeight anchors.centerIn : parent radius : UkuiPlatform.GlobalTheme.kRadiusMenu * scaleFactor backgroundColor : newDesktopDropArea.containsDrag ? UkuiPlatform.GlobalTheme.kGrayAlpha9 : UkuiPlatform.GlobalTheme.kModalMask UkuiItem.Icon { anchors.centerIn: parent width: Math.floor(32 * scaleFactor) height: width source: "list-add-symbolic" mode: UkuiItem.Icon.AutoHighlight } DropArea { id : newDesktopDropArea anchors.fill : parent onDropped : { newWorkspaceController.onSourceDropped(drop.source, rootWindow.highlightDesktop, desktopListView.count); } } } } }//culumnLayout } } ukui-window-switch-4.21.1.0/windowsview/qml/Tabbox.qml000077500000000000000000000365231522363675600226610ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import QtQuick 2.0 import QtQuick.Layouts 1.3 import QtQuick.Effects import "Controller.js" as Controller import org.kylin.thumbnail 1.0 as WlcomThumbnail import AppWindowFilterModel 1.0 //ukui-quick import org.ukui.quick.items 1.0 as UkuiItem import org.ukui.quick.platform 1.0 as UkuiPlatform //flow import org.ukui.positioner 1.0 FocusScope { id: root property int currentIndex: 0 property real yOffset: tabbox.shadowHeight width: tabbox.width height: tabbox.height + 2 * tabbox.shadowHeight focus: true UkuiItem.DtThemeBackground { id : tabbox anchors.centerIn: parent property var controller : new Controller.AppController(multitaskViewModel, tabbox, multitaskViewManager, ["none"]); property rect screenGeometry : multitaskViewManager.currentScreenRect property bool isOpenGL : true property int maxHeight : screenGeometry.height * 0.85 property var scaleFactor : devicePixelRatio property int viewMargin : 20 * scaleFactor property bool isLayoutLeftToRight: Qt.application.layoutDirection === Qt.LeftToRight property real shadowHeight : shadow.size + Math.abs(shadow.yOffset) focus : true useStyleTransparency : true backgroundColor : UkuiPlatform.GlobalTheme.kComponentNormal width : screenGeometry.width height : tabboxFlickable.height Keys.enabled : true border.width : UkuiPlatform.GlobalTheme.normalLine * scaleFactor borderColor : UkuiPlatform.GlobalTheme.kLineWindowActive shadowData: UkuiPlatform.GlobalTheme.kShadowMenu // TODO: replace 2 DtThemeBackgrounds by UkuiPlatform multi-shadow item, if supported. Loader { id: childShadowLoader anchors.fill: parent sourceComponent: childShadowComponent active: tabbox.shadowData.isMultiShadow onLoaded: { tabbox.shadowHeight = Math.max( tabbox.shadow.size, item.shadowHeight) } } Component { id: childShadowComponent UkuiItem.DtThemeBackground { property real shadowHeight : shadow.size + Math.abs(shadow.yOffset) anchors.fill: parent useStyleTransparency: false alpha: 0 shadowData: tabbox.shadowData.childShadow } } onActiveFocusChanged : { if(!tabbox.activeFocus) { multitaskViewManager.close() } else { /** 1. wlcom环境特定情况(快速操作按下alt+tab并松开)下,会出现本界面不隐藏问题,原因如下: 由于wlcom合成器与窗口选择器是两个独立的进程,使得窗口选择器被快捷键拉起时,向合成器发出的GrabKeyboard请求未被及时响应 导致在特定情况下窗口选择器无法收到Key_Alt的Released信号,进而无法通过响应alt released事件来关闭此界面 2. 当前实现,此界面显示时可以认为Key_Alt必定处于按下状态,因此针对特定情况处理如下: 在此界面显示并获取键盘焦点后,立即查询Key_Alt是否处于按下状态 如果按未处于按下状态,则激活选定窗口并退出;否则,不做特殊处理 **/ // fix https://gitee.com/openkylin/ukui-window-switch/issues/IAID8L?from=project-issue if (!multitaskViewManager.isAltKeyPressed()) { activateSelectedWindow(); return; } if (multitaskViewManager.isBackTab) { currentIndex = appWindowListModel.rowCount() > 1 ? appWindowListModel.rowCount() - 1 : 0; } else { currentIndex = appWindowListModel.rowCount() > 1 ? 1 : 0; } } } Flickable { id: tabboxFlickable anchors.leftMargin: tabbox.viewMargin //注意:间距为0则无法显示滚动条 anchors.rightMargin: tabbox.viewMargin width: contentWidth height: Math.min(contentHeight, tabbox.maxHeight) contentWidth: parent.width - 2 * tabbox.viewMargin contentHeight: tabboxFlow.height LayoutMirroring.enabled: !tabbox.isLayoutLeftToRight LayoutMirroring.childrenInherit: true clip: true UkuiItem.DtThemeScrollBar.vertical: UkuiItem.DtThemeScrollBar { id: tabboxScrollBar parent: tabboxFlickable.parent anchors.top: tabboxFlickable.top anchors.left: tabboxFlickable.right anchors.bottom: tabboxFlickable.bottom policy: UkuiItem.DtThemeScrollBar.AsNeeded visual: tabboxFlow.height > height } NumberAnimation { id : scrollMoveAnimation target : tabboxScrollBar property : "position" from : tabboxScrollBar.position duration : 300 easing.type : Easing.InOutQuart } UkuiFlow { id: tabboxFlow spacing: 8 * tabbox.scaleFactor padding: tabbox.viewMargin width: parent.width flow: Flow.LeftToRight layoutDirection: Qt.LeftToRight lineHorizontalCenterAlignment: true Connections { target: previewItemRepeater function onCountChanged() { tabboxFlow.forceLayout(); } } Repeater { id : previewItemRepeater model: appWindowListModel delegate: UkuiItem.DtThemeBackground { id: previewItem property string uuid: model.Uuid property int spaceWidth: 4 * tabbox.scaleFactor property int outerBorderWidth: UkuiPlatform.GlobalTheme.focusLine * tabbox.scaleFactor property int innerBorderWidth: UkuiPlatform.GlobalTheme.focusLine * tabbox.scaleFactor property int maxThumbnailWidth: (tabbox.screenGeometry.width - 2 * tabboxFlow.padding) / 4 property int thumbnailHeight: tabbox.screenGeometry.height / 22 * 5 property int minWidth: Math.floor(tabbox.width / 10) width: Math.max(thumbnailBorderItem.width + 2 * (spaceWidth + outerBorderWidth), minWidth) height: captionRow.height + thumbnailHeight + 5 * spaceWidth + 2 * (innerBorderWidth + outerBorderWidth) color: "transparent" borderColor: UkuiPlatform.GlobalTheme.kFontStrong border.width: index === currentIndex ? outerBorderWidth : 0 radius: tabbox.isOpenGL ? UkuiPlatform.GlobalTheme.kRadiusWindow : 0 MouseArea { anchors.fill: parent hoverEnabled: true Accessible.role: Accessible.Button Accessible.name: "active-window-" + model.caption Accessible.description: "preview-window, click to active the app window" onEntered : { thumbnailBorderItem.border.width = previewItem.innerBorderWidth; } onExited : { thumbnailBorderItem.border.width = 0; } onClicked : { currentIndex = index; tabbox.controller.onWindowClicked(model.Uuid); } } function getThumbnailSize() { var thumbHeight = thumbnailHeight var max_width = maxThumbnailWidth var clientWidth = model.Width var clientHeight = model.Height var thumbWidth = Math.floor(thumbHeight * clientWidth / clientHeight) if (thumbWidth > max_width) { thumbWidth = max_width thumbHeight = Math.floor(thumbWidth * clientHeight / clientWidth) } return [thumbWidth, thumbHeight] } ColumnLayout { anchors.fill: parent anchors.centerIn: parent anchors.margins: previewItem.spaceWidth spacing: 4 * tabbox.scaleFactor RowLayout { id: captionRow spacing: 8 * tabbox.scaleFactor Layout.preferredHeight: Math.max(iconItem.height, captionText.height) Layout.alignment: Qt.AlignCenter Layout.leftMargin: 2 * previewItem.spaceWidth UkuiItem.Icon { id: iconItem width: 24 * tabbox.scaleFactor height: width source: model.Icon } UkuiItem.DtThemeText { id: captionText verticalAlignment: Qt.AlignVCenter Layout.fillWidth: true Layout.preferredHeight: contentHeight text: model.Caption horizontalAlignment: Qt.AlignLeft elide: Text.ElideRight } } // RowLayout UkuiItem.DtThemeBackground { id: thumbnailBorderItem Layout.alignment: Qt.AlignCenter Layout.preferredWidth: getThumbnailSize()[0] + 2 * (previewItem.innerBorderWidth + previewItem.spaceWidth) Layout.preferredHeight: previewItem.thumbnailHeight + 2 * (previewItem.innerBorderWidth + previewItem.spaceWidth) color: "transparent" borderColor: UkuiPlatform.GlobalTheme.kFontStrong border.width: 0 radius: tabbox.isOpenGL ? UkuiPlatform.GlobalTheme.kRadiusMax : 0 // 预览图阴影 shadowData: UkuiPlatform.GlobalTheme.KShadowMin Rectangle { id: thumbnailBackItem width: getThumbnailSize()[0] height: getThumbnailSize()[1] anchors.centerIn: parent color: "transparent" clip: true layer.enabled: tabbox.isOpenGL ? true : false layer.effect: MultiEffect { maskEnabled: true maskSource: ShaderEffectSource { sourceItem: Rectangle { id: roundMask width: thumbnailBackItem.width height: thumbnailBackItem.height radius: thumbnailBorderItem.thumbnailRadius // 圆角半径 color: "white" // 必须设置颜色以启用 alpha 通道 visible: false // 遮罩不可见,仅用于裁剪 } hideSource: true // 隐藏原始遮罩源 } } WlcomThumbnail.ThumbnailItem { id: thumbnailItem anchors.fill: parent windowId: model.Uuid isActive: multitaskViewManager.altTabVisible } } } } // ColumnLayout } // Repeater.delegate } // Repeater } // Flow } // Flickable Keys.onDeletePressed : { multitaskViewManager.close() } Keys.onEscapePressed : { multitaskViewManager.close() } Keys.onBacktabPressed : { if (!multitaskViewManager.isAltKeyPressed()) { return; } if (isLayoutLeftToRight) { currentIndex = tabboxFlow.moveCurrentIndexLeft(currentIndex); } else { currentIndex = tabboxFlow.moveCurrentIndexRight(currentIndex); } } Keys.onTabPressed : { if (isLayoutLeftToRight) { currentIndex = tabboxFlow.moveCurrentIndexRight(currentIndex); } else { currentIndex = tabboxFlow.moveCurrentIndexLeft(currentIndex); } } Keys.onPressed : { if (event.key === Qt.Key_Left) { currentIndex = tabboxFlow.moveCurrentIndexLeft(currentIndex); } else if (event.key === Qt.Key_Right) { currentIndex = tabboxFlow.moveCurrentIndexRight(currentIndex); } else if (event.key === Qt.Key_Up) { currentIndex = tabboxFlow.moveCurrentIndexUp(currentIndex); } else if (event.key === Qt.Key_Down) { currentIndex = tabboxFlow.moveCurrentIndexDown(currentIndex); } else { return; } } Keys.onReleased : { if (event.key === Qt.Key_Alt) { activateSelectedWindow(); } else if (event.key === Qt.Key_Shift && !multitaskViewManager.isAltKeyPressed()) { activateSelectedWindow(); } } function activateSelectedWindow() { controller.onWindowClicked(previewItemRepeater.itemAt(currentIndex).uuid); } } onCurrentIndexChanged: { scrollToTabItem() } function scrollToTabItem() { var currentNextY = previewItemRepeater.itemAt(currentIndex).mapToItem(tabboxFlickable, 0, 0).y var previewWindowHeight = previewItemRepeater.itemAt(currentIndex).height if (currentNextY < 0) { scrollMoveAnimation.to = tabboxScrollBar.position - (-currentNextY + tabbox.viewMargin) / tabboxFlickable.contentHeight scrollMoveAnimation.start() } else if (currentNextY + previewWindowHeight > tabboxFlickable.height) { scrollMoveAnimation.to = tabboxScrollBar.position + (currentNextY + previewWindowHeight - tabboxFlickable.height + tabbox.viewMargin) / tabboxFlickable.contentHeight scrollMoveAnimation.start() } } } ukui-window-switch-4.21.1.0/windowsview/qml/TabletPreviewWindow.qml000066400000000000000000000350101522363675600253720ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import QtQuick 2.12 import QtQuick.Layouts 1.3 import QtQuick.Effects //ukui-quick import org.ukui.quick.items 1.0 as UkuiItem import org.ukui.quick.platform 1.0 as UkuiPlatform Item { id : root property bool closeButtonVisble : false property var screenIndex : null state : "default" property string wid : "" property int x_wid //当前预览窗口在桌面上的未缩放前的实际宽度 property int preViewNoScaledWidth : -1 //当前预览窗口在桌面上的未缩放前的实际高度 property int preViewNoScaledHeight : -1 //当前预览窗口在桌面上的未缩放前的X坐标 property int preViewNoScaledXCoordinate : -1 //当前预览窗口在桌面上的未缩放前的Y坐标 property int preViewNoScaledYCoordinate : -1 property string captionText : "" property real thumbAnchorRootMapGloableX : 0 property real thumbAnchorRootMapGloableY : 0 property int thumbnailRadius : UkuiPlatform.GlobalTheme.kRadiusWindow * tabletScaleFactor property var icon //drag event property bool dragActive: previewWindowMouseArea.drag.active property real dargBeginTime : Date.now() states : [ State { name : "default" PropertyChanges { target : thumbnailWindow; border.width : 0 } PropertyChanges { target : previewWindowCloseButton; visible : false } }, State { name : "hover" PropertyChanges { target : thumbnailWindow; border.width : borderWidth } PropertyChanges { target : previewWindowCloseButton; visible : true } } ] //控制白色边框是否显示 MouseArea { id : previewWindowMouseArea anchors.fill : parent hoverEnabled : true drag.target: root drag.axis: Drag.YAxis drag.maximumY: root.height / 10 Accessible.role: Accessible.Button Accessible.name: "active-window-" + root.caption Accessible.description: "preview-window, click to active the app window" onEntered : { if (!thumbnailWindow.thumbClicked) { root.state = "hover" } } onExited: { root.state = "default" } onClicked: { appWindowClicked() } ColumnLayout { id : columnLayout spacing : iconToThumbSpacing anchors.centerIn : parent Layout.fillHeight : true width : root.width RowLayout { id : captionRow spacing : Math.floor(12 * tabletScaleFactor) Layout.fillHeight : true layoutDirection: isLayoutLeftToRight ? Qt.LeftToRight : Qt.RightToLeft UkuiItem.Icon { id: iconItem width: iconAndCloseButtonHeight height: width source: icon } UkuiItem.DtThemeText { id : caption Layout.fillWidth : true text : captionText fontSizeMode : Text.HorizontalFit horizontalAlignment: isLayoutLeftToRight ? Qt.AlignLeft : Qt.AlignRight elide : isLayoutLeftToRight ? Text.ElideRight : Text.ElideLeft textColor : UkuiPlatform.GlobalTheme.kFontWhite } TabletViewCloseButton { id : previewWindowCloseButton Accessible.name: "close-window-" + captionText Accessible.description: "close-button, click to close the app window" onExited: { if (!previewWindowMouseArea.containsMouse) { root.state = "default" } } onClicked: { removePreviewWindow(wid) } } }//RowLayout captionRow UkuiItem.DtThemeBackground { id : thumbnailWindow height : root.height - iconToThumbSpacing - iconAndCloseButtonHeight width : root.width color : "transparent" radius : root.thumbnailRadius borderColor : UkuiPlatform.GlobalTheme.kWhite border.width : borderWidth property bool thumbClicked: false // 记录是否是点击缩略图 states: [ State { name : "mousestate" when : thumbnailWindow.thumbClicked ParentChange { target : thumbnailBackground parent : tabletViewMain } } ] UkuiItem.DtThemeBackground { id : thumbnailBackground /* * 此处必须使用 x, y, width, height 进行位置设置,且禁止使用 anchors.centerIn 和 anchors.fill 等 * 因为 thumbnailBackground 在动画过程中会改变 parent,所以如果使用锚点会导致 thumbnailBackground * 突然参考新的 parent 改变大小。设置 width 和 height 时,禁止使用 parent.width 和 parent.height * 也是如此。 */ x : borderWidth y : borderWidth width : thumbnailWindow.width - 2 * borderWidth height : thumbnailWindow.height - 2 * borderWidth // anchors.centerIn : parent useStyleTransparency: true backgroundColor : UkuiPlatform.GlobalTheme.kContainGeneralNormal radius : root.thumbnailRadius !== 0 ? root.thumbnailRadius - borderWidth : 0 Loader { id: thumbnail width : Math.floor(thumbWidth()) height : Math.floor(thumbHeight()) anchors.centerIn : parent property string thumbnailId : wid source: isWlcom ? "ThumbnailWithWlcom.qml" : "ThumbnailWithKwin.qml" clip : true layer.enabled : root.thumbnailRadius !== 0 layer.effect: MultiEffect { maskEnabled: true maskSource: ShaderEffectSource { sourceItem: Rectangle { id: roundMask width: thumbnail.width height: thumbnail.height radius: root.thumbnailRadius // 圆角半径 color: "white" // 必须设置颜色以启用 alpha 通道 visible: false // 遮罩不可见,仅用于裁剪 } hideSource: true // 隐藏原始遮罩源 } } function thumbWidth(){ var factor = model.height / thumbnailBackground.height; var width = model.width / factor; return Math.min(thumbnailBackground.width, width); } function thumbHeight(){ var factor = thumbnailBackground.width * model.height var height = factor / model.width; return Math.round(Math.min(thumbnailBackground.height, height)) } } } } } } onDragActiveChanged: { if (dragActive) { enlargeWindowAnimation.start() appWindowReturnBackAnimation.stop() dargBeginTime = Date.now() } else { var subTime = Date.now() - dargBeginTime var subDistance = -root.y var velocity = Math.abs(subDistance) / subTime; // console.log("移动距离: " + subDistance , "窗口的三分之二距离: ", root.height * 2 / 3) // console.log("速度为: " + velocity) // 平均速度或者位移距离 if ((velocity > 0.5 && subDistance > 0 ) || subDistance >= root.height * 2 / 3) { slideUpToCloseWindowAnimation.start() } else { appWindowReturnBackAnimation.start() } } } Connections { target : tabletViewMain function onClearAllWindowButtonClickSignal() { clearAllWindowAnimation.start() } function onBlankAreaClickSignal() { spaceClickedPreWindowAnimation.start() } } /***************************************动画***************************/ // 全部清除窗口的动效 ParallelAnimation { id : clearAllWindowAnimation NumberAnimation { target: root properties: "y" to: Math.floor(root.y - root.height * 2) duration: 300 easing.type: Easing.InOutQuart } NumberAnimation { target: root properties: "opacity" to: 0 duration: 300 easing.type: Easing.InOutQuart } onFinished : { removePreviewWindow(wid) } } // 点击空白处关闭多任务视图动效(小窗口逐渐在原地消失) NumberAnimation { id : spaceClickedPreWindowAnimation target : root property : "opacity" duration : 300 easing.type : Easing.InOutQuart from : 1 to : 0 onFinished: { closeMultitaskView() } } // 上滑关闭窗口动效 SmoothedAnimation { id : slideUpToCloseWindowAnimation target : root property : "y" //因为需要上滑完全离开屏幕 尤其第二行预览窗口,故需要-(预览窗口距离屏幕顶端的距离+预览窗口本身高度) to : Math.floor(0 - root.parent.y - root.height) velocity : 1100 reversingMode: SmoothedAnimation.Eased onFinished: { removePreviewWindow(wid) } } // 上滑窗口 放大窗口 NumberAnimation { id : enlargeWindowAnimation target: root property : "scale" duration : 200 to : 1.05 } // 取消上滑后,恢复到原始位置的动画 ParallelAnimation { id : appWindowReturnBackAnimation SpringAnimation { target : root property : "y" to : 0 easing.type : Easing.InOutQuart damping : 0.15 // 弹簧阻尼值。默认值为0,取值0~1.0。控制 spring : 2 // 弹性。有效值范围是0~5.0,默认值为0(禁用了spring的动作)。 } NumberAnimation { id : restoreWindowSizeAnimation target: root property : "scale" duration : 200 to : 1 } } // 点击应用程序预览窗口激活应用程序时的动画特效,只针对平板模式 ParallelAnimation { id : activateWindowAnimationForTabletMode NumberAnimation { target : thumbnailBackground property : "x" from : thumbAnchorRootMapGloableX to : preViewNoScaledXCoordinate duration : 1000 easing.type : Easing.InOutQuart } NumberAnimation { target : thumbnailBackground property : "y" from : thumbAnchorRootMapGloableY to : preViewNoScaledYCoordinate duration : 1000 easing.type : Easing.InOutQuart } NumberAnimation { target : thumbnailBackground property : "width" to : preViewNoScaledWidth duration : 1000 easing.type : Easing.InOutQuart } NumberAnimation { target : thumbnailBackground property : "height" to : preViewNoScaledHeight duration : 1000 easing.type : Easing.InOutQuart } onFinished: { closeMultitaskView() } } /***************************************函数*************************/ function closeMultitaskView() { multitaskViewManager.close() } function removePreviewWindow(wid) { console.log("removePreviewWindow", wid) if (multitaskViewModel.hasModalChildWindow(wid)) { multitaskViewModel.activateAppWindow(wid) if (multitaskViewModel.isTabletMode()) { activateWindowAnimationForTabletMode.start() } // If window has modal child window, calls close force. multitaskViewManager.close(); } else { // delete app multitaskViewModel.removeAppWindow(wid); } } function appWindowClicked() { if (multitaskViewModel.isTabletMode) { thumbAnchorRootMapGloableX = mapToGlobal(thumbnailBackground.x, thumbnailBackground.y).x thumbAnchorRootMapGloableY = mapToGlobal(thumbnailBackground.x, thumbnailBackground.y).y thumbnailWindow.thumbClicked = true captionRow.visible = false thumbnailWindow.border.width = 0 previewWindowCloseButton.visible = false multitaskViewModel.activateAppWindow(wid) activateWindowAnimationForTabletMode.start() } else { multitaskViewModel.activateAppWindow(wid); closeMultitaskView() } } } ukui-window-switch-4.21.1.0/windowsview/qml/TabletViewCloseButton.qml000066400000000000000000000051631522363675600256630ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import QtQuick 2.12 //ukui-quick import org.ukui.quick.items 1.0 as UkuiItem import org.ukui.quick.platform 1.0 as UkuiPlatform UkuiItem.DtThemeBackground { id : root visible : false width : iconAndCloseButtonHeight height : width radius : width / 2 state : "default" property alias closeButtonContainMouse: closeButtonMouseArea.containsMouse signal entered() signal exited() signal pressed() signal clicked() Accessible.role: Accessible.Button Accessible.name: "close" Accessible.description: "a push button, click to close the preview window" Accessible.onPressAction: { root.clicked() } states : [ State { name : "default" PropertyChanges { target: root; backgroundColor: UkuiPlatform.GlobalTheme.kContainGeneralAlphaNormal } }, State { name : "hover" PropertyChanges { target: root; backgroundColor: UkuiPlatform.GlobalTheme.kComponentHover } }, State { name : "press" PropertyChanges { target: root; backgroundColor: UkuiPlatform.GlobalTheme.kComponentClick } } ] UkuiItem.Icon { id: closeIcon anchors.centerIn: parent width: parent.width / 2 height: parent.height / 2 source: "window-close-symbolic" mode: parent.closeButtonContainMouse ? UkuiItem.Icon.AutoHighlight : UkuiItem.Icon.Highlight } MouseArea{ id : closeButtonMouseArea anchors.fill : parent hoverEnabled : true onEntered: { root.state = "hover" root.entered() } onExited: { root.state = "default" root.exited() } onPressed: { root.state = "press" root.pressed() } onClicked: { root.clicked() } } } ukui-window-switch-4.21.1.0/windowsview/qml/TabletViewMain.qml000066400000000000000000000465211522363675600243110ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import QtQuick 2.12 import QtQuick.Controls 2.5 import QtQuick.Layouts 1.3 import QtQuick.Window 2.12 import org.kylin.background 3.0 as KWin import AppWindowFilterModel 1.0 //ukui-quick import org.ukui.quick.items 1.0 as UkuiItem import org.ukui.quick.platform 1.0 as UkuiPlatform Repeater{ id : allrootRepeater model : screencnt property int screencnt : multitaskViewModel.logicalScreenCount //水平布局方向 property bool isLayoutLeftToRight: multitaskViewManager.isLayoutLeftToRight() Item { id : tabletViewMain property var isWlcom : multitaskViewManager.isWlcom() property var screenRect : multitaskViewModel.getFullScreenGeometry(multitaskViewModel.highlightDesktop, index) // 整体缩放比 property var tabletScaleFactor : screenRect.width > screenRect.height ? screenRect.height / 1080 : screenRect.width / 1080 // 预览窗口宽高比 property real previewWinAspectRatio: screenRect.width / screenRect.height // 图标和缩略图的间距 property int iconToThumbSpacing : 12 * tabletScaleFactor // 图标高度 property int iconAndCloseButtonHeight : 32 * tabletScaleFactor // 缩略图高度 property var preWinHeight // 缩略图宽度 property var preWinWidth property int borderWidth : 4 * tabletScaleFactor // 预览窗口列间距 property var preWinVecSpace // 预览窗口行间距 property var preWinHorSpace // 滚动区域距离左侧和右侧的间距 property var scrollViewLeftSpace // 滚动区域高度 property var scrollViewHeight // 滚动区域 y 轴起始高度 property var scrollViewYStartPoint : getCurrentPreWindowHeight() property ListModel tabletViewRootModel : ListModel{} property var language : multitaskViewModel.getCurrentLanguage() property int screenId: index x : Math.floor(screenRect.x) y : Math.floor(screenRect.y) width : Math.floor(screenRect.width) height : Math.floor(screenRect.height) // 这里放置后台提供的桌面背景的 Item KWin.DesktopBackground { anchors.fill : parent blurAlpha : 0.7 } function getCurrentPreWindowHeight() { console.log("当前开始计算每一个预览窗口的尺寸") if ( screenRect.width > screenRect.height ) { scrollViewYStartPoint = Math.floor(99 * tabletScaleFactor) preWinHeight = Math.floor(324 * tabletScaleFactor) preWinWidth = Math.floor(preWinHeight * previewWinAspectRatio) preWinVecSpace = Math.floor(112 * tabletScaleFactor) preWinHorSpace = Math.floor(56 * tabletScaleFactor) scrollViewLeftSpace = Math.floor(112 * tabletScaleFactor) scrollViewHeight = Math.floor(820 * tabletScaleFactor) } else { scrollViewYStartPoint = Math.floor(196 * tabletScaleFactor) preWinHeight = Math.floor(498 * tabletScaleFactor) preWinWidth = Math.floor(preWinHeight * previewWinAspectRatio) preWinVecSpace = Math.floor(96 * tabletScaleFactor) preWinHorSpace = Math.floor(68 * tabletScaleFactor) scrollViewLeftSpace = Math.floor(96 * tabletScaleFactor) scrollViewHeight = Math.floor(1196 * tabletScaleFactor) } } focus : true property int loadedWindowNum : 0 /* 此处的focus不可以删除,因为后台在grabbedKeyboardEvent()函数中增加了setfocus() 不增加focus:true前端无法接受键盘事件 这是正向解决方法,其他方法非正向解决,不推荐!!! */ signal blankAreaClickSignal() signal clearAllWindowButtonClickSignal() //由于执行小窗口关闭动效时,会关闭多任务视图多次,导致崩溃,故增加此属性 property bool alreadyCloseView: false function sequentialLoadWindow() { var appWindowCount = appListModel.rowCount() var info if (loadedWindowNum < appWindowCount && loadedWindowNum < 6 ) { info = appWindowListModel.getItemData(appListModel.mapToSource(appListModel.index(loadedWindowNum, 0))) tabletViewRootModel.append({"x": info.x, "y": info.y, "width": info.width, "height": info.height, "id": info.id, "minimized": info.minimized, "caption": info.caption, "uuid": String(info.uuid)}); loadedWindowNum = loadedWindowNum + 1 // console.log("加载窗口中,目前已加载窗口数量为" + loadedWindowNum) } else { sequentialLoadWindowTimer.stop() // console.log("计时器停止,窗口数量为: " + tabletViewRootModel.count) } if (loadedWindowNum >= 6) { sequentialLoadWindowTimer.stop() console.log("计时器停止,接下来一次性加载所有窗口") while (loadedWindowNum < appWindowCount) { info = appWindowListModel.getItemData(appListModel.mapToSource(appListModel.index(loadedWindowNum, 0))) tabletViewRootModel.append({"x": info.x, "y": info.y, "width": info.width, "height": info.height, "id": info.id, "minimized": info.minimized, "caption": info.caption, "uuid": String(info.uuid), "icon": info.icon}); loadedWindowNum = loadedWindowNum + 1 } } if (loadedWindowNum >= appWindowCount) { sequentialLoadWindowTimer.stop() // console.log("所有窗口加载完毕,显示全部清除按钮") clearAllWindowButtonAppearAni.start() } } function closeMultitaskView() { if (!alreadyCloseView) { alreadyCloseView = true console.log("closeMultitaskView() !") multitaskViewManager.close() } } // 控制启动动效中,小窗口之间的间隔 Timer { id : sequentialLoadWindowTimer interval : 150 repeat : true running : false triggeredOnStart : false onTriggered: { // console.log("计时器启动 间隔150") tabletViewMain.sequentialLoadWindow() } } UkuiItem.DtThemeBackground { id : scrollBackgroundArea anchors.fill: parent useStyleTransparency: true backgroundColor: UkuiPlatform.GlobalTheme.kModalMask // 无应用时的窗口显示 UkuiItem.DtThemeText { id : noWindowText anchors.centerIn : parent font.bold : true font.pixelSize : Math.floor(25 * tabletScaleFactor) textColor : UkuiPlatform.GlobalTheme.kFontWhite text : qsTr("No recent tasks") // 无应用开启 visible : tabletViewRootModel.count === 0 opacity : 0 SequentialAnimation{ id : noWindowTipsAnimation // 无窗口文字出现动画 NumberAnimation { id : noWindowTipsAppearAni target : noWindowText property : "opacity" duration : 1000 easing.type : Easing.InOutQuart from : 0 to : 1 } // 无窗口文字消失动画 NumberAnimation { id : noWindowTipsDisappearAni target : noWindowText property : "opacity" duration : 1000 easing.type : Easing.InOutQuart from : 1 to : 0 } onFinished: { console.log("无窗口文字消失动画") tabletViewMain.closeMultitaskView() } } } } // 预览窗口显示区域 ScrollView { id : previewWindowShownRegion anchors.fill : parent //更新滚动区域的大小,之所以这么做,是为了解决滚动区域增加鼠标事件后,滚动失效的问题 function getContentWidth() { var maxColumn = Math.ceil(tabletViewRootModel.count / 2) var scrollViewContentWidth = parent.width if (tabletViewRootModel.count <= 4) { scrollViewContentWidth = parent.width return Math.floor(scrollViewContentWidth) } scrollViewContentWidth = maxColumn * preWinWidth + maxColumn * gridLayout.columnSpacing + 2 * gridLayout.leftPadding return Math.floor(scrollViewContentWidth) } contentWidth : Math.floor(previewWindowShownRegion.getContentWidth()) contentHeight : Math.floor(this.height) ScrollBar.horizontal.policy : ScrollBar.AlwaysOff ScrollBar.vertical.policy : ScrollBar.AlwaysOff MouseArea { anchors.fill : parent onClicked : { if (multitaskViewModel.isTabletMode) { multitaskViewManager.setShowingDesktop(true) } tabletViewMain.blankAreaClickSignal() } } Grid { id : gridLayout anchors.fill : parent anchors.centerIn : parent topPadding : Math.floor(scrollViewYStartPoint) columnSpacing : Math.floor(preWinVecSpace) rowSpacing : Math.floor(preWinHorSpace) leftPadding : Math.floor(scrollViewLeftSpace) rightPadding : Math.floor(scrollViewLeftSpace) rows : 2 flow : Grid.TopToBottom transformOrigin : "TopLeft" //显示多任务视图时,每个Item在显示的时候执行的动效 add : Transition { id : displayPreviewWinAnimation ParallelAnimation { NumberAnimation { property : "opacity" duration : 900 easing.type : Easing.InOutQuart from : 0 to : 1 } NumberAnimation { property : "x" duration : 900 easing.type : Easing.InOutQuart from : Math.floor(parent.width / 2 - 510/*窗口的宽度*/ / 2) } NumberAnimation { property : "y" duration : 900 easing.type : Easing.InOutQuart from : Math.floor(parent.height) } NumberAnimation { property : "scale" from : 0 to : 1.0 duration : 450 } } } //关闭小窗口时,W补齐方式的动画 move : Transition { NumberAnimation{ properties : "x,y"; easing.type : Easing.InOutQuart; duration : 300 } } Repeater { id : previewWindowRepeater model : tabletViewRootModel Item { id : appWindowBack height : Math.floor(preWinHeight + iconToThumbSpacing + iconAndCloseButtonHeight) width : Math.floor(preWinWidth) + borderWidth * 2 TabletPreviewWindow { id : appWindow height : parent.height width : parent.width x_wid : model.id wid : model.uuid screenIndex : tabletViewMain.index captionText : model.caption preViewNoScaledWidth : model.width preViewNoScaledHeight : model.height preViewNoScaledXCoordinate : model.x preViewNoScaledYCoordinate : model.y icon: model.icon } } } } } // 清除所有窗口的按钮 UkuiItem.DtThemeBackground { id : clearAllWindowButton property int bottomMargin : 38 * tabletScaleFactor height : Math.floor(48 * tabletScaleFactor) width : language === "Chinese" ? Math.floor(112 * tabletScaleFactor) : Math.floor(184 * tabletScaleFactor) backgroundColor: clearAllMousearea.containsPress ? UkuiPlatform.GlobalTheme.kComponentClick : clearAllMousearea.containsMouse ? UkuiPlatform.GlobalTheme.kComponentHover : UkuiPlatform.GlobalTheme.kComponentNormal radius : Math.floor(24 * tabletScaleFactor) anchors.verticalCenter : parent.verticalCenter anchors.verticalCenterOffset : Math.floor(tabletViewMain.height / 2) - bottomMargin - this.height anchors.horizontalCenter : parent.horizontalCenter visible : tabletViewRootModel.count > 0 opacity : 0 Accessible.role: Accessible.Button Accessible.name: "clear" Accessible.description: "a push button, click to clear all preview windows" Row { anchors.centerIn: parent spacing: Math.floor(8 * tabletScaleFactor) UkuiItem.Icon { id : deleteIcon anchors.verticalCenter : parent.verticalCenter width : Math.floor(16 * tabletScaleFactor) height : Math.floor(16 * tabletScaleFactor) source: "window-close-symbolic" mode: UkuiItem.Icon.AutoHighlight } UkuiItem.DtThemeText { id : deletText anchors.verticalCenter : parent.verticalCenter text : qsTr("Clear") // 清除 elide : isLayoutLeftToRight ? Text.ElideRight : Text.ElideLeft font.pixelSize : Math.floor(18 * tabletScaleFactor) textColor : UkuiPlatform.GlobalTheme.kFontPrimary } } MouseArea { id: clearAllMousearea anchors.fill: parent hoverEnabled: true onClicked: { console.log("全部清除被点击!") clearAllWindowButtonDisappearAni.start() tabletViewMain.clearAllWindowButtonClickSignal() } } //全部清除按钮出现的动画 NumberAnimation { id : clearAllWindowButtonAppearAni target : clearAllWindowButton properties : "opacity" from : 0 to : 1 duration : tabletViewRootModel.count >= 6 ? 5 * 100 + 300 : (tabletViewRootModel.count - 1) * 100 + 300 easing.type : Easing.InOutQuart } //全部清除按钮消失的动画 NumberAnimation { id : clearAllWindowButtonDisappearAni target : clearAllWindowButton properties : "opacity" from : 1 to : 0 duration : 300 easing.type : Easing.InOutQuart } Connections { target : tabletViewMain function onBlankAreaClickSignal() { clearAllWindowButtonDisappearAni.start() } } } Component.onCompleted: { if (multitaskViewModel.currentDesktopHasWindow()) { console.log("顺序加载窗口的启动计时器") sequentialLoadWindowTimer.start() } else { console.log("启动无窗口动画") noWindowTipsAnimation.start() } } Keys.onPressed: { if (event.key === Qt.Key_Escape) { closeMultitaskView(); return; } if (event.modifiers & Qt.MetaModifier) { if (event.key === Qt.Key_Tab) { closeMultitaskView(); return; } } } Timer { id : closeViewTimer interval : 0 repeat : false running : false triggeredOnStart : false onTriggered: { closeMultitaskView() } } AppWindowFilterModel { id: appListModel desktopId: multitaskViewModel.highlightDesktop screenId: tabletViewMain.screenId sourceModel: appWindowListModel } Connections { target: multitaskViewModel function onAppWindowRemoved(windowId) { multitaskViewModel.removeAppWindow(windowId) // remove window from tabletViewRootModel for(var i = 0; i < tabletViewRootModel.count; i++){ var info = tabletViewRootModel.get(i); if(info.uuid === windowId) { tabletViewRootModel.remove(i); break; } } if (!multitaskViewModel.currentDesktopHasWindow()) { closeViewTimer.start() } } } } } ukui-window-switch-4.21.1.0/windowsview/qml/ThumbnailWithKwin.qml000066400000000000000000000016441522363675600250430ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import org.kde.kwin 3.0 as KWinComponents KWinComponents.WindowThumbnailItem { id : appWindowThumbnail anchors.fill : parent wId : thumbnailId } ukui-window-switch-4.21.1.0/windowsview/qml/ThumbnailWithWlcom.qml000066400000000000000000000016761522363675600252210ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import org.kylin.thumbnail 1.0 as WlcomThumbnail WlcomThumbnail.ThumbnailItem { anchors.fill: parent windowId: thumbnailId isActive: multitaskViewManager.winTabVisible } ukui-window-switch-4.21.1.0/windowsview/qml/VirtualDesktopWindow.qml000066400000000000000000000405071522363675600256040ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* 此文件是虚拟桌面的预览窗口的内容设置 */ import QtQuick 2.12 import QtQuick.Layouts 1.3 import QtQuick.Window 2.12 import org.kylin.background 3.0 as KWin import QtQuick.Effects import "Controller.js" as Controller //ukui-quick import org.ukui.quick.items 1.0 as UkuiItem import org.ukui.quick.platform 1.0 as UkuiPlatform Item { id : root width : isVerticalLayout ? desktopRectWidth : desktopRect.width height : isVerticalLayout ? desktopRect.height - 8 : desktopRectHeight activeFocusOnTab: index === 0 ? true : false focus : true property string windowType : "desktop" property var wid : index + 1 // Using the Drag attached property, any Item can be made a source of drag and drop events within a scene Drag.active : previewMouseArea.drag.active Drag.hotSpot.x : width / 2 Drag.hotSpot.y : height / 2 property bool windowDragActive : previewMouseArea.drag.active property bool nowDragActive: false property var controller : new Controller.DesktopController(multitaskViewModel, this, multitaskViewManager, ["app","desktop"]) property real posX : 0 property real posY : 0 // 用户自定义工作区名称 property string customName: "" states: [ State { name : "tabAndDragActive" when: root.activeFocus && root.windowDragActive && (multitaskViewManager.shouldShowTabBorder) PropertyChanges { target: previewArea; borderColor: tabFocusBorderColor } ParentChange { target: root; parent: desktopRect } }, State { name : "tabActive" when: root.activeFocus && (multitaskViewManager.shouldShowTabBorder) PropertyChanges { target: previewArea; borderColor: tabFocusBorderColor } }, State { name : "dragActive" when : nowDragActive ParentChange { target: root; parent: desktopRect } } ] Keys.onPressed: { if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) { controller.setCurrentDesktop(root.wid) controller.onWindowClicked(root.wid) event.accepted = true } else if (event.key === Qt.Key_Escape) { controller.closeMultitaskView() } else if (event.modifiers & Qt.MetaModifier) { if (event.key === Qt.Key_Tab) { controller.closeMultitaskView() } } else if (event.key === Qt.Key_Tab) { if (index === 0 ) { desktopListView.currentIndex = desktopListView.count - 1 multitaskViewManager.setShouldShowTabBorder(true) } } } onActiveFocusChanged: { if (index === 0 && root.activeFocus) { desktopListView.currentIndex = 0 var offsetPosition = isVerticalLayout ? desktopListView.contentX : desktopListView.contentY if (offsetPosition > 0) { contentMoveAnimation.to = 0 contentMoveAnimation.start() } multitaskViewManager.activeAreaChangeDataCollect("Workspace Preview Area") } } // 工作区位置移动触发下方信号 onWindowDragActiveChanged : { // 需要保证让 dragRectangle 先恢复原来的 parent 再移动到合适的位置 // 因为直接使用 windowDragActive 变量并无法实现上述控制顺序,所以 // 需要额外的变量 nowDragActive 来实现 ParentChange,然后再移动到 // 合适的位置 if (nowDragActive != windowDragActive) { nowDragActive = windowDragActive } if (windowDragActive) { opacity = 0.75 } else { // 工作区取消拖动后需要返回原来的位置,如果拖拽产 // 生了工作区的位置交换也没有关系,也不会影响动效 opacity = 1 this.posX = 0 this.posY = 0 controller.rejectSource(root) } } Item { id : desktopDragRect anchors.fill: parent anchors.centerIn : parent state : "default" property int desktopIndex: root.wid states : [ State { name : "default" PropertyChanges { target : previewArea borderColor : desktopDragRect.getWorkspaceDefaultBorderColor() } PropertyChanges { target : closeButton; visible : rootWindow.isTouchState ? true : false } PropertyChanges { target : editButton; visible : false } }, State { name : "hover" PropertyChanges { target : previewArea borderColor : desktopDragRect.getWorkspaceHoverBorderColor() } PropertyChanges { target : closeButton; visible : true && !captionEdit.editable } PropertyChanges { target : editButton; visible : true && !captionEdit.editable} } ] MouseArea { id : previewMouseArea anchors.fill : parent hoverEnabled : true preventStealing : true drag.axis : isVerticalLayout ? Drag.XAxis : Drag.YAxis drag.target : root Accessible.role: Accessible.Button Accessible.name: "desktop-" + root.wid Accessible.description: "preview-desktop, click to enter the desktop" onEntered : { controller.setHoverStatus(); } onExited : { controller.setDefaultStatus() } onClicked : { controller.onWindowClicked(root.wid) } ColumnLayout { id : mainVerticalLayout anchors.fill: parent anchors.centerIn : parent spacing : spacingWidth RowLayout { id : captionRow spacing : 0 Layout.fillHeight : true Layout.rightMargin: workspaceBorderWidth layoutDirection: isLayoutLeftToRight ? Qt.LeftToRight : Qt.RightToLeft Layout.preferredHeight: desktopCaptionHeight Layout.maximumHeight: root.height - mainVerticalLayout.spacing - previewArea.height LineEdit { id: captionEdit editable: false enableLayoutMirroring: !isLayoutLeftToRight Layout.fillWidth : true Layout.maximumWidth: (editable || !editButton.visible) ? desktopRectWidth : contentTextWidth + Math.floor(8 * scaleFactor) Layout.leftMargin : workspaceBorderWidth Layout.preferredHeight: Math.min(desktopCaptionHeight, captionRow.height) onTextEditingFinished: { if (itemDisplayText != defaultText) { customName = itemDisplayText } else { //清空输入则恢复默认名称 customName = captionEdit.isDefaultText ? "" : defaultText } //在输入状态按回车键保存时,要求仅保存名称,不退出任务视图界面 //工作区名称编辑结束,需要将焦点还给root,否则会影响工作区键盘导航 root.forceActiveFocus() } } Binding { id: defaultTextBinding target: captionEdit property: "defaultText" value: qsTr("Desktop") + " " + root.wid } Binding { target: captionEdit property: "itemDisplayText" value: customName.length === 0 ? captionEdit.defaultText : customName } Rectangle { id : editButton implicitWidth : Math.floor(16 * scaleFactor) implicitHeight: width color : "transparent" Accessible.role: Accessible.Button Accessible.name: "edit-desktop-name-" + root.wid Accessible.description: "push-button, click to rename the desktop" MouseArea { anchors.fill: parent onClicked: { captionEdit.editable = true } } UkuiItem.Icon { id: editIcon anchors.centerIn: parent width: parent.width height: width source: "document-edit-symbolic" mode: UkuiItem.Icon.AutoHighlight } } Item { // 填充剩余空间 Layout.fillWidth : true Layout.minimumWidth: Math.floor(8 * scaleFactor) visible: editButton.visible } CloseButton { id : closeButton implicitWidth : Math.min(iconAndCloseButtonHeight, captionRow.height) implicitHeight : width radius : width / 2 windowType : "desktop" Accessible.name: "close-desktop-" + root.wid Accessible.description: "close-button, click to remove the desktop" onClicked : { if (desktopListModel.rowCount() > 2) { //剩余[1个工作区+"新建工作区"]时不会删除"工作区1",属性绑定不能解除 defaultTextBinding.when = false } controller.removePreviewWindow(root.wid) } onExited: { if (!previewMouseArea.containsMouse) { root.setDefaultStatus() } } } }//RowLayout UkuiItem.DtThemeBackground { id : previewArea Layout.fillWidth: true Layout.fillHeight: false Layout.preferredHeight: desktopThumbnailHeight + 2 * border.width color : "transparent" borderColor : defaultBorderColor border.width : workspaceBorderWidth radius : UkuiPlatform.GlobalTheme.kRadiusWindow * scaleFactor Rectangle { id: workspace anchors.centerIn: parent width : desktopThumbnailWidth height : desktopThumbnailHeight color : "black" radius : UkuiPlatform.GlobalTheme.kRadiusMenu * scaleFactor clip : true visible : true layer.enabled : workspace.radius !== 0 layer.effect: MultiEffect { maskEnabled: true maskSource: ShaderEffectSource { sourceItem: Rectangle { id: roundMask width: desktopThumbnailWidth height: desktopThumbnailHeight radius: workspace.radius color: "white" // 必须设置颜色以启用 alpha 通道 visible: false // 遮罩不可见,仅用于裁剪 } hideSource: true // 隐藏原始遮罩源 } } KWin.DesktopBackground { id : desktopThumbnailBackground anchors.centerIn : parent width : desktopThumbnailWidth height : desktopThumbnailHeight blurAlpha : 0 } Loader { id : workSpaceThumbnailLoader width : desktopThumbnailWidth height : desktopThumbnailHeight source: isWlcom ? "WorkSpaceThumbnailWithWlcom.qml" : "WorkSpaceThumbnailWithKwin.qml" } UkuiItem.DtThemeBackground { id : desktopMaskColor visible : false anchors.fill: parent backgroundColor : UkuiPlatform.GlobalTheme.kModalMask } } } }//culumnLayout } // 应用程序预览窗口拖动到虚拟桌面,虚拟桌面区域收到下方信号 DropArea { id : previewDropArea anchors.fill : parent visible: !root.windowDragActive onEntered : { if (drag.source.windowType == "app") { desktopMaskColor.visible = true } if (drag.source.wid !== root.wid) { controller.onSourceEntered(drag.source, drag.source.wid, root.wid); } } onExited : { desktopMaskColor.visible = false } onDropped : { desktopMaskColor.visible = false controller.onSourceDropped(drop.source, rootWindow.highlightDesktop, root.wid); } } function getWorkspaceDefaultBorderColor() { if (root.activeFocus && (multitaskViewManager.shouldShowTabBorder)) { return tabFocusBorderColor } else if (highlightDesktop === root.wid) { return hoverBorderColor } else { return defaultBorderColor } } function getWorkspaceHoverBorderColor() { if (root.activeFocus && (multitaskViewManager.shouldShowTabBorder)) { return tabFocusBorderColor } else { return hoverBorderColor } } } NumberAnimation on x{ id : movePreX duration : 0 running : false } NumberAnimation on y{ id : movePreY duration : 0 running : false } function returnOriginal(x,y) { movePreX.to = 0 movePreY.to = 0 movePreX.from = x movePreY.from = y movePreX.stop() movePreY.stop() movePreX.start() movePreY.start() } function setDefaultStatus() { desktopDragRect.state = "default" } function setHoverStatus() { desktopDragRect.state = "hover" } Component.onCompleted: { if (root.activeFocusOnTab && appAreaModel.rowCount() === 0) { // 无应用窗口时获取tab焦点 root.forceActiveFocus() } } } ukui-window-switch-4.21.1.0/windowsview/qml/WorkSpaceThumbnailWithKwin.qml000066400000000000000000000032111522363675600266520ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import QtQuick 2.12 import QtQuick.Window 2.12 import org.kde.kwin 3.0 as KWinComponents import AppWindowFilterModel 1.0 Item { id: root anchors.fill: parent Repeater { id : desktopWindowRepeater model : AppWindowFilterModel { id: kwinWorkspaceThumbnailModel desktopId: desktopDragRect.desktopIndex screenId: mainView.screenIndex sourceModel: multitaskViewModel.isCurrentDesktopShowingDesktop() ? {} : appWindowListModel } KWinComponents.WindowThumbnailItem { width : Math.floor(model.Width * desktopScale) height : Math.floor(model.Height * desktopScale) visible : !(model.Minimized) x : Math.floor((model.X - screenRect.x) * desktopScale) y : Math.floor((model.Y - screenRect.y) * desktopScale) wId: model.Uuid } } } ukui-window-switch-4.21.1.0/windowsview/qml/WorkSpaceThumbnailWithWlcom.qml000066400000000000000000000021451522363675600270300ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import QtQuick 2.12 import QtQuick.Window 2.12 import org.kylin.thumbnail 1.0 as WlcomThumbnail WlcomThumbnail.ThumbnailItem { anchors.fill: parent thumbnailType: 2 outputId: multitaskViewModel.getOutputUuid(mainView.screenIndex) windowId: multitaskViewModel.getDesktopUuid(wid) isActive: multitaskViewManager.winTabVisible } ukui-window-switch-4.21.1.0/windowsview/screens-manager.cpp000066400000000000000000000103371522363675600237040ustar00rootroot00000000000000/* * * Copyright (C) 2024, KylinSoft Co., Ltd. * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see . * * * * Authors: iaom * */ #include #include "screens-manager.h" Screen::Screen(QScreen *screen, QObject *parent): QObject(parent), m_screen(screen) { } QRect Screen::geometry() const { return m_screen->geometry(); } QScreen *Screen::internal() { return m_screen; } bool Screen::enable() { return m_enable; } void Screen::setEnable(bool enable) { if(m_enable != enable) { m_enable = enable; Q_EMIT enableChanged(m_enable); } } ScreensManager::ScreensManager(QObject *parent) : QObject(parent) { for(auto screen : qApp->screens()) { onScreenAdded(screen); } connect(qApp, &QGuiApplication::screenAdded, this, &ScreensManager::onScreenAdded); connect(qApp, &QGuiApplication::screenRemoved, this, &ScreensManager::onScreenRemoved); connect(qApp, &QGuiApplication::primaryScreenChanged, this, &ScreensManager::onPrimaryScreenChanged); } ScreensManager::~ScreensManager() { qDeleteAll(m_screens); } QList ScreensManager::screens() { QList tmp; for(auto screen : m_screens) { if(screen->enable()) { tmp.append(screen); } } return tmp; } Screen *ScreensManager::primaryScreen() { return m_primaryScreen; } void ScreensManager::onScreenAdded(QScreen *screen) { auto s = new Screen(screen, this); if(screen == qApp->primaryScreen()) { m_primaryScreen = s; Q_EMIT primaryScreenChanged(s); } m_screens.append(s); connect(s->internal(), &QScreen::geometryChanged, this, [&, s](){ checkScreensGeometryStatus(s); }); connect(s, &Screen::enableChanged, this, [&, s](bool enable){ onEnableChanged(s, enable); }); checkScreensGeometryStatus(s); } void ScreensManager::onScreenRemoved(QScreen *screen) { int i = 0; for(; i <= m_screens.size(); ++i) { if(m_screens.at(i)->internal() == screen) { break; } } if(i < m_screens.size()) { auto s = m_screens.takeAt(i); Q_EMIT screenRemoved(s); s->deleteLater(); } } void ScreensManager::onPrimaryScreenChanged(QScreen *screen) { if(m_primaryScreen->internal() != screen) { for(auto s : m_screens) { if(s->internal() == screen) { if(!s->enable()) { s->setEnable(true); } m_primaryScreen = s; Q_EMIT primaryScreenChanged(s); return; } } } } void ScreensManager::onEnableChanged(Screen *screen, bool enable) { if(enable) { Q_EMIT screenAdded(screen); } else { Q_EMIT screenRemoved(screen); } } void ScreensManager::checkScreensGeometryStatus(Screen* screen) { if(screen == nullptr || m_primaryScreen == nullptr) { return; } for(auto s : m_screens) { if(s == nullptr) { continue; } if(s->internal()->geometry() == screen->geometry() && s != screen) { if(s == m_primaryScreen) { screen->setEnable(false); Q_EMIT s->geometryChanged(s->internal()->geometry()); return; } else { s->setEnable(false); Q_EMIT screen->geometryChanged(screen->internal()->geometry()); return; } } else { if(!s->enable()) { s->setEnable(true); } Q_EMIT s->geometryChanged(s->internal()->geometry()); } } } ukui-window-switch-4.21.1.0/windowsview/screens-manager.h000066400000000000000000000037611522363675600233540ustar00rootroot00000000000000/* * * Copyright (C) 2024, KylinSoft Co., Ltd. * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see . * * * * Authors: iaom * */ #ifndef SCREENS_MANAGER_H #define SCREENS_MANAGER_H #include #include class ScreensManager; class Screen : public QObject { Q_OBJECT public: explicit Screen(QScreen *screen, QObject *parent = nullptr); Q_DISABLE_COPY(Screen); public: QRect geometry() const; QScreen * internal(); bool enable(); void setEnable(bool enable); Q_SIGNALS: void geometryChanged(const QRect &geometry); void enableChanged(bool enable); private: QScreen *m_screen = nullptr; bool m_enable = false; }; class ScreensManager : public QObject { Q_OBJECT public: explicit ScreensManager(QObject *parent = nullptr); ~ScreensManager(); QList screens(); Screen * primaryScreen(); Q_SIGNALS: void screenAdded(Screen *); void screenRemoved(Screen *); void primaryScreenChanged(Screen *); private Q_SLOTS: void onScreenAdded(QScreen *screen); void onScreenRemoved(QScreen *screen); void onPrimaryScreenChanged(QScreen *screen); void onEnableChanged(Screen *screen, bool enable); void checkScreensGeometryStatus(Screen *screen); private: Screen *m_primaryScreen = nullptr; QList m_screens; }; #endif //SCREENS_MANAGER_H ukui-window-switch-4.21.1.0/windowsview/translations/000077500000000000000000000000001522363675600226435ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/translations/ukui-window-switch_bo_CN.ts000066400000000000000000000022341522363675600300350ustar00rootroot00000000000000 NewDesktopButton New Desktop ལས་ཁུལ་གསར་འཛུགས། TabletViewMain No recent tasks བེད་སྤྱོད་སྒོ་འབྱེད་མེད། Clear གསལ་པོར་བཤད་ན། VirtualDesktopWindow Desktop ཅོག་ཙེའི་སྟེང་གི ukui-window-switch-4.21.1.0/windowsview/translations/ukui-window-switch_de.ts000066400000000000000000000020741522363675600274470ustar00rootroot00000000000000 NewDesktopButton New Desktop Neuer Desktop TabletViewMain No recent tasks Keine aktuellen Aufgaben Clear Klar VirtualDesktopWindow Desktop Desktop ukui-window-switch-4.21.1.0/windowsview/translations/ukui-window-switch_es.ts000066400000000000000000000021021522363675600274560ustar00rootroot00000000000000 NewDesktopButton New Desktop Nuevo escritorio TabletViewMain No recent tasks No hay tareas recientes Clear Claro VirtualDesktopWindow Desktop Escritorio ukui-window-switch-4.21.1.0/windowsview/translations/ukui-window-switch_fr.ts000066400000000000000000000020751522363675600274670ustar00rootroot00000000000000 NewDesktopButton New Desktop Nouveau bureau TabletViewMain No recent tasks Pas de tâches récentes Clear Clair VirtualDesktopWindow Desktop Bureau ukui-window-switch-4.21.1.0/windowsview/translations/ukui-window-switch_kk.ts000066400000000000000000000020461522363675600274630ustar00rootroot00000000000000 NewDesktopButton New Desktop ۇستەل جوعارعى TabletViewMain No recent tasks جاقىنعى مىندەتتەر جوق Clear تازالاۋ VirtualDesktopWindow Desktop ۇستەل بەتى ukui-window-switch-4.21.1.0/windowsview/translations/ukui-window-switch_ky.ts000066400000000000000000000020431522363675600274760ustar00rootroot00000000000000 NewDesktopButton New Desktop شىرە ۉستۉ TabletViewMain No recent tasks جاقىندا مٸلدەتتەر جوق Clear تازالوو VirtualDesktopWindow Desktop ئۈستەلئۈستى ukui-window-switch-4.21.1.0/windowsview/translations/ukui-window-switch_mn.ts000066400000000000000000000022731522363675600274720ustar00rootroot00000000000000 NewDesktopButton New Desktop ᠱᠢᠨ᠎ᠡ᠎ᠪᠡᠷ ᠪᠠᠢᠭᠤᠯᠤᠭ᠍ᠰᠠᠨ ᠠᠵᠢᠯᠯᠠᠬᠤ ᠤᠷᠤᠨ TabletViewMain No recent tasks ᠨᠡᠬᠡᠬᠡᠬᠦ᠌ ᠬᠡᠷᠡᠭᠯᠡᠭᠡ ᠪᠠᠢᠬᠤ ᠦᠬᠡᠢ Clear ᠤᠰᠠᠳᠬᠠᠬᠤ VirtualDesktopWindow Desktop ᠠᠵᠢᠯᠯᠠᠬᠤ ᠤᠷᠤᠨ ukui-window-switch-4.21.1.0/windowsview/translations/ukui-window-switch_ms.ts000066400000000000000000000020141522363675600274700ustar00rootroot00000000000000 NewDesktopButton New Desktop TabletViewMain No recent tasks Clear VirtualDesktopWindow Desktop ukui-window-switch-4.21.1.0/windowsview/translations/ukui-window-switch_ug.ts000066400000000000000000000020541522363675600274700ustar00rootroot00000000000000 NewDesktopButton New Desktop ئۈستەل ئۈستىلىرى TabletViewMain No recent tasks يېقىنقى ۋەزىپىلەر يوق Clear تازلاش VirtualDesktopWindow Desktop ئۈستەل يۈزى ukui-window-switch-4.21.1.0/windowsview/translations/ukui-window-switch_vi.ts000066400000000000000000000020561522363675600274750ustar00rootroot00000000000000 NewDesktopButton New Desktop Máy tính để bàn mới TabletViewMain No recent tasks Không có ứng dụng nào được mở Clear Xóa sạch clipboard VirtualDesktopWindow Desktop Bàn làm việc ukui-window-switch-4.21.1.0/windowsview/translations/ukui-window-switch_zh_CN.ts000066400000000000000000000017641522363675600300650ustar00rootroot00000000000000 NewDesktopButton New Desktop 新建工作区 TabletViewMain No recent tasks 无应用开启 Clear 清除 VirtualDesktopWindow Desktop 工作区 ukui-window-switch-4.21.1.0/windowsview/translations/ukui-window-switch_zh_Hant.ts000066400000000000000000000017661522363675600304610ustar00rootroot00000000000000 NewDesktopButton New Desktop 新建工作區 TabletViewMain No recent tasks 無應用開啟 Clear 清除 VirtualDesktopWindow Desktop 工作區 ukui-window-switch-4.21.1.0/windowsview/ukui-flow.cpp000066400000000000000000001041441522363675600225540ustar00rootroot00000000000000/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. * Copyright (C) 2025, KylinSoft Co., Ltd. * ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtQml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ** iaom ****************************************************************************/ #include "ukui-flow.h" #include #include static const QQuickItemPrivate::ChangeTypes watchedChanges = QQuickItemPrivate::Geometry | QQuickItemPrivate::SiblingOrder | QQuickItemPrivate::Visibility | QQuickItemPrivate::Destroyed; void UkuiBasePositionerPrivate::watchChanges(QQuickItem *other) { QQuickItemPrivate *otherPrivate = QQuickItemPrivate::get(other); otherPrivate->addItemChangeListener(this, watchedChanges); } void UkuiBasePositionerPrivate::unwatchChanges(QQuickItem* other) { QQuickItemPrivate *otherPrivate = QQuickItemPrivate::get(other); otherPrivate->removeItemChangeListener(this, watchedChanges); } UkuiBasePositioner::PositionedItem::PositionedItem(QQuickItem *i) : item(i) , transitionableItem(nullptr) , index(-1) , isNew(false) , isVisible(true) , topPadding(0) , leftPadding(0) , rightPadding(0) , bottomPadding(0) { } qreal UkuiBasePositioner::PositionedItem::itemX() const { return transitionableItem ? transitionableItem->itemX() : item->x(); } qreal UkuiBasePositioner::PositionedItem::itemY() const { return transitionableItem ? transitionableItem->itemY() : item->y(); } void UkuiBasePositioner::PositionedItem::moveTo(const QPointF &pos) { if (transitionableItem) { transitionableItem->moveTo(pos); } else item->setPosition(pos); } void UkuiBasePositioner::PositionedItem::transitionNextReposition(QQuickItemViewTransitioner *transitioner, QQuickItemViewTransitioner::TransitionType type, bool asTarget) { if (!transitioner) return; if (!transitionableItem) transitionableItem = std::make_shared(item); transitioner->transitionNextReposition(transitionableItem.get(), type, asTarget); } bool UkuiBasePositioner::PositionedItem::prepareTransition(QQuickItemViewTransitioner *transitioner, const QRectF &viewBounds) { return transitionableItem ? transitionableItem->prepareTransition(transitioner, index, viewBounds) : false; } void UkuiBasePositioner::PositionedItem::startTransition(QQuickItemViewTransitioner *transitioner) { if (transitionableItem) transitionableItem->startTransition(transitioner, index); } void UkuiBasePositioner::PositionedItem::updatePadding(qreal lp, qreal tp, qreal rp, qreal bp) { leftPadding = lp; topPadding = tp; rightPadding = rp; bottomPadding = bp; } UkuiBasePositioner::UkuiBasePositioner(PositionerType at, QQuickItem *parent) : QQuickImplicitSizeItem(*(new UkuiBasePositionerPrivate), parent) { Q_D(UkuiBasePositioner); d->init(at); } UkuiBasePositioner::UkuiBasePositioner(UkuiBasePositionerPrivate &dd, PositionerType at, QQuickItem *parent) : QQuickImplicitSizeItem(dd, parent) { Q_D(UkuiBasePositioner); d->init(at); } UkuiBasePositioner::~UkuiBasePositioner() { Q_D(UkuiBasePositioner); delete d->transitioner; for (int i = 0; i < positionedItems.count(); ++i) d->unwatchChanges(positionedItems.at(i).item); for (int i = 0; i < unpositionedItems.count(); ++i) d->unwatchChanges(unpositionedItems.at(i).item); clearPositionedItems(&positionedItems); clearPositionedItems(&unpositionedItems); } void UkuiBasePositioner::updatePolish() { Q_D(UkuiBasePositioner); if (d->positioningDirty) prePositioning(); } qreal UkuiBasePositioner::spacing() const { Q_D(const UkuiBasePositioner); return d->spacing; } void UkuiBasePositioner::setSpacing(qreal s) { Q_D(UkuiBasePositioner); if (s == d->spacing) return; d->spacing = s; d->setPositioningDirty(); emit spacingChanged(); } QQuickTransition *UkuiBasePositioner::populate() const { Q_D(const UkuiBasePositioner); return d->transitioner ? d->transitioner->populateTransition : nullptr; } void UkuiBasePositioner::setPopulate(QQuickTransition *transition) { Q_D(UkuiBasePositioner); if (!d->transitioner) d->transitioner = new QQuickItemViewTransitioner; if (d->transitioner->populateTransition != transition) { d->transitioner->populateTransition = transition; emit populateChanged(); } } QQuickTransition *UkuiBasePositioner::move() const { Q_D(const UkuiBasePositioner); return d->transitioner ? d->transitioner->displacedTransition : nullptr; } void UkuiBasePositioner::setMove(QQuickTransition *mt) { Q_D(UkuiBasePositioner); if (!d->transitioner) d->transitioner = new QQuickItemViewTransitioner; if (mt == d->transitioner->displacedTransition) return; d->transitioner->displacedTransition = mt; emit moveChanged(); } QQuickTransition *UkuiBasePositioner::add() const { Q_D(const UkuiBasePositioner); return d->transitioner ? d->transitioner->addTransition : nullptr; } void UkuiBasePositioner::setAdd(QQuickTransition *add) { Q_D(UkuiBasePositioner); if (!d->transitioner) d->transitioner = new QQuickItemViewTransitioner; if (add == d->transitioner->addTransition) return; d->transitioner->addTransition = add; emit addChanged(); } void UkuiBasePositioner::componentComplete() { Q_D(UkuiBasePositioner); QQuickItem::componentComplete(); if (d->transitioner) d->transitioner->setPopulateTransitionEnabled(true); positionedItems.reserve(childItems().count()); prePositioning(); if (d->transitioner) d->transitioner->setPopulateTransitionEnabled(false); } void UkuiBasePositioner::itemChange(ItemChange change, const ItemChangeData &value) { Q_D(UkuiBasePositioner); if (change == ItemChildAddedChange) { d->setPositioningDirty(); } else if (change == ItemChildRemovedChange) { QQuickItem *child = value.item; UkuiBasePositioner::PositionedItem posItem(child); int idx = positionedItems.indexOf(posItem); if (idx >= 0) { d->unwatchChanges(child); removePositionedItem(&positionedItems, idx); } else if ((idx = unpositionedItems.indexOf(posItem)) >= 0) { d->unwatchChanges(child); removePositionedItem(&unpositionedItems, idx); } d->setPositioningDirty(); } QQuickItem::itemChange(change, value); } void UkuiBasePositioner::forceLayout() { updatePolish(); } void UkuiBasePositioner::prePositioning() { Q_D(UkuiBasePositioner); if (!isComponentComplete()) return; if (d->doingPositioning) return; d->positioningDirty = false; d->doingPositioning = true; //Need to order children by creation order modified by stacking order QList children = childItems(); QVector oldItems = positionedItems; positionedItems.clear(); for (int ii = 0; ii < unpositionedItems.count(); ii++) oldItems.append(unpositionedItems[ii]); unpositionedItems.clear(); int addedIndex = -1; for (int ii = 0; ii < children.count(); ++ii) { QQuickItem *child = children.at(ii); if (QQuickItemPrivate::get(child)->isTransparentForPositioner()) continue; QQuickItemPrivate *childPrivate = QQuickItemPrivate::get(child); PositionedItem posItem(child); int wIdx = oldItems.indexOf(posItem); if (wIdx < 0) { d->watchChanges(child); posItem.isNew = true; if (!childPrivate->explicitVisible || !child->width() || !child->height()) { posItem.isVisible = false; posItem.index = -1; unpositionedItems.append(posItem); } else { posItem.index = positionedItems.count(); positionedItems.append(posItem); if (d->transitioner) { if (addedIndex < 0) addedIndex = posItem.index; PositionedItem *theItem = &positionedItems[positionedItems.count()-1]; if (d->transitioner->canTransition(QQuickItemViewTransitioner::PopulateTransition, true)) theItem->transitionNextReposition(d->transitioner, QQuickItemViewTransitioner::PopulateTransition, true); else if (!d->transitioner->populateTransitionEnabled()) theItem->transitionNextReposition(d->transitioner, QQuickItemViewTransitioner::AddTransition, true); } } } else { PositionedItem *item = &oldItems[wIdx]; // Items are only omitted from positioning if they are explicitly hidden // i.e. their positioning is not affected if an ancestor is hidden. if (!childPrivate->explicitVisible || !child->width() || !child->height()) { item->isVisible = false; item->index = -1; unpositionedItems.append(*item); } else if (!item->isVisible) { // item changed from non-visible to visible, treat it as a "new" item item->isVisible = true; item->isNew = true; item->index = positionedItems.count(); positionedItems.append(*item); if (d->transitioner) { if (addedIndex < 0) addedIndex = item->index; positionedItems[positionedItems.count()-1].transitionNextReposition(d->transitioner, QQuickItemViewTransitioner::AddTransition, true); } } else { item->isNew = false; item->index = positionedItems.count(); positionedItems.append(*item); } } } if (d->transitioner) { for (int i=0; i= 0) { positionedItems[i].transitionNextReposition(d->transitioner, QQuickItemViewTransitioner::AddTransition, false); } else { // just queue the item for a move-type displace - if the item hasn't // moved anywhere, it won't be transitioned anyway positionedItems[i].transitionNextReposition(d->transitioner, QQuickItemViewTransitioner::MoveTransition, false); } } } } QSizeF contentSize(0,0); reportConflictingAnchors(); if (!d->anchorConflict) { doPositioning(&contentSize); updateAttachedProperties(); } if (d->transitioner) { QRectF viewBounds(QPointF(), contentSize); for (int i=0; itransitioner, viewBounds); for (int i=0; itransitioner); d->transitioner->resetTargetLists(); } d->doingPositioning = false; //Set implicit size to the size of its children setImplicitSize(contentSize.width(), contentSize.height()); emit positioningComplete(); } void UkuiBasePositioner::positionItem(qreal x, qreal y, PositionedItem *target) { if ( target->itemX() != x || target->itemY() != y ) target->moveTo(QPointF(x, y)); } void UkuiBasePositioner::positionItemX(qreal x, PositionedItem *target) { Q_D(UkuiBasePositioner); if (target->itemX() != x && (d->type == Horizontal || d->type == Both)) { target->moveTo(QPointF(x, target->itemY())); } } void UkuiBasePositioner::positionItemY(qreal y, PositionedItem *target) { Q_D(UkuiBasePositioner); if (target->itemY() != y && (d->type == Vertical || d->type == Both)) { target->moveTo(QPointF(target->itemX(), y)); } } /* Since PositionedItem values are stored by value, removed items rely on QVector destroying the element and releasing its transitionable item reference. */ void UkuiBasePositioner::removePositionedItem(QVector *items, int index) { Q_ASSERT(index >= 0 && index < items->count()); items->remove(index); } void UkuiBasePositioner::clearPositionedItems(QVector *items) { items->clear(); } UkuiPositionerAttached *UkuiBasePositioner::qmlAttachedProperties(QObject *obj) { return new UkuiPositionerAttached(obj); } void UkuiBasePositioner::updateAttachedProperties(UkuiPositionerAttached *specificProperty, QQuickItem *specificPropertyOwner) const { // If this function is deemed too expensive or shows up in profiles, it could // be changed to run only when there are attached properties present. This // could be a flag in the positioner that is set by the attached property // constructor. UkuiPositionerAttached *prevLastProperty = nullptr; UkuiPositionerAttached *lastProperty = nullptr; for (int ii = 0; ii < positionedItems.count(); ++ii) { const PositionedItem &child = positionedItems.at(ii); if (!child.item) continue; UkuiPositionerAttached *property = nullptr; if (specificProperty) { if (specificPropertyOwner == child.item) { property = specificProperty; } } else { property = static_cast(qmlAttachedPropertiesObject(child.item, false)); } if (property) { property->setIndex(ii); property->setIsFirstItem(ii == 0); if (property->isLastItem()) { if (prevLastProperty) prevLastProperty->setIsLastItem(false); // there can be only one last property prevLastProperty = property; } } lastProperty = property; } if (prevLastProperty && prevLastProperty != lastProperty) prevLastProperty->setIsLastItem(false); if (lastProperty) lastProperty->setIsLastItem(true); // clear attached properties for unpositioned items for (int ii = 0; ii < unpositionedItems.count(); ++ii) { const PositionedItem &child = unpositionedItems.at(ii); if (!child.item) continue; UkuiPositionerAttached *property = nullptr; if (specificProperty) { if (specificPropertyOwner == child.item) { property = specificProperty; } } else { property = static_cast(qmlAttachedPropertiesObject(child.item, false)); } if (property) { property->setIndex(-1); property->setIsFirstItem(false); property->setIsLastItem(false); } } } qreal UkuiBasePositioner::padding() const { Q_D(const UkuiBasePositioner); return d->padding(); } void UkuiBasePositioner::setPadding(qreal padding) { Q_D(UkuiBasePositioner); if (qFuzzyCompare(d->padding(), padding)) return; d->extra.value().padding = padding; d->setPositioningDirty(); emit paddingChanged(); if (!d->extra.isAllocated() || !d->extra->explicitTopPadding) emit topPaddingChanged(); if (!d->extra.isAllocated() || !d->extra->explicitLeftPadding) emit leftPaddingChanged(); if (!d->extra.isAllocated() || !d->extra->explicitRightPadding) emit rightPaddingChanged(); if (!d->extra.isAllocated() || !d->extra->explicitBottomPadding) emit bottomPaddingChanged(); } void UkuiBasePositioner::resetPadding() { setPadding(0); } qreal UkuiBasePositioner::topPadding() const { Q_D(const UkuiBasePositioner); if (d->extra.isAllocated() && d->extra->explicitTopPadding) return d->extra->topPadding; return d->padding(); } void UkuiBasePositioner::setTopPadding(qreal padding) { Q_D(UkuiBasePositioner); d->setTopPadding(padding); } void UkuiBasePositioner::resetTopPadding() { Q_D(UkuiBasePositioner); d->setTopPadding(0, true); } qreal UkuiBasePositioner::leftPadding() const { Q_D(const UkuiBasePositioner); if (d->extra.isAllocated() && d->extra->explicitLeftPadding) return d->extra->leftPadding; return d->padding(); } void UkuiBasePositioner::setLeftPadding(qreal padding) { Q_D(UkuiBasePositioner); d->setLeftPadding(padding); } void UkuiBasePositioner::resetLeftPadding() { Q_D(UkuiBasePositioner); d->setLeftPadding(0, true); } qreal UkuiBasePositioner::rightPadding() const { Q_D(const UkuiBasePositioner); if (d->extra.isAllocated() && d->extra->explicitRightPadding) return d->extra->rightPadding; return d->padding(); } void UkuiBasePositioner::setRightPadding(qreal padding) { Q_D(UkuiBasePositioner); d->setRightPadding(padding); } void UkuiBasePositioner::resetRightPadding() { Q_D(UkuiBasePositioner); d->setRightPadding(0, true); } qreal UkuiBasePositioner::bottomPadding() const { Q_D(const UkuiBasePositioner); if (d->extra.isAllocated() && d->extra->explicitBottomPadding) return d->extra->bottomPadding; return d->padding(); } void UkuiBasePositioner::setBottomPadding(qreal padding) { Q_D(UkuiBasePositioner); d->setBottomPadding(padding); } void UkuiBasePositioner::resetBottomPadding() { Q_D(UkuiBasePositioner); d->setBottomPadding(0, true); } UkuiBasePositionerPrivate::ExtraData::ExtraData() : padding(0) , topPadding(0) , leftPadding(0) , rightPadding(0) , bottomPadding(0) , explicitTopPadding(false) , explicitLeftPadding(false) , explicitRightPadding(false) , explicitBottomPadding(false) { } void UkuiBasePositionerPrivate::setTopPadding(qreal value, bool reset) { Q_Q(UkuiBasePositioner); qreal oldPadding = q->topPadding(); if (!reset || extra.isAllocated()) { extra.value().topPadding = value; extra.value().explicitTopPadding = !reset; } if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) { setPositioningDirty(); emit q->topPaddingChanged(); } } void UkuiBasePositionerPrivate::setLeftPadding(qreal value, bool reset) { Q_Q(UkuiBasePositioner); qreal oldPadding = q->leftPadding(); if (!reset || extra.isAllocated()) { extra.value().leftPadding = value; extra.value().explicitLeftPadding = !reset; } if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) { setPositioningDirty(); emit q->leftPaddingChanged(); } } void UkuiBasePositionerPrivate::setRightPadding(qreal value, bool reset) { Q_Q(UkuiBasePositioner); qreal oldPadding = q->rightPadding(); if (!reset || extra.isAllocated()) { extra.value().rightPadding = value; extra.value().explicitRightPadding = !reset; } if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) { setPositioningDirty(); emit q->rightPaddingChanged(); } } void UkuiBasePositionerPrivate::setBottomPadding(qreal value, bool reset) { Q_Q(UkuiBasePositioner); qreal oldPadding = q->bottomPadding(); if (!reset || extra.isAllocated()) { extra.value().bottomPadding = value; extra.value().explicitBottomPadding = !reset; } if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) { setPositioningDirty(); emit q->bottomPaddingChanged(); } } UkuiPositionerAttached::UkuiPositionerAttached(QObject *parent) : QObject(parent), m_index(-1), m_isFirstItem(false), m_isLastItem(false) { QQuickItem *attachedItem = qobject_cast(parent); if (attachedItem) { UkuiBasePositioner *positioner = qobject_cast(attachedItem->parent()); if (positioner) { positioner->updateAttachedProperties(this, attachedItem); } } } void UkuiPositionerAttached::setIndex(int index) { if (m_index == index) return; m_index = index; emit indexChanged(); } void UkuiPositionerAttached::setIsFirstItem(bool isFirstItem) { if (m_isFirstItem == isFirstItem) return; m_isFirstItem = isFirstItem; emit isFirstItemChanged(); } void UkuiPositionerAttached::setIsLastItem(bool isLastItem) { if (m_isLastItem == isLastItem) return; m_isLastItem = isLastItem; emit isLastItemChanged(); } class UkuiFlowPrivate : public UkuiBasePositionerPrivate { Q_DECLARE_PUBLIC(UkuiFlow) public: UkuiFlowPrivate() : UkuiBasePositionerPrivate(), flow(UkuiFlow::LeftToRight), lineHorizontalCenterAlignment(false) {} void effectiveLayoutDirectionChange() override { Q_Q(UkuiFlow); // Don't postpone, as it might be the only trigger for visible changes. q->prePositioning(); emit q->effectiveLayoutDirectionChanged(); } UkuiFlow::Flow flow; bool lineHorizontalCenterAlignment; QHash posCache; }; UkuiFlow::UkuiFlow(QQuickItem *parent) : UkuiBasePositioner(*(new UkuiFlowPrivate), Both, parent) { Q_D(UkuiFlow); // Flow layout requires relayout if its own size changes too. d->addItemChangeListener(d, QQuickItemPrivate::Geometry); } UkuiFlow::Flow UkuiFlow::flow() const { Q_D(const UkuiFlow); return d->flow; } void UkuiFlow::setFlow(Flow flow) { Q_D(UkuiFlow); if (d->flow != flow) { d->flow = flow; prePositioning(); emit flowChanged(); } } Qt::LayoutDirection UkuiFlow::layoutDirection() const { Q_D(const UkuiFlow); return d->layoutDirection; } void UkuiFlow::setLayoutDirection(Qt::LayoutDirection layoutDirection) { Q_D(UkuiFlow); if (d->layoutDirection != layoutDirection) { d->layoutDirection = layoutDirection; emit layoutDirectionChanged(); d->effectiveLayoutDirectionChange(); } } Qt::LayoutDirection UkuiFlow::effectiveLayoutDirection() const { return UkuiBasePositionerPrivate::getEffectiveLayoutDirection(this); } bool UkuiFlow::lineHorizontalCenterAlignment() const { Q_D(const UkuiFlow); return d->lineHorizontalCenterAlignment; } void UkuiFlow::setLineHorizontalCenterAlignment(bool lineHorizontalCenterAlignment) { Q_D(UkuiFlow); if (d->lineHorizontalCenterAlignment != lineHorizontalCenterAlignment) { d->lineHorizontalCenterAlignment = lineHorizontalCenterAlignment; d->setPositioningDirty(); emit lineHorizontalCenterAlignmentChanged(); } } int UkuiFlow::moveCurrentIndexLeft(int currentIndex) { if (effectiveLayoutDirection() == Qt::LayoutDirection::LeftToRight) { if (currentIndex > 0) { return currentIndex - 1; } else { return positionedItems.count() - 1; } } else { if (currentIndex < positionedItems.count() - 1) { return currentIndex + 1; } else { return 0; } } } int UkuiFlow::moveCurrentIndexRight(int currentIndex) { if (effectiveLayoutDirection() == Qt::LayoutDirection::LeftToRight) { if (currentIndex < positionedItems.count() - 1) { return currentIndex + 1; } else { return 0; } } else { if (currentIndex > 0) { return currentIndex - 1; } else { return positionedItems.count() - 1; } } } int UkuiFlow::moveCurrentIndexUp(int currentIndex) { // 只有一行时移动到末尾 if (positionedItems[0].itemY() == positionedItems[positionedItems.count() - 1].itemY()) { return positionedItems.count() - 1; } PositionedItem ¤tChild = positionedItems[currentIndex]; qreal currentRowY = currentChild.itemY(); int upRowStartIndex = 0; int upRowEndIndex = positionedItems.count() - 1; // 计算当前获取键盘焦点的窗口需要移动至哪一行 if (currentChild.itemY() == positionedItems[0].itemY()) { // 当前键盘焦点窗口位于第一行 currentRowY = positionedItems[positionedItems.count() - 1].itemY(); upRowEndIndex = positionedItems.count() - 1; } else { for (int i = positionedItems.count() - 1; i >= 0; i--) { if (positionedItems[i].itemY() < currentChild.itemY()) { currentRowY = positionedItems[i].itemY(); upRowEndIndex = i; break; } } } for (int i = upRowEndIndex; i >= 0; i--) { if (positionedItems[i].itemY() < currentRowY) { upRowStartIndex = i + 1; break; } } // 查找应该跳转到上一行的哪个窗口 return findUpDownItemIndex(currentIndex, upRowStartIndex, upRowEndIndex); } int UkuiFlow::moveCurrentIndexDown(int currentIndex) { // 只有一行时移动到首个 if (positionedItems[0].itemY() == positionedItems[positionedItems.count() - 1].itemY()) { return 0; } PositionedItem ¤tChild = positionedItems[currentIndex]; qreal currentRowY = currentChild.itemY(); int downRowStartIndex = 0; int downRowEndIndex = positionedItems.count() - 1; // 计算当前获取键盘焦点的窗口需要移动至哪一行 if (currentChild.itemY() == positionedItems[positionedItems.count() - 1].itemY()) { // 当前键盘焦点窗口位于最后一行 currentRowY = positionedItems[0].itemY(); downRowStartIndex = 0; } else { for (int i = 0; i < positionedItems.count(); i++) { if (positionedItems[i].itemY() > currentChild.itemY()) { currentRowY = positionedItems[i].itemY(); downRowStartIndex = i; break; } } } for (int i = downRowStartIndex; i < positionedItems.count(); i++) { if (positionedItems[i].itemY() > currentRowY) { downRowEndIndex = i - 1; break; } } // 查找应该跳转到下一行的哪个窗口 return findUpDownItemIndex(currentIndex, downRowStartIndex, downRowEndIndex); } int UkuiFlow::findUpDownItemIndex(int currentIndex, int startIndex, int endIndex) { PositionedItem ¤tChild = positionedItems[currentIndex]; // 获取当前键盘焦点窗口的leftX rightX qreal currentIndexLeftX = currentChild.itemX(); qreal currentIndexRightX = currentChild.itemX() + currentChild.item->width(); // 判断应该跳转到上/下一行的哪个窗口 int resultIndex = startIndex; qreal result = 0; for (int i = startIndex; i <= endIndex; i++) { qreal temp = 0; if ((positionedItems[i].itemX() + positionedItems[i].item->width()) < currentIndexLeftX) { resultIndex = i; continue; } if (positionedItems[i].itemX()> currentIndexRightX) { break; } if (positionedItems[i].itemX() <= currentIndexLeftX) { if ((positionedItems[i].itemX() + positionedItems[i].item->width()) <= currentIndexRightX) { temp = (positionedItems[i].itemX() + positionedItems[i].item->width()) - currentIndexLeftX; } else { temp = currentIndexRightX - currentIndexLeftX; } } else { if ((positionedItems[i].itemX() + positionedItems[i].item->width()) <= currentIndexRightX) { temp = (positionedItems[i].itemX() + positionedItems[i].item->width()) - positionedItems[i].itemX(); } else { temp = currentIndexRightX - positionedItems[i].itemX(); } } if (temp > result) { result = temp; resultIndex = i; } } return resultIndex; } void UkuiFlow::doPositioning(QSizeF *contentSize) { //Precondition: All items in the positioned list have a valid item pointer and should be positioned Q_D(UkuiFlow); qreal hoffset1 = leftPadding(); qreal hoffset2 = rightPadding(); if (!d->isLeftToRight()) qSwap(hoffset1, hoffset2); qreal hoffset = hoffset1; const qreal voffset1 = topPadding(); qreal voffset = voffset1; qreal linemax = 0; contentSize->setWidth(qMax(contentSize->width(), hoffset1 + hoffset2)); contentSize->setHeight(qMax(contentSize->height(), voffset + bottomPadding())); int lineFirstIndex = 0; for (int i = 0; i < positionedItems.count(); ++i) { PositionedItem &child = positionedItems[i]; if (d->flow == LeftToRight) { if (widthValid() && hoffset != hoffset1 && hoffset + child.item->width() + hoffset2 > width()) { //居中处理 if (d->lineHorizontalCenterAlignment) { PositionedItem &lineLastItem = positionedItems[i - 1]; qreal moveOffSet = (width() - (d->posCache.value(lineLastItem.index).x() + lineLastItem.item->width() - d->posCache.value(lineFirstIndex).x())) / 2; for (int j = lineFirstIndex; j < i; ++j) { PositionedItem &lineChild = positionedItems[j]; qreal posX = d->posCache.value(j).x() + moveOffSet; if (!d->isLeftToRight()) { posX = width() - lineChild.item->width() - posX; } positionItem(posX, d->posCache.value(j).y(), &lineChild); lineChild.updatePadding(leftPadding(), topPadding(), rightPadding(), bottomPadding()); } lineFirstIndex = i; } hoffset = hoffset1; voffset += linemax + spacing(); linemax = 0; } } else { if (heightValid() && voffset != voffset1 && voffset + child.item->height() + bottomPadding() > height()) { voffset = voffset1; hoffset += linemax + spacing(); linemax = 0; } } if (d->isLeftToRight()) { if(d->lineHorizontalCenterAlignment) { d->posCache.insert(child.index, {hoffset, voffset}); } else { positionItem(hoffset, voffset, &child); } } else { if(d->lineHorizontalCenterAlignment) { d->posCache.insert(child.index, {hoffset, voffset}); } else { positionItemY(voffset, &child); child.topPadding = topPadding(); child.bottomPadding = bottomPadding(); } } contentSize->setWidth(qMax(contentSize->width(), hoffset + child.item->width() + hoffset2)); contentSize->setHeight(qMax(contentSize->height(), voffset + child.item->height() + bottomPadding())); if (d->flow == LeftToRight) { hoffset += child.item->width(); hoffset += spacing(); linemax = qMax(linemax, child.item->height()); } else { voffset += child.item->height(); voffset += spacing(); linemax = qMax(linemax, child.item->width()); } } //最后一行 if (widthValid() && d->lineHorizontalCenterAlignment && lineFirstIndex < positionedItems.count()) { PositionedItem &lastItem = positionedItems[positionedItems.count() - 1]; if (d->flow == LeftToRight) { qreal moveOffSet = (width() - (d->posCache.value(lastItem.index).x() + lastItem.item->width() - d->posCache.value(lineFirstIndex).x())) / 2; for (int j = lineFirstIndex; j < positionedItems.count(); ++j) { PositionedItem &lineChild = positionedItems[j]; qreal posX = d->posCache.value(j).x() + moveOffSet; if (!d->isLeftToRight()) { posX = width() - lineChild.item->width() - posX; } positionItem(posX, d->posCache.value(j).y(), &lineChild); lineChild.updatePadding(leftPadding(), topPadding(), rightPadding(), bottomPadding()); } } } if(d->lineHorizontalCenterAlignment && d->flow == LeftToRight) { contentSize->setWidth(width()); } d->posCache.clear(); } void UkuiFlow::reportConflictingAnchors() { Q_D(UkuiFlow); for (int ii = 0; ii < positionedItems.count(); ++ii) { const PositionedItem &child = positionedItems.at(ii); if (child.item) { QQuickAnchors *anchors = QQuickItemPrivate::get(static_cast(child.item))->_anchors; if (anchors && (anchors->usedAnchors() || anchors->fill() || anchors->centerIn())) { d->anchorConflict = true; break; } } } if (d->anchorConflict) qmlWarning(this) << "Cannot specify anchors for items inside Flow." << " Flow will not function."; } ukui-window-switch-4.21.1.0/windowsview/ukui-flow.h000066400000000000000000000315771522363675600222320ustar00rootroot00000000000000/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. * Copyright (C) 2025, KylinSoft Co., Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtQuick module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ** iaom ****************************************************************************/ #ifndef UKUI_FLOW_H #define UKUI_FLOW_H #include #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) #include #include #include #include #include #else #include #include #include #include #include #endif #include #include #include class UkuiBasePositionerPrivate; class UkuiPositionerAttached : public QObject { Q_OBJECT public: UkuiPositionerAttached(QObject *parent); Q_PROPERTY(int index READ index NOTIFY indexChanged) Q_PROPERTY(bool isFirstItem READ isFirstItem NOTIFY isFirstItemChanged) Q_PROPERTY(bool isLastItem READ isLastItem NOTIFY isLastItemChanged) int index() const { return m_index; } void setIndex(int index); bool isFirstItem() const { return m_isFirstItem; } void setIsFirstItem(bool isFirstItem); bool isLastItem() const { return m_isLastItem; } void setIsLastItem(bool isLastItem); Q_SIGNALS: void indexChanged(); void isFirstItemChanged(); void isLastItemChanged(); private: int m_index; bool m_isFirstItem; bool m_isLastItem; }; class UkuiBasePositioner : public QQuickImplicitSizeItem { Q_OBJECT Q_PROPERTY(qreal spacing READ spacing WRITE setSpacing NOTIFY spacingChanged) Q_PROPERTY(QQuickTransition *populate READ populate WRITE setPopulate NOTIFY populateChanged) Q_PROPERTY(QQuickTransition *move READ move WRITE setMove NOTIFY moveChanged) Q_PROPERTY(QQuickTransition *add READ add WRITE setAdd NOTIFY addChanged) Q_PROPERTY(qreal padding READ padding WRITE setPadding RESET resetPadding NOTIFY paddingChanged) Q_PROPERTY(qreal topPadding READ topPadding WRITE setTopPadding RESET resetTopPadding NOTIFY topPaddingChanged) Q_PROPERTY(qreal leftPadding READ leftPadding WRITE setLeftPadding RESET resetLeftPadding NOTIFY leftPaddingChanged) Q_PROPERTY(qreal rightPadding READ rightPadding WRITE setRightPadding RESET resetRightPadding NOTIFY rightPaddingChanged) Q_PROPERTY(qreal bottomPadding READ bottomPadding WRITE setBottomPadding RESET resetBottomPadding NOTIFY bottomPaddingChanged) public: enum PositionerType { None = 0x0, Horizontal = 0x1, Vertical = 0x2, Both = 0x3 }; UkuiBasePositioner(PositionerType, QQuickItem *parent); ~UkuiBasePositioner(); qreal spacing() const; void setSpacing(qreal); QQuickTransition *populate() const; void setPopulate(QQuickTransition *); QQuickTransition *move() const; void setMove(QQuickTransition *); QQuickTransition *add() const; void setAdd(QQuickTransition *); static UkuiPositionerAttached *qmlAttachedProperties(QObject *obj); void updateAttachedProperties(UkuiPositionerAttached *specificProperty = nullptr, QQuickItem *specificPropertyOwner = nullptr) const; qreal padding() const; void setPadding(qreal padding); void resetPadding(); qreal topPadding() const; void setTopPadding(qreal padding); void resetTopPadding(); qreal leftPadding() const; void setLeftPadding(qreal padding); void resetLeftPadding(); qreal rightPadding() const; void setRightPadding(qreal padding); void resetRightPadding(); qreal bottomPadding() const; void setBottomPadding(qreal padding); void resetBottomPadding(); Q_INVOKABLE void forceLayout(); protected: UkuiBasePositioner(UkuiBasePositionerPrivate &dd, PositionerType at, QQuickItem *parent); void componentComplete() override; void itemChange(ItemChange, const ItemChangeData &) override; void updatePolish() override; Q_SIGNALS: void spacingChanged(); void populateChanged(); void moveChanged(); void addChanged(); void paddingChanged(); void topPaddingChanged(); void leftPaddingChanged(); void rightPaddingChanged(); void bottomPaddingChanged(); void positioningComplete(); protected Q_SLOTS: void prePositioning(); protected: virtual void doPositioning(QSizeF *contentSize)=0; virtual void reportConflictingAnchors()=0; class PositionedItem { public : PositionedItem(QQuickItem *i); ~PositionedItem() = default; bool operator==(const PositionedItem &other) const { return other.item == item; } qreal itemX() const; qreal itemY() const; void moveTo(const QPointF &pos); void transitionNextReposition(QQuickItemViewTransitioner *transitioner, QQuickItemViewTransitioner::TransitionType type, bool asTarget); bool prepareTransition(QQuickItemViewTransitioner *transitioner, const QRectF &viewBounds); void startTransition(QQuickItemViewTransitioner *transitioner); void updatePadding(qreal lp, qreal tp, qreal rp, qreal bp); QQuickItem *item; std::shared_ptr transitionableItem; int index; bool isNew; bool isVisible; qreal topPadding; qreal leftPadding; qreal rightPadding; qreal bottomPadding; }; QVector positionedItems; QVector unpositionedItems;//Still 'in' the positioner, just not positioned void positionItem(qreal x, qreal y, PositionedItem *target); void positionItemX(qreal, PositionedItem *target); void positionItemY(qreal, PositionedItem *target); void removePositionedItem(QVector *items, int index); void clearPositionedItems(QVector *items); private: Q_DISABLE_COPY(UkuiBasePositioner) Q_DECLARE_PRIVATE(UkuiBasePositioner) }; class UkuiBasePositionerPrivate : public QQuickImplicitSizeItemPrivate, public QQuickItemChangeListener { Q_DECLARE_PUBLIC(UkuiBasePositioner) public: struct ExtraData { ExtraData(); qreal padding; qreal topPadding; qreal leftPadding; qreal rightPadding; qreal bottomPadding; bool explicitTopPadding : 1; bool explicitLeftPadding : 1; bool explicitRightPadding : 1; bool explicitBottomPadding : 1; }; QLazilyAllocated extra; UkuiBasePositionerPrivate() : spacing(0), type(UkuiBasePositioner::None) , transitioner(0), positioningDirty(false) , doingPositioning(false), anchorConflict(false), layoutDirection(Qt::LeftToRight) { } void init(UkuiBasePositioner::PositionerType at) { type = at; } qreal spacing; UkuiBasePositioner::PositionerType type; QQuickItemViewTransitioner *transitioner; void watchChanges(QQuickItem *other); void unwatchChanges(QQuickItem* other); void setPositioningDirty() { Q_Q(UkuiBasePositioner); if (!positioningDirty) { positioningDirty = true; q->polish(); } } bool positioningDirty : 1; bool doingPositioning : 1; bool anchorConflict : 1; Qt::LayoutDirection layoutDirection; void mirrorChange() override { effectiveLayoutDirectionChange(); } bool isLeftToRight() const { if (type == UkuiBasePositioner::Vertical) return true; else return effectiveLayoutMirror ? layoutDirection == Qt::RightToLeft : layoutDirection == Qt::LeftToRight; } void itemSiblingOrderChanged(QQuickItem* other) override { Q_UNUSED(other); setPositioningDirty(); } void itemGeometryChanged(QQuickItem *, QQuickGeometryChange change, const QRectF &) override { if (change.sizeChange()) setPositioningDirty(); } void itemVisibilityChanged(QQuickItem *) override { setPositioningDirty(); } void itemDestroyed(QQuickItem *item) override { Q_Q(UkuiBasePositioner); int index = q->positionedItems.indexOf(UkuiBasePositioner::PositionedItem(item)); if (index >= 0) q->removePositionedItem(&q->positionedItems, index); else if ((index = q->unpositionedItems.indexOf(UkuiBasePositioner::PositionedItem(item))) >= 0) q->removePositionedItem(&q->unpositionedItems, index); } static Qt::LayoutDirection getLayoutDirection(const UkuiBasePositioner *positioner) { return positioner->d_func()->layoutDirection; } static Qt::LayoutDirection getEffectiveLayoutDirection(const UkuiBasePositioner *positioner) { if (positioner->d_func()->effectiveLayoutMirror) return positioner->d_func()->layoutDirection == Qt::RightToLeft ? Qt::LeftToRight : Qt::RightToLeft; else return positioner->d_func()->layoutDirection; } virtual void effectiveLayoutDirectionChange() { } inline qreal padding() const { return extra.isAllocated() ? extra->padding : 0.0; } void setTopPadding(qreal value, bool reset = false); void setLeftPadding(qreal value, bool reset = false); void setRightPadding(qreal value, bool reset = false); void setBottomPadding(qreal value, bool reset = false); }; class UkuiFlowPrivate; class UkuiFlow : public UkuiBasePositioner { Q_OBJECT Q_PROPERTY(Flow flow READ flow WRITE setFlow NOTIFY flowChanged) Q_PROPERTY(Qt::LayoutDirection layoutDirection READ layoutDirection WRITE setLayoutDirection NOTIFY layoutDirectionChanged) Q_PROPERTY(Qt::LayoutDirection effectiveLayoutDirection READ effectiveLayoutDirection NOTIFY effectiveLayoutDirectionChanged) Q_PROPERTY(bool lineHorizontalCenterAlignment READ lineHorizontalCenterAlignment WRITE setLineHorizontalCenterAlignment NOTIFY lineHorizontalCenterAlignmentChanged) public: UkuiFlow(QQuickItem *parent=nullptr); enum Flow { LeftToRight, TopToBottom }; Q_ENUM(Flow) Flow flow() const; void setFlow(Flow); Qt::LayoutDirection layoutDirection() const; void setLayoutDirection (Qt::LayoutDirection); Qt::LayoutDirection effectiveLayoutDirection() const; bool lineHorizontalCenterAlignment() const; void setLineHorizontalCenterAlignment(bool); public Q_SLOTS: int moveCurrentIndexLeft(int currentIndex); int moveCurrentIndexRight(int currentIndex); int moveCurrentIndexUp(int currentIndex); int moveCurrentIndexDown(int currentIndex); int findUpDownItemIndex(int currentIndex, int startIndex, int endIndex); Q_SIGNALS: void flowChanged(); void layoutDirectionChanged(); void effectiveLayoutDirectionChanged(); void lineHorizontalCenterAlignmentChanged(); protected: UkuiFlow(UkuiFlowPrivate &dd, QQuickItem *parent); void doPositioning(QSizeF *contentSize) override; void reportConflictingAnchors() override; private: Q_DISABLE_COPY(UkuiFlow) Q_DECLARE_PRIVATE(UkuiFlow) }; QML_DECLARE_TYPEINFO(UkuiPositionerAttached, QML_HAS_ATTACHED_PROPERTIES) #endif //UKUI_FLOW_H ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch000077500000000000000000000007001522363675600236260ustar00rootroot00000000000000#!/bin/bash process_name="kylin-wlcom" process_count=$(ps aux | grep -v grep | grep -c "$process_name") if [ "$1" == "--show-workspace" ]; then if [ $process_count -gt 0 ]; then /usr/bin/ukui-window-switch-wlcom --show-workspace else dbus-send --session --type=method_call --dest=org.kde.KWin /MultitaskView org.kde.KWin.MultitaskView.show fi else if [ $process_count -gt 0 ]; then /usr/bin/ukui-window-switch-wlcom fi fiukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/000077500000000000000000000000001522363675600250225ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/CMakeLists.txt000066400000000000000000000075741522363675600275770ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.16) # 调试多任务视图需要取消注释下面 add_definitions("-Wall -g") project(ukui-window-switch-wlcom) set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD 20) include(FeatureSummary) find_package(ECM NO_MODULE) set_package_properties(ECM PROPERTIES TYPE REQUIRED DESCRIPTION "Extra CMake Modules." URL "https://commits.kde.org/extra-cmake-modules") feature_summary(WHAT REQUIRED_PACKAGES_NOT_FOUND FATAL_ON_MISSING_REQUIRED_PACKAGES) set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${CMAKE_SOURCE_DIR}/cmake) find_package(PkgConfig REQUIRED) find_package(QT NAMES Qt6 Qt5 COMPONENTS Core Gui REQUIRED) find_package(Qt${QT_VERSION_MAJOR} NO_MODULE COMPONENTS Concurrent Quick Qml LinguistTools DBus REQUIRED) if (QT_VERSION_MAJOR EQUAL "5") set(KF_VERSION_MAJOR "5") find_package(KF5 COMPONENTS Config GlobalAccel I18n REQUIRED) find_package(Qt5Xdg REQUIRED) elseif (QT_VERSION_MAJOR EQUAL "6") set(KF_VERSION_MAJOR "6") find_package(KF6 COMPONENTS Config GlobalAccel I18n REQUIRED) find_package(Qt6Xdg REQUIRED) set(QT_NO_PRIVATE_MODULE_WARNING ON) find_package(Qt6 COMPONENTS QuickPrivate QmlPrivate REQUIRED) endif() find_package(EGL REQUIRED) find_package(ukui-search REQUIRED) find_package(ukui-quick COMPONENTS platform) pkg_check_modules(KDK REQUIRED kysdk-sysinfo) pkg_check_modules(DATACOLLECT REQUIRED kysdk-datacollect) pkg_check_modules(GL REQUIRED gl) include_directories(${KDK_INCLUDE_DIRS}) include_directories(${DATACOLLECT_INCLUDE_DIRS}) include_directories(${OPENGL_INCLUDE_DIR}) include_directories(${GL}) set(WLCSRCS main.cpp log-utils.h log-utils.cpp ../desktopbackground.cpp ../icontheme.cpp multitaskviewmanagerbywlcom.cpp dbusservice.cpp ../windowmanagerinterface.cpp ../multitaskviewabstractmodelhandler.h multitaskviewmodelbywlcomhandler.cpp context.cpp toplevel.cpp workspace.cpp output.cpp thumbnail.cpp ThumbnailItem.cpp ../desktoplistmodel.h ../desktoplistmodel.cpp ../appwindowlistmodel.h ../appwindowlistmodel.cpp ../appwindowfiltermodel.h ../appwindowfiltermodel.cpp ../ukui-flow.cpp ../ukui-flow.h ../screens-manager.cpp ../screens-manager.h ) add_subdirectory(qtsingleapplication) include_directories(qtsingleapplication/src) if (QT_VERSION_MAJOR EQUAL "5") qt5_add_resources(WLCSRCS ../data.qrc) else() qt_add_resources(WLCSRCS ../data.qrc) endif() add_executable(${PROJECT_NAME} ${WLCSRCS} ) target_link_directories(${PROJECT_NAME} PRIVATE KF${KF_VERSION_MAJOR}::WindowSystem) target_compile_definitions(${PROJECT_NAME} PRIVATE $<$:DISABLE_LOG_FILE>) target_compile_definitions(${PROJECT_NAME} PRIVATE $<$:QT_QML_DEBUG>) target_link_libraries( ${PROJECT_NAME} PRIVATE Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::GuiPrivate Qt${QT_VERSION_MAJOR}::Quick Qt${QT_VERSION_MAJOR}::Concurrent Qt${QT_VERSION_MAJOR}::DBus Qt${QT_VERSION_MAJOR}::Qml KF${KF_VERSION_MAJOR}::GlobalAccel qtsingleapplication kywc ${QGSettings_LIBRARIES} ${KDK_LINK_LIBRARIES} ${DATACOLLECT_LINK_LIBRARIES} ${OPENGL_gl_LIBRARY} ${EGL_LIBRARY} ${GL_LIBRARIES} Qt${QT_VERSION_MAJOR}Xdg ukui-search ukui-quick::platform ) if (QT_VERSION_MAJOR EQUAL "5") target_include_directories(${PROJECT_NAME} PRIVATE ${Qt5Quick_PRIVATE_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} PRIVATE Qt5::QuickPrivate Qt::QmlPrivate) else() target_link_libraries(${PROJECT_NAME} PRIVATE Qt::GuiPrivate Qt6::QuickPrivate) endif() install(TARGETS ukui-window-switch-wlcom DESTINATION /usr/bin) ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/ThumbnailItem.cpp000066400000000000000000000256171522363675600303030ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include "ThumbnailItem.h" #include #include #include #include #include #include class ThumbnailItem::Private { public: Private(ThumbnailItem *item); ~Private(); void createEglImage(Thumbnail *thumbnail); void imageFromMemfd(Thumbnail *thumbnail); EGLImage m_image = EGL_NO_IMAGE_KHR; QImage image; uint32_t format; QString m_id; QString m_outputid; void *mem_ptr = nullptr; Thumbnail::BufferFlags thumFlags = Thumbnail::BufferFlag::Dmabuf; uint8_t *map = nullptr; size_t dataSize = 0; private: ThumbnailItem *t; }; ThumbnailItem::Private::Private(ThumbnailItem *item) : t(item) {} ThumbnailItem::Private::~Private() {} QSGNode *ThumbnailItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) { QSGTexture *texture = NULL; if (pri->thumFlags & Thumbnail::BufferFlag::Dmabuf) { if (pri->m_image == EGL_NO_IMAGE_KHR) { QImage q_image(200, 200, QImage::Format_ARGB32_Premultiplied); q_image.fill(Qt::transparent); texture = window()->createTextureFromImage(q_image, QQuickWindow::TextureIsOpaque); } else { #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) const auto *context = window()->openglContext(); #else const auto *context = static_cast(window()->rendererInterface()->getResource(window(), QSGRendererInterface::OpenGLContextResource)); #endif if (!context || !context->isValid()) { qWarning() << "OpenGL context is not valid."; return NULL; } QOpenGLTexture *m_texture = new QOpenGLTexture(QOpenGLTexture::Target2D); bool created = m_texture->create(); Q_ASSERT(created); static auto s_glEGLImageTargetTexture2DOES = (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)eglGetProcAddress( "glEGLImageTargetTexture2DOES"); if (!s_glEGLImageTargetTexture2DOES) { qWarning() << "glEGLImageTargetTexture2DOES is not available" << window(); return NULL; } m_texture->bind(); s_glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, (GLeglImageOES)pri->m_image); m_texture->setWrapMode(QOpenGLTexture::ClampToEdge); m_texture->setMinMagFilters(QOpenGLTexture::Linear, QOpenGLTexture::Linear); m_texture->release(); m_texture->setSize(boundingRect().toRect().size().width(), boundingRect().toRect().size().height()); int textureId = m_texture->textureId(); QQuickWindow::CreateTextureOption textureOption = pri->format == DRM_FORMAT_ARGB8888 ? QQuickWindow::TextureHasAlphaChannel : QQuickWindow::TextureIsOpaque; #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) texture = window()->createTextureFromNativeObject(QQuickWindow::NativeObjectTexture, &textureId, 0 /*a vulkan thing?*/, window()->size(), textureOption); #else texture = QNativeInterface::QSGOpenGLTexture::fromNative(textureId, window(),window()->size(), textureOption); #endif } } else { if (pri->image.isNull()) { qWarning() << "image.isNull() " << strerror(errno); QImage errorImage(200, 200, QImage::Format_ARGB32_Premultiplied); errorImage.fill(Qt::red); pri->image = errorImage; } texture = window()->createTextureFromImage(pri->image, QQuickWindow::TextureIsOpaque); } QSGImageNode *textureNode = static_cast(oldNode); if (!textureNode) { textureNode = window()->createImageNode(); textureNode->setOwnsTexture(true); } textureNode->setTexture(texture); const auto br = boundingRect().toRect(); textureNode->setRect(br); return textureNode; } ThumbnailItem::ThumbnailItem(QQuickItem *parent) : QQuickItem(parent), pri(new Private(this)) { setFlag(ItemHasContents, true); // 必须设置,表明这个Item有内容需要绘制 QPlatformNativeInterface *native = QGuiApplication::platformNativeInterface(); if (!native) { return; } m_display = reinterpret_cast( native->nativeResourceForIntegration(QByteArrayLiteral("wl_display"))); if (!m_display) { qWarning("Failed to get Wayland display."); return; } } ThumbnailItem::~ThumbnailItem() { if(m_active && !m_thumbnailIsDeleted) { if (pri->map) { munmap(pri->map, pri->dataSize); pri->map = nullptr; } thumbnail->destory(); } } #define ADD_ATTRIB(name, value) \ do { \ attribs[num_attribs++] = (name); \ attribs[num_attribs++] = (value); \ attribs[num_attribs] = EGL_NONE; \ } while (0) void ThumbnailItem::Private::createEglImage(Thumbnail *thumbnail) { EGLDisplay display = EGL_NO_DISPLAY; display = static_cast( QGuiApplication::platformNativeInterface()->nativeResourceForIntegration("egldisplay")); if (display == EGL_NO_DISPLAY) { qWarning() << "egl get display failed "; return; } if (m_image) { if (thumFlags & Thumbnail::BufferFlag::Reused) return; static auto eglDestroyImageKHR = (PFNEGLDESTROYIMAGEKHRPROC)eglGetProcAddress("eglDestroyImageKHR"); eglDestroyImageKHR(display, m_image); } EGLint attribs[20] = { EGL_NONE }; int num_attribs = 0; ADD_ATTRIB(EGL_WIDTH, thumbnail->size().width()); ADD_ATTRIB(EGL_HEIGHT, thumbnail->size().height()); ADD_ATTRIB(EGL_LINUX_DRM_FOURCC_EXT, thumbnail->format()); ADD_ATTRIB(EGL_DMA_BUF_PLANE0_FD_EXT, thumbnail->fd()); ADD_ATTRIB(EGL_DMA_BUF_PLANE0_OFFSET_EXT, thumbnail->offset()); ADD_ATTRIB(EGL_DMA_BUF_PLANE0_PITCH_EXT, thumbnail->stride()); if (thumbnail->modifier() != DRM_FORMAT_MOD_INVALID) { ADD_ATTRIB(EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT, thumbnail->modifier() & 0xFFFFFFFF); ADD_ATTRIB(EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT, thumbnail->modifier() >> 32); } ADD_ATTRIB(EGL_IMAGE_PRESERVED_KHR, EGL_TRUE); format = thumbnail->format(); static auto eglCreateImageKHR = (PFNEGLCREATEIMAGEKHRPROC)eglGetProcAddress("eglCreateImageKHR"); Q_ASSERT(eglCreateImageKHR); m_image = eglCreateImageKHR(display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, attribs); if (m_image == EGL_NO_IMAGE_KHR) { qWarning() << "invalid eglCreateImageKHR" << glGetError(); } } void ThumbnailItem::Private::imageFromMemfd(Thumbnail *thumbnail) { if (thumFlags & Thumbnail::BufferFlag::Reused) return; dataSize = thumbnail->size().height() * thumbnail->stride() + thumbnail->offset(); map = static_cast(mmap(nullptr, dataSize, PROT_READ, MAP_PRIVATE, thumbnail->fd(), 0)); if (map == MAP_FAILED) { qWarning() << "Failed to mmap the memory: " << strerror(errno); return; } } void ThumbnailItem::BufferImportDmabuf() { Thumbnail *thum = qobject_cast(sender()); if (thum->flags() & Thumbnail::BufferFlag::Dmabuf) { pri->createEglImage(thum); } else { pri->imageFromMemfd(thum); if (pri->map) { const QImage::Format qtFormat = thumbnail->stride() / thumbnail->size().width() == 3 ? QImage::Format_RGB888 : QImage::Format_ARGB32; QImage img(pri->map, thumbnail->size().width(), thumbnail->size().height(), thumbnail->stride(), qtFormat); pri->image = img.copy(); } } pri->format = thumbnail->format(); pri->thumFlags = thumbnail->flags(); update(); } void ThumbnailItem::setOutputId(QString outputId) { pri->m_outputid = outputId; emit outputIdChanged(); } void ThumbnailItem::setWindowId(QString windowId) { if (pri->m_id != windowId) { pri->m_id = windowId; active(m_active && !windowId.isEmpty()); emit windowIdChanged(); } } void ThumbnailItem::setThumbnailType(int type) { m_thumbnailType = type; emit thumbnailTypeChanged(); } void ThumbnailItem::setActive(bool active) { this->active(active); } QString ThumbnailItem::outputId() const { return pri->m_outputid; } QString ThumbnailItem::windowId() const { return pri->m_id; } void ThumbnailItem::active(bool active) { if(active && !pri->m_id.isEmpty()) { if(m_currentUuid == pri->m_id || !isVisible()) { return; } if(!context) { context = new Context(m_display, Context::Capability::Thumbnail); context->start(); } if(!thumbnail) { thumbnail = new Thumbnail(this); connect(thumbnail, &Thumbnail::bufferUpdate, this, &ThumbnailItem::BufferImportDmabuf); connect(thumbnail, &Thumbnail::deleted, this, &ThumbnailItem::thumbnailIsDeleted); } context->thumbnail_init(thumbnail, (Thumbnail::Type)m_thumbnailType, pri->m_id, pri->m_outputid); m_active = true; emit isActiveChanged(); m_currentUuid = pri->m_id; m_thumbnailIsDeleted = false; } else { if(m_active && !m_thumbnailIsDeleted) { if (pri->map) { munmap(pri->map, pri->dataSize); pri->map = nullptr; } thumbnail->destory(); } } } void ThumbnailItem::thumbnailIsDeleted() { m_thumbnailIsDeleted = true; thumbnail = nullptr; m_active = false; emit isActiveChanged(); } ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/ThumbnailItem.h000066400000000000000000000044551522363675600277450ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef THUMBNAILITEM_H #define THUMBNAILITEM_H #include #include #include "context.h" class ThumbnailItem : public QQuickItem { Q_OBJECT Q_PROPERTY(QString windowId READ windowId WRITE setWindowId NOTIFY windowIdChanged) Q_PROPERTY(QString outputId READ outputId WRITE setOutputId NOTIFY outputIdChanged) Q_PROPERTY(int thumbnailType READ thumbnailType WRITE setThumbnailType NOTIFY thumbnailTypeChanged) Q_PROPERTY(bool isActive READ isActive WRITE setActive NOTIFY isActiveChanged) public: explicit ThumbnailItem(QQuickItem *parent = nullptr); ~ThumbnailItem(); QString windowId() const; void setWindowId(QString windowId); QString outputId() const; void setOutputId(QString outputId); int thumbnailType() { return m_thumbnailType; } void setThumbnailType(int type); bool isActive() { return m_active; } void setActive(bool active); signals: void windowIdChanged(); void outputIdChanged(); void thumbnailTypeChanged(); void isActiveChanged(); protected: QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) override; private Q_SLOTS: void BufferImportDmabuf(); void thumbnailIsDeleted(); private: void active(bool active); class Private; Private *pri; Context *context = nullptr; Thumbnail *thumbnail = nullptr; int m_thumbnailType = 1; bool m_active = false; bool m_thumbnailIsDeleted = false; QString m_currentUuid; wl_display *m_display = nullptr; }; #endif // ThumbnailItem_H ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/context.cpp000066400000000000000000000133741522363675600272220ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "context.h" #include #include #include class Context::Private { public: Private(Context *context); ~Private(); kywc_context *setup(uint32_t capability); kywc_context *k_context = nullptr; QSocketNotifier *notifier = nullptr; struct wl_display *display = NULL; uint32_t capabilities = 0; private: Context *ctx; static void createHandle(kywc_context *context, void *data); static void destroyHandle(kywc_context *context, void *data); static void newOutput(kywc_context *context, kywc_output *output, void *data); static void newToplevel(kywc_context *context, kywc_toplevel *toplevel, void *data); static void newWorkspace(kywc_context *context, kywc_workspace *workspace, void *data); static struct kywc_context_interface context_impl; }; Context::Private::Private(Context *context) : ctx(context) {} Context::Private::~Private() {} void Context::Private::createHandle(kywc_context *context, void *data) { Context::Private *p = (Context::Private *)data; emit p->ctx->created(); } void Context::Private::destroyHandle(kywc_context *context, void *data) { Context::Private *p = (Context::Private *)data; emit p->ctx->destroyed(); } void Context::Private::newOutput(kywc_context *context, kywc_output *output, void *data) { Context::Private *p = (Context::Private *)data; Output *o = new Output(p->ctx); o->setup(output); emit p->ctx->outputAdded(o); } void Context::Private::newToplevel(kywc_context *context, kywc_toplevel *toplevel, void *data) { Context::Private *p = (Context::Private *)data; Toplevel *t = new Toplevel(p->ctx); t->setup(toplevel); emit p->ctx->toplevelAdded(t); } void Context::Private::newWorkspace(kywc_context *context, kywc_workspace *workspace, void *data) { Context::Private *p = (Context::Private *)data; Workspace *w = new Workspace(p->ctx); w->setup(workspace); emit p->ctx->workespaceAdded(w); } struct kywc_context_interface Context::Private::context_impl = { createHandle, destroyHandle, newOutput, newToplevel, newWorkspace, }; kywc_context *Context::Private::setup(uint32_t capabilities) { if (!display) k_context = kywc_context_create(NULL, capabilities, &context_impl, this); else k_context = kywc_context_create_by_display(display, capabilities, &context_impl, this); return k_context; } Context::Context( struct wl_display *display, Capabilities caps, QObject *parent) : QObject{parent} , pri(new Private(this)) { pri->display = display; uint32_t capabilities = 0; if (caps & Context::Capability::Output) capabilities |= KYWC_CONTEXT_CAPABILITY_OUTPUT; if (caps & Context::Capability::Toplevel) capabilities |= KYWC_CONTEXT_CAPABILITY_TOPLEVEL; if (caps & Context::Capability::Workspace) capabilities |= KYWC_CONTEXT_CAPABILITY_WORKSPACE; if (caps & Context::Capability::Thumbnail) capabilities |= KYWC_CONTEXT_CAPABILITY_THUMBNAIL; pri->capabilities = capabilities; } Context::~Context() { qDebug()<<"~Context"; kywc_context_destroy(pri->k_context); } void Context::start() { kywc_context *ctx = NULL; if (!pri->display) { ctx = pri->setup(pri->capabilities); if (!ctx) { return; } pri->notifier = new QSocketNotifier(kywc_context_get_fd(ctx), QSocketNotifier::Read, this); connect(pri->notifier, &QSocketNotifier::activated, this, &Context::onContextReady); kywc_context_process(ctx); } else { ctx = pri->setup(pri->capabilities); if (!ctx) { return; } } } void Context::onContextReady() { if (kywc_context_process(pri->k_context) < 0) { disconnect(pri->notifier, &QSocketNotifier::activated, this, &Context::onContextReady); emit aboutToTeardown(); exit(-1); } } void Context::dispatch() { kywc_context_dispatch(pri->k_context); } void Context::addWorkspace(uint32_t position) { kywc_workspace_create(pri->k_context, NULL, position); } Workspace *Context::findWorkspace(QString uuid) { QByteArray qByteArray = uuid.toUtf8(); char *str = qByteArray.data(); kywc_workspace *workspace = kywc_context_find_workspace(pri->k_context, str); return (Workspace *)kywc_workspace_get_user_data(workspace); } Output *Context::findOutput(QString uuid) { QByteArray qByteArray = uuid.toUtf8(); char *str = qByteArray.data(); kywc_output *output = kywc_context_find_output(pri->k_context, str); return (Output *)kywc_output_get_user_data(output); } Toplevel *Context::findToplevel(QString uuid) { QByteArray qByteArray = uuid.toUtf8(); char *str = qByteArray.data(); kywc_toplevel *toplevel = kywc_context_find_toplevel(pri->k_context, str); return (Toplevel *)kywc_toplevel_get_user_data(toplevel); } void Context::thumbnail_init(Thumbnail *thumbnail, Thumbnail::Type type, QString uuid, QString output_uuid) { thumbnail->setup(pri->k_context, type, uuid, output_uuid); } ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/context.h000066400000000000000000000157471522363675600266750ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef CONTEXT_H #define CONTEXT_H #include #include #include #include #include typedef struct _kywc_context kywc_context; typedef struct _kywc_output kywc_output; typedef struct _kywc_toplevel kywc_toplevel; typedef struct _kywc_workspace kywc_workspace; typedef struct _kywc_thumbnail kywc_thumbnail; class Workspace : public QObject { Q_OBJECT public: enum class Mask { Name = 1 << 0, Position = 1 << 1, Activated = 1 << 2, }; Q_DECLARE_FLAGS(Masks, Mask); explicit Workspace(QObject *parent = nullptr); ~Workspace(); void setup(kywc_workspace *workspace); QString name() const; QString uuid() const; int position() const; bool isActivated() const; void setActivate(); void move(int position); void remove(); void setName(const QString name); Q_SIGNALS: void stateUpdated(Workspace::Masks mask); void deleted(); private: class Private; Private *pri; }; Q_DECLARE_OPERATORS_FOR_FLAGS(Workspace::Masks) class Output : public QObject { Q_OBJECT public: struct Mode { QSize size; int32_t refresh; // mHz bool preferred; }; enum class Capability { Power = 1 << 0, Brightness = 1 << 1, ColorTemp = 1 << 2, }; Q_DECLARE_FLAGS(Capabilities, Capability); enum class Mask { Enabled = 1 << 0, Mode = 1 << 1, Position = 1 << 2, Transform = 1 << 3, Scale = 1 << 4, Power = 1 << 5, Primary = 1 << 6, Brightness = 1 << 7, ColorTemp = 1 << 8, }; Q_DECLARE_FLAGS(Masks, Mask); explicit Output(QObject *parent = nullptr); ~Output(); void setup(kywc_output *output); QString name() const; QString uuid() const; QString make() const; QString model() const; QString serial() const; QString description() const; QSize physicalSize() const; Output::Capabilities capabilities() const; QList modes() const; Output::Mode curMode() const; QPoint point() const; QSize size() const; int transform() const; float scale() const; bool isEnabled() const; bool isPower() const; bool isPrimary() const; uint32_t brightness() const; uint32_t colorTemp() const; Q_SIGNALS: void stateUpdated(Output::Masks mask); void deleted(); private: class Private; Private *pri; }; Q_DECLARE_OPERATORS_FOR_FLAGS(Output::Capabilities) Q_DECLARE_OPERATORS_FOR_FLAGS(Output::Masks) class Toplevel : public QObject { Q_OBJECT public: enum class Capability { Taskbar = 1 << 0, Switcher = 1 << 1, }; Q_DECLARE_FLAGS(Capabilities, Capability); enum class Mask { AppId = 1 << 0, Title = 1 << 1, Activated = 1 << 2, Minimized = 1 << 3, Maximized = 1 << 4, Fullscreen = 1 << 5, PrimaryOutput = 1 << 6, Workspace = 1 << 7, Parent = 1 << 8, Icon = 1 << 9, Position = 1 << 10, Size = 1 << 11, }; Q_DECLARE_FLAGS(Masks, Mask) explicit Toplevel(QObject *parent = nullptr); ~Toplevel(); void setup(kywc_toplevel *toplevel); QString uuid() const; QString title() const; QString icon() const; QString appId() const; QPointer parent() const; QString primaryOutput() const; QStringList workspaces() const; QPoint point() const; QSize size() const; Toplevel::Capabilities capabilities() const; bool isActivated() const; bool isMinimized() const; bool isMaximized() const; bool isFullscreen() const; uint32_t pid() const; void setMaximized(QString output); void setMinimized(); void unsetMaximized(); void unsetMinimized(); void setFullscreen(QString output); void unsetFullscreen(); void setActivate(); void close(); void enterWorkspace(QString workspace); void leaveWorkspace(QString workspace); void moveToWorkspace(QString workspace); void moveToOutput(QString output); bool hasChildren(); void setDesktopFile(const QString &desktopFile); QString iconName() const; QString name() const; Q_SIGNALS: void stateUpdated(Toplevel::Masks mask); void deleted(); private: class Private; Private *pri; }; Q_DECLARE_OPERATORS_FOR_FLAGS(Toplevel::Capabilities) Q_DECLARE_OPERATORS_FOR_FLAGS(Toplevel::Masks) class Thumbnail : public QObject { Q_OBJECT public: enum Type{ Output, Toplevel, Workspace, }; enum BufferFlag { Dmabuf = 1 << 0, Reused = 1 << 1, }; Q_DECLARE_FLAGS(BufferFlags, BufferFlag); explicit Thumbnail(QObject *parent = nullptr); ~Thumbnail(); void setup(kywc_context *ctx, Thumbnail::Type type, QString uuid, QString output_uuid); void destory(); int32_t fd() const; uint32_t format() const; QSize size() const; uint32_t offset() const; uint32_t stride() const; uint64_t modifier() const; Thumbnail::BufferFlags flags() const; Q_SIGNALS: void bufferUpdate(); void deleted(); private: class Private; Private *pri; }; Q_DECLARE_OPERATORS_FOR_FLAGS(Thumbnail::BufferFlags) class Context : public QObject { Q_OBJECT public: enum class Capability { Output = 1 << 0, Toplevel = 1 << 1, Workspace = 1 << 2, Thumbnail = 1 << 3, }; Q_DECLARE_FLAGS(Capabilities, Capability) explicit Context(struct wl_display *display, Capabilities caps, QObject *parent = nullptr); ~Context(); void start(); void thumbnail_init(Thumbnail *thumbnail, Thumbnail::Type type, QString uuid, QString output_uuid); void addWorkspace(uint32_t position); Workspace *findWorkspace(QString uuid); Output *findOutput(QString uuid); Toplevel *findToplevel(QString uuid); void dispatch(); Q_SIGNALS: void aboutToTeardown(); void created(); void destroyed(); void workespaceAdded(Workspace *workspace); void outputAdded(Output *output); void toplevelAdded(Toplevel *toplevel); private Q_SLOTS: void onContextReady(); private: class Private; Private *pri; }; Q_DECLARE_OPERATORS_FOR_FLAGS(Context::Capabilities) #endif // CONTEXT_H ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/dbusservice.cpp000066400000000000000000000030131522363675600300410ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "dbusservice.h" #include "multitaskviewmanagerbywlcom.h" DBusService::DBusService(MultitaskViewManagerByWlcom *viewManager, QObject *parent) : QObject(parent), m_viewManager(viewManager), m_connection(QDBusConnection::sessionBus()) { startService(); } DBusService::~DBusService() { stopService(); } bool DBusService::startService() { return m_connection.registerService(m_serviceName) & m_connection.registerObject(m_servicePath, this, QDBusConnection::ExportAllSlots); } bool DBusService::stopService() { m_connection.unregisterObject(m_servicePath); return m_connection.unregisterService(m_serviceName); } void DBusService::show() { m_viewManager->open(); } void DBusService::hide() { m_viewManager->close(); } ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/dbusservice.h000066400000000000000000000031531522363675600275130ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef DBUSSERVICE_H #define DBUSSERVICE_H #include #include #include // 前置声明。解决dbusservice.h和multitaskviewmanager.h // 相互引用引发QtCreator提示DBusService类型找不到的问题 class MultitaskViewManagerByWlcom; class DBusService : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kylin.switch.MultitaskView") public: DBusService(MultitaskViewManagerByWlcom* viewManager, QObject *parent = nullptr); ~DBusService(); public slots: void show(); void hide(); private: bool startService(); bool stopService(); private: MultitaskViewManagerByWlcom* m_viewManager = nullptr; QString m_serviceName = "org.kylin.switch"; QString m_servicePath = "/MultitaskView"; QDBusConnection m_connection; }; #endif // DBUSSERVICE_H ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/log-utils.cpp000066400000000000000000000105771522363675600274570ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: iaom * */ #include "log-utils.h" #include #include #include #include #include #define LOG_FILE_COUNT 2 #define MAX_LOG_FILE_SIZE 4194304 #define MAX_LOG_CHECK_INTERVAL 43200000 quint64 LogUtils::m_startUpTime = 0; int LogUtils::m_logFileId = -1; QString LogUtils::m_logFileName; QString LogUtils::m_currentLogFile; static QString logFilePath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + "/.log/ukui-window-switch/"; void LogUtils::messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) { checkLogFile(); QByteArray localMsg = msg.toLocal8Bit(); QByteArray currentTime = QTime::currentTime().toString().toLocal8Bit(); const char *file = context.file ? context.file : ""; const char *function = context.function ? context.function : ""; FILE *log_file = fopen(m_currentLogFile.toLocal8Bit().constData(), "a+"); switch (type) { case QtDebugMsg: if (!log_file) { break; } fprintf(log_file, "Debug: %s: %s (%s:%u, %s)\n", currentTime.constData(), localMsg.constData(), file, context.line, function); break; case QtInfoMsg: fprintf(log_file? log_file: stdout, "Info: %s: %s (%s:%u, %s)\n", currentTime.constData(), localMsg.constData(), file, context.line, function); break; case QtWarningMsg: fprintf(log_file? log_file: stderr, "Warning: %s: %s (%s:%u, %s)\n", currentTime.constData(), localMsg.constData(), file, context.line, function); break; case QtCriticalMsg: fprintf(log_file? log_file: stderr, "Critical: %s: %s (%s:%u, %s)\n", currentTime.constData(), localMsg.constData(), file, context.line, function); break; case QtFatalMsg: fprintf(log_file? log_file: stderr, "Fatal: %s: %s (%s:%u, %s)\n", currentTime.constData(), localMsg.constData(), file, context.line, function); break; } if (log_file) { fclose(log_file); } } void LogUtils::initLogFile(const QString &fileName) { QDir dir; if (!dir.exists(logFilePath)) { if (!dir.mkpath(logFilePath)) { qWarning() << "Unable to create" << logFilePath; return; } } m_logFileName = logFilePath + fileName + "-%1.log"; for (int i = 0; i < LOG_FILE_COUNT; ++i) { m_currentLogFile = m_logFileName.arg(i); if (QFile::exists(m_currentLogFile)) { if (checkFileSize(m_currentLogFile)) { m_logFileId = i; break; } } else { QFile file(m_currentLogFile); file.open(QIODevice::WriteOnly); file.close(); } } if (m_logFileId < 0) { m_logFileId = 0; m_currentLogFile = m_logFileName.arg(m_logFileId); clearFile(m_currentLogFile); } qInfo() << "Current log file:" << m_currentLogFile; } void LogUtils::checkLogFile() { quint64 logTime = QDateTime::currentDateTime().toMSecsSinceEpoch(); quint64 spacing = std::max(logTime, m_startUpTime) - std::min(logTime, m_startUpTime); if (spacing <= MAX_LOG_CHECK_INTERVAL || checkFileSize(m_currentLogFile)) { return; } m_logFileId = ((m_logFileId + 1) % LOG_FILE_COUNT); m_currentLogFile = m_logFileName.arg(m_logFileId); if (!checkFileSize(m_currentLogFile)) { clearFile(m_currentLogFile); } } bool LogUtils::checkFileSize(const QString &fileName) { return QFile(fileName).size() < MAX_LOG_FILE_SIZE; } void LogUtils::clearFile(const QString &fileName) { QFile file(fileName); file.open(QIODevice::WriteOnly); file.write(""); file.flush(); file.close(); } ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/log-utils.h000066400000000000000000000024321522363675600271130ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: iaom * */ #ifndef LOGUTILS_H #define LOGUTILS_H #include class LogUtils { public: static void initLogFile(const QString &fileName); static void messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg); private: static void checkLogFile(); static bool checkFileSize(const QString &fileName); static void clearFile(const QString &fileName); static quint64 m_startUpTime; static int m_logFileId; static QString m_logFileName; static QString m_currentLogFile; }; #endif // LOGUTILS_H ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/main.cpp000066400000000000000000000035701522363675600264570ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include "qtsingleapplication.h" #include "context.h" #include "multitaskviewmanagerbywlcom.h" #include "log-utils.h" int main(int argc, char *argv[]) { #ifndef DISABLE_LOG_FILE LogUtils::initLogFile("ukui-window-switch-wlcom"); qInstallMessageHandler(LogUtils::messageOutput); #endif QtSingleApplication a(argc, argv); QCommandLineParser parser; QCommandLineOption showWorkSpaceOption("show-workspace","show multitaskView"); parser.addOption(showWorkSpaceOption); parser.process(a); if (a.isRunning()) { if (parser.isSet(showWorkSpaceOption)) { a.sendMessage(QApplication::arguments().length() > 1 ? QApplication::arguments().at(1) : a.applicationFilePath()); } return EXIT_SUCCESS; } MultitaskViewManagerByWlcom m; if (parser.isSet(showWorkSpaceOption)) { m.open(); } QObject::connect(&a, &QtSingleApplication::messageReceived, [&m](){ m.open(); }); return QtSingleApplication::exec(); } ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/manager.cpp000066400000000000000000000017141522363675600271430ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "manager.h" #include manager::manager() { m_view.reset(new QQuickView()); m_view->show(); m_view->setSource(QUrl("")); m_view->setGeometry(QRect(0,0,1000,1000)); } ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/manager.h000066400000000000000000000020731522363675600266070ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef MANAGER_H #define MANAGER_H #include #include #include #include #include "context.h" class manager : public QObject { Q_OBJECT public: manager(); kywc_context *ctx = nullptr; std::unique_ptr m_view = nullptr; }; #endif // MANAGER_H ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/multitaskviewmanagerbywlcom.cpp000066400000000000000000000560501522363675600333740ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "multitaskviewmanagerbywlcom.h" // kf5 kf6 #include // kysdk #include #include // Qt #include #include #include #include #include #include #include #include #include #include //ukui-quick #include #include "../windowmanagerinterface.h" #include "../desktopbackground.h" #include "../icontheme.h" #include "ThumbnailItem.h" #include "../appwindowfiltermodel.h" #include "../ukui-flow.h" bool MultitaskViewManagerByWlcom::m_isOpenGLBackend = true; bool MultitaskViewManagerByWlcom::isOpen = false; bool MultitaskViewManagerByWlcom::m_isEffect = false; #define CONTROL_CENTER_SETTING "org.ukui.control-center.personalise" #define CONTROL_CENTER_EFFECT_KEY "effect" MultitaskViewManagerByWlcom::MultitaskViewManagerByWlcom() { initializeProjectType(); registerQmlTypes(); registerShortcut(); initDBusService(); installTranslator(); initGuiLayouDirection(); initEffect(); WindowManagerInterface::getInstance(); const QByteArray id("org.mate.background"); if(QGSettings::isSchemaInstalled(id)){ QGSettings * backgSetting = new QGSettings(id, QByteArray(), this); connect(backgSetting, &QGSettings::changed,[=](QString key) { if ("pictureFilename" == key) { updateDesktopBackground(); } }); } updateDesktopBackground(); initModel(); initView(); connectSignals(); } MultitaskViewManagerByWlcom::~MultitaskViewManagerByWlcom() { close(); destroyView(); if (m_translator) { m_translator->deleteLater(); m_translator = nullptr; } } bool MultitaskViewManagerByWlcom::isCursorNavigationKey(const int &key) const { if (key == Qt::Key_Tab || key == Qt::Key_Left || key == Qt::Key_Right || key == Qt::Key_Up || key == Qt::Key_Down || key == Qt::Key_Home || key == Qt::Key_End || key == Qt::Key_PageUp || key == Qt::Key_PageDown) { return true; } return false; } void MultitaskViewManagerByWlcom::activeAreaChangeDataCollect(const QString &areaName) { QByteArray name = areaName.toLatin1(); QtConcurrent::run([name]() { const char* text = name.data(); KCustomProperty property[1]; property[0].key = (char*)"activeAreaName"; property[0].value = (char*)text; KTrackData *node = kdk_dia_data_init(KEVENTSOURCE_DESKTOP, KEVENT_CUSTOM); kdk_dia_append_custom_property(node, property, 1); kdk_dia_upload_default(node, (char*)"keyboard_navigation_active_area_changed_event", (char*)"ukui-window-switch"); kdk_dia_data_free(node); }); } bool MultitaskViewManagerByWlcom::isAltKeyPressed() { return QGuiApplication::queryKeyboardModifiers() & Qt::KeyboardModifier::AltModifier; } void MultitaskViewManagerByWlcom::keyNavigationDataCollect(const int &keyValue) { if (!isCursorNavigationKey(keyValue)) { return; } QByteArray name = QKeySequence(keyValue).toString().toLatin1(); QtConcurrent::run([name]() { const char* text = name.data(); KCustomProperty property[1]; property[0].key = (char*)"keyName"; property[0].value = (char*)text; KTrackData *node = kdk_dia_data_init(KEVENTSOURCE_DESKTOP, KEVENT_CLICK); kdk_dia_append_custom_property(node, property, 1); kdk_dia_upload_default(node, (char*)"keyboard_navigation_event", (char*)"ukui-window-switch"); kdk_dia_data_free(node); }); } void MultitaskViewManagerByWlcom:: open() { if (isOpen) { close(); return; } qDebug() << "开启多任务视图" << __FUNCTION__ << __LINE__ << isOpen; // 可旋转的机器,多任务视图打开的时候,禁用旋转 if(m_isLoadTabletModeQML && getRotationModeStatus()) { setRotationModeStatus(!m_isAutoRotateBeforeShowMultiTask); } m_isShowTabBorder = false; showTaskView(); isOpen = true; QtConcurrent::run([]() { KTrackData *node = kdk_dia_data_init(KEVENTSOURCE_DESKTOP, KEVENT_CUSTOM); kdk_dia_upload_default(node, (char*)"ukui_window_switch_start_event", (char*)"ukui-window-switch"); kdk_dia_data_free(node); }); } void MultitaskViewManagerByWlcom::openTab() { if (isOpen) { int currentIndex = m_tabView->rootObject()->property("currentIndex").toInt(); int allcount = m_appWindowListModel->rowCount(); if (currentIndex + 1 == allcount) { currentIndex = 0; } else { currentIndex++; } m_tabView->rootObject()->setProperty("currentIndex", currentIndex); return; } qDebug() << "正向遍历窗口" << __FUNCTION__ << __LINE__ << isOpen; m_isBackTab = false; // 可旋转的机器,多任务视图打开的时候,禁用旋转 if(m_isLoadTabletModeQML && getRotationModeStatus()) { setRotationModeStatus(!m_isAutoRotateBeforeShowMultiTask); } if (m_appWindowListModel->rowCount() == 0) { return; } showTabView(); isOpen = true; } void MultitaskViewManagerByWlcom::openBackTab() { if (isOpen) { int currentIndex = m_tabView->rootObject()->property("currentIndex").toInt(); if (currentIndex == 0) { currentIndex = m_appWindowListModel->rowCount() - 1; } else { currentIndex--; } m_tabView->rootObject()->setProperty("currentIndex", currentIndex); return; } qDebug() << "反向遍历窗口" << __FUNCTION__ << __LINE__ << isOpen; m_isBackTab = true; // 可旋转的机器,多任务视图打开的时候,禁用旋转 if(m_isLoadTabletModeQML && getRotationModeStatus()) { setRotationModeStatus(!m_isAutoRotateBeforeShowMultiTask); } if (m_appWindowListModel->rowCount() == 0) { return; } showTabView(); isOpen = true; } void MultitaskViewManagerByWlcom::close() { if (!isOpen) { return; } //可旋转的机器,多任务视图打开前 是打开了旋转的 那么关闭多任务视图的同时 打开旋转 if (m_isLoadTabletModeQML && m_isAutoRotateBeforeShowMultiTask) { setRotationModeStatus(m_isAutoRotateBeforeShowMultiTask); } hideTabView(); hideTaskView(); isOpen = false; QtConcurrent::run([]() { KTrackData *node = kdk_dia_data_init(KEVENTSOURCE_DESKTOP, KEVENT_CUSTOM); kdk_dia_upload_default(node, (char*)"ukui_window_switch_exit_event", (char*)"ukui-window-switch"); kdk_dia_data_free(node); }); } bool MultitaskViewManagerByWlcom::getRotationModeStatus() { QDBusMessage message = QDBusMessage::createMethodCall("com.kylin.statusmanager.interface", "/", "com.kylin.statusmanager.interface", "get_auto_rotation"); QDBusMessage response = QDBusConnection::sessionBus().call(message); if (response.type() == QDBusMessage::ReplyMessage) { m_isAutoRotateBeforeShowMultiTask = response.arguments().takeFirst().toBool(); } else { qDebug() << "get Rotation mode failed" << response.type(); } return m_isAutoRotateBeforeShowMultiTask; } void MultitaskViewManagerByWlcom::setRotationModeStatus(bool rotationModeStatus) { QDBusInterface iface("com.kylin.statusmanager.interface", "/", "com.kylin.statusmanager.interface"); if (!iface.isValid()) { qDebug() << QDBusConnection::sessionBus().lastError().message(); } QDBusReply reply = iface.call("set_auto_rotation",rotationModeStatus,"",""); if (reply.isValid()) { qDebug() << "set Rotation mode success"; return; } qDebug() << "set Rotation mode failed" << reply.error(); } void MultitaskViewManagerByWlcom::initGuiLayouDirection() { QString systemLang = QLocale::system().name(); if (systemLang == "ug_CN" || systemLang == "ky_KG" || systemLang == "kk_KZ") { m_isLayoutLeftToRight = false; } else { m_isLayoutLeftToRight = true; } } QRect MultitaskViewManagerByWlcom::currentScreenRect() { return UkuiQuick::WindowProxy::currentScreen()->geometry(); } bool MultitaskViewManagerByWlcom::isBackTab() { return m_isBackTab; } bool MultitaskViewManagerByWlcom::altTabVisible() { return m_tabView->isVisible(); } bool MultitaskViewManagerByWlcom::winTabVisible() { return m_taskView->isVisible(); } void MultitaskViewManagerByWlcom::updateDesktopBackground() { QString filePath = DesktopBackground::getBackgroundFile(); if (filePath.isEmpty()) { return; } auto loadImageFinishedCallback = [](const QImage &image) { DesktopBackground::setNonBlurBackground(image); DesktopBackground::setBlurBackground(image, 0.7); }; BackgroundImageHandler::loadBackgroundImageAsync(filePath, DesktopBackground::getSystemScalingFactor(), DesktopBackground::getBackgroundFillStyle(), this, loadImageFinishedCallback); } void MultitaskViewManagerByWlcom::setShowingDesktop(bool showing) { Q_UNUSED(showing) UkuiQuick::WindowManager::setShowingDesktop(true); } void MultitaskViewManagerByWlcom::initModel() { qDebug() << "创建model数据" << __FUNCTION__; m_desktopListModel.reset(new DesktopListModel()); m_appWindowListModel.reset(new AppWindowListModel()); } void MultitaskViewManagerByWlcom::initializeProjectType() { if ( getProjectCodeName() == QStringLiteral("V10SP1-edu") || getProjectSubName() == QStringLiteral("mavis") || getProductFeatures() == QString::number(2)) { m_projectType = MultitaskViewManagerByWlcom::TABLET; } else if (getProjectCodeName() == QStringLiteral("V10SP1") && getProductFeatures() == '\u0000') { // '\u0000' 空格的ASCII码 m_projectType = MultitaskViewManagerByWlcom::MASTER; m_isViewVerticalLayout = false; } else { m_projectType = MultitaskViewManagerByWlcom::TWOINONE; m_isViewVerticalLayout = true; } } void MultitaskViewManagerByWlcom::setQmlUrl() { if (m_projectType == MultitaskViewManagerByWlcom::TABLET || (m_projectType == MultitaskViewManagerByWlcom::TWOINONE && WindowManagerInterface::getInstance()->isTabletMode())) { m_qmlUrl = QUrl("qrc:/qml/TabletViewMain.qml"); m_isLoadTabletModeQML = true; } else if (m_projectType == MultitaskViewManagerByWlcom::MASTER || (m_projectType == MultitaskViewManagerByWlcom::TWOINONE && !WindowManagerInterface::getInstance()->isTabletMode())) { m_qmlUrl = QUrl("qrc:/qml/MultitaskView.qml"); m_isLoadTabletModeQML = false; } } void MultitaskViewManagerByWlcom::registerQmlTypes() { qmlRegisterType("org.kylin.thumbnail", 1, 0, "ThumbnailItem"); qmlRegisterType("org.kylin.background", 3, 0, "DesktopBackground"); qmlRegisterType("IconTheme", 1, 0, "IconTheme"); qmlRegisterType("AppWindowFilterModel", 1, 0, "AppWindowFilterModel"); qmlRegisterType("DesktopListModel", 1, 0, "DesktopListModel"); qRegisterMetaType >("QList"); qmlRegisterUncreatableType("org.ukui.positioner", 1, 0, "UkuiPositioner", "UkuiPositioner is an attached property"); qmlRegisterUncreatableType("org.ukui.positioner", 1, 0, "UkuiBasePositioner", "UkuiBasePositioner is an abstract type that is only available as an attached property."); qmlRegisterType("org.ukui.positioner", 1, 0, "UkuiFlow"); } void MultitaskViewManagerByWlcom::registerShortcut() { auto* action = new QAction(this); action->setObjectName("ShowMultitaskView"); action->setText("Show Multitask View"); QKeySequence keySeq(Qt::META | Qt::Key_Tab); KGlobalAccel::self()->setDefaultShortcut(action, QList() << keySeq); KGlobalAccel::self()->setShortcut(action, QList() << keySeq); connect(action, &QAction::triggered, this, &MultitaskViewManagerByWlcom::open); auto* tabaction = new QAction(this); tabaction->setObjectName("ShowTabbox"); tabaction->setText("Show Tabbox"); QKeySequence tabKeySeq(Qt::ALT | Qt::Key_Tab); KGlobalAccel::self()->setDefaultShortcut(tabaction, QList() << tabKeySeq); KGlobalAccel::self()->setShortcut(tabaction, QList() << tabKeySeq); connect(tabaction, &QAction::triggered, this, &MultitaskViewManagerByWlcom::openTab); auto* backtabaction = new QAction(this); backtabaction->setObjectName("ShowBackTabbox"); backtabaction->setText("Show Back Tabbox"); QKeySequence backtabKeySeq(Qt::ALT | Qt::SHIFT | Qt::Key_Backtab); KGlobalAccel::self()->setDefaultShortcut(backtabaction, QList() << backtabKeySeq); KGlobalAccel::self()->setShortcut(backtabaction, QList() << backtabKeySeq); connect(backtabaction, &QAction::triggered, this, &MultitaskViewManagerByWlcom::openBackTab); } void MultitaskViewManagerByWlcom::initDBusService() { m_dbusService.reset(new DBusService(this)); } void MultitaskViewManagerByWlcom::installTranslator() { m_translator = new QTranslator(qApp); m_translator->load(QLocale::system(), QLatin1String("ukui-window-switch"), QLatin1String("_"), TRANSLATION_DIR); QApplication::installTranslator(m_translator); } void MultitaskViewManagerByWlcom::initView() { qDebug() << " 初始化多任务视图 " << __FUNCTION__; //init alt-tab view m_tabView.reset(new QQuickView()); m_tabView->setFlags(Qt::FramelessWindowHint); m_tabView->setColor(Qt::transparent); m_tabWindowProxy = new UkuiQuick::WindowProxy(m_tabView.get()); m_tabWindowProxy->setWindowType(UkuiQuick::WindowType::Type::Switcher); m_tabWindowProxy->setWindowStates(UkuiQuick::WindowState::Focusable | UkuiQuick::WindowState::Activatable, true); qDebug() << "[DEBUG]: multitask view uses " << m_tabView->sceneGraphBackend(); if (m_tabView->rendererInterface()->graphicsApi() < 2) { m_isOpenGLBackend = false; WindowManagerInterface::getInstance()->setIsOpenGLBackend(m_isOpenGLBackend); } // 通过 QQmlContext::setContextProperty() 注册 C++ 的对象实例到 QML 中 m_tabView->rootContext()->setContextProperty("multitaskViewManager", this); m_tabView->rootContext()->setContextProperty("multitaskViewModel", WindowManagerInterface::getInstance()); m_tabView->rootContext()->setContextProperty("appWindowListModel", m_appWindowListModel.get()); m_tabView->rootContext()->setContextProperty("devicePixelRatio", qApp->primaryScreen()->logicalDotsPerInch() / 96.0); m_tabView->setSource(m_tabQmlUrl); m_tabView->setResizeMode(QQuickView::ResizeMode::SizeViewToRootObject); connect(m_tabView.get(), &QQuickView::heightChanged, this, &MultitaskViewManagerByWlcom::updateAltTabView); updateAltTabView(); //避免首次打开卡顿 //init win-tab view m_taskView.reset(new QQuickView()); m_taskView->setFlags(Qt::FramelessWindowHint); m_taskView->setColor(Qt::transparent); m_taskWindowProxy = new UkuiQuick::WindowProxy(m_taskView.get()); m_taskWindowProxy->setWindowType(UkuiQuick::WindowType::Type::Switcher); m_taskWindowProxy->setWindowStates(UkuiQuick::WindowState::Focusable | UkuiQuick::WindowState::Activatable, true); m_taskView->rootContext()->setContextProperty("multitaskViewManager", this); m_taskView->rootContext()->setContextProperty("multitaskViewModel", WindowManagerInterface::getInstance()); m_taskView->rootContext()->setContextProperty("appWindowListModel", m_appWindowListModel.get()); m_taskView->rootContext()->setContextProperty("devicePixelRatio", qApp->primaryScreen()->logicalDotsPerInch() / 96.0); m_taskView->rootContext()->setContextProperty("desktopListModel", m_desktopListModel.get()); setQmlUrl(); m_taskView->setSource(m_qmlUrl); m_taskView->setResizeMode(QQuickView::ResizeMode::SizeRootObjectToView); connect(m_taskView.get(), &QQuickView::activeFocusItemChanged, m_taskView.get(), [this] { if (!m_taskView || m_taskView->activeFocusItem()) { return; } close(); }, Qt::ConnectionType::UniqueConnection); } void MultitaskViewManagerByWlcom::initEffect() { const QByteArray id(CONTROL_CENTER_SETTING); if (QGSettings::isSchemaInstalled(id)) { auto settings = new QGSettings(id, QByteArray(), this); QStringList keys = settings->keys(); if (keys.contains(CONTROL_CENTER_EFFECT_KEY)) { m_isEffect = settings->get(CONTROL_CENTER_EFFECT_KEY).toBool(); } QObject::connect(settings, &QGSettings::changed, this, [=](const QString &key) { if (key == CONTROL_CENTER_EFFECT_KEY) { m_isEffect = settings->get(key).toBool(); } }); } } void MultitaskViewManagerByWlcom::destroyView() { if (m_tabView != nullptr && m_tabView->isVisible()) { m_tabView->hide(); emit altTabVisibleChanged(); } if (m_taskView != nullptr && m_taskView->isVisible()) { m_taskView->hide(); emit winTabVisibleChanged(); } // 1. 由于可以在QML中通过JS调用到close函数, // 因此,不能直接销毁 m_view 对象;必须延迟 // 销毁该对象 // 2. m_model 对象可以立刻销毁。但是,为了对称 // 和简化逻辑,需要保证 m_view 对象和 m_model 对象的 // 互相依赖的关系。因此,同时延迟销毁 m_model 对象。 // 3. MultitaskViewManagerByWlcom的析构函数需要确保 // m_view 对象和 m_model 对象完成销毁。为了简化逻辑, // MultitaskViewManagerByWlcom的析构函数选择直接调用 // destroyView函数,即采用了延迟销毁的做法。 m_tabView.release()->deleteLater(); m_taskView.release()->deleteLater(); m_desktopListModel.release()->deleteLater(); m_appWindowListModel.release()->deleteLater(); } void MultitaskViewManagerByWlcom::showTabView() { if (m_taskView == nullptr || m_taskWindowProxy == nullptr) { qWarning() << "ukui-window-switch view is null, open failed!"; return; } //显示alt-tab界面 updateAltTabView(); m_tabView->show(); emit altTabVisibleChanged(); } void MultitaskViewManagerByWlcom::hideTabView() { if (m_tabView == nullptr) { return; } if (m_tabView->isVisible()) { m_tabView->hide(); emit altTabVisibleChanged(); } } void MultitaskViewManagerByWlcom::showTaskView() { if (m_taskView == nullptr || m_taskWindowProxy == nullptr) { qWarning() << "ukui-window-switch view is null, open failed!"; return; } if (m_isLoadTabletModeQML) { qDebug() << "加载的qml为 " << m_qmlUrl; m_taskView->setSource(m_qmlUrl); } // 默认情况视图会随着QML中的根项调整大小,可以通过 setResizeMode(QQuickView::ResizeMode) 修改默认行为 // 但是多任务视图的 rootObject 是 Repeater,且没有设置大小,所以必须通过 setGeometry 设置视图大小。 // TODO: Repeater 继承了 Item 的 anchor 属性,Repeater 是否可以设置大小? // 必须在加载了QML之后才能设置 m_view 对象的大小,否则视图大小仍为 0x0 if (m_taskView->resizeMode() != QQuickView::ResizeMode::SizeRootObjectToView) { m_taskView->setResizeMode(QQuickView::ResizeMode::SizeRootObjectToView); } QRect bounding; for (int i= 0; i < QGuiApplication::screens().size(); i++) { bounding = bounding.united(QGuiApplication::screens().at(i)->geometry()); } m_taskWindowProxy->setGeometry(bounding); m_taskView->show(); emit winTabVisibleChanged(); emit desktopDataUpdated(); emit taskViewShowed(); } void MultitaskViewManagerByWlcom::hideTaskView() { if (m_taskView == nullptr) { return; } if (m_taskView->isVisible()) { m_taskView->hide(); emit winTabVisibleChanged(); } } void MultitaskViewManagerByWlcom::updateAltTabView() { if (m_tabView == nullptr) { return; } QRect bounding = UkuiQuick::WindowProxy::currentScreen()->geometry(); if (bounding.width() != m_tabView->width()) { // 修复主副屏尺寸不同,alt-tab界面宽度不更新问题 emit currentScreenRectChanged(); } QPainterPath path; qreal yOffset = m_tabView->rootObject()->property("yOffset").toReal(); path.addRect(0, yOffset, m_tabView->width(), m_tabView->height() - (yOffset * 2)); m_tabWindowProxy->setBlurRegion(m_tabView.get(), true, QRegion(path.toFillPolygon().toPolygon())); //毛玻璃 m_tabWindowProxy->setPosition(QPoint(bounding.x(),bounding.y() + bounding.height() * 0.5 - m_tabView->height() * 0.5)); } void MultitaskViewManagerByWlcom::onTabletModeChanged() { close(); setQmlUrl(); } void MultitaskViewManagerByWlcom::setShouldShowTabBorder(bool isShow) { if (m_isShowTabBorder == isShow) { return; } m_isShowTabBorder = isShow; emit shouldShowTabBorderChanged(); } void MultitaskViewManagerByWlcom::connectSignals() { qDebug() << "创建信号" << __FUNCTION__; //connect(WindowManagerInterface::getInstance(), &WindowManagerInterface::appWindowCreated, this, &MultitaskViewManagerByWlcom::close); connect(WindowManagerInterface::getInstance(), &WindowManagerInterface::screenCountChanged, this, &MultitaskViewManagerByWlcom::close); connect(WindowManagerInterface::getInstance(), &WindowManagerInterface::screenSizeChanged, this, &MultitaskViewManagerByWlcom::close); connect(WindowManagerInterface::getInstance(), &WindowManagerInterface::tabletModeChanged, this, &MultitaskViewManagerByWlcom::onTabletModeChanged); connect(qApp->primaryScreen(), &QScreen::geometryChanged, this, &MultitaskViewManagerByWlcom::currentScreenRectChanged); } QString MultitaskViewManagerByWlcom::getProjectCodeName() { return QString(kdk_system_get_projectName()); } QString MultitaskViewManagerByWlcom::getProjectSubName() { return QString(kdk_system_get_projectSubName()); } QString MultitaskViewManagerByWlcom::getProductFeatures() { return QString::number(kdk_system_get_productFeatures()); } ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/multitaskviewmanagerbywlcom.h000066400000000000000000000115561522363675600330430ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef MULTITASKVIEWMANAGERBYWLCOM_H #define MULTITASKVIEWMANAGERBYWLCOM_H #include #include //ukui-quick #include #include "dbusservice.h" #include "../desktoplistmodel.h" #include "../appwindowlistmodel.h" class QTranslator; class MultitaskViewManagerByWlcom : public QObject { Q_OBJECT Q_PROPERTY(QRect currentScreenRect READ currentScreenRect NOTIFY currentScreenRectChanged) Q_PROPERTY(bool shouldShowTabBorder READ shouldShowTabBorder WRITE setShouldShowTabBorder NOTIFY shouldShowTabBorderChanged) Q_PROPERTY(bool isBackTab READ isBackTab) Q_PROPERTY(bool altTabVisible READ altTabVisible NOTIFY altTabVisibleChanged) Q_PROPERTY(bool winTabVisible READ winTabVisible NOTIFY winTabVisibleChanged) public: MultitaskViewManagerByWlcom(); ~MultitaskViewManagerByWlcom(); enum ProjectType { TABLET, MASTER, TWOINONE, }; Q_INVOKABLE void open(); Q_INVOKABLE void close(); Q_INVOKABLE void openTab(); Q_INVOKABLE void openBackTab(); Q_INVOKABLE void setShowingDesktop(bool showing); Q_INVOKABLE bool isMultitaskViewVerticalLayout() const { return m_isViewVerticalLayout; } Q_INVOKABLE bool shouldShowTabBorder() const { return m_isShowTabBorder; } Q_INVOKABLE void setShouldShowTabBorder(bool isShow); Q_INVOKABLE void activeAreaChangeDataCollect(const QString &areaName); Q_INVOKABLE bool isWlcom() const {return true;}; Q_INVOKABLE bool isLayoutLeftToRight() { return m_isLayoutLeftToRight; }; Q_INVOKABLE bool isAltKeyPressed(); Q_INVOKABLE void keyNavigationDataCollect(const int &keyValue); QRect currentScreenRect(); bool isBackTab(); bool altTabVisible(); bool winTabVisible(); static bool m_isOpenGLBackend; static bool isOpen; static bool m_isEffect; private: void initModel(); void initializeProjectType(); void setQmlUrl(); void registerQmlTypes(); void registerShortcut(); void initDBusService(); void installTranslator(); void initView(); void initEffect(); void destroyView(); void connectSignals(); bool isCursorNavigationKey(const int &key) const; QString getProjectCodeName(); QString getProjectSubName(); QString getProductFeatures(); //! //! \brief getRotationModeStatus 获取当前旋转模式是否打开 //! bool getRotationModeStatus(); ///! //! \brief setRotationModeStatus //! void setRotationModeStatus(bool openRotationMode); void initGuiLayouDirection(); // 窗口选择界面 void showTabView(); void hideTabView(); // 多任务视图界面 void showTaskView(); void hideTaskView(); private: std::unique_ptr m_tabView = nullptr; std::unique_ptr m_taskView = nullptr; std::unique_ptr m_dbusService = nullptr; std::unique_ptr m_desktopListModel = nullptr; std::unique_ptr m_appWindowListModel = nullptr; ProjectType m_projectType = MultitaskViewManagerByWlcom::MASTER; QUrl m_qmlUrl = QUrl("qrc:/qml/MultitaskView.qml"); QUrl m_tabQmlUrl = QUrl("qrc:/qml/Tabbox.qml"); // 记录旋转模式是否打开 bool m_isAutoRotateBeforeShowMultiTask = false; // 记录是否加载平板模式的qml bool m_isLoadTabletModeQML = false; // 记录多任务视图整体布局方向是否为垂直方向 bool m_isViewVerticalLayout = false; // 记录走焦边框是否显示 bool m_isShowTabBorder = false; QTranslator *m_translator = nullptr; bool m_isLayoutLeftToRight = true; UkuiQuick::WindowProxy *m_tabWindowProxy = nullptr; UkuiQuick::WindowProxy *m_taskWindowProxy = nullptr; bool m_isBackTab = false; signals: void showedViewChanged(); void currentScreenRectChanged(); void shouldShowTabBorderChanged(); void desktopDataUpdated(); void taskViewShowed(); void altTabVisibleChanged(); void winTabVisibleChanged(); private Q_SLOTS: void updateDesktopBackground(); void updateAltTabView(); void onTabletModeChanged(); }; #endif // MULTITASKVIEWMANAGERBYWLCOM_H multitaskviewmodelbywlcomhandler.cpp000066400000000000000000000437541522363675600343500ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "multitaskviewmodelbywlcomhandler.h" #include #include #include #include #include #include #include #include #include #include "multitaskviewmanagerbywlcom.h" using namespace std; static UkuiSearch::ApplicationInfo *applicationInfo = nullptr; static std::once_flag flag; UkuiSearch::ApplicationInfo *MultitaskViewModelByWlcomHandler::getApplicationInfo() { std::call_once(flag, [ & ] { applicationInfo = new UkuiSearch::ApplicationInfo(); }); return applicationInfo; } QString MultitaskViewModelByWlcomHandler::desktopFileFromPid(uint pid) { QString desktopFile; getApplicationInfo()->tranPidToDesktopFp(pid, desktopFile); return desktopFile; } MultitaskViewModelByWlcomHandler::MultitaskViewModelByWlcomHandler(QObject *parent) : MultitaskViewAbstractModelHandler{} { createContext(); m_context->start(); connectSignals(); getApplicationInfo(); } MultitaskViewModelByWlcomHandler::~MultitaskViewModelByWlcomHandler() { delete m_context; } void MultitaskViewModelByWlcomHandler::createContext() { struct wl_display *display = NULL; QPlatformNativeInterface *native = QGuiApplication::platformNativeInterface(); if (!native) { return; } display = reinterpret_cast( native->nativeResourceForIntegration(QByteArrayLiteral("wl_display"))); if (!display) { qWarning("Failed to get Wayland display."); return; } m_context = new Context(nullptr, Context::Capability::Output | Context::Capability::Toplevel | Context::Capability::Workspace); connect(m_context, &Context::workespaceAdded, this, &MultitaskViewModelByWlcomHandler::onWorkSpaceAdded); connect(m_context, &Context::toplevelAdded, this, &MultitaskViewModelByWlcomHandler::onWindowAdded); connect(m_context, &Context::outputAdded, this, &MultitaskViewModelByWlcomHandler::onOutputAdded); } Toplevel *MultitaskViewModelByWlcomHandler::getToplevel(QString windowId) { Toplevel *toplevel = NULL; const auto wnds = m_allWindowList; for (auto const wnd: wnds) { if ((QString)wnd->uuid() == windowId) { toplevel = wnd; } } return toplevel; } Window MultitaskViewModelByWlcomHandler::windowFromToplevel(Toplevel *toplevel) { if (toplevel == nullptr) { return Window(); } Window window(toplevel->uuid().toInt(), toplevel->uuid(), toplevel->title().isEmpty() ? toplevel->name() : toplevel->title(), toplevel->point().x(), toplevel->point().y(), toplevel->size().width(), toplevel->size().height(), toplevel->isMinimized()); QList list; int desktopId = 1; for (int i = 0; i < m_workspaceList.size(); ++i) { if (toplevel->workspaces().contains((QString)m_workspaceList[i]->uuid())) { desktopId = i + 1; list.append(desktopId); } } int screenId = 0; QRect wndrect(toplevel->point().x(), toplevel->point().y(), toplevel->size().width(), toplevel->size().height()); for (int i = 0; i < QGuiApplication::screens().size(); i++) { if (QGuiApplication::screens().at(i)->geometry().contains(wndrect.center())) { screenId = i; } } window.setDesktopsId(list); window.setScreenId(screenId); window.setIcon(QVariant::fromValue(toplevel->iconName())); return window; } void MultitaskViewModelByWlcomHandler::removeAppWindow(QString windowId) { Toplevel *toplevel = getToplevel(windowId); if (toplevel == nullptr){ return; } toplevel->close(); } void MultitaskViewModelByWlcomHandler::moveAppWindowToDesktop(QString windowId, int srcDesktopInex, int destDesktopInex) { if (destDesktopInex -1 >= m_workspaceList.size()){ return; } Toplevel *toplevel = getToplevel(windowId); toplevel->moveToWorkspace(m_workspaceList[destDesktopInex-1]->uuid()); } void MultitaskViewModelByWlcomHandler::activateAppWindow(QString windowId) { getToplevel(windowId)->setActivate(); } QVariant MultitaskViewModelByWlcomHandler::getWindowIcon(QString windowId) { Toplevel *toplevel = getToplevel(windowId); if (!toplevel){ return ""; } QIcon themeIcon; themeIcon = QIcon::fromTheme(toplevel->icon(), themeIcon); if (!themeIcon.isNull()) { return themeIcon; } return toplevel->iconName(); } int MultitaskViewModelByWlcomHandler::getNumberOfDesktops() { return m_workspaceList.size(); } void MultitaskViewModelByWlcomHandler::removeDesktop(int desktopIndex) { m_workspaceList[desktopIndex-1]->remove(); } void MultitaskViewModelByWlcomHandler::moveDesktop(int srcDesktopIndex, int destDesktopIndex) { m_workspaceList[srcDesktopIndex-1]->move(destDesktopIndex - 1); m_workspaceList.move(srcDesktopIndex - 1, destDesktopIndex - 1); emit desktopMoved(srcDesktopIndex, destDesktopIndex); } void MultitaskViewModelByWlcomHandler::appendDesktop() { int desktopCount = m_workspaceList.size(); m_context->addWorkspace(desktopCount); QEventLoop loop; connect(this, &MultitaskViewModelByWlcomHandler::workspaceHasCreated, &loop, &QEventLoop::quit); loop.exec(); } int MultitaskViewModelByWlcomHandler::getCurrentDesktop() { for (int i = 0; i < m_workspaceList.size(); i++) { if (m_workspaceList[i]->isActivated()) { return i+1; } } return 1; } bool MultitaskViewModelByWlcomHandler::isCurrentDesktopShowingDesktop() { //wlcom 内部已实现,不需要获取该状态 return false; } void MultitaskViewModelByWlcomHandler::setCurrentDesktop(int desktopIndex) { m_workspaceList[desktopIndex-1]->setActivate(); } QRect MultitaskViewModelByWlcomHandler::getFullScreenGeometry(int desktopIndex, int screenIndex) { return QGuiApplication::screens().at(screenIndex)->geometry(); } bool MultitaskViewModelByWlcomHandler::hasModalChildWindow(QString windowId) { Toplevel *toplevel = getToplevel(windowId); if (toplevel){ return toplevel->hasChildren(); } return false; } bool MultitaskViewModelByWlcomHandler::isExtensionMode() { QRect bounding; for (int i = 0; i < QGuiApplication::screens().size(); i++) { bounding = bounding.united(QGuiApplication::screens().at(i)->geometry()); } for (int i = 0; i < QGuiApplication::screens().size(); i++) { if (bounding == QGuiApplication::screens().at(i)->geometry()) { return false; }; } return true; } int MultitaskViewModelByWlcomHandler::logicalScreenCount() { const auto screenCount = QGuiApplication::screens().size(); if (screenCount == 1 || !isExtensionMode()) { return 1; } return screenCount; } QList MultitaskViewModelByWlcomHandler::createWindowList(int desktopIndex, int screenIndex) { QList windowList; const auto wnds = m_allWindowList; for (auto const wnd: wnds) { if (!shouldAcceptWindow(wnd)) { continue; } bool isOnDesktop = false; for (int i = 0; i < wnd->workspaces().size(); i++) { if (wnd->workspaces()[i] == (QString)m_workspaceList[desktopIndex - 1]->uuid()){ isOnDesktop = true; break; } } if (!isOnDesktop){ continue; } QRect wndrect(wnd->point().x(), wnd->point().y(), wnd->size().width(), wnd->size().height()); if (!(QGuiApplication::screens().at(screenIndex)->geometry().contains(wndrect.center()))) { continue; } QString id =wnd->uuid(); QString title = wnd->title(); if (title.isEmpty()) { title = wnd->name(); } Window window(id.toInt(), wnd->uuid(), title, wnd->point().x(), wnd->point().y(), wnd->size().width(), wnd->size().height(), wnd->isMinimized()); QList list; int desktopId = 1; for (int i = 0; i < m_workspaceList.size(); ++i) { if (wnd->workspaces().contains((QString)m_workspaceList[i]->uuid())) { desktopId = i + 1; list.append(desktopId); } } window.setDesktopsId(list); window.setScreenId(screenIndex); window.setIcon(QVariant::fromValue(wnd->iconName())); windowList.append(window); } return windowList; } bool MultitaskViewModelByWlcomHandler::shouldAcceptWindow(Toplevel *toplevel) { return !(toplevel->capabilities() & Toplevel::Capability::Switcher); } QString MultitaskViewModelByWlcomHandler::getDesktopUuid(int desktopIndex) { return m_workspaceList[desktopIndex - 1]->uuid(); } QString MultitaskViewModelByWlcomHandler::getOutputUuid(int outputIndex) { if (m_outputList.size() == 1) { return m_outputList[0]->uuid(); } QString outputName = ""; if (QGuiApplication::screens().size() > outputIndex) { outputName = QGuiApplication::screens().at(outputIndex)->name(); } for (int i= 0; i < m_outputList.size(); i++) { if (m_outputList[i]->name() == outputName) { return m_outputList[i]->uuid(); } } qWarning() << "[Multitask]: getOutputUuid falied, invalid outputIndex" << outputIndex; return QString(); } void MultitaskViewModelByWlcomHandler::setDesktopName(const int desktopIndex, const QString name) { if (m_workspaceList.size() < desktopIndex) { return; } m_workspaceList[desktopIndex - 1]->setName(name); } void MultitaskViewModelByWlcomHandler::onWindowAdded(Toplevel *toplevel) { if (!shouldAcceptWindow(toplevel)) { //如果非独立子窗口的父窗口显示在任务视图, //激活非独立子窗口时,需要调整父窗口显示顺序,因此需要监听窗口状态变化 if (toplevel->parent() != nullptr && shouldAcceptWindow(toplevel->parent())) { connect(toplevel, &Toplevel::stateUpdated, this, &MultitaskViewModelByWlcomHandler::onWindowUpdate); } return; } m_allWindowList.push_back(toplevel); connect(toplevel, &Toplevel::stateUpdated, this, &MultitaskViewModelByWlcomHandler::onWindowUpdate); connect(toplevel, &Toplevel::deleted, this, &MultitaskViewModelByWlcomHandler::onWindowDeleted); if (toplevel->icon() == "fallback" || toplevel->title().isEmpty()) { // wlcom未找到应用图标,则通过ukui-search接口查找desktop文件,进而获取应用图标 QString desktopFile; getApplicationInfo()->desktopFilePathFromName(toplevel->appId(), desktopFile); if (desktopFile.isEmpty()) { desktopFile = desktopFileFromPid(toplevel->pid()); } toplevel->setDesktopFile(desktopFile); } emit appWindowAdd(windowFromToplevel(toplevel)); } void MultitaskViewModelByWlcomHandler::onOutputAdded(Output *output) { m_outputList.push_back(output); connect(output, &Output::deleted, this, &MultitaskViewModelByWlcomHandler::onOutputDeleted); } void MultitaskViewModelByWlcomHandler::onOutputDeleted() { Output *output = qobject_cast(sender()); for (int i = 0; i < m_outputList.size(); ++i) { if (output->uuid() == (QString)m_outputList[i]->uuid()) { m_outputList.removeAt(i); break; } } } void MultitaskViewModelByWlcomHandler::onWindowDeleted() { Toplevel *toplevel = qobject_cast(sender()); for (int i = 0; i < m_allWindowList.size(); i++){ if (m_allWindowList[i]->uuid() == toplevel->uuid()){ m_allWindowList.removeAt(i); break; } } QString id = toplevel->uuid(); qDebug()<<"toplevel"<parent() != nullptr && shouldAcceptWindow(toplevel->parent())) { int index = m_allWindowList.indexOf(toplevel->parent()); if (index != -1) { m_allWindowList.move(index, m_allWindowList.size() - 1); emit appWindowActivated(); } } return; } // KWin在发送windowActivated信号时 // window对象是有可能为空的。对于多任务 // 视图来说,只关心真正有窗口被激活的清空。 // 因此,如果window对象为空,则不转发 // 该信号 if (toplevel->appId() == nullptr) { return; } int index = m_allWindowList.indexOf(toplevel); if (index != -1) { m_allWindowList.move(index, m_allWindowList.size() - 1); emit appWindowActivated(); } } void MultitaskViewModelByWlcomHandler::onWindowUpdate(Toplevel::Masks mask) { Toplevel *toplevel = qobject_cast(sender()); if (mask & (Toplevel::Mask::Activated) && toplevel->isActivated()) { onWindowActivated(toplevel); } if (mask & (Toplevel::Mask::Size | Toplevel::Mask::Title | Toplevel::Mask::Icon)) { emit appWindowUpdated(windowFromToplevel(toplevel)); } if (mask & Toplevel::Mask::Workspace) { QStringList workspaces = toplevel->workspaces(); if (!workspaces.isEmpty()) { for (int i = 0; i uuid() == workspaces.at(0)) { onDesktopPresenceChanged(toplevel,0,i+1); break; } } } } } void MultitaskViewModelByWlcomHandler::onDesktopPresenceChanged(Toplevel *toplevel, int oldDesktopIndex ,int newDesktopIndex) { if (!shouldAcceptWindow(toplevel)) { return; } for (int i = 0; i < m_allWindowList.size(); i++){ if (m_allWindowList[i]->uuid() == toplevel->uuid()){ m_allWindowList[i] = toplevel; break; } } emit appWindowDesktopChanged(toplevel->uuid(), oldDesktopIndex, newDesktopIndex); } void MultitaskViewModelByWlcomHandler::onWorkSpaceAdded(Workspace *workspace) { m_workspaceList.push_back(workspace); connect(workspace, &Workspace::stateUpdated, this, &MultitaskViewModelByWlcomHandler::onCurrentDesktopChanged); connect(workspace, &Workspace::deleted, this, &MultitaskViewModelByWlcomHandler::onWorkSpaceDeleted); emit workspaceHasCreated(); emit desktopAppended(m_workspaceList.size()); } void MultitaskViewModelByWlcomHandler::onWorkSpaceDeleted() { Workspace *workspace = qobject_cast(sender()); for (int i = 0; i < m_workspaceList.size(); i++) { if (workspace->uuid() == (QString)m_workspaceList[i]->uuid()){ m_workspaceList.removeAt(i); emit desktopRemoved(i+1); break; } } } void MultitaskViewModelByWlcomHandler::onCurrentDesktopChanged(Workspace::Masks mask) { Workspace *workspace = qobject_cast(sender()); if (mask & Workspace::Mask::Position) { if (workspace->isActivated()){ for (int i = 0; i < m_workspaceList.size(); i++) { if (workspace->uuid() == m_workspaceList[i]->uuid()){ m_workspaceList[i] = workspace; emit currentDesktopChanged(0,i+1); break; } } } } if (mask & Workspace::Mask::Activated) { if (workspace->isActivated()){ for (int i = 0; i < m_workspaceList.size(); i++) { if (workspace->uuid() == m_workspaceList[i]->uuid()){ m_workspaceList[i] = workspace; emit currentDesktopChanged(0,i+1); break; } } } } } void MultitaskViewModelByWlcomHandler::connectSignals() { // QObject::connect(KWindowSystem::self(), &KWindowSystem::windowAdded, // this, &MultitaskViewModelByWlcomHandler::onWindowAdded); // QObject::connect(KWindowSystem::self(), &KWindowSystem::windowRemoved, // this, &MultitaskViewModelByWlcomHandler::onWindowDeleted); // QObject::connect(KWindowSystem::self(), &KWindowSystem::activeWindowChanged, // this, &MultitaskViewModelByWlcomHandler::onWindowActivated); // QObject::connect(KWindowSystem::self(), static_cast(&KWindowSystem::windowChanged), // this, &MultitaskViewModelByWlcomHandler::onDesktopPresenceChanged); // QObject::connect(KWindowSystem::self(), &KWindowSystem::currentDesktopChanged, // this, &MultitaskViewModelByWlcomHandler::onCurrentDesktopChanged); // QObject::connect(KWindowSystem::self(), SIGNAL(numberOfDesktopsChanged(int)), // this, SIGNAL(desktopNumberChanged())); } ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/multitaskviewmodelbywlcomhandler.h000066400000000000000000000066501522363675600340660ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef MULTITASKVIEWMODELBYWLCOMHANDLER_H #define MULTITASKVIEWMODELBYWLCOMHANDLER_H #include "../multitaskviewabstractmodelhandler.h" #include #include #include #include #include #include #include "context.h" //ukui-search #include class MultitaskViewModelByWlcomHandler : public MultitaskViewAbstractModelHandler { Q_OBJECT public: explicit MultitaskViewModelByWlcomHandler(QObject *parent = nullptr); ~MultitaskViewModelByWlcomHandler(); void removeAppWindow(QString windowId) override; void moveAppWindowToDesktop(QString windowId, int srcDesktopInex, int destDesktopInex) override; void activateAppWindow(QString windowId) override; QVariant getWindowIcon(QString windowId) override; void removeDesktop(int desktopIndex) override; void moveDesktop(int srcDesktopIndex, int destDesktopIndex) override; int getNumberOfDesktops() override; void appendDesktop() override; int getCurrentDesktop() override; bool isCurrentDesktopShowingDesktop() override; void setCurrentDesktop(int desktopIndex) override; QRect getFullScreenGeometry(int desktopIndex, int screenIndex) override; bool hasModalChildWindow(QString windowId) override; bool isExtensionMode() override; int logicalScreenCount() override; QList createWindowList(int desktopIndex, int screenIndex) override; QString getDesktopUuid(int desktopIndex) override; QString getOutputUuid(int outputIndex) override; void setDesktopName(const int desktopIndex, const QString name) override; static UkuiSearch::ApplicationInfo *getApplicationInfo(); static QString desktopFileFromPid(uint pid); private: bool shouldAcceptWindow(Toplevel *toplevel); void createContext(); void connectSignals(); Toplevel *getToplevel(QString windowId); Window windowFromToplevel(Toplevel *toplevel); Context *m_context = nullptr; QList m_allWindowList; QList m_workspaceList; QList m_outputList; signals: void workspaceHasCreated(); private slots: void onWindowAdded(Toplevel *toplevel); void onOutputAdded(Output *output); void onWindowDeleted(); void onWindowActivated(Toplevel *toplevel); void onWindowUpdate(Toplevel::Masks mask); void onWorkSpaceAdded(Workspace *workspace); void onWorkSpaceDeleted(); // void onWorkSpaceActivated(int windowId); void onCurrentDesktopChanged(Workspace::Masks mask); void onDesktopPresenceChanged(Toplevel *toplevel, int oldDesktopIndex ,int newDesktopIndex); void onOutputDeleted(); }; #endif // MULTITASKVIEWMODELBYWLCOMHANDLER_H ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/output.cpp000066400000000000000000000151131522363675600270670ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "context.h" #include class Output::Private { public: Private(Output *output); ~Private(); void setup(kywc_output *output); QString uuid; QString name; QString make; QString model; QString serial; QString description; QSize physical; QList mode_list; Mode cur_mode; QPoint point; QSize size; Output::Capabilities capabilities; int32_t transform; float scale; bool enabled, power, primary; uint32_t brightness, color_temp; kywc_output *k_output; private: Output *o; static void stateHandle(kywc_output *output, uint32_t mask); static void destroyHandle(kywc_output *output); static struct kywc_output_interface output_impl; }; Output::Private::Private(Output *output) : o(output) {} Output::Private::~Private() {} void Output::Private::stateHandle(kywc_output *output, uint32_t mask) { Output *o_output = (Output *)kywc_output_get_user_data(output); Output::Masks masks; if (mask & KYWC_OUTPUT_STATE_ENABLED) { o_output->pri->enabled = output->enabled; masks |= Output::Mask::Enabled; } if (mask & KYWC_OUTPUT_STATE_MODE) { struct kywc_output_mode *mode = output->mode; o_output->pri->cur_mode.size = QSize(mode->width, mode->height); o_output->pri->cur_mode.refresh = mode->refresh; o_output->pri->cur_mode.preferred = mode->preferred; masks |= Output::Mask::Mode; } if (mask & KYWC_OUTPUT_STATE_POSITION) { o_output->pri->point = QPoint(output->x, output->y); masks |= Output::Mask::Position; } if (mask & KYWC_OUTPUT_STATE_TRANSFORM) { o_output->pri->transform = output->transform; masks |= Output::Mask::Transform; } if (mask & KYWC_OUTPUT_STATE_SCALE) { o_output->pri->scale = output->scale; masks |= Output::Mask::Scale; } if (mask & KYWC_OUTPUT_STATE_POWER) { o_output->pri->power = output->power; masks |= Output::Mask::Power; } if (mask & KYWC_OUTPUT_STATE_PRIMARY) { o_output->pri->primary = output->primary; masks |= Output::Mask::Primary; } if (mask & KYWC_OUTPUT_STATE_BRIGHTNESS) { o_output->pri->brightness = output->brightness; masks |= Output::Mask::Brightness; } if (mask & KYWC_OUTPUT_STATE_COLOR_TEMP) { o_output->pri->color_temp = output->color_temp; masks |= Output::Mask::ColorTemp; } emit o_output->stateUpdated(masks); } void Output::Private::destroyHandle(kywc_output *output) { Output *o_output = (Output *)kywc_output_get_user_data(output); emit o_output->deleted(); } struct kywc_output_interface Output::Private::output_impl { stateHandle, destroyHandle, }; void Output::Private::setup(kywc_output *output) { k_output = output; uuid = QString(output->uuid); name = QString(output->name); make = QString(output->make); model = QString(output->model); serial = QString(output->serial); description = QString(output->description); physical = QSize(output->physical_width, output->physical_height); point = QPoint(output->x, output->y); transform = output->transform; scale = output->scale; enabled = output->enabled; power = output->power; primary = output->primary; brightness = output->brightness; color_temp = output->color_temp; if (output->capabilities & KYWC_OUTPUT_CAPABILITY_POWER) capabilities |= Output::Capability::Power; if (output->capabilities & KYWC_OUTPUT_CAPABILITY_BRIGHTNESS) capabilities |= Output::Capability::Brightness; if (output->capabilities & KYWC_OUTPUT_CAPABILITY_COLOR_TEMP) capabilities |= Output::Capability::ColorTemp; struct kywc_output_mode *output_mode, *tmp; wl_list_for_each_safe(output_mode, tmp, &output->modes, link) { Mode mod; mod.size = QSize(output_mode->width, output_mode->height); mod.refresh = output_mode->refresh; mod.preferred = output_mode->preferred; mode_list.append(mod); } struct kywc_output_mode *mode = output->mode; /* mode is null if output is disabled */ if (mode) { cur_mode.size = QSize(mode->width, mode->height); cur_mode.refresh = mode->refresh; cur_mode.preferred = mode->preferred; } else { cur_mode.size = QSize(0, 0); cur_mode.refresh = 0; cur_mode.preferred = false; } kywc_output_set_user_data(output, this->o); kywc_output_set_interface(output, &output_impl); } Output::Output(QObject *parent) : pri(new Private(this)) {} Output::~Output() {} void Output::setup(kywc_output *output) { pri->setup(output); } QString Output::name() const { return pri->name; } QString Output::uuid() const { return pri->uuid; } QString Output::make() const { return pri->make; } QString Output::model() const { return pri->model; } QString Output::serial() const { return pri->serial; } QString Output::description() const { return pri->description; } QSize Output::physicalSize() const { return pri->physical; } Output::Capabilities Output::capabilities() const { return pri->capabilities; } QList Output::modes() const { return pri->mode_list; } Output::Mode Output::curMode() const { return pri->cur_mode; } QPoint Output::point() const { return pri->point; } int Output::transform() const { return pri->transform; } float Output::scale() const { return pri->scale; } bool Output::isEnabled() const { return pri->enabled; } bool Output::isPower() const { return pri->power; } bool Output::isPrimary() const { return pri->primary; } uint32_t Output::brightness() const { return pri->brightness; } uint32_t Output::colorTemp() const { return pri->color_temp; } QSize Output::size() const { return pri->size; } ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/000077500000000000000000000000001522363675600310745ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/CMakeLists.txt000066400000000000000000000010551522363675600336350ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.16) project(qtsingleapplication) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core Gui Widgets Network REQUIRED) include_directories(src) set(SRCS src/qtsingleapplication.h src/qtsingleapplication.cpp src/qtlocalpeer.h src/qtlocalpeer.cpp) add_library(${PROJECT_NAME} STATIC ${SRCS}) target_include_directories(${PROJECT_NAME} PRIVATE src) target_link_libraries(${PROJECT_NAME} PRIVATE Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Gui Qt${QT_VERSION_MAJOR}::Widgets Qt${QT_VERSION_MAJOR}::Network) ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/INSTALL.TXT000066400000000000000000000223741522363675600326130ustar00rootroot00000000000000INSTALLATION INSTRUCTIONS These instructions refer to the package you are installing as some-package.tar.gz or some-package.zip. The .zip file is intended for use on Windows. The directory you choose for the installation will be referred to as your-install-dir. Note to Qt Visual Studio Integration users: In the instructions below, instead of building from command line with nmake, you can use the menu command 'Qt->Open Solution from .pro file' on the .pro files in the example and plugin directories, and then build from within Visual Studio. Unpacking and installation -------------------------- 1. Unpacking the archive (if you have not done so already). On Unix and Mac OS X (in a terminal window): cd your-install-dir gunzip some-package.tar.gz tar xvf some-package.tar This creates the subdirectory some-package containing the files. On Windows: Unpack the .zip archive by right-clicking it in explorer and choosing "Extract All...". If your version of Windows does not have zip support, you can use the infozip tools available from www.info-zip.org. If you are using the infozip tools (in a command prompt window): cd your-install-dir unzip some-package.zip 2. Configuring the package. The configure script is called "configure" on unix/mac and "configure.bat" on Windows. It should be run from a command line after cd'ing to the package directory. You can choose whether you want to use the component by including its source code directly into your project, or build the component as a dynamic shared library (DLL) that is loaded into the application at run-time. The latter may be preferable for technical or licensing (LGPL) reasons. If you want to build a DLL, run the configure script with the argument "-library". Also see the note about usage below. (Components that are Qt plugins, e.g. styles and image formats, are by default built as a plugin DLL.) The configure script will prompt you in some cases for further information. Answer these questions and carefully read the license text before accepting the license conditions. The package cannot be used if you do not accept the license conditions. 3. Building the component and examples (when required). If a DLL is to be built, or if you would like to build the examples, next give the commands qmake make [or nmake if your are using Microsoft Visual C++] The example program(s) can be found in the directory called "examples" or "example". Components that are Qt plugins, e.g. styles and image formats, are ready to be used as soon as they are built, so the rest of this installation instruction can be skipped. 4. Building the Qt Designer plugin (optional). Some of the widget components are provided with plugins for Qt Designer. To build and install the plugin, cd into the some-package/plugin directory and give the commands qmake make [or nmake if your are using Microsoft Visual C++] Restart Qt Designer to make it load the new widget plugin. Note: If you are using the built-in Qt Designer from the Qt Visual Studio Integration, you will need to manually copy the plugin DLL file, i.e. copy %QTDIR%\plugins\designer\some-component.dll to the Qt Visual Studio Integration plugin path, typically: C:\Program Files\Trolltech\Qt VS Integration\plugins Note: If you for some reason are using a Qt Designer that is built in debug mode, you will need to build the plugin in debug mode also. Edit the file plugin.pro in the plugin directory, changing 'release' to 'debug' in the CONFIG line, before running qmake. Solutions components are intended to be used directly from the package directory during development, so there is no 'make install' procedure. Using a component in your project --------------------------------- To use this component in your project, add the following line to the project's .pro file (or do the equivalent in your IDE): include(your-install-dir/some-package/src/some-package.pri) This adds the package's sources and headers to the SOURCES and HEADERS project variables respectively (or, if the component has been configured as a DLL, it adds that library to the LIBS variable), and updates INCLUDEPATH to contain the package's src directory. Additionally, the .pri file may include some dependencies needed by the package. To include a header file from the package in your sources, you can now simply use: #include or alternatively, in pre-Qt 4 style: #include Refer to the documentation to see the classes and headers this components provides. Install documentation (optional) -------------------------------- The HTML documentation for the package's classes is located in the your-install-dir/some-package/doc/html/index.html. You can open this file and read the documentation with any web browser. To install the documentation into Qt Assistant (for Qt version 4.4 and later): 1. In Assistant, open the Edit->Preferences dialog and choose the Documentation tab. Click the Add... button and select the file your-install-dir/some-package/doc/html/some-package.qch For Qt versions prior to 4.4, do instead the following: 1. The directory your-install-dir/some-package/doc/html contains a file called some-package.dcf. Execute the following commands in a shell, command prompt or terminal window: cd your-install-dir/some-package/doc/html/ assistant -addContentFile some-package.dcf The next time you start Qt Assistant, you can access the package's documentation. Removing the documentation from assistant ----------------------------------------- If you have installed the documentation into Qt Assistant, and want to uninstall it, do as follows, for Qt version 4.4 and later: 1. In Assistant, open the Edit->Preferences dialog and choose the Documentation tab. In the list of Registered Documentation, select the item com.nokia.qtsolutions.some-package_version, and click the Remove button. For Qt versions prior to 4.4, do instead the following: 1. The directory your-install-dir/some-package/doc/html contains a file called some-package.dcf. Execute the following commands in a shell, command prompt or terminal window: cd your-install-dir/some-package/doc/html/ assistant -removeContentFile some-package.dcf Using the component as a DLL ---------------------------- 1. Normal components The shared library (DLL) is built and placed in the some-package/lib directory. It is intended to be used directly from there during development. When appropriate, both debug and release versions are built, since the run-time linker will in some cases refuse to load a debug-built DLL into a release-built application or vice versa. The following steps are taken by default to help the dynamic linker to locate the DLL at run-time (during development): Unix: The some-package.pri file will add linker instructions to add the some-package/lib directory to the rpath of the executable. (When distributing, or if your system does not support rpath, you can copy the shared library to another place that is searched by the dynamic linker, e.g. the "lib" directory of your Qt installation.) Mac: The full path to the library is hardcoded into the library itself, from where it is copied into the executable at link time, and ready by the dynamic linker at run-time. (When distributing, you will want to edit these hardcoded paths in the same way as for the Qt DLLs. Refer to the document "Deploying an Application on Mac OS X" in the Qt Reference Documentation.) Windows: the .dll file(s) are copied into the "bin" directory of your Qt installation. The Qt installation will already have set up that directory to be searched by the dynamic linker. 2. Plugins For Qt Solutions plugins (e.g. image formats), both debug and release versions of the plugin are built by default when appropriate, since in some cases the release Qt library will not load a debug plugin, and vice versa. The plugins are automatically copied into the plugins directory of your Qt installation when built, so no further setup is required. Plugins may also be built statically, i.e. as a library that will be linked into your application executable, and so will not need to be redistributed as a separate plugin DLL to end users. Static building is required if Qt itself is built statically. To do it, just add "static" to the CONFIG variable in the plugin/plugin.pro file before building. Refer to the "Static Plugins" section in the chapter "How to Create Qt Plugins" for explanation of how to use a static plugin in your application. The source code of the example program(s) will also typically contain the relevant instructions as comments. Uninstalling ------------ The following command will remove any fils that have been automatically placed outside the package directory itself during installation and building make distclean [or nmake if your are using Microsoft Visual C++] If Qt Assistant documentation or Qt Designer plugins have been installed, they can be uninstalled manually, ref. above. Enjoy! :) - The Qt Solutions Team. ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/README.TXT000066400000000000000000000016411522363675600324340ustar00rootroot00000000000000Qt Solutions Component: Single Application The QtSingleApplication component provides support for applications that can be only started once per user. Version history: 2.0: - Version 1.3 ported to Qt 4. 2.1: - Fix compilation problem on Mac. 2.2: - Really fix the Mac compilation problem. - Mac: fix crash due to wrong object releasing. - Mac: Fix memory leak. 2.3: - Windows: Force creation of internal widget to make it work with Qt 4.2. 2.4: - Fix the system for automatic window raising on message reception. NOTE: minor API change. 2.5: - Mac: Fix isRunning() to work and report correctly. 2.6: - - initialize() is now obsolete, no longer necessary to call it - - Fixed race condition where multiple instances migth be started - - QtSingleCoreApplication variant provided for non-GUI (console) usage - Complete reimplementation. Visible changes: - LGPL release. ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/buildlib/000077500000000000000000000000001522363675600326625ustar00rootroot00000000000000buildlib.pro000066400000000000000000000007211522363675600351130ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/buildlibTEMPLATE=lib CONFIG += qt dll qtsingleapplication-buildlib mac:CONFIG += absolute_library_soname win32|mac:!wince*:!win32-msvc:!macx-xcode:CONFIG += debug_and_release build_all include(../src/qtsingleapplication.pri) TARGET = $$QTSINGLEAPPLICATION_LIBNAME DESTDIR = $$QTSINGLEAPPLICATION_LIBDIR win32 { DLLDESTDIR = $$[QT_INSTALL_BINS] QMAKE_DISTCLEAN += $$[QT_INSTALL_BINS]\\$${QTSINGLEAPPLICATION_LIBNAME}.dll } target.path = $$DESTDIR INSTALLS += target ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/common.pri000066400000000000000000000012471522363675600331040ustar00rootroot00000000000000exists(config.pri):infile(config.pri, SOLUTIONS_LIBRARY, yes): CONFIG += qtsingleapplication-uselib TEMPLATE += fakelib greaterThan(QT_MAJOR_VERSION, 5)|\ if(equals(QT_MAJOR_VERSION, 5):greaterThan(QT_MINOR_VERSION, 4))|\ if(equals(QT_MAJOR_VERSION, 5):equals(QT_MINOR_VERSION, 4):greaterThan(QT_PATCH_VERSION, 1)) { QTSINGLEAPPLICATION_LIBNAME = $$qt5LibraryTarget(QtSolutions_SingleApplication-head) } else { QTSINGLEAPPLICATION_LIBNAME = $$qtLibraryTarget(QtSolutions_SingleApplication-head) } TEMPLATE -= fakelib QTSINGLEAPPLICATION_LIBDIR = $$PWD/lib unix:qtsingleapplication-uselib:!qtsingleapplication-buildlib:QMAKE_RPATHDIR += $$QTSINGLEAPPLICATION_LIBDIR ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/configure000077500000000000000000000012611522363675600330030ustar00rootroot00000000000000#!/bin/sh if [ "x$1" != "x" -a "x$1" != "x-library" ]; then echo "Usage: $0 [-library]" echo echo "-library: Build the component as a dynamic library (DLL). Default is to" echo " include the component source code directly in the application." echo exit 0 fi rm -f config.pri if [ "x$1" = "x-library" ]; then echo "Configuring to build this component as a dynamic library." echo "SOLUTIONS_LIBRARY = yes" > config.pri fi echo echo "This component is now configured." echo echo "To build the component library (if requested) and example(s)," echo "run qmake and your make command." echo echo "To remove or reconfigure, run make distclean." echo ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/configure.bat000066400000000000000000000017621522363675600335530ustar00rootroot00000000000000:: Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). :: SPDX-License-Identifier: BSD-3-Clause @echo off rem rem "Main" rem if not "%1"=="" ( if not "%1"=="-library" ( call :PrintUsage goto EOF ) ) if exist config.pri. del config.pri if "%1"=="-library" ( echo Configuring to build this component as a dynamic library. echo SOLUTIONS_LIBRARY = yes > config.pri ) echo . echo This component is now configured. echo . echo To build the component library (if requested) and example(s), echo run qmake and your make or nmake command. echo . echo To remove or reconfigure, run make (nmake) distclean. echo . goto EOF :PrintUsage echo Usage: configure.bat [-library] echo . echo -library: Build the component as a dynamic library (DLL). Default is to echo include the component source directly in the application. echo A DLL may be preferable for technical or licensing (LGPL) reasons. echo . goto EOF :EOF ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/000077500000000000000000000000001522363675600316415ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/html/000077500000000000000000000000001522363675600326055ustar00rootroot00000000000000classic.css000066400000000000000000000074531522363675600346720ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/htmlBODY,H1,H2,H3,H4,H5,H6,P,CENTER,TD,TH,UL,DL,DIV { font-family: Arial, Geneva, Helvetica, sans-serif; } H1 { text-align: center; font-size: 160%; } H2 { font-size: 120%; } H3 { font-size: 100%; } h3.fn,span.fn { background-color: #eee; border-width: 1px; border-style: solid; border-color: #ddd; font-weight: bold; padding: 6px 0px 6px 10px; margin: 42px 0px 0px 0px; } hr { border: 0; color: #a0a0a0; background-color: #ccc; height: 1px; width: 100%; text-align: left; margin: 34px 0px 34px 0px; } table.valuelist { border-width: 1px 1px 1px 1px; border-style: solid; border-color: #dddddd; border-collapse: collapse; background-color: #f0f0f0; } table.indextable { border-width: 1px 1px 1px 1px; border-style: solid; border-collapse: collapse; background-color: #f0f0f0; border-color:#555; font-size: 100%; } table td.largeindex { border-width: 1px 1px 1px 1px; border-collapse: collapse; background-color: #f0f0f0; border-color:#555; font-size: 120%; } table.valuelist th { border-width: 1px 1px 1px 2px; padding: 4px; border-style: solid; border-color: #666; color:white; background-color:#666; } th.titleheader { border-width: 1px 0px 1px 0px; padding: 2px; border-style: solid; border-color: #666; color:white; background-color:#555; background-image:url('images/gradient.png')}; background-repeat: repeat-x; font-size: 100%; } th.largeheader { border-width: 1px 0px 1px 0px; padding: 4px; border-style: solid; border-color: #444; color:white; background-color:#555555; font-size: 120%; } p { margin-left: 4px; margin-top: 8px; margin-bottom: 8px; } a:link { color: #0046ad; text-decoration: none } a:visited { color: #672967; text-decoration: none } a.obsolete { color: #661100; text-decoration: none } a.compat { color: #661100; text-decoration: none } a.obsolete:visited { color: #995500; text-decoration: none } a.compat:visited { color: #995500; text-decoration: none } body { background: #ffffff; color: black } table.generic, table.annotated { border-width: 1px; border-color:#bbb; border-style:solid; border-collapse:collapse; } table td.memItemLeft { width: 180px; padding: 2px 0px 0px 8px; margin: 4px; border-width: 1px; border-color: #E0E0E0; border-style: none; font-size: 100%; white-space: nowrap } table td.memItemRight { padding: 2px 8px 0px 8px; margin: 4px; border-width: 1px; border-color: #E0E0E0; border-style: none; font-size: 100%; } table tr.odd { background: #f0f0f0; color: black; } table tr.even { background: #e4e4e4; color: black; } table.annotated th { padding: 3px; text-align: left } table.annotated td { padding: 3px; } table tr pre { padding-top: 0px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; border: none; background: none } tr.qt-style { background: #96E066; color: black } body pre { padding: 0.2em; border: #e7e7e7 1px solid; background: #f1f1f1; color: black } table tr.qt-code pre { padding: 0.2em; border: #e7e7e7 1px solid; background: #f1f1f1; color: black } span.preprocessor, span.preprocessor a { color: darkblue; } span.comment { color: darkred; font-style: italic } span.string,span.char { color: darkgreen; } .title { text-align: center } .subtitle { font-size: 0.8em } .small-subtitle { font-size: 0.65em } .qmlitem { padding: 0; } .qmlname { white-space: nowrap; } .qmltype { text-align: center; font-size: 160%; } .qmlproto { background-color: #eee; border-width: 1px; border-style: solid; border-color: #ddd; font-weight: bold; padding: 6px 10px 6px 10px; margin: 42px 0px 0px 0px; } .qmlreadonly { float: right; color: red } .qmldoc { } *.qmlitem p { } images/000077500000000000000000000000001522363675600337735ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/htmlqt-logo.png000066400000000000000000000077531522363675600360770ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/html/imagesPNG  IHDR9C:uIDATxb?bhJnJnJnJnJnJnԡ Є`r'Q( !!Nb_p??F&F312G.yG&ޏ?}eWSSgb( ~™t齸g0sVv`fcdY8E$xdUUex$xd9DDr=#gdd|Uףw9D- 2b8Ͽebddceᔐ╗SWScaB#cfd]-I\ _20110`xzw/).#'˯"ǯ*˫,+')@lY@}fۯͼ 2@d$1H')&#'ç,ϯ*˧,#/%́XgfdOX8Y9s2GC3g@ fFff.3O|v ,l%?fR_|bb`y엉3+ԇ,̌,4 "ͭ32>{E4އ ˯NԦ+Qefdϛ?6:&Ǜ?|"=\n$FFfF /0"`ddf cfbb`dx՛o yAP ,,eebWaá,QܬLL>5Lll10 m00wTVxOÚ bGB8GtUմXplII ׶R/@2 Y{ ]d9#ule+}N6XfJ"խJ13002³ @K"ŭzo?1000@{ lϿ`?ï2"ecgd H.fFfɆ}Ͽߌ"٭윌 y02000Ac<\po/."?;#ߛ!hgddd\<|\300<|?j"-U L9D8E i[ZP?z5fF6? o"b')~?3311g/ ֯cz߿>pvfL~g'""٭Qd'i `Ϳ'?HۅǞy?200 %)h1.7?."ͭ 32yVfFfGyO/:?LL [,?/?^}|:`luX-tN X"_CkǶ>w:7WlSofFcOv{OD7톚)*$@d"7$1CRgɉi[!.f&v_#ɧ{='JXXc`agպ]R\̅?ӧ_ᄏvѦ_2"g|fە(m )\!&&&F{ ba~>qci.O?l-"s܅Ǐ<Ϟn%hm)tN6P߿0H~̌,|ןhmF>1:19_/رcc7k䱞]ۯ咒SaB[?|}kf~?ɍkF/>9*qpQ( @##ïe1| QXn_ #ơp7B]X?F[a'K+ q/̌,,L L 7tDʡz /#300VnC")"/?110qp￿l_GVWNOU_UIPSCؐ?\e``=_R(2r-d?ÿ_?+78$$ +:xBVFn^?cbdd@yĂf```aba㔆L)J sI2Ҥ!#3 > ^y^~o (?+33d:.cfL(H*sJ`Mg222ڥž15,l l"< Single Application
  Home

Single Application

Description

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

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

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

Classes

Examples

Tested platforms

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


Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
qtsingleapplication-example-loader.html000066400000000000000000000167001522363675600423670ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/html Loading Documents
  Home

Loading Documents

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

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

 #include <qtsingleapplication.h>
 #include <QtCore/QFile>
 #include <QtGui/QMainWindow>
 #include <QtGui/QPrinter>
 #include <QtGui/QPainter>
 #include <QtGui/QTextEdit>
 #include <QtGui/QMdiArea>
 #include <QtCore/QTextStream>

 class MainWindow : public QMainWindow
 {
     Q_OBJECT
 public:
     MainWindow();

 public slots:
     void handleMessage(const QString& message);

 signals:
     void needToShow();

 private:
     QMdiArea *workspace;
 };

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

 MainWindow::MainWindow()
 {
     workspace = new QMdiArea(this);

     setCentralWidget(workspace);
 }

The MainWindow constructor creates a minimal user interface.

 void MainWindow::handleMessage(const QString& message)
 {
     enum Action {
         Nothing,
         Open,
         Print
     } action;

     action = Nothing;
     QString filename = message;
     if (message.toLower().startsWith("/print ")) {
         filename = filename.mid(7);
         action = Print;
     } else if (!message.isEmpty()) {
         action = Open;
     }
     if (action == Nothing) {
         emit needToShow();
         return;
     }

     QFile file(filename);
     QString contents;
     if (file.open(QIODevice::ReadOnly))
         contents = file.readAll();
     else
         contents = "[[Error: Could not load file " + filename + "]]";

     QTextEdit *view = new QTextEdit;
     view->setPlainText(contents);

     switch(action) {

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

     case Print:
         {
             QPrinter printer;
             view->print(&printer);
             delete view;
         }
         break;

     case Open:
         {
             workspace->addSubWindow(view);
             view->setWindowTitle(message);
             view->show();
             emit needToShow();
         }
         break;
     default:
         break;
     };
 }

Loading the file will also activate the window.

 #include "main.moc"

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

     if (instance.sendMessage(message))
         return 0;

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

     MainWindow mw;
     mw.handleMessage(message);
     mw.show();

     QObject::connect(&instance, SIGNAL(messageReceived(const QString&)),
                      &mw, SLOT(handleMessage(const QString&)));

     instance.setActivationWindow(&mw, false);
     QObject::connect(&mw, SIGNAL(needToShow()), &instance, SLOT(activateWindow()));

     return instance.exec();
 }

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


Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
qtsingleapplication-example-trivial.html000066400000000000000000000124341522363675600425730ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/html A Trivial Example
  Home

A Trivial Example

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

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

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

 #include <qtsingleapplication.h>
 #include <QtGui/QTextEdit>

 class TextEdit : public QTextEdit
 {
     Q_OBJECT
 public:
     TextEdit(QWidget *parent = 0)
         : QTextEdit(parent)
     {}
 public slots:
     void append(const QString &str)
     {
         QTextEdit::append(str);
     }
 };

 #include "main.moc"

 int main(int argc, char **argv)
 {
     QtSingleApplication instance(argc, argv);

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

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

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

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

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

     instance.setActivationWindow(&logview);

     QObject::connect(&instance, SIGNAL(messageReceived(const QString&)),
                      &logview, SLOT(append(const QString&)));

     return instance.exec();

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

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

Finally the event loop is entered.


Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
qtsingleapplication-members.html000066400000000000000000000737021522363675600411270ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/html List of All Members for QtSingleApplication
  Home

List of All Members for QtSingleApplication

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


Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
qtsingleapplication-obsolete.html000066400000000000000000000037211522363675600413030ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/html Obsolete Members for QtSingleApplication
  Home

Obsolete Members for QtSingleApplication

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

Public Functions

void initialize ( bool dummy = true )   (obsolete)

Member Function Documentation

void QtSingleApplication::initialize ( bool dummy = true )


Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
qtsingleapplication.dcf000066400000000000000000000050711522363675600372610ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/html
QtSingleApplication activateWindow activationWindow id isRunning messageReceived sendMessage setActivationWindow
QtSingleCoreApplication id isRunning messageReceived sendMessage
A non-GUI example
A Trivial Example
Loading Documents
Single Application
qtsingleapplication.html000066400000000000000000000520001522363675600374630ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/html QtSingleApplication Class Reference
  Home

QtSingleApplication Class Reference

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

 #include <QtSingleApplication>

Inherits QApplication.


Public Functions

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

Public Slots

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

Signals

void messageReceived ( const QString & message )

Additional Inherited Members


Detailed Description

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

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

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

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

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

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

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

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

 // Original
 int main(int argc, char **argv)
 {
     QApplication app(argc, argv);

     MyMainWidget mmw;
     mmw.show();
     return app.exec();
 }

 // Single instance
 int main(int argc, char **argv)
 {
     QtSingleApplication app(argc, argv);

     if (app.isRunning())
         return !app.sendMessage(someDataString);

     MyMainWidget mmw;
     app.setActivationWindow(&mmw);
     mmw.show();
     return app.exec();
 }

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

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

See also QtSingleCoreApplication.


Member Function Documentation

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

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

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

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

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

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

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

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

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

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

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

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

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

void QtSingleApplication::activateWindow ()   [slot]

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

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

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

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

QWidget * QtSingleApplication::activationWindow () const

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

See also setActivationWindow().

QString QtSingleApplication::id () const

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

bool QtSingleApplication::isRunning ()

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

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

See also sendMessage().

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

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

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

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

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

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

See also isRunning() and messageReceived().

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

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

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

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


Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
qtsingleapplication.index000066400000000000000000000317141522363675600376370ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/html qtsingleapplication.qhp000066400000000000000000000074111522363675600373150ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/html com.nokia.qtsolutions.qtsingleapplication_head qdoc qt solutions qtsingleapplication qt solutions qtsingleapplication
qtsingleapplication.html index.html qtsingleapplication-example-trivial.html qtsinglecoreapplication.html qtsingleapplication-example-loader.html qtsinglecoreapplication-example-console.html classic.css images/qt-logo.png qtsinglecoreapplication-example-console.html000066400000000000000000000124151522363675600434330ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/html A non-GUI example
  Home

A non-GUI example

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

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

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

2) The class name is QtSingleCoreApplication instead of QtSingleApplication.

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

console.pro:

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

main.cpp:

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

 #include "qtsinglecoreapplication.h"
 #include <QtCore/QDebug>

 void report(const QString& msg)
 {
     qDebug("[%i] %s", (int)QCoreApplication::applicationPid(), qPrintable(msg));
 }

 class MainClass : public QObject
 {
     Q_OBJECT
 public:
     MainClass()
         : QObject()
         {}

 public slots:
     void handleMessage(const QString& message)
         {
             report( "Message received: \"" + message + "\"");
         }
 };

 int main(int argc, char **argv)
 {
     report("Starting up");

     QtSingleCoreApplication app(argc, argv);

     if (app.isRunning()) {
         QString msg(QString("Hi master, I am %1.").arg(QCoreApplication::applicationPid()));
         bool sentok = app.sendMessage(msg, 2000);
         QString rep("Another instance is running, so I will exit.");
         rep += sentok ? " Message sent ok." : " Message sending failed; the other instance may be frozen.";
         report(rep);
         return 0;
     } else {
         report("No other instance is running; so I will.");
         MainClass mainObj;
         QObject::connect(&app, SIGNAL(messageReceived(const QString&)),
                          &mainObj, SLOT(handleMessage(const QString&)));
         return app.exec();
     }
 }

 #include "main.moc"


Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
qtsinglecoreapplication-members.html000066400000000000000000000357771522363675600420120ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/html List of All Members for QtSingleCoreApplication
  Home

List of All Members for QtSingleCoreApplication

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


Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
qtsinglecoreapplication.html000066400000000000000000000235661522363675600403530ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/html QtSingleCoreApplication Class Reference
  Home

QtSingleCoreApplication Class Reference

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

 #include <QtSingleCoreApplication>

Inherits QCoreApplication.


Public Functions

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

Public Slots

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

Signals

void messageReceived ( const QString & message )

Additional Inherited Members


Detailed Description

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

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

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

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

See also QtSingleApplication.


Member Function Documentation

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

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

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

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

QString QtSingleCoreApplication::id () const

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

bool QtSingleCoreApplication::isRunning ()

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

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

See also sendMessage().

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

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

See also sendMessage().

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

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

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

See also isRunning() and messageReceived().


Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions
ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/images/000077500000000000000000000000001522363675600331065ustar00rootroot00000000000000qt-logo.png000066400000000000000000000077531522363675600351330ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/doc/imagesPNG  IHDR9C:uIDATxb?bhJnJnJnJnJnJnԡ Є`r'Q( !!Nb_p??F&F312G.yG&ޏ?}eWSSgb( ~™t齸g0sVv`fcdY8E$xdUUex$xd9DDr=#gdd|Uףw9D- 2b8Ͽebddceᔐ╗SWScaB#cfd]-I\ _20110`xzw/).#'˯"ǯ*˫,+')@lY@}fۯͼ 2@d$1H')&#'ç,ϯ*˧,#/%́XgfdOX8Y9s2GC3g@ fFff.3O|v ,l%?fR_|bb`y엉3+ԇ,̌,4 "ͭ32>{E4އ ˯NԦ+Qefdϛ?6:&Ǜ?|"=\n$FFfF /0"`ddf cfbb`dx՛o yAP ,,eebWaá,QܬLL>5Lll10 m00wTVxOÚ bGB8GtUմXplII ׶R/@2 Y{ ]d9#ule+}N6XfJ"խJ13002³ @K"ŭzo?1000@{ lϿ`?ï2"ecgd H.fFfɆ}Ͽߌ"٭윌 y02000Ac<\po/."?;#ߛ!hgddd\<|\300<|?j"-U L9D8E i[ZP?z5fF6? o"b')~?3311g/ ֯cz߿>pvfL~g'""٭Qd'i `Ϳ'?HۅǞy?200 %)h1.7?."ͭ 32yVfFfGyO/:?LL [,?/?^}|:`luX-tN X"_CkǶ>w:7WlSofFcOv{OD7톚)*$@d"7$1CRgɉi[!.f&v_#ɧ{='JXXc`agպ]R\̅?ӧ_ᄏvѦ_2"g|fە(m )\!&&&F{ ba~>qci.O?l-"s܅Ǐ<Ϟn%hm)tN6P߿0H~̌,|ןhmF>1:19_/رcc7k䱞]ۯ咒SaB[?|}kf~?ɍkF/>9*qpQ( @##ïe1| QXn_ #ơp7B]X?F[a'K+ q/̌,,L L 7tDʡz /#300VnC")"/?110qp￿l_GVWNOU_UIPSCؐ?\e``=_R(2r-d?ÿ_?+78$$ +:xBVFn^?cbdd@yĂf```aba㔆L)J sI2Ҥ!#3 > ^y^~o (?+33d:.cfL(H*sJ`Mg222ڥž15,l l"< void report(const QString& msg) { qDebug("[%i] %s", (int)QCoreApplication::applicationPid(), qPrintable(msg)); } class MainClass : public QObject { Q_OBJECT public: MainClass() : QObject() {} public slots: void handleMessage(const QString& message) { report( "Message received: \"" + message + "\""); } }; int main(int argc, char **argv) { report("Starting up"); QtSingleCoreApplication app(argc, argv); if (app.isRunning()) { QString msg(QString("Hi master, I am %1.").arg(QCoreApplication::applicationPid())); bool sentok = app.sendMessage(msg, 2000); QString rep("Another instance is running, so I will exit."); rep += sentok ? " Message sent ok." : " Message sending failed; the other instance may be frozen."; report(rep); return 0; } else { report("No other instance is running; so I will."); MainClass mainObj; QObject::connect(&app, SIGNAL(messageReceived(const QString&)), &mainObj, SLOT(handleMessage(const QString&))); return app.exec(); } } #include "main.moc" examples.pro000066400000000000000000000001111522363675600351640ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/examplesTEMPLATE = subdirs SUBDIRS = trivial \ loader \ console loader/000077500000000000000000000000001522363675600341015ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/examplesfile1.qsl000066400000000000000000000000071522363675600356170ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/examples/loaderFile 1 file2.qsl000066400000000000000000000000071522363675600356200ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/examples/loaderFile 2 loader.pro000066400000000000000000000002061522363675600360670ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/examples/loadergreaterThan(QT_MAJOR_VERSION, 4): QT += printsupport TEMPLATE = app include(../../src/qtsingleapplication.pri) SOURCES += main.cpp loader.qdoc000066400000000000000000000033551522363675600362250ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/examples/loader// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). // SPDX-License-Identifier: BSD-3-Clause /*! \page qtsingleapplication-example-loader.html \title Loading Documents The application in this example loads or prints the documents passed as commandline parameters to further instances of this application. \quotefromfile loader/main.cpp \printuntil }; The user interface in this application is a QMainWindow subclass with a QMdiArea as the central widget. It implements a slot \c handleMessage() that will be connected to the messageReceived() signal of the QtSingleApplication class. \printuntil } The MainWindow constructor creates a minimal user interface. \printto case Print: The handleMessage() slot interprets the message passed in as a filename that can be prepended with \e /print to indicate that the file should just be printed rather than loaded. \printto #include Loading the file will also activate the window. \printto mw The \c main entry point function creates a QtSingleApplication object, and creates a message to send to a running instance of the application. If the message was sent successfully the process exits immediately. \printuntil } If the message could not be sent the application starts up. Note that \c false is passed to the call to setActivationWindow() to prevent automatic activation for every message received, e.g. when the application should just print a file. Instead, the message handling function determines whether activation is requested, and signals that by emitting the needToShow() signal. This is then simply connected directly to QtSingleApplication's activateWindow() slot. */ main.cpp000066400000000000000000000043241522363675600355340ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/examples/loader// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). // SPDX-License-Identifier: BSD-3-Clause #include #include #include #include #include #include #include #include class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(); public slots: void handleMessage(const QString& message); signals: void needToShow(); private: QMdiArea *workspace; }; MainWindow::MainWindow() { workspace = new QMdiArea(this); setCentralWidget(workspace); } void MainWindow::handleMessage(const QString& message) { enum Action { Nothing, Open, Print } action; action = Nothing; QString filename = message; if (message.toLower().startsWith("/print ")) { filename = filename.mid(7); action = Print; } else if (!message.isEmpty()) { action = Open; } if (action == Nothing) { emit needToShow(); return; } QFile file(filename); QString contents; if (file.open(QIODevice::ReadOnly)) contents = file.readAll(); else contents = "[[Error: Could not load file " + filename + "]]"; QTextEdit *view = new QTextEdit; view->setPlainText(contents); switch(action) { case Print: { QPrinter printer; view->print(&printer); delete view; } break; case Open: { workspace->addSubWindow(view); view->setWindowTitle(message); view->show(); emit needToShow(); } break; default: break; }; } #include "main.moc" int main(int argc, char **argv) { QtSingleApplication instance("File loader QtSingleApplication example", argc, argv); QString message; for (int a = 1; a < argc; ++a) { message += argv[a]; if (a < argc-1) message += " "; } if (instance.sendMessage(message)) return 0; MainWindow mw; mw.handleMessage(message); mw.show(); QObject::connect(&instance, SIGNAL(messageReceived(const QString&)), &mw, SLOT(handleMessage(const QString&))); instance.setActivationWindow(&mw, false); QObject::connect(&mw, SIGNAL(needToShow()), &instance, SLOT(activateWindow())); return instance.exec(); } trivial/000077500000000000000000000000001522363675600343055ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/examplesmain.cpp000066400000000000000000000014521522363675600357370ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/examples/trivial// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). // SPDX-License-Identifier: BSD-3-Clause #include #include class TextEdit : public QTextEdit { Q_OBJECT public: TextEdit(QWidget *parent = 0) : QTextEdit(parent) {} public slots: void append(const QString &str) { QTextEdit::append(str); } }; #include "main.moc" int main(int argc, char **argv) { QtSingleApplication instance(argc, argv); if (instance.sendMessage("Wake up!")) return 0; TextEdit logview; logview.setReadOnly(true); logview.show(); instance.setActivationWindow(&logview); QObject::connect(&instance, SIGNAL(messageReceived(const QString&)), &logview, SLOT(append(const QString&))); return instance.exec(); } trivial.pro000066400000000000000000000001211522363675600364730ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/examples/trivialTEMPLATE = app include(../../src/qtsingleapplication.pri) SOURCES += main.cpp trivial.qdoc000066400000000000000000000027111522363675600366300ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/examples/trivial// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). // SPDX-License-Identifier: BSD-3-Clause /*! \page qtsingleapplication-example-trivial.html \title A Trivial Example The application in this example has a log-view that displays messages sent by further instances of the same application. The example demonstrates the use of the QtSingleApplication class to detect and communicate with a running instance of the application using the sendMessage() API. The messageReceived() signal is used to display received messages in a QTextEdit log. \quotefromfile trivial/main.cpp \printuntil instance The example has only the \c main entry point function. A QtSingleApplication object is created immediately. \printuntil return If another instance of this application is already running, sendMessage() will succeed, and this instance just exits immediately. \printuntil show() Otherwise the instance continues as normal and creates the user interface. \printuntil return instance.exec(); The \c logview object is also set as the application's activation window. Every time a message is received, the window will be raised and activated automatically. The messageReceived() signal is also connected to the QTextEdit's append() slot. Every message received from further instances of this application will be displayed in the log. Finally the event loop is entered. */ qtsingleapplication.pro000066400000000000000000000001651522363675600356130ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplicationTEMPLATE=subdirs CONFIG += ordered include(common.pri) qtsingleapplication-uselib:SUBDIRS=buildlib SUBDIRS+=examples ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/src/000077500000000000000000000000001522363675600316635ustar00rootroot00000000000000QtLockedFile000066400000000000000000000000321522363675600340300ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/src#include "qtlockedfile.h" QtSingleApplication000066400000000000000000000000411522363675600354340ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/src#include "qtsingleapplication.h" qtlocalpeer.cpp000066400000000000000000000117451522363675600346330ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/src// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). // SPDX-License-Identifier: BSD-3-Clause #include "qtlocalpeer.h" #include #include #include #include #if defined(Q_OS_WIN) #include #include typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*); static PProcessIdToSessionId pProcessIdToSessionId = 0; #endif #if defined(Q_OS_UNIX) #include #include #include #endif namespace QtLP_Private { #include "qtlockedfile.cpp" #if defined(Q_OS_WIN) #include "qtlockedfile_win.cpp" #else #include "qtlockedfile_unix.cpp" #endif } const char* QtLocalPeer::ack = "ack"; QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId) : QObject(parent), id(appId) { QString prefix = id; if (id.isEmpty()) { id = QCoreApplication::applicationFilePath(); #if defined(Q_OS_WIN) id = id.toLower(); #endif prefix = id.section(QLatin1Char('/'), -1); } prefix.remove(QRegularExpression("[^a-zA-Z]")); prefix.truncate(6); QByteArray idc = id.toUtf8(); quint16 idNum = qChecksum(idc.constData(), idc.size()); socketName = QLatin1String("qtsingleapp-") + prefix + QLatin1Char('-') + QString::number(idNum, 16); #if defined(Q_OS_WIN) if (!pProcessIdToSessionId) { QLibrary lib("kernel32"); pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId"); } if (pProcessIdToSessionId) { DWORD sessionId = 0; pProcessIdToSessionId(GetCurrentProcessId(), &sessionId); socketName += QLatin1Char('-') + QString::number(sessionId, 16); } #else socketName += QLatin1Char('-') + QString::number(::getuid(), 16); #endif server = new QLocalServer(this); QString lockName = QDir(QDir::tempPath()).absolutePath() + QLatin1Char('/') + socketName + QLatin1String("-lockfile"); lockFile.setFileName(lockName); lockFile.open(QIODevice::ReadWrite); } bool QtLocalPeer::isClient() { if (lockFile.isLocked()) return false; if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false)) return true; bool res = server->listen(socketName); #if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0)) // ### Workaround if (!res && server->serverError() == QAbstractSocket::AddressInUseError) { QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName); res = server->listen(socketName); } #endif if (!res) qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString())); QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection())); return false; } bool QtLocalPeer::sendMessage(const QString &message, int timeout) { if (!isClient()) return false; QLocalSocket socket; bool connOk = false; for(int i = 0; i < 2; i++) { // Try twice, in case the other instance is just starting up socket.connectToServer(socketName); connOk = socket.waitForConnected(timeout/2); if (connOk || i) break; int ms = 250; #if defined(Q_OS_WIN) Sleep(DWORD(ms)); #else struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 }; nanosleep(&ts, NULL); #endif } if (!connOk) return false; QByteArray uMsg(message.toUtf8()); QDataStream ds(&socket); ds.writeBytes(uMsg.constData(), uMsg.size()); bool res = socket.waitForBytesWritten(timeout); if (res) { res &= socket.waitForReadyRead(timeout); // wait for ack if (res) res &= (socket.read(qstrlen(ack)) == ack); } return res; } void QtLocalPeer::receiveConnection() { QLocalSocket* socket = server->nextPendingConnection(); if (!socket) return; while (true) { if (socket->state() == QLocalSocket::UnconnectedState) { qWarning("QtLocalPeer: Peer disconnected"); delete socket; return; } if (socket->bytesAvailable() >= qint64(sizeof(quint32))) break; socket->waitForReadyRead(); } QDataStream ds(socket); QByteArray uMsg; quint32 remaining; ds >> remaining; uMsg.resize(remaining); int got = 0; char* uMsgBuf = uMsg.data(); do { got = ds.readRawData(uMsgBuf, remaining); remaining -= got; uMsgBuf += got; } while (remaining && got >= 0 && socket->waitForReadyRead(2000)); if (got < 0) { qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData()); delete socket; return; } QString message(QString::fromUtf8(uMsg)); socket->write(ack, qstrlen(ack)); socket->waitForBytesWritten(1000); socket->waitForDisconnected(1000); // make sure client reads ack delete socket; emit messageReceived(message); //### (might take a long time to return) } qtlocalpeer.h000066400000000000000000000014451522363675600342740ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/src// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). // SPDX-License-Identifier: BSD-3-Clause #ifndef QTLOCALPEER_H #define QTLOCALPEER_H #include #include #include #include "qtlockedfile.h" class QtLocalPeer : public QObject { Q_OBJECT public: QtLocalPeer(QObject *parent = 0, const QString &appId = QString()); bool isClient(); bool sendMessage(const QString &message, int timeout); QString applicationId() const { return id; } Q_SIGNALS: void messageReceived(const QString &message); protected Q_SLOTS: void receiveConnection(); protected: QString id; QString socketName; QLocalServer* server; QtLP_Private::QtLockedFile lockFile; private: static const char* ack; }; #endif // QTLOCALPEER_H qtlockedfile.cpp000066400000000000000000000102021522363675600347510ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/src// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). // SPDX-License-Identifier: BSD-3-Clause #include "qtlockedfile.h" /*! \class QtLockedFile \brief The QtLockedFile class extends QFile with advisory locking functions. A file may be locked in read or write mode. Multiple instances of \e QtLockedFile, created in multiple processes running on the same machine, may have a file locked in read mode. Exactly one instance may have it locked in write mode. A read and a write lock cannot exist simultaneously on the same file. The file locks are advisory. This means that nothing prevents another process from manipulating a locked file using QFile or file system functions offered by the OS. Serialization is only guaranteed if all processes that access the file use QLockedFile. Also, while holding a lock on a file, a process must not open the same file again (through any API), or locks can be unexpectedly lost. The lock provided by an instance of \e QtLockedFile is released whenever the program terminates. This is true even when the program crashes and no destructors are called. */ /*! \enum QtLockedFile::LockMode This enum describes the available lock modes. \value ReadLock A read lock. \value WriteLock A write lock. \value NoLock Neither a read lock nor a write lock. */ /*! Constructs an unlocked \e QtLockedFile object. This constructor behaves in the same way as \e QFile::QFile(). \sa QFile::QFile() */ QtLockedFile::QtLockedFile() : QFile() { #ifdef Q_OS_WIN wmutex = 0; rmutex = 0; #endif m_lock_mode = NoLock; } /*! Constructs an unlocked QtLockedFile object with file \a name. This constructor behaves in the same way as \e QFile::QFile(const QString&). \sa QFile::QFile() */ QtLockedFile::QtLockedFile(const QString &name) : QFile(name) { #ifdef Q_OS_WIN wmutex = 0; rmutex = 0; #endif m_lock_mode = NoLock; } /*! Opens the file in OpenMode \a mode. This is identical to QFile::open(), with the one exception that the Truncate mode flag is disallowed. Truncation would conflict with the advisory file locking, since the file would be modified before the write lock is obtained. If truncation is required, use resize(0) after obtaining the write lock. Returns true if successful; otherwise false. \sa QFile::open(), QFile::resize() */ bool QtLockedFile::open(OpenMode mode) { if (mode & QIODevice::Truncate) { qWarning("QtLockedFile::open(): Truncate mode not allowed."); return false; } return QFile::open(mode); } /*! Returns \e true if this object has a in read or write lock; otherwise returns \e false. \sa lockMode() */ bool QtLockedFile::isLocked() const { return m_lock_mode != NoLock; } /*! Returns the type of lock currently held by this object, or \e QtLockedFile::NoLock. \sa isLocked() */ QtLockedFile::LockMode QtLockedFile::lockMode() const { return m_lock_mode; } /*! \fn bool QtLockedFile::lock(LockMode mode, bool block = true) Obtains a lock of type \a mode. The file must be opened before it can be locked. If \a block is true, this function will block until the lock is aquired. If \a block is false, this function returns \e false immediately if the lock cannot be aquired. If this object already has a lock of type \a mode, this function returns \e true immediately. If this object has a lock of a different type than \a mode, the lock is first released and then a new lock is obtained. This function returns \e true if, after it executes, the file is locked by this object, and \e false otherwise. \sa unlock(), isLocked(), lockMode() */ /*! \fn bool QtLockedFile::unlock() Releases a lock. If the object has no lock, this function returns immediately. This function returns \e true if, after it executes, the file is not locked by this object, and \e false otherwise. \sa lock(), isLocked(), lockMode() */ /*! \fn QtLockedFile::~QtLockedFile() Destroys the \e QtLockedFile object. If any locks were held, they are released. */ qtlockedfile.h000066400000000000000000000025471522363675600344330ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/src// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). // SPDX-License-Identifier: BSD-3-Clause #ifndef QTLOCKEDFILE_H #define QTLOCKEDFILE_H #include #ifdef Q_OS_WIN #include #endif #if defined(Q_OS_WIN) # if !defined(QT_QTLOCKEDFILE_EXPORT) && !defined(QT_QTLOCKEDFILE_IMPORT) # define QT_QTLOCKEDFILE_EXPORT # elif defined(QT_QTLOCKEDFILE_IMPORT) # if defined(QT_QTLOCKEDFILE_EXPORT) # undef QT_QTLOCKEDFILE_EXPORT # endif # define QT_QTLOCKEDFILE_EXPORT __declspec(dllimport) # elif defined(QT_QTLOCKEDFILE_EXPORT) # undef QT_QTLOCKEDFILE_EXPORT # define QT_QTLOCKEDFILE_EXPORT __declspec(dllexport) # endif #else # define QT_QTLOCKEDFILE_EXPORT #endif namespace QtLP_Private { class QT_QTLOCKEDFILE_EXPORT QtLockedFile : public QFile { public: enum LockMode { NoLock = 0, ReadLock, WriteLock }; QtLockedFile(); QtLockedFile(const QString &name); ~QtLockedFile(); bool open(OpenMode mode); bool lock(LockMode mode, bool block = true); bool unlock(); bool isLocked() const; LockMode lockMode() const; private: #ifdef Q_OS_WIN Qt::HANDLE wmutex; Qt::HANDLE rmutex; QVector rmutexes; QString mutexname; Qt::HANDLE getMutexHandle(int idx, bool doCreate); bool waitMutex(Qt::HANDLE mutex, bool doBlock); #endif LockMode m_lock_mode; }; } #endif qtlockedfile_unix.cpp000066400000000000000000000030541522363675600360230ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/src// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). // SPDX-License-Identifier: BSD-3-Clause #include #include #include #include #include "qtlockedfile.h" bool QtLockedFile::lock(LockMode mode, bool block) { if (!isOpen()) { qWarning("QtLockedFile::lock(): file is not opened"); return false; } if (mode == NoLock) return unlock(); if (mode == m_lock_mode) return true; if (m_lock_mode != NoLock) unlock(); struct flock fl; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK; int cmd = block ? F_SETLKW : F_SETLK; int ret = fcntl(handle(), cmd, &fl); if (ret == -1) { if (errno != EINTR && errno != EAGAIN) qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); return false; } m_lock_mode = mode; return true; } bool QtLockedFile::unlock() { if (!isOpen()) { qWarning("QtLockedFile::unlock(): file is not opened"); return false; } if (!isLocked()) return true; struct flock fl; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fl.l_type = F_UNLCK; int ret = fcntl(handle(), F_SETLKW, &fl); if (ret == -1) { qWarning("QtLockedFile::lock(): fcntl: %s", strerror(errno)); return false; } m_lock_mode = NoLock; return true; } QtLockedFile::~QtLockedFile() { if (isOpen()) unlock(); } qtlockedfile_win.cpp000066400000000000000000000111211522363675600356270ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/src// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). // SPDX-License-Identifier: BSD-3-Clause #include "qtlockedfile.h" #include #include #define MUTEX_PREFIX "QtLockedFile mutex " // Maximum number of concurrent read locks. Must not be greater than MAXIMUM_WAIT_OBJECTS #define MAX_READERS MAXIMUM_WAIT_OBJECTS #if QT_VERSION >= 0x050000 #define QT_WA(unicode, ansi) unicode #endif Qt::HANDLE QtLockedFile::getMutexHandle(int idx, bool doCreate) { if (mutexname.isEmpty()) { QFileInfo fi(*this); mutexname = QString::fromLatin1(MUTEX_PREFIX) + fi.absoluteFilePath().toLower(); } QString mname(mutexname); if (idx >= 0) mname += QString::number(idx); Qt::HANDLE mutex; if (doCreate) { QT_WA( { mutex = CreateMutexW(NULL, FALSE, (TCHAR*)mname.utf16()); }, { mutex = CreateMutexA(NULL, FALSE, mname.toLocal8Bit().constData()); } ); if (!mutex) { qErrnoWarning("QtLockedFile::lock(): CreateMutex failed"); return 0; } } else { QT_WA( { mutex = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, (TCHAR*)mname.utf16()); }, { mutex = OpenMutexA(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, mname.toLocal8Bit().constData()); } ); if (!mutex) { if (GetLastError() != ERROR_FILE_NOT_FOUND) qErrnoWarning("QtLockedFile::lock(): OpenMutex failed"); return 0; } } return mutex; } bool QtLockedFile::waitMutex(Qt::HANDLE mutex, bool doBlock) { Q_ASSERT(mutex); DWORD res = WaitForSingleObject(mutex, doBlock ? INFINITE : 0); switch (res) { case WAIT_OBJECT_0: case WAIT_ABANDONED: return true; break; case WAIT_TIMEOUT: break; default: qErrnoWarning("QtLockedFile::lock(): WaitForSingleObject failed"); } return false; } bool QtLockedFile::lock(LockMode mode, bool block) { if (!isOpen()) { qWarning("QtLockedFile::lock(): file is not opened"); return false; } if (mode == NoLock) return unlock(); if (mode == m_lock_mode) return true; if (m_lock_mode != NoLock) unlock(); if (!wmutex && !(wmutex = getMutexHandle(-1, true))) return false; if (!waitMutex(wmutex, block)) return false; if (mode == ReadLock) { int idx = 0; for (; idx < MAX_READERS; idx++) { rmutex = getMutexHandle(idx, false); if (!rmutex || waitMutex(rmutex, false)) break; CloseHandle(rmutex); } bool ok = true; if (idx >= MAX_READERS) { qWarning("QtLockedFile::lock(): too many readers"); rmutex = 0; ok = false; } else if (!rmutex) { rmutex = getMutexHandle(idx, true); if (!rmutex || !waitMutex(rmutex, false)) ok = false; } if (!ok && rmutex) { CloseHandle(rmutex); rmutex = 0; } ReleaseMutex(wmutex); if (!ok) return false; } else { Q_ASSERT(rmutexes.isEmpty()); for (int i = 0; i < MAX_READERS; i++) { Qt::HANDLE mutex = getMutexHandle(i, false); if (mutex) rmutexes.append(mutex); } if (rmutexes.size()) { DWORD res = WaitForMultipleObjects(rmutexes.size(), rmutexes.constData(), TRUE, block ? INFINITE : 0); if (res != WAIT_OBJECT_0 && res != WAIT_ABANDONED) { if (res != WAIT_TIMEOUT) qErrnoWarning("QtLockedFile::lock(): WaitForMultipleObjects failed"); m_lock_mode = WriteLock; // trick unlock() to clean up - semiyucky unlock(); return false; } } } m_lock_mode = mode; return true; } bool QtLockedFile::unlock() { if (!isOpen()) { qWarning("QtLockedFile::unlock(): file is not opened"); return false; } if (!isLocked()) return true; if (m_lock_mode == ReadLock) { ReleaseMutex(rmutex); CloseHandle(rmutex); rmutex = 0; } else { foreach(Qt::HANDLE mutex, rmutexes) { ReleaseMutex(mutex); CloseHandle(mutex); } rmutexes.clear(); ReleaseMutex(wmutex); } m_lock_mode = QtLockedFile::NoLock; return true; } QtLockedFile::~QtLockedFile() { if (isOpen()) unlock(); if (wmutex) CloseHandle(wmutex); } qtsingleapplication.cpp000066400000000000000000000232501522363675600363640ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/src// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). // SPDX-License-Identifier: BSD-3-Clause #include "qtsingleapplication.h" #include "qtlocalpeer.h" #include /*! \class QtSingleApplication qtsingleapplication.h \brief The QtSingleApplication class provides an API to detect and communicate with running instances of an application. This class allows you to create applications where only one instance should be running at a time. I.e., if the user tries to launch another instance, the already running instance will be activated instead. Another usecase is a client-server system, where the first started instance will assume the role of server, and the later instances will act as clients of that server. By default, the full path of the executable file is used to determine whether two processes are instances of the same application. You can also provide an explicit identifier string that will be compared instead. The application should create the QtSingleApplication object early in the startup phase, and call isRunning() to find out if another instance of this application is already running. If isRunning() returns false, it means that no other instance is running, and this instance has assumed the role as the running instance. In this case, the application should continue with the initialization of the application user interface before entering the event loop with exec(), as normal. The messageReceived() signal will be emitted when the running application receives messages from another instance of the same application. When a message is received it might be helpful to the user to raise the application so that it becomes visible. To facilitate this, QtSingleApplication provides the setActivationWindow() function and the activateWindow() slot. If isRunning() returns true, another instance is already running. It may be alerted to the fact that another instance has started by using the sendMessage() function. Also data such as startup parameters (e.g. the name of the file the user wanted this new instance to open) can be passed to the running instance with this function. Then, the application should terminate (or enter client mode). If isRunning() returns true, but sendMessage() fails, that is an indication that the running instance is frozen. Here's an example that shows how to convert an existing application to use QtSingleApplication. It is very simple and does not make use of all QtSingleApplication's functionality (see the examples for that). \code // Original int main(int argc, char **argv) { QApplication app(argc, argv); MyMainWidget mmw; mmw.show(); return app.exec(); } // Single instance int main(int argc, char **argv) { QtSingleApplication app(argc, argv); if (app.isRunning()) return !app.sendMessage(someDataString); MyMainWidget mmw; app.setActivationWindow(&mmw); mmw.show(); return app.exec(); } \endcode Once this QtSingleApplication instance is destroyed (normally when the process exits or crashes), when the user next attempts to run the application this instance will not, of course, be encountered. The next instance to call isRunning() or sendMessage() will assume the role as the new running instance. For console (non-GUI) applications, QtSingleCoreApplication may be used instead of this class, to avoid the dependency on the QtGui library. \sa QtSingleCoreApplication */ void QtSingleApplication::sysInit(const QString &appId) { actWin = 0; peer = new QtLocalPeer(this, appId); connect(peer, SIGNAL(messageReceived(const QString&)), SIGNAL(messageReceived(const QString&))); } /*! Creates a QtSingleApplication object. The application identifier will be QCoreApplication::applicationFilePath(). \a argc, \a argv, and \a GUIenabled are passed on to the QAppliation constructor. If you are creating a console application (i.e. setting \a GUIenabled to false), you may consider using QtSingleCoreApplication instead. */ QtSingleApplication::QtSingleApplication(int &argc, char **argv, bool GUIenabled) : QApplication(argc, argv, GUIenabled) { sysInit(); } /*! Creates a QtSingleApplication object with the application identifier \a appId. \a argc and \a argv are passed on to the QAppliation constructor. */ QtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char **argv) : QApplication(argc, argv) { sysInit(appId); } #if QT_VERSION < 0x050000 /*! Creates a QtSingleApplication object. The application identifier will be QCoreApplication::applicationFilePath(). \a argc, \a argv, and \a type are passed on to the QAppliation constructor. */ QtSingleApplication::QtSingleApplication(int &argc, char **argv, Type type) : QApplication(argc, argv, type) { sysInit(); } # if defined(Q_WS_X11) /*! Special constructor for X11, ref. the documentation of QApplication's corresponding constructor. The application identifier will be QCoreApplication::applicationFilePath(). \a dpy, \a visual, and \a cmap are passed on to the QApplication constructor. */ QtSingleApplication::QtSingleApplication(Display* dpy, Qt::HANDLE visual, Qt::HANDLE cmap) : QApplication(dpy, visual, cmap) { sysInit(); } /*! Special constructor for X11, ref. the documentation of QApplication's corresponding constructor. The application identifier will be QCoreApplication::applicationFilePath(). \a dpy, \a argc, \a argv, \a visual, and \a cmap are passed on to the QApplication constructor. */ QtSingleApplication::QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap) : QApplication(dpy, argc, argv, visual, cmap) { sysInit(); } /*! Special constructor for X11, ref. the documentation of QApplication's corresponding constructor. The application identifier will be \a appId. \a dpy, \a argc, \a argv, \a visual, and \a cmap are passed on to the QApplication constructor. */ QtSingleApplication::QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap) : QApplication(dpy, argc, argv, visual, cmap) { sysInit(appId); } # endif // Q_WS_X11 #endif // QT_VERSION < 0x050000 /*! Returns true if another instance of this application is running; otherwise false. This function does not find instances of this application that are being run by a different user (on Windows: that are running in another session). \sa sendMessage() */ bool QtSingleApplication::isRunning() { return peer->isClient(); } /*! Tries to send the text \a message to the currently running instance. The QtSingleApplication object in the running instance will emit the messageReceived() signal when it receives the message. This function returns true if the message has been sent to, and processed by, the current instance. If there is no instance currently running, or if the running instance fails to process the message within \a timeout milliseconds, this function return false. \sa isRunning(), messageReceived() */ bool QtSingleApplication::sendMessage(const QString &message, int timeout) { return peer->sendMessage(message, timeout); } /*! Returns the application identifier. Two processes with the same identifier will be regarded as instances of the same application. */ QString QtSingleApplication::id() const { return peer->applicationId(); } /*! Sets the activation window of this application to \a aw. The activation window is the widget that will be activated by activateWindow(). This is typically the application's main window. If \a activateOnMessage is true (the default), the window will be activated automatically every time a message is received, just prior to the messageReceived() signal being emitted. \sa activateWindow(), messageReceived() */ void QtSingleApplication::setActivationWindow(QWidget* aw, bool activateOnMessage) { actWin = aw; if (activateOnMessage) connect(peer, SIGNAL(messageReceived(const QString&)), this, SLOT(activateWindow())); else disconnect(peer, SIGNAL(messageReceived(const QString&)), this, SLOT(activateWindow())); } /*! Returns the applications activation window if one has been set by calling setActivationWindow(), otherwise returns 0. \sa setActivationWindow() */ QWidget* QtSingleApplication::activationWindow() const { return actWin; } /*! De-minimizes, raises, and activates this application's activation window. This function does nothing if no activation window has been set. This is a convenience function to show the user that this application instance has been activated when he has tried to start another instance. This function should typically be called in response to the messageReceived() signal. By default, that will happen automatically, if an activation window has been set. \sa setActivationWindow(), messageReceived(), initialize() */ void QtSingleApplication::activateWindow() { if (actWin) { actWin->setWindowState(actWin->windowState() & ~Qt::WindowMinimized); actWin->raise(); actWin->activateWindow(); } } /*! \fn void QtSingleApplication::messageReceived(const QString& message) This signal is emitted when the current instance receives a \a message from another instance of this application. \sa sendMessage(), setActivationWindow(), activateWindow() */ /*! \fn void QtSingleApplication::initialize(bool dummy = true) \obsolete */ qtsingleapplication.h000066400000000000000000000040571522363675600360350ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/src// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). // SPDX-License-Identifier: BSD-3-Clause #ifndef QTSINGLEAPPLICATION_H #define QTSINGLEAPPLICATION_H #include class QtLocalPeer; #if defined(Q_OS_WIN) # if !defined(QT_QTSINGLEAPPLICATION_EXPORT) && !defined(QT_QTSINGLEAPPLICATION_IMPORT) # define QT_QTSINGLEAPPLICATION_EXPORT # elif defined(QT_QTSINGLEAPPLICATION_IMPORT) # if defined(QT_QTSINGLEAPPLICATION_EXPORT) # undef QT_QTSINGLEAPPLICATION_EXPORT # endif # define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllimport) # elif defined(QT_QTSINGLEAPPLICATION_EXPORT) # undef QT_QTSINGLEAPPLICATION_EXPORT # define QT_QTSINGLEAPPLICATION_EXPORT __declspec(dllexport) # endif #else # define QT_QTSINGLEAPPLICATION_EXPORT #endif class QT_QTSINGLEAPPLICATION_EXPORT QtSingleApplication : public QApplication { Q_OBJECT public: QtSingleApplication(int &argc, char **argv, bool GUIenabled = true); QtSingleApplication(const QString &id, int &argc, char **argv); #if QT_VERSION < 0x050000 QtSingleApplication(int &argc, char **argv, Type type); # if defined(Q_WS_X11) QtSingleApplication(Display* dpy, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0); QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap= 0); QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0); # endif // Q_WS_X11 #endif // QT_VERSION < 0x050000 bool isRunning(); QString id() const; void setActivationWindow(QWidget* aw, bool activateOnMessage = true); QWidget* activationWindow() const; // Obsolete: void initialize(bool dummy = true) { isRunning(); Q_UNUSED(dummy) } public Q_SLOTS: bool sendMessage(const QString &message, int timeout = 5000); void activateWindow(); Q_SIGNALS: void messageReceived(const QString &message); private: void sysInit(const QString &appId = QString()); QtLocalPeer *peer; QWidget *actWin; }; #endif // QTSINGLEAPPLICATION_H qtsingleapplication.pri000066400000000000000000000011101522363675600363630ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/srcinclude(../common.pri) INCLUDEPATH += $$PWD DEPENDPATH += $$PWD QT *= network greaterThan(QT_MAJOR_VERSION, 4): QT *= widgets qtsingleapplication-uselib:!qtsingleapplication-buildlib { LIBS += -L$$QTSINGLEAPPLICATION_LIBDIR -l$$QTSINGLEAPPLICATION_LIBNAME } else { SOURCES += $$PWD/qtsingleapplication.cpp $$PWD/qtlocalpeer.cpp HEADERS += $$PWD/qtsingleapplication.h $$PWD/qtlocalpeer.h } win32 { contains(TEMPLATE, lib):contains(CONFIG, shared):DEFINES += QT_QTSINGLEAPPLICATION_EXPORT else:qtsingleapplication-uselib:DEFINES += QT_QTSINGLEAPPLICATION_IMPORT } qtsinglecoreapplication.cpp000066400000000000000000000066151522363675600372430ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/src// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). // SPDX-License-Identifier: BSD-3-Clause #include "qtsinglecoreapplication.h" #include "qtlocalpeer.h" /*! \class QtSingleCoreApplication qtsinglecoreapplication.h \brief A variant of the QtSingleApplication class for non-GUI applications. This class is a variant of QtSingleApplication suited for use in console (non-GUI) applications. It is an extension of QCoreApplication (instead of QApplication). It does not require the QtGui library. The API and usage is identical to QtSingleApplication, except that functions relating to the "activation window" are not present, for obvious reasons. Please refer to the QtSingleApplication documentation for explanation of the usage. A QtSingleCoreApplication instance can communicate to a QtSingleApplication instance if they share the same application id. Hence, this class can be used to create a light-weight command-line tool that sends commands to a GUI application. \sa QtSingleApplication */ /*! Creates a QtSingleCoreApplication object. The application identifier will be QCoreApplication::applicationFilePath(). \a argc and \a argv are passed on to the QCoreAppliation constructor. */ QtSingleCoreApplication::QtSingleCoreApplication(int &argc, char **argv) : QCoreApplication(argc, argv) { peer = new QtLocalPeer(this); connect(peer, SIGNAL(messageReceived(const QString&)), SIGNAL(messageReceived(const QString&))); } /*! Creates a QtSingleCoreApplication object with the application identifier \a appId. \a argc and \a argv are passed on to the QCoreAppliation constructor. */ QtSingleCoreApplication::QtSingleCoreApplication(const QString &appId, int &argc, char **argv) : QCoreApplication(argc, argv) { peer = new QtLocalPeer(this, appId); connect(peer, SIGNAL(messageReceived(const QString&)), SIGNAL(messageReceived(const QString&))); } /*! Returns true if another instance of this application is running; otherwise false. This function does not find instances of this application that are being run by a different user (on Windows: that are running in another session). \sa sendMessage() */ bool QtSingleCoreApplication::isRunning() { return peer->isClient(); } /*! Tries to send the text \a message to the currently running instance. The QtSingleCoreApplication object in the running instance will emit the messageReceived() signal when it receives the message. This function returns true if the message has been sent to, and processed by, the current instance. If there is no instance currently running, or if the running instance fails to process the message within \a timeout milliseconds, this function return false. \sa isRunning(), messageReceived() */ bool QtSingleCoreApplication::sendMessage(const QString &message, int timeout) { return peer->sendMessage(message, timeout); } /*! Returns the application identifier. Two processes with the same identifier will be regarded as instances of the same application. */ QString QtSingleCoreApplication::id() const { return peer->applicationId(); } /*! \fn void QtSingleCoreApplication::messageReceived(const QString& message) This signal is emitted when the current instance receives a \a message from another instance of this application. \sa sendMessage() */ qtsinglecoreapplication.h000066400000000000000000000012651522363675600367040ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/src// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). // SPDX-License-Identifier: BSD-3-Clause #ifndef QTSINGLECOREAPPLICATION_H #define QTSINGLECOREAPPLICATION_H #include class QtLocalPeer; class QtSingleCoreApplication : public QCoreApplication { Q_OBJECT public: QtSingleCoreApplication(int &argc, char **argv); QtSingleCoreApplication(const QString &id, int &argc, char **argv); bool isRunning(); QString id() const; public Q_SLOTS: bool sendMessage(const QString &message, int timeout = 5000); Q_SIGNALS: void messageReceived(const QString &message); private: QtLocalPeer* peer; }; #endif // QTSINGLECOREAPPLICATION_H qtsinglecoreapplication.pri000066400000000000000000000005041522363675600372420ustar00rootroot00000000000000ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/qtsingleapplication/srcINCLUDEPATH += $$PWD DEPENDPATH += $$PWD HEADERS += $$PWD/qtsinglecoreapplication.h $$PWD/qtlocalpeer.h SOURCES += $$PWD/qtsinglecoreapplication.cpp $$PWD/qtlocalpeer.cpp QT *= network win32:contains(TEMPLATE, lib):contains(CONFIG, shared) { DEFINES += QT_QTSINGLECOREAPPLICATION_EXPORT=__declspec(dllexport) } ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/thumbnail.cpp000066400000000000000000000115111522363675600275100ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "context.h" #include class Thumbnail::Private { public: Private(Thumbnail *thumbnail); ~Private(); void setup(kywc_context *ctx, Thumbnail::Type type, QString uuid, QString output_uuid); int32_t fd; uint32_t format; QSize size; uint32_t offset; uint32_t stride; uint64_t modifier; Thumbnail::BufferFlags flags; Type type; QString source_uuid; QString output_uuid; kywc_thumbnail *k_thumbnail; private: Thumbnail *t; static bool bufferHandle(kywc_thumbnail *thumbnail, const struct kywc_thumbnail_buffer *buffer, void *data); static void destroyHandle(kywc_thumbnail *thumbnail, void *data); static struct kywc_thumbnail_interface thumbnail_impl; }; Thumbnail::Private::Private(Thumbnail *thumbnail) : t(thumbnail) {} Thumbnail::Private::~Private() {} bool Thumbnail::Private::bufferHandle(kywc_thumbnail *thumbnail, const struct kywc_thumbnail_buffer *buffer, void *data) { Thumbnail *thum = (Thumbnail *)data; switch (thumbnail->type) { case KYWC_THUMBNAIL_TYPE_OUTPUT: thum->pri->type = Thumbnail::Type::Output; break; case KYWC_THUMBNAIL_TYPE_TOPLEVEL: thum->pri->type = Thumbnail::Type::Toplevel; break; case KYWC_THUMBNAIL_TYPE_WORKSPACE: thum->pri->type = Thumbnail::Type::Workspace; break; } thum->pri->source_uuid = QString(thumbnail->source_uuid); thum->pri->output_uuid = QString(thumbnail->output_uuid); if (buffer->flags & KYWC_THUMBNAIL_BUFFER_IS_DMABUF) { thum->pri->flags |= Thumbnail::BufferFlag::Dmabuf; } if (buffer->flags & KYWC_THUMBNAIL_BUFFER_IS_REUSED) { thum->pri->flags |= Thumbnail::BufferFlag::Reused; } thum->pri->size = QSize(buffer->width, buffer->height); thum->pri->offset = buffer->offset; thum->pri->stride = buffer->stride; thum->pri->fd = buffer->fd; thum->pri->format = buffer->format; thum->pri->modifier = buffer->modifier; emit thum->bufferUpdate(); if (buffer->flags & KYWC_THUMBNAIL_BUFFER_IS_DMABUF) { return true; } else return false; } void Thumbnail::Private::destroyHandle(kywc_thumbnail *thumbnail, void *data) { Thumbnail *thum = (Thumbnail *)data; emit thum->deleted(); } struct kywc_thumbnail_interface Thumbnail::Private::thumbnail_impl { bufferHandle, destroyHandle, }; void Thumbnail::Private::setup(kywc_context *ctx, Thumbnail::Type type, QString uuid, QString output_uuid) { enum kywc_thumbnail_type flag = KYWC_THUMBNAIL_TYPE_TOPLEVEL; switch (type) { case Thumbnail::Type::Output: flag = KYWC_THUMBNAIL_TYPE_OUTPUT; break; case Thumbnail::Type::Toplevel: flag = KYWC_THUMBNAIL_TYPE_TOPLEVEL; break; case Thumbnail::Type::Workspace: flag = KYWC_THUMBNAIL_TYPE_WORKSPACE; break; } QByteArray qByteArray_uuid = uuid.toUtf8(); char *str = qByteArray_uuid.data(); QByteArray qByteArray = output_uuid.toUtf8(); char *output = qByteArray.data(); kywc_thumbnail *thumbnail = kywc_thumbnail_create(ctx, flag, str, output, &thumbnail_impl, this->t); k_thumbnail = thumbnail; } Thumbnail::Thumbnail(QObject *parent) : pri(new Private(this)) {} Thumbnail::~Thumbnail() {} void Thumbnail::setup(kywc_context *ctx, Thumbnail::Type type, QString uuid, QString output_uuid) { pri->setup(ctx, type, uuid, output_uuid); } int32_t Thumbnail::fd() const { return pri->fd; } uint32_t Thumbnail::format() const { return pri->format; } QSize Thumbnail::size() const { return pri->size; } uint32_t Thumbnail::offset() const { return pri->offset; } uint32_t Thumbnail::stride() const { return pri->stride; } uint64_t Thumbnail::modifier() const { return pri->modifier; } Thumbnail::BufferFlags Thumbnail::flags() const { return pri->flags; } void Thumbnail::destory() { if(pri->k_thumbnail) { kywc_thumbnail_destroy(pri->k_thumbnail); pri->k_thumbnail = nullptr; } } ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/toplevel.cpp000066400000000000000000000224511522363675600273640ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "context.h" #include #include class Toplevel::Private { public: Private(Toplevel *toplevel); ~Private(); void setup(kywc_toplevel *toplevel); QString uuid; QString title; QString app_id; QString icon; QPointer parent; QString primary_output; QStringList workspaces; QPoint point; QSize size; Toplevel::Capabilities capabilities; bool activated, minimized, maximized, fullscreen; uint32_t pid; kywc_toplevel *k_toplevel; XdgDesktopFile xdf; private: Toplevel *t; static void stateHandle(kywc_toplevel *toplevel, uint32_t mask); static void destroyHandle(kywc_toplevel *toplevel); static struct kywc_toplevel_interface toplevel_impl; }; Toplevel::Private::Private(Toplevel *toplevel) : t(toplevel) {} Toplevel::Private::~Private() {} void Toplevel::Private::stateHandle(kywc_toplevel *toplevel, uint32_t mask) { Toplevel *t_toplevel = (Toplevel *)kywc_toplevel_get_user_data(toplevel); Toplevel::Masks t_mask; if (mask & KYWC_TOPLEVEL_STATE_APP_ID) { t_mask |= Toplevel::Mask::AppId; t_toplevel->pri->app_id = QString(toplevel->app_id); } if (mask & KYWC_TOPLEVEL_STATE_TITLE) { t_mask |= Toplevel::Mask::Title; t_toplevel->pri->title = QString(toplevel->title); } if (mask & KYWC_TOPLEVEL_STATE_ACTIVATED) { t_mask |= Toplevel::Mask::Activated; t_toplevel->pri->activated = toplevel->activated; } if (mask & KYWC_TOPLEVEL_STATE_MINIMIZED) { t_mask |= Toplevel::Mask::Minimized; t_toplevel->pri->minimized = toplevel->minimized; } if (mask & KYWC_TOPLEVEL_STATE_MAXIMIZED) { t_mask |= Toplevel::Mask::Maximized; t_toplevel->pri->maximized = toplevel->maximized; } if (mask & KYWC_TOPLEVEL_STATE_FULLSCREEN) { t_mask |= Toplevel::Mask::Fullscreen; t_toplevel->pri->fullscreen = toplevel->fullscreen; } if (mask & KYWC_TOPLEVEL_STATE_PRIMARY_OUTPUT) { t_mask |= Toplevel::Mask::PrimaryOutput; t_toplevel->pri->primary_output = QString(toplevel->primary_output); } if (mask & KYWC_TOPLEVEL_STATE_WORKSPACE) { t_mask |= Toplevel::Mask::Workspace; t_toplevel->pri->workspaces.clear(); for (int i = 0; i < MAX_WORKSPACES; i++) { if (toplevel->workspaces[i] == NULL || toplevel->workspaces[i][0] == '\0') continue; t_toplevel->pri->workspaces << QString(toplevel->workspaces[i]); } } if (mask & KYWC_TOPLEVEL_STATE_PARENT) { t_mask |= Toplevel::Mask::Parent; if (toplevel->parent) { Toplevel *parent_toplevel = (Toplevel *)kywc_toplevel_get_user_data(toplevel->parent); if (parent_toplevel == nullptr) { parent_toplevel = new Toplevel; parent_toplevel->setup(toplevel->parent); } t_toplevel->pri->parent = parent_toplevel; } else t_toplevel->pri->parent = nullptr; } if (mask & KYWC_TOPLEVEL_STATE_ICON) { t_mask |= Toplevel::Mask::Icon; if (!QString(toplevel->icon).isEmpty() && QString(toplevel->icon) != "fallback") { t_toplevel->pri->icon = QString(toplevel->icon); } } if (mask & KYWC_TOPLEVEL_STATE_POSITION) { t_mask |= Toplevel::Mask::Position; t_toplevel->pri->point = QPoint(toplevel->x, toplevel->y); } if (mask & KYWC_TOPLEVEL_STATE_SIZE) { t_mask |= Toplevel::Mask::Size; t_toplevel->pri->size = QSize(toplevel->width, toplevel->height); } emit t_toplevel->stateUpdated(t_mask); } void Toplevel::Private::destroyHandle(kywc_toplevel *toplevel) { Toplevel *t_toplevel = (Toplevel *)kywc_toplevel_get_user_data(toplevel); emit t_toplevel->deleted(); } struct kywc_toplevel_interface Toplevel::Private::toplevel_impl { stateHandle, destroyHandle, }; void Toplevel::Private::setup(kywc_toplevel *toplevel) { k_toplevel = toplevel; uuid = QString(toplevel->uuid); title = QString(toplevel->title); icon = QString(toplevel->icon); app_id = QString(toplevel->app_id); pid = uint32_t(toplevel->pid); if (toplevel->parent) { Toplevel *parent_toplevel = (Toplevel *)kywc_toplevel_get_user_data(toplevel->parent); if (parent_toplevel == nullptr) { parent_toplevel = new Toplevel; parent_toplevel->setup(toplevel->parent); } parent = parent_toplevel; } else parent = nullptr; primary_output = toplevel->primary_output; for (int i = 0; i < MAX_WORKSPACES; i++) { if (toplevel->workspaces[i] == NULL || toplevel->workspaces[i][0] == '\0') continue; workspaces << QString(toplevel->workspaces[i]); } if (toplevel->capabilities & KYWC_TOPLEVEL_CAPABILITY_SKIP_TASKBAR) capabilities |= Toplevel::Capability::Taskbar; if (toplevel->capabilities & KYWC_TOPLEVEL_CAPABILITY_SKIP_SWITCHER) capabilities |= Toplevel::Capability::Switcher; activated = toplevel->activated; minimized = toplevel->minimized; maximized = toplevel->maximized; fullscreen = toplevel->fullscreen; point = QPoint(toplevel->x, toplevel->y); size = QSize(toplevel->width, toplevel->height); kywc_toplevel_set_interface(toplevel, &toplevel_impl); kywc_toplevel_set_user_data(toplevel, t); } Toplevel::Toplevel(QObject *parent) : pri(new Private(this)) {} Toplevel::~Toplevel() {} void Toplevel::setup(kywc_toplevel *toplevel) { pri->setup(toplevel); } QString Toplevel::uuid() const { return pri->uuid; } QString Toplevel::title() const { return pri->title; } QString Toplevel::icon() const { return pri->icon; } QString Toplevel::appId() const { return pri->app_id; } QPointer Toplevel::parent() const { return pri->parent; } QString Toplevel::primaryOutput() const { return pri->primary_output; } QStringList Toplevel::workspaces() const { return pri->workspaces; } QPoint Toplevel::point() const { return pri->point; } QSize Toplevel::size() const { return pri->size; } Toplevel::Capabilities Toplevel::capabilities() const { return pri->capabilities; } bool Toplevel::isActivated() const { return pri->activated; } bool Toplevel::isMinimized() const { return pri->minimized; } bool Toplevel::isMaximized() const { return pri->maximized; } bool Toplevel::isFullscreen() const { return pri->fullscreen; } uint32_t Toplevel::pid() const { return pri->pid; } void Toplevel::setMaximized(QString output) { QByteArray qByteArray = output.toUtf8(); char *str = qByteArray.data(); kywc_toplevel_set_maximized(pri->k_toplevel, str); } void Toplevel::unsetMaximized() { kywc_toplevel_unset_maximized(pri->k_toplevel); } void Toplevel::setMinimized() { kywc_toplevel_set_minimized(pri->k_toplevel); } void Toplevel::unsetMinimized() { kywc_toplevel_unset_minimized(pri->k_toplevel); } void Toplevel::setFullscreen(QString output) { QByteArray qByteArray = output.toUtf8(); char *str = qByteArray.data(); kywc_toplevel_set_fullscreen(pri->k_toplevel, str); } void Toplevel::unsetFullscreen() { kywc_toplevel_unset_fullscreen(pri->k_toplevel); } void Toplevel::setActivate() { kywc_toplevel_activate(pri->k_toplevel); } void Toplevel::close() { kywc_toplevel_close(pri->k_toplevel); } void Toplevel::enterWorkspace(QString workspace) { QByteArray qByteArray = workspace.toUtf8(); char *str = qByteArray.data(); kywc_toplevel_enter_workspace(pri->k_toplevel, str); } void Toplevel::leaveWorkspace(QString workspace) { QByteArray qByteArray = workspace.toUtf8(); char *str = qByteArray.data(); kywc_toplevel_leave_workspace(pri->k_toplevel, str); } void Toplevel::moveToWorkspace(QString workspace) { QByteArray qByteArray = workspace.toUtf8(); char *str = qByteArray.data(); kywc_toplevel_move_to_workspace(pri->k_toplevel, str); } void Toplevel::moveToOutput(QString output) { QByteArray qByteArray = output.toUtf8(); char *str = qByteArray.data(); kywc_toplevel_move_to_output(pri->k_toplevel, str); } bool Toplevel::hasChildren() { return kywc_toplevel_has_children(pri->k_toplevel); } void Toplevel::setDesktopFile(const QString & desktopFile) { pri->xdf.load(desktopFile); } QString Toplevel::iconName() const { if (icon().isEmpty() || icon() == "fallback") { return pri->xdf.iconName(); } else { return icon(); } } QString Toplevel::name() const { return pri->xdf.localizedValue("Name").toString(); } ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/ui.cpp000066400000000000000000001025641522363675600261530ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "widget.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { struct wl_display *display = NULL; QPlatformNativeInterface *native = QGuiApplication::platformNativeInterface(); if (!native) { return; } display = reinterpret_cast( native->nativeResourceForIntegration(QByteArrayLiteral("wl_display"))); if (!display) { qWarning("Failed to get Wayland display."); return; } context = new Context(display, Context::Capability::Output | Context::Capability::Toplevel | Context::Capability::Workspace); init_form(); context->start(); } MainWindow::~MainWindow() { delete context; } void MainWindow::init_workspace_widget(QWidget *widget) { QGridLayout *layout = new QGridLayout(widget); tableWidget_0 = new QTableWidget(); QStringList col_list_lable; // 列标题 col_list_lable << QString("uuid"); col_list_lable << QString("name"); col_list_lable << QString("position"); col_list_lable << QString("activated"); int col_list_lable_cnt = col_list_lable.count(); tableWidget_0->setColumnCount(col_list_lable_cnt); tableWidget_0->setHorizontalHeaderLabels(col_list_lable); tableWidget_0->setSelectionBehavior(QAbstractItemView::SelectRows); // 是否可选中 tableWidget_0->setStyleSheet("selection-background-color:pink"); tableWidget_0->setShowGrid(true); tableWidget_0->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); QPushButton *add_btn = new QPushButton("add new"); QPushButton *activited_btn = new QPushButton("set activited"); QPushButton *move_up_btn = new QPushButton("move up"); QPushButton *move_down_btn = new QPushButton("move down"); QPushButton *delete_btn = new QPushButton("delete"); add_btn->setFixedSize(100, 30); activited_btn->setFixedSize(100, 30); move_up_btn->setFixedSize(100, 30); move_down_btn->setFixedSize(100, 30); delete_btn->setFixedSize(100, 30); layout->addWidget(tableWidget_0, 0, 0, 5, 1); layout->addWidget(add_btn, 0, 1); layout->addWidget(activited_btn, 1, 1); layout->addWidget(move_up_btn, 2, 1); layout->addWidget(move_down_btn, 3, 1); layout->addWidget(delete_btn, 4, 1); layout->setColumnStretch(0, 8); layout->setColumnStretch(1, 2); widget->setLayout(layout); tableWidget_0->setMouseTracking(true); connect(tableWidget_0, SIGNAL(entered(QModelIndex)), this, SLOT(ShowTooltip(QModelIndex))); connect(add_btn, SIGNAL(clicked()), this, SLOT(add_btn_clicked())); connect(move_up_btn, SIGNAL(clicked()), this, SLOT(move_up_btn_clicked())); connect(move_down_btn, SIGNAL(clicked()), this, SLOT(move_down_btn_clicked())); connect(delete_btn, SIGNAL(clicked()), this, SLOT(delete_btn_clicked())); connect(activited_btn, SIGNAL(clicked()), this, SLOT(activited_btn_clicked())); workspace_count = 0; connect(context, &Context::workespaceAdded, this, &MainWindow::add_workspace_item); } void MainWindow::init_output_widget(QWidget *widget) { QGridLayout *layout = new QGridLayout(widget); tableWidget_1 = new QTableWidget(widget); QStringList col_list_lable; // 列标题 QLabel *label = new QLabel("Primary output :", widget); label->setFont(QFont("Helvetica")); pri_label = new QLabel(widget); pri_label->setStyleSheet("QLabel{background-color:rgb(192, 192, 192);}"); pri_label->setAutoFillBackground(true); pri_label->setAlignment(Qt::AlignCenter); pri_label->setGeometry(102, 4, 100, 25); tableWidget_1->setGeometry(0, 30, 100, 100); col_list_lable << QString("uuid"); col_list_lable << QString("name"); col_list_lable << QString("make"); col_list_lable << QString("model"); col_list_lable << QString("serial"); col_list_lable << QString("description"); col_list_lable << QString("phisical size"); col_list_lable << QString("capabilities"); col_list_lable << QString("modes"); col_list_lable << QString("current modes"); col_list_lable << QString("position"); col_list_lable << QString("transform"); col_list_lable << QString("scale"); col_list_lable << QString("enabled"); col_list_lable << QString("power"); col_list_lable << QString("brightness"); col_list_lable << QString("color_temp"); int col_list_lable_cnt = col_list_lable.count(); tableWidget_1->setColumnCount(col_list_lable_cnt); tableWidget_1->setHorizontalHeaderLabels(col_list_lable); tableWidget_1->resize(940, 240); tableWidget_1->horizontalScrollBar()->setEnabled(true); tableWidget_1->setEditTriggers(QAbstractItemView::NoEditTriggers); // 是否可编辑 tableWidget_1->setSelectionBehavior(QAbstractItemView::SelectRows); // 是否可选中 tableWidget_1->setStyleSheet("selection-background-color:pink"); tableWidget_1->setShowGrid(true); tableWidget_1->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); layout->addWidget(label, 0, 0); layout->addWidget(pri_label, 0, 1); layout->addWidget(tableWidget_1, 1, 0, 10, 10); widget->setLayout(layout); outputs_count = 0; tableWidget_1->setMouseTracking(true); connect(tableWidget_1, SIGNAL(entered(QModelIndex)), this, SLOT(ShowTooltip(QModelIndex))); connect(context, &Context::outputAdded, this, &MainWindow::add_output_item); } void MainWindow::init_toplevel_widget(QWidget *widget) { QVBoxLayout *layout = new QVBoxLayout(); widget->setLayout(layout); tableWidget_2 = new QTableWidget; layout->addWidget(tableWidget_2); tableWidget_2->setContextMenuPolicy(Qt::CustomContextMenu); connect(tableWidget_2, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(show_menu(QPoint))); QStringList col_list_lable; // 列标题 col_list_lable << QString("uuid"); col_list_lable << QString("title"); col_list_lable << QString("app_id"); col_list_lable << QString("icon"); col_list_lable << QString("position"); col_list_lable << QString("size"); col_list_lable << QString("capabilities"); col_list_lable << QString("parent"); col_list_lable << QString("primary output"); col_list_lable << QString("activited"); col_list_lable << QString("minimizad"); col_list_lable << QString("maximized"); col_list_lable << QString("fullscreen"); col_list_lable << QString("workespaces"); int col_list_lable_cnt = col_list_lable.count(); tableWidget_2->setColumnCount(col_list_lable_cnt); tableWidget_2->setHorizontalHeaderLabels(col_list_lable); tableWidget_2->horizontalScrollBar()->setEnabled(true); tableWidget_2->setEditTriggers(QAbstractItemView::NoEditTriggers); // 是否可编辑 tableWidget_2->setSelectionBehavior(QAbstractItemView::SelectRows); // 是否可选中 tableWidget_2->setStyleSheet("selection-background-color:pink"); tableWidget_2->setShowGrid(true); tableWidget_2->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); tableWidget_2->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); tableWidget_2->setMinimumSize(QSize(700, 500)); toplevel_count = 0; tableWidget_2->setMouseTracking(true); connect(tableWidget_2, SIGNAL(entered(QModelIndex)), this, SLOT(ShowTooltip(QModelIndex))); connect(context, &Context::toplevelAdded, this, &MainWindow::add_toplevel_item); } void MainWindow::ShowTooltip(QModelIndex index) { QToolTip::showText(QCursor::pos(), index.data().toString()); return; } void MainWindow::init_form() { QTabWidget *tabWidget = new QTabWidget(this); this->setCentralWidget(tabWidget); QWidget *pageWidget_0 = new QWidget; QWidget *pageWidget_1 = new QWidget; QWidget *pageWidget_2 = new QWidget; tabWidget->addTab(pageWidget_0, "workspace"); tabWidget->addTab(pageWidget_1, "output"); tabWidget->addTab(pageWidget_2, "toplevel"); tabWidget->resize(940, 300); init_workspace_widget(pageWidget_0); init_output_widget(pageWidget_1); init_toplevel_widget(pageWidget_2); } static int get_cur_rows(QTableWidget *tableWidget, QString uuid) { for (int i = 0; i < tableWidget->rowCount(); i++) { if (tableWidget->item(i, 0)->text() == uuid) return i; } return -1; } void MainWindow::update_output_item(Output::Masks mask) { Output *output = qobject_cast(sender()); int cur_row = get_cur_rows(tableWidget_1, output->uuid()); if (cur_row < 0) return; if (mask & Output::Mask::Enabled) { if (output->isEnabled()) tableWidget_1->item(cur_row, 13)->setText("yes"); else tableWidget_1->item(cur_row, 13)->setText("no"); } if (mask & Output::Mask::Mode) { Output::Mode cur_mode = output->curMode(); QString cur_m = QString("%1 x %2 px, %3 Hz") .arg(cur_mode.size.width()) .arg(cur_mode.size.height()) .arg(cur_mode.refresh); if (cur_mode.preferred) cur_m += " preferred"; tableWidget_1->item(cur_row, 9)->setText(cur_m); } if (mask & Output::Mask::Position) { QString position = QString("%1 , %2").arg(output->point().x()).arg(output->point().y()); tableWidget_1->item(cur_row, 10)->setText(position); } if (mask & Output::Mask::Transform) { QString transform = QString("%1").arg(output->transform()) + "°"; tableWidget_1->item(cur_row, 11)->setText(transform); } if (mask & Output::Mask::Scale) tableWidget_1->item(cur_row, 12)->setText(QString::number(output->scale(), 'f', 2)); if (mask & Output::Mask::Power) { if (output->isPower()) tableWidget_1->item(cur_row, 14)->setText("on"); else tableWidget_1->item(cur_row, 14)->setText("off"); } if (mask & Output::Mask::Primary) { if (output->isPrimary()) pri_label->setText(output->name()); } if (mask & Output::Mask::Brightness) tableWidget_1->item(cur_row, 15)->setText(QString("%1").arg(output->brightness())); if (mask & Output::Mask::ColorTemp) tableWidget_1->item(cur_row, 16)->setText(QString("%1").arg(output->colorTemp())); } void MainWindow::delete_output_item() { Output *output = qobject_cast(sender()); int cur_row = get_cur_rows(tableWidget_1, output->uuid()); if (cur_row < 0) return; tableWidget_1->removeRow(cur_row); // 删除 delete output; outputs_count--; } void MainWindow::add_output_item(Output *output) { int rows = tableWidget_1->rowCount(); int columns = tableWidget_1->columnCount(); if (outputs_count > (rows - 1)) tableWidget_1->insertRow(outputs_count); // 插入 for (int i = 0; i < columns; i++) { tableWidget_1->setItem(outputs_count, i, new QTableWidgetItem); tableWidget_1->setRowHeight(outputs_count, 30); tableWidget_1->item(outputs_count, i)->setTextAlignment(Qt::AlignCenter); // 居中显示 tableWidget_1->item(outputs_count, i)->setFont(QFont("Helvetica")); // 设置字体为黑体 } tableWidget_1->item(outputs_count, 0)->setText(output->uuid()); tableWidget_1->item(outputs_count, 1)->setText(output->name()); tableWidget_1->item(outputs_count, 2)->setText(output->make()); tableWidget_1->item(outputs_count, 3)->setText(output->model()); tableWidget_1->item(outputs_count, 4)->setText(output->serial()); tableWidget_1->item(outputs_count, 5)->setText(output->description()); QString phisical_size = QString("%1 x %2 mm") .arg(output->physicalSize().width()) .arg(output->physicalSize().height()); tableWidget_1->item(outputs_count, 6)->setText(phisical_size); QString caps; if (output->capabilities() & Output::Capability::Power) caps += "power "; if (output->capabilities() & Output::Capability::Brightness) caps += "brightness "; if (output->capabilities() & Output::Capability::ColorTemp) caps += "color_temp"; tableWidget_1->item(outputs_count, 7)->setText(caps); QComboBox *comBox_mode = new QComboBox(); QList modes = output->modes(); for (int i = 0; i < modes.size(); i++) { QString mode = QString("%1 x %2 px, %3 Hz") .arg(modes[i].size.width()) .arg(modes[i].size.height()) .arg(modes[i].refresh); if (modes[i].preferred) mode += " preferred"; comBox_mode->addItem(mode); } tableWidget_1->setCellWidget(outputs_count, 8, comBox_mode); if (output->isEnabled()) tableWidget_1->item(outputs_count, 13)->setText("yes"); else tableWidget_1->item(outputs_count, 13)->setText("no"); Output::Mode cur_mode = output->curMode(); QString cur_m = QString("%1 x %2 px, %3 Hz") .arg(cur_mode.size.width()) .arg(cur_mode.size.height()) .arg(cur_mode.refresh); if (cur_mode.preferred) cur_m += " preferred"; tableWidget_1->item(outputs_count, 9)->setText(cur_m); QString position = QString("%1 , %2").arg(output->point().x()).arg(output->point().y()); tableWidget_1->item(outputs_count, 10)->setText(position); QString transform = QString("%1").arg(output->transform()) + "°"; tableWidget_1->item(outputs_count, 11)->setText(transform); tableWidget_1->item(outputs_count, 12)->setText(QString::number(output->scale(), 'f', 2)); if (output->isPower()) tableWidget_1->item(outputs_count, 14)->setText("on"); else tableWidget_1->item(outputs_count, 14)->setText("off"); if (output->isPrimary()) pri_label->setText(output->name()); tableWidget_1->item(outputs_count, 15)->setText(QString("%1").arg(output->brightness())); tableWidget_1->item(outputs_count, 16)->setText(QString("%1").arg(output->colorTemp())); connect(output, &Output::stateUpdated, this, &MainWindow::update_output_item); connect(output, &Output::deleted, this, &MainWindow::delete_output_item); tableWidget_1->show(); outputs_count++; } void MainWindow::delete_toplevel_item() { Toplevel *toplevel = qobject_cast(sender()); int cur_row = get_cur_rows(tableWidget_2, toplevel->uuid()); if (cur_row < 0) return; tableWidget_2->removeRow(cur_row); // 删除 delete toplevel; toplevel_count--; } void MainWindow::update_toplevel_item(Toplevel::Masks mask) { Toplevel *toplevel = qobject_cast(sender()); int cur_row = get_cur_rows(tableWidget_2, toplevel->uuid()); if (cur_row < 0) return; if (mask & Toplevel::Mask::AppId) tableWidget_2->item(cur_row, 2)->setText(toplevel->appId()); if (mask & Toplevel::Mask::Title) tableWidget_2->item(cur_row, 1)->setText(toplevel->title()); if (mask & Toplevel::Mask::Activated) { if (toplevel->isActivated()) tableWidget_2->item(cur_row, 9)->setText("true"); else tableWidget_2->item(cur_row, 9)->setText("false"); } if (mask & Toplevel::Mask::Minimized) { if (toplevel->isMinimized()) tableWidget_2->item(cur_row, 10)->setText("true"); else tableWidget_2->item(cur_row, 10)->setText("false"); } if (mask & Toplevel::Mask::Maximized) { if (toplevel->isMaximized()) tableWidget_2->item(cur_row, 11)->setText("true"); else tableWidget_2->item(cur_row, 11)->setText("false"); } if (mask & Toplevel::Mask::Fullscreen) { if (toplevel->isFullscreen()) tableWidget_2->item(cur_row, 12)->setText("true"); else tableWidget_2->item(cur_row, 12)->setText("false"); } if (mask & Toplevel::Mask::PrimaryOutput) tableWidget_2->item(cur_row, 8)->setText(toplevel->primaryOutput()); if (mask & Toplevel::Mask::Workspace) { QStringList workspaces = toplevel->workspaces(); QComboBox *comBox_mode = new QComboBox(); if (!workspaces.isEmpty()) { for (int i = 0; i < workspaces.size(); i++) { comBox_mode->addItem(workspaces.at(i)); } } tableWidget_2->setCellWidget(cur_row, 13, comBox_mode); } if (mask & Toplevel::Mask::Parent) { Toplevel *parent = toplevel->parent(); if (parent) tableWidget_2->item(cur_row, 7)->setText(parent->uuid()); else tableWidget_2->item(cur_row, 7)->setText("NULL"); } if (mask & Toplevel::Mask::Position) { QString point = QString("%1 , %2").arg(toplevel->point().x()).arg(toplevel->point().y()); tableWidget_2->item(cur_row, 4)->setText(point); } if (mask & Toplevel::Mask::Size) { QString size = QString("%1 , %2").arg(toplevel->size().width()).arg(toplevel->size().height()); tableWidget_2->item(cur_row, 5)->setText(size); } if (mask & Toplevel::Mask::Icon) tableWidget_2->item(cur_row, 3)->setText(toplevel->icon()); } void MainWindow::add_toplevel_item(Toplevel *toplevel) { int rows = tableWidget_2->rowCount(); int columns = tableWidget_2->columnCount(); if (toplevel_count > (rows - 1)) tableWidget_2->insertRow(toplevel_count); // 插入 for (int i = 0; i < columns; i++) { tableWidget_2->setItem(toplevel_count, i, new QTableWidgetItem); tableWidget_2->setRowHeight(toplevel_count, 30); tableWidget_2->item(toplevel_count, i)->setTextAlignment(Qt::AlignCenter); // 居中显示 tableWidget_2->item(toplevel_count, i)->setFont(QFont("Helvetica")); // 设置字体为黑体 } tableWidget_2->item(toplevel_count, 0)->setText(toplevel->uuid()); QString point = QString("%1 , %2").arg(toplevel->point().x()).arg(toplevel->point().y()); tableWidget_2->item(toplevel_count, 4)->setText(point); QString size = QString("%1 , %2").arg(toplevel->size().width()).arg(toplevel->size().height()); tableWidget_2->item(toplevel_count, 5)->setText(size); QString caps; if (toplevel->capabilities() & Toplevel::Capability::Taskbar) caps += "taskbar "; if (toplevel->capabilities() & Toplevel::Capability::Switcher) caps += "switcher"; tableWidget_2->item(toplevel_count, 6)->setText(caps); tableWidget_2->item(toplevel_count, 2)->setText(toplevel->appId()); tableWidget_2->item(toplevel_count, 1)->setText(toplevel->title()); if (toplevel->isActivated()) tableWidget_2->item(toplevel_count, 9)->setText("true"); else tableWidget_2->item(toplevel_count, 9)->setText("false"); if (toplevel->isMinimized()) tableWidget_2->item(toplevel_count, 10)->setText("true"); else tableWidget_2->item(toplevel_count, 10)->setText("false"); if (toplevel->isMaximized()) tableWidget_2->item(toplevel_count, 11)->setText("true"); else tableWidget_2->item(toplevel_count, 11)->setText("false"); if (toplevel->isFullscreen()) tableWidget_2->item(toplevel_count, 12)->setText("true"); else tableWidget_2->item(toplevel_count, 12)->setText("false"); tableWidget_2->item(toplevel_count, 8)->setText(toplevel->primaryOutput()); QStringList workspaces = toplevel->workspaces(); QComboBox *comBox_mode = new QComboBox(); if (!workspaces.isEmpty()) { for (int i = 0; i < workspaces.size(); i++) comBox_mode->addItem(workspaces.at(i)); } tableWidget_2->setCellWidget(toplevel_count, 13, comBox_mode); Toplevel *parent = toplevel->parent(); if (parent) tableWidget_2->item(toplevel_count, 7)->setText(parent->uuid()); else tableWidget_2->item(toplevel_count, 7)->setText("NULL"); tableWidget_2->item(toplevel_count, 3)->setText(toplevel->icon()); tableWidget_2->show(); connect(toplevel, &Toplevel::stateUpdated, this, &MainWindow::update_toplevel_item); connect(toplevel, &Toplevel::deleted, this, &MainWindow::delete_toplevel_item); toplevel_count++; } void MainWindow::add_workspace_item(Workspace *workspace) { int rows = tableWidget_0->rowCount(); int columns = tableWidget_0->columnCount(); if (workspace_count > (rows - 1)) tableWidget_0->insertRow(workspace_count); // 插入 for (int i = 0; i < columns; i++) { tableWidget_0->setItem(workspace_count, i, new QTableWidgetItem); tableWidget_0->setRowHeight(workspace_count, 30); tableWidget_0->item(workspace_count, i)->setTextAlignment(Qt::AlignCenter); // 居中显示 tableWidget_0->item(workspace_count, i)->setFont(QFont("Helvetica")); // 设置字体为黑体 } tableWidget_0->item(workspace_count, 0)->setText(workspace->uuid()); tableWidget_0->item(workspace_count, 1)->setText(workspace->name()); tableWidget_0->item(workspace_count, 2)->setText(QString("%1").arg(workspace->position())); if (workspace->isActivated()) tableWidget_0->item(workspace_count, 3)->setText("true"); else tableWidget_0->item(workspace_count, 3)->setText("false"); connect(workspace, &Workspace::stateUpdated, this, &MainWindow::update_workspace_item); connect(workspace, &Workspace::deleted, this, &MainWindow::delete_workspace_item); workspace_count++; } void MainWindow::delete_workspace_item() { Workspace *workspace = qobject_cast(sender()); int cur_row = get_cur_rows(tableWidget_0, workspace->uuid()); if (cur_row < 0) return; tableWidget_0->removeRow(cur_row); // 删除 delete workspace; workspace_count--; } void MainWindow::update_workspace_item(Workspace::Masks mask) { Workspace *workspace = qobject_cast(sender()); int cur_row = get_cur_rows(tableWidget_0, workspace->uuid()); if (cur_row < 0) return; if (mask & Workspace::Mask::Name) tableWidget_0->item(cur_row, 1)->setText(workspace->name()); if (mask & Workspace::Mask::Position) tableWidget_0->item(cur_row, 2)->setText(QString("%1").arg(workspace->position())); if (mask & Workspace::Mask::Activated) { if (workspace->isActivated()) tableWidget_0->item(cur_row, 3)->setText("true"); else tableWidget_0->item(cur_row, 3)->setText("false"); } } void MainWindow::move_up_btn_clicked() { int cur_row = tableWidget_0->currentRow(); int columns = tableWidget_0->columnCount(); if (cur_row != 0) { tableWidget_0->insertRow(cur_row - 1); for (int i = 0; i < columns; ++i) { tableWidget_0->setItem( cur_row - 1, i, new QTableWidgetItem(tableWidget_0->item(cur_row + 1, i)->text())); tableWidget_0->item(cur_row - 1, i)->setTextAlignment(Qt::AlignCenter); // 居中显示 } tableWidget_0->removeRow(cur_row + 1); tableWidget_0->selectRow(cur_row - 1); QString uuid = tableWidget_0->item(tableWidget_0->currentRow(), 0)->text(); Workspace *workspace = context->findWorkspace(uuid); workspace->move(workspace->position() - 1); } } void MainWindow::move_down_btn_clicked() { int cur_row = tableWidget_0->currentRow(); int columns = tableWidget_0->columnCount(); if (cur_row < (tableWidget_0->rowCount() - 1)) { tableWidget_0->insertRow(cur_row + 2); // rowi为选中行的索引 for (int i = 0; i < columns; ++i) { tableWidget_0->setItem(cur_row + 2, i, new QTableWidgetItem(tableWidget_0->item(cur_row, i)->text())); tableWidget_0->item(cur_row + 2, i)->setTextAlignment(Qt::AlignCenter); } tableWidget_0->removeRow(cur_row); tableWidget_0->selectRow(cur_row + 1); QString uuid = tableWidget_0->item(tableWidget_0->currentRow(), 0)->text(); Workspace *workspace = context->findWorkspace(uuid); workspace->move(workspace->position() + 1); } } void MainWindow::delete_btn_clicked() { int cur_row = tableWidget_0->currentRow(); if (cur_row < 0) return; QString uuid = tableWidget_0->item(cur_row, 0)->text(); Workspace *workspace = context->findWorkspace(uuid); workspace->remove(); } void MainWindow::activited_btn_clicked() { int cur_row = tableWidget_0->currentRow(); if (cur_row < 0) return; QString uuid = tableWidget_0->item(cur_row, 0)->text(); Workspace *workspace = context->findWorkspace(uuid); workspace->setActivate(); } void MainWindow::add_btn_clicked() { context->addWorkspace(workspace_count); } void MainWindow::show_menu(const QPoint pos) { // 设置菜单选项 QMenu *menu = new QMenu(tableWidget_2); QAction *action1 = new QAction("set_maximized", tableWidget_2); QAction *action2 = new QAction("unset_maximized", tableWidget_2); QAction *action3 = new QAction("set_minimized", tableWidget_2); QAction *action4 = new QAction("unset_minimized", tableWidget_2); QAction *action5 = new QAction("set_fullscreen", tableWidget_2); QAction *action6 = new QAction("unset_fullscreen", tableWidget_2); QAction *action7 = new QAction("set_activate", tableWidget_2); QAction *action8 = new QAction("close", tableWidget_2); QAction *action9 = new QAction("enter_workspace", tableWidget_2); QAction *action10 = new QAction("leave_workspace", tableWidget_2); QAction *action11 = new QAction("toplevel_move_to_workspace", tableWidget_2); QAction *action12 = new QAction("send_to_output", tableWidget_2); menu->addAction(action1); menu->addAction(action2); menu->addAction(action3); menu->addAction(action4); menu->addAction(action5); menu->addAction(action6); menu->addAction(action7); menu->addAction(action8); menu->addAction(action9); menu->addAction(action10); menu->addAction(action11); menu->addAction(action12); menu->move(cursor().pos()); menu->show(); connect(action1, SIGNAL(triggered()), this, SLOT(toplevel_set_maximized())); connect(action2, SIGNAL(triggered()), this, SLOT(toplevel_unset_maximized())); connect(action3, SIGNAL(triggered()), this, SLOT(toplevel_set_minimized())); connect(action4, SIGNAL(triggered()), this, SLOT(toplevel_unset_minimized())); connect(action5, SIGNAL(triggered()), this, SLOT(toplevel_set_fullscreen())); connect(action6, SIGNAL(triggered()), this, SLOT(toplevel_unset_fullscreen())); connect(action7, SIGNAL(triggered()), this, SLOT(toplevel_set_activate())); connect(action8, SIGNAL(triggered()), this, SLOT(toplevel_close())); // 获得鼠标点击的x,y坐标点 int x = pos.x(); int y = pos.y(); QModelIndex index = tableWidget_2->indexAt(QPoint(x, y)); int row = index.row(); // 获得QTableWidget列表点击的行数 QMenu *moreWorspace = new QMenu(); for (int i = 0; i < tableWidget_0->rowCount(); i++) { QAction *action = new QAction(tableWidget_0->item(i, 1)->text()); moreWorspace->addAction(action); connect(action, SIGNAL(triggered()), this, SLOT(toplevel_enter_workspace())); } QMenu *leaveWorspaces = new QMenu(); for (int i = 0; i < tableWidget_0->rowCount(); i++) { QWidget *widget = tableWidget_2->cellWidget(row, 13); QComboBox *combox = (QComboBox *)widget; for (int j = 0; j < combox->count(); j++) { if (combox->itemText(j) == tableWidget_0->item(i, 0)->text()) { QAction *action = new QAction(tableWidget_0->item(i, 1)->text()); leaveWorspaces->addAction(action); connect(action, SIGNAL(triggered()), this, SLOT(toplevel_leave_workspace())); } } } QMenu *moveWorspace = new QMenu(); for (int i = 0; i < tableWidget_0->rowCount(); i++) { QAction *action = new QAction(tableWidget_0->item(i, 1)->text()); moveWorspace->addAction(action); connect(action, SIGNAL(triggered()), this, SLOT(toplevel_move_to_workspace())); } QWidget *widget = tableWidget_2->cellWidget(row, 13); QComboBox *combox = (QComboBox *)widget; if (combox->count() != 0) { action9->setMenu(moreWorspace); action10->setMenu(leaveWorspaces); action11->setMenu(moveWorspace); } QMenu *moreOutput = new QMenu(); for (int i = 0; i < tableWidget_1->rowCount(); i++) { QAction *action = new QAction(tableWidget_1->item(i, 1)->text()); moreOutput->addAction(action); connect(action, SIGNAL(triggered()), this, SLOT(toplevel_send_to_output())); } action12->setMenu(moreOutput); } void MainWindow::toplevel_set_maximized() { int row = tableWidget_2->currentRow(); QString output = tableWidget_2->item(row, 6)->text(); QString uuid = tableWidget_2->item(row, 0)->text(); Toplevel *toplevel = context->findToplevel(uuid); toplevel->setMaximized(output); } void MainWindow::toplevel_unset_maximized() { int row = tableWidget_2->currentRow(); QString output = tableWidget_2->item(row, 6)->text(); QString uuid = tableWidget_2->item(row, 0)->text(); Toplevel *toplevel = context->findToplevel(uuid); toplevel->unsetMaximized(); } void MainWindow::toplevel_set_minimized() { int row = tableWidget_2->currentRow(); QString uuid = tableWidget_2->item(row, 0)->text(); Toplevel *toplevel = context->findToplevel(uuid); toplevel->setMinimized(); } void MainWindow::toplevel_unset_minimized() { int row = tableWidget_2->currentRow(); QString uuid = tableWidget_2->item(row, 0)->text(); Toplevel *toplevel = context->findToplevel(uuid); toplevel->unsetMinimized(); } void MainWindow::toplevel_set_fullscreen() { int row = tableWidget_2->currentRow(); QString output = tableWidget_2->item(row, 6)->text(); QString uuid = tableWidget_2->item(row, 0)->text(); Toplevel *toplevel = context->findToplevel(uuid); toplevel->setFullscreen(output); } void MainWindow::toplevel_unset_fullscreen() { int row = tableWidget_2->currentRow(); QString uuid = tableWidget_2->item(row, 0)->text(); Toplevel *toplevel = context->findToplevel(uuid); toplevel->unsetFullscreen(); } void MainWindow::toplevel_set_activate() { int row = tableWidget_2->currentRow(); QString uuid = tableWidget_2->item(row, 0)->text(); Toplevel *toplevel = context->findToplevel(uuid); toplevel->setActivate(); } void MainWindow::toplevel_close() { int row = tableWidget_2->currentRow(); QString uuid = tableWidget_2->item(row, 0)->text(); Toplevel *toplevel = context->findToplevel(uuid); toplevel->close(); } void MainWindow::toplevel_enter_workspace() { QAction *action = qobject_cast(sender()); int row = tableWidget_2->currentRow(); QString uuid = tableWidget_2->item(row, 0)->text(); Toplevel *toplevel = context->findToplevel(uuid); for (int i = 0; i < tableWidget_0->rowCount(); i++) { if (tableWidget_0->item(i, 1)->text() == action->text()) { QString workspace = tableWidget_0->item(i, 0)->text(); toplevel->enterWorkspace(workspace); } } } void MainWindow::toplevel_leave_workspace() { QAction *action = qobject_cast(sender()); int row = tableWidget_2->currentRow(); QString uuid = tableWidget_2->item(row, 0)->text(); Toplevel *toplevel = context->findToplevel(uuid); for (int i = 0; i < tableWidget_0->rowCount(); i++) { if (tableWidget_0->item(i, 1)->text() == action->text()) { QString workspace = tableWidget_0->item(i, 0)->text(); toplevel->leaveWorkspace(workspace); } } } void MainWindow::toplevel_move_to_workspace() { QAction *action = qobject_cast(sender()); int row = tableWidget_2->currentRow(); QString uuid = tableWidget_2->item(row, 0)->text(); Toplevel *toplevel = context->findToplevel(uuid); for (int i = 0; i < tableWidget_0->rowCount(); i++) { if (tableWidget_0->item(i, 1)->text() == action->text()) { QString workspace = tableWidget_0->item(i, 0)->text(); toplevel->moveToWorkspace(workspace); } } } void MainWindow::toplevel_send_to_output() { QAction *action = qobject_cast(sender()); int row = tableWidget_2->currentRow(); QString uuid = tableWidget_2->item(row, 0)->text(); Toplevel *toplevel = context->findToplevel(uuid); for (int i = 0; i < tableWidget_1->rowCount(); i++) { if (tableWidget_1->item(i, 1)->text() == action->text()) { QString output = tableWidget_1->item(i, 0)->text(); toplevel->moveToOutput(output); } } } ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch-wlcom/workspace.cpp000066400000000000000000000065601522363675600275330ustar00rootroot00000000000000/* * Copyright (C) 2024, KylinSoft Co., Ltd. * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "context.h" #include class Workspace::Private { public: Private(Workspace *workspace); ~Private(); void setup(kywc_workspace *workspace); QString uuid; QString name; uint32_t position; bool activated; kywc_workspace *k_workspace; private: Workspace *w_space; static void stateHandle(kywc_workspace *workspace, uint32_t mask); static void destroyHandle(kywc_workspace *workspace); static struct kywc_workspace_interface workspace_impl; }; Workspace::Private::Private(Workspace *workspace) : w_space(workspace) {} Workspace::Private::~Private() {} void Workspace::Private::stateHandle(kywc_workspace *workspace, uint32_t mask) { Workspace *w = (Workspace *)kywc_workspace_get_user_data(workspace); Workspace::Masks masks; if (mask & KYWC_WORKSPACE_STATE_NAME) masks |= Workspace::Mask::Name; if (mask & KYWC_WORKSPACE_STATE_POSITION) masks |= Workspace::Mask::Position; if (mask & KYWC_WORKSPACE_STATE_ACTIVATED) masks |= Workspace::Mask::Activated; w->pri->name = QString(workspace->name); w->pri->position = workspace->position; w->pri->activated = workspace->activated; emit w->stateUpdated(masks); } void Workspace::Private::destroyHandle(kywc_workspace *workspace) { Workspace *w = (Workspace *)kywc_workspace_get_user_data(workspace); emit w->deleted(); } struct kywc_workspace_interface Workspace::Private::workspace_impl = { stateHandle, destroyHandle, }; void Workspace::Private::setup(kywc_workspace *workspace) { uuid = workspace->uuid; name = workspace->name; position = workspace->position; activated = workspace->activated; k_workspace = workspace; kywc_workspace_set_user_data(workspace, w_space); kywc_workspace_set_interface(workspace, &workspace_impl); } Workspace::Workspace(QObject *parent) : pri(new Private(this)) {} Workspace::~Workspace() {} void Workspace::setup(kywc_workspace *workspace) { pri->setup(workspace); } QString Workspace::name() const { return pri->name; } QString Workspace::uuid() const { return pri->uuid; } int Workspace::position() const { return pri->position; } bool Workspace::isActivated() const { return pri->activated; } void Workspace::setActivate() { kywc_workspace_activate(pri->k_workspace); } void Workspace::move(int position) { kywc_workspace_set_position(pri->k_workspace, position); } void Workspace::remove() { kywc_workspace_remove(pri->k_workspace); } void Workspace::setName(const QString name) { kywc_workspace_set_name(pri->k_workspace, name.toLocal8Bit().data()); } ukui-window-switch-4.21.1.0/windowsview/ukui-window-switch.desktop000077500000000000000000000004561522363675600253060ustar00rootroot00000000000000[Desktop Entry] Name=ukui-window-switch Name[zh_CN]=多任务视图 Exec=/usr/bin/ukui-window-switch #Icon=ukui-window-switch Terminal=false Type=Application NoDisplay=true OnlyShowIn=UKUI X-UKUI-Autostart-Delay=3 X-UKUI-Autostart-Phase=Application X-UKUI-Autostart-Notify=true X-UKUI-AutoRestart=true ukui-window-switch-4.21.1.0/windowsview/windowmanagerinterface.cpp000066400000000000000000000457251522363675600253660ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "windowmanagerinterface.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ukui-window-switch-wlcom/multitaskviewmodelbywlcomhandler.h" static constexpr int MAX_DESKTOP_COUNT = 15; static const QString UKUI_STYLE_SCHEMA = "org.ukui.style"; static const QString UKUI_STYLE_SCHEMA_STYLENAME = "styleName"; static const QString UKUI_STYLE_SCHEMA_FONTSIZE = "systemFontSize"; static const QString UKUI_STYLE_SCHEMA_FONT = "systemFont"; static const QString UKUI_STYLE_SCHEMA_WIDGETNAME = "widgetThemeName"; const QString IGNORE_WINDOW_CONFIG = "/usr/share/ukui/ukui-panel/panel-commission.ini"; static const QString DESKTOP_NAME = "desktop-name"; const QString DESKTOP_CONFIG_DIR = QDir::homePath() + QStringLiteral("/.config/org.ukui/ukui-window-switch/"); const QString DESKTOP_CONFIG = DESKTOP_CONFIG_DIR + QStringLiteral("multitaskview.conf"); const QString UKUI_FRAMEWORK_SERVICE = "org.ukui.Framework"; const QString UKUI_FRAMEWORK_MOUSE_PATH = "/org/ukui/Framework/Devices/Mouse"; const QString UKUI_FRAMEWORK_MOUSE_INTERFACE = "org.ukui.Framework.Devices.Mouse"; const QString UKUI_FRAMEWORK_TOUCHPAD_PATH = "/org/ukui/Framework/Devices/Touchpad"; const QString UKUI_FRAMEWORK_TOUCHPAD_INTERFACE = "org.ukui.Framework.Devices.Touchpad"; WindowManagerInterface *WindowManagerInterface::getInstance() { static WindowManagerInterface s_interface; return &s_interface; } WindowManagerInterface::WindowManagerInterface(QObject *parent) : QObject(parent) { m_modelhandler = new MultitaskViewModelByWlcomHandler(this); m_screenManager = new ScreensManager(this); initTouchState(); connectSignals(); if (QGSettings::isSchemaInstalled(UKUI_STYLE_SCHEMA.toUtf8())) { m_settings = new QGSettings(UKUI_STYLE_SCHEMA.toUtf8()); } updateScreenRectList(); QList screenList = m_screenManager->screens(); for (const auto &screen : screenList) { connect(screen, &Screen::geometryChanged, this, &WindowManagerInterface::onScreenSizeChanged); } } WindowManagerInterface::~WindowManagerInterface() { if (m_modelhandler != nullptr) { delete m_modelhandler; m_modelhandler = nullptr; } } bool WindowManagerInterface::currentDesktopHasWindow() const { for (int screenIndex = 0; screenIndex < logicalScreenCount(); screenIndex++) { if (m_modelhandler->createWindowList(getCurrentDesktop(), screenIndex).size() > 0) { return true; } } return false; } void WindowManagerInterface::setDesktopName(const int desktopIndex, const QString name) { if (!validateDesktopIndex(desktopIndex)) { return; } m_modelhandler->setDesktopName(desktopIndex, name); } QString WindowManagerInterface::getDesktopUuid(int desktopIndex) { if (!validateDesktopIndex(desktopIndex)) { return QString(); } return m_modelhandler->getDesktopUuid(desktopIndex); } QString WindowManagerInterface::getOutputUuid(int outputIndex) { return m_modelhandler->getOutputUuid(outputIndex); } void WindowManagerInterface::removeAppWindow(QString windowId) { m_modelhandler->removeAppWindow(windowId); } void WindowManagerInterface::removeAllAppWindowOnDesktop(int desktopIndex, int screenIndex) { QList windowList; windowList = m_modelhandler->createWindowList(desktopIndex, screenIndex); for (Window &window : windowList) { m_modelhandler->removeAppWindow(window.uuid()); } } int WindowManagerInterface::getNumberOfDesktops() const { return m_modelhandler->getNumberOfDesktops(); } void WindowManagerInterface::moveAppWindowToDesktop(QString windowId, int srcDesktopInex, int destDesktopInex) const { m_modelhandler->moveAppWindowToDesktop(windowId, srcDesktopInex, destDesktopInex); } void WindowManagerInterface::activateAppWindow(QString windowId) { m_modelhandler->activateAppWindow(windowId); } QVariant WindowManagerInterface::getWindowIcon(QString windowId) { return m_modelhandler->getWindowIcon(windowId); } void WindowManagerInterface::removeDesktop(int desktopIndex) { if (m_modelhandler->getNumberOfDesktops() <= 1) { return; } if (!validateDesktopIndex(desktopIndex)) { return; } m_modelhandler->removeDesktop(desktopIndex); } void WindowManagerInterface::appendDesktop() { if (m_modelhandler->getNumberOfDesktops() >= MAX_DESKTOP_COUNT) { return; } m_modelhandler->appendDesktop(); } void WindowManagerInterface::moveDesktop(int srcDesktopIndex, int destDesktopIndex) { if (srcDesktopIndex == destDesktopIndex) { return; } m_modelhandler->moveDesktop(srcDesktopIndex, destDesktopIndex); } QList WindowManagerInterface::createWindowList(int desktopIndex, int screenIndex) { return m_modelhandler->createWindowList(desktopIndex, screenIndex); } int WindowManagerInterface::getCurrentDesktop() const { return m_modelhandler->getCurrentDesktop(); } bool WindowManagerInterface::isCurrentDesktopShowingDesktop() const { return m_modelhandler->isCurrentDesktopShowingDesktop(); } void WindowManagerInterface::setCurrentDesktop(int desktopIndex) { if (!validateDesktopIndex(desktopIndex)) { return; } m_modelhandler->setCurrentDesktop(desktopIndex); } QRect WindowManagerInterface::getFullScreenGeometry(int desktopIndex, int screenIndex) const { return m_modelhandler->getFullScreenGeometry(desktopIndex, screenIndex); } bool WindowManagerInterface::hasModalChildWindow(QString windowId) { return m_modelhandler->hasModalChildWindow(windowId); } QString WindowManagerInterface::getUKUIStyleName() const { // default to ukui-default QString styleName = "ukui-default"; if (m_settings && m_settings->keys().contains(UKUI_STYLE_SCHEMA_STYLENAME)) { styleName = m_settings->get(UKUI_STYLE_SCHEMA_STYLENAME).toString(); } else { qWarning() << QString("未查询到Gesetting的键值(%1)").arg(UKUI_STYLE_SCHEMA_STYLENAME); } return styleName; } double WindowManagerInterface::getUKUIFontSize() const { // default to 11 double fontSize = 11; if (m_settings && m_settings->keys().contains(UKUI_STYLE_SCHEMA_FONTSIZE)) { fontSize = m_settings->get(UKUI_STYLE_SCHEMA_FONTSIZE).toDouble(); } else { qWarning() << QString("未查询到Gesetting的键值(%1)").arg(UKUI_STYLE_SCHEMA_FONTSIZE); } return fontSize; } QString WindowManagerInterface::getUKUIFont() const { // default to 11 QString font = "Noto Sans CJK SC"; if (m_settings && m_settings->keys().contains(UKUI_STYLE_SCHEMA_FONT)) { font = m_settings->get(UKUI_STYLE_SCHEMA_FONT).toString(); } else { qWarning() << QString("未查询到Gesetting的键值(%1)").arg(UKUI_STYLE_SCHEMA_FONT); } return font; } void WindowManagerInterface::setIsOpenGLBackend(bool isOpenGLBackend) { m_isOpenGLBackend = isOpenGLBackend; } int WindowManagerInterface::getRadius(QString type) const { return m_isOpenGLBackend ? getUKUIRadius(type) : 0; } int WindowManagerInterface::getUKUIRadius(QString type) const { // default to 8 QString widgetName = "default"; if (m_settings && m_settings->keys().contains(UKUI_STYLE_SCHEMA_WIDGETNAME)) { widgetName = m_settings->get(UKUI_STYLE_SCHEMA_WIDGETNAME).toString(); } else { qWarning() << QString("未查询到Gesetting的键值(%1)").arg(UKUI_STYLE_SCHEMA_WIDGETNAME); return 8; } QFile file(QString("/usr/share/qt5-ukui-platformtheme/themeconfig/%1.json").arg(widgetName)); if (!file.open(QIODevice::ReadOnly)) { qWarning() << "无法打开JSON文件"; return 8; } QByteArray jsonData = file.readAll(); file.close(); // 将JSON数据转换为QJsonDocument对象 QJsonParseError error; QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData, &error); if (error.error != QJsonParseError::NoError) { qWarning() << "JSON格式错误:" << error.errorString(); return 8; } // 获取属性 QJsonObject rootObj = jsonDoc.object(); QJsonObject radiusObj = rootObj["Radius"].toObject(); QJsonObject radiusValueObj = radiusObj[type].toObject(); return radiusValueObj["value"].toString().toInt(); } bool WindowManagerInterface::isExtensionMode() { return m_modelhandler->isExtensionMode(); } int WindowManagerInterface::logicalScreenCount() const { return m_modelhandler->logicalScreenCount(); } bool WindowManagerInterface::isTabletMode() const { // default to PC mode. bool tabletMode = false; QDBusMessage message = QDBusMessage::createMethodCall("com.kylin.statusmanager.interface", "/", "com.kylin.statusmanager.interface", "get_current_tabletmode"); QDBusMessage response = QDBusConnection::sessionBus().call(message); if (response.type() == QDBusMessage::ReplyMessage) { tabletMode = response.arguments().takeFirst().toBool(); } else { qDebug() << "get tablet mode failed " << response.type(); } return tabletMode; } bool WindowManagerInterface::isTouchState() const { return m_isTouchState; } QStringList WindowManagerInterface::getDesktopNames() const { QSettings desktopSettings(DESKTOP_CONFIG, QSettings::IniFormat); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) desktopSettings.setIniCodec("utf-8"); #endif QStringList nameList = desktopSettings.value("desktops/name").toStringList(); return nameList; } void WindowManagerInterface::saveDesktopNames(const QStringList &nameList) { QDir configDir; if (!configDir.exists(DESKTOP_CONFIG_DIR)) { configDir.mkdir(DESKTOP_CONFIG_DIR); } QSettings desktopSettings(DESKTOP_CONFIG, QSettings::IniFormat); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) desktopSettings.setIniCodec("utf-8"); #endif desktopSettings.beginGroup("desktops"); desktopSettings.setValue("name", QVariant(nameList)); desktopSettings.endGroup(); //qDebug() << "[MultitaskViewModel] save custom desktop names" << desktopSettings.value("desktops/name").toStringList(); } QList WindowManagerInterface::screenRectList() { return m_screenRectList; } void WindowManagerInterface::updateScreenRectList() { m_screenRectList = QList(); QList screenList = m_screenManager->screens(); for (int index = 0; index < screenList.size(); ++index) { m_screenRectList.append(screenList[index]->geometry()); } emit screenRectListChanged(); } QString WindowManagerInterface::getCurrentLanguage() const { // default to "Chinese". QLocale locale = QLocale::system(); QString language = "Chinese"; if (locale.language() == QLocale::Chinese) { language = "Chinese"; } else if (locale.language() == QLocale::Tibetan) { language = "Tibetan"; } return language; } bool WindowManagerInterface::validateDesktopIndex(int desktopIndex) const { return desktopIndex >= 1 && desktopIndex <= m_modelhandler->getNumberOfDesktops(); } bool WindowManagerInterface::validateScreenIndex(int screenIndex) const { return screenIndex >= 0 || screenIndex < logicalScreenCount(); } void WindowManagerInterface::connectSignals() { QObject::connect(m_modelhandler, &MultitaskViewAbstractModelHandler::currentDesktopChanged, this, &WindowManagerInterface::currentDesktopChanged, Qt::QueuedConnection); QObject::connect(m_modelhandler, &MultitaskViewAbstractModelHandler::desktopNumberChanged, this, &WindowManagerInterface::desktopNumberChanged, Qt::QueuedConnection); QObject::connect(m_modelhandler, &MultitaskViewAbstractModelHandler::desktopRemoved, this, &WindowManagerInterface::desktopRemoved, Qt::QueuedConnection); QObject::connect(m_modelhandler, &MultitaskViewAbstractModelHandler::desktopAppended, this, &WindowManagerInterface::desktopAppended, Qt::QueuedConnection); QObject::connect(m_modelhandler, &MultitaskViewAbstractModelHandler::desktopMoved, this, &WindowManagerInterface::desktopMoved, Qt::QueuedConnection); QObject::connect(m_modelhandler, &MultitaskViewAbstractModelHandler::appWindowCreated, this, &WindowManagerInterface::appWindowCreated, Qt::QueuedConnection); QObject::connect(m_modelhandler, &MultitaskViewAbstractModelHandler::appWindowAdd, this, &WindowManagerInterface::appWindowAdd, Qt::QueuedConnection); QObject::connect(m_modelhandler, &MultitaskViewAbstractModelHandler::appWindowRemoved, this, &WindowManagerInterface::appWindowRemoved, Qt::QueuedConnection); QObject::connect(m_modelhandler, &MultitaskViewAbstractModelHandler::appWindowActivated, this, &WindowManagerInterface::appWindowActivated, Qt::QueuedConnection); QObject::connect(m_modelhandler, &MultitaskViewAbstractModelHandler::appWindowUpdated, this, &WindowManagerInterface::appWindowUpdated, Qt::QueuedConnection); QObject::connect(m_modelhandler, &MultitaskViewAbstractModelHandler::appWindowDesktopChanged, this, &WindowManagerInterface::appWindowDesktopChanged, Qt::QueuedConnection); QObject::connect(m_modelhandler, &MultitaskViewAbstractModelHandler::screenSizeChanged, this, &WindowManagerInterface::onScreenSizeChanged, Qt::QueuedConnection); connect(m_screenManager, &ScreensManager::screenAdded, this, &WindowManagerInterface::onScreenAdd); connect(m_screenManager, &ScreensManager::screenRemoved, this, &WindowManagerInterface::onScreenRemove); QDBusConnection::sessionBus().connect(UKUI_FRAMEWORK_SERVICE, UKUI_FRAMEWORK_MOUSE_PATH, UKUI_FRAMEWORK_MOUSE_INTERFACE, "MouseCountChanged", this, SLOT(onMouseCountChanged(const int))); QDBusConnection::sessionBus().connect(UKUI_FRAMEWORK_SERVICE, UKUI_FRAMEWORK_TOUCHPAD_PATH, UKUI_FRAMEWORK_TOUCHPAD_INTERFACE, "TouchpadChanged", this, SLOT(onTouchpadCountChanged(const int))); QDBusConnection::sessionBus().connect("com.kylin.statusmanager.interface", "/", "com.kylin.statusmanager.interface", "mode_change_signal", this, SIGNAL(tabletModeChanged(bool))); } void WindowManagerInterface::onMouseCountChanged(const int count) { m_flagNeedGetMouse = false; if (count == -1) { // 接口返回 -1 代表获取设备数量失败 qDebug() << UKUI_FRAMEWORK_SERVICE << "mouse count reply -1, keep default"; return; } m_mouseAvailable = count > 0 ? true : false; updateTouchState(); } void WindowManagerInterface::onTouchpadCountChanged(const int count) { m_flagNeedGetTouchpad = false; if (count == -1) { // 接口返回 -1 代表获取设备数量失败 qDebug() << UKUI_FRAMEWORK_SERVICE << "touchpad count reply -1, keep default"; return; } m_touchpadAvailable = count > 0 ? true : false; updateTouchState(); } void WindowManagerInterface::initTouchState() { asyncGetGenericPointerCount(UKUI_FRAMEWORK_SERVICE, UKUI_FRAMEWORK_MOUSE_PATH, UKUI_FRAMEWORK_MOUSE_INTERFACE, "GetMouseCount"); asyncGetGenericPointerCount(UKUI_FRAMEWORK_SERVICE, UKUI_FRAMEWORK_TOUCHPAD_PATH, UKUI_FRAMEWORK_TOUCHPAD_INTERFACE, "GetTouchpadCount"); } void WindowManagerInterface::updateTouchState() { bool currentState = !(m_mouseAvailable || m_touchpadAvailable); if (m_isTouchState == currentState) { return; } m_isTouchState = currentState; emit touchStateChanged(m_isTouchState); } void WindowManagerInterface::asyncGetGenericPointerCount(const QString &destination, const QString &path, const QString &interface, const QString &method) { QDBusMessage message = QDBusMessage::createMethodCall(destination, path, interface, method); QDBusPendingCall pendingCall = QDBusConnection::sessionBus().asyncCall(message); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pendingCall); QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [method, this](QDBusPendingCallWatcher *w) { QDBusPendingReply reply = *w; w->deleteLater(); if (!reply.isValid()) { qDebug() << "Error:" << reply.error().message(); return; } if (method.contains("Mouse") && this->m_flagNeedGetMouse) { this->onMouseCountChanged(reply.value()); } else if (method.contains("Touchpad") && this->m_flagNeedGetTouchpad) { this->onTouchpadCountChanged(reply.value()); } }); } void WindowManagerInterface::onScreenSizeChanged() { emit screenSizeChanged(); updateScreenRectList(); } // 屏幕增加时,先更新屏幕列表,再发送信号screenCountChanged;屏幕移除时,反之 // 否则qml读取screenRect时会报错,如:MultitaskView.qml:84: TypeError: Cannot read property 'height' of undefined void WindowManagerInterface::onScreenAdd(Screen *screen) { if (screen != nullptr) { connect(screen, &Screen::geometryChanged, this, &WindowManagerInterface::onScreenSizeChanged); } updateScreenRectList(); emit screenCountChanged(); } void WindowManagerInterface::onScreenRemove() { emit screenCountChanged(); updateScreenRectList(); } ukui-window-switch-4.21.1.0/windowsview/windowmanagerinterface.h000066400000000000000000000130041522363675600250140ustar00rootroot00000000000000/* * Copyright (C) 2022, KylinSoft Co., Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef WINDOWMANAGERINTERFACE_H #define WINDOWMANAGERINTERFACE_H #include #include #include #include #include #include #include #include "multitaskviewabstractmodelhandler.h" #include "screens-manager.h" class QGSettings; class Window; class WindowManagerInterface : public QObject { Q_OBJECT Q_PROPERTY(int logicalScreenCount READ logicalScreenCount NOTIFY screenCountChanged) Q_PROPERTY(int highlightDesktop READ getCurrentDesktop WRITE setCurrentDesktop NOTIFY currentDesktopChanged) Q_PROPERTY(bool isTabletMode READ isTabletMode NOTIFY tabletModeChanged) Q_PROPERTY(bool isTouchState READ isTouchState NOTIFY touchStateChanged) Q_PROPERTY(QList screenRectList READ screenRectList NOTIFY screenRectListChanged) public: static WindowManagerInterface *getInstance(); ~WindowManagerInterface(); Q_INVOKABLE QString getCurrentLanguage() const; Q_INVOKABLE QString getUKUIStyleName() const; Q_INVOKABLE double getUKUIFontSize() const; Q_INVOKABLE QString getUKUIFont() const; Q_INVOKABLE int getRadius(QString type) const; void setIsOpenGLBackend(bool isOpenGLBackend); Q_INVOKABLE QRect getFullScreenGeometry(int desktopIndex, int screenIndex) const; // window Q_INVOKABLE void removeAppWindow(QString windowId); Q_INVOKABLE void moveAppWindowToDesktop(QString windowId, int srcDesktopInex, int destDesktopInex) const; Q_INVOKABLE void activateAppWindow(QString windowId); Q_INVOKABLE QVariant getWindowIcon(QString windowId); Q_INVOKABLE bool hasModalChildWindow(QString windowId); // desktop Q_INVOKABLE void removeDesktop(int desktopIndex); Q_INVOKABLE void moveDesktop(int srcDesktopIndex, int destDesktopIndex); Q_INVOKABLE void appendDesktop(); Q_INVOKABLE void setCurrentDesktop(int desktopIndex); Q_INVOKABLE QList createWindowList(int desktopIndex, int screenIndex); Q_INVOKABLE QString getDesktopUuid(int desktopIndex); Q_INVOKABLE QString getOutputUuid(int outputIndex); Q_INVOKABLE void removeAllAppWindowOnDesktop(int desktopIndex, int screenIndex); Q_INVOKABLE bool isCurrentDesktopShowingDesktop() const; Q_INVOKABLE bool currentDesktopHasWindow() const; void setDesktopName(const int desktopIndex, const QString name); int getNumberOfDesktops() const; int getCurrentDesktop() const; int logicalScreenCount() const; bool isTabletMode() const; bool isTouchState() const; QStringList getDesktopNames() const; void saveDesktopNames(const QStringList &nameList); QList screenRectList(); void updateScreenRectList(); signals: void appWindowCreated(); void appWindowAdd(const Window &window); void appWindowRemoved(QString windowId); void appWindowUpdated(const Window &window); void appWindowActivated(); void appWindowDesktopChanged(QString windowId, int oldDesktopIndex,int newDesktopIndex); void desktopRemoved(int desktopIndex); void desktopAppended(int desktopIndex); void desktopMoved(int oldDesktopIndex, int newDesktopIndex); void desktopNumberChanged(); void currentDesktopChanged(int oldCurrentDesktopIndex, int newCurrentDesktopIndex); void screenCountChanged(); void screenSizeChanged(); void tabletModeChanged(bool); void touchStateChanged(bool); void screenRectListChanged(); void logicalScreenCountChanged(); private slots: void onMouseCountChanged(const int count); void onTouchpadCountChanged(const int count); void onScreenSizeChanged(); void onScreenAdd(Screen *screen); void onScreenRemove(); private: explicit WindowManagerInterface(QObject *parent = nullptr); bool isExtensionMode(); bool validateDesktopIndex(int desktopIndex) const; bool validateScreenIndex(int screenIndex) const; void connectSignals(); int getUKUIRadius(QString type) const; /** * @brief "TouchState"是否处于无鼠标触摸屏场景 */ void initTouchState(); void updateTouchState(); /** * @brief 异步获取指针类设备数量 * @param 获取某类设备的dbus方法名称 * @param callback */ void asyncGetGenericPointerCount(const QString &destination, const QString &path, const QString &interface, const QString &method); private: QGSettings* m_settings = nullptr; bool m_isOpenGLBackend = true; MultitaskViewAbstractModelHandler *m_modelhandler = nullptr; bool m_isTouchState = false; bool m_mouseAvailable = true; bool m_touchpadAvailable = true; bool m_flagNeedGetMouse = true; bool m_flagNeedGetTouchpad = true; ScreensManager *m_screenManager = nullptr; QList m_screenRectList; }; #endif // WINDOWMANAGERINTERFACE_H