This commit is contained in:
寂静的羽夏 2022-07-16 17:39:56 +08:00
parent e2caea3ff2
commit ca794cf910
71 changed files with 6804 additions and 1933 deletions

View File

@ -1,73 +0,0 @@
WingSummer Commercial License
Last Updated: June 11, 2022.
COMMERCIAL SOFTWARE LICENSE AGREEMENT
PLEASE READ THE FOLLOWING TERMS AND CONDITIONS CAREFULLY BEFORE DOWNLOADING, INSTALLING OR USING THE SOFTWARE THAT ACCOMPANIES THIS SOFTWARE LICENSE AGREEMENT OR ANY ACCOMPANYING DOCUMENTATION (COLLECTIVELY, AND INCLUDING ANY UPDATES THERETO PROVIDED BY WINGSUMMER, THE “SOFTWARE”).
THE TERMS AND CONDITIONS OF THIS SOFTWARE LICENSE AGREEMENT AND THE ORDER FOR THE SOFTWARE THAT YOU AGREED TO (“ORDER”) AND, [COLLECTIVELY WITH THE ORDER AND] THIS SOFTWARE LICENSE AGREEMENT, THIS “AGREEMENT”) ARE AN AGREEMENT BETWEEN YOU AND WINGSUMMER AND GOVERN USE OF THE SOFTWARE, UNLESS YOU AND WINGSUMMER HAVE EXECUTED A SEPARATE WRITTEN AGREEMENT GOVERNING USE OF THE SOFTWARE.
WingSummer is willing to license the Software to you only upon the condition that you accept all the terms contained in this Agreement. By downloading, installing or using the Software, you have indicated that you understand this Agreement and accept all of its terms. If you are accepting the terms of this Agreement on behalf of a company or other legal entity, you represent and warrant that you have the authority to bind that company or other legal entity to the terms of this Agreement, and, in such event, “you” and “your” will refer to that company or other legal entity. If you do not accept all of the terms of this Agreement, then WingSummer is unwilling to license the Software to you, and you must return the Software to WingSummer or destroy all copies of the Software.
1. License.
1.1 License Grant. Subject to your compliance with the terms and conditions of this Agreement (including payment of the applicable fees in accordance with Section 3), WingSummer grants to you a non-exclusive, non-transferable, non-sublicenseable, worldwide limited license to (a) use the software products internally, in executable code form, and related Documentation (as defined in Section 6.1), as specified in the Order, including any error corrections, modifications and updates thereto provided by WingSummer to you under this Agreement (the “Software”), but only in the Licensed Configuration and only during the term of this Agreement and (b) copy and adapt the Software as provided herein. For purposes of this Agreement, “Licensed Configuration” means the features and usage limits for a specified time period, in each case, as specified in the Order. Your use of the Software is further limited according to the license type and other terms in the Order. You may copy the Software, as reasonably required to exercise your rights under this Section 1.1, and you may make a reasonable number of copies for backup or archival purposes.
1.2 Benefit of Third Parties. If the Order specifies a Right to Embed the Software for the benefit of end users, then the license in Section 1.1 shall be modified to allow you to operate the Software within a Customer Application (identified on the Order Form) and allow your end user customers (“End Users”) to access the Software as a part of the Customer Application.
1.3. Distribution License. If the Order specifies a Right to Distribute, then subject to your compliance with the terms and conditions of this Agreement (including payment of the applicable fees in accordance with Section 3), WingSummer grants to you a non-exclusive, non-transferable, non-sublicenseable, worldwide limited license to distribute the Software to End Users (i) as embedded in the Customer Application identified in the Order Form, (ii) solely for use by the end users of the Customer Application and not for further distribution and (iii) provided the End User executes an end user license agreement that protects WingSummer to the same extent this Agreement protects WingSummer (“End User License Agreement”).
1.4. Source Code Access; Modifications. Solely if your license type and pricing tier, as specified in the Order, includes access to the source code of the Software, subject to your compliance with the terms and conditions of this Agreement (including payment of the applicable fees in accordance with Section 3), WingSummer grants to you a non-exclusive, non-transferable, worldwide limited license to (i) use, reproduce, modify and create derivative works based upon the Software, solely for the purpose of customizing the Software to interface, embed, combine, or otherwise use with your products or services (as distributed to your customers). Notwithstanding anything to the contrary, you agree that you have the right to use any and all modifications, customizations, enhancements and extensions to the Software to the same extent, and solely to such extent, that you have the right to use the Software pursuant to this Agreement and your valid subscription. In addition, WingSummer prohibits you from modifying, and you agree not to modify, the Software (a) to enable features not available to customers at your license type and pricing tier by contacting me; or (b) to disable usage limits.
1.5. Limited Rights; License Restrictions. Your rights in the Software will be limited to those expressly granted in this Agreement. WingSummer reserves all rights and licenses in and to the Software not expressly granted to you under this Agreement. Except as expressly provided in this Agreement, you will not: (i) copy or modify the Software, in whole or in part; (ii) transfer, sublicense, lease, lend or rent or otherwise distribute the Software to any third party; (iii) make the functionality of the Software available to third-party users through any means; or (iv) disassemble, decompile or reverse engineer the Software or permit or authorize a third party to do so, except to the extent such restrictions are expressly prohibited by law.
1.6. Ownership. You expressly acknowledge that, as between WingSummer and you, WingSummer and its licensors own all worldwide right, title and interest in and to the Software, including all worldwide patent rights, copyrights, trade secrets, know-how and any other intellectual property rights embodied therein. You will not delete or in any manner alter the copyright, trademark or other proprietary rights notices appearing on the Software as delivered to you. You will reproduce such notices on all copies you make of the Software. Subject to Section 1.4, you will own your modifications to the Software (“Modifications”); provided that your ownership thereof will be subject to WingSummerss underlying intellectual property rights in the Software. At your option, you may submit your Modifications to the WingSummer open source project. In addition, you own all worldwide right, title and interest in and to all your data that is processed by the Software and the analyses that are generated by the Software based on such data.
1.7. Verification and Audit. At WingSummers written request, you will furnish WingSummer with an officers written certification verifying that the Software is being used in accordance with the terms of this Agreement. Upon at least thirty (30) days prior written notice, WingSummer may audit your use of the Software to ensure that you are in compliance with the terms of this Agreement, provided that no audit may take longer than 30 days to complete, and further provided that all individuals involved in the audit must sign a non-disclosure agreement consistent with Section 5, make no copies of documents, remove no materials from your premises, and agree to comply with all of your reasonable rules, policies and instructions that apply to persons accessing your premises or systems . If an audit reveals that you have underpaid fees to WingSummer during the period audited, then you will promptly pay WingSummer for such underpaid fees based on WingSummers price list in effect at the time the audit is completed.
2. Obligations and Support.
2.1 Customer Support by WingSummer. Subject to your compliance with the terms and conditions of this Agreement (including payment of the applicable fees in accordance with Section 3), WingSummer will make available to you at no additional cost WingSummers standard support for the license type and pricing tier specified in the Order in accordance with WingSummers then-standard support terms. WingSummer reserves the right to designate any additional new content or features as requiring separate payment or purchase of a separate subscription at any time. If you have entered into a separate support or similar agreement with WingSummer, then WingSummer will provide Software maintenance and support in accordance with the terms of that agreement, not this Agreement. For the avoidance of doubt, WingSummer shall have no obligation to provide support to End Users or any users of the Customer Application.
2.2 Customer Obligations. Customer shall make no representations or warranties with respect to the Software or any related services beyond those contained herein. Customer shall be solely responsible for, and WingSummer shall have no legal obligation to honor, any warranties that Customer provides to End Users to the extent that such warranties are broader or greater in scope than those made by WingSummer to Customer hereunder. Customer shall defend, indemnify and hold WingSummer and its affiliated companies harmless from any and all costs, losses, damages, liabilities and expenses (including reasonable attorneys fees and costs of litigation) resulting from Customers failure to comply with this Section.
3. Payment.
3.1 Subscription Fees. You will pay the fees and charges stated in the Order (“Subscription Fees”) for use of the Software. The base Subscription Fee for each Subscription Term (as defined in Section 4) will be specified in the Order (“Base Subscription Fee”) and is payable and charged at the beginning of each Subscription Term.
3.2 Units; True-Up. If specified in the Order, Subscription Fees will be calculated based on units of use of the Software (such as per server, per installation, per customer or per user) (each, a “Unit”). Where applicable, the Base Subscription Fee includes the number of Units specified in the Order for each Subscription Term. At the end of each Subscription Term, you will promptly confirm in writing to WingSummer (at the latest within five (5) business days of a request from WingSummer) the number of Units used by you during that Subscription Term. If your actual usage of the Software exceeds the Units covered by the Base Subscription Fee prepaid by you for a Subscription Term, WingSummer will charge you for the difference between the Units covered by the Base Subscription Fee and the number of Units actually used by you during that Subscription Term (“Additional Units Fee”).
3.3 Payment Terms. Because it is my own project,and is not the project of any company,only Wechat payment and Alipay payment are allowed.The payment QR codes are shown in the WingHexExplorer's code repository ,and I'm very sorry I can not issue an invoice to you.All amounts are stated and shall be paid in yuan and are exclusive of taxes. You are responsible for payment of all Taxes and any related interest and/or penalties resulting from any payments made to us, other than any taxes based on WingSummers net income. Except as specifically outlined in Section 4 and Section 7.3, all fees are non-refundable.
4. Term and Termination.
This Agreement will commence on the Effective Date and, unless terminated earlier in accordance with the terms of this Section 4, will continue in effect for the initial subscription term specified in the Order. At the end of such initial subscription term and each renewal subscription term thereafter, subject always to timely payment of the Subscription Fees, this Agreement will automatically renew for additional renewal subscription terms having the duration specified in the Order (or if no renewal term length is stated in the Order, having the same duration as the Initial Subscription Term), unless either party provides at least 30 days prior written notice of non-renewal. Such initial subscription term and each renewal subscription term are each individually referred to herein as a “Subscription Term.” Each party will have the right to terminate this Agreement if the other party breaches this Agreement and fails to cure such breach within 10 days after written notice thereof, provided that, for breaches that cannot be cured using reasonable efforts within 10 days, then up to an additional 20 days to cure. Notwithstanding the foregoing, if you fail to pay the applicable fees as specified in the Order and this Agreement, and that failure persists for 5 days after written notice, your license to the Software ends automatically. You acknowledge that upon expiration or termination of this Agreement, the Software and any license key may automatically de-activate and you may no longer be able to access and use the Software. Upon termination: (1), you must, at WingSummers option, either promptly destroy or return to WingSummer all copies of the Software and any WingSummer Confidential Information in your possession or control, provided that, upon agreeing to pay 25% of the prior years fee, we will allow you and your customers to continue to use the WingSummer Software for an additional three months; and (2) you shall not be entitled to a refund of any pre-paid fees, except that you will be entitled to a refund of pre-paid fees if this Agreement is terminated by you for our breach and as provided in Section 7.3. Sections 4, 5, 6.3, 8, 9 and 10 will survive any expiration or termination of the Agreement. Upon termination of this Agreement for any reason, the rights granted in Section 1.1 and 1.2 and 1.3 shall immediately terminate and you must ensure that your End Users delete the Customer Application.
5. Confidentiality.
Continuing until 5 years after the expiration or termination of this Agreement, each party (as such, a “recipient”) agrees to keep all information, documents and data received from the other party (as such, a “discloser”), which are marked as or which would reasonably be considered to be confidential (“Confidential Information”) as strictly confidential and to use such information only as follows: (i) with respect to WingSummer Confidential Information, within the scope of the licenses granted to you, and (ii) with respect to your Confidential Information, only as needed to provide you with the Software and services contemplated by this Agreement. The Software and its pricing are WingSummers Confidential Information. Notwithstanding the foregoing, “Confidential Information” shall not include any information, proven by documentation, which: (i) becomes generally available to the public other than as a result of a disclosure by the recipient; (ii) was available to the recipient on a non-confidential basis prior to its disclosure by the discloser; (iii) becomes available to the recipient on a non-confidential basis from a source other than the discloser, provided that such source is not known by the recipient to be bound by any duty to the discloser or another entity, to keep such information confidential; or (iv) is independently developed by the recipient, without use of the disclosers Confidential Information.
6. Warranties.
6.1. Limited Software Warranty WingSummer warrants that, for thirty (30) days following the Effective Date, the Software will perform in all material respects in accordance with the standard user documentation for the Software that WingSummer makes generally available to its customers (“Documentation”). As your sole and exclusive remedy and WingSummers entire liability for any breach of this limited warranty, WingSummer will at its option and expense promptly correct or replace the Software so that it conforms to this limited warranty. WingSummer does not warrant that the Software will meet your requirements, that the Software will operate in the combinations that you may select, that the operation of the Software will be error-free or uninterrupted, or that all Software errors will be corrected. The limited warranty set forth in this Section 6.1 does not apply to the extent that WingSummer provides you with the Software (or portions of the Software) for beta, evaluation, testing, or demonstration purposes.
6.2. No Excluded Licenses The Software and Documentation do not incorporate, combine with, or use software or materials distributed under an Excluded License (“Open Source Materials”). “Excluded License” means a license that requires, as a condition of use, modification, and/or distribution of such Open Source Materials that other software incorporated into, derived from, or distributed with such Open Source Materials be (i) disclosed or distributed in source code form, (ii) licensed for the purpose of making derivative works, or (iii) redistributedable at no charge.
6.3. Disclaimer EXCEPT AS EXPRESSLY SET FORTH ABOVE, THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND. WINGSUMMER DISCLAIMS ALL OTHER WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT, AND ANY WARRANTIES ARISING OUT OF COURSE OF DEALING OR USAGE OF TRADE. NO ADVICE OR INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED FROM WINGSUMMER OR ELSEWHERE WILL CREATE ANY WARRANTY NOT EXPRESSLY STATED IN THIS AGREEMENT.
7. Indemnification.
7.1 WingSummer Indemnity. WingSummer will defend, indemnify and hold you harmless from and against any damages, costs and expenses (including reasonable attorneys fees and other professional fees) awarded against you in a final non-appealable judgment or that are agreed to in settlement, to the extent based on a third-party claim that the Software, as provided by WingSummer to you, infringes any patent, copyright or misappropriates any trade secret of any third party; provided that you: (a) promptly notify WingSummer in writing of any such claim; (b) grant WingSummer sole control of the defense and settlement of the claim; and (c) provide WingSummer, at WingSummers expense, with all assistance, information and authority reasonably required for the defense and settlement of the claim. You have the right to retain counsel, at your expense, to participate in the defense or settlement of any claim. WingSummer will not be liable for any settlement or compromise that you enter into without WingSummers prior written consent.
7.2 Exclusions. WingSummers obligation to indemnify you pursuant to Section 7.1 will not apply to the extent any claim results from or is based on: (i) any combination, operation or use of the Software with any product, system, device, method or data not provided by WingSummer, if such claim would have been avoided but for such combination, operation or use; (ii) modification of the Software by anyone other than WingSummer, if a claim would have been avoided but for such modification; (iii) your failure to install and use any upgrades to the Software furnished by WingSummer, if such claim could have been avoided by such installation and use of such upgrades; or (iv) use of the Software other than in accordance with this Agreement. You will indemnify, defend and hold WingSummer harmless and will pay any costs damages and reasonable attorneys fees in connection with any third party claim to the extent it results from any of the foregoing activities in this Section 7.2, provided that WingSummer (a) promptly notifies you in writing of any such claim; (b) grants you sole control of the defense and settlement of the claim; and (c) provides you, at your expense, with all assistance, information and authority reasonably required for the defense and settlement of the claim.
7.3 Injunction. If your use of the Software is, or in WingSummers opinion is likely to be, enjoined due to the type of claim specified in Section 7.1, then WingSummer will at its sole option and expense: procure for you the right to continue using the Software under the terms of this Agreement; (ii) replace or modify the Software to make it non-infringing and of equivalent functionality; or (iii) if WingSummer is unable to accomplish either (i) or despite using its reasonable efforts, then WingSummer may terminate your rights and WingSummers obligation under this Agreement with respect to such Software and refund to you a pro-rata portion of the prepaid license fees you paid for such Software.
7.4 Customer Indemnity. In the event Customer has rights granted under Sections 1.2 and 1.3 herein, Customer agrees to defend and indemnify WingSummer, at Customers expense, against any legal action brought against WingSummer by a third party to the extent that it is based on a claim that Customer Application or any software, hardware, materials or technology therein (except for Software), or the combination of the Software with any other software, hardware, materials or technology used by Customer as part of the applicable Customer Application, infringes a patent, copyright or trademark of such third party or makes unlawful use of such partys trade secret, and Customer shall pay any settlement of such claim or final judgment against WingSummer in any such action if attributable to any such claim. However, such defense and payments are subject to the conditions that WingSummer must: (i) notify Customer promptly in writing of such claim, (ii) permit Customer to have sole control of the defense, compromise or settlement of such claim, including any appeals, and (iii) fully cooperate with Customer, at Customers expense, in the defense or settlement of such claim.
7.5 Sole Remedy. THIS SECTION 7 SETS FORTH WINGSUMMERS SOLE AND EXCLUSIVE OBLIGATIONS, AND YOUR SOLE AND EXCLUSIVE REMEDIES, WITH RESPECT TO INFRINGEMENT OR MISAPPROPRIATION OF INTELLECTUAL PROPERTY RIGHTS OF ANY KIND.
8. Limitation of Liability.
IN NO EVENT WILL EITHER PARTY BE LIABLE FOR ANY SPECIAL, INCIDENTAL, EXEMPLARY, PUNITIVE OR CONSEQUENTIAL DAMAGES, OR FOR ANY LOSS OF USE, LOSS OF DATA, LOSS OF PROFITS OR LOSS OF GOODWILL, OR THE COSTS OF PROCURING SUBSTITUTE PRODUCTS, WHETHER OR NOT FORESEEABLE, ARISING OUT OF OR IN CONNECTION WITH THIS AGREEMENT OR THE USE, OPERATION OR PERFORMANCE OF THE SOFTWARE, WHETHER SUCH LIABILITY ARISES FROM ANY CLAIM BASED UPON CONTRACT, WARRANTY, TORT (INCLUDING NEGLIGENCE), PRODUCT LIABILITY OR OTHERWISE, AND WHETHER OR NOT WINGSUMMER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGE. EACH PARTYS TOTAL AGGREGATE LIABILITY ARISING UNDER THIS AGREEMENT, FROM ALL CAUSES OF ACTION AND ALL THEORIES OF LIABILITY, WILL NOT EXCEED THE AMOUNTS PAID TO WINGSUMMER BY YOU FOR THE SPECIFIC SOFTWARE GIVING RISE TO A CLAIM FOR LIABILITY HEREUNDER DURING THE 12 MONTH PERIOD PRIOR TO THE FIRST CLAIM, PROVIDED THAT THIS SHALL NOT RELEASE YOU FROM PAYING ALL FEES AND CHARGES DUE HEREUNDER. The parties agree that the limitations and exclusions contained in this Section 8 and elsewhere in this Agreement will (a) not apply to any claims under indemnity and (b) survive and apply even if any exclusive remedy specified in this Agreement is found to have failed of its essential purpose.
9. Feedback; Modifications.
If you make any Modifications or provide any ideas, suggestions, or recommendations regarding the Software (“Feedback,” which term does not include Modifications), WingSummer will be free to use, disclose, reproduce, license or otherwise distribute, and exploit such Feedback as it sees fit, entirely without obligation or restriction of any kind; but shall not be free to use your Modifications (or any of your other intellectual property) without an express written license or grant of rights by you. By providing Feedback, you grant WingSummer a worldwide, perpetual, irrevocable, sublicenseable, fully-paid and royalty-free license to use and exploit in any manner such Feedback.
10. General.
This Agreement will be governed by and construed in accordance with the laws of China, without regard to or application of conflict of laws rules or principles. Any legal action or proceeding arising under this Agreement will be brought exclusively in courts located in China and each party irrevocably consents to the personal jurisdiction thereof and venue therein. You may not assign or transfer this Agreement or any rights granted hereunder, by operation of law or otherwise, without WingSummers prior written consent, and any attempt by you to do so, without such consent, will be void. WingSummer may freely assign this Agreement. Except as expressly set forth in this Agreement, the exercise by either party of any of its remedies under this Agreement will be without prejudice to its other remedies under this Agreement or otherwise. All notices or approvals required or permitted under this Agreement will be in writing and delivered by confirmed email transmission, by overnight delivery service, or by certified mail, and in each instance will be deemed given upon receipt. All notices or approvals will be sent to the addresses set forth in the Order or to such other address as may be specified by either party to the other in accordance with this Section. The failure by either party to enforce any provision of this Agreement will not constitute a waiver of future enforcement of that or any other provision. Any waiver, modification or amendment of any provision of this Agreement will be effective only if in writing and signed by authorized representatives of both parties. If any provision of this Agreement is held to be unenforceable or invalid, that provision will be enforced to the maximum extent possible, and the other provisions will remain in full force and effect. This Agreement is the complete and exclusive understanding and agreement between the parties regarding its subject matter, and supersedes all proposals, understandings or communications between the parties, oral or written, regarding its subject matter. This Agreement may be executed in counterparts, each of which will be deemed an original, but all of which together will constitute one and the same instrument.
11. Contact Information.
If you have any questions regarding this Agreement, you may contact WingSummer on Gitee or by the email wing-summer@qq.com .

668
LICENSE
View File

@ -1,7 +1,661 @@
Source code in this repository is variously licensed under the WingSummer OpenSource Lincense (OpenSource-LICENSE), or the WingHexExplorer Commercial License (Commerical-LICENSE).
本仓库的源代码采用多协议的授权模式: “羽夏开源协议” 和 “羽夏商业协议”,它们分别在 OpenSource-LICENSE 和 Commerical-LICENSE 有详细的说明。
When built, binary files are generated for the WingSummer OpenSource Lincense source code. Binaries located at my Gitee, Gitlink or Github repository and the spark store are released under the WingSummer OpenSource Lincense.
当你编译代码时,二进制文件遵守 “羽夏开源协议”。在我的 Gitee Gitlink 或 Github 和星火商店发布的二进制都遵守 “羽夏开源协议”。
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. httpfsf.org
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
andor modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised andor new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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 ANDOR 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 ANDOR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the copyright line and a pointer to where the full notice is found.
one line to give the program's name and a brief idea of what it does.
Copyright (C) year name of author
This program is free software you can redistribute it andor modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see httpwww.gnu.orglicenses.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a Source link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
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 AGPL, see
httpwww.gnu.orglicenses.

View File

@ -1,160 +0,0 @@
WingSummer OpenSource Lincense
Version 1,13 June 2022
Copyright (c) WingSummer
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to WingSummer OpenSource Lincense.
“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, subject to section 13. 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.
Subject to section 13, 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 not charge any price for each copy that you convey, but 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 only can convey the machine-readable Corresponding Source under the terms of this License free of charge.
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 for ANY COMMERICAL PURPOSE except as expressly provided under this License. Any attempt otherwise to propagate or modify FOR COMMERICAL PURPOSE it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
In other words,you can fork my repository and propagate or modify it for NON-COMMERICAL USE freely.It doesn't mean you can not make a profit from it for anyway.Any INCOME from any donation to maintain an open source code repository is allowed.
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 30 May 2022.
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 use, propagate or 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 use, propagate or 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. Offering the Program as a Service.
If you make the functionality of the Program or a modified version available to third parties as a service, you must make the Service Source Code available via network download to everyone at no charge, under the terms of this License. Making the functionality of the Program or modified version available to third parties as a service includes, without limitation, enabling third parties to interact with the functionality of the Program or modified version remotely through a computer network, offering a service the value of which entirely or primarily derives from the value of the Program or modified version, or offering a service that accomplishes for users the primary purpose of the Program or modified version.
14. Revised Versions of this License.
WingSummer may publish revised and/or new versions of the WingSummer OpenSource Lincense 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 WingSummer OpenSource Lincense “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 WingSummer. If the Program does not specify a version number of the WingSummer OpenSource Lincense, you may choose any version ever published by MongoDB, Inc.
If the Program specifies that a proxy can decide which future versions of the Server Side 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

956
PythonQt/PythonQt.h Normal file
View File

