./0000755000004100000410000000000013127642576011260 5ustar www-datawww-data./README0000644000004100000410000000706713127642576012152 0ustar www-datawww-data 1. Description 2. Running 3. Debug messages and logging 4. Building 5. QPA native interface 1. Description -------------- QtUbuntu contains a QPA (Qt Platform Abstraction) plugin based on the Ubuntu Platform API and Mir client API 2 Running --------- Considering the QPA plugin path is correctly set using either the QT_QPA_PLATFORM_PLUGIN_PATH environment variable or the "-platformpluginpath" command line switch, the following commands can be used to run with the Ubuntu QPA plugin: $ qmlscene -platform ubuntumirclient Foo.qml $ QT_QPA_PLATFORM=ubuntumirclient qmlscene Foo.qml This QPA plugin exposes the following environment variables: QT_QPA_EGLFS_SWAPINTERVAL: Specifies the required swap interval as an integer. 1 by default. QTUBUNTU_NO_THREADED_OPENGL: Disables QtQuick threaded OpenGL rendering. QTUBUNTU_NO_INPUT: Disables touchscreen and buttons. QTUBUNTU_ICON_THEME: Specifies the default icon theme name. 3 Debug messages and logging ---------------------------- QtUbuntu uses Qt logging categories (see QLoggingCategory class documentation for more information). By default warnings and critical messages are logged and debug messages are disabled. QtUbuntu provides the following logging categories: * qt.qpa.mirclient.cursor - Messages about the cursor. * qt.qpa.mirclient.input - Messages related to input and other Mir events. * qt.qpa.mirclient.graphics - Messages related to graphics, GL and EGL. * qt.qpa.mirclient.swapBuffers - Messages related to surface buffer swapping. * qt.qpa.mirclient - For all other messages form the ubuntumirclient QPA. * ubuntuappmenu.registrar - Messages related to application menu registration. * ubuntuappmenu - For all other messages form the ubuntuappmenu QPA theme. The QT_QPA_EGLFS_DEBUG environment variable prints a little more information from Qt's internals. 4. Building ----------- To compile QtUbuntu, create the makefiles with qmake and build with make: $ qmake $ make By default, QtUbuntu compiles a release build. To compile a debug build, the following qmake command should be used: $ qmake CONFIG+=debug 5. QPA native interface ----------------------- The QPA plugin exposes a native interface allowing to retrieve native handles and to filter out native events. In order to retrieve native handles, the following code can be used: #include #include ... QQuickView* view = new QQuickView(); ... QPlatformNativeInterface* native = QGuiApplication::platformNativeInterface(); printf("app: eglcontext=%p egldisplay=%p\n", native->nativeResourceForContext("eglcontext", view->openglContext()), native->nativeResourceForWindow("egldisplay", view)); Note that handles aren't valid until the application mainloop is started. The qmake .pro needs to add private gui include directories using QT += gui-private Some events exposed in the input compatibility layer can't be directly mapped to Qt. In order to retrieve such events, a native event filter needs to be installed. To do so, a QAbstractNativeEventFilter [1] filtering out "Event" events needs to be implemented and installed using QCoreApplication::installNativeEventFilter [2]. [1] http://doc-snapshot.qt-project.org/5.0/qabstractnativeeventfilter.html [2] http://doc-snapshot.qt-project.org/5.0/qcoreapplication.html#installNativeEventFilter ./COPYING0000644000004100000410000010451313127642576012317 0ustar www-datawww-data GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ./src/0000755000004100000410000000000013127642576012047 5ustar www-datawww-data./src/src.pro0000644000004100000410000000007513127642576013362 0ustar www-datawww-dataTEMPLATE = subdirs SUBDIRS += ubuntumirclient ubuntuappmenu ./src/shared/0000755000004100000410000000000013127642604013305 5ustar www-datawww-data./src/shared/ubuntutheme.h0000644000004100000410000000355713127642604016035 0ustar www-datawww-data/* * Copyright (C) 2016-2017 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ #include #include class UbuntuTheme : public QGenericUnixTheme { public: UbuntuTheme() : mSystemFont(QStringLiteral("Ubuntu Regular"), 10), mFixedFont(QStringLiteral("Ubuntu Mono Regular"), 13) { mSystemFont.setStyleHint(QFont::System); mFixedFont.setStyleHint(QFont::TypeWriter); } ~UbuntuTheme() = default; QVariant themeHint(ThemeHint hint) const override { switch (hint) { case QPlatformTheme::SystemIconThemeName: { QByteArray iconTheme = qgetenv("QTUBUNTU_ICON_THEME"); if (iconTheme.isEmpty()) { return QStringLiteral("suru"); } else { return iconTheme; } } default: break; } return QGenericUnixTheme::themeHint(hint); } const QFont *font(Font type) const override { switch (type) { case QPlatformTheme::SystemFont: return &mSystemFont; case QPlatformTheme::FixedFont: return &mFixedFont; default: return nullptr; } } private: QFont mSystemFont, mFixedFont; }; ./src/ubuntuappmenu/0000755000004100000410000000000013127642604014747 5ustar www-datawww-data./src/ubuntuappmenu/themeplugin.cpp0000644000004100000410000000216713127642576020012 0ustar www-datawww-data/* * Copyright (C) 2016 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ #include "themeplugin.h" #include "theme.h" #include /////////////////////////////////////////////////////////// UbuntuAppMenuThemePlugin::UbuntuAppMenuThemePlugin(QObject *parent) : QPlatformThemePlugin(parent) { } QPlatformTheme * UbuntuAppMenuThemePlugin::create(const QString &key, const QStringList&) { if (key.compare(QLatin1String(UbuntuAppMenuTheme::name), Qt::CaseInsensitive)) return 0; return new UbuntuAppMenuTheme(); } ./src/ubuntuappmenu/com.ubuntu.MenuRegistrar.xml0000644000004100000410000001216213127642576022370 0ustar www-datawww-data An interface to register a menu from an application to be displayed in another window. This manages that association between processes and/or Mir surface IDs and the dbus address and object that provides the menus using the org.gtk.Menus interface. The process ID of the application for which the menu is associated The dbus path where the gmenumodel interface for the application menu has been exported The dbus path where the gactionmenu interface for the application menu actions has been exported The dbus conection name of the client application to be registered (e.g. :1.23 or org.example.service) A method to allow removing an application menu from the database. The process id of the application The dbus path for the registered application menu to be unregistered The surface ID of the surface The dbus path where the gmenumodel interface for the surface menu has been exported The dbus path where the gactionmenu interface for the surface menu actions has been exported The dbus conection name of the client application to be registered (e.g. :1.23 or org.example.service) A method to allow removing a surface menu from the database. The surface id of the surface The dbus path for the registered surface menu to be unregistered ./src/ubuntuappmenu/themeplugin.h0000644000004100000410000000217413127642576017455 0ustar www-datawww-data/* * Copyright (C) 2016 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ #ifndef UBUNTUTHEMEPLUGIN_H #define UBUNTUTHEMEPLUGIN_H #include class UbuntuAppMenuThemePlugin : public QPlatformThemePlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QPA.QPlatformThemeFactoryInterface.5.1" FILE "ubuntuappmenu.json") public: UbuntuAppMenuThemePlugin(QObject *parent = 0); virtual QPlatformTheme *create(const QString &key, const QStringList ¶mList); static const char *name; }; #endif ./src/ubuntuappmenu/gmenumodelplatformmenu.cpp0000644000004100000410000003174713127642576022265 0ustar www-datawww-data/* * Copyright (C) 2016 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ // Local #include "gmenumodelplatformmenu.h" #include "gmenumodelexporter.h" #include "registry.h" #include "menuregistrar.h" #include "logging.h" // Qt #include #include #include #define BAR_DEBUG_MSG qCDebug(ubuntuappmenu).nospace() << "UbuntuPlatformMenuBar[" << (void*)this <<"]::" << __func__ #define MENU_DEBUG_MSG qCDebug(ubuntuappmenu).nospace() << "UbuntuPlatformMenu[" << (void*)this <<"]::" << __func__ #define ITEM_DEBUG_MSG qCDebug(ubuntuappmenu).nospace() << "UbuntuPlatformMenuItem[" << (void*)this <<"]::" << __func__ namespace { int logRecusion = 0; } QDebug operator<<(QDebug stream, UbuntuPlatformMenuBar* bar) { if (bar) return bar->operator<<(stream); return stream; } QDebug operator<<(QDebug stream, UbuntuPlatformMenu* menu) { if (menu) return menu->operator<<(stream); return stream; } QDebug operator<<(QDebug stream, UbuntuPlatformMenuItem* menuItem) { if (menuItem) return menuItem->operator<<(stream); return stream; } UbuntuPlatformMenuBar::UbuntuPlatformMenuBar() : m_exporter(new UbuntuMenuBarExporter(this)) , m_registrar(new UbuntuMenuRegistrar()) , m_ready(false) { BAR_DEBUG_MSG << "()"; connect(this, &UbuntuPlatformMenuBar::menuInserted, this, &UbuntuPlatformMenuBar::structureChanged); connect(this,&UbuntuPlatformMenuBar::menuRemoved, this, &UbuntuPlatformMenuBar::structureChanged); } UbuntuPlatformMenuBar::~UbuntuPlatformMenuBar() { BAR_DEBUG_MSG << "()"; } void UbuntuPlatformMenuBar::insertMenu(QPlatformMenu *menu, QPlatformMenu *before) { BAR_DEBUG_MSG << "(menu=" << menu << ", before=" << before << ")"; if (m_menus.contains(menu)) return; if (!before) { m_menus.push_back(menu); } else { for (auto iter = m_menus.begin(); iter != m_menus.end(); ++iter) { if (*iter == before) { m_menus.insert(iter, menu); break; } } } Q_EMIT menuInserted(menu); } void UbuntuPlatformMenuBar::removeMenu(QPlatformMenu *menu) { BAR_DEBUG_MSG << "(menu=" << menu << ")"; QMutableListIterator iterator(m_menus); while(iterator.hasNext()) { if (iterator.next() == menu) { iterator.remove(); break; } } Q_EMIT menuRemoved(menu); } void UbuntuPlatformMenuBar::syncMenu(QPlatformMenu *menu) { BAR_DEBUG_MSG << "(menu=" << menu << ")"; Q_UNUSED(menu) } void UbuntuPlatformMenuBar::handleReparent(QWindow *parentWindow) { BAR_DEBUG_MSG << "(parentWindow=" << parentWindow << ")"; setReady(true); m_registrar->registerMenuForWindow(parentWindow, QDBusObjectPath(m_exporter->menuPath())); } QPlatformMenu *UbuntuPlatformMenuBar::menuForTag(quintptr tag) const { Q_FOREACH(QPlatformMenu* menu, m_menus) { if (menu->tag() == tag) { return menu; } } return nullptr; } const QList UbuntuPlatformMenuBar::menus() const { return m_menus; } QDebug UbuntuPlatformMenuBar::operator<<(QDebug stream) { stream.nospace().noquote() << QString("%1").arg("", logRecusion, QLatin1Char('\t')) << "UbuntuPlatformMenuBar(this=" << (void*)this << ")" << endl; Q_FOREACH(QPlatformMenu* menu, m_menus) { auto myMenu = static_cast(menu); if (myMenu) { logRecusion++; stream << myMenu; logRecusion--; } } return stream; } #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) QPlatformMenu *UbuntuPlatformMenuBar::createMenu() const { return new UbuntuPlatformMenu(); } #endif void UbuntuPlatformMenuBar::setReady(bool isReady) { if (m_ready != isReady) { m_ready = isReady; Q_EMIT ready(); } } ////////////////////////////////////////////////////////////// UbuntuPlatformMenu::UbuntuPlatformMenu() : m_tag(reinterpret_cast(this)) , m_parentWindow(nullptr) , m_exporter(nullptr) , m_registrar(nullptr) { MENU_DEBUG_MSG << "()"; connect(this, &UbuntuPlatformMenu::menuItemInserted, this, &UbuntuPlatformMenu::structureChanged); connect(this, &UbuntuPlatformMenu::menuItemRemoved, this, &UbuntuPlatformMenu::structureChanged); } UbuntuPlatformMenu::~UbuntuPlatformMenu() { MENU_DEBUG_MSG << "()"; } void UbuntuPlatformMenu::insertMenuItem(QPlatformMenuItem *menuItem, QPlatformMenuItem *before) { MENU_DEBUG_MSG << "(menuItem=" << menuItem << ", before=" << before << ")"; if (m_menuItems.contains(menuItem)) return; if (!before) { m_menuItems.push_back(menuItem); } else { for (auto iter = m_menuItems.begin(); iter != m_menuItems.end(); ++iter) { if (*iter == before) { m_menuItems.insert(iter, menuItem); break; } } } Q_EMIT menuItemInserted(menuItem); } void UbuntuPlatformMenu::removeMenuItem(QPlatformMenuItem *menuItem) { MENU_DEBUG_MSG << "(menuItem=" << menuItem << ")"; QMutableListIterator iterator(m_menuItems); while(iterator.hasNext()) { if (iterator.next() == menuItem) { iterator.remove(); break; } } Q_EMIT menuItemRemoved(menuItem); } void UbuntuPlatformMenu::syncMenuItem(QPlatformMenuItem *menuItem) { MENU_DEBUG_MSG << "(menuItem=" << menuItem << ")"; Q_UNUSED(menuItem) } void UbuntuPlatformMenu::syncSeparatorsCollapsible(bool enable) { MENU_DEBUG_MSG << "(enable=" << enable << ")"; Q_UNUSED(enable) } void UbuntuPlatformMenu::setTag(quintptr tag) { MENU_DEBUG_MSG << "(tag=" << tag << ")"; m_tag = tag; } quintptr UbuntuPlatformMenu::tag() const { return m_tag; } void UbuntuPlatformMenu::setText(const QString &text) { MENU_DEBUG_MSG << "(text=" << text << ")"; if (m_text != text) { m_text = text; } } void UbuntuPlatformMenu::setIcon(const QIcon &icon) { MENU_DEBUG_MSG << "(icon=" << icon.name() << ")"; if (!icon.isNull() || (!m_icon.isNull() && icon.isNull())) { m_icon = icon; } } void UbuntuPlatformMenu::setEnabled(bool enabled) { MENU_DEBUG_MSG << "(enabled=" << enabled << ")"; if (m_enabled != enabled) { m_enabled = enabled; Q_EMIT enabledChanged(enabled); } } void UbuntuPlatformMenu::setVisible(bool isVisible) { MENU_DEBUG_MSG << "(visible=" << isVisible << ")"; if (m_visible != isVisible) { m_visible = isVisible; } } void UbuntuPlatformMenu::setMinimumWidth(int width) { MENU_DEBUG_MSG << "(width=" << width << ")"; Q_UNUSED(width) } void UbuntuPlatformMenu::setFont(const QFont &font) { MENU_DEBUG_MSG << "(font=" << font << ")"; Q_UNUSED(font) } void UbuntuPlatformMenu::showPopup(const QWindow *parentWindow, const QRect &targetRect, const QPlatformMenuItem *item) { MENU_DEBUG_MSG << "(parentWindow=" << parentWindow << ", targetRect=" << targetRect << ", item=" << item << ")"; if (!m_exporter) { m_exporter.reset(new UbuntuMenuExporter(this)); m_exporter->exportModels(); } if (parentWindow != m_parentWindow) { if (m_parentWindow) { m_registrar->unregisterMenu(); } m_parentWindow = parentWindow; if (m_parentWindow) { if (!m_registrar) m_registrar.reset(new UbuntuMenuRegistrar); m_registrar->registerMenuForWindow(const_cast(m_parentWindow), QDBusObjectPath(m_exporter->menuPath())); } } Q_UNUSED(targetRect); Q_UNUSED(item); setVisible(true); } void UbuntuPlatformMenu::dismiss() { MENU_DEBUG_MSG << "()"; if (m_registrar) { m_registrar->unregisterMenu(); } if (m_exporter) { m_exporter->unexportModels(); } } QPlatformMenuItem *UbuntuPlatformMenu::menuItemAt(int position) const { if (position < 0 || position >= m_menuItems.count()) return nullptr; return m_menuItems.at(position); } QPlatformMenuItem *UbuntuPlatformMenu::menuItemForTag(quintptr tag) const { Q_FOREACH(QPlatformMenuItem* menuItem, m_menuItems) { if (menuItem->tag() == tag) { return menuItem; } } return nullptr; } QPlatformMenuItem *UbuntuPlatformMenu::createMenuItem() const { return new UbuntuPlatformMenuItem(); } #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) QPlatformMenu *UbuntuPlatformMenu::createSubMenu() const { return new UbuntuPlatformMenu(); } #endif const QList UbuntuPlatformMenu::menuItems() const { return m_menuItems; } QDebug UbuntuPlatformMenu::operator<<(QDebug stream) { stream.nospace().noquote() << QString("%1").arg("", logRecusion, QLatin1Char('\t')) << "UbuntuPlatformMenu(this=" << (void*)this << ", text=\"" << m_text << "\")" << endl; Q_FOREACH(QPlatformMenuItem* item, m_menuItems) { logRecusion++; auto myItem = static_cast(item); if (myItem) { stream << myItem; } logRecusion--; } return stream; } ////////////////////////////////////////////////////////////// UbuntuPlatformMenuItem::UbuntuPlatformMenuItem() : m_menu(nullptr) , m_tag(reinterpret_cast(this)) { ITEM_DEBUG_MSG << "()"; } UbuntuPlatformMenuItem::~UbuntuPlatformMenuItem() { ITEM_DEBUG_MSG << "()"; } void UbuntuPlatformMenuItem::setTag(quintptr tag) { ITEM_DEBUG_MSG << "(tag=" << tag << ")"; m_tag = tag; } quintptr UbuntuPlatformMenuItem::tag() const { return m_tag; } void UbuntuPlatformMenuItem::setText(const QString &text) { ITEM_DEBUG_MSG << "(text=" << text << ")"; if (m_text != text) { m_text = text; } } void UbuntuPlatformMenuItem::setIcon(const QIcon &icon) { ITEM_DEBUG_MSG << "(icon=" << icon.name() << ")"; if (!icon.isNull() || (!m_icon.isNull() && icon.isNull())) { m_icon = icon; } } void UbuntuPlatformMenuItem::setVisible(bool isVisible) { ITEM_DEBUG_MSG << "(visible=" << isVisible << ")"; if (m_visible != isVisible) { m_visible = isVisible; Q_EMIT visibleChanged(m_visible); } } void UbuntuPlatformMenuItem::setIsSeparator(bool isSeparator) { ITEM_DEBUG_MSG << "(separator=" << isSeparator << ")"; if (m_separator != isSeparator) { m_separator = isSeparator; } } void UbuntuPlatformMenuItem::setFont(const QFont &font) { ITEM_DEBUG_MSG << "(font=" << font << ")"; Q_UNUSED(font); } void UbuntuPlatformMenuItem::setRole(QPlatformMenuItem::MenuRole role) { ITEM_DEBUG_MSG << "(role=" << role << ")"; Q_UNUSED(role); } void UbuntuPlatformMenuItem::setCheckable(bool checkable) { ITEM_DEBUG_MSG << "(checkable=" << checkable << ")"; if (m_checkable != checkable) { m_checkable = checkable; } } void UbuntuPlatformMenuItem::setChecked(bool isChecked) { ITEM_DEBUG_MSG << "(checked=" << isChecked << ")"; if (m_checked != isChecked) { m_checked = isChecked; Q_EMIT checkedChanged(isChecked); } } void UbuntuPlatformMenuItem::setShortcut(const QKeySequence &shortcut) { ITEM_DEBUG_MSG << "(shortcut=" << shortcut << ")"; if (m_shortcut != shortcut) { m_shortcut = shortcut; } } void UbuntuPlatformMenuItem::setEnabled(bool enabled) { ITEM_DEBUG_MSG << "(enabled=" << enabled << ")"; if (m_enabled != enabled) { m_enabled = enabled; Q_EMIT enabledChanged(enabled); } } void UbuntuPlatformMenuItem::setIconSize(int size) { ITEM_DEBUG_MSG << "(size=" << size << ")"; Q_UNUSED(size); } void UbuntuPlatformMenuItem::setMenu(QPlatformMenu *menu) { ITEM_DEBUG_MSG << "(menu=" << menu << ")"; if (m_menu != menu) { m_menu = menu; if (menu) { connect(menu, &QObject::destroyed, this, [this] { setMenu(nullptr); }); } } } QPlatformMenu *UbuntuPlatformMenuItem::menu() const { return m_menu; } QDebug UbuntuPlatformMenuItem::operator<<(QDebug stream) { QString properties = "text=\"" + m_text + "\""; stream.nospace().noquote() << QString("%1").arg("", logRecusion, QLatin1Char('\t')) << "UbuntuPlatformMenuItem(this=" << (void*)this << ", " << (m_separator ? "Separator" : properties) << ")" << endl; if (m_menu) { auto myMenu = static_cast(m_menu); if (myMenu) { logRecusion++; stream << myMenu; logRecusion--; } } return stream; } ./src/ubuntuappmenu/theme.cpp0000644000004100000410000000424713127642576016574 0ustar www-datawww-data/* * Copyright (C) 2016-2017 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ #include "theme.h" #include "gmenumodelplatformmenu.h" #include "logging.h" #include #include Q_LOGGING_CATEGORY(ubuntuappmenu, "ubuntuappmenu", QtWarningMsg) const char *UbuntuAppMenuTheme::name = "ubuntuappmenu"; namespace { bool useLocalMenu() { QByteArray menuProxy = qgetenv("UBUNTU_MENUPROXY"); bool menuProxyIsZero = !menuProxy.isEmpty() && menuProxy.at(0) == '0'; return menuProxyIsZero; } } UbuntuAppMenuTheme::UbuntuAppMenuTheme(): UbuntuTheme() { qCDebug(ubuntuappmenu, "UbuntuAppMenuTheme::UbuntuAppMenuTheme() - useLocalMenu=%s", useLocalMenu() ? "true" : "false"); } QPlatformMenuItem *UbuntuAppMenuTheme::createPlatformMenuItem() const { if (useLocalMenu()) return QGenericUnixTheme::createPlatformMenuItem(); return new UbuntuPlatformMenuItem(); } QPlatformMenu *UbuntuAppMenuTheme::createPlatformMenu() const { if (useLocalMenu()) return QGenericUnixTheme::createPlatformMenu(); return new UbuntuPlatformMenu(); } QPlatformMenuBar *UbuntuAppMenuTheme::createPlatformMenuBar() const { if (useLocalMenu()) return QGenericUnixTheme::createPlatformMenuBar(); return new UbuntuPlatformMenuBar(); } QPlatformSystemTrayIcon *UbuntuAppMenuTheme::createPlatformSystemTrayIcon() const { // We can't use QGenericUnixTheme implementation since it needs the platformMenu to // be a subclass of QDBusPlatformMenu and ours isn't // TODO Investigate if we're fine with not supporting system trays or we should fix it return nullptr; } ./src/ubuntuappmenu/registry.h0000644000004100000410000000351213127642576017001 0ustar www-datawww-data/* * Copyright (C) 2016 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ #ifndef UBUNTU_MENU_REGISTRY_H #define UBUNTU_MENU_REGISTRY_H #include #include class ComUbuntuMenuRegistrarInterface; class QDBusObjectPath; class QDBusServiceWatcher; class UbuntuMenuRegistry : public QObject { Q_OBJECT public: UbuntuMenuRegistry(QObject* parent = nullptr); virtual ~UbuntuMenuRegistry(); static UbuntuMenuRegistry *instance(); void registerApplicationMenu(pid_t pid, QDBusObjectPath menuObjectPath, const QString &service); void unregisterApplicationMenu(pid_t pid, QDBusObjectPath menuObjectPath); void registerSurfaceMenu(const QString &surfaceId, QDBusObjectPath menuObjectPath, const QString &service); void unregisterSurfaceMenu(const QString &surfaceId, QDBusObjectPath menuObjectPath); bool isConnected() const { return m_connected; } Q_SIGNALS: void serviceChanged(); private Q_SLOTS: void serviceOwnerChanged(const QString &serviceName, const QString& oldOwner, const QString &newOwner); private: QScopedPointer m_serviceWatcher; QScopedPointer m_interface; bool m_connected; }; #endif // UBUNTU_MENU_REGISTRY_H ./src/ubuntuappmenu/gmenumodelplatformmenu.h0000644000004100000410000001402513127642576021720 0ustar www-datawww-data/* * Copyright (C) 2016 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ #ifndef EXPORTEDPLATFORMMENUBAR_H #define EXPORTEDPLATFORMMENUBAR_H #include // Local class UbuntuGMenuModelExporter; class UbuntuMenuRegistrar; class QWindow; class UbuntuPlatformMenuBar : public QPlatformMenuBar { Q_OBJECT public: UbuntuPlatformMenuBar(); ~UbuntuPlatformMenuBar(); QString exportedPath() const; virtual void insertMenu(QPlatformMenu *menu, QPlatformMenu* before) override; virtual void removeMenu(QPlatformMenu *menu) override; virtual void syncMenu(QPlatformMenu *menu) override; virtual void handleReparent(QWindow *newParentWindow) override; virtual QPlatformMenu *menuForTag(quintptr tag) const override; const QList menus() const; QDebug operator<<(QDebug stream); #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) virtual QPlatformMenu *createMenu() const override; #endif Q_SIGNALS: void menuInserted(QPlatformMenu *menu); void menuRemoved(QPlatformMenu *menu); void structureChanged(); void ready(); private: void setReady(bool); QList m_menus; QScopedPointer m_exporter; QScopedPointer m_registrar; bool m_ready; }; #define MENU_PROPERTY(class, name, type, defaultValue) \ static type get_##name(const class *menuItem) { return menuItem->m_##name; } \ type m_##name = defaultValue; class Q_DECL_EXPORT UbuntuPlatformMenu : public QPlatformMenu { Q_OBJECT public: UbuntuPlatformMenu(); ~UbuntuPlatformMenu(); virtual void insertMenuItem(QPlatformMenuItem *menuItem, QPlatformMenuItem *before) override; virtual void removeMenuItem(QPlatformMenuItem *menuItem) override; virtual void syncMenuItem(QPlatformMenuItem *menuItem) override; virtual void syncSeparatorsCollapsible(bool enable) override; virtual void setTag(quintptr tag) override; virtual quintptr tag() const override; virtual void setText(const QString &text) override; virtual void setIcon(const QIcon &icon) override; virtual void setEnabled(bool isEnabled) override; virtual void setVisible(bool isVisible) override; virtual void setMinimumWidth(int width) override; virtual void setFont(const QFont &font) override; virtual void showPopup(const QWindow *parentWindow, const QRect &targetRect, const QPlatformMenuItem *item) override; virtual void dismiss() override; // Closes this and all its related menu popups virtual QPlatformMenuItem *menuItemAt(int position) const override; virtual QPlatformMenuItem *menuItemForTag(quintptr tag) const override; virtual QPlatformMenuItem *createMenuItem() const override; #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) virtual QPlatformMenu *createSubMenu() const override; #endif int id() const; const QList menuItems() const; QDebug operator<<(QDebug stream); Q_SIGNALS: void menuItemInserted(QPlatformMenuItem *menuItem); void menuItemRemoved(QPlatformMenuItem *menuItem); void structureChanged(); void enabledChanged(bool); private: MENU_PROPERTY(UbuntuPlatformMenu, visible, bool, true) MENU_PROPERTY(UbuntuPlatformMenu, text, QString, QString()) MENU_PROPERTY(UbuntuPlatformMenu, enabled, bool, true) MENU_PROPERTY(UbuntuPlatformMenu, icon, QIcon, QIcon()) quintptr m_tag; QList m_menuItems; const QWindow* m_parentWindow; QScopedPointer m_exporter; QScopedPointer m_registrar; friend class UbuntuGMenuModelExporter; }; class Q_DECL_EXPORT UbuntuPlatformMenuItem : public QPlatformMenuItem { Q_OBJECT public: UbuntuPlatformMenuItem(); ~UbuntuPlatformMenuItem(); virtual void setTag(quintptr tag) override; virtual quintptr tag() const override; virtual void setText(const QString &text) override; virtual void setIcon(const QIcon &icon) override; virtual void setMenu(QPlatformMenu *menu) override; virtual void setVisible(bool isVisible) override; virtual void setIsSeparator(bool isSeparator) override; virtual void setFont(const QFont &font) override; virtual void setRole(MenuRole role) override; virtual void setCheckable(bool checkable) override; virtual void setChecked(bool isChecked) override; virtual void setShortcut(const QKeySequence& shortcut) override; virtual void setEnabled(bool enabled) override; virtual void setIconSize(int size) override; QPlatformMenu* menu() const; QDebug operator<<(QDebug stream); Q_SIGNALS: void checkedChanged(bool); void enabledChanged(bool); void visibleChanged(bool); private: MENU_PROPERTY(UbuntuPlatformMenuItem, separator, bool, false) MENU_PROPERTY(UbuntuPlatformMenuItem, visible, bool, true) MENU_PROPERTY(UbuntuPlatformMenuItem, text, QString, QString()) MENU_PROPERTY(UbuntuPlatformMenuItem, enabled, bool, true) MENU_PROPERTY(UbuntuPlatformMenuItem, checkable, bool, false) MENU_PROPERTY(UbuntuPlatformMenuItem, checked, bool, false) MENU_PROPERTY(UbuntuPlatformMenuItem, shortcut, QKeySequence, QKeySequence()) MENU_PROPERTY(UbuntuPlatformMenuItem, icon, QIcon, QIcon()) MENU_PROPERTY(UbuntuPlatformMenuItem, iconSize, int, 16) MENU_PROPERTY(UbuntuPlatformMenuItem, menu, QPlatformMenu*, nullptr) quintptr m_tag; friend class UbuntuGMenuModelExporter; }; #endif // EXPORTEDPLATFORMMENUBAR_H ./src/ubuntuappmenu/menuregistrar.cpp0000644000004100000410000001003513127642576020351 0ustar www-datawww-data/* * Copyright (C) 2016 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ #include "menuregistrar.h" #include "registry.h" #include "logging.h" #include #include #include #include #include namespace { bool isMirClient() { return qGuiApp->platformName() == "ubuntumirclient"; } } UbuntuMenuRegistrar::UbuntuMenuRegistrar() : m_connection(nullptr) , m_registeredProcessId(~0) { GError *error = NULL; m_connection = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error); if (!m_connection) { qCWarning(ubuntuappmenuRegistrar, "Failed to retreive session bus - %s", error ? error->message : "unknown error"); g_error_free (error); return; } m_service = g_dbus_connection_get_unique_name(m_connection); connect(UbuntuMenuRegistry::instance(), &UbuntuMenuRegistry::serviceChanged, this, &UbuntuMenuRegistrar::onRegistrarServiceChanged); if (isMirClient()) { auto nativeInterface = qGuiApp->platformNativeInterface(); connect(nativeInterface, &QPlatformNativeInterface::windowPropertyChanged, this, [this](QPlatformWindow* window, const QString &property) { if (property != QStringLiteral("persistentSurfaceId")) { return; } if (window->window() == m_window) { registerMenuForWindow(m_window, m_path); } }); } } UbuntuMenuRegistrar::~UbuntuMenuRegistrar() { if (m_connection) { g_object_unref(m_connection); } unregisterMenu(); } void UbuntuMenuRegistrar::registerMenuForWindow(QWindow* window, const QDBusObjectPath& path) { unregisterMenu(); m_window = window; m_path = path; registerMenu(); } void UbuntuMenuRegistrar::registerMenu() { if (UbuntuMenuRegistry::instance()->isConnected() && m_window) { if (isMirClient()) { registerSurfaceMenu(); } else { registerApplicationMenu(); } } } void UbuntuMenuRegistrar::unregisterMenu() { if (!m_registeredSurfaceId.isEmpty()) { unregisterSurfaceMenu(); } else if (m_registeredProcessId != ~0) { unregisterApplicationMenu(); } } void UbuntuMenuRegistrar::registerSurfaceMenu() { auto nativeInterface = qGuiApp->platformNativeInterface(); QByteArray persistentSurfaceId = nativeInterface->windowProperty(m_window->handle(), "persistentSurfaceId", QByteArray()).toByteArray(); if (persistentSurfaceId.isEmpty()) return; UbuntuMenuRegistry::instance()->registerSurfaceMenu(persistentSurfaceId, m_path, m_service); m_registeredSurfaceId = persistentSurfaceId; } void UbuntuMenuRegistrar::unregisterSurfaceMenu() { if (UbuntuMenuRegistry::instance()->isConnected()) { UbuntuMenuRegistry::instance()->unregisterSurfaceMenu(m_registeredSurfaceId, m_path); } m_registeredSurfaceId.clear(); } void UbuntuMenuRegistrar::registerApplicationMenu() { pid_t pid = getpid(); UbuntuMenuRegistry::instance()->registerApplicationMenu(pid, m_path, m_service); m_registeredProcessId = pid; } void UbuntuMenuRegistrar::unregisterApplicationMenu() { if (UbuntuMenuRegistry::instance()->isConnected()) { UbuntuMenuRegistry::instance()->unregisterApplicationMenu(m_registeredProcessId, m_path); } m_registeredProcessId = ~0; } void UbuntuMenuRegistrar::onRegistrarServiceChanged() { unregisterMenu(); registerMenu(); } ./src/ubuntuappmenu/gmenumodelexporter.cpp0000644000004100000410000004344013127642576021415 0ustar www-datawww-data/* * Copyright (C) 2016 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ // Local #include "gmenumodelexporter.h" #include "registry.h" #include "logging.h" #include "qtubuntuextraactionhandler.h" #include #include #include namespace { // Derive an action name from the label by removing spaces and Capitilizing the words. // Also remove mnemonics from the label. inline QString getActionString(QString label) { QRegExp re("\\W"); label = label.replace(QRegExp("(&|_)"), ""); QStringList parts = label.split(re, QString::SkipEmptyParts); QString result; Q_FOREACH(const QString& part, parts) { result += part[0].toUpper(); result += part.right(part.length()-1); } return result; } static void activate_cb(GSimpleAction *action, GVariant *, gpointer user_data) { qCDebug(ubuntuappmenu, "Activate menu action '%s'", g_action_get_name(G_ACTION(action))); auto item = static_cast(user_data); item->activated(); } static uint s_menuId = 0; #define MENU_OBJECT_PATH "/com/ubuntu/Menu/%1" } // namespace UbuntuMenuBarExporter::UbuntuMenuBarExporter(UbuntuPlatformMenuBar * bar) : UbuntuGMenuModelExporter(bar) { qCDebug(ubuntuappmenu, "UbuntuMenuBarExporter::UbuntuMenuBarExporter"); connect(bar, &UbuntuPlatformMenuBar::structureChanged, this, [this]() { m_structureTimer.start(); }); connect(&m_structureTimer, &QTimer::timeout, this, [this, bar]() { clear(); Q_FOREACH(QPlatformMenu *platformMenu, bar->menus()) { GMenuItem* item = createSubmenu(platformMenu, nullptr); if (item) { g_menu_append_item(m_gmainMenu, item); g_object_unref(item); } UbuntuPlatformMenu* gplatformMenu = static_cast(platformMenu); if (gplatformMenu) { // Sadly we don't have a better way to propagate a enabled change in a top level menu // than reseting the whole menubar connect(gplatformMenu, &UbuntuPlatformMenu::enabledChanged, bar, &UbuntuPlatformMenuBar::structureChanged); } } }); connect(bar, &UbuntuPlatformMenuBar::ready, this, [this]() { exportModels(); }); } UbuntuMenuBarExporter::~UbuntuMenuBarExporter() { qCDebug(ubuntuappmenu, "UbuntuMenuBarExporter::~UbuntuMenuBarExporter"); } UbuntuMenuExporter::UbuntuMenuExporter(UbuntuPlatformMenu *menu) : UbuntuGMenuModelExporter(menu) { qCDebug(ubuntuappmenu, "UbuntuMenuExporter::UbuntuMenuExporter"); connect(menu, &UbuntuPlatformMenu::structureChanged, this, [this]() { m_structureTimer.start(); }); connect(&m_structureTimer, &QTimer::timeout, this, [this, menu]() { clear(); addSubmenuItems(menu, m_gmainMenu); }); addSubmenuItems(menu, m_gmainMenu); } UbuntuMenuExporter::~UbuntuMenuExporter() { qCDebug(ubuntuappmenu, "UbuntuMenuExporter::~UbuntuMenuExporter"); } UbuntuGMenuModelExporter::UbuntuGMenuModelExporter(QObject *parent) : QObject(parent) , m_connection(nullptr) , m_gmainMenu(g_menu_new()) , m_gactionGroup(g_simple_action_group_new()) , m_exportedModel(0) , m_exportedActions(0) , m_qtubuntuExtraHandler(nullptr) , m_menuPath(QStringLiteral(MENU_OBJECT_PATH).arg(s_menuId++)) { m_structureTimer.setSingleShot(true); m_structureTimer.setInterval(0); } UbuntuGMenuModelExporter::~UbuntuGMenuModelExporter() { unexportModels(); clear(); g_object_unref(m_gmainMenu); g_object_unref(m_gactionGroup); } // Clear the menu and actions that have been created. void UbuntuGMenuModelExporter::clear() { Q_FOREACH(const QVector& menuPropertyConnections, m_propertyConnections) { Q_FOREACH(const QMetaObject::Connection& connection, menuPropertyConnections) { QObject::disconnect(connection); } } m_propertyConnections.clear(); g_menu_remove_all(m_gmainMenu); Q_FOREACH(const QSet& menuActions, m_actions) { Q_FOREACH(const QByteArray& action, menuActions) { g_action_map_remove_action(G_ACTION_MAP(m_gactionGroup), action.constData()); } } m_actions.clear(); m_gmenusForMenus.clear(); } void UbuntuGMenuModelExporter::timerEvent(QTimerEvent *e) { // Find the menu, it's a very short list auto it = m_reloadMenuTimers.begin(); for (; it != m_reloadMenuTimers.end(); ++it) { if (e->timerId() == it.value()) break; } if (it != m_reloadMenuTimers.end()) { UbuntuPlatformMenu* gplatformMenu = it.key(); GMenu *menu = m_gmenusForMenus.value(gplatformMenu); if (menu) { Q_FOREACH(const QMetaObject::Connection& connection, m_propertyConnections[menu]) { QObject::disconnect(connection); } m_propertyConnections.remove(menu); Q_FOREACH(const QByteArray& action, m_actions[menu]) { g_action_map_remove_action(G_ACTION_MAP(m_gactionGroup), action.constData()); } m_actions.remove(menu); g_menu_remove_all(menu); addSubmenuItems(gplatformMenu, menu); } else { qWarning() << "Got an update timer for a menu that has no GMenu" << gplatformMenu; } m_reloadMenuTimers.erase(it); } else { qWarning() << "Got an update timer for a timer that was not running"; } killTimer(e->timerId()); } // Export the model on dbus void UbuntuGMenuModelExporter::exportModels() { GError *error = nullptr; m_connection = g_bus_get_sync (G_BUS_TYPE_SESSION, nullptr, &error); if (!m_connection) { qCWarning(ubuntuappmenu, "Failed to retreive session bus - %s", error ? error->message : "unknown error"); g_error_free (error); return; } QByteArray menuPath(m_menuPath.toUtf8()); if (m_exportedModel == 0) { m_exportedModel = g_dbus_connection_export_menu_model(m_connection, menuPath.constData(), G_MENU_MODEL(m_gmainMenu), &error); if (m_exportedModel == 0) { qCWarning(ubuntuappmenu, "Failed to export menu - %s", error ? error->message : "unknown error"); g_error_free (error); error = nullptr; } else { qCDebug(ubuntuappmenu, "Exported menu on %s", g_dbus_connection_get_unique_name(m_connection)); } } if (m_exportedActions == 0) { m_exportedActions = g_dbus_connection_export_action_group(m_connection, menuPath.constData(), G_ACTION_GROUP(m_gactionGroup), &error); if (m_exportedActions == 0) { qCWarning(ubuntuappmenu, "Failed to export actions - %s", error ? error->message : "unknown error"); g_error_free (error); error = nullptr; } else { qCDebug(ubuntuappmenu, "Exported actions on %s", g_dbus_connection_get_unique_name(m_connection)); } } if (!m_qtubuntuExtraHandler) { m_qtubuntuExtraHandler = new QtUbuntuExtraActionHandler(); if (!m_qtubuntuExtraHandler->connect(m_connection, menuPath, this)) { delete m_qtubuntuExtraHandler; m_qtubuntuExtraHandler = nullptr; } } } void UbuntuGMenuModelExporter::aboutToShow(quint64 tag) { UbuntuPlatformMenu* gplatformMenu = m_submenusWithTag.value(tag); if (!gplatformMenu) { qWarning() << "Got an aboutToShow call with an unknown tag"; return; } gplatformMenu->aboutToShow(); } // Unexport the model void UbuntuGMenuModelExporter::unexportModels() { GError *error = nullptr; if (!m_connection) { qCWarning(ubuntuappmenu, "Failed to retreive session bus - %s", error ? error->message : "unknown error"); return; } if (m_exportedModel != 0) { g_dbus_connection_unexport_menu_model(m_connection, m_exportedModel); m_exportedModel = 0; } if (m_exportedActions != 0) { g_dbus_connection_unexport_action_group(m_connection, m_exportedActions); m_exportedActions = 0; } if (m_qtubuntuExtraHandler) { m_qtubuntuExtraHandler->disconnect(m_connection); delete m_qtubuntuExtraHandler; m_qtubuntuExtraHandler = nullptr; } g_object_unref(m_connection); m_connection = nullptr; } // Create a submenu for the given platform menu. // Returns a gmenuitem entry for the menu, which must be cleaned up using g_object_unref. // If forItem is suplied, use it's label. GMenuItem *UbuntuGMenuModelExporter::createSubmenu(QPlatformMenu *platformMenu, UbuntuPlatformMenuItem *forItem) { UbuntuPlatformMenu* gplatformMenu = static_cast(platformMenu); if (!gplatformMenu) return nullptr; GMenu* menu = g_menu_new(); m_gmenusForMenus.insert(gplatformMenu, menu); QByteArray label; bool enabled; if (forItem) { label = UbuntuPlatformMenuItem::get_text(forItem).toUtf8(); enabled = UbuntuPlatformMenuItem::get_enabled(forItem); } else { label = UbuntuPlatformMenu::get_text(gplatformMenu).toUtf8(); enabled = UbuntuPlatformMenu::get_enabled(gplatformMenu); } addSubmenuItems(gplatformMenu, menu); Q_FOREACH(QPlatformMenuItem *childItem, gplatformMenu->menuItems()) { UbuntuPlatformMenuItem* gplatformMenuItem = static_cast(childItem); if (!gplatformMenuItem) continue; // Sadly we don't have a better way to propagate a enabled change in a item-that-is-submenu // than reseting the whole parent menu if (gplatformMenuItem->menu()) { connect(gplatformMenuItem, &UbuntuPlatformMenuItem::enabledChanged, gplatformMenu, &UbuntuPlatformMenu::structureChanged); } connect(gplatformMenuItem, &UbuntuPlatformMenuItem::visibleChanged, gplatformMenu, &UbuntuPlatformMenu::structureChanged); } GMenuItem* gmenuItem = g_menu_item_new_submenu(label.constData(), G_MENU_MODEL(menu)); const quint64 tag = gplatformMenu->tag(); if (tag != 0) { g_menu_item_set_attribute_value(gmenuItem, "qtubuntu-tag", g_variant_new_uint64 (tag)); m_submenusWithTag.insert(gplatformMenu->tag(), gplatformMenu); } g_object_unref(menu); g_menu_item_set_attribute_value(gmenuItem, "submenu-enabled", g_variant_new_boolean(enabled)); connect(gplatformMenu, &UbuntuPlatformMenu::structureChanged, this, [this, gplatformMenu] { if (!m_reloadMenuTimers.contains(gplatformMenu)) { const int timerId = startTimer(0); m_reloadMenuTimers.insert(gplatformMenu, timerId); } }); connect(gplatformMenu, &UbuntuPlatformMenu::destroyed, this, [this, tag, gplatformMenu] { m_submenusWithTag.remove(tag); m_gmenusForMenus.remove(gplatformMenu); auto timerIdIt = m_reloadMenuTimers.find(gplatformMenu); if (timerIdIt != m_reloadMenuTimers.end()) { killTimer(*timerIdIt); m_reloadMenuTimers.erase(timerIdIt); } }); return gmenuItem; } // Add a platform menu's items to the given gmenu. // The items are inserted into menus sections, split by the menu separators. void UbuntuGMenuModelExporter::addSubmenuItems(UbuntuPlatformMenu* gplatformMenu, GMenu* menu) { auto iter = gplatformMenu->menuItems().begin(); auto lastSectionStart = iter; // Iterate through all the menu items adding sections when a separator is found. for (; iter != gplatformMenu->menuItems().end(); ++iter) { UbuntuPlatformMenuItem* gplatformMenuItem = static_cast(*iter); if (!gplatformMenuItem) continue; // don't add a section until we have separator if (UbuntuPlatformMenuItem::get_separator(gplatformMenuItem)) { if (lastSectionStart != gplatformMenu->menuItems().begin()) { GMenuItem* section = createSection(lastSectionStart, iter); g_menu_append_item(menu, section); g_object_unref(section); } lastSectionStart = iter + 1; } else if (lastSectionStart == gplatformMenu->menuItems().begin()) { processItemForGMenu(gplatformMenuItem, menu); } } // Add the last section if (lastSectionStart != gplatformMenu->menuItems().begin() && lastSectionStart != gplatformMenu->menuItems().end()) { GMenuItem* gsectionItem = createSection(lastSectionStart, gplatformMenu->menuItems().end()); g_menu_append_item(menu, gsectionItem); g_object_unref(gsectionItem); } } // Create and return a gmenu item for the given platform menu item. // Returned GMenuItem must be cleaned up using g_object_unref GMenuItem *UbuntuGMenuModelExporter::createMenuItem(QPlatformMenuItem *platformMenuItem, GMenu *parentMenu) { UbuntuPlatformMenuItem* gplatformMenuItem = static_cast(platformMenuItem); if (!gplatformMenuItem) return nullptr; if (!UbuntuPlatformMenuItem::get_visible(gplatformMenuItem)) return nullptr; QByteArray label(UbuntuPlatformMenuItem::get_text(gplatformMenuItem).toUtf8()); QByteArray actionLabel(getActionString(UbuntuPlatformMenuItem::get_text(gplatformMenuItem)).toUtf8()); QByteArray shortcut(UbuntuPlatformMenuItem::get_shortcut(gplatformMenuItem).toString(QKeySequence::NativeText).toUtf8()); GMenuItem* gmenuItem = g_menu_item_new(label.constData(), nullptr); g_menu_item_set_attribute(gmenuItem, "accel", "s", shortcut.constData()); g_menu_item_set_detailed_action(gmenuItem, ("unity." + actionLabel).constData()); addAction(actionLabel, gplatformMenuItem, parentMenu); return gmenuItem; } // Create a menu section for a section of separated menu items. // Returned GMenuItem must be cleaned up using g_object_unref GMenuItem *UbuntuGMenuModelExporter::createSection(QList::const_iterator iter, QList::const_iterator end) { GMenu* gsectionMenu = g_menu_new(); for (; iter != end; ++iter) { processItemForGMenu(*iter, gsectionMenu); } GMenuItem* gsectionItem = g_menu_item_new_section("", G_MENU_MODEL(gsectionMenu)); g_object_unref(gsectionMenu); return gsectionItem; } // Add the given platform menu item to the menu. // If it has an attached submenu, then create and add the submenu. void UbuntuGMenuModelExporter::processItemForGMenu(QPlatformMenuItem *platformMenuItem, GMenu *gmenu) { UbuntuPlatformMenuItem* gplatformMenuItem = static_cast(platformMenuItem); if (!gplatformMenuItem) return; GMenuItem* gmenuItem = gplatformMenuItem->menu() ? createSubmenu(gplatformMenuItem->menu(), gplatformMenuItem) : createMenuItem(gplatformMenuItem, gmenu); if (gmenuItem) { g_menu_append_item(gmenu, gmenuItem); g_object_unref(gmenuItem); } } // Create and add an action for a menu item. void UbuntuGMenuModelExporter::addAction(const QByteArray &name, UbuntuPlatformMenuItem *gplatformMenuItem, GMenu *parentMenu) { disconnect(gplatformMenuItem, &UbuntuPlatformMenuItem::checkedChanged, this, 0); disconnect(gplatformMenuItem, &UbuntuPlatformMenuItem::enabledChanged, this, 0); QSet &actions = m_actions[parentMenu]; QVector &propertyConnections = m_propertyConnections[parentMenu]; if (actions.contains(name)) { g_action_map_remove_action(G_ACTION_MAP(m_gactionGroup), name.constData()); actions.remove(name); } bool checkable = UbuntuPlatformMenuItem::get_checkable(gplatformMenuItem); GSimpleAction* action = nullptr; if (checkable) { bool checked = UbuntuPlatformMenuItem::get_checked(gplatformMenuItem); action = g_simple_action_new_stateful(name.constData(), nullptr, g_variant_new_boolean(checked)); std::function updateChecked = [gplatformMenuItem, action](bool checked) { auto type = g_action_get_state_type(G_ACTION(action)); if (type && g_variant_type_equal(type, G_VARIANT_TYPE_BOOLEAN)) { g_simple_action_set_state(action, g_variant_new_boolean(checked ? TRUE : FALSE)); } }; // save the connection to disconnect in UbuntuGMenuModelExporter::clear() propertyConnections << connect(gplatformMenuItem, &UbuntuPlatformMenuItem::checkedChanged, this, updateChecked); } else { action = g_simple_action_new(name.constData(), nullptr); } // Enabled update std::function updateEnabled = [gplatformMenuItem, action](bool enabled) { GValue value = G_VALUE_INIT; g_value_init (&value, G_TYPE_BOOLEAN); g_value_set_boolean(&value, enabled ? TRUE : FALSE); g_object_set_property(G_OBJECT(action), "enabled", &value); }; updateEnabled(UbuntuPlatformMenuItem::get_enabled(gplatformMenuItem)); // save the connection to disconnect in UbuntuGMenuModelExporter::clear() propertyConnections << connect(gplatformMenuItem, &UbuntuPlatformMenuItem::enabledChanged, this, updateEnabled); g_signal_connect(action, "activate", G_CALLBACK(activate_cb), gplatformMenuItem); actions.insert(name); g_action_map_add_action(G_ACTION_MAP(m_gactionGroup), G_ACTION(action)); g_object_unref(action); } ./src/ubuntuappmenu/theme.h0000644000004100000410000000230613127642576016233 0ustar www-datawww-data/* * Copyright (C) 2016-2017 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ #ifndef UBUNTU_THEME_H #define UBUNTU_THEME_H #include "../shared/ubuntutheme.h" class UbuntuAppMenuTheme : public UbuntuTheme { public: static const char* name; UbuntuAppMenuTheme(); ~UbuntuAppMenuTheme() = default; // For the menus QPlatformMenuItem* createPlatformMenuItem() const override; QPlatformMenu* createPlatformMenu() const override; QPlatformMenuBar* createPlatformMenuBar() const override; QPlatformSystemTrayIcon *createPlatformSystemTrayIcon() const override; }; #endif // UBUNTU_THEME_H ./src/ubuntuappmenu/registry.cpp0000644000004100000410000000720613127642576017340 0ustar www-datawww-data/* * Copyright (C) 2016 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ #include "registry.h" #include "logging.h" #include "menuregistrar_interface.h" #include #include Q_LOGGING_CATEGORY(ubuntuappmenuRegistrar, "ubuntuappmenu.registrar", QtWarningMsg) #define REGISTRAR_SERVICE "com.ubuntu.MenuRegistrar" #define REGISTRY_OBJECT_PATH "/com/ubuntu/MenuRegistrar" UbuntuMenuRegistry *UbuntuMenuRegistry::instance() { static UbuntuMenuRegistry* registry(new UbuntuMenuRegistry()); return registry; } UbuntuMenuRegistry::UbuntuMenuRegistry(QObject* parent) : QObject(parent) , m_serviceWatcher(new QDBusServiceWatcher(REGISTRAR_SERVICE, QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForOwnerChange, this)) , m_interface(new ComUbuntuMenuRegistrarInterface(REGISTRAR_SERVICE, REGISTRY_OBJECT_PATH, QDBusConnection::sessionBus(), this)) , m_connected(m_interface->isValid()) { connect(m_serviceWatcher.data(), &QDBusServiceWatcher::serviceOwnerChanged, this, &UbuntuMenuRegistry::serviceOwnerChanged); } UbuntuMenuRegistry::~UbuntuMenuRegistry() { } void UbuntuMenuRegistry::registerApplicationMenu(pid_t pid, QDBusObjectPath menuObjectPath, const QString &service) { qCDebug(ubuntuappmenuRegistrar, "UbuntuMenuRegistry::registerMenu(pid=%d, menuObjectPath=%s, service=%s)", pid, qPrintable(menuObjectPath.path()), qPrintable(service)); m_interface->RegisterAppMenu(pid, menuObjectPath, menuObjectPath, service); } void UbuntuMenuRegistry::unregisterApplicationMenu(pid_t pid, QDBusObjectPath menuObjectPath) { qCDebug(ubuntuappmenuRegistrar, "UbuntuMenuRegistry::unregisterSurfaceMenu(pid=%d, menuObjectPath=%s)", pid, qPrintable(menuObjectPath.path())); m_interface->UnregisterAppMenu(pid, menuObjectPath); } void UbuntuMenuRegistry::registerSurfaceMenu(const QString &surfaceId, QDBusObjectPath menuObjectPath, const QString &service) { qCDebug(ubuntuappmenuRegistrar, "UbuntuMenuRegistry::registerMenu(surfaceId=%s, menuObjectPath=%s, service=%s)", qPrintable(surfaceId), qPrintable(menuObjectPath.path()), qPrintable(service)); m_interface->RegisterSurfaceMenu(surfaceId, menuObjectPath, menuObjectPath, service); } void UbuntuMenuRegistry::unregisterSurfaceMenu(const QString &surfaceId, QDBusObjectPath menuObjectPath) { qCDebug(ubuntuappmenuRegistrar, "UbuntuMenuRegistry::unregisterSurfaceMenu(surfaceId=%s, menuObjectPath=%s)", qPrintable(surfaceId), qPrintable(menuObjectPath.path())); m_interface->UnregisterSurfaceMenu(surfaceId, menuObjectPath); } void UbuntuMenuRegistry::serviceOwnerChanged(const QString &serviceName, const QString& oldOwner, const QString &newOwner) { qCDebug(ubuntuappmenuRegistrar, "UbuntuMenuRegistry::serviceOwnerChanged(newOwner=%s)", qPrintable(newOwner)); if (serviceName != REGISTRAR_SERVICE) return; if (oldOwner != newOwner) { m_connected = !newOwner.isEmpty(); Q_EMIT serviceChanged(); } } ./src/ubuntuappmenu/qtubuntuextraactionhandler.h0000644000004100000410000000225413127642576022622 0ustar www-datawww-data/* * Copyright (C) 2017 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ #ifndef QTUBUNTUEXTRAACTIONHANDLER_H #define QTUBUNTUEXTRAACTIONHANDLER_H #include class QByteArray; class UbuntuGMenuModelExporter; class QtUbuntuExtraActionHandler { public: QtUbuntuExtraActionHandler(); ~QtUbuntuExtraActionHandler(); bool connect(GDBusConnection *connection, const QByteArray &menuPath, UbuntuGMenuModelExporter *gmenuexporter); void disconnect(GDBusConnection *connection); private: GDBusNodeInfo *m_introspection_data; guint m_registration_id; }; #endif ./src/ubuntuappmenu/menuregistrar.h0000644000004100000410000000275113127642576020024 0ustar www-datawww-data/* * Copyright (C) 2016 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ #ifndef MENUREGISTRAR_H #define MENUREGISTRAR_H #include #include #include #include #include class UbuntuMenuRegistrar : public QObject { Q_OBJECT public: UbuntuMenuRegistrar(); ~UbuntuMenuRegistrar(); void registerMenuForWindow(QWindow* window, const QDBusObjectPath& path); void unregisterMenu(); private Q_SLOTS: void registerSurfaceMenu(); void onRegistrarServiceChanged(); private: void registerMenu(); void registerApplicationMenu(); void unregisterApplicationMenu(); void unregisterSurfaceMenu(); GDBusConnection *m_connection; QString m_service; QDBusObjectPath m_path; QPointer m_window; QString m_registeredSurfaceId; pid_t m_registeredProcessId; }; #endif // MENUREGISTRAR_H ./src/ubuntuappmenu/gmenumodelexporter.h0000644000004100000410000000574513127642576021070 0ustar www-datawww-data/* * Copyright (C) 2016 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ #ifndef GMENUMODELEXPORTER_H #define GMENUMODELEXPORTER_H #include "gmenumodelplatformmenu.h" #include #include #include #include #include class QtUbuntuExtraActionHandler; // Base class for a gmenumodel exporter class UbuntuGMenuModelExporter : public QObject { Q_OBJECT public: virtual ~UbuntuGMenuModelExporter(); void exportModels(); void unexportModels(); QString menuPath() const { return m_menuPath;} void aboutToShow(quint64 tag); protected: UbuntuGMenuModelExporter(QObject *parent); GMenuItem *createSubmenu(QPlatformMenu* platformMenu, UbuntuPlatformMenuItem* forItem); GMenuItem *createMenuItem(QPlatformMenuItem* platformMenuItem, GMenu *parentMenu); GMenuItem *createSection(QList::const_iterator iter, QList::const_iterator end); void addAction(const QByteArray& name, UbuntuPlatformMenuItem* gplatformItem, GMenu *parentMenu); void addSubmenuItems(UbuntuPlatformMenu* gplatformMenu, GMenu* menu); void processItemForGMenu(QPlatformMenuItem* item, GMenu* gmenu); void clear(); void timerEvent(QTimerEvent *e) override; protected: GDBusConnection *m_connection; GMenu *m_gmainMenu; GSimpleActionGroup *m_gactionGroup; guint m_exportedModel; guint m_exportedActions; QtUbuntuExtraActionHandler *m_qtubuntuExtraHandler; QTimer m_structureTimer; QString m_menuPath; // UbuntuPlatformMenu::tag -> UbuntuPlatformMenu QMap m_submenusWithTag; // UbuntuPlatformMenu -> reload TimerId (startTimer) QHash m_reloadMenuTimers; QHash m_gmenusForMenus; QHash> m_actions; QHash> m_propertyConnections; }; // Class which exports a qt platform menu bar. class UbuntuMenuBarExporter : public UbuntuGMenuModelExporter { public: UbuntuMenuBarExporter(UbuntuPlatformMenuBar *parent); ~UbuntuMenuBarExporter(); }; // Class which exports a qt platform menu. // This will allow exporting of context menus. class UbuntuMenuExporter : public UbuntuGMenuModelExporter { public: UbuntuMenuExporter(UbuntuPlatformMenu *parent); ~UbuntuMenuExporter(); }; #endif // GMENUMODELEXPORTER_H ./src/ubuntuappmenu/ubuntuappmenu.json0000644000004100000410000000004413127642576020560 0ustar www-datawww-data{ "Keys": [ "ubuntuappmenu" ] } ./src/ubuntuappmenu/qtubuntuextraactionhandler.cpp0000644000004100000410000000710413127642576023154 0ustar www-datawww-data/* * Copyright (C) 2017 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ #include "qtubuntuextraactionhandler.h" #include "gmenumodelexporter.h" #include "logging.h" static const gchar introspection_xml[] = "" " " " " " " " " " " ""; static void handle_method_call (GDBusConnection *, const gchar *, const gchar *, const gchar *, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { if (g_strcmp0 (method_name, "aboutToShow") == 0) { if (g_variant_check_format_string(parameters, "(t)", false)) { auto obj = static_cast(user_data); guint64 tag; g_variant_get (parameters, "(t)", &tag); obj->aboutToShow(tag); } g_dbus_method_invocation_return_value (invocation, NULL); } else { g_dbus_method_invocation_return_error(invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Unknown method"); } } static const GDBusInterfaceVTable interface_vtable = { handle_method_call, NULL, NULL, NULL }; QtUbuntuExtraActionHandler::QtUbuntuExtraActionHandler() : m_registration_id(0) { m_introspection_data = g_dbus_node_info_new_for_xml (introspection_xml, NULL); } QtUbuntuExtraActionHandler::~QtUbuntuExtraActionHandler() { g_clear_pointer(&m_introspection_data, g_dbus_node_info_unref); } bool QtUbuntuExtraActionHandler::connect(GDBusConnection *connection, const QByteArray &menuPath, UbuntuGMenuModelExporter *gmenuexporter) { if (m_registration_id != 0) { qCWarning(ubuntuappmenu, "Called connect in an already connected QtUbuntuExtraActionHandler"); return false; } GError *error = nullptr; m_registration_id = g_dbus_connection_register_object (connection, menuPath.constData(), m_introspection_data->interfaces[0], &interface_vtable, gmenuexporter, nullptr, &error); if (!m_registration_id) { qCWarning(ubuntuappmenu, "Failed to extra actions - %s", error ? error->message : "unknown error"); g_clear_error(&error); } return m_registration_id != 0; } void QtUbuntuExtraActionHandler::disconnect(GDBusConnection *connection) { if (m_registration_id) { g_dbus_connection_unregister_object (connection, m_registration_id); } } ./src/ubuntuappmenu/logging.h0000644000004100000410000000172113127642576016557 0ustar www-datawww-data/* * Copyright (C) 2016 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . */ #ifndef QUBUNTUTHEMELOGGING_H #define QUBUNTUTHEMELOGGING_H #include #define ASSERT(cond) ((!(cond)) ? qt_assert(#cond,__FILE__,__LINE__) : qt_noop()) Q_DECLARE_LOGGING_CATEGORY(ubuntuappmenu) Q_DECLARE_LOGGING_CATEGORY(ubuntuappmenuRegistrar) #endif // QUBUNTUTHEMELOGGING_H ./src/ubuntuappmenu/ubuntuappmenu.pro0000644000004100000410000000166513127642604020411 0ustar www-datawww-dataTARGET = ubuntuappmenu TEMPLATE = lib QT -= gui QT += core-private theme_support-private dbus CONFIG += plugin no_keywords # CONFIG += c++11 # only enables C++0x QMAKE_CXXFLAGS += -fvisibility=hidden -fvisibility-inlines-hidden -std=c++11 -Werror -Wall QMAKE_LFLAGS += -std=c++11 -Wl,-no-undefined CONFIG += link_pkgconfig PKGCONFIG += gio-2.0 DBUS_INTERFACES += com.ubuntu.MenuRegistrar.xml HEADERS += \ theme.h \ gmenumodelexporter.h \ gmenumodelplatformmenu.h \ logging.h \ menuregistrar.h \ registry.h \ themeplugin.h \ qtubuntuextraactionhandler.h \ ../shared/ubuntutheme.h SOURCES += \ theme.cpp \ gmenumodelexporter.cpp \ gmenumodelplatformmenu.cpp \ menuregistrar.cpp \ registry.cpp \ themeplugin.cpp \ qtubuntuextraactionhandler.cpp OTHER_FILES += \ ubuntuappmenu.json # Installation path target.path += $$[QT_INSTALL_PLUGINS]/platformthemes INSTALLS += target ./src/ubuntumirclient/0000755000004100000410000000000013127642604015270 5ustar www-datawww-data./src/ubuntumirclient/qmirclientwindow.cpp0000644000004100000410000011456513127642604021407 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2014-2017 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // Local #include "qmirclientwindow.h" #include "qmirclientdebugextension.h" #include "qmirclientnativeinterface.h" #include "qmirclientinput.h" #include "qmirclientintegration.h" #include "qmirclientscreen.h" #include "qmirclientlogging.h" #include #include // Qt #include #include #include #include #include #include #include Q_LOGGING_CATEGORY(mirclientBufferSwap, "qt.qpa.mirclient.bufferSwap", QtWarningMsg) namespace { const Qt::WindowType InputMethodWindowType = (Qt::WindowType)(0x00000080 | Qt::WindowType::Window); // Qt has no such thing const Qt::WindowType LowChromeWindowHint = (Qt::WindowType)0x00800000; struct MirSpecDeleter { void operator()(MirWindowSpec *spec) { mir_window_spec_release(spec); } }; using Spec = std::unique_ptr; EGLNativeWindowType nativeWindowFor(MirWindow *surf) { auto stream = mir_window_get_buffer_stream(surf); return reinterpret_cast(mir_buffer_stream_get_egl_native_window(stream)); } const char *qtWindowStateToStr(Qt::WindowState state) { switch (state) { case Qt::WindowNoState: return "NoState"; case Qt::WindowFullScreen: return "FullScreen"; case Qt::WindowMaximized: return "Maximized"; case Qt::WindowMinimized: return "Minimized"; case Qt::WindowActive: return "Active"; } Q_UNREACHABLE(); } const char *mirWindowStateToStr(MirWindowState windowState) { switch (windowState) { case mir_window_state_unknown: return "unknown"; case mir_window_state_restored: return "restored"; case mir_window_state_minimized: return "minimized"; case mir_window_state_maximized: return "vertmaximized"; case mir_window_state_vertmaximized: return "vertmaximized"; case mir_window_state_fullscreen: return "fullscreen"; case mir_window_state_horizmaximized: return "horizmaximized"; case mir_window_state_hidden: return "hidden"; case mir_window_states: Q_UNREACHABLE(); } Q_UNREACHABLE(); } const char *mirPixelFormatToStr(MirPixelFormat pixelFormat) { switch (pixelFormat) { case mir_pixel_format_invalid: return "invalid"; case mir_pixel_format_abgr_8888: return "ABGR8888"; case mir_pixel_format_xbgr_8888: return "XBGR8888"; case mir_pixel_format_argb_8888: return "ARGB8888"; case mir_pixel_format_xrgb_8888: return "XRGB8888"; case mir_pixel_format_bgr_888: return "BGR888"; case mir_pixel_format_rgb_888: return "RGB888"; case mir_pixel_format_rgb_565: return "RGB565"; case mir_pixel_format_rgba_5551: return "RGBA5551"; case mir_pixel_format_rgba_4444: return "RGBA4444"; case mir_pixel_formats: Q_UNREACHABLE(); } Q_UNREACHABLE(); } const char *mirWindowTypeToStr(MirWindowType type) { switch (type) { case mir_window_type_normal: return "Normal"; /**< AKA "regular" */ case mir_window_type_utility: return "Utility"; /**< AKA "floating regular" */ case mir_window_type_dialog: return "Dialog"; case mir_window_type_gloss: return "Gloss"; case mir_window_type_freestyle: return "Freestyle"; case mir_window_type_menu: return "Menu"; case mir_window_type_inputmethod: return "Input Method"; /**< AKA "OSK" or handwriting etc. */ case mir_window_type_satellite: return "Satellite"; /**< AKA "toolbox"/"toolbar" */ case mir_window_type_tip: return "Tip"; /**< AKA "tooltip" */ case mir_window_types: Q_UNREACHABLE(); } return ""; } MirWindowState qtWindowStateToMirWindowState(Qt::WindowState state) { switch (state) { case Qt::WindowNoState: case Qt::WindowActive: return mir_window_state_restored; case Qt::WindowFullScreen: return mir_window_state_fullscreen; case Qt::WindowMaximized: return mir_window_state_maximized; case Qt::WindowMinimized: return mir_window_state_minimized; } return mir_window_state_unknown; // should never be reached } MirWindowType qtWindowTypeToMirWindowType(Qt::WindowType type) { switch (type & Qt::WindowType_Mask) { case Qt::Dialog: return mir_window_type_dialog; case Qt::Sheet: case Qt::Drawer: return mir_window_type_utility; case Qt::Popup: return mir_window_type_menu; case Qt::Tool: return mir_window_type_satellite; case Qt::ToolTip: return mir_window_type_tip; case Qt::SplashScreen: return mir_window_type_freestyle; case InputMethodWindowType: return mir_window_type_inputmethod; case Qt::Window: default: return mir_window_type_normal; } } WId makeId() { static int id = 1; return id++; } QMirClientWindow *transientParentFor(QWindow *window) { QWindow *parent = window->transientParent(); return parent ? static_cast(parent->handle()) : nullptr; } bool requiresParent(const MirWindowType type) { switch (type) { case mir_window_type_dialog: //FIXME - not quite what the specification dictates, but is what Mir's api dictates case mir_window_type_utility: case mir_window_type_gloss: case mir_window_type_menu: case mir_window_type_satellite: case mir_window_type_tip: return true; default: return false; } } bool requiresParent(const Qt::WindowType type) { return requiresParent(qtWindowTypeToMirWindowType(type)); } Spec makeSurfaceSpec(QWindow *window, MirPixelFormat pixelFormat, QMirClientWindow *parentWindowHandle, MirConnection *connection) { const auto geometry = window->geometry(); const int width = geometry.width() > 0 ? geometry.width() : 1; const int height = geometry.height() > 0 ? geometry.height() : 1; auto type = qtWindowTypeToMirWindowType(window->type()); MirRectangle location{geometry.x(), geometry.y(), 0, 0}; MirWindow *parent = nullptr; if (parentWindowHandle) { parent = parentWindowHandle->mirWindow(); // Qt uses absolute positioning, but Mir positions surfaces relative to parent. location.top -= parentWindowHandle->geometry().top(); location.left -= parentWindowHandle->geometry().left(); } Spec spec; switch (type) { case mir_window_type_menu: spec = Spec{mir_create_menu_window_spec(connection, width, height, parent, &location, mir_edge_attachment_any)}; break; case mir_window_type_dialog: if (parent) { spec = Spec{mir_create_modal_dialog_window_spec(connection, width, height, parent)}; } else { spec = Spec{mir_create_dialog_window_spec(connection, width, height)}; } break; case mir_window_type_utility: // mir missing mir_create_utility_window_spec spec = Spec{mir_create_normal_window_spec(connection, width, height)}; mir_window_spec_set_type(spec.get(), mir_window_type_utility); break; case mir_window_type_tip: #if MIR_CLIENT_VERSION < MIR_VERSION_NUMBER(3, 4, 0) spec = Spec{mir_connection_create_spec_for_tooltip(connection, width, height, pixelFormat, parent, &location)}; #else spec = Spec{mir_create_tip_window_spec(connection, width, height, parent, &location, mir_edge_attachment_any)}; #endif break; case mir_window_type_inputmethod: spec = Spec{mir_create_input_method_window_spec(connection, width, height)}; break; case mir_window_type_satellite: // There's no helper function for satellite windows. Guess they're not very popular spec = Spec{mir_create_window_spec(connection)}; mir_window_spec_set_type(spec.get(), mir_window_type_satellite); mir_window_spec_set_buffer_usage(spec.get(), mir_buffer_usage_hardware); mir_window_spec_set_parent(spec.get(), parent); mir_window_spec_set_width(spec.get(), width); mir_window_spec_set_height(spec.get(), height); break; default: spec = Spec{mir_create_normal_window_spec(connection, width, height)}; break; } mir_window_spec_set_pixel_format(spec.get(), pixelFormat); qCDebug(mirclient, "makeSurfaceSpec(window=%p): %s spec (type=0x%x, position=(%d, %d)px, size=(%dx%d)px)", window, mirWindowTypeToStr(type), window->type(), location.left, location.top, width, height); return spec; } void setSizingConstraints(MirWindowSpec *spec, const QSize& minSize, const QSize& maxSize, const QSize& increment) { mir_window_spec_set_min_width(spec, minSize.width()); mir_window_spec_set_min_height(spec, minSize.height()); if (maxSize.width() >= minSize.width()) { mir_window_spec_set_max_width(spec, maxSize.width()); } if (maxSize.height() >= minSize.height()) { mir_window_spec_set_max_height(spec, maxSize.height()); } if (increment.width() > 0) { mir_window_spec_set_width_increment(spec, increment.width()); } if (increment.height() > 0) { mir_window_spec_set_height_increment(spec, increment.height()); } } void setMask(MirWindowSpec *spec, const QRegion& mask) { const int count = mask.rectCount(); if (count == 0) { mir_window_spec_set_input_shape(spec, nullptr, 0); return; } // Convert the QRegion into a list of MirRectangles auto rects = new MirRectangle[count]; int i=0; for (const auto &rect : mask.rects()) { rects[i].left = rect.x(); rects[i].top = rect.y(); rects[i].width = (unsigned int) rect.width(); rects[i].height = (unsigned int) rect.height(); i++; } mir_window_spec_set_input_shape(spec, rects, count); } MirWindow *createMirWindow(QWindow *window, int mirOutputId, QMirClientWindow *parentWindowHandle, MirPixelFormat pixelFormat, MirConnection *connection, MirWindowEventCallback inputCallback, void *inputContext) { auto spec = makeSurfaceSpec(window, pixelFormat, parentWindowHandle, connection); // Install event handler as early as possible mir_window_spec_set_event_handler(spec.get(), inputCallback, inputContext); const auto title = window->title().toUtf8(); mir_window_spec_set_name(spec.get(), title.constData()); setSizingConstraints(spec.get(), window->minimumSize(), window->maximumSize(), window->sizeIncrement()); setMask(spec.get(), window->mask()); if (window->windowState() == Qt::WindowFullScreen) { mir_window_spec_set_fullscreen_on_output(spec.get(), mirOutputId); } if (window->flags() & LowChromeWindowHint) { mir_window_spec_set_shell_chrome(spec.get(), mir_shell_chrome_low); } if (!window->isVisible()) { mir_window_spec_set_state(spec.get(), mir_window_state_hidden); } auto surface = mir_create_window_sync(spec.get()); Q_ASSERT(mir_window_is_valid(surface)); return surface; } QMirClientWindow *getParentIfNecessary(QWindow *window, QMirClientInput *input) { QMirClientWindow *parentWindowHandle = nullptr; if (requiresParent(window->type())) { parentWindowHandle = transientParentFor(window); if (parentWindowHandle == nullptr) { // NOTE: Mir requires this surface have a parent. Try using the last surface to receive input as that will // most likely be the one that caused this surface to be created parentWindowHandle = input->lastInputWindow(); } } return parentWindowHandle; } MirPixelFormat disableAlphaBufferIfPossible(MirPixelFormat pixelFormat) { switch (pixelFormat) { case mir_pixel_format_abgr_8888: return mir_pixel_format_xbgr_8888; case mir_pixel_format_argb_8888: return mir_pixel_format_xrgb_8888; default: // can do nothing, leave it alone return pixelFormat; } } // FIXME - in order to work around https://bugs.launchpad.net/mir/+bug/1346633 // we need to guess the panel height (3GU) int panelHeight() { const int defaultGridUnit = 8; int gridUnit = defaultGridUnit; QByteArray gridUnitString = qgetenv("GRID_UNIT_PX"); if (!gridUnitString.isEmpty()) { bool ok; gridUnit = gridUnitString.toInt(&ok); if (!ok) { gridUnit = defaultGridUnit; } } return gridUnit * 3; } } //namespace class UbuntuSurface { public: UbuntuSurface(QMirClientWindow *platformWindow, EGLDisplay display, QMirClientInput *input, MirConnection *connection); ~UbuntuSurface(); UbuntuSurface(const UbuntuSurface &) = delete; UbuntuSurface& operator=(const UbuntuSurface &) = delete; void updateGeometry(const QRect &newGeometry); void updateTitle(const QString& title); void setSizingConstraints(const QSize& minSize, const QSize& maxSize, const QSize& increment); void setMask(const QRegion &mask); void onSwapBuffersDone(); void handleSurfaceResized(int width, int height); int needsRepaint() const; MirWindowState state() const { return mir_window_get_state(mMirWindow); } void setState(MirWindowState state); MirWindowType type() const { return mir_window_get_type(mMirWindow); } void setShellChrome(MirShellChrome shellChrome); EGLSurface eglSurface() const { return mEglSurface; } MirWindow *mirWindow() const { return mMirWindow; } void setSurfaceParent(MirWindow*); bool hasParent() const { return mParented; } QSurfaceFormat format() const { return mFormat; } bool mNeedsExposeCatchup; QString persistentSurfaceId(); private: static void surfaceEventCallback(MirWindow* surface, const MirEvent *event, void* context); void postEvent(const MirEvent *event); QWindow * const mWindow; QMirClientWindow * const mPlatformWindow; QMirClientInput * const mInput; MirConnection * const mConnection; QMirClientWindow * mParentWindowHandle{nullptr}; MirWindow* mMirWindow; const EGLDisplay mEglDisplay; EGLSurface mEglSurface; bool mNeedsRepaint; bool mParented; QSize mBufferSize; QSurfaceFormat mFormat; MirPixelFormat mPixelFormat; QMutex mTargetSizeMutex; QSize mTargetSize; MirShellChrome mShellChrome; QString mPersistentIdStr; }; UbuntuSurface::UbuntuSurface(QMirClientWindow *platformWindow, EGLDisplay display, QMirClientInput *input, MirConnection *connection) : mWindow(platformWindow->window()) , mPlatformWindow(platformWindow) , mInput(input) , mConnection(connection) , mEglDisplay(display) , mNeedsRepaint(false) , mParented(mWindow->transientParent() || mWindow->parent()) , mFormat(mWindow->requestedFormat()) , mShellChrome(mWindow->flags() & LowChromeWindowHint ? mir_shell_chrome_low : mir_shell_chrome_normal) { // Have Qt choose most suitable EGLConfig for the requested surface format, and update format to reflect it EGLConfig config = q_configFromGLFormat(display, mFormat, true); if (config == 0) { // Older Intel Atom-based devices only support OpenGL 1.4 compatibility profile but by default // QML asks for at least OpenGL 2.0. The XCB GLX backend ignores this request and returns a // 1.4 context, but the XCB EGL backend tries to honor it, and fails. The 1.4 context appears to // have sufficient capabilities on MESA (i915) to render correctly however. So reduce the default // requested OpenGL version to 1.0 to ensure EGL will give us a working context (lp:1549455). static const bool isMesa = QString(eglQueryString(display, EGL_VENDOR)).contains(QStringLiteral("Mesa")); if (isMesa) { qCDebug(mirclientGraphics, "Attempting to choose OpenGL 1.4 context which may suit Mesa"); mFormat.setMajorVersion(1); mFormat.setMinorVersion(4); config = q_configFromGLFormat(display, mFormat, true); } } if (config == 0) { qCritical() << "Qt failed to choose a suitable EGLConfig to suit the surface format" << mFormat; } mFormat = q_glFormatFromConfig(display, config, mFormat); // Have Mir decide the pixel format most suited to the chosen EGLConfig. This is the only way // Mir will know what EGLConfig has been chosen - it cannot deduce it from the buffers. mPixelFormat = mir_connection_get_egl_pixel_format(connection, display, config); // But the chosen EGLConfig might have an alpha buffer enabled, even if not requested by the client. // If that's the case, try to edit the chosen pixel format in order to disable the alpha buffer. // This is an optimization for the compositor, as it can avoid blending this surface. if (mWindow->requestedFormat().alphaBufferSize() < 0) { mPixelFormat = disableAlphaBufferIfPossible(mPixelFormat); } const auto outputId = static_cast(mWindow->screen()->handle())->mirOutputId(); mParentWindowHandle = getParentIfNecessary(mWindow, input); mMirWindow = createMirWindow(mWindow, outputId, mParentWindowHandle, mPixelFormat, connection, surfaceEventCallback, this); mEglSurface = eglCreateWindowSurface(mEglDisplay, config, nativeWindowFor(mMirWindow), nullptr); mNeedsExposeCatchup = mir_window_get_visibility(mMirWindow) == mir_window_visibility_occluded; // Window manager can give us a final size different from what we asked for // so let's check what we ended up getting MirWindowParameters parameters; mir_window_get_parameters(mMirWindow, ¶meters); auto geom = mWindow->geometry(); geom.setWidth(parameters.width); geom.setHeight(parameters.height); // Assume that the buffer size matches the surface size at creation time mBufferSize = geom.size(); platformWindow->QPlatformWindow::setGeometry(geom); QWindowSystemInterface::handleGeometryChange(mWindow, geom); qCDebug(mirclient) << "Created surface with geometry:" << geom << "title:" << mWindow->title(); qCDebug(mirclientGraphics) << "Requested format:" << mWindow->requestedFormat() << "\nActual format:" << mFormat << "with associated Mir pixel format:" << mirPixelFormatToStr(mPixelFormat); } UbuntuSurface::~UbuntuSurface() { if (mEglSurface != EGL_NO_SURFACE) eglDestroySurface(mEglDisplay, mEglSurface); if (mMirWindow) { mir_window_release_sync(mMirWindow); } } void UbuntuSurface::updateGeometry(const QRect &newGeometry) { auto spec = Spec{mir_create_window_spec(mConnection)}; mir_window_spec_set_width(spec.get(), newGeometry.width()); mir_window_spec_set_height(spec.get(), newGeometry.height()); MirRectangle mirRect {0,0,0,0}; if (mParentWindowHandle) { qCDebug(mirclient,"updateGeometry(window=%p, x=%d, y=%d, width=%d, height=%d, child)", mWindow, newGeometry.x(), newGeometry.y(), newGeometry.width(), newGeometry.height()); mirRect.left = newGeometry.x() - mParentWindowHandle->window()->x(); mirRect.top = newGeometry.y() - mParentWindowHandle->window()->y(); } else { qCDebug(mirclient,"updateGeometry(window=%p, x=%d, y=%d, width=%d, height=%d, top-level)", mWindow, newGeometry.x(), newGeometry.y(), newGeometry.width(), newGeometry.height()); mirRect.left = newGeometry.x(); mirRect.top = newGeometry.y(); } mir_window_spec_set_placement(spec.get(), &mirRect, mir_placement_gravity_northwest /* rect_gravity */, mir_placement_gravity_northwest /* surface_gravity */, (MirPlacementHints)0, 0 /* offset_dx */, 0 /* offset_dy */); mir_window_apply_spec(mMirWindow, spec.get()); } void UbuntuSurface::updateTitle(const QString& newTitle) { const auto title = newTitle.toUtf8(); Spec spec{mir_create_window_spec(mConnection)}; mir_window_spec_set_name(spec.get(), title.constData()); mir_window_apply_spec(mMirWindow, spec.get()); } void UbuntuSurface::setSizingConstraints(const QSize& minSize, const QSize& maxSize, const QSize& increment) { Spec spec{mir_create_window_spec(mConnection)}; ::setSizingConstraints(spec.get(), minSize, maxSize, increment); mir_window_apply_spec(mMirWindow, spec.get()); } void UbuntuSurface::handleSurfaceResized(int width, int height) { QMutexLocker lock(&mTargetSizeMutex); // mir's resize event is mainly a signal that we need to redraw our content. We use the // width/height as identifiers to figure out if this is the latest surface resize event // that has posted, discarding any old ones. This avoids issuing too many redraw events. // see TODO in postEvent as the ideal way we should handle this. // The actual buffer size may or may have not changed at this point, so let the rendering // thread drive the window geometry updates. mNeedsRepaint = mTargetSize.width() == width && mTargetSize.height() == height; } int UbuntuSurface::needsRepaint() const { if (mNeedsRepaint) { if (mTargetSize != mBufferSize) { //If the buffer hasn't changed yet, we need at least two redraws, //once to get the new buffer size and propagate the geometry changes //and the second to redraw the content at the new size return 2; } else { // The buffer size has already been updated so we only need one redraw // to render at the new size return 1; } } return 0; } void UbuntuSurface::setState(MirWindowState state) { mir_window_set_state(mMirWindow, state); } void UbuntuSurface::setShellChrome(MirShellChrome chrome) { if (chrome != mShellChrome) { auto spec = Spec{mir_create_window_spec(mConnection)}; mir_window_spec_set_shell_chrome(spec.get(), chrome); mir_window_apply_spec(mMirWindow, spec.get()); mShellChrome = chrome; } } void UbuntuSurface::onSwapBuffersDone() { static int sFrameNumber = 0; ++sFrameNumber; EGLint eglSurfaceWidth = -1; EGLint eglSurfaceHeight = -1; eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, &eglSurfaceWidth); eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, &eglSurfaceHeight); const bool validSize = eglSurfaceWidth > 0 && eglSurfaceHeight > 0; if (validSize && (mBufferSize.width() != eglSurfaceWidth || mBufferSize.height() != eglSurfaceHeight)) { qCDebug(mirclientBufferSwap, "onSwapBuffersDone(window=%p) [%d] - size changed (%d, %d) => (%d, %d)", mWindow, sFrameNumber, mBufferSize.width(), mBufferSize.height(), eglSurfaceWidth, eglSurfaceHeight); mBufferSize.rwidth() = eglSurfaceWidth; mBufferSize.rheight() = eglSurfaceHeight; QRect newGeometry = mPlatformWindow->geometry(); newGeometry.setSize(mBufferSize); mPlatformWindow->QPlatformWindow::setGeometry(newGeometry); QWindowSystemInterface::handleGeometryChange(mWindow, newGeometry); } else { qCDebug(mirclientBufferSwap, "onSwapBuffersDone(window=%p) [%d] - buffer size (%d,%d)", mWindow, sFrameNumber, mBufferSize.width(), mBufferSize.height()); } } void UbuntuSurface::surfaceEventCallback(MirWindow *surface, const MirEvent *event, void* context) { Q_UNUSED(surface); Q_ASSERT(context != nullptr); auto s = static_cast(context); s->postEvent(event); } void UbuntuSurface::postEvent(const MirEvent *event) { const auto eventType = mir_event_get_type(event); if (mir_event_type_resize == eventType) { // TODO: The current event queue just accumulates all resize events; // It would be nicer if we could update just one event if that event has not been dispatched. // As a workaround, we use the width/height as an identifier of this latest event // so the event handler (handleSurfaceResized) can discard/ignore old ones. const auto resizeEvent = mir_event_get_resize_event(event); const auto width = mir_resize_event_get_width(resizeEvent); const auto height = mir_resize_event_get_height(resizeEvent); qCDebug(mirclient, "resizeEvent(window=%p, width=%d, height=%d)", mWindow, width, height); QMutexLocker lock(&mTargetSizeMutex); mTargetSize.rwidth() = width; mTargetSize.rheight() = height; } mInput->postEvent(mPlatformWindow, event); } void UbuntuSurface::setSurfaceParent(MirWindow* parent) { qCDebug(mirclient, "setSurfaceParent(window=%p)", mWindow); mParented = true; Spec spec{mir_create_window_spec(mConnection)}; mir_window_spec_set_parent(spec.get(), parent); mir_window_apply_spec(mMirWindow, spec.get()); } void UbuntuSurface::setMask(const QRegion ®ion) { qCDebug(mirclient).nospace() << "setMask(window=" << mWindow << ", region=" << region << ")"; Spec spec{mir_create_window_spec(mConnection)}; ::setMask(spec.get(), region); mir_window_apply_spec(mMirWindow, spec.get()); } QString UbuntuSurface::persistentSurfaceId() { if (mPersistentIdStr.isEmpty()) { auto id = mir_window_request_window_id_sync(mMirWindow); mPersistentIdStr = mir_window_id_as_string(id); mir_window_id_release(id); } return mPersistentIdStr; } Q_DECLARE_METATYPE(QPlatformWindow*) QMirClientWindow::QMirClientWindow(QWindow *w, QMirClientInput *input, QMirClientNativeInterface *native, QMirClientAppStateController *appState, EGLDisplay eglDisplay, MirConnection *mirConnection, QMirClientDebugExtension *debugExt) : QObject(nullptr) , QPlatformWindow(w) , mId(makeId()) , mWindowState(w->windowState()) , mWindowFlags(w->flags()) , mWindowVisible(false) , mAppStateController(appState) , mDebugExtention(debugExt) , mNativeInterface(native) , mSurface(new UbuntuSurface{this, eglDisplay, input, mirConnection}) , mScale(1.0) , mFormFactor(mir_form_factor_unknown) { static bool metaTypeRegistered = false; if (Q_UNLIKELY(!metaTypeRegistered)) { qRegisterMetaType(); metaTypeRegistered = true; } mWindowExposed = mSurface->mNeedsExposeCatchup == false; qCDebug(mirclient, "QMirClientWindow(window=%p, screen=%p, input=%p, surf=%p) with title '%s'", w, w->screen()->handle(), input, mSurface.get(), qPrintable(window()->title())); updatePanelHeightHack(mSurface->state() != mir_window_state_fullscreen); // queue the windowPropertyChanged signal. If it's emitted directly, the platformWindow will not yet be set for the window. QMetaObject::invokeMethod(mNativeInterface, "windowPropertyChanged", Qt::QueuedConnection, Q_ARG(QPlatformWindow*, this), Q_ARG(QString, "persistentSurfaceId")); } QMirClientWindow::~QMirClientWindow() { qCDebug(mirclient, "~QMirClientWindow(window=%p)", this); } void QMirClientWindow::handleSurfaceResized(int width, int height) { QMutexLocker lock(&mMutex); qCDebug(mirclient, "handleSurfaceResize(window=%p, size=(%dx%d)px", window(), width, height); mSurface->handleSurfaceResized(width, height); // This resize event could have occurred just after the last buffer swap for this window. // This means the client may still be holding a buffer with the older size. The first redraw call // will then render at the old size. After swapping the client now will get a new buffer with the // updated size but it still needs re-rendering so another redraw may be needed. // A mir API to drop the currently held buffer would help here, so that we wouldn't have to redraw twice auto const numRepaints = mSurface->needsRepaint(); lock.unlock(); qCDebug(mirclient, "handleSurfaceResize(window=%p) redraw %d times", window(), numRepaints); for (int i = 0; i < numRepaints; i++) { qCDebug(mirclient, "handleSurfaceResize(window=%p) repainting size=(%dx%d)dp", window(), geometry().size().width(), geometry().size().height()); QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size())); } } void QMirClientWindow::handleSurfaceExposeChange(bool exposed) { QMutexLocker lock(&mMutex); qCDebug(mirclient, "handleSurfaceExposeChange(window=%p, exposed=%s)", window(), exposed ? "true" : "false"); mSurface->mNeedsExposeCatchup = false; if (mWindowExposed == exposed) return; mWindowExposed = exposed; lock.unlock(); QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size())); } void QMirClientWindow::handleSurfaceFocusChanged(bool focused) { qCDebug(mirclient, "handleSurfaceFocusChanged(window=%p, focused=%d)", window(), focused); if (focused) { mAppStateController->setWindowFocused(true); QWindowSystemInterface::handleWindowActivated(window(), Qt::ActiveWindowFocusReason); } else { // Flush events so that we update QGuiApplicationPrivate::focus_window first QWindowSystemInterface::flushWindowSystemEvents(QEventLoop::ExcludeUserInputEvents); if (window() == QGuiApplicationPrivate::focus_window) { // don't handle unfocus if this window wasn't currently focused. QWindowSystemInterface::handleWindowActivated(nullptr, Qt::ActiveWindowFocusReason); mAppStateController->setWindowFocused(false); } } } void QMirClientWindow::handleSurfaceVisibilityChanged(bool visible) { qCDebug(mirclient, "handleSurfaceVisibilityChanged(window=%p, visible=%d)", window(), visible); if (mWindowVisible == visible) return; mWindowVisible = visible; QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size())); } void QMirClientWindow::handleSurfaceStateChanged(Qt::WindowState state) { qCDebug(mirclient, "handleSurfaceStateChanged(window=%p, %s)", window(), qtWindowStateToStr(state)); if (mWindowState == state) return; mWindowState = state; QWindowSystemInterface::handleWindowStateChanged(window(), state); } void QMirClientWindow::setWindowState(Qt::WindowState state) { QMutexLocker lock(&mMutex); qCDebug(mirclient, "setWindowState(window=%p, %s)", this, qtWindowStateToStr(state)); if (mWindowState == state) return; mWindowState = state; lock.unlock(); updateSurfaceState(); } void QMirClientWindow::setWindowFlags(Qt::WindowFlags flags) { QMutexLocker lock(&mMutex); qCDebug(mirclient, "setWindowFlags(window=%p, 0x%x)", this, (int)flags); if (mWindowFlags == flags) return; mWindowFlags = flags; mSurface->setShellChrome(mWindowFlags & LowChromeWindowHint ? mir_shell_chrome_low : mir_shell_chrome_normal); } /* FIXME: Mir does not let clients know the position of their windows in the virtual desktop space. So we have this ugly hack that assumes a phone situation where the window is always on the top-left corner, right below the indicators panel if not in fullscreen. */ void QMirClientWindow::updatePanelHeightHack(bool enable) { if ((window()->type() & Qt::WindowType_Mask) != Qt::Window) { // only plain windows get the hack return; } QMutexLocker lock(&mMutex); QRect newGeometry = geometry(); if (enable) { newGeometry.moveTop(panelHeight()); } else { newGeometry.moveTop(0); } if (newGeometry != geometry()) { lock.unlock(); QPlatformWindow::setGeometry(newGeometry); QWindowSystemInterface::handleGeometryChange(window(), newGeometry); } } QRect QMirClientWindow::geometry() const { if (mDebugExtention) { auto geom = QPlatformWindow::geometry(); geom.moveTopLeft(mDebugExtention->mapWindowPointToScreen(mSurface->mirWindow(), QPoint(0,0))); return geom; } else { return QPlatformWindow::geometry(); } } void QMirClientWindow::setGeometry(const QRect &rect) { QMutexLocker lock(&mMutex); if (window()->windowState() == Qt::WindowFullScreen || window()->windowState() == Qt::WindowMaximized) { qCDebug(mirclient, "setGeometry(window=%p) - not resizing, window is maximized or fullscreen", window()); return; } qCDebug(mirclient, "setGeometry (window=%p, position=(%d, %d)dp, size=(%dx%d)dp)", window(), rect.x(), rect.y(), rect.width(), rect.height()); // Immediately update internal geometry so Qt believes position updated QRect newPosition(geometry()); newPosition.moveTo(rect.topLeft()); QPlatformWindow::setGeometry(newPosition); mSurface->updateGeometry(rect); // Note: don't call handleGeometryChange here, wait to see what Mir replies with. } void QMirClientWindow::setVisible(bool visible) { QMutexLocker lock(&mMutex); qCDebug(mirclient, "setVisible (window=%p, visible=%s)", window(), visible ? "true" : "false"); if (mWindowVisible == visible) return; mWindowVisible = visible; if (visible) { if (!mSurface->hasParent() && window()->type() == Qt::Dialog) { // The dialog may have been parented after creation time // so morph it into a modal dialog auto parent = transientParentFor(window()); if (parent) { mSurface->setSurfaceParent(parent->mirWindow()); } } } lock.unlock(); updateSurfaceState(); QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size())); } void QMirClientWindow::setWindowTitle(const QString& title) { QMutexLocker lock(&mMutex); qCDebug(mirclient, "setWindowTitle(window=%p) title=%s)", window(), title.toUtf8().constData()); mSurface->updateTitle(title); } void QMirClientWindow::propagateSizeHints() { QMutexLocker lock(&mMutex); const auto win = window(); qCDebug(mirclient, "propagateSizeHints(window=%p) min(%d,%d), max(%d,%d) increment(%d, %d)", win, win->minimumSize().width(), win->minimumSize().height(), win->maximumSize().width(), win->maximumSize().height(), win->sizeIncrement().width(), win->sizeIncrement().height()); mSurface->setSizingConstraints(win->minimumSize(), win->maximumSize(), win->sizeIncrement()); } bool QMirClientWindow::isExposed() const { // mNeedsExposeCatchup because we need to render a frame to get the expose surface event from mir. return mWindowVisible && (mWindowExposed || (mSurface && mSurface->mNeedsExposeCatchup)); } void QMirClientWindow::setMask(const QRegion ®ion) { mSurface->setMask(region); } QSurfaceFormat QMirClientWindow::format() const { return mSurface->format(); } QPoint QMirClientWindow::mapToGlobal(const QPoint &pos) const { if (mDebugExtention) { return mDebugExtention->mapWindowPointToScreen(mSurface->mirWindow(), pos); } else { return pos; } } void* QMirClientWindow::eglSurface() const { return mSurface->eglSurface(); } MirWindow *QMirClientWindow::mirWindow() const { return mSurface->mirWindow(); } WId QMirClientWindow::winId() const { return mId; } void QMirClientWindow::onSwapBuffersDone() { QMutexLocker lock(&mMutex); mSurface->onSwapBuffersDone(); if (mSurface->mNeedsExposeCatchup) { mSurface->mNeedsExposeCatchup = false; mWindowExposed = false; lock.unlock(); QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size())); } } void QMirClientWindow::handleScreenPropertiesChange(MirFormFactor formFactor, float scale) { // Update the scale & form factor native-interface properties for the windows affected // as there is no convenient way to emit signals for those custom properties on a QScreen if (formFactor != mFormFactor) { mFormFactor = formFactor; Q_EMIT mNativeInterface->windowPropertyChanged(this, QStringLiteral("formFactor")); } if (!qFuzzyCompare(scale, mScale)) { mScale = scale; // update the panelHeight hack since it depends on GU updatePanelHeightHack(mSurface->state() != mir_window_state_fullscreen); Q_EMIT mNativeInterface->windowPropertyChanged(this, QStringLiteral("scale")); } } void QMirClientWindow::updateSurfaceState() { QMutexLocker lock(&mMutex); MirWindowState newState = mWindowVisible ? qtWindowStateToMirWindowState(mWindowState) : mir_window_state_hidden; qCDebug(mirclient, "updateSurfaceState (window=%p, surfaceState=%s)", window(), mirWindowStateToStr(newState)); if (newState != mSurface->state()) { mSurface->setState(newState); lock.unlock(); updatePanelHeightHack(newState != mir_window_state_fullscreen); } } QString QMirClientWindow::persistentSurfaceId() { return mSurface->persistentSurfaceId(); } ./src/ubuntumirclient/qmirclientorientationchangeevent_p.h0000644000004100000410000000457413127642576024635 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTORIENTATIONCHANGEEVENT_P_H #define QMIRCLIENTORIENTATIONCHANGEEVENT_P_H #include #include "qmirclientlogging.h" class OrientationChangeEvent : public QEvent { public: enum Orientation { TopUp, LeftUp, TopDown, RightUp }; OrientationChangeEvent(QEvent::Type type, Orientation orientation) : QEvent(type) , mOrientation(orientation) { } static const QEvent::Type mType; Orientation mOrientation; }; #endif // QMIRCLIENTORIENTATIONCHANGEEVENT_P_H ./src/ubuntumirclient/qmirclientintegration.cpp0000644000004100000410000003532413127642604022416 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2014-2017 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // Local #include "qmirclientintegration.h" #include "qmirclientbackingstore.h" #include "qmirclientclipboard.h" #include "qmirclientdebugextension.h" #include "qmirclientdesktopwindow.h" #include "qmirclientglcontext.h" #include "qmirclientinput.h" #include "qmirclientlogging.h" #include "qmirclientnativeinterface.h" #include "qmirclientscreen.h" #include "qmirclientwindow.h" #include "../shared/ubuntutheme.h" // Qt #include #include #include #include #include #include #include #include #include #include #include #include // platform-api #include #include #include static void resumedCallback(const UApplicationOptions */*options*/, void *context) { auto integration = static_cast(context); integration->appStateController()->setResumed(); } static void aboutToStopCallback(UApplicationArchive */*archive*/, void *context) { auto integration = static_cast(context); auto inputContext = integration->inputContext(); if (inputContext) { inputContext->hideInputPanel(); } else { qCWarning(mirclient) << "aboutToStopCallback(): no input context"; } integration->appStateController()->setSuspended(); } QMirClientClientIntegration::QMirClientClientIntegration(int argc, char **argv) : QPlatformIntegration() , mNativeInterface(new QMirClientNativeInterface(this)) , mFontDb(new QGenericUnixFontDatabase) , mServices(new QMirClientPlatformServices) , mAppStateController(new QMirClientAppStateController) , mScaleFactor(1.0) { QByteArray sessionName; { QStringList args = QCoreApplication::arguments(); setupOptions(args); sessionName = generateSessionName(args); setupDescription(sessionName); } // Create new application instance mInstance = u_application_instance_new_from_description_with_options(mDesc, mOptions); if (mInstance == nullptr) { qCritical("[QPA] QMirClientClientIntegration: connection to Mir server failed.\n"); // TODO: add API to platform-api to fetch Mir's error message (bug:1655970). // Workaround by retrying the connection here in order to get the message. auto mirConnection = mir_connect_sync(nullptr, sessionName.data()); qCritical("Mir returned: \"%s\"", mir_connection_get_error_message(mirConnection)); mir_connection_release(mirConnection); exit(EXIT_FAILURE); } mMirConnection = u_application_instance_get_mir_connection(mInstance); // Choose the default surface format suited to the Mir platform QSurfaceFormat defaultFormat; defaultFormat.setRedBufferSize(8); defaultFormat.setGreenBufferSize(8); defaultFormat.setBlueBufferSize(8); QSurfaceFormat::setDefaultFormat(defaultFormat); // Initialize EGL. mEglNativeDisplay = mir_connection_get_egl_native_display(mMirConnection); ASSERT((mEglDisplay = eglGetDisplay(mEglNativeDisplay)) != EGL_NO_DISPLAY); ASSERT(eglInitialize(mEglDisplay, nullptr, nullptr) == EGL_TRUE); // Has debug mode been requsted, either with "-testability" switch or QT_LOAD_TESTABILITY env var bool testability = qEnvironmentVariableIsSet("QT_LOAD_TESTABILITY"); for (int i=1; !testability && iisEnabled()) { mDebugExtension.reset(); } } } void QMirClientClientIntegration::initialize() { // Init the ScreenObserver mScreenObserver.reset(new QMirClientScreenObserver(mMirConnection)); connect(mScreenObserver.data(), &QMirClientScreenObserver::screenAdded, [this](QMirClientScreen *screen) { this->screenAdded(screen); }); connect(mScreenObserver.data(), &QMirClientScreenObserver::screenRemoved, this, &QMirClientClientIntegration::destroyScreen); Q_FOREACH (auto screen, mScreenObserver->screens()) { screenAdded(screen); } // Initialize input. mInput = new QMirClientInput(this); mInputContext = QPlatformInputContextFactory::create(); // compute the scale factor const int defaultGridUnit = 8; int gridUnit = defaultGridUnit; QByteArray gridUnitString = qgetenv("GRID_UNIT_PX"); if (!gridUnitString.isEmpty()) { bool ok; gridUnit = gridUnitString.toInt(&ok); if (!ok) { gridUnit = defaultGridUnit; } } mScaleFactor = static_cast(gridUnit) / defaultGridUnit; } QMirClientClientIntegration::~QMirClientClientIntegration() { eglTerminate(mEglDisplay); delete mInput; delete mInputContext; delete mServices; } QPlatformServices *QMirClientClientIntegration::services() const { return mServices; } void QMirClientClientIntegration::setupOptions(QStringList &args) { int argc = args.size() + 1; char **argv = new char*[argc]; for (int i = 0; i < argc - 1; i++) argv[i] = qstrdup(args.at(i).toLocal8Bit()); argv[argc - 1] = nullptr; mOptions = u_application_options_new_from_cmd_line(argc - 1, argv); for (int i = 0; i < argc; i++) delete [] argv[i]; delete [] argv; } void QMirClientClientIntegration::setupDescription(QByteArray &sessionName) { mDesc = u_application_description_new(); UApplicationId* id = u_application_id_new_from_stringn(sessionName.data(), sessionName.count()); u_application_description_set_application_id(mDesc, id); UApplicationLifecycleDelegate* delegate = u_application_lifecycle_delegate_new(); u_application_lifecycle_delegate_set_application_resumed_cb(delegate, &resumedCallback); u_application_lifecycle_delegate_set_application_about_to_stop_cb(delegate, &aboutToStopCallback); u_application_lifecycle_delegate_set_context(delegate, this); u_application_description_set_application_lifecycle_delegate(mDesc, delegate); } QByteArray QMirClientClientIntegration::generateSessionName(QStringList &args) { // Try to come up with some meaningful session name to uniquely identify this session, // helping with shell debugging if (args.count() == 0) { return QByteArray("QtUbuntu"); } if (args[0].contains("qmlscene")) { return generateSessionNameFromQmlFile(args); } else { // use the executable name QFileInfo fileInfo(args[0]); return fileInfo.fileName().toLocal8Bit(); } } QByteArray QMirClientClientIntegration::generateSessionNameFromQmlFile(QStringList &args) { Q_FOREACH (QString arg, args) { if (arg.endsWith(".qml")) { QFileInfo fileInfo(arg); return fileInfo.fileName().toLocal8Bit(); } } // give up return "qmlscene"; } QPlatformWindow* QMirClientClientIntegration::createPlatformWindow(QWindow* window) const { if (window->type() == Qt::Desktop) { // Desktop windows should not be backed up by a mir surface as they don't draw anything (nor should). return new QMirClientDesktopWindow(window); } else { return new QMirClientWindow(window, mInput, mNativeInterface, mAppStateController.data(), mEglDisplay, mMirConnection, mDebugExtension.data()); } } bool QMirClientClientIntegration::hasCapability(QPlatformIntegration::Capability cap) const { switch (cap) { case ThreadedOpenGL: if (qEnvironmentVariableIsEmpty("QTUBUNTU_NO_THREADED_OPENGL")) { return true; } else { qCDebug(mirclient, "disabled threaded OpenGL"); return false; } case ThreadedPixmaps: case OpenGL: case ApplicationState: case MultipleWindows: case NonFullScreenWindows: #if QT_VERSION > QT_VERSION_CHECK(5, 5, 0) case SwitchableWidgetComposition: #endif case RasterGLSurface: // needed for QQuickWidget return true; default: return QPlatformIntegration::hasCapability(cap); } } QAbstractEventDispatcher *QMirClientClientIntegration::createEventDispatcher() const { return createUnixEventDispatcher(); } QPlatformBackingStore* QMirClientClientIntegration::createPlatformBackingStore(QWindow* window) const { return new QMirClientBackingStore(window); } QPlatformOpenGLContext* QMirClientClientIntegration::createPlatformOpenGLContext( QOpenGLContext* context) const { QSurfaceFormat format(context->format()); auto platformContext = new QMirClientOpenGLContext(format, context->shareHandle(), mEglDisplay); if (!platformContext->isValid()) { // Older Intel Atom-based devices only support OpenGL 1.4 compatibility profile but by default // QML asks for at least OpenGL 2.0. The XCB GLX backend ignores this request and returns a // 1.4 context, but the XCB EGL backend tries to honor it, and fails. The 1.4 context appears to // have sufficient capabilities on MESA (i915) to render correctly however. So reduce the default // requested OpenGL version to 1.0 to ensure EGL will give us a working context (lp:1549455). static const bool isMesa = QString(eglQueryString(mEglDisplay, EGL_VENDOR)).contains(QStringLiteral("Mesa")); if (isMesa) { qCDebug(mirclientGraphics, "Attempting to choose OpenGL 1.4 context which may suit Mesa"); format.setMajorVersion(1); format.setMinorVersion(4); delete platformContext; platformContext = new QMirClientOpenGLContext(format, context->shareHandle(), mEglDisplay); } } return platformContext; } QStringList QMirClientClientIntegration::themeNames() const { return QStringList(QStringLiteral("ubuntuappmenu")); } QPlatformTheme* QMirClientClientIntegration::createPlatformTheme(const QString& name) const { Q_UNUSED(name); return new UbuntuTheme; } QVariant QMirClientClientIntegration::styleHint(StyleHint hint) const { switch (hint) { case QPlatformIntegration::StartDragDistance: { // default is 10 pixels (see QPlatformTheme::defaultThemeHint) return 10.0 * mScaleFactor; } case QPlatformIntegration::PasswordMaskDelay: { // return time in milliseconds - 1 second return QVariant(1000); } default: break; } return QPlatformIntegration::styleHint(hint); } QPlatformClipboard* QMirClientClientIntegration::clipboard() const { static QPlatformClipboard *clipboard = nullptr; if (!clipboard) { clipboard = new QMirClientClipboard; } return clipboard; } QPlatformNativeInterface* QMirClientClientIntegration::nativeInterface() const { return mNativeInterface; } QPlatformOffscreenSurface *QMirClientClientIntegration::createPlatformOffscreenSurface( QOffscreenSurface *surface) const { return new QEGLPbuffer(mEglDisplay, surface->requestedFormat(), surface); } void QMirClientClientIntegration::destroyScreen(QMirClientScreen *screen) { // FIXME: on deleting a screen while a Window is on it, Qt will automatically // move the window to the primaryScreen(). This will trigger a screenChanged // signal, causing things like QQuickScreenAttached to re-fetch screen properties // like DPI and physical size. However this is crashing, as Qt is calling virtual // functions on QPlatformScreen, for reasons unclear. As workaround, move window // to primaryScreen() before deleting the screen. Might be QTBUG-38650 QScreen *primaryScreen = QGuiApplication::primaryScreen(); if (screen != primaryScreen->handle()) { uint32_t movedWindowCount = 0; Q_FOREACH (QWindow *w, QGuiApplication::topLevelWindows()) { if (w->screen()->handle() == screen) { QWindowSystemInterface::handleWindowScreenChanged(w, primaryScreen); ++movedWindowCount; } } if (movedWindowCount > 0) { QWindowSystemInterface::flushWindowSystemEvents(); } } qCDebug(mirclient) << "Removing Screen with id" << screen->mirOutputId() << "and geometry" << screen->geometry(); #if QT_VERSION < QT_VERSION_CHECK(5, 5, 0) delete screen; #else QPlatformIntegration::destroyScreen(screen); #endif } QPlatformAccessibility *QMirClientClientIntegration::accessibility() const { if (!mAccessibility) { mAccessibility.reset(new QSpiAccessibleBridge()); } return mAccessibility.data(); } ./src/ubuntumirclient/qmirclientdebugextension.cpp0000644000004100000410000000542713127642576023127 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016-2017 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmirclientdebugextension.h" #include "qmirclientlogging.h" // mir client debug #include Q_LOGGING_CATEGORY(mirclientDebug, "qt.qpa.mirclient.debug") QMirClientDebugExtension::QMirClientDebugExtension(MirConnection *connection) : mExtension(mir_extension_window_coordinate_translation_v1(connection)) { if (mExtension == nullptr) { qCWarning(mirclientDebug) << "ERROR: no window coordinate translation extension available"; } } bool QMirClientDebugExtension::isEnabled() const { return mExtension != nullptr; } QPoint QMirClientDebugExtension::mapWindowPointToScreen(MirWindow *window, const QPoint &point) { if (!mExtension) { return point; } QPoint mappedPoint; mExtension->window_translate_coordinates(window, point.x(), point.y(), &mappedPoint.rx(), &mappedPoint.ry()); return mappedPoint; } ./src/ubuntumirclient/qmirclientinput.h0000644000004100000410000000657213127642576020712 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2014-2017 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTINPUT_H #define QMIRCLIENTINPUT_H // Qt #include #include class QMirClientClientIntegration; class QMirClientWindow; class QMirClientInput : public QObject { Q_OBJECT public: QMirClientInput(QMirClientClientIntegration* integration); virtual ~QMirClientInput(); // QObject methods. void customEvent(QEvent* event) override; void postEvent(QMirClientWindow* window, const MirEvent *event); QMirClientClientIntegration* integration() const { return mIntegration; } QMirClientWindow *lastInputWindow() const {return mLastInputWindow; } protected: void dispatchKeyEvent(QMirClientWindow *window, const MirInputEvent *event); void dispatchPointerEvent(QMirClientWindow *window, const MirInputEvent *event); void dispatchTouchEvent(QMirClientWindow *window, const MirInputEvent *event); void dispatchInputEvent(QMirClientWindow *window, const MirInputEvent *event); void dispatchOrientationEvent(QWindow* window, const MirOrientationEvent *event); void handleWindowEvent(const QPointer &window, const MirWindowEvent *event); void handleWindowOutputEvent(const QPointer &window, const MirWindowOutputEvent *event); private: QMirClientClientIntegration* mIntegration; QTouchDevice* mTouchDevice; const QByteArray mEventFilterType; const QEvent::Type mEventType; QMirClientWindow *mLastInputWindow; }; #endif // QMIRCLIENTINPUT_H ./src/ubuntumirclient/qmirclientscreenobserver.cpp0000644000004100000410000001457013127642576023132 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmirclientscreenobserver.h" #include "qmirclientscreen.h" #include "qmirclientwindow.h" #include "qmirclientlogging.h" // Qt #include #include // Mir #include #include #include namespace { static void displayConfigurationChangedCallback(MirConnection */*connection*/, void* context) { ASSERT(context != NULL); QMirClientScreenObserver *observer = static_cast(context); QMetaObject::invokeMethod(observer, "update"); } const char *mirFormFactorToStr(MirFormFactor formFactor) { switch (formFactor) { case mir_form_factor_unknown: return "unknown"; case mir_form_factor_phone: return "phone"; case mir_form_factor_tablet: return "tablet"; case mir_form_factor_monitor: return "monitor"; case mir_form_factor_tv: return "tv"; case mir_form_factor_projector: return "projector"; } Q_UNREACHABLE(); } } // anonymous namespace QMirClientScreenObserver::QMirClientScreenObserver(MirConnection *mirConnection) : mMirConnection(mirConnection) { mir_connection_set_display_config_change_callback(mirConnection, ::displayConfigurationChangedCallback, this); update(); } void QMirClientScreenObserver::update() { // Wrap MirDisplayConfiguration to always delete when out of scope auto configDeleter = [](MirDisplayConfig *config) { mir_display_config_release(config); }; using configUp = std::unique_ptr; configUp displayConfig(mir_connection_create_display_configuration(mMirConnection), configDeleter); // Mir only tells us something changed, it is up to us to figure out what. QList newScreenList; QList oldScreenList = mScreenList; mScreenList.clear(); for (int i = 0; i < mir_display_config_get_num_outputs(displayConfig.get()); i++) { const MirOutput *output = mir_display_config_get_output(displayConfig.get(), i); if (mir_output_is_enabled(output)) { QMirClientScreen *screen = findScreenWithId(oldScreenList, mir_output_get_id(output)); if (screen) { // we've already set up this display before screen->updateMirOutput(output); oldScreenList.removeAll(screen); } else { // new display, so create QMirClientScreen for it screen = new QMirClientScreen(output, mMirConnection); newScreenList.append(screen); qCDebug(mirclient) << "Added Screen with id" << mir_output_get_id(output) << "and geometry" << screen->geometry(); } mScreenList.append(screen); } } // Announce old & unused Screens, should be deleted by the slot Q_FOREACH (const auto screen, oldScreenList) { Q_EMIT screenRemoved(screen); } /* * Mir's MirDisplayOutput does not include formFactor or scale for some reason, but Qt * will want that information on creating the QScreen. Only way we get that info is when * Mir positions a Window on that Screen. See "handleScreenPropertiesChange" method */ // Announce new Screens Q_FOREACH (const auto screen, newScreenList) { Q_EMIT screenAdded(screen); } qCDebug(mirclient) << "======================================="; for (auto screen: mScreenList) { qCDebug(mirclient) << screen << "- id:" << screen->mirOutputId() << "geometry:" << screen->geometry() << "form factor:" << mirFormFactorToStr(screen->formFactor()) << "scale:" << screen->scale(); } qCDebug(mirclient) << "======================================="; } QMirClientScreen *QMirClientScreenObserver::findScreenWithId(int id) { return findScreenWithId(mScreenList, id); } QMirClientScreen *QMirClientScreenObserver::findScreenWithId(const QList &list, int id) { Q_FOREACH (const auto screen, list) { if (screen->mirOutputId() == id) { return screen; } } return nullptr; } void QMirClientScreenObserver::handleScreenPropertiesChange(QMirClientScreen *screen, int dpi, MirFormFactor formFactor, float scale) { screen->setAdditionalMirDisplayProperties(scale, formFactor, dpi); } ./src/ubuntumirclient/qmirclientlogging.h0000644000004100000410000000450713127642576021175 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTLOGGING_H #define QMIRCLIENTLOGGING_H #include #define ASSERT(cond) ((!(cond)) ? qt_assert(#cond,__FILE__,__LINE__) : qt_noop()) Q_DECLARE_LOGGING_CATEGORY(mirclient) Q_DECLARE_LOGGING_CATEGORY(mirclientBufferSwap) Q_DECLARE_LOGGING_CATEGORY(mirclientInput) Q_DECLARE_LOGGING_CATEGORY(mirclientGraphics) Q_DECLARE_LOGGING_CATEGORY(mirclientCursor) Q_DECLARE_LOGGING_CATEGORY(mirclientDebug) #endif // QMIRCLIENTLOGGING_H ./src/ubuntumirclient/qmirclientappstatecontroller.cpp0000644000004100000410000000670013127642576024024 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmirclientappstatecontroller.h" #include /* * QMirClientAppStateController - updates Qt's QApplication::applicationState property. * * Tries to avoid active-inactive-active invocations using a timer. The rapid state * change can confuse some applications. */ QMirClientAppStateController::QMirClientAppStateController() : m_suspended(false) , m_lastActive(true) { m_inactiveTimer.setSingleShot(true); m_inactiveTimer.setInterval(10); QObject::connect(&m_inactiveTimer, &QTimer::timeout, []() { QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationInactive); }); } void QMirClientAppStateController::setSuspended() { m_inactiveTimer.stop(); if (!m_suspended) { m_suspended = true; QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationSuspended); } } void QMirClientAppStateController::setResumed() { m_inactiveTimer.stop(); if (m_suspended) { m_suspended = false; if (m_lastActive) { QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationActive); } else { QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationInactive); } } } void QMirClientAppStateController::setWindowFocused(bool focused) { if (m_suspended) { return; } if (focused) { m_inactiveTimer.stop(); QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationActive); } else { m_inactiveTimer.start(); } m_lastActive = focused; } ./src/ubuntumirclient/qmirclientdesktopwindow.h0000644000004100000410000000425613127642576022451 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTDESKTOPWINDOW_H #define QMIRCLIENTDESKTOPWINDOW_H #include // TODO Implement it. For now it's just an empty, dummy class. class QMirClientDesktopWindow : public QPlatformWindow { public: QMirClientDesktopWindow(QWindow*); }; #endif // QMIRCLIENTDESKTOPWINDOW_H ./src/ubuntumirclient/qmirclientplatformservices.cpp0000644000004100000410000000552613127642576023474 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmirclientplatformservices.h" #include #include #include bool QMirClientPlatformServices::openUrl(const QUrl &url) { return callDispatcher(url); } bool QMirClientPlatformServices::openDocument(const QUrl &url) { return callDispatcher(url); } bool QMirClientPlatformServices::callDispatcher(const QUrl &url) { UAUrlDispatcherSession* session = ua_url_dispatcher_session(); if (!session) return false; ua_url_dispatcher_session_open(session, url.toEncoded().constData(), NULL, NULL); free(session); // We are returning true here because the other option // is spawning a nested event loop and wait for the // callback. But there is no guarantee on how fast // the callback is going to be so we prefer to avoid the // nested event loop. Long term plan is improve Qt API // to support an async openUrl return true; } ./src/ubuntumirclient/qmirclientglcontext.cpp0000644000004100000410000001156513127642604022103 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmirclientglcontext.h" #include "qmirclientlogging.h" #include "qmirclientwindow.h" #include #include #include #include Q_LOGGING_CATEGORY(mirclientGraphics, "qt.qpa.mirclient.graphics", QtWarningMsg) namespace { void printEglConfig(EGLDisplay display, EGLConfig config) { Q_ASSERT(display != EGL_NO_DISPLAY); Q_ASSERT(config != nullptr); const char *string = eglQueryString(display, EGL_VENDOR); qCDebug(mirclientGraphics, "EGL vendor: %s", string); string = eglQueryString(display, EGL_VERSION); qCDebug(mirclientGraphics, "EGL version: %s", string); string = eglQueryString(display, EGL_EXTENSIONS); qCDebug(mirclientGraphics, "EGL extensions: %s", string); qCDebug(mirclientGraphics, "EGL configuration attributes:"); q_printEglConfig(display, config); } } // anonymous namespace QMirClientOpenGLContext::QMirClientOpenGLContext(const QSurfaceFormat &format, QPlatformOpenGLContext *share, EGLDisplay display) : QEGLPlatformContext(format, share, display, 0) { if (mirclientGraphics().isDebugEnabled()) { printEglConfig(display, eglConfig()); } } static bool needsFBOReadBackWorkaround() { static bool set = false; static bool needsWorkaround = false; if (Q_UNLIKELY(!set)) { const char *rendererString = reinterpret_cast(glGetString(GL_RENDERER)); needsWorkaround = qstrncmp(rendererString, "Mali-400", 8) == 0 || qstrncmp(rendererString, "Mali-T7", 7) == 0 || qstrncmp(rendererString, "PowerVR Rogue G6200", 19) == 0; set = true; } return needsWorkaround; } bool QMirClientOpenGLContext::makeCurrent(QPlatformSurface* surface) { const bool ret = QEGLPlatformContext::makeCurrent(surface); if (Q_LIKELY(ret)) { QOpenGLContextPrivate *ctx_d = QOpenGLContextPrivate::get(context()); if (!ctx_d->workaround_brokenFBOReadBack && needsFBOReadBackWorkaround()) { ctx_d->workaround_brokenFBOReadBack = true; } } return ret; } // Following method used internally in the base class QEGLPlatformContext to access // the egl surface of a QPlatformSurface/QMirClientWindow EGLSurface QMirClientOpenGLContext::eglSurfaceForPlatformSurface(QPlatformSurface *surface) { if (surface->surface()->surfaceClass() == QSurface::Window) { return static_cast(surface)->eglSurface(); } else { return static_cast(surface)->pbuffer(); } } void QMirClientOpenGLContext::swapBuffers(QPlatformSurface *surface) { QEGLPlatformContext::swapBuffers(surface); if (surface->surface()->surfaceClass() == QSurface::Window) { // notify window on swap completion auto platformWindow = static_cast(surface); platformWindow->onSwapBuffersDone(); } } ./src/ubuntumirclient/qmirclientbackingstore.cpp0000644000004100000410000001367413127642604022552 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmirclientbackingstore.h" #include "qmirclientlogging.h" #include #include #include #include #include #include QMirClientBackingStore::QMirClientBackingStore(QWindow* window) : QPlatformBackingStore(window) , mContext(new QOpenGLContext) , mTexture(new QOpenGLTexture(QOpenGLTexture::Target2D)) , mBlitter(new QOpenGLTextureBlitter) { mContext->setFormat(window->requestedFormat()); mContext->setScreen(window->screen()); mContext->create(); window->setSurfaceType(QSurface::OpenGLSurface); } QMirClientBackingStore::~QMirClientBackingStore() { if (!mTexture->isCreated()) return; // Paraphrasing QOpenGLCompositorBackingStore: "With render-to-texture-widgets QWidget makes // sure the context is made current before destroying backingstores. That is however not the // case for windows with regular widgets only." auto context = QOpenGLContext::currentContext(); if (!context) { // QWindow's backing QPlatformSurface probably gone, use temp one for cleanup QOffscreenSurface tempSurface; tempSurface.setFormat(mContext->format()); tempSurface.create(); mContext->makeCurrent(&tempSurface); } // QOpenGLTexture will go out of scope, is then deleted. Then QOpenGLContext falls out of // scope, calls doneCurrent and is then deleted. } void QMirClientBackingStore::flush(QWindow* window, const QRegion& region, const QPoint& offset) { Q_UNUSED(region); Q_UNUSED(offset); mContext->makeCurrent(window); glViewport(0, 0, window->width(), window->height()); updateTexture(); if (!mBlitter->isCreated()) mBlitter->create(); mBlitter->bind(); mBlitter->blit(mTexture->textureId(), QMatrix4x4(), QOpenGLTextureBlitter::OriginTopLeft); mBlitter->release(); mContext->swapBuffers(window); } void QMirClientBackingStore::updateTexture() { if (mDirty.isNull()) return; if (!mTexture->isCreated()) { mTexture->setMinificationFilter(QOpenGLTexture::Nearest); mTexture->setMagnificationFilter(QOpenGLTexture::Nearest); mTexture->setWrapMode(QOpenGLTexture::ClampToEdge); mTexture->setData(mImage, QOpenGLTexture::DontGenerateMipMaps); mTexture->create(); } mTexture->bind(); QRegion fixed; QRect imageRect = mImage.rect(); for (const QRect &rect : mDirty.rects()) { // intersect with image rect to be sure QRect r = imageRect & rect; // if the rect is wide enough it is cheaper to just extend it instead of doing an image copy if (r.width() >= imageRect.width() / 2) { r.setX(0); r.setWidth(imageRect.width()); } fixed |= r; } for (const QRect &rect : fixed.rects()) { // if the sub-rect is full-width we can pass the image data directly to // OpenGL instead of copying, since there is no gap between scanlines if (rect.width() == imageRect.width()) { glTexSubImage2D(GL_TEXTURE_2D, 0, 0, rect.y(), rect.width(), rect.height(), GL_RGBA, GL_UNSIGNED_BYTE, mImage.constScanLine(rect.y())); } else { glTexSubImage2D(GL_TEXTURE_2D, 0, rect.x(), rect.y(), rect.width(), rect.height(), GL_RGBA, GL_UNSIGNED_BYTE, mImage.copy(rect).constBits()); } } /* End of code taken from QEGLPlatformBackingStore */ mDirty = QRegion(); } void QMirClientBackingStore::beginPaint(const QRegion& region) { mDirty |= region; } void QMirClientBackingStore::resize(const QSize& size, const QRegion& /*staticContents*/) { mImage = QImage(size, QImage::Format_RGBA8888); mContext->makeCurrent(window()); if (mTexture->isCreated()) mTexture->destroy(); } QPaintDevice* QMirClientBackingStore::paintDevice() { return &mImage; } QImage QMirClientBackingStore::toImage() const { // used by QPlatformBackingStore::composeAndFlush return mImage; } ./src/ubuntumirclient/qmirclientplugin.h0000644000004100000410000000452413127642576021044 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTPLUGIN_H #define QMIRCLIENTPLUGIN_H #include class QMirClientIntegrationPlugin : public QPlatformIntegrationPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID QPlatformIntegrationFactoryInterface_iid FILE "ubuntumirclient.json") public: QPlatformIntegration *create(const QString &system, const QStringList ¶mList, int &argc, char **argv) override; }; #endif // QMIRCLIENTPLUGIN_H ./src/ubuntumirclient/qmirclientscreenobserver.h0000644000004100000410000000550013127642576022570 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTSCREENOBSERVER_H #define QMIRCLIENTSCREENOBSERVER_H #include #include class QMirClientScreen; class QMirClientScreenObserver : public QObject { Q_OBJECT public: QMirClientScreenObserver(MirConnection *connection); QList screens() const { return mScreenList; } QMirClientScreen *findScreenWithId(int id); void handleScreenPropertiesChange(QMirClientScreen *screen, int dpi, MirFormFactor formFactor, float scale); Q_SIGNALS: void screenAdded(QMirClientScreen *screen); void screenRemoved(QMirClientScreen *screen); private Q_SLOTS: void update(); private: QMirClientScreen *findScreenWithId(const QList &list, int id); void removeScreen(QMirClientScreen *screen); MirConnection *mMirConnection; QList mScreenList; }; #endif // QMIRCLIENTSCREENOBSERVER_H ./src/ubuntumirclient/ubuntumirclient.json0000644000004100000410000000004613127642576021424 0ustar www-datawww-data{ "Keys": [ "ubuntumirclient" ] } ./src/ubuntumirclient/qmirclientplatformservices.h0000644000004100000410000000457313127642604023132 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTPLATFORMSERVICES_H #define QMIRCLIENTPLATFORMSERVICES_H #include #include #include class QMirClientPlatformServices : public QPlatformServices { public: bool openUrl(const QUrl &url) override; bool openDocument(const QUrl &url) override; private: bool callDispatcher(const QUrl &url); }; #endif // QMIRCLIENTPLATFORMSERVICES_H ./src/ubuntumirclient/qmirclientnativeinterface.h0000644000004100000410000000707113127642576022715 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016-2017 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTNATIVEINTERFACE_H #define QMIRCLIENTNATIVEINTERFACE_H #include #include "qmirclientintegration.h" class QPlatformScreen; class QMirClientNativeInterface : public QPlatformNativeInterface { Q_OBJECT public: enum ResourceType { EglDisplay, EglContext, NativeOrientation, Display, MirConnection, MirWindow, Scale, FormFactor }; QMirClientNativeInterface(const QMirClientClientIntegration *integration); ~QMirClientNativeInterface(); // QPlatformNativeInterface methods. void* nativeResourceForIntegration(const QByteArray &resource) override; void* nativeResourceForContext(const QByteArray& resourceString, QOpenGLContext* context) override; void* nativeResourceForWindow(const QByteArray& resourceString, QWindow* window) override; void* nativeResourceForScreen(const QByteArray& resourceString, QScreen* screen) override; QVariantMap windowProperties(QPlatformWindow *window) const override; QVariant windowProperty(QPlatformWindow *window, const QString &name) const override; QVariant windowProperty(QPlatformWindow *window, const QString &name, const QVariant &defaultValue) const override; // New methods. const QByteArray& genericEventFilterType() const { return mGenericEventFilterType; } Q_SIGNALS: // New signals void screenPropertyChanged(QPlatformScreen *screen, const QString &propertyName); private: const QMirClientClientIntegration *mIntegration; const QByteArray mGenericEventFilterType; Qt::ScreenOrientation* mNativeOrientation; }; #endif // QMIRCLIENTNATIVEINTERFACE_H ./src/ubuntumirclient/qmirclientplugin.cpp0000644000004100000410000000516113127642576021375 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmirclientplugin.h" #include "qmirclientintegration.h" #include "qmirclientlogging.h" Q_LOGGING_CATEGORY(mirclient, "qt.qpa.mirclient", QtWarningMsg) QPlatformIntegration *QMirClientIntegrationPlugin::create(const QString &system, const QStringList &/*paramList*/, int &argc, char **argv) { if (system.toLower() == QLatin1String("ubuntumirclient")) { #ifdef PLATFORM_API_TOUCH setenv("UBUNTU_PLATFORM_API_BACKEND", "touch_mirclient", 1); #else setenv("UBUNTU_PLATFORM_API_BACKEND", "desktop_mirclient", 1); #endif return new QMirClientClientIntegration(argc, argv); } else { return 0; } } ./src/ubuntumirclient/qmirclientbackingstore.h0000644000004100000410000000543213127642576022220 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTBACKINGSTORE_H #define QMIRCLIENTBACKINGSTORE_H #include class QOpenGLContext; class QOpenGLTexture; class QOpenGLTextureBlitter; class QMirClientBackingStore : public QPlatformBackingStore { public: QMirClientBackingStore(QWindow* window); virtual ~QMirClientBackingStore(); // QPlatformBackingStore methods. void beginPaint(const QRegion&) override; void flush(QWindow* window, const QRegion& region, const QPoint& offset) override; void resize(const QSize& size, const QRegion& staticContents) override; QPaintDevice* paintDevice() override; QImage toImage() const override; protected: void updateTexture(); private: QScopedPointer mContext; QScopedPointer mTexture; QScopedPointer mBlitter; QImage mImage; QRegion mDirty; }; #endif // QMIRCLIENTBACKINGSTORE_H ./src/ubuntumirclient/ubuntumirclient.pro0000644000004100000410000000343313127642604021246 0ustar www-datawww-dataTARGET = qpa-ubuntumirclient TEMPLATE = lib QT += \ core-private dbus linuxaccessibility_support-private \ theme_support-private eventdispatcher_support-private \ fontdatabase_support-private egl_support-private CONFIG += plugin no_keywords qpa/genericunixfontdatabase DEFINES += MESA_EGL_NO_X11_HEADERS # CONFIG += c++11 # only enables C++0x QMAKE_CXXFLAGS += -fvisibility=hidden -fvisibility-inlines-hidden -std=c++11 -Werror -Wall QMAKE_CXXFLAGS += -Wno-error=deprecated-declarations QMAKE_LFLAGS += -std=c++11 -Wl,-no-undefined CONFIG += link_pkgconfig PKGCONFIG += egl mirclient ubuntu-platform-api xkbcommon libcontent-hub SOURCES = \ qmirclientbackingstore.cpp \ qmirclientclipboard.cpp \ qmirclientcursor.cpp \ qmirclientdebugextension.cpp \ qmirclientdesktopwindow.cpp \ qmirclientglcontext.cpp \ qmirclientinput.cpp \ qmirclientintegration.cpp \ qmirclientnativeinterface.cpp \ qmirclientplatformservices.cpp \ qmirclientplugin.cpp \ qmirclientscreen.cpp \ qmirclientscreenobserver.cpp \ qmirclientwindow.cpp \ qmirclientappstatecontroller.cpp HEADERS = \ qmirclientbackingstore.h \ qmirclientclipboard.h \ qmirclientcursor.h \ qmirclientdebugextension.h \ qmirclientdesktopwindow.h \ qmirclientglcontext.h \ qmirclientinput.h \ qmirclientintegration.h \ qmirclientnativeinterface.h \ qmirclientorientationchangeevent_p.h \ qmirclientplatformservices.h \ qmirclientplugin.h \ qmirclientscreenobserver.h \ qmirclientscreen.h \ qmirclientwindow.h \ qmirclientlogging.h \ qmirclientappstatecontroller.h \ ../shared/ubuntutheme.h OTHER_FILES += \ ubuntumirclient.json # Installation path target.path += $$[QT_INSTALL_PLUGINS]/platforms INSTALLS += target ./src/ubuntumirclient/qmirclientdesktopwindow.cpp0000644000004100000410000000416113127642576022777 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmirclientdesktopwindow.h" // local #include "qmirclientlogging.h" QMirClientDesktopWindow::QMirClientDesktopWindow(QWindow *window) : QPlatformWindow(window) { qCDebug(mirclient, "QMirClientDesktopWindow(window=%p)", window); } ./src/ubuntumirclient/qmirclientglcontext.h0000644000004100000410000000501013127642604021534 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTGLCONTEXT_H #define QMIRCLIENTGLCONTEXT_H #include #include #include class QMirClientOpenGLContext : public QEGLPlatformContext { public: QMirClientOpenGLContext(const QSurfaceFormat &format, QPlatformOpenGLContext *share, EGLDisplay display); // QEGLPlatformContext methods. void swapBuffers(QPlatformSurface *surface) final; bool makeCurrent(QPlatformSurface *surface) final; protected: EGLSurface eglSurfaceForPlatformSurface(QPlatformSurface *surface) final; }; #endif // QMIRCLIENTGLCONTEXT_H ./src/ubuntumirclient/qmirclientscreen.h0000644000004100000410000001017213127642576021021 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2014-2017 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTSCREEN_H #define QMIRCLIENTSCREEN_H #include #include #include // just for MirFormFactor enum #include "qmirclientcursor.h" struct MirConnection; struct MirOutput; class QMirClientScreen : public QObject, public QPlatformScreen { Q_OBJECT public: QMirClientScreen(const MirOutput *output, MirConnection *connection); virtual ~QMirClientScreen(); // QPlatformScreen methods. QImage::Format format() const override { return mFormat; } int depth() const override { return mDepth; } QRect geometry() const override { return mGeometry; } QRect availableGeometry() const override { return mGeometry; } QSizeF physicalSize() const override { return mPhysicalSize; } qreal devicePixelRatio() const override { return mDevicePixelRatio; } QDpi logicalDpi() const override; Qt::ScreenOrientation nativeOrientation() const override { return mNativeOrientation; } Qt::ScreenOrientation orientation() const override { return mNativeOrientation; } QPlatformCursor *cursor() const override { return const_cast(&mCursor); } // Additional Screen properties from Mir int mirOutputId() const { return mOutputId; } MirFormFactor formFactor() const { return mFormFactor; } float scale() const { return mScale; } // Internally used methods void updateMirOutput(const MirOutput *output); void setAdditionalMirDisplayProperties(float scale, MirFormFactor formFactor, int dpi); void handleWindowSurfaceResize(int width, int height); // QObject methods. void customEvent(QEvent* event) override; private: void setMirOutput(const MirOutput *output); void updateLogicalDpi(); QRect mGeometry, mNativeGeometry; QSizeF mPhysicalSize; qreal mDevicePixelRatio; Qt::ScreenOrientation mNativeOrientation; Qt::ScreenOrientation mCurrentOrientation; QImage::Format mFormat; int mDepth; qreal mRefreshRate; MirFormFactor mFormFactor; float mScale; int mOutputId; QMirClientCursor mCursor; float mLogicalDpiEnv{0}; QDpi mLogicalDpi; static const float mMirScaleToLogicalDpiMultiplier; friend class QMirClientNativeInterface; }; #endif // QMIRCLIENTSCREEN_H ./src/ubuntumirclient/qmirclientcursor.cpp0000644000004100000410000002001113127642576021403 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2015-2017 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmirclientcursor.h" #include "qmirclientlogging.h" #include "qmirclientwindow.h" #include Q_LOGGING_CATEGORY(mirclientCursor, "qt.qpa.mirclient.cursor", QtWarningMsg) QMirClientCursor::QMirClientCursor(MirConnection *connection) : mConnection(connection) { /* * TODO: Add the missing cursors to Mir (LP: #1388987) * Those are the ones without a mir_ prefix, which are X11 cursors * and won't be understood by any shell other than Unity8. */ mShapeToCursorName[Qt::ArrowCursor] = mir_arrow_cursor_name; mShapeToCursorName[Qt::UpArrowCursor] = "up_arrow"; mShapeToCursorName[Qt::CrossCursor] = mir_crosshair_cursor_name; mShapeToCursorName[Qt::WaitCursor] = mir_busy_cursor_name; mShapeToCursorName[Qt::IBeamCursor] = mir_caret_cursor_name; mShapeToCursorName[Qt::SizeVerCursor] = mir_vertical_resize_cursor_name; mShapeToCursorName[Qt::SizeHorCursor] = mir_horizontal_resize_cursor_name; mShapeToCursorName[Qt::SizeBDiagCursor] = mir_diagonal_resize_bottom_to_top_cursor_name; mShapeToCursorName[Qt::SizeFDiagCursor] = mir_diagonal_resize_top_to_bottom_cursor_name; mShapeToCursorName[Qt::SizeAllCursor] = mir_omnidirectional_resize_cursor_name; mShapeToCursorName[Qt::BlankCursor] = mir_disabled_cursor_name; mShapeToCursorName[Qt::SplitVCursor] = mir_vsplit_resize_cursor_name; mShapeToCursorName[Qt::SplitHCursor] = mir_hsplit_resize_cursor_name; mShapeToCursorName[Qt::PointingHandCursor] = mir_pointing_hand_cursor_name; mShapeToCursorName[Qt::ForbiddenCursor] = "forbidden"; mShapeToCursorName[Qt::WhatsThisCursor] = "whats_this"; mShapeToCursorName[Qt::BusyCursor] = "left_ptr_watch"; mShapeToCursorName[Qt::OpenHandCursor] = mir_open_hand_cursor_name; mShapeToCursorName[Qt::ClosedHandCursor] = mir_closed_hand_cursor_name; mShapeToCursorName[Qt::DragCopyCursor] = "dnd-copy"; mShapeToCursorName[Qt::DragMoveCursor] = "dnd-move"; mShapeToCursorName[Qt::DragLinkCursor] = "dnd-link"; } namespace { const char *qtCursorShapeToStr(Qt::CursorShape shape) { switch (shape) { case Qt::ArrowCursor: return "Arrow"; case Qt::UpArrowCursor: return "UpArrow"; case Qt::CrossCursor: return "Cross"; case Qt::WaitCursor: return "Wait"; case Qt::IBeamCursor: return "IBeam"; case Qt::SizeVerCursor: return "SizeVer"; case Qt::SizeHorCursor: return "SizeHor"; case Qt::SizeBDiagCursor: return "SizeBDiag"; case Qt::SizeFDiagCursor: return "SizeFDiag"; case Qt::SizeAllCursor: return "SizeAll"; case Qt::BlankCursor: return "Blank"; case Qt::SplitVCursor: return "SplitV"; case Qt::SplitHCursor: return "SplitH"; case Qt::PointingHandCursor: return "PointingHand"; case Qt::ForbiddenCursor: return "Forbidden"; case Qt::WhatsThisCursor: return "WhatsThis"; case Qt::BusyCursor: return "Busy"; case Qt::OpenHandCursor: return "OpenHand"; case Qt::ClosedHandCursor: return "ClosedHand"; case Qt::DragCopyCursor: return "DragCopy"; case Qt::DragMoveCursor: return "DragMove"; case Qt::DragLinkCursor: return "DragLink"; case Qt::BitmapCursor: return "Bitmap"; default: return "???"; } } class CursorWindowSpec { public: CursorWindowSpec(MirConnection *connection, const char *name) : spec(mir_create_window_spec(connection)) { mir_window_spec_set_cursor_name(spec, name); } ~CursorWindowSpec() { mir_window_spec_release(spec); } void apply(MirWindow *window) { mir_window_apply_spec(window, spec); } private: MirWindowSpec * const spec; }; } // anonymous namespace void QMirClientCursor::changeCursor(QCursor *windowCursor, QWindow *window) { if (!window) { return; } MirWindow *mirWindow = static_cast(window->handle())->mirWindow(); if (!mirWindow) { return; } if (windowCursor) { qCDebug(mirclientCursor, "changeCursor shape=%s, window=%p", qtCursorShapeToStr(windowCursor->shape()), window); if (!windowCursor->pixmap().isNull()) { configureMirCursorWithPixmapQCursor(mirWindow, *windowCursor); } else if (windowCursor->shape() == Qt::BitmapCursor) { // TODO: Implement bitmap cursor support applyDefaultCursorConfiguration(mirWindow); } else { const auto &cursorName = mShapeToCursorName.value(windowCursor->shape(), QByteArray("left_ptr")); CursorWindowSpec spec(mConnection, cursorName.data()); spec.apply(mirWindow); } } else { applyDefaultCursorConfiguration(mirWindow); } } void QMirClientCursor::configureMirCursorWithPixmapQCursor(MirWindow *window, QCursor &cursor) { QImage image = cursor.pixmap().toImage(); if (image.format() != QImage::Format_ARGB32) { image = image.convertToFormat(QImage::Format_ARGB32); } MirBufferStream *bufferStream = mir_connection_create_buffer_stream_sync(mConnection, image.width(), image.height(), mir_pixel_format_argb_8888, mir_buffer_usage_software); { MirGraphicsRegion region; mir_buffer_stream_get_graphics_region(bufferStream, ®ion); char *regionLine = region.vaddr; Q_ASSERT(image.bytesPerLine() <= region.stride); for (int i = 0; i < image.height(); ++i) { memcpy(regionLine, image.scanLine(i), image.bytesPerLine()); regionLine += region.stride; } } mir_buffer_stream_swap_buffers_sync(bufferStream); { auto configuration = mir_cursor_configuration_from_buffer_stream(bufferStream, cursor.hotSpot().x(), cursor.hotSpot().y()); mir_window_configure_cursor(window, configuration); mir_cursor_configuration_destroy(configuration); } mir_buffer_stream_release_sync(bufferStream); } void QMirClientCursor::applyDefaultCursorConfiguration(MirWindow *window) { CursorWindowSpec spec(mConnection, "left_ptr"); spec.apply(window); } ./src/ubuntumirclient/qmirclientdebugextension.h0000644000004100000410000000455013127642576022570 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016-2017 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTDEBUGEXTENSION_H #define QMIRCLIENTDEBUGEXTENSION_H #include #include struct MirExtensionWindowCoordinateTranslationV1; class QMirClientDebugExtension { public: QMirClientDebugExtension(MirConnection *connection); bool isEnabled() const; QPoint mapWindowPointToScreen(MirWindow *, const QPoint &point); private: MirExtensionWindowCoordinateTranslationV1 const *mExtension; }; #endif // QMIRCLIENTDEBUGEXTENSION_H ./src/ubuntumirclient/qmirclientwindow.h0000644000004100000410000001071513127642576021054 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2014-2017 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTWINDOW_H #define QMIRCLIENTWINDOW_H #include #include #include #include // needed only for MirFormFactor enum #include #include #include class QMirClientAppStateController; class QMirClientDebugExtension; class QMirClientNativeInterface; class QMirClientInput; class QMirClientScreen; class UbuntuSurface; struct MirConnection; class QMirClientWindow : public QObject, public QPlatformWindow { Q_OBJECT public: QMirClientWindow(QWindow *w, QMirClientInput *input, QMirClientNativeInterface *native, QMirClientAppStateController *appState, EGLDisplay eglDisplay, MirConnection *mirConnection, QMirClientDebugExtension *debugExt); virtual ~QMirClientWindow(); // QPlatformWindow methods. WId winId() const override; QRect geometry() const override; void setGeometry(const QRect&) override; void setWindowState(Qt::WindowState state) override; void setWindowFlags(Qt::WindowFlags flags) override; void setVisible(bool visible) override; void setWindowTitle(const QString &title) override; void propagateSizeHints() override; bool isExposed() const override; void setMask(const QRegion ®ion) override; QPoint mapToGlobal(const QPoint &pos) const override; QSurfaceFormat format() const override; // Additional Window properties exposed by NativeInterface MirFormFactor formFactor() const { return mFormFactor; } float scale() const { return mScale; } // New methods. void *eglSurface() const; MirWindow *mirWindow() const; void handleSurfaceResized(int width, int height); void handleSurfaceExposeChange(bool exposed); void handleSurfaceFocusChanged(bool focused); void handleSurfaceVisibilityChanged(bool visible); void handleSurfaceStateChanged(Qt::WindowState state); void onSwapBuffersDone(); void handleScreenPropertiesChange(MirFormFactor formFactor, float scale); QString persistentSurfaceId(); private: void updatePanelHeightHack(bool enable); void updateSurfaceState(); mutable QMutex mMutex; const WId mId; Qt::WindowState mWindowState; Qt::WindowFlags mWindowFlags; bool mWindowVisible; bool mWindowExposed; QMirClientAppStateController *mAppStateController; QMirClientDebugExtension *mDebugExtention; QMirClientNativeInterface *mNativeInterface; std::unique_ptr mSurface; float mScale; MirFormFactor mFormFactor; }; #endif // QMIRCLIENTWINDOW_H ./src/ubuntumirclient/qmirclientclipboard.cpp0000644000004100000410000001425713127642576022044 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qmirclientclipboard.h" #include "qmirclientlogging.h" #include "qmirclientwindow.h" #include #include #include #include #include // content-hub #include // get this cumbersome nested namespace out of the way using namespace com::ubuntu::content; QMirClientClipboard::QMirClientClipboard() : mMimeData(new QMimeData) , mContentHub(Hub::Client::instance()) { connect(mContentHub, &Hub::pasteboardChanged, this, [this]() { if (mClipboardState == QMirClientClipboard::SyncedClipboard) { mClipboardState = QMirClientClipboard::OutdatedClipboard; emitChanged(QClipboard::Clipboard); } }); connect(qGuiApp, &QGuiApplication::applicationStateChanged, this, &QMirClientClipboard::onApplicationStateChanged); requestMimeData(); } QMirClientClipboard::~QMirClientClipboard() { delete mMimeData; } QMimeData* QMirClientClipboard::mimeData(QClipboard::Mode mode) { if (mode != QClipboard::Clipboard) return nullptr; // Blocks dataChanged() signal from being emitted. Makes no sense to emit it from // inside the data getter. const QSignalBlocker blocker(this); if (mClipboardState == OutdatedClipboard) { updateMimeData(); } else if (mClipboardState == SyncingClipboard) { mPasteReply->waitForFinished(); } return mMimeData; } void QMirClientClipboard::setMimeData(QMimeData* mimeData, QClipboard::Mode mode) { QWindow *focusWindow = QGuiApplication::focusWindow(); if (focusWindow && mode == QClipboard::Clipboard && mimeData != nullptr) { QString surfaceId = static_cast(focusWindow->handle())->persistentSurfaceId(); QDBusPendingCall reply = mContentHub->createPaste(surfaceId, *mimeData); // Don't care whether it succeeded QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); connect(watcher, &QDBusPendingCallWatcher::finished, watcher, &QObject::deleteLater); mMimeData = mimeData; mClipboardState = SyncedClipboard; emitChanged(QClipboard::Clipboard); } } bool QMirClientClipboard::supportsMode(QClipboard::Mode mode) const { return mode == QClipboard::Clipboard; } bool QMirClientClipboard::ownsMode(QClipboard::Mode mode) const { Q_UNUSED(mode); return false; } void QMirClientClipboard::onApplicationStateChanged(Qt::ApplicationState state) { if (state == Qt::ApplicationActive) { // Only focused or active applications might be allowed to paste, so we probably // missed changes in the clipboard while we were hidden, inactive or, more importantly, // suspended. requestMimeData(); } } void QMirClientClipboard::updateMimeData() { if (qGuiApp->applicationState() != Qt::ApplicationActive) { // Don't even bother asking as content-hub would probably ignore our request (and should). return; } QWindow *focusWindow = QGuiApplication::focusWindow(); if (focusWindow) { delete mMimeData; QString surfaceId = static_cast(focusWindow->handle())->persistentSurfaceId(); mMimeData = mContentHub->latestPaste(surfaceId); mClipboardState = SyncedClipboard; emitChanged(QClipboard::Clipboard); } } void QMirClientClipboard::requestMimeData() { if (qGuiApp->applicationState() != Qt::ApplicationActive) { // Don't even bother asking as content-hub would probably ignore our request (and should). return; } QWindow *focusWindow = QGuiApplication::focusWindow(); if (!focusWindow) { return; } QString surfaceId = static_cast(focusWindow->handle())->persistentSurfaceId(); QDBusPendingCall reply = mContentHub->requestLatestPaste(surfaceId); mClipboardState = SyncingClipboard; mPasteReply = new QDBusPendingCallWatcher(reply, this); connect(mPasteReply, &QDBusPendingCallWatcher::finished, this, [this]() { delete mMimeData; mMimeData = mContentHub->paste(*mPasteReply); mClipboardState = SyncedClipboard; mPasteReply->deleteLater(); mPasteReply = nullptr; emitChanged(QClipboard::Clipboard); }); } ./src/ubuntumirclient/qmirclientcursor.h0000644000004100000410000000476313127642576021070 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2015-2017 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTCURSOR_H #define QMIRCLIENTCURSOR_H #include #include #include #include struct MirConnection; class QMirClientCursor : public QPlatformCursor { public: QMirClientCursor(MirConnection *connection); void changeCursor(QCursor *windowCursor, QWindow *window) override; private: void configureMirCursorWithPixmapQCursor(MirWindow *window, QCursor &cursor); void applyDefaultCursorConfiguration(MirWindow *window); QMap mShapeToCursorName; MirConnection *mConnection; }; #endif // QMIRCLIENTCURSOR_H ./src/ubuntumirclient/qmirclientintegration.h0000644000004100000410000001241113127642576022063 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTINTEGRATION_H #define QMIRCLIENTINTEGRATION_H #include #include #include "qmirclientappstatecontroller.h" #include "qmirclientplatformservices.h" #include "qmirclientscreenobserver.h" // platform-api #include #include #include class QMirClientDebugExtension; class QMirClientInput; class QMirClientNativeInterface; class QMirClientScreen; struct MirConnection; class QMirClientClientIntegration : public QObject, public QPlatformIntegration { Q_OBJECT public: QMirClientClientIntegration(int argc, char **argv); virtual ~QMirClientClientIntegration(); // QPlatformIntegration methods. bool hasCapability(QPlatformIntegration::Capability cap) const override; QAbstractEventDispatcher *createEventDispatcher() const override; QPlatformNativeInterface* nativeInterface() const override; QPlatformBackingStore* createPlatformBackingStore(QWindow* window) const override; QPlatformOpenGLContext* createPlatformOpenGLContext(QOpenGLContext* context) const override; QPlatformFontDatabase* fontDatabase() const override { return mFontDb; } QStringList themeNames() const override; QPlatformTheme* createPlatformTheme(const QString& name) const override; QVariant styleHint(StyleHint hint) const override; QPlatformServices *services() const override; QPlatformWindow* createPlatformWindow(QWindow* window) const override; QPlatformInputContext* inputContext() const override { return mInputContext; } QPlatformClipboard* clipboard() const override; void initialize() override; QPlatformOffscreenSurface *createPlatformOffscreenSurface(QOffscreenSurface *surface) const override; QPlatformAccessibility *accessibility() const override; // New methods. MirConnection *mirConnection() const { return mMirConnection; } EGLDisplay eglDisplay() const { return mEglDisplay; } EGLNativeDisplayType eglNativeDisplay() const { return mEglNativeDisplay; } QMirClientAppStateController *appStateController() const { return mAppStateController.data(); } QMirClientScreenObserver *screenObserver() const { return mScreenObserver.data(); } QMirClientDebugExtension *debugExtension() const { return mDebugExtension.data(); } private Q_SLOTS: void destroyScreen(QMirClientScreen *screen); private: void setupOptions(QStringList &args); void setupDescription(QByteArray &sessionName); static QByteArray generateSessionName(QStringList &args); static QByteArray generateSessionNameFromQmlFile(QStringList &args); QMirClientNativeInterface* mNativeInterface; QPlatformFontDatabase* mFontDb; QMirClientPlatformServices* mServices; QMirClientInput* mInput; QPlatformInputContext* mInputContext; mutable QScopedPointer mAccessibility; QScopedPointer mDebugExtension; QScopedPointer mScreenObserver; QScopedPointer mAppStateController; qreal mScaleFactor; MirConnection *mMirConnection; // Platform API stuff UApplicationOptions* mOptions; UApplicationDescription* mDesc; UApplicationInstance* mInstance; // EGL related EGLDisplay mEglDisplay{EGL_NO_DISPLAY}; EGLNativeDisplayType mEglNativeDisplay; }; #endif // QMIRCLIENTINTEGRATION_H ./src/ubuntumirclient/qmirclientappstatecontroller.h0000644000004100000410000000440613127642576023472 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTAPPSTATECONTROLLER_H #define QMIRCLIENTAPPSTATECONTROLLER_H #include class QMirClientAppStateController { public: QMirClientAppStateController(); void setSuspended(); void setResumed(); void setWindowFocused(bool focused); private: bool m_suspended; bool m_lastActive; QTimer m_inactiveTimer; }; #endif // QMIRCLIENTAPPSTATECONTROLLER_H ./src/ubuntumirclient/qmirclientnativeinterface.cpp0000644000004100000410000002045613127642576023252 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016-2017 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // Local #include "qmirclientnativeinterface.h" #include "qmirclientscreen.h" #include "qmirclientglcontext.h" #include "qmirclientwindow.h" // Qt #include #include #include #include class UbuntuResourceMap : public QMap { public: UbuntuResourceMap() : QMap() { insert("egldisplay", QMirClientNativeInterface::EglDisplay); insert("eglcontext", QMirClientNativeInterface::EglContext); insert("nativeorientation", QMirClientNativeInterface::NativeOrientation); insert("display", QMirClientNativeInterface::Display); insert("mirconnection", QMirClientNativeInterface::MirConnection); insert("mirwindow", QMirClientNativeInterface::MirWindow); insert("scale", QMirClientNativeInterface::Scale); insert("formfactor", QMirClientNativeInterface::FormFactor); } }; Q_GLOBAL_STATIC(UbuntuResourceMap, ubuntuResourceMap) QMirClientNativeInterface::QMirClientNativeInterface(const QMirClientClientIntegration *integration) : mIntegration(integration) , mGenericEventFilterType(QByteArrayLiteral("Event")) , mNativeOrientation(nullptr) { } QMirClientNativeInterface::~QMirClientNativeInterface() { delete mNativeOrientation; mNativeOrientation = nullptr; } void* QMirClientNativeInterface::nativeResourceForIntegration(const QByteArray &resourceString) { const QByteArray lowerCaseResource = resourceString.toLower(); if (!ubuntuResourceMap()->contains(lowerCaseResource)) { return nullptr; } const ResourceType resourceType = ubuntuResourceMap()->value(lowerCaseResource); if (resourceType == QMirClientNativeInterface::MirConnection) { return mIntegration->mirConnection(); } else { return nullptr; } } void* QMirClientNativeInterface::nativeResourceForContext( const QByteArray& resourceString, QOpenGLContext* context) { if (!context) return nullptr; const QByteArray kLowerCaseResource = resourceString.toLower(); if (!ubuntuResourceMap()->contains(kLowerCaseResource)) return nullptr; const ResourceType kResourceType = ubuntuResourceMap()->value(kLowerCaseResource); if (kResourceType == QMirClientNativeInterface::EglContext) return static_cast(context->handle())->eglContext(); else return nullptr; } void* QMirClientNativeInterface::nativeResourceForWindow(const QByteArray& resourceString, QWindow* window) { const QByteArray kLowerCaseResource = resourceString.toLower(); if (!ubuntuResourceMap()->contains(kLowerCaseResource)) return NULL; const ResourceType kResourceType = ubuntuResourceMap()->value(kLowerCaseResource); switch (kResourceType) { case EglDisplay: return mIntegration->eglDisplay(); case NativeOrientation: // Return the device's native screen orientation. if (window) { QMirClientScreen *ubuntuScreen = static_cast(window->screen()->handle()); mNativeOrientation = new Qt::ScreenOrientation(ubuntuScreen->nativeOrientation()); } else { QPlatformScreen *platformScreen = QGuiApplication::primaryScreen()->handle(); mNativeOrientation = new Qt::ScreenOrientation(platformScreen->nativeOrientation()); } return mNativeOrientation; case MirWindow: if (window) { auto ubuntuWindow = static_cast(window->handle()); if (ubuntuWindow) { return ubuntuWindow->mirWindow(); } else { return nullptr; } } else { return nullptr; } default: return nullptr; } } void* QMirClientNativeInterface::nativeResourceForScreen(const QByteArray& resourceString, QScreen* screen) { const QByteArray kLowerCaseResource = resourceString.toLower(); if (!ubuntuResourceMap()->contains(kLowerCaseResource)) return NULL; const ResourceType kResourceType = ubuntuResourceMap()->value(kLowerCaseResource); if (!screen) screen = QGuiApplication::primaryScreen(); auto ubuntuScreen = static_cast(screen->handle()); if (kResourceType == QMirClientNativeInterface::Display) { return mIntegration->eglNativeDisplay(); // Changes to the following properties are emitted via the QMirClientNativeInterface::screenPropertyChanged // signal fired by QMirClientScreen. Connect to this signal for these properties updates. // WARNING: code highly thread unsafe! } else if (kResourceType == QMirClientNativeInterface::Scale) { // In application code, read with: // float scale = *reinterpret_cast(nativeResourceForScreen("scale", screen())); return &ubuntuScreen->mScale; } else if (kResourceType == QMirClientNativeInterface::FormFactor) { return &ubuntuScreen->mFormFactor; } else return NULL; } // Changes to these properties are emitted via the QMirClientNativeInterface::windowPropertyChanged // signal fired by QMirClientWindow. Connect to this signal for these properties updates. QVariantMap QMirClientNativeInterface::windowProperties(QPlatformWindow *window) const { QVariantMap propertyMap; auto w = static_cast(window); if (w) { propertyMap.insert("scale", w->scale()); propertyMap.insert("formFactor", w->formFactor()); propertyMap.insert("persistentSurfaceId", w->persistentSurfaceId()); } return propertyMap; } QVariant QMirClientNativeInterface::windowProperty(QPlatformWindow *window, const QString &name) const { auto w = static_cast(window); if (!w) { return QVariant(); } if (name == QStringLiteral("scale")) { return w->scale(); } else if (name == QStringLiteral("formFactor")) { return w->formFactor(); } else if (name == QStringLiteral("persistentSurfaceId")) { return w->persistentSurfaceId(); } else { return QVariant(); } } QVariant QMirClientNativeInterface::windowProperty(QPlatformWindow *window, const QString &name, const QVariant &defaultValue) const { QVariant returnVal = windowProperty(window, name); if (!returnVal.isValid()) { return defaultValue; } else { return returnVal; } } ./src/ubuntumirclient/qmirclientscreen.cpp0000644000004100000410000002570413127642604021353 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2014-2017 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // local #include "qmirclientscreen.h" #include "qmirclientlogging.h" #include "qmirclientorientationchangeevent_p.h" #include "qmirclientnativeinterface.h" #include // Qt #include #include #include #include #include #include #include #define ENV_LOGICAL_DPI "QT_LOGICAL_DPI" static const int overrideDevicePixelRatio = qgetenv("QT_DEVICE_PIXEL_RATIO").toInt(); const float QMirClientScreen::mMirScaleToLogicalDpiMultiplier = 96.0; // by definition in qtmir static const char *orientationToStr(Qt::ScreenOrientation orientation) { switch (orientation) { case Qt::PrimaryOrientation: return "primary"; case Qt::PortraitOrientation: return "portrait"; case Qt::LandscapeOrientation: return "landscape"; case Qt::InvertedPortraitOrientation: return "inverted portrait"; case Qt::InvertedLandscapeOrientation: return "inverted landscape"; } Q_UNREACHABLE(); } const QEvent::Type OrientationChangeEvent::mType = static_cast(QEvent::registerEventType()); QMirClientScreen::QMirClientScreen(const MirOutput *output, MirConnection *connection) : mDevicePixelRatio(1.0) , mFormat(QImage::Format_RGB32) , mDepth(32) , mFormFactor{mir_form_factor_unknown} , mScale{1.0} , mOutputId(0) , mCursor(connection) { if (qEnvironmentVariableIsSet(ENV_LOGICAL_DPI)) { QByteArray stringValue = qgetenv(ENV_LOGICAL_DPI); bool ok; float value = stringValue.toFloat(&ok); if (ok && value > 0) { mLogicalDpiEnv = value; } } updateLogicalDpi(); setMirOutput(output); } QMirClientScreen::~QMirClientScreen() { } void QMirClientScreen::customEvent(QEvent* event) { Q_ASSERT(QThread::currentThread() == thread()); OrientationChangeEvent* oReadingEvent = static_cast(event); switch (oReadingEvent->mOrientation) { case OrientationChangeEvent::LeftUp: { mCurrentOrientation = (screen()->primaryOrientation() == Qt::LandscapeOrientation) ? Qt::InvertedPortraitOrientation : Qt::LandscapeOrientation; break; } case OrientationChangeEvent::TopUp: { mCurrentOrientation = (screen()->primaryOrientation() == Qt::LandscapeOrientation) ? Qt::LandscapeOrientation : Qt::PortraitOrientation; break; } case OrientationChangeEvent::RightUp: { mCurrentOrientation = (screen()->primaryOrientation() == Qt::LandscapeOrientation) ? Qt::PortraitOrientation : Qt::InvertedLandscapeOrientation; break; } case OrientationChangeEvent::TopDown: { mCurrentOrientation = (screen()->primaryOrientation() == Qt::LandscapeOrientation) ? Qt::InvertedLandscapeOrientation : Qt::InvertedPortraitOrientation; break; } } // Raise the event signal so that client apps know the orientation changed qCDebug(mirclient, "QMirClientScreen::customEvent - handling orientation change to %s", orientationToStr(mCurrentOrientation)); QWindowSystemInterface::handleScreenOrientationChange(screen(), mCurrentOrientation); } void QMirClientScreen::handleWindowSurfaceResize(int windowWidth, int windowHeight) { if ((windowWidth > windowHeight && mGeometry.width() < mGeometry.height()) || (windowWidth < windowHeight && mGeometry.width() > mGeometry.height())) { // The window aspect ratio differ's from the screen one. This means that // unity8 has rotated the window in its scene. // As there's no way to express window rotation in Qt's API, we have // Flip QScreen's dimensions so that orientation properties match // (primaryOrientation particularly). // FIXME: This assumes a phone scenario. Won't work, or make sense, // on the desktop QRect currGeometry = mGeometry; mGeometry.setWidth(currGeometry.height()); mGeometry.setHeight(currGeometry.width()); qCDebug(mirclient, "QMirClientScreen::handleWindowSurfaceResize - new screen geometry (w=%d, h=%d)", mGeometry.width(), mGeometry.height()); QWindowSystemInterface::handleScreenGeometryChange(screen(), mGeometry /* newGeometry */, mGeometry /* newAvailableGeometry */); if (mGeometry.width() < mGeometry.height()) { mCurrentOrientation = Qt::PortraitOrientation; } else { mCurrentOrientation = Qt::LandscapeOrientation; } qCDebug(mirclient, "QMirClientScreen::handleWindowSurfaceResize - new orientation %s",orientationToStr(mCurrentOrientation)); QWindowSystemInterface::handleScreenOrientationChange(screen(), mCurrentOrientation); } } void QMirClientScreen::setMirOutput(const MirOutput *output) { // Physical screen size (in mm) mPhysicalSize.setWidth(mir_output_get_physical_width_mm(output)); mPhysicalSize.setHeight(mir_output_get_physical_height_mm(output)); // Pixel Format // mFormat = qImageFormatFromMirPixelFormat(mir_output_get_current_pixel_format(output)); // GERRY: TODO // Pixel depth mDepth = 8 * MIR_BYTES_PER_PIXEL(mir_output_get_current_pixel_format(output)); // Mode = Resolution & refresh rate const MirOutputMode *mode = mir_output_get_current_mode(output); mNativeGeometry.setX(mir_output_get_position_x(output)); mNativeGeometry.setY(mir_output_get_position_y(output)); mNativeGeometry.setWidth(mir_output_mode_get_width(mode)); mNativeGeometry.setHeight(mir_output_mode_get_height(mode)); mRefreshRate = mir_output_mode_get_refresh_rate(mode); // UI scale & DPR mScale = mir_output_get_scale_factor(output); updateLogicalDpi(); if (overrideDevicePixelRatio > 0) { mDevicePixelRatio = overrideDevicePixelRatio; } else { mDevicePixelRatio = 1.0; // FIXME - need to determine suitable DPR for the specified scale } mFormFactor = mir_output_get_form_factor(output); mOutputId = mir_output_get_id(output); mGeometry.setX(mNativeGeometry.x()); mGeometry.setY(mNativeGeometry.y()); mGeometry.setWidth(mNativeGeometry.width()); mGeometry.setHeight(mNativeGeometry.height()); // Set the default orientation based on the initial screen dimensions. mNativeOrientation = (mGeometry.width() >= mGeometry.height()) ? Qt::LandscapeOrientation : Qt::PortraitOrientation; // If it's a landscape device (i.e. some tablets), start in landscape, otherwise portrait mCurrentOrientation = (mNativeOrientation == Qt::LandscapeOrientation) ? Qt::LandscapeOrientation : Qt::PortraitOrientation; } void QMirClientScreen::updateMirOutput(const MirOutput *output) { auto oldRefreshRate = mRefreshRate; auto oldScale = mScale; auto oldFormFactor = mFormFactor; auto oldGeometry = mGeometry; setMirOutput(output); // Emit change signals in particular order if (oldGeometry != mGeometry) { QWindowSystemInterface::handleScreenGeometryChange(screen(), mGeometry /* newGeometry */, mGeometry /* newAvailableGeometry */); } if (!qFuzzyCompare(mRefreshRate, oldRefreshRate)) { QWindowSystemInterface::handleScreenRefreshRateChange(screen(), mRefreshRate); } auto nativeInterface = static_cast(qGuiApp->platformNativeInterface()); if (!qFuzzyCompare(mScale, oldScale)) { nativeInterface->screenPropertyChanged(this, QStringLiteral("scale")); } if (mFormFactor != oldFormFactor) { nativeInterface->screenPropertyChanged(this, QStringLiteral("formFactor")); } } void QMirClientScreen::setAdditionalMirDisplayProperties(float scale, MirFormFactor formFactor, int /*dpi*/) { auto nativeInterface = static_cast(qGuiApp->platformNativeInterface()); if (!qFuzzyCompare(mScale, scale)) { mScale = scale; updateLogicalDpi(); nativeInterface->screenPropertyChanged(this, QStringLiteral("scale")); } if (mFormFactor != formFactor) { mFormFactor = formFactor; nativeInterface->screenPropertyChanged(this, QStringLiteral("formFactor")); } } QDpi QMirClientScreen::logicalDpi() const { return mLogicalDpi; } void QMirClientScreen::updateLogicalDpi() { auto oldDpi = mLogicalDpi; if (mLogicalDpiEnv != 0) { mLogicalDpi.first = mLogicalDpi.second = mLogicalDpiEnv; } else { mLogicalDpi.first = mLogicalDpi.second = mScale * mMirScaleToLogicalDpiMultiplier; } if (oldDpi.first != 0 && oldDpi.second != 0 && oldDpi != mLogicalDpi) { QWindowSystemInterface::handleScreenLogicalDotsPerInchChange(screen(), mLogicalDpi.first, mLogicalDpi.second); } } ./src/ubuntumirclient/qmirclientinput.cpp0000644000004100000410000006411613127642576021243 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2014-2017 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // Local #include "qmirclientinput.h" #include "qmirclientintegration.h" #include "qmirclientnativeinterface.h" #include "qmirclientscreen.h" #include "qmirclientwindow.h" #include "qmirclientlogging.h" #include "qmirclientorientationchangeevent_p.h" // Qt #include #include #include #include #include #include #include #include #include #include Q_LOGGING_CATEGORY(mirclientInput, "qt.qpa.mirclient.input", QtWarningMsg) namespace { // XKB Keysyms which do not map directly to Qt types (i.e. Unicode points) static const uint32_t KeyTable[] = { XKB_KEY_Escape, Qt::Key_Escape, XKB_KEY_Tab, Qt::Key_Tab, XKB_KEY_ISO_Left_Tab, Qt::Key_Backtab, XKB_KEY_BackSpace, Qt::Key_Backspace, XKB_KEY_Return, Qt::Key_Return, XKB_KEY_Insert, Qt::Key_Insert, XKB_KEY_Delete, Qt::Key_Delete, XKB_KEY_Clear, Qt::Key_Delete, XKB_KEY_Pause, Qt::Key_Pause, XKB_KEY_Print, Qt::Key_Print, XKB_KEY_Home, Qt::Key_Home, XKB_KEY_End, Qt::Key_End, XKB_KEY_Left, Qt::Key_Left, XKB_KEY_Up, Qt::Key_Up, XKB_KEY_Right, Qt::Key_Right, XKB_KEY_Down, Qt::Key_Down, XKB_KEY_Prior, Qt::Key_PageUp, XKB_KEY_Next, Qt::Key_PageDown, XKB_KEY_Shift_L, Qt::Key_Shift, XKB_KEY_Shift_R, Qt::Key_Shift, XKB_KEY_Shift_Lock, Qt::Key_Shift, XKB_KEY_Control_L, Qt::Key_Control, XKB_KEY_Control_R, Qt::Key_Control, XKB_KEY_Meta_L, Qt::Key_Meta, XKB_KEY_Meta_R, Qt::Key_Meta, XKB_KEY_Alt_L, Qt::Key_Alt, XKB_KEY_Alt_R, Qt::Key_Alt, XKB_KEY_Caps_Lock, Qt::Key_CapsLock, XKB_KEY_Num_Lock, Qt::Key_NumLock, XKB_KEY_Scroll_Lock, Qt::Key_ScrollLock, XKB_KEY_Super_L, Qt::Key_Super_L, XKB_KEY_Super_R, Qt::Key_Super_R, XKB_KEY_Menu, Qt::Key_Menu, XKB_KEY_Hyper_L, Qt::Key_Hyper_L, XKB_KEY_Hyper_R, Qt::Key_Hyper_R, XKB_KEY_Help, Qt::Key_Help, XKB_KEY_KP_Space, Qt::Key_Space, XKB_KEY_KP_Tab, Qt::Key_Tab, XKB_KEY_KP_Enter, Qt::Key_Enter, XKB_KEY_KP_Home, Qt::Key_Home, XKB_KEY_KP_Left, Qt::Key_Left, XKB_KEY_KP_Up, Qt::Key_Up, XKB_KEY_KP_Right, Qt::Key_Right, XKB_KEY_KP_Down, Qt::Key_Down, XKB_KEY_KP_Prior, Qt::Key_PageUp, XKB_KEY_KP_Next, Qt::Key_PageDown, XKB_KEY_KP_End, Qt::Key_End, XKB_KEY_KP_Begin, Qt::Key_Clear, XKB_KEY_KP_Insert, Qt::Key_Insert, XKB_KEY_KP_Delete, Qt::Key_Delete, XKB_KEY_KP_Equal, Qt::Key_Equal, XKB_KEY_KP_Multiply, Qt::Key_Asterisk, XKB_KEY_KP_Add, Qt::Key_Plus, XKB_KEY_KP_Separator, Qt::Key_Comma, XKB_KEY_KP_Subtract, Qt::Key_Minus, XKB_KEY_KP_Decimal, Qt::Key_Period, XKB_KEY_KP_Divide, Qt::Key_Slash, XKB_KEY_ISO_Level3_Shift, Qt::Key_AltGr, XKB_KEY_Multi_key, Qt::Key_Multi_key, XKB_KEY_Codeinput, Qt::Key_Codeinput, XKB_KEY_SingleCandidate, Qt::Key_SingleCandidate, XKB_KEY_MultipleCandidate, Qt::Key_MultipleCandidate, XKB_KEY_PreviousCandidate, Qt::Key_PreviousCandidate, // dead keys XKB_KEY_dead_grave, Qt::Key_Dead_Grave, XKB_KEY_dead_acute, Qt::Key_Dead_Acute, XKB_KEY_dead_circumflex, Qt::Key_Dead_Circumflex, XKB_KEY_dead_tilde, Qt::Key_Dead_Tilde, XKB_KEY_dead_macron, Qt::Key_Dead_Macron, XKB_KEY_dead_breve, Qt::Key_Dead_Breve, XKB_KEY_dead_abovedot, Qt::Key_Dead_Abovedot, XKB_KEY_dead_diaeresis, Qt::Key_Dead_Diaeresis, XKB_KEY_dead_abovering, Qt::Key_Dead_Abovering, XKB_KEY_dead_doubleacute, Qt::Key_Dead_Doubleacute, XKB_KEY_dead_caron, Qt::Key_Dead_Caron, XKB_KEY_dead_cedilla, Qt::Key_Dead_Cedilla, XKB_KEY_dead_ogonek, Qt::Key_Dead_Ogonek, XKB_KEY_dead_iota, Qt::Key_Dead_Iota, XKB_KEY_dead_voiced_sound, Qt::Key_Dead_Voiced_Sound, XKB_KEY_dead_semivoiced_sound, Qt::Key_Dead_Semivoiced_Sound, XKB_KEY_dead_belowdot, Qt::Key_Dead_Belowdot, XKB_KEY_dead_hook, Qt::Key_Dead_Hook, XKB_KEY_dead_horn, Qt::Key_Dead_Horn, XKB_KEY_Mode_switch, Qt::Key_Mode_switch, XKB_KEY_script_switch, Qt::Key_Mode_switch, XKB_KEY_XF86AudioRaiseVolume, Qt::Key_VolumeUp, XKB_KEY_XF86AudioLowerVolume, Qt::Key_VolumeDown, XKB_KEY_XF86PowerOff, Qt::Key_PowerOff, XKB_KEY_XF86PowerDown, Qt::Key_PowerDown, 0, 0 }; Qt::WindowState mirWindowStateToQt(MirWindowState state) { switch (state) { case mir_window_state_fullscreen: return Qt::WindowFullScreen; case mir_window_state_maximized: case mir_window_state_vertmaximized: case mir_window_state_horizmaximized: return Qt::WindowMaximized; case mir_window_state_minimized: return Qt::WindowMinimized; case mir_window_state_hidden: // We should be handling this state separately. Q_ASSERT(false); case mir_window_state_restored: case mir_window_state_unknown: default: return Qt::WindowNoState; } } } // namespace class UbuntuEvent : public QEvent { public: UbuntuEvent(QMirClientWindow* window, const MirEvent *event, QEvent::Type type) : QEvent(type), window(window) { nativeEvent = mir_event_ref(event); } ~UbuntuEvent() { mir_event_unref(nativeEvent); } QPointer window; const MirEvent *nativeEvent; }; QMirClientInput::QMirClientInput(QMirClientClientIntegration* integration) : QObject(nullptr) , mIntegration(integration) , mEventFilterType(static_cast( integration->nativeInterface())->genericEventFilterType()) , mEventType(static_cast(QEvent::registerEventType())) , mLastInputWindow(nullptr) { // Initialize touch device. mTouchDevice = new QTouchDevice; mTouchDevice->setType(QTouchDevice::TouchScreen); mTouchDevice->setCapabilities( QTouchDevice::Position | QTouchDevice::Area | QTouchDevice::Pressure | QTouchDevice::NormalizedPosition); QWindowSystemInterface::registerTouchDevice(mTouchDevice); } QMirClientInput::~QMirClientInput() { // Qt will take care of deleting mTouchDevice. } static const char* nativeEventTypeToStr(MirEventType t) { switch (t) { case mir_event_type_key: return "key"; case mir_event_type_motion: return "motion"; case mir_event_type_window: return "window"; case mir_event_type_resize: return "resize"; case mir_event_type_prompt_session_state_change: return "prompt_session_state_change"; case mir_event_type_orientation: return "orientation"; case mir_event_type_close_window: return "close_window"; case mir_event_type_input: return "input"; case mir_event_type_keymap: return "keymap"; case mir_event_type_window_output: return "window_output"; case mir_event_type_input_device_state: return "input_device_state"; case mir_event_type_window_placement: return "window_placement"; default: Q_UNREACHABLE(); } Q_UNREACHABLE(); } void QMirClientInput::customEvent(QEvent* event) { Q_ASSERT(QThread::currentThread() == thread()); UbuntuEvent* ubuntuEvent = static_cast(event); const MirEvent *nativeEvent = ubuntuEvent->nativeEvent; if ((ubuntuEvent->window == nullptr) || (ubuntuEvent->window->window() == nullptr)) { qCWarning(mirclient) << "Attempted to deliver an event to a non-existent window, ignoring."; return; } // Event filtering. long result; if (QWindowSystemInterface::handleNativeEvent( ubuntuEvent->window->window(), mEventFilterType, const_cast(static_cast(nativeEvent)), &result) == true) { qCDebug(mirclient, "event filtered out by native interface"); return; } qCDebug(mirclientInput, "customEvent(type=%s)", nativeEventTypeToStr(mir_event_get_type(nativeEvent))); // Event dispatching. switch (mir_event_get_type(nativeEvent)) { case mir_event_type_input: dispatchInputEvent(ubuntuEvent->window, mir_event_get_input_event(nativeEvent)); break; case mir_event_type_resize: { auto resizeEvent = mir_event_get_resize_event(nativeEvent); // Enable workaround for Screen rotation auto const targetWindow = ubuntuEvent->window; if (targetWindow) { auto const screen = static_cast(targetWindow->screen()); if (screen) { screen->handleWindowSurfaceResize( mir_resize_event_get_width(resizeEvent), mir_resize_event_get_height(resizeEvent)); } targetWindow->handleSurfaceResized( mir_resize_event_get_width(resizeEvent), mir_resize_event_get_height(resizeEvent)); } break; } case mir_event_type_window: handleWindowEvent(ubuntuEvent->window, mir_event_get_window_event(nativeEvent)); break; case mir_event_type_window_output: handleWindowOutputEvent(ubuntuEvent->window, mir_event_get_window_output_event(nativeEvent)); break; case mir_event_type_orientation: dispatchOrientationEvent(ubuntuEvent->window->window(), mir_event_get_orientation_event(nativeEvent)); break; case mir_event_type_close_window: QWindowSystemInterface::handleCloseEvent(ubuntuEvent->window->window()); break; default: qCDebug(mirclient, "unhandled event type: %d", static_cast(mir_event_get_type(nativeEvent))); } } void QMirClientInput::postEvent(QMirClientWindow *platformWindow, const MirEvent *event) { QWindow *window = platformWindow->window(); QCoreApplication::postEvent(this, new UbuntuEvent( platformWindow, event, mEventType)); if ((window->flags().testFlag(Qt::WindowTransparentForInput)) && window->parent()) { QCoreApplication::postEvent(this, new UbuntuEvent( static_cast(platformWindow->QPlatformWindow::parent()), event, mEventType)); } } void QMirClientInput::dispatchInputEvent(QMirClientWindow *window, const MirInputEvent *ev) { switch (mir_input_event_get_type(ev)) { case mir_input_event_type_key: dispatchKeyEvent(window, ev); break; case mir_input_event_type_touch: dispatchTouchEvent(window, ev); break; case mir_input_event_type_pointer: dispatchPointerEvent(window, ev); break; case mir_input_event_types: Q_UNREACHABLE(); } } void QMirClientInput::dispatchTouchEvent(QMirClientWindow *window, const MirInputEvent *ev) { const MirTouchEvent *tev = mir_input_event_get_touch_event(ev); // FIXME(loicm) Max pressure is device specific. That one is for the Samsung Galaxy Nexus. That // needs to be fixed as soon as the compat input lib adds query support. const float kMaxPressure = 1.28; const QRect kWindowGeometry = window->geometry(); QList touchPoints; // TODO: Is it worth setting the Qt::TouchPointStationary ones? Currently they are left // as Qt::TouchPointMoved const unsigned int kPointerCount = mir_touch_event_point_count(tev); for (unsigned int i = 0; i < kPointerCount; ++i) { QWindowSystemInterface::TouchPoint touchPoint; const float kX = mir_touch_event_axis_value(tev, i, mir_touch_axis_x) + kWindowGeometry.x(); const float kY = mir_touch_event_axis_value(tev, i, mir_touch_axis_y) + kWindowGeometry.y(); // see bug lp:1346633 workaround comments elsewhere const float kW = mir_touch_event_axis_value(tev, i, mir_touch_axis_touch_major); const float kH = mir_touch_event_axis_value(tev, i, mir_touch_axis_touch_minor); const float kP = mir_touch_event_axis_value(tev, i, mir_touch_axis_pressure); touchPoint.id = mir_touch_event_id(tev, i); touchPoint.normalPosition = QPointF(kX / kWindowGeometry.width(), kY / kWindowGeometry.height()); touchPoint.area = QRectF(kX - (kW / 2.0), kY - (kH / 2.0), kW, kH); touchPoint.pressure = kP / kMaxPressure; MirTouchAction touch_action = mir_touch_event_action(tev, i); switch (touch_action) { case mir_touch_action_down: mLastInputWindow = window; touchPoint.state = Qt::TouchPointPressed; break; case mir_touch_action_up: touchPoint.state = Qt::TouchPointReleased; break; case mir_touch_action_change: touchPoint.state = Qt::TouchPointMoved; break; case mir_touch_actions: Q_UNREACHABLE(); } touchPoints.append(touchPoint); } ulong timestamp = mir_input_event_get_event_time(ev) / 1000000; QWindowSystemInterface::handleTouchEvent(window->window(), timestamp, mTouchDevice, touchPoints); } static uint32_t translateKeysym(uint32_t sym, const QString &text) { int code = 0; QTextCodec *systemCodec = QTextCodec::codecForLocale(); if (sym < 128 || (sym < 256 && systemCodec->mibEnum() == 4)) { // upper-case key, if known code = isprint((int)sym) ? toupper((int)sym) : 0; } else if (sym >= XKB_KEY_F1 && sym <= XKB_KEY_F35) { return Qt::Key_F1 + (int(sym) - XKB_KEY_F1); } else if (text.length() == 1 && text.unicode()->unicode() > 0x1f && text.unicode()->unicode() != 0x7f && !(sym >= XKB_KEY_dead_grave && sym <= XKB_KEY_dead_currency)) { code = text.unicode()->toUpper().unicode(); } else { for (int i = 0; KeyTable[i]; i += 2) if (sym == KeyTable[i]) code = KeyTable[i + 1]; } return code; } namespace { Qt::KeyboardModifiers qt_modifiers_from_mir(MirInputEventModifiers modifiers) { Qt::KeyboardModifiers q_modifiers = Qt::NoModifier; if (modifiers & mir_input_event_modifier_shift) { q_modifiers |= Qt::ShiftModifier; } if (modifiers & mir_input_event_modifier_ctrl) { q_modifiers |= Qt::ControlModifier; } if (modifiers & mir_input_event_modifier_alt_left) { q_modifiers |= Qt::AltModifier; } if (modifiers & mir_input_event_modifier_meta) { q_modifiers |= Qt::MetaModifier; } if (modifiers & mir_input_event_modifier_alt_right) { q_modifiers |= Qt::GroupSwitchModifier; } return q_modifiers; } } void QMirClientInput::dispatchKeyEvent(QMirClientWindow *window, const MirInputEvent *event) { const MirKeyboardEvent *key_event = mir_input_event_get_keyboard_event(event); ulong timestamp = mir_input_event_get_event_time(event) / 1000000; xkb_keysym_t xk_sym = mir_keyboard_event_key_code(key_event); quint32 scan_code = mir_keyboard_event_scan_code(key_event); quint32 native_modifiers = mir_keyboard_event_modifiers(key_event); // Key modifier and unicode index mapping. auto modifiers = qt_modifiers_from_mir(native_modifiers); MirKeyboardAction action = mir_keyboard_event_action(key_event); QEvent::Type keyType = action == mir_keyboard_action_up ? QEvent::KeyRelease : QEvent::KeyPress; if (action == mir_keyboard_action_down) mLastInputWindow = window; QString text; QVarLengthArray chars(32); { int result = xkb_keysym_to_utf8(xk_sym, chars.data(), chars.size()); if (result > 0) { text = QString::fromUtf8(chars.constData()); } } int sym = translateKeysym(xk_sym, text); bool is_auto_rep = action == mir_keyboard_action_repeat; QPlatformInputContext *context = QGuiApplicationPrivate::platformIntegration()->inputContext(); if (context) { QKeyEvent qKeyEvent(keyType, sym, modifiers, scan_code, xk_sym, native_modifiers, text, is_auto_rep); qKeyEvent.setTimestamp(timestamp); if (context->filterEvent(&qKeyEvent)) { qCDebug(mirclient, "key event filtered out by input context"); return; } } QWindowSystemInterface::handleExtendedKeyEvent(window->window(), timestamp, keyType, sym, modifiers, scan_code, xk_sym, native_modifiers, text, is_auto_rep); } namespace { Qt::MouseButtons extract_buttons(const MirPointerEvent *pev) { Qt::MouseButtons buttons = Qt::NoButton; if (mir_pointer_event_button_state(pev, mir_pointer_button_primary)) buttons |= Qt::LeftButton; if (mir_pointer_event_button_state(pev, mir_pointer_button_secondary)) buttons |= Qt::RightButton; if (mir_pointer_event_button_state(pev, mir_pointer_button_tertiary)) buttons |= Qt::MiddleButton; if (mir_pointer_event_button_state(pev, mir_pointer_button_back)) buttons |= Qt::BackButton; if (mir_pointer_event_button_state(pev, mir_pointer_button_forward)) buttons |= Qt::ForwardButton; return buttons; } } void QMirClientInput::dispatchPointerEvent(QMirClientWindow *platformWindow, const MirInputEvent *ev) { const auto window = platformWindow->window(); const auto timestamp = mir_input_event_get_event_time(ev) / 1000000; const auto pev = mir_input_event_get_pointer_event(ev); const auto action = mir_pointer_event_action(pev); const auto modifiers = qt_modifiers_from_mir(mir_pointer_event_modifiers(pev)); const auto localPoint = QPointF(mir_pointer_event_axis_value(pev, mir_pointer_axis_x), mir_pointer_event_axis_value(pev, mir_pointer_axis_y)); mLastInputWindow = platformWindow; switch (action) { case mir_pointer_action_button_up: case mir_pointer_action_button_down: case mir_pointer_action_motion: { const float hDelta = mir_pointer_event_axis_value(pev, mir_pointer_axis_hscroll); const float vDelta = mir_pointer_event_axis_value(pev, mir_pointer_axis_vscroll); if (hDelta != 0 || vDelta != 0) { // QWheelEvent::DefaultDeltasPerStep = 120 but doesn't exist on vivid const QPoint angleDelta(120 * hDelta, 120 * vDelta); QWindowSystemInterface::handleWheelEvent(window, timestamp, localPoint, window->position() + localPoint, QPoint(), angleDelta, modifiers, Qt::ScrollUpdate); } auto buttons = extract_buttons(pev); QWindowSystemInterface::handleMouseEvent(window, timestamp, localPoint, window->position() + localPoint /* Should we omit global point instead? */, buttons, modifiers); break; } case mir_pointer_action_enter: QWindowSystemInterface::handleEnterEvent(window, localPoint, window->position() + localPoint); break; case mir_pointer_action_leave: QWindowSystemInterface::handleLeaveEvent(window); break; case mir_pointer_actions: Q_UNREACHABLE(); } } static const char* nativeOrientationDirectionToStr(MirOrientation orientation) { switch (orientation) { case mir_orientation_normal: return "Normal"; case mir_orientation_left: return "Left"; case mir_orientation_inverted: return "Inverted"; case mir_orientation_right: return "Right"; } Q_UNREACHABLE(); } void QMirClientInput::dispatchOrientationEvent(QWindow *window, const MirOrientationEvent *event) { MirOrientation mir_orientation = mir_orientation_event_get_direction(event); qCDebug(mirclientInput, "orientation direction: %s", nativeOrientationDirectionToStr(mir_orientation)); if (!window->screen()) { qCDebug(mirclient, "Window has no associated screen, dropping orientation event"); return; } OrientationChangeEvent::Orientation orientation; switch (mir_orientation) { case mir_orientation_normal: orientation = OrientationChangeEvent::TopUp; break; case mir_orientation_left: orientation = OrientationChangeEvent::LeftUp; break; case mir_orientation_inverted: orientation = OrientationChangeEvent::TopDown; break; case mir_orientation_right: orientation = OrientationChangeEvent::RightUp; break; default: qCDebug(mirclient, "No such orientation %d", mir_orientation); return; } // Dispatch orientation event to [Platform]Screen, as that is where Qt reads it. Screen will handle // notifying Qt of the actual orientation change - done to prevent multiple Windows each creating // an identical orientation change event and passing it directly to Qt. // [Platform]Screen can also factor in the native orientation. QCoreApplication::postEvent(static_cast(window->screen()->handle()), new OrientationChangeEvent(OrientationChangeEvent::mType, orientation)); } void QMirClientInput::handleWindowEvent(const QPointer &window, const MirWindowEvent *event) { auto windowEventAttribute = mir_window_event_get_attribute(event); switch (windowEventAttribute) { case mir_window_attrib_focus: { window->handleSurfaceFocusChanged( mir_window_event_get_attribute_value(event) == mir_window_focus_state_focused); break; } case mir_window_attrib_visibility: { window->handleSurfaceExposeChange( mir_window_event_get_attribute_value(event) == mir_window_visibility_exposed); break; } // Remaining attributes are ones client sets for server, and server should not override them case mir_window_attrib_state: { MirWindowState state = static_cast(mir_window_event_get_attribute_value(event)); if (state == mir_window_state_hidden) { window->handleSurfaceVisibilityChanged(false); } else { // it's visible! window->handleSurfaceVisibilityChanged(true); window->handleSurfaceStateChanged(mirWindowStateToQt(state)); } break; } case mir_window_attrib_type: case mir_window_attrib_swapinterval: case mir_window_attrib_dpi: case mir_window_attrib_preferred_orientation: case mir_window_attribs: break; } } void QMirClientInput::handleWindowOutputEvent(const QPointer &window, const MirWindowOutputEvent *event) { const uint32_t outputId = mir_window_output_event_get_output_id(event); const int dpi = mir_window_output_event_get_dpi(event); const MirFormFactor formFactor = mir_window_output_event_get_form_factor(event); const float scale = mir_window_output_event_get_scale(event); const auto screenObserver = mIntegration->screenObserver(); QMirClientScreen *screen = screenObserver->findScreenWithId(outputId); if (!screen) { qCWarning(mirclient) << "Mir notified window" << window->window() << "on an unknown screen with id" << outputId; return; } screenObserver->handleScreenPropertiesChange(screen, dpi, formFactor, scale); window->handleScreenPropertiesChange(formFactor, scale); if (window->screen() != screen) { QWindowSystemInterface::handleWindowScreenChanged(window->window(), screen->screen()); } } ./src/ubuntumirclient/qmirclientclipboard.h0000644000004100000410000000640013127642576021500 0ustar www-datawww-data/**************************************************************************** ** ** Copyright (C) 2016 Canonical, Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMIRCLIENTCLIPBOARD_H #define QMIRCLIENTCLIPBOARD_H #include #include #include namespace com { namespace ubuntu { namespace content { class Hub; } } } class QDBusPendingCallWatcher; class QMirClientClipboard : public QObject, public QPlatformClipboard { Q_OBJECT public: QMirClientClipboard(); virtual ~QMirClientClipboard(); // QPlatformClipboard methods. QMimeData* mimeData(QClipboard::Mode mode = QClipboard::Clipboard) override; void setMimeData(QMimeData* data, QClipboard::Mode mode = QClipboard::Clipboard) override; bool supportsMode(QClipboard::Mode mode) const override; bool ownsMode(QClipboard::Mode mode) const override; private Q_SLOTS: void onApplicationStateChanged(Qt::ApplicationState state); private: void updateMimeData(); void requestMimeData(); QMimeData *mMimeData; enum { OutdatedClipboard, // Our mimeData is outdated, need to fetch latest from ContentHub SyncingClipboard, // Our mimeData is outdated and we are waiting for ContentHub to reply with the latest paste SyncedClipboard // Our mimeData is in sync with what ContentHub has } mClipboardState{OutdatedClipboard}; com::ubuntu::content::Hub *mContentHub; QDBusPendingCallWatcher *mPasteReply{nullptr}; }; #endif // QMIRCLIENTCLIPBOARD_H ./COPYING.LGPL0000644000004100000410000001674313127642576013063 0ustar www-datawww-data GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. ./qtubuntu.pro0000644000004100000410000000004213127642576013665 0ustar www-datawww-dataTEMPLATE = subdirs SUBDIRS += src