diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index bfd8a6c..8d7447c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -4,90 +4,90 @@ name: Build Executables # Does not handle packaging or publishing - that's the caller's responsibility. on: - workflow_call: - inputs: - version: - description: "Version string for the build" - required: true - type: string + workflow_call: + inputs: + version: + description: "Version string for the build" + required: true + type: string jobs: - build-windows: - if: github.repository_owner == 'synodic' - runs-on: windows-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Install PDM - uses: pdm-project/setup-pdm@v4 - with: - python-version: "3.14" - cache: true - - - name: Install dependencies - run: pdm install -G build - - - name: Build executable - run: pdm run pyinstaller tool/pyinstaller/synodic.spec --distpath dist - - - name: Upload build artifact - uses: actions/upload-artifact@v4 - with: - name: build-windows-x64 - path: dist/* - - build-linux: - if: github.repository_owner == 'synodic' - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Install system dependencies - run: | - sudo apt-get update - sudo apt-get install -y libxcb-cursor0 libxkbcommon-x11-0 - - - name: Install PDM - uses: pdm-project/setup-pdm@v4 - with: - python-version: "3.14" - cache: true - - - name: Install dependencies - run: pdm install -G build - - - name: Build executable - run: pdm run pyinstaller tool/pyinstaller/synodic.spec --distpath dist - - - name: Upload build artifact - uses: actions/upload-artifact@v4 - with: - name: build-linux-x64 - path: dist/* - - build-macos: - if: github.repository_owner == 'synodic' - runs-on: macos-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Install PDM - uses: pdm-project/setup-pdm@v4 - with: - python-version: "3.14" - cache: true - - - name: Install dependencies - run: pdm install -G build - - - name: Build executable - run: pdm run pyinstaller tool/pyinstaller/synodic.spec --distpath dist - - - name: Upload build artifact - uses: actions/upload-artifact@v4 - with: - name: build-macos-x64 - path: dist/* + build-windows: + if: github.repository_owner == 'synodic' + runs-on: windows-latest + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Install PDM + uses: pdm-project/setup-pdm@v4 + with: + python-version: "3.14" + cache: true + + - name: Install dependencies + run: pdm install -G build + + - name: Build executable + run: pdm run pyinstaller tool/pyinstaller/synodic.spec --distpath dist + + - name: Upload build artifact + uses: actions/upload-artifact@v4 + with: + name: build-windows-x64 + path: dist/* + + build-linux: + if: github.repository_owner == 'synodic' + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Install system dependencies + run: | + sudo apt-get update + sudo apt-get install -y libxcb-cursor0 libxkbcommon-x11-0 + + - name: Install PDM + uses: pdm-project/setup-pdm@v4 + with: + python-version: "3.14" + cache: true + + - name: Install dependencies + run: pdm install -G build + + - name: Build executable + run: pdm run pyinstaller tool/pyinstaller/synodic.spec --distpath dist + + - name: Upload build artifact + uses: actions/upload-artifact@v4 + with: + name: build-linux-x64 + path: dist/* + + build-macos: + if: github.repository_owner == 'synodic' + runs-on: macos-latest + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Install PDM + uses: pdm-project/setup-pdm@v4 + with: + python-version: "3.14" + cache: true + + - name: Install dependencies + run: pdm install -G build + + - name: Build executable + run: pdm run pyinstaller tool/pyinstaller/synodic.spec --distpath dist + + - name: Upload build artifact + uses: actions/upload-artifact@v4 + with: + name: build-macos-x64 + path: dist/* diff --git a/.github/workflows/dev-release-build.yml b/.github/workflows/dev-release-build.yml index 97061ff..fd2c02b 100644 --- a/.github/workflows/dev-release-build.yml +++ b/.github/workflows/dev-release-build.yml @@ -22,7 +22,7 @@ jobs: version: ${{ steps.set-version.outputs.version }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: fetch-depth: 0 filter: blob:none @@ -37,7 +37,7 @@ jobs: - name: Set Version id: set-version run: | - version=${{ steps.version.outputs.version }}.dev${{ github.run_number }} + version=${{ steps.version.outputs.version }}.dev${{ steps.version.outputs.increment }} echo "version=${version}" >> $GITHUB_OUTPUT echo "Development version: $version" diff --git a/LICENSE.md b/LICENSE.md index bc0390e..e1f5a8d 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,504 +1,842 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the 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 -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 - USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random - Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + 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. + +--- + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 08d0ed6..9a43476 100644 --- a/README.md +++ b/README.md @@ -5,3 +5,15 @@ An application frontend for [porringer](https://www.github.com/synodic/porringer ## Documentation See the [full documentation](https://synodic.github.io/synodic-client) for installation, usage, and development guides. + +## Development + +We use [pdm](https://pdm-project.org/en/latest/) as our build system and package manager. Scripts for development tasks are defined in `pyproject.toml` under the `[tool.pdm.scripts]` section. + +See [Development](https://synodic.github.io/porringer/development) for additional build, test, and installation instructions. + +For contribution guidelines, see [CONTRIBUTING.md](https://github.com/synodic/.github/blob/stable/CONTRIBUTING.md). + +## License + +This project is licensed under the [GNU Lesser General Public License v3.0 or later](LICENSE.md) (LGPL-3.0-or-later). diff --git a/data/icon.png b/data/icon.png index fcee3ea..0e08de8 100644 Binary files a/data/icon.png and b/data/icon.png differ diff --git a/docs/index.md b/docs/index.md index be92fbe..3ade33c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -26,7 +26,19 @@ pdm add synodic-client Launch the application: ```bash -synodic-client +synodic-c +``` + +Or with a `synodic://` URI: + +```bash +synodic-c "synodic://install?manifest=https://example.com/porringer.json" +``` + +Show the version: + +```bash +synodic-c --version ``` The application runs in the system tray. Right-click the tray icon to access: diff --git a/examples/python-bootstrap/README.md b/examples/python-bootstrap/README.md new file mode 100644 index 0000000..cebd53f --- /dev/null +++ b/examples/python-bootstrap/README.md @@ -0,0 +1,73 @@ +# Python Bootstrap Example + +[![Install with Porringer](https://img.shields.io/badge/Install_with-Porringer-blue)](synodic://install?manifest=https://raw.githubusercontent.com/synodic/porringer/development/examples/python-bootstrap/porringer.json) + +This example demonstrates using Porringer to bootstrap a complete Python +development environment from scratch — the same chain a developer would +follow manually. + +## Bootstrap Chain + +The manifest executes in **phased order**: + +1. **`runtimes.python`** → installs Python 3.14 via `pim` (Windows) or + `pyenv` (macOS / Linux). The resolved interpreter path is propagated + to all downstream phases. +2. **`packages.python`** → installs `pipx` into the current Python + environment via `pip` or `uv`. +3. **`tools.python`** → installs `pdm` as an isolated CLI tool via + `pipx`. The pipx backend is **deferred** at preview time — it becomes + available only after Phase 2 installs it. +4. **`post_sync`** → runs `pdm install` in the manifest directory, + creating the project virtualenv and installing all dependencies from + `pyproject.toml`. + +## Manifest Overview + +```text +runtimes.python ─► pim / pyenv ─► Python 3.14 +packages.python ─► pip / uv ─► pipx +tools.python ─► pipx ─► pdm (deferred resolution) +post_sync ─► pdm install (project sync) +``` + +## Usage + +### Preview what will happen + +```shell +porringer sync --path examples/python-bootstrap --dry-run +``` + +### Execute with confirmation + +```shell +porringer sync --path examples/python-bootstrap +``` + +### Execute without confirmation (non-interactive) + +```shell +porringer sync --path examples/python-bootstrap --yes +``` + +## How It Works + +Porringer's execution engine splits `PACKAGE`-type actions into sub-phases: + +- **Phase 1 (Runtime):** Runtime providers (pim / pyenv) run first. The + resolved interpreter is forwarded to all `RuntimeConsumer` plugins so + that subsequent pip / uv commands target the correct Python. +- **Phase 2a (Package):** Regular package installs (pip / uv). This is + where pipx gets installed. +- **Phase 2b (Tool):** After Phase 2a the engine **re-discovers** + available plugins. Pipx is now on PATH, so the `tools.python` section + resolves to the pipx backend and pdm is installed. +- **Phase 3 (Project Sync):** Project-environment plugins (pdm, uv, + poetry) run their native sync / install command. +- **Phase 4 (Post-sync):** Arbitrary shell commands execute in the + manifest directory. + +If a tool backend is not available at preview time (e.g. pipx is not yet +installed), the action is created with a *deferred* installer. Resolution +happens just before Phase 2b, after packages have been installed. diff --git a/examples/python-bootstrap/porringer.json b/examples/python-bootstrap/porringer.json new file mode 100644 index 0000000..c56b8c2 --- /dev/null +++ b/examples/python-bootstrap/porringer.json @@ -0,0 +1,31 @@ +{ + "version": "1", + "name": "Python Bootstrap", + "description": "Bootstrap a complete Python development environment from scratch", + "author": "Synodic Software", + "url": "https://github.com/synodic/porringer", + "runtimes": { + "python": [ + "3.14" + ] + }, + "packages": { + "python": [ + { + "name": "pipx", + "description": "Install and run Python applications in isolated environments" + } + ] + }, + "tools": { + "python": [ + { + "name": "pdm", + "description": "Python package and dependency manager" + } + ] + }, + "post_sync": [ + "pdm install" + ] +} \ No newline at end of file diff --git a/pdm.lock b/pdm.lock index 0af3cef..8f26156 100644 --- a/pdm.lock +++ b/pdm.lock @@ -5,7 +5,7 @@ groups = ["default", "build", "lint", "test"] strategy = ["inherit_metadata"] lock_version = "4.5.0" -content_hash = "sha256:5cdbfc993ab725406e4f5a48caf2ef54f3ce085cf0e1f8b984139d9faaea4108" +content_hash = "sha256:f6af68110df7ee9fd0c1d4ac8ee45a8508c86aecbfa33d9f022ed5c7be3ac66b" [[metadata.targets]] requires_python = ">=3.14,<3.15" @@ -20,6 +20,17 @@ files = [ {file = "altgraph-0.17.5.tar.gz", hash = "sha256:c87b395dd12fabde9c99573a9749d67da8d29ef9de0125c7f536699b4a9bc9e7"}, ] +[[package]] +name = "annotated-doc" +version = "0.0.4" +requires_python = ">=3.8" +summary = "Document parameters, class attributes, return types, and variables inline, with Annotated." +groups = ["default"] +files = [ + {file = "annotated_doc-0.0.4-py3-none-any.whl", hash = "sha256:571ac1dc6991c450b25a9c2d84a3705e2ae7a53467b5d111c24fa8baabbed320"}, + {file = "annotated_doc-0.0.4.tar.gz", hash = "sha256:fbcda96e87e9c92ad167c2e53839e57503ecfda18804ea28102353485033faa4"}, +] + [[package]] name = "annotated-types" version = "0.7.0" @@ -34,6 +45,17 @@ files = [ {file = "annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89"}, ] +[[package]] +name = "certifi" +version = "2026.1.4" +requires_python = ">=3.7" +summary = "Python package for providing Mozilla's CA Bundle." +groups = ["default"] +files = [ + {file = "certifi-2026.1.4-py3-none-any.whl", hash = "sha256:9943707519e4add1115f44c2bc244f782c0249876bf51b6599fee1ffbedd685c"}, + {file = "certifi-2026.1.4.tar.gz", hash = "sha256:ac726dd470482006e014ad384921ed6438c457018f4b3d204aea4281258b2120"}, +] + [[package]] name = "click" version = "8.3.1" @@ -139,6 +161,20 @@ files = [ {file = "coverage-7.13.2.tar.gz", hash = "sha256:044c6951ec37146b72a50cc81ef02217d27d4c3640efd2640311393cbbf143d3"}, ] +[[package]] +name = "httpx" +version = "1.0.dev3" +requires_python = ">=3.10" +summary = "HTTP, for Python." +groups = ["default"] +dependencies = [ + "certifi", +] +files = [ + {file = "httpx-1.0.dev3-py3-none-any.whl", hash = "sha256:80b33db1bc8e1fac2a15f419839e324d472d528822608ea6b7a93fed2011722d"}, + {file = "httpx-1.0.dev3.tar.gz", hash = "sha256:e95700e4f9cf6430295f4c195f9cb0ca0549bab4294927f8002bf196851d40db"}, +] + [[package]] name = "iniconfig" version = "2.3.0" @@ -236,20 +272,21 @@ files = [ [[package]] name = "porringer" -version = "0.1.1.dev12" +version = "0.2.1.dev19" requires_python = ">=3.14" summary = "" groups = ["default"] dependencies = [ - "packaging>=25.0", + "httpx>=0.28.1", + "packaging>=26.0", "platformdirs>=4.5.1", "pydantic>=2.12.5", "typer[all]>=0.21.1", "userpath>=1.9.2", ] files = [ - {file = "porringer-0.1.1.dev12-py3-none-any.whl", hash = "sha256:da817f50f3350b347cea37d446c0881f5d7b390ec0e785f319ee55eb2922fb9e"}, - {file = "porringer-0.1.1.dev12.tar.gz", hash = "sha256:ca2cf24f82868ba2401d0a5325ae099350b91e0787bc6cb58f258d66c6fbce77"}, + {file = "porringer-0.2.1.dev19-py3-none-any.whl", hash = "sha256:271d0707b3270d1c23cc5429cb4e5595b6b2e471aab9b1514eeb81976691ce10"}, + {file = "porringer-0.2.1.dev19.tar.gz", hash = "sha256:f00b7fe87bd23581c564fb7e9051cfcfae8aa0474a41017cf7261ed345d8fd42"}, ] [[package]] @@ -323,7 +360,7 @@ files = [ [[package]] name = "pyinstaller" -version = "6.18.0" +version = "6.19.0" requires_python = "<3.15,>=3.8" summary = "PyInstaller bundles a Python application and all its dependencies into a single package." groups = ["build"] @@ -333,23 +370,23 @@ dependencies = [ "macholib>=1.8; sys_platform == \"darwin\"", "packaging>=22.0", "pefile>=2022.5.30; sys_platform == \"win32\"", - "pyinstaller-hooks-contrib>=2025.9", + "pyinstaller-hooks-contrib>=2026.0", "pywin32-ctypes>=0.2.1; sys_platform == \"win32\"", "setuptools>=42.0.0", ] files = [ - {file = "pyinstaller-6.18.0-py3-none-macosx_10_13_universal2.whl", hash = "sha256:cb7aa5a71bfa7c0af17a4a4e21855663c89e4bd7c40f1d337c8370636d8847c3"}, - {file = "pyinstaller-6.18.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:07785459b3bf8a48889eac0b4d0667ade84aef8930ce030bc7cbb32f41283b33"}, - {file = "pyinstaller-6.18.0-py3-none-manylinux2014_i686.whl", hash = "sha256:f998675b7ccb2dabbb1dc2d6f18af61d55428ad6d38e6c4d700417411b697d37"}, - {file = "pyinstaller-6.18.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:779817a0cf69604cddcdb5be1fd4959dc2ce048d6355c73e5da97884df2f3387"}, - {file = "pyinstaller-6.18.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:31b5d109f8405be0b7cddcede43e7b074792bc9a5bbd54ec000a3e779183c2af"}, - {file = "pyinstaller-6.18.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:4328c9837f1aef4fe1a127d4ff1b09a12ce53c827ce87c94117628b0e1fd098b"}, - {file = "pyinstaller-6.18.0-py3-none-musllinux_1_1_aarch64.whl", hash = "sha256:3638fc81eb948e5e5eab1d4ad8f216e3fec6d4a350648304f0adb227b746ee5e"}, - {file = "pyinstaller-6.18.0-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:8fbe59da34269e637f97fd3c43024f764586fc319141d245ff1a2e9af1036aa3"}, - {file = "pyinstaller-6.18.0-py3-none-win32.whl", hash = "sha256:496205e4fa92ec944f9696eb597962a83aef4d4c3479abfab83d730e1edf016b"}, - {file = "pyinstaller-6.18.0-py3-none-win_amd64.whl", hash = "sha256:976fabd90ecfbda47571c87055ad73413ec615ff7dea35e12a4304174de78de9"}, - {file = "pyinstaller-6.18.0-py3-none-win_arm64.whl", hash = "sha256:dba4b70e3c9ba09aab51152c72a08e58a751851548f77ad35944d32a300c8381"}, - {file = "pyinstaller-6.18.0.tar.gz", hash = "sha256:cdc507542783511cad4856fce582fdc37e9f29665ca596889c663c83ec8c6ec9"}, + {file = "pyinstaller-6.19.0-py3-none-macosx_10_13_universal2.whl", hash = "sha256:4190e76b74f0c4b5c5f11ac360928cd2e36ec8e3194d437bf6b8648c7bc0c134"}, + {file = "pyinstaller-6.19.0-py3-none-manylinux2014_aarch64.whl", hash = "sha256:8bd68abd812d8a6ba33b9f1810e91fee0f325969733721b78151f0065319ca11"}, + {file = "pyinstaller-6.19.0-py3-none-manylinux2014_i686.whl", hash = "sha256:1ec54ef967996ca61dacba676227e2b23219878ccce5ee9d6f3aada7b8ed8abf"}, + {file = "pyinstaller-6.19.0-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:4ab2bb52e58448e14ddf9450601bdedd66800465043501c1d8f1cab87b60b122"}, + {file = "pyinstaller-6.19.0-py3-none-manylinux2014_s390x.whl", hash = "sha256:da6d5c6391ccefe73554b9fa29b86001c8e378e0f20c2a4004f836ba537eff63"}, + {file = "pyinstaller-6.19.0-py3-none-manylinux2014_x86_64.whl", hash = "sha256:a0fc5f6b3c55aa54353f0c74ffa59b1115433c1850c6f655d62b461a2ed6cbbe"}, + {file = "pyinstaller-6.19.0-py3-none-musllinux_1_1_aarch64.whl", hash = "sha256:e649ba6bd1b0b89b210ad92adb5fbdc8a42dd2c5ca4f72ef3a0bfec83a424b83"}, + {file = "pyinstaller-6.19.0-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:481a909c8e60c8692fc60fcb1344d984b44b943f8bc9682f2fcdae305ad297e6"}, + {file = "pyinstaller-6.19.0-py3-none-win32.whl", hash = "sha256:3c5c251054fe4cfaa04c34a363dcfbf811545438cb7198304cd444756bc2edd2"}, + {file = "pyinstaller-6.19.0-py3-none-win_amd64.whl", hash = "sha256:b5bb6536c6560330d364d91522250f254b107cf69129d9cbcd0e6727c570be33"}, + {file = "pyinstaller-6.19.0-py3-none-win_arm64.whl", hash = "sha256:c2d5a539b0bfe6159d5522c8c70e1c0e487f22c2badae0f97d45246223b798ea"}, + {file = "pyinstaller-6.19.0.tar.gz", hash = "sha256:ec73aeb8bd9b7f2f1240d328a4542e90b3c6e6fbc106014778431c616592a865"}, ] [[package]] @@ -370,74 +407,74 @@ files = [ [[package]] name = "pyrefly" -version = "0.50.1" +version = "0.52.0" requires_python = ">=3.8" summary = "A fast type checker and language server for Python with powerful IDE features" groups = ["lint"] files = [ - {file = "pyrefly-0.50.1-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:16ea4052b3df75206f5677a87ca7ee6c4c3a92b086081250206e98c60d85e7a8"}, - {file = "pyrefly-0.50.1-py3-none-macosx_11_0_arm64.whl", hash = "sha256:aac15d38f3ad548b2cd50a7fc054241743e32753a32872fe5d4bb88982d29b35"}, - {file = "pyrefly-0.50.1-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:603c4f7893eba4f8472523cfceb41f200a30ae89c0af90f4ba03de4eebf9732b"}, - {file = "pyrefly-0.50.1-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2d2408be4b1f618ef80855042d6a3599128546a067654878002e34fdd56bfc54"}, - {file = "pyrefly-0.50.1-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9483e700ec0e156b249c2805896833c1393eda787f0b83ab430084c2723fec7e"}, - {file = "pyrefly-0.50.1-py3-none-win32.whl", hash = "sha256:68ff5eac338bfc74469f67ff79cc3500e826b51a753bba349ac2cfcb5705b32b"}, - {file = "pyrefly-0.50.1-py3-none-win_amd64.whl", hash = "sha256:ef9b5644cfef560fefe3e5093a78128f17d8d055eb01c5306e88644063c37a38"}, - {file = "pyrefly-0.50.1-py3-none-win_arm64.whl", hash = "sha256:b813120b2de86122933c424ebdb8e905e13191e72fca6403ea75ca94154eb898"}, - {file = "pyrefly-0.50.1.tar.gz", hash = "sha256:1859f36fb1dc4a903ba2298442c224dfadcda7fce5691aebd6bbc21c5f703299"}, + {file = "pyrefly-0.52.0-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:90d7bf2fb812ee3a920a962da2aa2387e2f4109c62604e5be1a736046a3260c7"}, + {file = "pyrefly-0.52.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:848764fdbc474fd36412d7ccf230d13a12ab3b2c28968124d9e9d51df79b7b8e"}, + {file = "pyrefly-0.52.0-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:43b712830df1247798fb79f478a236b0ffbe5983bdde5eb2f5b99a9411e09f35"}, + {file = "pyrefly-0.52.0-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:baa4130c460ad7c8d7efcff9017b7bc74c71736c5959ebfc2b7e405c2ce07d5d"}, + {file = "pyrefly-0.52.0-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3297751b1b13ecb582af48c8798e0b652c41c33a7e4ed72676164b29561655f6"}, + {file = "pyrefly-0.52.0-py3-none-win32.whl", hash = "sha256:d24ed11ef5eab93625df0bb4e67f7f946208b2b0ed4359b78f69cabbc6f78e3d"}, + {file = "pyrefly-0.52.0-py3-none-win_amd64.whl", hash = "sha256:0e5bee368fbdce6430b7672304bc4e36f11bc3b72ad067cbfde934d380701a3b"}, + {file = "pyrefly-0.52.0-py3-none-win_arm64.whl", hash = "sha256:8cabc07740e90c0baea12a1e7c48d6422130a19331033e8d9a16dd63e7e90db0"}, + {file = "pyrefly-0.52.0.tar.gz", hash = "sha256:abe022b68e67a2fd9adad4f8fe2deced2a786df32601b0eecbb00b40ea1f3b93"}, ] [[package]] name = "pyside6" -version = "6.10.1" +version = "6.10.2" requires_python = "<3.15,>=3.9" summary = "Python bindings for the Qt cross-platform application and UI framework" groups = ["default"] dependencies = [ - "PySide6-Addons==6.10.1", - "PySide6-Essentials==6.10.1", - "shiboken6==6.10.1", + "PySide6-Addons==6.10.2", + "PySide6-Essentials==6.10.2", + "shiboken6==6.10.2", ] files = [ - {file = "pyside6-6.10.1-cp39-abi3-macosx_13_0_universal2.whl", hash = "sha256:d0e70dd0e126d01986f357c2a555722f9462cf8a942bf2ce180baf69f468e516"}, - {file = "pyside6-6.10.1-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:4053bf51ba2c2cb20e1005edd469997976a02cec009f7c46356a0b65c137f1fa"}, - {file = "pyside6-6.10.1-cp39-abi3-manylinux_2_39_aarch64.whl", hash = "sha256:7d3ca20a40139ca5324a7864f1d91cdf2ff237e11bd16354a42670f2a4eeb13c"}, - {file = "pyside6-6.10.1-cp39-abi3-win_amd64.whl", hash = "sha256:9f89ff994f774420eaa38cec6422fddd5356611d8481774820befd6f3bb84c9e"}, - {file = "pyside6-6.10.1-cp39-abi3-win_arm64.whl", hash = "sha256:9c5c1d94387d1a32a6fae25348097918ef413b87dfa3767c46f737c6d48ae437"}, + {file = "pyside6-6.10.2-cp39-abi3-macosx_13_0_universal2.whl", hash = "sha256:4b084293caa7845d0064aaf6af258e0f7caae03a14a33537d0a552131afddaf0"}, + {file = "pyside6-6.10.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:1b89ce8558d4b4f35b85bff1db90d680912e4d3ce9e79ff804d6fef1d1a151ef"}, + {file = "pyside6-6.10.2-cp39-abi3-manylinux_2_39_aarch64.whl", hash = "sha256:0439f5e9b10ebe6177981bac9e219096ec970ac6ec215bef055279802ba50601"}, + {file = "pyside6-6.10.2-cp39-abi3-win_amd64.whl", hash = "sha256:032bad6b18a17fcbf4dddd0397f49b07f8aae7f1a45b7e4de7037bf7fd6e0edf"}, + {file = "pyside6-6.10.2-cp39-abi3-win_arm64.whl", hash = "sha256:65a59ad0bc92525639e3268d590948ce07a80ee97b55e7a9200db41d493cac31"}, ] [[package]] name = "pyside6-addons" -version = "6.10.1" +version = "6.10.2" requires_python = "<3.15,>=3.9" summary = "Python bindings for the Qt cross-platform application and UI framework (Addons)" groups = ["default"] dependencies = [ - "PySide6-Essentials==6.10.1", - "shiboken6==6.10.1", + "PySide6-Essentials==6.10.2", + "shiboken6==6.10.2", ] files = [ - {file = "pyside6_addons-6.10.1-cp39-abi3-macosx_13_0_universal2.whl", hash = "sha256:4d2b82bbf9b861134845803837011e5f9ac7d33661b216805273cf0c6d0f8e82"}, - {file = "pyside6_addons-6.10.1-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:330c229b58d30083a7b99ed22e118eb4f4126408429816a4044ccd0438ae81b4"}, - {file = "pyside6_addons-6.10.1-cp39-abi3-manylinux_2_39_aarch64.whl", hash = "sha256:56864b5fecd6924187a2d0f7e98d968ed72b6cc267caa5b294cd7e88fff4e54c"}, - {file = "pyside6_addons-6.10.1-cp39-abi3-win_amd64.whl", hash = "sha256:b6e249d15407dd33d6a2ffabd9dc6d7a8ab8c95d05f16a71dad4d07781c76341"}, - {file = "pyside6_addons-6.10.1-cp39-abi3-win_arm64.whl", hash = "sha256:0de303c0447326cdc6c8be5ab066ef581e2d0baf22560c9362d41b8304fdf2db"}, + {file = "pyside6_addons-6.10.2-cp39-abi3-macosx_13_0_universal2.whl", hash = "sha256:0de7d0c9535e17d5e3b634b61314a1867f3b0f6d35c3d7cdc99efc353192faff"}, + {file = "pyside6_addons-6.10.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:030a851163b51dbf0063be59e9ddb6a9e760bde89a28e461ccc81a224d286eaf"}, + {file = "pyside6_addons-6.10.2-cp39-abi3-manylinux_2_39_aarch64.whl", hash = "sha256:fcee0373e3fd7b98f014094e5e37b4a39e4de7c5a47c13f654a7d557d4a426ad"}, + {file = "pyside6_addons-6.10.2-cp39-abi3-win_amd64.whl", hash = "sha256:c20150068525a17494f3b6576c5d61c417cf9a5870659e29f5ebd83cd20a78ea"}, + {file = "pyside6_addons-6.10.2-cp39-abi3-win_arm64.whl", hash = "sha256:3d18db739b46946ba7b722d8ad4cc2097135033aa6ea57076e64d591e6a345f3"}, ] [[package]] name = "pyside6-essentials" -version = "6.10.1" +version = "6.10.2" requires_python = "<3.15,>=3.9" summary = "Python bindings for the Qt cross-platform application and UI framework (Essentials)" groups = ["default"] dependencies = [ - "shiboken6==6.10.1", + "shiboken6==6.10.2", ] files = [ - {file = "pyside6_essentials-6.10.1-cp39-abi3-macosx_13_0_universal2.whl", hash = "sha256:cd224aff3bb26ff1fca32c050e1c4d0bd9f951a96219d40d5f3d0128485b0bbe"}, - {file = "pyside6_essentials-6.10.1-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:e9ccbfb58c03911a0bce1f2198605b02d4b5ca6276bfc0cbcf7c6f6393ffb856"}, - {file = "pyside6_essentials-6.10.1-cp39-abi3-manylinux_2_39_aarch64.whl", hash = "sha256:ec8617c9b143b0c19ba1cc5a7e98c538e4143795480cb152aee47802c18dc5d2"}, - {file = "pyside6_essentials-6.10.1-cp39-abi3-win_amd64.whl", hash = "sha256:9555a48e8f0acf63fc6a23c250808db841b28a66ed6ad89ee0e4df7628752674"}, - {file = "pyside6_essentials-6.10.1-cp39-abi3-win_arm64.whl", hash = "sha256:4d1d248644f1778f8ddae5da714ca0f5a150a5e6f602af2765a7d21b876da05c"}, + {file = "pyside6_essentials-6.10.2-cp39-abi3-macosx_13_0_universal2.whl", hash = "sha256:1dee2cb9803ff135f881dadeb5c0edcef793d1ec4f8a9140a1348cecb71074e1"}, + {file = "pyside6_essentials-6.10.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:660aea45bfa36f1e06f799b934c2a7df963bd31abc5083e8bb8a5bfaef45686b"}, + {file = "pyside6_essentials-6.10.2-cp39-abi3-manylinux_2_39_aarch64.whl", hash = "sha256:c2b028e4c6f8047a02c31f373408e23b4eedfd405f56c6aba8d0525c29472835"}, + {file = "pyside6_essentials-6.10.2-cp39-abi3-win_amd64.whl", hash = "sha256:0741018c2b6395038cad4c41775cfae3f13a409e87995ac9f7d89e5b1fb6b22a"}, + {file = "pyside6_essentials-6.10.2-cp39-abi3-win_arm64.whl", hash = "sha256:db5f4913648bb6afddb8b347edae151ee2378f12bceb03c8b2515a530a4b38d9"}, ] [[package]] @@ -504,7 +541,7 @@ files = [ [[package]] name = "rich" -version = "14.3.1" +version = "14.3.2" requires_python = ">=3.8.0" summary = "Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal" groups = ["default"] @@ -513,36 +550,35 @@ dependencies = [ "pygments<3.0.0,>=2.13.0", ] files = [ - {file = "rich-14.3.1-py3-none-any.whl", hash = "sha256:da750b1aebbff0b372557426fb3f35ba56de8ef954b3190315eb64076d6fb54e"}, - {file = "rich-14.3.1.tar.gz", hash = "sha256:b8c5f568a3a749f9290ec6bddedf835cec33696bfc1e48bcfecb276c7386e4b8"}, + {file = "rich-14.3.2-py3-none-any.whl", hash = "sha256:08e67c3e90884651da3239ea668222d19bea7b589149d8014a21c633420dbb69"}, + {file = "rich-14.3.2.tar.gz", hash = "sha256:e712f11c1a562a11843306f5ed999475f09ac31ffb64281f73ab29ffdda8b3b8"}, ] [[package]] name = "ruff" -version = "0.14.14" +version = "0.15.1" requires_python = ">=3.7" summary = "An extremely fast Python linter and code formatter, written in Rust." groups = ["lint"] files = [ - {file = "ruff-0.14.14-py3-none-linux_armv6l.whl", hash = "sha256:7cfe36b56e8489dee8fbc777c61959f60ec0f1f11817e8f2415f429552846aed"}, - {file = "ruff-0.14.14-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:6006a0082336e7920b9573ef8a7f52eec837add1265cc74e04ea8a4368cd704c"}, - {file = "ruff-0.14.14-py3-none-macosx_11_0_arm64.whl", hash = "sha256:026c1d25996818f0bf498636686199d9bd0d9d6341c9c2c3b62e2a0198b758de"}, - {file = "ruff-0.14.14-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f666445819d31210b71e0a6d1c01e24447a20b85458eea25a25fe8142210ae0e"}, - {file = "ruff-0.14.14-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:3c0f18b922c6d2ff9a5e6c3ee16259adc513ca775bcf82c67ebab7cbd9da5bc8"}, - {file = "ruff-0.14.14-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1629e67489c2dea43e8658c3dba659edbfd87361624b4040d1df04c9740ae906"}, - {file = "ruff-0.14.14-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:27493a2131ea0f899057d49d303e4292b2cae2bb57253c1ed1f256fbcd1da480"}, - {file = "ruff-0.14.14-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:01ff589aab3f5b539e35db38425da31a57521efd1e4ad1ae08fc34dbe30bd7df"}, - {file = "ruff-0.14.14-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1cc12d74eef0f29f51775f5b755913eb523546b88e2d733e1d701fe65144e89b"}, - {file = "ruff-0.14.14-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bb8481604b7a9e75eff53772496201690ce2687067e038b3cc31aaf16aa0b974"}, - {file = "ruff-0.14.14-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:14649acb1cf7b5d2d283ebd2f58d56b75836ed8c6f329664fa91cdea19e76e66"}, - {file = "ruff-0.14.14-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:e8058d2145566510790eab4e2fad186002e288dec5e0d343a92fe7b0bc1b3e13"}, - {file = "ruff-0.14.14-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:e651e977a79e4c758eb807f0481d673a67ffe53cfa92209781dfa3a996cf8412"}, - {file = "ruff-0.14.14-py3-none-musllinux_1_2_i686.whl", hash = "sha256:cc8b22da8d9d6fdd844a68ae937e2a0adf9b16514e9a97cc60355e2d4b219fc3"}, - {file = "ruff-0.14.14-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:16bc890fb4cc9781bb05beb5ab4cd51be9e7cb376bf1dd3580512b24eb3fda2b"}, - {file = "ruff-0.14.14-py3-none-win32.whl", hash = "sha256:b530c191970b143375b6a68e6f743800b2b786bbcf03a7965b06c4bf04568167"}, - {file = "ruff-0.14.14-py3-none-win_amd64.whl", hash = "sha256:3dde1435e6b6fe5b66506c1dff67a421d0b7f6488d466f651c07f4cab3bf20fd"}, - {file = "ruff-0.14.14-py3-none-win_arm64.whl", hash = "sha256:56e6981a98b13a32236a72a8da421d7839221fa308b223b9283312312e5ac76c"}, - {file = "ruff-0.14.14.tar.gz", hash = "sha256:2d0f819c9a90205f3a867dbbd0be083bee9912e170fd7d9704cc8ae45824896b"}, + {file = "ruff-0.15.1-py3-none-linux_armv6l.whl", hash = "sha256:b101ed7cf4615bda6ffe65bdb59f964e9f4a0d3f85cbf0e54f0ab76d7b90228a"}, + {file = "ruff-0.15.1-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:939c995e9277e63ea632cc8d3fae17aa758526f49a9a850d2e7e758bfef46602"}, + {file = "ruff-0.15.1-py3-none-macosx_11_0_arm64.whl", hash = "sha256:1d83466455fdefe60b8d9c8df81d3c1bbb2115cede53549d3b522ce2bc703899"}, + {file = "ruff-0.15.1-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a9457e3c3291024866222b96108ab2d8265b477e5b1534c7ddb1810904858d16"}, + {file = "ruff-0.15.1-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:92c92b003e9d4f7fbd33b1867bb15a1b785b1735069108dfc23821ba045b29bc"}, + {file = "ruff-0.15.1-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1fe5c41ab43e3a06778844c586251eb5a510f67125427625f9eb2b9526535779"}, + {file = "ruff-0.15.1-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:66a6dd6df4d80dc382c6484f8ce1bcceb55c32e9f27a8b94c32f6c7331bf14fb"}, + {file = "ruff-0.15.1-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6a4a42cbb8af0bda9bcd7606b064d7c0bc311a88d141d02f78920be6acb5aa83"}, + {file = "ruff-0.15.1-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4ab064052c31dddada35079901592dfba2e05f5b1e43af3954aafcbc1096a5b2"}, + {file = "ruff-0.15.1-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:5631c940fe9fe91f817a4c2ea4e81f47bee3ca4aa646134a24374f3c19ad9454"}, + {file = "ruff-0.15.1-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:68138a4ba184b4691ccdc39f7795c66b3c68160c586519e7e8444cf5a53e1b4c"}, + {file = "ruff-0.15.1-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:518f9af03bfc33c03bdb4cb63fabc935341bb7f54af500f92ac309ecfbba6330"}, + {file = "ruff-0.15.1-py3-none-musllinux_1_2_i686.whl", hash = "sha256:da79f4d6a826caaea95de0237a67e33b81e6ec2e25fc7e1993a4015dffca7c61"}, + {file = "ruff-0.15.1-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:3dd86dccb83cd7d4dcfac303ffc277e6048600dfc22e38158afa208e8bf94a1f"}, + {file = "ruff-0.15.1-py3-none-win32.whl", hash = "sha256:660975d9cb49b5d5278b12b03bb9951d554543a90b74ed5d366b20e2c57c2098"}, + {file = "ruff-0.15.1-py3-none-win_amd64.whl", hash = "sha256:c820fef9dd5d4172a6570e5721704a96c6679b80cf7be41659ed439653f62336"}, + {file = "ruff-0.15.1-py3-none-win_arm64.whl", hash = "sha256:5ff7d5f0f88567850f45081fac8f4ec212be8d0b963e385c3f7d0d2eb4899416"}, + {file = "ruff-0.15.1.tar.gz", hash = "sha256:c590fe13fb57c97141ae975c03a1aedb3d3156030cabd740d6ff0b0d601e203f"}, ] [[package]] @@ -569,48 +605,48 @@ files = [ [[package]] name = "shiboken6" -version = "6.10.1" +version = "6.10.2" requires_python = "<3.15,>=3.9" summary = "Python/C++ bindings helper module" groups = ["default"] files = [ - {file = "shiboken6-6.10.1-cp39-abi3-macosx_13_0_universal2.whl", hash = "sha256:9f2990f5b61b0b68ecadcd896ab4441f2cb097eef7797ecc40584107d9850d71"}, - {file = "shiboken6-6.10.1-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:f4221a52dfb81f24a0d20cc4f8981cb6edd810d5a9fb28287ce10d342573a0e4"}, - {file = "shiboken6-6.10.1-cp39-abi3-manylinux_2_39_aarch64.whl", hash = "sha256:c095b00f4d6bf578c0b2464bb4e264b351a99345374478570f69e2e679a2a1d0"}, - {file = "shiboken6-6.10.1-cp39-abi3-win_amd64.whl", hash = "sha256:c1601d3cda1fa32779b141663873741b54e797cb0328458d7466281f117b0a4e"}, - {file = "shiboken6-6.10.1-cp39-abi3-win_arm64.whl", hash = "sha256:5cf800917008587b551005a45add2d485cca66f5f7ecd5b320e9954e40448cc9"}, + {file = "shiboken6-6.10.2-cp39-abi3-macosx_13_0_universal2.whl", hash = "sha256:3bd4e94e9a3c8c1fa8362fd752d399ef39265d5264e4e37bae61cdaa2a00c8c7"}, + {file = "shiboken6-6.10.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:ace0790032d9cb0adda644b94ee28d59410180d9773643bb6cf8438c361987ad"}, + {file = "shiboken6-6.10.2-cp39-abi3-manylinux_2_39_aarch64.whl", hash = "sha256:f74d3ed1f92658077d0630c39e694eb043aeb1d830a5d275176c45d07147427f"}, + {file = "shiboken6-6.10.2-cp39-abi3-win_amd64.whl", hash = "sha256:10f3c8c5e1b8bee779346f21c10dbc14cff068f0b0b4e62420c82a6bf36ac2e7"}, + {file = "shiboken6-6.10.2-cp39-abi3-win_arm64.whl", hash = "sha256:20c671645d70835af212ee05df60361d734c5305edb2746e9875c6a31283f963"}, ] [[package]] name = "typer" -version = "0.21.1" +version = "0.23.1" requires_python = ">=3.9" summary = "Typer, build great CLIs. Easy to code. Based on Python type hints." groups = ["default"] dependencies = [ + "annotated-doc>=0.0.2", "click>=8.0.0", "rich>=10.11.0", "shellingham>=1.3.0", - "typing-extensions>=3.7.4.3", ] files = [ - {file = "typer-0.21.1-py3-none-any.whl", hash = "sha256:7985e89081c636b88d172c2ee0cfe33c253160994d47bdfdc302defd7d1f1d01"}, - {file = "typer-0.21.1.tar.gz", hash = "sha256:ea835607cd752343b6b2b7ce676893e5a0324082268b48f27aa058bdb7d2145d"}, + {file = "typer-0.23.1-py3-none-any.whl", hash = "sha256:3291ad0d3c701cbf522012faccfbb29352ff16ad262db2139e6b01f15781f14e"}, + {file = "typer-0.23.1.tar.gz", hash = "sha256:2070374e4d31c83e7b61362fd859aa683576432fd5b026b060ad6b4cd3b86134"}, ] [[package]] name = "typer" -version = "0.21.1" +version = "0.23.1" extras = ["all"] requires_python = ">=3.9" summary = "Typer, build great CLIs. Easy to code. Based on Python type hints." groups = ["default"] dependencies = [ - "typer==0.21.1", + "typer==0.23.1", ] files = [ - {file = "typer-0.21.1-py3-none-any.whl", hash = "sha256:7985e89081c636b88d172c2ee0cfe33c253160994d47bdfdc302defd7d1f1d01"}, - {file = "typer-0.21.1.tar.gz", hash = "sha256:ea835607cd752343b6b2b7ce676893e5a0324082268b48f27aa058bdb7d2145d"}, + {file = "typer-0.23.1-py3-none-any.whl", hash = "sha256:3291ad0d3c701cbf522012faccfbb29352ff16ad262db2139e6b01f15781f14e"}, + {file = "typer-0.23.1.tar.gz", hash = "sha256:2070374e4d31c83e7b61362fd859aa683576432fd5b026b060ad6b4cd3b86134"}, ] [[package]] diff --git a/pyproject.toml b/pyproject.toml index 4b62d9f..e5328cf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,7 @@ [project] description = "" -license = { text = "LGPLv2" } +license = { text = "LGPL-3.0-or-later" } name = "synodic_client" authors = [{ name = "Synodic Software", email = "contact@synodic.software" }] @@ -12,10 +12,11 @@ dynamic = ["version"] requires-python = ">=3.14, <3.15" dependencies = [ - "pyside6>=6.10.1", + "pyside6>=6.10.2", "packaging>=26.0", - "porringer>=0.1.1.dev12", + "porringer>=0.2.1.dev10", "velopack>=0.0.1369.dev7516", + "typer>=0.23.0", ] [project.urls] @@ -24,9 +25,12 @@ repository = "https://github.com/synodic/synodic-client" [dependency-groups] build = ["pyinstaller>=6.18.0"] -lint = ["ruff>=0.14.14", "pyrefly>=0.50.1"] +lint = ["ruff>=0.15.0", "pyrefly>=0.52.0"] test = ["pytest>=9.0.2", "pytest-cov>=7.0.0", "pytest-mock>=3.15.1"] +[project.scripts] +synodic-c = "synodic_client.cli:app" + [project.gui-scripts] synodic-client = "synodic_client.application.qt:application" @@ -71,11 +75,16 @@ source = "scm" write_to = "synodic_client/_version.py" write_template = "__version__ = '{}'\n" +[tool.pdm.resolution] +allow-prereleases = true + [tool.pdm.scripts] analyze = "ruff check synodic_client tests" +dev = { call = "tool.scripts.dev:main" } format = "ruff format" lint = { composite = ["analyze", "format", "type-check"] } -package = "pyinstaller --clean tool/pyinstaller/synodic.spec" +package = { call = "tool.scripts.package:main" } +post_install = { call = "tool.scripts.setup_dev:main" } test = "pytest --cov=synodic_client --verbose tests" type-check = "pyrefly check" serve = "zensical serve" diff --git a/synodic_client/__init__.py b/synodic_client/__init__.py index f080961..1a0a256 100644 --- a/synodic_client/__init__.py +++ b/synodic_client/__init__.py @@ -3,14 +3,8 @@ import importlib.metadata from synodic_client.client import Client -from synodic_client.schema import ( - UpdateChannel, - UpdateCheckResult, - UpdateProgress, - UpdateStatus, - VersionInformation, -) from synodic_client.updater import ( + UpdateChannel, UpdateConfig, UpdateInfo, Updater, @@ -26,12 +20,8 @@ '__version__', 'Client', 'UpdateChannel', - 'UpdateCheckResult', 'UpdateConfig', 'UpdateInfo', - 'UpdateProgress', 'UpdateState', - 'UpdateStatus', 'Updater', - 'VersionInformation', ] diff --git a/synodic_client/__main__.py b/synodic_client/__main__.py new file mode 100644 index 0000000..cfa26cd --- /dev/null +++ b/synodic_client/__main__.py @@ -0,0 +1,5 @@ +"""Allow running the package directly with ``python -m synodic_client``.""" + +from synodic_client.cli import app + +app() diff --git a/synodic_client/application/icon.py b/synodic_client/application/icon.py new file mode 100644 index 0000000..bef97ef --- /dev/null +++ b/synodic_client/application/icon.py @@ -0,0 +1,29 @@ +"""Centralised application icon. + +Loads the icon once from package resources and caches the ``QIcon`` +so every caller shares the same instance. +""" + +from __future__ import annotations + +from PySide6.QtGui import QIcon, QPixmap + +from synodic_client.client import Client + +_cached_icon: QIcon | None = None + + +def app_icon() -> QIcon: + """Return the shared application ``QIcon``, loading it on first call. + + The icon is loaded eagerly via ``QPixmap`` so it survives the + ``importlib.resources`` context-manager cleanup. + + Returns: + A ``QIcon`` backed by the application logo. + """ + global _cached_icon # noqa: PLW0603 + if _cached_icon is None: + with Client.resource(Client.icon) as icon_path: + _cached_icon = QIcon(QPixmap(str(icon_path))) + return _cached_icon diff --git a/synodic_client/application/instance.py b/synodic_client/application/instance.py new file mode 100644 index 0000000..3149fa3 --- /dev/null +++ b/synodic_client/application/instance.py @@ -0,0 +1,108 @@ +"""Single-instance application management using Qt local sockets. + +Ensures only one instance of Synodic Client runs at a time. When a second +instance is launched (e.g. by clicking a ``synodic://`` URI), it sends the +URI to the already-running instance and exits. +""" + +import logging + +from PySide6.QtCore import QByteArray, QObject, Signal +from PySide6.QtNetwork import QLocalServer, QLocalSocket + +from synodic_client.application.theme import SOCKET_TIMEOUT_MS +from synodic_client.config import is_dev_mode + +logger = logging.getLogger(__name__) + +_SERVER_NAME = 'synodic-client' +_SERVER_NAME_DEV = 'synodic-client-dev' + + +def _server_name() -> str: + """Return the server name, namespaced for dev mode.""" + return _SERVER_NAME_DEV if is_dev_mode() else _SERVER_NAME + + +class SingleInstance(QObject): + """Manages single-instance enforcement via a local socket server. + + Signals: + uri_received: Emitted when another instance sends a URI string. + """ + + uri_received = Signal(str) + + def __init__(self, parent: QObject | None = None) -> None: + """Initialize the single instance manager. + + Args: + parent: Optional parent QObject. + """ + super().__init__(parent) + self._server: QLocalServer | None = None + + @staticmethod + def try_send_to_existing(message: str) -> bool: + """Attempt to send a message to an already-running instance. + + Args: + message: The message (typically a ``synodic://`` URI) to send. + + Returns: + True if the message was sent successfully (another instance is running). + False if no other instance was found. + """ + socket = QLocalSocket() + socket.connectToServer(_server_name()) + + if socket.waitForConnected(SOCKET_TIMEOUT_MS): + socket.write(QByteArray(message.encode('utf-8'))) + socket.waitForBytesWritten(SOCKET_TIMEOUT_MS) + socket.disconnectFromServer() + logger.info('Sent message to existing instance: %s', message) + return True + + return False + + def start_server(self) -> bool: + """Start the local socket server to listen for incoming messages. + + If a stale server exists (e.g. from a crash), it will be cleaned up + and a new server started. + + Returns: + True if the server started successfully. + """ + self._server = QLocalServer(self) + self._server.newConnection.connect(self._on_new_connection) + + if not self._server.listen(_server_name()): + # Clean up stale socket from a previous crash + QLocalServer.removeServer(_server_name()) + if not self._server.listen(_server_name()): + logger.error('Failed to start single-instance server: %s', self._server.errorString()) + return False + + logger.debug('Single-instance server listening as "%s"', _server_name()) + return True + + def _on_new_connection(self) -> None: + """Handle an incoming connection from another instance.""" + if self._server is None: + return + + socket = self._server.nextPendingConnection() + if socket is None: + return + + if socket.waitForReadyRead(SOCKET_TIMEOUT_MS): + raw = socket.readAll().data() + data = raw.decode('utf-8') if isinstance(raw, (bytes, bytearray)) else str(raw) + if data: + logger.info('Received message from another instance: %s', data) + self.uri_received.emit(data) + else: + logger.info('Another instance connected (no URI)') + + socket.disconnectFromServer() diff --git a/synodic_client/application/qt.py b/synodic_client/application/qt.py index 904cb1a..a608e54 100644 --- a/synodic_client/application/qt.py +++ b/synodic_client/application/qt.py @@ -1,58 +1,222 @@ -"""gui""" +"""GUI entry point for the Synodic Client application.""" +import ctypes import logging +import signal +import subprocess import sys +import types +from collections.abc import Callable +from urllib.parse import parse_qs, urlparse -from porringer.api import API, APIParameters -from porringer.schema import ListPluginsParameters, LocalConfiguration -from PySide6.QtCore import Qt +from porringer.api import API +from porringer.schema import LocalConfiguration +from PySide6.QtCore import Qt, QTimer from PySide6.QtWidgets import QApplication +from synodic_client.application.icon import app_icon +from synodic_client.application.instance import SingleInstance +from synodic_client.application.screen.install import InstallPreviewWindow from synodic_client.application.screen.screen import Screen from synodic_client.application.screen.tray import TrayScreen from synodic_client.client import Client -from synodic_client.updater import UpdateChannel, UpdateConfig, initialize_velopack +from synodic_client.config import GlobalConfiguration, set_dev_mode +from synodic_client.logging import configure_logging +from synodic_client.protocol import register_protocol +from synodic_client.resolution import resolve_config, resolve_update_config +from synodic_client.updater import initialize_velopack -def application() -> None: - """Entrypoint""" - # Initialize Velopack early, before any UI - initialize_velopack() +def parse_uri(uri: str) -> dict[str, str | list[str]]: + """Parse a ``synodic://`` URI into its components. - client = Client() + Example: + ``synodic://install?manifest=https://example.com/foo.toml`` + returns ``{'action': 'install', 'manifest': ['https://example.com/foo.toml']}``. - logger = logging.getLogger('synodic_client') - logging.basicConfig(level=logging.INFO) + Args: + uri: A ``synodic://`` URI string. + + Returns: + A dict with ``'action'`` (the host/path) and any query parameters. + """ + parsed = urlparse(uri) + result: dict[str, str | list[str]] = { + 'action': parsed.netloc or parsed.path.strip('/'), + } + result.update(parse_qs(parsed.query)) + return result + + +def _init_services(logger: logging.Logger) -> tuple[Client, API, GlobalConfiguration]: + """Create and configure core services. + + Returns: + A (Client, porringer API, resolved config) tuple. + """ + config = resolve_config() + client = Client() local_config = LocalConfiguration() - api_params = APIParameters(logger) - porringer = API(local_config, api_params) - - # Initialize the updater - # Use DEVELOPMENT channel if running from source (not frozen) - is_dev = not getattr(sys, 'frozen', False) - update_channel = UpdateChannel.DEVELOPMENT if is_dev else UpdateChannel.STABLE - update_config = UpdateConfig(channel=update_channel) + porringer = API(local_config) + + update_config = resolve_update_config(config) client.initialize_updater(update_config) - logger.info('Synodic Client v%s started (channel: %s)', client.version, update_channel.name) + logger.info( + 'Synodic Client v%s started (channel: %s, source: %s)', + client.version, + update_config.channel.name, + update_config.repo_url, + ) + + porringer.plugin.list() + + return client, porringer, config + + +def _process_uri(uri: str, handler: Callable[[str], None]) -> None: + """Parse a ``synodic://`` URI and dispatch install actions.""" + parsed_data = parse_uri(uri) + action = parsed_data.get('action') + if action == 'install': + manifests = parsed_data.get('manifest') + if isinstance(manifests, list) and manifests: + handler(manifests[0]) + + +def _suppress_subprocess_consoles() -> None: + """Monkey-patch ``subprocess.Popen`` to hide console windows on Windows. + + When the application is built as a windowed executable (``console=False`` + in PyInstaller), every ``subprocess.Popen`` call that launches a console + program (pip, pipx, uv, winget, etc.) would briefly flash a visible + console window. This patch adds ``CREATE_NO_WINDOW`` to *creationflags* + for all calls that don't already set it, suppressing those flashes. + """ + if sys.platform != 'win32': + return + + _original_init = subprocess.Popen.__init__ + + def _patched_init(self: subprocess.Popen, *args: object, **kwargs: object) -> None: # type: ignore[override] + if 'creationflags' not in kwargs: + kwargs['creationflags'] = subprocess.CREATE_NO_WINDOW + _original_init(self, *args, **kwargs) # type: ignore[arg-type] + + subprocess.Popen.__init__ = _patched_init # type: ignore[assignment] - list_params = ListPluginsParameters() - porringer.plugin.list(list_params) + +def _install_exception_hook(logger: logging.Logger) -> None: + """Redirect unhandled exceptions to the log file. + + Ensures tracebacks are visible even in windowed (``console=False``) + PyInstaller builds. + """ + _original_excepthook = sys.excepthook + + def _exception_hook( + exc_type: type[BaseException], + exc_value: BaseException, + exc_tb: types.TracebackType | None, + ) -> None: + logger.critical('Unhandled exception', exc_info=(exc_type, exc_value, exc_tb)) + _original_excepthook(exc_type, exc_value, exc_tb) + + sys.excepthook = _exception_hook + + +def _init_app() -> QApplication: + """Create and configure the ``QApplication``.""" + # Set the App User Model ID so Windows uses our icon on the taskbar + # instead of the generic python.exe icon. + if sys.platform == 'win32': + ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('synodic.client') # type: ignore[union-attr] app = QApplication([]) app.setQuitOnLastWindowClosed(False) - - # Reduce CPU usage when idle - process events less aggressively + app.setWindowIcon(app_icon()) app.setAttribute(Qt.ApplicationAttribute.AA_CompressHighFrequencyEvents) - _screen = Screen() - _tray = TrayScreen(app, client, Client.icon, _screen.window) + # Allow Ctrl+C in the terminal to terminate the application. + # Qt's event loop blocks Python's default SIGINT handling, so we + # install our own handler and use a short timer to let Python + # process it between Qt events. + signal.signal(signal.SIGINT, lambda *_args: app.quit()) + _signal_timer = QTimer(app) + _signal_timer.start(500) + _signal_timer.timeout.connect(lambda: None) + + return app + + +def application(*, uri: str | None = None, dev_mode: bool = False) -> None: + """Application entry point. + + Args: + uri: Optional ``synodic://`` URI to process on launch. + dev_mode: When ``True``, activate dev-mode isolation so that + the development instance does not share configuration, + log files, or single-instance locks with the user-installed + application. Velopack initialisation and protocol + registration are skipped. + """ + # Activate dev-mode namespacing before anything reads config paths. + set_dev_mode(dev_mode) + + # Suppress console window flashes from subprocess calls (e.g. porringer + # running pip, pipx, uv) before any subprocesses are spawned. Skipped + # in dev mode because the source-run process already has a console. + if not dev_mode: + _suppress_subprocess_consoles() + # Initialize Velopack early, before any UI + initialize_velopack() + register_protocol(sys.executable) + + configure_logging() + logger = logging.getLogger('synodic_client') + _install_exception_hook(logger) + + if uri: + logger.info('Received URI: %s', uri) + + client, porringer, config = _init_services(logger) + + app = _init_app() + + instance = SingleInstance(app) + if instance.try_send_to_existing(uri or ''): + logger.info('Another instance is already running, exiting') + sys.exit(0) + instance.start_server() + + _screen = Screen(porringer, config) + _tray = TrayScreen(app, client, _screen.window, config=config) + + # Keep install preview windows alive until the app exits + _install_windows: list[InstallPreviewWindow] = [] + + def _handle_install_uri(manifest_url: str) -> None: + logger.info('Opening install preview for: %s', manifest_url) + window = InstallPreviewWindow(porringer, manifest_url) + _install_windows.append(window) + window.show() + window.raise_() + window.activateWindow() + window.start() + + instance.uri_received.connect(lambda received_uri: _process_uri(received_uri, _handle_install_uri)) + + if uri: + _process_uri(uri, _handle_install_uri) # sys.exit ensures proper cleanup and exit code propagation # Leading underscore indicates references kept alive intentionally until exec() returns sys.exit(app.exec()) +_PROTOCOL_SCHEME = 'synodic' + if __name__ == '__main__': - application() + _uri = next((a for a in sys.argv[1:] if a.lower().startswith(f'{_PROTOCOL_SCHEME}://')), None) + application(uri=_uri) diff --git a/synodic_client/application/screen/__init__.py b/synodic_client/application/screen/__init__.py index 6523f79..6d80e7b 100644 --- a/synodic_client/application/screen/__init__.py +++ b/synodic_client/application/screen/__init__.py @@ -1 +1,53 @@ -"""The `synodic_client.application` package contains the GUI application logic for the Synodic Client.""" +"""The ``synodic_client.application.screen`` package — shared display helpers. + +Label mappings and helpers used by both the install module and the +execution log panel live here to avoid circular imports. +""" + +from __future__ import annotations + +from porringer.schema import PluginKind, SkipReason + +ACTION_KIND_LABELS: dict[PluginKind | None, str] = { + PluginKind.PACKAGE: 'Package', + PluginKind.TOOL: 'Tool', + PluginKind.PROJECT: 'Project', + PluginKind.RUNTIME: 'Runtime', + PluginKind.SCM: 'SCM', + None: 'Command', +} + +PLUGIN_KIND_GROUP_LABELS: dict[PluginKind, str] = { + PluginKind.PACKAGE: 'Packages', + PluginKind.TOOL: 'Tools', + PluginKind.PROJECT: 'Projects', + PluginKind.RUNTIME: 'Runtimes', + PluginKind.SCM: 'Source Control', +} +"""Human-readable group headings for the plugins view. + +Unknown kinds fall back to a title-cased version of the enum name so +newly added :class:`PluginKind` values are handled automatically. +""" + + +def plugin_kind_group_label(kind: PluginKind) -> str: + """Return the display label for a plugin-kind group header. + + Falls back to a title-cased version of the enum member name when + *kind* is not in :data:`PLUGIN_KIND_GROUP_LABELS`. + """ + return PLUGIN_KIND_GROUP_LABELS.get(kind, kind.name.replace('_', ' ').title()) + + +SKIP_REASON_LABELS: dict[SkipReason, str] = { + SkipReason.ALREADY_INSTALLED: 'Already installed', + SkipReason.NO_PROJECT_DIRECTORY: 'No project directory', +} + + +def skip_reason_label(reason: SkipReason | None) -> str: + """Return a human-readable label for a skip reason.""" + if reason is None: + return 'Skipped' + return SKIP_REASON_LABELS.get(reason, reason.name.replace('_', ' ').capitalize()) diff --git a/synodic_client/application/screen/install.py b/synodic_client/application/screen/install.py new file mode 100644 index 0000000..d86229b --- /dev/null +++ b/synodic_client/application/screen/install.py @@ -0,0 +1,915 @@ +"""Install preview widgets and workers. + +Provides a reusable :class:`SetupPreviewWidget` for displaying dry-run +previews and executing porringer setup actions, along with the standalone +:class:`InstallPreviewWindow` used for URI-based manifest installs. + +Execution runs on a background ``QThread`` with a real-time +:class:`~synodic_client.application.screen.log_panel.ExecutionLogPanel`. +""" + +from __future__ import annotations + +import asyncio +import logging +import shutil +import tempfile +from pathlib import Path +from typing import Any +from urllib.parse import urlparse +from urllib.request import url2pathname + +from porringer.api import API +from porringer.schema import ( + CancellationToken, + DownloadParameters, + PluginKind, + ProgressEventKind, + SetupAction, + SetupActionResult, + SetupParameters, + SetupResults, + SubActionProgress, +) +from PySide6.QtCore import QObject, Qt, QTimer, Signal +from PySide6.QtGui import QFont, QKeySequence, QShortcut +from PySide6.QtWidgets import ( + QApplication, + QFileDialog, + QHBoxLayout, + QHeaderView, + QLabel, + QLineEdit, + QMainWindow, + QMessageBox, + QPushButton, + QScrollArea, + QStackedWidget, + QTableWidget, + QTableWidgetItem, + QToolButton, + QVBoxLayout, + QWidget, +) + +from synodic_client.application.screen import ACTION_KIND_LABELS, skip_reason_label +from synodic_client.application.screen.log_panel import ExecutionLogPanel +from synodic_client.application.theme import ( + COMMAND_HEADER_STYLE, + COMPACT_MARGINS, + CONTENT_MARGINS, + COPY_BTN_SIZE, + COPY_BTN_STYLE, + COPY_FEEDBACK_MS, + COPY_ICON, + HEADER_STYLE, + INSTALL_PREVIEW_MIN_SIZE, + MONOSPACE_FAMILY, + MONOSPACE_SIZE, + MUTED_STYLE, + NO_MARGINS, +) +from synodic_client.application.threading import ThreadRunner + +logger = logging.getLogger(__name__) + + +def format_cli_command(action: SetupAction) -> str: + """Return a copyable CLI command string for *action*.""" + if parts := (action.cli_command or action.command): + return ' '.join(parts) + if action.kind == PluginKind.PACKAGE and action.package: + return f'{action.installer or "pip"} install {action.package}' + return action.description + + +class InstallWorker(QObject): + """Background worker that executes setup actions via porringer. + + Uses the ``execute_stream`` async generator to consume progress events + and emits per-action progress signals for GUI updates. + """ + + finished = Signal(object) # SetupResults + progress = Signal(object, object) # (SetupAction, SetupActionResult) + action_started = Signal(object) # SetupAction + sub_progress = Signal(object, object) # (SetupAction, SubActionProgress) + error = Signal(str) + + def __init__( + self, + porringer: API, + manifest_path: Path, + cancellation_token: CancellationToken, + *, + project_directory: Path | None = None, + ) -> None: + """Initialize the worker. + + Args: + porringer: The porringer API instance. + manifest_path: Path to the manifest file to execute. + cancellation_token: Token for cooperative cancellation. + project_directory: Working directory for project sync actions. + """ + super().__init__() + self._porringer = porringer + self._manifest_path = manifest_path + self._cancellation_token = cancellation_token + self._project_directory = project_directory + + def run(self) -> None: + """Execute the setup actions on this thread's event loop.""" + try: + results = asyncio.run(self._execute()) + self.finished.emit(results) + except asyncio.CancelledError: + self.finished.emit(SetupResults(actions=[])) + except Exception as exc: + logger.exception('Install execution failed') + self.error.emit(str(exc)) + + async def _execute(self) -> SetupResults: + """Stream execution events and collect results.""" + params = SetupParameters( + paths=[self._manifest_path], + project_directory=self._project_directory, + ) + actions: list[SetupAction] = [] + collected: list[SetupActionResult] = [] + manifest_result: SetupResults | None = None + + async for event in self._porringer.sync.execute_stream(params): + if self._cancellation_token.is_cancelled: + raise asyncio.CancelledError + + if event.kind == ProgressEventKind.MANIFEST_LOADED and event.manifest: + manifest_result = event.manifest + actions = list(event.manifest.actions) + + if event.kind == ProgressEventKind.ACTION_STARTED and event.action: + self.action_started.emit(event.action) + + if event.kind == ProgressEventKind.SUB_ACTION_PROGRESS and event.action and event.sub_action: + self.sub_progress.emit(event.action, event.sub_action) + + if event.kind == ProgressEventKind.ACTION_COMPLETED and event.result: + collected.append(event.result) + self.progress.emit(event.action, event.result) + + return SetupResults( + actions=actions, + results=collected, + manifest_path=manifest_result.manifest_path if manifest_result else None, + metadata=manifest_result.metadata if manifest_result else None, + ) + + +class CommandListWidget(QScrollArea): + """Scrollable list of per-action CLI commands with copy buttons.""" + + def __init__(self, parent: QWidget | None = None) -> None: + """Initialise the command list widget.""" + super().__init__(parent) + self.setWidgetResizable(True) + + def populate(self, actions: list[SetupAction]) -> None: + """Build per-action command fields with descriptive labels above each.""" + container = QWidget() + layout = QVBoxLayout(container) + layout.setContentsMargins(*NO_MARGINS) + + mono = QFont(MONOSPACE_FAMILY, MONOSPACE_SIZE) + for i, action in enumerate(actions, 1): + label_text = ACTION_KIND_LABELS.get(action.kind, 'Action') + desc = action.package_description or action.description + header = QLabel(f'{i}. [{label_text}] {desc}') + header.setStyleSheet(COMMAND_HEADER_STYLE) + layout.addWidget(header) + + field = QLineEdit(format_cli_command(action)) + field.setReadOnly(True) + field.setFont(mono) + + row_layout = QHBoxLayout() + row_layout.setContentsMargins(*NO_MARGINS) + row_layout.setSpacing(4) + row_layout.addWidget(field) + row_layout.addWidget(_make_copy_button(field)) + + row_widget = QWidget() + row_widget.setLayout(row_layout) + layout.addWidget(row_widget) + + layout.addStretch() + self.setWidget(container) + + +def _make_copy_button(field: QLineEdit) -> QToolButton: + """Create a copy-to-clipboard button bound to *field*.""" + btn = QToolButton() + btn.setText(COPY_ICON) + btn.setToolTip('Copy to clipboard') + btn.setFixedSize(*COPY_BTN_SIZE) + btn.setStyleSheet(COPY_BTN_STYLE) + btn.setCursor(Qt.CursorShape.PointingHandCursor) + btn.clicked.connect(lambda: _copy_command(field, btn)) + return btn + + +def _copy_command(field: QLineEdit, button: QToolButton) -> None: + """Copy the field text to the clipboard and briefly show a check mark.""" + clipboard = QApplication.clipboard() + if clipboard: + clipboard.setText(field.text()) + button.setText('\u2713') + button.setToolTip('Copied!') + + def _restore() -> None: + try: + button.setText(COPY_ICON) + button.setToolTip('Copy to clipboard') + except RuntimeError: + pass + + QTimer.singleShot(COPY_FEEDBACK_MS, _restore) + + +# --------------------------------------------------------------------------- +# SetupPreviewWidget — reusable preview + install widget +# --------------------------------------------------------------------------- + + +class SetupPreviewWidget(QWidget): + """Reusable widget that displays a dry-run preview and executes installs. + + This widget is embedded by both :class:`InstallPreviewWindow` (for + URI-based installs) and ``ProjectsView`` (for cached-directory + projects). It owns the actions table, command list, metadata display, + status label, and install execution pipeline. + + The caller is responsible for providing a manifest path and project + directory. Preview data is fed in via + :meth:`on_preview_ready` / :meth:`on_action_checked` / + :meth:`on_preview_finished` / :meth:`on_preview_error` signal slots. + """ + + #: Emitted when the user clicks Close (or after a fatal preview error). + close_requested = Signal() + + #: Emitted after a successful install completes. + install_finished = Signal(object) # SetupResults + + def __init__(self, porringer: API, parent: QWidget | None = None, *, show_close: bool = True) -> None: + """Initialize the preview widget. + + Args: + porringer: The porringer API instance. + parent: Optional parent widget. + show_close: Whether to show the Close button. Set ``False`` + when embedding inside a persistent view (e.g. a tab). + """ + super().__init__(parent) + self._porringer = porringer + self._show_close = show_close + self._preview: SetupResults | None = None + self._manifest_path: Path | None = None + self._project_directory: Path | None = None + self._runner: ThreadRunner | None = None + self._cancellation_token: CancellationToken | None = None + self._completed_count = 0 + self._action_statuses: list[str] = [] + + self._init_ui() + + # --- UI construction --- + + def _init_ui(self) -> None: + """Build the widget layout.""" + layout = QVBoxLayout(self) + layout.setContentsMargins(*NO_MARGINS) + + # Metadata labels (populated after preview completes) + self._name_label = QLabel() + self._name_label.setStyleSheet(HEADER_STYLE) + self._name_label.hide() + layout.addWidget(self._name_label) + + self._description_label = QLabel() + self._description_label.setWordWrap(True) + self._description_label.hide() + layout.addWidget(self._description_label) + + self._meta_label = QLabel() + self._meta_label.setStyleSheet(MUTED_STYLE) + self._meta_label.hide() + layout.addWidget(self._meta_label) + + # Status label + self._status_label = QLabel() + layout.addWidget(self._status_label) + + # --- View stack (table / command list / execution log) --- + self._view_stack = QStackedWidget() + + self._table = self._init_actions_table() + self._view_stack.addWidget(self._table) # page 0 + + self._command_list = CommandListWidget() + self._view_stack.addWidget(self._command_list) # page 1 + + self._log_panel = ExecutionLogPanel() + self._view_stack.addWidget(self._log_panel) # page 2 + + layout.addWidget(self._view_stack) + + # Button bar + layout.addLayout(self._init_button_bar()) + + def _init_actions_table(self) -> QTableWidget: + """Create and configure the actions table widget.""" + table = QTableWidget() + table.setColumnCount(5) + table.setHorizontalHeaderLabels(['Type', 'Plugin', 'Package', 'Description', 'Status']) + table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers) + table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows) + table.setAlternatingRowColors(True) + header = table.horizontalHeader() + header.setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents) + header.setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents) + header.setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents) + header.setSectionResizeMode(3, QHeaderView.ResizeMode.Stretch) + header.setSectionResizeMode(4, QHeaderView.ResizeMode.ResizeToContents) + QShortcut(QKeySequence.StandardKey.Copy, table, self._copy_table_selection) + return table + + def _init_button_bar(self) -> QHBoxLayout: + """Create the bottom button bar.""" + self._toggle_btn = QPushButton('Show Commands') + self._toggle_btn.setEnabled(False) + self._toggle_btn.clicked.connect(self._toggle_view) + + button_bar = QHBoxLayout() + button_bar.addWidget(self._toggle_btn) + button_bar.addStretch() + + self._install_btn = QPushButton('Install') + self._install_btn.setEnabled(False) + self._install_btn.clicked.connect(self._on_install) + button_bar.addWidget(self._install_btn) + + self._close_btn = QPushButton('Close') + self._close_btn.clicked.connect(self.close_requested.emit) + if not self._show_close: + self._close_btn.hide() + button_bar.addWidget(self._close_btn) + + return button_bar + + # --- Public API --- + + def set_project_directory(self, path: Path) -> None: + """Set the project directory used for install execution. + + Args: + path: Working directory for project sync actions. + """ + self._project_directory = path + + def reset(self) -> None: + """Clear all state and UI for a fresh preview.""" + self._preview = None + self._manifest_path = None + self._runner = None + self._cancellation_token = None + self._completed_count = 0 + self._action_statuses = [] + + self._table.setRowCount(0) + self._log_panel.clear() + self._name_label.hide() + self._description_label.hide() + self._meta_label.hide() + self._status_label.setText('') + self._status_label.setStyleSheet('') + self._install_btn.setEnabled(False) + self._toggle_btn.setEnabled(False) + self._view_stack.setCurrentIndex(0) + + def show_not_found(self, message: str) -> None: + """Display a muted 'not found' message in the status label. + + Used by callers that want to report a missing directory or manifest + without popping a modal dialog. + + Args: + message: The human-readable error or not-found description. + """ + self._status_label.setText(message) + self._status_label.setStyleSheet(MUTED_STYLE) + + # --- Preview callbacks (connect to PreviewWorker signals) --- + + def on_preview_ready(self, preview: SetupResults, manifest_path: str, temp_dir_path: str) -> None: + """Handle a successful preview. + + Args: + preview: The setup preview results. + manifest_path: Path to the manifest file. + temp_dir_path: Path to the temp directory (kept alive for execution). + """ + logger.info('Preview ready: %d action(s) from %s', len(preview.actions), manifest_path) + self._preview = preview + self._manifest_path = Path(manifest_path) + self._status_label.setStyleSheet('') + + self._show_metadata(preview) + + if not preview.actions: + self._status_label.setText('No actions to perform — the manifest is empty.') + return + + self._action_statuses = ['Checking…'] * len(preview.actions) + self._status_label.setText(f'{len(preview.actions)} action(s) — checking status…') + self._populate_table(preview.actions) + self._install_btn.setEnabled(True) + + def on_action_checked(self, row: int, result: SetupActionResult) -> None: + """Update the data model and table row with the dry-run result.""" + label = skip_reason_label(result.skip_reason) if result.skipped else 'Needed' + + if 0 <= row < len(self._action_statuses): + self._action_statuses[row] = label + + item = self._table.item(row, 4) + if item is None: + return + + item.setText(label) + if result.skipped: + item.setForeground(self.palette().placeholderText()) + else: + item.setForeground(self.palette().text()) + + def on_preview_finished(self) -> None: + """Finalize the preview after the dry-run check completes.""" + if not self._action_statuses: + return + + # Resolve any still-pending statuses as 'Needed' + for i, status in enumerate(self._action_statuses): + if status == 'Checking…': + self._action_statuses[i] = 'Needed' + item = self._table.item(i, 4) + if item is not None: + item.setText('Needed') + item.setForeground(self.palette().text()) + + total = len(self._action_statuses) + needed = sum(1 for s in self._action_statuses if s == 'Needed') + satisfied = total - needed + + if needed == 0: + self._status_label.setText(f'{total} action(s) — all already satisfied.') + self._install_btn.setEnabled(False) + else: + self._status_label.setText(f'{total} action(s): {needed} needed, {satisfied} already satisfied.') + + logger.info('Preview complete: %d total, %d needed, %d satisfied', total, needed, satisfied) + + def on_preview_error(self, message: str) -> None: + """Handle a preview error.""" + logger.error('Preview failed: %s', message) + self._status_label.setText('') + QMessageBox.critical(self, 'Preview Failed', message) + self.close_requested.emit() + + # --- Metadata --- + + def _show_metadata(self, preview: SetupResults) -> None: + """Display manifest metadata labels if available.""" + metadata = preview.metadata + if not metadata: + return + + if metadata.name: + self._name_label.setText(metadata.name) + self._name_label.show() + if metadata.description: + self._description_label.setText(metadata.description) + self._description_label.show() + + meta_parts: list[str] = [] + if metadata.author: + meta_parts.append(f'Author: {metadata.author}') + if metadata.url: + meta_parts.append(f'URL: {metadata.url}') + if meta_parts: + self._meta_label.setText(' | '.join(meta_parts)) + self._meta_label.show() + + # --- View toggle --- + + def _toggle_view(self) -> None: + """Cycle between overview table, command list, and execution log.""" + current = self._view_stack.currentIndex() + if current == 0: + self._view_stack.setCurrentIndex(1) + self._toggle_btn.setText('Show Log') + elif current == 1: + self._view_stack.setCurrentIndex(2) + self._toggle_btn.setText('Show Overview') + else: + self._view_stack.setCurrentIndex(0) + self._toggle_btn.setText('Show Commands') + + # --- Table / command list --- + + def _copy_table_selection(self) -> None: + """Copy selected table rows to the clipboard as tab-separated text.""" + rows = sorted({idx.row() for idx in self._table.selectedIndexes()}) + if not rows: + return + cols = self._table.columnCount() + lines = [ + '\t'.join((item.text() if (item := self._table.item(r, c)) else '') for c in range(cols)) for r in rows + ] + clipboard = QApplication.clipboard() + if clipboard: + clipboard.setText('\n'.join(lines)) + + def _populate_table(self, actions: list[SetupAction]) -> None: + """Fill the actions table from a list of SetupAction objects.""" + self._table.setRowCount(len(actions)) + for row, action in enumerate(actions): + self._table.setItem(row, 0, QTableWidgetItem(ACTION_KIND_LABELS.get(action.kind, 'Action'))) + self._table.setItem(row, 1, QTableWidgetItem(action.installer or '')) + self._table.setItem(row, 2, QTableWidgetItem(str(action.package) if action.package else '')) + self._table.setItem(row, 3, QTableWidgetItem(action.package_description or action.description)) + + status_item = QTableWidgetItem('Checking…') + status_item.setForeground(self.palette().placeholderText()) + self._table.setItem(row, 4, status_item) + + self._command_list.populate(actions) + self._toggle_btn.setEnabled(True) + + # --- Install execution --- + + def _on_install(self) -> None: + """Handle the Install button click.""" + if self._manifest_path is None: + return + + self._install_btn.setEnabled(False) + self._close_btn.setEnabled(False) + self._toggle_btn.setEnabled(False) + self._completed_count = 0 + + self._cancellation_token = CancellationToken() + + # Switch to the execution log panel view + self._log_panel.clear() + self._view_stack.setCurrentIndex(2) + self._status_label.setText('Installing…') + + # Worker thread + worker = InstallWorker( + self._porringer, + self._manifest_path, + self._cancellation_token, + project_directory=self._project_directory, + ) + worker.action_started.connect(self._on_action_started) + worker.sub_progress.connect(self._on_sub_progress) + worker.progress.connect(self._on_action_progress) + worker.finished.connect(self._on_install_finished) + worker.error.connect(self._on_install_error) + + self._runner = ThreadRunner(worker) + self._runner.start() + + def _on_action_started(self, action: SetupAction) -> None: + """Handle an action starting execution — create a log section.""" + self._log_panel.add_section(action) + + def _on_sub_progress(self, action: SetupAction, progress: SubActionProgress) -> None: + """Handle a sub-action progress event — route to the log panel.""" + self._log_panel.on_sub_progress(action, progress) + + def _on_action_progress(self, action: SetupAction, result: SetupActionResult) -> None: + """Handle a single action completion from the worker.""" + row = self._completed_count + self._completed_count += 1 + + # Update the execution log panel + self._log_panel.on_action_completed(action, result) + + # Update the table status too (for when user switches back to table view) + self._update_table_status(row, result) + + # Update status label + total = len(self._preview.actions) if self._preview else 0 + self._status_label.setText(f'Installing… ({self._completed_count}/{total})') + + def _update_table_status(self, row: int, result: SetupActionResult) -> None: + """Update the status cell for a table row from an action result.""" + item = self._table.item(row, 4) + if item is None: + return + + if result.skipped: + item.setText(skip_reason_label(result.skip_reason)) + item.setForeground(self.palette().placeholderText()) + elif result.success: + item.setText('Done') + item.setForeground(self.palette().text()) + else: + item.setText(f'Failed: {result.message}' if result.message else 'Failed') + item.setForeground(self.palette().text()) + + def _on_cancel(self) -> None: + """Handle cancel request.""" + if self._cancellation_token: + self._cancellation_token.cancel() + + def _on_install_finished(self, results: SetupResults) -> None: + """Handle install completion.""" + succeeded = sum(1 for r in results.results if r.success and not r.skipped) + skipped = sum(1 for r in results.results if r.skipped) + failed = sum(1 for r in results.results if not r.success) + + parts = [] + if succeeded: + parts.append(f'{succeeded} succeeded') + if skipped: + parts.append(f'{skipped} skipped') + if failed: + parts.append(f'{failed} failed') + + summary = ', '.join(parts) if parts else 'No actions executed.' + self._status_label.setText(f'Done — {summary}') + self._install_btn.setEnabled(False) + self._close_btn.setEnabled(True) + self._toggle_btn.setEnabled(True) + self.install_finished.emit(results) + + def _on_install_error(self, message: str) -> None: + """Handle install error.""" + self._status_label.setText(f'Install failed: {message}') + self._install_btn.setEnabled(True) + self._close_btn.setEnabled(True) + self._toggle_btn.setEnabled(True) + + +# --------------------------------------------------------------------------- +# InstallPreviewWindow — standalone URI-based install window +# --------------------------------------------------------------------------- + + +class InstallPreviewWindow(QMainWindow): + """Standalone window that previews and executes a URI-based manifest install. + + Wraps :class:`SetupPreviewWidget` and owns the download lifecycle + (temp directory, ``PreviewWorker``). + """ + + def __init__(self, porringer: API, manifest_url: str, parent: QWidget | None = None) -> None: + """Initialize the install preview window. + + Args: + porringer: The porringer API instance. + manifest_url: The URL of the manifest to install. + parent: Optional parent widget. + """ + super().__init__(parent) + self._porringer = porringer + self._manifest_url = manifest_url + self._temp_dir_path: str | None = None + self._runner: ThreadRunner | None = None + + # Default project directory to the current working directory + self._project_directory: Path = Path.cwd() + + self.setWindowTitle('Install Preview') + self.setMinimumSize(*INSTALL_PREVIEW_MIN_SIZE) + + self._init_ui() + + def _init_ui(self) -> None: + """Build the UI layout.""" + central = QWidget() + self.setCentralWidget(central) + layout = QVBoxLayout(central) + layout.setContentsMargins(*CONTENT_MARGINS) + + # URL header + self._url_label = QLabel() + self._url_label.setWordWrap(True) + layout.addWidget(self._url_label) + + # Project directory input + layout.addLayout(self._init_project_dir_row()) + + # Shared preview widget + self._preview_widget = SetupPreviewWidget(self._porringer, self) + self._preview_widget.close_requested.connect(self.close) + self._preview_widget.set_project_directory(self._project_directory) + layout.addWidget(self._preview_widget) + + def _init_project_dir_row(self) -> QHBoxLayout: + """Create the project directory input row.""" + row = QHBoxLayout() + row.setContentsMargins(*COMPACT_MARGINS) + + label = QLabel('Project path:') + row.addWidget(label) + + self._project_dir_field = QLineEdit(str(self._project_directory)) + self._project_dir_field.setToolTip('Working directory for project sync and post-sync commands') + self._project_dir_field.textChanged.connect(self._on_project_dir_changed) + row.addWidget(self._project_dir_field) + + browse_btn = QPushButton('Browse…') + browse_btn.clicked.connect(self._on_browse_project_dir) + row.addWidget(browse_btn) + + return row + + def _on_project_dir_changed(self, text: str) -> None: + """Update the project directory from the text field.""" + self._project_directory = Path(text) + self._preview_widget.set_project_directory(self._project_directory) + + def _on_browse_project_dir(self) -> None: + """Open a directory picker for the project path.""" + chosen = QFileDialog.getExistingDirectory( + self, + 'Select Project Directory', + str(self._project_directory), + ) + if chosen: + self._project_directory = Path(chosen) + self._project_dir_field.setText(chosen) + + # --- Lifecycle --- + + def showEvent(self, event: Any) -> None: + """Log when the window becomes visible.""" + super().showEvent(event) + logger.info('Install preview window shown (visible=%s)', self.isVisible()) + + def closeEvent(self, event: Any) -> None: + """Clean up the temp directory when the window is closed.""" + logger.info('Install preview window closing') + self._cleanup_temp_dir() + super().closeEvent(event) + + def _cleanup_temp_dir(self) -> None: + """Remove the temporary download directory if it exists.""" + if self._temp_dir_path: + _safe_rmtree(self._temp_dir_path) + self._temp_dir_path = None + + # --- Public API --- + + def start(self) -> None: + """Download the manifest and populate the preview. + + Call this after ``show()`` to begin the download → preview flow. + """ + logger.info('Starting install preview for: %s', self._manifest_url) + self._url_label.setText(f'Manifest: {self._manifest_url}') + + preview_worker = PreviewWorker(self._porringer, self._manifest_url, project_directory=self._project_directory) + + preview_worker.preview_ready.connect(self._on_preview_ready) + preview_worker.action_checked.connect(self._preview_widget.on_action_checked) + preview_worker.finished.connect(self._preview_widget.on_preview_finished) + preview_worker.error.connect(self._preview_widget.on_preview_error) + + self._runner = ThreadRunner(preview_worker) + self._runner.start() + + # --- Preview callback (intercepts to capture temp dir) --- + + def _on_preview_ready(self, preview: SetupResults, manifest_path: str, temp_dir_path: str) -> None: + """Capture the temp dir path and forward to the preview widget.""" + self._temp_dir_path = temp_dir_path + + # Update window title from metadata + if preview.metadata and preview.metadata.name: + self.setWindowTitle(f'Install Preview — {preview.metadata.name}') + + self._preview_widget.on_preview_ready(preview, manifest_path, temp_dir_path) + + +class PreviewWorker(QObject): + """Background worker that downloads a manifest and performs a dry-run. + + Combines two stages into a single background pipeline: + + 1. Download the manifest (if remote). + 2. Run ``execute_stream`` with ``dry_run=True`` to list actions and check status. + """ + + preview_ready = Signal(object, str, str) # (SetupResults, manifest_path, temp_dir_path) + action_checked = Signal(int, object) # (row_index, SetupActionResult) + finished = Signal() + error = Signal(str) + + def __init__(self, porringer: API, url: str, *, project_directory: Path | None = None) -> None: + """Initialize the preview worker.""" + super().__init__() + self._porringer = porringer + self._url = url + self._project_directory = project_directory + + def run(self) -> None: + """Download the manifest and perform a dry-run to check status.""" + logger.info('PreviewWorker starting for: %s', self._url) + temp_dir = None + try: + local_path = resolve_local_path(self._url) + + if local_path is not None: + if not local_path.exists(): + self.error.emit(f'Manifest not found:\n{local_path}') + return + manifest_path = local_path + else: + temp_dir = tempfile.mkdtemp(prefix='synodic_install_') + dest = Path(temp_dir) / 'porringer.json' + + params = DownloadParameters(url=self._url, destination=dest, timeout=3) + result = self._porringer.sync.download(params) + + if not result.success: + _safe_rmtree(temp_dir) + self.error.emit(f'Failed to download manifest:\n{result.message}') + return + + manifest_path = dest + + # Dry-run: parses manifest, resolves actions, and checks status + asyncio.run(self._dry_run(manifest_path, temp_dir or '')) + + self.finished.emit() + + except Exception as exc: + if temp_dir: + _safe_rmtree(temp_dir) + logger.exception('Preview failed') + self.error.emit(str(exc)) + + async def _dry_run(self, manifest_path: Path, temp_dir: str) -> None: + """Stream dry-run events, emitting preview_ready and action_checked signals.""" + params = SetupParameters( + paths=[manifest_path], + dry_run=True, + project_directory=self._project_directory, + ) + action_index: dict[int, int] = {} + + async for event in self._porringer.sync.execute_stream(params): + if event.kind == ProgressEventKind.MANIFEST_LOADED and event.manifest: + action_index = {id(a): i for i, a in enumerate(event.manifest.actions)} + self.preview_ready.emit(event.manifest, str(manifest_path), temp_dir) + + elif event.kind == ProgressEventKind.ACTION_COMPLETED and event.result and event.action: + row = action_index.get(id(event.action)) + if row is not None: + self.action_checked.emit(row, event.result) + + +def resolve_local_path(manifest_ref: str) -> Path | None: + r"""Return a ``Path`` if *manifest_ref* points to a local file, else ``None``. + + Recognised forms: + * ``file:///C:/path/to/porringer.json`` + * An absolute OS path (``C:\...`` or ``/...``) + * A relative path that exists on disk + """ + parsed = urlparse(manifest_ref) + + if parsed.scheme == 'file': + # file:///C:/Users/... → C:/Users/... + return Path(url2pathname(parsed.path)) + + if parsed.scheme in {'http', 'https'}: + return None + + # No scheme — treat as a filesystem path + candidate = Path(manifest_ref) + if candidate.is_absolute() or candidate.exists(): + return candidate + + return None + + +def _safe_rmtree(path: str) -> None: + """Remove a directory tree, ignoring errors.""" + try: + shutil.rmtree(path) + except OSError: + logger.debug('Failed to clean up temp dir: %s', path) diff --git a/synodic_client/application/screen/log_panel.py b/synodic_client/application/screen/log_panel.py new file mode 100644 index 0000000..3aed548 --- /dev/null +++ b/synodic_client/application/screen/log_panel.py @@ -0,0 +1,261 @@ +"""Collapsible execution log panel for install operations. + +Provides :class:`ExecutionLogPanel`, a scrollable container of +:class:`ActionLogSection` widgets — one per setup action. Each section +has a collapsible header (default: open) with a status badge and a +monospace output area that receives colour-coded stdout/stderr lines. +""" + +from __future__ import annotations + +import html +import logging + +from porringer.schema import SetupAction, SetupActionResult, SubActionProgress +from PySide6.QtCore import Qt +from PySide6.QtGui import QFont, QTextCursor +from PySide6.QtWidgets import ( + QHBoxLayout, + QLabel, + QScrollArea, + QSizePolicy, + QTextEdit, + QVBoxLayout, + QWidget, +) + +from synodic_client.application.screen import ACTION_KIND_LABELS, skip_reason_label +from synodic_client.application.theme import ( + LOG_CHEVRON_STYLE, + LOG_COLOR_ERROR, + LOG_COLOR_PHASE, + LOG_COLOR_STDERR, + LOG_COLOR_STDOUT, + LOG_COLOR_SUCCESS, + LOG_OUTPUT_STYLE, + LOG_SECTION_HEADER_STYLE, + LOG_SECTION_TITLE_STYLE, + LOG_STATUS_FAILED, + LOG_STATUS_RUNNING, + LOG_STATUS_SKIPPED, + LOG_STATUS_SUCCESS, + MONOSPACE_FAMILY, + MONOSPACE_SIZE, + NO_MARGINS, +) + +logger = logging.getLogger(__name__) + +# Unicode chevrons +CHEVRON_DOWN = '\u25bc' +CHEVRON_RIGHT = '\u25b6' + + +class ActionLogSection(QWidget): + """A single collapsible action log section. + + Shows a clickable header with chevron + action description + status badge, + and a monospace ``QTextEdit`` body that displays colour-coded output lines. + """ + + def __init__(self, action: SetupAction, index: int, parent: QWidget | None = None) -> None: + """Initialise the section. + + Args: + action: The setup action this section represents. + index: 1-based display index. + parent: Optional parent widget. + """ + super().__init__(parent) + self._action = action + self._expanded = True + + layout = QVBoxLayout(self) + layout.setContentsMargins(*NO_MARGINS) + layout.setSpacing(0) + + # --- Header --- + self._header = QWidget() + self._header.setObjectName('sectionHeader') + self._header.setStyleSheet(LOG_SECTION_HEADER_STYLE) + self._header.setCursor(Qt.CursorShape.PointingHandCursor) + self._header.mousePressEvent = lambda _event: self._toggle() + + header_layout = QHBoxLayout(self._header) + header_layout.setContentsMargins(0, 0, 0, 0) + header_layout.setSpacing(6) + + self._chevron = QLabel(CHEVRON_DOWN) + self._chevron.setStyleSheet(LOG_CHEVRON_STYLE) + self._chevron.setFixedWidth(14) + header_layout.addWidget(self._chevron) + + kind_label = ACTION_KIND_LABELS.get(action.kind, 'Action') + desc = action.package_description or action.description + title = QLabel(f'{index}. [{kind_label}] {desc}') + title.setStyleSheet(LOG_SECTION_TITLE_STYLE) + header_layout.addWidget(title, stretch=1) + + self._status_label = QLabel('Running…') + self._status_label.setStyleSheet(LOG_STATUS_RUNNING) + header_layout.addWidget(self._status_label) + + layout.addWidget(self._header) + + # --- Output body --- + self._output = QTextEdit() + self._output.setReadOnly(True) + self._output.setFont(QFont(MONOSPACE_FAMILY, MONOSPACE_SIZE)) + self._output.setStyleSheet(LOG_OUTPUT_STYLE) + self._output.setMinimumHeight(60) + self._output.setMaximumHeight(300) + self._output.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) + layout.addWidget(self._output) + + # --- Public API --- + + def append_output(self, text: str, stream: str | None = None) -> None: + """Append a line of output with stream-appropriate colouring. + + Args: + text: The output line text. + stream: ``'stdout'``, ``'stderr'``, or ``None`` for phase messages. + """ + colour = LOG_COLOR_STDOUT + if stream == 'stderr': + colour = LOG_COLOR_STDERR + elif stream is None: + colour = LOG_COLOR_PHASE + + escaped = html.escape(text) + self._output.append(f'{escaped}') + + # Auto-scroll to bottom + cursor = self._output.textCursor() + cursor.movePosition(QTextCursor.MoveOperation.End) + self._output.setTextCursor(cursor) + + def set_result(self, result: SetupActionResult) -> None: + """Update the section header with the final action result. + + Args: + result: The action result. + """ + if result.skipped: + label = skip_reason_label(result.skip_reason) + self._status_label.setText(label) + self._status_label.setStyleSheet(LOG_STATUS_SKIPPED) + self.append_output(f'⏭ Skipped: {label}', None) + elif result.success: + self._status_label.setText('Done') + self._status_label.setStyleSheet(LOG_STATUS_SUCCESS) + msg = result.message or 'Completed successfully' + self._output.append(f'✓ {html.escape(msg)}') + else: + self._status_label.setText('Failed') + self._status_label.setStyleSheet(LOG_STATUS_FAILED) + msg = result.message or 'Unknown error' + self._output.append(f'✗ {html.escape(msg)}') + + # --- Collapse / expand --- + + def _toggle(self) -> None: + """Toggle the output body visibility.""" + self._expanded = not self._expanded + self._output.setVisible(self._expanded) + self._chevron.setText(CHEVRON_DOWN if self._expanded else CHEVRON_RIGHT) + + +class ExecutionLogPanel(QScrollArea): + """Scrollable container of :class:`ActionLogSection` widgets. + + Used as the execution view during install operations. Sections are + added dynamically as ``ACTION_STARTED`` events arrive. + """ + + def __init__(self, parent: QWidget | None = None) -> None: + """Initialise the log panel.""" + super().__init__(parent) + self.setWidgetResizable(True) + + self._container = QWidget() + self._layout = QVBoxLayout(self._container) + self._layout.setContentsMargins(4, 4, 4, 4) + self._layout.setSpacing(6) + self._layout.addStretch() + + self.setWidget(self._container) + + # Map action id → section widget for quick lookup + self._sections: dict[int, ActionLogSection] = {} + self._section_count = 0 + + # --- Public API --- + + def add_section(self, action: SetupAction) -> ActionLogSection: + """Add a new collapsible section for an action. + + Args: + action: The setup action starting execution. + + Returns: + The created section widget. + """ + self._section_count += 1 + section = ActionLogSection(action, self._section_count, self._container) + # Insert before the stretch + self._layout.insertWidget(self._layout.count() - 1, section) + self._sections[id(action)] = section + + # Scroll to show the new section + self.ensureWidgetVisible(section) + + return section + + def get_section(self, action: SetupAction) -> ActionLogSection | None: + """Look up the section widget for a given action. + + Args: + action: The setup action to look up. + + Returns: + The section widget, or ``None`` if not found. + """ + return self._sections.get(id(action)) + + def on_sub_progress(self, action: SetupAction, progress: SubActionProgress) -> None: + """Handle a sub-action progress event. + + Routes output lines and phase messages to the correct section. + + Args: + action: The parent action. + progress: The sub-action progress update. + """ + section = self.get_section(action) + if section is None: + return + + if progress.output is not None: + section.append_output(progress.output, progress.stream) + elif progress.message is not None: + section.append_output(progress.message) + + def on_action_completed(self, action: SetupAction, result: SetupActionResult) -> None: + """Handle an action completion event. + + Args: + action: The completed action. + result: The action result. + """ + section = self.get_section(action) + if section is not None: + section.set_result(result) + + def clear(self) -> None: + """Remove all sections.""" + for section in self._sections.values(): + self._layout.removeWidget(section) + section.deleteLater() + self._sections.clear() + self._section_count = 0 diff --git a/synodic_client/application/screen/screen.py b/synodic_client/application/screen/screen.py index f2a7e9a..41498ed 100644 --- a/synodic_client/application/screen/screen.py +++ b/synodic_client/application/screen/screen.py @@ -1,19 +1,719 @@ """Screen class for the Synodic Client application.""" -from PySide6.QtWidgets import QMainWindow +from __future__ import annotations + +import logging +from collections import OrderedDict +from dataclasses import dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING + +from porringer.api import API +from porringer.schema import PluginInfo, PluginKind +from PySide6.QtCore import Qt, Signal +from PySide6.QtGui import QStandardItem +from PySide6.QtWidgets import ( + QComboBox, + QFileDialog, + QHBoxLayout, + QHeaderView, + QLabel, + QMainWindow, + QPushButton, + QScrollArea, + QTableWidget, + QTableWidgetItem, + QTabWidget, + QVBoxLayout, + QWidget, +) + +from synodic_client.application.icon import app_icon +from synodic_client.application.screen import plugin_kind_group_label +from synodic_client.application.screen.install import PreviewWorker, SetupPreviewWidget +from synodic_client.application.theme import ( + COMPACT_MARGINS, + LOG_CHEVRON_STYLE, + LOG_SECTION_TITLE_STYLE, + MAIN_WINDOW_MIN_SIZE, + PLUGIN_GROUP_HEADER_STYLE, + PLUGIN_GROUP_SECTION_SPACING, + PLUGIN_GROUP_TITLE_STYLE, + PLUGIN_SECTION_HEADER_STYLE, + PLUGIN_SECTION_SPACING, + PLUGIN_TOGGLE_STYLE, + PLUGIN_UPDATE_STYLE, +) +from synodic_client.application.threading import ThreadRunner +from synodic_client.config import GlobalConfiguration, save_config + +if TYPE_CHECKING: + from porringer.schema import ManifestDirectory + +logger = logging.getLogger(__name__) + +# Plugin kinds that support auto-update and per-plugin upgrade. +_UPDATABLE_KINDS = frozenset({PluginKind.TOOL, PluginKind.PACKAGE}) + +# Unicode chevrons +_CHEVRON_DOWN = '\u25bc' +_CHEVRON_RIGHT = '\u25b6' + + +@dataclass +class PluginSectionData: + """Data needed to construct a :class:`PluginSection`.""" + + name: str + version: str + packages: list[tuple[str, str]] = field(default_factory=list) + auto_update: bool = True + show_controls: bool = False + found: bool = True + + +class PluginSection(QWidget): + """Collapsible section displaying a single plugin and its managed packages.""" + + auto_update_toggled = Signal(str, bool) + """Emitted with ``(plugin_name, enabled)`` when the auto-update toggle changes.""" + + update_requested = Signal(str) + """Emitted with the plugin name when the per-plugin Update button is clicked.""" + + def __init__(self, data: PluginSectionData, parent: QWidget | None = None) -> None: + """Initialise the section. + + Args: + data: Plugin metadata and package list. + parent: Optional parent widget. + """ + super().__init__(parent) + self._plugin_name = data.name + self._expanded = False + + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(0) + + self._header = self._build_header( + data.name, + data.version, + data.auto_update, + data.show_controls, + found=data.found, + ) + layout.addWidget(self._header) + + self._body = self._build_body(data.packages) + self._body.setVisible(False) + layout.addWidget(self._body) + + # --- Header / body builders --- + + def _build_header( + self, + plugin_name: str, + version: str, + auto_update: bool, + show_controls: bool, + *, + found: bool = True, + ) -> QWidget: + """Construct the clickable header row.""" + header = QWidget() + header.setObjectName('pluginHeader') + header.setStyleSheet(PLUGIN_SECTION_HEADER_STYLE) + header.setCursor(Qt.CursorShape.PointingHandCursor) + header.mousePressEvent = lambda _event: self._toggle() + + header_layout = QHBoxLayout(header) + header_layout.setContentsMargins(0, 0, 0, 0) + header_layout.setSpacing(6) + + self._chevron = QLabel(_CHEVRON_RIGHT) + self._chevron.setStyleSheet(LOG_CHEVRON_STYLE) + self._chevron.setFixedWidth(14) + header_layout.addWidget(self._chevron) + + title = QLabel(plugin_name) + title.setStyleSheet(LOG_SECTION_TITLE_STYLE) + header_layout.addWidget(title) + + version_label = QLabel(version) + version_label.setStyleSheet('color: grey;') + header_layout.addWidget(version_label) + + header_layout.addStretch() + + if show_controls: + self._toggle_btn = QPushButton('Auto') + self._toggle_btn.setCheckable(True) + self._toggle_btn.setChecked(auto_update) + self._toggle_btn.setStyleSheet(PLUGIN_TOGGLE_STYLE) + self._toggle_btn.setToolTip('Enable automatic updates for this plugin') + self._toggle_btn.clicked.connect(self._on_toggle_clicked) + header_layout.addWidget(self._toggle_btn) + + update_btn = QPushButton('Update') + update_btn.setStyleSheet(PLUGIN_UPDATE_STYLE) + update_btn.setToolTip(f'Upgrade packages via {plugin_name} now') + update_btn.clicked.connect( + lambda: self.update_requested.emit(self._plugin_name), + ) + header_layout.addWidget(update_btn) + + if not found: + self._toggle_btn.setEnabled(False) + self._toggle_btn.setChecked(False) + self._toggle_btn.setToolTip('Plugin not found \u2014 cannot auto-update') + update_btn.setEnabled(False) + update_btn.setToolTip('Plugin not found \u2014 cannot update') + + return header + + @staticmethod + def _build_body(packages: list[tuple[str, str]]) -> QWidget: + """Construct the collapsible body with a package table.""" + body = QWidget() + body_layout = QVBoxLayout(body) + body_layout.setContentsMargins(20, 4, 0, 4) + body_layout.setSpacing(2) + + if packages: + table = QTableWidget(len(packages), 2) + table.setHorizontalHeaderLabels(['Package', 'Project']) + table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers) + table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows) + table.setAlternatingRowColors(True) + table.verticalHeader().setVisible(False) + h = table.horizontalHeader() + h.setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch) + h.setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch) + for row, (pkg, proj) in enumerate(packages): + table.setItem(row, 0, QTableWidgetItem(pkg)) + table.setItem(row, 1, QTableWidgetItem(proj)) + body_layout.addWidget(table) + else: + body_layout.addWidget(QLabel('No packages found')) + + return body + + # --- Collapse / expand --- + + def _toggle(self) -> None: + """Toggle the body visibility.""" + self._expanded = not self._expanded + self._body.setVisible(self._expanded) + self._chevron.setText(_CHEVRON_DOWN if self._expanded else _CHEVRON_RIGHT) + + # --- Callbacks --- + + def _on_toggle_clicked(self, checked: bool) -> None: + """Forward auto-update toggle state change.""" + self.auto_update_toggled.emit(self._plugin_name, checked) + + +class PluginGroupSection(QWidget): + """Collapsible group of :class:`PluginSection` widgets sharing the same kind. + + The group header displays a human-readable label derived from the + :class:`~porringer.schema.PluginKind`. New kinds are handled + automatically via :func:`plugin_kind_group_label`. + """ + + def __init__( + self, + kind: PluginKind, + parent: QWidget | None = None, + ) -> None: + """Initialise the group section. + + Args: + kind: The plugin kind this group represents. + parent: Optional parent widget. + """ + super().__init__(parent) + self._kind = kind + self._expanded = True + self._sections: list[PluginSection] = [] + + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(0) + + self._header = self._build_header(kind) + layout.addWidget(self._header) + + self._body = QWidget() + self._body_layout = QVBoxLayout(self._body) + self._body_layout.setContentsMargins(8, 0, 0, 0) + self._body_layout.setSpacing(PLUGIN_GROUP_SECTION_SPACING) + layout.addWidget(self._body) + + # --- Header builder --- + + def _build_header(self, kind: PluginKind) -> QWidget: + """Construct the clickable group header row.""" + header = QWidget() + header.setObjectName('pluginGroupHeader') + header.setStyleSheet(PLUGIN_GROUP_HEADER_STYLE) + header.setCursor(Qt.CursorShape.PointingHandCursor) + header.mousePressEvent = lambda _event: self._toggle() + + header_layout = QHBoxLayout(header) + header_layout.setContentsMargins(0, 0, 0, 0) + header_layout.setSpacing(6) + + self._chevron = QLabel(_CHEVRON_DOWN) + self._chevron.setStyleSheet(LOG_CHEVRON_STYLE) + self._chevron.setFixedWidth(14) + header_layout.addWidget(self._chevron) + + title = QLabel(plugin_kind_group_label(kind)) + title.setStyleSheet(PLUGIN_GROUP_TITLE_STYLE) + header_layout.addWidget(title) + + header_layout.addStretch() + return header + + # --- Public helpers --- + + @property + def kind(self) -> PluginKind: + """Return the plugin kind for this group.""" + return self._kind + + @property + def sections(self) -> list[PluginSection]: + """Return the child plugin sections.""" + return list(self._sections) + + def add_section(self, section: PluginSection) -> None: + """Append a :class:`PluginSection` to this group.""" + self._body_layout.addWidget(section) + self._sections.append(section) + + # --- Collapse / expand --- + + def _toggle(self) -> None: + """Toggle the body visibility.""" + self._expanded = not self._expanded + self._body.setVisible(self._expanded) + self._chevron.setText(_CHEVRON_DOWN if self._expanded else _CHEVRON_RIGHT) + + +class PluginsView(QWidget): + """Scrollable list of collapsible plugin sections with auto-update controls.""" + + update_all_requested = Signal() + """Emitted when the global *Update All* button is clicked.""" + + plugin_update_requested = Signal(str) + """Emitted with a plugin name when its per-plugin *Update* button is clicked.""" + + def __init__( + self, + porringer: API, + config: GlobalConfiguration, + parent: QWidget | None = None, + ) -> None: + """Initialize the plugins view. + + Args: + porringer: The porringer API instance. + config: Resolved global configuration (for auto-update toggles). + parent: Optional parent widget. + """ + super().__init__(parent) + self._porringer = porringer + self._config = config + self._groups: list[PluginGroupSection] = [] + self._init_ui() + + def _init_ui(self) -> None: + """Initialize the UI components.""" + outer = QVBoxLayout(self) + outer.setContentsMargins(*COMPACT_MARGINS) + + # Toolbar + toolbar = QHBoxLayout() + toolbar.addStretch() + update_all_btn = QPushButton('Update All') + update_all_btn.setToolTip('Upgrade all auto-update-enabled plugins now') + update_all_btn.clicked.connect(self.update_all_requested.emit) + toolbar.addWidget(update_all_btn) + outer.addLayout(toolbar) + + # Scroll area + self._scroll = QScrollArea() + self._scroll.setWidgetResizable(True) + self._scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + + self._container = QWidget() + self._container_layout = QVBoxLayout(self._container) + self._container_layout.setSpacing(PLUGIN_SECTION_SPACING) + self._container_layout.setContentsMargins(0, 0, 0, 0) + self._container_layout.addStretch() + + self._scroll.setWidget(self._container) + outer.addWidget(self._scroll) + + # --- Public API --- + + def refresh(self) -> None: + """Rebuild the plugin sections from porringer data, grouped by kind.""" + # Clear existing groups + for group in self._groups: + self._container_layout.removeWidget(group) + group.deleteLater() + self._groups.clear() + + plugins = self._porringer.plugin.list() + directories = self._porringer.cache.list_directories() + auto_update_map = self._config.plugin_auto_update or {} + + # Bucket plugins by kind, preserving discovery order within each bucket + kind_buckets: OrderedDict[PluginKind, list[PluginInfo]] = OrderedDict() + for plugin in plugins: + kind_buckets.setdefault(plugin.kind, []).append(plugin) + + for kind, bucket in kind_buckets.items(): + group = PluginGroupSection(kind, parent=self._container) + + for plugin in bucket: + section = self._build_plugin_section( + plugin, + directories, + auto_update_map, + parent=group, + ) + section.auto_update_toggled.connect(self._on_auto_update_toggled) + section.update_requested.connect(self.plugin_update_requested.emit) + group.add_section(section) + + # Insert before the trailing stretch + idx = self._container_layout.count() - 1 + self._container_layout.insertWidget(idx, group) + self._groups.append(group) + + def _build_plugin_section( + self, + plugin: PluginInfo, + directories: list[ManifestDirectory], + auto_update_map: dict[str, bool], + *, + parent: QWidget | None = None, + ) -> PluginSection: + """Create a :class:`PluginSection` for a single plugin.""" + found = plugin.installed + version = str(plugin.tool_version) if plugin.tool_version is not None else 'Installed' if found else 'Not found' + show_controls = plugin.kind in _UPDATABLE_KINDS + auto_update = auto_update_map.get(plugin.name, True) + + packages = self._gather_packages(plugin.name, directories) if show_controls else [] + + return PluginSection( + PluginSectionData( + name=plugin.name, + version=version, + packages=packages, + auto_update=auto_update, + show_controls=show_controls, + found=found, + ), + parent=parent, + ) + + def _gather_packages( + self, + plugin_name: str, + directories: list[ManifestDirectory], + ) -> list[tuple[str, str]]: + """Collect packages managed by *plugin_name* across cached projects.""" + packages: list[tuple[str, str]] = [] + for directory in directories: + try: + pkgs = self._porringer.plugin.list_packages( + plugin_name, + Path(directory.path), + ) + for pkg in pkgs: + packages.append( + (str(pkg.name), directory.name or str(directory.path)), + ) + except Exception: + logger.debug( + 'Could not list packages for %s in %s', + plugin_name, + directory.path, + exc_info=True, + ) + return packages + + # --- Callbacks --- + + def _on_auto_update_toggled(self, plugin_name: str, enabled: bool) -> None: + """Persist the auto-update toggle change to config.""" + mapping = self._config.plugin_auto_update + if mapping is None: + mapping = {} + self._config.plugin_auto_update = mapping + + if enabled: + mapping.pop(plugin_name, None) + else: + mapping[plugin_name] = False + + # Clean up the dict if all plugins are enabled + if not mapping: + self._config.plugin_auto_update = None + + save_config(self._config) + logger.info('Auto-update for %s set to %s', plugin_name, enabled) + + +class ProjectsView(QWidget): + """Widget for managing project directories and previewing their manifests. + + Combines a cached-directory selector (editable ``QComboBox`` with + Browse) and a :class:`SetupPreviewWidget` for dry-run preview and + install execution. + """ + + def __init__(self, porringer: API, parent: QWidget | None = None) -> None: + """Initialize the projects view. + + Args: + porringer: The porringer API instance. + parent: Optional parent widget. + """ + super().__init__(parent) + self._porringer = porringer + self._runner: ThreadRunner | None = None + self._init_ui() + + def _init_ui(self) -> None: + """Initialize the UI components.""" + layout = QVBoxLayout(self) + layout.setContentsMargins(*COMPACT_MARGINS) + + # --- Project directory selector --- + selector_row = QHBoxLayout() + selector_row.setContentsMargins(0, 0, 0, 8) + + self._combo = QComboBox() + self._combo.setEditable(True) + self._combo.setToolTip('Select a cached project directory or enter a new path') + self._combo.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon) + self._combo.setMinimumContentsLength(40) + self._combo.currentIndexChanged.connect(self._on_selection_changed) + selector_row.addWidget(self._combo, 1) + + self._browse_btn = QPushButton('Browse…') + self._browse_btn.clicked.connect(self._on_browse) + selector_row.addWidget(self._browse_btn) + + self._remove_btn = QPushButton('Remove') + self._remove_btn.setToolTip('Remove the selected directory from the cache') + self._remove_btn.clicked.connect(self._on_remove) + self._remove_btn.setEnabled(False) + selector_row.addWidget(self._remove_btn) + + layout.addLayout(selector_row) + + # --- Shared preview widget --- + self._preview = SetupPreviewWidget(self._porringer, self, show_close=False) + self._preview.install_finished.connect(self._on_install_finished) + layout.addWidget(self._preview) + + # --- Public API --- + + def refresh(self) -> None: + """Refresh the cached directories combo box from porringer cache.""" + self._combo.blockSignals(True) + current_text = self._combo.currentText() + self._combo.clear() + + directories = self._porringer.cache.list_directories() + for directory in directories: + display = str(directory.path) + tooltip = directory.name or '' + exists = Path(directory.path).is_dir() + + idx = self._combo.count() + self._combo.addItem(display) + self._combo.setItemData(idx, tooltip, Qt.ItemDataRole.ToolTipRole) + self._combo.setItemData(idx, str(directory.path), Qt.ItemDataRole.UserRole) + + if not exists: + # Grey out entries whose directory no longer exists on disk + item = self._combo.model().item(idx) # type: ignore[union-attr] + if isinstance(item, QStandardItem): + item.setForeground(self.palette().placeholderText()) + item.setToolTip(f'{tooltip} \u2014 directory not found' if tooltip else 'Directory not found') + + # Restore previous selection if it still exists + idx = self._combo.findText(current_text) + if idx >= 0: + self._combo.setCurrentIndex(idx) + elif self._combo.count() > 0: + self._combo.setCurrentIndex(0) + + self._combo.blockSignals(False) + self._update_remove_btn() + + # Trigger preview for the current selection + if self._combo.currentText(): + self._load_preview() + + # --- Event handlers --- + + def _on_selection_changed(self, _index: int) -> None: + """Handle combo box selection changes.""" + self._update_remove_btn() + if self._combo.currentText(): + self._load_preview() + + def _on_browse(self) -> None: + """Open a directory picker and set the combo text.""" + chosen = QFileDialog.getExistingDirectory( + self, + 'Select Project Directory', + self._combo.currentText() or '', + QFileDialog.Option.ShowDirsOnly, + ) + if chosen: + self._combo.setEditText(chosen) + self._load_preview() + + def _on_remove(self) -> None: + """Remove the currently selected directory from the cache.""" + idx = self._combo.currentIndex() + if idx < 0: + return + + path_str = self._combo.itemData(idx, Qt.ItemDataRole.UserRole) + if path_str: + self._porringer.cache.remove_directory(Path(path_str)) + + self.refresh() + + def _on_install_finished(self, _results: object) -> None: + """Register a new path in the cache after successful install.""" + current_text = self._combo.currentText().strip() + if not current_text: + return + + # Only register if the path isn't already in the combo's cached items + idx = self._combo.findText(current_text) + item_data = self._combo.itemData(idx, Qt.ItemDataRole.UserRole) if idx >= 0 else None + if item_data is None: + try: + self._porringer.cache.add_directory(Path(current_text)) + logger.info('Registered new project directory: %s', current_text) + self.refresh() + except ValueError: + logger.debug('Directory already cached or invalid: %s', current_text) + + # --- Preview loading --- + + def _load_preview(self) -> None: + """Run a dry-run preview for the currently selected path.""" + path_text = self._combo.currentText().strip() + if not path_text: + return + + project_path = Path(path_text) + manifest_path = project_path / 'porringer.json' + + self._preview.reset() + + if not project_path.is_dir(): + self._preview.show_not_found(f'Directory not found: {project_path}') + return + + self._preview.set_project_directory(project_path) + + preview_worker = PreviewWorker( + self._porringer, + str(manifest_path), + project_directory=project_path, + ) + preview_worker.preview_ready.connect(self._preview.on_preview_ready) + preview_worker.action_checked.connect(self._preview.on_action_checked) + preview_worker.finished.connect(self._preview.on_preview_finished) + preview_worker.error.connect(self._on_preview_error) + + self._runner = ThreadRunner(preview_worker) + self._runner.start() + + def _on_preview_error(self, message: str) -> None: + """Handle preview errors inline instead of showing a modal dialog.""" + logger.warning('Preview error: %s', message) + self._preview.show_not_found(message) + + def _update_remove_btn(self) -> None: + """Enable the Remove button only for cached (non-freeform) entries.""" + idx = self._combo.currentIndex() + has_data = idx >= 0 and self._combo.itemData(idx, Qt.ItemDataRole.UserRole) is not None + self._remove_btn.setEnabled(has_data) class MainWindow(QMainWindow): """Main window for the application.""" - def __init__(self) -> None: - """Initialize the main window.""" + _tabs: QTabWidget | None = None + _plugins_view: PluginsView | None = None + _projects_view: ProjectsView | None = None + + def __init__( + self, + porringer: API | None = None, + config: GlobalConfiguration | None = None, + ) -> None: + """Initialize the main window. + + Args: + porringer: Optional porringer API instance for manifest display. + config: Resolved global configuration for plugin auto-update state. + """ super().__init__() + self._porringer = porringer + self._config = config or GlobalConfiguration() self.setWindowTitle('Synodic Client') + self.setMinimumSize(*MAIN_WINDOW_MIN_SIZE) + self.setWindowIcon(app_icon()) + + @property + def porringer(self) -> API | None: + """Return the porringer API instance, if available.""" + return self._porringer + + @property + def plugins_view(self) -> PluginsView | None: + """Return the plugins view, if initialised.""" + return self._plugins_view def show(self) -> None: """Show the window, initializing UI lazily on first show.""" - # Future: Initialize heavy UI components here on first show + if self._tabs is None and self._porringer is not None: + self._tabs = QTabWidget(self) + + self._projects_view = ProjectsView(self._porringer, self) + self._tabs.addTab(self._projects_view, 'Projects') + + self._plugins_view = PluginsView(self._porringer, self._config, self) + self._tabs.addTab(self._plugins_view, 'Plugins') + + self.setCentralWidget(self._tabs) + + # Refresh both views + if self._plugins_view is not None: + self._plugins_view.refresh() + if self._projects_view is not None: + self._projects_view.refresh() + super().show() @@ -22,6 +722,20 @@ class Screen: _window: MainWindow | None = None + def __init__( + self, + porringer: API | None = None, + config: GlobalConfiguration | None = None, + ) -> None: + """Initialize the screen. + + Args: + porringer: Optional porringer API instance. + config: Resolved global configuration. + """ + self._porringer = porringer + self._config = config + @property def window(self) -> MainWindow: """Lazily create the main window on first access. @@ -30,5 +744,5 @@ def window(self) -> MainWindow: The MainWindow instance. """ if self._window is None: - self._window = MainWindow() + self._window = MainWindow(self._porringer, self._config) return self._window diff --git a/synodic_client/application/screen/tray.py b/synodic_client/application/screen/tray.py index 2eddadd..86c56af 100644 --- a/synodic_client/application/screen/tray.py +++ b/synodic_client/application/screen/tray.py @@ -1,15 +1,38 @@ """Tray screen for the application.""" +import asyncio import logging -from typing import LiteralString - -from PySide6.QtCore import QObject, QThread, Signal -from PySide6.QtGui import QAction, QIcon -from PySide6.QtWidgets import QApplication, QMenu, QMessageBox, QProgressDialog, QSystemTrayIcon - +from pathlib import Path + +from porringer.api import API +from porringer.schema import SetupParameters, SyncStrategy +from PySide6.QtCore import QObject, QTimer, Signal +from PySide6.QtGui import QAction +from PySide6.QtWidgets import ( + QApplication, + QDialog, + QFileDialog, + QHBoxLayout, + QLabel, + QLineEdit, + QMenu, + QMessageBox, + QProgressDialog, + QPushButton, + QSystemTrayIcon, + QVBoxLayout, + QWidget, +) + +from synodic_client.application.icon import app_icon from synodic_client.application.screen.screen import MainWindow +from synodic_client.application.theme import UPDATE_SOURCE_DIALOG_MIN_WIDTH +from synodic_client.application.threading import ThreadRunner from synodic_client.client import Client -from synodic_client.updater import UpdateInfo +from synodic_client.config import GlobalConfiguration +from synodic_client.logging import open_log +from synodic_client.resolution import resolve_config, resolve_enabled_plugins, resolve_update_config, update_and_resolve +from synodic_client.updater import GITHUB_REPO_URL, UpdateChannel, UpdateInfo logger = logging.getLogger(__name__) @@ -61,40 +84,206 @@ def progress_callback(percentage: int) -> None: self.error.emit(str(e)) +class ToolUpdateWorker(QObject): + """Worker for re-syncing manifest-declared tools in a background thread.""" + + finished = Signal(int) # number of manifests processed + error = Signal(str) + + def __init__(self, porringer: API, plugins: list[str] | None = None) -> None: + """Initialize the worker. + + Args: + porringer: The porringer API instance. + plugins: Optional include-list of plugin names. When set, only + actions handled by these plugins are executed. ``None`` + means all plugins. + """ + super().__init__() + self._porringer = porringer + self._plugins = plugins + + def run(self) -> None: + """Re-sync all cached project manifests.""" + try: + directories = self._porringer.cache.list_directories() + count = 0 + for directory in directories: + manifest = Path(directory.path) / 'porringer.json' + if not manifest.exists(): + logger.debug('Skipping missing manifest: %s', manifest) + continue + params = SetupParameters( + paths=[manifest], + project_directory=Path(directory.path), + strategy=SyncStrategy.LATEST, + plugins=self._plugins, + ) + asyncio.run(self._sync(params)) + count += 1 + self.finished.emit(count) + except Exception as e: + logger.exception('Tool update failed') + self.error.emit(str(e)) + + async def _sync(self, params: SetupParameters) -> None: + """Execute a sync stream for the given parameters.""" + async for _event in self._porringer.sync.execute_stream(params): + pass # consume events to completion + + +class UpdateSourceDialog(QDialog): + """Dialog for editing the Velopack update source URL or local path.""" + + def __init__(self, current_source: str | None, parent: QWidget | None = None) -> None: + """Initialise the dialog. + + Args: + current_source: The current update source value (may be ``None``). + parent: Optional parent widget. + """ + super().__init__(parent) + self.setWindowTitle('Update Source') + self.setMinimumWidth(UPDATE_SOURCE_DIALOG_MIN_WIDTH) + + layout = QVBoxLayout(self) + + label = QLabel( + 'Enter a URL or local path for Velopack releases.\nLeave blank to use the default GitHub source.', + ) + layout.addWidget(label) + + self._source_edit = QLineEdit(current_source or '') + self._source_edit.setPlaceholderText(GITHUB_REPO_URL) + + browse_button = QPushButton('Browse...') + browse_button.clicked.connect(self._browse) + + row = QHBoxLayout() + row.addWidget(self._source_edit) + row.addWidget(browse_button) + layout.addLayout(row) + + button_row = QHBoxLayout() + ok_button = QPushButton('OK') + cancel_button = QPushButton('Cancel') + button_row.addStretch() + button_row.addWidget(ok_button) + button_row.addWidget(cancel_button) + layout.addLayout(button_row) + + ok_button.clicked.connect(self.accept) + cancel_button.clicked.connect(self.reject) + + def _browse(self) -> None: + path = QFileDialog.getExistingDirectory(self, 'Select Releases Directory') + if path: + self._source_edit.setText(path) + + @property + def source(self) -> str | None: + """Return the trimmed source text, or ``None`` if blank.""" + return self._source_edit.text().strip() or None + + class TrayScreen: """Tray screen for the application.""" - def __init__(self, app: QApplication, client: Client, icon_name: LiteralString, window: MainWindow) -> None: - """Initialize the tray icon.""" + def __init__( + self, + app: QApplication, + client: Client, + window: MainWindow, + config: GlobalConfiguration | None = None, + ) -> None: + """Initialize the tray icon. + + Args: + app: The running ``QApplication``. + client: The Synodic Client service. + window: The main application window. + config: Optional pre-resolved configuration. When ``None``, + the configuration is resolved from disk on demand. + """ self._app = app self._client = client self._window = window - self._update_thread: QThread | None = None - self._update_worker: UpdateCheckWorker | UpdateDownloadWorker | None = None + self._config = config + self._runner: ThreadRunner | None = None + self._tool_runner: ThreadRunner | None = None self._progress_dialog: QProgressDialog | None = None + self._pending_update_info: UpdateInfo | None = None + self._download_cancelled = False - with client.resource(icon_name) as icon_path: - self.tray_icon = QIcon(str(icon_path)) + self.tray_icon = app_icon() self.tray = QSystemTrayIcon() self.tray.setIcon(self.tray_icon) - + self.tray.messageClicked.connect(self._on_notification_clicked) + self.tray.activated.connect(self._on_tray_activated) self.tray.setVisible(True) + self._build_menu(app, window) + + # Periodic auto-update checking + self._auto_update_timer: QTimer | None = None + self._start_auto_update_timer() + + # Periodic tool update checking + self._tool_update_timer: QTimer | None = None + self._start_tool_update_timer() + + # Connect PluginsView signals when available + plugins_view = window.plugins_view + if plugins_view is not None: + plugins_view.update_all_requested.connect(self._on_tool_update) + plugins_view.plugin_update_requested.connect(self._on_single_plugin_update) + + def _build_menu(self, app: QApplication, window: MainWindow) -> None: + """Build the tray context menu.""" self.menu = QMenu() self.open_action = QAction('Open', self.menu) self.menu.addAction(self.open_action) self.open_action.triggered.connect(window.show) - self.settings_action = QAction('Settings', self.menu) - self.menu.addAction(self.settings_action) + # Settings submenu + self.settings_menu = QMenu('Settings', self.menu) + self.menu.addMenu(self.settings_menu) - self.menu.addSeparator() - - self.update_action = QAction('Check for Updates...', self.menu) + self.update_action = QAction('Check for Updates...', self.settings_menu) self.update_action.triggered.connect(self._on_check_updates) - self.menu.addAction(self.update_action) + self.settings_menu.addAction(self.update_action) + + self.settings_menu.addSeparator() + + # Update Source action + self.update_source_action = QAction('Update Source...', self.settings_menu) + self.update_source_action.triggered.connect(self._on_update_source) + self.settings_menu.addAction(self.update_source_action) + + # Update Channel submenu + self.channel_menu = QMenu('Update Channel', self.settings_menu) + self.settings_menu.addMenu(self.channel_menu) + + self._channel_stable_action = QAction('Stable', self.channel_menu) + self._channel_stable_action.setCheckable(True) + self._channel_stable_action.triggered.connect(lambda: self._on_channel_changed(UpdateChannel.STABLE)) + self.channel_menu.addAction(self._channel_stable_action) + + self._channel_dev_action = QAction('Development', self.channel_menu) + self._channel_dev_action.setCheckable(True) + self._channel_dev_action.triggered.connect(lambda: self._on_channel_changed(UpdateChannel.DEVELOPMENT)) + self.channel_menu.addAction(self._channel_dev_action) + + # Set initial channel check state from config + self._sync_channel_checks() + + self.settings_menu.addSeparator() + + self.open_log_action = QAction('Open Log...', self.settings_menu) + self.open_log_action.triggered.connect(open_log) + self.settings_menu.addAction(self.open_log_action) self.menu.addSeparator() @@ -104,90 +293,261 @@ def __init__(self, app: QApplication, client: Client, icon_name: LiteralString, self.tray.setContextMenu(self.menu) + # -- Config helpers -- + + def _resolve_config(self) -> GlobalConfiguration: + """Return the injected config or resolve from disk.""" + if self._config is not None: + return self._config + return resolve_config() + + def _start_auto_update_timer(self) -> None: + """Start (or restart) the periodic auto-update timer from config.""" + if self._auto_update_timer is not None: + self._auto_update_timer.stop() + self._auto_update_timer = None + + config = resolve_update_config(self._resolve_config()) + interval_minutes = config.auto_update_interval_minutes + if interval_minutes <= 0: + logger.info('Automatic update checking is disabled') + return + + interval_ms = interval_minutes * 60 * 1000 + self._auto_update_timer = QTimer() + self._auto_update_timer.setInterval(interval_ms) + self._auto_update_timer.timeout.connect(self._on_auto_check_updates) + self._auto_update_timer.start() + logger.info('Automatic update checking enabled (every %d minute(s))', interval_minutes) + + def _start_tool_update_timer(self) -> None: + """Start (or restart) the periodic tool update timer from config.""" + if self._tool_update_timer is not None: + self._tool_update_timer.stop() + self._tool_update_timer = None + + config = resolve_update_config(self._resolve_config()) + interval_minutes = config.tool_update_interval_minutes + if interval_minutes <= 0: + logger.info('Automatic tool updating is disabled') + return + + interval_ms = interval_minutes * 60 * 1000 + self._tool_update_timer = QTimer() + self._tool_update_timer.setInterval(interval_ms) + self._tool_update_timer.timeout.connect(self._on_tool_update) + self._tool_update_timer.start() + logger.info('Automatic tool updating enabled (every %d minute(s))', interval_minutes) + + def _sync_channel_checks(self) -> None: + """Synchronize channel checkmarks with the current config.""" + config = self._resolve_config() + is_dev = config.update_channel == 'dev' + self._channel_stable_action.setChecked(not is_dev) + self._channel_dev_action.setChecked(is_dev) + + def _on_tray_activated(self, reason: QSystemTrayIcon.ActivationReason) -> None: + """Handle tray icon activation (e.g. double-click).""" + if reason == QSystemTrayIcon.ActivationReason.DoubleClick: + self._window.show() + self._window.raise_() + self._window.activateWindow() + + def _on_update_source(self) -> None: + """Open a dialog to edit the update source URL or local path.""" + config = self._resolve_config() + + parent = self._window if self._window.isVisible() else None + dialog = UpdateSourceDialog(config.update_source, parent) + + if dialog.exec() == QDialog.DialogCode.Accepted: + config.update_source = dialog.source + logger.info('Update source changed to: %s', dialog.source or '(default)') + self._reinitialize_updater(config) + + def _on_channel_changed(self, channel: UpdateChannel) -> None: + """Handle channel selection change.""" + config = self._resolve_config() + config.update_channel = 'dev' if channel == UpdateChannel.DEVELOPMENT else 'stable' + logger.info('Update channel changed to: %s', config.update_channel) + self._sync_channel_checks() + self._reinitialize_updater(config) + + def _reinitialize_updater(self, config: GlobalConfiguration) -> None: + """Re-derive update settings and restart the updater and timers.""" + update_cfg = update_and_resolve(config) + self._client.initialize_updater(update_cfg) + self._start_auto_update_timer() + self._start_tool_update_timer() + logger.info('Updater re-initialized (channel: %s, source: %s)', update_cfg.channel.name, update_cfg.repo_url) + + def _reset_update_action(self) -> None: + """Restore the 'Check for Updates' action to its idle state.""" + self.update_action.setEnabled(True) + self.update_action.setText('Check for Updates...') + + def _close_progress(self) -> None: + """Close and discard the download progress dialog, if open.""" + if self._progress_dialog: + self._progress_dialog.close() + self._progress_dialog = None + def _on_check_updates(self) -> None: - """Handle check for updates action.""" + """Handle manual check for updates action.""" + self._do_check_updates(silent=False) + + def _on_auto_check_updates(self) -> None: + """Handle automatic (periodic) check for updates. + + Failures and no-update results are logged silently without + showing Windows notifications. + """ + self._do_check_updates(silent=True) + + def _do_check_updates(self, *, silent: bool) -> None: + """Run an update check. + + Args: + silent: When ``True``, suppress notifications for failures + and no-update results. Notifications are still shown + when an update *is* available. + """ if self._client.updater is None: - QMessageBox.warning( - self._window, - 'Update Error', - 'Updater is not initialized.', - ) + if not silent: + self.tray.showMessage( + 'Update Error', + 'Updater is not initialized.', + QSystemTrayIcon.MessageIcon.Warning, + ) return # Disable the action while checking self.update_action.setEnabled(False) self.update_action.setText('Checking for Updates...') - # Create worker and thread - self._update_thread = QThread() - self._update_worker = UpdateCheckWorker(self._client) - self._update_worker.moveToThread(self._update_thread) + worker = UpdateCheckWorker(self._client) + worker.finished.connect(lambda result: self._on_update_check_finished(result, silent=silent)) + worker.error.connect(lambda error: self._on_update_check_error(error, silent=silent)) - # Connect signals - self._update_thread.started.connect(self._update_worker.run) - self._update_worker.finished.connect(self._on_update_check_finished) - self._update_worker.error.connect(self._on_update_check_error) - self._update_worker.finished.connect(self._update_thread.quit) - self._update_worker.error.connect(self._update_thread.quit) + self._runner = ThreadRunner(worker) + self._runner.start() - # Start the thread - self._update_thread.start() - - def _on_update_check_finished(self, result: UpdateInfo | None) -> None: + def _on_update_check_finished(self, result: UpdateInfo | None, *, silent: bool = False) -> None: """Handle update check completion.""" - self.update_action.setEnabled(True) - self.update_action.setText('Check for Updates...') + self._reset_update_action() if result is None: - QMessageBox.warning( - self._window, - 'Update Check Failed', - 'Failed to check for updates. Please try again later.', - ) + if not silent: + self.tray.showMessage( + 'Update Check Failed', + 'Failed to check for updates. Please try again later.', + QSystemTrayIcon.MessageIcon.Warning, + ) + else: + logger.warning('Automatic update check failed (no result)') return if result.error: - QMessageBox.warning( - self._window, - 'Update Check Failed', - f'Failed to check for updates:\n{result.error}', - ) + if not silent: + self.tray.showMessage( + 'Update Check Failed', + f'Failed to check for updates: {result.error}', + QSystemTrayIcon.MessageIcon.Warning, + ) + else: + logger.warning('Automatic update check failed: %s', result.error) return if not result.available: - QMessageBox.information( - self._window, - 'No Updates Available', - f'You are running the latest version ({result.current_version}).', - ) + if not silent: + self.tray.showMessage( + 'No Updates Available', + f'You are running the latest version ({result.current_version}).', + QSystemTrayIcon.MessageIcon.Information, + ) + else: + logger.debug('Automatic update check: no update available') return - # Update available - prompt user - reply = QMessageBox.question( - self._window, + # Update available - always show notification, clicking it starts download + self._pending_update_info = result + self.tray.showMessage( 'Update Available', - f'A new version is available!\n\n' - f'Current version: {result.current_version}\n' - f'New version: {result.latest_version}\n\n' - f'Would you like to download and install it?', - QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, - QMessageBox.StandardButton.Yes, + f'Version {result.latest_version} is available (current: {result.current_version}).\nClick to download.', + QSystemTrayIcon.MessageIcon.Information, ) - if reply == QMessageBox.StandardButton.Yes: - self._start_download() - - def _on_update_check_error(self, error: str) -> None: + def _on_update_check_error(self, error: str, *, silent: bool = False) -> None: """Handle update check error.""" - self.update_action.setEnabled(True) - self.update_action.setText('Check for Updates...') + self._reset_update_action() - QMessageBox.critical( - self._window, - 'Update Check Error', - f'An error occurred while checking for updates:\n{error}', + if not silent: + self.tray.showMessage( + 'Update Check Error', + f'An error occurred: {error}', + QSystemTrayIcon.MessageIcon.Critical, + ) + else: + logger.warning('Automatic update check error: %s', error) + + # -- Tool update helpers -- + + def _on_tool_update(self) -> None: + """Trigger a background re-sync of manifest-declared tools.""" + porringer = self._window.porringer + if porringer is None: + logger.warning('Tool update skipped: porringer not available') + return + + logger.info('Starting periodic tool update check') + + config = self._resolve_config() + all_names = [p.name for p in porringer.plugin.list() if p.installed] + enabled = resolve_enabled_plugins(config, all_names) + + worker = ToolUpdateWorker(porringer, plugins=enabled) + worker.finished.connect(self._on_tool_update_finished) + worker.error.connect(self._on_tool_update_error) + + self._tool_runner = ThreadRunner(worker) + self._tool_runner.start() + + def _on_single_plugin_update(self, plugin_name: str) -> None: + """Upgrade a single plugin across all cached projects.""" + porringer = self._window.porringer + if porringer is None: + logger.warning('Single plugin update skipped: porringer not available') + return + + logger.info('Starting update for plugin: %s', plugin_name) + + worker = ToolUpdateWorker(porringer, plugins=[plugin_name]) + worker.finished.connect(self._on_tool_update_finished) + worker.error.connect(self._on_tool_update_error) + + self._tool_runner = ThreadRunner(worker) + self._tool_runner.start() + + def _on_tool_update_finished(self, count: int) -> None: + """Handle tool update completion.""" + logger.info('Tool update completed: %d manifest(s) processed', count) + self._window.show() + + def _on_tool_update_error(self, error: str) -> None: + """Handle tool update error.""" + logger.error('Tool update failed: %s', error) + self.tray.showMessage( + 'Tool Update Error', + f'An error occurred during tool update: {error}', + QSystemTrayIcon.MessageIcon.Warning, ) + def _on_notification_clicked(self) -> None: + """Handle notification click - starts download if update is pending.""" + if self._pending_update_info is not None and self._pending_update_info.available: + self._pending_update_info = None + self._start_download() + def _start_download(self) -> None: """Start downloading the update.""" # Create progress dialog @@ -201,47 +561,48 @@ def _start_download(self) -> None: self._progress_dialog.setWindowTitle('Downloading Update') self._progress_dialog.setAutoClose(False) self._progress_dialog.setAutoReset(False) + self._progress_dialog.canceled.connect(self._on_download_cancelled) + self._download_cancelled = False self._progress_dialog.show() - # Create worker and thread - self._update_thread = QThread() - self._update_worker = UpdateDownloadWorker(self._client) - self._update_worker.moveToThread(self._update_thread) + worker = UpdateDownloadWorker(self._client) + worker.finished.connect(self._on_download_finished) + worker.progress.connect(self._on_download_progress) + worker.error.connect(self._on_download_error) - # Connect signals - self._update_thread.started.connect(self._update_worker.run) - self._update_worker.finished.connect(self._on_download_finished) - self._update_worker.progress.connect(self._on_download_progress) - self._update_worker.error.connect(self._on_download_error) - self._update_worker.finished.connect(self._update_thread.quit) - self._update_worker.error.connect(self._update_thread.quit) + self._runner = ThreadRunner(worker) + self._runner.start() - # Start the thread - self._update_thread.start() + def _on_download_cancelled(self) -> None: + """Handle cancel button on the download progress dialog.""" + self._download_cancelled = True + self._close_progress() + logger.info('Update download cancelled by user') def _on_download_progress(self, percentage: int) -> None: """Handle download progress update.""" - if self._progress_dialog: + if self._progress_dialog and not self._download_cancelled: self._progress_dialog.setValue(percentage) self._progress_dialog.setLabelText(f'Downloading update... {percentage}%') def _on_download_finished(self, success: bool) -> None: """Handle download completion.""" - if self._progress_dialog: - self._progress_dialog.close() - self._progress_dialog = None + self._close_progress() + + if self._download_cancelled: + return if not success: - QMessageBox.warning( - self._window, + self.tray.showMessage( 'Download Failed', 'Failed to download the update. Please try again later.', + QSystemTrayIcon.MessageIcon.Warning, ) return - # Prompt to apply update + # Prompt to apply update - keep as dialog since it needs user choice reply = QMessageBox.question( - self._window, + self._window if self._window.isVisible() else None, 'Download Complete', 'The update has been downloaded.\n\n' 'Would you like to install it now?\n' @@ -255,14 +616,12 @@ def _on_download_finished(self, success: bool) -> None: def _on_download_error(self, error: str) -> None: """Handle download error.""" - if self._progress_dialog: - self._progress_dialog.close() - self._progress_dialog = None + self._close_progress() - QMessageBox.critical( - self._window, + self.tray.showMessage( 'Download Error', - f'An error occurred while downloading the update:\n{error}', + f'An error occurred while downloading: {error}', + QSystemTrayIcon.MessageIcon.Critical, ) def _apply_update(self) -> None: @@ -274,17 +633,16 @@ def _apply_update(self) -> None: # Schedule update to apply on exit, then quit the app self._client.apply_update_on_exit(restart=True) - QMessageBox.information( - self._window, + self.tray.showMessage( 'Update Ready', - 'The update will be applied when the application closes.\n' - 'The application will restart automatically with the new version.', + 'The update will be applied when the application closes.\nThe application will restart automatically.', + QSystemTrayIcon.MessageIcon.Information, ) self._app.quit() except Exception as e: - QMessageBox.warning( - self._window, + self.tray.showMessage( 'Update Failed', f'Failed to apply the update: {e}', + QSystemTrayIcon.MessageIcon.Warning, ) diff --git a/synodic_client/application/theme.py b/synodic_client/application/theme.py new file mode 100644 index 0000000..824b09d --- /dev/null +++ b/synodic_client/application/theme.py @@ -0,0 +1,146 @@ +"""Centralised UI constants, sizes, and style fragments. + +Collecting magic numbers and inline stylesheets here keeps the widget +code focused on layout and behaviour rather than pixel tweaking. +""" + +from __future__ import annotations + +# --------------------------------------------------------------------------- +# Window sizes (width, height) +# --------------------------------------------------------------------------- +INSTALL_PREVIEW_MIN_SIZE = (650, 400) +MAIN_WINDOW_MIN_SIZE = (600, 400) +UPDATE_SOURCE_DIALOG_MIN_WIDTH = 450 + +# --------------------------------------------------------------------------- +# Layout margins (left, top, right, bottom) +# --------------------------------------------------------------------------- +CONTENT_MARGINS = (12, 12, 12, 12) +COMPACT_MARGINS = (8, 8, 8, 8) +NO_MARGINS = (0, 0, 0, 0) + +# --------------------------------------------------------------------------- +# Timers / durations (milliseconds) +# --------------------------------------------------------------------------- +COPY_FEEDBACK_MS = 1200 +"""How long the copy-button shows a ✓ before reverting.""" + +SOCKET_TIMEOUT_MS = 1000 +"""Timeout used by :class:`SingleInstance` socket operations.""" + +# --------------------------------------------------------------------------- +# Fonts +# --------------------------------------------------------------------------- +MONOSPACE_FAMILY = 'Consolas' +MONOSPACE_SIZE = 10 + +# --------------------------------------------------------------------------- +# Copy button +# --------------------------------------------------------------------------- +COPY_ICON = '\U0001f4cb' +COPY_BTN_SIZE = (28, 28) +COPY_BTN_STYLE = ( + 'QToolButton { border: none; padding: 2px 4px; }' + 'QToolButton:hover { background: palette(midlight); border-radius: 3px; }' +) + +# --------------------------------------------------------------------------- +# Stylesheet fragments +# --------------------------------------------------------------------------- +HEADER_STYLE = 'font-size: 14px; font-weight: bold;' +MUTED_STYLE = 'color: grey;' +COMMAND_HEADER_STYLE = 'color: grey; margin-top: 6px;' + +# --------------------------------------------------------------------------- +# Execution log panel +# --------------------------------------------------------------------------- + +# Section header styles +LOG_SECTION_HEADER_STYLE = ( + 'QWidget#sectionHeader {' + ' background: palette(midlight);' + ' border: 1px solid palette(mid);' + ' border-radius: 3px;' + ' padding: 4px 8px;' + '}' +) +LOG_CHEVRON_STYLE = 'font-size: 10px; color: palette(text);' +LOG_SECTION_TITLE_STYLE = 'font-weight: bold; font-size: 12px;' + +# Status badge colours +LOG_STATUS_RUNNING = 'color: #3794ff;' +"""Blue — action is currently executing.""" + +LOG_STATUS_SUCCESS = 'color: #89d185;' +"""Green — action completed successfully.""" + +LOG_STATUS_FAILED = 'color: #f48771;' +"""Red-orange — action failed.""" + +LOG_STATUS_SKIPPED = 'color: grey;' +"""Grey — action was skipped.""" + +# Output text colours (used in HTML spans inside QTextEdit) +LOG_COLOR_STDOUT = '#d4d4d4' +"""Default text — stdout lines.""" + +LOG_COLOR_STDERR = '#d7ba7d' +"""Amber — stderr lines.""" + +LOG_COLOR_PHASE = '#808080' +"""Grey — phase/status messages.""" + +LOG_COLOR_ERROR = '#f48771' +"""Red-orange — error messages.""" + +LOG_COLOR_SUCCESS = '#89d185' +"""Green — success messages.""" + +# Output area style +LOG_OUTPUT_STYLE = ( + 'QTextEdit {' + ' background: #1e1e1e;' + ' border: 1px solid palette(mid);' + ' border-top: none;' + ' border-bottom-left-radius: 3px;' + ' border-bottom-right-radius: 3px;' + ' padding: 6px;' + '}' +) + +# --------------------------------------------------------------------------- +# Plugin section panel +# --------------------------------------------------------------------------- +PLUGIN_GROUP_HEADER_STYLE = 'QWidget#pluginGroupHeader { padding: 6px 4px 2px 0px;}' +"""Style for the collapsible group header in the plugins view.""" + +PLUGIN_GROUP_TITLE_STYLE = 'font-weight: bold; font-size: 13px;' +"""Style for the group heading label text.""" + +PLUGIN_GROUP_SECTION_SPACING = 2 +"""Pixels between plugin sections within a group.""" + +PLUGIN_SECTION_HEADER_STYLE = ( + 'QWidget#pluginHeader {' + ' background: palette(midlight);' + ' border: 1px solid palette(mid);' + ' border-radius: 3px;' + ' padding: 4px 8px;' + '}' +) +PLUGIN_TOGGLE_STYLE = ( + 'QPushButton { padding: 2px 8px; border: 1px solid palette(mid); border-radius: 3px;' + ' min-width: 60px; max-width: 60px; }' + 'QPushButton:checked { background: #89d185; color: black; }' + 'QPushButton:disabled { color: palette(mid); border-color: palette(mid); background: transparent; }' + 'QPushButton:checked:disabled { background: transparent; color: palette(mid); }' +) + +PLUGIN_UPDATE_STYLE = ( + 'QPushButton { padding: 2px 8px; border: 1px solid palette(mid); border-radius: 3px;' + ' min-width: 60px; max-width: 60px; }' + 'QPushButton:disabled { color: palette(mid); border-color: palette(mid); background: transparent; }' +) +PLUGIN_SECTION_SPACING = 4 +"""Pixels between plugin sections in the scroll area.""" diff --git a/synodic_client/application/threading.py b/synodic_client/application/threading.py new file mode 100644 index 0000000..474c9da --- /dev/null +++ b/synodic_client/application/threading.py @@ -0,0 +1,82 @@ +"""Reusable QThread worker runner. + +Encapsulates the boilerplate for moving a ``QObject`` worker onto a +``QThread``, wiring lifecycle signals, and starting execution. + +.. note:: + + The caller **must** store the returned ``ThreadRunner`` as an instance + attribute to prevent premature garbage collection. +""" + +from __future__ import annotations + +from PySide6.QtCore import QObject, QThread, Signal + + +class ThreadRunner(QObject): + """Manages a worker ``QObject`` on a dedicated ``QThread``. + + Usage:: + + runner = ThreadRunner(my_worker) + runner.start() + + The runner connects ``thread.started`` → ``worker.run()`` and ensures + both the thread and worker are cleaned up via ``deleteLater`` when the + thread finishes. + + Callers should connect domain signals (``finished``, ``error``, etc.) + on the *worker* before calling :meth:`start`. + """ + + #: Emitted when the managed thread finishes (for external cleanup). + thread_finished = Signal() + + def __init__(self, worker: QObject, parent: QObject | None = None) -> None: + """Initialise the runner. + + Args: + worker: A ``QObject`` with a ``run()`` slot. Must **not** + already be parented — ``moveToThread`` requires this. + parent: Optional parent for preventing GC. + """ + super().__init__(parent) + self._thread = QThread() + self._worker = worker + worker.moveToThread(self._thread) + + # Start the worker when the thread begins + self._thread.started.connect(worker.run) # type: ignore[attr-defined] + + # Quit-and-cleanup wiring: connect any ``finished`` / ``error`` + # signals on the worker so the thread stops automatically. + for signal_name in ('finished', 'error'): + signal = getattr(worker, signal_name, None) + if signal is not None: + signal.connect(self._thread.quit) + + self._thread.finished.connect(self._thread.deleteLater) + self._thread.finished.connect(worker.deleteLater) + self._thread.finished.connect(self.thread_finished) + + # -- public helpers -- + + def start(self) -> None: + """Start the background thread.""" + self._thread.start() + + def quit_and_wait(self) -> None: + """Ask the thread to quit and block until it finishes.""" + self._thread.quit() + self._thread.wait() + + @property + def managed_thread(self) -> QThread: + """Return the underlying ``QThread``.""" + return self._thread + + @property + def worker(self) -> QObject: + """Return the managed worker.""" + return self._worker diff --git a/synodic_client/cli.py b/synodic_client/cli.py new file mode 100644 index 0000000..0a0a55e --- /dev/null +++ b/synodic_client/cli.py @@ -0,0 +1,41 @@ +"""CLI entry point for the Synodic Client application.""" + +from typing import Annotated + +import typer + +from synodic_client import __version__ +from synodic_client.application.qt import application + +app = typer.Typer( + name='synodic-c', + help='Synodic Client — a system tray frontend for porringer.', + add_completion=False, +) + + +def _version_callback(value: bool) -> None: + """Print the version and exit.""" + if value: + typer.echo(f'synodic-client {__version__}') + raise typer.Exit + + +@app.command() +def main( + uri: Annotated[ + str | None, + typer.Argument(help='A synodic:// URI to process on launch.'), + ] = None, + *, + version: Annotated[ + bool | None, + typer.Option('--version', callback=_version_callback, is_eager=True, help='Show version and exit.'), + ] = None, + dev: Annotated[ + bool, + typer.Option('--dev', help='Run in dev mode with isolated config, logs, and instance lock.'), + ] = False, +) -> None: + """Launch the Synodic Client GUI application.""" + application(uri=uri, dev_mode=dev) diff --git a/synodic_client/config.py b/synodic_client/config.py new file mode 100644 index 0000000..be502d5 --- /dev/null +++ b/synodic_client/config.py @@ -0,0 +1,190 @@ +"""Persistent configuration for the Synodic Client. + +Two configuration layers are supported: + +- **LocalConfiguration** — a portable ``config.json`` next to the executable + (frozen builds only). Written by the packaging script for dev builds. + Fields set here override the global configuration. + +- **GlobalConfiguration** — a user-scoped ``config.json`` in the OS application + data directory. On Windows this is ``%LOCALAPPDATA%/Synodic/config.json``. + Persisted by the Settings UI. + +Merging and resolution of these layers is handled by +:mod:`synodic_client.resolution`. +""" + +import json +import logging +import os +import sys +from pathlib import Path + +from pydantic import BaseModel + +logger = logging.getLogger(__name__) + +_APP_NAME = 'Synodic' +_APP_NAME_DEV = 'Synodic-Dev' +_CONFIG_FILENAME = 'config.json' + +_dev_mode: bool = False + + +def set_dev_mode(enabled: bool) -> None: + """Enable or disable dev-mode path namespacing. + + When enabled, :func:`config_dir` returns a separate directory so that + the development build does not share state with the user-installed + application. + + Must be called **before** any configuration is loaded. + + Args: + enabled: ``True`` to activate dev-mode namespacing. + """ + global _dev_mode # noqa: PLW0603 + _dev_mode = enabled + + +def is_dev_mode() -> bool: + """Return whether dev-mode namespacing is active.""" + return _dev_mode + + +class _ConfigBase(BaseModel): + """Shared fields for both configuration layers.""" + + # URL or local file path for Velopack releases. + # None means use the default GitHub release source. + update_source: str | None = None + + # Update channel: "stable" or "dev". + # None means auto-detect from sys.frozen. + update_channel: str | None = None + + # Interval in minutes between automatic update checks. + # 0 disables automatic checking. None uses the default (30 minutes). + auto_update_interval_minutes: int | None = None + + # Interval in minutes between tool update checks. + # 0 disables automatic checking. None uses the default (20 minutes). + tool_update_interval_minutes: int | None = None + + # Per-plugin auto-update toggle. Maps plugin name to enabled state. + # None or absent means all plugins auto-update. Explicitly False + # entries disable auto-update for that plugin. + plugin_auto_update: dict[str, bool] | None = None + + +class LocalConfiguration(_ConfigBase): + """Portable configuration embedded next to the executable. + + Written by the packaging script (e.g. ``pdm run package -- --local-source``). + Fields set here override the corresponding ``GlobalConfiguration`` values. + """ + + +class GlobalConfiguration(_ConfigBase): + """User-scoped configuration persisted in the OS application data directory. + + On Windows: ``%LOCALAPPDATA%/Synodic/config.json``. + """ + + +def _portable_config_path() -> Path | None: + """Return the path to a portable config file next to the executable, if it exists. + + Only checked when running as a frozen (PyInstaller) build. + + Returns: + Path to the portable config file, or None if not applicable. + """ + if not getattr(sys, 'frozen', False): + return None + + exe_dir = Path(sys.executable).resolve().parent + candidate = exe_dir / _CONFIG_FILENAME + if candidate.exists(): + return candidate + return None + + +def _load_local_config() -> LocalConfiguration | None: + """Load the portable local configuration, if present. + + Returns: + The loaded local config, or None. + """ + portable = _portable_config_path() + if portable is None: + return None + + try: + data = json.loads(portable.read_text(encoding='utf-8')) + config = LocalConfiguration.model_validate(data) + logger.debug('Loaded local config from %s', portable) + return config + except Exception: + logger.exception('Failed to load local config from %s', portable) + return None + + +def config_dir() -> Path: + """Return the platform-appropriate global configuration directory. + + When dev-mode is active (see :func:`set_dev_mode`) the returned path + is namespaced (e.g. ``Synodic-Dev``) so that development and + user-installed builds maintain independent configuration. + + Returns: + Path to the configuration directory. + """ + app_name = _APP_NAME_DEV if _dev_mode else _APP_NAME + + if sys.platform == 'win32': + base = os.environ.get('LOCALAPPDATA', '') + if not base: + base = str(Path.home() / 'AppData' / 'Local') + return Path(base) / app_name + # Stub for non-Windows platforms + logger.warning('Config directory is not fully supported on %s', sys.platform) + return Path.home() / f'.{app_name.lower()}' + + +def _load_global_config() -> GlobalConfiguration: + """Load the global configuration from the OS data directory. + + Returns: + The loaded or default global configuration. + """ + path = config_dir() / _CONFIG_FILENAME + if not path.exists(): + logger.debug('No global config at %s, using defaults', path) + return GlobalConfiguration() + + try: + data = json.loads(path.read_text(encoding='utf-8')) + config = GlobalConfiguration.model_validate(data) + logger.debug('Loaded global config from %s', path) + return config + except Exception: + logger.exception('Failed to load global config from %s, using defaults', path) + return GlobalConfiguration() + + +def save_config(config: GlobalConfiguration) -> None: + """Save configuration to the global (system) config directory. + + Args: + config: The configuration to persist. + """ + directory = config_dir() + directory.mkdir(parents=True, exist_ok=True) + path = directory / _CONFIG_FILENAME + + try: + path.write_text(config.model_dump_json(indent=2), encoding='utf-8') + logger.info('Saved config to %s', path) + except Exception: + logger.exception('Failed to save config to %s', path) diff --git a/synodic_client/logging.py b/synodic_client/logging.py new file mode 100644 index 0000000..040cb6b --- /dev/null +++ b/synodic_client/logging.py @@ -0,0 +1,84 @@ +"""Centralised logging configuration for the Synodic Client. + +Provides a rotating file handler with eager flushing and a helper to open +the current log file in the system's default editor. +""" + +import logging +import tempfile +from logging.handlers import RotatingFileHandler +from pathlib import Path + +from PySide6.QtCore import QUrl +from PySide6.QtGui import QDesktopServices + +from synodic_client.config import is_dev_mode + +_LOG_FILENAME = 'synodic.log' +_LOG_FILENAME_DEV = 'synodic-dev.log' +_MAX_BYTES = 5_242_880 # 5 MB +_BACKUP_COUNT = 3 +_FORMAT = '%(asctime)s [%(levelname)s] %(name)s: %(message)s' + + +def log_path() -> Path: + """Return the path to the application log file. + + The file lives in the system temp directory so it is cleaned up + automatically by the OS and avoids permission issues. + + Returns: + Path to the log file. + """ + return Path(tempfile.gettempdir()) / (_LOG_FILENAME_DEV if is_dev_mode() else _LOG_FILENAME) + + +class EagerRotatingFileHandler(RotatingFileHandler): + """RotatingFileHandler that flushes after every record. + + This ensures log entries are visible immediately when the file is + opened in an external editor. + """ + + def emit(self, record: logging.LogRecord) -> None: + """Emit a record and flush the stream.""" + super().emit(record) + self.flush() + + +def configure_logging() -> None: + """Set up application-wide logging. + + Attaches a :class:`EagerRotatingFileHandler` to the ``synodic_client`` + and ``porringer`` loggers and configures :func:`logging.basicConfig` + for ``INFO`` level output on *stderr*. + """ + logging.basicConfig(level=logging.INFO) + + handler = EagerRotatingFileHandler( + str(log_path()), + maxBytes=_MAX_BYTES, + backupCount=_BACKUP_COUNT, + encoding='utf-8', + ) + handler.setFormatter(logging.Formatter(_FORMAT)) + + app_logger = logging.getLogger('synodic_client') + app_logger.addHandler(handler) + + porringer_logger = logging.getLogger('porringer') + porringer_logger.addHandler(handler) + porringer_logger.setLevel(logging.INFO) + + +def open_log() -> None: + """Open the log file in the system's default editor. + + Creates an empty file if one does not yet exist so that the OS always + has something to open. + """ + path = log_path() + if not path.exists(): + path.touch() + + QDesktopServices.openUrl(QUrl.fromLocalFile(str(path))) diff --git a/synodic_client/protocol.py b/synodic_client/protocol.py new file mode 100644 index 0000000..8bfb60a --- /dev/null +++ b/synodic_client/protocol.py @@ -0,0 +1,83 @@ +r"""URI protocol handler registration for the ``synodic://`` scheme. + +On Windows this writes registry keys under ``HKCU\Software\Classes\synodic`` +so that clicking a ``synodic://`` link in a browser or file manager launches the +Synodic Client with the URI as an argument. + +Other platforms are stubbed with no-op implementations. +""" + +import logging +import sys + +if sys.platform == 'win32': + import winreg + +logger = logging.getLogger(__name__) + +PROTOCOL_NAME = 'synodic' +_PROTOCOL_DESCRIPTION = 'Synodic Client Protocol' + + +def register_protocol(exe_path: str) -> None: + """Register the ``synodic://`` URI protocol handler. + + Args: + exe_path: Absolute path to the application executable. + """ + if sys.platform != 'win32': + logger.warning('Protocol registration is only supported on Windows (current: %s)', sys.platform) + return + + key_path = f'Software\\Classes\\{PROTOCOL_NAME}' + + try: + # Create the protocol key + with winreg.CreateKey(winreg.HKEY_CURRENT_USER, key_path) as key: + winreg.SetValueEx(key, '', 0, winreg.REG_SZ, _PROTOCOL_DESCRIPTION) + winreg.SetValueEx(key, 'URL Protocol', 0, winreg.REG_SZ, '') + + # Create the shell\open\command key with the exe path + command_path = f'{key_path}\\shell\\open\\command' + with winreg.CreateKey(winreg.HKEY_CURRENT_USER, command_path) as key: + winreg.SetValueEx(key, '', 0, winreg.REG_SZ, f'"{exe_path}" "%1"') + + logger.info('Registered synodic:// protocol handler -> %s', exe_path) + except OSError: + logger.exception('Failed to register synodic:// protocol handler') + + +def remove_protocol() -> None: + """Remove the ``synodic://`` URI protocol handler registration.""" + if sys.platform != 'win32': + logger.warning('Protocol removal is only supported on Windows (current: %s)', sys.platform) + return + + key_path = f'Software\\Classes\\{PROTOCOL_NAME}' + + try: + _delete_key_recursive(winreg.HKEY_CURRENT_USER, key_path) + logger.info('Removed synodic:// protocol handler registration') + except FileNotFoundError: + logger.debug('Protocol handler registration not found, nothing to remove') + except OSError: + logger.exception('Failed to remove synodic:// protocol handler') + + +def _delete_key_recursive(root: int, key_path: str) -> None: + """Recursively delete a registry key and all its subkeys. + + Args: + root: Registry root (e.g. ``winreg.HKEY_CURRENT_USER``). + key_path: Path to the key to delete. + """ + with winreg.OpenKey(root, key_path, 0, winreg.KEY_ALL_ACCESS) as key: + # Enumerate and delete all subkeys first + while True: + try: + subkey_name = winreg.EnumKey(key, 0) + _delete_key_recursive(root, f'{key_path}\\{subkey_name}') + except OSError: + break + + winreg.DeleteKey(root, key_path) diff --git a/synodic_client/resolution.py b/synodic_client/resolution.py new file mode 100644 index 0000000..3117459 --- /dev/null +++ b/synodic_client/resolution.py @@ -0,0 +1,140 @@ +"""Configuration resolution for the Synodic Client. + +Merges ``LocalConfiguration`` (portable, next to exe) and ``GlobalConfiguration`` +(user-scoped, ``%LOCALAPPDATA%``) into a single resolved configuration, then +derives runtime objects like ``UpdateConfig``. +""" + +import logging +import sys + +from synodic_client.config import ( + GlobalConfiguration, + LocalConfiguration, + _load_global_config, + _load_local_config, + save_config, +) +from synodic_client.updater import ( + DEFAULT_AUTO_UPDATE_INTERVAL_MINUTES, + DEFAULT_TOOL_UPDATE_INTERVAL_MINUTES, + GITHUB_REPO_URL, + UpdateChannel, + UpdateConfig, +) + +logger = logging.getLogger(__name__) + + +def merge_config( + global_config: GlobalConfiguration, + local_config: LocalConfiguration | None, +) -> GlobalConfiguration: + """Merge local overrides into a global configuration. + + Fields explicitly set (not None) in the local config override the + corresponding global values. + + Args: + global_config: The user-scoped global configuration. + local_config: The portable local configuration, or None. + + Returns: + A ``GlobalConfiguration`` with merged values. + """ + if local_config is None: + return global_config + + merged = global_config.model_dump() + for field_name, value in local_config.model_dump().items(): + if value is not None: + merged[field_name] = value + + return GlobalConfiguration.model_validate(merged) + + +def resolve_config() -> GlobalConfiguration: + """Load and merge both configuration layers. + + Returns: + A fully resolved ``GlobalConfiguration``. + """ + return merge_config(_load_global_config(), _load_local_config()) + + +def resolve_update_config(config: GlobalConfiguration) -> UpdateConfig: + """Derive an ``UpdateConfig`` from resolved configuration values. + + Args: + config: A resolved global configuration. + + Returns: + An ``UpdateConfig`` ready to initialise the updater. + """ + is_dev = not getattr(sys, 'frozen', False) + + if config.update_channel is not None: + channel = UpdateChannel.DEVELOPMENT if config.update_channel == 'dev' else UpdateChannel.STABLE + else: + channel = UpdateChannel.DEVELOPMENT if is_dev else UpdateChannel.STABLE + + repo_url = config.update_source or GITHUB_REPO_URL + + interval = config.auto_update_interval_minutes + if interval is None: + interval = DEFAULT_AUTO_UPDATE_INTERVAL_MINUTES + + tool_interval = config.tool_update_interval_minutes + if tool_interval is None: + tool_interval = DEFAULT_TOOL_UPDATE_INTERVAL_MINUTES + + return UpdateConfig( + channel=channel, + repo_url=repo_url, + auto_update_interval_minutes=interval, + tool_update_interval_minutes=tool_interval, + ) + + +def resolve_enabled_plugins( + config: GlobalConfiguration, + all_plugin_names: list[str], +) -> list[str] | None: + """Derive the include-list of plugins that should auto-update. + + Returns the list of plugin names whose auto-update is **not** disabled. + If all plugins are enabled (the common case), returns ``None`` to + indicate "no filtering". + + Args: + config: A resolved global configuration. + all_plugin_names: Every known plugin name. + + Returns: + A list of enabled plugin names, or ``None`` when all are enabled. + """ + mapping = config.plugin_auto_update + if not mapping: + return None + + disabled = {name for name, enabled in mapping.items() if not enabled} + if not disabled: + return None + + return [n for n in all_plugin_names if n not in disabled] + + +def update_and_resolve(config: GlobalConfiguration) -> UpdateConfig: + """Save a modified global config and resolve it into an UpdateConfig. + + Convenience function for the Settings UI: persists the change, then + returns the derived ``UpdateConfig``. + + Args: + config: The modified global configuration to save. + + Returns: + An ``UpdateConfig`` derived from the saved configuration. + """ + save_config(config) + return resolve_update_config(config) diff --git a/synodic_client/schema.py b/synodic_client/schema.py deleted file mode 100644 index 08d93e1..0000000 --- a/synodic_client/schema.py +++ /dev/null @@ -1,49 +0,0 @@ -"""Schema for the client""" - -from enum import StrEnum - -from pydantic import BaseModel - - -class VersionInformation(BaseModel): - """Comparable information that can be extracted from a Python package""" - - version: str - - -class UpdateChannel(StrEnum): - """Update channel for selecting release types.""" - - STABLE = 'stable' - DEVELOPMENT = 'development' - - -class UpdateStatus(StrEnum): - """Status of an update check or operation.""" - - NO_UPDATE = 'no_update' - UPDATE_AVAILABLE = 'update_available' - DOWNLOADING = 'downloading' - DOWNLOADED = 'downloaded' - APPLYING = 'applying' - APPLIED = 'applied' - FAILED = 'failed' - ROLLBACK_REQUIRED = 'rollback_required' - - -class UpdateCheckResult(BaseModel): - """Result of an update check operation.""" - - status: UpdateStatus - current_version: str - latest_version: str | None = None - download_url: str | None = None - error_message: str | None = None - - -class UpdateProgress(BaseModel): - """Progress information for an update download.""" - - bytes_downloaded: int - total_bytes: int | None = None - percentage: float | None = None diff --git a/synodic_client/updater.py b/synodic_client/updater.py index f0f37a7..791bb35 100644 --- a/synodic_client/updater.py +++ b/synodic_client/updater.py @@ -11,12 +11,14 @@ import sys from collections.abc import Callable from dataclasses import dataclass, field -from enum import Enum, auto +from enum import Enum, StrEnum, auto from typing import Any import velopack from packaging.version import Version +from synodic_client.protocol import register_protocol, remove_protocol + logger = logging.getLogger(__name__) # GitHub repository for Velopack updates @@ -24,11 +26,11 @@ GITHUB_REPO_URL = 'https://github.com/synodic/synodic-client' -class UpdateChannel(Enum): +class UpdateChannel(StrEnum): """Update channel selection.""" - STABLE = auto() - DEVELOPMENT = auto() + STABLE = 'stable' + DEVELOPMENT = 'development' class UpdateState(Enum): @@ -56,6 +58,13 @@ class UpdateInfo: _velopack_info: Any = field(default=None, repr=False) +# Default interval for automatic update checks (minutes) +DEFAULT_AUTO_UPDATE_INTERVAL_MINUTES = 30 + +# Default interval for tool update checks (minutes) +DEFAULT_TOOL_UPDATE_INTERVAL_MINUTES = 20 + + @dataclass class UpdateConfig: """Configuration for the updater.""" @@ -66,6 +75,12 @@ class UpdateConfig: # Channel determines whether to use dev or stable releases channel: UpdateChannel = UpdateChannel.STABLE + # Interval in minutes between automatic update checks (0 = disabled) + auto_update_interval_minutes: int = DEFAULT_AUTO_UPDATE_INTERVAL_MINUTES + + # Interval in minutes between tool update checks (0 = disabled) + tool_update_interval_minutes: int = DEFAULT_TOOL_UPDATE_INTERVAL_MINUTES + @property def channel_name(self) -> str: """Get the channel name for Velopack.""" @@ -293,15 +308,42 @@ def _get_velopack_manager(self) -> Any: return None +def _on_after_install(version: str) -> None: # noqa: ARG001 + """Velopack hook: called after the app is installed. + + Registers the ``synodic://`` URI protocol handler. + + Args: + version: The installed version string (provided by Velopack). + """ + register_protocol(sys.executable) + + +def _on_before_uninstall(version: str) -> None: # noqa: ARG001 + """Velopack hook: called before the app is uninstalled. + + Removes the ``synodic://`` URI protocol handler registration. + + Args: + version: The current version string (provided by Velopack). + """ + remove_protocol() + + def initialize_velopack() -> None: """Initialize Velopack at application startup. This should be called as early as possible in the application lifecycle, before any UI is shown. Velopack may need to perform cleanup or apply pending updates. + + On Windows, install/uninstall hooks register the ``synodic://`` URI protocol. """ try: - velopack.App().run() # type: ignore[attr-defined] + app = velopack.App() # type: ignore[attr-defined] + app.on_after_install_fast_callback(_on_after_install) + app.on_before_uninstall_fast_callback(_on_before_uninstall) + app.run() logger.debug('Velopack initialized') except Exception as e: logger.debug('Velopack initialization skipped: %s', e) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..8772b22 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,21 @@ +"""Shared pytest fixtures for the Synodic Client test suite.""" + +from pathlib import Path + +import pytest + +_REPO_ROOT = Path(__file__).resolve().parents[1] +_EXAMPLES_DIR = _REPO_ROOT / 'examples' + + +def _discover_example_dirs() -> list[Path]: + """Return all subdirectories under ``examples/``.""" + if not _EXAMPLES_DIR.is_dir(): + return [] + return sorted(child for child in _EXAMPLES_DIR.iterdir() if child.is_dir()) + + +@pytest.fixture(params=_discover_example_dirs(), ids=lambda p: p.name) +def example_dir(request: pytest.FixtureRequest) -> Path: + """Parametrised fixture yielding each example directory in turn.""" + return request.param diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py new file mode 100644 index 0000000..5d6dd01 --- /dev/null +++ b/tests/unit/test_cli.py @@ -0,0 +1,52 @@ +"""Tests for the CLI entry point.""" + +from unittest.mock import patch + +from typer.testing import CliRunner + +from synodic_client.cli import app + +runner = CliRunner() + + +class TestCli: + """Tests for the synodic-c CLI.""" + + @staticmethod + def test_version() -> None: + """Verify --version prints the version string.""" + result = runner.invoke(app, ['--version']) + assert result.exit_code == 0 + assert 'synodic-client' in result.output + + @staticmethod + def test_help() -> None: + """Verify --help shows usage information.""" + result = runner.invoke(app, ['--help']) + assert result.exit_code == 0 + assert 'synodic://' in result.output.lower() or 'uri' in result.output.lower() + + @staticmethod + def test_launches_application_without_uri() -> None: + """Verify invoking with no args calls application(uri=None, dev_mode=False).""" + with patch('synodic_client.cli.application') as mock_app: + result = runner.invoke(app, []) + assert result.exit_code == 0 + mock_app.assert_called_once_with(uri=None, dev_mode=False) + + @staticmethod + def test_launches_application_with_uri() -> None: + """Verify invoking with a URI passes it to application().""" + test_uri = 'synodic://install?manifest=https://example.com/foo.json' + with patch('synodic_client.cli.application') as mock_app: + result = runner.invoke(app, [test_uri]) + assert result.exit_code == 0 + mock_app.assert_called_once_with(uri=test_uri, dev_mode=False) + + @staticmethod + def test_launches_application_with_dev_flag() -> None: + """Verify --dev flag sets dev_mode=True.""" + with patch('synodic_client.cli.application') as mock_app: + result = runner.invoke(app, ['--dev']) + assert result.exit_code == 0 + mock_app.assert_called_once_with(uri=None, dev_mode=True) diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py new file mode 100644 index 0000000..23fb411 --- /dev/null +++ b/tests/unit/test_config.py @@ -0,0 +1,167 @@ +"""Tests for the persistent configuration module.""" + +import json +from pathlib import Path +from unittest.mock import patch + +import pytest + +from synodic_client.config import ( + GlobalConfiguration, + LocalConfiguration, + config_dir, + save_config, + set_dev_mode, +) + + +class TestLocalConfiguration: + """Tests for the LocalConfiguration model.""" + + @staticmethod + def test_defaults() -> None: + """Verify default values for a fresh config.""" + config = LocalConfiguration() + assert config.update_source is None + assert config.update_channel is None + assert config.auto_update_interval_minutes is None + assert config.tool_update_interval_minutes is None + assert config.plugin_auto_update is None + + @staticmethod + def test_with_values() -> None: + """Verify config accepts explicit values.""" + config = LocalConfiguration(update_source='/path/to/releases', update_channel='dev') + assert config.update_source == '/path/to/releases' + assert config.update_channel == 'dev' + + +class TestGlobalConfiguration: + """Tests for the GlobalConfiguration model.""" + + @staticmethod + def test_defaults() -> None: + """Verify default values for a fresh config.""" + config = GlobalConfiguration() + assert config.update_source is None + assert config.update_channel is None + assert config.auto_update_interval_minutes is None + assert config.tool_update_interval_minutes is None + assert config.plugin_auto_update is None + + @staticmethod + def test_with_values() -> None: + """Verify config accepts explicit values.""" + config = GlobalConfiguration(update_source='/path/to/releases', update_channel='dev') + assert config.update_source == '/path/to/releases' + assert config.update_channel == 'dev' + + @staticmethod + def test_plugin_auto_update_round_trip() -> None: + """Verify plugin_auto_update survives JSON round-trip.""" + mapping = {'pipx': False, 'pip': True} + original = GlobalConfiguration(plugin_auto_update=mapping) + data = json.loads(original.model_dump_json()) + restored = GlobalConfiguration.model_validate(data) + assert restored.plugin_auto_update == mapping + + @staticmethod + def test_json_round_trip() -> None: + """Verify config can round-trip through JSON.""" + original = GlobalConfiguration(update_source='https://example.com', update_channel='stable') + data = json.loads(original.model_dump_json()) + restored = GlobalConfiguration.model_validate(data) + assert restored == original + + @staticmethod + def test_json_round_trip_defaults() -> None: + """Verify default config round-trips cleanly.""" + original = GlobalConfiguration() + data = json.loads(original.model_dump_json()) + restored = GlobalConfiguration.model_validate(data) + assert restored.update_source is None + assert restored.update_channel is None + + @staticmethod + def test_extra_fields_ignored() -> None: + """Verify unrecognized fields do not cause errors.""" + data = {'update_source': None, 'update_channel': None, 'unknown_field': 42} + config = GlobalConfiguration.model_validate(data) + assert config.update_source is None + + +class TestConfigDir: + """Tests for the config_dir helper.""" + + @staticmethod + @pytest.mark.skipif(__import__('sys').platform != 'win32', reason='Windows only') + def test_windows_uses_localappdata() -> None: + """Verify config dir uses LOCALAPPDATA on Windows.""" + with patch.dict('os.environ', {'LOCALAPPDATA': 'C:\\Users\\Test\\AppData\\Local'}): + result = config_dir() + assert result == Path('C:\\Users\\Test\\AppData\\Local\\Synodic') + + @staticmethod + @pytest.mark.skipif(__import__('sys').platform != 'win32', reason='Windows only') + def test_windows_fallback_without_env() -> None: + """Verify fallback when LOCALAPPDATA is not set.""" + with patch.dict('os.environ', {'LOCALAPPDATA': ''}): + result = config_dir() + # Should still produce a path ending in Synodic + assert result.name == 'Synodic' + + @staticmethod + @pytest.mark.skipif(__import__('sys').platform != 'win32', reason='Windows only') + def test_dev_mode_uses_separate_dir() -> None: + """Verify config dir is namespaced when dev mode is active.""" + set_dev_mode(True) + try: + with patch.dict('os.environ', {'LOCALAPPDATA': 'C:\\Users\\Test\\AppData\\Local'}): + result = config_dir() + assert result == Path('C:\\Users\\Test\\AppData\\Local\\Synodic-Dev') + finally: + set_dev_mode(False) + + +class TestSaveConfig: + """Tests for save_config.""" + + @staticmethod + def test_creates_file(tmp_path: Path) -> None: + """Verify config is saved to disk.""" + config = GlobalConfiguration(update_source='/my/releases', update_channel='stable') + + with patch('synodic_client.config.config_dir', return_value=tmp_path): + save_config(config) + + saved_path = tmp_path / 'config.json' + assert saved_path.exists() + + data = json.loads(saved_path.read_text(encoding='utf-8')) + assert data['update_source'] == '/my/releases' + assert data['update_channel'] == 'stable' + + @staticmethod + def test_creates_directory(tmp_path: Path) -> None: + """Verify save_config creates the directory if missing.""" + nested = tmp_path / 'nested' / 'dir' + config = GlobalConfiguration() + + with patch('synodic_client.config.config_dir', return_value=nested): + save_config(config) + + assert (nested / 'config.json').exists() + + @staticmethod + def test_overwrites_existing(tmp_path: Path) -> None: + """Verify save_config overwrites an existing file.""" + config_path = tmp_path / 'config.json' + config_path.write_text('{}', encoding='utf-8') + + config = GlobalConfiguration(update_source='http://new-source') + + with patch('synodic_client.config.config_dir', return_value=tmp_path): + save_config(config) + + data = json.loads(config_path.read_text(encoding='utf-8')) + assert data['update_source'] == 'http://new-source' diff --git a/tests/unit/test_examples.py b/tests/unit/test_examples.py new file mode 100644 index 0000000..f743378 --- /dev/null +++ b/tests/unit/test_examples.py @@ -0,0 +1,49 @@ +"""Tests that run across all example directories. + +These validate client-level invariants — not porringer manifest semantics. +""" + +import re +from pathlib import Path + +from synodic_client.application.qt import parse_uri + +_URI_PATTERN = re.compile(r'synodic://\S+') + + +def _extract_uris_from_file(path: Path) -> list[str]: + """Extract all ``synodic://`` URIs from a text file.""" + text = path.read_text(encoding='utf-8') + return _URI_PATTERN.findall(text) + + +def _collect_uris(directory: Path) -> list[str]: + """Collect every ``synodic://`` URI found in any text file in *directory*.""" + uris: list[str] = [] + for child in directory.iterdir(): + if child.is_file() and child.suffix in {'.md', '.toml', '.json', '.txt'}: + uris.extend(_extract_uris_from_file(child)) + return uris + + +class TestExampleStructure: + """Validate the structure of each example directory.""" + + @staticmethod + def test_has_readme(example_dir: Path) -> None: + """Every example must include a README.""" + assert (example_dir / 'README.md').exists(), f'{example_dir.name}/ is missing a README.md' + + +class TestExampleUris: + """Validate any ``synodic://`` URIs embedded in example files.""" + + @staticmethod + def test_embedded_uris_are_parseable(example_dir: Path) -> None: + """Every embedded synodic:// URI must be parseable by the client.""" + uris = _collect_uris(example_dir) + + for uri in uris: + parsed = parse_uri(uri) + assert 'action' in parsed, f'URI missing action: {uri}' + assert parsed['action'], f'URI has empty action: {uri}' diff --git a/tests/unit/test_install_preview.py b/tests/unit/test_install_preview.py new file mode 100644 index 0000000..2178a59 --- /dev/null +++ b/tests/unit/test_install_preview.py @@ -0,0 +1,483 @@ +"""Tests for the install preview window and URI-based install flow.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock + +from porringer.schema import ( + CancellationToken, + DownloadResult, + PluginKind, + ProgressEvent, + ProgressEventKind, + SetupActionResult, + SetupResults, + SkipReason, +) + +from synodic_client.application.qt import parse_uri +from synodic_client.application.screen import ( + ACTION_KIND_LABELS, + SKIP_REASON_LABELS, + skip_reason_label, +) +from synodic_client.application.screen.install import ( + InstallWorker, + PreviewWorker, + format_cli_command, + resolve_local_path, +) + + +class TestParseUriInstall: + """Tests for parsing install URIs.""" + + @staticmethod + def test_install_action_parsed() -> None: + """Verify the action is 'install' for an install URI.""" + result = parse_uri('synodic://install?manifest=https://example.com/porringer.json') + assert result['action'] == 'install' + + @staticmethod + def test_manifest_key_present() -> None: + """Verify the manifest query parameter is extracted.""" + result = parse_uri('synodic://install?manifest=https://example.com/porringer.json') + assert 'manifest' in result + assert isinstance(result['manifest'], list) + assert result['manifest'][0] == 'https://example.com/porringer.json' + + @staticmethod + def test_multiple_manifests() -> None: + """Verify multiple manifest values are captured.""" + result = parse_uri('synodic://install?manifest=https://a.com/a.json&manifest=https://b.com/b.json') + manifests = result['manifest'] + assert isinstance(manifests, list) + assert len(manifests) == 2 # noqa: PLR2004 + + @staticmethod + def test_unknown_action() -> None: + """Verify unknown actions are still parsed without error.""" + result = parse_uri('synodic://unknown?foo=bar') + assert result['action'] == 'unknown' + + +class TestInstallPreviewWindow: + """Tests for InstallPreviewWindow table population logic.""" + + @staticmethod + def _make_action( + kind: str = 'PACKAGE', + description: str = 'Install test', + installer: str = 'pip', + package: str = 'requests', + ) -> MagicMock: + """Create a mock SetupAction.""" + action = MagicMock() + action.kind = getattr(PluginKind, kind) + action.description = description + action.installer = installer + action.package = package + action.command = None + action.cli_command = None + return action + + @staticmethod + def test_action_kind_labels() -> None: + """Verify action kind label mapping covers all kinds plus None.""" + for plugin_kind in PluginKind: + assert plugin_kind in ACTION_KIND_LABELS + assert None in ACTION_KIND_LABELS + + @staticmethod + def test_skip_reason_labels() -> None: + """Verify skip reason label mapping covers all reasons.""" + for reason in SkipReason: + assert reason in SKIP_REASON_LABELS + + @staticmethod + def test_skip_reason_label_human_readable() -> None: + """Verify skip reason labels are human-readable, not raw enum names.""" + assert skip_reason_label(SkipReason.ALREADY_INSTALLED) == 'Already installed' + assert skip_reason_label(None) == 'Skipped' + + +class TestFormatCliCommand: + """Tests for format_cli_command helper.""" + + @staticmethod + def _make_action(**overrides: Any) -> MagicMock: + """Create a mock SetupAction with optional attribute overrides.""" + defaults: dict[str, Any] = { + 'kind': 'PACKAGE', + 'description': 'Install test', + 'installer': 'pip', + 'package': 'requests', + 'cli_command': None, + 'command': None, + } + defaults.update(overrides) + action = MagicMock() + kind = defaults['kind'] + action.kind = getattr(PluginKind, kind) if isinstance(kind, str) else kind + action.description = defaults['description'] + action.installer = defaults['installer'] + action.package = defaults['package'] + action.command = defaults['command'] + action.cli_command = defaults['cli_command'] + return action + + def test_prefers_cli_command(self) -> None: + """Verify cli_command takes precedence over command and fallback.""" + action = self._make_action(cli_command=['uv', 'pip', 'install', 'requests']) + assert format_cli_command(action) == 'uv pip install requests' + + def test_falls_back_to_command(self) -> None: + """Verify command is used when cli_command is absent.""" + action = self._make_action( + kind='TOOL', + command=['echo', 'hello'], + ) + assert format_cli_command(action) == 'echo hello' + + def test_synthesises_package_command(self) -> None: + """Verify package actions synthesise installer + package.""" + action = self._make_action(installer='pip', package='ruff') + assert format_cli_command(action) == 'pip install ruff' + + def test_synthesises_default_installer(self) -> None: + """Verify pip is used as default installer for package actions.""" + action = self._make_action(installer=None, package='ruff') + assert format_cli_command(action) == 'pip install ruff' + + def test_description_fallback(self) -> None: + """Verify description is returned when nothing else is available.""" + action = self._make_action( + kind='TOOL', + description='Custom step', + package=None, + ) + assert format_cli_command(action) == 'Custom step' + + +class TestInstallWorker: + """Tests for InstallWorker signal emission.""" + + @staticmethod + def test_worker_emits_finished_on_success() -> None: + """Verify worker emits finished signal with results.""" + porringer = MagicMock() + manifest_path = Path('/tmp/test/porringer.json') + + action = MagicMock() + manifest = SetupResults(actions=[action]) + manifest_event = ProgressEvent(kind=ProgressEventKind.MANIFEST_LOADED, manifest=manifest) + + result = MagicMock(spec=SetupActionResult) + completed_event = ProgressEvent( + kind=ProgressEventKind.ACTION_COMPLETED, + action=action, + result=result, + ) + + async def mock_stream(*args, **kwargs): # noqa: ANN002, ANN003 + yield manifest_event + yield completed_event + + porringer.sync.execute_stream = mock_stream + + token = CancellationToken() + worker = InstallWorker(porringer, manifest_path, token) + + received: list[SetupResults] = [] + worker.finished.connect(received.append) + worker.run() + + assert len(received) == 1 + assert received[0].actions == manifest.actions + + @staticmethod + def test_worker_emits_error_on_failure() -> None: + """Verify worker emits error signal on exception.""" + porringer = MagicMock() + manifest_path = Path('/tmp/test/porringer.json') + + async def mock_stream(*args, **kwargs): # noqa: ANN002, ANN003 + if False: + yield # pragma: no cover — establishes async generator protocol + msg = 'boom' + raise RuntimeError(msg) + + porringer.sync.execute_stream = mock_stream + + token = CancellationToken() + worker = InstallWorker(porringer, manifest_path, token) + + errors: list[str] = [] + worker.error.connect(errors.append) + worker.run() + + assert len(errors) == 1 + assert 'boom' in errors[0] + + +class TestResolveLocalPath: + """Tests for _resolve_local_path helper.""" + + @staticmethod + def test_http_url_returns_none() -> None: + """HTTP URLs should not resolve to a local path.""" + assert resolve_local_path('https://example.com/porringer.json') is None + + @staticmethod + def test_absolute_path_returns_path() -> None: + """Absolute OS paths should resolve.""" + result = resolve_local_path('C:\\Users\\test\\porringer.json') + assert result is not None + assert result == Path('C:\\Users\\test\\porringer.json') + + @staticmethod + def test_file_uri_returns_path() -> None: + """file:// URIs should resolve to a local path.""" + result = resolve_local_path('file:///C:/Users/test/porringer.json') + assert result is not None + assert 'porringer.json' in str(result) + + @staticmethod + def test_existing_relative_path(tmp_path: Path) -> None: + """Relative paths that exist on disk should resolve.""" + manifest = tmp_path / 'porringer.json' + manifest.write_text('{}') + result = resolve_local_path(str(manifest)) + assert result is not None + + +class TestPreviewWorkerLocal: + """Tests for PreviewWorker with local manifest files.""" + + @staticmethod + def test_local_manifest_skips_download(tmp_path: Path) -> None: + """Verify PreviewWorker skips download for local files.""" + manifest = tmp_path / 'porringer.json' + manifest.write_text('{}') + + porringer = MagicMock() + expected = SetupResults(actions=[]) + manifest_event = ProgressEvent(kind=ProgressEventKind.MANIFEST_LOADED, manifest=expected) + + async def mock_stream(*args: Any, **kwargs: Any) -> Any: + yield manifest_event + + porringer.sync.execute_stream = mock_stream + + worker = PreviewWorker(porringer, str(manifest)) + + results: list[tuple[object, str, str]] = [] + worker.preview_ready.connect(lambda r, p, t: results.append((r, p, t))) + worker.run() + + assert len(results) == 1 + assert results[0][0] is expected + # download should NOT have been called + porringer.sync.download.assert_not_called() + + @staticmethod + def test_local_manifest_not_found() -> None: + """Verify PreviewWorker emits error for missing local file.""" + porringer = MagicMock() + worker = PreviewWorker(porringer, 'C:\\nonexistent\\porringer.json') + + errors: list[str] = [] + worker.error.connect(errors.append) + worker.run() + + assert len(errors) == 1 + assert 'not found' in errors[0].lower() + + +class TestPreviewWorker: + """Tests for PreviewWorker download and preview flow.""" + + @staticmethod + def test_emits_error_on_download_failure() -> None: + """Verify PreviewWorker emits error when download fails.""" + porringer = MagicMock() + porringer.sync.download.return_value = DownloadResult( + success=False, + path=None, + verified=False, + size=0, + message='Network error', + ) + + worker = PreviewWorker(porringer, 'https://example.com/bad.json') + + errors: list[str] = [] + worker.error.connect(errors.append) + worker.run() + + assert len(errors) == 1 + assert 'Network error' in errors[0] + + @staticmethod + def test_emits_preview_ready_on_success() -> None: + """Verify PreviewWorker emits preview_ready with SetupResults.""" + porringer = MagicMock() + porringer.sync.download.return_value = DownloadResult( + success=True, + path=Path('/tmp/test/porringer.json'), + verified=True, + size=100, + message='OK', + ) + expected = SetupResults(actions=[]) + manifest_event = ProgressEvent(kind=ProgressEventKind.MANIFEST_LOADED, manifest=expected) + + async def mock_stream(*args: Any, **kwargs: Any) -> Any: + yield manifest_event + + porringer.sync.execute_stream = mock_stream + + worker = PreviewWorker(porringer, 'https://example.com/good.json') + + results: list[tuple[object, str, str]] = [] + worker.preview_ready.connect(lambda r, p, t: results.append((r, p, t))) + worker.run() + + assert len(results) == 1 + assert results[0][0] is expected + + +class TestPreviewWorkerSignals: + """Tests for PreviewWorker signal emission and dry-run status check.""" + + @staticmethod + def test_emits_preview_ready_and_finished(tmp_path: Path) -> None: + """Verify worker emits preview_ready then finished for a local manifest.""" + manifest = tmp_path / 'porringer.json' + manifest.write_text('{}') + + porringer = MagicMock() + action = MagicMock() + action.kind = PluginKind.PACKAGE + preview = SetupResults(actions=[action]) + + # Dry-run stream yields manifest loaded then one completed event + manifest_event = ProgressEvent(kind=ProgressEventKind.MANIFEST_LOADED, manifest=preview) + result = SetupActionResult(action=action, success=True, skipped=False, skip_reason=None) + completed_event = ProgressEvent(kind=ProgressEventKind.ACTION_COMPLETED, action=action, result=result) + + async def mock_stream(*args: Any, **kwargs: Any) -> Any: + yield manifest_event + yield completed_event + + porringer.sync.execute_stream = mock_stream + + worker = PreviewWorker(porringer, str(manifest)) + + ready_calls: list[tuple[object, str, str]] = [] + checked: list[tuple[int, SetupActionResult]] = [] + finished_count: list[int] = [] + worker.preview_ready.connect(lambda p, m, t: ready_calls.append((p, m, t))) + worker.action_checked.connect(lambda row, r: checked.append((row, r))) + worker.finished.connect(lambda: finished_count.append(1)) + worker.run() + + assert len(ready_calls) == 1 + assert ready_calls[0][0] is preview + assert len(checked) == 1 + assert checked[0] == (0, result) + assert len(finished_count) == 1 + + @staticmethod + def test_emits_finished_for_empty_actions(tmp_path: Path) -> None: + """Verify worker emits finished signal even with no actions.""" + manifest = tmp_path / 'porringer.json' + manifest.write_text('{}') + + porringer = MagicMock() + preview = SetupResults(actions=[]) + manifest_event = ProgressEvent(kind=ProgressEventKind.MANIFEST_LOADED, manifest=preview) + + async def mock_stream(*args: Any, **kwargs: Any) -> Any: + yield manifest_event + + porringer.sync.execute_stream = mock_stream + + worker = PreviewWorker(porringer, str(manifest)) + + finished_count: list[int] = [] + worker.finished.connect(lambda: finished_count.append(1)) + worker.run() + + assert len(finished_count) == 1 + + @staticmethod + def test_action_checked_maps_correct_rows(tmp_path: Path) -> None: + """Verify action_checked emits correct row indices via identity matching.""" + manifest = tmp_path / 'porringer.json' + manifest.write_text('{}') + + porringer = MagicMock() + action_a = MagicMock() + action_a.kind = PluginKind.RUNTIME + action_b = MagicMock() + action_b.kind = PluginKind.PACKAGE + preview = SetupResults(actions=[action_a, action_b]) + + manifest_event = ProgressEvent(kind=ProgressEventKind.MANIFEST_LOADED, manifest=preview) + result_b = SetupActionResult( + action=action_b, success=True, skipped=True, skip_reason=SkipReason.ALREADY_INSTALLED + ) + result_a = SetupActionResult(action=action_a, success=True, skipped=False, skip_reason=None) + + # Stream returns in execution order (b before a), not preview order + event_b = ProgressEvent(kind=ProgressEventKind.ACTION_COMPLETED, action=action_b, result=result_b) + event_a = ProgressEvent(kind=ProgressEventKind.ACTION_COMPLETED, action=action_a, result=result_a) + + async def mock_stream(*args: Any, **kwargs: Any) -> Any: + yield manifest_event + yield event_b + yield event_a + + porringer.sync.execute_stream = mock_stream + + worker = PreviewWorker(porringer, str(manifest)) + + checked: list[tuple[int, SetupActionResult]] = [] + worker.action_checked.connect(lambda row, r: checked.append((row, r))) + worker.run() + + assert len(checked) == 2 # noqa: PLR2004 + # action_b is at index 1 in preview, action_a at index 0 + assert checked[0] == (1, result_b) + assert checked[1] == (0, result_a) + + @staticmethod + def test_emits_error_when_dry_run_fails(tmp_path: Path) -> None: + """Verify worker emits error when dry-run raises.""" + manifest = tmp_path / 'porringer.json' + manifest.write_text('{}') + + porringer = MagicMock() + + async def mock_stream(*args: Any, **kwargs: Any) -> Any: + if False: + yield # pragma: no cover — establishes async generator protocol + msg = 'dry-run boom' + raise RuntimeError(msg) + + porringer.sync.execute_stream = mock_stream + + worker = PreviewWorker(porringer, str(manifest)) + + errors: list[str] = [] + finished_count: list[int] = [] + worker.error.connect(errors.append) + worker.finished.connect(lambda: finished_count.append(1)) + worker.run() + + assert len(errors) == 1 + assert 'dry-run boom' in errors[0] + assert len(finished_count) == 0 diff --git a/tests/unit/test_log_panel.py b/tests/unit/test_log_panel.py new file mode 100644 index 0000000..31da817 --- /dev/null +++ b/tests/unit/test_log_panel.py @@ -0,0 +1,609 @@ +"""Tests for the execution log panel widgets and new InstallWorker signals.""" + +from __future__ import annotations + +import sys +from pathlib import Path +from unittest.mock import MagicMock + +from porringer.schema import ( + CancellationToken, + PluginKind, + ProgressEvent, + ProgressEventKind, + SetupAction, + SetupActionResult, + SetupResults, + SkipReason, + SubActionProgress, +) + +# PySide6 widgets require a QApplication; create one once for the module. +from PySide6.QtWidgets import QApplication + +from synodic_client.application.screen.install import InstallWorker +from synodic_client.application.screen.log_panel import ( + CHEVRON_DOWN, + CHEVRON_RIGHT, + ActionLogSection, + ExecutionLogPanel, +) +from synodic_client.application.theme import ( + LOG_COLOR_ERROR, + LOG_COLOR_PHASE, + LOG_COLOR_STDERR, + LOG_COLOR_STDOUT, + LOG_COLOR_SUCCESS, + LOG_STATUS_FAILED, + LOG_STATUS_RUNNING, + LOG_STATUS_SKIPPED, + LOG_STATUS_SUCCESS, +) + +_app = QApplication.instance() or QApplication(sys.argv) + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _make_action( + kind: PluginKind = PluginKind.PACKAGE, + description: str = 'Install requests', + installer: str = 'pip', + package: str = 'requests', + package_description: str | None = None, +) -> SetupAction: + """Create a mock SetupAction with sensible defaults.""" + action = MagicMock(spec=SetupAction) + action.kind = kind + action.description = description + action.installer = installer + action.package = package + action.package_description = package_description or description + action.command = None + action.cli_command = None + return action + + +def _make_result( + action: SetupAction | None = None, + *, + success: bool = True, + skipped: bool = False, + skip_reason: SkipReason | None = None, + message: str | None = None, +) -> SetupActionResult: + """Create a SetupActionResult.""" + return SetupActionResult( + action=action or _make_action(), + success=success, + skipped=skipped, + skip_reason=skip_reason, + message=message, + ) + + +def _output_html(section: ActionLogSection) -> str: + """Return the full HTML content of a section's output text edit.""" + return section._output.toHtml() + + +# --------------------------------------------------------------------------- +# ActionLogSection +# --------------------------------------------------------------------------- + + +class TestActionLogSection: + """Tests for ActionLogSection widget.""" + + @staticmethod + def test_initial_status_shows_running() -> None: + """Section header starts with 'Running…' status.""" + action = _make_action() + section = ActionLogSection(action, index=1) + assert section._status_label.text() == 'Running…' + assert LOG_STATUS_RUNNING in section._status_label.styleSheet() + + @staticmethod + def test_initial_chevron_is_down() -> None: + """Section starts expanded with the down-pointing chevron.""" + action = _make_action() + section = ActionLogSection(action, index=1) + assert section._chevron.text() == CHEVRON_DOWN + assert section._expanded is True + assert not section._output.isHidden() + + @staticmethod + def test_toggle_collapses_and_expands() -> None: + """Toggling collapses the output, toggling again restores it.""" + action = _make_action() + section = ActionLogSection(action, index=1) + + section._toggle() + assert not section._expanded + assert section._output.isHidden() + assert section._chevron.text() == CHEVRON_RIGHT + + section._toggle() + assert section._expanded + assert not section._output.isHidden() + assert section._chevron.text() == CHEVRON_DOWN + + @staticmethod + def test_append_stdout_output() -> None: + """Stdout lines are coloured with the stdout colour.""" + action = _make_action() + section = ActionLogSection(action, index=1) + section.append_output('hello world', 'stdout') + + html = _output_html(section) + assert LOG_COLOR_STDOUT in html + assert 'hello world' in html + + @staticmethod + def test_append_stderr_output() -> None: + """Stderr lines use the stderr/amber colour.""" + action = _make_action() + section = ActionLogSection(action, index=1) + section.append_output('warning: something', 'stderr') + + html = _output_html(section) + assert LOG_COLOR_STDERR in html + assert 'warning: something' in html + + @staticmethod + def test_append_output_none_stream_uses_phase_colour() -> None: + """Lines with stream=None use the phase/muted colour.""" + action = _make_action() + section = ActionLogSection(action, index=1) + section.append_output('Verifying checksums', None) + + html = _output_html(section) + assert LOG_COLOR_PHASE in html + assert 'Verifying checksums' in html + + @staticmethod + def test_append_phase_uses_phase_colour() -> None: + """Phase messages (stream=None) use the muted grey colour.""" + action = _make_action() + section = ActionLogSection(action, index=1) + section.append_output('downloading', None) + + html = _output_html(section) + assert LOG_COLOR_PHASE in html + assert 'downloading' in html + + @staticmethod + def test_html_escaping_in_output() -> None: + """Special HTML characters are escaped in output lines.""" + action = _make_action() + section = ActionLogSection(action, index=1) + section.append_output('', 'stdout') + + html = _output_html(section) + # HTML entities should have been escaped + assert '<script>' in html + assert '