@ -0,0 +1,956 @@
#ifndef PYTHONQT_H
#define PYTHONQT_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQt.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-05
*/
//----------------------------------------------------------------------------------
#include "PythonQtClassWrapper.h"
#include "PythonQtInstanceWrapper.h"
#include "PythonQtObjectPtr.h"
#include "PythonQtSlot.h"
#include "PythonQtStdIn.h"
#include "PythonQtSystem.h"
#include "PythonQtUtils.h"
#include <QByteArray>
#include <QHash>
#include <QList>
#include <QObject>
#include <QStringList>
#include <QVariant>
#include <QtDebug>
#include <iostream>
class PythonQtClassInfo;
class PythonQtPrivate;
class PythonQtMethodInfo;
class PythonQtSignalReceiver;
class PythonQtImportFileInterface;
class PythonQtCppWrapperFactory;
class PythonQtForeignWrapperFactory;
class PythonQtQFileImporter;
typedef void PythonQtVoidPtrCB(void *object);
typedef void PythonQtQObjectWrappedCB(QObject *object);
typedef void PythonQtQObjectNoLongerWrappedCB(QObject *object);
typedef void *PythonQtPolymorphicHandlerCB(const void *ptr,
const char **class_name);
typedef void
PythonQtShellSetInstanceWrapperCB(void *object,
PythonQtInstanceWrapper *wrapper);
template <class T>
void PythonQtSetInstanceWrapperOnShell(void *object,
PythonQtInstanceWrapper *wrapper) {
(reinterpret_cast<T *>(object))->_wrapper = wrapper;
}
//! Helper template that allows to pass the ownership of a C++ instance between
//! C++ and Python (it is used as a slot return type or parameter type so that
//! it can be detected by the PythonQt
//! slot calling code).
template <class T> class PythonQtPassOwnershipToCPP {
public:
//! Allow conversion from T to PythonQtPassOwnershipToCPP<T>
PythonQtPassOwnershipToCPP(const T &t) : _t(t) {}
//! Allow conversion from PythonQtPassOwnershipToCPP<T> to T
operator T() const { return _t; }
//! Stored value. This is important so that it has the same memory layout
//! as a pointer if T is a pointer type (which is the typical use case for
//! this class).
T _t;
};
//! Helper template that allows to pass the ownership of a C++ instance between
//! C++ and Python (it is used as a slot return type or parameter type so that
//! it can be detected by the PythonQt
//! slot calling code).
template <class T> class PythonQtPassOwnershipToPython {
public:
//! Allow conversion from T to PythonQtPassOwnershipToPython<T>
PythonQtPassOwnershipToPython(const T &t) : _t(t) {}
//! Allow conversion from PythonQtPassOwnershipToPython<T> to T
operator T() const { return _t; }
//! Stored value. This is important so that it has the same memory layout
//! as a pointer if T is a pointer type (which is the typical use case for
//! this class).
T _t;
};
//! Helper template that allows to pass the ownership of a C++ instance between
//! C++ and Python (it is used as a slot return type or parameter type so that
//! it can be detected by the PythonQt
//! slot calling code).
template <class T> class PythonQtNewOwnerOfThis {
public:
//! Allow conversion from T to PythonQtNewOwnerOfThis<T>
PythonQtNewOwnerOfThis(const T &t) : _t(t) {}
//! Allow conversion from PythonQtNewOwnerOfThis<T> to T
operator T() const { return _t; }
//! Stored value. This is important so that it has the same memory layout
//! as a pointer if T is a pointer type (which is the typical use case for
//! this class).
T _t;
};
//! returns the offset that needs to be added to upcast an object of type T1 to
//! T2
template <class T1, class T2> int PythonQtUpcastingOffset() {
return ((reinterpret_cast<char *>(
static_cast<T2 *>(reinterpret_cast<T1 *>(0x100)))) -
(reinterpret_cast<char *>(reinterpret_cast<T1 *>(0x100))));
}
//! callback to create a QObject lazily
typedef QObject *PythonQtQObjectCreatorFunctionCB();
//! helper template to create a derived QObject class
template <class T> QObject *PythonQtCreateObject() { return new T(); };
//! The main interface to the Python Qt binding, realized as a singleton
/*!
Use PythonQt::init() to initialize the singleton and PythonQt::self() to access
it. While there can be only one PythonQt instance, you can have any number of
Python context to do scripting in. One possibility is to use
createModuleFromFile(), createModuleFromScript() or createUniqueModule() to get
a context that is separated from the other contexts. Alternatively you can use
Python dicts as contexts for script evaluation, but you will need to populate
the dict with the __builtins__ instance to have all Pythons available when
running code in the scope of a dict.
*/
class PYTHONQT_EXPORT PythonQt : public QObject {
Q_OBJECT
public:
//! flags that can be passed to PythonQt::init()
enum InitFlags {
RedirectStdOut = 1, //!<< sets if the std out/err is redirected to
//!< pythonStdOut() and pythonStdErr() signals
IgnoreSiteModule = 2, //!<< sets if Python should ignore the site module
ExternalHelp = 4, //!<< sets if help() calls on PythonQt modules are
//!< forwarded to the pythonHelpRequest() signal
PythonAlreadyInitialized = 8 //!<< sets that PythonQt should not can
//!< PyInitialize, since it is already done
};
//! flags that tell PythonQt which operators to expect on the registered type
enum TypeSlots {
Type_Add = 1,
Type_Subtract = 1 << 1,
Type_Multiply = 1 << 2,
Type_Divide = 1 << 3,
Type_Mod = 1 << 4,
Type_And = 1 << 5,
Type_Or = 1 << 6,
Type_Xor = 1 << 7,
Type_LShift = 1 << 8,
Type_RShift = 1 << 9,
Type_InplaceAdd = 1 << 10,
Type_InplaceSubtract = 1 << 11,
Type_InplaceMultiply = 1 << 12,
Type_InplaceDivide = 1 << 13,
Type_InplaceMod = 1 << 14,
Type_InplaceAnd = 1 << 15,
Type_InplaceOr = 1 << 16,
Type_InplaceXor = 1 << 17,
Type_InplaceLShift = 1 << 18,
Type_InplaceRShift = 1 << 19,
Type_Length = 1 << 20,
Type_MappingSetItem = 1 << 21,
Type_MappingGetItem = 1 << 22,
Type_Invert = 1 << 29,
Type_RichCompare = 1 << 30,
Type_NonZero = 1u << 31,
};
//! enum for profiling callback
enum ProfilingCallbackState { Enter = 1, Leave = 2 };
//! callback for profiling. className and methodName are only passed when
//! state == Enter, otherwise they are NULL.
typedef void ProfilingCB(ProfilingCallbackState state, const char *className,
const char *methodName, PyObject *args);
//---------------------------------------------------------------------------
//! \name Singleton Initialization
//@{
//! initialize the python qt binding (flags are a or combination of
//! PythonQt::InitFlags), if \c pythonQtModuleName is given it defines the
//! name of the python module that PythonQt will add, otherwise "PythonQt" is
//! used. This can be used to e.g. pass in PySide or PyQt4 to make it more
//! compatible.
static void init(int flags = IgnoreSiteModule | RedirectStdOut,
const QByteArray &pythonQtModuleName = QByteArray());
//! cleanup of the singleton
static void cleanup();
//! get the singleton instance
static PythonQt *self();
//@}
//! defines the object types for introspection
enum ObjectType {
Class,
Function,
Variable,
Module,
Anything,
CallOverloads
};
//---------------------------------------------------------------------------
//! \name Standard input handling
//@{
//! Overwrite default handling of stdin using a custom callback. It internally
//! backup the original 'sys.stdin' into 'sys.pythonqt_original_stdin'
void setRedirectStdInCallback(PythonQtInputChangedCB *callback,
void *callbackData = nullptr);
//! Enable or disable stdin custom callback. It resets 'sys.stdin' using
//! either 'sys.pythonqt_stdin' or 'sys.pythonqt_original_stdin'
void setRedirectStdInCallbackEnabled(bool enabled);
//@}
//---------------------------------------------------------------------------
//! \name Modules
//@{
//! get the __main__ module of python
PythonQtObjectPtr getMainModule();
//! import the given module and return a reference to it (useful to import
//! e.g. "sys" and call something on it) If a module is already imported, this
//! returns the already imported module.
PythonQtObjectPtr importModule(const QString &name);
//! creates the new module \c name and evaluates the given file in the context
//! of that module If the \c script is empty, the module contains no initial
//! code. You can use evalScript/evalCode to add code to a module later on.
//! The user needs to make sure that the \c name is unique in the python
//! module dictionary.
PythonQtObjectPtr createModuleFromFile(const QString &name,
const QString &filename);
//! creates the new module \c name and evaluates the given script in the
//! context of that module. If the \c script is empty, the module contains no
//! initial code. You can use evalScript/evalCode to add code to a module
//! later on. The user needs to make sure that the \c name is unique in the
//! python module dictionary.
PythonQtObjectPtr createModuleFromScript(const QString &name,
const QString &script = QString());
//! create a uniquely named module, you can use evalFile or evalScript to
//! populate the module with script code
PythonQtObjectPtr createUniqueModule();
//@}
//---------------------------------------------------------------------------
//! \name Importing/Paths
//@{
//! overwrite the python sys path (call this directly after PythonQt::init()
//! if you want to change the std python sys path)
void overwriteSysPath(const QStringList &paths);
//! prepend a path to sys.path to allow importing from it
void addSysPath(const QString &path);
//! sets the __path__ list of a module to the given list (important for local
//! imports)
void setModuleImportPath(PyObject *module, const QStringList &paths);
//@}
//---------------------------------------------------------------------------
//! \name Registering Classes
//@{
//! registers a QObject derived class to PythonQt (this is implicitly called
//! by addObject as well)
/* Since Qt4 does not offer a way to detect if a given classname is derived
from QObject and thus has a QMetaObject, you MUST register all your QObject
derived classes here when you want them to be detected in signal and slot
calls */
void registerClass(const QMetaObject *metaobject,
const char *package = nullptr,
PythonQtQObjectCreatorFunctionCB *wrapperCreator = nullptr,
PythonQtShellSetInstanceWrapperCB *shell = nullptr);
//! add a wrapper object for the given QMetaType typeName, also does an
//! addClassDecorators() to add constructors for variants (ownership of
//! wrapper is passed to PythonQt)
/*! Make sure that you have done a qRegisterMetaType first, if typeName is a
user type!
This will add a wrapper object that is used to make calls to the given
classname \c typeName. All slots that take a pointer to typeName as the first
argument will be callable from Python on a variant object that contains such
a type.
*/
void
registerCPPClass(const char *typeName, const char *parentTypeName = nullptr,
const char *package = nullptr,
PythonQtQObjectCreatorFunctionCB *wrapperCreator = nullptr,
PythonQtShellSetInstanceWrapperCB *shell = nullptr);
//! as an alternative to registerClass, you can tell PythonQt the names of
//! QObject derived classes and it will register the classes when it first
//! sees a pointer to such a derived class
void registerQObjectClassNames(const QStringList &names);
//! add a parent class relation to the \c given typeName, the upcastingOffset
//! is needed for multiple inheritance and can be calculated using
//! PythonQtUpcastingOffset<type,parentType>(), which also verifies that type
//! is really derived from parentType. Returns false if the typeName was not
//! yet registered.
bool addParentClass(const char *typeName, const char *parentTypeName,
int upcastingOffset = 0);
//! add a handler for polymorphic downcasting
void addPolymorphicHandler(const char *typeName,
PythonQtPolymorphicHandlerCB *cb);
//@}
//---------------------------------------------------------------------------
//! \name Script Parsing and Evaluation
//@{
//! parses the given file and returns the python code object, this can then be
//! used to call evalCode()
PythonQtObjectPtr parseFile(const QString &filename);
//! evaluates the given code and returns the result value (use Py_Compile etc.
//! to create pycode from string) If pycode is NULL, a python error is
//! printed.
QVariant evalCode(PyObject *object, PyObject *pycode);
//! evaluates the given script code and returns the result value
QVariant evalScript(PyObject *object, const QString &script,
int start = Py_file_input);
//! evaluates the given script code from file
void evalFile(PyObject *object, const QString &filename);
//@}
//---------------------------------------------------------------------------
//! \name Signal Handlers
//@{
//! add a signal handler to the given \c signal of \c obj and connect it to a
//! callable \c objectname in module
bool addSignalHandler(QObject *obj, const char *signal, PyObject *module,
const QString &objectname);
//! remove a signal handler from the given \c signal of \c obj
bool removeSignalHandler(QObject *obj, const char *signal, PyObject *module,
const QString &objectname);
//! add a signal handler to the given \c signal of \c obj and connect it to a
//! callable \c receiver
bool addSignalHandler(QObject *obj, const char *signal, PyObject *receiver);
//! remove a signal handler from the given \c signal of \c obj
bool removeSignalHandler(QObject *obj, const char *signal,
PyObject *receiver);
//! globally removes all signal handlers (connections between QObjects and
//! Python).
void removeSignalHandlers();
//@}
//---------------------------------------------------------------------------
//! \name Variable access
//@{
//! add the given \c qObject to the python \c object as a variable with \c
//! name (it can be removed via clearVariable)
void addObject(PyObject *object, const QString &name, QObject *qObject);
//! add the given variable to the object
void addVariable(PyObject *object, const QString &name, const QVariant &v);
//! remove the given variable
void removeVariable(PyObject *module, const QString &name);
//! get the variable with the \c name of the \c object, returns an invalid
//! QVariant on error
QVariant getVariable(PyObject *object, const QString &name);
//! read vars etc. in scope of an \c object, optional looking inside of an
//! object \c objectname
QStringList introspection(PyObject *object, const QString &objectname,
ObjectType type);
//! read vars etc. in scope of the given \c object
QStringList introspectObject(PyObject *object, ObjectType type);
//! read vars etc. in scope of the type object called \c typename. First the
//! typename of the form module.type is split into module and type. Then the
//! module is looked up in sys.modules. If the module or type is not found
//! there, then the type is looked up in the __builtin__ module.
QStringList introspectType(const QString &typeName, ObjectType type);
//! returns the found callable object or NULL
//! @return new reference
PythonQtObjectPtr lookupCallable(PyObject *object, const QString &name);
//! returns the return type of the method of a wrapped c++ object referenced
//! by \c objectname
QString getReturnTypeOfWrappedMethod(PyObject *module,
const QString &objectname);
//! returns the return type of the method \c methodName of a wrapped c++ type
//! referenced by \c typeName
QString getReturnTypeOfWrappedMethod(const QString &typeName,
const QString &methodName);
//@}
//---------------------------------------------------------------------------
//! \name Calling Python Objects
//@{
//! call the given python \c callable in the scope of object, returns the
//! result converted to a QVariant
QVariant call(PyObject *object, const QString &callable,
const QVariantList &args = QVariantList(),
const QVariantMap &kwargs = QVariantMap());
//! call the given python object, returns the result converted to a QVariant
QVariant call(PyObject *callable, const QVariantList &args = QVariantList(),
const QVariantMap &kwargs = QVariantMap());
//! call the given python object, returns the result as new PyObject
PyObject *callAndReturnPyObject(PyObject *callable,
const QVariantList &args = QVariantList(),
const QVariantMap &kwargs = QVariantMap());
//@}
//---------------------------------------------------------------------------
//! \name Decorations, Constructors, Wrappers...
//@{
//! add an object whose slots will be used as decorator slots for
//! other QObjects or CPP classes. The slots need to follow the
//! convention that the first argument is a pointer to the wrapped object.
//! (ownership is passed to PythonQt)
/*!
Example:
A slot with the signature
\code
bool doSomething(QWidget* w, int a)
\endcode
will extend QWidget instances (and derived classes) with a "bool
doSomething(int a)" slot that will be called with the concrete instance as
first argument. So in Python you can now e.g. call
\code
someWidget.doSomething(12)
\endcode
without QWidget really having this method. This allows to easily make normal
methods of Qt classes callable by forwarding them with such decorator slots or
to make CPP classes (which are not derived from QObject) callable from Python.
*/
void addInstanceDecorators(QObject *o);
//! add an object whose slots will be used as decorator slots for
//! class objects (ownership is passed to PythonQt)
/*!
The slots need to follow the following convention:
- SomeClass* new_SomeClass(...)
- QVariant new_SomeClass(...)
- void delete_SomeClass(SomeClass*)
- ... static_SomeClass_someName(...)
This will add:
- a constructor
- a constructor which generates a QVariant
- a destructor (only useful for CPP objects)
- a static decorator slot which will be available on the MetaObject (visible
in PythonQt module)
*/
void addClassDecorators(QObject *o);
//! this will add the object both as class and instance decorator (ownership
//! is passed to PythonQt)
void addDecorators(QObject *o);
//! add the given factory to PythonQt (ownership stays with caller)
void addWrapperFactory(PythonQtCppWrapperFactory *factory);
//! add the given factory to PythonQt (ownership stays with caller)
void addWrapperFactory(PythonQtForeignWrapperFactory *factory);
//! remove the wrapper factory
void removeWrapperFactory(PythonQtCppWrapperFactory *factory);
//! remove the wrapper factory
void removeWrapperFactory(PythonQtForeignWrapperFactory *factory);
//@}
//---------------------------------------------------------------------------
//! \name Custom Importer
//@{
//! replace the internal import implementation and use the supplied interface
//! to load files (both py and pyc files) (this method should be called
//! directly after initialization of init() and before calling
//! overwriteSysPath(). On the first call to this method, it will install a
//! generic PythonQt importer in Pythons "path_hooks". This is not reversible,
//! so even setting setImporter(NULL) afterwards will keep the custom PythonQt
//! importer with a QFile default import interface. Subsequent python import
//! calls will make use of the passed importInterface which forwards all
//! import calls to the given \c importInterface. Passing NULL will install a
//! default QFile importer.
//! (\c importInterface ownership stays with caller)
void setImporter(PythonQtImportFileInterface *importInterface);
//! this installs the default QFile importer (which effectively does a
//! setImporter(NULL)) (without calling setImporter or installDefaultImporter
//! at least once, the default python import mechanism is in place) the
//! default importer allows to import files from anywhere QFile can read from,
//! including the Qt resource system using ":". Keep in mind that you need to
//! extend "sys.path" with ":" to be able to import from the Qt resources.
void installDefaultImporter() { setImporter(nullptr); }
//! set paths that the importer should ignore
void setImporterIgnorePaths(const QStringList &paths);
//! get paths that the importer should ignore
const QStringList &getImporterIgnorePaths();
//! get access to the file importer (if set)
static PythonQtImportFileInterface *importInterface();
//@}
//---------------------------------------------------------------------------
//! \name Other Stuff
//@{
//! get access to internal data (should not be used on the public API, but is
//! used by some C functions)
static PythonQtPrivate *priv() { return _self->_p; }
//! clear all NotFound entries on all class infos, to ensure that
//! newly loaded wrappers can add methods even when the object was wrapped by
//! PythonQt before the wrapper was loaded
void clearNotFoundCachedMembers();
//! handle a python error, call this when a python function fails. If no error
//! occurred, it returns false. The error is currently just output to the
//! python stderr, future version might implement better trace printing
bool handleError();
//! return \a true if \a handleError() has been called and an error occurred.
bool hadError() const;
//! reset error flag. After calling this, hadError() will return false.
//! \sa hadError()
void clearError();
//! if set to true, the systemExitExceptionRaised signal will be emitted if
//! exception SystemExit is caught \sa handleError()
void setSystemExitExceptionHandlerEnabled(bool value);
//! return \a true if SystemExit exception is handled by PythonQt
//! \sa setSystemExitExceptionHandlerEnabled()
bool systemExitExceptionHandlerEnabled() const;
//! set a callback that is called when a QObject with parent == NULL is
//! wrapped by PythonQt
void setQObjectWrappedCallback(PythonQtQObjectWrappedCB *cb);
//! set a callback that is called when a QObject with parent == NULL is no
//! longer wrapped by PythonQt
void setQObjectNoLongerWrappedCallback(PythonQtQObjectNoLongerWrappedCB *cb);
//! call the callback if it is set
static void qObjectNoLongerWrappedCB(QObject *o);
//! called by internal help methods
PyObject *helpCalled(PythonQtClassInfo *info);
//! returns the found object or NULL
//! @return new reference
PythonQtObjectPtr lookupObject(PyObject *module, const QString &name);
//! sets a callback that is called before and after function calls for
//! profiling
void setProfilingCallback(ProfilingCB *cb);
//@}
Q_SIGNALS:
//! emitted when python outputs something to stdout (and redirection is turned
//! on)
void pythonStdOut(const QString &str);
//! emitted when python outputs something to stderr (and redirection is turned
//! on)
void pythonStdErr(const QString &str);
//! emitted when help() is called on a PythonQt object and \c ExternalHelp is
//! enabled
void pythonHelpRequest(const QByteArray &cppClassName);
//! emitted when both custom SystemExit exception handler is enabled and a
//! SystemExit exception is raised. \sa
//! setSystemExitExceptionHandlerEnabled(bool)
void systemExitExceptionRaised(int exitCode);
private:
void initPythonQtModule(bool redirectStdOut,
const QByteArray &pythonQtModuleName);
QString
getReturnTypeOfWrappedMethodHelper(const PythonQtObjectPtr &variableObject,
const QString &methodName,
const QString &context);
PyObject *getObjectByType(const QString &typeName);
//! callback for stdout redirection, emits pythonStdOut signal
static void stdOutRedirectCB(const QString &str);
//! callback for stderr redirection, emits pythonStdErr signal
static void stdErrRedirectCB(const QString &str);
//! get (and create if not available) the signal receiver of that QObject,
//! signal receiver is made child of the passed \c obj
PythonQtSignalReceiver *getSignalReceiver(QObject *obj);
PythonQt(int flags, const QByteArray &pythonQtModuleName);
~PythonQt();
static PythonQt *_self;
static int _uniqueModuleCount;
PythonQtPrivate *_p;
};
class PythonQtDebugAPI;
//! internal PythonQt details
class PYTHONQT_EXPORT PythonQtPrivate : public QObject {
Q_OBJECT
public:
PythonQtPrivate();
~PythonQtPrivate();
enum DecoratorTypes {
StaticDecorator = 1,
ConstructorDecorator = 2,
DestructorDecorator = 4,
InstanceDecorator = 8,
AllDecorators = 0xffff
};
//! get the suffixes that are used for shared libraries
const QStringList &sharedLibrarySuffixes() { return _sharedLibrarySuffixes; }
//! returns if the id is the id for PythonQtObjectPtr
bool isPythonQtObjectPtrMetaId(int id) {
return _PythonQtObjectPtr_metaId == id;
}
//! add the wrapper pointer (for reuse if the same obj appears while wrapper
//! still exists)
void addWrapperPointer(void *obj, PythonQtInstanceWrapper *wrapper);
//! remove the wrapper ptr again
void removeWrapperPointer(void *obj);
//! called by destructor of shells to allow invalidation of the Python wrapper
void shellClassDeleted(void *shellClass);
//! try to unwrap the given object to a C++ pointer using the foreign wrapper
//! factories
void *unwrapForeignWrapper(const QByteArray &classname, PyObject *obj);
//! add parent class relation
bool addParentClass(const char *typeName, const char *parentTypeName,
int upcastingOffset);
//! add a handler for polymorphic downcasting
void addPolymorphicHandler(const char *typeName,
PythonQtPolymorphicHandlerCB *cb);
//! lookup existing classinfo and return new if not yet present
PythonQtClassInfo *lookupClassInfoAndCreateIfNotPresent(const char *typeName);
//! called when a signal emitting QObject is destroyed to remove the signal
//! handler from the hash map
void removeSignalEmitter(QObject *obj);
//! wrap the given QObject into a Python object (or return existing wrapper!)
PyObject *wrapQObject(QObject *obj);
//! wrap the given ptr into a Python object (or return existing wrapper!) if
//! there is a known QObject of that name or a known wrapper in the factory.
//! If passOwnership == true, the ownership is passed to PythonQt, so the
//! object will be deleted by PythonQt when the Python wrapper goes away.
PyObject *wrapPtr(void *ptr, const QByteArray &name,
bool passOwnership = false);
//! create a read-only buffer object from the given memory
static PyObject *wrapMemoryAsBuffer(const void *data, Py_ssize_t size);
//! create a read-write buffer object from the given memory
static PyObject *wrapMemoryAsBuffer(void *data, Py_ssize_t size);
//! registers a QObject derived class to PythonQt (this is implicitly called
//! by addObject as well)
/* Since Qt4 does not offer a way to detect if a given classname is derived
from QObject and thus has a QMetaObject,
you MUST register all your QObject derived classes here when you want them
to be detected in signal and slot calls */
void registerClass(const QMetaObject *metaobject,
const char *package = nullptr,
PythonQtQObjectCreatorFunctionCB *wrapperCreator = nullptr,
PythonQtShellSetInstanceWrapperCB *shell = nullptr,
PyObject *module = nullptr, int typeSlots = 0);
//! add a wrapper object for the given QMetaType typeName, also does an
//! addClassDecorators() to add constructors for variants (ownership of
//! wrapper is passed to PythonQt)
/*! Make sure that you have done a qRegisterMetaType first, if typeName is a
user type!
This will add a wrapper object that is used to make calls to the given
classname \c typeName. All slots that take a pointer to typeName as the first
argument will be callable from Python on a variant object that contains such
a type.
*/
void
registerCPPClass(const char *typeName, const char *parentTypeName = nullptr,
const char *package = nullptr,
PythonQtQObjectCreatorFunctionCB *wrapperCreator = nullptr,
PythonQtShellSetInstanceWrapperCB *shell = nullptr,
PyObject *module = nullptr, int typeSlots = 0);
//! as an alternative to registerClass, you can tell PythonQt the names of
//! QObject derived classes and it will register the classes when it first
//! sees a pointer to such a derived class
void registerQObjectClassNames(const QStringList &names);
//! add a decorator object
void addDecorators(QObject *o, int decoTypes);
//! helper method that creates a PythonQtClassWrapper object (returns a new
//! reference)
PythonQtClassWrapper *
createNewPythonQtClassWrapper(PythonQtClassInfo *info, PyObject *module,
const QByteArray &pythonClassName);
//! create a new instance of the given enum type with given value (returns a
//! new reference)
static PyObject *createEnumValueInstance(PyObject *enumType,
unsigned int enumValue);
//! helper that creates a new int derived class that represents the enum of
//! the given name (returns a new reference)
static PyObject *createNewPythonQtEnumWrapper(const char *enumName,
PyObject *parentObject);
//! helper method that creates a PythonQtInstanceWrapper object and registers
//! it in the object map
PythonQtInstanceWrapper *
createNewPythonQtInstanceWrapper(QObject *obj, PythonQtClassInfo *info,
void *wrappedPtr = nullptr);
//! get the class info for a meta object (if available)
PythonQtClassInfo *getClassInfo(const QMetaObject *meta);
//! get the class info for a meta object (if available)
PythonQtClassInfo *getClassInfo(const QByteArray &className);
//! register a class name that causes lazy loading of the moduleToImport when
//! PythonQt encounters the type
void registerLazyClass(const QByteArray &name,
const QByteArray &moduleToImport);
//! creates the new module from the given pycode
PythonQtObjectPtr createModule(const QString &name, PyObject *pycode);
//! get the current class info (for the next PythonQtClassWrapper that is
//! created) and reset it to NULL again
PythonQtClassInfo *currentClassInfoForClassWrapperCreation();
//! the dummy tuple (which is empty and may be used to detected that a wrapper
//! is called from internal wrapper creation
static PyObject *dummyTuple();
//! called by virtual overloads when a python return value can not be
//! converted to the required Qt type
void handleVirtualOverloadReturnError(const char *signature,
const PythonQtMethodInfo *methodInfo,
PyObject *result);
//! get access to the PythonQt module
PythonQtObjectPtr pythonQtModule() const { return _pythonQtModule; }
//! returns the profiling callback, which may be NULL
PythonQt::ProfilingCB *profilingCB() const { return _profilingCB; }
//! determines the signature of the given callable object (similar as pydoc)
QString getSignature(PyObject *object);
//! returns true if the object is a method descriptor (same as
//! inspect.ismethoddescriptor() in inspect.py)
bool isMethodDescriptor(PyObject *object) const;
//! get the dynamic meta object for the given wrapper. It will contain the
//! signals/slots that have been added in Python
const QMetaObject *
getDynamicMetaObject(PythonQtInstanceWrapper *wrapper,
const QMetaObject *prototypeMetaObject);
//! recursively creates the dynamic meta object chain down to the Qt class
//! wrapper.
const QMetaObject *
setupDynamicMetaObjectChain(PythonQtClassWrapper *type,
const QMetaObject *prototypeMetaObject);
//! builds and returns the dynamic meta object for the given type, derived
//! from prototypeMetaObject.
const QMetaObject *
buildDynamicMetaObject(PythonQtClassWrapper *type,
const QMetaObject *prototypeMetaObject);
//! redirected from shell classes, tries to call the given meta call on the
//! Python wrapper.
int handleMetaCall(QObject *object, PythonQtInstanceWrapper *wrapper,
QMetaObject::Call call, int id, void **args);
//! calls the given method on Python function with same name.
void callMethodInPython(QMetaMethod &method, PythonQtInstanceWrapper *wrapper,
void **args);
private:
//! Setup the shared library suffixes by getting them from the "imp" module.
void setupSharedLibrarySuffixes();
//! create a new pythonqt class wrapper and place it in the pythonqt module
void createPythonQtClassWrapper(PythonQtClassInfo *info, const char *package,
PyObject *module = nullptr);
//! get/create new package module (the returned object is a borrowed
//! reference)
PyObject *packageByName(const char *name);
//! get the wrapper for a given pointer (and remove a wrapper of an already
//! destroyed qobject)
PythonQtInstanceWrapper *findWrapperAndRemoveUnused(void *obj);
//! stores pointer to PyObject mapping of wrapped QObjects AND C++ objects
QHash<void *, PythonQtInstanceWrapper *> _wrappedObjects;
//! stores the meta info of known Qt classes
QHash<QByteArray, PythonQtClassInfo *> _knownClassInfos;
//! names of qobject derived classes that can be casted to qobject savely
QHash<QByteArray, bool> _knownQObjectClassNames;
//! lazy classes that cause PythonQt to trigger an import if they are
//! encountered.
QHash<QByteArray, QByteArray> _knownLazyClasses;
//! stores signal receivers for QObjects
QHash<QObject *, PythonQtSignalReceiver *> _signalReceivers;
//! the PythonQt python module
PythonQtObjectPtr _pythonQtModule;
//! the name of the PythonQt python module
QByteArray _pythonQtModuleName;
//! the importer interface (if set)
PythonQtImportFileInterface *_importInterface;
//! the default importer
PythonQtQFileImporter *_defaultImporter;
PythonQtQObjectNoLongerWrappedCB *_noLongerWrappedCB;
PythonQtQObjectWrappedCB *_wrappedCB;
QStringList _importIgnorePaths;
QStringList _sharedLibrarySuffixes;
//! the cpp object wrapper factories
QList<PythonQtCppWrapperFactory *> _cppWrapperFactories;
QList<PythonQtForeignWrapperFactory *> _foreignWrapperFactories;
QHash<QByteArray, PyObject *> _packages;
PythonQtClassInfo *_currentClassInfoForClassWrapperCreation;
PythonQt::ProfilingCB *_profilingCB;
PythonQtDebugAPI *_debugAPI;
int _initFlags;
int _PythonQtObjectPtr_metaId;
bool _hadError;
bool _systemExitExceptionHandlerEnabled;
friend class PythonQt;
};
#endif

View File

