feat(client): redesign native UI, themes, settings and avatars
Separate conversation drafts and voice view state, add native settings and restricted CSS themes, implement validated avatar cropping, and refresh dependencies with documented desktop compatibility backports.
This commit is contained in:
parent
44d284a568
commit
8e5ab56611
276 changed files with 53546 additions and 3399 deletions
232
patches/i-slint-backend-winit/COPYING
vendored
Normal file
232
patches/i-slint-backend-winit/COPYING
vendored
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
|
||||
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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
|
||||
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:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
|
||||
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 <http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
423
patches/i-slint-backend-winit/Cargo.toml
vendored
Normal file
423
patches/i-slint-backend-winit/Cargo.toml
vendored
Normal file
|
|
@ -0,0 +1,423 @@
|
|||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2024"
|
||||
rust-version = "1.92"
|
||||
name = "i-slint-backend-winit"
|
||||
version = "1.18.1"
|
||||
authors = ["Slint Developers <info@slint.dev>"]
|
||||
build = "build.rs"
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "Winit backend for Slint"
|
||||
homepage = "https://slint.dev"
|
||||
readme = "README.md"
|
||||
license = "GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0"
|
||||
repository = "https://github.com/slint-ui/slint"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = [
|
||||
"wayland",
|
||||
"renderer-software",
|
||||
"raw-window-handle-06",
|
||||
]
|
||||
rustdoc-args = ["--generate-link-to-definition"]
|
||||
|
||||
[features]
|
||||
accessibility = [
|
||||
"dep:accesskit",
|
||||
"dep:accesskit_winit",
|
||||
"i-slint-core/accessibility-text",
|
||||
]
|
||||
default = []
|
||||
raw-window-handle-06 = ["i-slint-core/raw-window-handle-06"]
|
||||
renderer-femtovg = [
|
||||
"i-slint-renderer-femtovg/opengl",
|
||||
"dep:glutin",
|
||||
"dep:glutin-winit",
|
||||
"windows/Win32_Graphics_OpenGL",
|
||||
]
|
||||
renderer-femtovg-wgpu = [
|
||||
"i-slint-renderer-femtovg/wgpu",
|
||||
"dep:i-slint-renderer-femtovg",
|
||||
"unstable-wgpu-30",
|
||||
]
|
||||
renderer-skia = ["i-slint-renderer-skia"]
|
||||
renderer-skia-opengl = [
|
||||
"renderer-skia",
|
||||
"i-slint-renderer-skia/opengl",
|
||||
]
|
||||
renderer-skia-vulkan = [
|
||||
"renderer-skia",
|
||||
"i-slint-renderer-skia/vulkan",
|
||||
]
|
||||
renderer-software = [
|
||||
"dep:softbuffer",
|
||||
"dep:imgref",
|
||||
"dep:rgb",
|
||||
"dep:i-slint-renderer-software",
|
||||
"i-slint-renderer-software/std",
|
||||
"dep:bytemuck",
|
||||
]
|
||||
renderer-vello = [
|
||||
"dep:i-slint-renderer-anyrender",
|
||||
"i-slint-renderer-anyrender/vello",
|
||||
"unstable-wgpu-29",
|
||||
]
|
||||
unstable-wgpu-29 = [
|
||||
"i-slint-core/unstable-wgpu-29",
|
||||
"i-slint-renderer-skia?/unstable-wgpu-29",
|
||||
]
|
||||
unstable-wgpu-30 = [
|
||||
"i-slint-core/unstable-wgpu-30",
|
||||
"i-slint-renderer-femtovg?/unstable-wgpu-30",
|
||||
"i-slint-renderer-skia?/unstable-wgpu-30",
|
||||
]
|
||||
wayland = [
|
||||
"winit/wayland",
|
||||
"winit/wayland-csd-adwaita-crossfont",
|
||||
"glutin?/wayland",
|
||||
"glutin-winit?/wayland",
|
||||
"dep:arboard",
|
||||
"arboard/wayland-data-control",
|
||||
"i-slint-renderer-skia?/wayland",
|
||||
"softbuffer?/wayland",
|
||||
"softbuffer?/wayland-dlopen",
|
||||
]
|
||||
x11 = [
|
||||
"winit/x11",
|
||||
"glutin?/x11",
|
||||
"glutin?/glx",
|
||||
"glutin-winit?/x11",
|
||||
"glutin-winit?/glx",
|
||||
"dep:arboard",
|
||||
"i-slint-renderer-skia?/x11",
|
||||
"softbuffer?/x11",
|
||||
"softbuffer?/x11-dlopen",
|
||||
]
|
||||
|
||||
[lib]
|
||||
name = "i_slint_backend_winit"
|
||||
path = "lib.rs"
|
||||
|
||||
[[test]]
|
||||
name = "hide_from_window_event"
|
||||
path = "tests/hide_from_window_event.rs"
|
||||
harness = false
|
||||
|
||||
[[test]]
|
||||
name = "hide_with_external_reference"
|
||||
path = "tests/hide_with_external_reference.rs"
|
||||
harness = false
|
||||
|
||||
[[test]]
|
||||
name = "menubar_borrow"
|
||||
path = "tests/menubar_borrow.rs"
|
||||
harness = false
|
||||
|
||||
[dependencies.bytemuck]
|
||||
version = "1.13.1"
|
||||
features = ["derive"]
|
||||
optional = true
|
||||
|
||||
[dependencies.cfg-if]
|
||||
version = "1"
|
||||
|
||||
[dependencies.i-slint-common]
|
||||
version = "=1.18.1"
|
||||
features = ["default"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.i-slint-core]
|
||||
version = "=1.18.1"
|
||||
features = ["default"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.i-slint-core-macros]
|
||||
version = "=1.18.1"
|
||||
features = ["default"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.i-slint-renderer-anyrender]
|
||||
version = "=1.18.1"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.i-slint-renderer-femtovg]
|
||||
version = "=1.18.1"
|
||||
features = ["default"]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.i-slint-renderer-skia]
|
||||
version = "=1.18.1"
|
||||
features = ["default"]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.i-slint-renderer-software]
|
||||
version = "=1.18.1"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.imgref]
|
||||
version = "1.6.1"
|
||||
optional = true
|
||||
|
||||
[dependencies.lyon_path]
|
||||
version = "1.0"
|
||||
default-features = false
|
||||
|
||||
[dependencies.pin-weak]
|
||||
version = "1"
|
||||
|
||||
[dependencies.raw-window-handle]
|
||||
version = "0.6"
|
||||
features = ["alloc"]
|
||||
|
||||
[dependencies.rgb]
|
||||
version = "0.8.27"
|
||||
optional = true
|
||||
|
||||
[dependencies.scoped-tls-hkt]
|
||||
version = "0.1"
|
||||
|
||||
[dependencies.scopeguard]
|
||||
version = "1.1.0"
|
||||
default-features = false
|
||||
|
||||
[dependencies.softbuffer]
|
||||
version = "0.4.4"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.strum]
|
||||
version = "0.28"
|
||||
features = ["derive"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.webbrowser]
|
||||
version = "1.2.0"
|
||||
|
||||
[dependencies.winit]
|
||||
version = "0.30.2"
|
||||
features = ["rwh_06"]
|
||||
default-features = false
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
[build-dependencies.cfg_aliases]
|
||||
version = "0.2.2"
|
||||
|
||||
[target.'cfg(all(not(target_arch = "wasm32"), not(all(target_vendor = "apple", not(target_os = "macos")))))'.dependencies.glutin]
|
||||
version = "0.32.0"
|
||||
features = [
|
||||
"egl",
|
||||
"wgl",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(all(not(target_arch = "wasm32"), not(all(target_vendor = "apple", not(target_os = "macos")))))'.dependencies.glutin-winit]
|
||||
version = "0.5"
|
||||
features = [
|
||||
"egl",
|
||||
"wgl",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(all(target_vendor = "apple", not(target_os = "macos")))'.dependencies.i-slint-renderer-skia]
|
||||
version = "=1.18.1"
|
||||
features = ["default"]
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(any(target_os = "macos", target_family = "windows"))'.dependencies.muda]
|
||||
version = "0.19.0"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(any(target_os = "macos", target_family = "windows"))'.dependencies.vtable]
|
||||
version = "0.5"
|
||||
|
||||
[target.'cfg(not(any(target_family = "windows", target_vendor = "apple", target_arch = "wasm32", target_os = "android")))'.dependencies.arboard]
|
||||
version = "3.6"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(not(any(target_family = "windows", target_vendor = "apple", target_arch = "wasm32", target_os = "android")))'.dependencies.futures]
|
||||
version = "0.3.31"
|
||||
|
||||
[target.'cfg(not(any(target_family = "windows", target_vendor = "apple", target_arch = "wasm32", target_os = "android")))'.dependencies.zbus]
|
||||
version = "6.1"
|
||||
features = ["default-rt", "proxy", "service", "object-manager"]
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.accesskit]
|
||||
version = "0.24"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.accesskit_winit]
|
||||
version = "0.33"
|
||||
features = [
|
||||
"accesskit_unix",
|
||||
"async-io",
|
||||
"rwh_06",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.i-slint-core]
|
||||
version = "=1.18.1"
|
||||
features = [
|
||||
"image-decoders",
|
||||
"svg",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies.wasm-bindgen]
|
||||
version = "0.2"
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies.web-sys]
|
||||
version = "0.3.72"
|
||||
features = [
|
||||
"HtmlInputElement",
|
||||
"HtmlCanvasElement",
|
||||
"Window",
|
||||
"Document",
|
||||
"Event",
|
||||
"EventTarget",
|
||||
"FocusEvent",
|
||||
"KeyboardEvent",
|
||||
"InputEvent",
|
||||
"CompositionEvent",
|
||||
"DomStringMap",
|
||||
"ClipboardEvent",
|
||||
"DataTransfer",
|
||||
"Node",
|
||||
"WebGlContextEvent",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies.block2]
|
||||
version = "0.6.2"
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies.objc2]
|
||||
version = "0.6.3"
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies.objc2-foundation]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"block2",
|
||||
"NSString",
|
||||
"NSNotification",
|
||||
"NSOperation",
|
||||
"NSGeometry",
|
||||
"NSRunLoop",
|
||||
"objc2-core-foundation",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies.objc2-quartz-core]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"CADisplayLink",
|
||||
"CATransaction",
|
||||
"CAFrameRateRange",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_os = "ios")'.dependencies.objc2-ui-kit]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"UIApplication",
|
||||
"UIScene",
|
||||
"UISceneDefinitions",
|
||||
"UISceneOptions",
|
||||
"UISceneSession",
|
||||
"UIScreen",
|
||||
"UIWindow",
|
||||
"UIWindowScene",
|
||||
"UIView",
|
||||
"UIViewAnimating",
|
||||
"UIViewPropertyAnimator",
|
||||
"UIResponder",
|
||||
"UIInterface",
|
||||
"UIPasteboard",
|
||||
"UITrait",
|
||||
"UITraitCollection",
|
||||
"UIFont",
|
||||
"UIFontDescriptor",
|
||||
"objc2-core-foundation",
|
||||
"objc2-quartz-core",
|
||||
"block2",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies.arboard]
|
||||
version = "3.6"
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies.block2]
|
||||
version = "0.6.2"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies.objc2]
|
||||
version = "0.6.3"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies.objc2-app-kit]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"NSColor",
|
||||
"NSView",
|
||||
"NSWindow",
|
||||
"NSResponder",
|
||||
"objc2-core-foundation",
|
||||
"objc2-quartz-core",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies.objc2-foundation]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"block2",
|
||||
"NSString",
|
||||
"NSNotification",
|
||||
"NSOperation",
|
||||
"NSRunLoop",
|
||||
"NSObjCRuntime",
|
||||
"NSUserDefaults",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies.objc2-quartz-core]
|
||||
version = "0.3.2"
|
||||
features = ["CADisplayLink"]
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies.arboard]
|
||||
version = "3.6"
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies.windows]
|
||||
version = "0.62"
|
||||
features = [
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
"Win32_UI_HiDpi",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_Graphics_Dwm",
|
||||
]
|
||||
232
patches/i-slint-backend-winit/LICENSES/GPL-3.0-only.txt
vendored
Normal file
232
patches/i-slint-backend-winit/LICENSES/GPL-3.0-only.txt
vendored
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
|
||||
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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
|
||||
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:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
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 <http://www.gnu.org/licenses/>.
|
||||
|
||||
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 <http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
43
patches/i-slint-backend-winit/LICENSES/LicenseRef-Slint-Royalty-free-2.0.md
vendored
Normal file
43
patches/i-slint-backend-winit/LICENSES/LicenseRef-Slint-Royalty-free-2.0.md
vendored
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
# Slint Royalty-free Desktop, Mobile, and Web Applications License
|
||||
|
||||
Version 2.0
|
||||
|
||||
## Preamble
|
||||
|
||||
Slint is a toolkit that can be used to build user interfaces for applications. Slint (hereafter referred to as **Software**) is made available under different licenses by SixtyFPS GmbH incorporated at Oranienburger Str. 44, 16540 Hohen Neuendorf, Germany (**SixtyFPS**). The **Slint Royalty-free Desktop, Mobile, and Web Applications License** is suitable for those who develop desktop, mobile, or web applications and do not want to use open source components under copyleft licenses.
|
||||
|
||||
## 1. Grant of Rights
|
||||
|
||||
SixtyFPS hereby grants You a world-wide, royalty-free, non-exclusive license to use, reproduce, make available, modify, display, perform, distribute the Software as part of a Desktop, Mobile, or Web Application.
|
||||
|
||||
A **Desktop Application** is a computer program that is designed to run on a general-purpose computer (PC or notebook), typically installed and executed locally on the computer's operating system.
|
||||
|
||||
A **Mobile Application** is a computer program that is designed to run on a general-purpose mobile computer (mobile phone or tablet), typically installed and executed locally on the computer's operating system.
|
||||
|
||||
A **Web Application** is a computer program that is designed to run in the sandbox environment provided by a web browser.
|
||||
|
||||
Desktop Application, Mobile Application, and Web Application are hereafter referred to as **Application**.
|
||||
|
||||
## 2. License Conditions - Attribution
|
||||
|
||||
You may distribute the Software as part of an Application, modified or unmodified, provided that You do either of the following:
|
||||
|
||||
(a) Display the [`AboutSlint`](https://docs.slint.dev/latest/docs/slint/reference/std-widgets/misc/aboutslint/) widget in an "About" screen or dialog that is accessible from the top level menu of the Application. In the absence of such a screen or dialog, display the widget in the "Splash Screen" of the Application.
|
||||
|
||||
(b) Display the [Slint attribution badge](https://github.com/slint-ui/slint/tree/master/logo/MadeWithSlint-logo-whitebg.png) on a public webpage, preferably where the binaries of your Application can be downloaded from, in such a way that it can be easily found by any visitor to that page.
|
||||
|
||||
## 3. Limitations
|
||||
|
||||
The License does not permit to distribute or make the Software publicly available alone and without integration into an Application. For this purpose you may use the Software under the GNU General Public License, version 3.
|
||||
|
||||
The License does not permit the use of the Software within Embedded Systems. An **Embedded System** is a computer system designed to perform a specific task within a larger mechanical or electrical system.
|
||||
|
||||
The License does not permit the distribution of Application that exposes the APIs, in part or in total, of the Software.
|
||||
|
||||
You may not remove or alter any license notices (including copyright notices, disclaimers of warranty, or limitations of liability) contained within the source code form of the Software.
|
||||
|
||||
## 4. Warranty and Liability
|
||||
|
||||
SixtyFPS is only liable for conflicting rights of third parties if SixtyFPS was aware of these rights without informing you. Unless required by applicable law or agreed to in writing, SixtyFPS provides the Software on an "as is" basis, without warranties or conditions of any kind, either express or implied, including, without limitation, any warranties or conditions of merchantability, or fitness for a particular purpose.
|
||||
|
||||
Unless required by law, SixtyFPS won't be liable for any direct, indirect, incidental, or consequential damages arising in any way out of the use of the Software.
|
||||
117
patches/i-slint-backend-winit/LICENSES/LicenseRef-Slint-Software-3.0.md
vendored
Normal file
117
patches/i-slint-backend-winit/LICENSES/LicenseRef-Slint-Software-3.0.md
vendored
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
# Slint Software License
|
||||
|
||||
Version 3.0.5
|
||||
|
||||
## Preamble
|
||||
|
||||
Slint is a toolkit that can be used to build user interfaces for applications. Slint (hereafter referred to as **Software**) is made available under different licenses by SixtyFPS GmbH incorporated at Oranienburger Str. 44, 16540 Hohen Neuendorf, Germany (**SixtyFPS**). The **Slint Software License** is suitable for those who do not want to use open source components under copyleft licenses.
|
||||
|
||||
## 1. Grant of Rights
|
||||
|
||||
SixtyFPS hereby grants You a world-wide, non-exclusive license to use, reproduce, make available, modify, display, perform, distribute the Software as part of a Desktop, Mobile, or Web Application or as part of an Embedded System (each of which is defined below).
|
||||
|
||||
A **Desktop Application** is a computer program that is designed to run on a general-purpose computer (PC or notebook), typically installed and executed locally on the computer's operating system.
|
||||
|
||||
A **Mobile Application** is a computer program that is designed to run on a general-purpose mobile computer (mobile phone or tablet), typically installed and executed locally on the computer's operating system.
|
||||
|
||||
A **Web Application** is a computer program that is designed to run in the sandbox environment provided by a web browser.
|
||||
|
||||
An **Embedded System** is a computer system designed to perform a specific task within a larger mechanical or electrical system.
|
||||
|
||||
Desktop Application, Mobile Application, and Web Application are hereafter referred to as **Application**.
|
||||
|
||||
## 2. License Conditions
|
||||
|
||||
The grant of rights in section 1 are conditional, provided that You do all of the following:
|
||||
|
||||
(a) You have purchased an appropriate **Paid License Plan** ([see Annex 1](#annex-1-paid-license-plans)) and the required amount of seats to cover all individual users of the Software associated with the designing, developing, or testing your Application or Embedded System. For clarity, each individual user is counted as one seat.
|
||||
|
||||
(b) In the case that You are distributing the Software as part of an Embedded System, You have purchased an appropriate quantity of **Royalties**, one Royalty for each Embedded System. Royalties become due and payable upon manufacture of the Embedded System, regardless of whether such is subsequently sold, shipped, returned, replaced under warranty, or recalled. Payment of royalties is non-refundable under any circumstances. Royalties are not necessary for non-commercial projects, personal projects, and open source projects.
|
||||
|
||||
## 3. Limitations
|
||||
|
||||
The License does not permit to distribute or make the Software publicly available alone and without integration into an Application or into an Embedded System. For this purpose you may use the Software under the GNU General Public License, version 3.
|
||||
|
||||
The License is limited to only the versions of Software that were made available to you under the Paid License Plan. For all other versions, you may use the Software under either the GNU General Public License, version 3 or the Slint Royalty-free Desktop, Mobile, and Web Applications License.
|
||||
|
||||
The License does not permit the distribution of Application that exposes the APIs, in part or in total, of the Software.
|
||||
|
||||
You may not remove or alter any license notices (including copyright notices, disclaimers of warranty, or limitations of liability) contained within the source code form of the Software.
|
||||
|
||||
## 4. Audit Rights
|
||||
|
||||
SixtyFPS or an independent certified auditor on SixtyFPS's behalf, may, upon its reasonable request, with 30 (thirty) days written notice, and at its sole expense, examine your books and records solely with respect to your use of the Software. Any such audit shall be conducted during regular business hours at your facilities and shall not unreasonably interfere with your business activities. The auditor shall not remove, copy, or redistribute any electronic material during an audit. If an audit reveals that you are using the Software in a way that is in material violation of the terms of this License, then you shall pay SixtyFPS reasonable costs of conducting the audit. The auditor shall only be allowed to report violations of the terms of this License, with a copy to you. You shall be provided the right to provide comments to the report before it is finalized.
|
||||
|
||||
## 5. Termination
|
||||
|
||||
(a) SixtyFPS may terminate this License if You materially breach any obligation hereunder, provided You have been provided notice of such breach and an opportunity to cure such breach during a period of not less than sixty (60) days following such notice.
|
||||
|
||||
(b) You may terminate this License with or without cause upon no less than thirty (30) days advance written notice to SixtyFPS.
|
||||
|
||||
(c) Upon termination of this License, You will immediately cease using, reproducing, making available, modifying, displaying, performing, distributing the Software and pay immediately any unpaid Fees and contractual penalties.
|
||||
|
||||
(d) Sections 3 through 8 of this License will survive any termination of the License to the extent necessary to implement their objectives.
|
||||
|
||||
## 6. Assignment
|
||||
|
||||
You may assign this License, in whole or in part (whether by operation of law or otherwise), with prior consent from SixtyFPS, which shall not be unreasonably withheld or delayed. SixtyFPS may assign any of its rights or delegate any of its obligations hereunder with prior notice to You, provided that the successor maintains at least the same level of security, confidentiality, and data protection measures as in place at the time of assignment or delegation. Any attempt to assign this License other than in accordance with this Section 6 shall be null and void.
|
||||
|
||||
## 7. Severability
|
||||
|
||||
In the event that any provision of this License will, for any reason, be determined by any court of competent jurisdiction to be invalid, illegal or unenforceable in any respect, such invalidity, illegality or unenforceability will be interpreted as closely as possible so as not affect any other provision of this License, and such provision will further be modified by said court to permit its enforcement to the maximum extent permitted by law.
|
||||
|
||||
## 8. Governing Law
|
||||
|
||||
This Agreement shall be construed, interpreted, and governed by the laws of the Federal Republic of Germany.
|
||||
|
||||
## Annex 1: Paid License Plans
|
||||
|
||||
### Enterprise Plan
|
||||
|
||||
The following is included as part of the plan
|
||||
|
||||
(a) No restriction on the number of applications that are developed with Slint.
|
||||
|
||||
(b) Live Preview.
|
||||
|
||||
(c) Standard Support that includes addressing technical queries, troubleshooting, and rectifying bugs or errors (faults) present in the latest official stable release.
|
||||
|
||||
(d) Perpetual Fallback License that allows continued use of a specific Slint version, including all bugfix updates (i.e., all Z releases within the X.Y.Z version), without an active subscription. This license applies only to those versions of Slint for which at least 12 consecutive months of subscription have been paid.
|
||||
|
||||
(e) GUI Test Framework.
|
||||
|
||||
### Small Enterprise Plan
|
||||
|
||||
This plan is limited to individual companies with a staff headcount of upto 50 and either a turnover or balance sheet total of 10 million EUR or less. If You are a Small Enterprise, You are required to submit the self-assessment report generated from the EU SME Self-Assessment Tool (https://ec.europa.eu/info/funding-tenders/opportunities/portal/sme/public/organisation-name).
|
||||
|
||||
The following is included as part of the plan
|
||||
|
||||
(a) No restriction on the number of applications that are developed with Slint.
|
||||
|
||||
(b) Live Preview.
|
||||
|
||||
(c) Standard Support that includes addressing technical queries, troubleshooting, and rectifying bugs or errors (faults) present in the latest official stable release.
|
||||
|
||||
The following can be purchased as an Add-On
|
||||
|
||||
(a) Perpetual Fallback License that allows continued use of a specific Slint version, including all bugfix updates (i.e., all Z releases within the X.Y.Z version), without an active subscription. This license applies only to those versions of Slint for which at least 12 consecutive months of subscription have been paid.
|
||||
|
||||
(b) GUI Test Framework.
|
||||
|
||||
### Startup & Individual Plan
|
||||
|
||||
This plan is limited to individuals and individual companies with a staff headcount of less than 10 and either a turnover or balance sheet total of 2 million EUR or less. If You are a Startup, you are required to submit the self-assessment report generated from the EU SME Self-Assessment Tool (https://ec.europa.eu/info/funding-tenders/opportunities/portal/sme/public/organisation-name).
|
||||
|
||||
The following is included as part of the plan
|
||||
|
||||
(a) No restriction on the number of applications that are developed with Slint.
|
||||
|
||||
(b) Live Preview.
|
||||
|
||||
The following can be purchased as an Add-On
|
||||
|
||||
(a) Standard Support that includes addressing technical queries, troubleshooting, and rectifying bugs or errors (faults) present in the latest official stable release.
|
||||
|
||||
(b) Perpetual Fallback License that allows continued use of a specific Slint version, including all bugfix updates (i.e., all Z releases within the X.Y.Z version), without an active subscription. This license applies only to those versions of Slint for which at least 12 consecutive months of subscription have been paid.
|
||||
|
||||
(c) GUI Test Framework.
|
||||
51
patches/i-slint-backend-winit/README.md
vendored
Normal file
51
patches/i-slint-backend-winit/README.md
vendored
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
|
||||
**NOTE**: This library is an **internal** crate of the [Slint project](https://slint.dev).
|
||||
This crate should **not be used directly** by applications using Slint.
|
||||
You should use the `slint` crate instead.
|
||||
|
||||
**WARNING**: This crate does not follow the semver convention for versioning and can
|
||||
only be used with `version = "=x.y.z"` in Cargo.toml.
|
||||
|
||||
# The Slint winit Backend
|
||||
|
||||
This crate implements the winit backend/platform for Slint.
|
||||
It is enabled by default as a default feature of the `slint` crate.
|
||||
|
||||
Although this crate is primarily internal, it can also be used by applications
|
||||
to leverage the full power of [`winit::window::Window`] for Slint Window.
|
||||
|
||||
To use this functionality, you need to be cautious when importing dependencies since
|
||||
this crate does not adhere to semver and may introduce breaking changes in any patch release.
|
||||
Additionally, the version of this crate must match the version of Slint.
|
||||
To indicate that you specifically want this version, include the `=` symbol in the version string.
|
||||
|
||||
Make sure that the version of winit matches the version used by this crate.
|
||||
Check this crate's dependencies to determine the required version.
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
slint = { version = "x.y.z", ... }
|
||||
i-slint-backend-winit = "=x.y.z"
|
||||
winit = "0.w"
|
||||
```
|
||||
|
||||
To ensure that the runtime backend is selected, initialize the backend as the first step in the `main` function:
|
||||
|
||||
```rust
|
||||
slint::platform::set_platform(Box::new(i_slint_backend_winit::Backend::new().unwrap()));
|
||||
// ...
|
||||
```
|
||||
|
||||
Once you have a [`slint::Window`](i_slint_core::api::Window)
|
||||
(accessible through the [window()](i_slint_core::api::ComponentHandle::window()) function of the generated component),
|
||||
you can utilize the [`WinitWindowAccessor::with_winit_window`] function to access the [`winit::window::Window`] object.
|
||||
|
||||
```rust,no_run
|
||||
# // similar to code generated by the slint! macro
|
||||
# struct C; impl C { fn window(&self) ->i_slint_core::api::Window {todo!()} }
|
||||
# let my_ui = C;
|
||||
use i_slint_backend_winit::WinitWindowAccessor; // import the trait
|
||||
my_ui.window().with_winit_window(|winit_window: &winit::window::Window| {
|
||||
// Here, you can use the winit API
|
||||
});
|
||||
```
|
||||
14
patches/i-slint-backend-winit/VNOX-PATCH.md
vendored
Normal file
14
patches/i-slint-backend-winit/VNOX-PATCH.md
vendored
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
# Vnox maintenance patch: i-slint-backend-winit 1.18.1
|
||||
|
||||
Source: published crates.io i-slint-backend-winit 1.18.1, upstream revision `372cf0ee5577c3dfec309a45e7b778ba4e81b734`. The published archive includes the original license texts in `LICENSES/` (not root `LICENSE*` files). They are preserved without alteration.
|
||||
|
||||
For this GPL-licensed Vnox distribution, this backport uses the upstream **GPL-3.0-only** option. `COPYING` is copied from the official exact-revision GPL text below and was byte-compared with the archive's `LICENSES/GPL-3.0-only.txt`. This does not grant or claim a commercial Slint license.
|
||||
|
||||
Official license source: https://raw.githubusercontent.com/slint-ui/slint/372cf0ee5577c3dfec309a45e7b778ba4e81b734/LICENSES/GPL-3.0-only.txt
|
||||
SHA-256: `b6a8bf63ae2c95b0aa256ee774680d7bd18f21f457da75466f7610b3b16acc4e`.
|
||||
|
||||
This is a maintained-parent compatibility backport, not a fork of an unmaintained D-Bus codec. Vnox updates dependencies/imports to maintained zbus 6, which merged zvariant and zbus_names. The original package version identifies its API baseline; no version is spoofed to suppress RustSec.
|
||||
|
||||
The Slint Winit patch additionally uses Winit's supported crossfont CSD backend to avoid the unmaintained ttf-parser chain while retaining Wayland client-side title decorations.
|
||||
|
||||
Remove this patch once upstream publishes the equivalent migration. Changes must be tested with full client build, native rendering, accessibility/portal interfaces and RustSec audit.
|
||||
1011
patches/i-slint-backend-winit/accesskit.rs
vendored
Normal file
1011
patches/i-slint-backend-winit/accesskit.rs
vendored
Normal file
File diff suppressed because it is too large
Load diff
19
patches/i-slint-backend-winit/build.rs
vendored
Normal file
19
patches/i-slint-backend-winit/build.rs
vendored
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use cfg_aliases::cfg_aliases;
|
||||
|
||||
fn main() {
|
||||
// Setup cfg aliases
|
||||
cfg_aliases! {
|
||||
ios_and_friends: { all(target_vendor = "apple", not(target_os = "macos"))},
|
||||
enable_skia_renderer: { any(feature = "renderer-skia", feature = "renderer-skia-opengl", feature = "renderer-skia-vulkan", ios_and_friends) },
|
||||
enable_femtovg_renderer: { any(feature = "renderer-femtovg", feature = "renderer-femtovg-wgpu") },
|
||||
enable_accesskit: { all(feature = "accessibility", not(target_arch = "wasm32")) },
|
||||
supports_opengl: { all(any(feature = "renderer-skia-opengl", feature = "renderer-femtovg"), not(ios_and_friends)) },
|
||||
supports_vulkan: { any(all(target_family = "unix", not(target_vendor = "apple")), all(any(target_vendor = "apple", target_family = "windows"), feature = "renderer-skia-vulkan")) },
|
||||
xdg_desktop_settings: { not(any(target_family = "windows", target_vendor = "apple", target_arch = "wasm32", target_os = "android")) },
|
||||
muda: { all(feature = "muda", any(target_os = "windows", target_os = "macos")) },
|
||||
}
|
||||
println!("cargo:rustc-check-cfg=cfg(slint_nightly_test)");
|
||||
}
|
||||
132
patches/i-slint-backend-winit/clipboard.rs
vendored
Normal file
132
patches/i-slint-backend-winit/clipboard.rs
vendored
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
/// Minimal clipboard abstraction implemented by the platform backends below.
|
||||
pub trait ClipboardProvider {
|
||||
fn get_contents(
|
||||
&mut self,
|
||||
) -> Result<String, Box<dyn std::error::Error + Send + Sync + 'static>>;
|
||||
fn set_contents(
|
||||
&mut self,
|
||||
contents: String,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>>;
|
||||
}
|
||||
|
||||
/// The Default, and the selection clipboard
|
||||
pub type ClipboardPair = (Box<dyn ClipboardProvider>, Box<dyn ClipboardProvider>);
|
||||
|
||||
pub fn select_clipboard(
|
||||
pair: &mut ClipboardPair,
|
||||
clipboard: i_slint_core::platform::Clipboard,
|
||||
) -> Option<&mut dyn ClipboardProvider> {
|
||||
match clipboard {
|
||||
i_slint_core::platform::Clipboard::DefaultClipboard => Some(pair.0.as_mut()),
|
||||
i_slint_core::platform::Clipboard::SelectionClipboard => Some(pair.1.as_mut()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Silent no-op fallback for platforms or configurations without clipboard support.
|
||||
struct SilentClipboardContext;
|
||||
impl ClipboardProvider for SilentClipboardContext {
|
||||
fn get_contents(
|
||||
&mut self,
|
||||
) -> Result<String, Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
Ok(Default::default())
|
||||
}
|
||||
|
||||
fn set_contents(
|
||||
&mut self,
|
||||
_: String,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", target_os = "macos"))]
|
||||
struct SystemClipboard(arboard::Clipboard);
|
||||
#[cfg(any(target_os = "windows", target_os = "macos"))]
|
||||
impl ClipboardProvider for SystemClipboard {
|
||||
fn get_contents(
|
||||
&mut self,
|
||||
) -> Result<String, Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
self.0.get_text().map_err(Into::into)
|
||||
}
|
||||
|
||||
fn set_contents(
|
||||
&mut self,
|
||||
contents: String,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
self.0.set_text(contents).map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
unix,
|
||||
not(any(target_vendor = "apple", target_os = "android", target_os = "emscripten")),
|
||||
any(feature = "x11", feature = "wayland")
|
||||
))]
|
||||
struct SelectableClipboard {
|
||||
clipboard: arboard::Clipboard,
|
||||
kind: arboard::LinuxClipboardKind,
|
||||
}
|
||||
#[cfg(all(
|
||||
unix,
|
||||
not(any(target_vendor = "apple", target_os = "android", target_os = "emscripten")),
|
||||
any(feature = "x11", feature = "wayland")
|
||||
))]
|
||||
impl ClipboardProvider for SelectableClipboard {
|
||||
fn get_contents(
|
||||
&mut self,
|
||||
) -> Result<String, Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
use arboard::GetExtLinux;
|
||||
self.clipboard.get().clipboard(self.kind).text().map_err(Into::into)
|
||||
}
|
||||
|
||||
fn set_contents(
|
||||
&mut self,
|
||||
contents: String,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
use arboard::SetExtLinux;
|
||||
self.clipboard.set().clipboard(self.kind).text(contents).map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_clipboard(
|
||||
_display_handle: &winit::raw_window_handle::DisplayHandle<'_>,
|
||||
) -> ClipboardPair {
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(all(
|
||||
unix,
|
||||
not(any(target_vendor = "apple", target_os = "android", target_os = "emscripten")),
|
||||
any(feature = "x11", feature = "wayland")
|
||||
))] {
|
||||
// arboard selects Wayland (data-control protocol, with the "wayland" feature)
|
||||
// or X11 at runtime; on compositors without wlr-data-control it falls back to
|
||||
// the X11/XWayland clipboard, which such compositors keep in sync.
|
||||
let make = |kind| -> Box<dyn ClipboardProvider> {
|
||||
arboard::Clipboard::new().map_or(
|
||||
Box::new(SilentClipboardContext) as Box<dyn ClipboardProvider>,
|
||||
|clipboard| Box::new(SelectableClipboard { clipboard, kind }),
|
||||
)
|
||||
};
|
||||
(
|
||||
make(arboard::LinuxClipboardKind::Clipboard),
|
||||
make(arboard::LinuxClipboardKind::Primary),
|
||||
)
|
||||
} else if #[cfg(target_os = "ios")] {
|
||||
// iOS exposes a single general pasteboard; the selection clipboard is a no-op.
|
||||
(Box::new(crate::ios::UiPasteboardClipboard), Box::new(SilentClipboardContext))
|
||||
} else if #[cfg(any(target_os = "windows", target_os = "macos"))] {
|
||||
(
|
||||
arboard::Clipboard::new().map_or(
|
||||
Box::new(SilentClipboardContext) as Box<dyn ClipboardProvider>,
|
||||
|clipboard| Box::new(SystemClipboard(clipboard)) as Box<dyn ClipboardProvider>,
|
||||
),
|
||||
Box::new(SilentClipboardContext),
|
||||
)
|
||||
} else {
|
||||
(Box::new(SilentClipboardContext), Box::new(SilentClipboardContext))
|
||||
}
|
||||
}
|
||||
}
|
||||
97
patches/i-slint-backend-winit/drag_resize_window.rs
vendored
Normal file
97
patches/i-slint-backend-winit/drag_resize_window.rs
vendored
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
// cSpell: ignore xdir ydir
|
||||
use i_slint_core::lengths::LogicalLength;
|
||||
use winit::window::{CursorIcon, ResizeDirection};
|
||||
|
||||
pub fn handle_cursor_move_for_resize(
|
||||
window: &winit::window::Window,
|
||||
position: winit::dpi::PhysicalPosition<f64>,
|
||||
current_direction: Option<ResizeDirection>,
|
||||
border_width: LogicalLength,
|
||||
) -> Option<ResizeDirection> {
|
||||
if !window.is_decorated() && window.is_resizable() {
|
||||
let border_size = f64::from(border_width.get()) * window.scale_factor();
|
||||
let location = get_resize_direction(window.inner_size(), position, border_size);
|
||||
|
||||
if current_direction != location {
|
||||
window.set_cursor(resize_direction_cursor_icon(location));
|
||||
}
|
||||
|
||||
return location;
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
pub fn handle_resize(window: &winit::window::Window, direction: Option<ResizeDirection>) {
|
||||
if let Some(dir) = direction {
|
||||
let _ = window.drag_resize_window(dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the cursor icon that corresponds to the resize direction.
|
||||
fn resize_direction_cursor_icon(resize_direction: Option<ResizeDirection>) -> CursorIcon {
|
||||
match resize_direction {
|
||||
Some(resize_direction) => match resize_direction {
|
||||
ResizeDirection::East => CursorIcon::EResize,
|
||||
ResizeDirection::North => CursorIcon::NResize,
|
||||
ResizeDirection::NorthEast => CursorIcon::NeResize,
|
||||
ResizeDirection::NorthWest => CursorIcon::NwResize,
|
||||
ResizeDirection::South => CursorIcon::SResize,
|
||||
ResizeDirection::SouthEast => CursorIcon::SeResize,
|
||||
ResizeDirection::SouthWest => CursorIcon::SwResize,
|
||||
ResizeDirection::West => CursorIcon::WResize,
|
||||
},
|
||||
None => CursorIcon::Default,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_resize_direction(
|
||||
win_size: winit::dpi::PhysicalSize<u32>,
|
||||
position: winit::dpi::PhysicalPosition<f64>,
|
||||
border_size: f64,
|
||||
) -> Option<ResizeDirection> {
|
||||
enum X {
|
||||
West,
|
||||
East,
|
||||
Default,
|
||||
}
|
||||
|
||||
enum Y {
|
||||
North,
|
||||
South,
|
||||
Default,
|
||||
}
|
||||
|
||||
let xdir = if position.x < border_size {
|
||||
X::West
|
||||
} else if position.x > (win_size.width as f64 - border_size) {
|
||||
X::East
|
||||
} else {
|
||||
X::Default
|
||||
};
|
||||
|
||||
let ydir = if position.y < border_size {
|
||||
Y::North
|
||||
} else if position.y > (win_size.height as f64 - border_size) {
|
||||
Y::South
|
||||
} else {
|
||||
Y::Default
|
||||
};
|
||||
|
||||
Some(match (xdir, ydir) {
|
||||
(X::West, Y::North) => ResizeDirection::NorthWest,
|
||||
(X::West, Y::South) => ResizeDirection::SouthWest,
|
||||
(X::West, Y::Default) => ResizeDirection::West,
|
||||
|
||||
(X::East, Y::North) => ResizeDirection::NorthEast,
|
||||
(X::East, Y::South) => ResizeDirection::SouthEast,
|
||||
(X::East, Y::Default) => ResizeDirection::East,
|
||||
|
||||
(X::Default, Y::North) => ResizeDirection::North,
|
||||
(X::Default, Y::South) => ResizeDirection::South,
|
||||
(X::Default, Y::Default) => return None,
|
||||
})
|
||||
}
|
||||
385
patches/i-slint-backend-winit/event_loop.rs
vendored
Normal file
385
patches/i-slint-backend-winit/event_loop.rs
vendored
Normal file
|
|
@ -0,0 +1,385 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
#![warn(missing_docs)]
|
||||
/*!
|
||||
This module contains the event loop implementation using winit, as well as the
|
||||
[WindowAdapter] trait used by the generated code and the run-time to change
|
||||
aspects of windows on the screen.
|
||||
*/
|
||||
use crate::EventResult;
|
||||
use crate::winitwindowadapter::WindowVisibility;
|
||||
use crate::{SharedBackendData, SlintEvent};
|
||||
use corelib::platform::PlatformError;
|
||||
use corelib::window::*;
|
||||
use i_slint_core as corelib;
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use std::cell::{RefCell, RefMut};
|
||||
use std::rc::Rc;
|
||||
use winit::event::WindowEvent;
|
||||
use winit::event_loop::{ActiveEventLoop, ControlFlow};
|
||||
|
||||
/// This enum captures run-time specific events that can be dispatched to the event loop in
|
||||
/// addition to the winit events.
|
||||
pub enum CustomEvent {
|
||||
/// On wasm request_redraw doesn't wake the event loop, so we need to manually send an event
|
||||
/// so that the event loop can run
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
WakeEventLoopWorkaround,
|
||||
/// Slint internal: Invoke the
|
||||
UserEvent(Box<dyn FnOnce() + Send>),
|
||||
/// Invoke the callback with the [`ActiveEventLoop`], for [`crate::invoke_from_active_event_loop`]
|
||||
UserEventWithEventLoop(Box<dyn FnOnce(&ActiveEventLoop) + Send>),
|
||||
/// Emitted from quit_event_loop with the current event loop generation
|
||||
Exit(usize),
|
||||
#[cfg(enable_accesskit)]
|
||||
Accesskit(accesskit_winit::Event),
|
||||
#[cfg(muda)]
|
||||
Muda(muda::MenuEvent),
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for CustomEvent {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Self::WakeEventLoopWorkaround => write!(f, "WakeEventLoopWorkaround"),
|
||||
Self::UserEvent(_) => write!(f, "UserEvent"),
|
||||
Self::UserEventWithEventLoop(_) => write!(f, "UserEventWithEventLoop"),
|
||||
Self::Exit(_) => write!(f, "Exit"),
|
||||
#[cfg(enable_accesskit)]
|
||||
Self::Accesskit(a) => write!(f, "AccessKit({a:?})"),
|
||||
#[cfg(muda)]
|
||||
Self::Muda(e) => write!(f, "Muda({e:?})"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EventLoopState {
|
||||
shared_backend_data: Rc<SharedBackendData>,
|
||||
|
||||
loop_error: Option<PlatformError>,
|
||||
|
||||
/// Set to true when pumping events for the shortest amount of time possible.
|
||||
pumping_events_instantly: bool,
|
||||
|
||||
custom_application_handler: Option<Box<dyn crate::CustomApplicationHandler>>,
|
||||
}
|
||||
|
||||
impl EventLoopState {
|
||||
pub fn new(
|
||||
shared_backend_data: Rc<SharedBackendData>,
|
||||
custom_application_handler: Option<Box<dyn crate::CustomApplicationHandler>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
shared_backend_data,
|
||||
loop_error: Default::default(),
|
||||
pumping_events_instantly: Default::default(),
|
||||
custom_application_handler,
|
||||
}
|
||||
}
|
||||
|
||||
/// Free graphics resources for any hidden windows. Called when quitting the event loop, to work
|
||||
/// around #8795.
|
||||
fn suspend_all_hidden_windows(&self) {
|
||||
let windows_to_suspend = self
|
||||
.shared_backend_data
|
||||
.active_windows
|
||||
.borrow()
|
||||
.values()
|
||||
.filter_map(|w| w.upgrade())
|
||||
.filter(|w| matches!(w.visibility(), WindowVisibility::Hidden))
|
||||
.collect::<Vec<_>>();
|
||||
for window in windows_to_suspend.into_iter() {
|
||||
let _ = window.suspend();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl winit::application::ApplicationHandler<SlintEvent> for EventLoopState {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if matches!(
|
||||
self.custom_application_handler
|
||||
.as_mut()
|
||||
.map_or(EventResult::Propagate, |handler| { handler.resumed(event_loop) }),
|
||||
EventResult::PreventDefault
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if let Err(err) = self.shared_backend_data.create_inactive_windows(event_loop) {
|
||||
self.loop_error = Some(err);
|
||||
event_loop.exit();
|
||||
}
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
window_id: winit::window::WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
let Some(window) = self.shared_backend_data.window_by_id(window_id) else {
|
||||
if let Some(handler) = self.custom_application_handler.as_mut() {
|
||||
handler.window_event(event_loop, window_id, None, None, &event);
|
||||
}
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(winit_window) = window.winit_window() else {
|
||||
return;
|
||||
};
|
||||
|
||||
if matches!(
|
||||
self.custom_application_handler.as_mut().map_or(EventResult::Propagate, |handler| {
|
||||
handler.window_event(
|
||||
event_loop,
|
||||
window_id,
|
||||
Some(&*winit_window),
|
||||
Some(window.window()),
|
||||
&event,
|
||||
)
|
||||
}),
|
||||
EventResult::PreventDefault
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
let result = window.dispatch_winit_window_event(event_loop, &winit_window, event);
|
||||
|
||||
// A window hidden during the dispatch looks kept alive until this reference is gone.
|
||||
drop(winit_window);
|
||||
self.shared_backend_data.warn_about_windows_kept_alive();
|
||||
|
||||
if let Err(err) = result {
|
||||
self.loop_error = Some(err);
|
||||
event_loop.exit();
|
||||
}
|
||||
}
|
||||
|
||||
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: SlintEvent) {
|
||||
match event.0 {
|
||||
CustomEvent::UserEvent(user_callback) => user_callback(),
|
||||
CustomEvent::UserEventWithEventLoop(user_callback) => user_callback(event_loop),
|
||||
CustomEvent::Exit(generation) => {
|
||||
if self
|
||||
.shared_backend_data
|
||||
.event_loop_generation
|
||||
.load(std::sync::atomic::Ordering::Relaxed)
|
||||
== generation
|
||||
{
|
||||
self.suspend_all_hidden_windows();
|
||||
event_loop.exit()
|
||||
}
|
||||
// else ignore the event, since it's from a previous run of the event loop
|
||||
}
|
||||
#[cfg(enable_accesskit)]
|
||||
CustomEvent::Accesskit(accesskit_winit::Event { window_id, window_event }) => {
|
||||
if let Some(window) = self.shared_backend_data.window_by_id(window_id) {
|
||||
let deferred_action = window
|
||||
.accesskit_adapter()
|
||||
.expect("internal error: accesskit adapter must exist when window exists")
|
||||
.borrow_mut()
|
||||
.process_accesskit_event(window_event);
|
||||
// access kit adapter not borrowed anymore, now invoke the deferred action
|
||||
if let Some(deferred_action) = deferred_action {
|
||||
deferred_action.invoke(window.window());
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
CustomEvent::WakeEventLoopWorkaround => {
|
||||
event_loop.set_control_flow(ControlFlow::Poll);
|
||||
}
|
||||
#[cfg(muda)]
|
||||
CustomEvent::Muda(event) => {
|
||||
if let Some((window, eid, muda_type)) =
|
||||
event.id().0.split_once('|').and_then(|(w, e)| {
|
||||
let (e, muda_type) = e.split_once('|')?;
|
||||
Some((
|
||||
self.shared_backend_data.window_by_id(
|
||||
winit::window::WindowId::from(w.parse::<u64>().ok()?),
|
||||
)?,
|
||||
e.parse::<usize>().ok()?,
|
||||
muda_type.parse::<crate::muda::MudaType>().ok()?,
|
||||
))
|
||||
})
|
||||
{
|
||||
window.muda_event(eid, muda_type);
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: winit::event::StartCause) {
|
||||
if matches!(
|
||||
self.custom_application_handler.as_mut().map_or(EventResult::Propagate, |handler| {
|
||||
handler.new_events(event_loop, cause)
|
||||
}),
|
||||
EventResult::PreventDefault
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
event_loop.set_control_flow(ControlFlow::Wait);
|
||||
|
||||
self.shared_backend_data.context().update_timers_and_animations();
|
||||
}
|
||||
|
||||
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||
self.shared_backend_data.flush_pending_mouse_move();
|
||||
// For the windows hidden outside of a window event, from a timer for example.
|
||||
self.shared_backend_data.warn_about_windows_kept_alive();
|
||||
|
||||
if matches!(
|
||||
self.custom_application_handler
|
||||
.as_mut()
|
||||
.map_or(EventResult::Propagate, |handler| { handler.about_to_wait(event_loop) }),
|
||||
EventResult::PreventDefault
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Err(err) = self.shared_backend_data.create_inactive_windows(event_loop) {
|
||||
self.loop_error = Some(err);
|
||||
}
|
||||
|
||||
if !event_loop.exiting() {
|
||||
for w in self
|
||||
.shared_backend_data
|
||||
.active_windows
|
||||
.borrow()
|
||||
.values()
|
||||
.filter_map(|w| w.upgrade())
|
||||
{
|
||||
if w.window().has_active_animations() {
|
||||
w.request_redraw();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if event_loop.control_flow() == ControlFlow::Wait
|
||||
&& let Some(next_timer) =
|
||||
self.shared_backend_data.context().duration_until_next_timer_update()
|
||||
{
|
||||
event_loop.set_control_flow(ControlFlow::wait_duration(next_timer));
|
||||
}
|
||||
|
||||
if self.pumping_events_instantly {
|
||||
event_loop.set_control_flow(ControlFlow::Poll);
|
||||
}
|
||||
}
|
||||
|
||||
fn device_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
device_id: winit::event::DeviceId,
|
||||
event: winit::event::DeviceEvent,
|
||||
) {
|
||||
if let Some(handler) = self.custom_application_handler.as_mut() {
|
||||
handler.device_event(event_loop, device_id, event);
|
||||
}
|
||||
}
|
||||
|
||||
fn suspended(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if let Some(handler) = self.custom_application_handler.as_mut() {
|
||||
handler.suspended(event_loop);
|
||||
}
|
||||
}
|
||||
|
||||
fn exiting(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if let Some(handler) = self.custom_application_handler.as_mut() {
|
||||
handler.exiting(event_loop);
|
||||
}
|
||||
}
|
||||
|
||||
fn memory_warning(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if let Some(handler) = self.custom_application_handler.as_mut() {
|
||||
handler.memory_warning(event_loop);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EventLoopState {
|
||||
/// Runs the event loop and renders the items in the provided `component` in its
|
||||
/// own window.
|
||||
#[allow(unused_mut)] // mut need changes for wasm
|
||||
pub fn run(mut self) -> Result<Self, corelib::platform::PlatformError> {
|
||||
let not_running_loop_instance = self
|
||||
.shared_backend_data
|
||||
.not_running_event_loop
|
||||
.take()
|
||||
.ok_or_else(|| PlatformError::from("Nested event loops are not supported"))?;
|
||||
let mut winit_loop = not_running_loop_instance;
|
||||
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(any(target_arch = "wasm32", ios_and_friends))] {
|
||||
winit_loop
|
||||
.run_app(&mut self)
|
||||
.map_err(|e| format!("Error running winit event loop: {e}"))?;
|
||||
// This can't really happen, as run() doesn't return
|
||||
Ok(Self::new(self.shared_backend_data.clone(), None))
|
||||
} else {
|
||||
use winit::platform::run_on_demand::EventLoopExtRunOnDemand as _;
|
||||
winit_loop
|
||||
.run_app_on_demand(&mut self)
|
||||
.map_err(|e| format!("Error running winit event loop: {e}"))?;
|
||||
|
||||
// Keep the EventLoop instance alive and re-use it in future invocations of run_event_loop().
|
||||
// Winit does not support creating multiple instances of the event loop.
|
||||
self.shared_backend_data.not_running_event_loop.replace(Some(winit_loop));
|
||||
|
||||
if let Some(error) = self.loop_error {
|
||||
return Err(error);
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the event loop and renders the items in the provided `component` in its
|
||||
/// own window.
|
||||
#[cfg(all(not(target_arch = "wasm32"), not(ios_and_friends)))]
|
||||
pub fn pump_events(
|
||||
mut self,
|
||||
timeout: Option<std::time::Duration>,
|
||||
) -> Result<(Self, winit::platform::pump_events::PumpStatus), corelib::platform::PlatformError>
|
||||
{
|
||||
use winit::platform::pump_events::EventLoopExtPumpEvents;
|
||||
|
||||
let not_running_loop_instance = self
|
||||
.shared_backend_data
|
||||
.not_running_event_loop
|
||||
.take()
|
||||
.ok_or_else(|| PlatformError::from("Nested event loops are not supported"))?;
|
||||
let mut winit_loop = not_running_loop_instance;
|
||||
|
||||
self.pumping_events_instantly = timeout.is_some_and(|duration| duration.is_zero());
|
||||
|
||||
let result = winit_loop.pump_app_events(timeout, &mut self);
|
||||
|
||||
self.pumping_events_instantly = false;
|
||||
|
||||
// Keep the EventLoop instance alive and re-use it in future invocations of run_event_loop().
|
||||
// Winit does not support creating multiple instances of the event loop.
|
||||
self.shared_backend_data.not_running_event_loop.replace(Some(winit_loop));
|
||||
|
||||
if let Some(error) = self.loop_error {
|
||||
return Err(error);
|
||||
}
|
||||
Ok((self, result))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn spawn(self) -> Result<(), corelib::platform::PlatformError> {
|
||||
use winit::platform::web::EventLoopExtWebSys;
|
||||
let not_running_loop_instance = self
|
||||
.shared_backend_data
|
||||
.not_running_event_loop
|
||||
.take()
|
||||
.ok_or_else(|| PlatformError::from("Nested event loops are not supported"))?;
|
||||
|
||||
not_running_loop_instance.spawn_app(self);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
98
patches/i-slint-backend-winit/frame_throttle.rs
vendored
Normal file
98
patches/i-slint-backend-winit/frame_throttle.rs
vendored
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use std::rc::{Rc, Weak};
|
||||
|
||||
use i_slint_core::timers::{Timer, TimerMode};
|
||||
|
||||
#[cfg(target_vendor = "apple")]
|
||||
mod apple_display_link;
|
||||
|
||||
use crate::winitwindowadapter::WinitWindowAdapter;
|
||||
|
||||
pub fn create_frame_throttle(
|
||||
window_adapter: Weak<WinitWindowAdapter>,
|
||||
_winit_window: &winit::window::Window,
|
||||
_is_wayland: bool,
|
||||
) -> Box<dyn FrameThrottle> {
|
||||
if _is_wayland {
|
||||
WinitBasedFrameThrottle::create()
|
||||
} else {
|
||||
#[cfg(target_vendor = "apple")]
|
||||
if let Some(throttle) =
|
||||
apple_display_link::try_create(window_adapter.clone(), _winit_window)
|
||||
{
|
||||
return throttle;
|
||||
}
|
||||
TimerBasedFrameThrottle::create(window_adapter)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait FrameThrottle {
|
||||
fn request_throttled_redraw(&self, winit_window: &winit::window::Window);
|
||||
}
|
||||
|
||||
struct TimerBasedFrameThrottle {
|
||||
window_adapter: Weak<WinitWindowAdapter>,
|
||||
timer: Rc<Timer>,
|
||||
}
|
||||
|
||||
impl TimerBasedFrameThrottle {
|
||||
fn create(window_adapter: Weak<WinitWindowAdapter>) -> Box<dyn FrameThrottle> {
|
||||
Box::new(Self { window_adapter, timer: Rc::new(Timer::default()) })
|
||||
}
|
||||
}
|
||||
|
||||
impl FrameThrottle for TimerBasedFrameThrottle {
|
||||
fn request_throttled_redraw(&self, winit_window: &winit::window::Window) {
|
||||
if self.timer.running() {
|
||||
return;
|
||||
}
|
||||
let refresh_interval_millihertz = winit_window
|
||||
.current_monitor()
|
||||
.and_then(|monitor| monitor.refresh_rate_millihertz())
|
||||
.unwrap_or(60000) as u64;
|
||||
let window_adapter = self.window_adapter.clone();
|
||||
let timer = Rc::downgrade(&self.timer);
|
||||
let interval =
|
||||
std::time::Duration::from_millis((1000 * 1000) / refresh_interval_millihertz);
|
||||
self.timer.start(TimerMode::Repeated, interval, move || {
|
||||
redraw_now(&window_adapter);
|
||||
|
||||
let Some(timer) = timer.upgrade() else { return };
|
||||
let Some(window_adapter) = window_adapter.upgrade() else { return };
|
||||
|
||||
let keep_running = window_adapter.pending_redraw();
|
||||
|
||||
if timer.running() {
|
||||
if !keep_running {
|
||||
timer.stop();
|
||||
}
|
||||
} else if keep_running {
|
||||
timer.restart();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn redraw_now(window_adapter: &Weak<WinitWindowAdapter>) {
|
||||
let Some(winit_window) = window_adapter.upgrade().and_then(|adapter| adapter.winit_window())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
winit_window.request_redraw();
|
||||
}
|
||||
|
||||
struct WinitBasedFrameThrottle;
|
||||
|
||||
impl WinitBasedFrameThrottle {
|
||||
fn create() -> Box<dyn FrameThrottle> {
|
||||
Box::new(Self)
|
||||
}
|
||||
}
|
||||
|
||||
impl FrameThrottle for WinitBasedFrameThrottle {
|
||||
fn request_throttled_redraw(&self, winit_window: &winit::window::Window) {
|
||||
winit_window.request_redraw();
|
||||
}
|
||||
}
|
||||
177
patches/i-slint-backend-winit/frame_throttle/apple_display_link.rs
vendored
Normal file
177
patches/i-slint-backend-winit/frame_throttle/apple_display_link.rs
vendored
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
// CADisplayLink based frame throttle, shared between macOS and the other Apple
|
||||
// platforms (iOS, etc.). The display link target, the throttle and the tick
|
||||
// logic are identical; only the way the `CADisplayLink` is obtained differs, so
|
||||
// that part lives in the platform-specific `try_create` below.
|
||||
|
||||
use std::rc::Weak;
|
||||
|
||||
use i_slint_core as corelib;
|
||||
use i_slint_core::platform::WindowAdapter as _;
|
||||
use objc2::rc::Retained;
|
||||
use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send};
|
||||
use objc2_foundation::{NSObject, NSObjectProtocol, NSRunLoop, NSRunLoopCommonModes};
|
||||
use objc2_quartz_core::CADisplayLink;
|
||||
|
||||
use crate::winitwindowadapter::WinitWindowAdapter;
|
||||
|
||||
struct DisplayLinkTargetIvars {
|
||||
window_adapter: Weak<WinitWindowAdapter>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super = NSObject)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = DisplayLinkTargetIvars]
|
||||
struct DisplayLinkTarget;
|
||||
|
||||
unsafe impl NSObjectProtocol for DisplayLinkTarget {}
|
||||
|
||||
impl DisplayLinkTarget {
|
||||
#[unsafe(method(tick:))]
|
||||
fn tick(&self, display_link: &CADisplayLink) {
|
||||
let Some(adapter) = self.ivars().window_adapter.upgrade() else {
|
||||
// The window is gone, so there is nothing for this display link to drive.
|
||||
return;
|
||||
};
|
||||
corelib::window::WindowInner::from_pub(adapter.window())
|
||||
.context()
|
||||
.update_timers_and_animations();
|
||||
// Call draw() directly rather than request_redraw(), because
|
||||
// during modal tracking loops (e.g. context menus) winit's
|
||||
// event loop is blocked and would never process RedrawRequested.
|
||||
if let Err(e) = adapter.draw() {
|
||||
i_slint_core::debug_log!("Error rendering during modal loop: {e}");
|
||||
display_link.setPaused(true);
|
||||
return;
|
||||
}
|
||||
if !adapter.window().has_active_animations() && !adapter.pending_redraw() {
|
||||
display_link.setPaused(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl DisplayLinkTarget {
|
||||
fn new(mtm: MainThreadMarker, window_adapter: Weak<WinitWindowAdapter>) -> Retained<Self> {
|
||||
let this = Self::alloc(mtm).set_ivars(DisplayLinkTargetIvars { window_adapter });
|
||||
unsafe { msg_send![super(this), init] }
|
||||
}
|
||||
}
|
||||
|
||||
struct CADisplayLinkFrameThrottle {
|
||||
// The display link retains its target per Apple docs, so storing both here
|
||||
// without a back-reference from target to display link avoids a retain cycle.
|
||||
_target: Retained<DisplayLinkTarget>,
|
||||
display_link: Retained<CADisplayLink>,
|
||||
}
|
||||
|
||||
impl Drop for CADisplayLinkFrameThrottle {
|
||||
fn drop(&mut self) {
|
||||
self.display_link.invalidate();
|
||||
}
|
||||
}
|
||||
|
||||
impl super::FrameThrottle for CADisplayLinkFrameThrottle {
|
||||
fn request_throttled_redraw(&self, winit_window: &winit::window::Window) {
|
||||
request_screen_frame_rate(&self.display_link, winit_window);
|
||||
self.display_link.setPaused(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// macOS already drives the link at the display's rate, so there is nothing to ask for.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn request_screen_frame_rate(_display_link: &CADisplayLink, _winit_window: &winit::window::Window) {
|
||||
}
|
||||
|
||||
/// Ask for the screen's full refresh rate, which iOS otherwise limits to 60Hz.
|
||||
///
|
||||
/// On iPhone the request is granted only when the bundle sets
|
||||
/// `CADisableMinimumFrameDurationOnPhone`; see the iOS platform guide under `docs/astro`.
|
||||
/// The minimum leaves the system room to halve the rate when it needs to.
|
||||
#[cfg(ios_and_friends)]
|
||||
fn request_screen_frame_rate(display_link: &CADisplayLink, winit_window: &winit::window::Window) {
|
||||
use objc2::sel;
|
||||
use objc2_quartz_core::CAFrameRateRange;
|
||||
|
||||
// -[CADisplayLink setPreferredFrameRateRange:] is only available on iOS 15.0+,
|
||||
// while the platform guide's template still deploys back to 13.0.
|
||||
if !display_link.respondsToSelector(sel!(setPreferredFrameRateRange:)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Ask on every redraw rather than once at creation, so that a window moving to
|
||||
// a screen with a different rate picks the new one up.
|
||||
let Some(millihertz) =
|
||||
winit_window.current_monitor().and_then(|monitor| monitor.refresh_rate_millihertz())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let max = millihertz as f32 / 1000.;
|
||||
// A 60Hz screen has nothing to unlock, and asking would only widen the range
|
||||
// downwards, leaving the system free to settle at 30.
|
||||
if max <= 60. {
|
||||
return;
|
||||
}
|
||||
display_link.setPreferredFrameRateRange(CAFrameRateRange::new(max / 2., max, max));
|
||||
}
|
||||
|
||||
/// Register `display_link` on the main run loop and wrap it into a throttle that
|
||||
/// starts out paused (the tick is driven on demand via `request_throttled_redraw`).
|
||||
fn into_throttle(
|
||||
target: Retained<DisplayLinkTarget>,
|
||||
display_link: Retained<CADisplayLink>,
|
||||
) -> Box<dyn super::FrameThrottle> {
|
||||
// Use NSRunLoopCommonModes so the callback fires during modal tracking loops
|
||||
// (context menus, window resize, scrolling, etc.)
|
||||
unsafe {
|
||||
display_link.addToRunLoop_forMode(&NSRunLoop::mainRunLoop(), NSRunLoopCommonModes);
|
||||
}
|
||||
|
||||
display_link.setPaused(true);
|
||||
|
||||
Box::new(CADisplayLinkFrameThrottle { _target: target, display_link })
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(super) fn try_create(
|
||||
window_adapter: Weak<WinitWindowAdapter>,
|
||||
winit_window: &winit::window::Window,
|
||||
) -> Option<Box<dyn super::FrameThrottle>> {
|
||||
use objc2::runtime::AnyClass;
|
||||
use objc2::sel;
|
||||
|
||||
// -[NSView displayLinkWithTarget:selector:] is only available on macOS
|
||||
// 14.0+. The CADisplayLink class itself is reachable on older macOS via
|
||||
// QuartzCore, so check for the selector instead of the class.
|
||||
if !AnyClass::get(c"NSView")?.responds_to(sel!(displayLinkWithTarget:selector:)) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mtm = MainThreadMarker::new().expect("frame throttle must be created on main thread");
|
||||
|
||||
let ns_view = crate::macos::ns_view(winit_window)?;
|
||||
|
||||
let target = DisplayLinkTarget::new(mtm, window_adapter);
|
||||
let display_link = unsafe { ns_view.displayLinkWithTarget_selector(&target, sel!(tick:)) };
|
||||
|
||||
Some(into_throttle(target, display_link))
|
||||
}
|
||||
|
||||
#[cfg(ios_and_friends)]
|
||||
pub(super) fn try_create(
|
||||
window_adapter: Weak<WinitWindowAdapter>,
|
||||
_winit_window: &winit::window::Window,
|
||||
) -> Option<Box<dyn super::FrameThrottle>> {
|
||||
use objc2::sel;
|
||||
|
||||
let mtm = MainThreadMarker::new().expect("frame throttle must be created on main thread");
|
||||
|
||||
let target = DisplayLinkTarget::new(mtm, window_adapter);
|
||||
let display_link =
|
||||
unsafe { CADisplayLink::displayLinkWithTarget_selector(&target, sel!(tick:)) };
|
||||
|
||||
Some(into_throttle(target, display_link))
|
||||
}
|
||||
20
patches/i-slint-backend-winit/ios.rs
vendored
Normal file
20
patches/i-slint-backend-winit/ios.rs
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
mod clipboard;
|
||||
mod color_scheme;
|
||||
mod font_size;
|
||||
mod keyboard_animator;
|
||||
mod scene;
|
||||
mod trait_observer;
|
||||
mod virtual_keyboard;
|
||||
|
||||
pub(crate) use clipboard::UiPasteboardClipboard;
|
||||
pub(crate) use color_scheme::{current_color_scheme, install_color_scheme_observer};
|
||||
pub(crate) use font_size::{current_default_font_size, install_font_size_observer};
|
||||
pub(crate) use keyboard_animator::KeyboardCurveSampler;
|
||||
pub(crate) use scene::{
|
||||
SceneLifecycle, attach_window_to_scene, content_view, install_scene_lifecycle,
|
||||
};
|
||||
pub(crate) use trait_observer::TraitChangeObserver;
|
||||
pub(crate) use virtual_keyboard::{KeyboardNotifications, register_keyboard_notifications};
|
||||
26
patches/i-slint-backend-winit/ios/clipboard.rs
vendored
Normal file
26
patches/i-slint-backend-winit/ios/clipboard.rs
vendored
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use crate::clipboard::ClipboardProvider;
|
||||
use objc2_foundation::NSString;
|
||||
use objc2_ui_kit::UIPasteboard;
|
||||
|
||||
pub(crate) struct UiPasteboardClipboard;
|
||||
|
||||
impl ClipboardProvider for UiPasteboardClipboard {
|
||||
fn get_contents(
|
||||
&mut self,
|
||||
) -> Result<String, Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
let pasteboard = UIPasteboard::generalPasteboard();
|
||||
Ok(unsafe { pasteboard.string() }.map(|s| s.to_string()).unwrap_or_default())
|
||||
}
|
||||
|
||||
fn set_contents(
|
||||
&mut self,
|
||||
data: String,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
let pasteboard = UIPasteboard::generalPasteboard();
|
||||
unsafe { pasteboard.setString(Some(&NSString::from_str(&data))) };
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
42
patches/i-slint-backend-winit/ios/color_scheme.rs
vendored
Normal file
42
patches/i-slint-backend-winit/ios/color_scheme.rs
vendored
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
// Stopgap until winit ships iOS appearance support (rust-windowing/winit#4570).
|
||||
// Once that lands, `winit_window.theme()` and `WindowEvent::ThemeChanged` will
|
||||
// work on iOS and this whole module — plus the `ios_color_scheme_observer`
|
||||
// wiring in winitwindowadapter.rs — can be deleted.
|
||||
|
||||
use std::rc::Weak;
|
||||
|
||||
use objc2::ClassType;
|
||||
use objc2_ui_kit::{
|
||||
UITraitEnvironment as _, UITraitUserInterfaceStyle, UIUserInterfaceStyle, UIView,
|
||||
};
|
||||
|
||||
use i_slint_core::items::ColorScheme;
|
||||
|
||||
use super::trait_observer::{TraitChangeObserver, install_trait_change_observer};
|
||||
use crate::winitwindowadapter::WinitWindowAdapter;
|
||||
|
||||
fn style_to_color_scheme(style: UIUserInterfaceStyle) -> ColorScheme {
|
||||
match style {
|
||||
UIUserInterfaceStyle::Dark => ColorScheme::Dark,
|
||||
UIUserInterfaceStyle::Light => ColorScheme::Light,
|
||||
_ => ColorScheme::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn current_color_scheme(view: &UIView) -> ColorScheme {
|
||||
style_to_color_scheme(unsafe { view.traitCollection().userInterfaceStyle() })
|
||||
}
|
||||
|
||||
pub(crate) fn install_color_scheme_observer(
|
||||
view: &UIView,
|
||||
adapter: Weak<WinitWindowAdapter>,
|
||||
) -> Option<TraitChangeObserver> {
|
||||
install_trait_change_observer(view, UITraitUserInterfaceStyle::class(), move |env| {
|
||||
let Some(adapter) = adapter.upgrade() else { return };
|
||||
let scheme = style_to_color_scheme(unsafe { env.traitCollection().userInterfaceStyle() });
|
||||
adapter.set_color_scheme(scheme);
|
||||
})
|
||||
}
|
||||
43
patches/i-slint-backend-winit/ios/font_size.rs
vendored
Normal file
43
patches/i-slint-backend-winit/ios/font_size.rs
vendored
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
// Feeds the system's preferred body text size (Dynamic Type) into the
|
||||
// SlintContext, where it serves as the default font size for windows that
|
||||
// don't set `default-font-size` themselves (and as the basis for `rem`).
|
||||
|
||||
use std::rc::Weak;
|
||||
|
||||
use objc2::ClassType;
|
||||
use objc2_ui_kit::{
|
||||
UIFont, UIFontTextStyleBody, UITraitCollection, UITraitEnvironment as _,
|
||||
UITraitPreferredContentSizeCategory, UIView,
|
||||
};
|
||||
|
||||
use i_slint_core::lengths::LogicalLength;
|
||||
|
||||
use super::trait_observer::{TraitChangeObserver, install_trait_change_observer};
|
||||
use crate::winitwindowadapter::WinitWindowAdapter;
|
||||
|
||||
/// Returns the preferred size for body text under the given trait collection's
|
||||
/// content size category. iOS points map 1:1 to Slint's logical pixels.
|
||||
fn body_font_size(traits: &UITraitCollection) -> LogicalLength {
|
||||
let font = UIFont::preferredFontForTextStyle_compatibleWithTraitCollection(
|
||||
unsafe { UIFontTextStyleBody },
|
||||
Some(traits),
|
||||
);
|
||||
LogicalLength::new(unsafe { font.pointSize() } as f32)
|
||||
}
|
||||
|
||||
pub(crate) fn current_default_font_size(view: &UIView) -> LogicalLength {
|
||||
body_font_size(&view.traitCollection())
|
||||
}
|
||||
|
||||
pub(crate) fn install_font_size_observer(
|
||||
view: &UIView,
|
||||
adapter: Weak<WinitWindowAdapter>,
|
||||
) -> Option<TraitChangeObserver> {
|
||||
install_trait_change_observer(view, UITraitPreferredContentSizeCategory::class(), move |env| {
|
||||
let Some(adapter) = adapter.upgrade() else { return };
|
||||
adapter.set_platform_default_font_size(body_font_size(&env.traitCollection()));
|
||||
})
|
||||
}
|
||||
151
patches/i-slint-backend-winit/ios/keyboard_animator.rs
vendored
Normal file
151
patches/i-slint-backend-winit/ios/keyboard_animator.rs
vendored
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
// cSpell: ignore Subview Superview
|
||||
use std::cell::{OnceCell, RefCell};
|
||||
|
||||
use block2::RcBlock;
|
||||
use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, rc::Retained};
|
||||
use objc2_foundation::{NSDefaultRunLoopMode, NSObject, NSObjectProtocol, NSRect, NSRunLoop};
|
||||
use objc2_quartz_core::{CADisplayLink, CATransaction};
|
||||
use objc2_ui_kit::{UIView, UIViewAnimating as _, UIViewAnimationCurve, UIViewPropertyAnimator};
|
||||
|
||||
struct DisplayLinkTargetIvars {
|
||||
view: Retained<UIView>,
|
||||
callback: Box<dyn Fn(NSRect)>,
|
||||
animator: RefCell<Option<Retained<UIViewPropertyAnimator>>>,
|
||||
display_link: OnceCell<Retained<CADisplayLink>>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super = NSObject)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = DisplayLinkTargetIvars]
|
||||
struct DisplayLinkTarget;
|
||||
|
||||
unsafe impl NSObjectProtocol for DisplayLinkTarget {}
|
||||
|
||||
impl DisplayLinkTarget {
|
||||
#[unsafe(method(tick:))]
|
||||
fn tick(&self, display_link: &CADisplayLink) {
|
||||
let this = self.ivars();
|
||||
if let Some(layer) = unsafe { this.view.layer().presentationLayer() } {
|
||||
(this.callback)(layer.frame());
|
||||
}
|
||||
let mut animator_ref = this.animator.borrow_mut();
|
||||
if let Some(false) = animator_ref.as_ref().map(|animator| animator.isRunning()) {
|
||||
display_link.setPaused(true);
|
||||
*animator_ref = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl DisplayLinkTarget {
|
||||
fn new(
|
||||
mtm: MainThreadMarker,
|
||||
view: Retained<UIView>,
|
||||
callback: impl Fn(NSRect) + 'static,
|
||||
) -> Retained<Self> {
|
||||
let this = Self::alloc(mtm).set_ivars(DisplayLinkTargetIvars {
|
||||
view,
|
||||
callback: Box::new(callback),
|
||||
animator: Default::default(),
|
||||
display_link: OnceCell::new(),
|
||||
});
|
||||
unsafe { msg_send![super(this), init] }
|
||||
}
|
||||
|
||||
fn set_display_link(&self, display_link: Retained<CADisplayLink>) {
|
||||
self.ivars().display_link.set(display_link).unwrap();
|
||||
}
|
||||
|
||||
fn stop(&self) {
|
||||
let ivars = self.ivars();
|
||||
ivars.display_link.get().unwrap().setPaused(true);
|
||||
if let Some(animator) = ivars.animator.borrow_mut().take() {
|
||||
animator.stopAnimation(true);
|
||||
}
|
||||
}
|
||||
|
||||
fn start(&self, animator: Retained<UIViewPropertyAnimator>) {
|
||||
let ivars = self.ivars();
|
||||
animator.startAnimation();
|
||||
if let Some(old_animator) = ivars.animator.borrow_mut().replace(animator) {
|
||||
old_animator.stopAnimation(true);
|
||||
}
|
||||
ivars.display_link.get().unwrap().setPaused(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// A helper to sample keyboard animation curves.
|
||||
/// Since the iOS keyboard animation is not directly accessible, we create a hidden UIView
|
||||
/// and animate its frame using the same parameters as the keyboard animation.
|
||||
/// The animation curve used by iOS is private and not documented, but using UIViewPropertyAnimator
|
||||
/// with the same duration and curve produces identical results.
|
||||
pub(crate) struct KeyboardCurveSampler {
|
||||
view: Retained<UIView>,
|
||||
target: Retained<DisplayLinkTarget>,
|
||||
mtm: MainThreadMarker,
|
||||
}
|
||||
|
||||
impl KeyboardCurveSampler {
|
||||
pub(crate) fn new(content_view: &UIView, sampler: impl Fn(NSRect) + 'static) -> Self {
|
||||
let mtm = MainThreadMarker::new().expect("Must be created on main thread");
|
||||
let view = UIView::new(mtm);
|
||||
content_view.addSubview(&view);
|
||||
|
||||
let target = DisplayLinkTarget::new(mtm, view.clone(), sampler);
|
||||
let display_link =
|
||||
unsafe { CADisplayLink::displayLinkWithTarget_selector(&target, objc2::sel!(tick:)) };
|
||||
|
||||
unsafe {
|
||||
display_link.addToRunLoop_forMode(&NSRunLoop::currentRunLoop(), NSDefaultRunLoopMode);
|
||||
}
|
||||
|
||||
display_link.setPaused(true);
|
||||
target.set_display_link(display_link);
|
||||
|
||||
Self { view, target, mtm }
|
||||
}
|
||||
|
||||
pub(crate) fn start(
|
||||
&self,
|
||||
duration: f64,
|
||||
curve: UIViewAnimationCurve,
|
||||
begin: NSRect,
|
||||
end: NSRect,
|
||||
) {
|
||||
CATransaction::begin();
|
||||
CATransaction::setDisableActions(true);
|
||||
self.target.stop();
|
||||
self.view.setFrame(begin);
|
||||
CATransaction::commit();
|
||||
|
||||
let view = self.view.clone();
|
||||
let animations = RcBlock::new(move || {
|
||||
view.setFrame(end);
|
||||
});
|
||||
|
||||
let animator = UIViewPropertyAnimator::initWithDuration_curve_animations(
|
||||
UIViewPropertyAnimator::alloc(self.mtm),
|
||||
duration, // duration is already in seconds
|
||||
curve,
|
||||
Some(&animations),
|
||||
);
|
||||
|
||||
self.target.start(animator);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DisplayLinkTargetIvars {
|
||||
fn drop(&mut self) {
|
||||
if let Some(display_link) = self.display_link.get() {
|
||||
display_link.invalidate();
|
||||
}
|
||||
if let Some(animator) = self.animator.borrow_mut().take() {
|
||||
animator.stopAnimation(true);
|
||||
}
|
||||
self.view.removeFromSuperview();
|
||||
}
|
||||
}
|
||||
172
patches/i-slint-backend-winit/ios/scene.rs
vendored
Normal file
172
patches/i-slint-backend-winit/ios/scene.rs
vendored
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
// The scene delegate that apps name in their `UIApplicationSceneManifest`, so
|
||||
// that they adopt the UIScene lifecycle. iOS 27 aborts an app that connects a
|
||||
// scene without adopting it, and UIKit decides adoption from the manifest's
|
||||
// `UISceneConfigurations` alone: a delegate installed at runtime is too late.
|
||||
//
|
||||
// A window scene owns the windows drawn on its screen, so the windows winit
|
||||
// creates have to be handed to the scene. winit may create a window before or
|
||||
// after UIKit connects the scene, so both orders attach it.
|
||||
//
|
||||
// Apple's TN3187 describes the migration and the manifest keys:
|
||||
// https://developer.apple.com/documentation/technotes/tn3187-migrating-to-the-uikit-scene-based-life-cycle
|
||||
//
|
||||
// None of this is specific to Slint, so it belongs next to the windows winit
|
||||
// creates.
|
||||
// TODO: Upstream it when upgrading to the next winit version.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::ptr::NonNull;
|
||||
use std::rc::Weak;
|
||||
|
||||
use block2::RcBlock;
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2::{ClassType as _, MainThreadMarker, MainThreadOnly, Message as _, define_class};
|
||||
use objc2_foundation::{
|
||||
NSNotification, NSNotificationCenter, NSObject, NSObjectProtocol, NSString,
|
||||
};
|
||||
use objc2_ui_kit::{
|
||||
UIApplication, UISceneDelegate, UISceneWillConnectNotification, UIView, UIWindow,
|
||||
UIWindowScene, UIWindowSceneDelegate, UIWindowSceneSessionRoleApplication,
|
||||
};
|
||||
use winit::window::WindowId;
|
||||
|
||||
use crate::winitwindowadapter::WinitWindowAdapter;
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super = NSObject)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[name = "SlintWindowSceneDelegate"]
|
||||
struct SlintWindowSceneDelegate;
|
||||
|
||||
unsafe impl NSObjectProtocol for SlintWindowSceneDelegate {}
|
||||
|
||||
// UIKit only needs this class to exist and to conform. The windows are
|
||||
// attached from `register_scene_notifications`, which can reach them.
|
||||
unsafe impl UISceneDelegate for SlintWindowSceneDelegate {}
|
||||
|
||||
unsafe impl UIWindowSceneDelegate for SlintWindowSceneDelegate {}
|
||||
);
|
||||
|
||||
/// Attaches the window hosting `view` to the app's window scene, for windows
|
||||
/// created after the scene connected. A window created before that is attached
|
||||
/// by [`register_scene_notifications`].
|
||||
pub(crate) fn attach_window_to_scene(view: &UIView) {
|
||||
if let Some(mtm) = MainThreadMarker::new()
|
||||
&& let Some(window_scene) = window_scene(mtm)
|
||||
&& let Some(window) = view.window()
|
||||
{
|
||||
attach(&window, &window_scene);
|
||||
}
|
||||
}
|
||||
|
||||
/// The `UIView` winit renders into.
|
||||
pub(crate) fn content_view(winit_window: &winit::window::Window) -> Retained<UIView> {
|
||||
use raw_window_handle::HasWindowHandle as _;
|
||||
|
||||
let raw_window_handle::RawWindowHandle::UiKit(handle) = winit_window
|
||||
.window_handle()
|
||||
.expect("a winit window on iOS always has a window handle")
|
||||
.as_raw()
|
||||
else {
|
||||
unreachable!("winit hands out UIKit window handles on iOS")
|
||||
};
|
||||
unsafe { &*(handle.ui_view.as_ptr() as *const UIView) }.retain()
|
||||
}
|
||||
|
||||
/// Keeps the scene-connection observer alive. Dropping it stops attaching
|
||||
/// windows to the scenes that connect afterwards.
|
||||
pub(crate) struct SceneLifecycle(Retained<ProtocolObject<dyn NSObjectProtocol>>);
|
||||
|
||||
impl Drop for SceneLifecycle {
|
||||
fn drop(&mut self) {
|
||||
unsafe { NSNotificationCenter::defaultCenter().removeObserver(self.0.as_ref()) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts everything the UIScene lifecycle needs in place: the delegate class the
|
||||
/// app's `UIApplicationSceneManifest` names, and the observer that attaches the
|
||||
/// windows winit created before the scene connected. Such a window belongs to
|
||||
/// no scene, which keeps it out of `UIApplication.windows` and so out of reach
|
||||
/// of the delegate.
|
||||
///
|
||||
/// Call this before `UIApplicationMain`, which is where UIKit looks the class up
|
||||
/// and connects the first scene.
|
||||
pub(crate) fn install_scene_lifecycle(
|
||||
active_windows: Weak<RefCell<HashMap<WindowId, Weak<WinitWindowAdapter>>>>,
|
||||
) -> SceneLifecycle {
|
||||
// UIKit looks the delegate up by the name in the manifest, so the class has
|
||||
// to be registered with the runtime by then.
|
||||
let _ = SlintWindowSceneDelegate::class();
|
||||
|
||||
let block = RcBlock::new(move |notification: NonNull<NSNotification>| {
|
||||
let Some(active_windows) = active_windows.upgrade() else { return };
|
||||
let Some(window_scene) = unsafe { notification.as_ref() }
|
||||
.object()
|
||||
.and_then(|scene| scene.downcast::<UIWindowScene>().ok())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if !is_app_scene(&window_scene) {
|
||||
return;
|
||||
}
|
||||
let active_windows = active_windows.borrow();
|
||||
for adapter in active_windows.values().filter_map(Weak::upgrade) {
|
||||
let Some(window) = adapter
|
||||
.winit_window()
|
||||
.map(|winit_window| content_view(&winit_window))
|
||||
.and_then(|view| view.window())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
// A hidden window belongs to whoever hid it, and attaching it here
|
||||
// would put it on screen.
|
||||
if !window.isHidden() {
|
||||
attach(&window, &window_scene);
|
||||
}
|
||||
}
|
||||
});
|
||||
// Pass no queue, so that the block runs while the scene connects rather than
|
||||
// a run loop turn later. UIKit posts this on the main thread.
|
||||
SceneLifecycle(unsafe {
|
||||
NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(
|
||||
Some(UISceneWillConnectNotification),
|
||||
None,
|
||||
None,
|
||||
&block,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// The scene that Slint's windows live on. A Slint app declares a single scene
|
||||
/// configuration, so the one connected application scene is it.
|
||||
fn window_scene(mtm: MainThreadMarker) -> Option<Retained<UIWindowScene>> {
|
||||
UIApplication::sharedApplication(mtm)
|
||||
.connectedScenes()
|
||||
.iter()
|
||||
.filter_map(|scene| scene.downcast_ref::<UIWindowScene>().map(UIWindowScene::retain))
|
||||
.find(|scene| is_app_scene(scene))
|
||||
}
|
||||
|
||||
/// The system connects window scenes of its own next to the app's.
|
||||
/// An iOS app running on macOS gets one with the role
|
||||
/// `FUWindowSceneSessionRoleSystemUI`, after the app's scene.
|
||||
/// A window attached to it never reaches the screen.
|
||||
fn is_app_scene(scene: &UIWindowScene) -> bool {
|
||||
let application_role: &NSString = unsafe { UIWindowSceneSessionRoleApplication };
|
||||
*scene.session().role() == *application_role
|
||||
}
|
||||
|
||||
fn attach(window: &UIWindow, window_scene: &UIWindowScene) {
|
||||
if window.windowScene().as_deref() == Some(window_scene) {
|
||||
return;
|
||||
}
|
||||
window.setWindowScene(Some(window_scene));
|
||||
// winit already made the window visible, but a window without a scene never
|
||||
// reached the screen.
|
||||
window.makeKeyAndVisible();
|
||||
}
|
||||
63
patches/i-slint-backend-winit/ios/trait_observer.rs
vendored
Normal file
63
patches/i-slint-backend-winit/ios/trait_observer.rs
vendored
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
// Shared scaffolding for observing UIKit trait changes (color scheme, content
|
||||
// size category, ...) on a view. Callers pass the trait class to watch and a
|
||||
// plain closure; the block plumbing and (de)registration live here.
|
||||
|
||||
use std::ptr::NonNull;
|
||||
|
||||
use block2::RcBlock;
|
||||
use objc2::{
|
||||
Message, available, msg_send,
|
||||
rc::Retained,
|
||||
runtime::{AnyClass, ProtocolObject},
|
||||
};
|
||||
use objc2_foundation::NSArray;
|
||||
use objc2_ui_kit::{
|
||||
UITraitChangeObservable, UITraitChangeRegistration, UITraitCollection, UITraitEnvironment,
|
||||
UIView,
|
||||
};
|
||||
|
||||
pub(crate) struct TraitChangeObserver {
|
||||
view: Retained<UIView>,
|
||||
registration: Retained<ProtocolObject<dyn UITraitChangeRegistration>>,
|
||||
}
|
||||
|
||||
impl Drop for TraitChangeObserver {
|
||||
fn drop(&mut self) {
|
||||
self.view.unregisterForTraitChanges(&self.registration);
|
||||
}
|
||||
}
|
||||
|
||||
/// Invokes `handler` with the changed trait environment whenever `trait_class`
|
||||
/// changes on `view`. `registerForTraitChanges:withHandler:` is iOS 17+; on older
|
||||
/// iOS this returns `None` and callers fall back to their initial one-shot query.
|
||||
pub(crate) fn install_trait_change_observer(
|
||||
view: &UIView,
|
||||
trait_class: &AnyClass,
|
||||
handler: impl Fn(&ProtocolObject<dyn UITraitEnvironment>) + 'static,
|
||||
) -> Option<TraitChangeObserver> {
|
||||
if !available!(ios = 17.0) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let handler = RcBlock::new(
|
||||
move |env: NonNull<ProtocolObject<dyn UITraitEnvironment>>,
|
||||
_prev: NonNull<UITraitCollection>| {
|
||||
handler(unsafe { env.as_ref() });
|
||||
},
|
||||
);
|
||||
|
||||
let traits: Retained<NSArray<AnyClass>> = NSArray::from_slice(&[trait_class]);
|
||||
|
||||
let registration: Retained<ProtocolObject<dyn UITraitChangeRegistration>> = unsafe {
|
||||
msg_send![
|
||||
view,
|
||||
registerForTraitChanges: &*traits,
|
||||
withHandler: &*handler,
|
||||
]
|
||||
};
|
||||
|
||||
Some(TraitChangeObserver { view: view.retain(), registration })
|
||||
}
|
||||
139
patches/i-slint-backend-winit/ios/virtual_keyboard.rs
vendored
Normal file
139
patches/i-slint-backend-winit/ios/virtual_keyboard.rs
vendored
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use std::{cell::RefCell, collections::HashMap, ptr::NonNull, rc::Weak};
|
||||
|
||||
use block2::RcBlock;
|
||||
use objc2_foundation::{
|
||||
NSNotification, NSNotificationCenter, NSNumber, NSOperationQueue, NSRect, NSValue,
|
||||
};
|
||||
use objc2_ui_kit::{UICoordinateSpace, UIScreen, UIViewAnimationCurve};
|
||||
use raw_window_handle::HasWindowHandle;
|
||||
use winit::window::WindowId;
|
||||
|
||||
use crate::winitwindowadapter::WinitWindowAdapter;
|
||||
|
||||
pub(crate) struct KeyboardNotifications(
|
||||
[objc2::rc::Retained<objc2::runtime::ProtocolObject<dyn objc2_foundation::NSObjectProtocol>>;
|
||||
3],
|
||||
);
|
||||
|
||||
impl Drop for KeyboardNotifications {
|
||||
fn drop(&mut self) {
|
||||
for notification_object in &self.0 {
|
||||
unsafe {
|
||||
objc2_foundation::NSNotificationCenter::defaultCenter()
|
||||
.removeObserver(notification_object.as_ref());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn register_keyboard_notifications(
|
||||
active_windows: Weak<RefCell<HashMap<WindowId, Weak<WinitWindowAdapter>>>>,
|
||||
) -> KeyboardNotifications {
|
||||
let event_block = RcBlock::new(move |notification: NonNull<NSNotification>| {
|
||||
if let Some(active_windows) = active_windows.upgrade() {
|
||||
handle_keyboard_notification(
|
||||
unsafe { notification.as_ref() },
|
||||
active_windows.borrow().values(),
|
||||
);
|
||||
}
|
||||
});
|
||||
let default_center = NSNotificationCenter::defaultCenter();
|
||||
let main_queue = NSOperationQueue::mainQueue();
|
||||
KeyboardNotifications(unsafe {
|
||||
[
|
||||
objc2_ui_kit::UIKeyboardWillShowNotification,
|
||||
objc2_ui_kit::UIKeyboardWillHideNotification,
|
||||
objc2_ui_kit::UIKeyboardWillChangeFrameNotification,
|
||||
]
|
||||
.map(|name| {
|
||||
default_center.addObserverForName_object_queue_usingBlock(
|
||||
Some(name),
|
||||
None,
|
||||
Some(&main_queue),
|
||||
&event_block,
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn rect_intersects(r1: NSRect, r2: NSRect) -> bool {
|
||||
r1.origin.x < r2.origin.x + r2.size.width
|
||||
&& r1.origin.x + r1.size.width > r2.origin.x
|
||||
&& r1.origin.y < r2.origin.y + r2.size.height
|
||||
&& r1.origin.y + r1.size.height > r2.origin.y
|
||||
}
|
||||
|
||||
fn handle_keyboard_notification<'a>(
|
||||
notification: &NSNotification,
|
||||
windows: impl IntoIterator<Item = &'a Weak<WinitWindowAdapter>>,
|
||||
) -> Option<()> {
|
||||
let user_info = notification.userInfo()?;
|
||||
let is_local = user_info
|
||||
.objectForKey(unsafe { objc2_ui_kit::UIKeyboardIsLocalUserInfoKey })?
|
||||
.downcast::<NSNumber>()
|
||||
.ok()?
|
||||
.as_bool();
|
||||
if !is_local {
|
||||
return Some(());
|
||||
}
|
||||
let screen = notification.object()?.downcast::<UIScreen>().ok()?;
|
||||
let coordinate_space = screen.coordinateSpace();
|
||||
|
||||
let frame_begin = unsafe {
|
||||
user_info
|
||||
.objectForKey(objc2_ui_kit::UIKeyboardFrameBeginUserInfoKey)?
|
||||
.downcast::<NSValue>()
|
||||
.ok()?
|
||||
.rectValue()
|
||||
};
|
||||
let frame_end = unsafe {
|
||||
user_info
|
||||
.objectForKey(objc2_ui_kit::UIKeyboardFrameEndUserInfoKey)?
|
||||
.downcast::<NSValue>()
|
||||
.ok()?
|
||||
.rectValue()
|
||||
};
|
||||
let animation_duration = user_info
|
||||
.objectForKey(unsafe { objc2_ui_kit::UIKeyboardAnimationDurationUserInfoKey })?
|
||||
.downcast::<NSNumber>()
|
||||
.ok()?
|
||||
.as_f64();
|
||||
let curve = UIViewAnimationCurve(
|
||||
user_info
|
||||
.objectForKey(unsafe { objc2_ui_kit::UIKeyboardAnimationCurveUserInfoKey })?
|
||||
.downcast::<NSNumber>()
|
||||
.unwrap()
|
||||
.as_isize(),
|
||||
);
|
||||
|
||||
let name = notification.name();
|
||||
if name.isEqualToString(unsafe { objc2_ui_kit::UIKeyboardWillChangeFrameNotification }) {
|
||||
for adapter in windows.into_iter() {
|
||||
let adapter = adapter.upgrade()?;
|
||||
let raw_window_handle::RawWindowHandle::UiKit(window_handle) =
|
||||
adapter.winit_window()?.window_handle().ok()?.as_raw()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let view = unsafe { &*(window_handle.ui_view.as_ptr() as *const objc2_ui_kit::UIView) };
|
||||
let frame_begin = view.convertRect_fromCoordinateSpace(frame_begin, &coordinate_space);
|
||||
let frame_end = view.convertRect_fromCoordinateSpace(frame_end, &coordinate_space);
|
||||
|
||||
// Assumes that the keyboard animation doesn't pass over the window without
|
||||
// starting or ending while intersecting.
|
||||
// Although, in this strange edge case we should probably ignore the keyboard anyways.
|
||||
if rect_intersects(view.bounds(), frame_begin)
|
||||
|| rect_intersects(view.bounds(), frame_end)
|
||||
{
|
||||
adapter.with_keyboard_curve_sampler(|kcs| {
|
||||
kcs.start(animation_duration, curve, frame_begin, frame_end);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
1399
patches/i-slint-backend-winit/lib.rs
vendored
Normal file
1399
patches/i-slint-backend-winit/lib.rs
vendored
Normal file
File diff suppressed because it is too large
Load diff
51
patches/i-slint-backend-winit/macos.rs
vendored
Normal file
51
patches/i-slint-backend-winit/macos.rs
vendored
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
//! Keeps a freshly shown window invisible until its first frame is submitted.
|
||||
//!
|
||||
//! wgpu's Metal surface hands out no drawable while the hosting `NSWindow` reports itself
|
||||
//! as not visible (gfx-rs/wgpu#8309).
|
||||
//! A window that hasn't been ordered front yet counts as such.
|
||||
//! So the frame rendered before showing the window is dropped,
|
||||
//! and AppKit maps the window with an empty content layer.
|
||||
//! The title bar shows up alone until `occlusionState` catches up and a redraw lands.
|
||||
//! Ordering the window front with an alpha of zero hides that gap.
|
||||
//! The window server still reports such a window as visible, so the redraw goes through,
|
||||
//! and the alpha is restored once a frame is submitted.
|
||||
//!
|
||||
//! wgpu fixes this in <https://github.com/gfx-rs/wgpu/pull/10302>.
|
||||
//! Remove this module once every wgpu version Slint builds against contains that fix.
|
||||
|
||||
use objc2::rc::Retained;
|
||||
use objc2_app_kit::{NSView, NSWindow};
|
||||
|
||||
/// Makes a window fully transparent for as long as this value lives.
|
||||
/// Drop it when the first frame is submitted.
|
||||
pub(crate) struct RevealOnFirstFrame {
|
||||
ns_window: Retained<NSWindow>,
|
||||
alpha: f64,
|
||||
}
|
||||
|
||||
impl RevealOnFirstFrame {
|
||||
pub(crate) fn new(winit_window: &winit::window::Window) -> Option<Self> {
|
||||
let ns_window = ns_view(winit_window)?.window()?;
|
||||
let alpha = ns_window.alphaValue();
|
||||
ns_window.setAlphaValue(0.0);
|
||||
Some(Self { ns_window, alpha })
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RevealOnFirstFrame {
|
||||
fn drop(&mut self) {
|
||||
self.ns_window.setAlphaValue(self.alpha);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn ns_view(winit_window: &winit::window::Window) -> Option<&NSView> {
|
||||
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
|
||||
|
||||
let RawWindowHandle::AppKit(handle) = winit_window.window_handle().ok()?.as_raw() else {
|
||||
return None;
|
||||
};
|
||||
Some(unsafe { handle.ns_view.cast().as_ref() })
|
||||
}
|
||||
448
patches/i-slint-backend-winit/muda.rs
vendored
Normal file
448
patches/i-slint-backend-winit/muda.rs
vendored
Normal file
|
|
@ -0,0 +1,448 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
// cSpell: ignore nsapp
|
||||
use super::CustomEvent;
|
||||
use super::WinitWindowAdapter;
|
||||
use crate::SlintEvent;
|
||||
use core::pin::Pin;
|
||||
use i_slint_core::api::LogicalPosition;
|
||||
use i_slint_core::items::MenuEntry;
|
||||
use i_slint_core::menus::MenuVTable;
|
||||
use i_slint_core::properties::{PropertyDirtyHandler, PropertyTracker};
|
||||
use muda::ContextMenu;
|
||||
use std::rc::Weak;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use winit::event_loop::EventLoopProxy;
|
||||
use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle};
|
||||
use winit::window::Window;
|
||||
|
||||
pub struct MudaAdapter {
|
||||
entries: Vec<MenuEntry>,
|
||||
tracker: Option<Pin<Box<PropertyTracker<false, MudaPropertyTracker>>>>,
|
||||
menu: Option<muda::Menu>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, strum::EnumString, strum::Display)]
|
||||
pub enum MudaType {
|
||||
Menubar,
|
||||
Context,
|
||||
}
|
||||
|
||||
static MUDA_SET_EVENT_HANDLER_INSTALLED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Returns true when `SLINT_NO_MUDA` is set, in which case the menu bar and the context menus
|
||||
/// are rendered by Slint. That's the only way to exercise these code paths on macOS and Windows.
|
||||
pub fn is_disabled() -> bool {
|
||||
std::env::var_os("SLINT_NO_MUDA").is_some()
|
||||
}
|
||||
|
||||
struct MudaPropertyTracker {
|
||||
window_adapter_weak: Weak<WinitWindowAdapter>,
|
||||
}
|
||||
|
||||
impl PropertyDirtyHandler for MudaPropertyTracker {
|
||||
fn notify(self: Pin<&Self>) {
|
||||
let win = self.window_adapter_weak.clone();
|
||||
i_slint_core::timers::Timer::single_shot(Default::default(), move || {
|
||||
if let Some(win) = win.upgrade() {
|
||||
win.rebuild_menubar();
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl MudaAdapter {
|
||||
pub fn setup(
|
||||
menubar: &vtable::VRc<MenuVTable>,
|
||||
winit_window: &Window,
|
||||
proxy: EventLoopProxy<SlintEvent>,
|
||||
window_adapter_weak: Weak<WinitWindowAdapter>,
|
||||
) -> Self {
|
||||
install_event_handler_if_necessary(proxy);
|
||||
|
||||
let tracker =
|
||||
Some(Box::pin(PropertyTracker::new_with_dirty_handler(MudaPropertyTracker {
|
||||
window_adapter_weak,
|
||||
})));
|
||||
|
||||
let mut s = Self { entries: Default::default(), tracker, menu: None };
|
||||
s.rebuild_menu(winit_window, Some(menubar), MudaType::Menubar);
|
||||
s
|
||||
}
|
||||
|
||||
pub fn show_context_menu(
|
||||
context_menu: &vtable::VRc<MenuVTable>,
|
||||
winit_window: &Window,
|
||||
position: LogicalPosition,
|
||||
proxy: EventLoopProxy<SlintEvent>,
|
||||
) -> Option<Self> {
|
||||
install_event_handler_if_necessary(proxy);
|
||||
|
||||
let mut s = Self { entries: Default::default(), tracker: None, menu: None };
|
||||
s.rebuild_menu(winit_window, Some(context_menu), MudaType::Context);
|
||||
|
||||
match winit_window.window_handle().ok()?.as_raw() {
|
||||
#[cfg(target_os = "windows")]
|
||||
RawWindowHandle::Win32(handle) => {
|
||||
let position = i_slint_core::api::WindowPosition::Logical(position);
|
||||
let position = crate::winitwindowadapter::position_to_winit(&position);
|
||||
unsafe {
|
||||
s.menu
|
||||
.as_ref()
|
||||
.expect("context menus should always have a menu")
|
||||
.show_context_menu_for_hwnd(handle.hwnd.get(), Some(position));
|
||||
}
|
||||
Some(s)
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
RawWindowHandle::AppKit(handle) => {
|
||||
// muda assumes a non-flipped NSView and flips Y internally. But winit's view
|
||||
// has isFlipped=true, so we pre-flip Y to compensate.
|
||||
let h =
|
||||
winit_window.inner_size().to_logical::<f64>(winit_window.scale_factor()).height;
|
||||
let position = Some(winit::dpi::Position::Logical(
|
||||
winit::dpi::LogicalPosition::new(position.x as f64, h - position.y as f64),
|
||||
));
|
||||
unsafe {
|
||||
s.menu
|
||||
.as_ref()
|
||||
.expect("context menus should always have a menu")
|
||||
.show_context_menu_for_nsview(handle.ns_view.as_ptr(), position)
|
||||
};
|
||||
Some(s)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rebuild_menu(
|
||||
&mut self,
|
||||
winit_window: &Window,
|
||||
menu_tree: Option<&vtable::VRc<MenuVTable>>,
|
||||
muda_type: MudaType,
|
||||
) {
|
||||
let must_set_window_redraw = cfg!(windows) && winit_window.is_visible() == Some(true);
|
||||
if must_set_window_redraw {
|
||||
win32_set_window_redraw(winit_window, false);
|
||||
}
|
||||
|
||||
// clear the menu
|
||||
self.entries.clear();
|
||||
|
||||
fn generate_menu_entry(
|
||||
menu: vtable::VRef<'_, MenuVTable>,
|
||||
entry: &MenuEntry,
|
||||
depth: usize,
|
||||
map: &mut Vec<MenuEntry>,
|
||||
window_id: &str,
|
||||
muda_type: MudaType,
|
||||
) -> Box<dyn muda::IsMenuItem> {
|
||||
let id = muda::MenuId(format!("{window_id}|{}|{}", map.len(), muda_type));
|
||||
map.push(entry.clone());
|
||||
if entry.is_separator {
|
||||
Box::new(muda::PredefinedMenuItem::separator())
|
||||
} else if !entry.has_sub_menu {
|
||||
let accelerator = keys_to_accelerator(&entry.shortcut);
|
||||
|
||||
let err_handler = |err| {
|
||||
i_slint_core::debug_log!(
|
||||
"Warning: Could not set accelerator {} for menu item {}: {err}",
|
||||
entry.shortcut,
|
||||
entry.title
|
||||
)
|
||||
};
|
||||
|
||||
// the top level always has a sub menu regardless of entry.has_sub_menu
|
||||
if entry.checkable {
|
||||
let check_menu = muda::CheckMenuItem::with_id(
|
||||
id.clone(),
|
||||
&entry.title,
|
||||
entry.enabled,
|
||||
entry.checked,
|
||||
None,
|
||||
);
|
||||
check_menu.set_key_accelerator(accelerator).map_err(err_handler).ok();
|
||||
Box::new(check_menu)
|
||||
} else if let Some(rgba) = entry.icon.to_rgba8() {
|
||||
let icon = muda::Icon::from_rgba(
|
||||
rgba.as_bytes().to_vec(),
|
||||
rgba.width(),
|
||||
rgba.height(),
|
||||
)
|
||||
.ok();
|
||||
let icon_menu = muda::IconMenuItem::with_id(
|
||||
id.clone(),
|
||||
&entry.title,
|
||||
entry.enabled,
|
||||
icon,
|
||||
None,
|
||||
);
|
||||
icon_menu.set_key_accelerator(accelerator).map_err(err_handler).ok();
|
||||
Box::new(icon_menu)
|
||||
} else {
|
||||
let menu_item =
|
||||
muda::MenuItem::with_id(id.clone(), &entry.title, entry.enabled, None);
|
||||
menu_item.set_key_accelerator(accelerator).map_err(err_handler).ok();
|
||||
Box::new(menu_item)
|
||||
}
|
||||
} else {
|
||||
let sub_menu = muda::Submenu::with_id(id.clone(), &entry.title, entry.enabled);
|
||||
if depth < 15 {
|
||||
let mut sub_entries = Default::default();
|
||||
menu.sub_menu(Some(entry), &mut sub_entries);
|
||||
for e in sub_entries {
|
||||
sub_menu
|
||||
.append(&*generate_menu_entry(
|
||||
menu,
|
||||
&e,
|
||||
depth + 1,
|
||||
map,
|
||||
window_id,
|
||||
muda_type,
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
} else {
|
||||
// infinite menu depth is possible, but we want to limit the amount of item passed to muda
|
||||
sub_menu
|
||||
.append(&muda::MenuItem::new(
|
||||
"<Error: Menu Depth limit reached>",
|
||||
false,
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
Box::new(sub_menu)
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(menu_tree) = menu_tree {
|
||||
let mut build_menu = || {
|
||||
let mut menu_entries = Default::default();
|
||||
if vtable::VRc::borrow(menu_tree).visible() {
|
||||
vtable::VRc::borrow(menu_tree).sub_menu(None, &mut menu_entries);
|
||||
}
|
||||
|
||||
if menu_entries.is_empty() && muda_type == MudaType::Menubar {
|
||||
self.menu = None;
|
||||
} else if let Some(menu) = self.menu.as_ref() {
|
||||
while menu.remove_at(0).is_some() {}
|
||||
} else {
|
||||
self.menu = Some(muda::Menu::new());
|
||||
|
||||
if muda_type == MudaType::Menubar
|
||||
&& let Some(menu) = self.menu.as_ref()
|
||||
{
|
||||
#[cfg(target_os = "windows")]
|
||||
if let RawWindowHandle::Win32(handle) =
|
||||
winit_window.window_handle().unwrap().as_raw()
|
||||
{
|
||||
let theme = match winit_window.theme() {
|
||||
Some(winit::window::Theme::Dark) => muda::MenuTheme::Dark,
|
||||
Some(winit::window::Theme::Light) => muda::MenuTheme::Light,
|
||||
None => muda::MenuTheme::Auto,
|
||||
};
|
||||
unsafe {
|
||||
menu.init_for_hwnd_with_theme(handle.hwnd.get(), theme).unwrap()
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
menu.init_for_nsapp();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Until we have menu roles, always create an app menu on macOS.
|
||||
#[cfg(target_os = "macos")]
|
||||
if matches!(muda_type, MudaType::Menubar)
|
||||
&& let Some(menu) = self.menu.as_ref()
|
||||
{
|
||||
create_default_app_menu(menu).unwrap();
|
||||
}
|
||||
|
||||
let window_id = u64::from(winit_window.id()).to_string();
|
||||
if let Some(menu) = self.menu.as_ref() {
|
||||
for e in menu_entries {
|
||||
menu.append(&*generate_menu_entry(
|
||||
vtable::VRc::borrow(menu_tree),
|
||||
&e,
|
||||
0,
|
||||
&mut self.entries,
|
||||
&window_id,
|
||||
muda_type,
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(tracker) = self.tracker.as_ref() {
|
||||
tracker.as_ref().evaluate(build_menu);
|
||||
} else {
|
||||
build_menu()
|
||||
}
|
||||
}
|
||||
|
||||
if must_set_window_redraw {
|
||||
win32_set_window_redraw(winit_window, true);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn invoke(&self, menubar: &vtable::VRc<MenuVTable>, entry_id: usize) {
|
||||
let Some(entry) = &self.entries.get(entry_id) else { return };
|
||||
vtable::VRc::borrow(menubar).activate(entry);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn set_menubar_theme(
|
||||
&self,
|
||||
winit_window: &Window,
|
||||
theme: i_slint_core::items::ColorScheme,
|
||||
) {
|
||||
let theme = match theme {
|
||||
i_slint_core::items::ColorScheme::Dark => muda::MenuTheme::Dark,
|
||||
i_slint_core::items::ColorScheme::Light => muda::MenuTheme::Light,
|
||||
i_slint_core::items::ColorScheme::Unknown | _ => muda::MenuTheme::Auto,
|
||||
};
|
||||
if let RawWindowHandle::Win32(handle) = winit_window.window_handle().unwrap().as_raw()
|
||||
&& let Some(menu) = self.menu.as_ref()
|
||||
{
|
||||
unsafe { menu.set_theme_for_hwnd(handle.hwnd.get(), theme).unwrap() };
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn setup_default_menu_bar() -> Result<Self, i_slint_core::api::PlatformError> {
|
||||
let menu_bar = muda::Menu::new();
|
||||
create_default_app_menu(&menu_bar)?;
|
||||
menu_bar.init_for_nsapp();
|
||||
Ok(Self { entries: Vec::new(), menu: Some(menu_bar), tracker: None })
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn window_activation_changed(&self, is_active: bool) {
|
||||
if is_active && let Some(menu) = self.menu.as_ref() {
|
||||
menu.init_for_nsapp();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn key_string_to_key(string: &str) -> muda::accelerator::Key {
|
||||
use muda::accelerator::Key;
|
||||
macro_rules! key_string_to_code_impl {
|
||||
($($char:literal # $_name:ident # $($_shifted:ident)? $(=> $($muda:ident)? # $($_qt:ident)|* # $($_winit:ident $(($_pos:ident))?)|* # $($_xkb:ident)|*)?;)*) => {
|
||||
match string.chars().next() {
|
||||
$($($(Some($char) => Key::$muda,)?)?)*
|
||||
_ => Key::Character(string.to_owned()),
|
||||
}
|
||||
};
|
||||
}
|
||||
i_slint_common::for_each_keys!(key_string_to_code_impl)
|
||||
}
|
||||
|
||||
fn keys_to_accelerator(
|
||||
keys: &i_slint_core::input::Keys,
|
||||
) -> Option<muda::accelerator::KeyAccelerator> {
|
||||
use muda::accelerator::*;
|
||||
|
||||
if *keys == i_slint_core::input::Keys::default() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let shortcut = i_slint_core::input::KeysInner::from_pub(keys);
|
||||
|
||||
let mut modifiers = Modifiers::empty();
|
||||
if shortcut.modifiers.control {
|
||||
if i_slint_core::is_apple_platform() {
|
||||
modifiers |= Modifiers::SUPER;
|
||||
} else {
|
||||
modifiers |= Modifiers::CONTROL;
|
||||
}
|
||||
}
|
||||
if shortcut.modifiers.alt {
|
||||
modifiers |= Modifiers::ALT;
|
||||
}
|
||||
if shortcut.modifiers.shift {
|
||||
modifiers |= Modifiers::SHIFT;
|
||||
}
|
||||
if shortcut.modifiers.meta {
|
||||
if i_slint_core::is_apple_platform() {
|
||||
modifiers |= Modifiers::CONTROL;
|
||||
} else {
|
||||
modifiers |= Modifiers::SUPER;
|
||||
}
|
||||
}
|
||||
let key = key_string_to_key(&shortcut.key);
|
||||
|
||||
Some(KeyAccelerator::new(Some(modifiers), key))
|
||||
}
|
||||
|
||||
fn install_event_handler_if_necessary(proxy: EventLoopProxy<SlintEvent>) {
|
||||
// `MenuEvent::set_event_handler()` in `muda` seems to use `OnceCell`, which is an
|
||||
// can only be set a single time. Therefore, we need to take care to only call this
|
||||
// a single time
|
||||
//
|
||||
// Arguably, `set_event_handler()` is unsafe
|
||||
if !MUDA_SET_EVENT_HANDLER_INSTALLED.load(Ordering::Relaxed) {
|
||||
muda::MenuEvent::set_event_handler(Some(move |e| {
|
||||
let _ = proxy.send_event(SlintEvent(CustomEvent::Muda(e)));
|
||||
}));
|
||||
|
||||
MUDA_SET_EVENT_HANDLER_INSTALLED.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn create_default_app_menu(menu_bar: &muda::Menu) -> Result<(), i_slint_core::api::PlatformError> {
|
||||
let app_menu = muda::Submenu::new("App", true);
|
||||
menu_bar
|
||||
.append(&app_menu)
|
||||
.and_then(|_| {
|
||||
app_menu.append_items(&[
|
||||
&muda::PredefinedMenuItem::about(None, None),
|
||||
&muda::PredefinedMenuItem::separator(),
|
||||
&muda::PredefinedMenuItem::services(None),
|
||||
&muda::PredefinedMenuItem::separator(),
|
||||
&muda::PredefinedMenuItem::hide(None),
|
||||
&muda::PredefinedMenuItem::hide_others(None),
|
||||
&muda::PredefinedMenuItem::show_all(None),
|
||||
&muda::PredefinedMenuItem::separator(),
|
||||
&muda::PredefinedMenuItem::quit(None),
|
||||
])
|
||||
})
|
||||
.map_err(|menu_bar_err| {
|
||||
i_slint_core::api::PlatformError::Other(menu_bar_err.to_string())
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// On Windows, we need to disable window redraw while rebuilding the menu, otherwise
|
||||
/// we might see flickering
|
||||
#[allow(unused_variables)]
|
||||
fn win32_set_window_redraw(winit_window: &Window, redraw: bool) {
|
||||
#[cfg(target_os = "windows")]
|
||||
if let RawWindowHandle::Win32(handle) = winit_window.window_handle().unwrap().as_raw() {
|
||||
use std::os::raw::c_void;
|
||||
use windows::Win32::Foundation::HWND;
|
||||
use windows::Win32::Foundation::WPARAM;
|
||||
use windows::Win32::UI::WindowsAndMessaging::DrawMenuBar;
|
||||
use windows::Win32::UI::WindowsAndMessaging::SendMessageW;
|
||||
use windows::Win32::UI::WindowsAndMessaging::WM_SETREDRAW;
|
||||
|
||||
let hwnd = HWND(handle.hwnd.get() as *mut c_void);
|
||||
|
||||
unsafe {
|
||||
SendMessageW(hwnd, WM_SETREDRAW, Some(WPARAM(redraw as usize)), None);
|
||||
}
|
||||
|
||||
if redraw {
|
||||
unsafe {
|
||||
let _ = DrawMenuBar(hwnd);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
330
patches/i-slint-backend-winit/renderer/femtovg.rs
vendored
Normal file
330
patches/i-slint-backend-winit/renderer/femtovg.rs
vendored
Normal file
|
|
@ -0,0 +1,330 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
// cSpell: ignore glcontext glprobe webglcontextlost webglcontextrestored
|
||||
use std::rc::Rc;
|
||||
#[cfg(supports_opengl)]
|
||||
use std::rc::Weak;
|
||||
use std::sync::Arc;
|
||||
|
||||
use i_slint_core::renderer::{DrawOutcome, Renderer};
|
||||
use i_slint_core::{graphics::RequestedGraphicsAPI, platform::PlatformError};
|
||||
#[cfg(supports_opengl)]
|
||||
use i_slint_renderer_femtovg::{FemtoVGOpenGLRendererExt, opengl};
|
||||
use i_slint_renderer_femtovg::{FemtoVGRenderer, FemtoVGRendererExt};
|
||||
|
||||
use winit::event_loop::ActiveEventLoop;
|
||||
#[cfg(all(target_arch = "wasm32", supports_opengl))]
|
||||
use winit::platform::web::WindowExtWebSys;
|
||||
|
||||
use super::WinitCompatibleRenderer;
|
||||
|
||||
#[cfg(all(supports_opengl, not(target_arch = "wasm32")))]
|
||||
mod glcontext;
|
||||
#[cfg(all(supports_opengl, target_os = "windows"))]
|
||||
mod glprobe;
|
||||
|
||||
#[cfg(supports_opengl)]
|
||||
pub struct GlutinFemtoVGRenderer {
|
||||
renderer: FemtoVGRenderer<opengl::OpenGLBackend>,
|
||||
_requested_graphics_api: Option<RequestedGraphicsAPI>,
|
||||
_shared_backend_data_weak: Weak<crate::SharedBackendData>,
|
||||
}
|
||||
|
||||
#[cfg(supports_opengl)]
|
||||
impl GlutinFemtoVGRenderer {
|
||||
pub fn new_suspended(
|
||||
shared_backend_data: &Rc<crate::SharedBackendData>,
|
||||
) -> Result<Box<dyn WinitCompatibleRenderer>, PlatformError> {
|
||||
// Bail out before a window is created, so that the backend can still fall back to
|
||||
// another renderer.
|
||||
#[cfg(target_os = "windows")]
|
||||
if !glprobe::opengl_2_available() {
|
||||
return Err("The FemtoVG renderer requires an OpenGL 2.0 driver".into());
|
||||
}
|
||||
|
||||
Ok(Box::new(Self {
|
||||
renderer: FemtoVGRenderer::new_suspended(),
|
||||
_requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
|
||||
_shared_backend_data_weak: Rc::downgrade(shared_backend_data),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(supports_opengl)]
|
||||
impl super::WinitCompatibleRenderer for GlutinFemtoVGRenderer {
|
||||
fn render(&self, _window: &i_slint_core::api::Window) -> Result<DrawOutcome, PlatformError> {
|
||||
self.renderer.render().map(|()| DrawOutcome::Success)
|
||||
}
|
||||
|
||||
fn as_core_renderer(&self) -> &dyn Renderer {
|
||||
&self.renderer
|
||||
}
|
||||
|
||||
fn resume(
|
||||
&self,
|
||||
active_event_loop: &ActiveEventLoop,
|
||||
window_attributes: winit::window::WindowAttributes,
|
||||
_window_adapter_weak: std::rc::Weak<crate::winitwindowadapter::WinitWindowAdapter>,
|
||||
) -> Result<Arc<winit::window::Window>, PlatformError> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let (winit_window, opengl_context) = glcontext::OpenGLContext::new_context(
|
||||
window_attributes,
|
||||
active_event_loop,
|
||||
self._requested_graphics_api.as_ref().map(TryInto::try_into).transpose()?,
|
||||
)?;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let winit_window = Arc::new(active_event_loop.create_window(window_attributes).map_err(
|
||||
|winit_os_error| {
|
||||
PlatformError::from(format!(
|
||||
"FemtoVG Renderer: Could not create winit window wrapper for DOM canvas: {}",
|
||||
winit_os_error
|
||||
))
|
||||
},
|
||||
)?);
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
let html_canvas = winit_window
|
||||
.canvas()
|
||||
.ok_or_else(|| "FemtoVG Renderer: winit didn't return a canvas")?;
|
||||
|
||||
self.renderer.set_opengl_context(
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
opengl_context,
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
html_canvas.clone(),
|
||||
)?;
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
self.setup_webgl_context_loss_handlers(winit_window.id(), html_canvas);
|
||||
|
||||
Ok(winit_window)
|
||||
}
|
||||
|
||||
fn suspend(&self) -> Result<(), PlatformError> {
|
||||
self.renderer.clear_graphics_context()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(supports_opengl, target_family = "wasm"))]
|
||||
impl GlutinFemtoVGRenderer {
|
||||
fn setup_webgl_context_loss_handlers(
|
||||
&self,
|
||||
window_id: winit::window::WindowId,
|
||||
html_canvas: web_sys::HtmlCanvasElement,
|
||||
) {
|
||||
use wasm_bindgen::JsCast;
|
||||
use wasm_bindgen::closure::Closure;
|
||||
|
||||
let add_listener = |name, closure: Closure<dyn Fn(web_sys::WebGlContextEvent)>| {
|
||||
html_canvas
|
||||
.add_event_listener_with_callback(name, closure.as_ref().unchecked_ref())
|
||||
.unwrap();
|
||||
closure.forget();
|
||||
};
|
||||
|
||||
add_listener(
|
||||
"webglcontextlost",
|
||||
Closure::wrap(Box::new({
|
||||
let shared_backend_data_weak = self._shared_backend_data_weak.clone();
|
||||
move |event: web_sys::WebGlContextEvent| {
|
||||
let Some(window_adapter) = shared_backend_data_weak
|
||||
.upgrade()
|
||||
.and_then(|backend_data| backend_data.window_by_id(window_id))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
i_slint_core::debug_log!(
|
||||
"Slint: Suspending renderer due to WebGL context loss"
|
||||
);
|
||||
let this = (window_adapter.renderer() as &dyn std::any::Any)
|
||||
.downcast_ref::<Self>()
|
||||
.unwrap();
|
||||
let _ = this.renderer.clear_graphics_context().ok();
|
||||
// Preventing default is the way to make sure the browser sends a webglcontextrestored event
|
||||
// when the context is back.
|
||||
event.prevent_default();
|
||||
}
|
||||
}) as Box<dyn Fn(web_sys::WebGlContextEvent)>),
|
||||
);
|
||||
add_listener(
|
||||
"webglcontextrestored",
|
||||
Closure::wrap(Box::new({
|
||||
let shared_backend_data_weak = self._shared_backend_data_weak.clone();
|
||||
let html_canvas = html_canvas.clone();
|
||||
move |_event: web_sys::WebGlContextEvent| {
|
||||
let Some(window_adapter) = shared_backend_data_weak
|
||||
.upgrade()
|
||||
.and_then(|backend_data| backend_data.window_by_id(window_id))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
i_slint_core::debug_log!(
|
||||
"Slint: Restoring renderer due to WebGL context restoration"
|
||||
);
|
||||
let this = (window_adapter.renderer() as &dyn std::any::Any)
|
||||
.downcast_ref::<Self>()
|
||||
.unwrap();
|
||||
if this.renderer.set_opengl_context(html_canvas.clone()).is_ok() {
|
||||
use i_slint_core::platform::WindowAdapter;
|
||||
window_adapter.request_redraw();
|
||||
let _ = window_adapter.draw().ok();
|
||||
}
|
||||
}
|
||||
}) as Box<dyn Fn(web_sys::WebGlContextEvent)>),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "renderer-femtovg-wgpu")]
|
||||
fn wgpu_backends_to_avoid() -> i_slint_core::graphics::wgpu_30::wgpu::Backends {
|
||||
// On WASM keep GL so wgpu can fall through to WebGL when WebGPU is missing.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
i_slint_core::graphics::wgpu_30::default_backends_to_avoid()
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
i_slint_core::graphics::wgpu_30::wgpu::Backends::empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "renderer-femtovg-wgpu")]
|
||||
pub struct WGPUFemtoVGRenderer {
|
||||
renderer: FemtoVGRenderer<i_slint_renderer_femtovg::wgpu::WGPUBackend>,
|
||||
requested_graphics_api: Option<RequestedGraphicsAPI>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "renderer-femtovg-wgpu")]
|
||||
impl WGPUFemtoVGRenderer {
|
||||
pub fn new_suspended(
|
||||
shared_backend_data: &Rc<crate::SharedBackendData>,
|
||||
) -> Result<Box<dyn WinitCompatibleRenderer>, PlatformError> {
|
||||
if !i_slint_core::graphics::wgpu_30::any_wgpu30_adapters_with_gpu(
|
||||
shared_backend_data.requested_graphics_api.clone(),
|
||||
wgpu_backends_to_avoid(),
|
||||
) {
|
||||
return Err(PlatformError::from("WGPU: No GPU adapters found"));
|
||||
}
|
||||
Ok(Box::new(Self {
|
||||
renderer: FemtoVGRenderer::<i_slint_renderer_femtovg::wgpu::WGPUBackend>::new_suspended(
|
||||
),
|
||||
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "renderer-femtovg-wgpu")]
|
||||
impl WinitCompatibleRenderer for WGPUFemtoVGRenderer {
|
||||
#[cfg(target_os = "macos")]
|
||||
fn set_transparent(&self, transparent: bool) -> Result<(), PlatformError> {
|
||||
self.renderer.set_transparent(transparent);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn render(&self, window: &i_slint_core::api::Window) -> Result<DrawOutcome, PlatformError> {
|
||||
// Use the Ext entry point so we get the `DrawOutcome` back without changing
|
||||
// `FemtoVGRenderer::render`'s public `Result<(), _>` signature.
|
||||
self.renderer.render_transformed_with_post_callback(0., (0., 0.), window.size(), None)
|
||||
}
|
||||
|
||||
fn as_core_renderer(&self) -> &dyn Renderer {
|
||||
&self.renderer
|
||||
}
|
||||
|
||||
fn suspend(&self) -> Result<(), PlatformError> {
|
||||
self.renderer.clear_graphics_context()
|
||||
}
|
||||
|
||||
fn resume(
|
||||
&self,
|
||||
active_event_loop: &ActiveEventLoop,
|
||||
window_attributes: winit::window::WindowAttributes,
|
||||
window_adapter_weak: std::rc::Weak<crate::winitwindowadapter::WinitWindowAdapter>,
|
||||
) -> Result<Arc<winit::window::Window>, PlatformError> {
|
||||
let transparent = window_attributes.transparent;
|
||||
let winit_window = Arc::new(active_event_loop.create_window(window_attributes).map_err(
|
||||
|winit_os_error| {
|
||||
PlatformError::from(format!(
|
||||
"Error creating native window for FemtoVG rendering: {}",
|
||||
winit_os_error
|
||||
))
|
||||
},
|
||||
)?);
|
||||
|
||||
let requested_graphics_api = self.requested_graphics_api.clone();
|
||||
let window_handle = Box::new(winit_window.clone())
|
||||
as Box<dyn i_slint_core::graphics::wgpu_30::wgpu::DisplayAndWindowHandle>;
|
||||
let winit_window_for_size = winit_window.clone();
|
||||
|
||||
let context = {
|
||||
let window_adapter = window_adapter_weak.upgrade().ok_or_else(|| {
|
||||
PlatformError::from("Cannot initialize wgpu: window adapter is destroyed")
|
||||
})?;
|
||||
use i_slint_core::platform::WindowAdapter;
|
||||
i_slint_core::window::WindowInner::from_pub(window_adapter.window()).context().clone()
|
||||
};
|
||||
|
||||
i_slint_core::graphics::wgpu_30::init_instance_adapter_device_queue_surface_then(
|
||||
&context,
|
||||
window_handle,
|
||||
requested_graphics_api,
|
||||
wgpu_backends_to_avoid(),
|
||||
move |instance, adapter, device, queue, surface| {
|
||||
finalize_wgpu_init(
|
||||
&window_adapter_weak,
|
||||
&winit_window_for_size,
|
||||
instance,
|
||||
adapter,
|
||||
device,
|
||||
queue,
|
||||
surface,
|
||||
transparent,
|
||||
)?;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
i_slint_core::debug_log!("Slint: Using FemtoVG WGPU renderer");
|
||||
Ok(())
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(winit_window)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "renderer-femtovg-wgpu")]
|
||||
fn finalize_wgpu_init(
|
||||
window_adapter_weak: &std::rc::Weak<crate::winitwindowadapter::WinitWindowAdapter>,
|
||||
winit_window: &Arc<winit::window::Window>,
|
||||
instance: i_slint_core::graphics::wgpu_30::wgpu::Instance,
|
||||
adapter: i_slint_core::graphics::wgpu_30::wgpu::Adapter,
|
||||
device: i_slint_core::graphics::wgpu_30::wgpu::Device,
|
||||
queue: i_slint_core::graphics::wgpu_30::wgpu::Queue,
|
||||
surface: i_slint_core::graphics::wgpu_30::wgpu::Surface<'static>,
|
||||
transparent: bool,
|
||||
) -> Result<(), PlatformError> {
|
||||
let Some(window_adapter) = window_adapter_weak.upgrade() else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let this = (window_adapter.renderer() as &dyn std::any::Any)
|
||||
.downcast_ref::<WGPUFemtoVGRenderer>()
|
||||
.unwrap();
|
||||
|
||||
use crate::winit_compat::WindowSurfaceSizeExt;
|
||||
let slint_size =
|
||||
crate::winitwindowadapter::physical_size_to_slint(&winit_window.surface_size());
|
||||
this.renderer.configure_surface_from_init_result(
|
||||
instance,
|
||||
adapter,
|
||||
device,
|
||||
queue,
|
||||
surface,
|
||||
slint_size,
|
||||
transparent,
|
||||
);
|
||||
|
||||
use i_slint_core::platform::WindowAdapter;
|
||||
window_adapter.request_redraw();
|
||||
Ok(())
|
||||
}
|
||||
220
patches/i-slint-backend-winit/renderer/femtovg/glcontext.rs
vendored
Normal file
220
patches/i-slint-backend-winit/renderer/femtovg/glcontext.rs
vendored
Normal file
|
|
@ -0,0 +1,220 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use std::{num::NonZeroU32, sync::Arc};
|
||||
|
||||
use crate::winit_compat::WindowSurfaceSizeExt;
|
||||
use glutin::{
|
||||
config::GlConfig,
|
||||
context::{ContextApi, ContextAttributesBuilder},
|
||||
display::GetGlDisplay,
|
||||
prelude::*,
|
||||
surface::{SurfaceAttributesBuilder, WindowSurface},
|
||||
};
|
||||
use i_slint_core::{graphics::RequestedOpenGLVersion, platform::PlatformError};
|
||||
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
|
||||
|
||||
pub struct OpenGLContext {
|
||||
context: glutin::context::PossiblyCurrentContext,
|
||||
surface: glutin::surface::Surface<glutin::surface::WindowSurface>,
|
||||
winit_window: Arc<winit::window::Window>,
|
||||
}
|
||||
|
||||
unsafe impl i_slint_renderer_femtovg::opengl::OpenGLInterface for OpenGLContext {
|
||||
fn ensure_current(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
if !self.context.is_current() {
|
||||
self.context.make_current(&self.surface).map_err(|glutin_error| -> PlatformError {
|
||||
format!("FemtoVG: Error making context current: {glutin_error}").into()
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn swap_buffers(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
self.winit_window.pre_present_notify();
|
||||
|
||||
self.surface.swap_buffers(&self.context).map_err(|glutin_error| -> PlatformError {
|
||||
format!("FemtoVG: Error swapping buffers: {glutin_error}").into()
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn resize(
|
||||
&self,
|
||||
width: NonZeroU32,
|
||||
height: NonZeroU32,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
self.ensure_current()?;
|
||||
self.surface.resize(&self.context, width, height);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_proc_address(&self, name: &std::ffi::CStr) -> *const std::ffi::c_void {
|
||||
self.context.display().get_proc_address(name)
|
||||
}
|
||||
}
|
||||
|
||||
impl OpenGLContext {
|
||||
pub(crate) fn new_context(
|
||||
window_attributes: winit::window::WindowAttributes,
|
||||
active_event_loop: &winit::event_loop::ActiveEventLoop,
|
||||
requested_opengl_version: Option<RequestedOpenGLVersion>,
|
||||
) -> Result<(Arc<winit::window::Window>, Self), PlatformError> {
|
||||
let config_template_builder = glutin::config::ConfigTemplateBuilder::new();
|
||||
|
||||
// On macOS, there's only one GL config and that's initialized based on the values in the config template
|
||||
// builder. So if that one has transparency enabled, it'll show up in the config, and will be set on the
|
||||
// context later. So we must enable it here, there's no way of enabling it later.
|
||||
// On EGL/GLX/WGL there are system provided configs that may or may not support transparency. Here in case
|
||||
// the system doesn't support transparency, we want to fall back to a config that doesn't - better than not
|
||||
// rendering anything at all. So we don't want to limit the configurations we get to see early on.
|
||||
// Commented out due to https://github.com/rust-windowing/glutin/issues/1640
|
||||
#[cfg(target_os = "macos")]
|
||||
let config_template_builder = config_template_builder.with_transparency(true);
|
||||
|
||||
let display_builder = glutin_winit::DisplayBuilder::new()
|
||||
.with_preference(glutin_winit::ApiPreference::FallbackEgl)
|
||||
.with_window_attributes(Some(window_attributes.clone()));
|
||||
let config_picker = |it: Box<dyn Iterator<Item = glutin::config::Config> + '_>| {
|
||||
it.reduce(|accum, config| {
|
||||
let transparency_check = config.supports_transparency().unwrap_or(false)
|
||||
& !accum.supports_transparency().unwrap_or(false);
|
||||
|
||||
if transparency_check || config.num_samples() < accum.num_samples() {
|
||||
config
|
||||
} else {
|
||||
accum
|
||||
}
|
||||
})
|
||||
.expect("internal error: Could not find any matching GL configuration")
|
||||
};
|
||||
let (window, gl_config) = display_builder
|
||||
.build(active_event_loop, config_template_builder, config_picker)
|
||||
.map_err(|glutin_err| {
|
||||
format!(
|
||||
"Error creating OpenGL display ({:?}) with glutin: {}",
|
||||
active_event_loop.display_handle(),
|
||||
glutin_err
|
||||
)
|
||||
})?;
|
||||
|
||||
let gl_display = gl_config.display();
|
||||
|
||||
let raw_window_handle = window
|
||||
.as_ref()
|
||||
.map(|w| w.window_handle())
|
||||
.transpose()
|
||||
.map_err(|err| {
|
||||
format!(
|
||||
"Failed to retrieve a window handle while creating an OpenGL display: {err:?}"
|
||||
)
|
||||
})?
|
||||
.map(|h| h.as_raw());
|
||||
|
||||
let requested_opengl_version =
|
||||
requested_opengl_version.unwrap_or(RequestedOpenGLVersion::OpenGLES(Some((2, 0))));
|
||||
let preferred_context_attributes = match requested_opengl_version {
|
||||
RequestedOpenGLVersion::OpenGL(version) => {
|
||||
let version =
|
||||
version.map(|(major, minor)| glutin::context::Version { major, minor });
|
||||
ContextAttributesBuilder::new()
|
||||
.with_context_api(ContextApi::OpenGl(version))
|
||||
.build(raw_window_handle)
|
||||
}
|
||||
RequestedOpenGLVersion::OpenGLES(version) => {
|
||||
let version =
|
||||
version.map(|(major, minor)| glutin::context::Version { major, minor });
|
||||
|
||||
ContextAttributesBuilder::new()
|
||||
.with_context_api(ContextApi::Gles(version))
|
||||
.build(raw_window_handle)
|
||||
}
|
||||
};
|
||||
|
||||
let fallback_context_attributes = ContextAttributesBuilder::new().build(raw_window_handle);
|
||||
|
||||
let not_current_gl_context = unsafe {
|
||||
gl_display
|
||||
.create_context(&gl_config, &preferred_context_attributes)
|
||||
.or_else(|_| gl_display.create_context(&gl_config, &fallback_context_attributes))
|
||||
.map_err(|glutin_err| format!("Cannot create OpenGL context: {glutin_err}"))?
|
||||
};
|
||||
|
||||
let window = match window {
|
||||
Some(window) => window,
|
||||
None => glutin_winit::finalize_window(active_event_loop, window_attributes, &gl_config)
|
||||
.map_err(|winit_os_error| {
|
||||
format!("Error finalizing window for OpenGL rendering: {winit_os_error}")
|
||||
})?,
|
||||
};
|
||||
|
||||
let raw_window_handle = window.window_handle().map_err(|err| {
|
||||
format!("Failed to retrieve a window handle for window we just created: {err:?}")
|
||||
})?;
|
||||
|
||||
let size: winit::dpi::PhysicalSize<u32> = window.surface_size();
|
||||
|
||||
let width: std::num::NonZeroU32 = size.width.try_into().map_err(|_| {
|
||||
format!(
|
||||
"Attempting to create an OpenGL window surface with an invalid width: {}",
|
||||
size.width
|
||||
)
|
||||
})?;
|
||||
let height: std::num::NonZeroU32 = size.height.try_into().map_err(|_| {
|
||||
format!(
|
||||
"Attempting to create an OpenGL window surface with an invalid height: {}",
|
||||
size.height
|
||||
)
|
||||
})?;
|
||||
|
||||
let attrs = SurfaceAttributesBuilder::<WindowSurface>::new().build(
|
||||
raw_window_handle.as_raw(),
|
||||
width,
|
||||
height,
|
||||
);
|
||||
|
||||
let surface = unsafe {
|
||||
gl_display.create_window_surface(&gl_config, &attrs).map_err(|glutin_err| {
|
||||
format!("Error creating OpenGL Window surface: {glutin_err}")
|
||||
})?
|
||||
};
|
||||
|
||||
let context = not_current_gl_context.make_current(&surface)
|
||||
.map_err(|glutin_error: glutin::error::Error| -> PlatformError {
|
||||
format!("FemtoVG Renderer: Failed to make newly created OpenGL context current: {glutin_error}")
|
||||
.into()
|
||||
})?;
|
||||
|
||||
// Align the GL layer to the top-left, so that resizing only invalidates the bottom/right
|
||||
// part of the window.
|
||||
#[cfg(target_os = "macos")]
|
||||
if let raw_window_handle::RawWindowHandle::AppKit(raw_window_handle::AppKitWindowHandle {
|
||||
ns_view,
|
||||
..
|
||||
}) = window
|
||||
.window_handle()
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"Error obtaining window handle to adjust nsview layer contents placement: {e}"
|
||||
)
|
||||
})?
|
||||
.as_raw()
|
||||
{
|
||||
let ns_view: &objc2_app_kit::NSView = unsafe { ns_view.cast().as_ref() };
|
||||
ns_view.setLayerContentsPlacement(objc2_app_kit::NSViewLayerContentsPlacement::TopLeft);
|
||||
}
|
||||
|
||||
// Try to default to vsync and ignore if the driver doesn't support it.
|
||||
surface
|
||||
.set_swap_interval(
|
||||
&context,
|
||||
glutin::surface::SwapInterval::Wait(NonZeroU32::new(1).unwrap()),
|
||||
)
|
||||
.ok();
|
||||
|
||||
let window = Arc::new(window);
|
||||
|
||||
Ok((window.clone(), Self { context, surface, winit_window: window }))
|
||||
}
|
||||
}
|
||||
142
patches/i-slint-backend-winit/renderer/femtovg/glprobe.rs
vendored
Normal file
142
patches/i-slint-backend-winit/renderer/femtovg/glprobe.rs
vendored
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
// cSpell: ignore clipchildren clipsiblings doublebuffer owndc
|
||||
// cSpell: ignore pixelformatdescriptor wndclassw
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
|
||||
use windows::Win32::Graphics::Gdi::{GetDC, HDC, ReleaseDC};
|
||||
use windows::Win32::Graphics::OpenGL::{
|
||||
ChoosePixelFormat, PFD_DOUBLEBUFFER, PFD_DRAW_TO_WINDOW, PFD_MAIN_PLANE, PFD_SUPPORT_OPENGL,
|
||||
PFD_TYPE_RGBA, PIXELFORMATDESCRIPTOR, SetPixelFormat, wglCreateContext, wglDeleteContext,
|
||||
wglGetCurrentContext, wglGetCurrentDC, wglGetProcAddress, wglMakeCurrent,
|
||||
};
|
||||
use windows::Win32::UI::WindowsAndMessaging::{
|
||||
CS_OWNDC, CreateWindowExW, DefWindowProcW, DestroyWindow, RegisterClassW, UnregisterClassW,
|
||||
WINDOW_EX_STYLE, WNDCLASSW, WS_CLIPCHILDREN, WS_CLIPSIBLINGS, WS_OVERLAPPED,
|
||||
};
|
||||
use windows::core::{s, w};
|
||||
|
||||
pub fn opengl_2_available() -> bool {
|
||||
static AVAILABLE: OnceLock<bool> = OnceLock::new();
|
||||
// A probe that couldn't run says nothing about the driver, and glutin may still
|
||||
// reach a working one through EGL.
|
||||
*AVAILABLE.get_or_init(|| unsafe { probe() }.unwrap_or(true))
|
||||
}
|
||||
|
||||
/// Every Windows installation has an opengl32.dll, but in virtual machines it often provides
|
||||
/// only OpenGL 1.1, without the shader entry points. Creating a context still succeeds there,
|
||||
/// so probe with a throwaway window and context up-front.
|
||||
///
|
||||
/// Returns `None` if the probe couldn't run, which says nothing about the driver.
|
||||
unsafe fn probe() -> Option<bool> {
|
||||
unsafe {
|
||||
let class_name = w!("SlintOpenGLProbe");
|
||||
let window_class = WNDCLASSW {
|
||||
style: CS_OWNDC,
|
||||
lpfnWndProc: Some(window_proc),
|
||||
lpszClassName: class_name,
|
||||
..Default::default()
|
||||
};
|
||||
if RegisterClassW(&window_class) == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// WGL requires a window that clips its children and siblings.
|
||||
let available = CreateWindowExW(
|
||||
WINDOW_EX_STYLE::default(),
|
||||
class_name,
|
||||
w!(""),
|
||||
WS_OVERLAPPED | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.ok()
|
||||
.and_then(|window| {
|
||||
let available = probe_window(window);
|
||||
let _ = DestroyWindow(window);
|
||||
available
|
||||
});
|
||||
|
||||
let _ = UnregisterClassW(class_name, None);
|
||||
|
||||
available
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "system" fn window_proc(
|
||||
window: HWND,
|
||||
message: u32,
|
||||
wparam: WPARAM,
|
||||
lparam: LPARAM,
|
||||
) -> LRESULT {
|
||||
unsafe { DefWindowProcW(window, message, wparam, lparam) }
|
||||
}
|
||||
|
||||
unsafe fn probe_window(window: HWND) -> Option<bool> {
|
||||
unsafe {
|
||||
let hdc = GetDC(Some(window));
|
||||
if hdc.is_invalid() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let available = probe_device_context(hdc);
|
||||
|
||||
ReleaseDC(Some(window), hdc);
|
||||
|
||||
available
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn probe_device_context(hdc: HDC) -> Option<bool> {
|
||||
unsafe {
|
||||
let pixel_format_descriptor = PIXELFORMATDESCRIPTOR {
|
||||
nSize: std::mem::size_of::<PIXELFORMATDESCRIPTOR>() as u16,
|
||||
nVersion: 1,
|
||||
dwFlags: PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
|
||||
iPixelType: PFD_TYPE_RGBA,
|
||||
cColorBits: 32,
|
||||
cDepthBits: 24,
|
||||
iLayerType: PFD_MAIN_PLANE.0 as u8,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let pixel_format = ChoosePixelFormat(hdc, &pixel_format_descriptor);
|
||||
if pixel_format == 0 {
|
||||
return None;
|
||||
}
|
||||
SetPixelFormat(hdc, pixel_format, &pixel_format_descriptor).ok()?;
|
||||
|
||||
let context = wglCreateContext(hdc).ok()?;
|
||||
|
||||
// Restore whatever was current before, so that probing from a thread that already
|
||||
// renders through WGL is harmless.
|
||||
let previous_context = wglGetCurrentContext();
|
||||
let previous_hdc = wglGetCurrentDC();
|
||||
|
||||
let available = wglMakeCurrent(hdc, context).is_ok().then(|| {
|
||||
let address = wglGetProcAddress(s!("glCreateShader")).map_or(0, |entry| entry as usize);
|
||||
let _ = wglMakeCurrent(previous_hdc, previous_context);
|
||||
// Besides null, some drivers report a missing entry point as 1, 2, 3 or -1.
|
||||
!matches!(address, 0 | 1 | 2 | 3 | usize::MAX)
|
||||
});
|
||||
|
||||
let _ = wglDeleteContext(context);
|
||||
|
||||
available
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_runs() {
|
||||
// The answer depends on the machine, so this only covers the probe running to completion.
|
||||
opengl_2_available();
|
||||
}
|
||||
210
patches/i-slint-backend-winit/renderer/skia.rs
vendored
Normal file
210
patches/i-slint-backend-winit/renderer/skia.rs
vendored
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::winit_compat::WindowSurfaceSizeExt;
|
||||
use crate::winitwindowadapter::physical_size_to_slint;
|
||||
use i_slint_core::graphics::RequestedGraphicsAPI;
|
||||
use i_slint_core::platform::PlatformError;
|
||||
use i_slint_core::renderer::DrawOutcome;
|
||||
use i_slint_renderer_skia::SkiaRenderer;
|
||||
|
||||
pub struct WinitSkiaRenderer {
|
||||
renderer: SkiaRenderer,
|
||||
requested_graphics_api: Option<RequestedGraphicsAPI>,
|
||||
}
|
||||
|
||||
impl WinitSkiaRenderer {
|
||||
pub fn new_suspended(
|
||||
shared_backend_data: &Rc<crate::SharedBackendData>,
|
||||
) -> Result<Box<dyn super::WinitCompatibleRenderer>, PlatformError> {
|
||||
Ok(Box::new(Self {
|
||||
renderer: SkiaRenderer::default(&shared_backend_data.skia_context),
|
||||
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "android"))]
|
||||
pub fn new_software_suspended(
|
||||
shared_backend_data: &Rc<crate::SharedBackendData>,
|
||||
) -> Result<Box<dyn super::WinitCompatibleRenderer>, PlatformError> {
|
||||
Ok(Box::new(Self {
|
||||
renderer: SkiaRenderer::default_software(&shared_backend_data.skia_context),
|
||||
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(not(ios_and_friends))]
|
||||
pub fn new_opengl_suspended(
|
||||
shared_backend_data: &Rc<crate::SharedBackendData>,
|
||||
) -> Result<Box<dyn super::WinitCompatibleRenderer>, PlatformError> {
|
||||
Ok(Box::new(Self {
|
||||
renderer: SkiaRenderer::default_opengl(&shared_backend_data.skia_context),
|
||||
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(target_vendor = "apple")]
|
||||
pub fn new_metal_suspended(
|
||||
shared_backend_data: &Rc<crate::SharedBackendData>,
|
||||
) -> Result<Box<dyn super::WinitCompatibleRenderer>, PlatformError> {
|
||||
Ok(Box::new(Self {
|
||||
renderer: SkiaRenderer::default_metal(&shared_backend_data.skia_context),
|
||||
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(supports_vulkan)]
|
||||
pub fn new_vulkan_suspended(
|
||||
shared_backend_data: &Rc<crate::SharedBackendData>,
|
||||
) -> Result<Box<dyn super::WinitCompatibleRenderer>, PlatformError> {
|
||||
Ok(Box::new(Self {
|
||||
renderer: SkiaRenderer::default_vulkan(&shared_backend_data.skia_context),
|
||||
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(target_family = "windows")]
|
||||
pub fn new_direct3d_suspended(
|
||||
shared_backend_data: &Rc<crate::SharedBackendData>,
|
||||
) -> Result<Box<dyn super::WinitCompatibleRenderer>, PlatformError> {
|
||||
Ok(Box::new(Self {
|
||||
renderer: SkiaRenderer::default_direct3d(&shared_backend_data.skia_context),
|
||||
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable-wgpu-29")]
|
||||
pub fn new_wgpu_29_suspended(
|
||||
shared_backend_data: &Rc<crate::SharedBackendData>,
|
||||
) -> Result<Box<dyn super::WinitCompatibleRenderer>, PlatformError> {
|
||||
Ok(Box::new(Self {
|
||||
renderer: SkiaRenderer::default_wgpu_29(&shared_backend_data.skia_context),
|
||||
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
// skia depends on default features which includes wgpu_30, so this is always available
|
||||
pub fn new_wgpu_30_suspended(
|
||||
shared_backend_data: &Rc<crate::SharedBackendData>,
|
||||
) -> Result<Box<dyn super::WinitCompatibleRenderer>, PlatformError> {
|
||||
Ok(Box::new(Self {
|
||||
renderer: SkiaRenderer::default_wgpu_30(&shared_backend_data.skia_context),
|
||||
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn factory_for_graphics_api(
|
||||
requested_graphics_api: Option<&RequestedGraphicsAPI>,
|
||||
) -> Result<
|
||||
fn(
|
||||
&Rc<crate::SharedBackendData>,
|
||||
) -> Result<Box<dyn crate::WinitCompatibleRenderer>, PlatformError>,
|
||||
PlatformError,
|
||||
> {
|
||||
match requested_graphics_api {
|
||||
Some(api) => {
|
||||
match api {
|
||||
RequestedGraphicsAPI::OpenGL(_) => {
|
||||
#[cfg(not(ios_and_friends))]
|
||||
return Ok(Self::new_opengl_suspended);
|
||||
#[cfg(ios_and_friends)]
|
||||
return Err(format!(
|
||||
"OpenGL rendering requested but this is not supported on iOS"
|
||||
)
|
||||
.into());
|
||||
}
|
||||
RequestedGraphicsAPI::Metal => {
|
||||
#[cfg(target_vendor = "apple")]
|
||||
return Ok(Self::new_metal_suspended);
|
||||
#[cfg(not(target_vendor = "apple"))]
|
||||
return Err("Metal rendering requested but this is only supported on Apple platforms".to_string().into());
|
||||
}
|
||||
RequestedGraphicsAPI::Vulkan => {
|
||||
#[cfg(supports_vulkan)]
|
||||
return Ok(Self::new_vulkan_suspended);
|
||||
#[cfg(not(supports_vulkan))]
|
||||
return Err(
|
||||
"Vulkan rendering requested but renderer-skia-vulkan is not enabled"
|
||||
.to_string()
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
RequestedGraphicsAPI::Direct3D => {
|
||||
#[cfg(target_family = "windows")]
|
||||
return Ok(Self::new_direct3d_suspended);
|
||||
#[cfg(not(target_family = "windows"))]
|
||||
return Err(
|
||||
"Direct3D rendering requested but this is only supported on Windows"
|
||||
.to_string()
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
#[cfg(feature = "unstable-wgpu-29")]
|
||||
RequestedGraphicsAPI::WGPU29(..) => Ok(Self::new_wgpu_29_suspended),
|
||||
#[cfg(feature = "unstable-wgpu-30")]
|
||||
RequestedGraphicsAPI::WGPU30(..) => Ok(Self::new_wgpu_30_suspended),
|
||||
}
|
||||
}
|
||||
None => Ok(Self::new_suspended),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl super::WinitCompatibleRenderer for WinitSkiaRenderer {
|
||||
fn render(&self, _window: &i_slint_core::api::Window) -> Result<DrawOutcome, PlatformError> {
|
||||
self.renderer.render()
|
||||
}
|
||||
|
||||
fn as_core_renderer(&self) -> &dyn i_slint_core::renderer::Renderer {
|
||||
&self.renderer
|
||||
}
|
||||
|
||||
fn suspend(&self) -> Result<(), PlatformError> {
|
||||
self.renderer.set_pre_present_callback(None);
|
||||
self.renderer.suspend()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn set_transparent(&self, transparent: bool) -> Result<(), PlatformError> {
|
||||
self.renderer.set_transparent(transparent)
|
||||
}
|
||||
|
||||
fn resume(
|
||||
&self,
|
||||
active_event_loop: &winit::event_loop::ActiveEventLoop,
|
||||
window_attributes: winit::window::WindowAttributes,
|
||||
_window_adapter_weak: std::rc::Weak<crate::winitwindowadapter::WinitWindowAdapter>,
|
||||
) -> Result<Arc<winit::window::Window>, PlatformError> {
|
||||
let transparent = window_attributes.transparent;
|
||||
let winit_window = Arc::new(active_event_loop.create_window(window_attributes).map_err(
|
||||
|winit_os_error| {
|
||||
PlatformError::from(format!(
|
||||
"Error creating native window for Skia rendering: {}",
|
||||
winit_os_error
|
||||
))
|
||||
},
|
||||
)?);
|
||||
|
||||
let size = winit_window.surface_size();
|
||||
|
||||
self.renderer.set_window_handle(
|
||||
winit_window.clone(),
|
||||
winit_window.clone(),
|
||||
physical_size_to_slint(&size),
|
||||
self.requested_graphics_api.clone(),
|
||||
transparent,
|
||||
)?;
|
||||
|
||||
self.renderer.set_pre_present_callback(Some(Box::new({
|
||||
let winit_window = winit_window.clone();
|
||||
move || {
|
||||
winit_window.pre_present_notify();
|
||||
}
|
||||
})));
|
||||
|
||||
Ok(winit_window)
|
||||
}
|
||||
}
|
||||
214
patches/i-slint-backend-winit/renderer/sw.rs
vendored
Normal file
214
patches/i-slint-backend-winit/renderer/sw.rs
vendored
Normal file
|
|
@ -0,0 +1,214 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
//! Delegate the rendering to the [`i_slint_renderer_software::SoftwareRenderer`]
|
||||
|
||||
use core::num::NonZeroU32;
|
||||
use core::ops::DerefMut;
|
||||
use i_slint_core::graphics::Rgb8Pixel;
|
||||
use i_slint_core::platform::PlatformError;
|
||||
use i_slint_core::renderer::DrawOutcome;
|
||||
pub use i_slint_renderer_software::SoftwareRenderer;
|
||||
use i_slint_renderer_software::{PremultipliedRgbaColor, RepaintBufferType, TargetPixel};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use winit::event_loop::ActiveEventLoop;
|
||||
|
||||
use super::WinitCompatibleRenderer;
|
||||
|
||||
pub struct WinitSoftwareRenderer {
|
||||
renderer: SoftwareRenderer,
|
||||
_context: RefCell<Option<softbuffer::Context<Arc<winit::window::Window>>>>,
|
||||
surface: RefCell<
|
||||
Option<softbuffer::Surface<Arc<winit::window::Window>, Arc<winit::window::Window>>>,
|
||||
>,
|
||||
}
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct SoftBufferPixel(pub u32);
|
||||
|
||||
impl From<SoftBufferPixel> for PremultipliedRgbaColor {
|
||||
#[inline]
|
||||
fn from(pixel: SoftBufferPixel) -> Self {
|
||||
let v = pixel.0;
|
||||
PremultipliedRgbaColor {
|
||||
red: (v >> 16) as u8,
|
||||
green: (v >> 8) as u8,
|
||||
blue: v as u8,
|
||||
alpha: (v >> 24) as u8,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PremultipliedRgbaColor> for SoftBufferPixel {
|
||||
#[inline]
|
||||
fn from(pixel: PremultipliedRgbaColor) -> Self {
|
||||
Self(
|
||||
(pixel.alpha as u32) << 24
|
||||
| ((pixel.red as u32) << 16)
|
||||
| ((pixel.green as u32) << 8)
|
||||
| (pixel.blue as u32),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl TargetPixel for SoftBufferPixel {
|
||||
fn blend(&mut self, color: PremultipliedRgbaColor) {
|
||||
let mut x = PremultipliedRgbaColor::from(*self);
|
||||
x.blend(color);
|
||||
*self = x.into();
|
||||
}
|
||||
|
||||
fn from_rgb(r: u8, g: u8, b: u8) -> Self {
|
||||
Self(0xff000000 | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32))
|
||||
}
|
||||
|
||||
fn background() -> Self {
|
||||
Self(0)
|
||||
}
|
||||
}
|
||||
|
||||
impl WinitSoftwareRenderer {
|
||||
pub fn new_suspended(
|
||||
_shared_backend_data: &Rc<crate::SharedBackendData>,
|
||||
) -> Result<Box<dyn WinitCompatibleRenderer>, PlatformError> {
|
||||
Ok(Box::new(Self {
|
||||
renderer: SoftwareRenderer::new(),
|
||||
_context: RefCell::new(None),
|
||||
surface: RefCell::new(None),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl super::WinitCompatibleRenderer for WinitSoftwareRenderer {
|
||||
fn render(&self, window: &i_slint_core::api::Window) -> Result<DrawOutcome, PlatformError> {
|
||||
let size = window.size();
|
||||
|
||||
let Some((width, height)) = size.width.try_into().ok().zip(size.height.try_into().ok())
|
||||
else {
|
||||
// Nothing to render
|
||||
return Ok(DrawOutcome::Success);
|
||||
};
|
||||
|
||||
let mut borrowed_surface = self.surface.borrow_mut();
|
||||
let Some(surface) = borrowed_surface.as_mut() else {
|
||||
// Nothing to render
|
||||
return Ok(DrawOutcome::Success);
|
||||
};
|
||||
|
||||
let winit_window = surface.window().clone();
|
||||
|
||||
surface
|
||||
.resize(width, height)
|
||||
.map_err(|e| format!("Error resizing softbuffer surface: {e}"))?;
|
||||
|
||||
let mut target_buffer = surface
|
||||
.buffer_mut()
|
||||
.map_err(|e| format!("Error retrieving softbuffer rendering buffer: {e}"))?;
|
||||
|
||||
let age = target_buffer.age();
|
||||
self.renderer.set_repaint_buffer_type(match age {
|
||||
1 => RepaintBufferType::ReusedBuffer,
|
||||
2 => RepaintBufferType::SwappedBuffers,
|
||||
_ => RepaintBufferType::NewBuffer,
|
||||
});
|
||||
|
||||
let region = if std::env::var_os("SLINT_LINE_BY_LINE").is_none() {
|
||||
let buffer: &mut [SoftBufferPixel] =
|
||||
bytemuck::cast_slice_mut(target_buffer.deref_mut());
|
||||
self.renderer.render(buffer, width.get() as usize)
|
||||
} else {
|
||||
// SLINT_LINE_BY_LINE is set and this is a debug mode where we also render in a Rgb565Pixel
|
||||
struct FrameBuffer<'a> {
|
||||
buffer: &'a mut [u32],
|
||||
line: Vec<i_slint_renderer_software::Rgb565Pixel>,
|
||||
}
|
||||
impl i_slint_renderer_software::LineBufferProvider for FrameBuffer<'_> {
|
||||
type TargetPixel = i_slint_renderer_software::Rgb565Pixel;
|
||||
fn process_line(
|
||||
&mut self,
|
||||
line: usize,
|
||||
range: core::ops::Range<usize>,
|
||||
render_fn: impl FnOnce(&mut [Self::TargetPixel]),
|
||||
) {
|
||||
let line_begin = line * self.line.len();
|
||||
let sub = &mut self.line[..range.len()];
|
||||
render_fn(sub);
|
||||
for (dst, src) in self.buffer[line_begin..][range].iter_mut().zip(sub) {
|
||||
let p = Rgb8Pixel::from(*src);
|
||||
*dst =
|
||||
0xff000000 | ((p.r as u32) << 16) | ((p.g as u32) << 8) | (p.b as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.renderer.render_by_line(FrameBuffer {
|
||||
buffer: &mut target_buffer,
|
||||
line: vec![Default::default(); width.get() as usize],
|
||||
})
|
||||
};
|
||||
|
||||
let damage = region
|
||||
.iter()
|
||||
.filter_map(|(pos, size)| {
|
||||
Some(softbuffer::Rect {
|
||||
x: pos.x as u32,
|
||||
y: pos.y as u32,
|
||||
width: NonZeroU32::new(size.width)?,
|
||||
height: NonZeroU32::new(size.height)?,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if !damage.is_empty() {
|
||||
winit_window.pre_present_notify();
|
||||
target_buffer
|
||||
.present_with_damage(&damage)
|
||||
.map_err(|e| format!("Error presenting softbuffer buffer: {e}"))?;
|
||||
}
|
||||
Ok(DrawOutcome::Success)
|
||||
}
|
||||
|
||||
fn as_core_renderer(&self) -> &dyn i_slint_core::renderer::Renderer {
|
||||
&self.renderer
|
||||
}
|
||||
|
||||
fn occluded(&self, _: bool) {
|
||||
// On X11 and Windows, the buffer is completely cleared when the window is hidden
|
||||
// and the buffer age doesn't respect that, so clean the partial rendering cache
|
||||
self.renderer.set_repaint_buffer_type(RepaintBufferType::NewBuffer);
|
||||
}
|
||||
|
||||
fn resume(
|
||||
&self,
|
||||
active_event_loop: &ActiveEventLoop,
|
||||
window_attributes: winit::window::WindowAttributes,
|
||||
_window_adapter_weak: std::rc::Weak<crate::winitwindowadapter::WinitWindowAdapter>,
|
||||
) -> Result<Arc<winit::window::Window>, PlatformError> {
|
||||
let winit_window =
|
||||
active_event_loop.create_window(window_attributes).map_err(|winit_os_error| {
|
||||
PlatformError::from(format!(
|
||||
"Error creating native window for software rendering: {winit_os_error}"
|
||||
))
|
||||
})?;
|
||||
let winit_window = Arc::new(winit_window);
|
||||
|
||||
let context = softbuffer::Context::new(winit_window.clone())
|
||||
.map_err(|e| format!("Error creating softbuffer context: {e}"))?;
|
||||
|
||||
let surface = softbuffer::Surface::new(&context, winit_window.clone()).map_err(
|
||||
|softbuffer_error| format!("Error creating softbuffer surface: {softbuffer_error}"),
|
||||
)?;
|
||||
|
||||
*self._context.borrow_mut() = Some(context);
|
||||
*self.surface.borrow_mut() = Some(surface);
|
||||
|
||||
Ok(winit_window)
|
||||
}
|
||||
|
||||
fn suspend(&self) -> Result<(), PlatformError> {
|
||||
drop(self.surface.borrow_mut().take());
|
||||
drop(self._context.borrow_mut().take());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
96
patches/i-slint-backend-winit/renderer/vello.rs
vendored
Normal file
96
patches/i-slint-backend-winit/renderer/vello.rs
vendored
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
//! Delegate the rendering to vello, through
|
||||
//! [`i_slint_renderer_anyrender::VelloRenderer`].
|
||||
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use i_slint_core::graphics::RequestedGraphicsAPI;
|
||||
use i_slint_core::platform::PlatformError;
|
||||
use i_slint_core::renderer::{DrawOutcome, Renderer};
|
||||
use i_slint_renderer_anyrender::VelloRenderer;
|
||||
use winit::event_loop::ActiveEventLoop;
|
||||
|
||||
use super::WinitCompatibleRenderer;
|
||||
|
||||
pub struct WinitVelloRenderer {
|
||||
renderer: VelloRenderer,
|
||||
requested_graphics_api: Option<RequestedGraphicsAPI>,
|
||||
}
|
||||
|
||||
impl WinitVelloRenderer {
|
||||
pub fn new_suspended(
|
||||
shared_backend_data: &Rc<crate::SharedBackendData>,
|
||||
) -> Result<Box<dyn WinitCompatibleRenderer>, PlatformError> {
|
||||
if !i_slint_core::graphics::wgpu_29::any_wgpu29_adapters_with_gpu(
|
||||
shared_backend_data.requested_graphics_api.clone(),
|
||||
i_slint_core::graphics::wgpu_29::default_backends_to_avoid(),
|
||||
) {
|
||||
return Err(PlatformError::from("WGPU: No GPU adapters found"));
|
||||
}
|
||||
Ok(Box::new(Self {
|
||||
renderer: VelloRenderer::new_vello(),
|
||||
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl WinitCompatibleRenderer for WinitVelloRenderer {
|
||||
fn render(&self, _window: &i_slint_core::api::Window) -> Result<DrawOutcome, PlatformError> {
|
||||
self.renderer.render()
|
||||
}
|
||||
|
||||
fn as_core_renderer(&self) -> &dyn Renderer {
|
||||
&self.renderer
|
||||
}
|
||||
|
||||
fn suspend(&self) -> Result<(), PlatformError> {
|
||||
// Also releases the winit window the callback holds on to.
|
||||
self.renderer.set_pre_present_callback(None);
|
||||
self.renderer.suspend_window();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn set_transparent(&self, transparent: bool) -> Result<(), PlatformError> {
|
||||
self.renderer.set_transparent(transparent);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn resume(
|
||||
&self,
|
||||
active_event_loop: &ActiveEventLoop,
|
||||
window_attributes: winit::window::WindowAttributes,
|
||||
_window_adapter_weak: std::rc::Weak<crate::winitwindowadapter::WinitWindowAdapter>,
|
||||
) -> Result<Arc<winit::window::Window>, PlatformError> {
|
||||
let transparent = window_attributes.transparent;
|
||||
|
||||
let winit_window = Arc::new(active_event_loop.create_window(window_attributes).map_err(
|
||||
|winit_os_error| {
|
||||
PlatformError::from(format!(
|
||||
"Error creating native window for vello rendering: {winit_os_error}"
|
||||
))
|
||||
},
|
||||
)?);
|
||||
|
||||
let size = winit_window.inner_size();
|
||||
self.renderer.resume_window(
|
||||
winit_window.clone(),
|
||||
size.width.max(1),
|
||||
size.height.max(1),
|
||||
transparent,
|
||||
self.requested_graphics_api.clone(),
|
||||
)?;
|
||||
|
||||
self.renderer.set_pre_present_callback(Some(Box::new({
|
||||
let winit_window = winit_window.clone();
|
||||
move || {
|
||||
winit_window.pre_present_notify();
|
||||
}
|
||||
})));
|
||||
|
||||
Ok(winit_window)
|
||||
}
|
||||
}
|
||||
81
patches/i-slint-backend-winit/tests/hide_from_window_event.rs
vendored
Normal file
81
patches/i-slint-backend-winit/tests/hide_from_window_event.rs
vendored
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
//! Hiding a window from one of its own event handlers must not report that the window
|
||||
//! is kept alive: the event loop holds a reference to it while dispatching the event.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
use slint::winit_030::{CustomApplicationHandler, EventResult, winit};
|
||||
|
||||
/// Part of the message the backend logs about a window kept alive after being hidden.
|
||||
const REPORT: &str = "references to it still exist";
|
||||
|
||||
slint::slint! {
|
||||
export component App inherits Window {
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
}
|
||||
}
|
||||
|
||||
/// Hides the window from a winit event, like an application does on a click on the close button.
|
||||
struct HideOnRedraw {
|
||||
hidden: Rc<Cell<bool>>,
|
||||
}
|
||||
|
||||
impl CustomApplicationHandler for HideOnRedraw {
|
||||
fn window_event(
|
||||
&mut self,
|
||||
_event_loop: &winit::event_loop::ActiveEventLoop,
|
||||
_window_id: winit::window::WindowId,
|
||||
_winit_window: Option<&winit::window::Window>,
|
||||
slint_window: Option<&slint::Window>,
|
||||
event: &winit::event::WindowEvent,
|
||||
) -> EventResult {
|
||||
// Every platform delivers a redraw for a window that was just shown.
|
||||
if !self.hidden.get()
|
||||
&& matches!(event, winit::event::WindowEvent::RedrawRequested)
|
||||
&& let Some(slint_window) = slint_window
|
||||
{
|
||||
self.hidden.set(true);
|
||||
slint_window.hide().unwrap();
|
||||
}
|
||||
EventResult::Propagate
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Only Wayland destroys the window when it is hidden, and only then is there
|
||||
// something that could be kept alive. Take that path on every platform.
|
||||
unsafe { std::env::set_var("SLINT_DESTROY_WINDOW_ON_HIDE", "1") };
|
||||
|
||||
let hidden = Rc::new(Cell::new(false));
|
||||
slint::BackendSelector::new()
|
||||
.backend_name("winit".into())
|
||||
.with_winit_custom_application_handler(HideOnRedraw { hidden: hidden.clone() })
|
||||
.select()
|
||||
.unwrap();
|
||||
|
||||
let messages = Rc::new(RefCell::new(Vec::new()));
|
||||
let collect = messages.clone();
|
||||
i_slint_core::with_global_context(
|
||||
|| unreachable!("the backend selector set the platform"),
|
||||
|ctx| {
|
||||
ctx.set_log_message_handler(Some(Box::new(move |message| {
|
||||
collect.borrow_mut().push(message.message_arguments().to_string());
|
||||
})))
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let app = App::new().unwrap();
|
||||
app.show().unwrap();
|
||||
// The window is the only one, so the event loop returns once it is hidden.
|
||||
slint::run_event_loop().unwrap();
|
||||
|
||||
assert!(hidden.get(), "the window was never hidden");
|
||||
let reports: Vec<_> =
|
||||
messages.take().into_iter().filter(|message| message.contains(REPORT)).collect();
|
||||
assert!(reports.is_empty(), "the window was reported as kept alive: {reports:?}");
|
||||
}
|
||||
63
patches/i-slint-backend-winit/tests/hide_with_external_reference.rs
vendored
Normal file
63
patches/i-slint-backend-winit/tests/hide_with_external_reference.rs
vendored
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
//! An application that keeps the winit window of a hidden window alive is told about it.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use slint::winit_030::WinitWindowAccessor;
|
||||
|
||||
/// Part of the message the backend logs about a window kept alive after being hidden.
|
||||
const REPORT: &str = "references to it still exist";
|
||||
|
||||
slint::slint! {
|
||||
export component App inherits Window {
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Only Wayland destroys the window when it is hidden, and only then is there
|
||||
// something that could be kept alive. Take that path on every platform.
|
||||
unsafe { std::env::set_var("SLINT_DESTROY_WINDOW_ON_HIDE", "1") };
|
||||
|
||||
slint::BackendSelector::new().backend_name("winit".into()).select().unwrap();
|
||||
|
||||
let messages = Rc::new(RefCell::new(Vec::new()));
|
||||
let collect = messages.clone();
|
||||
i_slint_core::with_global_context(
|
||||
|| unreachable!("the backend selector set the platform"),
|
||||
|ctx| {
|
||||
ctx.set_log_message_handler(Some(Box::new(move |message| {
|
||||
collect.borrow_mut().push(message.message_arguments().to_string());
|
||||
})))
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let reported = messages.clone();
|
||||
slint::spawn_local(async move {
|
||||
let app = App::new().unwrap();
|
||||
app.show().unwrap();
|
||||
let kept_alive = app.window().winit_window().await.unwrap();
|
||||
|
||||
app.window().hide().unwrap();
|
||||
|
||||
// The report comes once the event loop is done with what hid the window, so read it
|
||||
// on the next iteration.
|
||||
slint::Timer::single_shot(std::time::Duration::default(), move || {
|
||||
let reports: Vec<_> =
|
||||
reported.take().into_iter().filter(|message| message.contains(REPORT)).collect();
|
||||
assert_eq!(reports.len(), 1, "expected one report, got {reports:?}");
|
||||
|
||||
// Let go of the window while the event loop is still there to destroy it.
|
||||
drop(kept_alive);
|
||||
slint::quit_event_loop().unwrap();
|
||||
});
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
slint::run_event_loop_until_quit().unwrap();
|
||||
}
|
||||
38
patches/i-slint-backend-winit/tests/menubar_borrow.rs
vendored
Normal file
38
patches/i-slint-backend-winit/tests/menubar_borrow.rs
vendored
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
fn main() {
|
||||
slint::slint! {
|
||||
import { Palette } from "std-widgets.slint";
|
||||
export component App inherits Window {
|
||||
property <bool> dark-mode: Palette.color-scheme == ColorScheme.dark;
|
||||
MenuBar {
|
||||
Menu {
|
||||
title: @tr("Settings");
|
||||
MenuItem {
|
||||
title: @tr("Toggle dark mode");
|
||||
checkable: true;
|
||||
checked: { Palette.color-scheme == ColorScheme.dark } // Result in panic "RefCell already mutably borrowed"
|
||||
activated => {
|
||||
Palette.color-scheme = root.dark-mode ? ColorScheme.light : ColorScheme.dark;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
use slint::winit_030::WinitWindowAccessor;
|
||||
slint::BackendSelector::new().backend_name("winit".into()).select().unwrap();
|
||||
slint::spawn_local(async move {
|
||||
let app = App::new().unwrap();
|
||||
let slint_window = app.window();
|
||||
|
||||
app.show().unwrap();
|
||||
let result = slint_window.winit_window().await;
|
||||
assert!(result.is_ok(), "Failed to get winit window: {:?}", result.err());
|
||||
slint::quit_event_loop().unwrap();
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
slint::run_event_loop().unwrap();
|
||||
}
|
||||
109
patches/i-slint-backend-winit/touch_finger_id.rs
vendored
Normal file
109
patches/i-slint-backend-winit/touch_finger_id.rs
vendored
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
//! Maps winit touch ids to small stable i32 finger ids.
|
||||
//!
|
||||
//! winit's touch id doesn't fit an i32 on every platform.
|
||||
//! Native iOS stores a `UITouch` pointer address in it.
|
||||
//! The web backend sign-extends Safari's negative `PointerEvent.pointerId`,
|
||||
//! which lands far outside i32 range even though the id itself would fit.
|
||||
//!
|
||||
//! The id is also only unique within its device, so the key includes the
|
||||
//! device the touch came from.
|
||||
|
||||
/// A winit touch, identified by its device and the id winit gave it there.
|
||||
pub(crate) type TouchId = (winit::event::DeviceId, u64);
|
||||
|
||||
pub(crate) struct TouchFingerIdAllocator<Id = TouchId> {
|
||||
/// Index in this vector = the allocated finger id; entry = the touch
|
||||
/// currently occupying that slot.
|
||||
slots: Vec<Option<Id>>,
|
||||
}
|
||||
|
||||
impl<Id> Default for TouchFingerIdAllocator<Id> {
|
||||
fn default() -> Self {
|
||||
Self { slots: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<Id: Copy + PartialEq> TouchFingerIdAllocator<Id> {
|
||||
/// Returns the finger id for `touch`, claiming the lowest free slot for touches not seen yet.
|
||||
/// The slots grow with the number of fingers down at once, so no touch is dropped.
|
||||
pub(crate) fn id_for(&mut self, touch: Id) -> i32 {
|
||||
let index = self
|
||||
.slot_of(touch)
|
||||
.or_else(|| self.slots.iter().position(Option::is_none))
|
||||
.unwrap_or_else(|| {
|
||||
self.slots.push(None);
|
||||
self.slots.len() - 1
|
||||
});
|
||||
self.slots[index] = Some(touch);
|
||||
index as i32
|
||||
}
|
||||
|
||||
pub(crate) fn take(&mut self, touch: Id) -> Option<i32> {
|
||||
let index = self.slot_of(touch)?;
|
||||
self.slots[index] = None;
|
||||
Some(index as i32)
|
||||
}
|
||||
|
||||
fn slot_of(&self, touch: Id) -> Option<usize> {
|
||||
self.slots.iter().position(|slot| *slot == Some(touch))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::TouchFingerIdAllocator;
|
||||
|
||||
/// Stands in for `winit::event::DeviceId`, which only exposes one value to construct.
|
||||
type TestTouchId = (u8, u64);
|
||||
|
||||
fn allocator() -> TouchFingerIdAllocator<TestTouchId> {
|
||||
TouchFingerIdAllocator::default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allocates_and_frees_slots() {
|
||||
let mut alloc = allocator();
|
||||
assert_eq!(alloc.id_for((0, 11)), 0);
|
||||
assert_eq!(alloc.id_for((0, 22)), 1);
|
||||
// The same touch keeps its id for the rest of the gesture.
|
||||
assert_eq!(alloc.id_for((0, 11)), 0);
|
||||
assert_eq!(alloc.take((0, 11)), Some(0));
|
||||
// The freed slot is the lowest one, so the next touch reclaims it.
|
||||
assert_eq!(alloc.id_for((0, 33)), 0);
|
||||
assert_eq!(alloc.take((0, 99)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_ids_outside_i32_range() {
|
||||
let mut alloc = allocator();
|
||||
// Converting this id used to panic.
|
||||
let sign_extended = -440423654i64 as u64;
|
||||
assert!(i32::try_from(sign_extended).is_err());
|
||||
assert_eq!(alloc.id_for((0, sign_extended)), 0);
|
||||
assert_eq!(alloc.take((0, sign_extended)), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracks_more_fingers_than_one_pair_of_hands() {
|
||||
let mut alloc = allocator();
|
||||
for i in 0..20 {
|
||||
assert_eq!(alloc.id_for((0, 100 + i as u64)), i);
|
||||
}
|
||||
for i in 0..20 {
|
||||
assert_eq!(alloc.take((0, 100 + i as u64)), Some(i));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_touches_from_different_devices_apart() {
|
||||
let mut alloc = allocator();
|
||||
// Devices number their touches independently, so the same id is two fingers here.
|
||||
assert_eq!(alloc.id_for((0, 1)), 0);
|
||||
assert_eq!(alloc.id_for((1, 1)), 1);
|
||||
assert_eq!(alloc.take((0, 1)), Some(0));
|
||||
assert_eq!(alloc.id_for((1, 1)), 1);
|
||||
}
|
||||
}
|
||||
356
patches/i-slint-backend-winit/wasm_input_helper.rs
vendored
Normal file
356
patches/i-slint-backend-winit/wasm_input_helper.rs
vendored
Normal file
|
|
@ -0,0 +1,356 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
// cSpell: ignore autocapitalize compositionend compositionupdate keyup
|
||||
//! Helper for wasm that adds a hidden `<input>` and process its events
|
||||
//!
|
||||
//! Without it, the key event are sent to the canvas and processed by winit.
|
||||
//! But this winit handling doesn't show the keyboard on mobile devices, and
|
||||
//! also has bugs as the modifiers are not reported the same way and we don't
|
||||
//! record them.
|
||||
//!
|
||||
//! This just interpret the keyup and keydown events. But this is not working
|
||||
//! on mobile either as we only get these for a bunch of non-printable key
|
||||
//! that do not interact with the composing input. For anything else we
|
||||
//! check that we get input event when no normal key are pressed, and we send
|
||||
//! that as text.
|
||||
//! Since the slint core lib doesn't support composition yet, when we get
|
||||
//! composition event, we just send that as key, and if the composition changes,
|
||||
//! we just simulate a few backspaces.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::{Rc, Weak};
|
||||
|
||||
use i_slint_core::SharedString;
|
||||
use i_slint_core::input::{InternalKeyEvent, KeyEvent, KeyEventType};
|
||||
use i_slint_core::platform::WindowEvent;
|
||||
use i_slint_core::window::{WindowAdapter, WindowInner};
|
||||
use wasm_bindgen::JsCast;
|
||||
use wasm_bindgen::closure::Closure;
|
||||
use wasm_bindgen::convert::FromWasmAbi;
|
||||
|
||||
pub struct WasmInputHelper {
|
||||
input: web_sys::HtmlInputElement,
|
||||
canvas: web_sys::HtmlCanvasElement,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct WasmInputState {
|
||||
/// If there was a "keydown" event received that is not part of a composition
|
||||
has_key_down: bool,
|
||||
}
|
||||
|
||||
impl WasmInputHelper {
|
||||
#[allow(unused)]
|
||||
pub fn new(
|
||||
window_adapter: Weak<dyn WindowAdapter>,
|
||||
canvas: web_sys::HtmlCanvasElement,
|
||||
) -> Self {
|
||||
let window = web_sys::window().unwrap();
|
||||
let input = window
|
||||
.document()
|
||||
.unwrap()
|
||||
.create_element("input")
|
||||
.unwrap()
|
||||
.dyn_into::<web_sys::HtmlInputElement>()
|
||||
.unwrap();
|
||||
let style = input.style();
|
||||
style.set_property("z-index", "-1").unwrap();
|
||||
style.set_property("position", "absolute").unwrap();
|
||||
style.set_property("left", &format!("{}px", canvas.offset_left())).unwrap();
|
||||
style.set_property("top", &format!("{}px", canvas.offset_top())).unwrap();
|
||||
style.set_property("width", &format!("{}px", canvas.offset_width())).unwrap();
|
||||
style.set_property("height", &format!("{}px", canvas.offset_height())).unwrap();
|
||||
style.set_property("opacity", "0").unwrap(); // Hide the cursor on mobile Safari
|
||||
input.set_attribute("autocapitalize", "none").unwrap(); // Otherwise everything would be capitalized as we need to clear the input
|
||||
canvas.before_with_node_1(&input).unwrap();
|
||||
let mut h = Self { input, canvas: canvas.clone() };
|
||||
|
||||
// macos, or ipad with an attached keyboard, etc.
|
||||
let is_apple = i_slint_core::is_apple_platform();
|
||||
|
||||
let shared_state = Rc::new(RefCell::new(WasmInputState::default()));
|
||||
let win = window_adapter.clone();
|
||||
h.add_event_listener("paste", move |e: web_sys::ClipboardEvent| {
|
||||
if let Some(window_adapter) = win.upgrade() {
|
||||
let Some(text) = e.clipboard_data().and_then(|data| data.get_data("text").ok())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
e.prevent_default();
|
||||
let synthetic_clipboard_data = RefCell::new(text);
|
||||
CURRENT_WASM_CLIPBOARD_DATA.set(&synthetic_clipboard_data, || {
|
||||
if let Some(focus_item) = WindowInner::from_pub(&window_adapter.window())
|
||||
.focus_item
|
||||
.borrow()
|
||||
.upgrade()
|
||||
{
|
||||
if let Some(text_input) =
|
||||
focus_item.downcast::<i_slint_core::items::TextInput>()
|
||||
{
|
||||
text_input.as_pin_ref().paste(&window_adapter, &focus_item);
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
});
|
||||
let win = window_adapter.clone();
|
||||
h.add_event_listener("copy", move |e: web_sys::ClipboardEvent| {
|
||||
if let Some(window_adapter) = win.upgrade() {
|
||||
e.prevent_default();
|
||||
|
||||
let synthetic_clipboard_data = RefCell::new(String::default());
|
||||
CURRENT_WASM_CLIPBOARD_DATA.set(&synthetic_clipboard_data, || {
|
||||
if let Some(focus_item) = WindowInner::from_pub(&window_adapter.window())
|
||||
.focus_item
|
||||
.borrow()
|
||||
.upgrade()
|
||||
{
|
||||
if let Some(text_input) =
|
||||
focus_item.downcast::<i_slint_core::items::TextInput>()
|
||||
{
|
||||
let text = text_input.as_pin_ref().copy(&window_adapter, &focus_item);
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(data) = e.clipboard_data() {
|
||||
data.set_data("text", &synthetic_clipboard_data.into_inner()).ok();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let win = window_adapter.clone();
|
||||
h.add_event_listener("cut", move |e: web_sys::ClipboardEvent| {
|
||||
if let Some(window_adapter) = win.upgrade() {
|
||||
e.prevent_default();
|
||||
if let Some(focus_item) =
|
||||
WindowInner::from_pub(&window_adapter.window()).focus_item.borrow().upgrade()
|
||||
{
|
||||
if let Some(text_input) =
|
||||
focus_item.downcast::<i_slint_core::items::TextInput>()
|
||||
{
|
||||
let (anchor, cursor) =
|
||||
text_input.as_pin_ref().selection_anchor_and_cursor();
|
||||
if anchor == cursor {
|
||||
return;
|
||||
}
|
||||
let text = text_input.as_pin_ref().text();
|
||||
if let Some(data) = e.clipboard_data() {
|
||||
data.set_data("text", &text[anchor..cursor]).ok();
|
||||
}
|
||||
text_input.as_pin_ref().delete_selection(
|
||||
&window_adapter,
|
||||
&focus_item,
|
||||
i_slint_core::items::TextChangeNotify::TriggerCallbacks,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let win = window_adapter.clone();
|
||||
h.add_event_listener("blur", move |e: web_sys::FocusEvent| {
|
||||
// Make sure that the window gets marked as unfocused when the focus leaves the input
|
||||
if let Some(window_adapter) = win.upgrade() {
|
||||
let canvas_receiving_focus = e.related_target().is_some_and(|target| {
|
||||
// related_target is the element receiving focus, see https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent/relatedTarget
|
||||
target
|
||||
.dyn_ref::<web_sys::Node>()
|
||||
.is_some_and(|node| canvas.is_same_node(Some(node)))
|
||||
});
|
||||
// the correct thing to do to see what is focused (or more accurately, *going* to
|
||||
// be focused) during a blur event is to look at relatedTarget. Some old
|
||||
// browsers may not implement relatedTarget correctly, so this falls back to
|
||||
// .matches(), hoping that the browser focuses the target before dispatching
|
||||
// the blur event
|
||||
let canvas_already_focused = canvas.matches(":focus").unwrap_or(false);
|
||||
if !canvas_receiving_focus && !canvas_already_focused {
|
||||
window_adapter.window().dispatch_event(WindowEvent::WindowActiveChanged(false));
|
||||
}
|
||||
}
|
||||
});
|
||||
let win = window_adapter.clone();
|
||||
let shared_state2 = shared_state.clone();
|
||||
h.add_event_listener("keydown", move |e: web_sys::KeyboardEvent| {
|
||||
if let (Some(window_adapter), Some(mut text)) =
|
||||
(win.upgrade(), event_text(&e, is_apple))
|
||||
{
|
||||
// Same logic as in winit to prevent the default <https://github.com/rust-windowing/winit/blob/master/src/platform_impl/web/web_sys/canvas.rs#L202-L213>
|
||||
let event_key = &e.key();
|
||||
let is_key_string = event_key.len() == 1 || !event_key.is_ascii();
|
||||
let ctrl_key = if is_apple { e.meta_key() } else { e.ctrl_key() };
|
||||
let is_shortcut_modifiers =
|
||||
(ctrl_key || e.alt_key()) && !e.get_modifier_state("AltGr");
|
||||
if !is_key_string || is_shortcut_modifiers {
|
||||
// Also let copy/paste/cut through
|
||||
if !matches!(text.as_str(), "c" | "v" | "x") {
|
||||
e.prevent_default();
|
||||
}
|
||||
}
|
||||
|
||||
shared_state2.borrow_mut().has_key_down = true;
|
||||
let win_event = if e.repeat() {
|
||||
WindowEvent::KeyPressRepeated { text }
|
||||
} else {
|
||||
WindowEvent::KeyPressed { text }
|
||||
};
|
||||
window_adapter.window().dispatch_event(win_event);
|
||||
}
|
||||
});
|
||||
|
||||
let win = window_adapter.clone();
|
||||
let shared_state2 = shared_state.clone();
|
||||
h.add_event_listener("keyup", move |e: web_sys::KeyboardEvent| {
|
||||
if let (Some(window_adapter), Some(mut text)) =
|
||||
(win.upgrade(), event_text(&e, is_apple))
|
||||
{
|
||||
e.prevent_default();
|
||||
shared_state2.borrow_mut().has_key_down = false;
|
||||
window_adapter.window().dispatch_event(WindowEvent::KeyReleased { text });
|
||||
}
|
||||
});
|
||||
|
||||
let win = window_adapter.clone();
|
||||
let shared_state2 = shared_state.clone();
|
||||
let input = h.input.clone();
|
||||
h.add_event_listener("input", move |e: web_sys::InputEvent| {
|
||||
if let (Some(window_adapter), Some(data)) = (win.upgrade(), e.data()) {
|
||||
if !e.is_composing() && e.input_type() != "insertCompositionText" {
|
||||
if !shared_state2.borrow_mut().has_key_down {
|
||||
let text: SharedString = data.into();
|
||||
window_adapter
|
||||
.window()
|
||||
.dispatch_event(WindowEvent::KeyPressed { text: text.clone() });
|
||||
window_adapter.window().dispatch_event(WindowEvent::KeyReleased { text });
|
||||
shared_state2.borrow_mut().has_key_down = false;
|
||||
}
|
||||
input.set_value("");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let win = window_adapter.clone();
|
||||
let input = h.input.clone();
|
||||
h.add_event_listener("compositionend", move |e: web_sys::CompositionEvent| {
|
||||
if let (Some(window_adapter), Some(data)) = (win.upgrade(), e.data()) {
|
||||
let mut key_event = KeyEvent::default();
|
||||
key_event.text = data.into();
|
||||
|
||||
window_adapter.window().dispatch_event(WindowEvent::internal(InternalKeyEvent {
|
||||
key_event,
|
||||
event_type: KeyEventType::CommitComposition,
|
||||
..Default::default()
|
||||
}));
|
||||
input.set_value("");
|
||||
}
|
||||
});
|
||||
|
||||
let win = window_adapter.clone();
|
||||
h.add_event_listener("compositionupdate", move |e: web_sys::CompositionEvent| {
|
||||
if let (Some(window_adapter), Some(data)) = (win.upgrade(), e.data()) {
|
||||
window_adapter.window().dispatch_event(WindowEvent::internal(InternalKeyEvent {
|
||||
preedit_text: data.into(),
|
||||
event_type: KeyEventType::UpdateComposition,
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
});
|
||||
|
||||
h
|
||||
}
|
||||
|
||||
/// Returns whether the fake input element has focus
|
||||
pub fn has_focus(&self) -> bool {
|
||||
self.input.matches(":focus").unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn show(&self) {
|
||||
self.input.style().set_property("visibility", "visible").unwrap();
|
||||
self.input.focus().unwrap();
|
||||
}
|
||||
|
||||
pub fn hide(&self) {
|
||||
if self.has_focus() {
|
||||
self.canvas.focus().unwrap()
|
||||
}
|
||||
self.input.style().set_property("visibility", "hidden").unwrap();
|
||||
}
|
||||
|
||||
fn add_event_listener<Arg: FromWasmAbi + 'static>(
|
||||
&mut self,
|
||||
event: &str,
|
||||
closure: impl Fn(Arg) + 'static,
|
||||
) {
|
||||
let closure = move |arg: Arg| {
|
||||
closure(arg);
|
||||
// wake up event loop
|
||||
i_slint_core::api::invoke_from_event_loop(|| {}).ok();
|
||||
};
|
||||
let closure = Closure::wrap(Box::new(closure) as Box<dyn Fn(_)>);
|
||||
self.input
|
||||
.add_event_listener_with_callback(event, closure.as_ref().unchecked_ref())
|
||||
.unwrap();
|
||||
closure.forget();
|
||||
}
|
||||
}
|
||||
|
||||
fn event_text(e: &web_sys::KeyboardEvent, is_apple: bool) -> Option<SharedString> {
|
||||
if e.is_composing() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let key = e.key();
|
||||
|
||||
use i_slint_core::platform::Key;
|
||||
|
||||
macro_rules! check_non_printable_code {
|
||||
($($char:literal # $name:ident # $($shifted:ident)? $(=> $($_muda:ident)? # $($qt:ident)|* # $($_winit:ident $(($_pos:ident))?)|* # $($_xkb:ident)|* )? ;)*) => {
|
||||
match key.as_str() {
|
||||
"Tab" if e.shift_key() => return Some(Key::Backtab.into()),
|
||||
"Meta" if is_apple => return Some(Key::Control.into()),
|
||||
"Control" if is_apple => return Some(Key::Meta.into()),
|
||||
// Only emit a case for each special key (e.g. the ones that have any of the
|
||||
// qt/winit/xkb variants) to avoid emitting a lot of non-special keys.
|
||||
$($(stringify!($name) => {
|
||||
// phony let to make sure this only emits a match arm on special keys
|
||||
$(let _ = stringify!($qt);)*
|
||||
return Some($char.into());
|
||||
})?)*
|
||||
// Why did we diverge from DOM there?
|
||||
"ArrowLeft" => return Some(Key::LeftArrow.into()),
|
||||
"ArrowUp" => return Some(Key::UpArrow.into()),
|
||||
"ArrowRight" => return Some(Key::RightArrow.into()),
|
||||
"ArrowDown" => return Some(Key::DownArrow.into()),
|
||||
"Enter" => return Some(Key::Return.into()),
|
||||
_ => (),
|
||||
}
|
||||
};
|
||||
}
|
||||
i_slint_common::for_each_keys!(check_non_printable_code);
|
||||
|
||||
let mut chars = key.chars();
|
||||
match chars.next() {
|
||||
Some(first_char) if chars.next().is_none() => Some(first_char.into()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
scoped_tls_hkt::scoped_thread_local!(static CURRENT_WASM_CLIPBOARD_DATA : for<'a> &'a RefCell<String>);
|
||||
|
||||
pub(crate) fn set_clipboard_text(data: String, clipboard: i_slint_core::platform::Clipboard) {
|
||||
if CURRENT_WASM_CLIPBOARD_DATA.is_set()
|
||||
&& matches!(clipboard, i_slint_core::platform::Clipboard::DefaultClipboard)
|
||||
{
|
||||
CURRENT_WASM_CLIPBOARD_DATA.with(|current_data| *current_data.borrow_mut() = data)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn get_clipboard_text(clipboard: i_slint_core::platform::Clipboard) -> Option<String> {
|
||||
if CURRENT_WASM_CLIPBOARD_DATA.is_set()
|
||||
&& matches!(clipboard, i_slint_core::platform::Clipboard::DefaultClipboard)
|
||||
{
|
||||
Some(CURRENT_WASM_CLIPBOARD_DATA.with(|current_data| current_data.borrow().clone()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
19
patches/i-slint-backend-winit/winit_compat.rs
vendored
Normal file
19
patches/i-slint-backend-winit/winit_compat.rs
vendored
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
//! Polyfill for `winit::window::Window::surface_size()`, which becomes a built-in method in
|
||||
//! winit 0.31.
|
||||
|
||||
pub(crate) trait WindowSurfaceSizeExt {
|
||||
fn surface_size(&self) -> winit::dpi::PhysicalSize<u32>;
|
||||
}
|
||||
|
||||
impl WindowSurfaceSizeExt for winit::window::Window {
|
||||
/// The physical size of the rendering surface backing a winit window.
|
||||
fn surface_size(&self) -> winit::dpi::PhysicalSize<u32> {
|
||||
// winit 0.30's iOS `inner_size()` returns the safe-area frame but the `CAMetalLayer` fills the whole
|
||||
// window, so the render surface must match `outer_size()`. That's also what `WindowEvent::Resized`
|
||||
// delivers.
|
||||
if cfg!(target_os = "ios") { self.outer_size() } else { self.inner_size() }
|
||||
}
|
||||
}
|
||||
2419
patches/i-slint-backend-winit/winitwindowadapter.rs
vendored
Normal file
2419
patches/i-slint-backend-winit/winitwindowadapter.rs
vendored
Normal file
File diff suppressed because it is too large
Load diff
296
patches/i-slint-backend-winit/xdg_desktop_settings.rs
vendored
Normal file
296
patches/i-slint-backend-winit/xdg_desktop_settings.rs
vendored
Normal file
|
|
@ -0,0 +1,296 @@
|
|||
// Copyright © SixtyFPS GmbH <info@slint.dev>
|
||||
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::rc::{Rc, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
use i_slint_core::SlintContextWeak;
|
||||
use i_slint_core::graphics::Color;
|
||||
use i_slint_core::items::ColorScheme;
|
||||
use i_slint_core::lengths::LogicalLength;
|
||||
|
||||
use crate::SharedBackendData;
|
||||
|
||||
/// How long the first windows wait for the appearance query before mapping with
|
||||
/// defaults. Keep it above portal activation time; a missing portal fails fast.
|
||||
const APPEARANCE_QUERY_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
|
||||
/// Desktop settings read from the XDG portal: cursor blink and the one-time
|
||||
/// appearance query the first windows wait for. Updated by [`watch`].
|
||||
pub(crate) struct DesktopSettings {
|
||||
/// Whether the cursor blinks at all.
|
||||
cursor_blink_enabled: Cell<bool>,
|
||||
/// The cursor blink period, used when blinking is enabled.
|
||||
cursor_blink_time: Cell<Duration>,
|
||||
/// True while the appearance query is in flight; the backend holds the first
|
||||
/// windows in `inactive_windows` until it clears, to avoid a default flash.
|
||||
appearance_pending: Cell<bool>,
|
||||
}
|
||||
|
||||
impl DesktopSettings {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
cursor_blink_enabled: Cell::new(true),
|
||||
cursor_blink_time: Cell::new(crate::DEFAULT_CURSOR_FLASH_CYCLE),
|
||||
appearance_pending: Cell::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// The cursor blink period, or zero when blinking is disabled.
|
||||
pub(crate) fn cursor_flash_cycle(&self) -> Duration {
|
||||
if self.cursor_blink_enabled.get() { self.cursor_blink_time.get() } else { Duration::ZERO }
|
||||
}
|
||||
|
||||
/// Whether the first windows must still wait for the appearance query.
|
||||
pub(crate) fn is_appearance_pending(&self) -> bool {
|
||||
self.appearance_pending.get()
|
||||
}
|
||||
}
|
||||
|
||||
const APPEARANCE: &str = "org.freedesktop.appearance";
|
||||
const GNOME_INTERFACE: &str = "org.gnome.desktop.interface";
|
||||
|
||||
/// Handles passed to a setting's `apply` function so it can push the parsed value
|
||||
/// into the runtime context or the backend.
|
||||
struct SettingsContext<'a> {
|
||||
ctx: &'a SlintContextWeak,
|
||||
shared: &'a Weak<SharedBackendData>,
|
||||
}
|
||||
|
||||
/// One desktop setting read from the portal. The initial read and the
|
||||
/// `SettingChanged` handler both call `apply`, so a new setting is one row.
|
||||
struct SettingDescriptor {
|
||||
namespace: &'static str,
|
||||
key: &'static str,
|
||||
apply: fn(zbus::wire::OwnedVariant, &SettingsContext),
|
||||
}
|
||||
|
||||
/// Every desktop setting Slint reacts to. Add a row here (and a small `apply_*`
|
||||
/// function) to support a new one.
|
||||
static SETTINGS: &[SettingDescriptor] = &[
|
||||
SettingDescriptor {
|
||||
namespace: APPEARANCE,
|
||||
key: "color-scheme",
|
||||
apply: apply_color_scheme_value,
|
||||
},
|
||||
SettingDescriptor { namespace: APPEARANCE, key: "accent-color", apply: apply_accent_value },
|
||||
SettingDescriptor { namespace: GNOME_INTERFACE, key: "font-name", apply: apply_font_value },
|
||||
SettingDescriptor {
|
||||
namespace: GNOME_INTERFACE,
|
||||
key: "cursor-blink",
|
||||
apply: apply_cursor_blink_value,
|
||||
},
|
||||
SettingDescriptor {
|
||||
namespace: GNOME_INTERFACE,
|
||||
key: "cursor-blink-time",
|
||||
apply: apply_cursor_blink_time_value,
|
||||
},
|
||||
];
|
||||
|
||||
/// Parses the trailing point size from a GNOME font description such as
|
||||
/// `"Helvetica 11"` or `"Sans Bold 10.5"`.
|
||||
fn parse_font_points(font_name: &str) -> Option<f32> {
|
||||
let last = font_name.split_whitespace().next_back()?;
|
||||
last.parse::<f32>().ok().filter(|p| p.is_finite() && *p > 0.0)
|
||||
}
|
||||
|
||||
fn xdg_color_scheme_to_slint(value: zbus::wire::OwnedVariant) -> ColorScheme {
|
||||
match value.downcast_ref::<u32>() {
|
||||
Ok(1) => ColorScheme::Dark,
|
||||
Ok(2) => ColorScheme::Light,
|
||||
_ => ColorScheme::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
fn xdg_accent_color_to_slint(value: zbus::wire::OwnedVariant) -> Option<Color> {
|
||||
// The accent-color setting returns a (ddd) tuple of RGB doubles in [0.0, 1.0]
|
||||
let (r, g, b) = value.downcast_ref::<(f64, f64, f64)>().ok()?;
|
||||
Some(Color::from_argb_f32(1.0, r as f32, g as f32, b as f32))
|
||||
}
|
||||
|
||||
/// Sets the color scheme on the context and pushes the matching winit theme to
|
||||
/// every mapped window so client-side decorations stay in sync.
|
||||
fn apply_color_scheme_value(value: zbus::wire::OwnedVariant, cx: &SettingsContext) {
|
||||
let scheme = xdg_color_scheme_to_slint(value);
|
||||
if let Some(ctx) = cx.ctx.upgrade() {
|
||||
ctx.set_color_scheme(scheme);
|
||||
}
|
||||
let Some(shared) = cx.shared.upgrade() else { return };
|
||||
let theme = match scheme {
|
||||
ColorScheme::Dark => Some(winit::window::Theme::Dark),
|
||||
ColorScheme::Light => Some(winit::window::Theme::Light),
|
||||
ColorScheme::Unknown => None,
|
||||
_ => None,
|
||||
};
|
||||
for adapter_weak in shared.active_windows.borrow().values() {
|
||||
if let Some(adapter) = adapter_weak.upgrade()
|
||||
&& let Some(winit_window) = adapter.winit_window()
|
||||
{
|
||||
winit_window.set_theme(theme);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_accent_value(value: zbus::wire::OwnedVariant, cx: &SettingsContext) {
|
||||
if let Some(color) = xdg_accent_color_to_slint(value)
|
||||
&& let Some(ctx) = cx.ctx.upgrade()
|
||||
{
|
||||
ctx.set_accent_color(color);
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_font_value(value: zbus::wire::OwnedVariant, cx: &SettingsContext) {
|
||||
if let Ok(name) = value.downcast_ref::<&str>()
|
||||
&& let Some(points) = parse_font_points(name)
|
||||
&& let Some(ctx) = cx.ctx.upgrade()
|
||||
{
|
||||
ctx.set_platform_default_font_size(Some(LogicalLength::new(points * 96.0 / 72.0)));
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_cursor_blink_value(value: zbus::wire::OwnedVariant, cx: &SettingsContext) {
|
||||
if let Ok(enabled) = value.downcast_ref::<bool>()
|
||||
&& let Some(shared) = cx.shared.upgrade()
|
||||
{
|
||||
shared.desktop_settings.cursor_blink_enabled.set(enabled);
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_cursor_blink_time_value(value: zbus::wire::OwnedVariant, cx: &SettingsContext) {
|
||||
if let Ok(ms) = value.downcast_ref::<i32>()
|
||||
&& ms > 0
|
||||
&& let Some(shared) = cx.shared.upgrade()
|
||||
{
|
||||
shared.desktop_settings.cursor_blink_time.set(Duration::from_millis(ms as u64));
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads every entry in [`SETTINGS`] concurrently and applies each result, so the
|
||||
/// whole batch costs roughly one round-trip instead of one per setting.
|
||||
async fn read_all_settings(settings_proxy: &zbus::Proxy<'_>, cx: &SettingsContext<'_>) {
|
||||
futures::future::join_all(SETTINGS.iter().map(|setting| async move {
|
||||
if let Ok(value) = read_setting(settings_proxy, setting).await {
|
||||
(setting.apply)(value, cx);
|
||||
}
|
||||
}))
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Reads one setting.
|
||||
/// Portals older than 1.15 (Ubuntu 22.04 and earlier) only implement the deprecated `Read`,
|
||||
/// whose extra variant wrapping `downcast_ref()` unwraps transparently.
|
||||
async fn read_setting(
|
||||
settings_proxy: &zbus::Proxy<'_>,
|
||||
setting: &SettingDescriptor,
|
||||
) -> zbus::Result<zbus::wire::OwnedVariant> {
|
||||
let args = (setting.namespace, setting.key);
|
||||
#[cfg_attr(slint_nightly_test, allow(non_exhaustive_omitted_patterns))]
|
||||
match settings_proxy.call("ReadOne", &args).await {
|
||||
Err(zbus::Error::MethodError(name, ..))
|
||||
if name.as_str() == "org.freedesktop.DBus.Error.UnknownMethod" =>
|
||||
{
|
||||
settings_proxy.call("Read", &args).await
|
||||
}
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears the pending flag so the backend creates and shows the first windows.
|
||||
fn finish_appearance_query(shared: &Weak<SharedBackendData>) {
|
||||
if let Some(shared) = shared.upgrade() {
|
||||
shared.desktop_settings.appearance_pending.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
async fn watch(
|
||||
shared_data_weak: &Weak<SharedBackendData>,
|
||||
ctx_weak: SlintContextWeak,
|
||||
) -> zbus::Result<()> {
|
||||
// Safety net: create the windows anyway if the portal never answers.
|
||||
// After the timer fires, the event loop returns to `about_to_wait`,
|
||||
// which then creates any pending inactive windows.
|
||||
{
|
||||
let shared_weak = shared_data_weak.clone();
|
||||
i_slint_core::timers::Timer::single_shot(APPEARANCE_QUERY_TIMEOUT, move || {
|
||||
finish_appearance_query(&shared_weak);
|
||||
});
|
||||
}
|
||||
|
||||
let connection = zbus::Connection::session().await?;
|
||||
let settings_proxy: zbus::Proxy = zbus::proxy::Builder::new(&connection)
|
||||
.interface("org.freedesktop.portal.Settings")
|
||||
.path("/org/freedesktop/portal/desktop")
|
||||
.destination("org.freedesktop.portal.Desktop")
|
||||
.build()
|
||||
.await?;
|
||||
|
||||
let cx = SettingsContext { ctx: &ctx_weak, shared: shared_data_weak };
|
||||
|
||||
// Subscribe before the initial read so no change is missed in the gap between them.
|
||||
use futures::stream::StreamExt;
|
||||
let mut settings_stream = settings_proxy.receive_signal("SettingChanged").await?;
|
||||
|
||||
read_all_settings(&settings_proxy, &cx).await;
|
||||
|
||||
// The appearance is known now, so the first windows can be created and shown.
|
||||
finish_appearance_query(shared_data_weak);
|
||||
|
||||
while let Some(message) = settings_stream.next().await {
|
||||
let Ok((namespace, key, value)) =
|
||||
message.body().deserialize::<(String, String, zbus::wire::OwnedVariant)>()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if let Some(setting) = SETTINGS.iter().find(|s| s.namespace == namespace && s.key == key) {
|
||||
(setting.apply)(value, &cx);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// True when the error only means the session bus or the settings portal is missing,
|
||||
/// which is normal on headless systems and bare compositors.
|
||||
fn portal_unavailable(err: &zbus::Error) -> bool {
|
||||
#[cfg_attr(slint_nightly_test, allow(non_exhaustive_omitted_patterns))]
|
||||
match err {
|
||||
// No session bus address, or nothing listening on it.
|
||||
zbus::Error::Address(_) | zbus::Error::InputOutput(_) => true,
|
||||
zbus::Error::MethodError(name, ..) => matches!(
|
||||
name.as_str(),
|
||||
"org.freedesktop.DBus.Error.ServiceUnknown"
|
||||
| "org.freedesktop.DBus.Error.NameHasNoOwner"
|
||||
),
|
||||
zbus::Error::FDO(err) => matches!(
|
||||
**err,
|
||||
zbus::fdo::Error::ServiceUnknown(_) | zbus::fdo::Error::NameHasNoOwner(_)
|
||||
),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the portal watcher and the timeout that releases the first windows if
|
||||
/// the portal is slow or missing. Returns the task so the backend can abort it.
|
||||
pub(crate) fn spawn(
|
||||
shared_data: &Rc<SharedBackendData>,
|
||||
ctx: &SlintContextWeak,
|
||||
) -> Option<i_slint_core::future::JoinHandle<()>> {
|
||||
let strong_ctx = ctx.upgrade().expect("spawn is called while the SlintContext is still alive");
|
||||
// Hold back the first windows until the query applies the real appearance.
|
||||
shared_data.desktop_settings.appearance_pending.set(true);
|
||||
|
||||
let shared_weak = Rc::downgrade(shared_data);
|
||||
let ctx_weak = ctx.clone();
|
||||
strong_ctx
|
||||
.spawn_local(async move {
|
||||
if let Err(err) = watch(&shared_weak, ctx_weak).await {
|
||||
if !portal_unavailable(&err) {
|
||||
i_slint_core::debug_log!("Error watching for xdg desktop settings: {err}");
|
||||
}
|
||||
// The portal is unavailable; create the waiting windows anyway.
|
||||
finish_appearance_query(&shared_weak);
|
||||
}
|
||||
})
|
||||
.ok()
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue