pax_global_header00006660000000000000000000000064145016012420014505gustar00rootroot0000000000000052 comment=1907f8681d6d421517c63d94f425f9cdd74d0034 pystray-0.19.5/000077500000000000000000000000001450160124200133145ustar00rootroot00000000000000pystray-0.19.5/.gitignore000066400000000000000000000000671450160124200153070ustar00rootroot00000000000000*.egg-info/ *.eggs/ *.pyc *.sublime-* build/* dist/* pystray-0.19.5/CHANGES.rst000066400000000000000000000203121450160124200151140ustar00rootroot00000000000000Release Notes ============= v0.19.5 (2023-09-17) - Various fixes ------------------------------------ * Change image flags to *Pillow* to those actually supported by newer versions of that library. * Correct visibility for *appindicator* backend. Thanks to *Stephan Helma*! * Do not stop the icon unless it is running. * Correct issue where the icon would become blurry on screen resolution changes on *Windows*. v0.19.4 (2022-06-20) - Notifications for macOS ---------------------------------------------- * Enable notifications for *macOS*. Thanks to *danrossi*! * Added FAQ. * Correctly set title for *appindicator* when icon is created. Thanks to *SpookedByRoaches*! * Verify that *Gtk* actually works before trying to use it. Thanks to *Peter Hjalmarsson*! * Corrected regression for the *dummy* backend. Thanks to *Simon Robinson*! * Corrected regression with ``run_detached`` for *Xorg*. v0.19.3 (2022-03-18) - Various fixes ------------------------------------ * Do not crash when passed a ``None`` menu. * Only let ``pystray.Icon.stop`` block for 5 seconds when waiting for the ``setup`` function to complete. * Made usage example single, runnable script. v0.19.2 (2022-01-01) - Allow tuple as menu argument --------------------------------------------------- * Corrected menu implementation to allow tuples as arguments as indicated by the documentation. v0.19.1 (2021-12-06) - Simplify packaging ----------------------------------------- * Simplify loading of backends to make packaging into a standalone package easier. * Added release dates to release notes. v0.19.0 (2021-12-05) - Ayatana AppIndicator support --------------------------------------------------- * Added support for *Ayatana AppIndicator* under *Linux*. Thanks to *Paulo Martinez*! * Corrected support for ``run_detached`` under *Linux* and *Windows*. v0.18.0 (2021-10-20) - Easier integration with other libraries -------------------------------------------------------------- * Added a detached run mode to enable integration with libraries with a run loop. Thanks to *PySimpleGUI* and *glight2000* for their testing efforts! * Do not crash when running the icon in a non-main thread when using a *GTK+* backend. * Updated documentation. v0.17.4 (2021-06-26) - Corrected import on Windows -------------------------------------------------- * Corrected imports from _WinDLL_ to ensure argument definitions are private to this library. Thanks to *TomsonBoylett*! v0.17.3 (2021-04-02) - macOS and AppIndicator bug fixes ------------------------------------------------------- * Let the default timeout for notifications when using the *AppIndicator* backend be decided by the desktop environment, not infinity. Thanks to *Angelo Naselli*! * Do not attempt to create a menu before the icon has started on *macOS*. v0.17.2 (2020-12-02) - Windows bug fixes ---------------------------------------- * Actually release loaded icons on *Windows*. Thanks to *Bob1011941*! * Let mouse button release trigger menu and action on *Windows* as expected. Thanks to *Ennea*! v0.17.1 (2020-08-30) - Corrected release notes ---------------------------------------------- * Corrected attribution of *Windows* notification fix. v0.17.0 (2020-08-30) - Various bug fixes ---------------------------------------- * Corrected signalling in *GTK* backend. Thanks to *Simon Lindholm*! * Corrected hinding of notification message in *GTK backend*. Thanks to *Simon Lindholm*! * Corrected notification structure on *Windows*. Thanks to *flameiguana*! v0.16.0 (2020-06-09) - Enable notifications ------------------------------------------- * Added support for notifications. Thanks to *ralphwetzel* and *Chr0nicT*! * Added support for forcing the backend to use. v0.15.0 (2019-12-04) - Allow methods as menu callbacks ------------------------------------------------------ * Allow passing a method as menu callback. * Ensure that the temporary file is removed when running under *AppIndicator*. Thanks to *superjamie*! v0.14.4 (2018-09-18) - Allow setting icon after construction ------------------------------------------------------------ * Do not require setting ``icon`` twice when not passing the icon to the constructor. * Clarified documentation regarding name of menu argument. v0.14.3 (2017-03-29) - Full license coverage -------------------------------------------- * Added license preamble to all source files. Thanks to *Björn Esser*! v0.14.2 (2017-03-27) - Proper license files ------------------------------------------- * Added proper license files. Thanks to *Björn Esser*! v0.14.1 (2017-03-05) - Restore icon after *explorer.exe* crash -------------------------------------------------------------- * Restore the icon when *explorer exe* restarts after a crash. Thanks to *Michael Dubner*! v0.14 (2017-02-23) - Disabled menu items ---------------------------------------- * Added support for disabling menu items. v0.13 (2017-02-18) - Corrections for X -------------------------------------- * Make sure to set window size hints on *X*. Thanks to *filonenko-mikhail*! v0.12 (2017-01-21) - Simplified API ----------------------------------- * Do not require use of ``setup`` to show icon. * Pass reference to menu item to action handler. If action handlers do not support this argument, they will be wrapped. * Updated documentation. v0.11 (2016-12-05) - Radio buttons ---------------------------------- * Added support for radio buttons. * Corrected transparent icons for *OSX*. v0.10 (2016-09-27) - Changed Xlib backend library ------------------------------------------------- * Changed *Xlib* library. * Corrected test with incorrect parameter. v0.9 (2016-09-26) - Submenus ---------------------------- * Added support for nested menus. v0.8 (2016-09-21) - Platform independent API and checkable ---------------------------------------------------------- * Added method to explicitly update menu to enable support for other platforms. * Added support for *AppIndicator* backend. * Re-added native clickability for *OSX*. * Added support for check boxes. v0.7 (2016-08-24) - Dynamic menus --------------------------------- * Added support for dynamically generating menu item properties when a popup menu is displayed. * Display the default menu item distinctly. * Changed the menu item API slightly. * Corrected logging on Windows. v0.6 (2016-08-21) - Simplified API ---------------------------------- * Removed explicit default action parameter ``on_activate``. * Allow terminating the application with *ctrl+c* on *OSX*. * Added basic logging. v0.5 (2016-08-16) - Menu support -------------------------------- * Added support for popup menus. * Corrected bug which prevented stopping the icon on *Windows*. * Corrected documentation. v0.4 (2016-08-05) - GTK+ 3 support ---------------------------------- * Added support for *GTK+* on *Linux*. v0.3.5 (2016-06-21) - Corrected import errors --------------------------------------------- * Propagate import errors raised on Linux to help troubleshoot missing ``Xlib`` module. Thanks to Lance Kindle! * Properly declare ``six`` as a dependency. * Declare ``python3-xlib`` as dependency on *Linux* for *Python 3*. v0.3.4 (2016-05-24) - Corrected Python 3 issues on Xorg ------------------------------------------------------- * Make sure that ``pystray`` can be used on *Python 3* on *Xorg*. * Make sure the release making script runs on *Python 3*. v0.3.3 (2016-04-21) - Corrected encoding issues ----------------------------------------------- * Make sure building works even when default encoding is not *utf-8*. * Corrected issue with click selector on *OSX*. v0.3.2 (2016-04-19) - Universal wheel ------------------------------------- * Make sure to build a universal wheel for all python versions. v0.3.1 (2016-04-10) - No-change packaging update ------------------------------------------------ * Do not package an old version of ``pynput``. v0.3 (2016-04-05) - Proper Python 3 Support ------------------------------------------- * Corrected Python 3 bugs. * Made ``Icon.run()`` mandatory on all platforms. v0.2 (2016-03-27) - Initial Release ----------------------------------- * Support for adding a system tray icon on *Linux*, *Mac OSX* and *Windows*. pystray-0.19.5/COPYING000066400000000000000000001045201450160124200143510ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007-2022 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 . pystray-0.19.5/COPYING.LGPL000066400000000000000000000167501450160124200151150ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007-2022 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. pystray-0.19.5/README.rst000066400000000000000000000004461450160124200150070ustar00rootroot00000000000000pystray Package Documentation ============================= This library allows you to create a *system tray icon*. Supported platforms are *Linux* under *Xorg*, *GNOME* and *Ubuntu*, *macOS* and *Windows*. See `here `_ for the full documentation. pystray-0.19.5/docs/000077500000000000000000000000001450160124200142445ustar00rootroot00000000000000pystray-0.19.5/docs/conf.py000066400000000000000000000037501450160124200155500ustar00rootroot00000000000000# -*- coding: utf-8 -*- import datetime import sys import os # Make sure we can import the package sys.path.insert( 0, os.path.join( os.path.dirname(__file__), os.path.pardir, 'lib')) os.environ['PYSTRAY_BACKEND'] = 'dummy' import pystray as package import pystray._info as INFO # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = package.__package__ original_year = 2016 current_year = datetime.date.today().year if original_year == current_year: copyright = u'%d, %s' % ( current_year, INFO.__author__) else: copyright = u'%d-%d, %s' % ( original_year, current_year, INFO.__author__) # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # The short X.Y version. version = '.'.join(str(v) for v in INFO.__version__) # The full version, including alpha/beta/rc tags. release = version # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'alabaster' # Output file base name for HTML help builder. htmlhelp_basename = '%sdoc' % package.__package__ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ( 'index', package.__package__, u'%s Documentation' % package.__package__, [package._info.__author__], 1)] pystray-0.19.5/docs/faq.rst000066400000000000000000000035441450160124200155530ustar00rootroot00000000000000Frequently asked question ------------------------- How do I use *pystray* in a *virtualenv* on *Linux*? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ On *Linux*, runtime introspection data is required to use the *AppIndicator* backend, and the *GTK* backend may not be fully functional without installing desktop environment extensions. The *XOrg* backend will work, but it provides limited functionality. In order to use the *AppIndicator* backend, you may install the package ``PyGObject``. No wheel is provided, so the package must be built locally. On *Debian* derivatives, such as *Ubuntu*, the following packages, in addition to compilers and *pkg-config*, must be installed: - ``libcairo-dev`` - ``libgirepository1.0-dev`` I am trying to integrate with a framework, but ``run_detached`` does not work ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``run_detached`` method is used to allow a different framework to drive the main loop. This requires that the framework uses the same kind of mainloop. On *Windows* and *macOS*, this will be the case if you use the platform GUI toolkits. On *Linux*, the situation is a bit more complicated. Generally, the *xorg* backend will work with any toolkit, as long as you run it in an *X* session and not under *Wayland*. The *GTK* and *AppIndicator* backends will work if your toolkit is based on *GObject*. However, ``run_detached`` is strictly necessary only on *macOS*. For other platforms, it is possible to just launch the icon mainloop in a thread:: import pystray import threading import some_toolkit # Create the icon icon = pystray.Icon( 'test name', icon=create_icon()) # Run the icon mainloop in a separate thread threading.Thread(target=icon.run).start() # Run the toolkit mainlon in the main thread some_toolkit.mainloop() pystray-0.19.5/docs/index.rst000066400000000000000000000006651450160124200161140ustar00rootroot00000000000000pystray Package Documentation ============================= This library allows you to create a *system tray icon*. It allows specifying an icon, a title and a callback for when the icon is activated. The icon and title can be changed after the icon has been created, and the visibility of the icon can be toggled. Table of contents ----------------- .. toctree:: :maxdepth: 2 usage faq reference * :ref:`genindex` pystray-0.19.5/docs/reference.rst000066400000000000000000000002331450160124200167320ustar00rootroot00000000000000Reference ========= .. autoclass:: pystray.Icon :members: .. autoclass:: pystray.Menu :members: .. autoclass:: pystray.MenuItem :members: pystray-0.19.5/docs/usage.rst000066400000000000000000000235111450160124200161040ustar00rootroot00000000000000Creating a *system tray icon* ----------------------------- In order to create a *system tray icon*, the class ``pystray.Icon`` is used:: import pystray from PIL import Image, ImageDraw def create_image(width, height, color1, color2): # Generate an image and draw a pattern image = Image.new('RGB', (width, height), color1) dc = ImageDraw.Draw(image) dc.rectangle( (width // 2, 0, width, height // 2), fill=color2) dc.rectangle( (0, height // 2, width // 2, height), fill=color2) return image # In order for the icon to be displayed, you must provide an icon icon = pystray.Icon( 'test name', icon=create_image(64, 64, 'black', 'white')) # To finally show you icon, call run icon.run() The call to ``pystray.Icon.run()`` is blocking, and it must be performed from the main thread of the application. The reason for this is that the *system tray icon* implementation for *OSX* will fail unless called from the main thread, and it also requires the application runloop to be running. ``pystray.Icon.run()`` will start the runloop. If you only target *Windows*, calling ``run()`` from a thread other than the main thread is safe. The ``run()`` method accepts an optional argument: ``setup``, a callable. The ``setup`` function will be run in a separate thread once the *system tray icon* is ready. The icon does not wait for it to complete, so you may put any code that would follow the call to ``pystray.Icon.run()`` in it. The call to ``pystray.Icon.run()`` will not complete until ``stop()`` is called. Getting input from the *system tray icon* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In order to receive notifications about user interaction with the icon, a popup menu can be added with the ``menu`` constructor argument. This must be an instance of ``pystray.Menu``. Please see the reference for more information about the format. It will be displayed when the right-hand button has been pressed on the icon on *Windows*, and when the icon has been clicked on other platforms. Menus are not supported on *X*. Menus also support a default item. On *Windows*, and *X*, this item will be activated when the user clicks on the icon using the primary button. On other platforms it will be activated if the menu contains no visible entries; it does not have to be visible. All properties of menu items, except for the callback, can be dynamically calculated by supplying callables instead of values to the menu item constructor. The properties are recalculated every time the icon is clicked or any menu item is activated. If the dynamic properties change because of an external event, you must ensure that ``Icon.update_menu`` is called. This is required since not all supported platforms allow for the menu to be generated when displayed. Creating the menu ~~~~~~~~~~~~~~~~~ *This is not supported on Xorg; please check Icon.HAS_MENU at runtime for support on the current platform.* A menu can be attached to a system tray icon by passing an instance of :class:`pystray.Menu` as the ``menu`` keyword argument. A menu consists of a list of menu items, optionally separated by menu separators. Separators are intended to group menu items into logical groups. They will not be displayed as the first and last visible item, and adjacent separators will be hidden. A menu item has several attributes: *text* and *action* The menu item text and its associated action. These are the only required attributes. Please see *submenu* below for alternate interpretations of *action*. *checked* Whether the menu item is checked. This can be one of three values: ``False`` The item is decorated with an unchecked check box. ``True`` The item is decorated with a checked check box. ``None`` There is no hint that the item is checkable. If you want this to actually be togglable, you must pass a callable that returns the current state:: from pystray import Icon as icon, Menu as menu, MenuItem as item state = False def on_clicked(icon, item): global state state = not item.checked # Update the state in `on_clicked` and return the new state in # a `checked` callable icon('test', create_image(), menu=menu( item( 'Checkable', on_clicked, checked=lambda item: state))).run() *radio* *This is not supported on macOS; please check Icon.HAS_MENU_RADIO at runtime for support on the current platform.* Whether this is a radio button. This is used only if ``checked`` is ``True`` or ``False``, and only has a visual meaning. The menu has no concept of radio button groups:: from pystray import Icon as icon, Menu as menu, MenuItem as item state = 0 def set_state(v): def inner(icon, item): global state state = v return inner def get_state(v): def inner(item): return state == v return inner # Let the menu items be a callable returning a sequence of menu # items to allow the menu to grow icon('test', create_image(), menu=menu(lambda: ( item( 'State %d' % i, set_state(i), checked=get_state(i), radio=True) for i in range(max(5, state + 2))))).run() *default* *This is not supported on Darwin and using AppIndicator; please check Icon.HAS_DEFAULT at runtime for support on the current platform.* Whether this is the default item. It is drawn in a distinguished style and will be activated as the default item on platforms that support default actions. On *X*, this is the only action available. *visible* Whether the menu item is visible. *enabled* Whether the menu item is enabled. Disabled menu items are displayed, but are greyed out and cannot be activated. *submenu* The submenu, if any, that is attached to this menu item. Either a submenu or an action can be passed as the second argument to the constructor. The submenu must be an instance of :class:`Menu`:: from pystray import Icon as icon, Menu as menu, MenuItem as item icon('test', create_image(), menu=menu( item( 'With submenu', menu( item( 'Submenu item 1', lambda icon, item: 1), item( 'Submenu item 2', lambda icon, item: 2))))).run() Once created, menus and menu items cannot be modified. All attributes except for the menu item callbacks can however be set to callables returning the current value. This also applies to the sequence of menu items belonging to a menu: this can be a callable returning the current sequence. Displaying notifications ~~~~~~~~~~~~~~~~~~~~~~~~ *This is not supported on macOS and Xorg; please check Icon.HAS_NOTIFICATION at runtime for support on the current platform.* To display a system notification, use :meth:`pystray.Icon.notify`:: from pystray import Icon as icon, Menu as menu, MenuItem as item icon('test', create_image(), menu=menu( item( 'With submenu', menu( item( 'Show message', lambda icon, item: icon.notify('Hello World!')), item( 'Submenu item 2', lambda icon, item: icon.remove_notification()))))).run() Integrating with other frameworks --------------------------------- The *pystray* ``run`` method is blocking, and must be called from the main thread to maintain platform independence. This is troublesome when attempting to use frameworks with an event loop, since they may also require running in the main thread. For this case you can use ``run_detached``. This allows you to setup the icon and then pass control to the framework. Please see the documentation for more information. Selecting a backend ------------------- *pystray* aims to provide a unified *API* for all supported platforms. In some cases, however, that is not entirely possible. This library supports a number of backends. On *macOS* and *Windows*, the operating system has system tray icons built-in, so the default backends should be used, but on *Linux* you may have to make a decision depending on your needs. By setting the environment variable ``PYSTRAY_BACKEND`` to one of the strings in the next section, the automatic selection is turned off. Supported backends ~~~~~~~~~~~~~~~~~~ *appindicator* This is one of the backends available on *Linux*, and is the preferred choice. All *pystray* features except for a menu default action are supported, and if the *appindicator* library is installed on the system and the desktop environment supports it, the icon is guaranteed to be displayed. If the *appindicator* library is not available on the system, a fallback on *ayatana-appindicator* is attempted. *darwin* This is the default backend when running on *macOS*. All *pystray* features are available. *gtk* This is one of the backends available on *Linux*, and is prioritised above the *XOrg* backend. It uses *GTK* as underlying library. All *pystray* features are available, but it may not actually result in a visible icon: when running a *gnome-shell* session, an third party plugin is required to display legacy tray icons. *win32* This is the default backend when running on *Windows*. All *pystray* features are available. *xorg* This is one of the backends available on *Linux*. It is used as a fallback when no other backend can be loaded. It does not support any menu functionality except for a default action. pystray-0.19.5/lib/000077500000000000000000000000001450160124200140625ustar00rootroot00000000000000pystray-0.19.5/lib/pystray/000077500000000000000000000000001450160124200155755ustar00rootroot00000000000000pystray-0.19.5/lib/pystray/__init__.py000066400000000000000000000040741450160124200177130ustar00rootroot00000000000000# coding=utf-8 # pystray # Copyright (C) 2016-2022 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . import os import sys def backend(): """Returns the backend module. """ def dummy(): from . import _dummy as backend; return backend def appindicator(): from . import _appindicator as backend; return backend def darwin(): from . import _darwin as backend; return backend def gtk(): from . import _gtk as backend; return backend def win32(): from . import _win32 as backend; return backend def xorg(): from . import _xorg as backend; return backend backends = {b.__name__: b for b in ( dummy, appindicator, darwin, gtk, win32, xorg)} backend_name = os.environ.get('PYSTRAY_BACKEND', None) if backend_name: try: candidates = [backends[backend_name]] except KeyError as e: raise ImportError('unknown backend: {}'.format(e)) elif sys.platform == 'darwin': candidates = [darwin] elif sys.platform == 'win32': candidates = [win32] else: candidates = [appindicator, gtk, xorg] errors = [] for candidate in candidates: try: return candidate() except ImportError as e: errors.append(e) raise ImportError('this platform is not supported: {}'.format( '; '.join(str(e) for e in errors))) Icon = backend().Icon del backend from ._base import Menu, MenuItem pystray-0.19.5/lib/pystray/_appindicator.py000066400000000000000000000062211450160124200207640ustar00rootroot00000000000000# coding=utf-8 # pystray # Copyright (C) 2016-2022 Moses Palmér # Copyright (C) 2022 Stephan Helma # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk try: gi.require_version('AppIndicator3', '0.1') from gi.repository import AppIndicator3 as AppIndicator except ValueError: gi.require_version('AyatanaAppIndicator3', '0.1') from gi.repository import AyatanaAppIndicator3 as AppIndicator from ._util.gtk import GtkIcon, mainloop from . import _base class Icon(GtkIcon): # We expand the menu on primary button click, and we do not even support # empty menus HAS_DEFAULT_ACTION = False def __init__(self, *args, **kwargs): super(Icon, self).__init__(*args, **kwargs) self._appindicator = AppIndicator.Indicator.new( self.name, '', AppIndicator.IndicatorCategory.APPLICATION_STATUS) if self.icon: self._update_icon() if self.visible: self._show() else: self._hide() @mainloop def _show(self): self._appindicator.set_icon(self._icon_path) self._appindicator.set_menu( self._menu_handle or self._create_default_menu()) self._appindicator.set_title(self.title) self._appindicator.set_status(AppIndicator.IndicatorStatus.ACTIVE) @mainloop def _hide(self): self._appindicator.set_status(AppIndicator.IndicatorStatus.PASSIVE) @mainloop def _update_icon(self): self._remove_fs_icon() self._update_fs_icon() self._appindicator.set_icon(self._icon_path) @mainloop def _update_title(self): self._appindicator.set_title(self.title) @mainloop def _update_menu(self): self._menu_handle = self._create_menu(self.menu) or \ self._create_default_menu() self._appindicator.set_menu(self._menu_handle) def _finalize(self): super(Icon, self)._finalize() del self._appindicator def _create_default_menu(self): """Creates a :class:`Gtk.Menu` from the default menu entry. :return: a :class:`Gtk.Menu` """ menu = Gtk.Menu.new() if self.menu is not None: menu.append(self._create_menu_item(next( menu_item for menu_item in self.menu.items if menu_item.default))) else: menu.append(self._create_menu_item( _base.MenuItem(self.name, lambda _: None))) menu.show_all() return menu pystray-0.19.5/lib/pystray/_base.py000066400000000000000000000511141450160124200172220ustar00rootroot00000000000000# coding=utf-8 # pystray # Copyright (C) 2016-2022 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . import functools import inspect import itertools import logging import threading from six.moves import queue class Icon(object): """A representation of a system tray icon. The icon is initially hidden. Set :attr:`visible` to ``True`` to show it. :param str name: The name of the icon. This is used by the system to identify the icon. :param icon: The icon to use. If this is specified, it must be a :class:`PIL.Image.Image` instance. :param str title: A short title for the icon. :param menu: A menu to use as popup menu. This can be either an instance of :class:`Menu` or an iterable, which will be interpreted as arguments to the :class:`Menu` constructor, or ``None``, which disables the menu. The behaviour of the menu depends on the platform. Only one action is guaranteed to be invokable: the first menu item whose :attr:`~pystray.MenuItem.default` attribute is set. Some platforms allow both menu interaction and a special way of activating the default action, some platform allow only either an invisible menu with a default entry as special action or a full menu with no special way to activate the default item, and some platforms do not support a menu at all. :param kwargs: Any non-standard platform dependent options. These should be prefixed with the platform name thus: ``appindicator_``, ``darwin_``, ``gtk_``, ``win32_`` or ``xorg_``. Supported values are: ``darwin_nsapplication`` An ``NSApplication`` instance used to run the event loop. If this is not specified, the shared application will be used. """ #: Whether this particular implementation has a default action that can be #: invoked in a special way, such as clicking on the icon. HAS_DEFAULT_ACTION = True #: Whether this particular implementation supports menus. HAS_MENU = True #: Whether this particular implementation supports displaying mutually #: exclusive menu items using the :attr:`MenuItem.radio` attribute. HAS_MENU_RADIO = True #: Whether this particular implementation supports displaying a #: notification. HAS_NOTIFICATION = True #: The timeout, in secods, before giving up on waiting for the setup thread #: when stopping the icon. SETUP_THREAD_TIMEOUT = 5.0 def __init__( self, name, icon=None, title=None, menu=None, **kwargs): self._name = name self._icon = icon or None self._title = title or '' self._menu = menu if isinstance(menu, Menu) \ else Menu(*menu) if menu is not None \ else None self._visible = False self._icon_valid = False self._log = logging.getLogger(__name__) self._running = False self.__queue = queue.Queue() prefix = self.__class__.__module__.rsplit('.', 1)[-1][1:] + '_' self._options = { key[len(prefix):]: value for key, value in kwargs.items() if key.startswith(prefix)} def __del__(self): if self.visible: self._hide() def __call__(self): if self._menu is not None: self._menu(self) self.update_menu() @property def name(self): """The name passed to the constructor. """ return self._name @property def icon(self): """The current icon. Setting this to a falsy value will hide the icon. Setting this to an image while the icon is hidden has no effect until the icon is shown. """ return self._icon @icon.setter def icon(self, value): self._icon = value self._icon_valid = False if value: if self.visible: self._update_icon() else: if self.visible: self.visible = False @property def title(self): """The current icon title. """ return self._title @title.setter def title(self, value): if value != self._title: self._title = value if self.visible: self._update_title() @property def menu(self): """The menu. Setting this to a falsy value will disable the menu. """ return self._menu @menu.setter def menu(self, value): self._menu = value self.update_menu() @property def visible(self): """Whether the icon is currently visible. :raises ValueError: if set to ``True`` and no icon image has been set """ return self._visible @visible.setter def visible(self, value): if self._visible == value: return if value: if not self._icon: raise ValueError('cannot show icon without icon data') if not self._icon_valid: self._update_icon() self._show() self._visible = True else: self._hide() self._visible = False def run(self, setup=None): """Enters the loop handling events for the icon. This method is blocking until :meth:`stop` is called. It *must* be called from the main thread. :param callable setup: An optional callback to execute in a separate thread once the loop has started. It is passed the icon as its sole argument. Please note that this function is started in a thread, and when the icon is stopped, an attempt to join this thread is made, so stopping the icon may be blocking for up to ``SETUP_THREAD_TIMEOUT`` seconds if the function is not well-behaved. If not specified, a simple setup function setting :attr:`visible` to ``True`` is used. If you specify a custom setup function, you must explicitly set this attribute. """ self._start_setup(setup) self._run() def run_detached(self, setup=None): """Prepares for running the loop handling events detached. This allows integrating *pystray* with other libraries requiring a mainloop. Call this method before entering the mainloop of the other library. Depending on the backend used, calling this method may require special preparations: macOS Pass an instance of ``NSApplication`` retrieved from the library with which you are integrating as the argument ``darwin_nsapplication``. This will allow this library to integrate with the main loop. :param callable setup: An optional callback to execute in a separate thread once the loop has started. It is passed the icon as its sole argument. If not specified, a simple setup function setting :attr:`visible` to ``True`` is used. If you specify a custom setup function, you must explicitly set this attribute. :raises NotImplementedError: if this is not implemented for the preparations taken """ self._start_setup(setup) self._run_detached() def stop(self): """Stops the loop handling events for the icon. If the icon is not running, calling this method has no effect. """ if self._running: self._stop() if self._setup_thread.ident != threading.current_thread().ident: self._setup_thread.join(timeout=self.SETUP_THREAD_TIMEOUT) if self._setup_thread.is_alive(): self._log.warning( 'The function passed as setup to the icon did not ' 'finish within {} seconds after icon was ' 'stopped'.format( self.SETUP_THREAD_TIMEOUT)) self._running = False def update_menu(self): """Updates the menu. If the properties of the menu descriptor are dynamic, that is, any are defined by callables and not constants, and the return values of these callables change by actions other than the menu item activation callbacks, calling this function is required to keep the menu in sync. This is required since not all supported platforms allow the menu to be generated when shown. For simple use cases where menu changes are triggered by interaction with the menu, this method is not necessary. """ self._update_menu() def notify(self, message, title=None): """Displays a notification. The notification will generally be visible until :meth:`remove_notification` is called. The class field :attr:`HAS_NOTIFICATION` indicates whether this feature is supported on the current platform. :param str message: The message of the notification. :param str title: The title of the notification. This will be replaced with :attr:`title` if ``None``. """ self._notify(message, title) def remove_notification(self): """Remove a notification. """ self._remove_notification() def _mark_ready(self): """Marks the icon as ready. The setup callback passed to :meth:`run` will not be called until this method has been invoked. Before the setup method is scheduled to be called, :meth:`update_menu` is called. """ self._running = True try: self.update_menu() finally: self.__queue.put(True) def _handler(self, callback): """Generates a callback handler. This method is used in platform implementations to create callback handlers. It will return a function taking any parameters, which will call ``callback`` with ``self`` and then call :meth:`update_menu`. :param callable callback: The callback to wrap. :return: a wrapped callback """ @functools.wraps(callback) def inner(*args, **kwargs): try: callback(self) finally: self.update_menu() return inner def _show(self): """The implementation of the :meth:`show` method. This is a platform dependent implementation. """ raise NotImplementedError() def _hide(self): """The implementation of the :meth:`hide` method. This is a platform dependent implementation. """ raise NotImplementedError() def _update_icon(self): """Updates the image for an already shown icon. This method should self :attr:`_icon_valid` to ``True`` if the icon is successfully updated. This is a platform dependent implementation. """ raise NotImplementedError() def _update_title(self): """Updates the title for an already shown icon. This is a platform dependent implementation. """ raise NotImplementedError() def _update_menu(self): """Updates the native menu state to mimic :attr:`menu`. This is a platform dependent implementation. """ raise NotImplementedError() def _run(self): """Runs the event loop. This method must call :meth:`_mark_ready` once the loop is ready. This is a platform dependent implementation. """ raise NotImplementedError() def _run_detached(self): """Runs detached. This method must call :meth:`_mark_ready` once ready. This is a platform dependent implementation. """ raise NotImplementedError() def _start_setup(self, setup): """Starts the setup thread. :param callable setup: The thread handler. """ def setup_handler(): self.__queue.get() if setup: setup(self) else: self.visible = True self._setup_thread = threading.Thread(target=setup_handler) self._setup_thread.start() def _stop(self): """Stops the event loop. This is a platform dependent implementation. """ raise NotImplementedError() def _notify(self, message, title=None): """Show a notification. This is a platform dependent implementation. """ raise NotImplementedError() def _remove_notification(self): """Remove a notification. This is a platform dependent implementation. """ raise NotImplementedError() class MenuItem(object): """A single menu item. A menu item is immutable. It has a text and an action. The action is either a callable of a menu. It is callable; when called, the activation callback is called. The :attr:`visible` attribute is provided to make menu creation easier; all menu items with this value set to ``False`` will be discarded when a :class:`Menu` is constructed. """ def __init__( self, text, action, checked=None, radio=False, default=False, visible=True, enabled=True): self.__name__ = str(text) self._text = self._wrap(text or '') self._action = self._assert_action(action) self._checked = self._assert_callable(checked, lambda _: None) self._radio = self._wrap(radio) self._default = self._wrap(default) self._visible = self._wrap(visible) self._enabled = self._wrap(enabled) def __call__(self, icon): if not isinstance(self._action, Menu): return self._action(icon, self) def __str__(self): if isinstance(self._action, Menu): return '%s =>\n%s' % (self.text, str(self._action)) else: return self.text @property def text(self): """The menu item text. """ return self._text(self) @property def checked(self): """Whether this item is checked. This can be either ``True``, which implies that the item is checkable and checked, ``False``, which implies that the item is checkable but not checked, and ``None`` for uncheckable items. Depending on platform, uncheckable items may be rendered differently from unchecked items. """ return self._checked(self) @property def radio(self): """Whether this item is a radio button. This is only used for checkable items. It is always set to ``False`` for uncheckable items. """ if self.checked is not None: return self._radio(self) else: return False @property def default(self): """Whether this is the default menu item. """ return self._default(self) @property def visible(self): """Whether this menu item is visible. If the action for this menu item is a menu, that also has to be visible for this property to be ``True``. """ if isinstance(self._action, Menu): return self._visible(self) and self._action.visible else: return self._visible(self) @property def enabled(self): """Whether this menu item is enabled. """ return self._enabled(self) @property def submenu(self): """The submenu used by this menu item, or ``None``. """ return self._action if isinstance(self._action, Menu) else None def _assert_action(self, action): """Ensures that a callable can be called with the expected number of arguments. :param callable action: The action to modify. If this callable takes less than the expected number of arguments, a wrapper will be returned. :raises ValueError: if ``action`` requires more than the expected number of arguments :return: a callable """ if action is None: return lambda *_: None elif not hasattr(action, '__code__'): return action else: argcount = action.__code__.co_argcount - ( 1 if inspect.ismethod(action) else 0) if argcount == 0: @functools.wraps(action) def wrapper0(*args): return action() return wrapper0 elif argcount == 1: @functools.wraps(action) def wrapper1(icon, *args): return action(icon) return wrapper1 elif argcount == 2: return action else: raise ValueError(action) def _assert_callable(self, value, default): """Asserts that a value is callable. If the value is a callable, it will be returned. If the value is ``None``, ``default`` will be returned, otherwise a :class:`ValueError` will be raised. :param value: The callable to check. :param callable default: The default value to return if ``value`` is ``None`` :return: a callable """ if value is None: return default elif callable(value): return value else: raise ValueError(value) def _wrap(self, value): """Wraps a value in a callable. If the value already is a callable, it is returned unmodified :param value: The value or callable to wrap. """ return value if callable(value) else lambda _: value class Menu(object): """A description of a menu. A menu description is immutable. It is created with a sequence of :class:`Menu.Item` instances, or a single callable which must return a generator for the menu items. First, non-visible menu items are removed from the list, then any instances of :attr:`SEPARATOR` occurring at the head or tail of the item list are removed, and any consecutive separators are reduced to one. """ #: A representation of a simple separator SEPARATOR = MenuItem('- - - -', None) def __init__(self, *items): self._items = tuple(items) @property def items(self): """All menu items. """ if (True and len(self._items) == 1 and not isinstance(self._items[0], MenuItem) and callable(self._items[0])): return self._items[0]() else: return self._items @property def visible(self): """Whether this menu is visible. """ return bool(self) def __call__(self, icon): try: return next( menuitem for menuitem in self.items if menuitem.default)(icon) except StopIteration: pass def __iter__(self): return iter(self._visible_items()) def __bool__(self): return len(self._visible_items()) > 0 __nonzero__ = __bool__ def __str__(self): return '\n'.join( '\n'.join( ' %s' % l for l in str(i).splitlines()) for i in self) def _visible_items(self): """Returns all visible menu items. This method also filters redundant separators as is described in the class documentation. :return: a tuple containing all currently visible items """ def cleaned(items): was_separator = False for i in items: if not i.visible: continue if i is self.SEPARATOR: if was_separator: continue was_separator = True else: was_separator = False yield i def strip_head(items): return itertools.dropwhile(lambda i: i is self.SEPARATOR, items) def strip_tail(items): return reversed(list(strip_head(reversed(list(items))))) return tuple(strip_tail(strip_head(cleaned(self.items)))) pystray-0.19.5/lib/pystray/_darwin.py000066400000000000000000000213031450160124200175710ustar00rootroot00000000000000# coding=utf-8 # pystray # Copyright (C) 2016-2022 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . import io import signal import subprocess import AppKit import Foundation import objc import PIL import PyObjCTools.MachSignals from . import _base class Icon(_base.Icon): #: The selector for the button action _ACTION_SELECTOR = b'activate:sender' #: The selector for the menu item actions _MENU_ITEM_SELECTOR = b'activateMenuItem:sender' # We support only a default action with an empty menu HAS_DEFAULT_ACTION = False # Mutually exclusive menu itema are not displayed distinctly HAS_MENU_RADIO = False def __init__(self, *args, **kwargs): super(Icon, self).__init__(*args, **kwargs) #: The NSImage version of the icon self._icon_image = None #: The NSApplication managing this icon self._app = self._options['nsapplication'] \ if 'nsapplication' in self._options \ else AppKit.NSApplication.sharedApplication() #: The icon delegate self._delegate = IconDelegate.alloc().init() self._delegate.icon = self self._status_bar = AppKit.NSStatusBar.systemStatusBar() self._status_item = self._status_bar.statusItemWithLength_( AppKit.NSVariableStatusItemLength) self._status_item.button().setTarget_(self._delegate) self._status_item.button().setAction_(self._ACTION_SELECTOR) def _show(self): self._assert_image() self._update_title() self._status_item.button().setHidden_(False) def _hide(self): self._status_item.button().setHidden_(True) def _update_icon(self): self._icon_image = None if self.visible: self._assert_image() self._icon_valid = True def _update_title(self): self._status_item.button().setToolTip_(self.title) def _update_menu(self): callbacks = [] nsmenu = self._create_menu(self.menu, callbacks) if nsmenu: self._status_item.setMenu_(nsmenu) self._menu_handle = (nsmenu, callbacks) else: self._status_item.setMenu_(None) self._menu_handle = None def _run(self): # Notify the setup callback self._mark_ready() def sigint(*args): self._app.terminate_(None) if previous_sigint: previous_sigint(*args) # Make sure that we do not inhibit ctrl+c previous_sigint = PyObjCTools.MachSignals.signal(signal.SIGINT, sigint) try: self._app.run() except: self._log.error( 'An error occurred in the main loop', exc_info=True) finally: if PyObjCTools.MachSignals.getsignal(signal.SIGINT) == sigint: PyObjCTools.MachSignals.signal(signal.SIGINT, previous_sigint) self._status_bar.removeStatusItem_(self._status_item) def _run_detached(self): self._mark_ready() def _notify(self, message, title=None): subprocess.check_call([ 'osascript', '-e', 'display notification "{}" with title "{}"'.format( message.replace('\\', '\\\\').replace('"', '\\"'), title.replace('\\', '\\\\').replace('"', '\\"'))]) def _remove_notification(self): pass def _stop(self): self._app.stop_(self._app) # Post a dummy event; stop_ will only set a flag in NSApp, so it will # not terminate until an event has been processed event = getattr( AppKit.NSEvent, 'otherEventWithType_' 'location_' 'modifierFlags_' 'timestamp_' 'windowNumber_' 'context_' 'subtype_' 'data1_' 'data2_')( AppKit.NSApplicationDefined, AppKit.NSPoint(0, 0), 0, 0.0, 0, None, 0, 0, 0) self._app.postEvent_atStart_(event, False) def _assert_image(self): """Asserts that the cached icon image exists. """ thickness = self._status_bar.thickness() size = (int(thickness), int(thickness)) if self._icon_image and self._icon_image.size() == size: return if self._icon.size == size: source = self._icon else: source = PIL.Image.new( 'RGBA', size) source.paste(self._icon.resize( size, PIL.Image.LANCZOS)) # Convert the PIL image to an NSImage b = io.BytesIO() source.save(b, 'png') data = Foundation.NSData(b.getvalue()) self._icon_image = AppKit.NSImage.alloc().initWithData_(data) self._status_item.button().setImage_(self._icon_image) def _create_menu(self, descriptors, callbacks): """Creates a :class:`AppKit.NSMenu` from a :class:`pystray.Menu` instance. If :meth:`_run` has not yet been called, ``None`` is returned. :param descriptors: The menu descriptors. If this is falsy, ``None`` is returned. :param callbacks: A list to which a callback is appended for every menu item created. The menu item tags correspond to the items in this list. :return: a menu """ if not descriptors: return None else: # Generate the menu nsmenu = AppKit.NSMenu.alloc().initWithTitle_(self.name) nsmenu.setAutoenablesItems_(False) for descriptor in descriptors: # Append the callback after creating the menu item to ensure # that the first item gets the tag 0 nsmenu.addItem_( self._create_menu_item(descriptor, callbacks)) callbacks.append(self._handler(descriptor)) return nsmenu def _create_menu_item(self, descriptor, callbacks): """Creates a :class:`AppKit.NSMenuItem` from a :class:`pystray.MenuItem` instance. :param descriptor: The menu item descriptor. :param callbacks: A list to which a callback is appended for every menu item created. The menu item tags correspond to the items in this list. :return: a :class:`AppKit.NSMenuItem` """ if descriptor is _base.Menu.SEPARATOR: return AppKit.NSMenuItem.separatorItem() else: menu_item = AppKit.NSMenuItem.alloc() \ .initWithTitle_action_keyEquivalent_( descriptor.text, self._MENU_ITEM_SELECTOR, '') if descriptor.submenu: menu_item.setSubmenu_(self._create_menu( descriptor.submenu, callbacks)) else: menu_item.setAction_(self._MENU_ITEM_SELECTOR) menu_item.setTarget_(self._delegate) menu_item.setTag_(len(callbacks)) if descriptor.default: menu_item.setAttributedTitle_( Foundation.NSAttributedString.alloc() .initWithString_attributes_( descriptor.text, Foundation.NSDictionary.alloc() .initWithObjectsAndKeys_( AppKit.NSFont.boldSystemFontOfSize_( AppKit.NSFont.menuFontOfSize_(0) .pointSize()), AppKit.NSFontAttributeName))) if descriptor.checked is not None: menu_item.setState_( AppKit.NSOnState if descriptor.checked else AppKit.NSOffState) menu_item.setEnabled_(descriptor.enabled) return menu_item class IconDelegate(Foundation.NSObject): @objc.namedSelector(Icon._ACTION_SELECTOR) def activate_button(self, sender): self.icon() @objc.namedSelector(Icon._MENU_ITEM_SELECTOR) def activate_menu_item(self, sender): nsmenu, callbacks = self.icon._menu_handle callbacks[sender.tag()](self.icon) pystray-0.19.5/lib/pystray/_dummy.py000066400000000000000000000015421450160124200174430ustar00rootroot00000000000000# coding=utf-8 # pystray # Copyright (C) 2016-2022 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . """ This module contains a dummy implementation. It cannot be used, but importing it will not raise any exceptions. """ from ._base import Icon pystray-0.19.5/lib/pystray/_gtk.py000066400000000000000000000044701450160124200171000ustar00rootroot00000000000000# coding=utf-8 # pystray # Copyright (C) 2016-2022 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from ._util.gtk import GtkIcon, mainloop class Icon(GtkIcon): def __init__(self, *args, **kwargs): super(Icon, self).__init__(*args, **kwargs) self._status_icon = Gtk.StatusIcon.new() self._status_icon.connect( 'activate', self._on_status_icon_activate) self._status_icon.connect( 'popup-menu', self._on_status_icon_popup_menu) if self.icon: self._update_icon() @mainloop def _show(self): self._status_icon.set_visible(True) @mainloop def _hide(self): self._status_icon.set_visible(False) @mainloop def _update_icon(self): self._remove_fs_icon() self._update_fs_icon() self._status_icon.set_from_file(self._icon_path) @mainloop def _update_menu(self): self._menu_handle = self._create_menu(self.menu) @mainloop def _update_title(self): self._status_icon.set_title(self.title) def _on_status_icon_activate(self, status_icon): """The handler for *activate* for the status icon. This signal handler will activate the icon. """ self() def _on_status_icon_popup_menu(self, status_icon, button, activate_time): """The handler for *popup-menu* for the status icon. This signal handler will display the menu if one is set. """ if self._menu_handle: self._menu_handle.popup( None, None, Gtk.StatusIcon.position_menu, self._status_icon, 0, Gtk.get_current_event_time()) pystray-0.19.5/lib/pystray/_info.py000066400000000000000000000014101450160124200172350ustar00rootroot00000000000000# coding=utf-8 # pystray # Copyright (C) 2016-2022 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . __author__ = u'Moses Palmér' __version__ = (0, 19, 5) pystray-0.19.5/lib/pystray/_util/000077500000000000000000000000001450160124200167115ustar00rootroot00000000000000pystray-0.19.5/lib/pystray/_util/__init__.py000066400000000000000000000030651450160124200210260ustar00rootroot00000000000000# coding=utf-8 # pystray # Copyright (C) 2016-2022 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . import contextlib import os import tempfile @contextlib.contextmanager def serialized_image(image, format, extension=None): """Creates an image file from a :class:`PIL.Image.Image`. This function is a context manager that yields a temporary file name. The file is removed when the block is exited. :param PIL.Image.Image image: The in-memory image. :param str format: The format of the image. This format must be handled by *Pillow*. :param extension: The file extension. This defaults to ``format`` lowercased. :type extensions: str or None """ fd, path = tempfile.mkstemp('.%s' % (extension or format.lower())) try: with os.fdopen(fd, 'wb') as f: image.save(f, format=format) yield path finally: try: os.unlink(path) except: raise pystray-0.19.5/lib/pystray/_util/gtk.py000066400000000000000000000126171450160124200200570ustar00rootroot00000000000000# coding=utf-8 # pystray # Copyright (C) 2016-2022 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . import atexit import functools import os import signal import tempfile import gi gi.require_version('Gtk', '3.0') from gi.repository import GLib, GObject, Gtk from pystray import _base from . import notify_dbus # Make sure Gtk works if not Gtk.init_check()[0]: raise ImportError('Gtk could not be initialised') def mainloop(f): """Marks a function to be executed in the main loop. The function will be scheduled to be executed later in the mainloop. :param callable f: The function to execute. Its return value is discarded. """ @functools.wraps(f) def inner(*args, **kwargs): def callback(*args, **kwargs): """A callback that executes ``f`` and then returns ``False``. """ try: f(*args, **kwargs) finally: return False # Execute the callback as an idle function GObject.idle_add(callback, *args, **kwargs) return inner class GtkIcon(_base.Icon): def __init__(self, *args, **kwargs): super(GtkIcon, self).__init__(*args, **kwargs) self._loop = None self._icon_path = None self._notifier = None def _run(self): self._loop = GLib.MainLoop.new(None, False) self._initialize() try: self._loop.run() except: self._log.error( 'An error occurred in the main loop', exc_info=True) finally: self._finalize() def _run_detached(self): self._initialize() atexit.register(lambda: self._finalize()) def _initialize(self): """Performs shared initialisation steps. """ # Make sure that we do not inhibit ctrl+c; this is only possible from # the main thread try: signal.signal(signal.SIGINT, signal.SIG_DFL) except ValueError: pass self._notifier = notify_dbus.Notifier() self._mark_ready() @mainloop def _notify(self, message, title=None): self._notifier.notify(title or self.title, message, self._icon_path) @mainloop def _remove_notification(self): self._notifier.hide() @mainloop def _stop(self): if self._loop is not None: self._loop.quit() def _create_menu(self, descriptors): """Creates a :class:`Gtk.Menu` from a :class:`pystray.Menu` instance. :param descriptors: The menu descriptors. If this is falsy, ``None`` is returned. :return: a :class:`Gtk.Menu` or ``None`` """ if not descriptors: return None else: menu = Gtk.Menu.new() for descriptor in descriptors: menu.append(self._create_menu_item(descriptor)) menu.show_all() return menu def _create_menu_item(self, descriptor): """Creates a :class:`Gtk.MenuItem` from a :class:`pystray.MenuItem` instance. :param descriptor: The menu item descriptor. :return: a :class:`Gtk.MenuItem` """ if descriptor is _base.Menu.SEPARATOR: return Gtk.SeparatorMenuItem() else: if descriptor.checked is not None: menu_item = Gtk.CheckMenuItem.new_with_label(descriptor.text) menu_item.set_active(descriptor.checked) menu_item.set_draw_as_radio(descriptor.radio) else: menu_item = Gtk.MenuItem.new_with_label(descriptor.text) if descriptor.submenu: menu_item.set_submenu(self._create_menu(descriptor.submenu)) else: menu_item.connect('activate', self._handler(descriptor)) if descriptor.default: menu_item.get_children()[0].set_markup( '%s' % GLib.markup_escape_text(descriptor.text)) menu_item.set_sensitive(descriptor.enabled) return menu_item def _finalize(self): self._remove_fs_icon() self._notifier.hide() def _remove_fs_icon(self): """Removes the temporary file used for the icon. """ try: if self._icon_path: os.unlink(self._icon_path) self._icon_path = None except: pass self._icon_valid = False def _update_fs_icon(self): """Updates the icon file. This method will update :attr:`_icon_path` and create a new image file. If an icon is already set, call :meth:`_remove_fs_icon` first to ensure that the old file is removed. """ self._icon_path = tempfile.mktemp() with open(self._icon_path, 'wb') as f: self.icon.save(f, 'PNG') self._icon_valid = True pystray-0.19.5/lib/pystray/_util/notify_dbus.py000066400000000000000000000054421450160124200216150ustar00rootroot00000000000000# coding=utf-8 # pystray # Copyright (C) 2016-2022 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . import atexit import os import shutil import tempfile import gi gi.require_version('DBus', '1.0') gi.require_version('Gio', '2.0') from gi.repository import GLib, Gio #: The destination name. DESTINATION = 'org.freedesktop.Notifications' #: The destination path. PATH = '/org/freedesktop/Notifications' class Notifier(object): def __init__(self): self._connection = Gio.bus_get_sync( Gio.BusType.SESSION, None) self._notify = Gio.DBusProxy.new_sync( self._connection, 0, None, DESTINATION, PATH, DESTINATION, None) self._nid = 0 icon_path = tempfile.mktemp('.png') self._icon = icon_path @atexit.register def cleanup(): try: os.unlink(icon_path) except: # Ignore any error pass def notify(self, title, message, icon): """Displays a notification message. :param str title: The message title. :param str message: The actual message. :param str icon: The icon path. """ # Make sure the file exists after having been updated by the Icon # instance by copying the file to a temporary file self._nid = self._notify.call_sync( 'Notify', GLib.Variant( '(susssasa{sv}i)', ( '', self._nid, shutil.copy(icon, self._icon), title, message, [], [], -1)), Gio.DBusCallFlags.NONE, -1, None).unpack()[0] def hide(self): """Hides the notification displayed by :meth:`notify`. """ self._notify.call_sync( 'CloseNotification', GLib.Variant( '(u)', ( self._nid, )), Gio.DBusCallFlags.NONE, -1, None) self._nid = 0 pystray-0.19.5/lib/pystray/_util/win32.py000066400000000000000000000235471450160124200202400ustar00rootroot00000000000000# coding=utf-8 # pystray # Copyright (C) 2016-2022 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . import ctypes from ctypes import wintypes windll = ctypes.LibraryLoader(ctypes.WinDLL) WM_CREATE = 0x0001 WM_DISPLAYCHANGE = 0x007E WM_NCCREATE = 0x0081 WM_LBUTTONUP = 0x0202 WM_RBUTTONUP = 0x0205 WM_USER = 0x400 WM_STOP = WM_USER + 10 WM_NOTIFY = WM_USER + 11 LR_DEFAULTSIZE = 0x00000040 LR_LOADFROMFILE = 0x00000010 MFS_CHECKED = 0x00000008 MFS_DEFAULT = 0x00001000 MFS_DISABLED = 0x00000003 MFS_ENABLED = 0x00000000 MFS_GRAYED = 0x00000003 MFS_HILITE = 0x00000080 MFS_UNCHECKED = 0x00000000 MFS_UNHILITE = 0x00000000 MFT_BITMAP = 0x00000004 MFT_MENUBARBREAK = 0x00000020 MFT_MENUBREAK = 0x00000040 MFT_OWNERDRAW = 0x00000100 MFT_RADIOCHECK = 0x00000200 MFT_RIGHTJUSTIFY = 0x00004000 MFT_RIGHTORDER = 0x00002000 MFT_SEPARATOR = 0x00000800 MFT_STRING = 0x00000000 MIIM_BITMAP = 0x00000080 MIIM_CHECKMARKS = 0x00000008 MIIM_DATA = 0x00000020 MIIM_FTYPE = 0x00000100 MIIM_ID = 0x00000002 MIIM_STATE = 0x00000001 MIIM_STRING = 0x00000040 MIIM_SUBMENU = 0x00000004 MIIM_TYPE = 0x00000010 MSGFLT_ALLOW = 1 MSGFLT_DISALLOW = 2 MSGFLT_RESET = 0 NIF_MESSAGE = 0x00000001 NIF_ICON = 0x00000002 NIF_TIP = 0x00000004 NIF_STATE = 0x00000008 NIF_INFO = 0x00000010 NIF_GUID = 0x00000020 NIF_REALTIME = 0x00000040 NIF_SHOWTIP = 0x00000080 NIM_ADD = 0x00000000 NIM_MODIFY = 0x00000001 NIM_DELETE = 0x00000002 NIM_SETFOCUS = 0x00000003 NIM_SETVERSION = 0x00000004 TPM_CENTERALIGN = 0x0004 TPM_LEFTALIGN = 0x0000 TPM_RIGHTALIGN = 0x0008 TPM_BOTTOMALIGN = 0x0020 TPM_TOPALIGN = 0x0000 TPM_VCENTERALIGN = 0x0010 TPM_NONOTIFY = 0x0080 TPM_RETURNCMD = 0x0100 TPM_LEFTBUTTON = 0x0000 TPM_RIGHTBUTTON = 0x0002 TPM_HORNEGANIMATION = 0x0800 TPM_HORPOSANIMATION = 0x0400 TPM_NOANIMATION = 0x4000 TPM_VERNEGANIMATION = 0x2000 TPM_VERPOSANIMATION = 0x1000 TPM_HORIZONTAL = 0x0000 TPM_VERTICAL = 0x0040 WS_POPUP = 0x80000000 PM_NOREMOVE = 0 COLOR_WINDOW = 5 HWND_MESSAGE = -3 IMAGE_ICON = 1 LPMSG = ctypes.POINTER(wintypes.MSG) LPPOINT = ctypes.POINTER(wintypes.POINT) WNDPROC = ctypes.WINFUNCTYPE( ctypes.HRESULT, wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM) class MENUITEMINFO(ctypes.Structure): _fields_ = [ ('cbSize', wintypes.UINT), ('fMask', wintypes.UINT), ('fType', wintypes.UINT), ('fState', wintypes.UINT), ('wID', wintypes.UINT), ('hSubMenu', wintypes.HMENU), ('hbmpChecked', wintypes.HBITMAP), ('hbmpUnchecked', wintypes.HBITMAP), ('dwItemData', wintypes.LPVOID), ('dwTypeData', wintypes.LPCWSTR), ('cch', wintypes.UINT), ('hbmpItem', wintypes.HBITMAP)] LPMENUITEMINFO = ctypes.POINTER(MENUITEMINFO) class NOTIFYICONDATAW(ctypes.Structure): class VERSION_OR_TIMEOUT(ctypes.Union): _fields_ = [ ('uTimeout', wintypes.UINT), ('uVersion', wintypes.UINT)] class GUID(ctypes.Structure): _fields_ = [ ('Data1', wintypes.ULONG), ('Data2', wintypes.WORD), ('Data3', wintypes.WORD), ('Data4', wintypes.BYTE * 8)] _fields_ = [ ('cbSize', wintypes.DWORD), ('hWnd', wintypes.HWND), ('uID', wintypes.UINT), ('uFlags', wintypes.UINT), ('uCallbackMessage', wintypes.UINT), ('hIcon', wintypes.HICON), ('szTip', wintypes.WCHAR * 128), ('dwState', wintypes.DWORD), ('dwStateMask', wintypes.DWORD), ('szInfo', wintypes.WCHAR * 256), ('version_or_timeout', VERSION_OR_TIMEOUT), ('szInfoTitle', wintypes.WCHAR * 64), ('dwInfoFlags', wintypes.DWORD), ('guidItem', GUID), ('hBalloonIcon', wintypes.HICON)] _anonymous_ = [ 'version_or_timeout'] LPNOTIFYICONDATAW = ctypes.POINTER(NOTIFYICONDATAW) class TPMPARAMS(ctypes.Structure): _fields_ = [ ('cbSize', wintypes.UINT), ('rcExclude', wintypes.RECT)] LPTPMPARAMS = ctypes.POINTER(TPMPARAMS) class WNDCLASSEX(ctypes.Structure): _fields_ = [ ('cbSize', wintypes.UINT), ('style', wintypes.UINT), ('lpfnWndProc', WNDPROC), ('cbClsExtra', wintypes.INT), ('cbWndExtra', wintypes.INT), ('hInstance', wintypes.HANDLE), ('hIcon', wintypes.HICON), ('hCursor', wintypes.HANDLE), ('hbrBackground', wintypes.HBRUSH), ('lpszMenuName', wintypes.LPCWSTR), ('lpszClassName', wintypes.LPCWSTR), ('hIconSm', wintypes.HICON)] def _err(result, func, arguments): """A *ctypes* ``errchecker`` that ensures truthy values. """ if not result: raise ctypes.WinError() else: return result LPWNDCLASSEX = ctypes.POINTER(WNDCLASSEX) CreatePopupMenu = windll.user32.CreatePopupMenu CreatePopupMenu.argtypes = () CreatePopupMenu.restype = wintypes.HMENU CreatePopupMenu.errcheck = _err CreateWindowEx = windll.user32.CreateWindowExW CreateWindowEx.argtypes = ( wintypes.DWORD, wintypes.ATOM, wintypes.LPCWSTR, wintypes.DWORD, wintypes.INT, wintypes.INT, wintypes.INT, wintypes.INT, wintypes.HWND, wintypes.HMENU, wintypes.HINSTANCE, wintypes.LPVOID) CreateWindowEx.restype = wintypes.HWND CreateWindowEx.errcheck = _err DefWindowProc = windll.user32.DefWindowProcW DefWindowProc.argtypes = ( wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM) DefWindowProc.restype = wintypes.DWORD DestroyIcon = windll.user32.DestroyIcon DestroyIcon.argtypes = ( wintypes.HICON,) DestroyIcon.restype = wintypes.BOOL DestroyIcon.errcheck = _err DestroyMenu = windll.user32.DestroyMenu DestroyMenu.argtypes = ( wintypes.HMENU,) DestroyMenu.restype = wintypes.BOOL DestroyMenu.errcheck = _err DestroyWindow = windll.user32.DestroyWindow DestroyWindow.argtypes = ( wintypes.HWND,) DestroyWindow.restype = wintypes.BOOL DestroyWindow.errcheck = _err DispatchMessage = windll.user32.DispatchMessageW DispatchMessage.argtypes = ( LPMSG,) DispatchMessage.restype = wintypes.DWORD GetCursorPos = windll.user32.GetCursorPos GetCursorPos.argtypes = ( LPPOINT,) GetCursorPos.restype = wintypes.BOOL GetCursorPos.errcheck = _err GetMessage = windll.user32.GetMessageW GetMessage.argtypes = ( LPMSG, wintypes.HWND, wintypes.UINT, wintypes.UINT) GetMessage.restype = wintypes.BOOL GetModuleHandle = windll.kernel32.GetModuleHandleW GetModuleHandle.argtypes = ( wintypes.LPCWSTR,) GetModuleHandle.restype = wintypes.HMODULE GetModuleHandle.errcheck = _err InsertMenuItem = windll.user32.InsertMenuItemW InsertMenuItem.argtypes = ( wintypes.HMENU, wintypes.UINT, wintypes.BOOL, LPMENUITEMINFO) InsertMenuItem.restype = wintypes.BOOL InsertMenuItem.errcheck = _err LoadImage = windll.user32.LoadImageW LoadImage.argtypes = ( wintypes.HINSTANCE, wintypes.LPCWSTR, wintypes.UINT, wintypes.INT, wintypes.INT, wintypes.UINT) LoadImage.restype = wintypes.HANDLE LoadImage.errcheck = _err PeekMessage = windll.user32.PeekMessageW PeekMessage.argtypes = ( LPMSG, wintypes.HWND, wintypes.UINT, wintypes.UINT, wintypes.UINT) PeekMessage.restype = wintypes.BOOL PostMessage = windll.user32.PostMessageW PostMessage.argtypes = ( wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM) PostMessage.restype = wintypes.BOOL PostMessage.restype = wintypes.BOOL PostQuitMessage = windll.user32.PostQuitMessage PostQuitMessage.argtypes = ( wintypes.INT,) RegisterClassEx = windll.user32.RegisterClassExW RegisterClassEx.argtypes = ( LPWNDCLASSEX,) RegisterClassEx.restype = wintypes.ATOM RegisterClassEx.errcheck = _err SetForegroundWindow = windll.user32.SetForegroundWindow SetForegroundWindow.argtypes = ( wintypes.HWND,) SetForegroundWindow.restype = wintypes.BOOL Shell_NotifyIcon = windll.shell32.Shell_NotifyIconW Shell_NotifyIcon.argtypes = ( wintypes.DWORD, LPNOTIFYICONDATAW) Shell_NotifyIcon.restype = wintypes.BOOL TranslateMessage = windll.user32.TranslateMessage TranslateMessage.argtypes = ( LPMSG,) TranslateMessage.restype = wintypes.BOOL TrackPopupMenuEx = windll.user32.TrackPopupMenuEx TrackPopupMenuEx.argtypes = ( wintypes.HMENU, wintypes.UINT, wintypes.INT, wintypes.INT, wintypes.HWND, LPTPMPARAMS) UnregisterClass = windll.user32.UnregisterClassW UnregisterClass.argtypes = ( wintypes.ATOM, wintypes.HINSTANCE) UnregisterClass.restype = wintypes.BOOL UnregisterClass.errcheck = _err RegisterWindowMessage = windll.user32.RegisterWindowMessageW RegisterWindowMessage.argtypes = ( wintypes.LPCWSTR,) RegisterWindowMessage.restype = wintypes.UINT RegisterWindowMessage.errcheck = _err #: The message broadcast to top-level windows on Explorer restart WM_TASKBARCREATED = RegisterWindowMessage('TaskbarCreated') # Ensure that we receive WM_TASKBARCREATED even when running with elevated # privileges try: ChangeWindowMessageFilterEx = windll.user32.ChangeWindowMessageFilterEx ChangeWindowMessageFilterEx.argtypes = ( wintypes.HWND, wintypes.UINT, wintypes.DWORD, wintypes.LPVOID) ChangeWindowMessageFilterEx.restype = wintypes.BOOL ChangeWindowMessageFilterEx.errcheck = _err except KeyError: def ChangeWindowMessageFilterEx( hWnd, message, action, pCHangeFilterStruct): """A dummy implementation of ``ChangeWindowMessageFilterEx`` always returning ``TRUE``. This is used on version of *Windows* prior to *Windows Vista*. """ return True pystray-0.19.5/lib/pystray/_win32.py000066400000000000000000000322111450160124200172470ustar00rootroot00000000000000# coding=utf-8 # pystray # Copyright (C) 2016-2022 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . import ctypes import threading from ctypes import wintypes from six.moves import queue from ._util import serialized_image, win32 from . import _base class Icon(_base.Icon): _HWND_TO_ICON = {} def __init__(self, *args, **kwargs): super(Icon, self).__init__(*args, **kwargs) self._atom = self._register_class() self._icon_handle = None self._hwnd = None self._menu_hwnd = None self._hmenu = None # This is a mapping from win32 event codes to handlers used by the # mainloop self._message_handlers = { win32.WM_DISPLAYCHANGE: self._on_display_change, win32.WM_STOP: self._on_stop, win32.WM_NOTIFY: self._on_notify, win32.WM_TASKBARCREATED: self._on_taskbarcreated} self._queue = queue.Queue() def __del__(self): if self._running: self._stop() if self._thread.ident != threading.current_thread().ident: self._thread.join() self._release_icon() def _show(self): self._assert_icon_handle() self._message( win32.NIM_ADD, win32.NIF_MESSAGE | win32.NIF_ICON | win32.NIF_TIP, uCallbackMessage=win32.WM_NOTIFY, hIcon=self._icon_handle, szTip=self.title) def _hide(self): self._message( win32.NIM_DELETE, 0) def _update_icon(self): self._release_icon() self._assert_icon_handle() self._message( win32.NIM_MODIFY, win32.NIF_ICON, hIcon=self._icon_handle) self._icon_valid = True def _update_title(self): self._message( win32.NIM_MODIFY, win32.NIF_TIP, szTip=self.title) def _notify(self, message, title=None): self._message( win32.NIM_MODIFY, win32.NIF_INFO, szInfo=message, szInfoTitle=title or self.title or '') def _remove_notification(self): self._message( win32.NIM_MODIFY, win32.NIF_INFO, szInfo='') def _update_menu(self): try: hmenu, callbacks = self._menu_handle win32.DestroyMenu(hmenu) except: pass callbacks = [] hmenu = self._create_menu(self.menu, callbacks) if hmenu: self._menu_handle = (hmenu, callbacks) else: self._menu_handle = None def _run(self): # Create the message loop msg = wintypes.MSG() lpmsg = ctypes.byref(msg) win32.PeekMessage( lpmsg, None, win32.WM_USER, win32.WM_USER, win32.PM_NOREMOVE) self._hwnd = self._create_window(self._atom) self._menu_hwnd = self._create_window(self._atom) self._HWND_TO_ICON[self._hwnd] = self self._mark_ready() # Run the event loop self._thread = threading.current_thread() self._mainloop() def _run_detached(self): threading.Thread(target=lambda: self._run()).start() def _stop(self): win32.PostMessage(self._hwnd, win32.WM_STOP, 0, 0) def _mainloop(self): """The body of the main loop thread. This method retrieves all events from *Windows* and makes sure to dispatch clicks. """ # Pump messages try: msg = wintypes.MSG() lpmsg = ctypes.byref(msg) while True: r = win32.GetMessage(lpmsg, None, 0, 0) if not r: break elif r == -1: break else: win32.TranslateMessage(lpmsg) win32.DispatchMessage(lpmsg) except: self._log.error( 'An error occurred in the main loop', exc_info=True) finally: try: self._hide() del self._HWND_TO_ICON[self._hwnd] except: # Ignore pass win32.DestroyWindow(self._hwnd) win32.DestroyWindow(self._menu_hwnd) if self._menu_handle: hmenu, callbacks = self._menu_handle win32.DestroyMenu(hmenu) self._unregister_class(self._atom) def _on_display_change(self, wparam, lparam): """Handles ``WM_DISPLAYCHANGE``. This method updates the icon to prevent blurring when changing resolutions. """ if self.visible: self._hide() self._show() def _on_stop(self, wparam, lparam): """Handles ``WM_STOP``. This method posts a quit message, causing the mainloop thread to terminate. """ win32.PostQuitMessage(0) def _on_notify(self, wparam, lparam): """Handles ``WM_NOTIFY``. If this is a left button click, this icon will be activated. If a menu is registered and this is a right button click, the popup menu will be displayed. """ if lparam == win32.WM_LBUTTONUP: self() elif self._menu_handle and lparam == win32.WM_RBUTTONUP: # TrackPopupMenuEx does not behave unless our systray window is the # foreground window win32.SetForegroundWindow(self._hwnd) # Get the cursor position to determine where to display the menu point = wintypes.POINT() win32.GetCursorPos(ctypes.byref(point)) # Display the menu and get the menu item identifier; the identifier # is the menu item index hmenu, descriptors = self._menu_handle index = win32.TrackPopupMenuEx( hmenu, win32.TPM_RIGHTALIGN | win32.TPM_BOTTOMALIGN | win32.TPM_RETURNCMD, point.x, point.y, self._menu_hwnd, None) if index > 0: descriptors[index - 1](self) def _on_taskbarcreated(self, wparam, lparam): """Handles ``WM_TASKBARCREATED``. This message is broadcast when the notification area becomes available. Handling this message allows catching explorer restarts. """ if self.visible: self._show() def _create_window(self, atom): """Creates the system tray icon window. :param atom: The window class atom. :return: a window """ # Broadcast messages (including WM_TASKBARCREATED) can be caught # only by top-level windows, so we cannot create a message-only window hwnd = win32.CreateWindowEx( 0, atom, None, win32.WS_POPUP, 0, 0, 0, 0, 0, None, win32.GetModuleHandle(None), None) # On Vista+, we must explicitly opt-in to receive WM_TASKBARCREATED # when running with escalated privileges win32.ChangeWindowMessageFilterEx( hwnd, win32.WM_TASKBARCREATED, win32.MSGFLT_ALLOW, None) return hwnd def _create_menu(self, descriptors, callbacks): """Creates a :class:`ctypes.wintypes.HMENU` from a :class:`pystray.Menu` instance. :param descriptors: The menu descriptors. If this is falsy, ``None`` is returned. :param callbacks: A list to which a callback is appended for every menu item created. The menu item IDs correspond to the items in this list plus one. :return: a menu """ if not descriptors: return None else: # Generate the menu hmenu = win32.CreatePopupMenu() for i, descriptor in enumerate(descriptors): # Append the callbacks before creating the menu items to ensure # that the first item gets the ID 1 callbacks.append(self._handler(descriptor)) menu_item = self._create_menu_item(descriptor, callbacks) win32.InsertMenuItem(hmenu, i, True, ctypes.byref(menu_item)) return hmenu def _create_menu_item(self, descriptor, callbacks): """Creates a :class:`pystray._util.win32.MENUITEMINFO` from a :class:`pystray.MenuItem` instance. :param descriptor: The menu item descriptor. :param callbacks: A list to which a callback is appended for every menu item created. The menu item IDs correspond to the items in this list plus one. :return: a :class:`pystray._util.win32.MENUITEMINFO` """ if descriptor is _base.Menu.SEPARATOR: return win32.MENUITEMINFO( cbSize=ctypes.sizeof(win32.MENUITEMINFO), fMask=win32.MIIM_FTYPE, fType=win32.MFT_SEPARATOR) else: return win32.MENUITEMINFO( cbSize=ctypes.sizeof(win32.MENUITEMINFO), fMask=win32.MIIM_ID | win32.MIIM_STRING | win32.MIIM_STATE | win32.MIIM_FTYPE | win32.MIIM_SUBMENU, wID=len(callbacks), dwTypeData=descriptor.text, fState=0 | (win32.MFS_DEFAULT if descriptor.default else 0) | (win32.MFS_CHECKED if descriptor.checked else 0) | (win32.MFS_DISABLED if not descriptor.enabled else 0), fType=0 | (win32.MFT_RADIOCHECK if descriptor.radio else 0), hSubMenu=self._create_menu(descriptor.submenu, callbacks) if descriptor.submenu else None) def _message(self, code, flags, **kwargs): """Sends a message the the systray icon. This method adds ``cbSize``, ``hWnd``, ``hId`` and ``uFlags`` to the message data. :param int message: The message to send. This should be one of the ``NIM_*`` constants. :param int flags: The value of ``NOTIFYICONDATAW::uFlags``. :param kwargs: Data for the :class:`NOTIFYICONDATAW` object. """ win32.Shell_NotifyIcon(code, win32.NOTIFYICONDATAW( cbSize=ctypes.sizeof(win32.NOTIFYICONDATAW), hWnd=self._hwnd, hID=id(self), uFlags=flags, **kwargs)) def _release_icon(self): """Releases the icon handle and sets it to ``None``. If not icon handle is set, no action is performed. """ if self._icon_handle: win32.DestroyIcon(self._icon_handle) self._icon_handle = None def _assert_icon_handle(self): """Asserts that the cached icon handle exists. """ if self._icon_handle: return with serialized_image(self.icon, 'ICO') as icon_path: self._icon_handle = win32.LoadImage( None, icon_path, win32.IMAGE_ICON, 0, 0, win32.LR_DEFAULTSIZE | win32.LR_LOADFROMFILE) def _register_class(self): """Registers the systray window class. :return: the class atom """ return win32.RegisterClassEx(win32.WNDCLASSEX( cbSize=ctypes.sizeof(win32.WNDCLASSEX), style=0, lpfnWndProc=_dispatcher, cbClsExtra=0, cbWndExtra=0, hInstance=win32.GetModuleHandle(None), hIcon=None, hCursor=None, hbrBackground=win32.COLOR_WINDOW + 1, lpszMenuName=None, lpszClassName='%s%dSystemTrayIcon' % (self.name, id(self)), hIconSm=None)) def _unregister_class(self, atom): """Unregisters the systray window class. :param atom: The class atom returned by :meth:`_register_class`. """ win32.UnregisterClass(atom, win32.GetModuleHandle(None)) @win32.WNDPROC def _dispatcher(hwnd, uMsg, wParam, lParam): """The function used as window procedure for the systray window. """ # These messages are sent before Icon._HWND_TO_ICON[hwnd] has been set, so # we handle them explicitly if uMsg == win32.WM_NCCREATE: return True if uMsg == win32.WM_CREATE: return 0 try: icon = Icon._HWND_TO_ICON[hwnd] except KeyError: return win32.DefWindowProc(hwnd, uMsg, wParam, lParam) try: return int(icon._message_handlers.get( uMsg, lambda w, l: 0)(wParam, lParam) or 0) except: icon._log.error( 'An error occurred when calling message handler', exc_info=True) return 0 pystray-0.19.5/lib/pystray/_xorg.py000066400000000000000000000356041450160124200172750ustar00rootroot00000000000000# coding=utf-8 # pystray # Copyright (C) 2016-2022 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . import contextlib import functools import six import sys import threading import types import PIL import Xlib.display import Xlib.threaded import Xlib.XK from six.moves import queue from . import _base # Create a display to verify that we have an X connection display = Xlib.display.Display() display.close() del display class XError(Exception): """An error that is thrown at the end of a code block managed by a :func:`display_manager` if an *X* error occurred. """ pass @contextlib.contextmanager def display_manager(display): """Traps *X* errors and raises an :class:`XError` at the end if any error occurred. This handler also ensures that the :class:`Xlib.display.Display` being managed is sync'd. :param Xlib.display.Display display: The *X* display. """ errors = [] def handler(*args): errors.append(args) old_handler = display.set_error_handler(handler) try: yield display.sync() finally: display.set_error_handler(old_handler) if errors: raise XError(errors) class Icon(_base.Icon): _XEMBED_VERSION = 0 _XEMBED_MAPPED = 1 _SYSTEM_TRAY_REQUEST_DOCK = 0 # We support only the default action HAS_MENU = False # We support no menu HAS_MENU_RADIO = False # No notification (yet)! HAS_NOTIFICATION = False def __init__(self, *args, **kwargs): super(Icon, self).__init__(*args, **kwargs) #: The properly scaled version of the icon image self._icon_data = None #: The window currently embedding this icon self._systray_manager = None # This is a mapping from X event codes to handlers used by the mainloop self._message_handlers = { Xlib.X.ButtonPress: self._on_button_press, Xlib.X.ConfigureNotify: self._on_expose, Xlib.X.DestroyNotify: self._on_destroy_notify, Xlib.X.Expose: self._on_expose} self._queue = queue.Queue() # Connect to X self._display = Xlib.display.Display() with display_manager(self._display): # Create the atoms; some of these are required when creating # the window self._create_atoms() # Create the window and get a graphics context self._window = self._create_window() self._gc = self._window.create_gc() # Rewrite the platform implementation methods to ensure they # are executed in this thread self._rewrite_implementation( self._show, self._hide, self._update_icon, self._update_title, self._stop) def __del__(self): try: # Destroying the window will stop the mainloop thread if self._running: self._stop() if threading.current_thread().ident != self._thread.ident: self._thread.join() finally: self._display.close() def _show(self): """The implementation of :meth:`_show`, executed in the mainloop thread. """ try: self._assert_docked() except AssertionError: # There is no systray selection owner, so we cannot dock; ignore # and dock later self._log.error( 'Failed to dock icon', exc_info=True) def _hide(self): """The implementation of :meth:`_hide`, executed in the mainloop thread. """ if self._systray_manager: self._undock_window() def _update_icon(self): """The implementation of :meth:`_update_icon`, executed in the mainloop thread. """ try: self._assert_docked() except AssertionError: # If we are not docked, we cannot update the icon self._log.error( 'Failed to dock icon', exc_info=True) return # Setting _icon_data to None will force regeneration of the icon # from _icon self._icon_data = None self._draw() self._icon_valid = True def _update_title(self): """The implementation of :meth:`_update_title`, executed in the mainloop thread. """ # The title is the window name self._window.set_wm_name(self.title) def _update_menu(self): # Menus are not supported on X pass def _run(self): self._mark_ready() # Run the event loop self._thread = threading.current_thread() self._mainloop() def _run_detached(self): threading.Thread(target=lambda: self.run()).start() def _stop(self): """Stops the mainloop. """ self._window.destroy() self._display.flush() def _mainloop(self): """The body of the main loop thread. This method retrieves all events from *X* and makes sure to dispatch clicks. """ try: for event in self._events(): # If the systray window is destroyed, the icon has been hidden if (event.type == Xlib.X.DestroyNotify and event.window == self._window): break self._message_handlers.get(event.type, lambda e: None)(event) except: self._log.error( 'An error occurred in the main loop', exc_info=True) def _on_button_press(self, event): """Handles ``Xlib.X.ButtonPress``. This method calls the activate callback. It will only be called for left button clicks. """ if event.detail == 1: self() def _on_destroy_notify(self, event): """Handles ``Xlib.X.DestroyNotify``. This method clears :attr:`_systray_manager` if it is destroyed. """ # Handle only the systray manager window; the destroy notification # for our own window is handled in the event loop if event.window.id != self._systray_manager.id: return # Try to locate a new systray selection owner self._systray_manager = None try: self._assert_docked() except AssertionError: # There is no new selection owner; we must retry later self._log.error( 'Failed to dock icon', exc_info=True) def _on_expose(self, event): """Handles ``Xlib.X.ConfigureNotify`` and ``Xlib.X.Expose``. This method redraws the window. """ # Redraw only our own window if event.window.id != self._window.id: return self._draw() def _create_atoms(self): """Creates the atoms used by the *XEMBED* and *systray* specifications. """ self._xembed_info = self._display.intern_atom( '_XEMBED_INFO') self._net_system_tray_sx = self._display.intern_atom( '_NET_SYSTEM_TRAY_S%d' % ( self._display.get_default_screen())) self._net_system_tray_opcode = self._display.intern_atom( '_NET_SYSTEM_TRAY_OPCODE') def _rewrite_implementation(self, *args): """Overwrites the platform implementation methods with ones causing the mainloop to execute the code instead. :param args: The methods to rewrite. """ def dispatcher(original, atom): @functools.wraps(original) def inner(self): # Just invoke the method if we are currently in the correct # thread if threading.current_thread().ident == self._thread.ident: original() else: self._send_message(self._window, atom) self._display.flush() # Wait for the mainloop to execute the actual method, wait # for completion and reraise any exceptions result = self._queue.get() if result is not True: six.reraise(*result) return types.MethodType(inner, self) def wrapper(original): @functools.wraps(original) def inner(): try: original() self._queue.put(True) except: self._queue.put(sys.exc_info()) return inner def on_client_message(event): handlers.get(event.client_type, lambda: None)() # Create the atoms and a mapping from atom to actual implementation atoms = [ self._display.intern_atom( '_PYSTRAY_%s' % original.__name__.upper()) for original in args] handlers = { atom: wrapper(original) for original, atom in zip(args, atoms)} # Replace the old methods for original, atom in zip(args, atoms): setattr( self, original.__name__, dispatcher(original, atom)) # Make sure that we handle ClientMessage self._message_handlers[Xlib.X.ClientMessage] = on_client_message def _create_window(self): """Creates the system tray icon window. :return: a window """ with display_manager(self._display): # Create the window screen = self._display.screen() window = screen.root.create_window( -1, -1, 1, 1, 0, screen.root_depth, event_mask=Xlib.X.ExposureMask | Xlib.X.StructureNotifyMask, window_class=Xlib.X.InputOutput) flags = ( Xlib.Xutil.PPosition | Xlib.Xutil.PSize | Xlib.Xutil.PMinSize) window.set_wm_class('%sSystemTrayIcon' % self.name, self.name) window.set_wm_name(self.title) window.set_wm_normal_hints( flags=flags, min_width=24, min_height=24) # Enable XEMBED for the window window.change_property(self._xembed_info, self._xembed_info, 32, [ self._XEMBED_VERSION, self._XEMBED_MAPPED]) return window def _draw(self): """Paints the icon image. """ try: dim = self._window.get_geometry() self._assert_icon_data(dim.width, dim.height) self._window.put_pil_image(self._gc, 0, 0, self._icon_data) except Xlib.error.BadDrawable: # The window has been destroyed; ignore pass def _assert_icon_data(self, width, height): """Asserts that the cached icon data matches the requested dimensions. If no cached icon data exists, or its dimensions do not match the requested size, the image is generated. :param int width: The requested width. :param int height: The requested height. """ if self._icon_data and self._icon_data.size == (width, height): return self._icon_data = PIL.Image.new( 'RGB', (width, height)) self._icon_data.paste(self._icon.resize( (width, height), PIL.Image.LANCZOS)) self._icon_data.tostring = self._icon_data.tobytes def _assert_docked(self): """Asserts that the icon is docked in the systray. :raises AssertionError: if the window is not docked """ self._dock_window() assert self._systray_manager def _dock_window(self): """Docks the window in the systray. """ # Get the selection owner systray_manager = self._get_systray_manager() if not systray_manager: return self._systray_manager = systray_manager # Request being docked self._send_message( self._systray_manager, self._net_system_tray_opcode, self._SYSTEM_TRAY_REQUEST_DOCK, self._window.id) # Make sure we get destroy notifications systray_manager.change_attributes( event_mask=Xlib.X.StructureNotifyMask) self._display.flush() self._systray_manager = systray_manager def _undock_window(self): """Undocks the window from the systray. """ # Make sure we get do not get any notifications try: self._systray_manager.change_attributes( event_mask=Xlib.X.NoEventMask) except XError: # The systray manager may have been destroyed self._log.error( 'Failed to stop notifications', exc_info=True) self._window.unmap() self._window.reparent(self._display.screen().root, 0, 0) self._systray_manager = None self._display.flush() def _get_systray_manager(self): """Returns the *X* window that owns the systray selection. :return: the window owning the selection, or ``None`` if no window owns it """ self._display.grab_server() try: systray_manager = self._display.get_selection_owner( self._net_system_tray_sx) finally: self._display.ungrab_server() self._display.flush() if systray_manager != Xlib.X.NONE: return self._display.create_resource_object( 'window', systray_manager.id) def _send_message(self, window, client_type, l0=0, l1=0, l2=0, l3=0): """Sends a generic client message message. This method does not trap *X* errors; that is up to the caller. :param int l0: Message specific data. :param int l1: Message specific data. :param int l2: Message specific data. :param int l3: Message specific data. """ self._display.send_event( window, Xlib.display.event.ClientMessage( type=Xlib.X.ClientMessage, client_type=client_type, window=window.id, data=( 32, (Xlib.X.CurrentTime, l0, l1, l2, l3))), event_mask=Xlib.X.NoEventMask) def _events(self): """Yields all events. """ while True: event = self._display.next_event() if not event: break else: yield event pystray-0.19.5/setup.cfg000066400000000000000000000002211450160124200151300ustar00rootroot00000000000000[bdist_wheel] universal = 1 [build_sphinx] source-dir = docs build-dir = build/docs all-files = 1 [upload_sphinx] upload-dir = build/docs/html pystray-0.19.5/setup.py000066400000000000000000000056041450160124200150330ustar00rootroot00000000000000#!/usr/bin/env python # coding: utf-8 import os import setuptools import sys #: The name of the package on PyPi PYPI_PACKAGE_NAME = 'pystray' #: The name of the main Python package MAIN_PACKAGE_NAME = 'pystray' #: The package URL PACKAGE_URL = 'https://github.com/moses-palmer/pystray' #: The author email AUTHOR_EMAIL = 'moses.palmer@gmail.com' #: The runtime requirements RUNTIME_PACKAGES = [ 'Pillow', 'six'] #: Additional requirements used during setup SETUP_PACKAGES = RUNTIME_PACKAGES + [ 'sphinx >=1.3.1'] #: Packages requires for different environments EXTRA_PACKAGES = { ':sys_platform == "darwin"': [ 'pyobjc-framework-Quartz >=7.0'], ':sys_platform == "linux"': [ 'python-xlib >=0.17']} # Read globals from ._info without loading it INFO = {} with open(os.path.join( os.path.dirname(__file__), 'lib', MAIN_PACKAGE_NAME, '_info.py'), 'rb') as f: data = ( f.read().decode('utf-8') if sys.version_info.major >= 3 else f.read()) code = compile(data, '_info.py', 'exec') exec(code, {}, INFO) INFO['author'] = INFO['__author__'] INFO['version'] = '.'.join(str(v) for v in INFO['__version__']) # Load the read me try: with open(os.path.join( os.path.dirname(__file__), 'README.rst', 'rb')) as f: README = f.read().decode('utf-8') with open(os.path.join( os.path.dirname(__file__), 'docs', 'usage.rst'), 'rb') as f: README += '\n\n' + f.read().decode('utf-8') except IOError: README = '' # Load the release notes try: with open(os.path.join( os.path.dirname(__file__), 'CHANGES.rst'), 'rb') as f: CHANGES = f.read().decode('utf-8') except IOError: CHANGES = '' setuptools.setup( name=PYPI_PACKAGE_NAME, version=INFO['version'], description='Provides systray integration', long_description=README + '\n\n' + CHANGES, install_requires=RUNTIME_PACKAGES, setup_requires=RUNTIME_PACKAGES + SETUP_PACKAGES, extras_require=EXTRA_PACKAGES, author=INFO['author'], author_email=AUTHOR_EMAIL, url=PACKAGE_URL, packages=setuptools.find_packages( os.path.join( os.path.dirname(__file__), 'lib')), package_dir={'': 'lib'}, zip_safe=True, test_suite='tests', license='LGPLv3', keywords='system tray icon, systray icon', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Lesser General Public License v3 ' '(LGPLv3)', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows :: Windows NT/2000', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4']) pystray-0.19.5/tests/000077500000000000000000000000001450160124200144565ustar00rootroot00000000000000pystray-0.19.5/tests/__init__.py000066400000000000000000000071671450160124200166020ustar00rootroot00000000000000# coding=utf-8 # pystray # Copyright (C) 2016-2022 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . from __future__ import print_function import itertools from PIL import Image, ImageDraw from six.moves import input import pystray from pystray import MenuItem as item COLORS = itertools.cycle(( 'black', 'white', 'red', 'yellow', 'blue', 'red', 'green', 'white')) def say(*args, **kwargs): """Prints a message, ensuring space between messages. """ print('\n') print(*args, **kwargs) def action(on_activate): """A convenience function to create a hidden default menu item. :param callable on_activate: The activation callback. """ return item('Default', on_activate, default=True, visible=False) def separator(): """A wrapper around :attr:`pystray.Menu.SEPARATOR`. """ return pystray.Menu.SEPARATOR def icon(no_image=False, **kwargs): """Generates a systray icon with the specified colours. A systray icon created by this method will be automatically hidden when the current test finishes. :return: the tuple ``(icon, colors)``, where ``icon`` is a hidden systray icon, and ``colors`` is the ``colors`` return value of :meth:`image`. """ img, colors = image() ico = pystray.Icon( 'test', icon=img if not no_image else None, **kwargs) return ico, colors def image(width=64, height=64): """Generates an icon image. :return: the tuple ``(image, colors)``, where ``image`` is a *PIL* image and ``colors`` is a tuple containing the colours as *PIL* colour names, suitable for printing; the stringification of the tuple is also suitable for printing """ class Colors(tuple): def __str__(self): return ' and '.join(self) colors = Colors((next_color(), next_color())) img = Image.new('RGB', (width, height), colors[0]) dc = ImageDraw.Draw(img) dc.rectangle((width // 2, 0, width, height // 2), fill=colors[1]) dc.rectangle((0, height // 2, width // 2, height), fill=colors[1]) return img, colors def next_color(): """Returns the next colour to use. """ return next(COLORS) def confirm(self, statement, *fmt): """Asks the user to confirm a statement. :param self: An instance of a test suite. :param str statement: The statement to confirm. :raises AssertionError: if the user does not confirm """ valid_responses = ('yes', 'y', 'no', 'n') accept_responses = valid_responses[:2] message = ('\n' + statement % fmt) + ' ' while True: response = input(message) if response.lower() in valid_responses: self.assertIn( response.lower(), accept_responses, 'User declined statement "%s"' % message) return else: print( 'Please respond %s' % ', '.join( '"%s"' % r for r in valid_responses)) def true(*args): """Returns ``True``. """ return True pystray-0.19.5/tests/icon_tests.py000066400000000000000000000322101450160124200172000ustar00rootroot00000000000000# coding=utf-8 # pystray # Copyright (C) 2016-2022 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . import sys import unittest import pystray from six.moves import queue from six import reraise from time import sleep from pystray import Menu as menu, MenuItem as item from . import action, confirm, icon, image, say, separator, true #: The number of seconds to wait for interactive commands TIMEOUT = 10 def test(icon): """A decorator to mark an inner function as the actual test code. The decorated function will be run in a separate thread as the ``setup`` argument to :meth:`pystray.Icon.run`. This decorator actually runs the decorated method, and does not return anything. """ def inner(f): q = queue.Queue() def setup(icon): try: f() q.put(True) except: q.put(sys.exc_info()) finally: icon.visible = False icon.stop() icon.run(setup=setup) result = q.get() if result is not True: reraise(*result) return inner def for_default_action(test): """Prevents a test from being run on implementations not supporting default action on click. :param test: The test. """ if pystray.Icon.HAS_DEFAULT_ACTION: return test else: return lambda *a: None def for_menu(test): """Prevents a test from being run on implementations not supporting a menu. :param test: The test. """ if pystray.Icon.HAS_MENU: return test else: return lambda *a: None def for_menu_radio(test): """Prevents a test from being run on implementations not supporting mutually exclusive menu item groups. :param test: The test. """ if pystray.Icon.HAS_MENU_RADIO: return test else: return lambda *a: None def for_notification(test): """Prevents a test from being run on implementations not supporting notifications :param test: The test. """ if pystray.Icon.HAS_NOTIFICATION: return test else: return lambda *a: None class IconTest(unittest.TestCase): def test_set_icon(self): """Tests that updating the icon works. """ ico, colors1 = icon() original = ico.icon alternative, colors2 = image() @test(ico) def _(): ico.visible = True for i in range(8): ico.icon = (alternative, original)[i % 2] sleep(0.5) confirm( self, 'Did an alternating %s, and %s icon appear?', colors1, colors2) def test_set_icon_after_constructor(self): """Tests that updating the icon works. """ ico, colors1 = icon(no_image=True) alternative, colors2 = image() @test(ico) def _(): ico.icon = alternative ico.visible = True confirm( self, 'Did an icon appear?') def test_set_icon_to_none(self): """Tests that setting the icon to None hides it. """ ico, colors = icon() @test(ico) def _(): ico.visible = True sleep(1.0) ico.icon = None self.assertFalse(ico.visible) confirm( self, 'Did the %s icon disappear?', colors) def test_title(self): """Tests that initialising with a title works. """ title = 'pystray test icon' ico, colors = icon(title=title) @test(ico) def _(): ico.visible = True confirm( self, 'Did an %s icon with the title "%s" appear?', colors, title) def test_title_set_hidden(self): """Tests that setting the title of a hidden icon works. """ title = 'pystray test icon' ico, colors = icon(title='this is incorrect') @test(ico) def _(): ico.title = title ico.visible = True confirm( self, 'Did a %s icon with the title "%s" appear?', colors, title) def test_title_set_visible(self): """Tests that setting the title of a visible icon works. """ title = 'pystray test icon' ico, colors = icon(title='this is incorrect') @test(ico) def _(): ico.visible = True ico.title = title confirm( self, 'Did a %s icon with the title "%s" appear?', colors, title) def test_visible(self): """Tests that the ``visible`` attribute reflects the visibility. """ ico, colors = icon(title='this is incorrect') @test(ico) def _(): self.assertFalse(ico.visible) ico.visible = True self.assertTrue(ico.visible) def test_visible_set(self): """Tests that showing a simple icon works. """ ico, colors = icon() @test(ico) def _(): ico.visible = True confirm( self, 'Did a %s icon appear?', colors) def test_visible_set_no_icon(self): """Tests that setting the icon when none is set shows the icon. """ ico = pystray.Icon('test') @test(ico) def _(): try: with self.assertRaises(ValueError): ico.visible = True finally: ico.visible = False def test_show_hide(self): """Tests that showing and hiding the icon works. """ ico, colors = icon() @test(ico) def _(): for i in range(4): ico.visible = True sleep(0.5) ico.visible = False sleep(0.5) confirm( self, 'Did a flashing %s icon appear?', colors) @for_default_action def test_activate(self): """Tests that ``on_activate`` is correctly called. """ q = queue.Queue() def on_activate(icon): q.put(True) ico, colors = icon(menu=menu( action(on_activate),)) @test(ico) def _(): ico.visible = True say('Click the icon') q.get(timeout=TIMEOUT) def test_activate_with_default(self): """Tests that the default menu item is activated when activating icon. """ q = queue.Queue() def on_activate(icon): q.put(True) ico, colors = icon(menu=menu( item('Item 1', None), item('Default', on_activate, default=True))) @test(ico) def _(): ico.visible = True say('Click the icon or select the default menu item') q.get(timeout=TIMEOUT) @for_menu def test_menu_construct(self): """Tests that the menu is constructed. """ ico, colors = icon(menu=menu( item('Item 1', None), item('Item 2', None))) @test(ico) def _(): ico.visible = True say('Expand the popup menu') confirm( self, 'Was it\n%s?' % str(ico.menu)) @for_menu def test_menu_activate(self): """Tests that the menu can be activated. """ q = queue.Queue() def on_activate(): q.put(True) ico, colors = icon(menu=( item('Item 1', on_activate), item('Item 2', None))) @test(ico) def _(): ico.visible = True say('Click Item 1') q.get(timeout=TIMEOUT) @for_menu def test_menu_activate_method(self): """Tests that the menu can be activated and a method can be used. """ q = queue.Queue() class C: def on_activate(self): q.put(True) c = C() ico, colors = icon(menu=( item('Item 1', c.on_activate), item('Item 2', None))) @test(ico) def _(): ico.visible = True say('Click Item 1') q.get(timeout=TIMEOUT) @for_menu def test_menu_activate_submenu(self): """Tests that an item in a submenu can be activated. """ q = queue.Queue() def on_activate(): q.put(True) ico, colors = icon(menu=( item('Item 1', None), item('Submenu', menu( item('Item 2', None), item('Item 3', on_activate))))) @test(ico) def _(): ico.visible = True say('Click Item 3 in the submenu') q.get(timeout=TIMEOUT) @for_default_action def test_menu_invisble(self): """Tests that a menu consisting of only empty items does not show. """ q = queue.Queue() def on_activate(): q.put(True) ico, colors = icon(menu=menu( item('Item1', None, visible=False), item('Item2', on_activate, default=True, visible=False))) @test(ico) def _(): ico.visible = True say('Ensure that the menu does not show and then click the icon') q.get(timeout=TIMEOUT) @for_menu def test_menu_dynamic(self): """Tests that a dynamic menu works. """ q = queue.Queue() q.ticks = 0 def on_activate(): q.put(True) q.ticks += 1 ico, colors = icon(menu=menu( item('Item 1', on_activate), item('Item 2', None), item(lambda _:'Item ' + str(q.ticks + 3), None))) @test(ico) def _(): ico.visible = True say('Click Item 1') q.get(timeout=TIMEOUT) say('Expand the popup menu') confirm( self, 'Was it\n%s?' % str(ico.menu)) @for_default_action @for_menu def test_menu_dynamic_show_hide(self): """Tests that a dynamic menu that is hidden works as expected. """ q = queue.Queue() q.ticks = 0 def on_activate(): q.put(True) q.ticks += 1 def visible(menu_item): return q.ticks % 2 == 0 ico, colors = icon(menu=menu( item('Default', on_activate, default=True, visible=visible), item('Item 2', None, visible=visible))) @test(ico) def _(): ico.visible = True say('Click the icon or select the default menu item') q.get(timeout=TIMEOUT) say('Ensure that the menu does not show and then click the icon') q.get(timeout=TIMEOUT) say('Expand the popup menu') confirm( self, 'Was it\n%s?' % str(ico.menu)) @for_menu_radio def test_menu_radio(self): """Tests that mutually exclusive items are displayed separately. """ ico, colors = icon(menu=menu( item('Item 1', None, checked=true), item('Item 2', None, checked=true, radio=True))) @test(ico) def _(): ico.visible = True say('Expand the popup menu') confirm( self, 'Was displayed differently from ?') @for_menu_radio def test_menu_enabled(self): """Tests that menu items can be disabled. """ ico, colors = icon(menu=menu( item('Item 1', None, enabled=true), item('Item 2', None, enabled=False))) @test(ico) def _(): ico.visible = True say('Expand the popup menu') confirm( self, 'Was enabled and disabled?') @for_notification def test_show_notification(self): """Tests that generation of a notification works. """ ico, colors = icon() @test(ico) def _(): ico.notify(title='Title: Test', message='This is a message!') confirm( self, 'Did a notification appear?') @for_notification def test_hide_notification(self): """Tests that a notification can be removed again. """ ico, colors = icon() @test(ico) def _(): ico.notify(title='Title: Test', message='This is a message!') sleep(5.0) ico.remove_notification() confirm( self, 'Was the notification removed?') pystray-0.19.5/tests/menu_descriptor_tests.py000066400000000000000000000145121450160124200214570ustar00rootroot00000000000000# coding=utf-8 # pystray # Copyright (C) 2016-2022 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . import unittest import pystray from pystray import Menu as menu from pystray import MenuItem as item from . import separator, true class MenuDescriptorTests(unittest.TestCase): def test_item_name(self): """Tests that the text is set correctly. """ self.assertEqual( 'Test entry', item('Test entry', None).text) def test_item_call(self): """Tests that calling a menu item works as expected. """ data = [] item('', lambda: data.append(True))(None) self.assertEqual( [True], data) def test_item_call_various_args(self): """Tests that calling a menu item works as expected. """ item('', lambda: None)(None) item('', lambda a: a)(None) item('', lambda a, b: (a, b))(None) with self.assertRaises(ValueError): item('', lambda a, b, c: (a, b, )) def test_menu_construct(self): """Tests menu construction. """ self.assertEqual( ''' Test entry one Test entry two Test entry three Test entry four''', '\n' + str(menu( item('Test entry one', None), item('Test entry two', None), item('Test entry three', None), item('Test entry four', None)))) def test_menu_construct_from_generator(self): """Tests menu construction. """ self.assertEqual( ''' Test entry 1 Test entry 2 Test entry 3 Test entry 4''', '\n' + str(menu(lambda: ( item('Test entry %d' % (i + 1), None) for i in range(4))))) def test_menu_construct_from_none(self): """Tests menu construction. """ self.assertEqual( '', '\n' + str(menu(None))) def test_menu_construct_with_submenu(self): """Tests menu construction. """ self.assertEqual( ''' Test entry 1 Test entry 2 => Test entry 3 Test entry 4 Test entry 5''', '\n' + str(menu( item('Test entry 1', None), item('Test entry 2', menu( item('Test entry 3', None), item('Test entry 4', None))), item('Test entry 5', None)))) def test_menu_separator(self): """Tests menu construction with separators. """ # Separators at the head and tail are ignored self.assertEqual( ''' Test entry one - - - - Test entry two''', '\n' + str(menu( separator(), separator(), item('Test entry one', None), separator(), item('Test entry hidden', None, visible=False), separator(), item('Test entry two', None), separator(), separator()))) def test_menu_default_none(self): """Tests that an invalid number of default menu items fails. """ self.assertIsNone( menu( item('one', true, default=False), item('two', true, default=False))(None)) def test_menu_default_callable(self): """Tests that the default menu item is activated when calling the menu. """ self.assertEqual( 'test result', menu( item('one', lambda: 'test result', default=True))(None)) def test_menu_visible_submenu(self): """Tests that ``visible`` is correctly set when a submenu is set. """ self.assertTrue( item('Test', menu( item('Item', None)), visible=True).visible) self.assertFalse( item('Test', menu( item('Item', None)), visible=False).visible) self.assertFalse( item('Test', menu( item('Item', None, visible=False)), visible=True).visible) def test_menu_enabled_default(self): """Tests that a menu item is enabled by default. """ self.assertTrue( item( 'one', lambda: 'test result').enabled) def test_menu_enabled_callable(self): """Tests that the enabled state can be set. """ self.assertFalse( item( 'one', lambda: 'test result', enabled=False).enabled) def test_menu_checked_none(self): """Tests that not providing a value for ``default`` works. """ self.assertFalse( item('Test', None).checked) def test_menu_checked_non_callable(self): """Tests that not passing a callable as checked fails. """ with self.assertRaises(ValueError): item('Test', None, checked=False) def test_menu_checked_non_callable(self): """Tests that not providing a value for ``default`` works. """ self.assertTrue( item('Test', None, checked=true).checked) def test_menu_radio_uncheckable(self): """Tests that not providing a value for ``checked`` for uncheckable items works. """ self.assertFalse( item('Test', None).radio) self.assertFalse( item('Test', None, radio=False).radio) self.assertFalse( item('Test', None, radio=True).radio) def test_menu_radio_checkable(self): """Tests that providing a value for ``checked`` for checkable items works. """ self.assertFalse( item('Test', None, checked=true).radio) self.assertTrue( item('Test', None, checked=true, radio=True).radio) self.assertTrue( item('Test', None, checked=true, radio=true).radio) pystray-0.19.5/tools/000077500000000000000000000000001450160124200144545ustar00rootroot00000000000000pystray-0.19.5/tools/make-release.py000077500000000000000000000143621450160124200173720ustar00rootroot00000000000000#!/usr/bin/env python import os import re import subprocess import sys DESCRIPTION='''Makes a full release. This script will update the version number of the package and perform all steps necessary to make a full release. ''' ROOT = os.path.join( os.path.dirname(__file__), os.pardir) LIB_DIR = os.path.join(ROOT, 'lib') PACKAGE_NAME = next( name for name in os.listdir(LIB_DIR) if name[0] != '_') PACKAGE_DIR = os.path.join(LIB_DIR, PACKAGE_NAME) def main(version): assert_current_branch_is_clean() update_info(version) check_readme() check_release_notes(version) commit_changes(version) try: tag_release(version) except: commit_changes.undo() raise push_to_origin() upload_to_pypi() def assert_current_branch_is_clean(): """Asserts that the current branch contains no local changes. :raises RuntimeError: if the repository contains local changes """ try: git('diff-index', '--quiet', 'HEAD', '--') except RuntimeError as e: print(e.args[0] % e.args[1:]) raise RuntimeError('Your repository contains local changes') def update_info(version): """Updates the version information in ``._info.`` :param tuple version: The version to set. """ gsub( os.path.join(PACKAGE_DIR, '_info.py'), re.compile(r'__version__\s*=\s*(\([0-9]+(\s*,\s*[0-9]+)*\))'), 1, repr(version)) def check_readme(): """Verifies that the ``README`` is *reStructuredText* compliant. """ python('setup.py', 'check', '--restructuredtext', '--strict') def check_release_notes(version): """Displays the release notes and allows the user to cancel the release process. :param tuple version: The version that is being released. """ CHANGES = os.path.join(ROOT, 'CHANGES.rst') header = 'v%s' % '.'.join(str(v) for v in version) # Read the release notes found = False release_notes = [] with open(CHANGES) as f: for line in (l.strip() for l in f): if found: if not line: # Break on the first empty line after release notes break elif set(line) == {'-'}: # Ignore underline lines continue release_notes.append(line) elif line.startswith(header): # The release notes begin after the header found = True while True: # Display the release notes sys.stdout.write('Release notes for %s:\n' % header) sys.stdout.write( '\n'.join( ' %s' % release_note for release_note in release_notes) + '\n') sys.stdout.write('Is this correct [yes/no]? ') sys.stdout.flush() response = sys.stdin.readline().strip() if response in ('yes', 'y'): break elif response in ('no', 'n'): raise RuntimeError('Release notes are not up to date') def commit_changes(version): """Commits all local changes. :param tuple version: The version that is being released. """ git('commit', '-a', '-m', 'Release %s' % '.'.join(str(v) for v in version)) def _commit_changes_undo(): git('reset', '--hard', 'HEAD^') commit_changes.undo = _commit_changes_undo def tag_release(version): """Tags the current commit as a release. :param version: The version that is being released. :type version: tuple of version parts """ git('tag', '-a', '-m', 'Release %s' % '.'.join(str(v) for v in version), 'v' + '.'.join(str(v) for v in version)) def push_to_origin(): """Pushes master to origin. """ print('Pushing to origin...') git('push', 'origin', 'HEAD:master') git('push', '--tags') def upload_to_pypi(): """Uploads this project to PyPi. """ print('Uploading to PyPi...') python( os.path.join(ROOT, 'setup.py'), 'sdist', 'bdist_egg', 'bdist_wheel', 'upload') def git(*args): """Executes ``git`` with the command line arguments given. :param args: The arguments to ``git``. :return: stdout of ``git`` :raises RuntimeError: if ``git`` returns non-zero """ return command('git', *args) def python(*args): """Executes *Python* with the command line arguments given. The *Python* used is the one executing the current script. :param args: The arguments to *Python*. :return: stdout of *Python* :raises RuntimeError: if *Python* returns non-zero """ return command(sys.executable, *args) def gsub(path, regex, group, replacement): """Runs a regular expression on the contents of a file and replaces a group. :param str path: The path to the file. :param regex: The regular expression to use. :param int group: The group of the regular expression to replace. :param str replacement: The replacement string. """ with open(path) as f: data = f.read() def sub(match): full = match.group(0) o = match.start(0) return full[:match.start(group) - o] \ + replacement \ + full[match.end(group) - o:] with open(path, 'w') as f: f.write(regex.sub(sub, data)) def command(*args): """Executes a command. :param args: The command and arguments. :return: stdout of the command :raises RuntimeError: if the command returns non-zero """ g = subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = g.communicate() if g.returncode != 0: raise RuntimeError( 'Failed to execute <%s> (%d): %s', ' '.join(args), g.returncode, stderr) else: return stdout.decode('utf-8') if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument( 'version', type=lambda s: tuple(int(v) for v in s.split('.'))) try: main(**vars(parser.parse_args())) except Exception as e: try: sys.stderr.write(e.args[0] % e.args[1:] + '\n') except: sys.stderr.write('%s\n' % str(e)) sys.exit(1)