@ -0,0 +1,60 @@
#ifndef _PYTHONQTBOOLRESULT_H
#define _PYTHONQTBOOLRESULT_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtBoolResultt.h
// \author Florian Link
// \date 2014-09
*/
//----------------------------------------------------------------------------------
#include "PythonQtPythonInclude.h"
#include "PythonQtSystem.h"
#include "structmember.h"
extern PYTHONQT_EXPORT PyTypeObject PythonQtBoolResult_Type;
#define PythonQtBoolResult_Check(op) (Py_TYPE(op) == &PythonQtBoolResult_Type)
//! defines a python object that stores a single bool
typedef struct {
PyObject_HEAD
bool _value;
} PythonQtBoolResultObject;
#endif

View File

@ -0,0 +1,307 @@
#ifndef _PYTHONQTCLASSINFO_H
#define _PYTHONQTCLASSINFO_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
#include <QMetaObject>
#include <QMetaMethod>
#include <QHash>
#include <QByteArray>
#include <QList>
#include "PythonQt.h"
class PythonQtSlotInfo;
class PythonQtClassInfo;
struct PythonQtDynamicClassInfo
{
PythonQtDynamicClassInfo() { _dynamicMetaObject = NULL; _classInfo = NULL; }
~PythonQtDynamicClassInfo();
const QMetaObject* _dynamicMetaObject;
PythonQtClassInfo* _classInfo;
};
struct PythonQtMemberInfo {
enum Type {
Invalid, Slot, Signal, EnumValue, EnumWrapper, Property, NestedClass, NotFound
};
PythonQtMemberInfo():_type(Invalid),_slot(NULL),_pythonType(NULL),_enumValue(0) { }
PythonQtMemberInfo(PythonQtSlotInfo* info);
PythonQtMemberInfo(const PythonQtObjectPtr& enumValue);
PythonQtMemberInfo(const QMetaProperty& prop);
Type _type;
// TODO: this could be a union...
PythonQtSlotInfo* _slot;
PyObject* _pythonType;
PythonQtObjectPtr _enumValue;
QMetaProperty _property;
};
//! a class that stores all required information about a Qt object (and an optional associated C++ class name)
/*! for fast lookup of slots when calling the object from Python
*/
class PYTHONQT_EXPORT PythonQtClassInfo {
public:
PythonQtClassInfo();
~PythonQtClassInfo();
//! store information about parent classes
struct ParentClassInfo {
ParentClassInfo(PythonQtClassInfo* parent, int upcastingOffset=0):_parent(parent),_upcastingOffset(upcastingOffset)
{};
PythonQtClassInfo* _parent;
int _upcastingOffset;
};
//! setup as a QObject, taking the meta object as meta information about the QObject
void setupQObject(const QMetaObject* meta);
//! setup as a CPP (non-QObject), taking the classname
void setupCPPObject(const QByteArray& classname);
//! set the type capabilities
void setTypeSlots(int typeSlots) { _typeSlots = typeSlots; }
//! get the type capabilities
int typeSlots() const { return _typeSlots; }
//! get the Python method definition for a given slot name (without return type and signature)
PythonQtMemberInfo member(const char* member);
//! get access to the constructor slot (which may be overloaded if there are multiple constructors)
PythonQtSlotInfo* constructors();
//! get access to the destructor slot
PythonQtSlotInfo* destructor();
//! add a constructor, ownership is passed to classinfo
void addConstructor(PythonQtSlotInfo* info);
//! set a destructor, ownership is passed to classinfo
void setDestructor(PythonQtSlotInfo* info);
//! add a decorator slot, ownership is passed to classinfo
void addDecoratorSlot(PythonQtSlotInfo* info);
//! add a nested class, so that it can be shown as outer class member
void addNestedClass(PythonQtClassInfo* info);
//! get the classname (either of the QObject or of the wrapped CPP object)
const QByteArray& className() const;
//! get the unscoped classname (without ParentClass::) for nested classes
QByteArray unscopedClassName() const;
//! returns if the QObject
bool isQObject() { return _isQObject; }
//! returns if the class is a CPP wrapper
bool isCPPWrapper() { return !_isQObject; }
//! get the meta object
const QMetaObject* metaObject() { return _meta; }
//! set the meta object, this will reset the caching
void setMetaObject(const QMetaObject* meta);
//! returns if this class inherits from the given classname
bool inherits(const char* classname);
//! returns if this class inherits from the given classinfo
bool inherits(PythonQtClassInfo* info);
//! casts the given \c ptr to an object of type \c classname, returns the new pointer
//! which might be different to \c ptr due to C++ multiple inheritance
//! (if the cast is not possible or if ptr is NULL, NULL is returned)
void* castTo(void* ptr, const char* classname);
//! get help string for the metaobject
QString help();
//! get list of all properties (on QObjects only, otherwise the list is empty)
QStringList propertyList();
//! get list of all members (excluding properties, which can be listed with propertyList())
QStringList memberList();
//! get the meta type id of this class (only valid for isCPPWrapper() == true)
int metaTypeId() { return _metaTypeId; }
//! set an additional decorator provider that offers additional decorator slots for this class
void setDecoratorProvider(PythonQtQObjectCreatorFunctionCB* cb);
//! get the decorator qobject instance
QObject* decorator();
//! add the parent class info of a CPP object
void addParentClass(const ParentClassInfo& info) { _parentClasses.append(info); }
//! set the associated PythonQtClassWrapper (which handles instance creation of this type)
void setPythonQtClassWrapper(PyObject* obj) { _pythonQtClassWrapper = obj; }
//! get the associated PythonQtClassWrapper (which handles instance creation of this type)
PyObject* pythonQtClassWrapper() { return _pythonQtClassWrapper; }
//! set the shell set instance wrapper cb
void setShellSetInstanceWrapperCB(PythonQtShellSetInstanceWrapperCB* cb) {
_shellSetInstanceWrapperCB = cb;
}
//! get the shell set instance wrapper cb
PythonQtShellSetInstanceWrapperCB* shellSetInstanceWrapperCB() {
return _shellSetInstanceWrapperCB;
}
//! add a handler for polymorphic downcasting
void addPolymorphicHandler(PythonQtPolymorphicHandlerCB* cb) { _polymorphicHandlers.append(cb); }
//! cast the pointer down in the class hierarchy if a polymorphic handler allows to do that
void* castDownIfPossible(void* ptr, PythonQtClassInfo** resultClassInfo);
//! returns if the localScope has an enum of that type name or if the enum contains a :: scope, if that class contails the enum
static PyObject* findEnumWrapper(const QByteArray& name, PythonQtClassInfo* localScope, bool* isLocalEnum = NULL);
//! clear all members that where cached as "NotFound"
void clearNotFoundCachedMembers();
//! get nested classes
const QList<PythonQtClassInfo*>& nestedClasses() { return _nestedClasses; }
//! Create a copy of the given C++ object (which is known to be of a derived class), wrapped by Python and owned by PythonQt.
//! This will downcast if possible and return a copy of the down casted object.
//! This either requires a copy constructor on the class or it needs to be registered
//! as a meta type.
PyObject* copyObject(void* cppObject);
//! Get the copy constructor for this class
PythonQtSlotInfo* getCopyConstructor();
//! Sets reference counting callbacks for this class and all its subclasses
void setReferenceCounting(PythonQtVoidPtrCB* refCB, PythonQtVoidPtrCB* unrefCB);
//! Returns the ref counting CB, if there is any
PythonQtVoidPtrCB* referenceCountingRefCB();
//! Returns the unref counting CB, if there is any
PythonQtVoidPtrCB* referenceCountingUnrefCB();
//! Returns the Python type object for a given property.
//! (the returned object does not get an extra reference count)
PyObject* getPythonTypeForProperty(const QString& name);
//! Returns the class info for given property, if available.
PythonQtClassInfo* getClassInfoForProperty( const QString& name );
//! Returns if the class supports rich compare. This tests for
//! __eq__, __ne__, __lt__, __le__, __gt__, __ge__ slots and if
//! any of the slots is present it returns true and modifies the
//! _typeSlots with Type_RichCompare. The result is cached internally.
bool supportsRichCompare();
private:
void updateRefCountingCBs();
void createEnumWrappers(const QObject* decoratorProvider);
void createEnumWrappers(const QMetaObject* meta);
PyObject* findEnumWrapper(const char* name);
//! clear all cached members
void clearCachedMembers();
void* recursiveCastDownIfPossible(void* ptr, const char** resultClassName);
PythonQtSlotInfo* findDecoratorSlotsFromDecoratorProvider(const char* memberName, PythonQtSlotInfo* inputInfo, bool &found, QHash<QByteArray, PythonQtMemberInfo>& memberCache, int upcastingOffset);
void listDecoratorSlotsFromDecoratorProvider(QStringList& list, bool metaOnly);
PythonQtSlotInfo* recursiveFindDecoratorSlotsFromDecoratorProvider(const char* memberName, PythonQtSlotInfo* inputInfo, bool &found, QHash<QByteArray, PythonQtMemberInfo>& memberCache, int upcastingOffset);
void recursiveCollectClassInfos(QList<PythonQtClassInfo*>& classInfoObjects);
void recursiveCollectDecoratorObjects(QList<QObject*>& decoratorObjects);
bool lookForPropertyAndCache(const char* memberName);
bool lookForMethodAndCache(const char* memberName);
bool lookForEnumAndCache(const QMetaObject* m, const char* memberName);
PythonQtSlotInfo* findDecoratorSlots(const char* memberName, PythonQtSlotInfo* tail, bool &found, QHash<QByteArray, PythonQtMemberInfo>& memberCache, int upcastingOffset);
int findCharOffset(const char* sigStart, char someChar);
QHash<QByteArray, PythonQtMemberInfo> _cachedMembers;
PythonQtSlotInfo* _constructors;
PythonQtSlotInfo* _destructor;
PythonQtVoidPtrCB* _refCallback;
PythonQtVoidPtrCB* _unrefCallback;
QList<PythonQtSlotInfo*> _decoratorSlots;
QList<PythonQtObjectPtr> _enumWrappers;
const QMetaObject* _meta;
QByteArray _wrappedClassName;
QList<ParentClassInfo> _parentClasses;
QList<PythonQtPolymorphicHandlerCB*> _polymorphicHandlers;
QList<PythonQtClassInfo*> _nestedClasses;
QObject* _decoratorProvider;
PythonQtQObjectCreatorFunctionCB* _decoratorProviderCB;
PyObject* _pythonQtClassWrapper;
PythonQtShellSetInstanceWrapperCB* _shellSetInstanceWrapperCB;
int _metaTypeId;
int _typeSlots;
bool _isQObject;
bool _enumsCreated;
bool _richCompareDetectionDone;
bool _searchPolymorphicHandlerOnParent;
bool _searchRefCountCB;
};
//---------------------------------------------------------------
#endif

View File

@ -0,0 +1,81 @@
#ifndef _PYTHONQTCLASSWRAPPER_H
#define _PYTHONQTCLASSWRAPPER_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtClassWrapper.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-05
*/
//----------------------------------------------------------------------------------
#include "PythonQtPythonInclude.h"
#include "PythonQtSystem.h"
#include "structmember.h"
#include "methodobject.h"
#include "compile.h"
#include "eval.h"
#include <QString>
class PythonQtClassInfo;
//! the type of the PythonQt class wrapper objects
extern PYTHONQT_EXPORT PyTypeObject PythonQtClassWrapper_Type;
struct PythonQtDynamicClassInfo;
//---------------------------------------------------------------
//! a Python wrapper object for PythonQt wrapped classes
//! which inherits from the Python type object to allow
//! deriving of wrapped CPP classes from Python.
typedef struct {
PyHeapTypeObject _base;
//! the additional class information that PythonQt stores for the CPP class
PythonQtClassInfo* _classInfo;
//! get the class info
PythonQtClassInfo* classInfo() { return _classInfo; }
PythonQtDynamicClassInfo* _dynamicClassInfo;
} PythonQtClassWrapper;
//---------------------------------------------------------------
#endif

View File

