ukui-sni/0000775000175000017500000000000015160527101011242 5ustar fengfengukui-sni/dbus/0000775000175000017500000000000015153755017012212 5ustar fengfengukui-sni/dbus/org.freedesktop.DBus.Properties.xml0000664000175000017500000000221015153755017021017 0ustar fengfeng ukui-sni/dbus/org.kde.StatusNotifierWatcher.xml0000664000175000017500000000313215153755017020564 0ustar fengfeng ukui-sni/dbus/org.kde.StatusNotifierItem.xml0000664000175000017500000000650415153755017020073 0ustar fengfeng ukui-sni/LICENSE0000664000175000017500000010575515153755017012277 0ustar fengfeng GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ukui-sni/README.md0000664000175000017500000000064315153755017012537 0ustar fengfeng# ukui-sni #### 介绍 ukui-sni是ukui桌面环境中系统托盘服务相关功能的集合。 托盘功能基于[ukui4托盘协议](https://yayqg9ul2g.feishu.cn/docx/Q1Ptd8S0VoKryFxUQFxcbRS4n4g)。 #### status-notifier-host 用于实现可视化托盘区域功能的接口。 #### status-notifier-watcher sni协议中的Watcher服务实现。 #### ukui-system-tray 可视化托盘插件(会显示在任务栏上)ukui-sni/man/0000775000175000017500000000000015153755611012030 5ustar fengfengukui-sni/man/xembed-sni-proxy.10000664000175000017500000000046115153755611015325 0ustar fengfeng.TH XEMBED-SNI-PROXY 1 .SH NAME xembed-sni-proxy \- XEmbed to Status Notifier Item proxy .SH SYNOPSIS .B xembed-sni-proxy .SH DESCRIPTION .B xembed-sni-proxy converts legacy XEmbed system tray icons to the Status Notifier Item protocol. .SH SEE ALSO .BR ukui-sni-watcher (1) .SH AUTHOR KylinSoft Co., Ltd.ukui-sni/man/ukui-sni-watcher.10000664000175000017500000000050315153755611015307 0ustar fengfeng.TH UKUI-SNI-WATCHER 1 .SH NAME ukui-sni-watcher \- Status Notifier Item watcher .SH SYNOPSIS .B ukui-sni-watcher .SH DESCRIPTION .B ukui-sni-watcher is a backend service that implements the Status Notifier Item protocol for the UKUI desktop environment. .SH SEE ALSO .BR xembed-sni-proxy (1) .SH AUTHOR KylinSoft Co., Ltd.ukui-sni/ukui-system-tray/0000775000175000017500000000000015153755611014531 5ustar fengfengukui-sni/ukui-system-tray/translations/0000775000175000017500000000000015153755611017252 5ustar fengfengukui-sni/ukui-system-tray/translations/ukui-system-tray_zh_CN.ts0000664000175000017500000000102615153755611024156 0ustar fengfeng TrayView Folding display icon 折叠显示图标 Expand hidden icon 展开隐藏图标 ukui-sni/ukui-system-tray/widget/0000775000175000017500000000000015153755017016014 5ustar fengfengukui-sni/ukui-system-tray/widget/ui/0000775000175000017500000000000015153755611016431 5ustar fengfengukui-sni/ukui-system-tray/widget/ui/ControlPanel.qml0000664000175000017500000000743615153755611021556 0ustar fengfengimport QtQuick 2.15 import QtQuick.Controls 2.15 import QtQml.Models 2.15 import org.ukui.systemTray 1.0 import org.ukui.quick.items 1.0 as UkuiItems ListView { id: controlPanelView height: dropArea.isHorizontal ? dropArea.scaleFactor * 40 : count * dropArea.scaleFactor * 26 + (count - 1) * spacing; width: dropArea.isHorizontal ? count * dropArea.scaleFactor * 26 + (count - 1) * spacing : dropArea.scaleFactor * 40 orientation: dropArea.isHorizontal ? ListView.Horizontal : ListView.Vertical layoutDirection: ListView.RightToLeft verticalLayoutDirection: ListView.Qt.BottomToTop spacing: 0 interactive: false model: DelegateModel { id: panelModel model: ControlPanelModel delegate: MouseArea { width: dropArea.isHorizontal ? dropArea.scaleFactor * 26 : dropArea.scaleFactor * 40 height: dropArea.isHorizontal ? dropArea.scaleFactor * 40 : dropArea.scaleFactor * 26 acceptedButtons: Qt.LeftButton | Qt.RightButton hoverEnabled: true Accessible.role: Accessible.Button Accessible.description: "This is a ukui-system-tray button of ukui-sni" Accessible.name: model.Id === undefined ? "" : "ukui-system-tray_" + model.Id Component.onCompleted: { Qt.callLater(()=>{ Accessible.name = Qt.binding(function () { return model.Id === undefined ? "" : "ukui-system-tray_" + model.Id; }); }); } UkuiItems.Icon { id: icon anchors.centerIn: parent width: Math.round(dropArea.scaleFactor * (dropArea.onTopBar ? 20 : 16)) height: Math.round(dropArea.scaleFactor * (dropArea.onTopBar ? 20 : 16)) mode: UkuiItems.Icon.AutoHighlight source: model.Icon Component.onCompleted: { Qt.callLater(()=>{ source = Qt.binding(function () {return model.Icon}); }); } } UkuiItems.Tooltip { id: tooltip anchors.fill: parent mainText: model.ToolTipTitle === undefined ? "" : model.ToolTipTitle.length === 0 ? model.Title : model.ToolTipTitle posFollowCursor: false location: { switch(dropArea.panelPos) { case UkuiItems.Types.Bottom: return UkuiItems.Dialog.BottomEdge; case UkuiItems.Types.Left: return UkuiItems.Dialog.LeftEdge; case UkuiItems.Types.Top: return UkuiItems.Dialog.TopEdge; case UkuiItems.Types.Right: return UkuiItems.Dialog.RightEdge; } } margin: dropArea.isHorizontal ? (dropArea.height - control.height)/2 + 8 : (dropArea.width - control.width)/2 + 8 Component.onCompleted: { Qt.callLater(()=>{ mainText = Qt.binding(function () { return model.ToolTipTitle === undefined ? "" : model.ToolTipTitle.length === 0 ? model.Title : model.ToolTipTitle; }); }); } } onClicked: { if (mouse.button === Qt.LeftButton) { panelModel.model.activate(index); } if (mouse.button === Qt.RightButton) { panelModel.model.showContextMenu(panelModel.modelIndex(index), showDropArea); dropArea.callMenu = true; } } } } } ukui-sni/ukui-system-tray/widget/ui/TrayView.qml0000664000175000017500000006075215153755611020730 0ustar fengfengimport QtQuick 2.15 import QtQuick.Controls 2.15 import QtQml.Models 2.15 import QtQuick.Layouts 1.15 import org.ukui.systemTray 1.0 import org.ukui.quick.items 1.0 as UkuiItems import org.ukui.quick.platform 1.0 as Platform DropArea { property real scaleFactor property real itemWidth property real itemHeight property real itemLong property real itemShort property real controlPanelWidth: isHorizontal ? controlPanelLength : itemLong property real controlPanelHeight: isHorizontal ? itemLong : controlPanelLength property int controlPanelLength: scaleFactor * getControlPanelLength() property bool isHorizontal: true property int panelPos property int dragType property bool inserted: false property int targetIndex property int indexInFold property bool isOverLength: false property bool callMenu: false property int showCount: 11 property int maxLength: dropArea.isHorizontal ? parent.parent.Layout.maximumWidth : parent.parent.Layout.maximumHeight height: isHorizontal ? parent.height : flowArea.height width: isHorizontal ? flowArea.width : parent.width MouseArea { z: 1 anchors.fill: parent acceptedButtons: { let button = Qt.NoButton; if (FunctionControl.disableMouseLeftButton) { button |= Qt.LeftButton } if (FunctionControl.disableMouseRightButton) { button |= Qt.RightButton } return button; } enabled: FunctionControl.disableMouseLeftButton | FunctionControl.disableMouseRightButton } onItemShortChanged: { trayview.viewWidth = trayview.calculateLength(); } onControlPanelLengthChanged: { trayview.viewWidth = trayview.calculateLength(); } onPanelPosChanged: { foldWindow.hide(); trayview.isFold = false; } onMaxLengthChanged: { getShowCount(); } GroupModel { id: showModel modelType: ItemGroupModel.Show showCount: dropArea.showCount } GroupModel { id: foldModel modelType: ItemGroupModel.Fold showCount: dropArea.showCount } function getShowCount() { dropArea.showCount = maxLength / (dropArea.itemShort + trayview.viewSpacing) - 2; } function getControlPanelLength() { switch(ControlPanelModel.rowCount) { case 0: return 0; case 1: return 32; case 2: return 58; case 3: return 84; default: return 0; } } Item {id: dragItem} Flow { id: flowArea anchors.verticalCenter: parent.verticalCenter anchors.horizontalCenter: parent.horizontalCenter flow: dropArea.isHorizontal ? GridLayout.LeftToRight : GridLayout.TopToBottom spacing: trayview.viewSpacing DropArea { width: foldItem.visible ? dropArea.itemWidth : 0 height: foldItem.visible ? dropArea.itemHeight : 0 onEntered: { } onDropped: { if (drag.source.rootId !== dropArea) return; if (dragType === 1) { if (trayModel.count > dropArea.showCount) return; ItemModel.setOrderInGroup(foldModel, foldModel.index(foldBase.sourceIndex,0), 0) ItemModel.setSeparateIndex(showModel.currentSeparateIndex + 1); } if (dragType === 0) { ItemModel.setOrderInGroup(showModel, showModel.index(trayview.sourceIndex, 0), trayModel.items.count - 1); ItemModel.setSeparateIndex(showModel.currentSeparateIndex - 1); dropArea.panelActive = false; } } UkuiItems.DtThemeBackground { id: foldItem visible: !foldBase.isEmpty clip: true useStyleTransparency: false anchors.fill: parent backgroundColor: foldControl.containsPress ? Platform.GlobalTheme.kComponentAlphaClick : foldControl.containsMouse ? Platform.GlobalTheme.kComponentAlphaHover : Platform.GlobalTheme.kContainGeneralAlphaNormal radius: dropArea.onTopBar ? 0 : Platform.GlobalTheme.kRadiusNormal TrayIcon { id: foldControl Accessible.role: Accessible.Button Accessible.description: "This is a foldControl button on ukui-system-tray of ukui-sni" Accessible.name: "foldControl-button" width: dropArea.itemWidth height: dropArea.itemHeight appIcon: showModel.foldIcon() iconRotation: appIconRotation() hoverEnabled: true enabled: foldItem.visible acceptedButtons: Qt.LeftButton | Qt.RightButton UkuiItems.Tooltip { anchors.fill: parent mainText: trayview.isFold ? qsTr("Folding display icon") : qsTr("Expand hidden icon") posFollowCursor: false location: { switch(dropArea.panelPos) { case UkuiItems.Types.Bottom: return UkuiItems.Dialog.BottomEdge; case UkuiItems.Types.Left: return UkuiItems.Dialog.LeftEdge; case UkuiItems.Types.Top: return UkuiItems.Dialog.TopEdge; case UkuiItems.Types.Right: return UkuiItems.Dialog.RightEdge; } } margin: dropArea.isHorizontal ? (dropArea.height - foldControl.height)/2 + 8 : (dropArea.width - foldControl.width)/2 + 8 } onClicked: { if (mouse.button === Qt.LeftButton) { foldWindowReply(); } } function appIconRotation() { if (dropArea.panelPos === UkuiItems.Types.Left) { return trayview.isFold ? 180 : 0; } else if (dropArea.panelPos === UkuiItems.Types.Top) { return trayview.isFold ? 270 : 90; } else if (dropArea.panelPos === UkuiItems.Types.Right) { return trayview.isFold ? 0 : 180; } else if (dropArea.panelPos === UkuiItems.Types.Bottom) { return trayview.isFold ? 90 : 270; } return 0; } function foldWindowReply() { if (trayview.isFold) { foldWindow.hide(); trayview.isFold = false; } else { if (!foldBase.isEmpty) { updateFoldWindowPosition(); foldWindow.show(); } trayview.isFold = true; } } function updateFoldWindowPosition() { if (dropArea.panelPos === UkuiItems.Types.Left) { foldWindow.slideWindow.fromEdge = Platform.WindowProxy.LeftEdge foldWindow.location = UkuiItems.Types.LeftEdge } else if (dropArea.panelPos === UkuiItems.Types.Top) { foldWindow.slideWindow.fromEdge = Platform.WindowProxy.TopEdge foldWindow.location = UkuiItems.Types.TopEdge } else if (dropArea.panelPos === UkuiItems.Types.Right) { foldWindow.slideWindow.fromEdge = Platform.WindowProxy.RightEdge foldWindow.location = UkuiItems.Types.RightEdge } else if (dropArea.panelPos === UkuiItems.Types.Bottom) { foldWindow.slideWindow.fromEdge = Platform.WindowProxy.BottomEdge foldWindow.location = UkuiItems.Types.BottomEdge } foldWindow.margin = dropArea.isHorizontal ? (dropArea.height - foldItem.height)/2 + 8 : (dropArea.width - foldItem.width)/2 + 8; } } UkuiItems.Dialog { id: foldWindow visualParent: foldItem mainItem: foldBase enableWindowBlur: true type: Platform.WindowType.SystemWindow slideWindow.offset: 0 minimumWidth: foldBase.width maximumWidth: minimumWidth minimumHeight: foldBase.height maximumHeight: minimumHeight FoldArea { id: foldBase foldWindowVisible: foldWindow.visible onFoldAreaDragFinshed: fromIndex => { if (dropArea.inserted) { if (dropArea.dragType === 1) { dropArea.inserted = false; if (trayview.itemAtIndex(dropArea.targetIndex).isFixed) return; trayModel.items.remove(dropArea.targetIndex); ItemModel.setOrderBetweenGroups(foldModel, foldModel.index(dropArea.isOverLength ? fromIndex + 1 : fromIndex, 0), showModel, dropArea.targetIndex); ItemModel.setSeparateIndex(showModel.currentSeparateIndex + 1); } } } onIsEmptyChanged: { foldItem.visible = !foldBase.isEmpty; foldWindow.hide(); trayview.isFold = false; } } onVisibleChanged: { dropArea.panelActive = foldWindow.visible; } onActiveFocusItemChanged: { if (foldControl.pressed) return; if (trayview.isFold) { if (activeFocusItem === null) { foldWindow.hide(); trayview.isFold = false; } } } } } } ListView { id: trayview property string idSelect: "" property bool isFold: false property int sortIndex property int sourceIndex property real viewWidth: 0 property int viewSpacing: dropArea.onTopBar ? 6 : 0 height: dropArea.isHorizontal ? dropArea.itemHeight : viewWidth width: dropArea.isHorizontal ? viewWidth : dropArea.itemWidth orientation: dropArea.isHorizontal ? ListView.Horizontal : ListView.Vertical layoutDirection: ListView.RightToLeft verticalLayoutDirection: ListView.Qt.BottomToTop spacing: viewSpacing interactive: false onViewSpacingChanged: { trayview.viewWidth = trayview.calculateLength(); dropArea.getShowCount(); } Component.onCompleted: { var i = trayview.calculateLength(); viewWidth = i; } displaced: Transition { SequentialAnimation { ScriptAction { script: { trayview.viewWidth = trayview.calculateLength(); } } NumberAnimation { properties: "x,y"; easing.type: Easing.OutQuad; duration: 200 } NumberAnimation { properties: "z"; to: 1; easing.type: Easing.OutQuad; duration: 1 } ScriptAction { script: { trayview.viewWidth += 1; trayview.viewWidth -= 1; } } } } move: Transition { ScriptAction { script: { trayview.viewWidth = trayview.calculateLength(); } } NumberAnimation { properties: "x,y"; easing.type: Easing.OutQuad; duration: 200 } NumberAnimation { properties: "z"; to: 0; easing.type: Easing.OutQuad; duration: 1 } } ListView.onAdd: SequentialAnimation { ScriptAction { script: { trayview.viewWidth = trayview.calculateLength(); } } } ListView.onRemove: SequentialAnimation { ScriptAction { script: { trayview.viewWidth = trayview.calculateLength(); } } } model: DelegateModel { id: trayModel model: showModel groups: DelegateModelGroup { name: "foldItems" includeByDefault: false } delegate: Item { id: showDropArea property int visualIndex: DelegateModel.itemsIndex property bool isFixed: model.Fixed === undefined ? false : model.Fixed property bool isControlPanel: ControlPanelModel.rowCount > 1 && model.Id === "ukui-sidebar" width: isControlPanel ? dropArea.controlPanelWidth : dropArea.itemWidth height: isControlPanel ? dropArea.controlPanelHeight : dropArea.itemHeight clip: true Binding { target: control; property: "selectIndex"; value: visualIndex} UkuiItems.DtThemeBackground { id: controlBase clip: true useStyleTransparency: false anchors.fill: parent backgroundColor: control.containsPress ? Platform.GlobalTheme.kComponentAlphaClick : control.containsMouse ? Platform.GlobalTheme.kComponentAlphaHover : Platform.GlobalTheme.kContainGeneralAlphaNormal radius: dropArea.onTopBar ? 0 : Platform.GlobalTheme.kRadiusNormal TrayIcon { id: control Accessible.role: Accessible.Button Accessible.description: "This is a ukui-system-tray button of ukui-sni" Accessible.name: model.Id === undefined ? "" : "ukui-system-tray_" + model.Id property int selectIndex: 0 property var rootId: dropArea anchors.fill: parent appStatus: model.Status === undefined ? "" : model.Status appAttentionMovieName: model.AttentionMovieName === undefined ? "" : model.AttentionMovieName appIcon: model.Icon appAttentionIcon: model.AttentionIcon appOverlayIcon: model.OverlayIcon showControlPanel: showDropArea.isControlPanel hoverEnabled: true acceptedButtons: Qt.LeftButton | Qt.RightButton Drag.active: false Drag.hotSpot.x: width / 2 Drag.hotSpot.y: height / 2 Drag.dragType: Drag.Automatic Drag.mimeData: { "source": "ukui-system-tray" } drag.target: model.Fixed ? null : dragItem drag.onActiveChanged: { if (drag.active) { toStartDrag(); control.opacity = 0; exited(); } Drag.active = drag.active; } UkuiItems.Tooltip { id: tooltip anchors.fill: parent mainText: model.ToolTipTitle === undefined ? "" : model.ToolTipTitle.length === 0 ? model.Title : model.ToolTipTitle posFollowCursor: false visible: !control.showControlPanel location: { switch(dropArea.panelPos) { case UkuiItems.Types.Bottom: return UkuiItems.Dialog.BottomEdge; case UkuiItems.Types.Left: return UkuiItems.Dialog.LeftEdge; case UkuiItems.Types.Top: return UkuiItems.Dialog.TopEdge; case UkuiItems.Types.Right: return UkuiItems.Dialog.RightEdge; } } margin: dropArea.isHorizontal ? (dropArea.height - control.height)/2 + 8 : (dropArea.width - control.width)/2 + 8 } onClicked: { if (mouse.button === Qt.LeftButton) { trayModel.model.onActivate(trayModel.modelIndex(index)); } if (mouse.button === Qt.RightButton) { trayModel.model.onContextMenu(trayModel.modelIndex(index), showDropArea); dropArea.callMenu = true; } } onPressed: { if (model.Fixed) return; if (mouse.button === Qt.LeftButton) { control.grabToImage(function(result) { control.Drag.imageSource = result.url; }) } } Drag.onDragFinished: { control.opacity = 1 foldItem.visible = !foldBase.isEmpty; dropArea.panelActive = false; if (dropArea.dragType === 0) { if (trayview.itemAtIndex(visualIndex).isFixed) return; ItemModel.setOrderInGroup(showModel, showModel.index(trayview.sourceIndex, 0), visualIndex); } } function toStartDrag() { foldWindow.hide(); trayview.isFold = false; trayview.sourceIndex = selectIndex; dropArea.dragType = 0; if (!foldItem.visible) foldItem.visible = true; dropArea.panelActive = true; } } } } onCountChanged: { trayview.viewWidth = trayview.calculateLength(); } } function calculateLength() { if (ControlPanelModel.rowCount > 1) { update(); return trayModel.count * dropArea.itemShort + (trayModel.count - 1) * trayview.viewSpacing + (dropArea.controlPanelLength - dropArea.itemShort); } else { return trayModel.count * dropArea.itemShort + (trayModel.count - 1) * trayview.viewSpacing; } } } } function changeFoldWindowPosition() { if (foldWindow.visible) { foldWindow.updatePosition(); } } onPositionChanged: drag => { if (drag.source.rootId !== dropArea) return; var target = getTarget(drag.x, drag.y); if (target === -1) return; if (dropArea.dragType === 0) { if (trayview.itemAtIndex(target).isFixed) return; trayModel.items.move(drag.source.selectIndex, target); } else if (dropArea.dragType === 1) { if (trayview.itemAtIndex(target).isFixed) return; dropArea.targetIndex = target; if (dropArea.inserted) { var i = target trayModel.items.move(drag.source.selectIndex, target) drag.source.selectIndex = i } else { dropArea.inserted = true; dropArea.indexInFold = drag.source.selectIndex; if (trayModel.count > dropArea.showCount) { dropArea.isOverLength = true; showModel.currentSeparateIndex--; foldModel.currentSeparateIndex--; } else { dropArea.isOverLength = false; } drag.source.selectIndex = target; trayModel.items.insert(target, {}); } } } onExited: { if (dropArea.inserted) { if (dropArea.isOverLength) { showModel.currentSeparateIndex++; foldModel.currentSeparateIndex++; } trayModel.items.remove(dropArea.targetIndex); dropArea.inserted = false; drag.source.selectIndex = dropArea.indexInFold; } } function getTarget(x, y) { switch (dropArea.panelPos) { case UkuiItems.Types.Top: case UkuiItems.Types.Bottom: return trayview.indexAt((x + trayview.contentX - trayview.x), y); case UkuiItems.Types.Left: case UkuiItems.Types.Right: return trayview.indexAt(x, y + trayview.contentY - trayview.y); default: return -1; } } function menuStateChange(state) { if (dropArea.callMenu) { dropArea.panelActive = foldWindow.visible ? true : state; dropArea.callMenu = state; } } Component.onCompleted: { ItemModel.menuStateChanged.connect(menuStateChange); } Component.onDestruction: { ItemModel.menuStateChanged.disconnect(menuStateChange); } } ukui-sni/ukui-system-tray/widget/ui/FoldArea.qml0000664000175000017500000001774215153755611020634 0ustar fengfengimport QtQuick 2.15 import QtQuick.Controls 2.15 import QtQml.Models 2.15 import org.ukui.systemTray 1.0 import org.ukui.quick.items 1.0 as UkuiItems import org.ukui.quick.platform 1.0 as Platform DropArea { property bool isEmpty: foldAreaModel.count > 0 ? false : true property int sourceIndex property bool foldWindowVisible: false signal foldAreaDragFinshed(int selectIndex) width: foldAreaModel.count > 5 ? foldView.cellWidth * 5 + 8 : foldAreaModel.count * foldView.cellWidth + 8 height: (foldAreaModel.count % 5) === 0 ? Math.floor((foldAreaModel.count / 5)) * foldView.cellHeight + 8 : Math.floor((foldAreaModel.count / 5) + 1) * foldView.cellHeight + 8 UkuiItems.DtThemeBackground { anchors.fill: parent backgroundColor: Platform.GlobalTheme.baseActive GridView { id: foldView property string idSelect: "" anchors.fill: parent anchors.topMargin: 4 anchors.leftMargin: 4 cellWidth: dropArea.scaleFactor * 40 cellHeight: dropArea.scaleFactor * 40 interactive: false moveDisplaced: Transition { NumberAnimation { properties: "x,y"; easing.type: Easing.OutQuad; duration: 200 } NumberAnimation { properties: "z"; to: 1; easing.type: Easing.OutQuad; duration: 1 } } model: DelegateModel { id: foldAreaModel model: foldModel delegate: DropArea { property int vIndex: DelegateModel.itemsIndex id: foldDropArea width: foldView.cellWidth height: foldView.cellHeight clip: true GridView.onAdd: SequentialAnimation { NumberAnimation {target: foldDropArea; property: "scale"; from: 0; to: 1; duration: 250; easing.type: Easing.InOutQuad} } onDropped: { if (drag.source.rootId !== dropArea) return; ItemModel.setOrderInGroup(foldModel, foldModel.index(foldBase.sourceIndex, 0), drag.source.selectIndex); } onEntered: { if (drag.source.rootId !== dropArea) return; foldAreaModel.items.move(drag.source.selectIndex, vIndex) } Binding { target: controlFold; property: "selectIndex"; value: vIndex} UkuiItems.DtThemeBackground { id: controlBaseFold clip: true useStyleTransparency: false anchors.fill: parent backgroundColor: controlFold.containsPress ? Platform.GlobalTheme.kComponentAlphaClick : controlFold.containsMouse ? Platform.GlobalTheme.kComponentAlphaHover : Platform.GlobalTheme.kContainGeneralAlphaNormal radius: Platform.GlobalTheme.kRadiusNormal TrayIcon { id: controlFold Accessible.role: Accessible.Button Accessible.description: "This is a ukui-system-tray button of ukui-sni" Accessible.name: model.Id === undefined ? "" : "ukui-system-tray_" + model.Id property int selectIndex: 0 property var rootId: dropArea anchors.fill: parent appStatus: model.Status appAttentionMovieName: model.AttentionMovieName appIcon: model.Icon appAttentionIcon: model.AttentionIcon appOverlayIcon: model.OverlayIcon hoverEnabled: true acceptedButtons: Qt.LeftButton | Qt.RightButton Drag.active: false Drag.hotSpot.x: width / 2 Drag.hotSpot.y: height / 2 Drag.dragType: Drag.Automatic Drag.mimeData: { "source": "ukui-system-tray" } drag.target: controlFold; drag.onActiveChanged: { if (drag.active) { toStartDrag(); controlFold.opacity = 0; exited(); } else { x = 0; y = 0; } Drag.active = drag.active; } UkuiItems.Tooltip { id: tooltip anchors.fill: parent mainText: model.ToolTipTitle.length === 0 ? model.Title : model.ToolTipTitle posFollowCursor: false active: foldWindowVisible location: { switch (dropArea.panelPos) { case UkuiItems.Types.Bottom: case UkuiItems.Types.Left: case UkuiItems.Types.Right: return UkuiItems.Dialog.BottomEdge; case UkuiItems.Types.Top: return UkuiItems.Dialog.TopEdge; } } margin: 8 } onClicked: { if (mouse.button === Qt.LeftButton) { foldAreaModel.model.onActivate(foldAreaModel.modelIndex(index)); } if (mouse.button === Qt.RightButton) { foldAreaModel.model.onContextMenu(foldAreaModel.modelIndex(index), foldDropArea); } } onPressed: { if (mouse.button === Qt.LeftButton) { controlFold.grabToImage(function(result) { controlFold.Drag.imageSource = result.url; }) } } onReleased: { } Drag.onDragFinished: { if (dropArea.inserted) { foldAreaDragFinshed(foldBase.sourceIndex); } else { controlFold.parent = controlBaseFold; controlFold.opacity = 1 if (foldBase.sourceIndex === vIndex) return; ItemModel.setOrderInGroup(foldModel, foldModel.index(foldBase.sourceIndex, 0), vIndex); } } function toStartDrag() { x = controlFold.mapToItem(foldView,0,0).x; y = controlFold.mapToItem(foldView,0,0).y; foldBase.sourceIndex = vIndex; dropArea.dragType = 1; } } } } } } } } ukui-sni/ukui-system-tray/widget/ui/main.qml0000664000175000017500000000236015153755611020071 0ustar fengfengimport QtQuick 2.15 import QtQuick.Layouts 1.15 import org.ukui.quick.widgets 1.0 import org.ukui.quick.items 1.0 WidgetItem { property bool isHorizontal: (Widget.orientation === Types.Horizontal) property int pos: Widget.container.position property real ratio: parent.ratio ? parent.ratio : 1 Layout.fillWidth: !isHorizontal Layout.fillHeight: isHorizontal Layout.preferredWidth: childrenRect.width Layout.preferredHeight: childrenRect.height clip: true Widget.active: dropArea.panelActive TrayView { id: dropArea property bool panelActive: false property bool onTopBar: parent.height < 40 scaleFactor: parent.ratio isHorizontal: parent.isHorizontal itemWidth: onTopBar ? 28 : isHorizontal ? scaleFactor * 32 : scaleFactor * 40 itemHeight: onTopBar ? 28 : isHorizontal ? scaleFactor * 40 : scaleFactor * 32 itemLong: onTopBar ? 28 : scaleFactor * 40 itemShort: onTopBar ? 28 : scaleFactor * 32 panelPos: parent.pos } onWidthChanged: { dropArea.changeFoldWindowPosition(); } onHeightChanged: { dropArea.changeFoldWindowPosition(); } } ukui-sni/ukui-system-tray/widget/ui/TrayIcon.qml0000664000175000017500000000335015153755017020675 0ustar fengfengimport QtQuick 2.15 import QtQuick.Controls 2.15 import org.ukui.systemTray 1.0 import org.ukui.quick.items 1.0 as UkuiItems MouseArea { id: control property string appStatus: "" property string appAttentionMovieName: "" property var appIcon property var appAttentionIcon property var appOverlayIcon property int iconRotation: 0 property real iconRatio: dropArea.onTopBar ? 24 : 16 property bool showControlPanel: false Item { id: trayitem anchors.fill: parent rotation: control.iconRotation Loader { anchors.centerIn: parent sourceComponent: showControlPanel ? controlPanelComponent : ((control.appStatus === "NeedsAttention") && (control.appAttentionMovieName !== "")) ? movieComponent : iconComponent } Component { id: iconComponent UkuiItems.Icon { width: Math.round(dropArea.scaleFactor * iconRatio) height: Math.round(dropArea.scaleFactor * iconRatio) source: (control.appStatus === "NeedsAttention") ? control.appAttentionIcon : control.appIcon mode: UkuiItems.Icon.AutoHighlight // overlayIcon: appOverlayIcon // isInverseColor: false } } Component { id: movieComponent AnimatedImage { width: Math.round(dropArea.scaleFactor * iconRatio) height: Math.round(dropArea.scaleFactor * iconRatio) source: control.appAttentionMovieName } } Component { id: controlPanelComponent ControlPanel {} } } } ukui-sni/ukui-system-tray/widget/metadata.json0000664000175000017500000000110115153755017020460 0ustar fengfeng{ "Authors": [ { "Name": "gjq", "Email": "guojiaqi@kylinos.cn" } ], "Id": "org.ukui.systemTray", "Icon": "ukui-menu", "Name": "ukui-system-tray", "Name[zh_CN]": "系统托盘", "Tooltip": "system tray", "Tooltip[zh_CN]": "系统托盘", "Description": "system tray", "Description[zh_CN]": "系统托盘", "Version": "1.0", "Website": "https://ukui.org", "BugReport": "https://gitee.com/openkylin/ukui-panel/issues", "ShowIn": "Panel", "Contents": { "Main": "ui/main.qml", "I18n": "translations/ukui-system-tray" } } ukui-sni/ukui-system-tray/CMakeLists.txt0000664000175000017500000000511115153755611017267 0ustar fengfengcmake_minimum_required(VERSION 3.14) project(ukui-system-tray) set(VERSION_MAJOR 1) set(VERSION_MINOR 0) set(VERSION_MICRO 0) set(UKUI_SYSTEM_TRAY_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_MICRO}) set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) set(CMAKE_CXX_STANDARD_REQUIRED ON) find_package(QT NAMES Qt6 Qt5 COMPONENTS Core Gui Widgets Quick LinguistTools DBus REQUIRED) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core Gui Widgets Quick LinguistTools DBus REQUIRED) find_package(ukui-quick COMPONENTS framework platform) find_package(ukui-search REQUIRED) set(PROJECT_SOURCES plugin/system-tray-plugin.h plugin/system-tray-plugin.cpp plugin/tray-items-model.h plugin/tray-items-model.cpp plugin/tray-item.h plugin/tray-item.cpp plugin/item-group-model.h plugin/item-group-model.cpp plugin/security-function-control.h plugin/security-function-control.cpp plugin/items-filter-model.h plugin/items-filter-model.cpp plugin/control-panel-model.cpp plugin/control-panel-model.h ) include_directories(${CMAKE_SOURCE_DIR}/status-notifier-host) file(GLOB TS_FILES translations/*.ts) set(UKUI_SYSTEM_TRAY_TRANSLATION_DIR "/usr/share/ukui/widgets/org.ukui.systemTray/translations") if(${QT_VERSION_MAJOR} GREATER_EQUAL 6) qt_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR} ${TS_FILES} OPTIONS -no-obsolete -no-ui-lines) add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES} ${QRC_FILES} ${QM_FILES}) else() qt5_create_translation(QM_FILES ${CMAKE_CURRENT_SOURCE_DIR} ${TS_FILES} OPTIONS -no-obsolete -no-ui-lines) add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES} ${QRC_FILES} ${QM_FILES}) endif() target_compile_definitions(${PROJECT_NAME} PRIVATE $<$,$>:QT_QML_DEBUG> ) target_link_libraries(${PROJECT_NAME} PRIVATE Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Quick Qt${QT_MAJOR_VERSION}::Gui Qt${QT_VERSION_MAJOR}::Widgets Qt${QT_VERSION_MAJOR}::DBus ukui-sni-host ukui-quick::framework ukui-quick::platform ukui-search ) install(DIRECTORY "widget/" DESTINATION "/usr/share/ukui/widgets/org.ukui.systemTray") install(FILES "plugin/qmldir" DESTINATION "/usr/lib/${CMAKE_LIBRARY_ARCHITECTURE}/qt${QT_VERSION_MAJOR}/qml/org/ukui/systemTray") install(FILES ${QM_FILES} DESTINATION ${UKUI_SYSTEM_TRAY_TRANSLATION_DIR}) install(TARGETS ${PROJECT_NAME} LIBRARY DESTINATION "/usr/lib/${CMAKE_LIBRARY_ARCHITECTURE}/qt${QT_VERSION_MAJOR}/qml/org/ukui/systemTray") ukui-sni/ukui-system-tray/plugin/0000775000175000017500000000000015153755611016027 5ustar fengfengukui-sni/ukui-system-tray/plugin/qmldir0000664000175000017500000000006315153755017017241 0ustar fengfengmodule org.ukui.systemTray plugin ukui-system-tray ukui-sni/ukui-system-tray/plugin/control-panel-model.cpp0000664000175000017500000000537315153755611022416 0ustar fengfeng/* * Copyright (C) 2025, 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 "control-panel-model.h" #include #include #include #include #include static std::once_flag onceFlag; static ControlPanelModel* g_instance = nullptr; ControlPanelModel* ControlPanelModel::self() { std::call_once(onceFlag, [ & ] { g_instance = new ControlPanelModel(); }); return g_instance; } void ControlPanelModel::activate(int modelIndex) { Q_UNUSED(modelIndex); QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.ukui.Sidebar"), QStringLiteral("/org/ukui/Sidebar"), QStringLiteral("org.ukui.Sidebar"), QStringLiteral("shortcutsActive")); QDBusConnection::sessionBus().send(message); } void ControlPanelModel::showContextMenu(const QModelIndex &index, QQuickItem *item) { m_sourceModel->showContextMenu(mapToSource(index), item); } bool ControlPanelModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { QModelIndex sourceIndex = sourceModel()->index(sourceRow, 0, sourceParent); return m_sourceModel->getControlPanelItems().contains(sourceIndex.data(TrayItemsModel::Id).toString()); } bool ControlPanelModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const { return m_sourceModel->getControlPanelItems().indexOf(source_left.data(TrayItemsModel::Id).toString()) < m_sourceModel->getControlPanelItems().indexOf(source_right.data(TrayItemsModel::Id).toString()); } ControlPanelModel::ControlPanelModel(QObject* parent) { QSortFilterProxyModel::setSourceModel(TrayItemsModel::instance()); m_sourceModel = TrayItemsModel::instance(); connect(this, &QAbstractItemModel::rowsInserted, this, &ControlPanelModel::rowCountChanged); connect(this, &QAbstractItemModel::rowsRemoved, this, &ControlPanelModel::rowCountChanged); sort(0); } ukui-sni/ukui-system-tray/plugin/control-panel-model.h0000664000175000017500000000313415153755611022054 0ustar fengfeng/* * Copyright (C) 2025, 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 CONTROL_PANEL_MODEL_H #define CONTROL_PANEL_MODEL_H #include #include "tray-items-model.h" #include "items-filter-model.h" class QQuickItem; class ControlPanelModel : public QSortFilterProxyModel { Q_OBJECT Q_PROPERTY(int rowCount READ rowCount NOTIFY rowCountChanged) public: static ControlPanelModel* self(); Q_INVOKABLE void activate(int modelIndex); Q_INVOKABLE void showContextMenu(const QModelIndex &index, QQuickItem *item); Q_SIGNALS: void rowCountChanged(); protected: bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override; bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override; private: explicit ControlPanelModel(QObject* parent = nullptr); TrayItemsModel* m_sourceModel = nullptr; }; #endif //CONTROL_PANEL_MODEL_H ukui-sni/ukui-system-tray/plugin/tray-item.cpp0000664000175000017500000001325515153755017020454 0ustar fengfeng/* * 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: youdiansaodongxi * */ #include "tray-item.h" #include "status-notifier-item.h" #include #include QIcon extractIcon(const QIcon&icon, const QIcon&defaultValue) { return icon.isNull() ? defaultValue : icon; } class TrayItemPrivate { public: QString m_source; QString m_desktop; UkuiSni::StatusNotifierItem* m_item {nullptr}; bool m_fixed {false}; bool m_recordOrder {false}; bool m_isReady {false}; QQuickItem *m_parentItem {nullptr}; }; TrayItem::TrayItem(const QString&itemSource, QObject* parent) : QObject(parent), d(new TrayItemPrivate) { d->m_source = itemSource; d->m_item = UkuiSni::StatusNotifierHost::self()->itemForService(d->m_source); connect(d->m_item, &UkuiSni::StatusNotifierItem::dataUpdated, this, &TrayItem::dataUpdated); connect(d->m_item, &UkuiSni::StatusNotifierItem::contextMenuReady, this, &TrayItem::contextMenuReady, Qt::QueuedConnection); connect(d->m_item, &UkuiSni::StatusNotifierItem::activateResult, this, &TrayItem::activateResult); connect(d->m_item, &UkuiSni::StatusNotifierItem::menuStateChange, this, &TrayItem::menuStateChanged); } TrayItem::~TrayItem() { if(d) { delete d; d = nullptr; } } QString TrayItem::service() const { if (d->m_item) { return d->m_item->service(); } return {}; } QIcon TrayItem::attentionIcon() const { if (d->m_item) { return d->m_item->attentionIcon().isNull() ? icon() : d->m_item->attentionIcon(); } return {}; } QString TrayItem::attentionIconName() const { if(d->m_item) { return d->m_item->attentionIconName(); } return {}; } QString TrayItem::attentionMovieName() const { if(d->m_item) { return d->m_item->attentionMovieName(); } return {}; } QString TrayItem::category() const { if(d->m_item) { return d->m_item->category(); } return {}; } QIcon TrayItem::icon() const { if (d->m_item) { return d->m_item->icon().isNull()? QIcon::fromTheme("application-x-executable") : d->m_item->icon(); } return {}; } QString TrayItem::iconName() const { if(d->m_item) { return d->m_item->iconName(); } return {}; } QString TrayItem::iconThemePath() const { if(d->m_item) { return d->m_item->iconThemePath(); } return {}; } QString TrayItem::id() const { if(d->m_item) { return d->m_item->id(); } return {}; } bool TrayItem::itemIsMenu() const { if(d->m_item) { return d->m_item->itemIsMenu(); } return false; } QIcon TrayItem::overlayIcon() const { if(d->m_item) { return d->m_item->overlayIcon(); } return {}; } QString TrayItem::overlayIconName() const { if(d->m_item) { return d->m_item->overlayIconName(); } return {}; } QString TrayItem::status() const { if(d->m_item) { return d->m_item->status(); } return "Passive"; } QString TrayItem::title() const { if(d->m_item) { return d->m_item->title(); } return {}; } QString TrayItem::toolTipSubTitle() const { if(d->m_item) { return d->m_item->toolTipSubTitle(); } return {}; } QString TrayItem::toolTipTitle() const { if(d->m_item) { return d->m_item->toolTipTitle(); } return {}; } QString TrayItem::windowId() const { if(d->m_item) { return d->m_item->windowId(); } return {}; } QString TrayItem::desktop() const { return d->m_desktop; } uint TrayItem::pid() const { return d->m_item->pid(); } bool TrayItem::fixed() const { return d->m_fixed; } void TrayItem::setFixed(bool fixed) { d->m_fixed = fixed; } bool TrayItem::recordOrder() const { return d->m_recordOrder; } void TrayItem::setRecordOrder(bool recordOrder) { d->m_recordOrder = recordOrder; } void TrayItem::setParentItem(QQuickItem *item) { d->m_parentItem = item; } void TrayItem::setDesktop(const QString &desktop) { d->m_desktop = desktop; } QString TrayItem::source() const { return d->m_source; } void TrayItem::contextMenu(int x, int y) { d->m_item->contextMenu(x, y); } void TrayItem::activate(int x, int y) { d->m_item->activate(x, y); } void TrayItem::secondaryActivate(int x, int y) { d->m_item->secondaryActivate(x, y); } void TrayItem::scroll(int delta, const QString &direction) { d->m_item->scroll(delta, direction); } void TrayItem::provideXdgActivationToken(const QString &token) { d->m_item->provideXdgActivationToken(token); } void TrayItem::dataUpdated() { if (!d->m_isReady) { if (d->m_item->id() != "") { d->m_isReady = true; Q_EMIT itemReady(this); } } Q_EMIT itemDataChanged(d->m_source); } void TrayItem::contextMenuReady(QMenu *menu) { if(menu && !menu->isEmpty()) { menu->winId(); if(menu->windowHandle() && d->m_parentItem) { menu->windowHandle()->setTransientParent(d->m_parentItem->window()); } menu->popup(QCursor::pos()); } } ukui-sni/ukui-system-tray/plugin/security-function-control.cpp0000664000175000017500000002054415153755017023710 0ustar fengfeng/* * 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: youdiansaodongxi * */ #include "security-function-control.h" #include "function-control.h" SecurityFunctionControl *SecurityFunctionControl::instance() { static SecurityFunctionControl instance(nullptr); return &instance; } bool SecurityFunctionControl::disableMouseLeftButton() const { return m_disableMouseLeftButton; } bool SecurityFunctionControl::disableMouseRightButton() const { return m_disableMouseRightButton; } bool SecurityFunctionControl::disableMouseHover() const { return m_disableMouseHover; } QStringList SecurityFunctionControl::appWhiteList() const { return m_appWhiteList; } QStringList SecurityFunctionControl::appBlackList() const { return m_appBlackList; } QStringList SecurityFunctionControl::leftClickBlackList() const { return m_leftClickBlackList; } QStringList SecurityFunctionControl::rightClickBlackList() const { return m_rightClickBlackList; } bool SecurityFunctionControl::canAppDisplay(const QString &desktop) const { if (!m_appWhiteList.isEmpty()) { if (!std::any_of(m_appWhiteList.constBegin(), m_appWhiteList.constEnd(), [&](const QString& app) { return desktop.endsWith(app); })) { return false; } } if (!m_appBlackList.isEmpty()) { if (std::any_of(m_appBlackList.constBegin(), m_appBlackList.constEnd(), [&](const QString& app) { return desktop.endsWith(app); })) { return false; } } return true; } bool SecurityFunctionControl::canLeftClick(const QString &desktop) const { if (!m_leftClickBlackList.isEmpty()) { if (std::any_of(m_leftClickBlackList.constBegin(), m_leftClickBlackList.constEnd(), [&](const QString& app) { return desktop.endsWith(app); })) { return false; } } return true; } bool SecurityFunctionControl::canRightClick(const QString &desktop) const { if (!m_rightClickBlackList.isEmpty()) { if (std::any_of(m_rightClickBlackList.constBegin(), m_rightClickBlackList.constEnd(), [&](const QString& app) { return desktop.endsWith(app); })) { return false; } } return true; } bool SecurityFunctionControl::controlEnabled() const { return m_controlEnabled; } SecurityFunctionControl::SecurityFunctionControl(QObject *parent) : QObject(parent) { UkuiQuick::FunctionControl::instance()->addWatch(QStringLiteral("ukui-sni-v11")); onFunctionControlChanged("ukui-sni-v11", false); connect(UkuiQuick::FunctionControl::instance(), &UkuiQuick::FunctionControl::functionControlChanged, this, [&](const QString &name) { onFunctionControlChanged(name); }); connect(UkuiQuick::FunctionControl::instance(), &UkuiQuick::FunctionControl::functionControlExit, this, [&]() { onFunctionControlChanged(QStringLiteral("ukui-sni-v11"), true); }); } bool SecurityFunctionControl::compareListBySort(QStringList &list1, QStringList &list2) { if (list1.size() != list2.size()) return false; list1.sort(); list2.sort(); return list1 == list2; } void SecurityFunctionControl::onFunctionControlChanged(const QString &name, bool exit) { if (name != QStringLiteral("ukui-sni-v11")) { return; } //管控中有值时,设置为管控值,否则设置为配置文件中的值 auto config = exit ? QJsonObject(): UkuiQuick::FunctionControl::instance()->functionControlObject(name).value(name).toObject(); qDebug() << "ukui-sni function control config:" << config; bool controlEnabled = !config.isEmpty(); if (m_controlEnabled != controlEnabled) { m_controlEnabled = controlEnabled; Q_EMIT controlEnabledChanged(m_controlEnabled); } //禁用左键点击 if (config.contains(QStringLiteral("disableMouseLeftButton"))) { bool disableMouseLeftButton = config.value(QStringLiteral("disableMouseLeftButton")).toBool(); if (m_disableMouseLeftButton != disableMouseLeftButton) { m_disableMouseLeftButton = disableMouseLeftButton; Q_EMIT disableMouseLeftButtonChanged(); } } else { if (m_disableMouseLeftButton != false) { m_disableMouseLeftButton = false; Q_EMIT disableMouseLeftButtonChanged(); } } //禁用右键点击 if (config.contains(QStringLiteral("disableMouseRightButton"))) { bool disableMouseRightButton = config.value(QStringLiteral("disableMouseRightButton")).toBool(); if (m_disableMouseRightButton != disableMouseRightButton) { m_disableMouseRightButton = disableMouseRightButton; Q_EMIT disableMouseRightButtonChanged(); } } else { if (m_disableMouseRightButton != false) { m_disableMouseRightButton = false; Q_EMIT disableMouseRightButtonChanged(); } } //禁用鼠标悬浮 if (config.contains(QStringLiteral("disableMouseHover"))) { bool disableMouseHover = config.value(QStringLiteral("disableMouseHover")).toBool(); if (m_disableMouseHover != disableMouseHover) { m_disableMouseHover = disableMouseHover; Q_EMIT disableMouseHoverChanged(); } } else { if (m_disableMouseHover != false) { m_disableMouseHover = false; Q_EMIT disableMouseHoverChanged(); } } //应用白名单 if (config.contains(QStringLiteral("appWhiteList"))) { QStringList appWhiteList; for (QVariant &app : config.value(QStringLiteral("appWhiteList")).toArray().toVariantList()) { appWhiteList.append(app.toString()); } if (!compareListBySort(m_appWhiteList, appWhiteList)) { m_appWhiteList = appWhiteList; Q_EMIT appWhiteListChanged(); } } else if (!m_appWhiteList.isEmpty()) { m_appWhiteList.clear(); Q_EMIT appWhiteListChanged(); } //应用黑名单 if (config.contains(QStringLiteral("appBlackList"))) { QStringList appBlackList; for (QVariant &app : config.value(QStringLiteral("appBlackList")).toArray().toVariantList()) { appBlackList.append(app.toString()); } if (!compareListBySort(m_appBlackList, appBlackList)) { m_appBlackList= appBlackList; Q_EMIT appBlackListChanged(); } } else if (!m_appBlackList.isEmpty()) { m_appBlackList.clear(); Q_EMIT appBlackListChanged(); } //左键点击黑名单 if (config.contains(QStringLiteral("leftClickBlackList"))) { QStringList leftClickBlackList; for (QVariant &app : config.value(QStringLiteral("leftClickBlackList")).toArray().toVariantList()) { leftClickBlackList.append(app.toString()); } if (!compareListBySort(m_leftClickBlackList, leftClickBlackList)) { m_leftClickBlackList = leftClickBlackList; Q_EMIT leftClickBlackListChanged(); } } else if (!m_leftClickBlackList.isEmpty()) { m_leftClickBlackList.clear(); Q_EMIT leftClickBlackListChanged(); } //右键点击黑名单 if (config.contains(QStringLiteral("rightClickBlackList"))) { QStringList rightClickBlackList; for (QVariant &app : config.value(QStringLiteral("rightClickBlackList")).toArray().toVariantList()) { rightClickBlackList.append(app.toString()); } if (!compareListBySort(m_rightClickBlackList, rightClickBlackList)) { m_rightClickBlackList = rightClickBlackList; Q_EMIT rightClickBlackListChanged(); } } else if (!m_rightClickBlackList.isEmpty()) { m_rightClickBlackList.clear(); Q_EMIT rightClickBlackListChanged(); } } ukui-sni/ukui-system-tray/plugin/items-filter-model.h0000664000175000017500000000360415153755017021705 0ustar fengfeng/* * 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: youdiansaodongxi * */ #ifndef ITEMSFILTERMODEL_H #define ITEMSFILTERMODEL_H #include #include class TrayItemsModel; class ItemGroupModel; class ItemsFilterModel : public QSortFilterProxyModel { Q_OBJECT public: static ItemsFilterModel *instance(); QVariant data(const QModelIndex &index, int role) const override; Q_INVOKABLE void activate(const QModelIndex &index); Q_INVOKABLE void showContextMenu(const QModelIndex &index, QQuickItem *item); Q_INVOKABLE void setOrderInGroup(ItemGroupModel *group, const QModelIndex &groupIndex, int order); Q_INVOKABLE void setOrderBetweenGroups(ItemGroupModel *fromGroup, const QModelIndex &beginIndex, ItemGroupModel *toGroup, int order); Q_INVOKABLE void setSeparateIndex(int index); Q_INVOKABLE int getSeparateIndex(); void setOrder(const QModelIndex &index, int order); Q_SIGNALS: void menuStateChanged(bool state); protected: bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; private: ItemsFilterModel(QObject *parent = nullptr); TrayItemsModel *m_sourceModel = nullptr; }; #endif // ITEMSFILTERMODEL_H ukui-sni/ukui-system-tray/plugin/tray-item.h0000664000175000017500000000341615153755017020117 0ustar fengfeng#ifndef TRAYITEM_H #define TRAYITEM_H #include #include #include #include "status-notifier-host.h" class TrayItemPrivate; class TrayItem : public QObject { Q_OBJECT public: explicit TrayItem(const QString& itemSource, QObject* parent = nullptr); ~TrayItem(); QString source() const; QString service() const; QIcon attentionIcon() const; QString attentionIconName() const; QString attentionMovieName() const; QString category() const; QIcon icon() const; QString iconName() const; QString iconThemePath() const; QString id() const; bool itemIsMenu() const; QIcon overlayIcon() const; QString overlayIconName() const; QString status() const; QString title() const; QString toolTipSubTitle() const; QString toolTipTitle() const; QString windowId() const; QString desktop() const; uint pid() const; /** * fixed in system tray */ bool fixed() const; void setFixed(bool fixed); /** * need record relative order */ bool recordOrder() const; void setRecordOrder(bool recordOrder); void setParentItem(QQuickItem *item); void setDesktop(const QString & desktop); void contextMenu(int x, int y); void activate(int x, int y); void secondaryActivate(int x, int y); void scroll(int delta, const QString &direction); void provideXdgActivationToken(const QString &token); public Q_SLOTS: void dataUpdated(); void contextMenuReady(QMenu *menu); Q_SIGNALS: void itemDataChanged(const QString &source); void activateResult(bool success); void itemReady(TrayItem* item); void menuStateChanged(bool state); private: TrayItemPrivate *d = nullptr; void getDesktop(); }; #endif // TRAYITEM_H ukui-sni/ukui-system-tray/plugin/tray-items-model.h0000664000175000017500000000517515153755017021404 0ustar fengfeng#ifndef TRAYITEMSMODEL_H #define TRAYITEMSMODEL_H #include #include #include #include #include #include #include "status-notifier-host.h" #include "status-notifier-item.h" #include "tray-item.h" #include "application-info.h" class ItemGroupModel; class TrayItemsModel : public QAbstractListModel { Q_OBJECT public: enum Role { Service, AttentionIcon, AttentionIconName, AttentionMovieName, Category, Icon, IconName, IconThemePath, Id, ItemIsMenu, OverlayIcon, OverlayIconName, Status, Title, ToolTipSubTitle, ToolTipTitle, WindowId, Fixed, RecordOrder, Row, Desktop }; Q_ENUM(Role) static TrayItemsModel *instance(); ~TrayItemsModel(); int rowCount(const QModelIndex &parent) const override; QVariant data(const QModelIndex &index, int role) const override; QHash roleNames() const override; void activate(const QModelIndex &index); void showContextMenu(const QModelIndex &index, QQuickItem *item); void setOrderInGroup(ItemGroupModel *group, const QModelIndex &groupIndex, int order); void setOrderBetweenGroups(ItemGroupModel *fromGroup, const QModelIndex &beginIndex, ItemGroupModel *toGroup, int order); void setSeparateIndex(int index); int getSeparateIndex(); QStringList getControlPanelItems(); void setOrder(const QModelIndex &index, int order); Q_SIGNALS: void separateIndexChanged(); void menuStateChanged(bool state); private Q_SLOTS: void addSource(const QString &source); void removeSource(const QString &source); void insertItem(TrayItem* item); void dataUpdated(const QString &sourceName); void controlStateChanged(bool controlState); private: TrayItemsModel(QObject *parent = nullptr); UkuiSni::StatusNotifierHost *m_sniHost = nullptr; UkuiSearch::ApplicationInfo *m_applicationInfo = nullptr; UkuiQuick::Config *m_config {nullptr}; QVector m_item; QStringList m_fixList; QStringList m_orderList; QStringList m_hideList; QStringList m_controlPanelList; QStringList m_canHideList; int m_currentSeparateIndex = 7; int m_separateIndex = 7; QMap m_itemInfo; static QVariant extractIcon(const QIcon &icon, const QVariant &defaultValue = QVariant()); QString getDesktop(const uint & pid); int indexOfSource(const QString &source) const; void removeItem(const QString &source); }; #endif // TRAYITEMSMODEL_H ukui-sni/ukui-system-tray/plugin/tray-items-model.cpp0000664000175000017500000004101015153755611021723 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: youdiansaodongxi * */ #include "tray-items-model.h" #include "item-group-model.h" #include "security-function-control.h" #include #include #include #include #include static std::once_flag onceFlag; static TrayItemsModel* g_instance = nullptr; static const QStringList DEFAULT_ORDERED_ITEMS = {"ukui-bluetooth", "Fcitx", "kylin-virtual-keyboard", "kylin-vpn"}; static const QStringList DEFAULT_FIXED_ITEMS = {"ukui-sidebar"}; static const QStringList DEFAULT_CONTROL_PANEL_ITEMS = {"ukui-power-manager-tray", "ukui-volume-control-applet-qt", "kylin-nm"}; static const QStringList DEFAULT_CAN_HIDE_ITEMS = {"ukui-bluetooth", "Fcitx"}; TrayItemsModel *TrayItemsModel::instance() { std::call_once(onceFlag, [ & ] { g_instance = new TrayItemsModel(); }); return g_instance; } TrayItemsModel::~TrayItemsModel() { if (!m_applicationInfo) { delete m_applicationInfo; m_applicationInfo = nullptr; } g_instance = nullptr; } TrayItemsModel::TrayItemsModel(QObject *parent) : QAbstractListModel(parent) { if (!m_config) { m_config = UkuiQuick::ConfigLoader::getConfig("org.ukui.systemTray"); } const auto &data = m_config->data(); //get separateIndex if (!data.contains(QStringLiteral("separateIndex"))) { m_config->setValue(QStringLiteral("separateIndex"), m_separateIndex); } else { m_separateIndex = m_config->getValue("separateIndex").toInt(); } //fixed items if (!data.contains(QStringLiteral("fixedItems"))) { m_fixList = DEFAULT_FIXED_ITEMS; m_config->setValue(QStringLiteral("fixedItems"), DEFAULT_FIXED_ITEMS); } else { m_fixList = m_config->getValue("fixedItems").toStringList(); } //showed items if (!data.contains(QStringLiteral("version"))) { m_config->setValue(QStringLiteral("version"), QStringLiteral("1.0")); m_orderList = DEFAULT_ORDERED_ITEMS; m_config->setValue(QStringLiteral("orderedItems"), DEFAULT_ORDERED_ITEMS); } else { if (!data.contains(QStringLiteral("orderedItems"))) { m_orderList = DEFAULT_ORDERED_ITEMS; m_config->setValue(QStringLiteral("orderedItems"), DEFAULT_ORDERED_ITEMS); } else { m_orderList = m_config->getValue(QStringLiteral("orderedItems")).toStringList(); } } //hide items m_hideList = m_config->getValue(QStringLiteral("trayIconsInhibited")).toStringList(); //2.x版本号校验 QString version = m_config->getValue("version").toString(); if (QVersionNumber::fromString(version).majorVersion() < 2) { m_controlPanelList = DEFAULT_CONTROL_PANEL_ITEMS; m_config->setValue("controlPanelItems", DEFAULT_CONTROL_PANEL_ITEMS); for (const QString & item : DEFAULT_CONTROL_PANEL_ITEMS) { m_fixList.removeAll(item); m_orderList.removeAll(item); m_hideList.removeAll(item); } m_config->setValue("fixedItems", m_fixList); m_config->setValue("orderedItems", m_orderList); m_config->setValue("trayIconsInhibited", m_hideList); m_config->setValue("version", "2.0"); } else { m_controlPanelList = m_config->getValue("controlPanelItems").toStringList(); } //2.1版本号校验,新增trayIconsCanInhibited if (QVersionNumber::fromString(version).minorVersion() < 1) { m_config->setValue("version", "2.1"); } //2.2版本号校验,从可隐藏列表中移除vpn if (QVersionNumber::fromString(version).minorVersion() < 2) { m_hideList.removeAll("kylin-vpn"); m_config->setValue("trayIconsInhibited", m_hideList); m_config->setValue("version", "2.2"); } //固定的items放在order items的前面 m_orderList = m_fixList + m_orderList; m_sniHost = UkuiSni::StatusNotifierHost::self(); m_sniHost->registerHost(); m_applicationInfo = new UkuiSearch::ApplicationInfo; connect(m_config, &UkuiQuick::Config::configChanged, this, [=] { QStringList hidelist = m_config->getValue(QStringLiteral("trayIconsInhibited")).toStringList(); for (QString &itemId : hidelist) { if (!m_hideList.contains(itemId)) { //处理新增的隐藏 m_hideList.append(itemId); QStringList sourceList = m_itemInfo.keys(itemId); for (QString &itemSource : sourceList) { removeItem(itemSource); } } } QStringList list = m_hideList; for (QString &itemId : list) { if (!hidelist.contains(itemId)) { //处理新增的显示 m_hideList.removeOne(itemId); QStringList sourceList = m_itemInfo.keys(itemId); for (QString &itemSource : sourceList) { addSource(itemSource); } } } }); connect(m_sniHost, &UkuiSni::StatusNotifierHost::itemAdded, this, &TrayItemsModel::addSource); connect(m_sniHost, &UkuiSni::StatusNotifierHost::itemRemoved, this, &TrayItemsModel::removeSource); connect(SecurityFunctionControl::instance(), &SecurityFunctionControl::controlEnabledChanged, this, &TrayItemsModel::controlStateChanged); for (auto &service : m_sniHost->services()) { addSource(service); } m_config->forceSync(); } int TrayItemsModel::rowCount(const QModelIndex &parent) const { return m_item.length(); } QVariant TrayItemsModel::data(const QModelIndex &index, int role) const { int i = index.row(); if ((i < 0) || (i >= m_item.length())) { return QVariant(); } TrayItem* item = m_item[i]; switch (static_cast(role)) { case Role::Service: return item->service(); case Role::AttentionIcon: return item->attentionIcon(); case Role::AttentionIconName: return item->attentionIconName(); case Role::AttentionMovieName: return item->attentionMovieName(); case Role::Category: return item->category(); case Role::Icon: return item->icon(); case Role::IconName: return item->iconName(); case Role::IconThemePath: return item->iconThemePath(); case Role::Id: return item->id(); case Role::ItemIsMenu: return item->itemIsMenu(); case Role::OverlayIcon: return item->overlayIcon(); case Role::OverlayIconName: return item->overlayIconName(); case Role::Status: return item->status(); case Role::Title: return item->title(); case Role::ToolTipSubTitle: return item->toolTipSubTitle(); case Role::ToolTipTitle: return item->toolTipTitle(); case Role::WindowId: return item->windowId(); case Role::Fixed: return item->fixed(); case Role::RecordOrder: return item->recordOrder(); case Role::Row: return index.row(); case Role::Desktop: return item->desktop(); default: return {}; } } QHash TrayItemsModel::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 TrayItemsModel::activate(const QModelIndex &index) { if (!index.isValid()) return; m_item.at(index.row())->activate(QCursor::pos().x(), QCursor::pos().y()); } void TrayItemsModel::showContextMenu(const QModelIndex &index, QQuickItem *item) { if (!index.isValid()) return; m_item.at(index.row())->setParentItem(item); m_item.at(index.row())->contextMenu(QCursor::pos().x(), QCursor::pos().y()); } QVariant TrayItemsModel::extractIcon(const QIcon &icon, const QVariant &defaultValue) { if (!icon.isNull()) { return icon; } else { return defaultValue; } } QString TrayItemsModel::getDesktop(const uint &pid) { QString desktop; m_applicationInfo->tranPidToDesktopFp(pid, desktop); return desktop; } int TrayItemsModel::indexOfSource(const QString &source) const { for (int i = 0; i < rowCount(QModelIndex()); i++) { if (m_item[i]->source() == source) { return i; } } return -1; } void TrayItemsModel::removeItem(const QString &source) { int i = indexOfSource(source); if (i >= 0) { auto item = m_item.at(i); beginRemoveRows({}, i, i); m_item.removeAt(i); endRemoveRows(); if (item) { item->disconnect(); item->deleteLater(); } } Q_EMIT dataChanged(index(i, 0, {}), index(m_item.size() - 1, 0, {}), {Role::Row}); } void TrayItemsModel::setOrderInGroup(ItemGroupModel *group, const QModelIndex &groupIndex, int order) { int end = group->groupEnd(); int newOrder = group->groupBegin() + order; if(newOrder > end) { newOrder = end; } setOrder(group->mapToSource(groupIndex), newOrder); } void TrayItemsModel::setOrderBetweenGroups(ItemGroupModel *fromGroup, const QModelIndex &beginIndex, ItemGroupModel *toGroup, int order) { int newOrder = toGroup->groupBegin() + order; if(newOrder > toGroup->groupEnd()) { newOrder = toGroup->groupEnd() + 1; } setOrder(fromGroup->mapToSource(beginIndex), newOrder); } void TrayItemsModel::setSeparateIndex(int index) { m_separateIndex = index; if (m_separateIndex > m_item.length() - 1) { m_separateIndex = m_item.length() - 1; } Q_EMIT separateIndexChanged(); m_config->setValue(QStringLiteral("separateIndex"), index); m_config->forceSync(); } void TrayItemsModel::setOrder(const QModelIndex &index, int order) { int oldRow = index.row(); if ((oldRow < 0) || (oldRow >= m_item.length())) { return; } auto item = m_item.at(oldRow); if(item->fixed()) { return; } if(oldRow == order) { return; } QString id = m_item.at(index.row())->id(); if(order > oldRow) { if(item->recordOrder()) { QString idBefore; for(int row = order; row > oldRow; --row) { if(m_item.at(row)->recordOrder()) { idBefore = m_item.at(row)->id(); break; } } if(!idBefore.isEmpty()) { int targetOrder = m_orderList.indexOf(idBefore); m_orderList.insert(targetOrder, m_orderList.takeAt(m_orderList.indexOf(id))); m_config->setValue(QStringLiteral("orderedItems"), QStringList(m_orderList.mid(m_fixList.size()))); } } beginMoveRows(index.parent(), oldRow, oldRow, index.parent(), order + 1); m_item.insert(order, m_item.takeAt(oldRow)); endMoveRows(); Q_EMIT dataChanged(this->index(oldRow, 0), this->index(order, 0), {Role::Row}); } else { if(item->recordOrder()) { QString idAfter; for(int row = order; row < oldRow; ++row) { if(m_item.at(row)->recordOrder()) { idAfter = m_item.at(row)->id(); break; } } if(!idAfter.isEmpty()) { int targetOrder = m_orderList.indexOf(idAfter); m_orderList.insert(targetOrder, m_orderList.takeAt(m_orderList.indexOf(id))); m_config->setValue(QStringLiteral("orderedItems"), QStringList(m_orderList.mid(m_fixList.size()))); } } beginMoveRows(index.parent(), oldRow, oldRow, index.parent(), order); m_item.insert(order, m_item.takeAt(oldRow)); endMoveRows(); Q_EMIT dataChanged(this->index(order, 0), this->index(oldRow, 0), {Role::Row}); } m_config->forceSync(); } int TrayItemsModel::getSeparateIndex() { return m_separateIndex; } QStringList TrayItemsModel::getControlPanelItems() { return m_controlPanelList; } void TrayItemsModel::addSource(const QString &source) { for (TrayItem* &trayItem : m_item) { if (trayItem->source() == source) { return; } } auto item = new TrayItem(source); if (SecurityFunctionControl::instance()->controlEnabled()) { item->setDesktop(getDesktop(item->pid())); } connect(item, &TrayItem::itemReady, this, &TrayItemsModel::insertItem); if (item->id() != "") { insertItem(item); } } void TrayItemsModel::removeSource(const QString &source) { QString id = m_itemInfo.value(source); if (DEFAULT_CAN_HIDE_ITEMS.contains(id)) { m_canHideList.removeAll(id); m_config->setValue("trayIconsCanInhibited", m_canHideList); } m_itemInfo.remove(source); removeItem(source); } void TrayItemsModel::insertItem(TrayItem* item) { if (m_item.contains(item)) return; m_itemInfo.insert(item->source(), item->id()); if (DEFAULT_CAN_HIDE_ITEMS.contains(item->id())) { if (!m_canHideList.contains(item->id())) { m_canHideList.append(item->id()); m_config->setValue("trayIconsCanInhibited", m_canHideList); } } if (m_hideList.contains(item->id())) { removeItem(item->source()); return; } int order = m_item.size(); for(const QString &id : m_orderList) { if(id == item->id()) { int index = m_orderList.indexOf(id); if(index <= m_fixList.size() - 1) { item->setFixed(true); } else { item->setRecordOrder(true); } //index为0表示第一个 if(index == 0) { order = 0; } else if(index > 0){ bool find = false; //寻找前一个item所在的位置,前一个item未注册时寻找再前一个的位置 for(int preIndex = index - 1; preIndex >= 0 && !find; preIndex--) { QString preId = m_orderList.at(preIndex); for(int i = 0; i < m_item.size(); i++) { if(m_item.at(i)->id() == preId) { order = i + 1; find = true; break; } } } //找不到放到第一个 if(!find) { order = 0; } } break; } } beginInsertRows(QModelIndex(), order, order); m_item.insert(order, item); endInsertRows(); Q_EMIT dataChanged(index(order, 0, {}), index(m_item.size() - 1, 0, {}), {Role::Row}); connect(item, &TrayItem::itemDataChanged, this, &TrayItemsModel::dataUpdated); connect(item, &TrayItem::menuStateChanged, this, &TrayItemsModel::menuStateChanged); } void TrayItemsModel::dataUpdated(const QString &sourceName) { for (TrayItem* &trayItem : m_item) { if (trayItem->source() == sourceName) { int i = indexOfSource(sourceName); if (i >= 0) { Q_EMIT dataChanged(index(i, 0, {}), index(i, 0, {})); } return; } } } void TrayItemsModel::controlStateChanged(bool controlState) { if (controlState) { for (int i = 0; i < rowCount(QModelIndex()); i++) { if (m_item[i]->desktop() != "") continue; m_item[i]->setDesktop(getDesktop(m_item[i]->pid())); Q_EMIT dataChanged(index(i, 0, {}), index(i, 0, {}), {Role::Desktop}); } } } ukui-sni/ukui-system-tray/plugin/items-filter-model.cpp0000664000175000017500000000722015153755017022236 0ustar fengfeng/* * 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: youdiansaodongxi * */ #include "items-filter-model.h" #include "tray-items-model.h" #include "item-group-model.h" #include "security-function-control.h" #include ItemsFilterModel *ItemsFilterModel::instance() { static ItemsFilterModel model; return &model; } QVariant ItemsFilterModel::data(const QModelIndex &index, int role) const { return sourceModel()->data(mapToSource(index), role); } void ItemsFilterModel::activate(const QModelIndex &index) { if (SecurityFunctionControl::instance()->canLeftClick(index.data(TrayItemsModel::Desktop).toString())) { m_sourceModel->activate(mapToSource(index)); } } void ItemsFilterModel::showContextMenu(const QModelIndex &index, QQuickItem *item) { if (SecurityFunctionControl::instance()->canRightClick(index.data(TrayItemsModel::Desktop).toString())) { m_sourceModel->showContextMenu(mapToSource(index), item); } } void ItemsFilterModel::setOrderInGroup(ItemGroupModel *group, const QModelIndex &groupIndex, int order) { int end = group->groupEnd(); int newOrder = group->groupBegin() + order; if(newOrder > end) { newOrder = end; } m_sourceModel->setOrder(mapToSource(group->mapToSource(groupIndex)), mapToSource(this->index(newOrder, 0)).row()); } void ItemsFilterModel::setOrderBetweenGroups(ItemGroupModel *fromGroup, const QModelIndex &beginIndex, ItemGroupModel *toGroup, int order) { int newOrder = toGroup->groupBegin() + order; if(newOrder > toGroup->groupEnd()) { newOrder = toGroup->groupEnd() + 1; } m_sourceModel->setOrder(mapToSource(fromGroup->mapToSource(beginIndex)), mapToSource(this->index(newOrder, 0)).row()); } void ItemsFilterModel::setSeparateIndex(int index) { if (index > rowCount() - 1) { index = rowCount() - 1; } m_sourceModel->setSeparateIndex(index); } int ItemsFilterModel::getSeparateIndex() { return m_sourceModel->getSeparateIndex(); } bool ItemsFilterModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { QModelIndex sourceIndex = sourceModel()->index(source_row, 0, source_parent); return SecurityFunctionControl::instance()->canAppDisplay(sourceIndex.data(TrayItemsModel::Desktop).toString()) && !m_sourceModel->getControlPanelItems().contains(sourceIndex.data(TrayItemsModel::Id).toString()); } ItemsFilterModel::ItemsFilterModel(QObject *parent) : QSortFilterProxyModel(parent) { setSourceModel(TrayItemsModel::instance()); m_sourceModel = TrayItemsModel::instance(); connect(m_sourceModel, &TrayItemsModel::menuStateChanged, this, &ItemsFilterModel::menuStateChanged); connect(SecurityFunctionControl::instance(), &SecurityFunctionControl::appWhiteListChanged, this, &ItemsFilterModel::invalidateFilter); connect(SecurityFunctionControl::instance(), &SecurityFunctionControl::appBlackListChanged, this, &ItemsFilterModel::invalidateFilter); } ukui-sni/ukui-system-tray/plugin/system-tray-plugin.cpp0000664000175000017500000000333115153755017022330 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: iaom * */ #include "system-tray-plugin.h" #include "items-filter-model.h" #include "item-group-model.h" #include "security-function-control.h" #include "control-panel-model.h" #include #include void SystemTrayPlugin::registerTypes(const char *uri) { Q_ASSERT(QLatin1String(uri) == QLatin1String("org.ukui.systemTray")); qmlRegisterUncreatableType(uri,1,0,"ItemGroupModel", ""); qmlRegisterType(uri, 1, 0, "GroupModel"); qmlRegisterSingletonType(uri,1,0,"ItemModel", [] (QQmlEngine *, QJSEngine *) -> QObject* { return ItemsFilterModel::instance(); }); qmlRegisterSingletonType(uri,1,0,"FunctionControl", [] (QQmlEngine *, QJSEngine *) -> QObject* { return SecurityFunctionControl::instance(); }); qmlRegisterSingletonType(uri,1,0,"ControlPanelModel", [] (QQmlEngine *, QJSEngine *) -> QObject* { return ControlPanelModel::self(); }); } ukui-sni/ukui-system-tray/plugin/system-tray-plugin.h0000664000175000017500000000051715153755017022000 0ustar fengfeng#ifndef UKUI_PANEL_START_MENU_PLUGIN_H #define UKUI_PANEL_START_MENU_PLUGIN_H #include class SystemTrayPlugin : public QQmlExtensionPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID QQmlExtensionInterface_iid) public: void registerTypes(const char *uri) override; }; #endif //UKUI_PANEL_START_MENU_PLUGIN_H ukui-sni/ukui-system-tray/plugin/security-function-control.h0000664000175000017500000000525015153755017023352 0ustar fengfeng/* * 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: youdiansaodongxi * */ #ifndef SECURITYFUNCTIONCONTROL_H #define SECURITYFUNCTIONCONTROL_H #include #include #include class SecurityFunctionControl : public QObject { Q_OBJECT public: static SecurityFunctionControl *instance(); Q_PROPERTY(bool disableMouseLeftButton READ disableMouseLeftButton NOTIFY disableMouseLeftButtonChanged) Q_PROPERTY(bool disableMouseRightButton READ disableMouseRightButton NOTIFY disableMouseRightButtonChanged) Q_PROPERTY(bool disableMouseHover READ disableMouseHover NOTIFY disableMouseHoverChanged) bool disableMouseLeftButton() const; bool disableMouseRightButton() const; bool disableMouseHover() const; QStringList appWhiteList() const; QStringList appBlackList() const; QStringList leftClickBlackList() const; QStringList rightClickBlackList() const; bool canAppDisplay(const QString &desktop) const; bool canLeftClick(const QString &desktop) const; bool canRightClick(const QString &desktop) const; bool controlEnabled() const; Q_SIGNALS: void disableMouseLeftButtonChanged(); void disableMouseRightButtonChanged(); void disableMouseHoverChanged(); void appWhiteListChanged(); void appBlackListChanged(); void leftClickBlackListChanged(); void rightClickBlackListChanged(); void controlEnabledChanged(bool controlEnabled); private: explicit SecurityFunctionControl(QObject *parent = nullptr); bool compareListBySort(QStringList &list1, QStringList &list2); bool m_disableMouseLeftButton {false}; bool m_disableMouseRightButton {false}; bool m_disableMouseHover {false}; QStringList m_appWhiteList {}; QStringList m_appBlackList {}; QStringList m_leftClickBlackList {}; QStringList m_rightClickBlackList {}; bool m_controlEnabled {false}; private Q_SLOTS: void onFunctionControlChanged(const QString& name, bool exit = false); }; #endif // SECURITYFUNCTIONCONTROL_H ukui-sni/ukui-system-tray/plugin/item-group-model.cpp0000664000175000017500000001016015153755017021717 0ustar fengfeng/* * 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: youdiansaodongxi * */ #include "item-group-model.h" #include "tray-items-model.h" #include "items-filter-model.h" #include "security-function-control.h" #include #include ItemGroupModel::ItemGroupModel(QObject *parent) : QSortFilterProxyModel(parent) { QSortFilterProxyModel::setSourceModel(ItemsFilterModel::instance()); m_sourceModel = ItemsFilterModel::instance(); setFilterRole(TrayItemsModel::Row); connect(TrayItemsModel::instance(), &TrayItemsModel::separateIndexChanged, this, &ItemGroupModel::onSeparateIndexChanged); setCurrentSeparateIndex(m_sourceModel->getSeparateIndex()); } void ItemGroupModel::setModelType(GroupType type) { m_groupType = type; } ItemGroupModel::GroupType ItemGroupModel::getModelType() { return m_groupType; } int ItemGroupModel::currentSeparateIndex() { return m_currentSeparateIndex; } void ItemGroupModel::setCurrentSeparateIndex(int index) { if (index < 0) return; m_currentSeparateIndex = index; invalidateFilter(); Q_EMIT currentSeparateIndexChanged(); } int ItemGroupModel::showCount() { return m_showCount; } void ItemGroupModel::setShowCount(int index) { m_showCount = index <= 0 ? 0 : index; onShowCountChanged(); Q_EMIT showCountChanged(); } void ItemGroupModel::onActivate(const QModelIndex &index) { m_sourceModel->activate(mapToSource(index)); } void ItemGroupModel::onContextMenu(const QModelIndex &index, QQuickItem *item) { m_sourceModel->showContextMenu(mapToSource(index), item); } QVariant ItemGroupModel::data(const QModelIndex &index, int role) const { return sourceModel()->data(mapToSource(index), role); } QVariant ItemGroupModel::foldIcon() { return QIcon::fromTheme("ukui-end-symbolic"); } int ItemGroupModel::groupBegin() const { if (m_groupType == GroupType::Show) { return 0; } else if (m_groupType == GroupType::Fold) { return m_currentSeparateIndex + 1; } } int ItemGroupModel::groupEnd() const { if (m_groupType == GroupType::Show) { return m_currentSeparateIndex; } else if (m_groupType == GroupType::Fold) { return m_sourceModel->rowCount(QModelIndex()) - 1; } } bool ItemGroupModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { if (m_groupType == GroupType::Show) { return source_row >= 0 && source_row <= m_currentSeparateIndex; } else if (m_groupType == GroupType::Fold) { return source_row > m_currentSeparateIndex && source_row <= (m_sourceModel->rowCount(QModelIndex()) - 1); } return true; } void ItemGroupModel::onShowCountChanged() { if (m_showCount < m_currentSeparateIndex) { if (m_showCount <= 0) { setCurrentSeparateIndex(0); } else { setCurrentSeparateIndex(m_showCount); } } else { if (m_currentSeparateIndex != m_sourceModel->getSeparateIndex()) { if (m_sourceModel->getSeparateIndex() < m_showCount) { setCurrentSeparateIndex(m_sourceModel->getSeparateIndex()); } else { setCurrentSeparateIndex(m_showCount); } } } Q_EMIT currentSeparateIndexChanged(); } void ItemGroupModel::onSeparateIndexChanged() { setCurrentSeparateIndex(m_showCount < m_sourceModel->getSeparateIndex() ? m_showCount : m_sourceModel->getSeparateIndex()); Q_EMIT currentSeparateIndexChanged(); } ukui-sni/ukui-system-tray/plugin/item-group-model.h0000664000175000017500000000341515153755017021371 0ustar fengfeng#ifndef ITEMGROUPMODEL_H #define ITEMGROUPMODEL_H #include #include #include #include #include #include #include "tray-item.h" class ItemsFilterModel; class ItemGroupModel : public QSortFilterProxyModel { Q_OBJECT Q_PROPERTY(GroupType modelType READ getModelType WRITE setModelType) Q_PROPERTY(int currentSeparateIndex READ currentSeparateIndex WRITE setCurrentSeparateIndex NOTIFY currentSeparateIndexChanged) Q_PROPERTY(int showCount READ showCount WRITE setShowCount NOTIFY showCountChanged) public: enum GroupType {Show, Fold}; Q_ENUM(GroupType) explicit ItemGroupModel(QObject *parent = nullptr); void setModelType(GroupType type); GroupType getModelType(); int currentSeparateIndex(); void setCurrentSeparateIndex(int index); int showCount(); void setShowCount(int index); QVariant data(const QModelIndex &index, int role) const override; Q_INVOKABLE void onActivate(const QModelIndex &index); Q_INVOKABLE void onContextMenu(const QModelIndex &index, QQuickItem *item); Q_INVOKABLE QVariant foldIcon(); Q_INVOKABLE int groupBegin() const; Q_INVOKABLE int groupEnd() const; Q_SIGNALS: void currentSeparateIndexChanged(); void showCountChanged(); protected: bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; private: void onShowCountChanged(); void onSeparateIndexChanged(); QHash m_order; ItemsFilterModel *m_sourceModel = nullptr; int m_groupBegin = 0; int m_groupEnd = 0; GroupType m_groupType = GroupType::Show; int m_currentSeparateIndex = 0; int m_showCount = 0; }; #endif // ITEMGROUPMODEL_H ukui-sni/CMakeLists.txt0000664000175000017500000000145215153755611014017 0ustar fengfengcmake_minimum_required(VERSION 3.14) project(ukui-sni VERSION 1.0 LANGUAGES C CXX) set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_AUTOUIC ON) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) find_package(QT NAMES Qt6 Qt5 COMPONENTS Core DBus Network Gui Widgets Quick REQUIRED) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core DBus Network Gui Widgets Quick REQUIRED) if (QT_VERSION_MAJOR EQUAL 5) find_package(Qt5 COMPONENTS X11Extras REQUIRED) elseif (QT_VERSION_MAJOR EQUAL 6) find_package(Qt6 COMPONENTS GuiPrivate REQUIRED) endif() add_subdirectory(status-notifier-watcher) add_subdirectory(status-notifier-host) add_subdirectory(ukui-system-tray) add_subdirectory(xembed-sni-proxy) if(BUILD_TEST) add_subdirectory(test) endif() ukui-sni/status-notifier-host/0000775000175000017500000000000015153755611015370 5ustar fengfengukui-sni/status-notifier-host/status-notifier-host.h0000664000175000017500000000276115153755017021662 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: iaom * */ #ifndef UKUI_SNI_STATUS_NOTIFIER_HOST_H #define UKUI_SNI_STATUS_NOTIFIER_HOST_H #include #include "status-notifier-item.h" namespace UkuiSni { class StatusNotifierHostPrivate; class StatusNotifierHost : public QObject { Q_OBJECT public: static StatusNotifierHost *self(); ~StatusNotifierHost() override; void registerHost(); QList items(); const QList services() const; UkuiSni::StatusNotifierItem *itemForService(const QString service); Q_SIGNALS: void itemAdded(const QString &service); void itemRemoved(const QString &service); private: explicit StatusNotifierHost(QObject *parent = nullptr); StatusNotifierHostPrivate *d = nullptr; }; } #endif //UKUI_SNI_STATUS_NOTIFIER_HOST_H ukui-sni/status-notifier-host/ukui-sni-host.pc.in0000664000175000017500000000044315153755017021041 0ustar fengfengprefix=/usr exec_prefix=${prefix} libdir=${prefix}/lib/@CMAKE_LIBRARY_ARCHITECTURE@ includedir=${prefix}/include/ukui-sni-host Name: ukui-sni-host Description: ukui-sni-host header files URL: https://www.ukui.org/ Version: @VERSION@ Cflags: -I${includedir} Libs: -L${libdir} -lukui-sni-hostukui-sni/status-notifier-host/status-notifier-item-private.h0000664000175000017500000000607315153755017023313 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: iaom * */ #ifndef UKUI_SNI_STATUS_NOTIFIER_ITEM_PRIVATE_H #define UKUI_SNI_STATUS_NOTIFIER_ITEM_PRIVATE_H #include #include #include "dbusmenu-importer.h" #include "dbus-types.h" #include "statusnotifieritem_interface.h" namespace UkuiSni { class UkuiDBusMenuImporter : public DBusMenuImporter { public: UkuiDBusMenuImporter(const QString &service, const QString &path, QObject *parent = 0); protected: QIcon iconForName(const QString & iconName) override; }; class StatusNotifierItemPrivate : public QObject { friend class StatusNotifierItem; Q_OBJECT public: explicit StatusNotifierItemPrivate(const QString &service, StatusNotifierItem *q, QObject *parent = nullptr); void init(); void contextMenu(int x, int y); void activate(int x, int y); void secondaryActivate(int x, int y); void scroll(int delta, const QString &direction); void provideXdgActivationToken(const QString &token); private Q_SLOTS: void refresh(); void performRefresh(); void syncStatus(const QString &status); void refreshMenu(); void refreshCallback(QDBusPendingCallWatcher *call); void activateCallback(QDBusPendingCallWatcher *call); private: QIcon loadIcon(const QVariantMap &properties, const QString &iconName, const QString &pixmapKey); QPixmap DbusImageStructToPixmap(const DbusImageStruct &image) const; QIcon imageVectorToPixmap(const DbusImageVector &vector) const; static QString displayFormPid(int pid); QTimer m_refreshTimer; bool m_refreshing : 1; bool m_needsReRefreshing : 1; bool m_valid = false; QString m_serviceNamePath; QString m_serviceName; UkuiDBusMenuImporter *m_menuImporter = nullptr; int m_pendingMenuToShow = 0; org::kde::StatusNotifierItem *m_statusNotifierItemInterface = nullptr; QIcon m_attentionIcon; QString m_attentionIconName; QString m_attentionMovieName; QString m_category; QIcon m_icon; QString m_iconName; QString m_iconThemePath; QString m_id; bool m_itemIsMenu{}; QIcon m_overlayIcon; QString m_overlayIconName; QString m_status; QString m_title; QIcon m_toolTipIcon; QString m_toolTipSubTitle; QString m_toolTipTitle; QString m_windowId; QString m_display; uint m_pid = 0; StatusNotifierItem *q; }; } #endif //UKUI_SNI_STATUS_NOTIFIER_ITEM_PRIVATE_H ukui-sni/status-notifier-host/status-notifier-item.cpp0000664000175000017500000003745715153755611022210 0ustar fengfeng/* SPDX-FileCopyrightText: 2009 Marco Martin SPDX-FileCopyrightText: 2009 Matthieu Gallien SPDX-FileCopyrightText: 2023 iaom SPDX-License-Identifier: GPL-2.0-or-later */ #include "status-notifier-item.h" #include "status-notifier-item-private.h" #include #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) #include #else #include #endif #include #include using namespace UkuiSni; UkuiDBusMenuImporter::UkuiDBusMenuImporter(const QString &service, const QString &path, QObject *parent) :DBusMenuImporter(service, path, parent) { } QIcon UkuiDBusMenuImporter::iconForName(const QString &iconName) { return QIcon::fromTheme(iconName); } StatusNotifierItemPrivate::StatusNotifierItemPrivate(const QString &service, StatusNotifierItem *q, QObject *parent) : QObject(parent) , m_refreshing(false) , m_needsReRefreshing(false) , q(q) { m_serviceNamePath = service; } void StatusNotifierItemPrivate::init() { qDBusRegisterMetaType(); qDBusRegisterMetaType(); qDBusRegisterMetaType(); //service = service name + path(/StatusNotifierItem) int slash = m_serviceNamePath.indexOf('/'); QString path; if (slash == -1) { m_serviceName = m_serviceNamePath; path = QStringLiteral("/StatusNotifierItem"); } else { m_serviceName = m_serviceNamePath.left(slash); path = m_serviceNamePath.mid(slash); } m_display = displayFormPid(m_serviceNamePath.section("-", 1, 1).toInt()); m_statusNotifierItemInterface = new org::kde::StatusNotifierItem(m_serviceName, path, QDBusConnection::sessionBus()); m_refreshTimer.setSingleShot(true); m_refreshTimer.setInterval(10); connect(&m_refreshTimer, &QTimer::timeout, this, &StatusNotifierItemPrivate::performRefresh); if (!m_serviceName.isEmpty() && m_statusNotifierItemInterface->isValid()) { connect(m_statusNotifierItemInterface, &OrgKdeStatusNotifierItem::NewTitle, this, &StatusNotifierItemPrivate::refresh); connect(m_statusNotifierItemInterface, &OrgKdeStatusNotifierItem::NewIcon, this, &StatusNotifierItemPrivate::refresh); connect(m_statusNotifierItemInterface, &OrgKdeStatusNotifierItem::NewAttentionIcon, this, &StatusNotifierItemPrivate::refresh); connect(m_statusNotifierItemInterface, &OrgKdeStatusNotifierItem::NewOverlayIcon, this, &StatusNotifierItemPrivate::refresh); connect(m_statusNotifierItemInterface, &OrgKdeStatusNotifierItem::NewToolTip, this, &StatusNotifierItemPrivate::refresh); connect(m_statusNotifierItemInterface, &OrgKdeStatusNotifierItem::NewStatus, this, &StatusNotifierItemPrivate::syncStatus); connect(m_statusNotifierItemInterface, &OrgKdeStatusNotifierItem::NewMenu, this, &StatusNotifierItemPrivate::refreshMenu); refresh(); } else { qWarning() << "Invalid notifierItemService:" << m_serviceNamePath; m_valid = false; } } void StatusNotifierItemPrivate::contextMenu(int x, int y) { if (m_menuImporter) { m_menuImporter->updateMenu(); m_pendingMenuToShow ++; } else { qWarning() << "DBusMenu interface not available, falling back to calling ContextMenu()"; if (m_statusNotifierItemInterface && m_statusNotifierItemInterface->isValid()) { m_statusNotifierItemInterface->call(QDBus::NoBlock, QStringLiteral("ContextMenu"), x, y); } } } void StatusNotifierItemPrivate::activate(int x, int y) { if (m_statusNotifierItemInterface && m_statusNotifierItemInterface->isValid()) { QDBusMessage message = QDBusMessage::createMethodCall(m_statusNotifierItemInterface->service(), m_statusNotifierItemInterface->path(), m_statusNotifierItemInterface->interface(), QStringLiteral("Activate")); message << x << y; QDBusPendingCall call = m_statusNotifierItemInterface->connection().asyncCall(message); auto *watcher = new QDBusPendingCallWatcher(call, this); connect(watcher, &QDBusPendingCallWatcher::finished, this, &StatusNotifierItemPrivate::activateCallback); } } void StatusNotifierItemPrivate::refresh() { if (!m_refreshTimer.isActive()) { m_refreshTimer.start(); } } void StatusNotifierItemPrivate::performRefresh() { if (m_refreshing) { m_needsReRefreshing = true; return; } m_refreshing = true; QDBusMessage message = QDBusMessage::createMethodCall(m_statusNotifierItemInterface->service(), m_statusNotifierItemInterface->path(), QStringLiteral("org.freedesktop.DBus.Properties"), QStringLiteral("GetAll")); message << m_statusNotifierItemInterface->interface(); QDBusPendingCall call = m_statusNotifierItemInterface->connection().asyncCall(message); auto *watcher = new QDBusPendingCallWatcher(call, this); connect(watcher, &QDBusPendingCallWatcher::finished, this, &StatusNotifierItemPrivate::refreshCallback); } void StatusNotifierItemPrivate::syncStatus(const QString &status) { m_status = status; Q_EMIT q->dataUpdated(); } void StatusNotifierItemPrivate::refreshMenu() { if (m_menuImporter) { delete m_menuImporter; m_menuImporter = nullptr; } refresh(); } void StatusNotifierItemPrivate::refreshCallback(QDBusPendingCallWatcher *call) { m_refreshing = false; if (m_needsReRefreshing) { m_needsReRefreshing = false; performRefresh(); call->deleteLater(); return; } QDBusPendingReply reply = *call; if (reply.isError()) { m_valid = false; qDebug() << "Fail to refresh" << m_serviceName; } else { QVariantMap properties = reply.argumentAt<0>(); m_category = properties[QStringLiteral("Category")].toString(); m_id = properties[QStringLiteral("Id")].toString(); m_title = properties[QStringLiteral("Title")].toString(); m_status = properties[QStringLiteral("Status")].toString(); m_windowId = properties[QStringLiteral("WindowId")].toString(); m_itemIsMenu = properties[QStringLiteral("ItemIsMenu")].toBool(); m_attentionMovieName = properties[QStringLiteral("AttentionMovieName")].toString(); m_iconThemePath = properties[QStringLiteral("IconThemePath")].toString(); //TODO support overlayIcon m_overlayIcon = loadIcon(properties, m_overlayIconName, QStringLiteral("OverlayIconPixmap")); m_overlayIconName = properties[QStringLiteral("OverlayIconName")].toString(); m_iconName = properties[QStringLiteral("IconName")].toString(); m_icon = loadIcon(properties, m_iconName, QStringLiteral("IconPixmap")); m_attentionIconName = properties[QStringLiteral("AttentionIconName")].toString(); m_attentionIcon = loadIcon(properties, m_attentionIconName, QStringLiteral("AttentionIconPixmap")); DbusToolTipStruct toolTip; properties[QStringLiteral("ToolTip")].value() >> toolTip; if (toolTip.title.isEmpty()) { m_toolTipTitle = QString(); m_toolTipSubTitle = QString(); m_toolTipIcon = QIcon(); } else { QIcon toolTipIcon; if (toolTip.image.empty()) { toolTipIcon = QIcon::fromTheme(toolTip.icon); } else { toolTipIcon = imageVectorToPixmap(toolTip.image); } m_toolTipTitle = toolTip.title; m_toolTipSubTitle = toolTip.subTitle; if (toolTipIcon.isNull() || toolTipIcon.availableSizes().isEmpty()) { m_toolTipIcon = QIcon(); } else { m_toolTipIcon = toolTipIcon; } } // Menu if (!m_menuImporter) { QString menuObjectPath = properties[QStringLiteral("Menu")].value().path(); if (!menuObjectPath.isEmpty()) { if (menuObjectPath == QLatin1String("/NO_DBUSMENU")) { qWarning() << "DBusMenu disabled for this item" << m_serviceNamePath; } else { m_menuImporter = new UkuiDBusMenuImporter(m_statusNotifierItemInterface->service(), menuObjectPath, this); connect(m_menuImporter, &UkuiDBusMenuImporter::menuUpdated, this, [this](QMenu *menu) { if(m_pendingMenuToShow && menu == m_menuImporter->menu()) { --m_pendingMenuToShow; Q_EMIT q->contextMenuReady(m_menuImporter->menu()); } }); if (m_menuImporter->menu()) { connect(m_menuImporter->menu(), &QMenu::aboutToShow, this, [this] { Q_EMIT q->menuStateChange(true); }); connect(m_menuImporter->menu(), &QMenu::aboutToHide, this, [this] { Q_EMIT q->menuStateChange(false); }); } } } } } Q_EMIT q->dataUpdated(); call->deleteLater(); } QIcon StatusNotifierItemPrivate::loadIcon(const QVariantMap &properties, const QString &iconName, const QString &pixmapKey) { if(!m_iconThemePath.isEmpty()) { auto list = QIcon::fallbackSearchPaths(); list.append(m_iconThemePath); list.removeDuplicates(); QIcon::setFallbackSearchPaths(list); } if(!iconName.isEmpty()) { QIcon icon = QIcon::fromTheme(iconName); if(!icon.isNull()) { return icon; } } DbusImageVector image; properties[pixmapKey].value() >> image; if(!image.isEmpty()) { QIcon icon = imageVectorToPixmap(image); if(!icon.isNull()) { return icon; } } return {}; } QPixmap StatusNotifierItemPrivate::DbusImageStructToPixmap(const DbusImageStruct &image) const { // swap from network byte order if we are little endian if (QSysInfo::ByteOrder == QSysInfo::LittleEndian) { uint *uintBuf = (uint *)image.data.data(); for (uint i = 0; i < image.data.size() / sizeof(uint); ++i) { *uintBuf = ntohl(*uintBuf); ++uintBuf; } } if (image.width == 0 || image.height == 0) { return {}; } // avoid a deep copy of the image data // we need to keep a reference to the image.data alive for the lifespan of the image, even if the image is copied // we create a new QByteArray with a shallow copy of the original data on the heap, then delete this in the QImage cleanup auto dataRef = new QByteArray(image.data); QImage iconImage( reinterpret_cast(dataRef->data()), image.width, image.height, QImage::Format_ARGB32, [](void *ptr) { delete static_cast(ptr); }, dataRef); return QPixmap::fromImage(iconImage); } QIcon StatusNotifierItemPrivate::imageVectorToPixmap(const DbusImageVector &vector) const { QIcon icon; for (const auto & i : vector) { icon.addPixmap(DbusImageStructToPixmap(i)); } return icon; } void StatusNotifierItemPrivate::activateCallback(QDBusPendingCallWatcher *call) { QDBusPendingReply reply = *call; Q_EMIT q->activateResult(!reply.isError()); call->deleteLater(); } void StatusNotifierItemPrivate::secondaryActivate(int x, int y) { if (m_statusNotifierItemInterface && m_statusNotifierItemInterface->isValid()) { m_statusNotifierItemInterface->call(QDBus::NoBlock, QStringLiteral("SecondaryActivate"), x, y); } } void StatusNotifierItemPrivate::scroll(int delta, const QString &direction) { if (m_statusNotifierItemInterface && m_statusNotifierItemInterface->isValid()) { m_statusNotifierItemInterface->call(QDBus::NoBlock, QStringLiteral("Scroll"), delta, direction); } } void StatusNotifierItemPrivate::provideXdgActivationToken(const QString &token) { if (m_statusNotifierItemInterface && m_statusNotifierItemInterface->isValid()) { m_statusNotifierItemInterface->ProvideXdgActivationToken(token); } } QString StatusNotifierItemPrivate::displayFormPid(int pid) { QFile environFile(QStringLiteral("/proc/%1/environ").arg(QString::number(pid))); if (environFile.open(QIODevice::ReadOnly | QIODevice::Text)) { const QByteArray DISPLAY = QX11Info::isPlatformX11()? QByteArrayLiteral("DISPLAY") : QByteArrayLiteral("WAYLAND_DISPLAY"); const auto lines = environFile.readAll().split('\0'); for (const QByteArray &line : lines) { const int equalsIdx = line.indexOf('='); if (equalsIdx <= 0) { continue; } const QByteArray key = line.left(equalsIdx); if (key == DISPLAY) { const QByteArray value = line.mid(equalsIdx + 1); return value; } } } return {}; } StatusNotifierItem::StatusNotifierItem(QObject *parent) : QObject(parent) ,d(new StatusNotifierItemPrivate({}, this, this)) { } StatusNotifierItem::StatusNotifierItem(const QString &service, QObject *parent): QObject(parent) ,d(new StatusNotifierItemPrivate(service, this, this)) { d->init(); } void StatusNotifierItem::setServiceName(const QString &service) { if(d) { delete d; } d = new StatusNotifierItemPrivate(service, this, this); d->init(); } void StatusNotifierItem::setPid(const uint &pid) { d->m_pid = pid; } void StatusNotifierItem::contextMenu(int x, int y) { d->contextMenu(x, y); } void StatusNotifierItem::activate(int x, int y) { d->activate(x, y); } void StatusNotifierItem::secondaryActivate(int x, int y) { d->secondaryActivate(x, y); } void StatusNotifierItem::scroll(int delta, const QString &direction) { d->scroll(delta, direction); } void StatusNotifierItem::provideXdgActivationToken(const QString &token) { d->provideXdgActivationToken(token); } QString StatusNotifierItem::service() { return d->m_serviceName; } QIcon StatusNotifierItem::attentionIcon() const { return d->m_attentionIcon; } QString StatusNotifierItem::attentionIconName() const { return d->m_attentionIconName; } QString StatusNotifierItem::attentionMovieName() const { return d->m_attentionMovieName; } QString StatusNotifierItem::category() const { return d->m_category; } QIcon StatusNotifierItem::icon() const { return d->m_icon; } QString StatusNotifierItem::iconName() const { return d->m_iconName; } QString StatusNotifierItem::id() const { return d->m_id; } bool StatusNotifierItem::itemIsMenu() const { return d->m_itemIsMenu; } QIcon StatusNotifierItem::overlayIcon() const { return d->m_overlayIcon; } QString StatusNotifierItem::overlayIconName() const { return d->m_overlayIconName; } QString StatusNotifierItem::status() const { return d->m_status; } QString StatusNotifierItem::title() const { return d->m_title; } QVariant StatusNotifierItem::toolTipIcon() const { return d->m_toolTipIcon; } QString StatusNotifierItem::toolTipSubTitle() const { return d->m_toolTipSubTitle; } QString StatusNotifierItem::toolTipTitle() const { return d->m_toolTipTitle; } QString StatusNotifierItem::windowId() const { return d->m_windowId; } QString StatusNotifierItem::display() const { return d->m_display; } uint StatusNotifierItem::pid() const { return d->m_pid; } QString StatusNotifierItem::iconThemePath() const { return d->m_iconThemePath; } ukui-sni/status-notifier-host/CMakeLists.txt0000664000175000017500000001016515153755611020133 0ustar fengfengproject(ukui-sni-host VERSION 1.0 LANGUAGES C CXX) set(VERSION_MAJOR 1) set(VERSION_MINOR 0) set(VERSION_MICRO 0) set(UKUI_SNI_HOST_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_MICRO}) include_directories(../common) set(ukui-sni-host_LIB_SRCS status-notifier-host.cpp ../common/dbus-types.cpp status-notifier-item.cpp status-notifier-item-private.h libdbusmenu-qt/dbusmenu-importer.cpp libdbusmenu-qt/dbusmenu-importer.h libdbusmenu-qt/dbusmenu-shortcut_p.cpp libdbusmenu-qt/dbusmenu-shortcut_p.h libdbusmenu-qt/dbusmenu-types_p.cpp libdbusmenu-qt/dbusmenu-types_p.h libdbusmenu-qt/utils.cpp libdbusmenu-qt/utils_p.h ) set(HEADERS status-notifier-host.h status-notifier-item.h ) set(statusnotifierwatcher_xml ../dbus/org.kde.StatusNotifierWatcher.xml) set_source_files_properties(${statusnotifierwatcher_xml} PROPERTIES NO_NAMESPACE false INCLUDE "../common/dbus-types.h" ) qt_add_dbus_interface(ukui-sni-host_LIB_SRCS ${statusnotifierwatcher_xml} statusnotifierwatcher_interface) qt_add_dbus_interface(ukui-sni-host_LIB_SRCS ../dbus/org.freedesktop.DBus.Properties.xml dbusproperties) set(statusnotifieritem_xml ../dbus/org.kde.StatusNotifierItem.xml) set_source_files_properties(${statusnotifieritem_xml} PROPERTIES NO_NAMESPACE false INCLUDE "../common/dbus-types.h" CLASSNAME OrgKdeStatusNotifierItem ) qt_add_dbus_interface(ukui-sni-host_LIB_SRCS ${statusnotifieritem_xml} statusnotifieritem_interface) set_source_files_properties(libdbusmenu-qt/com.canonical.dbusmenu.xml PROPERTIES NO_NAMESPACE true INCLUDE "dbusmenu-types_p.h" CLASSNAME DBusMenuInterface ) qt_add_dbus_interface(ukui-sni-host_LIB_SRCS libdbusmenu-qt/com.canonical.dbusmenu.xml dbusmenu_interface) include_directories(../common libdbusmenu-qt) add_library(${PROJECT_NAME} SHARED ${ukui-sni-host_LIB_SRCS}) set_target_properties(${PROJECT_NAME} PROPERTIES VERSION ${UKUI_SNI_HOST_VERSION} SOVERSION ${VERSION_MAJOR} OUTPUT_NAME ${PROJECT_NAME} ) target_link_libraries(${PROJECT_NAME} PRIVATE Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::DBus Qt${QT_VERSION_MAJOR}::Gui Qt${QT_VERSION_MAJOR}::Widgets ) if (QT_VERSION_MAJOR EQUAL 5) target_link_libraries(${PROJECT_NAME} PRIVATE Qt5::X11Extras ) elseif(QT_VERSION_MAJOR EQUAL 6) target_link_libraries(${PROJECT_NAME} PRIVATE Qt6::GuiPrivate ) endif() include(CMakePackageConfigHelpers) set(CMAKE_CONFIG_INSTALL_DIR "/usr/share/cmake/ukui-sni-host") set(HEADERS_INSTALL_DIR /usr/include/ukui-sni-host) set(PC_INSTALL_DIR "/usr/lib/${CMAKE_LIBRARY_ARCHITECTURE}/pkgconfig") target_include_directories(${PROJECT_NAME} PUBLIC $) configure_package_config_file( "${CMAKE_CURRENT_SOURCE_DIR}/ukui-sni-host-config.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/ukui-sni-host-config.cmake" INSTALL_DESTINATION ${CMAKE_CONFIG_INSTALL_DIR}) write_basic_package_version_file( ${CMAKE_CURRENT_BINARY_DIR}/ukui-sni-host-config-version.cmake VERSION ${LIBUKUI_SEARCH_VERSION} COMPATIBILITY SameMajorVersion ) configure_package_config_file( "${CMAKE_CURRENT_SOURCE_DIR}/ukui-sni-host.pc.in" "${CMAKE_CURRENT_BINARY_DIR}/pkgconfig/ukui-sni-host.pc" INSTALL_DESTINATION ${PC_INSTALL_DIR}) install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} PUBLIC_HEADER DESTINATION ${HEADERS_INSTALL_DIR} LIBRARY DESTINATION /usr/lib/${CMAKE_LIBRARY_ARCHITECTURE} ) install(EXPORT ${PROJECT_NAME} FILE ${PROJECT_NAME}-targets.cmake DESTINATION ${CMAKE_CONFIG_INSTALL_DIR}) install(FILES ${HEADERS} DESTINATION ${HEADERS_INSTALL_DIR}) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/pkgconfig/ukui-sni-host.pc DESTINATION ${PC_INSTALL_DIR}) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/ukui-sni-host-config.cmake ${CMAKE_CURRENT_BINARY_DIR}/ukui-sni-host-config-version.cmake DESTINATION ${CMAKE_CONFIG_INSTALL_DIR}) ukui-sni/status-notifier-host/status-notifier-item.h0000664000175000017500000000450315153755017021637 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: iaom * */ #ifndef UKUI_SNI_STATUS_NOTIFIER_ITEM_H #define UKUI_SNI_STATUS_NOTIFIER_ITEM_H #include #include namespace UkuiSni { class StatusNotifierItemPrivate; class StatusNotifierItem: public QObject { Q_OBJECT public: explicit StatusNotifierItem(QObject *parent = nullptr); explicit StatusNotifierItem(const QString &service, QObject *parent = nullptr); Q_DISABLE_COPY(StatusNotifierItem) //service name + path void setServiceName(const QString &service); void setPid(const uint &pid); void contextMenu(int x, int y); void activate(int x, int y); void secondaryActivate(int x, int y); void scroll(int delta, const QString &direction); void provideXdgActivationToken(const QString &token); QString service(); QIcon attentionIcon() const; QString attentionIconName() const; QString attentionMovieName() const; QString category() const; QIcon icon() const; QString iconName() const; QString iconThemePath() const; QString id() const; bool itemIsMenu() const; QIcon overlayIcon() const; QString overlayIconName() const; QString status() const; QString title() const; QVariant toolTipIcon() const; QString toolTipSubTitle() const; QString toolTipTitle() const; QString windowId() const; QString display() const; uint pid() const; Q_SIGNALS: void contextMenuReady(QMenu *menu); void activateResult(bool success); void dataUpdated(); void menuStateChange(bool state); private: StatusNotifierItemPrivate *d = nullptr; }; } #endif //UKUI_SNI_STATUS_NOTIFIER_ITEM_H ukui-sni/status-notifier-host/ukui-sni-host-config.cmake.in0000664000175000017500000000041115153755017022755 0ustar fengfeng@PACKAGE_INIT@ include(CMakeFindDependencyMacro) find_dependency(Qt@QT_VERSION_MAJOR@Core) find_dependency(Qt@QT_VERSION_MAJOR@Widgets) if(TARGET Qt6::Core) find_dependency(Qt6Core5Compat) endif() include("${CMAKE_CURRENT_LIST_DIR}/ukui-sni-host-targets.cmake")ukui-sni/status-notifier-host/libdbusmenu-qt/0000775000175000017500000000000015153755017020323 5ustar fengfengukui-sni/status-notifier-host/libdbusmenu-qt/com.canonical.dbusmenu.xml0000664000175000017500000000417115153755017025375 0ustar fengfeng ukui-sni/status-notifier-host/libdbusmenu-qt/dbusmenu-shortcut_p.cpp0000664000175000017500000000470015153755017025042 0ustar fengfeng/* This file is part of the dbusmenu-qt library SPDX-FileCopyrightText: 2009 Canonical SPDX-FileContributor: Aurelien Gateau SPDX-FileContributor: iaom SPDX-License-Identifier: LGPL-2.0-or-later */ #include "dbusmenu-shortcut_p.h" // Qt #include static const int QT_COLUMN = 0; static const int DM_COLUMN = 1; static void processKeyTokens(QStringList *tokens, int srcCol, int dstCol) { struct Row { const char *zero; const char *one; const char *operator[](int col) const { return col == 0 ? zero : one; } }; static const Row table[] = {{"Meta", "Super"}, {"Ctrl", "Control"}, // Special cases for compatibility with libdbusmenu-glib which uses // "plus" for "+" and "minus" for "-". // cf https://bugs.launchpad.net/libdbusmenu-qt/+bug/712565 {"+", "plus"}, {"-", "minus"}, {nullptr, nullptr}}; const Row *ptr = table; for (; ptr->zero != nullptr; ++ptr) { const char *from = (*ptr)[srcCol]; const char *to = (*ptr)[dstCol]; tokens->replaceInStrings(from, to); } } DBusMenuShortcut DBusMenuShortcut::fromKeySequence(const QKeySequence &sequence) { QString string = sequence.toString(); DBusMenuShortcut shortcut; QStringList tokens = string.split(QStringLiteral(", ")); Q_FOREACH (QString token, tokens) { // Hack: Qt::CTRL | Qt::Key_Plus is turned into the string "Ctrl++", // but we don't want the call to token.split() to consider the // second '+' as a separator so we replace it with its final value. token.replace(QLatin1String("++"), QLatin1String("+plus")); QStringList keyTokens = token.split('+'); processKeyTokens(&keyTokens, QT_COLUMN, DM_COLUMN); shortcut << keyTokens; } return shortcut; } QKeySequence DBusMenuShortcut::toKeySequence() const { QStringList tmp; Q_FOREACH (const QStringList &keyTokens_, *this) { QStringList keyTokens = keyTokens_; processKeyTokens(&keyTokens, DM_COLUMN, QT_COLUMN); tmp << keyTokens.join(QLatin1String("+")); } QString string = tmp.join(QLatin1String(", ")); return QKeySequence::fromString(string); } ukui-sni/status-notifier-host/libdbusmenu-qt/dbusmenu-importer.h0000664000175000017500000000472415153755017024164 0ustar fengfeng/* This file is part of the dbusmenu-qt library SPDX-FileCopyrightText: 2009 Canonical SPDX-FileContributor: Aurelien Gateau SPDX-FileContributor: iaom SPDX-License-Identifier: LGPL-2.0-or-later */ #pragma once // Qt #include class QAction; class QDBusPendingCallWatcher; class QIcon; class QMenu; class DBusMenuImporterPrivate; /** * A DBusMenuImporter instance can recreate a menu serialized over DBus by * DBusMenuExporter */ class DBusMenuImporter : public QObject { Q_OBJECT public: /** * Creates a DBusMenuImporter listening over DBus on service, path */ DBusMenuImporter(const QString &service, const QString &path, QObject *parent = nullptr); ~DBusMenuImporter() override; QAction *actionForId(int id) const; /** * The menu created from listening to the DBusMenuExporter over DBus */ QMenu *menu() const; public Q_SLOTS: /** * Load the menu * * Will Q_EMIT menuUpdated() when complete. * This should be done before showing a menu */ void updateMenu(); void updateMenu(QMenu *menu); Q_SIGNALS: /** * Emitted after a call to updateMenu(). * @see updateMenu() */ void menuUpdated(QMenu *menu); /** * Emitted when the exporter was asked to activate an action */ void actionActivationRequested(QAction *); protected: /** * Must create a menu, may be customized to fit host appearance. * Default implementation creates a simple QMenu. */ virtual QMenu *createMenu(QWidget *parent); /** * Must convert a name into an icon. * Default implementation returns a null icon. */ virtual QIcon iconForName(const QString &); private Q_SLOTS: void sendClickedEvent(int); void slotMenuAboutToShow(); void slotMenuAboutToHide(); void slotAboutToShowDBusCallFinished(QDBusPendingCallWatcher *); void slotItemActivationRequested(int id, uint timestamp); void processPendingLayoutUpdates(); void slotLayoutUpdated(uint revision, int parentId); void slotGetLayoutFinished(QDBusPendingCallWatcher *); private: Q_DISABLE_COPY(DBusMenuImporter) DBusMenuImporterPrivate *const d; friend class DBusMenuImporterPrivate; // Use Q_PRIVATE_SLOT to avoid exposing DBusMenuItemList Q_PRIVATE_SLOT(d, void slotItemsPropertiesUpdated(const DBusMenuItemList &updatedList, const DBusMenuItemKeysList &removedList)) }; ukui-sni/status-notifier-host/libdbusmenu-qt/dbusmenu-types_p.cpp0000664000175000017500000000662515153755017024343 0ustar fengfeng/* This file is part of the dbusmenu-qt library SPDX-FileCopyrightText: 2009 Canonical SPDX-FileContributor: Aurelien Gateau SPDX-FileContributor: iaom SPDX-License-Identifier: LGPL-2.0-or-later */ #include "dbusmenu-types_p.h" // Local #include "dbusmenu-shortcut_p.h" // Qt #include #include //// DBusMenuItem QDBusArgument &operator<<(QDBusArgument &argument, const DBusMenuItem &obj) { argument.beginStructure(); argument << obj.id << obj.properties; argument.endStructure(); return argument; } const QDBusArgument &operator>>(const QDBusArgument &argument, DBusMenuItem &obj) { argument.beginStructure(); argument >> obj.id >> obj.properties; argument.endStructure(); return argument; } //// DBusMenuItemKeys QDBusArgument &operator<<(QDBusArgument &argument, const DBusMenuItemKeys &obj) { argument.beginStructure(); argument << obj.id << obj.properties; argument.endStructure(); return argument; } const QDBusArgument &operator>>(const QDBusArgument &argument, DBusMenuItemKeys &obj) { argument.beginStructure(); argument >> obj.id >> obj.properties; argument.endStructure(); return argument; } //// DBusMenuLayoutItem QDBusArgument &operator<<(QDBusArgument &argument, const DBusMenuLayoutItem &obj) { argument.beginStructure(); argument << obj.id << obj.properties; argument.beginArray(qMetaTypeId()); Q_FOREACH (const DBusMenuLayoutItem &child, obj.children) { argument << QDBusVariant(QVariant::fromValue(child)); } argument.endArray(); argument.endStructure(); return argument; } const QDBusArgument &operator>>(const QDBusArgument &argument, DBusMenuLayoutItem &obj) { argument.beginStructure(); argument >> obj.id >> obj.properties; argument.beginArray(); while (!argument.atEnd()) { QDBusVariant dbusVariant; argument >> dbusVariant; QDBusArgument childArgument = dbusVariant.variant().value(); DBusMenuLayoutItem child; childArgument >> child; obj.children.append(child); } argument.endArray(); argument.endStructure(); return argument; } //// DBusMenuShortcut QDBusArgument &operator<<(QDBusArgument &argument, const DBusMenuShortcut &obj) { argument.beginArray(qMetaTypeId()); typename QList::ConstIterator it = obj.constBegin(); typename QList::ConstIterator end = obj.constEnd(); for (; it != end; ++it) argument << *it; argument.endArray(); return argument; } const QDBusArgument &operator>>(const QDBusArgument &argument, DBusMenuShortcut &obj) { argument.beginArray(); obj.clear(); while (!argument.atEnd()) { QStringList item; argument >> item; obj.push_back(item); } argument.endArray(); return argument; } void DBusMenuTypes_register() { static bool registered = false; if (registered) { return; } qDBusRegisterMetaType(); qDBusRegisterMetaType(); qDBusRegisterMetaType(); qDBusRegisterMetaType(); qDBusRegisterMetaType(); qDBusRegisterMetaType(); qDBusRegisterMetaType(); registered = true; } ukui-sni/status-notifier-host/libdbusmenu-qt/dbusmenu-shortcut_p.h0000664000175000017500000000107015153755017024504 0ustar fengfeng/* This file is part of the dbusmenu-qt library SPDX-FileCopyrightText: 2009 Canonical SPDX-FileContributor: Aurelien Gateau SPDX-FileContributor: iaom SPDX-License-Identifier: LGPL-2.0-or-later */ #pragma once // Qt #include #include class QKeySequence; class DBusMenuShortcut : public QList { public: QKeySequence toKeySequence() const; static DBusMenuShortcut fromKeySequence(const QKeySequence &); }; Q_DECLARE_METATYPE(DBusMenuShortcut) ukui-sni/status-notifier-host/libdbusmenu-qt/dbusmenu-types_p.h0000664000175000017500000000400415153755017023775 0ustar fengfeng/* This file is part of the dbusmenu-qt library SPDX-FileCopyrightText: 2009 Canonical SPDX-FileContributor: Aurelien Gateau SPDX-FileContributor: iaom SPDX-License-Identifier: LGPL-2.0-or-later */ #pragma once // Qt #include #include #include class QDBusArgument; //// DBusMenuItem /** * Internal struct used to communicate on DBus */ struct DBusMenuItem { int id; QVariantMap properties; }; Q_DECLARE_METATYPE(DBusMenuItem) QDBusArgument &operator<<(QDBusArgument &argument, const DBusMenuItem &item); const QDBusArgument &operator>>(const QDBusArgument &argument, DBusMenuItem &item); typedef QList DBusMenuItemList; Q_DECLARE_METATYPE(DBusMenuItemList) //// DBusMenuItemKeys /** * Represents a list of keys for a menu item */ struct DBusMenuItemKeys { int id; QStringList properties; }; Q_DECLARE_METATYPE(DBusMenuItemKeys) QDBusArgument &operator<<(QDBusArgument &argument, const DBusMenuItemKeys &); const QDBusArgument &operator>>(const QDBusArgument &argument, DBusMenuItemKeys &); typedef QList DBusMenuItemKeysList; Q_DECLARE_METATYPE(DBusMenuItemKeysList) //// DBusMenuLayoutItem /** * Represents an item with its children. GetLayout() returns a * DBusMenuLayoutItemList. */ struct DBusMenuLayoutItem; struct DBusMenuLayoutItem { int id; QVariantMap properties; QList children; }; Q_DECLARE_METATYPE(DBusMenuLayoutItem) QDBusArgument &operator<<(QDBusArgument &argument, const DBusMenuLayoutItem &); const QDBusArgument &operator>>(const QDBusArgument &argument, DBusMenuLayoutItem &); typedef QList DBusMenuLayoutItemList; Q_DECLARE_METATYPE(DBusMenuLayoutItemList) //// DBusMenuShortcut class DBusMenuShortcut; QDBusArgument &operator<<(QDBusArgument &argument, const DBusMenuShortcut &); const QDBusArgument &operator>>(const QDBusArgument &argument, DBusMenuShortcut &); void DBusMenuTypes_register();ukui-sni/status-notifier-host/libdbusmenu-qt/utils.cpp0000664000175000017500000000256115153755017022173 0ustar fengfeng/* This file is part of the dbusmenu-qt library SPDX-FileCopyrightText: 2010 Canonical SPDX-FileContributor: Aurelien Gateau SPDX-FileContributor: iaom SPDX-License-Identifier: LGPL-2.0-or-later */ #include "utils_p.h" // Qt #include QString swapMnemonicChar(const QString &in, const char src, const char dst) { QString out; bool mnemonicFound = false; for (int pos = 0; pos < in.length();) { QChar ch = in[pos]; if (ch == src) { if (pos == in.length() - 1) { // 'src' at the end of string, skip it ++pos; } else { if (in[pos + 1] == src) { // A real 'src' out += src; pos += 2; } else if (!mnemonicFound) { // We found the mnemonic mnemonicFound = true; out += dst; ++pos; } else { // We already have a mnemonic, just skip the char ++pos; } } } else if (ch == dst) { // Escape 'dst' out += dst; out += dst; ++pos; } else { out += ch; ++pos; } } return out; } ukui-sni/status-notifier-host/libdbusmenu-qt/utils_p.h0000664000175000017500000000070015153755017022150 0ustar fengfeng/* This file is part of the dbusmenu-qt library SPDX-FileCopyrightText: 2010 Canonical SPDX-FileContributor: Aurelien Gateau SPDX-FileContributor: iaom SPDX-License-Identifier: LGPL-2.0-or-later */ #pragma once class QString; /** * Swap mnemonic char: Qt uses '&', while dbusmenu uses '_' */ QString swapMnemonicChar(const QString &in, const char src, const char dst); ukui-sni/status-notifier-host/libdbusmenu-qt/dbusmenu-importer.cpp0000664000175000017500000004072215153755017024515 0ustar fengfeng/* This file is part of the dbusmenu-qt library SPDX-FileCopyrightText: 2009 Canonical SPDX-FileContributor: Aurelien Gateau SPDX-FileContributor: iaom SPDX-License-Identifier: LGPL-2.0-or-later */ #include "dbusmenu-importer.h" // Qt #include #include #include #include #include #include #include #include #include #include #include #include // Local #include "dbusmenu-shortcut_p.h" #include "dbusmenu-types_p.h" #include "utils_p.h" // Generated #include "dbusmenu_interface.h" //#define BENCHMARK #ifdef BENCHMARK static QTime sChrono; #endif #define DMRETURN_IF_FAIL(cond) \ if (!(cond)) { \ qWarning() << "Condition failed: " #cond; \ return; \ } static const char *DBUSMENU_PROPERTY_ID = "_dbusmenu_id"; static const char *DBUSMENU_PROPERTY_ICON_NAME = "_dbusmenu_icon_name"; static const char *DBUSMENU_PROPERTY_ICON_DATA_HASH = "_dbusmenu_icon_data_hash"; static QAction *createKdeTitle(QAction *action, QWidget *parent) { QToolButton *titleWidget = new QToolButton(nullptr); QFont font = titleWidget->font(); font.setBold(true); titleWidget->setFont(font); titleWidget->setIcon(action->icon()); titleWidget->setText(action->text()); titleWidget->setDown(true); titleWidget->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); QWidgetAction *titleAction = new QWidgetAction(parent); titleAction->setDefaultWidget(titleWidget); return titleAction; } class DBusMenuImporterPrivate { public: DBusMenuImporter *q; DBusMenuInterface *m_interface; QMenu *m_menu; using ActionForId = QMap>; ActionForId m_actionForId; QTimer *m_pendingLayoutUpdateTimer; QSet m_idsRefreshedByAboutToShow; QSet m_pendingLayoutUpdates; QDBusPendingCallWatcher *refresh(int id) { auto call = m_interface->GetLayout(id, 1, QStringList()); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(call, q); watcher->setProperty(DBUSMENU_PROPERTY_ID, id); QObject::connect(watcher, &QDBusPendingCallWatcher::finished, q, &DBusMenuImporter::slotGetLayoutFinished); return watcher; } QMenu *createMenu(QWidget *parent) { QMenu *menu = q->createMenu(parent); return menu; } /** * Init all the immutable action properties here * TODO: Document immutable properties? * * Note: we remove properties we handle from the map (using QMap::take() * instead of QMap::value()) to avoid warnings about these properties in * updateAction() */ QAction *createAction(int id, const QVariantMap &_map, QWidget *parent) { QVariantMap map = _map; QAction *action = new QAction(parent); action->setProperty(DBUSMENU_PROPERTY_ID, id); QString type = map.take(QStringLiteral("type")).toString(); if (type == QLatin1String("separator")) { action->setSeparator(true); } if (map.take(QStringLiteral("children-display")).toString() == QLatin1String("submenu")) { QMenu *menu = createMenu(parent); action->setMenu(menu); } QString toggleType = map.take(QStringLiteral("toggle-type")).toString(); if (!toggleType.isEmpty()) { action->setCheckable(true); if (toggleType == QLatin1String("radio")) { QActionGroup *group = new QActionGroup(action); group->addAction(action); } } bool isKdeTitle = map.take(QStringLiteral("x-kde-title")).toBool(); updateAction(action, map, map.keys()); if (isKdeTitle) { action = createKdeTitle(action, parent); } return action; } /** * Update mutable properties of an action. A property may be listed in * requestedProperties but not in map, this means we should use the default value * for this property. * * @param action the action to update * @param map holds the property values * @param requestedProperties which properties has been requested */ void updateAction(QAction *action, const QVariantMap &map, const QStringList &requestedProperties) { Q_FOREACH (const QString &key, requestedProperties) { updateActionProperty(action, key, map.value(key)); } } void updateActionProperty(QAction *action, const QString &key, const QVariant &value) { if (key == QLatin1String("label")) { updateActionLabel(action, value); } else if (key == QLatin1String("enabled")) { updateActionEnabled(action, value); } else if (key == QLatin1String("toggle-state")) { updateActionChecked(action, value); } else if (key == QLatin1String("icon-name")) { updateActionIconByName(action, value); } else if (key == QLatin1String("icon-data")) { updateActionIconByData(action, value); } else if (key == QLatin1String("visible")) { updateActionVisible(action, value); } else if (key == QLatin1String("shortcut")) { updateActionShortcut(action, value); } else { qDebug() << "Unhandled property update" << key; } } void updateActionLabel(QAction *action, const QVariant &value) { QString text = swapMnemonicChar(value.toString(), '_', '&'); action->setText(text); } void updateActionEnabled(QAction *action, const QVariant &value) { action->setEnabled(value.isValid() ? value.toBool() : true); } void updateActionChecked(QAction *action, const QVariant &value) { if (action->isCheckable() && value.isValid()) { action->setChecked(value.toInt() == 1); } } void updateActionIconByName(QAction *action, const QVariant &value) { const QString iconName = value.toString(); const QString previous = action->property(DBUSMENU_PROPERTY_ICON_NAME).toString(); if (previous == iconName) { return; } action->setProperty(DBUSMENU_PROPERTY_ICON_NAME, iconName); if (iconName.isEmpty()) { action->setIcon(QIcon()); return; } action->setIcon(q->iconForName(iconName)); } void updateActionIconByData(QAction *action, const QVariant &value) { const QByteArray data = value.toByteArray(); uint dataHash = qHash(data); uint previousDataHash = action->property(DBUSMENU_PROPERTY_ICON_DATA_HASH).toUInt(); if (previousDataHash == dataHash) { return; } action->setProperty(DBUSMENU_PROPERTY_ICON_DATA_HASH, dataHash); QPixmap pix; if (!pix.loadFromData(data)) { qDebug() << "Failed to decode icon-data property for action" << action->text(); action->setIcon(QIcon()); return; } action->setIcon(QIcon(pix)); } void updateActionVisible(QAction *action, const QVariant &value) { action->setVisible(value.isValid() ? value.toBool() : true); } void updateActionShortcut(QAction *action, const QVariant &value) { QDBusArgument arg = value.value(); DBusMenuShortcut dmShortcut; arg >> dmShortcut; QKeySequence keySequence = dmShortcut.toKeySequence(); action->setShortcut(keySequence); } QMenu *menuForId(int id) const { if (id == 0) { return q->menu(); } QAction *action = m_actionForId.value(id); if (!action) { return nullptr; } return action->menu(); } void slotItemsPropertiesUpdated(const DBusMenuItemList &updatedList, const DBusMenuItemKeysList &removedList); void sendEvent(int id, const QString &eventId) { m_interface->Event(id, eventId, QDBusVariant(QString()), 0u); } }; DBusMenuImporter::DBusMenuImporter(const QString &service, const QString &path, QObject *parent) : QObject(parent) , d(new DBusMenuImporterPrivate) { DBusMenuTypes_register(); d->q = this; d->m_interface = new DBusMenuInterface(service, path, QDBusConnection::sessionBus(), this); d->m_menu = nullptr; d->m_pendingLayoutUpdateTimer = new QTimer(this); d->m_pendingLayoutUpdateTimer->setSingleShot(true); connect(d->m_pendingLayoutUpdateTimer, &QTimer::timeout, this, &DBusMenuImporter::processPendingLayoutUpdates); connect(d->m_interface, &DBusMenuInterface::LayoutUpdated, this, &DBusMenuImporter::slotLayoutUpdated); connect(d->m_interface, &DBusMenuInterface::ItemActivationRequested, this, &DBusMenuImporter::slotItemActivationRequested); connect(d->m_interface, &DBusMenuInterface::ItemsPropertiesUpdated, this, [this](const DBusMenuItemList &updatedList, const DBusMenuItemKeysList &removedList) { d->slotItemsPropertiesUpdated(updatedList, removedList); }); d->refresh(0); } DBusMenuImporter::~DBusMenuImporter() { // Do not use "delete d->m_menu": even if we are being deleted we should // leave enough time for the menu to finish what it was doing, for example // if it was being displayed. d->m_menu->deleteLater(); delete d; } void DBusMenuImporter::slotLayoutUpdated(uint revision, int parentId) { Q_UNUSED(revision) if (d->m_idsRefreshedByAboutToShow.remove(parentId)) { return; } d->m_pendingLayoutUpdates << parentId; if (!d->m_pendingLayoutUpdateTimer->isActive()) { d->m_pendingLayoutUpdateTimer->start(); } } void DBusMenuImporter::processPendingLayoutUpdates() { QSet ids = d->m_pendingLayoutUpdates; d->m_pendingLayoutUpdates.clear(); Q_FOREACH (int id, ids) { d->refresh(id); } } QMenu *DBusMenuImporter::menu() const { if (!d->m_menu) { d->m_menu = d->createMenu(nullptr); } return d->m_menu; } void DBusMenuImporterPrivate::slotItemsPropertiesUpdated(const DBusMenuItemList &updatedList, const DBusMenuItemKeysList &removedList) { Q_FOREACH (const DBusMenuItem &item, updatedList) { QAction *action = m_actionForId.value(item.id); if (!action) { // We don't know this action. It probably is in a menu we haven't fetched yet. continue; } QVariantMap::ConstIterator it = item.properties.constBegin(), end = item.properties.constEnd(); for (; it != end; ++it) { updateActionProperty(action, it.key(), it.value()); } } Q_FOREACH (const DBusMenuItemKeys &item, removedList) { QAction *action = m_actionForId.value(item.id); if (!action) { // We don't know this action. It probably is in a menu we haven't fetched yet. continue; } Q_FOREACH (const QString &key, item.properties) { updateActionProperty(action, key, QVariant()); } } } QAction *DBusMenuImporter::actionForId(int id) const { return d->m_actionForId.value(id); } void DBusMenuImporter::slotItemActivationRequested(int id, uint /*timestamp*/) { QAction *action = d->m_actionForId.value(id); DMRETURN_IF_FAIL(action); actionActivationRequested(action); } void DBusMenuImporter::slotGetLayoutFinished(QDBusPendingCallWatcher *watcher) { int parentId = watcher->property(DBUSMENU_PROPERTY_ID).toInt(); watcher->deleteLater(); QMenu *menu = d->menuForId(parentId); QDBusPendingReply reply = *watcher; if (!reply.isValid()) { qDebug() << reply.error().message(); if (menu) { Q_EMIT menuUpdated(menu); } return; } #ifdef BENCHMARK DMDEBUG << "- items received:" << sChrono.elapsed() << "ms"; #endif DBusMenuLayoutItem rootItem = reply.argumentAt<1>(); if (!menu) { qDebug() << "No menu for id" << parentId; return; } // remove outdated actions QSet newDBusMenuItemIds; newDBusMenuItemIds.reserve(rootItem.children.count()); #if QT_VERSION < QT_VERSION_CHECK(6, 6, 0) for (const DBusMenuLayoutItem &item : qAsConst(rootItem.children)) { #else for (const DBusMenuLayoutItem &item : std::as_const(rootItem.children)) { #endif newDBusMenuItemIds << item.id; } for (QAction *action : menu->actions()) { int id = action->property(DBUSMENU_PROPERTY_ID).toInt(); if (!newDBusMenuItemIds.contains(id)) { d->m_actionForId.remove(id); } } menu->clear(); // insert or update new actions into our menu #if QT_VERSION < QT_VERSION_CHECK(6, 6, 0) for (const DBusMenuLayoutItem &dbusMenuItem : qAsConst(rootItem.children)) { #else for (const DBusMenuLayoutItem &dbusMenuItem : std::as_const(rootItem.children)) { #endif DBusMenuImporterPrivate::ActionForId::Iterator it = d->m_actionForId.find(dbusMenuItem.id); int id = dbusMenuItem.id; auto action = d->createAction(id, dbusMenuItem.properties, menu); if (it == d->m_actionForId.end()) { d->m_actionForId.insert(id, action); } else { delete *it; *it = action; } connect(action, &QAction::triggered, this, [id, this]() { sendClickedEvent(id); }); if (QMenu *menuAction = action->menu()) { connect(menuAction, &QMenu::aboutToShow, this, &DBusMenuImporter::slotMenuAboutToShow, Qt::UniqueConnection); updateMenu(menuAction); } connect(menu, &QMenu::aboutToHide, this, &DBusMenuImporter::slotMenuAboutToHide, Qt::UniqueConnection); menu->addAction(action); } Q_EMIT menuUpdated(menu); } void DBusMenuImporter::sendClickedEvent(int id) { d->sendEvent(id, QStringLiteral("clicked")); } void DBusMenuImporter::updateMenu() { updateMenu(DBusMenuImporter::menu()); } void DBusMenuImporter::updateMenu(QMenu *menu) { Q_ASSERT(menu); QAction *action = menu->menuAction(); Q_ASSERT(action); int id = action->property(DBUSMENU_PROPERTY_ID).toInt(); auto call = d->m_interface->AboutToShow(id); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(call, this); watcher->setProperty(DBUSMENU_PROPERTY_ID, id); connect(watcher, &QDBusPendingCallWatcher::finished, this, &DBusMenuImporter::slotAboutToShowDBusCallFinished); // Firefox deliberately ignores "aboutToShow" whereas Qt ignores" opened", so we'll just send both all the time... d->sendEvent(id, QStringLiteral("opened")); } void DBusMenuImporter::slotAboutToShowDBusCallFinished(QDBusPendingCallWatcher *watcher) { int id = watcher->property(DBUSMENU_PROPERTY_ID).toInt(); watcher->deleteLater(); QMenu *menu = d->menuForId(id); if (!menu) { return; } QDBusPendingReply reply = *watcher; if (reply.isError()) { qDebug() << "Call to AboutToShow() failed:" << reply.error().message(); Q_EMIT menuUpdated(menu); return; } // Note, this isn't used by Qt's QPT - but we get a LayoutChanged emitted before // this returns, which equates to the same thing bool needRefresh = reply.argumentAt<0>(); if (needRefresh || menu->actions().isEmpty()) { d->m_idsRefreshedByAboutToShow << id; d->refresh(id); } else { Q_EMIT menuUpdated(menu); } } void DBusMenuImporter::slotMenuAboutToHide() { QMenu *menu = qobject_cast(sender()); Q_ASSERT(menu); QAction *action = menu->menuAction(); Q_ASSERT(action); int id = action->property(DBUSMENU_PROPERTY_ID).toInt(); d->sendEvent(id, QStringLiteral("closed")); } void DBusMenuImporter::slotMenuAboutToShow() { QMenu *menu = qobject_cast(sender()); Q_ASSERT(menu); updateMenu(menu); } QMenu *DBusMenuImporter::createMenu(QWidget *parent) { return new QMenu(parent); } QIcon DBusMenuImporter::iconForName(const QString & /*name*/) { return QIcon(); } #include "moc_dbusmenu-importer.cpp" ukui-sni/status-notifier-host/status-notifier-host.cpp0000664000175000017500000002333715153755017022217 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: iaom * */ #include #include #include "status-notifier-host.h" #include "status-notifier-item.h" #include "statusnotifierwatcher_interface.h" #include "dbusproperties.h" namespace UkuiSni { static std::once_flag flag; static StatusNotifierHost *s_self; static const QString s_watcherServiceName(QStringLiteral("org.kde.StatusNotifierWatcher")); class StatusNotifierHostPrivate : public QObject { friend class StatusNotifierHost; Q_OBJECT public: explicit StatusNotifierHostPrivate(StatusNotifierHost *q); ~StatusNotifierHostPrivate(); void registerHost(); private: void serviceChange(const QString &name, const QString &oldOwner, const QString &newOwner); void registerHost(const QString &service); void unregisterHost(const QString &service); void itemRegistered(const QString &service); void itemUnregistered(const QString &service); void removeAllItems(); QString displayFromPid(uint pid); org::kde::StatusNotifierWatcher *m_statusNotifierWatcher = nullptr; QString m_serviceName; static const int s_protocolVersion = 0; QHash m_registeredItems; StatusNotifierHost *q = nullptr; QString m_display; QString m_sessionType; }; StatusNotifierHostPrivate::StatusNotifierHostPrivate(StatusNotifierHost *q) : QObject(q), q(q) { if(QString(getenv("XDG_SESSION_TYPE")) == "wayland") { m_sessionType = "wayland"; m_display = getenv("WAYLAND_DISPLAY"); } else { m_sessionType = "x11"; m_display = getenv("DISPLAY"); } qDebug() << "Current DISPLAY: " << m_display << "XDG_SESSION_TYPE" << m_sessionType; } StatusNotifierHostPrivate::~StatusNotifierHostPrivate() { } void StatusNotifierHostPrivate::registerHost() { if (QDBusConnection::sessionBus().isConnected()) { m_serviceName = "org.kde.StatusNotifierHost-" + QString::number(QCoreApplication::applicationPid()); QDBusConnection::sessionBus().registerService(m_serviceName); auto *watcher = new QDBusServiceWatcher(s_watcherServiceName, QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForOwnerChange, this); connect(watcher, &QDBusServiceWatcher::serviceOwnerChanged, this, &StatusNotifierHostPrivate::serviceChange); registerHost(s_watcherServiceName); } } void StatusNotifierHostPrivate::serviceChange(const QString &name, const QString &oldOwner, const QString &newOwner) { qDebug() << "Service" << name << "status change, old owner:" << oldOwner << "new:" << newOwner; if (newOwner.isEmpty()) { unregisterHost(name); } else if (oldOwner.isEmpty()) { registerHost(name); } } void StatusNotifierHostPrivate::registerHost(const QString &service) { if (service == s_watcherServiceName) { if(m_statusNotifierWatcher) { delete m_statusNotifierWatcher; m_statusNotifierWatcher = nullptr; } m_statusNotifierWatcher = new org::kde::StatusNotifierWatcher(s_watcherServiceName, QStringLiteral("/StatusNotifierWatcher"), QDBusConnection::sessionBus(), this); if (m_statusNotifierWatcher->isValid()) { m_statusNotifierWatcher->call(QDBus::NoBlock, QStringLiteral("RegisterStatusNotifierHost"), m_serviceName); connect(m_statusNotifierWatcher, QOverload::of(&OrgKdeStatusNotifierWatcherInterface::StatusNotifierItemRegistered), this, &StatusNotifierHostPrivate::itemRegistered); connect(m_statusNotifierWatcher, QOverload::of(&OrgKdeStatusNotifierWatcherInterface::StatusNotifierItemUnregistered), this, &StatusNotifierHostPrivate::itemUnregistered); OrgFreedesktopDBusPropertiesInterface propertiesIface(m_statusNotifierWatcher->service(), m_statusNotifierWatcher->path(), m_statusNotifierWatcher->connection()); QDBusPendingReply pendingItems = propertiesIface.Get(m_statusNotifierWatcher->interface(), "RegisteredStatusNotifierItems"); auto *watcher = new QDBusPendingCallWatcher(pendingItems, this); connect(watcher, &QDBusPendingCallWatcher::finished, this, [&, watcher]() { watcher->deleteLater(); QDBusReply reply = *watcher; QStringList registeredItems = reply.value().variant().toStringList(); for(const QString &service : registeredItems) { if (!m_registeredItems.contains(service)) { itemRegistered(service); } } }); } else { if(m_statusNotifierWatcher) { delete m_statusNotifierWatcher; m_statusNotifierWatcher = nullptr; } qDebug() << "Status notifier Watcher not reachable"; } } } void StatusNotifierHostPrivate::unregisterHost(const QString &service) { if (service == s_watcherServiceName) { removeAllItems(); if(m_statusNotifierWatcher) { delete m_statusNotifierWatcher; m_statusNotifierWatcher = nullptr; } } } void StatusNotifierHostPrivate::itemRegistered(const QString &service) { if(!m_registeredItems.contains(service)) { QString realService; int slash = service.indexOf('/'); if (slash == 0) { qWarning() << "Invalid service:" << service; return; } else if(slash > 0){ realService = service.left(slash); } else { realService = service; } uint pid = 0; if(realService.contains(QStringLiteral("org.ukui.proxy.StatusNotifierItem"))) { QString pidStr = realService.section("-", 1, 1); if(!pidStr.isEmpty()) { pid = pidStr.toUInt(); } } else { QDBusReply pidReply = QDBusConnection::sessionBus().interface()->servicePid(realService); if(pidReply.isValid()) { pid = pidReply.value(); } } QString display = pid > 0 ? displayFromPid(pid) : ""; if(m_display != display && !display.isEmpty()) { return; } auto *item = new StatusNotifierItem(service); item->setPid(pid); m_registeredItems.insert(service, item); Q_EMIT q->itemAdded(service); qDebug() << "Registering sni" << service; } } void StatusNotifierHostPrivate::itemUnregistered(const QString &service) { if (m_registeredItems.contains(service)) { Q_EMIT q->itemRemoved(service); auto item = m_registeredItems.value(service); item->disconnect(); item->deleteLater(); m_registeredItems.remove(service); } } void StatusNotifierHostPrivate::removeAllItems() { for(const QString &service : m_registeredItems.keys()) { delete m_registeredItems.value(service); m_registeredItems.remove(service); Q_EMIT q->itemRemoved(service); } } QString StatusNotifierHostPrivate::displayFromPid(uint pid) { QFile environFile(QStringLiteral("/proc/%1/environ").arg(QString::number(pid))); if (environFile.open(QIODevice::ReadOnly | QIODevice::Text)) { const QByteArray DISPLAY = m_sessionType == "wayland" ? QByteArrayLiteral("WAYLAND_DISPLAY") : QByteArrayLiteral("DISPLAY"); const auto lines = environFile.readAll().split('\0'); for (const QByteArray &line : lines) { const int equalsIdx = line.indexOf('='); if (equalsIdx <= 0) { continue; } const QByteArray key = line.left(equalsIdx); if (key == DISPLAY) { const QByteArray value = line.mid(equalsIdx + 1); return value; } } } return {}; } StatusNotifierHost *StatusNotifierHost::self() { std::call_once(flag, [ & ] { s_self = new StatusNotifierHost(); }); return s_self; } StatusNotifierHost::StatusNotifierHost(QObject *parent): QObject(parent), d(new StatusNotifierHostPrivate(this)) { } StatusNotifierHost::~StatusNotifierHost() { } QList StatusNotifierHost::items() { return d->m_registeredItems.values(); } const QList StatusNotifierHost::services() const { return d->m_registeredItems.keys(); } StatusNotifierItem *StatusNotifierHost::itemForService(const QString service) { return d->m_registeredItems.value(service); } void StatusNotifierHost::registerHost() { d->registerHost(); } } #include "status-notifier-host.moc" ukui-sni/common/0000775000175000017500000000000015153755017012545 5ustar fengfengukui-sni/common/dbus-types.h0000664000175000017500000000143115153755017015014 0ustar fengfeng/* SPDX-FileCopyrightText: 2009 Marco Martin SPDX-FileCopyrightText: 2023 iaom SPDX-License-Identifier: GPL-2.0-or-later */ #pragma once #include #include "typedefs.h" const QDBusArgument &operator<<(QDBusArgument &argument, const DbusImageStruct &icon); const QDBusArgument &operator>>(const QDBusArgument &argument, DbusImageStruct &icon); const QDBusArgument &operator<<(QDBusArgument &argument, const DbusImageVector &iconVector); const QDBusArgument &operator>>(const QDBusArgument &argument, DbusImageVector &iconVector); const QDBusArgument &operator<<(QDBusArgument &argument, const DbusToolTipStruct &toolTip); const QDBusArgument &operator>>(const QDBusArgument &argument, DbusToolTipStruct &toolTip); ukui-sni/common/typedefs.h0000664000175000017500000000145415153755017014545 0ustar fengfeng/* SPDX-FileCopyrightText: 2009 Marco Martin SPDX-FileCopyrightText: 2023 iaom SPDX-License-Identifier: GPL-2.0-or-later */ #pragma once #include #include #include #include #include #include struct DbusImageStruct { DbusImageStruct(){}; explicit DbusImageStruct(const QImage &image); int width; int height; QByteArray data; }; typedef QVector DbusImageVector; struct DbusToolTipStruct { QString icon; DbusImageVector image; QString title; QString subTitle; }; typedef QList UintList; Q_DECLARE_METATYPE(UintList) Q_DECLARE_METATYPE(DbusImageStruct) Q_DECLARE_METATYPE(DbusImageVector) Q_DECLARE_METATYPE(DbusToolTipStruct) ukui-sni/common/dbus-types.cpp0000664000175000017500000000711515153755017015354 0ustar fengfeng/* SPDX-FileCopyrightText: 2009 Marco Martin SPDX-FileCopyrightText: 2023 iaom SPDX-License-Identifier: GPL-2.0-or-later */ #include "dbus-types.h" #include #include DbusImageStruct::DbusImageStruct(const QImage &image) { width = image.size().width(); height = image.size().height(); if (image.format() == QImage::Format_ARGB32) { data = QByteArray((char *)image.bits(), image.sizeInBytes()); } else { QImage image32 = image.convertToFormat(QImage::Format_ARGB32); data = QByteArray((char *)image32.bits(), image32.sizeInBytes()); } // swap to network byte order if we are little endian if (QSysInfo::ByteOrder == QSysInfo::LittleEndian) { quint32 *uintBuf = (quint32 *)data.data(); for (uint i = 0; i < data.size() / sizeof(quint32); ++i) { *uintBuf = qToBigEndian(*uintBuf); ++uintBuf; } } } // Marshall the ImageStruct data into a D-BUS argument const QDBusArgument &operator<<(QDBusArgument &argument, const DbusImageStruct &icon) { argument.beginStructure(); argument << icon.width; argument << icon.height; argument << icon.data; argument.endStructure(); return argument; } #include // Retrieve the ImageStruct data from the D-BUS argument const QDBusArgument &operator>>(const QDBusArgument &argument, DbusImageStruct &icon) { qint32 width = 0; qint32 height = 0; QByteArray data; if (argument.currentType() == QDBusArgument::StructureType) { argument.beginStructure(); argument >> width; argument >> height; argument >> data; argument.endStructure(); } icon.width = width; icon.height = height; icon.data = data; return argument; } // Marshall the ImageVector data into a D-BUS argument const QDBusArgument &operator<<(QDBusArgument &argument, const DbusImageVector &iconVector) { argument.beginArray(qMetaTypeId()); for (int i = 0; i < iconVector.size(); ++i) { argument << iconVector[i]; } argument.endArray(); return argument; } // Retrieve the ImageVector data from the D-BUS argument const QDBusArgument &operator>>(const QDBusArgument &argument, DbusImageVector &iconVector) { iconVector.clear(); if (argument.currentType() == QDBusArgument::ArrayType) { argument.beginArray(); while (!argument.atEnd()) { DbusImageStruct element; argument >> element; iconVector.append(element); } argument.endArray(); } return argument; } // Marshall the ToolTipStruct data into a D-BUS argument const QDBusArgument &operator<<(QDBusArgument &argument, const DbusToolTipStruct &toolTip) { argument.beginStructure(); argument << toolTip.icon; argument << toolTip.image; argument << toolTip.title; argument << toolTip.subTitle; argument.endStructure(); return argument; } // Retrieve the ToolTipStruct data from the D-BUS argument const QDBusArgument &operator>>(const QDBusArgument &argument, DbusToolTipStruct &toolTip) { QString icon; DbusImageVector image; QString title; QString subTitle; if (argument.currentType() == QDBusArgument::StructureType) { argument.beginStructure(); argument >> icon; argument >> image; argument >> title; argument >> subTitle; argument.endStructure(); } toolTip.icon = icon; toolTip.image = image; toolTip.title = title; toolTip.subTitle = subTitle; return argument; }ukui-sni/status-notifier-watcher/0000775000175000017500000000000015153755611016050 5ustar fengfengukui-sni/status-notifier-watcher/ukui-sni-watcher.desktop0000664000175000017500000000034415153755017022643 0ustar fengfeng[Desktop Entry] Name=ukui-sni-watcher Name[zh_CN]=ukui-sni-watcher Name[zh_TW]=ukui-sni-watcher Exec=ukui-sni-watcher Type=Application OnlyShowIn=UKUI; NoDisplay=true X-UKUI-AutoRestart=true X-UKUI-Autostart-Phase=Initializationukui-sni/status-notifier-watcher/CMakeLists.txt0000664000175000017500000000437615153755017020622 0ustar fengfengproject(ukui-sni-watcher VERSION 1.0 LANGUAGES C CXX) set(VERSION_MAJOR 1) set(VERSION_MINOR 0) set(VERSION_MICRO 0) set(UKUI_SNI_WATCHER_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_MICRO}) set(3rdParties_DIR ../3rd-parties/qtsingleapplication/src/) configure_file (ukui-sni-watcher-config.h.in ukui-sni-watcher-config.h @ONLY) include_directories(../common) include_directories(../) set(ukuiSNIWatcher_SRCS ${3rdParties_DIR}qtsinglecoreapplication.h ${3rdParties_DIR}qtsinglecoreapplication.cpp ${3rdParties_DIR}qtlocalpeer.h ${3rdParties_DIR}qtlocalpeer.cpp watcher.cpp watcher.h watcher-private.h status-notifier-watcher-application.cpp status-notifier-watcher-application.h ../log-utils.cpp ../log-utils.h main.cpp) set_source_files_properties(../dbus/org.kde.StatusNotifierWatcher.xml PROPERTIES NO_NAMESPACE false INCLUDE "./watcher-private.h" CLASSNAME StatusNotifierWatcherAdaptor ) if(COMMAND qt_add_dbus_adaptor) qt_add_dbus_adaptor(ukuiSNIWatcher_SRCS ../dbus/org.kde.StatusNotifierWatcher.xml watcher-private.h WatcherPrivate) else() qt5_add_dbus_adaptor(ukuiSNIWatcher_SRCS ../dbus/org.kde.StatusNotifierWatcher.xml watcher-private.h WatcherPrivate) endif() set(STATUS_NOTIFIER_ITEM_XML ../dbus/org.kde.StatusNotifierItem.xml) set_source_files_properties(${STATUS_NOTIFIER_ITEM_XML} PROPERTIES NO_NAMESPACE false INCLUDE "../common/typedefs.h" CLASSNAME OrgKdeStatusNotifierItemInterface ) if(COMMAND qt_add_dbus_interface) qt_add_dbus_interface(ukuiSNIWatcher_SRCS ../dbus/org.kde.StatusNotifierItem.xml statusnotifieriteminterface) else() qt5_add_dbus_interface(ukuiSNIWatcher_SRCS ../dbus/org.kde.StatusNotifierItem.xml statusnotifieriteminterface) endif() add_executable(${PROJECT_NAME} ${ukuiSNIWatcher_SRCS}) target_include_directories(${PROJECT_NAME} PUBLIC ${3rdParties_DIR}) target_link_libraries(${PROJECT_NAME} PRIVATE Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::DBus Qt${QT_VERSION_MAJOR}::Network Qt${QT_VERSION_MAJOR}::Gui ) install(TARGETS ${PROJECT_NAME} DESTINATION /usr/bin) install(FILES ukui-sni-watcher.desktop DESTINATION /etc/xdg/autostart)ukui-sni/status-notifier-watcher/main.cpp0000664000175000017500000000213015153755017017474 0ustar fengfeng/* * 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 "status-notifier-watcher-application.h" #include "log-utils.h" int main(int argc, char *argv[]) { LogUtils::initLogFile("ukui-sni-watcher"); qInstallMessageHandler(LogUtils::messageOutput); StatusNotifierWatcherApplication app(argc, argv); if(app.isRunning()) { return 0; } return StatusNotifierWatcherApplication::exec(); } ukui-sni/status-notifier-watcher/watcher-private.h0000664000175000017500000000454615153755017021337 0ustar fengfeng/* * 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 UKUI_SNI_WATCHER_PRIVATE_H #define UKUI_SNI_WATCHER_PRIVATE_H #include #include #include #include #include #include "typedefs.h" class WatcherPrivate : public QObject, protected QDBusContext { Q_OBJECT Q_PROPERTY(QStringList RegisteredStatusNotifierItems READ RegisteredStatusNotifierItems) Q_PROPERTY(UintList RegisteredStatusNotifierItemPids READ RegisteredStatusNotifierItemPids) Q_PROPERTY(bool IsStatusNotifierHostRegistered READ IsStatusNotifierHostRegistered) Q_PROPERTY(int ProtocolVersion READ ProtocolVersion) public: explicit WatcherPrivate(QObject *parent = nullptr); ~WatcherPrivate() override; QStringList RegisteredStatusNotifierItems() const; UintList RegisteredStatusNotifierItemPids() const; bool IsStatusNotifierHostRegistered() const; int ProtocolVersion() const; public Q_SLOTS: void RegisterStatusNotifierItem(const QString &service); void RegisterStatusNotifierHost(const QString &service); Q_SIGNALS: void StatusNotifierItemRegistered(const QString &service); void StatusNotifierHostRegistered(); void StatusNotifierItemUnregistered(const QString &service); void StatusNotifierHostUnregistered(); void StatusNotifierItemRegistered(quint32 pid); void StatusNotifierItemUnregistered(quint32 pid); private: void serviceUnregistered(const QString &service); QDBusServiceWatcher *m_serviceWatcher = nullptr; QMultiMap m_registeredServices; // notifierItemId->pid QSet m_statusNotifierHostServices; }; #endif //UKUI_SNI_WATCHER_PRIVATE_H ukui-sni/status-notifier-watcher/status-notifier-watcher-application.h0000664000175000017500000000242615153755017025321 0ustar fengfeng/* * 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 UKUI_SNI_STATUS_NOTIFIER_WATCHER_APPLICATION_H #define UKUI_SNI_STATUS_NOTIFIER_WATCHER_APPLICATION_H #include #include "qtsinglecoreapplication.h" class StatusNotifierWatcherApplication : public QtSingleCoreApplication { Q_OBJECT public: StatusNotifierWatcherApplication(int &argc, char *argv[], const QString &applicationName = "ukui-sni-watcher"); ~StatusNotifierWatcherApplication(); protected Q_SLOTS: void parseCmd(const QString& msg, bool isPrimary); }; #endif //UKUI_SNI_STATUS_NOTIFIER_WATCHER_APPLICATION_H ukui-sni/status-notifier-watcher/watcher.cpp0000664000175000017500000001312315153755611020211 0ustar fengfeng/* * 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 "watcher-private.h" #include "statusnotifierwatcheradaptor.h" #include "statusnotifieriteminterface.h" #include "watcher.h" WatcherPrivate::WatcherPrivate(QObject *parent) : QObject(parent) { qDBusRegisterMetaType(); new StatusNotifierWatcherAdaptor(this); QDBusConnection dbus = QDBusConnection::sessionBus(); dbus.registerObject(QStringLiteral("/StatusNotifierWatcher"), this); dbus.registerService(QStringLiteral("org.kde.StatusNotifierWatcher")); m_serviceWatcher = new QDBusServiceWatcher(this); m_serviceWatcher->setConnection(dbus); m_serviceWatcher->setWatchMode(QDBusServiceWatcher::WatchForUnregistration); connect(m_serviceWatcher, &QDBusServiceWatcher::serviceUnregistered, this, &WatcherPrivate::serviceUnregistered); } WatcherPrivate::~WatcherPrivate() { QDBusConnection dbus = QDBusConnection::sessionBus(); dbus.unregisterService(QStringLiteral("org.kde.StatusNotifierWatcher")); } QStringList WatcherPrivate::RegisteredStatusNotifierItems() const { return m_registeredServices.keys(); } UintList WatcherPrivate::RegisteredStatusNotifierItemPids() const { QStringList pidList = m_registeredServices.values(); pidList.removeDuplicates(); pidList.removeAll("0"); QList pids; for(const QString &pid : pidList) { pids.append(pid.toUInt()); } return pids; } bool WatcherPrivate::IsStatusNotifierHostRegistered() const { // return !m_statusNotifierHostServices.isEmpty(); return true; } int WatcherPrivate::ProtocolVersion() const { return 0; } void WatcherPrivate::RegisterStatusNotifierItem(const QString &service) { QString realService; QString path; int slash = service.indexOf('/'); if (slash == 0) { realService = message().service(); path = service; } else if(slash > 0){ realService = service.left(slash); path = service.mid(slash); } else { realService = service; path = QStringLiteral("/StatusNotifierItem"); } QString notifierItemId = realService + path; if (m_registeredServices.contains(notifierItemId)) { return; } if (QDBusConnection::sessionBus().interface()->isServiceRegistered(realService).value()) { // check if the service has registered a SystemTray object org::kde::StatusNotifierItem item(realService, path, QDBusConnection::sessionBus()); if (item.isValid()) { qDebug() << "Registering" << notifierItemId << "to system tray"; m_serviceWatcher->addWatchedService(realService); //get Pid for item QString pid = "0"; if(realService.contains(QStringLiteral("org.ukui.proxy.StatusNotifierItem"))) { QString pidStr = realService.section("-", 1, 1); if(!pidStr.isEmpty()) { pid = pidStr; } } else { QDBusReply pidReply = connection().interface()->servicePid(message().service()); if(pidReply.isValid()) { pid = QString::number(pidReply.value()); } } m_registeredServices.insert(notifierItemId, pid); Q_EMIT StatusNotifierItemRegistered(notifierItemId); if(pid.toUInt() > 0) { Q_EMIT StatusNotifierItemRegistered(pid.toUInt()); } } } } void WatcherPrivate::RegisterStatusNotifierHost(const QString &service) { if (service.contains(QLatin1String("org.kde.StatusNotifierHost-")) && QDBusConnection::sessionBus().interface()->isServiceRegistered(service).value() && !m_statusNotifierHostServices.contains(service)) { qDebug() << "Registering" << service << "as system tray"; m_statusNotifierHostServices.insert(service); m_serviceWatcher->addWatchedService(service); Q_EMIT StatusNotifierHostRegistered(); } } void WatcherPrivate::serviceUnregistered(const QString &service) { qDebug() << "Service " << service << "unregistered"; m_serviceWatcher->removeWatchedService(service); const QString match = service + QLatin1Char('/'); for(const QString &servicePath : m_registeredServices.keys()) { if(servicePath.startsWith(match)) { QString pid = m_registeredServices.take(servicePath); Q_EMIT StatusNotifierItemUnregistered(servicePath); if(!m_registeredServices.values().contains(pid) && pid.toUInt() > 0) { Q_EMIT StatusNotifierItemUnregistered(pid.toUInt()); } } } if (m_statusNotifierHostServices.contains(service)) { m_statusNotifierHostServices.remove(service); Q_EMIT StatusNotifierHostUnregistered(); } } Watcher &Watcher::self() { static Watcher self; return self; } Watcher::Watcher(): d(new WatcherPrivate) { } Watcher::~Watcher() { if(d) { delete d; d = nullptr; } } ukui-sni/status-notifier-watcher/ukui-sni-watcher-config.h.in0000664000175000017500000000202715153755017023271 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: iaom */ #ifndef NOTIFICATION_SERVER_CONFIG_H_IN #define NOTIFICATION_SERVER_CONFIG_H_IN #define VERSION_MAJOR "@VERSION_MAJOR@" #define VERSION_MINOR "@VERSION_MINOR@" #define VERSION_MICRO "@VERSION_MICRO@" #define UKUI_SNI_WATCHER_VERSION "@UKUI_SNI_WATCHER_VERSION@" #endif // UKUI_SNI_WATCHER_CONFIG_Hukui-sni/status-notifier-watcher/watcher.h0000664000175000017500000000201515153755017017654 0ustar fengfeng/* * 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 UKUI_SNI_WATCHER_H #define UKUI_SNI_WATCHER_H #include class WatcherPrivate; class Watcher { public: static Watcher &self(); ~Watcher(); private: explicit Watcher(); Q_DISABLE_COPY(Watcher) WatcherPrivate *d = nullptr; }; #endif //UKUI_SNI_WATCHER_H ukui-sni/status-notifier-watcher/status-notifier-watcher-application.cpp0000664000175000017500000000445115153755017025654 0ustar fengfeng/* * 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 #include #include "status-notifier-watcher-application.h" #include #include "ukui-sni-watcher-config.h" #include "watcher.h" StatusNotifierWatcherApplication::StatusNotifierWatcherApplication(int &argc, char **argv, const QString &applicationName) : QtSingleCoreApplication(applicationName, argc, argv) { setApplicationVersion(UKUI_SNI_WATCHER_VERSION); qApp->setProperty("IS_UKUI_NOTIFICATION_SERVER", QVariant(true)); if (!this->isRunning()) { connect(this, &QtSingleCoreApplication::messageReceived, [=](QString msg) { this->parseCmd(std::move(msg), true); }); Watcher::self(); } parseCmd(arguments().join(" ").toUtf8(), !isRunning()); } void StatusNotifierWatcherApplication::parseCmd(const QString& msg, bool isPrimary) { QCommandLineParser parser; parser.addHelpOption(); parser.addVersionOption(); QCommandLineOption quitOption(QStringList()<<"q"<<"quit", tr("Quit ukui-sni-watcher")); parser.addOption(quitOption); if (isPrimary) { const QStringList args = QString(msg).split(' '); parser.process(args); if (parser.isSet(quitOption)) { qApp->quit(); return; } } else { if (arguments().count() < 2) { parser.showHelp(); } parser.process(arguments()); sendMessage(msg); } } StatusNotifierWatcherApplication::~StatusNotifierWatcherApplication() { } ukui-sni/log-utils.h0000664000175000017500000000243215153755611013346 0ustar fengfeng/* * 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-sni/cmake/0000775000175000017500000000000015153755017012335 5ustar fengfengukui-sni/cmake/find-modules/0000775000175000017500000000000015153755017014723 5ustar fengfengukui-sni/cmake/find-modules/FindXCB.cmake0000664000175000017500000000160315153755017017142 0ustar fengfenginclude(FeatureSummary) set_package_properties(XCB PROPERTIES URL "https://xcb.freedesktop.org/" DESCRIPTION "X protocol C-language Binding") find_package(PkgConfig) pkg_check_modules(PC_XCB xcb ${XCB_FIND_COMPONENTS}) find_library(XCB_LIBRARIES xcb HINTS ${PC_XCB_LIBRARY_DIRS}) find_path(XCB_INCLUDE_DIRS xcb/xcb.h PATH_SUFFIXES xcb HINTS ${PC_XCB_INCLUDE_DIRS}) foreach(COMPONENT ${XCB_FIND_COMPONENTS}) find_library(XCB_LIBRARIES_${COMPONENT} ${COMPONENT} HINTS ${PC_XCB_LIBRARY_DIRS}) list(APPEND XCB_LIBRARIES ${XCB_LIBRARIES_${COMPONENT}}) mark_as_advanced(XCB_LIBRARIES_${COMPONENT}) endforeach(COMPONENT ${XCB_FIND_COMPONENTS}) set(XCB_DEFINITIONS ${PC_XCB_CFLAGS_OTHER}) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(XCB DEFAULT_MSG XCB_LIBRARIES XCB_INCLUDE_DIRS) mark_as_advanced(XCB_INCLUDE_DIRS XCB_LIBRARIES XCB_DEFINITIONS)ukui-sni/xembed-sni-proxy/0000775000175000017500000000000015153755611014467 5ustar fengfengukui-sni/xembed-sni-proxy/xtest-sender.h0000664000175000017500000000064715153755017017274 0ustar fengfeng/* Wrap XLIB code in a new file as it defines keywords that conflict with Qt SPDX-FileCopyrightText: 2017 David Edmundson SPDX-FileCopyrightText: 2023 iaom SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once typedef struct _XDisplay Display; void sendXTestPressed(Display *display, int button); void sendXTestReleased(Display *display, int button); ukui-sni/xembed-sni-proxy/xcb-utils.h0000664000175000017500000000537115153755017016560 0ustar fengfeng/* SPDX-FileCopyrightText: 2012, 2013 Martin Graesslin SPDX-FileCopyrightText: 2015 David Edmudson SPDX-FileCopyrightText: 2023 iaom SPDX-License-Identifier: GPL-2.0-or-later */ #pragma once #include #include #include #include #include #include #include #include #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) #include #else #include #endif #include /** XEMBED messages */ #define XEMBED_EMBEDDED_NOTIFY 0 #define XEMBED_WINDOW_ACTIVATE 1 #define XEMBED_WINDOW_DEACTIVATE 2 #define XEMBED_REQUEST_FOCUS 3 #define XEMBED_FOCUS_IN 4 #define XEMBED_FOCUS_OUT 5 #define XEMBED_FOCUS_NEXT 6 #define XEMBED_FOCUS_PREV 7 namespace Xcb { class Atom { public: explicit Atom(const QByteArray &name, bool onlyIfExists = false, xcb_connection_t *c = QX11Info::connection()) : m_connection(c) , m_retrieved(false) , m_cookie(xcb_intern_atom_unchecked(m_connection, onlyIfExists, name.length(), name.constData())) , m_atom(XCB_ATOM_NONE) , m_name(name) { } Atom() = delete; Atom(const Atom &) = delete; ~Atom() { if (!m_retrieved && m_cookie.sequence) { xcb_discard_reply(m_connection, m_cookie.sequence); } } operator xcb_atom_t() const { (const_cast(this))->getReply(); return m_atom; } bool isValid() { getReply(); return m_atom != XCB_ATOM_NONE; } bool isValid() const { (const_cast(this))->getReply(); return m_atom != XCB_ATOM_NONE; } inline const QByteArray &name() const { return m_name; } private: void getReply() { if (m_retrieved || !m_cookie.sequence) { return; } UniqueCPointer reply(xcb_intern_atom_reply(m_connection, m_cookie, nullptr)); if (reply) { m_atom = reply->atom; } m_retrieved = true; } xcb_connection_t *m_connection; bool m_retrieved; xcb_intern_atom_cookie_t m_cookie; xcb_atom_t m_atom; QByteArray m_name; }; class Atoms { public: Atoms() : xembedAtom("_XEMBED") , selectionAtom(xcb_atom_name_by_screen("_NET_SYSTEM_TRAY", QX11Info::appScreen())) , opcodeAtom("_NET_SYSTEM_TRAY_OPCODE") , messageData("_NET_SYSTEM_TRAY_MESSAGE_DATA") , visualAtom("_NET_SYSTEM_TRAY_VISUAL") { } Atom xembedAtom; Atom selectionAtom; Atom opcodeAtom; Atom messageData; Atom visualAtom; }; extern Atoms *atoms; } // namespace Xcb ukui-sni/xembed-sni-proxy/xtest-sender.cpp0000664000175000017500000000104415153755017017617 0ustar fengfeng/* Wrap XLIB code in a new file as it defines keywords that conflict with Qt SPDX-FileCopyrightText: 2017 David Edmundson SPDX-FileCopyrightText: 2023 iaom SPDX-License-Identifier: LGPL-2.1-or-later */ #include "xtest-sender.h" #include void sendXTestPressed(Display *display, int button) { XTestFakeButtonEvent(display, button, true, 0); } void sendXTestReleased(Display *display, int button) { XTestFakeButtonEvent(display, button, false, 0); } ukui-sni/xembed-sni-proxy/sni-proxy.h0000664000175000017500000001007715153755611016615 0ustar fengfeng/* Holds one embedded window, registers as DBus entry SPDX-FileCopyrightText: 2015 David Edmundson SPDX-FileCopyrightText: 2019 Konrad Materka SPDX-FileCopyrightText: 2023 iaom SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include #include #include #include #include #include #include #include #include "typedefs.h" class SNIProxy : public QObject { Q_OBJECT Q_PROPERTY(QString Category READ Category) Q_PROPERTY(QString Id READ Id) Q_PROPERTY(QString Title READ Title) Q_PROPERTY(QString Status READ Status) Q_PROPERTY(int WindowId READ WindowId) Q_PROPERTY(QDBusObjectPath Menu READ Menu) Q_PROPERTY(bool ItemIsMenu READ ItemIsMenu) Q_PROPERTY(DbusImageVector IconPixmap READ IconPixmap) public: explicit SNIProxy(xcb_window_t wid, QObject *parent = nullptr); ~SNIProxy() override; void update(); void resizeWindow(const uint16_t width, const uint16_t height) const; /** * @return the category of the application associated to this item * @see Category */ QString Category() const; /** * @return the id of this item */ QString Id() const; /** * @return the title of this item */ QString Title() const; /** * @return The status of this item * @see Status */ QString Status() const; /** * @return The id of the main window of the application that controls the item */ int WindowId() const; QDBusObjectPath Menu() const; /** * @return The item only support the context menu, the visualization should prefer sending ContextMenu() instead of Activate() */ bool ItemIsMenu() const; /** * @return a serialization of the icon data */ DbusImageVector IconPixmap() const; public Q_SLOTS: // interaction /** * Shows the context menu associated to this item * at the desired screen position */ void ContextMenu(int x, int y); /** * Shows the main widget and try to position it on top * of the other windows, if the widget is already visible, hide it. */ void Activate(int x, int y); /** * The user activated the item in an alternate way (for instance with middle mouse button, this depends from the systray implementation) */ void SecondaryActivate(int x, int y); /** * Inform this item that the mouse wheel was used on its representation */ void Scroll(int delta, const QString &orientation); void ProvideXdgActivationToken(const QString &token); Q_SIGNALS: /** * Inform the systemtray that the own main icon has been changed, * so should be reloaded */ void NewIcon(); /** * Inform the systemtray that there is a new icon to be used as overlay */ void NewOverlayIcon(); /** * Inform the systemtray that the requesting attention icon * has been changed, so should be reloaded */ void NewAttentionIcon(); /** * Inform the systemtray that something in the tooltip has been changed */ void NewToolTip(); /** * Signal the new status when it has been changed * @see Status */ void NewStatus(const QString &status); private: enum InjectMode { Direct, XTest, }; QSize calculateClientWindowSize() const; void sendClick(uint8_t mouseButton, int x, int y); QImage getImageNonComposite() const; bool isTransparentImage(const QImage &image) const; QImage convertFromNative(xcb_image_t *xcbImage) const; QPoint calculateClickPoint() const; void setActiveForInput(bool active) const; uint getPid(const xcb_window_t windowId); QDBusConnection m_dbus; xcb_window_t m_windowId; xcb_window_t m_containerWid; static int s_serviceCount; QPixmap m_pixmap; bool sendingClickEvent; InjectMode m_injectMode; xcb_atom_t m_pidAtom; QMap m_pidToProxyCount; }; ukui-sni/xembed-sni-proxy/fdo-selection-manager.cpp0000664000175000017500000001764015153755611021346 0ustar fengfeng/* Registers as a embed container SPDX-FileCopyrightText: 2015 David Edmundson SPDX-FileCopyrightText: 2019 Konrad Materka SPDX-FileCopyrightText: 2023 iaom SPDX-License-Identifier: LGPL-2.1-or-later */ #include "fdo-selection-manager.h" #include #include #include #include #include #include #include #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) #include #else #include #endif #include "sni-proxy.h" #include "xcb-utils.h" #include "c_ptr.h" #define SYSTEM_TRAY_REQUEST_DOCK 0 #define SYSTEM_TRAY_BEGIN_MESSAGE 1 #define SYSTEM_TRAY_CANCEL_MESSAGE 2 FdoSelectionManager::FdoSelectionManager() : QObject() , m_selectionOwner(new KSelectionOwner(Xcb::atoms->selectionAtom, -1, this)) { qDebug() << "starting"; // we may end up calling QCoreApplication::quit() in this method, at which point we need the event loop running QTimer::singleShot(0, this, &FdoSelectionManager::init); } FdoSelectionManager::~FdoSelectionManager() { qDebug() << "closing"; m_selectionOwner->release(); } void FdoSelectionManager::init() { // load damage extension xcb_connection_t *c = QX11Info::connection(); xcb_prefetch_extension_data(c, &xcb_damage_id); const auto *reply = xcb_get_extension_data(c, &xcb_damage_id); if (reply && reply->present) { m_damageEventBase = reply->first_event; xcb_damage_query_version_unchecked(c, XCB_DAMAGE_MAJOR_VERSION, XCB_DAMAGE_MINOR_VERSION); } else { // no XDamage means qCritical() << "could not load damage extension. Quitting"; qApp->exit(-1); } qApp->installNativeEventFilter(this); connect(m_selectionOwner, &KSelectionOwner::claimedOwnership, this, &FdoSelectionManager::onClaimedOwnership); connect(m_selectionOwner, &KSelectionOwner::failedToClaimOwnership, this, &FdoSelectionManager::onFailedToClaimOwnership); connect(m_selectionOwner, &KSelectionOwner::lostOwnership, this, &FdoSelectionManager::onLostOwnership); m_selectionOwner->claim(false); } bool FdoSelectionManager::addDamageWatch(xcb_window_t client) { qDebug() << "adding damage watch for " << client; xcb_connection_t *c = QX11Info::connection(); const auto attribsCookie = xcb_get_window_attributes_unchecked(c, client); const auto damageId = xcb_generate_id(c); m_damageWatches[client] = damageId; xcb_damage_create(c, damageId, client, XCB_DAMAGE_REPORT_LEVEL_NON_EMPTY); xcb_generic_error_t *error = nullptr; UniqueCPointer attr(xcb_get_window_attributes_reply(c, attribsCookie, &error)); UniqueCPointer getAttrError(error); uint32_t events = XCB_EVENT_MASK_STRUCTURE_NOTIFY; if (attr) { events = events | attr->your_event_mask; } // if window is already gone, there is no need to handle it. if (getAttrError && getAttrError->error_code == XCB_WINDOW) { return false; } // the event mask will not be removed again. We cannot track whether another component also needs STRUCTURE_NOTIFY (e.g. KWindowSystem). // if we would remove the event mask again, other areas will break. const auto changeAttrCookie = xcb_change_window_attributes_checked(c, client, XCB_CW_EVENT_MASK, &events); UniqueCPointer changeAttrError(xcb_request_check(c, changeAttrCookie)); // if window is gone by this point, it will be caught by eventFilter, so no need to check later errors. if (changeAttrError && changeAttrError->error_code == XCB_WINDOW) { return false; } return true; } #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) bool FdoSelectionManager::nativeEventFilter(const QByteArray &eventType, void *message, qintptr *result) #else bool FdoSelectionManager::nativeEventFilter(const QByteArray &eventType, void *message, long *result) #endif { Q_UNUSED(result) if (eventType != "xcb_generic_event_t") { return false; } xcb_generic_event_t *ev = static_cast(message); const auto responseType = XCB_EVENT_RESPONSE_TYPE(ev); if (responseType == XCB_CLIENT_MESSAGE) { const auto ce = reinterpret_cast(ev); if (ce->type == Xcb::atoms->opcodeAtom) { switch (ce->data.data32[1]) { case SYSTEM_TRAY_REQUEST_DOCK: dock(ce->data.data32[2]); return true; } } } else if (responseType == XCB_UNMAP_NOTIFY) { const auto unmappedWId = reinterpret_cast(ev)->window; if (m_proxies.contains(unmappedWId)) { undock(unmappedWId); } } else if (responseType == XCB_DESTROY_NOTIFY) { const auto destroyedWId = reinterpret_cast(ev)->window; if (m_proxies.contains(destroyedWId)) { undock(destroyedWId); } } else if (responseType == m_damageEventBase + XCB_DAMAGE_NOTIFY) { const auto damagedWId = reinterpret_cast(ev)->drawable; const auto sniProxy = m_proxies.value(damagedWId); if (sniProxy) { sniProxy->update(); xcb_damage_subtract(QX11Info::connection(), m_damageWatches[damagedWId], XCB_NONE, XCB_NONE); } } else if (responseType == XCB_CONFIGURE_REQUEST) { const auto event = reinterpret_cast(ev); const auto sniProxy = m_proxies.value(event->window); if (sniProxy) { // The embedded window tries to move or resize. Ignore move, handle resize only. if ((event->value_mask & XCB_CONFIG_WINDOW_WIDTH) || (event->value_mask & XCB_CONFIG_WINDOW_HEIGHT)) { sniProxy->resizeWindow(event->width, event->height); } } } return false; } void FdoSelectionManager::dock(xcb_window_t winId) { qDebug() << "trying to dock window " << winId; if (m_proxies.contains(winId)) { return; } if (addDamageWatch(winId)) { m_proxies[winId] = new SNIProxy(winId, this); } } void FdoSelectionManager::undock(xcb_window_t winId) { qDebug() << "trying to undock window " << winId; if (!m_proxies.contains(winId)) { return; } m_proxies[winId]->deleteLater(); m_proxies.remove(winId); } void FdoSelectionManager::onClaimedOwnership() { qDebug() << "Manager selection claimed"; setSystemTrayVisual(); } void FdoSelectionManager::onFailedToClaimOwnership() { qWarning() << "failed to claim ownership of Systray Manager"; qApp->exit(-1); } void FdoSelectionManager::onLostOwnership() { qWarning() << "lost ownership of Systray Manager"; qApp->exit(-1); } void FdoSelectionManager::setSystemTrayVisual() { xcb_connection_t *c = QX11Info::connection(); auto screen = xcb_setup_roots_iterator(xcb_get_setup(c)).data; auto trayVisual = screen->root_visual; xcb_depth_iterator_t depth_iterator = xcb_screen_allowed_depths_iterator(screen); xcb_depth_t *depth = nullptr; while (depth_iterator.rem) { if (depth_iterator.data->depth == 32) { depth = depth_iterator.data; break; } xcb_depth_next(&depth_iterator); } if (depth) { xcb_visualtype_iterator_t visualtype_iterator = xcb_depth_visuals_iterator(depth); while (visualtype_iterator.rem) { xcb_visualtype_t *visualtype = visualtype_iterator.data; if (visualtype->_class == XCB_VISUAL_CLASS_TRUE_COLOR) { trayVisual = visualtype->visual_id; break; } xcb_visualtype_next(&visualtype_iterator); } } xcb_change_property(c, XCB_PROP_MODE_REPLACE, m_selectionOwner->ownerWindow(), Xcb::atoms->visualAtom, XCB_ATOM_VISUALID, 32, 1, &trayVisual); } ukui-sni/xembed-sni-proxy/sni-proxy.cpp0000664000175000017500000006012615153755611017150 0ustar fengfeng/* Holds one embedded window, registers as DBus entry SPDX-FileCopyrightText: 2015 David Edmundson SPDX-FileCopyrightText: 2019 Konrad Materka SPDX-FileCopyrightText: 2023 iaom SPDX-License-Identifier: LGPL-2.1-or-later */ #include "sni-proxy.h" #include #include #include #include #include "xcb-utils.h" #include #include #include #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) #include #else #include #endif #include #include #include #include #include "statusnotifieritemadaptor.h" #include "statusnotifierwatcher_interface.h" #include "xtest-sender.h" #include "c_ptr.h" // #define VISUAL_DEBUG #define SNI_WATCHER_SERVICE_NAME "org.kde.StatusNotifierWatcher" #define SNI_WATCHER_PATH "/StatusNotifierWatcher" static uint16_t s_embedSize = 32; // max size of window to embed. We no longer resize the embedded window as Chromium acts stupidly. static unsigned int XEMBED_VERSION = 0; int SNIProxy::s_serviceCount = 0; qreal getCurrentScale(int x = 0, int y = 0) { // Get scaling factor from the screen containing the click coordinates qreal scale = 1.0; QScreen *targetScreen = QGuiApplication::screenAt(QPoint(x, y)); if (!targetScreen) { qDebug() << "using primary screen info"; targetScreen = QGuiApplication::primaryScreen(); } if (targetScreen) { qreal logicalDotsPerInch = targetScreen->logicalDotsPerInch(); scale = logicalDotsPerInch / 96.0; } qDebug() << "get scaling factor:" << scale << "for coordinates (" << x << ", " << y << ")"; return scale; } void xembed_message_send(xcb_window_t towin, long message, long d1, long d2, long d3) { xcb_client_message_event_t ev; ev.response_type = XCB_CLIENT_MESSAGE; ev.window = towin; ev.format = 32; ev.data.data32[0] = XCB_CURRENT_TIME; ev.data.data32[1] = message; ev.data.data32[2] = d1; ev.data.data32[3] = d2; ev.data.data32[4] = d3; ev.type = Xcb::atoms->xembedAtom; xcb_send_event(QX11Info::connection(), false, towin, XCB_EVENT_MASK_NO_EVENT, (char *)&ev); } static bool checkWindowOrDescendantWantButtonEvents(xcb_window_t window) { auto connection = QX11Info::connection(); auto waCookie = xcb_get_window_attributes(connection, window); UniqueCPointer windowAttributes(xcb_get_window_attributes_reply(connection, waCookie, nullptr)); if (windowAttributes && windowAttributes->all_event_masks & XCB_EVENT_MASK_BUTTON_PRESS) { return true; } if (windowAttributes && windowAttributes->do_not_propagate_mask & XCB_EVENT_MASK_BUTTON_PRESS) { return false; } auto treeCookie = xcb_query_tree(connection, window); UniqueCPointer tree(xcb_query_tree_reply(connection, treeCookie, nullptr)); if (!tree) { return false; } std::span children(xcb_query_tree_children(tree.get()), xcb_query_tree_children_length(tree.get())); return std::ranges::any_of(children, &checkWindowOrDescendantWantButtonEvents); } SNIProxy::SNIProxy(xcb_window_t wid, QObject *parent) : QObject(parent) , // Work round a bug in our SNIWatcher with multiple SNIs per connection. // there is an undocumented feature that you can register an SNI by path, however it doesn't detect an object on a service being removed, only the entire // service closing instead lets use one DBus connection per SNI m_dbus(QDBusConnection::connectToBus(QDBusConnection::SessionBus, QStringLiteral("XembedSniProxy%1").arg(s_serviceCount++))) , m_windowId(wid) , m_injectMode(Direct) { new StatusNotifierItemAdaptor(this); uint pid = getPid(m_windowId); QString serviceName; if(pid > 0) { uint count = 0; if(m_pidToProxyCount.contains(pid)) { count = m_pidToProxyCount.value(pid) + 1; m_pidToProxyCount.insert(pid, count); } else { m_pidToProxyCount.insert(pid, 1); } serviceName = QStringLiteral("org.ukui.proxy.StatusNotifierItem-") + QString::number(pid) + QStringLiteral("-") + QString::number(count); m_dbus.registerService(serviceName); } // create new SNI m_dbus.registerObject(QStringLiteral("/StatusNotifierItem"), this); auto statusNotifierWatcher = new org::kde::StatusNotifierWatcher(QStringLiteral(SNI_WATCHER_SERVICE_NAME), QStringLiteral(SNI_WATCHER_PATH), QDBusConnection::sessionBus(), this); auto reply = statusNotifierWatcher->RegisterStatusNotifierItem(serviceName.isEmpty()? m_dbus.baseService() : serviceName); reply.waitForFinished(); if (reply.isError()) { qWarning() << "could not register SNI:" << reply.error().message(); } auto c = QX11Info::connection(); // create a container window auto screen = xcb_setup_roots_iterator(xcb_get_setup(c)).data; m_containerWid = xcb_generate_id(c); uint32_t values[3]; uint32_t mask = XCB_CW_BACK_PIXEL | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK; values[0] = screen->black_pixel; // draw a solid background so the embedded icon doesn't get garbage in it values[1] = true; // bypass wM values[2] = XCB_EVENT_MASK_STRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT; xcb_create_window(c, /* connection */ XCB_COPY_FROM_PARENT, /* depth */ m_containerWid, /* window Id */ screen->root, /* parent window */ 0, 0, /* x, y */ s_embedSize, s_embedSize, /* width, height */ 0, /* border_width */ XCB_WINDOW_CLASS_INPUT_OUTPUT, /* class */ screen->root_visual, /* visual */ mask, values); /* masks */ /* We need the window to exist and be mapped otherwise the child won't render it's contents We also need it to exist in the right place to get the clicks working as GTK will check sendEvent locations to see if our window is in the right place. So even though our contents are drawn via compositing we still put this window in the right place Set opacity to 0 just to make sure this container never appears And set the input region to null so everything just clicks through */ setActiveForInput(false); #ifndef VISUAL_DEBUG NETWinInfo wm(c, m_containerWid, screen->root, NET::Properties(), NET::Properties2()); wm.setOpacity(0); #endif xcb_flush(c); xcb_map_window(c, m_containerWid); xcb_reparent_window(c, wid, m_containerWid, 0, 0); /* * Render the embedded window offscreen */ xcb_composite_redirect_window(c, wid, XCB_COMPOSITE_REDIRECT_MANUAL); /* we grab the window, but also make sure it's automatically reparented back * to the root window if we should die. */ xcb_change_save_set(c, XCB_SET_MODE_INSERT, wid); // tell client we're embedding it xembed_message_send(wid, XEMBED_EMBEDDED_NOTIFY, 0, m_containerWid, XEMBED_VERSION); // move window we're embedding const uint32_t windowMoveConfigVals[2] = {0, 0}; xcb_configure_window(c, wid, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, windowMoveConfigVals); QSize clientWindowSize = calculateClientWindowSize(); // show the embedded window otherwise nothing happens xcb_map_window(c, wid); xcb_clear_area(c, 0, wid, 0, 0, clientWindowSize.width(), clientWindowSize.height()); xcb_flush(c); // guess which input injection method to use // we can either send an X event to the client or XTest // some don't support direct X events (GTK3/4), and some don't support XTest because reasons // note also some clients might not have the XTest extension. We may as well assume it does and just fail to send later. // we query if the client selected button presses in the event mask // if the client does supports that we send directly, otherwise we'll use xtest auto waCookie = xcb_get_window_attributes(c, wid); UniqueCPointer windowAttributes(xcb_get_window_attributes_reply(c, waCookie, nullptr)); if (!checkWindowOrDescendantWantButtonEvents(wid)) { m_injectMode = XTest; } // there's no damage event for the first paint, and sometimes it's not drawn immediately // not ideal, but it works better than nothing // test with xchat before changing QTimer::singleShot(500, this, &SNIProxy::update); } SNIProxy::~SNIProxy() { auto c = QX11Info::connection(); xcb_destroy_window(c, m_containerWid); QDBusConnection::disconnectFromBus(m_dbus.name()); } void SNIProxy::update() { const QImage image = getImageNonComposite(); if (image.isNull()) { qDebug() << "No xembed icon for" << m_windowId << Title(); return; } int w = image.width(); int h = image.height(); m_pixmap = QPixmap::fromImage(image); if (w > s_embedSize || h > s_embedSize) { qDebug() << "Scaling pixmap of window" << m_windowId << Title() << "from w*h" << w << h; m_pixmap = m_pixmap.scaled(s_embedSize, s_embedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); } Q_EMIT NewIcon(); Q_EMIT NewToolTip(); } void SNIProxy::resizeWindow(const uint16_t width, const uint16_t height) const { auto connection = QX11Info::connection(); uint16_t widthNormalized = std::min(width, s_embedSize); uint16_t heighNormalized = std::min(height, s_embedSize); const uint32_t windowSizeConfigVals[2] = {widthNormalized, heighNormalized}; xcb_configure_window(connection, m_windowId, XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT, windowSizeConfigVals); xcb_flush(connection); } QSize SNIProxy::calculateClientWindowSize() const { auto c = QX11Info::connection(); auto cookie = xcb_get_geometry(c, m_windowId); UniqueCPointer clientGeom(xcb_get_geometry_reply(c, cookie, nullptr)); QSize clientWindowSize; if (clientGeom) { clientWindowSize = QSize(clientGeom->width, clientGeom->height); } // if the window is a clearly stupid size resize to be something sensible // this is needed as chromium and such when resized just fill the icon with transparent space and only draw in the middle // however KeePass2 does need this as by default the window size is 273px wide and is not transparent // use an arbitrary heuristic to make sure icons are always sensible if (clientWindowSize.isEmpty() || clientWindowSize.width() > s_embedSize || clientWindowSize.height() > s_embedSize) { qDebug() << "Resizing window" << m_windowId << Title() << "from w*h" << clientWindowSize; resizeWindow(s_embedSize, s_embedSize); clientWindowSize = QSize(s_embedSize, s_embedSize); } return clientWindowSize; } void sni_cleanup_xcb_image(void *data) { xcb_image_destroy(static_cast(data)); } bool SNIProxy::isTransparentImage(const QImage &image) const { int w = image.width(); int h = image.height(); // check for the center and sub-center pixels first and avoid full image scan if (!(qAlpha(image.pixel(w >> 1, h >> 1)) + qAlpha(image.pixel(w >> 2, h >> 2)) == 0)) return false; // skip scan altogether if sub-center pixel found to be opaque // and break out from the outer loop too on full scan for (int x = 0; x < w; ++x) { for (int y = 0; y < h; ++y) { if (qAlpha(image.pixel(x, y))) { // Found an opaque pixel. return false; } } } return true; } QImage SNIProxy::getImageNonComposite() const { auto c = QX11Info::connection(); QSize clientWindowSize = calculateClientWindowSize(); xcb_image_t *image = xcb_image_get(c, m_windowId, 0, 0, clientWindowSize.width(), clientWindowSize.height(), 0xFFFFFFFF, XCB_IMAGE_FORMAT_Z_PIXMAP); // Don't hook up cleanup yet, we may use a different QImage after all QImage naiveConversion; if (image) { naiveConversion = QImage(image->data, image->width, image->height, QImage::Format_ARGB32); } else { qDebug() << "Skip NULL image returned from xcb_image_get() for" << m_windowId << Title(); return QImage(); } if (isTransparentImage(naiveConversion)) { QImage elaborateConversion = QImage(convertFromNative(image)); // Update icon only if it is at least partially opaque. // This is just a workaround for X11 bug: xembed icon may suddenly // become transparent for a one or few frames. Reproducible at least // with WINE applications. if (isTransparentImage(elaborateConversion)) { qDebug() << "Skip transparent xembed icon for" << m_windowId << Title(); return QImage(); } else return elaborateConversion; } else { // Now we are sure we can eventually delete the xcb_image_t with this version return QImage(image->data, image->width, image->height, image->stride, QImage::Format_ARGB32, sni_cleanup_xcb_image, image); } } QImage SNIProxy::convertFromNative(xcb_image_t *xcbImage) const { QImage::Format format = QImage::Format_Invalid; switch (xcbImage->depth) { case 1: format = QImage::Format_MonoLSB; break; case 16: format = QImage::Format_RGB16; break; case 24: format = QImage::Format_RGB32; break; case 30: { // Qt doesn't have a matching image format. We need to convert manually quint32 *pixels = reinterpret_cast(xcbImage->data); for (uint i = 0; i < (xcbImage->size / 4); i++) { int r = (pixels[i] >> 22) & 0xff; int g = (pixels[i] >> 12) & 0xff; int b = (pixels[i] >> 2) & 0xff; pixels[i] = qRgba(r, g, b, 0xff); } // fall through, Qt format is still Format_ARGB32_Premultiplied Q_FALLTHROUGH(); } case 32: format = QImage::Format_ARGB32_Premultiplied; break; default: return QImage(); // we don't know } QImage image(xcbImage->data, xcbImage->width, xcbImage->height, xcbImage->stride, format, sni_cleanup_xcb_image, xcbImage); if (image.isNull()) { return QImage(); } if (format == QImage::Format_RGB32 && xcbImage->bpp == 32) { QImage m = image.createHeuristicMask(); QPixmap p = QPixmap::fromImage(std::move(image)); p.setMask(QBitmap::fromImage(std::move(m))); image = p.toImage(); } // work around an abort in QImage::color if (image.format() == QImage::Format_MonoLSB) { image.setColorCount(2); image.setColor(0, QColor(Qt::white).rgb()); image.setColor(1, QColor(Qt::black).rgb()); } return image; } /* Wine is using XWindow Shape Extension for transparent tray icons. We need to find first clickable point starting from top-left. */ QPoint SNIProxy::calculateClickPoint() const { QSize clientSize = calculateClientWindowSize(); QPoint clickPoint = QPoint(clientSize.width() / 2, clientSize.height() / 2); auto c = QX11Info::connection(); // request extent to check if shape has been set xcb_shape_query_extents_cookie_t extentsCookie = xcb_shape_query_extents(c, m_windowId); // at the same time make the request for rectangles (even if this request isn't needed) xcb_shape_get_rectangles_cookie_t rectaglesCookie = xcb_shape_get_rectangles(c, m_windowId, XCB_SHAPE_SK_BOUNDING); UniqueCPointer extentsReply(xcb_shape_query_extents_reply(c, extentsCookie, nullptr)); UniqueCPointer rectanglesReply(xcb_shape_get_rectangles_reply(c, rectaglesCookie, nullptr)); if (!extentsReply || !rectanglesReply || !extentsReply->bounding_shaped) { return clickPoint; } xcb_rectangle_t *rectangles = xcb_shape_get_rectangles_rectangles(rectanglesReply.get()); if (!rectangles) { return clickPoint; } const QImage image = getImageNonComposite(); double minLength = sqrt(pow(image.height(), 2) + pow(image.width(), 2)); const int nRectangles = xcb_shape_get_rectangles_rectangles_length(rectanglesReply.get()); for (int i = 0; i < nRectangles; ++i) { double length = sqrt(pow(rectangles[i].x, 2) + pow(rectangles[i].y, 2)); if (length < minLength) { minLength = length; clickPoint = QPoint(rectangles[i].x, rectangles[i].y); } } qDebug() << "Click point:" << clickPoint; return clickPoint; } void SNIProxy::setActiveForInput(bool active) const { auto c = QX11Info::connection(); if (active) { xcb_rectangle_t rectangle; rectangle.x = 0; rectangle.y = 0; rectangle.width = s_embedSize; rectangle.height = s_embedSize; xcb_shape_rectangles(c, XCB_SHAPE_SO_SET, XCB_SHAPE_SK_INPUT, 0, m_containerWid, 0, 0, 1, &rectangle); const uint32_t stackData[] = {XCB_STACK_MODE_ABOVE}; xcb_configure_window(c, m_containerWid, XCB_CONFIG_WINDOW_STACK_MODE, stackData); } else { xcb_rectangle_t rectangle; rectangle.x = 0; rectangle.y = 0; rectangle.width = 0; rectangle.height = 0; xcb_shape_rectangles(c, XCB_SHAPE_SO_SET, XCB_SHAPE_SK_INPUT, 0, m_containerWid, 0, 0, 1, &rectangle); const uint32_t stackData[] = {XCB_STACK_MODE_BELOW}; xcb_configure_window(c, m_containerWid, XCB_CONFIG_WINDOW_STACK_MODE, stackData); } } //____________properties__________ QString SNIProxy::Category() const { return QStringLiteral("ApplicationStatus"); } QString SNIProxy::Id() const { const auto title = Title(); // we always need /some/ ID so if no window title exists, just use the winId. if (title.isEmpty()) { return QString::number(m_windowId); } return title; } DbusImageVector SNIProxy::IconPixmap() const { DbusImageStruct dbusImage(m_pixmap.toImage()); return DbusImageVector() << dbusImage; } bool SNIProxy::ItemIsMenu() const { return false; } QString SNIProxy::Status() const { return QStringLiteral("Active"); } QString SNIProxy::Title() const { KWindowInfo window(m_windowId, NET::WMName); return window.name(); } int SNIProxy::WindowId() const { return m_windowId; } //____________actions_____________ void SNIProxy::Activate(int x, int y) { sendClick(XCB_BUTTON_INDEX_1, x, y); } void SNIProxy::SecondaryActivate(int x, int y) { sendClick(XCB_BUTTON_INDEX_2, x, y); } void SNIProxy::ContextMenu(int x, int y) { sendClick(XCB_BUTTON_INDEX_3, x, y); } void SNIProxy::Scroll(int delta, const QString &orientation) { if (orientation == QLatin1String("vertical")) { sendClick(delta > 0 ? XCB_BUTTON_INDEX_4 : XCB_BUTTON_INDEX_5, 0, 0); } else { sendClick(delta > 0 ? 6 : 7, 0, 0); } } void SNIProxy::ProvideXdgActivationToken(const QString &token) { } void SNIProxy::sendClick(uint8_t mouseButton, int x, int y) { // it's best not to look at this code // GTK doesn't like send_events and double checks the mouse position matches where the window is and is top level // in order to solve this we move the embed container over to where the mouse is then replay the event using send_event // if patching, test with xchat + xchat context menus // note x,y are not actually where the mouse is, but the plasmoid // ideally we should make this match the plasmoid hit area qDebug() << "Received click" << mouseButton << "with passed x*y" << x << y; auto c = QX11Info::connection(); auto cookieSize = xcb_get_geometry(c, m_windowId); UniqueCPointer clientGeom(xcb_get_geometry_reply(c, cookieSize, nullptr)); if (!clientGeom) { return; } // move our window so the mouse is within its geometry uint32_t configVals[2] = {0, 0}; const QPoint clickPoint = calculateClickPoint(); qreal scale = getCurrentScale(x, y); if (mouseButton >= XCB_BUTTON_INDEX_4) { // scroll event, take pointer position auto cookie = xcb_query_pointer(c, m_windowId); UniqueCPointer pointer(xcb_query_pointer_reply(c, cookie, nullptr)); configVals[0] = pointer->root_x; configVals[1] = pointer->root_y; } else { // Convert logical coordinates to physical pixels int physicalX = static_cast(x * scale); int physicalY = static_cast(y * scale); configVals[0] = static_cast(physicalX - clickPoint.x()); configVals[1] = static_cast(physicalY - clickPoint.y()); } qDebug() << configVals[0] << configVals[1]; xcb_configure_window(c, m_containerWid, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, configVals); setActiveForInput(true); if (qgetenv("XDG_SESSION_TYPE") == "wayland") { xcb_warp_pointer(c, XCB_NONE, m_windowId, 0, 0, 0, 0, clickPoint.x(), clickPoint.y()); } // mouse down if (m_injectMode == Direct) { xcb_button_press_event_t *event = new xcb_button_press_event_t; memset(event, 0x00, sizeof(xcb_button_press_event_t)); event->response_type = XCB_BUTTON_PRESS; event->event = m_windowId; event->time = QX11Info::getTimestamp(); event->same_screen = 1; event->root = QX11Info::appRootWindow(); event->root_x = static_cast(x * scale); event->root_y = static_cast(y * scale); event->event_x = static_cast(clickPoint.x()); event->event_y = static_cast(clickPoint.y()); event->child = 0; event->state = 0; event->detail = mouseButton; xcb_send_event(c, false, m_windowId, XCB_EVENT_MASK_BUTTON_PRESS, (char *)event); delete event; } else { sendXTestPressed(QX11Info::display(), mouseButton); } // mouse up if (m_injectMode == Direct) { xcb_button_release_event_t *event = new xcb_button_release_event_t; memset(event, 0x00, sizeof(xcb_button_release_event_t)); event->response_type = XCB_BUTTON_RELEASE; event->event = m_windowId; event->time = QX11Info::getTimestamp(); event->same_screen = 1; event->root = QX11Info::appRootWindow(); event->root_x = static_cast(x * scale); event->root_y = static_cast(y * scale); event->event_x = static_cast(clickPoint.x()); event->event_y = static_cast(clickPoint.y()); event->child = 0; event->state = 0; event->detail = mouseButton; xcb_send_event(c, false, m_windowId, XCB_EVENT_MASK_BUTTON_RELEASE, (char *)event); delete event; } else { sendXTestReleased(QX11Info::display(), mouseButton); } if (m_injectMode == Direct) { setActiveForInput(false); } else { // delayed because on xwayland with the new libei path it will go to XWayland // then kwin, then back to X // we need to delay slightly until that happens if (qgetenv("XDG_SESSION_TYPE") == QByteArrayLiteral("wayland")) { QTimer::singleShot(300, this, [this]() { setActiveForInput(false); }); } else { setActiveForInput(false); } } } uint SNIProxy::getPid(const xcb_window_t windowId) { xcb_intern_atom_cookie_t cookie1 = xcb_intern_atom(QX11Info::connection(), false, 11, "_NET_WM_PID"); xcb_intern_atom_reply_t *reply1 = xcb_intern_atom_reply(QX11Info::connection(), cookie1, nullptr); m_pidAtom = reply1->atom; free(reply1); xcb_get_property_cookie_t cookie2 = xcb_get_property(QX11Info::connection(), false, windowId, m_pidAtom, XCB_ATOM_CARDINAL, 0, 1); xcb_get_property_reply_t *reply2 = xcb_get_property_reply(QX11Info::connection(), cookie2, nullptr); uint pid = 0; pid = *(uint *)xcb_get_property_value(reply2); free(reply2); return pid; } QDBusObjectPath SNIProxy::Menu() const { return QDBusObjectPath("/NO_DBUSMENU"); } ukui-sni/xembed-sni-proxy/CMakeLists.txt0000664000175000017500000000364615153755611017240 0ustar fengfengset(CMAKE_CXX_STANDARD 20) include(../cmake/find-modules/FindXCB.cmake) set(XCB_LIBS xcb xcb-util xcb-damage xcb-image xcb-composite xcb-shape ) if (QT_VERSION_MAJOR EQUAL 6) find_package(KF6WindowSystem REQUIRED) elseif (QT_VERSION_MAJOR EQUAL 5) find_package(KF5WindowSystem REQUIRED) endif() include_directories(../common) include_directories(../) set(XEMBED_SNI_PROXY_SOURCES main.cpp fdo-selection-manager.cpp fdo-selection-manager.h sni-proxy.cpp sni-proxy.h xtest-sender.cpp xtest-sender.h xcb-utils.h ../common/dbus-types.cpp ../common/dbus-types.h ../common/typedefs.h c_ptr.h ../log-utils.cpp ../log-utils.h ) qt_add_dbus_adaptor(XEMBED_SNI_PROXY_SOURCES ../dbus/org.kde.StatusNotifierItem.xml sni-proxy.h SNIProxy) set(statusnotifierwatcher_xml ../dbus/org.kde.StatusNotifierWatcher.xml) set_source_files_properties(${statusnotifierwatcher_xml} PROPERTIES NO_NAMESPACE false INCLUDE "../common/dbus-types.h" ) qt_add_dbus_interface(XEMBED_SNI_PROXY_SOURCES ${statusnotifierwatcher_xml} statusnotifierwatcher_interface) add_executable(xembed-sni-proxy ${XEMBED_SNI_PROXY_SOURCES}) target_include_directories(xembed-sni-proxy PUBLIC ../common) set_package_properties(XCB PROPERTIES TYPE REQUIRED) target_link_libraries(xembed-sni-proxy Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::DBus Qt${QT_VERSION_MAJOR}::Gui KF${QT_VERSION_MAJOR}::WindowSystem ${XCB_LIBS} X11::Xtst ) if (QT_MAJOR_VERSION EQUAL "5") target_link_libraries(xembed-sni-proxy Qt::X11Extras) else() target_link_libraries(xembed-sni-proxy Qt${QT_VERSION_MAJOR}::GuiPrivate) endif() install(TARGETS xembed-sni-proxy DESTINATION /usr/bin) install(FILES xembed-sni-proxy.desktop DESTINATION /etc/xdg/autostart) ukui-sni/xembed-sni-proxy/main.cpp0000664000175000017500000000315115153755017016117 0ustar fengfeng/* Main SPDX-FileCopyrightText: 2015 David Edmundson SPDX-FileCopyrightText: 2023 iaom SPDX-License-Identifier: LGPL-2.1-or-later */ #include #include #include "fdo-selection-manager.h" #include "dbus-types.h" #include "xcb-utils.h" #include #include #include namespace Xcb { Xcb::Atoms *atoms; } int main(int argc, char **argv) { LogUtils::initLogFile("xembed-sni-proxy"); qInstallMessageHandler(LogUtils::messageOutput); // the whole point of this is to interact with X, if we are in any other session, force trying to connect to X // if the QPA can't load xcb, this app is useless anyway. qputenv("QT_QPA_PLATFORM", "xcb"); QGuiApplication::setDesktopSettingsAware(false); QGuiApplication app(argc, argv); if (!KWindowSystem::isPlatformX11()) { qFatal("xembed-sni-proxy is only useful XCB. Aborting"); } auto disableSessionManagement = [](QSessionManager &sm) { sm.setRestartHint(QSessionManager::RestartNever); }; QObject::connect(&app, &QGuiApplication::commitDataRequest, disableSessionManagement); QObject::connect(&app, &QGuiApplication::saveStateRequest, disableSessionManagement); app.setQuitOnLastWindowClosed(false); qDBusRegisterMetaType(); qDBusRegisterMetaType(); qDBusRegisterMetaType(); Xcb::atoms = new Xcb::Atoms(); FdoSelectionManager manager; auto rc = app.exec(); delete Xcb::atoms; return rc; } ukui-sni/xembed-sni-proxy/fdo-selection-manager.h0000664000175000017500000000237515153755017021012 0ustar fengfeng/* Registers as a embed container SPDX-FileCopyrightText: 2015 David Edmundson SPDX-FileCopyrightText: 2023 iaom SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include #include #include #include class KSelectionOwner; class SNIProxy; class FdoSelectionManager : public QObject, public QAbstractNativeEventFilter { Q_OBJECT public: FdoSelectionManager(); ~FdoSelectionManager() override; protected: #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) bool nativeEventFilter(const QByteArray &eventType, void *message, qintptr *result) override; #else bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) override; #endif private Q_SLOTS: void onClaimedOwnership(); void onFailedToClaimOwnership(); void onLostOwnership(); private: void init(); bool addDamageWatch(xcb_window_t client); void dock(xcb_window_t embed_win); void undock(xcb_window_t client); void setSystemTrayVisual(); uint8_t m_damageEventBase; QHash m_damageWatches; QHash m_proxies; KSelectionOwner *m_selectionOwner; }; ukui-sni/xembed-sni-proxy/c_ptr.h0000664000175000017500000000065715153755017015757 0ustar fengfeng/* SPDX-FileCopyrightText: 2022 Xaver Hugl SPDX-FileCopyrightText: 2024 iaom SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include struct CDeleter { template void operator()(T *ptr) { if (ptr) { free(ptr); } } }; template using UniqueCPointer = std::unique_ptr; ukui-sni/xembed-sni-proxy/xembed-sni-proxy.desktop0000664000175000017500000000034415153755017021275 0ustar fengfeng[Desktop Entry] Exec=xembed-sni-proxy Name=xembed-sni-proxy Name[zh_CN]=xembed-sni-proxy Name[zh_TW]=xembed-sni-proxy Type=Application NoDisplay=true OnlyShowIn=UKUI; X-UKUI-AutoRestart=true X-UKUI-Autostart-Phase=Initializationukui-sni/test/0000775000175000017500000000000015153755611012234 5ustar fengfengukui-sni/test/status-notifier-model.cpp0000664000175000017500000001263315153755017017203 0ustar fengfeng#include "status-notifier-model.h" #include statusNotifierModel::statusNotifierModel(QObject *parent) : QAbstractListModel(parent) { m_sniHost = UkuiSni::StatusNotifierHost::self(); connect(m_sniHost, &UkuiSni::StatusNotifierHost::itemAdded, this, &statusNotifierModel::addSource); connect(m_sniHost, &UkuiSni::StatusNotifierHost::itemRemoved, this, &statusNotifierModel::removeSource); for (auto service : m_sniHost->services()) { addSource(service); } } int statusNotifierModel::rowCount(const QModelIndex &parent) const { return m_itemSource.length(); } QVariant statusNotifierModel::data(const QModelIndex &index, int role) const { int i = index.row(); if ((i < 0) || (i >= m_itemSource.length())) { return QVariant(); } UkuiSni::StatusNotifierItem *item = m_sniHost->itemForService(m_itemSource[i]); switch (static_cast(role)) { case Role::DataEngineSource: return m_itemSource[i]; case Role::Service: return item->service(); case Role::AttentionIcon: return extractIcon(item->attentionIcon(), item->icon()); case Role::AttentionIconName: return ("image://itemIcon/" + item->attentionIconName()); case Role::AttentionMovieName: return item->attentionMovieName(); case Role::Category: return item->category(); case Role::Icon: return extractIcon(item->icon()); case Role::IconName: return ("image://itemIcon/" + item->iconName()); case Role::IconThemePath: return "file://" + item->iconThemePath() + "/" +item->iconName(); case Role::Id: return item->id(); case Role::ItemIsMenu: return item->itemIsMenu(); case Role::OverlayIcon: return item->overlayIcon(); case Role::OverlayIconName: return item->overlayIconName(); case Role::Status: return item->status(); case Role::Title: return item->title(); case Role::ToolTipSubTitle: return item->toolTipSubTitle(); case Role::ToolTipTitle: return item->toolTipTitle(); case Role::WindowId: return item->windowId(); default: return QVariant(); } } QHash statusNotifierModel::roleNames() const { QHash roles; roles.insert(static_cast(Role::DataEngineSource), QByteArrayLiteral("DataEngineSource")); roles.insert(static_cast(Role::Service), QByteArrayLiteral("Service")); roles.insert(static_cast(Role::AttentionIcon), QByteArrayLiteral("AttentionIcon")); roles.insert(static_cast(Role::AttentionIconName), QByteArrayLiteral("AttentionIconName")); roles.insert(static_cast(Role::AttentionMovieName), QByteArrayLiteral("AttentionMovieName")); roles.insert(static_cast(Role::Category), QByteArrayLiteral("Category")); roles.insert(static_cast(Role::Icon), QByteArrayLiteral("Icon")); roles.insert(static_cast(Role::IconName), QByteArrayLiteral("IconName")); roles.insert(static_cast(Role::IconThemePath), QByteArrayLiteral("IconThemePath")); roles.insert(static_cast(Role::Id), QByteArrayLiteral("Id")); roles.insert(static_cast(Role::ItemIsMenu), QByteArrayLiteral("ItemIsMenu")); roles.insert(static_cast(Role::OverlayIcon), QByteArrayLiteral("OverlayIcon")); roles.insert(static_cast(Role::OverlayIconName), QByteArrayLiteral("OverlayIconName")); roles.insert(static_cast(Role::Status), QByteArrayLiteral("Status")); roles.insert(static_cast(Role::Title), QByteArrayLiteral("Title")); roles.insert(static_cast(Role::ToolTipSubTitle), QByteArrayLiteral("ToolTipSubTitle")); roles.insert(static_cast(Role::ToolTipTitle), QByteArrayLiteral("ToolTipTitle")); roles.insert(static_cast(Role::WindowId), QByteArrayLiteral("WindowId")); return roles; } QVariant statusNotifierModel::extractIcon(const QIcon &icon, const QVariant &defaultValue) { if (!icon.isNull()) { return icon; } else { return defaultValue; } } int statusNotifierModel::indexOfSource(const QString &source) const { for (int i = 0; i < rowCount(); i++) { if (m_itemSource[i] == source) { return i; } } return -1; } void statusNotifierModel::onActivate(int i) { m_sniHost->itemForService(m_itemSource[i])->activate(0,0); } void statusNotifierModel::onContextMenu(int i) { m_sniHost->itemForService(m_itemSource[i])->contextMenu(0,0); } void statusNotifierModel::addSource(const QString &source) { int i = rowCount(QModelIndex()); beginInsertRows(QModelIndex(), i, i); connect(m_sniHost->itemForService(source), &UkuiSni::StatusNotifierItem::dataUpdated, this, [=, this]() { dataUpdated(source); }); connect(m_sniHost->itemForService(source), &UkuiSni::StatusNotifierItem::contextMenuReady, this, &statusNotifierModel::showMenu); m_itemSource.append(source); endInsertRows(); } void statusNotifierModel::removeSource(const QString &source) { int i = indexOfSource(source); if (i >= 0) { beginRemoveRows(QModelIndex(), i, i); m_itemSource.removeAt(i); endRemoveRows(); } } void statusNotifierModel::dataUpdated(const QString &sourceName) { int i = indexOfSource(sourceName); if (i >= 0) { Q_EMIT dataChanged(index(i, 0), index(i, 0)); } } void statusNotifierModel::showMenu(QMenu *menu) { menu->exec(QCursor::pos()); } ukui-sni/test/dbus/0000775000175000017500000000000015153755017013171 5ustar fengfengukui-sni/test/dbus/org.kde.TrayAppStatusNotifierItem.xml0000664000175000017500000000627615153755017022361 0ustar fengfeng ukui-sni/test/tray-app.h0000664000175000017500000000640515153755017014147 0ustar fengfeng#ifndef TRAYAPP_H #define TRAYAPP_H #include #include "../common/dbus-types.h" #include "statusnotifierwatcher_interface.h" class TrayApp : public QObject { Q_OBJECT Q_PROPERTY(QString attentionIconName READ attentionIconName) Q_PROPERTY(DbusImageVector AttentionIconPixmap READ AttentionIconPixmap) Q_PROPERTY(QString AttentionMovieName READ AttentionMovieName) Q_PROPERTY(QString Category READ Category) Q_PROPERTY(QString IconName READ IconName) Q_PROPERTY(DbusImageVector IconPixmap READ IconPixmap) Q_PROPERTY(QString IconThemePath READ IconThemePath) Q_PROPERTY(QString Id READ Id) Q_PROPERTY(bool ItemIsMenu READ ItemIsMenu) Q_PROPERTY(QDBusObjectPath Menu READ Menu) Q_PROPERTY(QString OverlayIconName READ OverlayIconName) Q_PROPERTY(DbusImageVector OverlayIconPixmap READ OverlayIconPixmap) Q_PROPERTY(QString Status READ Status) Q_PROPERTY(QString Title READ Title) Q_PROPERTY(DbusToolTipStruct ToolTip READ ToolTip) Q_PROPERTY(int WindowId READ WindowId) public: TrayApp(QObject *parent = nullptr); void init(qint64 pid); QString attentionIconName() const { return m_attentionIconName; } DbusImageVector AttentionIconPixmap() const { return m_attentionIconPixmap; } QString AttentionMovieName() const { return m_attentionMovieName; } QString Category() const { return m_category; } QString IconName() const { return m_iconName; } DbusImageVector IconPixmap() const { return m_iconPixmap; } QString IconThemePath() const { return m_iconThemePath; } QString Id() const { return m_id; } bool ItemIsMenu() const { return m_itemIsMenu; } QDBusObjectPath Menu() const { return m_menu; } QString OverlayIconName() const { return m_overlayIconName; } DbusImageVector OverlayIconPixmap() const { return m_overlayIconPixmap; } QString Status() const { return m_status; } QString Title() const { return m_title; } DbusToolTipStruct ToolTip() const { return m_toolTip; } int WindowId() const { return m_windowId; } public Q_SLOTS: // METHODS void Activate(int x, int y); void ContextMenu(int x, int y); void ProvideXdgActivationToken(const QString &token); void Scroll(int delta, const QString &orientation); void SecondaryActivate(int x, int y); Q_SIGNALS: // SIGNALS void NewAttentionIcon(); void NewIcon(); void NewMenu(); void NewOverlayIcon(); void NewStatus(const QString &status); void NewTitle(); void NewToolTip(); private: org::kde::StatusNotifierWatcher *m_statusNotifierWatcher = nullptr; QString m_attentionIconName = ""; DbusImageVector m_attentionIconPixmap; QString m_attentionMovieName = ""; // QString m_attentionMovieName = "file:///home/gjq/gitcode/ukui-sni/test/res/icon/actionmovie.gif"; QString m_category = ""; QString m_iconName = "ukui-virtual-keyboard-symbolic"; DbusImageVector m_iconPixmap; QString m_iconThemePath; QString m_id = "Tray App"; bool m_itemIsMenu = false; QDBusObjectPath m_menu = QDBusObjectPath("/MenuBar"); QString m_overlayIconName = ""; DbusImageVector m_overlayIconPixmap; QString m_status = "NeedsAttention"; QString m_title = "Tray App"; DbusToolTipStruct m_toolTip; int m_windowId; }; #endif // TRAYAPP_H ukui-sni/test/item-icon-provider.h0000664000175000017500000000152515153755017016124 0ustar fengfeng#ifndef ITEMICONPROVIDER_H #define ITEMICONPROVIDER_H #include #include class ItemIconProvider : public QQuickImageProvider { public: ItemIconProvider(); QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) override; static QPixmap getPixmap(const QString &id, QSize *size, const QSize &requestedSize); private: static void loadPixmap(const QString &id, QPixmap &pixmap); static void loadDefault(QPixmap &pixmap); static bool loadPixmapFromUrl(const QUrl &url, QPixmap &pixmap); static bool loadPixmapFromPath(const QString &path, QPixmap &pixmap); static bool loadPixmapFromTheme(const QString &name, QPixmap &pixmap); static bool loadPixmapFromXdg(const QString &name, QPixmap &pixmap); static QSize m_defaultSize; }; #endif // ITEMICONPROVIDER_H ukui-sni/test/CMakeLists.txt0000664000175000017500000000355115153755611015000 0ustar fengfengif (QT_VERSION_MAJOR EQUAL 5) find_package(Qt5Xdg REQUIRED) else () find_package(Qt6Xdg REQUIRED) endif() set(statusNotifierHostTest_SRCS status-notifier-model.cpp status-notifier-model.h item-icon-provider.cpp item-icon-provider.h icon-item.cpp icon-item.h tray-app.cpp tray-app.h # setting.cpp setting.h main.cpp ) set(QRC_FILES qml.qrc) find_package(PkgConfig REQUIRED) set(UKUI_SNI_EXTERNAL_LIBS "") if (QT_VERSION_MAJOR EQUAL "5") set(UKUI_SNI_PC_PKGS gsettings-qt) elseif (QT_VERSION_MAJOR EQUAL "6") set(UKUI_SNI_PC_PKGS gsettings-qt6) endif() foreach(external_lib IN ITEMS ${UKUI_SNI_PC_PKGS}) pkg_check_modules(${external_lib} REQUIRED ${external_lib}) if(${${external_lib}_FOUND}) include_directories(${${external_lib}_INCLUDE_DIRS}) link_directories(${${external_lib}_LIBRARY_DIRS}) list(APPEND UKUI_SNI_EXTERNAL_LIBS ${${external_lib}_LIBRARIES}) endif() endforeach() message(STATUS "External libraries found: ${UKUI_SNI_EXTERNAL_LIBS}") include_directories(${CMAKE_SOURCE_DIR}/status-notifier-host) message(${CMAKE_SOURCE_DIR}) if(COMMAND qt_add_dbus_adaptor) qt_add_dbus_adaptor(statusNotifierHostTest_SRCS dbus/org.kde.TrayAppStatusNotifierItem.xml tray-app.h TrayApp) else() qt5_add_dbus_adaptor(statusNotifierHostTest_SRCS dbus/org.kde.TrayAppStatusNotifierItem.xml tray-app.h TrayApp) endif() qt_add_dbus_interface(statusNotifierHostTest_SRCS ../dbus/org.kde.StatusNotifierWatcher.xml statusnotifierwatcher_interface) add_executable(ukui-sni-test ${statusNotifierHostTest_SRCS} ${QRC_FILES}) target_link_libraries(ukui-sni-test PRIVATE Qt${QT_MAJOR_VERSION}::Core Qt${QT_MAJOR_VERSION}::Gui Qt${QT_VERSION_MAJOR}::Widgets Qt${QT_MAJOR_VERSION}::Quick Qt${QT_MAJOR_VERSION}Xdg ukui-sni-host ) ukui-sni/test/main.cpp0000664000175000017500000000357215153755017013673 0ustar fengfeng/* * Copyright (C) 2023, KylinSoft Co., Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Authors: iaom */ #include #include #include #include #include #include #include "status-notifier-host.h" #include "status-notifier-model.h" #include "item-icon-provider.h" #include "icon-item.h" #include "tray-app.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); QQmlApplicationEngine engine; engine.addImageProvider("itemIcon", new ItemIconProvider()); qmlRegisterType("IconItemModule",1,0,"IconItem"); TrayApp trayApp; trayApp.init(app.applicationPid()); UkuiSni::StatusNotifierHost::self()->registerHost(); QQmlContext *qmlCtx = engine.rootContext(); statusNotifierModel itemModel; qmlCtx->setContextProperty("itemModel", &itemModel); const QUrl url(QStringLiteral("qrc:/main.qml")); QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); qWarning() << QDir::currentPath(); return app.exec(); } ukui-sni/test/res/0000775000175000017500000000000015153755017013025 5ustar fengfengukui-sni/test/res/icon/0000775000175000017500000000000015153755017013755 5ustar fengfengukui-sni/test/res/icon/actionmovie.gif0000664000175000017500000025304515153755017016772 0ustar fengfengGIF89aw6ᅞ!4L|͛S~KnnoMz~yf~ϛ88Ӝ[8i h%v}~bfZ:|ɕFlў|˘H> "~+3+5~őUԽ(}WJȔ~vd*-/ 6LLLp~7~~¹*ןI~_~=>>pAA(~!\fl,llPPP 0Aτ''BeTz55c7D&HZ\kDv[ƙur˻`j5䇫g`o戝|ٶ!! NETSCAPE2.0,w H*\ȰÇ#JHŋ3jȱǏ CIɓ(S\ɲ˗0cʜI͛8sɳϟ@ JѣH*]ʴӧPJJիXjʵׯ`ÊKٳhӪ]˶۷pʝK=Qݺ3x@(~m0R*fkB̘2ϛ9Ɖ60=c" b31ɬ =el0ku޿x('eyγy{,^xul{g{7?/Oۇ߶yOac0⑗|els9ωNndg;Iuʓ锝=OwFg@YĀ tf+y[lC7Jt eUD/ j(E5Аbt-IOZӢ+=GҘʴ@MmzSQOuNvvMzۻj ] |{̄NOK'q :&>YrGN(OWNZ1pDY*%~fUj;X@ɯ<PzʇNu l1^BY`ԫ>t{?"p9_n .ccnwK 79t; m) 3?=./|o/ zrdqN@o=ů x$gqO|^L\mŏ>q'G^Kԗ}֭ O_ÕF|ԫ_쇹m|mwuwzv~hcumx ~VGW((~$&)wVٷ}0(8~ {ס}K'b7}98a|} A8v|ɵ|)v~KM{r%GrwUx(7zYG{M_y(zfxfukxa8ytfzG{tX`Rl!v&DWgB:fP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Z̦6nzS8IrL:׹NӀ~ @JЂ͂BJi}4+@ъRtChE1ыrT(H?jjvԤ#%GUZkT$ZB@\ 9%@ZZӍB)DJT (!u(mjVY@;ukui-sni/test/res/icon/computer.png0000664000175000017500000000046515153755017016326 0ustar fengfengPNG  IHDRaIDATxbp R5"o 8A_}^mI9kc߳8HT vɠ1`ԹHMa(`dRׯI;<\r7w g3]'Q1"A]h Mm m+PRgzn`-x_o{ H2@CCҥK-m߶?w˯Z2mB> _@Ćfa9;)IENDB`ukui-sni/test/res/icon/text.png0000664000175000017500000003335315153755017015456 0ustar fengfengPNG  IHDR@ƾgAMA a cHRMz&u0`:pQ<bKGD pHYs+tIME%$O25IDATxyUߙ$$d !(¾oaZQVYUADP6PPAeqٚ!@@Z!{r2s;SLzdnݮ]]u|TJ@LLLLڏ0xxx x[4J[LJ@LLLL1KRJXLޕ>__i;,}ݕ>2qRVʅ/<)0X ,qfIJ'fSW-ٓRf{>0 [^|^ WW#,{pigodll xʊJx[cD`۵}ϊ͕>\bY/oQjO?9Ŕok`_ںm6g*WzPкX|L^ gTܿ(ļTcvZ4'zpeb%Œnӿh5j `kyXp2Y/P+o 7J8bJ_ ^'J5O` 7< m+Nu_7E2!W쿫? TUzNV9nTz2 ❵sXsT4z잗QlB_MAg#*EyW9E9:d;uv@7+O WB )T،i2g0EWIcv9?Lj};*TzŠ,SD3`oh y8\4\^1Yb:Z7*s+ԽM@ vy+ܟ]9x 8/Pyc,o Ϩ9_]xWa4-wl<Y~[GEKq$PϱMw#UzHP%Z*^ac f (|Qmw9`6bpwxgrA4l ɯjp3t}On&`K= $@./T{.ñe _+c8)Ͼ5*pBZ P=iPc\9?*wm?o?eo`FQT5}}v/dA<20K\jуp1wo _'/@w=<OL_`,. ȱ Ö}aFph=]Ga $@w3y x[a={Ja(=c,o ū݆F5X(XS*^G*Ig ٘71ٜM(TlUD:k9^4|')J|nulZr[P)Cg2H4X4 sI X0(a_l3yyBb$gDCh>εywu4ua!6JT0C~= $18/@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yyHy4?$])}b xV_~B "d 6-4Đ gAoN=z`#(R j`[rxMK/5iD_/:<5D }~Pnݕ-GݺuXAIF(L$ KH2C(L8(:-\#ax2_oQt@$``$& 5AkXtR6Z1y .25o l{ehƍ,eęq[+L--M|Dc}&dI^p .3JMoiut m8]@G^DH D`lZeٲ_HVvӔ hKCP\Cj,كe*.ZΝ;P89==]Nd=۰k:xY1Dވ4Uj9e7`/ma۶,4h>U`5>1²81? *5D 85ћYJ/`ؒߴiSV Г΃aƮuԞzADfl&hLhF 9jڌTFM|mzС,/-DfQb5`8/ʨnݺ?h5E\pvȶ1h(q*ԑV J p~ lcXCdz-b0Ê8vfMw 'jؤIu'G+r [Ҹ  ?_IJi`Xݻw' 0Wf@c/8ICCQ֭ߐSJ|a+$3 Cr|H }|߾}e˖Le0JeLÇ BRbSKdF^APgϒ;eѮ]5EA#Ft֍e#oC!c>8QJ^Npr er"=I!h`4]*`$>`˖-yfC| ӧOWNz ==<sj֬8vkx-@{<>\@S ѥ3f G9 6Hz~?p7crJ5\|B̬^#;l՞W' B _-`Hz<ћi]g26իu/$aƙ!C<%338ʼ''!SIGΝSsŊ4gaU 6d)KpLP->@b v) YN2ha' U3g46 >|x+20 ? ;uĮWw Da{Dڳ{X,Dx@ݻ/=x$0k,c0lX#557~LrCS6m"xРa咝Q 7رv:#i*rs o4 #c "۷~\ ˶ҩzGYc!@ \dRh&fU|;P\\Z>$Gl .[鉯z uWnuQQ=+VdvRЦ <0*^L0#BX.&W^LVz|1.۷{TYVNU >4>_UgB-~JcNX-̙aF\ @Clpڜ={ΟuرK-&fL: ?;;ʬw5@=X]@|Pԡhٲe ZD>3r4q1JQ^^arPG, aX˅P:CD؁␓ #include #include #include "status-notifier-host.h" #include "status-notifier-item.h" class statusNotifierModel : public QAbstractListModel { Q_OBJECT public: enum class Role { DataEngineSource = 0, Service, AttentionIcon, AttentionIconName, AttentionMovieName, Category, Icon, IconName, IconThemePath, Id, ItemIsMenu, OverlayIcon, OverlayIconName, Status, Title, ToolTipSubTitle, ToolTipTitle, WindowId, }; explicit statusNotifierModel(QObject *parent = nullptr); int rowCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role) const override; QHash roleNames() const override; Q_INVOKABLE void onActivate(int i); Q_INVOKABLE void onContextMenu(int i); private Q_SLOTS: void addSource(const QString &source); void removeSource(const QString &source); void dataUpdated(const QString &sourceName); void showMenu(QMenu *menu); private: UkuiSni::StatusNotifierHost *m_sniHost = nullptr; QVector m_itemSource; static QVariant extractIcon(const QIcon &icon, const QVariant &defaultValue = QVariant()); int indexOfSource(const QString &source) const; }; #endif // STATUSNOTIFIERMODEL_H ukui-sni/test/item-icon-provider.cpp0000664000175000017500000000603115153755017016454 0ustar fengfeng#include #include #include #if QT_VERSION < QT_VERSION_CHECK(6,0,0) #include #else #include #endif #include "item-icon-provider.h" QSize ItemIconProvider::m_defaultSize = QSize(56, 56); ItemIconProvider::ItemIconProvider() : QQuickImageProvider(QQmlImageProviderBase::Pixmap) { } QPixmap ItemIconProvider::requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) { return ItemIconProvider::getPixmap(id, size, requestedSize); } QPixmap ItemIconProvider::getPixmap(const QString &id, QSize *size, const QSize &requestedSize) { Q_UNUSED(requestedSize); QPixmap pixmap; loadPixmap(id, pixmap); if (size) { QSize pixmapSize = pixmap.size(); size->setWidth(pixmapSize.width()); size->setHeight(pixmapSize.height()); } return pixmap; } void ItemIconProvider::loadPixmap(const QString &id, QPixmap &pixmap) { if (id.isEmpty()) { loadDefault(pixmap); return; } bool isOk; QUrl url(id); if (!url.scheme().isEmpty()) { isOk = loadPixmapFromUrl(url, pixmap); } else if (id.startsWith(QLatin1String("/")) || id.startsWith(QLatin1String(":/"))) { //qrc path: :/xxx/xxx.png isOk = loadPixmapFromPath(id, pixmap); } else { isOk = loadPixmapFromTheme(id, pixmap); if (!isOk) { isOk = loadPixmapFromXdg(id, pixmap); } } if (!isOk) { loadDefault(pixmap); } } void ItemIconProvider::loadDefault(QPixmap &pixmap) { if (!loadPixmapFromTheme("application-x-desktop", pixmap)) { loadPixmapFromPath(":/test/icon/application-x-desktop.png", pixmap); } } bool ItemIconProvider::loadPixmapFromUrl(const QUrl &url, QPixmap &pixmap) { QString path = url.path(); if (path.isEmpty()) { qWarning() << "Error: loadPixmapFromUrl, path is empty"; return false; } if (url.scheme() == QLatin1String("qrc")) { path.prepend(QLatin1String(":")); return loadPixmapFromPath(path, pixmap); } return false; } bool ItemIconProvider::loadPixmapFromPath(const QString &path, QPixmap &pixmap) { if (!QFile::exists(path)) { qWarning() << "Error: loadPixmapFromPath, File dose not exists" << path; return false; } QPixmap filePixmap; bool isok = filePixmap.load(path); if (!isok) { return false; } pixmap.swap(filePixmap); return true; } bool ItemIconProvider::loadPixmapFromTheme(const QString &name, QPixmap &pixmap) { if (!QIcon::hasThemeIcon(name)) { return false; } QIcon icon = QIcon::fromTheme(name); pixmap = icon.pixmap(ItemIconProvider::m_defaultSize); return true; } bool ItemIconProvider::loadPixmapFromXdg(const QString &name, QPixmap &pixmap) { QIcon icon = XdgIcon::fromTheme(name); if (icon.isNull()) { qWarning() << "Error: loadPixmapFromXdg, icon dose not exists. name:" << name; return false; } pixmap = icon.pixmap(ItemIconProvider::m_defaultSize); return true; } ukui-sni/test/main.qml0000664000175000017500000000457515153755017013706 0ustar fengfengimport QtQuick 2.15 import QtQuick.Window 2.15 import QtQuick.Controls 2.15 import IconItemModule 1.0 Window { width: 800 height: 50 visible: true title: qsTr("tray demo") ListView { id: trayview anchors.fill: parent model: itemModel orientation: ListView.Horizontal spacing: 5 delegate: Rectangle { id: trayitem property bool isSelect: false color: isSelect ? "lightblue" : "white" width: 50 height: 25 Loader { anchors.centerIn: parent sourceComponent: ((model.Status === "NeedsAttention") && (model.AttentionMovieName !== "")) ? movieComponent : iconComponent } Component { id: iconComponent IconItem { width: 20 height: 20 icon: (model.Status === "NeedsAttention") ? model.AttentionIcon : model.Icon overlayIcon: model.OverlayIcon isInverseColor: false MouseArea { id: control anchors.fill: parent hoverEnabled: true acceptedButtons: Qt.LeftButton | Qt.RightButton onClicked: { if (mouse.button === Qt.LeftButton) { trayview.model.onActivate(index); } if (mouse.button === Qt.RightButton) { trayview.model.onContextMenu(index); } } ToolTip.visible: control.containsMouse ToolTip.text: model.ToolTipTitle ToolTip.delay: 500 } } } Component { id: movieComponent AnimatedImage { width: 20 height: 20 source: model.AttentionMovieName } } } } // AnimatedSprite { // frameX: 0 // frameY: 0 // frameWidth: 64 // frameHeight: 64 // frameDuration: 1000 // frameCount: 10 // interpolate: false // source: "://res/icon/text.png" // } } ukui-sni/test/icon-item.h0000664000175000017500000000172315153755017014274 0ustar fengfeng#ifndef ICONITEM_H #define ICONITEM_H #include #include #include #include #include #include class IconItem : public QQuickPaintedItem { Q_OBJECT Q_PROPERTY(QVariant icon READ getIcon WRITE setIcon) Q_PROPERTY(QVariant overlayIcon READ getOverlayIcon WRITE setOverlayIcon) Q_PROPERTY(bool isInverseColor READ getIsInverseColor WRITE setIsInverseColor) public: IconItem(QQuickItem *parent = nullptr); QVariant getIcon() const; void setIcon(QVariant icon); QVariant getOverlayIcon() const; void setOverlayIcon(QVariant overlayIcon); bool getIsInverseColor(); bool setIsInverseColor(bool isInverseColor); protected: void paint(QPainter *painter) override; private: bool isPixmapPureColor(const QPixmap &pixmap); QVariant m_icon; QVariant m_overlayIcon; bool m_isInverseColor = false; static QColor symbolicColor; }; #endif // ICONITEM_H ukui-sni/test/qml.qrc0000664000175000017500000000062315153755017013535 0ustar fengfeng main.qml res/icon/text.png res/icon/application-x-desktop.png res/icon/actionmovie.gif res/icon/computer.png ukui-sni/test/tray-app.cpp0000664000175000017500000000431715153755017014502 0ustar fengfeng#include "tray-app.h" #include #include "trayappstatusnotifieritemadaptor.h" #include TrayApp::TrayApp(QObject *parent) : QObject(parent) { QImage image; image.load("://res/icon/application-x-desktop.png"); DbusImageVector vector; vector.append(DbusImageStruct(image)); m_attentionIconPixmap = vector; QImage image1; image1.load("://res/icon/computer.png"); DbusImageVector vector1; vector1.append(DbusImageStruct(image1)); m_overlayIconPixmap = vector1; } void TrayApp::Activate(int x, int y) { } void TrayApp::ContextMenu(int x, int y) { } void TrayApp::ProvideXdgActivationToken(const QString &token) { } void TrayApp::Scroll(int delta, const QString &orientation) { } void TrayApp::SecondaryActivate(int x, int y) { } void TrayApp::init(qint64 pid) { QString serviceName = QStringLiteral("org.kde.StatusNotifierItem") + QStringLiteral("-") + QString::number(pid) + QStringLiteral("-1"); new StatusNotifierItemAdaptor(this); QDBusConnection connection = QDBusConnection::sessionBus(); auto registration = connection.interface()->registerService(serviceName); if(m_statusNotifierWatcher) { delete m_statusNotifierWatcher; m_statusNotifierWatcher = nullptr; } m_statusNotifierWatcher = new org::kde::StatusNotifierWatcher(QStringLiteral("org.kde.StatusNotifierWatcher"), QStringLiteral("/StatusNotifierWatcher"), QDBusConnection::sessionBus(), this); if (m_statusNotifierWatcher->isValid()) { m_statusNotifierWatcher->call(QDBus::NoBlock, QStringLiteral("RegisterStatusNotifierItem"), serviceName); } if (registration.value() != QDBusConnectionInterface::ServiceRegistered) { qWarning() << "Failed to register StatusNotifierItem service on DBus!"; return; } if(!connection.registerObject(QStringLiteral("/StatusNotifierItem"), this)) { qWarning() << "Failed to register StatusNotifierItem DBus object!" << connection.lastError().message(); return; } return; } ukui-sni/test/icon-item.cpp0000664000175000017500000001033215153755017014623 0ustar fengfeng#include "icon-item.h" #include #include #include #include #include #define COLOR_DIFFERENCE 10 QColor IconItem::symbolicColor = QColor(31, 32, 34, 192); IconItem::IconItem(QQuickItem *parent) : QQuickPaintedItem(parent) { } QVariant IconItem::getIcon() const { return m_icon; } void IconItem::setIcon(QVariant icon) { m_icon = icon; update(); } QVariant IconItem::getOverlayIcon() const { return m_overlayIcon; } void IconItem::setOverlayIcon(QVariant overlayIcon) { m_overlayIcon = overlayIcon; update(); } bool IconItem::getIsInverseColor() { return m_isInverseColor; } bool IconItem::setIsInverseColor(bool isInverseColor) { m_isInverseColor = isInverseColor; update(); } void IconItem::paint(QPainter *painter) { QIcon icon = m_icon.value(); QPixmap pix = icon.pixmap(QSize(width(), height())); if (m_isInverseColor) { if (isPixmapPureColor(pix)) { QPainter p(&pix); p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); p.setCompositionMode(QPainter::CompositionMode_SourceIn); p.fillRect(pix.rect(), QGuiApplication::palette().color(QPalette::HighlightedText)); } } painter->drawPixmap(QRect(0,0,width(), height()), pix); QIcon overlayIcon = m_overlayIcon.value(); if (overlayIcon.isNull()) { return; } QPainter overlayPainter(&pix); int iconSize = qMin(width(), height()); int overlaySize; if (iconSize < 32) { overlaySize = 8; } else if (iconSize <= 48) { overlaySize = 16; } else if (iconSize <= 96) { overlaySize = 22; } else if (iconSize < 256) { overlaySize = 32; } else { overlaySize = 64; } QPixmap pixmap = overlayIcon.pixmap(overlaySize, overlaySize); pixmap.setDevicePixelRatio(pix.devicePixelRatio()); int margin = pixmap.devicePixelRatio() * 0.05 * iconSize; QPoint startPoint; startPoint = QPoint(width() - overlaySize - margin, height() - overlaySize - margin); startPoint /= pix.devicePixelRatio(); overlayPainter.drawPixmap(startPoint, pixmap); qWarning() << overlaySize; painter->drawPixmap(QRect(0,0,width(), height()), pix); } bool IconItem::isPixmapPureColor(const QPixmap &pixmap) { if (pixmap.isNull()) { qWarning("pixmap is null!"); return false; } QImage image = pixmap.toImage(); QVector vector; int total_red = 0; int total_green = 0; int total_blue = 0; bool pure = true; for (int y = 0; y < image.height(); ++y) { for (int x = 0; x < image.width(); ++x) { if (image.pixelColor(x, y).alphaF() > 0.3) { QColor color = image.pixelColor(x, y); vector << color; total_red += color.red(); total_green += color.green(); total_blue += color.blue(); int dr = qAbs(color.red() - symbolicColor.red()); int dg = qAbs(color.green() - symbolicColor.green()); int db = qAbs(color.blue() - symbolicColor.blue()); if (dr > COLOR_DIFFERENCE || dg > COLOR_DIFFERENCE || db > COLOR_DIFFERENCE) pure = false; } } } if (pure) return true; qreal squareRoot_red = 0; qreal squareRoot_green = 0; qreal squareRoot_blue = 0; qreal average_red = total_red / vector.count(); qreal average_green = total_green / vector.count(); qreal average_blue = total_blue / vector.count(); for (QColor color : vector) { squareRoot_red += (color.red() - average_red) * (color.red() - average_red); squareRoot_green += (color.green() - average_green) * (color.green() - average_green); squareRoot_blue += (color.blue() - average_blue) * (color.blue() - average_blue); } qreal arithmeticSquareRoot_red = qSqrt(squareRoot_red / vector.count()); qreal arithmeticSquareRoot_green = qSqrt(squareRoot_green / vector.count()); qreal arithmeticSquareRoot_blue = qSqrt(squareRoot_blue / vector.count()); return arithmeticSquareRoot_red < 2.0 && arithmeticSquareRoot_green < 2.0 && arithmeticSquareRoot_blue < 2.0; } ukui-sni/3rd-parties/0000775000175000017500000000000015153755017013412 5ustar fengfengukui-sni/3rd-parties/qtsingleapplication/0000775000175000017500000000000015153755017017464 5ustar fengfengukui-sni/3rd-parties/qtsingleapplication/src/0000775000175000017500000000000015153755017020253 5ustar fengfengukui-sni/3rd-parties/qtsingleapplication/src/qtlocalpeer.h0000664000175000017500000000144515153755017022743 0ustar fengfeng// 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 ukui-sni/3rd-parties/qtsingleapplication/src/qtsingleapplication.pri0000664000175000017500000000111015153755017025032 0ustar fengfenginclude(../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 } ukui-sni/3rd-parties/qtsingleapplication/src/CMakeLists.txt0000664000175000017500000000011615153755017023011 0ustar fengfengtarget_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})ukui-sni/3rd-parties/qtsingleapplication/src/qtlockedfile.cpp0000664000175000017500000001020215153755017023420 0ustar fengfeng// 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. */ ukui-sni/3rd-parties/qtsingleapplication/src/qtlockedfile.h0000664000175000017500000000254715153755017023102 0ustar fengfeng// 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 ukui-sni/3rd-parties/qtsingleapplication/src/qtsinglecoreapplication.h0000664000175000017500000000126515153755017025353 0ustar fengfeng// 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 ukui-sni/3rd-parties/qtsingleapplication/src/QtLockedFile0000664000175000017500000000003215153755017022477 0ustar fengfeng#include "qtlockedfile.h" ukui-sni/3rd-parties/qtsingleapplication/src/qtlockedfile_unix.cpp0000664000175000017500000000305415153755017024472 0ustar fengfeng// 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(); } ukui-sni/3rd-parties/qtsingleapplication/src/qtsingleapplication.cpp0000664000175000017500000002325015153755017025033 0ustar fengfeng// 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 */ ukui-sni/3rd-parties/qtsingleapplication/src/qtlocalpeer.cpp0000664000175000017500000001215115153755017023272 0ustar fengfeng// 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(); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) quint16 idNum = qChecksum(idc.constData(), idc.size()); #else quint16 idNum = qChecksum(QByteArrayView(idc.constData(), idc.size())); #endif 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) } ukui-sni/3rd-parties/qtsingleapplication/src/qtsingleapplication.h0000664000175000017500000000405715153755017024504 0ustar fengfeng// 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 ukui-sni/3rd-parties/qtsingleapplication/src/qtlockedfile_win.cpp0000664000175000017500000001112115153755017024276 0ustar fengfeng// 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); } ukui-sni/3rd-parties/qtsingleapplication/src/qtsinglecoreapplication.pri0000664000175000017500000000050415153755017025711 0ustar fengfengINCLUDEPATH += $$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-sni/3rd-parties/qtsingleapplication/src/qtsinglecoreapplication.cpp0000664000175000017500000000661515153755017025712 0ustar fengfeng// 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() */ ukui-sni/3rd-parties/qtsingleapplication/src/QtSingleApplication0000664000175000017500000000004115153755017024103 0ustar fengfeng#include "qtsingleapplication.h" ukui-sni/3rd-parties/qtsingleapplication/doc/0000775000175000017500000000000015153755017020231 5ustar fengfengukui-sni/3rd-parties/qtsingleapplication/doc/images/0000775000175000017500000000000015153755017021476 5ustar fengfengukui-sni/3rd-parties/qtsingleapplication/doc/images/qt-logo.png0000664000175000017500000000775315153755017023602 0ustar fengfengPNG  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"< QtSingleApplication Class Reference
  Home