@ -0,0 +1,525 @@
#ifndef _PYTHONQTCONVERSION_H
#define _PYTHONQTCONVERSION_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtConversion.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-05
*/
//----------------------------------------------------------------------------------
#include "PythonQt.h"
#include "PythonQtMisc.h"
#include "PythonQtClassInfo.h"
#include "PythonQtMethodInfo.h"
#include <QList>
#include <vector>
typedef PyObject* PythonQtConvertMetaTypeToPythonCB(const void* inObject, int metaTypeId);
typedef bool PythonQtConvertPythonToMetaTypeCB(PyObject* inObject, void* outObject, int metaTypeId, bool strict);
typedef QVariant PythonQtConvertPythonSequenceToQVariantListCB(PyObject* inObject);
#define PythonQtRegisterListTemplateConverter(type, innertype) \
{ int typeId = qRegisterMetaType<type<innertype > >(#type"<"#innertype">"); \
PythonQtConv::registerPythonToMetaTypeConverter(typeId, PythonQtConvertPythonListToListOfValueType<type<innertype >, innertype>); \
PythonQtConv::registerMetaTypeToPythonConverter(typeId, PythonQtConvertListOfValueTypeToPythonList<type<innertype >, innertype>); \
}
#define PythonQtRegisterListTemplateConverterForKnownClass(type, innertype) \
{ int typeId = qRegisterMetaType<type<innertype > >(#type"<"#innertype">"); \
PythonQtConv::registerPythonToMetaTypeConverter(typeId, PythonQtConvertPythonListToListOfKnownClass<type<innertype >, innertype>); \
PythonQtConv::registerMetaTypeToPythonConverter(typeId, PythonQtConvertListOfKnownClassToPythonList<type<innertype >, innertype>); \
}
#define PythonQtRegisterQPairConverter(type1, type2) \
{ int typeId = qRegisterMetaType<QPair<type1, type2> >("QPair<"#type1","#type2">"); \
PythonQtConv::registerPythonToMetaTypeConverter(typeId, PythonQtConvertPythonToPair<type1, type2>); \
PythonQtConv::registerMetaTypeToPythonConverter(typeId, PythonQtConvertPairToPython<type1, type2>); \
}
#define PythonQtRegisterIntegerMapConverter(type, innertype) \
{ int typeId = qRegisterMetaType<type<int, innertype > >(#type"<int, "#innertype">"); \
PythonQtConv::registerPythonToMetaTypeConverter(typeId, PythonQtConvertPythonToIntegerMap<type<int, innertype >, innertype>); \
PythonQtConv::registerMetaTypeToPythonConverter(typeId, PythonQtConvertIntegerMapToPython<type<int, innertype >, innertype>); \
}
#define PythonQtRegisterListTemplateQPairConverter(listtype, type1, type2) \
{ \
qRegisterMetaType<QPair<type1, type2> >("QPair<"#type1","#type2">"); \
int typeId = qRegisterMetaType<listtype<QPair<type1, type2> > >(#listtype"<QPair<"#type1","#type2">>"); \
PythonQtConv::registerPythonToMetaTypeConverter(typeId, PythonQtConvertPythonListToListOfPair<listtype<QPair<type1, type2> >, type1, type2>); \
PythonQtConv::registerMetaTypeToPythonConverter(typeId, PythonQtConvertListOfPairToPythonList<listtype<QPair<type1, type2> >, type1, type2>); \
}
#define PythonQtRegisterToolClassesTemplateConverter(innertype) \
PythonQtRegisterListTemplateConverter(QList, innertype); \
PythonQtRegisterListTemplateConverter(QVector, innertype); \
PythonQtRegisterListTemplateConverter(std::vector, innertype);
#define PythonQtRegisterToolClassesTemplateConverterForKnownClass(innertype) \
PythonQtRegisterListTemplateConverterForKnownClass(QList, innertype); \
PythonQtRegisterListTemplateConverterForKnownClass(QVector, innertype); \
PythonQtRegisterListTemplateConverterForKnownClass(std::vector, innertype);
//! a static class that offers methods for type conversion
class PYTHONQT_EXPORT PythonQtConv {
public:
//! get a ref counted True or False Python object
static PyObject* GetPyBool(bool val);
//! converts the Qt parameter given in \c data, interpreting it as a \c info parameter, into a Python object,
static PyObject* ConvertQtValueToPython(const PythonQtMethodInfo::ParameterInfo& info, const void* data);
//! convert python object to Qt (according to the given parameter) and if the conversion should be strict (classInfo is currently not used anymore)
static void* ConvertPythonToQt(const PythonQtMethodInfo::ParameterInfo& info, PyObject* obj, bool strict, PythonQtClassInfo* classInfo, void* alreadyAllocatedCPPObject = NULL);
//! creates a data storage for the passed parameter type and returns a void pointer to be set as arg[0] of qt_metacall
static void* CreateQtReturnValue(const PythonQtMethodInfo::ParameterInfo& info);
//! converts QString to Python string (unicode!)
static PyObject* QStringToPyObject(const QString& str);
//! converts QStringList to Python tuple
static PyObject* QStringListToPyObject(const QStringList& list);
//! converts QStringList to Python list
static PyObject* QStringListToPyList(const QStringList& list);
//! get string representation of py object
static QString PyObjGetRepresentation(PyObject* val);
//! get string value from py object
static QString PyObjGetString(PyObject* val) { bool ok; QString s = PyObjGetString(val, false, ok); return s; }
//! get string value from py object
static QString PyObjGetString(PyObject* val, bool strict, bool &ok);
//! get bytes from py object
static QByteArray PyObjGetBytes(PyObject* val, bool strict, bool &ok);
//! get int from py object
static int PyObjGetInt(PyObject* val, bool strict, bool &ok);
//! get int64 from py object
static qint64 PyObjGetLongLong(PyObject* val, bool strict, bool &ok);
//! get int64 from py object
static quint64 PyObjGetULongLong(PyObject* val, bool strict, bool &ok);
//! get double from py object
static double PyObjGetDouble(PyObject* val, bool strict, bool &ok);
//! get bool from py object
static bool PyObjGetBool(PyObject* val, bool strict, bool &ok);
//! create a string list from python sequence
static QStringList PyObjToStringList(PyObject* val, bool strict, bool& ok);
//! convert python object to qvariant, if type is given it will try to create a qvariant of that type, otherwise
//! it will guess from the python type
static QVariant PyObjToQVariant(PyObject* val, int type = -1);
//! convert QVariant from PyObject
static PyObject* QVariantToPyObject(const QVariant& v);
static PyObject* QVariantHashToPyObject(const QVariantHash& m);
static PyObject* QVariantMapToPyObject(const QVariantMap& m);
static PyObject* QVariantListToPyObject(const QVariantList& l);
//! get human readable string from CPP object (when the metatype is known)
static QString CPPObjectToString(int type, const void* data);
//! register a converter callback from python to cpp for given metatype
static void registerPythonToMetaTypeConverter(int metaTypeId, PythonQtConvertPythonToMetaTypeCB* cb) { _pythonToMetaTypeConverters.insert(metaTypeId, cb); }
//! register a converter callback from cpp to python for given metatype
static void registerMetaTypeToPythonConverter(int metaTypeId, PythonQtConvertMetaTypeToPythonCB* cb) { _metaTypeToPythonConverters.insert(metaTypeId, cb); }
//! set a callback that is called when a Python sequence should be converted to a QVariantList
//! to allow special conversion.
static void setPythonSequenceToQVariantListCallback(PythonQtConvertPythonSequenceToQVariantListCB* cb) { _pythonSequenceToQVariantListCB = cb; }
//! converts the Qt parameter given in \c data, interpreting it as a \c type registered qvariant/meta type, into a Python object,
static PyObject* convertQtValueToPythonInternal(int type, const void* data);
//! creates a copy of given object, using the QMetaType
static PyObject* createCopyFromMetaType( int type, const void* object );
//! cast wrapper to given className if possible
static void* castWrapperTo(PythonQtInstanceWrapper* wrapper, const QByteArray& className, bool& ok);
static bool convertToPythonQtObjectPtr(PyObject* obj, void* /* PythonQtObjectPtr* */ outPtr, int /*metaTypeId*/, bool /*strict*/);
static PyObject* convertFromPythonQtObjectPtr(const void* /* PythonQtObjectPtr* */ inObject, int /*metaTypeId*/);
static bool convertToQListOfPythonQtObjectPtr(PyObject* obj, void* /* QList<PythonQtObjectPtr>* */ outList, int /*metaTypeId*/, bool /*strict*/);
static PyObject* convertFromQListOfPythonQtObjectPtr(const void* /* QList<PythonQtObjectPtr>* */ inObject, int /*metaTypeId*/);
static PyObject* convertFromStringRef(const void* inObject, int /*metaTypeId*/);
//! Returns the name of the equivalent CPP type (for signals and slots)
static QByteArray getCPPTypeName(PyObject* type);
//! Returns if the given object is a string (or unicode string)
static bool isStringType(PyTypeObject* type);
public:
static PythonQtValueStorage<qint64, 128> global_valueStorage;
static PythonQtValueStorage<void*, 128> global_ptrStorage;
static PythonQtValueStorageWithCleanup<QVariant, 128> global_variantStorage;
protected:
static QHash<int, PythonQtConvertMetaTypeToPythonCB*> _metaTypeToPythonConverters;
static QHash<int, PythonQtConvertPythonToMetaTypeCB*> _pythonToMetaTypeConverters;
static PythonQtConvertPythonSequenceToQVariantListCB* _pythonSequenceToQVariantListCB;
//! handle automatic conversion of some special types (QColor, QBrush, ...)
static void* handlePythonToQtAutoConversion(int typeId, PyObject* obj, void* alreadyAllocatedCPPObject);
//! converts the list of pointers of given type to Python
static PyObject* ConvertQListOfPointerTypeToPythonList(QList<void*>* list, const PythonQtMethodInfo::ParameterInfo& info);
//! tries to convert the python object to a QList of pointers to \c type objects, returns true on success
static bool ConvertPythonListToQListOfPointerType(PyObject* obj, QList<void*>* list, const PythonQtMethodInfo::ParameterInfo& info, bool strict);
//! helper template method for conversion from Python to QVariantMap/Hash
template <typename Map>
static void pythonToMapVariant(PyObject* val, QVariant& result);
//! helper template function for QVariantMapToPyObject/QVariantHashToPyObject
template <typename Map>
static PyObject* mapToPython (const Map& m);
};
template<class ListType, class T>
PyObject* PythonQtConvertListOfValueTypeToPythonList(const void* /*QList<T>* */ inList, int metaTypeId)
{
ListType* list = (ListType*)inList;
static const int innerType = PythonQtMethodInfo::getInnerTemplateMetaType(QByteArray(QMetaType::typeName(metaTypeId)));
if (innerType == QVariant::Invalid) {
std::cerr << "PythonQtConvertListOfValueTypeToPythonList: unknown inner type " << QMetaType::typeName(metaTypeId) << std::endl;
}
PyObject* result = PyTuple_New(list->size());
int i = 0;
Q_FOREACH (const T& value, *list) {
PyTuple_SET_ITEM(result, i, PythonQtConv::convertQtValueToPythonInternal(innerType, &value));
i++;
}
return result;
}
template<class ListType, class T>
bool PythonQtConvertPythonListToListOfValueType(PyObject* obj, void* /*QList<T>* */ outList, int metaTypeId, bool /*strict*/)
{
ListType* list = (ListType*)outList;
static const int innerType = PythonQtMethodInfo::getInnerTemplateMetaType(QByteArray(QMetaType::typeName(metaTypeId)));
if (innerType == QVariant::Invalid) {
std::cerr << "PythonQtConvertPythonListToListOfValueType: unknown inner type " << QMetaType::typeName(metaTypeId) << std::endl;
}
bool result = false;
if (PySequence_Check(obj)) {
int count = PySequence_Size(obj);
if (count >= 0) {
result = true;
PyObject* value;
for (int i = 0;i<count;i++) {
value = PySequence_GetItem(obj,i);
// this is quite some overhead, but it avoids having another large switch...
QVariant v = PythonQtConv::PyObjToQVariant(value, innerType);
Py_XDECREF(value);
if (v.isValid()) {
list->push_back(qvariant_cast<T>(v));
} else {
result = false;
break;
}
}
}
}
return result;
}
//--------------------------------------------------------------------------------------------------------------------
template<class ListType, class T>
PyObject* PythonQtConvertListOfKnownClassToPythonList(const void* /*QList<T>* */ inList, int metaTypeId)
{
ListType* list = (ListType*)inList;
static PythonQtClassInfo* innerType = PythonQt::priv()->getClassInfo(PythonQtMethodInfo::getInnerListTypeName(QByteArray(QMetaType::typeName(metaTypeId))));
if (innerType == NULL) {
std::cerr << "PythonQtConvertListOfKnownClassToPythonList: unknown inner type " << innerType->className().constData() << std::endl;
}
PyObject* result = PyTuple_New(list->size());
int i = 0;
Q_FOREACH(const T& value, *list) {
T* newObject = new T(value);
PythonQtInstanceWrapper* wrap = (PythonQtInstanceWrapper*)PythonQt::priv()->wrapPtr(newObject, innerType->className());
wrap->_ownedByPythonQt = true;
PyTuple_SET_ITEM(result, i, (PyObject*)wrap);
i++;
}
return result;
}
template<class ListType, class T>
bool PythonQtConvertPythonListToListOfKnownClass(PyObject* obj, void* /*QList<T>* */ outList, int metaTypeId, bool /*strict*/)
{
ListType* list = (ListType*)outList;
static PythonQtClassInfo* innerType = PythonQt::priv()->getClassInfo(PythonQtMethodInfo::getInnerListTypeName(QByteArray(QMetaType::typeName(metaTypeId))));
if (innerType == NULL) {
std::cerr << "PythonQtConvertListOfKnownClassToPythonList: unknown inner type " << innerType->className().constData() << std::endl;
}
bool result = false;
if (PySequence_Check(obj)) {
int count = PySequence_Size(obj);
if (count >= 0) {
result = true;
PyObject* value;
for (int i = 0; i < count; i++) {
value = PySequence_GetItem(obj, i);
if (PyObject_TypeCheck(value, &PythonQtInstanceWrapper_Type)) {
PythonQtInstanceWrapper* wrap = (PythonQtInstanceWrapper*)value;
bool ok;
T* object = (T*)PythonQtConv::castWrapperTo(wrap, innerType->className(), ok);
Py_XDECREF(value);
if (ok) {
list->push_back(*object);
} else {
result = false;
break;
}
} else {
Py_XDECREF(value);
result = false;
break;
}
}
}
}
return result;
}
//--------------------------------------------------------------------------------------------------------------------
template<class T1, class T2>
PyObject* PythonQtConvertPairToPython(const void* /*QPair<T1,T2>* */ inPair, int metaTypeId)
{
QPair<T1, T2>* pair = (QPair<T1, T2>*)inPair;
static int innerType1 = -1;
static int innerType2 = -1;
if (innerType1==-1) {
QByteArray innerTypes = PythonQtMethodInfo::getInnerTemplateTypeName(QByteArray(QMetaType::typeName(metaTypeId)));
QList<QByteArray> names = innerTypes.split(',');
innerType1 = QMetaType::type(names.at(0).trimmed());
innerType2 = QMetaType::type(names.at(1).trimmed());
}
if (innerType1 == QVariant::Invalid || innerType2 == QVariant::Invalid) {
std::cerr << "PythonQtConvertPairToPython: unknown inner type " << QMetaType::typeName(metaTypeId) << std::endl;
}
PyObject* result = PyTuple_New(2);
PyTuple_SET_ITEM(result, 0, PythonQtConv::convertQtValueToPythonInternal(innerType1, &pair->first));
PyTuple_SET_ITEM(result, 1, PythonQtConv::convertQtValueToPythonInternal(innerType2, &pair->second));
return result;
}
template<class T1, class T2>
bool PythonQtConvertPythonToPair(PyObject* obj, void* /*QPair<T1,T2>* */ outPair, int metaTypeId, bool /*strict*/)
{
QPair<T1, T2>* pair = (QPair<T1, T2>*)outPair;
static int innerType1 = -1;
static int innerType2 = -1;
if (innerType1 == -1) {
QByteArray innerTypes = PythonQtMethodInfo::getInnerTemplateTypeName(QByteArray(QMetaType::typeName(metaTypeId)));
QList<QByteArray> names = innerTypes.split(',');
innerType1 = QMetaType::type(names.at(0).trimmed());
innerType2 = QMetaType::type(names.at(1).trimmed());
}
if (innerType1 == QVariant::Invalid || innerType2 == QVariant::Invalid) {
std::cerr << "PythonQtConvertPythonToPair: unknown inner type " << QMetaType::typeName(metaTypeId) << std::endl;
}
bool result = false;
if (PySequence_Check(obj)) {
int count = PySequence_Size(obj);
if (count == 2) {
result = true;
PyObject* value;
value = PySequence_GetItem(obj, 0);
// this is quite some overhead, but it avoids having another large switch...
QVariant v = PythonQtConv::PyObjToQVariant(value, innerType1);
Py_XDECREF(value);
if (v.isValid()) {
pair->first = qvariant_cast<T1>(v);
} else {
return false;
}
value = PySequence_GetItem(obj, 1);
// this is quite some overhead, but it avoids having another large switch...
v = PythonQtConv::PyObjToQVariant(value, innerType2);
Py_XDECREF(value);
if (v.isValid()) {
pair->second = qvariant_cast<T2>(v);
} else {
return false;
}
}
}
return result;
}
//--------------------------------------------------------------------------------------------------------------------
template<class ListType, class T1, class T2>
PyObject* PythonQtConvertListOfPairToPythonList(const void* /*QList<QPair<T1,T2> >* */ inList, int metaTypeId)
{
ListType* list = (ListType*)inList;
static int innerType = PythonQtMethodInfo::getInnerTemplateMetaType(QByteArray(QMetaType::typeName(metaTypeId)));
if (innerType == QVariant::Invalid) {
std::cerr << "PythonQtConvertListOfPairToPythonList: unknown inner type " << QMetaType::typeName(metaTypeId) << std::endl;
}
PyObject* result = PyTuple_New(list->size());
int i = 0;
typedef const QPair<T1, T2> Pair;
Q_FOREACH(Pair& value, *list) {
PyObject* object = PythonQtConvertPairToPython<T1, T2>(&value, innerType);
PyTuple_SET_ITEM(result, i, object);
i++;
}
return result;
}
template<class ListType, class T1, class T2>
bool PythonQtConvertPythonListToListOfPair(PyObject* obj, void* /*QList<QPair<T1,T2> >* */ outList, int metaTypeId, bool /*strict*/)
{
ListType* list = (ListType*)outList;
static int innerType = PythonQtMethodInfo::getInnerTemplateMetaType(QByteArray(QMetaType::typeName(metaTypeId)));
if (innerType == QVariant::Invalid) {
std::cerr << "PythonQtConvertPythonListToListOfPair: unknown inner type " << QMetaType::typeName(metaTypeId) << std::endl;
}
bool result = false;
if (PySequence_Check(obj)) {
int count = PySequence_Size(obj);
if (count >= 0) {
result = true;
PyObject* value;
for (int i = 0; i < count; i++) {
QPair<T1, T2> pair;
value = PySequence_GetItem(obj, i);
if (PythonQtConvertPythonToPair<T1,T2>(value, &pair, innerType, false)) {
Py_XDECREF(value);
list->push_back(pair);
} else {
Py_XDECREF(value);
result = false;
break;
}
}
}
}
return result;
}
//--------------------------------------------------------------------------------------------------------------------
template<class MapType, class T>
PyObject* PythonQtConvertIntegerMapToPython(const void* /*QMap<int, T>* */ inMap, int metaTypeId)
{
MapType* map = (MapType*)inMap;
static int innerType = -1;
if (innerType == -1) {
QByteArray innerTypes = PythonQtMethodInfo::getInnerTemplateTypeName(QByteArray(QMetaType::typeName(metaTypeId)));
QList<QByteArray> names = innerTypes.split(',');
innerType = QMetaType::type(names.at(1).trimmed());
}
if (innerType == QVariant::Invalid) {
std::cerr << "PythonQtConvertIntegerMapToPython: unknown inner type " << QMetaType::typeName(metaTypeId) << std::endl;
}
PyObject* result = PyDict_New();
typename MapType::const_iterator t = map->constBegin();
PyObject* key;
PyObject* val;
for (; t != map->constEnd(); t++) {
key = PyInt_FromLong(t.key());
val = PythonQtConv::convertQtValueToPythonInternal(innerType, &t.value());
PyDict_SetItem(result, key, val);
Py_DECREF(key);
Py_DECREF(val);
}
return result;
}
template<class MapType, class T>
bool PythonQtConvertPythonToIntegerMap(PyObject* val, void* /*QMap<int, T>* */ outMap, int metaTypeId, bool /*strict*/)
{
MapType* map = (MapType*)outMap;
static int innerType = -1;
if (innerType == -1) {
QByteArray innerTypes = PythonQtMethodInfo::getInnerTemplateTypeName(QByteArray(QMetaType::typeName(metaTypeId)));
QList<QByteArray> names = innerTypes.split(',');
innerType = QMetaType::type(names.at(1).trimmed());
}
if (innerType == QVariant::Invalid) {
std::cerr << "PythonQtConvertPythonToIntegerMap: unknown inner type " << QMetaType::typeName(metaTypeId) << std::endl;
}
bool result = false;
if (PyMapping_Check(val)) {
result = true;
PyObject* items = PyMapping_Items(val);
if (items) {
int count = PyList_Size(items);
PyObject* value;
PyObject* key;
PyObject* tuple;
for (int i = 0; i < count; i++) {
tuple = PyList_GetItem(items, i);
key = PyTuple_GetItem(tuple, 0);
value = PyTuple_GetItem(tuple, 1);
bool ok;
int intKey = PythonQtConv::PyObjGetInt(key, false, ok);
// this is quite some overhead, but it avoids having another large switch...
QVariant v = PythonQtConv::PyObjToQVariant(value, innerType);
if (v.isValid() && ok) {
map->insert(intKey, qvariant_cast<T>(v));
} else {
result = false;
break;
}
}
Py_DECREF(items);
}
}
return result;
}
#endif

View File

@ -0,0 +1,86 @@
#ifndef _PYTHONQTCPPWRAPPERFACTORY_H
#define _PYTHONQTCPPWRAPPERFACTORY_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtCppWrapperFactory.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-06
*/
//----------------------------------------------------------------------------------
#include "PythonQtPythonInclude.h"
#include "PythonQtSystem.h"
#include <QObject>
#include <QByteArray>
//! Factory interface for C++ classes that can be wrapped by QObject objects
/*! To create your own factory, derive PythonQtCppWrapperFactory and implement
the create() method.
A factory can be added to PythonQt by PythonQt::addCppWrapperFactory().
*/
class PYTHONQT_EXPORT PythonQtCppWrapperFactory
{
public:
PythonQtCppWrapperFactory() {};
virtual ~PythonQtCppWrapperFactory() {};
//! create a wrapper for the given object
virtual QObject* create(const QByteArray& classname, void *ptr) = 0;
};
//! Factory interface for C++ classes that can be mapped directly from/to
//! Python with other means than PythonQt/QObjects.
class PYTHONQT_EXPORT PythonQtForeignWrapperFactory
{
public:
PythonQtForeignWrapperFactory() {};
virtual ~PythonQtForeignWrapperFactory() {};
//! create a Python object (with new reference count), wrapping the given \p ptr as class of type \p classname
//! Return NULL (and not Py_None) if the object could not be wrapped.
virtual PyObject* wrap(const QByteArray& classname, void *ptr) = 0;
//! unwrap the given object to a C++ object of type \p classname if possible
//! Return NULL otherwise.
virtual void* unwrap(const QByteArray& classname, PyObject* object) = 0;
};
#endif

574
PythonQt/PythonQtDoc.h Normal file
View File

@ -0,0 +1,574 @@
#ifndef _PYTHONQTDOC_H
#define _PYTHONQTDOC_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtDoc.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-10
*/
//----------------------------------------------------------------------------------
/*!
\if USE_GLOBAL_DOXYGEN_DOC
\page PythonQtPage PythonQt Overview
\else
\mainpage notitle
\endif
\image html PythonQt.jpg
\section Introduction
\b PythonQt is a dynamic <a href="http://www.python.org" target="_blank">
Python</a> binding for the <a href="http://qt-project.org/" target="_blank">
Qt framework</a>.
It offers an easy way to embed the Python scripting language into
your C++ Qt applications.
The focus of PythonQt is on embedding Python into an existing C++ application, not on writing the whole
application completely in Python.
If you are looking for a simple way to embed Python objects into your C++/Qt Application
and to script parts of your application via Python, PythonQt is the way to go!
PythonQt is a stable library that was developed to make the
Image Processing and Visualization platform <a href="http://www.mevislab.de" target="_blank">MeVisLab</a>
scriptable from Python.
- \ref Features
- \ref Download
- \ref License
- \ref Developer
- \ref Building
- \ref Examples
\page Features Features
\section Builtin Built-in Features
The following are the built-in features of the PythonQt library:
- Access all \b slots, \b properties, children and registered enums of any QObject derived class from Python
- Connecting Qt Signals to Python functions (both from within Python and from C++)
- Easy wrapping of Python objects from C++ with smart, reference-counting PythonQtObjectPtr.
- Convenient conversions to/from QVariant for PythonQtObjectPtr.
- Wrapping of C++ objects (which are not derived from QObject) via PythonQtCppWrapperFactory
- Extending C++ and QObject derived classes with additional slots, static methods and constructors (see Decorators)
- StdOut/Err redirection to Qt signals instead of cout
- Interface for creating your own \c import replacement, so that Python scripts can be e.g. signed/verified before they are executed (PythonQtImportFileInterface)
- Mapping of plain-old-datatypes and ALL QVariant types to and from Python
- Support for wrapping of user QVariant types which are registerd via QMetaType
- Support for Qt namespace (with all enumerators)
- All PythonQt wrapped objects support the dir() statement, so that you can see easily which attributes a QObject, CPP object or QVariant has
- No preprocessing/wrapping tool needs to be started, PythonQt can script any QObject without prior knowledge about it (except for the MetaObject information from the \b moc)
- Multiple inheritance for C++ objects (e.g. a QWidget is derived from QObject and QPaintDevice, PythonQt will automatically cast a QWidget to a QPaintDevice when needed)
- Polymorphic downcasting (if e.g. PythonQt sees a QEvent, it can downcast it depending on the type(), so the Python e.g. sees a QPaintEvent instead of a plain QEvent)
- Deriving C++ objects from Python and overwriting virtual method with a Python implementation (requires usage of wrapper generator or manual work!)
- Extensible handler for Python/C++ conversion of complex types, e.g. mapping of QVector<SomeObject> to/from a Python array
- Setting of dynamic QObject properties via setProperty(), dynamic properties can be accessed for reading and writing like normal Python attributes (but creating a new property needs to be done with setProperty(), to distinguish from normal Python attributes)
- Support for QtCore.Signal, QtCore.Slot and QtCore.Property, including the creation of a dynamic QMetaObject.
\section FeaturesQtAll Features with wrapper generator
PythonQt offers the additional PythonQt_QtAll library which wraps the complete Qt API, including all C++ classes and all non-slots on QObject derived classes.
This offers the following features:
- Complete Qt API wrapped and accessible
- The following modules are available as submodules of the PythonQt module:
- QtCore
- QtGui
- QtNetwork
- QtOpenGL
- QtSql
- QtSvg
- QtWebKit
- QtXml
- QtXmlPatterns
- QtMultimedia
- QtQml
- QtQuick
- Any Qt class that has virtual methods can be easily derived from Python and the virtual methods can be reimplemented in Python
- Polymorphic downcasting on QEvent, QGraphicsItem, QStyleOption, ...
- Multiple inheritance support (e.g., QGraphicsTextItem is a QObject and a QGraphicsItem, PythonQt will handle this well)
- QtQuick support is experimental and currently it is not possible to register new qml components from Python
\section Supported Supported Versions
PythonQt supports:
- Python 2 (>= Python 2.6)
- Python 3 (>= Python 3.3)
- Qt 4.x (Qt 4.7 and Qt 4.8 recommended)
- Qt 5.x (Tested with Qt 5.0, 5.3, 5.4 and 5.6)
The last working Qt4 version is available at svn branches/Qt4LastWorkingVersion or you can download the PythonQt 3.0 release.
The current svn trunk no longer supports Qt4, since we started to make use of some Qt5-only features.
\section Comparison Comparison with PySide
- PythonQt is not as pythonic as PySide in many details (e.g. buffer protocol, pickling, translation support, ...) and it is mainly thought for embedding and intercommunication between Qt/Cpp and Python
- PythonQt offers properties as Python attributes, while PySide offers them as setter/getter methods (e.g. QWidget.width is a property in PythonQt and a method in PySide)
- PythonQt currently does not support instanceof checks for Qt classes, except for the exact match and derived Python classes
- QObject.emit to emit Qt signals from Python is not yet implemented but PythonQt allows to just emit a signal by calling it like a normal slot
- Ownership handling of objects is not as complete as in PySide and PySide, especially in situations where the ownership is not clearly passed to C++ on the C++ API.
- QStrings are always converted to unicode Python objects, QByteArray always stays a QByteArray and can be converted using QByteArray.data()
- Qt methods that take an extra "bool* ok" parameter can be called passing PythonQt.BoolResult as parameter. In PySide, a tuple is returned instead.
\page Download Download
PythonQt is hosted on <a href="http://sourceforge.net/projects/pythonqt/" target="_blank">SourceForge</a>.
You can download the source code as a tarball at http://sourceforge.net/projects/pythonqt/files/.
Alternatively you can get the latest version from the svn repository.
You can also browse the source code online via ViewVC: http://pythonqt.svn.sourceforge.net/viewvc/pythonqt/trunk/
\note We do not offer prebuilt binaries, since there are so many possible combinations of
platforms (Windows/Linux/MacOs), architectures (32/64 bit) and Qt / Python versions.
\page License License
PythonQt is distributed under the LGPL 2.1 license. It can be used in commercial applications when following the LGPL 2.1 obligations.
The build system of PythonQt makes use of a modified version of the LGPL'ed QtScript generator,
located in the "generator" directory.
See http://qt.gitorious.org/qt-labs/qtscriptgenerator for details on the original project.
Thanks a lot to the QtJambi guys and the QtScript Generator project for the C++ parser and
Qt typesystem files!
The PythonQt wrappers generated by the generator located in the "generated_cpp" directory are free to be used without any licensing restrictions.
The generated wrappers are pre-generated and checked-in for 5.0, 5.3, 5.4 and 5.6, so you only need to build and run the
generator when you want to build additional wrappers or you want to upgrade/downgrade to another Qt version.
You may use the generator to generate C++ bindings for your own C++ classes (e.g., to make them inheritable in Python),
but this is currently not documented and involves creating your own typesystem files.
\page Developer Developer
\section Interface Interface
The main interface to PythonQt is the PythonQt singleton.
PythonQt needs to be initialized via PythonQt::init() once.
Afterwards you communicate with the singleton via PythonQt::self().
PythonQt offers a complete Qt binding, which
needs to be enabled via PythonQt_QtAll::init().
\section Datatype Datatype Mapping
The following table shows the mapping between Python and Qt objects:
<table>
<tr><th>Qt/C++</th><th>Python</th></tr>
<tr><td>bool</td><td>bool</td></tr>
<tr><td>double</td><td>float</td></tr>
<tr><td>float</td><td>float</td></tr>
<tr><td>char/uchar,int/uint,short,ushort,QChar</td><td>integer</td></tr>
<tr><td>long</td><td>integer</td></tr>
<tr><td>ulong,longlong,ulonglong</td><td>long</td></tr>
<tr><td>QString</td><td>unicode string</td></tr>
<tr><td>QByteArray</td><td>QByteArray wrapper</td></tr>
<tr><td>char*</td><td>str</td></tr>
<tr><td>QStringList</td><td>tuple of unicode strings</td></tr>
<tr><td>QVariantList</td><td>tuple of objects</td></tr>
<tr><td>QVariantMap</td><td>dict of objects</td></tr>
<tr><td>QVariant</td><td>depends on type, see below</td></tr>
<tr><td>QSize, QRect and all other standard Qt QVariants</td><td>variant wrapper that supports complete API of the respective Qt classes</td></tr>
<tr><td>OwnRegisteredMetaType</td><td>C++ wrapper, optionally with additional information/wrapping provided by registerCPPClass()</td></tr>
<tr><td>QList<AnyObject*></td><td>converts to a list of CPP wrappers</td></tr>
<tr><td>QVector<AnyObject*></td><td>converts to a list of CPP wrappers</td></tr>
<tr><td>EnumType</td><td>Enum wrapper derived from python integer</td></tr>
<tr><td>QObject (and derived classes)</td><td>QObject wrapper</td></tr>
<tr><td>C++ object</td><td>CPP wrapper, either wrapped via PythonQtCppWrapperFactory or just decorated with decorators</td></tr>
<tr><td>PyObject</td><td>PyObject</td></tr>
</table>
PyObject is passed as direct pointer, which allows to pass/return any Python object directly to/from
a Qt slot that uses PyObject* as its argument/return value.
QVariants are mapped recursively as given above, e.g. a dictionary can
contain lists of dictionaries of doubles.
All Qt QVariant types are implemented, PythonQt supports the complete Qt API for these object.
\section QObject QObject Wrapping
All classes derived from QObject are automatically wrapped with a python wrapper class
when they become visible to the Python interpreter. This can happen via
- the PythonQt::addObject() method
- when a Qt \b slot returns a QObject derived object to python
- when a Qt \b signal contains a QObject and is connected to a python function
It is important that you call PythonQt::registerClass() for any QObject derived class
that may become visible to Python, except when you add it via PythonQt::addObject().
This will register the complete parent hierachy of the registered class, so that
when you register e.g. a QPushButton, QWidget will be registered as well (and all intermediate
parents).
From Python, you can talk to the returned QObjects in a natural way by calling
their slots and receiving the return values. You can also read/write all
properties of the objects as if they where normal python properties.
In addition to this, the wrapped objects support
- className() - returns a string that reprents the classname of the QObject
- help() - shows all properties, slots, enums, decorator slots and constructors of the object, in a printable form
- delete() - deletes the object (use with care, especially if you passed the ownership to C++)
- connect(signal, function) - connect the signal of the given object to a python function
- connect(signal, qobject, slot) - connect the signal of the given object to a slot of another QObject
- disconnect(signal, function) - disconnect the signal of the given object from a python function
- disconnect(signal, qobject, slot) - disconnect the signal of the given object from a slot of another QObject
- children() - returns the children of the object
- setParent(QObject) - set the parent
- QObject* parent() - get the parent
The below example shows how to connect signals in Python:
\code
# define a signal handler function
def someFunction(flag):
print flag
# button1 is a QPushButton that has been added to Python via addObject()
# connect the clicked signal to a python function:
button1.connect("clicked(bool)", someFunction)
\endcode
\section CPP CPP Wrapping
You can create dedicated wrapper QObjects for any C++ class. This is done by deriving from PythonQtCppWrapperFactory
and adding your factory via addWrapperFactory().
Whenever PythonQt encounters a CPP pointer (e.g. on a slot or signal)
and it does not known it as a QObject derived class, it will create a generic CPP wrapper. So even unknown C++ objects
can be passed through Python. If the wrapper factory supports the CPP class, a QObject wrapper will be created for each
instance that enters Python. An alternative to a complete wrapper via the wrapper factory are decorators, see \ref Decorators
\section MetaObject Meta Object/Class access
For each known C++ class, PythonQt provides a Python class. These classes are visible
inside of the "PythonQt" python module or in subpackages if a package is given when the class is registered.
A Meta class supports:
- access to all declared enum values
- constructors
- static methods
- unbound non-static methods
- help() and className()
From within Python, you can import the module "PythonQt" to access these classes and the Qt namespace.
\code
from PythonQt import QtCore
# namespace access:
print QtCore.Qt.AlignLeft
# constructors
a = QtCore.QSize(12,13)
b = QtCore.QFont()
# static method
QtCore.QDate.currentDate()
# enum value
QtCore.QFont.UltraCondensed
\endcode
\section Decorators Decorator slots
PythonQt introduces a new generic approach to extend any wrapped QObject or CPP object with
- constructors
- destructors (for CPP objects)
- additional slots
- static slots (callable on both the Meta object and the instances)
The idea behind decorators is that we wanted to make it as easy as possible to extend
wrapped objects. Since we already have an implementation for invoking any Qt Slot from
Python, it looked promising to use this approach for the extension of wrapped objects as well.
This avoids that the PythonQt user needs to care about how Python arguments are mapped from/to
Qt when he wants to create static methods, constructors and additional member functions.
The basic idea about decorators is to create a QObject derived class that implements slots
which take one of the above roles (e.g. constructor, destructor etc.) via a naming convention.
These slots are then assigned to other classes via the naming convention.
- SomeClassName* new_SomeClassName(...) - defines a constructor for "SomeClassName" that returns a new object of type SomeClassName (where SomeClassName can be any CPP class, not just QObject classes)
- void delete_SomeClassName(SomeClassName* o) - defines a destructor, which should delete the passed in object o
- anything static_SomeClassName_someMethodName(...) - defines a static method that is callable on instances and the meta class
- anything someMethodName(SomeClassName* o, ...) - defines a slot that will be available on SomeClassName instances (and derived instances). When such a slot is called the first argument is the pointer to the instance and the rest of the arguments can be used to make a call on the instance.
The below example shows all kinds of decorators in action:
\code
// an example CPP object
class YourCPPObject {
public:
YourCPPObject(int arg1, float arg2) { a = arg1; b = arg2; }
float doSomething(int arg1) { return arg1*a*b; };
private:
int a;
float b;
};
// an example decorator
class ExampleDecorator : public QObject
{
Q_OBJECT
public slots:
// add a constructor to QSize that takes a QPoint
QSize* new_QSize(const QPoint& p) { return new QSize(p.x(), p.y()); }
// add a constructor for QPushButton that takes a text and a parent widget
QPushButton* new_QPushButton(const QString& text, QWidget* parent=NULL) { return new QPushButton(text, parent); }
// add a constructor for a CPP object
YourCPPObject* new_YourCPPObject(int arg1, float arg2) { return new YourCPPObject(arg1, arg2); }
// add a destructor for a CPP object
void delete_YourCPPObject(YourCPPObject* obj) { delete obj; }
// add a static method to QWidget
QWidget* static_QWidget_mouseGrabber() { return QWidget::mouseGrabber(); }
// add an additional slot to QWidget (make move() callable, which is not declared as a slot in QWidget)
void move(QWidget* w, const QPoint& p) { w->move(p); }
// add an additional slot to QWidget, overloading the above move method
void move(QWidget* w, int x, int y) { w->move(x,y); }
// add a method to your own CPP object
int doSomething(YourCPPObject* obj, int arg1) { return obj->doSomething(arg1); }
};
...
PythonQt::self()->addDecorators(new ExampleDecorator());
PythonQt::self()->registerCPPClass("YourCPPObject");
\endcode
After you have registered an instance of the above ExampleDecorator, you can do the following from Python
(all these calls are mapped to the above decorator slots):
\code
from PythonQt import QtCore, QtGui, YourCPPObject
# call our new constructor of QSize
size = QtCore.QSize(QPoint(1,2));
# call our new QPushButton constructor
button = QtGui.QPushButton("sometext");
# call the move slot (overload1)
button.move(QPoint(0,0))
# call the move slot (overload2)
button.move(0,0)
# call the static method
grabber = QtGui.QWidget.mouseWrapper();
# create a CPP object via constructor
yourCpp = YourCPPObject(1,11.5)
# call the wrapped method on CPP object
print yourCpp.doSomething(1);
# destructor will be called:
yourCpp = None
\endcode
\section Ownership Ownership management
In PythonQt, each wrapped C++ object is either owned by Python or C++. When an object is created via a Python constructor,
it is owned by Python by default. When an object is returned from a C++ API (e.g. a slot), it is owned by C++ by default.
Since the Qt API contains various APIs that pass the ownership from/to other C++ objects, PythonQt needs to keep track of
such API calls. This is archieved by annotating arguments and return values in wrapper slots with magic templates:
- PythonQtPassOwnershipToCPP
- PythonQtPassOwnershipToPython
- PythonQtNewOwnerOfThis
These annotation templates work for since C++ pointer types. In addition to that, they work for QList<AnyObject*>,
to pass the ownership for each object in the list.
Examples:
\code
public slots:
//! Pass ownership of return value to Python
PythonQtPassOwnershipToPython<QGraphicsItem*> createNewItemOwnedByPython();
//! Pass ownership of item to C++
void addItemToCPP(PythonQtPassOwnershipToPython<QGraphicsItem*> item);
//! Pass ownership of items to C++ (Note that the QList can't be a reference nor a pointer).
void addItemToCPP(PythonQtPassOwnershipToPython<QList<QGraphicsItem*> > items);
//! Pass ownership of wrapped object to C++ if parent is != NULL
void addItemParent(QGraphicsItem* wrappedObject, PythonQtNewOwnerOfThis<QGraphicsItem*> parent);
\endcode
\page Building Building
PythonQt requires at least Qt 4.6.1 (for earlier Qt versions, you will need to run the pythonqt_generator, Qt 4.3 is the absolute minimum) and Python 2.6.x/2.7.x or Python 3.3 (or higher).
To compile PythonQt, you will need a python developer installation which includes Python's header files and
the python2x.[lib | dll | so | dynlib].
The recommended way to build PythonQt is to use the QMake-based *.pro file.
The build scripts a currently set to use Python 2.6.
You may need to tweak the \b build/python.prf file to set the correct Python includes and libs on your system.
\subsection Windows
On Windows, the (non-source) Python Windows installer can be used.
Make sure that you use the same compiler as the one that your Python distribution is built with.
If you want to use another compiler, you will need to build
Python yourself, using your compiler.
To build PythonQt, you need to set the environment variable \b PYTHON_PATH to point to the root
dir of the python installation and \b PYTHON_LIB to point to
the directory where the python lib file is located.
When using the prebuild Python installer, this will be:
\code
> set PYTHON_PATH = c:\Python26
> set PYTHON_LIB = c:\Python26\libs
\endcode
When using the python sources, this will be something like:
\code
> set PYTHON_PATH = c:\yourDir\Python-2.6.1\
> set PYTHON_LIB = c:\yourDir\Python-2.6.1\PCbuild8\Win32
\endcode
To build all, do the following (after setting the above variables):
\code
> cd PythonQtRoot
> vcvars32
> qmake
> nmake
\endcode
This should build everything. If Python can not be linked or include files can not be found,
you probably need to tweak \b build/python.prf
The tests and examples are located in PythonQt/lib.
When using a Python distribution, the debug build typically does not work because the
pythonxx_d.lib/.dll are not provided. You can tweak linking of the debug build to the release
Python version, but this typically requires patching pyconfig.h and removing Py_DEBUG and linker pragmas
(google for it!).
\subsection Linux
On Linux, you need to install a Python-dev package.
If Python can not be linked or include files can not be found,
you probably need to tweak \b build/python.prf
To build PythonQt, just do a:
\code
> cd PythonQtRoot
> qmake
> make all
\endcode
The tests and examples are located in PythonQt/lib.
You should add PythonQt/lib to your LD_LIBRARY_PATH so that the runtime
linker can find the *.so files.
\subsection MacOsX
On Mac, Python is installed as a Framework, so you should not need to install it.
To build PythonQt, just do a:
\code
> cd PythonQtRoot
> qmake
> make all
\endcode
\section Tests
There is a unit test that tests most features of PythonQt, see the \b tests subdirectory for details.
\page Examples Examples
Examples are available in the \b examples directory. The PyScriptingConsole implements a simple
interactive scripting console that shows how to script a simple application. The PyLauncher application can be used to run arbitrary PythonQt scripts given on the commandline.
The following shows a simple example on how to integrate PythonQt into your Qt application:
\code
#include "PythonQt.h"
#include <QApplication>
...
int main( int argc, char **argv )
{
QApplication qapp(argc, argv);
// init PythonQt and Python itself
PythonQt::init();
// get a smart pointer to the __main__ module of the Python interpreter
PythonQtObjectPtr context = PythonQt::self()->getMainModule();
// add a QObject as variable of name "example" to the namespace of the __main__ module
PyExampleObject example;
context.addObject("example", &example);
// do something
context.evalScript("print example");
context.evalScript("def multiply(a,b):\n return a*b;\n");
QVariantList args;
args << 42 << 47;
QVariant result = context.call("multiply", args);
...
\endcode
*/

View File

@ -0,0 +1,81 @@
#ifndef _PYTHONQTIMPORTFILEINTERFACE_H
#define _PYTHONQTIMPORTFILEINTERFACE_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtImportFileInterface.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-05
*/
//----------------------------------------------------------------------------------
#include <QDateTime>
#include <QString>
#include <QByteArray>
//! Defines an abstract interface to file access for the Python import statement.
//! see PythonQt::setImporter()
class PythonQtImportFileInterface {
public:
// get rid of warnings
virtual ~PythonQtImportFileInterface() {}
//! read the given file as byte array, without doing any linefeed translations
virtual QByteArray readFileAsBytes(const QString& filename) = 0;
//! read a source file, expects a readable Python text file with translated line feeds.
//! If the file can not be load OR it can not be verified, ok is set to false
virtual QByteArray readSourceFile(const QString& filename, bool& ok) = 0;
//! returns if the file exists
virtual bool exists(const QString& filename) = 0;
//! get the last modified data of a file
virtual QDateTime lastModifiedDate(const QString& filename) = 0;
//! indicates that *.py files which are newer than their corresponding *.pyc files
//! are ignored
virtual bool ignoreUpdatedPythonSourceFiles() { return false; }
//! called by PythonQt after successful import to allow
//! recording of imports
virtual void importedModule(const QString& /*module*/) {};
};
#endif

146
PythonQt/PythonQtImporter.h Normal file
View File

@ -0,0 +1,146 @@
#ifndef _PYTHONQTIMPORTER_
#define _PYTHONQTIMPORTER_
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtImporter.h
// \author Florian Link
// \author Last changed by $Author: stk $
// \date 2004-06
*/
//----------------------------------------------------------------------------------
#include "PythonQtPythonInclude.h"
#include "structmember.h"
#include "osdefs.h"
#include "marshal.h"
#include "compile.h"
#include <time.h>
#include <qobject.h>
#include <qstring.h>
//! defines a python object that stores a Qt slot info
typedef struct _PythonQtImporter {
PyObject_HEAD
QString* _path;
} PythonQtImporter;
//! implements importing of python files into PythonQt
/*! also compiles/marshalls/unmarshalls py/pyc files and handles time stamps correctly
*/
class PythonQtImport
{
public:
enum ModuleType {
MI_NOT_FOUND,
MI_MODULE,
MI_PACKAGE,
MI_SHAREDLIBRARY
};
struct ModuleInfo {
ModuleInfo() {
type = MI_NOT_FOUND;
}
QString fullPath; //!< the full path to the found file
QString moduleName; //!< the module name without the package prefix
ModuleType type;
};
//! initialize
static void init();
//! writes the python code to disk, marshalling and writing the time stamp
static void writeCompiledModule(PyCodeObject *co, const QString& filename, long mtime, long sourceSize);
/*! Given the contents of a .py[co] file in a buffer, unmarshal the data
and return the code object. Return None if it the magic word doesn't
match (we do this instead of raising an exception as we fall back
to .py if available and we don't want to mask other errors).
Returns a new reference. */
static PyObject *unmarshalCode(const QString& path, const QByteArray& data, time_t mtime);
//! Given a string buffer containing Python source code, compile it
//! return and return a code object as a new reference.
static PyObject *compileSource(const QString& path, const QByteArray& data);
//! Return the code object for the module named by 'fullname' from the
//! Zip archive as a new reference.
static PyObject *getCodeFromData(const QString& path, int isbytecode = 0, int ispackage = 0,
time_t mtime = 0);
//! Get the code object associated with the module specified by
//! 'fullname'. In Python3, modpath will always be the path to the *.py file and cachemodpath the path
//! to the *.pyc file (if it exists).
static PyObject * getModuleCode(PythonQtImporter *self,
const char* fullname, QString& modpath, QString& cachemodpath);
//! gets the compiled code for the given *.py file if there is a valid pyc file, otherwise compiles the file and writes the pyc
static PyObject* getCodeFromPyc(const QString& file);
//! Return if module exists and is a package or a module
static ModuleInfo getModuleInfo(PythonQtImporter* self, const QString& fullname);
//! get the last name of a dot chain (first.second.last)
static QString getSubName(const QString& str);
//! Given a buffer, return the long that is represented by the first
//! 4 bytes, encoded as little endian. This partially reimplements
//! marshal.c:r_long()
static long getLong(unsigned char *buf);
//! get time stamp of file
static time_t getMTimeOfSource(const QString& path);
//! replace extension of file
static QString replaceExtension(const QString& str, const QString& ext);
//! Returns the filename of the cache file for the given source file, e.g. test.pyc for test.py.
//! Python 3 places cache files inside a __pycache__ directory, this also handled here.
static QString getCacheFilename(const QString& sourceFile, bool isOptimizedFilename);
//! Returns the filename of the source file for the given cache file, e.g. test.py for test.pyc.
//! Python 3 places cache files inside a __pycache__ directory, this also handled here.
static QString getSourceFilename(const QString& cacheFile);
};
#endif

View File

@ -0,0 +1,136 @@
#ifndef _PYTHONQTINSTANCEWRAPPER_H
#define _PYTHONQTINSTANCEWRAPPER_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtInstanceWrapper.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-05
*/
//----------------------------------------------------------------------------------
#include "PythonQtPythonInclude.h"
#include "PythonQtSystem.h"
#include "PythonQtClassWrapper.h"
#include <QPointer>
#include "structmember.h"
#include "methodobject.h"
#include "compile.h"
#include "eval.h"
class PythonQtClassInfo;
class QObject;
extern PYTHONQT_EXPORT PyTypeObject PythonQtInstanceWrapper_Type;
//---------------------------------------------------------------
//! a Python wrapper object for Qt objects and C++ objects (that are themselves wrapped by wrapper QObjects)
typedef struct PythonQtInstanceWrapperStruct {
PyObject_HEAD
//! the class information, this is set even if the _obj or _wrappedPtr is NULL to support typed NULL pointers
inline PythonQtClassInfo* classInfo()
{ return ((PythonQtClassWrapper*)Py_TYPE(this))->_classInfo; }
inline PythonQtDynamicClassInfo* dynamicClassInfo()
{ return ((PythonQtClassWrapper*)Py_TYPE(this))->_dynamicClassInfo; }
//! set the QObject pointer
void setQObject(QObject* object) {
_obj = object;
_objPointerCopy = object;
}
//! Passes the ownership of the wrapped object to C++
void passOwnershipToCPP() {
// we pass the ownership to C++
_ownedByPythonQt = false;
// handle shell instance
if (_isShellInstance) {
if (!_shellInstanceRefCountsWrapper) {
// ref count the wrapper, so that the Python part of the shell instance can not go
// away until the C++ object gets deleted...
Py_INCREF((PyObject*)this);
_shellInstanceRefCountsWrapper = true;
}
}
}
//! Passes the ownership to Python
void passOwnershipToPython() {
_ownedByPythonQt = true;
// if the shell instance was owned by C++ and the ownership goes to Python,
// we need to remove the extra ref count that kept the Python part alive from the C++ side.
if (_shellInstanceRefCountsWrapper) {
Py_DECREF((PyObject*)this);
_shellInstanceRefCountsWrapper = false;
}
}
//! pointer to the wrapped Qt object or if _wrappedPtr is set, the Qt object that wraps the C++ Ptr
QPointer<QObject> _obj;
//! a copy of the _obj pointer, which is required because the wrapper needs to
//! deregister itself via the _obj pointer, even when the QPointer<QObject> object was destroyed
void* _objPointerCopy;
//! optional C++ object Ptr that is wrapped by the above _obj
void* _wrappedPtr;
// TODO xxx: put booleans into int that holds flags
//! flag that stores if the object is owned by pythonQt
bool _ownedByPythonQt;
//! stores that the owned object should be destroyed using QMetaType::destroy()
bool _useQMetaTypeDestroy;
//! stores if the object is a shell instance
bool _isShellInstance;
//! stores if the shell instance (C++) owns the wrapper with its ref count
bool _shellInstanceRefCountsWrapper;
} PythonQtInstanceWrapper;
int PythonQtInstanceWrapper_init(PythonQtInstanceWrapper * self, PyObject * args, PyObject * kwds);
PyObject *PythonQtInstanceWrapper_delete(PythonQtInstanceWrapper * self);
#endif

View File

@ -0,0 +1,227 @@
#ifndef _PYTHONQTMETHODINFO_H
#define _PYTHONQTMETHODINFO_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtMethodInfo.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-05
*/
//----------------------------------------------------------------------------------
#include "PythonQtSystem.h"
#include <QByteArray>
#include <QHash>
#include <QList>
#include <QMetaMethod>
class PythonQtClassInfo;
struct _object;
typedef struct _object PyObject;
//! stores information about a specific signal/slot/method
class PYTHONQT_EXPORT PythonQtMethodInfo
{
public:
enum ParameterType {
Unknown = -1,
Variant = -2
};
//! stores various informations about a parameter/type name
struct ParameterInfo {
QByteArray name;
QByteArray innerName; // if the type is a template, this stores the inner name
PyObject* enumWrapper; // if it is an enum, a pointer to the enum wrapper
int typeId; // a mixture from QMetaType and ParameterType
char pointerCount; // the number of pointer indirections
char innerNamePointerCount; // the number of pointer indirections in the inner name
bool isConst;
bool isReference;
bool isQList;
bool passOwnershipToCPP;
bool passOwnershipToPython;
bool newOwnerOfThis;
};
PythonQtMethodInfo() {};
~PythonQtMethodInfo() {};
PythonQtMethodInfo(const QMetaMethod& meta, PythonQtClassInfo* classInfo);
PythonQtMethodInfo(const QByteArray& typeName, const QList<QByteArray>& args);
PythonQtMethodInfo(const PythonQtMethodInfo& other) {
_parameters = other._parameters;
}
//! returns the method info of the signature, uses a cache internally to speed up
//! multiple requests for the same method, classInfo is passed to allow local enum resolution (if NULL is passed, no local enums are recognized)
static const PythonQtMethodInfo* getCachedMethodInfo(const QMetaMethod& method, PythonQtClassInfo* classInfo);
//! get the cached method info using the passed in list of return value and arguments, return value needs to be passed as first arg
static const PythonQtMethodInfo* getCachedMethodInfoFromArgumentList(int numArgs, const char** args);
//! cleanup the cache
static void cleanupCachedMethodInfos();
//! returns the number of parameters including the return value
int parameterCount() const { return _parameters.size(); };
//! returns the id for the given type (using an internal dictionary)
static int nameToType(const char* name);
//! get the parameter infos
const QList<ParameterInfo>& parameters() const { return _parameters; }
//! add an alias for a typename, e.g. QObjectList and QList<QObject*>.
static void addParameterTypeAlias(const QByteArray& alias, const QByteArray& name);
//! fill the parameter info for the given type name
static void fillParameterInfo(ParameterInfo& type, const QByteArray& name, PythonQtClassInfo* classInfo = NULL);
//! returns a parameter info for the given metatype (and creates and caches one if it is not yet present)
static const ParameterInfo& getParameterInfoForMetaType(int type);
//! returns the inner type id of a simple template of the form SomeObject<InnerType>
static int getInnerTemplateMetaType(const QByteArray& typeName);
//! returns the inner type name of a simple template of the form SomeObject<InnerType>
static QByteArray getInnerTemplateTypeName(const QByteArray& typeName);
//! returns the inner type name of a simple template or the typename without appended "List".
static QByteArray getInnerListTypeName(const QByteArray& typeName);
protected:
static QHash<QByteArray, int> _parameterTypeDict;
static QHash<QByteArray, QByteArray> _parameterNameAliases;
//! stores the cached signatures of methods to speedup mapping from Qt to Python types
static QHash<QByteArray, PythonQtMethodInfo*> _cachedSignatures;
static QHash<int, ParameterInfo> _cachedParameterInfos;
QList<ParameterInfo> _parameters;
};
//! stores information about a slot, including a next pointer to overloaded slots
class PYTHONQT_EXPORT PythonQtSlotInfo : public PythonQtMethodInfo
{
public:
enum Type {
MemberSlot, InstanceDecorator, ClassDecorator
};
PythonQtSlotInfo(const PythonQtSlotInfo& info):PythonQtMethodInfo() {
_meta = info._meta;
_parameters = info._parameters;
_slotIndex = info._slotIndex;
_next = NULL;
_decorator = info._decorator;
_type = info._type;
_upcastingOffset = 0;
}
PythonQtSlotInfo(PythonQtClassInfo* classInfo, const QMetaMethod& meta, int slotIndex, QObject* decorator = NULL, Type type = MemberSlot ):PythonQtMethodInfo()
{
const PythonQtMethodInfo* info = getCachedMethodInfo(meta, classInfo);
_meta = meta;
_parameters = info->parameters();
_slotIndex = slotIndex;
_next = NULL;
_decorator = decorator;
_type = type;
_upcastingOffset = 0;
}
public:
//! get the parameter infos for the arguments, without return type and instance decorator.
QList<ParameterInfo> arguments() const;
void deleteOverloadsAndThis();
const QMetaMethod* metaMethod() const { return &_meta; }
void setUpcastingOffset(int upcastingOffset) { _upcastingOffset = upcastingOffset; }
int upcastingOffset() const { return _upcastingOffset; }
//! get the index of the slot (needed for qt_metacall)
int slotIndex() const { return _slotIndex; }
//! get next overloaded slot (which has the same name)
PythonQtSlotInfo* nextInfo() const { return _next; }
//! set the next overloaded slot
void setNextInfo(PythonQtSlotInfo* next) { _next = next; }
//! returns if the slot is a decorator slot
bool isInstanceDecorator() const { return _decorator!=NULL && _type == InstanceDecorator; }
//! returns if the slot is a constructor slot
bool isClassDecorator() const { return _decorator!=NULL && _type == ClassDecorator; }
QObject* decorator() const { return _decorator; }
//! get the full signature including return type
QString fullSignature(bool skipReturnValue = false, int optionalArgsIndex = -1) const;
//! get the Qt signature of the slot
QByteArray signature() const;
//! get the short slot name
QByteArray slotName(bool removeDecorators = false) const;
//! gets a list of all overload signatures. Signatures
//! which only differ because of default values are joined using "[]" to
//! indicate the optional arguments.
QStringList overloads(bool skipReturnValue = false) const;
//! Returns the class name that originally implements this method,
//! regardless where the wrapper is located/implemented.
QByteArray getImplementingClassName() const;
private:
int _slotIndex;
PythonQtSlotInfo* _next;
QObject* _decorator;
Type _type;
QMetaMethod _meta;
int _upcastingOffset;
};
#endif

175
PythonQt/PythonQtMisc.h Normal file
View File

@ -0,0 +1,175 @@
#ifndef _PYTHONQTMISC_H
#define _PYTHONQTMISC_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtMisc.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-05
*/
//----------------------------------------------------------------------------------
#include <QList>
#define PythonQtValueStorage_ADD_VALUE(store, type, value, ptr) \
{ type* item = (type*)store.nextValuePtr(); \
*item = value; \
ptr = (void*)item; \
}
#define PythonQtValueStorage_ADD_VALUE_IF_NEEDED(alreadyAllocatedPtr,store, type, value, ptr) \
{ \
type* item = (type*)(alreadyAllocatedPtr?alreadyAllocatedPtr:store.nextValuePtr()); \
*item = value; \
ptr = (void*)item; \
}
//! stores a position in the PythonQtValueStorage
class PythonQtValueStoragePosition {
public:
PythonQtValueStoragePosition() { chunkIdx = 0; chunkOffset = 0; }
int chunkIdx;
int chunkOffset;
};
//! a helper class that stores basic C++ value types in chunks
template <typename T, int chunkEntries> class PythonQtValueStorage
{
public:
PythonQtValueStorage() {
_chunkIdx = 0;
_chunkOffset = 0;
_currentChunk = new T[chunkEntries];
_chunks.append(_currentChunk);
};
//! clear all memory
void clear() {
T* chunk;
Q_FOREACH(chunk, _chunks) {
delete[]chunk;
}
_chunks.clear();
}
//! get the current position to be restored with setPos
void getPos(PythonQtValueStoragePosition & pos) {
pos.chunkIdx = _chunkIdx;
pos.chunkOffset = _chunkOffset;
}
//! set the current position (without freeing memory, thus caching old entries for reuse)
void setPos(const PythonQtValueStoragePosition& pos) {
_chunkOffset = pos.chunkOffset;
if (_chunkIdx != pos.chunkIdx) {
_chunkIdx = pos.chunkIdx;
_currentChunk = _chunks.at(_chunkIdx);
}
}
//! add one default constructed value and return the pointer to it
T* nextValuePtr() {
if (_chunkOffset>=chunkEntries) {
_chunkIdx++;
if (_chunkIdx >= _chunks.size()) {
T* newChunk = new T[chunkEntries];
_chunks.append(newChunk);
_currentChunk = newChunk;
} else {
_currentChunk = _chunks.at(_chunkIdx);
}
_chunkOffset = 0;
}
T* newEntry = _currentChunk + _chunkOffset;
_chunkOffset++;
return newEntry;
};
protected:
QList<T*> _chunks;
int _chunkIdx;
int _chunkOffset;
T* _currentChunk;
};
//! a helper class that stores basic C++ value types in chunks and clears the unused values on setPos() usage.
template <typename T, int chunkEntries> class PythonQtValueStorageWithCleanup : public PythonQtValueStorage<T, chunkEntries>
{
public:
void setPos(const PythonQtValueStoragePosition& pos) {
if (_chunkIdx > pos.chunkIdx) {
T* firstChunk = _chunks.at(pos.chunkIdx);
// clear region in first chunk
for (int i = pos.chunkOffset; i < chunkEntries; i++) {
firstChunk[i] = T();
}
for (int chunk = pos.chunkIdx + 1; chunk < _chunkIdx; chunk++) {
// clear the full chunks between the first and last chunk
T* fullChunk = _chunks.at(chunk);
for (int i = 0; i < chunkEntries; i++) {
fullChunk[i] = T();
}
}
// clear region in last chunk
T* lastChunk = _chunks.at(_chunkIdx);
for (int i = 0; i < _chunkOffset; i++) {
lastChunk[i] = T();
}
} else if (_chunkIdx == pos.chunkIdx) {
// clear the region in the last chunk only
T* lastChunk = _chunks.at(_chunkIdx);
for (int i = pos.chunkOffset; i<_chunkOffset; i++) {
lastChunk[i] = T();
}
}
PythonQtValueStorage<T, chunkEntries>::setPos(pos);
}
private:
using PythonQtValueStorage<T, chunkEntries>::_chunks;
using PythonQtValueStorage<T, chunkEntries>::_chunkIdx;
using PythonQtValueStorage<T, chunkEntries>::_chunkOffset;
using PythonQtValueStorage<T, chunkEntries>::_currentChunk;
};
#endif

View File

@ -0,0 +1,164 @@
#ifndef PYTHONQTOBJECTPTR_H
#define PYTHONQTOBJECTPTR_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtObjectPtr.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-05
*/
//----------------------------------------------------------------------------------
#include "PythonQtPythonInclude.h"
#include "PythonQtSystem.h"
#include <QVariant>
#include <QVariantList>
#include <QVariantMap>
//! a smart pointer that stores a PyObject pointer and that handles reference
//! counting automatically
class PYTHONQT_EXPORT PythonQtObjectPtr {
public:
PythonQtObjectPtr() : _object(nullptr) {}
PythonQtObjectPtr(const PythonQtObjectPtr &p) : _object(nullptr) {
setObject(p.object());
}
//! If the given variant holds a PythonQtObjectPtr, extract the value from it
//! and hold onto the reference. This results in an increment of the reference
//! count.
PythonQtObjectPtr(const QVariant &variant) : _object(nullptr) {
fromVariant(variant);
}
PythonQtObjectPtr(PyObject *o);
~PythonQtObjectPtr();
//! If the given variant holds a PythonQtObjectPtr, extract the value from it
//! and hold onto the reference. This results in an increment of the reference
//! count.
bool fromVariant(const QVariant &variant);
PythonQtObjectPtr &operator=(const PythonQtObjectPtr &p) {
setObject(p.object());
return *this;
}
PythonQtObjectPtr &operator=(PyObject *o) {
setObject(o);
return *this;
}
PythonQtObjectPtr &operator=(const QVariant &variant) {
fromVariant(variant);
return *this;
}
bool operator==(const PythonQtObjectPtr &p) const {
return object() == p.object();
}
bool operator!=(const PythonQtObjectPtr &p) const { return !(*this == p); }
bool operator==(PyObject *p) const { return object() == p; }
bool operator!=(PyObject *p) const { return object() != p; }
bool isNull() const { return !object(); }
PyObject *operator->() const { return object(); }
PyObject &operator*() const { return *(object()); }
operator PyObject *() const { return object(); }
//! sets the object and passes the ownership (stealing the reference, in
//! Python slang)
void setNewRef(PyObject *o);
PyObject *object() const { return _object; }
//! evaluates the given script code in the context of this object and returns
//! the result value
QVariant evalScript(const QString &script, int start = Py_file_input);
//! evaluates the given code and returns the result value (use Py_Compile etc.
//! to create pycode from string) If pycode is NULL, a python error is
//! printed.
QVariant evalCode(PyObject *pycode);
//! evaluates the given code in the context
void evalFile(const QString &filename);
//! add the given \c object to the \c module as a variable with \c name (it
//! can be removed via clearVariable)
void addObject(const QString &name, QObject *object);
//! add the given variable to the module
void addVariable(const QString &name, const QVariant &v);
//! remove the given variable
void removeVariable(const QString &name);
//! get the variable with the \c name of the \c module, returns an invalid
//! QVariant on error
QVariant getVariable(const QString &name);
//! call the given python object (in the scope of the current object), returns
//! the result converted to a QVariant
QVariant call(const QString &callable,
const QVariantList &args = QVariantList(),
const QVariantMap &kwargs = QVariantMap());
//! call the contained python object directly, returns the result converted to
//! a QVariant
QVariant call(const QVariantList &args = QVariantList(),
const QVariantMap &kwargs = QVariantMap());
protected:
void setObject(PyObject *o);
private:
PyObject *_object;
};
// register it to the meta type system
Q_DECLARE_METATYPE(PythonQtObjectPtr)
#endif

View File

@ -0,0 +1,94 @@
#pragma once
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
#include "PythonQtSystem.h"
#include "PythonQtPythonInclude.h"
#include <QByteArray>
#include <QList>
#include <structmember.h>
extern PYTHONQT_EXPORT PyTypeObject PythonQtProperty_Type;
#define PythonQtProperty_Check(op) (Py_TYPE(op) == &PythonQtProperty_Type)
struct PythonQtPropertyData
{
PythonQtPropertyData() {
fget = NULL;
fset = NULL;
fdel = NULL;
freset = NULL;
notify = NULL;
doc = NULL;
designable = true;
scriptable = true;
stored = true;
user = false;
constant = false;
final = false;
}
//! Call the fset method in Python, bound to the wrapper object.
//! Returns true if successful
bool callSetter(PyObject* wrapper, PyObject* newValue);
//! Call the fget method in Python, bound to the wrapper object.
//! Returns the return value of the call (with a new ref).
PyObject* callGetter(PyObject* wrapper);
//! Call the freset method in Python, bound to the wrapper object.
bool callReset(PyObject* wrapper);
QByteArray cppType;
PyObject* fget;
PyObject* fset;
PyObject* fdel;
PyObject* freset;
PyObject* notify;
PyObject* doc;
bool designable;
bool scriptable;
bool stored;
bool user;
bool constant;
bool final;
};
typedef struct {
PyObject_HEAD
PythonQtPropertyData* data;
} PythonQtProperty;

View File

@ -0,0 +1,93 @@
/*
*
* Copyright (C) 2011 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
#ifndef __PythonQtPythonInclude_h
#define __PythonQtPythonInclude_h
// Undefine macros that Python.h defines to avoid redefinition warning.
#undef _POSIX_C_SOURCE
#undef _POSIX_THREADS
#undef _XOPEN_SOURCE
// Undefine Qt keywords that conflict with Python headers
#ifdef slots
#undef slots
#define PYTHONQT_RESTORE_KEYWORDS
#endif
// If PYTHONQT_USE_RELEASE_PYTHON_FALLBACK is enabled, try to link
// release Python DLL if it is available by undefining _DEBUG while
// including Python.h
#if defined(PYTHONQT_USE_RELEASE_PYTHON_FALLBACK) && defined(_DEBUG)
#undef _DEBUG
#if defined(_MSC_VER) && _MSC_VER >= 1400
#define _CRT_NOFORCE_MANIFEST 1
#define _STL_NOFORCE_MANIFEST 1
#endif
#include <Python.h>
#define _DEBUG
#else
#include <Python.h>
#endif
// get Qt keywords back
#ifdef PYTHONQT_RESTORE_KEYWORDS
#define slots Q_SLOTS
#undef PYTHONQT_RESTORE_KEYWORDS
#endif
#if PY_MAJOR_VERSION >= 3
#define PY3K
// Helper defines to facilitate porting
#define PyString_FromString PyUnicode_FromString
#define PyString_AS_STRING PyUnicode_AsUTF8
#define PyString_AsString PyUnicode_AsUTF8
#define PyString_FromFormat PyUnicode_FromFormat
#define PyString_Check PyUnicode_Check
#define PyInt_Type PyLong_Type
#define PyInt_FromLong PyLong_FromLong
#define PyInt_AS_LONG PyLong_AS_LONG
#define PyInt_Check PyLong_Check
#define PyInt_AsLong PyLong_AsLong
#else
// Defines to use Python 3 names in Python 2 code
#define PyBytes_Type PyString_Type
#define PyBytes_Check PyString_Check
#define PyBytes_AS_STRING PyString_AS_STRING
#define PyBytes_AsString PyString_AsString
#define PyBytes_GET_SIZE PyString_GET_SIZE
#define PyBytes_FromStringAndSize PyString_FromStringAndSize
#endif
#endif

View File

@ -0,0 +1,63 @@
#ifndef _PYTHONQTQFILEIMPORTER_H
#define _PYTHONQTQFILEIMPORTER_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtQFileImporter.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2009-03
*/
//----------------------------------------------------------------------------------
#include <PythonQtImportFileInterface.h>
//! default importer implementation using QFile to load python code
class PythonQtQFileImporter : public PythonQtImportFileInterface {
public:
PythonQtQFileImporter();
~PythonQtQFileImporter();
QByteArray readFileAsBytes (const QString &filename);
QByteArray readSourceFile (const QString &filename, bool &ok);
bool exists (const QString &filename);
QDateTime lastModifiedDate (const QString &filename);
};
#endif

75
PythonQt/PythonQtSignal.h Normal file
View File

@ -0,0 +1,75 @@
#ifndef _PythonQtSignal_H
#define _PythonQtSignal_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtSignal.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-05
*/
//----------------------------------------------------------------------------------
#include "PythonQtPythonInclude.h"
#include "PythonQtSystem.h"
#include "structmember.h"
class PythonQtSlotInfo;
extern PYTHONQT_EXPORT PyTypeObject PythonQtSignalFunction_Type;
#define PythonQtSignalFunction_Check(op) (Py_TYPE(op) == &PythonQtSignalFunction_Type)
PyObject* PythonQtSignalFunction_New(PythonQtSlotInfo *, PyObject *,
PyObject *);
struct PythonQtDynamicSignalInfo
{
QByteArray name;
QList<QByteArray> signatures;
};
//! defines a python object that stores a Qt signal info
typedef struct {
PyObject_HEAD
PythonQtSlotInfo *m_ml; /* Description of the C function to call */
PyObject *m_self; /* Passed as 'self' arg to the C func, can be NULL */
PyObject *m_module; /* The __module__ attribute, can be anything */
PythonQtDynamicSignalInfo* _dynamicInfo;
} PythonQtSignalFunctionObject;
#endif

View File

@ -0,0 +1,144 @@
#ifndef _PYTHONQTSIGNALRECEIVER_H
#define _PYTHONQTSIGNALRECEIVER_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtSignalReceiver.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-05
*/
//----------------------------------------------------------------------------------
#include "PythonQtPythonInclude.h"
#include "PythonQtSystem.h"
#include "PythonQtObjectPtr.h"
class PythonQtMethodInfo;
class PythonQtClassInfo;
//! stores information about a signal target
/*! copy construction and assignment works fine with the C++ standard behavior and are thus not implemented
*/
class PYTHONQT_EXPORT PythonQtSignalTarget {
public:
PythonQtSignalTarget() {
_signalId = -1;
_methodInfo = NULL;
_slotId = -1;
}
PythonQtSignalTarget(int signalId,const PythonQtMethodInfo* methodInfo, int slotId, PyObject* callable)
{
_signalId = signalId;
_slotId = slotId;
_methodInfo = methodInfo;
_callable = callable;
};
~PythonQtSignalTarget() {
};
//! get the id of the original signal
int signalId() const { return _signalId; }
//! get the id that was assigned to this simulated slot
int slotId() const { return _slotId; }
//! get the signals parameter info
const PythonQtMethodInfo* methodInfo() const { return _methodInfo; }
//! call the python callable with the given arguments (as defined in methodInfo)
void call(void **arguments) const;
//! check if it is the same signal target
bool isSame(int signalId, PyObject* callable) const;
//! call the given callable with arguments described by PythonQtMethodInfo, returns a new reference as result value (or NULL)
static PyObject* call(PyObject* callable, const PythonQtMethodInfo* methodInfo, void **arguments, bool skipFirstArgumentOfMethodInfo = false);
private:
int _signalId;
int _slotId;
const PythonQtMethodInfo* _methodInfo;
PythonQtObjectPtr _callable;
};
//! base class for signal receivers
/*!
*/
class PythonQtSignalReceiverBase : public QObject {
Q_OBJECT
public:
PythonQtSignalReceiverBase(QObject* obj):QObject(obj) {};
};
//! receives all signals for one QObject
/*! we derive from our base but do not declare the QObject macro because we want to reimplement qt_metacall only.
*/
class PythonQtSignalReceiver : public PythonQtSignalReceiverBase {
public:
PythonQtSignalReceiver(QObject* obj);
~PythonQtSignalReceiver();
//! add a signal handler
bool addSignalHandler(const char* signal, PyObject* callable);
//! remove a signal handler for given callable (or all callables on that signal if callable is NULL)
bool removeSignalHandler(const char* signal, PyObject* callable = NULL);
//! we implement this method to simulate a number of slots that match the ids in _targets
virtual int qt_metacall(QMetaObject::Call c, int id, void **arguments);
private:
//! get the index of the signal
int getSignalIndex(const char* signal);
QObject* _obj;
PythonQtClassInfo* _objClassInfo;
int _slotCount;
int _destroyedSignalCount;
// linear list may get slow on multiple targets, but I think typically we have many objects and just a few signals
QList<PythonQtSignalTarget> _targets;
static int _destroyedSignal1Id;
static int _destroyedSignal2Id;
};
#endif

92
PythonQt/PythonQtSlot.h Normal file
View File

@ -0,0 +1,92 @@
#ifndef _PYTHONQTSLOT_H
#define _PYTHONQTSLOT_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtSlot.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-05
*/
//----------------------------------------------------------------------------------
#include "PythonQtPythonInclude.h"
#include "PythonQtSystem.h"
#include "structmember.h"
class PythonQtSlotInfo;
enum PythonQtPassThisOwnershipType
{
IgnoreOwnership,
PassOwnershipToCPP,
PassOwnershipToPython
};
extern PYTHONQT_EXPORT PyTypeObject PythonQtSlotFunction_Type;
#define PythonQtSlotFunction_Check(op) (Py_TYPE(op) == &PythonQtSlotFunction_Type)
PythonQtSlotInfo* PythonQtSlotFunction_GetSlotInfo(PyObject *);
PyObject* PythonQtSlotFunction_GetSelf(PyObject *);
/* Macros for direct access to these values. Type checks are *not*
done, so use with care. */
#define PythonQtSlotFunction_GET_SELF(func) \
(((PythonQtSlotFunctionObject *)func) -> m_self)
PyObject* PythonQtSlotFunction_Call(PyObject *, PyObject *, PyObject *);
PyObject *PythonQtSlotFunction_CallImpl(PythonQtClassInfo* classInfo, QObject* objectToCall, PythonQtSlotInfo* info, PyObject *args, PyObject *kw, void* firstArg=NULL, void** directReturnValuePointer=NULL, PythonQtPassThisOwnershipType* passThisOwnershipToCPP = NULL);
PyObject* PythonQtSlotFunction_New(PythonQtSlotInfo *, PyObject *,
PyObject *);
PyObject *PythonQtMemberFunction_Call(PythonQtSlotInfo* info, PyObject* m_self, PyObject *args, PyObject *kw);
PyObject *PythonQtMemberFunction_parameterTypes(PythonQtSlotInfo* theInfo);
PyObject *PythonQtMemberFunction_parameterNames(PythonQtSlotInfo* theInfo);
PyObject *PythonQtMemberFunction_typeName(PythonQtSlotInfo* theInfo);
//! defines a python object that stores a Qt slot info
typedef struct {
PyObject_HEAD
PythonQtSlotInfo *m_ml; /* Description of the C function to call */
PyObject *m_self; /* Passed as 'self' arg to the C func, can be NULL */
PyObject *m_module; /* The __module__ attribute, can be anything */
} PythonQtSlotFunctionObject;
#endif

View File

@ -0,0 +1,50 @@
#pragma once
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
#include "PythonQtSystem.h"
#include "PythonQtPythonInclude.h"
#include <QByteArray>
#include <QList>
#include <structmember.h>
extern PYTHONQT_EXPORT PyTypeObject PythonQtSlotDecorator_Type;
#define PythonQtSlotDecorator_Check(op) (Py_TYPE(op) == &PythonQtSlotDecorator_Type)
typedef struct {
PyObject_HEAD
QByteArray* args;
QByteArray* returnType;
} PythonQtSlotDecorator;

View File

@ -0,0 +1,282 @@
#ifndef _PYTHONQTSTDDECORATORS_H
#define _PYTHONQTSTDDECORATORS_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtStdDecorators.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2007-04
*/
//----------------------------------------------------------------------------------
#include "PythonQtPythonInclude.h"
#include "PythonQt.h"
#include <QColor>
#include <QDate>
#include <QDateTime>
#include <QImage>
#include <QMetaEnum>
#include <QMetaMethod>
#include <QMetaProperty>
#include <QObject>
#include <QTextDocument>
#include <QTime>
#include <QTimer>
#include <QVariantList>
class PYTHONQT_EXPORT PythonQtStdDecorators : public QObject {
Q_OBJECT
public Q_SLOTS:
bool connect(QObject *sender, const QString &signal, PyObject *callable);
bool connect(QObject *sender, const QString &signal, QObject *receiver,
const QString &slot,
Qt::ConnectionType type = Qt::AutoConnection);
bool connect(QObject *receiver, QObject *sender, const QString &signal,
const QString &slot,
Qt::ConnectionType type = Qt::AutoConnection) {
return connect(sender, signal, receiver, slot, type);
}
bool static_QObject_connect(QObject *sender, const QString &signal,
PyObject *callable) {
return connect(sender, signal, callable);
}
bool static_QObject_connect(QObject *sender, const QString &signal,
QObject *receiver, const QString &slot,
Qt::ConnectionType type = Qt::AutoConnection) {
return connect(sender, signal, receiver, slot, type);
}
bool disconnect(QObject *sender, const QString &signal,
PyObject *callable = NULL);
bool disconnect(QObject *sender, const QString &signal, QObject *receiver,
const QString &slot);
bool static_QObject_disconnect(QObject *sender, const QString &signal,
PyObject *callable = NULL) {
return disconnect(sender, signal, callable);
}
bool static_QObject_disconnect(QObject *sender, const QString &signal,
QObject *receiver, const QString &slot) {
return connect(sender, signal, receiver, slot);
}
const QMetaObject *metaObject(QObject *obj);
QObject *parent(QObject *o);
void setParent(QObject *o, PythonQtNewOwnerOfThis<QObject *> parent);
const QObjectList *children(QObject *o);
QObject *findChild(QObject *parent, PyObject *type,
const QString &name = QString());
QList<QObject *> findChildren(QObject *parent, PyObject *type,
const QString &name = QString());
QList<QObject *> findChildren(QObject *parent, PyObject *type,
const QRegExp &regExp);
bool setProperty(QObject *o, const char *name, const QVariant &value);
QVariant property(QObject *o, const char *name);
double static_Qt_qAbs(double a) { return qAbs(a); }
double static_Qt_qBound(double a, double b, double c) {
return qBound(a, b, c);
}
void static_Qt_qDebug(const QByteArray &msg) {
qDebug("%s", msg.constData());
}
// TODO: multi arg qDebug...
void static_Qt_qWarning(const QByteArray &msg) {
qWarning("%s", msg.constData());
}
// TODO: multi arg qWarning...
void static_Qt_qCritical(const QByteArray &msg) {
qCritical("%s", msg.constData());
}
// TODO: multi arg qCritical...
void static_Qt_qFatal(const QByteArray &msg) {
qFatal("%s", msg.constData());
}
// TODO: multi arg qFatal...
bool static_Qt_qFuzzyCompare(double a, double b) {
return qFuzzyCompare(a, b);
}
double static_Qt_qMax(double a, double b) { return qMax(a, b); }
double static_Qt_qMin(double a, double b) { return qMin(a, b); }
int static_Qt_qRound(double a) { return qRound(a); }
qint64 static_Qt_qRound64(double a) { return qRound64(a); }
const char *static_Qt_qVersion() { return qVersion(); }
int static_Qt_qrand() { return qrand(); }
void static_Qt_qsrand(uint a) { qsrand(a); }
QString tr(QObject *obj, const QString &text,
const QString &ambig = QString(), int n = -1);
QString static_Qt_SIGNAL(const QString &s) { return QString("2") + s; }
QString static_Qt_SLOT(const QString &s) { return QString("1") + s; }
void static_QTimer_singleShot(int msec, PyObject *callable);
private:
QObject *findChild(QObject *parent, const char *typeName,
const QMetaObject *meta, const QString &name);
int findChildren(QObject *parent, const char *typeName,
const QMetaObject *meta, const QString &name,
QList<QObject *> &list);
int findChildren(QObject *parent, const char *typeName,
const QMetaObject *meta, const QRegExp &regExp,
QList<QObject *> &list);
};
class PythonQtSingleShotTimer : public QTimer {
Q_OBJECT
public:
PythonQtSingleShotTimer(int msec, const PythonQtObjectPtr &callable);
public Q_SLOTS:
void slotTimeout();
private:
PythonQtObjectPtr _callable;
};
class PythonQtWrapper_QMetaObject : public QObject {
Q_OBJECT
public Q_SLOTS:
const char *className(QMetaObject *obj) const { return obj->className(); }
const QMetaObject *superClass(QMetaObject *obj) const {
return obj->superClass();
}
int methodOffset(QMetaObject *obj) const { return obj->methodOffset(); }
int enumeratorOffset(QMetaObject *obj) const {
return obj->enumeratorOffset();
}
int propertyOffset(QMetaObject *obj) const { return obj->propertyOffset(); }
int classInfoOffset(QMetaObject *obj) const { return obj->classInfoOffset(); }
int constructorCount(QMetaObject *obj) const {
return obj->constructorCount();
}
int methodCount(QMetaObject *obj) const { return obj->methodCount(); }
int enumeratorCount(QMetaObject *obj) const { return obj->enumeratorCount(); }
int propertyCount(QMetaObject *obj) const { return obj->propertyCount(); }
int classInfoCount(QMetaObject *obj) const { return obj->classInfoCount(); }
int indexOfConstructor(QMetaObject *obj, const char *constructor) const {
return obj->indexOfConstructor(constructor);
}
int indexOfMethod(QMetaObject *obj, const char *method) const {
return obj->indexOfMethod(method);
}
int indexOfSignal(QMetaObject *obj, const char *signal) const {
return obj->indexOfSignal(signal);
}
int indexOfSlot(QMetaObject *obj, const char *slot) const {
return obj->indexOfSlot(slot);
}
int indexOfEnumerator(QMetaObject *obj, const char *name) const {
return obj->indexOfEnumerator(name);
}
int indexOfProperty(QMetaObject *obj, const char *name) const {
return obj->indexOfProperty(name);
}
int indexOfClassInfo(QMetaObject *obj, const char *name) const {
return obj->indexOfClassInfo(name);
}
QMetaMethod constructor(QMetaObject *obj, int index) const {
return obj->constructor(index);
}
QMetaMethod method(QMetaObject *obj, int index) const {
return obj->method(index);
}
QMetaEnum enumerator(QMetaObject *obj, int index) const {
return obj->enumerator(index);
}
QMetaProperty property(QMetaObject *obj, int index) const {
return obj->property(index);
}
QMetaClassInfo classInfo(QMetaObject *obj, int index) const {
return obj->classInfo(index);
}
QMetaProperty userProperty(QMetaObject *obj) const {
return obj->userProperty();
}
bool static_QMetaObject_checkConnectArgs(const char *signal,
const char *method) {
return QMetaObject::checkConnectArgs(signal, method);
}
QByteArray static_QMetaObject_normalizedSignature(const char *method) {
return QMetaObject::normalizedSignature(method);
}
QByteArray static_QMetaObject_normalizedType(const char *type) {
return QMetaObject::normalizedType(type);
}
};
//! Some helper methods that allow testing of the ownership
class PYTHONQT_EXPORT PythonQtDebugAPI : public QObject {
Q_OBJECT
public:
PythonQtDebugAPI(QObject *parent) : QObject(parent){};
public slots:
//! Returns if the C++ object is owned by PythonQt and will be deleted when
//! the reference goes away.
bool isOwnedByPython(PyObject *object);
//! Returns if the C++ object is an instance of a Python class that derives a
//! C++ class.
bool isDerivedShellInstance(PyObject *object);
//! Returns if the shell instance has an extra ref count from the C++ side.
bool hasExtraShellRefCount(PyObject *object);
//! Pass the ownership of the given object to CPP (so that it will not be
//! deleted by Python if the reference goes away)
bool passOwnershipToCPP(PyObject *object);
//! Pass the ownership of the given object to Python (so that the C++ object
//! will be deleted when the Python reference goes away)
bool passOwnershipToPython(PyObject *object);
//! Returns if the given object is a PythonQt instance wrapper (or derived
//! class)
bool isPythonQtInstanceWrapper(PyObject *object);
//! Returns if the given object is a PythonQt class wrapper (or derived class)
bool isPythonQtClassWrapper(PyObject *object);
};
#endif

63
PythonQt/PythonQtStdIn.h Normal file
View File

@ -0,0 +1,63 @@
#ifndef _PYTHONQTSTDIN_H
#define _PYTHONQTSTDIN_H
/*
*
* Copyright (C) 2011 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtStdIn.h
// \author Jean-Christophe Fillion-Robin
// \author Last changed by $Author: jcfr $
// \date 2011
*/
//----------------------------------------------------------------------------------
#include "PythonQtPythonInclude.h"
#include "structmember.h"
#include <QString>
//! declares the type of the stdout redirection class
extern PyTypeObject PythonQtStdInRedirectType;
//! declares the callback that is called from the write() function
typedef QString PythonQtInputChangedCB(void* callData);
//! declares the stdin redirection class
typedef struct {
PyObject_HEAD
PythonQtInputChangedCB* _cb;
void * _callData;
} PythonQtStdInRedirect;
#endif

65
PythonQt/PythonQtStdOut.h Normal file
View File

@ -0,0 +1,65 @@
#ifndef _PYTHONQTSTDOUT_H
#define _PYTHONQTSTDOUT_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtStdOut.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-05
*/
//----------------------------------------------------------------------------------
#include "PythonQtPythonInclude.h"
#include "structmember.h"
#include <QString>
//! declares the type of the stdout redirection class
extern PyTypeObject PythonQtStdOutRedirectType;
//! declares the callback that is called from the write() function
typedef void PythonQtOutputChangedCB(const QString& str);
//! declares the stdout redirection class
typedef struct {
PyObject_HEAD
PythonQtOutputChangedCB* _cb;
int softspace;
bool closed;
} PythonQtStdOutRedirect;
#endif

56
PythonQt/PythonQtSystem.h Normal file
View File

@ -0,0 +1,56 @@
#ifndef _PYTHONQTSYSTEM_
#define _PYTHONQTSYSTEM_
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtSystem.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-05
*/
//----------------------------------------------------------------------------------
#ifdef WIN32
#ifdef PYTHONQT_EXPORTS
#define PYTHONQT_EXPORT __declspec(dllexport)
#else
#define PYTHONQT_EXPORT __declspec(dllimport)
#endif
#else
#define PYTHONQT_EXPORT
#endif
#endif

97
PythonQt/PythonQtUtils.h Normal file
View File

@ -0,0 +1,97 @@
#ifndef _PYTHONQTUTILS_H
#define _PYTHONQTUTILS_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtUtils.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2014-09
*/
//----------------------------------------------------------------------------------
#include "PythonQtPythonInclude.h"
#include "PythonQtSystem.h"
#include <QByteArray>
#include <QMetaMethod>
namespace PythonQtUtils
{
inline QByteArray signature(const QMetaMethod& method) {
#if( QT_VERSION >= QT_VERSION_CHECK(5,0,0) )
return method.methodSignature();
#else
return QByteArray(method.signature());
#endif
}
inline QByteArray methodName(const QMetaMethod& method) {
#if( QT_VERSION >= QT_VERSION_CHECK(5,0,0) )
return method.name();
#else
QByteArray sig(method.signature());
int idx = sig.indexOf('(');
sig = sig.left(idx);
return sig;
#endif
}
inline QByteArray typeName(const QMetaMethod& method) {
#if( QT_VERSION >= QT_VERSION_CHECK(5,0,0) )
QByteArray result = method.typeName();
if (result == "void") {
return QByteArray();
} else {
return result;
}
#else
return method.typeName();
#endif
}
//! Returns of the python object is a class type
inline bool isPythonClassType(PyObject* obj) {
#ifdef PY3K
return PyType_Check(obj);
#else
// support old-style classes and new style classes
return (obj->ob_type == &PyClass_Type || obj->ob_type == &PyType_Type);
#endif
}
}
#endif

View File

@ -0,0 +1,78 @@
#ifndef _PYTHONQTVARIANTS_
#define _PYTHONQTVARIANTS_
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtVariants.h
// \author Florian Link
// \author Last changed by $Author: stk $
// \date 2006-08
*/
//----------------------------------------------------------------------------------
#include <QBitArray>
#include <QDate>
#include <QTime>
#include <QDateTime>
#include <QUrl>
#include <QLocale>
#include <QRect>
#include <QRectF>
#include <QLine>
#include <QLineF>
#include <QPoint>
#include <QPointF>
#include <QRegExp>
#include <QFont>
#include <QBitmap>
#include <QBrush>
#include <QColor>
#include <QPalette>
#include <QIcon>
#include <QImage>
#include <QPolygon>
#include <QRegion>
#include <QBitmap>
#include <QCursor>
#include <QSizePolicy>
#include <QKeySequence>
#include <QPen>
#include <QTextLength>
#include <QTextFormat>
#include <QMatrix>
#endif

View File

@ -0,0 +1,555 @@
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtScriptingConsole.cpp
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-10
*/
//----------------------------------------------------------------------------------
#include "PythonQtScriptingConsole.h"
#include <QAbstractItemView>
#include <QApplication>
#include <QCompleter>
#include <QDebug>
#include <QKeyEvent>
#include <QMenu>
#include <QMouseEvent>
#include <QScrollBar>
#include <QStringListModel>
#include <QTextBlock>
#include <QTextCursor>
#include <QTextDocumentFragment>
//-----------------------------------------------------------------------------
PythonQtScriptingConsole::PythonQtScriptingConsole(
QWidget *parent, const PythonQtObjectPtr &context,
Qt::WindowFlags windowFlags)
: QTextEdit(parent) {
setWindowFlags(windowFlags);
_defaultTextCharacterFormat = currentCharFormat();
_context = context;
_historyPosition = 0;
_hadError = false;
_completer = new QCompleter(this);
_completer->setWidget(this);
QObject::connect(_completer, SIGNAL(activated(const QString &)), this,
SLOT(insertCompletion(const QString &)));
clear();
connect(PythonQt::self(), SIGNAL(pythonStdOut(const QString &)), this,
SLOT(stdOut(const QString &)));
connect(PythonQt::self(), SIGNAL(pythonStdErr(const QString &)), this,
SLOT(stdErr(const QString &)));
}
//-----------------------------------------------------------------------------
void PythonQtScriptingConsole::stdOut(const QString &s) {
_stdOut += s;
int idx;
while ((idx = _stdOut.indexOf('\n')) != -1) {
auto msg = _stdOut.left(idx);
consoleMessage(QString("<font color=\"green\">%1</font>")
.arg(msg)); // modified by wingsummer
std::cout << msg.toLatin1().data() << std::endl;
_stdOut = _stdOut.mid(idx + 1);
}
}
void PythonQtScriptingConsole::stdErr(const QString &s) {
_hadError = true;
_stdErr += s;
int idx;
while ((idx = _stdErr.indexOf('\n')) != -1) {
auto msg = _stdErr.left(idx);
consoleMessage(QString("<font color=\"red\">%1</font>")
.arg(msg)); // modified by wingsummer
std::cerr << msg.toLatin1().data() << std::endl;
_stdErr = _stdErr.mid(idx + 1);
}
}
void PythonQtScriptingConsole::flushStdOut() {
if (!_stdOut.isEmpty()) {
stdOut("\n");
}
if (!_stdErr.isEmpty()) {
stdErr("\n");
}
}
//-----------------------------------------------------------------------------
PythonQtScriptingConsole::~PythonQtScriptingConsole() {}
//-----------------------------------------------------------------------------
void PythonQtScriptingConsole::clear() {
QTextEdit::clear();
appendCommandPrompt();
}
//-----------------------------------------------------------------------------
void PythonQtScriptingConsole::executeLine(bool storeOnly) {
QTextCursor textCursor = this->textCursor();
textCursor.movePosition(QTextCursor::End);
// Select the text from the command prompt until the end of the block
// and get the selected text.
textCursor.setPosition(commandPromptPosition());
textCursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
QString code = textCursor.selectedText();
// i don't know where this trailing space is coming from, blast it!
if (code.endsWith(" ")) {
code.truncate(code.length() - 1);
}
if (!code.isEmpty()) {
// Update the history
_history << code;
_historyPosition = _history.count();
_currentMultiLineCode += code + "\n";
if (!storeOnly) {
executeCode(_currentMultiLineCode);
_currentMultiLineCode = "";
}
}
// Insert a new command prompt
appendCommandPrompt(storeOnly);
}
void PythonQtScriptingConsole::executeCode(const QString &code) {
// put visible cursor to the end of the line
QTextCursor cursor = QTextEdit::textCursor();
cursor.movePosition(QTextCursor::End);
setTextCursor(cursor);
// int cursorPosition = this->textCursor().position();
// evaluate the code
_stdOut = "";
_stdErr = "";
PythonQtObjectPtr p;
PyObject *dict = nullptr;
if (PyModule_Check(_context)) {
dict = PyModule_GetDict(_context);
} else if (PyDict_Check(_context)) {
dict = _context;
}
if (dict) {
p.setNewRef(
PyRun_String(code.toLatin1().data(), Py_single_input, dict, dict));
}
if (!p) {
PythonQt::self()->handleError();
}
flushStdOut();
// bool messageInserted = (this->textCursor().position() != cursorPosition);
// If a message was inserted, then put another empty line before the command
// prompt to improve readability.
// if (messageInserted) {
// append(QString());
//}
}
//-----------------------------------------------------------------------------
void PythonQtScriptingConsole::appendCommandPrompt(bool storeOnly) {
if (storeOnly) {
_commandPrompt = "... > ";
} else {
_commandPrompt = "py > ";
}
append(_commandPrompt);
QTextCursor cursor = textCursor();
cursor.movePosition(QTextCursor::End);
setTextCursor(cursor);
}
//-----------------------------------------------------------------------------
void PythonQtScriptingConsole::setCurrentFont(const QColor &color, bool bold) {
QTextCharFormat charFormat(_defaultTextCharacterFormat);
QFont font(charFormat.font());
font.setBold(bold);
charFormat.setFont(font);
QBrush brush(charFormat.foreground());
brush.setColor(color);
charFormat.setForeground(brush);
setCurrentCharFormat(charFormat);
}
//-----------------------------------------------------------------------------
int PythonQtScriptingConsole::commandPromptPosition() {
QTextCursor textCursor(this->textCursor());
textCursor.movePosition(QTextCursor::End);
return textCursor.block().position() + _commandPrompt.length();
}
//-----------------------------------------------------------------------------
void PythonQtScriptingConsole::insertCompletion(const QString &completion) {
QTextCursor tc = textCursor();
tc.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor);
if (tc.selectedText() == ".") {
tc.insertText(QString(".") + completion);
} else {
tc = textCursor();
tc.movePosition(QTextCursor::StartOfWord, QTextCursor::MoveAnchor);
tc.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
tc.insertText(completion);
setTextCursor(tc);
}
}
//-----------------------------------------------------------------------------
void PythonQtScriptingConsole::handleTabCompletion() {
QTextCursor textCursor = this->textCursor();
int pos = textCursor.position();
textCursor.setPosition(commandPromptPosition());
textCursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
int startPos = textCursor.selectionStart();
int offset = pos - startPos;
QString text = textCursor.selectedText();
QString textToComplete;
int cur = offset;
while (cur--) {
QChar c = text.at(cur);
if (c.isLetterOrNumber() || c == '.' || c == '_') {
textToComplete.prepend(c);
} else {
break;
}
}
QString lookup;
QString compareText = textToComplete;
int dot = compareText.lastIndexOf('.');
if (dot != -1) {
lookup = compareText.mid(0, dot);
compareText = compareText.mid(dot + 1, offset);
}
if (!lookup.isEmpty() || !compareText.isEmpty()) {
compareText = compareText.toLower();
QStringList found;
QStringList l =
PythonQt::self()->introspection(_context, lookup, PythonQt::Anything);
Q_FOREACH (QString n, l) {
if (n.toLower().startsWith(compareText)) {
found << n;
}
}
if (!found.isEmpty()) {
_completer->setCompletionPrefix(compareText);
_completer->setCompletionMode(QCompleter::PopupCompletion);
_completer->setModel(new QStringListModel(found, _completer));
_completer->setCaseSensitivity(Qt::CaseInsensitive);
QTextCursor c = this->textCursor();
c.movePosition(QTextCursor::StartOfWord);
QRect cr = cursorRect(c);
cr.setWidth(_completer->popup()->sizeHintForColumn(0) +
_completer->popup()->verticalScrollBar()->sizeHint().width());
cr.translate(0, 8);
_completer->complete(cr);
} else {
_completer->popup()->hide();
}
} else {
_completer->popup()->hide();
}
}
void PythonQtScriptingConsole::keyPressEvent(QKeyEvent *event) {
if (_completer && _completer->popup()->isVisible()) {
// The following keys are forwarded by the completer to the widget
switch (event->key()) {
case Qt::Key_Return:
if (!_completer->popup()->currentIndex().isValid()) {
insertCompletion(_completer->currentCompletion());
_completer->popup()->hide();
event->accept();
}
event->ignore();
return;
break;
case Qt::Key_Enter:
case Qt::Key_Escape:
case Qt::Key_Tab:
case Qt::Key_Backtab:
event->ignore();
return; // let the completer do default behavior
default:
break;
}
}
bool eventHandled = false;
QTextCursor textCursor = this->textCursor();
int key = event->key();
switch (key) {
case Qt::Key_Left:
// Moving the cursor left is limited to the position
// of the command prompt.
if (textCursor.position() <= commandPromptPosition()) {
QApplication::beep();
eventHandled = true;
}
break;
case Qt::Key_Up:
// Display the previous command in the history
if (_historyPosition > 0) {
_historyPosition--;
changeHistory();
}
eventHandled = true;
break;
case Qt::Key_Down:
// Display the next command in the history
if (_historyPosition + 1 < _history.count()) {
_historyPosition++;
changeHistory();
}
eventHandled = true;
break;
case Qt::Key_Return:
executeLine(event->modifiers() & Qt::ShiftModifier);
eventHandled = true;
break;
case Qt::Key_Backspace:
if (textCursor.hasSelection()) {
cut();
eventHandled = true;
} else {
// Intercept backspace key event to check if
// deleting a character is allowed. It is not
// allowed, if the user wants to delete the
// command prompt.
if (textCursor.position() <= commandPromptPosition()) {
QApplication::beep();
eventHandled = true;
}
}
break;
case Qt::Key_Delete:
cut();
eventHandled = true;
break;
default:
if (key >= Qt::Key_Space && key <= Qt::Key_division) {
if (textCursor.hasSelection() && !verifySelectionBeforeDeletion()) {
// The selection must not be deleted.
eventHandled = true;
} else {
// The key is an input character, check if the cursor is
// behind the last command prompt, else inserting the
// character is not allowed.
int commandPromptPosition = this->commandPromptPosition();
if (textCursor.position() < commandPromptPosition) {
textCursor.setPosition(commandPromptPosition);
setTextCursor(textCursor);
}
}
}
}
if (eventHandled) {
_completer->popup()->hide();
event->accept();
} else {
QTextEdit::keyPressEvent(event);
QString text = event->text();
if (!text.isEmpty()) {
handleTabCompletion();
} else {
_completer->popup()->hide();
}
eventHandled = true;
}
}
//-----------------------------------------------------------------------------
void PythonQtScriptingConsole::cut() {
bool deletionAllowed = verifySelectionBeforeDeletion();
if (deletionAllowed) {
QTextEdit::cut();
}
}
//-----------------------------------------------------------------------------
bool PythonQtScriptingConsole::verifySelectionBeforeDeletion() {
bool deletionAllowed = true;
QTextCursor textCursor = this->textCursor();
int commandPromptPosition = this->commandPromptPosition();
int selectionStart = textCursor.selectionStart();
int selectionEnd = textCursor.selectionEnd();
if (textCursor.hasSelection()) {
// Selected text may only be deleted after the last command prompt.
// If the selection is partly after the command prompt set the selection
// to the part and deletion is allowed. If the selection occurs before the
// last command prompt, then deletion is not allowed.
if (selectionStart < commandPromptPosition ||
selectionEnd < commandPromptPosition) {
// Assure selectionEnd is bigger than selection start
if (selectionStart > selectionEnd) {
int tmp = selectionEnd;
selectionEnd = selectionStart;
selectionStart = tmp;
}
if (selectionEnd < commandPromptPosition) {
// Selection is completely before command prompt,
// so deletion is not allowed.
QApplication::beep();
deletionAllowed = false;
} else {
// The selectionEnd is after the command prompt, so set
// the selection start to the commandPromptPosition.
selectionStart = commandPromptPosition;
textCursor.setPosition(selectionStart);
textCursor.setPosition(selectionStart, QTextCursor::KeepAnchor);
setTextCursor(textCursor);
}
}
} else { // if (hasSelectedText())
// When there is no selected text, deletion is not allowed before the
// command prompt.
if (textCursor.position() < commandPromptPosition) {
QApplication::beep();
deletionAllowed = false;
}
}
return deletionAllowed;
}
//-----------------------------------------------------------------------------
void PythonQtScriptingConsole::changeHistory() {
// Select the text after the last command prompt ...
QTextCursor textCursor = this->textCursor();
textCursor.movePosition(QTextCursor::End);
textCursor.setPosition(commandPromptPosition(), QTextCursor::KeepAnchor);
// ... and replace it with the history text.
textCursor.insertText(_history.value(_historyPosition));
textCursor.movePosition(QTextCursor::End);
setTextCursor(textCursor);
}
//-----------------------------------------------------------------------------
void PythonQtScriptingConsole::consoleMessage(const QString &message) {
append(QString());
insertHtml(message); // modified by wingsummer
// Reset all font modifications done by the html string
setCurrentCharFormat(_defaultTextCharacterFormat);
}

View File

@ -0,0 +1,147 @@
#ifndef PythonQtScriptingConsole_H
#define PythonQtScriptingConsole_H
/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQtScriptingConsole.h
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-10
*/
//----------------------------------------------------------------------------------
#include "../PythonQt.h"
#include <QTextEdit>
#include <QVariant>
class QCompleter;
//-------------------------------------------------------------------------------
//! A simple console for python scripting
class PYTHONQT_EXPORT PythonQtScriptingConsole : public QTextEdit {
Q_OBJECT
public:
PythonQtScriptingConsole(QWidget *parent, const PythonQtObjectPtr &context,
Qt::WindowFlags i = Qt::Widget);
~PythonQtScriptingConsole();
public Q_SLOTS:
//! execute current line
void executeLine(bool storeOnly);
//! derived key press event
void keyPressEvent(QKeyEvent *e);
//! output from console
void consoleMessage(const QString &message);
//! get history
QStringList history() { return _history; }
//! set history
void setHistory(const QStringList &h) {
_history = h;
_historyPosition = 0;
}
//! clear the console
void clear();
//! overridden to control which characters a user may delete
virtual void cut();
//! output redirection
void stdOut(const QString &s);
//! output redirection
void stdErr(const QString &s);
void insertCompletion(const QString &);
//! Appends a newline and command prompt at the end of the document.
void appendCommandPrompt(bool storeOnly = false);
public:
//! returns true if python cerr had an error
bool hadError() { return _hadError; }
//! returns true if python cerr had an error
void clearError() { _hadError = false; }
protected:
//! handle the pressing of tab
void handleTabCompletion();
//! Returns the position of the command prompt
int commandPromptPosition();
//! Returns if deletion is allowed at the current cursor
//! (with and without selected text)
bool verifySelectionBeforeDeletion();
//! Sets the current font
void setCurrentFont(const QColor &color = QColor(0, 0, 0), bool bold = false);
//! change the history according to _historyPos
void changeHistory();
//! flush output that was not yet printed
void flushStdOut();
private:
void executeCode(const QString &code);
PythonQtObjectPtr _context;
QStringList _history;
int _historyPosition;
QString _clickedAnchor;
QString _storageKey;
QString _commandPrompt;
QString _currentMultiLineCode;
QString _stdOut;
QString _stdErr;
QTextCharFormat _defaultTextCharacterFormat;
QCompleter *_completer;
bool _hadError;
};
#endif

Binary file not shown.

View File

@ -19,20 +19,27 @@
#include <QTextBlock>
#include <QTextCharFormat>
// PythonQt
#include <QStringListModel>
static QVector<QPair<QString, QString>> parentheses = {
{"(", ")"}, {"{", "}"}, {"[", "]"}, {"\"", "\""}, {"'", "'"}};
QCodeEditor::QCodeEditor(QWidget *widget)
: QTextEdit(widget), m_highlighter(nullptr), m_syntaxStyle(nullptr),
m_lineNumberArea(new QLineNumberArea(this)), m_completer(nullptr),
m_lineNumberArea(new QLineNumberArea(this)),
m_completer(new QCompleter(this)),
m_framedAttribute(new QFramedTextAttribute(this)),
m_autoIndentation(true), m_autoParentheses(true), m_replaceTab(true),
m_tabReplace(QString(4, ' ')) {
initDocumentLayoutHandlers();
initFont();
performConnections();
setSyntaxStyle(QSyntaxStyle::defaultStyle());
py = PythonQt::self();
_context = py->getMainModule();
connect(m_completer, QOverload<const QString &>::of(&QCompleter::activated),
this, &QCodeEditor::insertCompletion);
}
void QCodeEditor::initDocumentLayoutHandlers() {
@ -318,7 +325,16 @@ bool QCodeEditor::proceedCompleterBegin(QKeyEvent *e) {
if (m_completer && m_completer->popup()->isVisible()) {
switch (e->key()) {
case Qt::Key_Enter:
case Qt::Key_Return:
case Qt::Key_Return: { // added by wingsummer
if (!m_completer->popup()->currentIndex().isValid()) {
insertCompletion(m_completer->currentCompletion());
m_completer->popup()->hide();
e->accept();
}
e->ignore();
return true;
break;
}
case Qt::Key_Escape:
case Qt::Key_Tab:
case Qt::Key_Backtab:
@ -356,18 +372,18 @@ void QCodeEditor::proceedCompleterEnd(QKeyEvent *e) {
return;
}
if (completionPrefix != m_completer->completionPrefix()) {
m_completer->setCompletionPrefix(completionPrefix);
m_completer->popup()->setCurrentIndex(
m_completer->completionModel()->index(0, 0));
}
// if (completionPrefix != m_completer->completionPrefix()) {
// m_completer->setCompletionPrefix(completionPrefix);
// m_completer->popup()->setCurrentIndex(
// m_completer->completionModel()->index(0, 0));
// }
auto cursRect = cursorRect();
cursRect.setWidth(
m_completer->popup()->sizeHintForColumn(0) +
m_completer->popup()->verticalScrollBar()->sizeHint().width());
// auto cursRect = cursorRect();
// cursRect.setWidth(
// m_completer->popup()->sizeHintForColumn(0) +
// m_completer->popup()->verticalScrollBar()->sizeHint().width());
m_completer->complete(cursRect);
handleTabCompletion();
}
void QCodeEditor::keyPressEvent(QKeyEvent *e) {
@ -478,6 +494,65 @@ void QCodeEditor::keyPressEvent(QKeyEvent *e) {
proceedCompleterEnd(e);
}
void QCodeEditor::handleTabCompletion() {
QTextCursor textCursor = this->textCursor();
int pos = textCursor.position();
textCursor.movePosition(QTextCursor::StartOfLine);
textCursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
int startPos = textCursor.selectionStart();
int offset = pos - startPos;
QString text = textCursor.selectedText();
QString textToComplete;
int cur = offset;
while (cur--) {
QChar c = text.at(cur);
if (c.isLetterOrNumber() || c == '.' || c == '_') {
textToComplete.prepend(c);
} else {
break;
}
}
QString lookup;
QString compareText = textToComplete;
int dot = compareText.lastIndexOf('.');
if (dot != -1) {
lookup = compareText.mid(0, dot);
compareText = compareText.mid(dot + 1, offset);
}
if (!lookup.isEmpty() || !compareText.isEmpty()) {
compareText = compareText.toLower();
QStringList found;
QStringList l = py->introspection(_context, lookup, PythonQt::Anything);
Q_FOREACH (QString n, l) {
if (n.toLower().startsWith(compareText)) {
found << n;
}
}
if (!found.isEmpty()) {
m_completer->setCompletionPrefix(compareText);
m_completer->setCompletionMode(QCompleter::PopupCompletion);
m_completer->setModel(new QStringListModel(found, m_completer));
m_completer->setCaseSensitivity(Qt::CaseInsensitive);
QTextCursor c = this->textCursor();
c.movePosition(QTextCursor::StartOfWord);
QRect cr = cursorRect(c);
cr.setWidth(
m_completer->popup()->sizeHintForColumn(0) +
m_completer->popup()->verticalScrollBar()->sizeHint().width());
cr.translate(0, 8);
m_completer->complete(cr);
} else {
m_completer->popup()->hide();
}
} else {
m_completer->popup()->hide();
}
}
void QCodeEditor::setAutoIndentation(bool enabled) {
m_autoIndentation = enabled;
}
@ -502,24 +577,6 @@ void QCodeEditor::setTabReplaceSize(int val) {
int QCodeEditor::tabReplaceSize() const { return m_tabReplace.size(); }
void QCodeEditor::setCompleter(QCompleter *completer) {
if (m_completer) {
disconnect(m_completer, nullptr, this, nullptr);
}
m_completer = completer;
if (!m_completer) {
return;
}
m_completer->setWidget(this);
m_completer->setCompletionMode(QCompleter::CompletionMode::PopupCompletion);
connect(m_completer, QOverload<const QString &>::of(&QCompleter::activated),
this, &QCodeEditor::insertCompletion);
}
void QCodeEditor::focusInEvent(QFocusEvent *e) {
if (m_completer) {
m_completer->setWidget(this);
@ -539,8 +596,6 @@ void QCodeEditor::insertCompletion(QString s) {
setTextCursor(tc);
}
QCompleter *QCodeEditor::completer() const { return m_completer; }
QChar QCodeEditor::charUnderCursor(int offset) const {
auto block = textCursor().blockNumber();
auto index = textCursor().positionInBlock();

View File

@ -4,6 +4,8 @@
// Qt
#include <QTextEdit> // Required for inheritance
#include "PythonQt/PythonQt.h"
class QCompleter;
class QLineNumberArea;
class QSyntaxStyle;
@ -94,18 +96,6 @@ public:
*/
bool autoIndentation() const;
/**
* @brief Method for setting completer.
* @param completer Pointer to completer object.
*/
void setCompleter(QCompleter *completer);
/**
* @brief Method for getting completer.
* @return Pointer to completer.
*/
QCompleter *completer() const;
public Q_SLOTS:
/**
@ -224,6 +214,8 @@ private:
bool proceedCompleterBegin(QKeyEvent *e);
void proceedCompleterEnd(QKeyEvent *e);
void handleTabCompletion(); // added by wingsummer from PythonQt
/**
* @brief Method for getting character under
* cursor.
@ -268,6 +260,9 @@ private:
bool m_autoParentheses;
bool m_replaceTab;
QString m_tabReplace;
PythonQt *py;
PythonQtObjectPtr _context;
};
#endif

View File

@ -1,36 +0,0 @@
// QCodeEditor
#include "QPythonCompleter.hpp"
#include "QLanguage.hpp"
// Qt
#include <QFile>
#include <QStringListModel>
QPythonCompleter::QPythonCompleter(QObject *parent) : QCompleter(parent) {
// Setting up Python types
QStringList list;
QFile fl(":/python.xml");
if (!fl.open(QIODevice::ReadOnly)) {
return;
}
QLanguage language(&fl);
if (!language.isLoaded()) {
return;
}
auto keys = language.keys();
for (auto &&key : keys) {
auto names = language.names(key);
list.append(names);
}
setModel(new QStringListModel(list, this));
setCompletionColumn(0);
setModelSorting(QCompleter::CaseInsensitivelySortedModel);
setCaseSensitivity(Qt::CaseSensitive);
setWrapAround(true);
}

View File

@ -1,22 +0,0 @@
#ifndef QPYTHONCOMPLETER_H
#define QPYTHONCOMPLETER_H
// Qt
#include <QCompleter> // Required for inheritance
/**
* @brief Class, that describes completer with
* glsl specific types and functions.
*/
class QPythonCompleter : public QCompleter {
Q_OBJECT
public:
/**
* @brief Constructor.
* @param parent Pointer to parent QObject.
*/
explicit QPythonCompleter(QObject *parent = nullptr);
};
#endif

View File

@ -19,10 +19,120 @@
<name>and</name>
<name>enumerate</name>
</section>
<section name="Namespace">
<name>WingPlgReader</name>
<name>WingPlgCtl</name>
<name>WingPlgService</name>
</section>
<section name="Function">
<name>min</name>
<name>max</name>
<name>len</name>
<name>main</name>
<name>currentDoc</name>
<name>currentDocFilename</name>
<name>isReadOnly</name>
<name>isKeepSize</name>
<name>isLocked</name>
<name>documentLines</name>
<name>documentBytes</name>
<name>currentPos</name>
<name>selectionPos</name>
<name>currentRow</name>
<name>currentColumn</name>
<name>currentOffset</name>
<name>selectlength</name>
<name>stringVisible</name>
<name>addressVisible</name>
<name>headerVisible</name>
<name>addressBase</name>
<name>isModified</name>
<name>isEmpty</name>
<name>atEnd</name>
<name>canUndo</name>
<name>canRedo</name>
<name>copy</name>
<name>read</name>
<name>searchForward</name>
<name>searchBackward</name>
<name>findAllBytes</name>
<name>documentLastLine</name>
<name>documentLastColumn</name>
<name>lineHasMetadata</name>
<name>getMetadatas</name>
<name>getMetaLine</name>
<name>lineHasBookMark</name>
<name>getsBookmarkPos</name>
<name>bookMark</name>
<name>bookMarkComment</name>
<name>getBookMarks</name>
<name>existBookMark</name>
<name>getOpenFiles</name>
<name>getSupportedEncodings</name>
<name>currentEncoding</name>
<name>switchDocument</name>
<name>setKeepSize</name>
<name>setStringVisible</name>
<name>setAddressVisible</name>
<name>setHeaderVisible</name>
<name>setAddressBase</name>
<name>undo</name>
<name>redo</name>
<name>cut</name>
<name>paste</name>
<name>insert</name>
<name>paste</name>
<name>remove</name>
<name>moveTo</name>
<name>select</name>
<name>selectOffset</name>
<name>setInsertionMode</name>
<name>enabledCursor</name>
<name>metadata</name>
<name>removeMetadata</name>
<name>clearMeta</name>
<name>color</name>
<name>foreground</name>
<name>background</name>
<name>comment</name>
<name>applyMetas</name>
<name>setMetaVisible</name>
<name>setMetafgVisible</name>
<name>setMetabgVisible</name>
<name>setMetaCommentVisible</name>
<name>newFile</name>
<name>openFile</name>
<name>openDriver</name>
<name>closeFile</name>
<name>saveFile</name>
<name>exportFile</name>
<name>exportFileGUI</name>
<name>saveasFile</name>
<name>saveasFileGUI</name>
<name>closeCurrentFile</name>
<name>saveCurrentFile</name>
<name>openFileGUI</name>
<name>openDriverGUI</name>
<name>findGUI</name>
<name>gotoGUI</name>
<name>fillGUI</name>
<name>fillzeroGUI</name>
<name>fillnopGUI</name>
<name>addBookMark</name>
<name>modBookMark</name>
<name>applyBookMarks</name>
<name>removeBookMark</name>
<name>clearBookMark</name>
<name>openWorkSpace</name>
<name>setCurrentEncoding</name>
<name>toast</name>
<name>print</name>
<name>errPrint</name>
<name>infoPrint</name>
<name>warnPrint</name>
<name>requestControl</name>
<name>hasControl</name>
<name>requestRelease</name>
</section>
<section name="PrimitiveType">
<name>float</name>
@ -33,6 +143,7 @@
<name>str</name>
<name>unicode</name>
<name>byte</name>
<name>bytearray</name>
<name>set</name>
<name>dict</name>
</section>

View File

@ -6,9 +6,8 @@
</p>
<p align="center">
<img alt="作者" src="authorband.svg">
<img alt="开源协议" src="olband.svg">
<img alt="商用协议" src="clband.svg">
<img alt="作者" src="https://img.shields.io/badge/Author-Wingsummer-green">
<img alt="开源协议" src="https://img.shields.io/badge/License-AGPL--3.0-red">
</p>
- 开源不易,给个 Star 或者 [捐助](#捐助) 吧
@ -38,9 +37,7 @@
### 协议
&emsp;&emsp;本软件如果用于非商业用途,采用`WingSummer OpenSource Lincense`协议,对应的协议内容在仓库`OpenSource-LICENSE`文件。 **没有我的任何授权,不得将该软件用于任何形式的商业用途,包括我改良的部分,除非你直接使用原组件,不限于商业二次开发、换 UI 套壳、二手转卖等,我不允许任何人随意把我当作免费劳动力作为赚钱的工具!** 我的初衷是让 Linux 的生态更加完整,早日让祖国推动操作系统国产化。我不希望“吸血鬼”们利益归自己,脏活累活给开源,都那么理所当然,开源就是这么被败坏的。我不希望因为版权的事情牵扯了大量的精力。
&emsp;&emsp;如果你想将本软件或者本软件的部分代码用于商业用途,必须亲自咨询我,商讨商业授权相关事宜。如果得到授权则采用`WingSummer Commerical License`协议,也就是本仓库的`Commerical-LICENSE`文件的内容。
&emsp;&emsp;本插件仓库将采用`AGPL-3.0`协议,不得将该插件代码用于改协议之外的用途。
### issue 前必读
@ -54,7 +51,7 @@
### 有关 QCodeEditor
&emsp;&emsp;本软件自带的编写脚本编辑器基于`QCodeEditor`,我对该软件进行的删减和修改以适配该插件的功能。如下是原仓库的必要说明,详情请点击 [此链接](https://github.com/Megaxela/QCodeEditor)
&emsp;&emsp;本软件自带的编写脚本编辑器基于`QCodeEditor`,我对该软件进行的删减和修改增强以适配该插件的功能。如下是原仓库的部分说明,详情请点击 [此链接](https://github.com/Megaxela/QCodeEditor)
---
@ -109,6 +106,24 @@ SOFTWARE.
---
### 有关 PythonQt
&emsp;&emsp;所有的 QT C++ 代码与 Python 脚本进行交互基础支持库,如果没有该框架,就不会有该插件的出现。该库遵守`LGPL`协议,如下是原仓库的部分说明,详情请点击 [此链接](https://github.com/MeVisLab/pythonqt)
---
PythonQt is a dynamic Python binding for Qt. It offers an easy way to embed the Python scripting language into your Qt applications.
Documentation
API documentation is available at: https://mevislab.github.io/pythonqt
Licensing
PythonQt is distributed under the LGPL 2.1 license.
---
&emsp;&emsp;鉴于 Linux 的动态库调用没有 Windows 方便之处,所以我使用了静态链接,按照协议必须开源修改后的代码。我把该库的`PythonQtScriptingConsole`单独出来进行编译,所有修改的代码都在头文件(减少警告)和代码文件`PythonQtScriptingConsole.hpp`和`PythonQtScriptingConsole.cpp`中。也就是说,所有的修改部分均在我的仓库文件当中。
## 效果图
<p align="center">
@ -135,4 +150,10 @@ SOFTWARE.
## 有关仓库
* GitLink https://www.gitlink.org.cn/wingsummer/WingHexPy
* Gitea https://code.gitlink.org.cn/wingsummer/WingHexPy
* Gitee https://gitee.com/wingsummer/wing-hex-py
## WIKI
> 插件完成后建设

View File

@ -29,12 +29,13 @@ SOURCES += \
QCodeEditor/QCodeEditor.cpp \
QCodeEditor/QFramedTextAttribute.cpp \
QCodeEditor/QLineNumberArea.cpp \
QCodeEditor/QPythonCompleter.cpp \
QCodeEditor/QPythonHighlighter.cpp \
QCodeEditor/QStyleSyntaxHighlighter.cpp \
QCodeEditor/QSyntaxStyle.cpp \
QCodeEditor/QLanguage.cpp \
scriptwindow.cpp
scriptwindow.cpp \
recentfilemanager.cpp \
PythonQt/gui/PythonQtScriptingConsole.cpp
HEADERS += \
winghexpy.h \
@ -43,24 +44,53 @@ HEADERS += \
QCodeEditor/QCodeEditor.hpp \
QCodeEditor/QFramedTextAttribute.hpp \
QCodeEditor/QLineNumberArea.hpp \
QCodeEditor/QPythonCompleter.hpp \
QCodeEditor/QPythonHighlighter.hpp \
QCodeEditor/QStyleSyntaxHighlighter.hpp \
QCodeEditor/QSyntaxStyle.hpp \
QCodeEditor/QHighlightBlockRule.hpp \
QCodeEditor/QHighlightRule.hpp \
QCodeEditor/QLanguage.hpp \
scriptwindow.h
scriptwindow.h \
recentfilemanager.h \
PythonQt/PythonQt.h \
PythonQt/PythonQtBoolResult.h \
PythonQt/PythonQtClassInfo.h \
PythonQt/PythonQtClassWrapper.h \
PythonQt/PythonQtConversion.h \
PythonQt/PythonQtCppWrapperFactory.h \
PythonQt/PythonQtDoc.h \
PythonQt/PythonQtImporter.h \
PythonQt/PythonQtImportFileInterface.h \
PythonQt/PythonQtInstanceWrapper.h \
PythonQt/PythonQtMethodInfo.h \
PythonQt/PythonQtMisc.h \
PythonQt/PythonQtObjectPtr.h \
PythonQt/PythonQtProperty.h \
PythonQt/PythonQtPythonInclude.h \
PythonQt/PythonQtQFileImporter.h \
PythonQt/PythonQtSignal.h \
PythonQt/PythonQtSignalReceiver.h \
PythonQt/PythonQtSlot.h \
PythonQt/PythonQtSlotDecorator.h \
PythonQt/PythonQtStdDecorators.h \
PythonQt/PythonQtStdIn.h \
PythonQt/PythonQtStdOut.h \
PythonQt/PythonQtSystem.h \
PythonQt/PythonQtUtils.h \
PythonQt/PythonQtVariants.h \
PythonQt/gui/PythonQtScriptingConsole.h
DISTFILES += WingHexPy.json
TRANSLATIONS += \
$$PWD/WingHexPy.ts
INCLUDEPATH += -I /usr/include/python3.7
LIBS += /usr/lib/x86_64-linux-gnu/libpython3.7m.so.1
LIBS += $$PWD/PythonQt/libPythonQt-Qt5-Python3.7.a
FORMS +=
DEFINES += PYTHONQT_CATCH_ALL_EXCEPTIONS
LIBS += /usr/lib/x86_64-linux-gnu/libpython3.7m.so.1
INCLUDEPATH += -I /usr/include/python3.7
RESOURCES += \
resources.qrc

View File

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="130" height="20" role="img" aria-label="Author: Wingsummer"><title>Author: Wingsummer</title><linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="r"><rect width="130" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#r)"><rect width="47" height="20" fill="#555"/><rect x="47" width="83" height="20" fill="#97ca00"/><rect width="130" height="20" fill="url(#s)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="245" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="370">Author</text><text x="245" y="140" transform="scale(.1)" fill="#fff" textLength="370">Author</text><text aria-hidden="true" x="875" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="730">Wingsummer</text><text x="875" y="140" transform="scale(.1)" fill="#fff" textLength="730">Wingsummer</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

View File

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="318" height="20" role="img" aria-label="Commerical License: WingSummer Commerical License"><title>Commerical License: WingSummer Commerical License</title><linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="r"><rect width="318" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#r)"><rect width="119" height="20" fill="#555"/><rect x="119" width="199" height="20" fill="#e05d44"/><rect width="318" height="20" fill="url(#s)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="605" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="1090">Commerical License</text><text x="605" y="140" transform="scale(.1)" fill="#fff" textLength="1090">Commerical License</text><text aria-hidden="true" x="2175" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="1890">WingSummer Commerical License</text><text x="2175" y="140" transform="scale(.1)" fill="#fff" textLength="1890">WingSummer Commerical License</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

BIN
img/author.jpg Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

BIN
img/author.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

BIN
img/clearhis.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

BIN
img/close.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

BIN
img/copy.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

BIN
img/cut.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

BIN
img/del.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

BIN
img/edit.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

BIN
img/file.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

BIN
img/jmp.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

BIN
img/new.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

BIN
img/open.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

BIN
img/paste.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

BIN
img/redo.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

BIN
img/run.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

BIN
img/save.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

BIN
img/saveas.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

BIN
img/soft.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

BIN
img/sponsor.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

BIN
img/undo.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

View File

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="322" height="20" role="img" aria-label="OpenSource License: WingSummer OpenSource License"><title>OpenSource License: WingSummer OpenSource License</title><linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="r"><rect width="322" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#r)"><rect width="121" height="20" fill="#555"/><rect x="121" width="201" height="20" fill="#e05d44"/><rect width="322" height="20" fill="url(#s)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="615" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="1110">OpenSource License</text><text x="615" y="140" transform="scale(.1)" fill="#fff" textLength="1110">OpenSource License</text><text aria-hidden="true" x="2205" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="1910">WingSummer OpenSource License</text><text x="2205" y="140" transform="scale(.1)" fill="#fff" textLength="1910">WingSummer OpenSource License</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

File diff suppressed because it is too large Load Diff

View File

@ -1,13 +1,16 @@
#ifndef PLGINTERFACE_H
#define PLGINTERFACE_H
#define PY_SSIZE_T_CLEAN
#include "../WingHexExplorer/wing-hex-explorer.sourcecode/WingHexExplorer/plugin/iwingplugin.h"
#include <Python.h>
#include "PythonQt/PythonQt.h"
#include "PythonQt/gui/PythonQtScriptingConsole.h"
#include <QObject>
#define INFOLOG(msg) "<font color=\"green\">" + msg + "</font><br />"
#define ERRLOG(msg) "<font color=\"red\">" + msg + "</font><br />"
#define WARNLOG(msg) "<font color=\"yellow\">" + msg + "</font><br />"
#define INFOLOG(msg) "<font color=\"green\">" + msg + "</font>"
#define ERRLOG(msg) "<font color=\"red\">" + msg + "</font>"
#define WARNLOG(msg) "<font color=\"yellow\">" + msg + "</font>"
class PlgInterface : public QObject {
Q_OBJECT
@ -19,271 +22,43 @@ signals:
public:
bool init();
PythonQtScriptingConsole *getScriptingConsole();
void RunPyFile(QString filename);
void RunPyText(QString content);
bool requestControl(int timeout = 1500);
bool requestRelease();
bool RunPyFile(QString filename);
bool RunPyText(QString content);
static PlgInterface *instance();
private slots:
//--------------reader--------------
static PyObject *currentDoc(PyObject *self, PyObject *args); // int
static PyObject *currentDocFilename(PyObject *self,
PyObject *args); // QString
// document
static PyObject *isReadOnly(PyObject *self, PyObject *args); // bool
static PyObject *isKeepSize(PyObject *self, PyObject *args); // bool
static PyObject *isLocked(PyObject *self, PyObject *args); // bool
static PyObject *documentLines(PyObject *self, PyObject *args); // quint64
static PyObject *documentBytes(PyObject *self, PyObject *args); // quint64
static PyObject *currentPos(PyObject *self, PyObject *args); // HexPosition
static PyObject *selectionPos(PyObject *self, PyObject *args); // HexPosition
static PyObject *currentRow(PyObject *self, PyObject *args); // quint64
static PyObject *currentColumn(PyObject *self, PyObject *args); // quint64
static PyObject *currentOffset(PyObject *self, PyObject *args); // quint64
static PyObject *selectlength(PyObject *self, PyObject *args); // quint64
static PyObject *stringVisible(PyObject *self, PyObject *args); // bool
static PyObject *addressVisible(PyObject *self, PyObject *args); // bool
static PyObject *headerVisible(PyObject *self, PyObject *args); // bool
static PyObject *addressBase(PyObject *self, PyObject *args); // quint64
static PyObject *isModified(PyObject *self, PyObject *args); // bool
static PyObject *isEmpty(PyObject *self, PyObject *args); // bool
static PyObject *atEnd(PyObject *self, PyObject *args); // bool
static PyObject *canUndo(PyObject *self, PyObject *args); // bool
static PyObject *canRedo(PyObject *self, PyObject *args); // bool
static PyObject *copy(PyObject *self,
PyObject *args); // void : bool hex = false
static PyObject *read(PyObject *self,
PyObject *args); // QByteArray : qint64 offset, int len
static PyObject *
searchForward(PyObject *self,
PyObject *args); // qint64 : qint64 begin, const QByteArray &ba
static PyObject *
searchBackward(PyObject *self,
PyObject *args); // qint64 : qint64 begin, const QByteArray &ba
static PyObject *findAllBytes(PyObject *self, PyObject *args);
// void : qlonglong begin, qlonglong end, QByteArray b,
// QList<quint64>&results, int maxCount = -1
// render
static PyObject *documentLastLine(PyObject *self, PyObject *args); // quint64
static PyObject *documentLastColumn(PyObject *self, PyObject *args); // int
// metadata
static PyObject *lineHasMetadata(PyObject *self,
PyObject *args); // bool : quint64 line
static PyObject *getMetadatas(
PyObject *self,
PyObject *args); // QList<HexMetadataAbsoluteItem> : qint64 offset
static PyObject *
getMetaLine(PyObject *self,
PyObject *args); // HexLineMetadata : quint64 line
// bookmark
static PyObject *lineHasBookMark(PyObject *self,
PyObject *args); // bool : quint64 line
static PyObject *
getsBookmarkPos(PyObject *self,
PyObject *args); // QList<qint64> : quint64 line
static PyObject *bookMark(PyObject *self,
PyObject *args); // BookMark : qint64 pos
static PyObject *bookMarkComment(PyObject *self,
PyObject *args); // QString : qint64 pos
static PyObject *
getBookMarks(PyObject *self,
PyObject *args); // void : QList<BookMark> &bookmarks
static PyObject *existBookMark(PyObject *self,
PyObject *args); // bool : qint64 pos
// extension
static PyObject *getOpenFiles(PyObject *self,
PyObject *args); // QList<QString>
static PyObject *getSupportedEncodings(PyObject *self,
PyObject *args); // QStringList
static PyObject *currentEncoding(PyObject *self, PyObject *args); // QString
//--------------controller--------------
// document
static PyObject *
switchDocument(PyObject *self,
PyObject *args); // bool : int index, bool gui = false
static PyObject *setLockedFile(PyObject *self,
PyObject *args); // bool : bool b
static PyObject *setKeepSize(PyObject *self,
PyObject *args); // bool : bool b
static PyObject *setStringVisible(PyObject *self,
PyObject *args); // void : bool b
static PyObject *setAddressVisible(PyObject *self,
PyObject *args); // void : bool b
static PyObject *setHeaderVisible(PyObject *self,
PyObject *args); // void : bool b
static PyObject *setAddressBase(PyObject *self,
PyObject *args); // void : quint64 base
static PyObject *undo(PyObject *self, PyObject *args); // void
static PyObject *redo(PyObject *self, PyObject *args); // void
static PyObject *cut(PyObject *self,
PyObject *args); // bool : bool hex = false
static PyObject *paste(PyObject *self,
PyObject *args); // void : bool hex = false
static PyObject *
insert(PyObject *self,
PyObject *args); // bool : qint64 offset, const QByteArray &data
static PyObject *
replace(PyObject *self,
PyObject *args); // bool : qint64 offset, const QByteArray &data
static PyObject *remove(PyObject *self,
PyObject *args); // bool : qint64 offset, int len
// cursor
static PyObject *moveTo(PyObject *self,
PyObject *args); // void:
// quint64 line, int column, int nibbleindex
// qint64 offset
static PyObject *
select(PyObject *self,
PyObject *args); // void : quint64 line, int column, int nibbleindex
// qint64 offset, int length
static PyObject *
selectOffset(PyObject *self,
PyObject *args); // void : qint64 offset, int length
static PyObject *setInsertionMode(PyObject *self,
PyObject *args); // void : bool isinsert
static PyObject *enabledCursor(PyObject *self,
PyObject *args); // void : bool b
// metadata
static PyObject *metadata(PyObject *self, PyObject *args);
// bool : qint64 begin, qint64 end, const QColor &fgcolor,
// const QColor &bgcolor, const QString &comment
static PyObject *removeMetadata(PyObject *self,
PyObject *args); // bool : qint64 offset
static PyObject *clearMeta(PyObject *self,
PyObject *args); // bool
static PyObject *color(PyObject *self,
PyObject *args); // bool
// quint64 line, int start, int length, const QColor &fgcolor,
// const QColor &bgcolor
static PyObject *foreground(PyObject *self,
PyObject *args); // bool
// quint64 line, int start, int length, const QColor &fgcolor
static PyObject *background(PyObject *self,
PyObject *args); // bool
// quint64 line, int start, int length, const QColor &bgcolor
static PyObject *comment(PyObject *self,
PyObject *args); // bool
// quint64 line, int start, int length, const QString &comment
static PyObject *
applyMetas(PyObject *self,
PyObject *args); // void : QList<HexMetadataAbsoluteItem> metas
static PyObject *setMetaVisible(PyObject *self,
PyObject *args); // bool : bool b
static PyObject *setMetafgVisible(PyObject *self,
PyObject *args); // void : bool b
static PyObject *setMetabgVisible(PyObject *self,
PyObject *args); // void : bool b
static PyObject *setMetaCommentVisible(PyObject *self,
PyObject *args); // void : bool b
// mainwindow
static PyObject *newFile(PyObject *self,
PyObject *args); // void : bool bigfile = false
static PyObject *
openFile(PyObject *self,
PyObject *args); // ErrFile : QString filename, bool readonly
static PyObject *openDriver(PyObject *self,
PyObject *args); // ErrFile : QString driver
static PyObject *closeFile(PyObject *self,
PyObject *args); // ErrFile : int index, bool force
static PyObject *saveFile(PyObject *self,
PyObject *args); // ErrFile : int index
static PyObject *
exportFile(PyObject *self,
PyObject *args); // ErrFile : QString filename, int index
static PyObject *exportFileGUI(PyObject *self,
PyObject *args); // void
static PyObject *
saveasFile(PyObject *self,
PyObject *args); // ErrFile : QString filename, int index
static PyObject *saveasFileGUI(PyObject *self,
PyObject *args); // void
static PyObject *closeCurrentFile(PyObject *self,
PyObject *args); // ErrFile : bool force
static PyObject *saveCurrentFile(PyObject *self,
PyObject *args); // ErrFile
static PyObject *openFileGUI(PyObject *self,
PyObject *args); // void
static PyObject *openDriverGUI(PyObject *self,
PyObject *args); // void
static PyObject *findGUI(PyObject *self,
PyObject *args); // void
static PyObject *gotoGUI(PyObject *self,
PyObject *args); // void
static PyObject *fillGUI(PyObject *self,
PyObject *args); // void
static PyObject *fillzeroGUI(PyObject *self,
PyObject *args); // void
static PyObject *fillnopGUI(PyObject *self,
PyObject *args); // void
// bookmark
static PyObject *
addBookMark(PyObject *self,
PyObject *args); // bool : qint64 pos, QString comment
static PyObject *
modBookMark(PyObject *self,
PyObject *args); // bool : qint64 pos, QString comment
static PyObject *
applyBookMarks(PyObject *self,
PyObject *args); // void : QList<BookMark> books
static PyObject *removeBookMark(PyObject *self,
PyObject *args); // bool : qint64 pos
static PyObject *clearBookMark(PyObject *self,
PyObject *args); // bool
// workspace
static PyObject *
openWorkSpace(PyObject *self,
PyObject *args); // bool : QString filename, bool readonly
static PyObject *
setCurrentEncoding(PyObject *self,
PyObject *args); // bool : QString encoding
// extension
static PyObject *toast(PyObject *self,
PyObject *args); // void : QIcon icon, QString message
//--------------service--------------
static PyObject *print(PyObject *self, PyObject *args);
static PyObject *errPrint(PyObject *self, PyObject *args);
static PyObject *infoPrint(PyObject *self, PyObject *args);
static PyObject *warnPrint(PyObject *self, PyObject *args);
static PyObject *requestControl(PyObject *self,
PyObject *args); // bool : int timeout = 1500
static PyObject *hasControl(PyObject *self,
PyObject *args); // bool
static PyObject *requestRelease(PyObject *self, PyObject *args); // bool
private:
static PyMethodDef rEmbMethods[], cEmbMethods[], sEmbMethods[];
static PyModuleDef WingPlgReader, WingPlgCtl, WingPlgService;
static IWingPlugin *plg;
static PlgInterface *self;
IWingPlugin *plg;
PythonQtObjectPtr mainContext;
PythonQtScriptingConsole *console;
private:
static PyObject *PyInit_WingPlgReader(void);
static PyObject *PyInit_WingPlgCtl(void);
static PyObject *PyInit_WingPlgService(void);
static PlgInterface *m_instace;
};
class PlgService : public QObject {
Q_OBJECT
public:
PlgService() {}
PlgService(PlgInterface *parent) : inter(parent) {}
public slots:
bool requestControl(int timeout = 1500) {
return inter->requestControl(timeout);
}
bool requestRelease() { return inter->requestRelease(); }
void print(QString message) { inter->log(message); }
void errPrint(QString message) { inter->log(ERRLOG(message)); }
void infoPrint(QString message) { inter->log(INFOLOG(message)); }
void warnPrint(QString message) { inter->log(WARNLOG(message)); }
private:
PlgInterface *inter;
};
#endif // PLGINTERFACE_H

124
recentfilemanager.cpp Normal file
View File

@ -0,0 +1,124 @@
#include "recentfilemanager.h"
#include <DInputDialog>
#include <DMenu>
#include <DMessageManager>
#include <QApplication>
#include <QFile>
#include <QSettings>
#define ICONRES(name) QIcon(":/img/" name ".png")
RecentFileManager::RecentFileManager(DMenu *menu, DMainWindow *parent)
: QObject(parent), m_menu(menu), m_parent(parent) {}
void RecentFileManager::apply() {
QAction *a;
a = new QAction(m_menu);
a->setText(tr("ClearHistory"));
a->setIcon(ICONRES("clearhis"));
connect(a, &QAction::triggered, this, &RecentFileManager::clearFile);
m_menu->addAction(a);
a = new QAction(m_menu);
a->setText(tr("RemoveItem"));
a->setIcon(ICONRES("del"));
connect(a, &QAction::triggered, [=] {
if (hitems.count() == 0) {
DMessageManager::instance()->sendMessage(m_parent, ICONRES("clearhis"),
tr("NoHistoryDel"));
return;
}
bool ok;
auto d = DInputDialog::getInt(nullptr, tr("Input"), tr("InputIndex"), 0, 0,
m_recents.count(), 1, &ok);
if (ok) {
m_menu->removeAction(hitems.at(d));
m_recents.removeAt(d);
for (auto it = hitems.begin() + d; it != hitems.end(); it++) {
(*it)->setIconText(QString::number(d++));
}
}
});
m_menu->addAction(a);
m_menu->addSeparator();
QSettings settings(QApplication::organizationName(), "WingHexPy");
auto s = settings.value("recent").toStringList();
int i = 0;
for (auto item : s) {
if (QFile::exists(item)) {
if (m_recents.count() > 10)
break;
m_recents << item;
a = new QAction(m_menu);
a->setText(QString("%1 : %2").arg(i++).arg(item));
a->setData(item);
connect(a, &QAction::triggered, this, &RecentFileManager::trigger);
hitems.push_back(a);
m_menu->addAction(a);
}
}
}
RecentFileManager::~RecentFileManager() {
QSettings settings(QApplication::organizationName(), "WingHexPy");
settings.setValue("recent", m_recents);
}
void RecentFileManager::addRecentFile(QString filename) {
while (m_recents.count() >= 10) {
m_recents.pop_back();
}
if (QFile::exists(filename) && m_recents.indexOf(filename) < 0) {
auto a = new QAction(m_menu);
a = new QAction(m_menu);
a->setData(filename);
connect(a, &QAction::triggered, this, &RecentFileManager::trigger);
m_recents.push_front(filename);
if (hitems.count())
m_menu->insertAction(hitems.first(), a);
else
m_menu->addAction(a);
hitems.push_front(a);
auto i = 0;
for (auto item : hitems) {
item->setText(QString("%1 : %2").arg(i++).arg(item->data().toString()));
}
}
}
void RecentFileManager::trigger() {
auto send = qobject_cast<QAction *>(sender());
if (send) {
auto f = send->data().toString();
if (QFile::exists(f)) {
emit openFile(f);
return;
}
}
auto index = hitems.indexOf(send);
if (index >= 0) {
m_menu->removeAction(send);
hitems.removeAt(index);
m_recents.removeAt(index);
}
}
void RecentFileManager::clearFile() {
if (hitems.count() == 0) {
DMessageManager::instance()->sendMessage(m_parent, ICONRES("clearhis"),
tr("NoHistoryDel"));
return;
}
for (auto item : hitems) {
m_menu->removeAction(item);
}
m_recents.clear();
hitems.clear();
QSettings settings(QApplication::organizationName(), "WingHexPy");
settings.setValue("recent", m_recents);
DMessageManager::instance()->sendMessage(m_parent, ICONRES("clearhis"),
tr("HistoryClearFinished"));
}

32
recentfilemanager.h Normal file
View File

@ -0,0 +1,32 @@
#ifndef RECENTFILEMANAGER_H
#define RECENTFILEMANAGER_H
#include <DMainWindow>
#include <DMenu>
#include <QAction>
#include <QList>
#include <QObject>
DWIDGET_USE_NAMESPACE
class RecentFileManager : public QObject {
Q_OBJECT
public:
explicit RecentFileManager(DMenu *menu, DMainWindow *parent = nullptr);
~RecentFileManager();
void addRecentFile(QString filename);
void clearFile();
void apply();
signals:
bool openFile(QString filename);
private:
DMenu *m_menu;
QStringList m_recents;
QList<QAction *> hitems;
DMainWindow *m_parent;
void trigger();
};
#endif // RECENTFILEMANAGER_H

View File

@ -4,5 +4,26 @@
<file alias="default_style.xml">QCodeEditor/default_style.xml</file>
<file>img/pys.png</file>
<file alias="drakula.xml">QCodeEditor/drakula.xml</file>
<file>img/icon.png</file>
<file>img/author.jpg</file>
<file>img/author.png</file>
<file>img/copy.png</file>
<file>img/cut.png</file>
<file>img/del.png</file>
<file>img/file.png</file>
<file>img/jmp.png</file>
<file>img/new.png</file>
<file>img/open.png</file>
<file>img/paste.png</file>
<file>img/redo.png</file>
<file>img/save.png</file>
<file>img/saveas.png</file>
<file>img/soft.png</file>
<file>img/sponsor.png</file>
<file>img/undo.png</file>
<file>img/clearhis.png</file>
<file>img/close.png</file>
<file>img/edit.png</file>
<file>img/run.png</file>
</qresource>
</RCC>

View File

@ -1,12 +1,14 @@
#include "scriptwindow.h"
#include "../WingHexExplorer/wing-hex-explorer.sourcecode/WingHexExplorer/plugin/iwingplugin.h"
#include "QCodeEditor/QPythonCompleter.hpp"
#include "QCodeEditor/QPythonHighlighter.hpp"
#include "plginterface.h"
#include <DTitlebar>
#include <DWidgetUtil>
#include <Python.h>
#include <QVBoxLayout>
#define ICONRES(name) QIcon(":/img/" name ".png")
ScriptWindow *ScriptWindow::m_instance = nullptr;
ScriptWindow *ScriptWindow::instance() {
@ -20,11 +22,10 @@ ScriptWindow::ScriptWindow(DMainWindow *parent) : DMainWindow(parent) {
setMinimumSize(QSize(600, 500));
auto _title = titlebar();
auto picon = QIcon(":/img/pys.png");
auto picon = ICONRES("pys");
setWindowIcon(picon);
_title->setIcon(picon);
_title->setTitle(tr("WingHexPyScriptWindow"));
auto w = new QWidget(this);
setCentralWidget(w);
auto vlayout = new QVBoxLayout(w);
@ -42,7 +43,6 @@ ScriptWindow::ScriptWindow(DMainWindow *parent) : DMainWindow(parent) {
m_styles[1] = darkstyle;
editor = new QCodeEditor(this);
editor->setCompleter(new QPythonCompleter(this));
editor->setHighlighter(new QPythonHighlighter);
editor->setSyntaxStyle(
m_styles[guihelper->themeType() == DGuiApplicationHelper::LightType ? 0
@ -54,19 +54,84 @@ ScriptWindow::ScriptWindow(DMainWindow *parent) : DMainWindow(parent) {
vlayout->addWidget(editor);
PluginMenuInitBegin(menu, "") {
PluginMenuAddItemLamba(menu, tr("New"), [=] {
Q_UNUSED(a);
QMenu *m;
PluginMenuInitBegin(m, tr("File")) {
m->setIcon(ICONRES("file"));
PluginMenuAddItemIconAction(m, tr("New"), ICONRES("new"),
ScriptWindow::on_new);
PluginMenuAddItemIconAction(m, tr("Open"), ICONRES("open"),
ScriptWindow::on_open);
PluginMenuAddItemIconAction(m, tr("Save"), ICONRES("save"),
ScriptWindow::on_save);
PluginMenuAddItemIconAction(m, tr("SaveAs"), ICONRES("saveas"),
ScriptWindow::on_saveas);
auto rm = new QMenu(menu);
rm->setTitle(tr("RecentFile"));
recentmanager = new RecentFileManager(rm, this);
recentmanager->apply();
m->addMenu(rm);
PluginMenuAddItemIconAction(m, tr("Close"), ICONRES("close"),
ScriptWindow::on_close);
}
PluginMenuInitEnd();
menu->addMenu(m);
});
PluginMenuInitBegin(m, tr("Edit")) {
m->setIcon(ICONRES("edit"));
PluginMenuAddItemIconAction(m, tr("Undo"), ICONRES("undo"),
ScriptWindow::on_undo);
a->setEnabled(false);
mundo = a;
PluginMenuAddItemIconAction(m, tr("Redo"), ICONRES("redo"),
ScriptWindow::on_redo);
a->setEnabled(false);
mredo = a;
m->addSeparator();
PluginMenuAddItemIconAction(m, tr("Cut"), ICONRES("cut"),
ScriptWindow::on_cut);
PluginMenuAddItemIconAction(m, tr("Copy"), ICONRES("copy"),
ScriptWindow::on_copy);
PluginMenuAddItemIconAction(m, tr("Paste"), ICONRES("paste"),
ScriptWindow::on_paste);
}
PluginMenuInitEnd();
menu->addMenu(m);
}
PluginMenuInitEnd();
_title->setMenu(menu);
_title->setFullScreenButtonVisible(true);
_title->setSwitchThemeMenuVisible(false);
_title->setQuitMenuVisible(false);
PluginToolBarInitBegin(toolbar, "") {
PluginToolBarAddLamba(
toolbar, QIcon(), [=] {}, tr(""));
PluginToolBarAddAction(toolbar, ICONRES("new"), ScriptWindow::on_new,
tr("New"));
PluginToolBarAddAction(toolbar, ICONRES("open"), ScriptWindow::on_open,
tr("Open"));
PluginToolBarAddAction(toolbar, ICONRES("save"), ScriptWindow::on_save,
tr("Save"));
PluginToolBarAddAction(toolbar, ICONRES("saveas"), ScriptWindow::on_saveas,
tr("SaveAs"));
toolbar->addSeparator();
PluginToolBarAddAction(toolbar, ICONRES("undo"), ScriptWindow::on_undo,
tr("Undo"));
a->setEnabled(false);
aundo = a;
PluginToolBarAddAction(toolbar, ICONRES("redo"), ScriptWindow::on_redo,
tr("Redo"));
a->setEnabled(false);
aredo = a;
PluginToolBarAddAction(toolbar, ICONRES("cut"), ScriptWindow::on_cut,
tr("Cut"));
PluginToolBarAddAction(toolbar, ICONRES("copy"), ScriptWindow::on_copy,
tr("Copy"));
PluginToolBarAddAction(toolbar, ICONRES("paste"), ScriptWindow::on_saveas,
tr("Paste"));
toolbar->addSeparator();
PluginToolBarAddAction(toolbar, ICONRES("run"), ScriptWindow::on_run,
tr("Run"));
}
PluginToolBarInitEnd();
@ -75,6 +140,15 @@ ScriptWindow::ScriptWindow(DMainWindow *parent) : DMainWindow(parent) {
status = new DStatusBar(this);
setStatusBar(status);
connect(editor, &QCodeEditor::undoAvailable, this, [=](bool b) {
aundo->setEnabled(b);
mundo->setEnabled(b);
});
connect(editor, &QCodeEditor::redoAvailable, this, [=](bool b) {
aredo->setEnabled(b);
mredo->setEnabled(b);
});
Dtk::Widget::moveToCenter(this);
}
@ -85,3 +159,28 @@ void ScriptWindow::setTheme(DGuiApplicationHelper::ColorType theme) {
editor->setSyntaxStyle(m_styles[1]);
}
}
void ScriptWindow::on_new() {}
void ScriptWindow::on_open() {}
void ScriptWindow::on_save() {}
void ScriptWindow::on_saveas() {}
void ScriptWindow::on_close() { close(); }
void ScriptWindow::on_redo() { editor->redo(); }
void ScriptWindow::on_undo() { editor->undo(); }
void ScriptWindow::on_copy() { editor->copy(); }
void ScriptWindow::on_cut() { editor->cut(); }
void ScriptWindow::on_paste() { editor->paste(); }
void ScriptWindow::on_run() {
auto inst = PlgInterface::instance();
inst->RunPyText(editor->toPlainText());
}

View File

@ -3,6 +3,7 @@
#include "QCodeEditor/QCodeEditor.hpp"
#include "QCodeEditor/QSyntaxStyle.hpp"
#include "recentfilemanager.h"
#include <DGuiApplicationHelper>
#include <DMainWindow>
#include <DStatusBar>
@ -19,13 +20,32 @@ public:
private:
void setTheme(DGuiApplicationHelper::ColorType theme);
public:
bool openFile(QString filename, bool readonly = false);
private:
void on_new();
void on_open();
void on_save();
void on_saveas();
void on_undo();
void on_redo();
void on_copy();
void on_cut();
void on_paste();
void on_run();
void on_close();
private:
QCodeEditor *editor;
static ScriptWindow *m_instance;
QSyntaxStyle *m_styles[2];
DToolBar *toolbar;
DStatusBar *status;
QAction *aundo, *aredo;
QAction *mundo, *mredo;
DMenu *menu;
RecentFileManager *recentmanager;
};
#endif // SCRIPTWINDOW_H

View File

@ -34,7 +34,7 @@ bool WingHexPy::init(QList<WingPluginInfo> loadedplugin) {
}
PluginMenuInitEnd();
txt = new QTextBrowser;
txt = plgint->getScriptingConsole();
PluginDockWidgetInit(dw, txt, tr("WingHexPyConsole"), "WingHexPyConsole");
PluginToolBarInitBegin(tb, "WingHexPy") {
@ -47,15 +47,11 @@ bool WingHexPy::init(QList<WingPluginInfo> loadedplugin) {
return true;
}
bool WingHexPy::RunPyFile(QString filename) {
return plgint->RunPyFile(filename);
}
void WingHexPy::RunPyFile(QString filename) { plgint->RunPyFile(filename); }
bool WingHexPy::RunPyText(QString content) {
return plgint->RunPyText(content);
}
void WingHexPy::RunPyText(QString content) { plgint->RunPyText(content); }
void WingHexPy::unload() { Py_Finalize(); }
void WingHexPy::unload() {}
void WingHexPy::plugin2MessagePipe(WingPluginMessage type,
QList<QVariant> msg) {
@ -83,4 +79,4 @@ QDockWidget *WingHexPy::registerDockWidget() { return dw; }
QToolBar *WingHexPy::registerToolBar() { return tb; }
void WingHexPy::log(QString message) { txt->insertHtml(message); }
void WingHexPy::log(QString message) { txt->consoleMessage(message); }

View File

@ -2,6 +2,7 @@
#define GENERICPLUGIN_H
#include "../WingHexExplorer/wing-hex-explorer.sourcecode/WingHexExplorer/plugin/iwingplugin.h"
#include "PythonQt/gui/PythonQtScriptingConsole.h"
#include "plginterface.h"
#include <Python.h>
#include <QTextBrowser>
@ -36,16 +37,15 @@ public:
void log(QString message);
public:
bool RunPyFile(QString filename);
bool RunPyText(QString content);
void RunPyFile(QString filename);
void RunPyText(QString content);
private:
PlgInterface *plgint;
QMenu *menu;
QToolBar *tb;
QDockWidget *dw;
QTextBrowser *txt;
PythonQtScriptingConsole *txt;
};
#endif // GENERICPLUGIN_H