QtSingleApplication Class Reference

 #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
ukui-sni/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication-members.html0000664000175000017500000007370215153755017027576 0ustar fengfeng 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
ukui-sni/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication.dcf0000664000175000017500000000507115153755017025730 0ustar fengfeng
QtSingleApplication activateWindow activationWindow id isRunning messageReceived sendMessage setActivationWindow
QtSingleCoreApplication id isRunning messageReceived sendMessage
A non-GUI example
A Trivial Example
Loading Documents
Single Application
ukui-sni/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication-example-trivial.html0000664000175000017500000001243415153755017031242 0ustar fengfeng 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
ukui-sni/3rd-parties/qtsingleapplication/doc/html/images/0000775000175000017500000000000015153755017022442 5ustar fengfengukui-sni/3rd-parties/qtsingleapplication/doc/html/images/qt-logo.png0000664000175000017500000000775315153755017024546 0ustar fengfengPNG  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"< 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
ukui-sni/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication-example-loader.html0000664000175000017500000001670015153755017031036 0ustar fengfeng 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
ukui-sni/3rd-parties/qtsingleapplication/doc/html/qtsinglecoreapplication.html0000664000175000017500000002356615153755017027022 0ustar fengfeng 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-sni/3rd-parties/qtsingleapplication/doc/html/qtsinglecoreapplication-members.html0000664000175000017500000003577715153755017030461 0ustar fengfeng 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
ukui-sni/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication.index0000664000175000017500000003171415153755017026306 0ustar fengfeng ukui-sni/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication-obsolete.html0000664000175000017500000000372115153755017027752 0ustar fengfeng 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
ukui-sni/3rd-parties/qtsingleapplication/doc/html/qtsingleapplication.qhp0000664000175000017500000000741115153755017025764 0ustar fengfeng 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 ukui-sni/3rd-parties/qtsingleapplication/doc/html/index.html0000664000175000017500000000527515153755017023203 0ustar fengfeng 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
ukui-sni/3rd-parties/qtsingleapplication/configure.bat0000664000175000017500000000176215153755017022143 0ustar fengfeng:: 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-sni/3rd-parties/qtsingleapplication/common.pri0000664000175000017500000000124715153755017021474 0ustar fengfengexists(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-sni/3rd-parties/qtsingleapplication/qtsingleapplication.pro0000664000175000017500000000016515153755017024262 0ustar fengfengTEMPLATE=subdirs CONFIG += ordered include(common.pri) qtsingleapplication-uselib:SUBDIRS=buildlib SUBDIRS+=examples ukui-sni/3rd-parties/qtsingleapplication/README.TXT0000664000175000017500000000164115153755017021024 0ustar fengfengQt 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-sni/3rd-parties/qtsingleapplication/INSTALL.TXT0000664000175000017500000002237415153755017021203 0ustar fengfengINSTALLATION 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-sni/3rd-parties/qtsingleapplication/examples/0000775000175000017500000000000015153755017021302 5ustar fengfengukui-sni/3rd-parties/qtsingleapplication/examples/examples.pro0000664000175000017500000000011115153755017023633 0ustar fengfengTEMPLATE = subdirs SUBDIRS = trivial \ loader \ console ukui-sni/3rd-parties/qtsingleapplication/examples/trivial/0000775000175000017500000000000015153755017022754 5ustar fengfengukui-sni/3rd-parties/qtsingleapplication/examples/trivial/trivial.qdoc0000664000175000017500000000271115153755017025277 0ustar fengfeng// 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. */ ukui-sni/3rd-parties/qtsingleapplication/examples/trivial/trivial.pro0000664000175000017500000000012115153755017025142 0ustar fengfengTEMPLATE = app include(../../src/qtsingleapplication.pri) SOURCES += main.cpp ukui-sni/3rd-parties/qtsingleapplication/examples/trivial/main.cpp0000664000175000017500000000145215153755017024406 0ustar fengfeng// 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(); } ukui-sni/3rd-parties/qtsingleapplication/examples/loader/0000775000175000017500000000000015153755017022550 5ustar fengfengukui-sni/3rd-parties/qtsingleapplication/examples/loader/loader.pro0000664000175000017500000000020615153755017024536 0ustar fengfenggreaterThan(QT_MAJOR_VERSION, 4): QT += printsupport TEMPLATE = app include(../../src/qtsingleapplication.pri) SOURCES += main.cpp ukui-sni/3rd-parties/qtsingleapplication/examples/loader/file1.qsl0000664000175000017500000000000715153755017024266 0ustar fengfengFile 1 ukui-sni/3rd-parties/qtsingleapplication/examples/loader/main.cpp0000664000175000017500000000432415153755017024203 0ustar fengfeng// 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(); } ukui-sni/3rd-parties/qtsingleapplication/examples/loader/file2.qsl0000664000175000017500000000000715153755017024267 0ustar fengfengFile 2 ukui-sni/3rd-parties/qtsingleapplication/examples/loader/loader.qdoc0000664000175000017500000000335515153755017024674 0ustar fengfeng// 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. */ ukui-sni/3rd-parties/qtsingleapplication/examples/console/0000775000175000017500000000000015153755017022744 5ustar fengfengukui-sni/3rd-parties/qtsingleapplication/examples/console/console.pro0000664000175000017500000000016515153755017025132 0ustar fengfengTEMPLATE = app CONFIG += console SOURCES += main.cpp include(../../src/qtsinglecoreapplication.pri) QT -= gui ukui-sni/3rd-parties/qtsingleapplication/examples/console/console.qdoc0000664000175000017500000000150115153755017025253 0ustar fengfeng// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). // SPDX-License-Identifier: BSD-3-Clause /*! \page qtsinglecoreapplication-example-console.html \title A non-GUI example This example shows how to use the single-application functionality in a console application. It does not require the \c QtGui library at all. The only differences from the GUI application usage demonstrated in the other examples are: 1) The \c.pro file should include \c qtsinglecoreapplication.pri instead of \c qtsingleapplication.pri 2) The class name is \c QtSingleCoreApplication instead of \c QtSingleApplication. 3) No calls are made regarding window activation, for obvious reasons. console.pro: \quotefile console/console.pro main.cpp: \quotefile console/main.cpp */ ukui-sni/3rd-parties/qtsingleapplication/examples/console/main.cpp0000664000175000017500000000245615153755017024403 0ustar fengfeng// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). // SPDX-License-Identifier: BSD-3-Clause #include "qtsinglecoreapplication.h" #include void report(const QString& msg) { qDebug("[%i] %s", (int)QCoreApplication::applicationPid(), qPrintable(msg)); } class MainClass : public QObject { Q_OBJECT public: MainClass() : QObject() {} public slots: void handleMessage(const QString& message) { report( "Message received: \"" + message + "\""); } }; int main(int argc, char **argv) { report("Starting up"); QtSingleCoreApplication app(argc, argv); if (app.isRunning()) { QString msg(QString("Hi master, I am %1.").arg(QCoreApplication::applicationPid())); bool sentok = app.sendMessage(msg, 2000); QString rep("Another instance is running, so I will exit."); rep += sentok ? " Message sent ok." : " Message sending failed; the other instance may be frozen."; report(rep); return 0; } else { report("No other instance is running; so I will."); MainClass mainObj; QObject::connect(&app, SIGNAL(messageReceived(const QString&)), &mainObj, SLOT(handleMessage(const QString&))); return app.exec(); } } #include "main.moc" ukui-sni/3rd-parties/qtsingleapplication/buildlib/0000775000175000017500000000000015153755017021252 5ustar fengfengukui-sni/3rd-parties/qtsingleapplication/buildlib/buildlib.pro0000664000175000017500000000072115153755017023562 0ustar fengfengTEMPLATE=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-sni/3rd-parties/qtsingleapplication/configure0000775000175000017500000000126115153755017021373 0ustar fengfeng#!/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-sni/log-utils.cpp0000664000175000017500000001056515153755611013707 0ustar fengfeng/* * 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-sni/"; 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(); }

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