././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1716810829.808581
orange-canvas-core-0.2.1/ 0000775 0001750 0001750 00000000000 14625072116 014236 5 ustar 00marko marko ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/LICENSE.txt 0000664 0001750 0001750 00000104513 14625071541 016066 0 ustar 00marko marko GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/MANIFEST.in 0000664 0001750 0001750 00000000071 14625071541 015773 0 ustar 00marko marko include LICENSE.txt README.rst
recursive-include docs *.* ././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1716810829.808581
orange-canvas-core-0.2.1/PKG-INFO 0000664 0001750 0001750 00000003100 14625072116 015325 0 ustar 00marko marko Metadata-Version: 2.1
Name: orange-canvas-core
Version: 0.2.1
Summary: Core component of Orange Canvas
Home-page: http://orange.biolab.si/
Author: Bioinformatics Laboratory, FRI UL
Author-email: contact@orange.biolab.si
License: GPLv3
Project-URL: Bug Reports, https://github.com/biolab/orange-canvas-core/issues
Project-URL: Source, https://github.com/biolab/orange-canvas-core/
Project-URL: Documentation, https://orange-canvas-core.readthedocs.io/en/latest/
Requires-Python: >=3.6
Description-Content-Type: text/x-rst
Provides-Extra: DOCBUILD
License-File: LICENSE.txt
Orange Canvas Core
==================
.. image:: https://github.com/biolab/orange-canvas-core/workflows/Run%20tests/badge.svg
:target: https://github.com/biolab/orange-canvas-core/actions?query=workflow%3A%22Run+tests%22
:alt: Github Actions CI Build Status
.. image:: https://readthedocs.org/projects/orange-canvas-core/badge/?version=latest
:target: https://orange-canvas-core.readthedocs.io/en/latest/?badge=latest
:alt: Documentation Status
Orange Canvas Core is a framework for building graphical user
interfaces for editing workflows. It is a component used to build
the Orange Canvas (http://orange.biolab.si) data-mining application
(for which it was developed in the first place).
Installation
------------
Orange Canvas Core is pip installable (https://pip.pypa.io/), simply run::
pip install orange-canvas-core
Or use the::
pip install ./
to install from the sources.
Documentation
-------------
Some incomplete documentation is available at https://orange-canvas-core.readthedocs.io
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/README.rst 0000664 0001750 0001750 00000002003 14625071541 015721 0 ustar 00marko marko Orange Canvas Core
==================
.. image:: https://github.com/biolab/orange-canvas-core/workflows/Run%20tests/badge.svg
:target: https://github.com/biolab/orange-canvas-core/actions?query=workflow%3A%22Run+tests%22
:alt: Github Actions CI Build Status
.. image:: https://readthedocs.org/projects/orange-canvas-core/badge/?version=latest
:target: https://orange-canvas-core.readthedocs.io/en/latest/?badge=latest
:alt: Documentation Status
Orange Canvas Core is a framework for building graphical user
interfaces for editing workflows. It is a component used to build
the Orange Canvas (http://orange.biolab.si) data-mining application
(for which it was developed in the first place).
Installation
------------
Orange Canvas Core is pip installable (https://pip.pypa.io/), simply run::
pip install orange-canvas-core
Or use the::
pip install ./
to install from the sources.
Documentation
-------------
Some incomplete documentation is available at https://orange-canvas-core.readthedocs.io
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1716810829.7645812
orange-canvas-core-0.2.1/docs/ 0000775 0001750 0001750 00000000000 14625072116 015166 5 ustar 00marko marko ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/make.bat 0000664 0001750 0001750 00000016151 14625071541 016600 0 ustar 00marko marko @ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source
set I18NSPHINXOPTS=%SPHINXOPTS% source
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^` where ^ is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. xml to make Docutils-native XML files
echo. pseudoxml to make pseudoxml-XML files for display purposes
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
echo. coverage to run coverage check of the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
REM Check if sphinx-build is available and fallback to Python version if any
%SPHINXBUILD% 2> nul
if errorlevel 9009 goto sphinx_python
goto sphinx_ok
:sphinx_python
set SPHINXBUILD=python -m sphinx.__init__
%SPHINXBUILD% 2> nul
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
:sphinx_ok
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\OrangeCanvasCore.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\OrangeCanvasCore.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdf" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf
cd %~dp0
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdfja" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf-ja
cd %~dp0
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
if "%1" == "coverage" (
%SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage
if errorlevel 1 exit /b 1
echo.
echo.Testing of coverage in the sources finished, look at the ^
results in %BUILDDIR%/coverage/python.txt.
goto end
)
if "%1" == "xml" (
%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The XML files are in %BUILDDIR%/xml.
goto end
)
if "%1" == "pseudoxml" (
%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
goto end
)
:end
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/requirements-rtd.txt 0000664 0001750 0001750 00000000533 14625071541 021243 0 ustar 00marko marko --only-binary PyQt5,numpy
setuptools
sphinx~=4.2.0
sphinx-rtd-theme
PyQt5~=5.9.2
AnyQt
# sphinx pins docutils version, but the installation in the RTD worker/config
# overrides it because docutils is also in our dependencies.
# https://docs.readthedocs.io/en/stable/faq.html#i-need-to-install-a-package-in-a-environment-with-pinned-versions
-e . ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1716810829.7645812
orange-canvas-core-0.2.1/docs/source/ 0000775 0001750 0001750 00000000000 14625072116 016466 5 ustar 00marko marko ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/conf.py 0000664 0001750 0001750 00000023007 14625071541 017770 0 ustar 00marko marko # -*- coding: utf-8 -*-
#
# Orange Canvas Core documentation build configuration file, created by
# sphinx-quickstart on Thu Jun 4 12:15:21 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
import importlib_metadata
dist = importlib_metadata.distribution("orange-canvas-core")
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.coverage',
'sphinx.ext.napoleon',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Orange Canvas Core'
copyright = u'2019, Bioinformatics Laboratory, FRI UL'
author = u'Bioinformatics Laboratory, FRI UL'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = dist.version
# The full version, including alpha/beta/rc tags.
release = dist.version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
'collapse_navigation': True,
}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
#html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'OrangeCanvasCoredoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'OrangeCanvasCore.tex', u'Orange Canvas Core Documentation',
u'Bioinformatics Laboratory, FRI UL', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'orangecanvascore', u'Orange Canvas Core Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'OrangeCanvasCore', u'Orange Canvas Core Documentation',
author, 'OrangeCanvasCore', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/index.rst 0000664 0001750 0001750 00000000772 14625071541 020336 0 ustar 00marko marko .. Orange Canvas Core documentation master file, created by
sphinx-quickstart on Thu Jun 4 12:15:21 2015.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to Orange Canvas Core's documentation!
==============================================
Contents:
.. toctree::
:maxdepth: 2
orangecanvas/overview
orangecanvas/index
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1716810829.7685812
orange-canvas-core-0.2.1/docs/source/orangecanvas/ 0000775 0001750 0001750 00000000000 14625072116 021135 5 ustar 00marko marko ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/application.canvasmain.rst 0000664 0001750 0001750 00000001133 14625071541 026310 0 ustar 00marko marko ===================================
Canvas Main Window (``canvasmain``)
===================================
.. currentmodule:: orangecanvas.application.canvasmain
.. autoclass:: orangecanvas.application.canvasmain.CanvasMainWindow
:member-order: bysource
:show-inheritance:
.. automethod:: set_widget_registry(widget_registry: WidgetRegistry)
.. method:: current_document() -> SchemeEditWidget
Return the current displayed editor (:class:`.SchemeEditWidget`)
.. automethod:: create_new_window() -> CanvasMainWindow
.. automethod:: new_workflow_window() -> CanvasMainWindow ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/application.rst 0000664 0001750 0001750 00000000353 14625071541 024174 0 ustar 00marko marko .. application:
#############################
Application (``application``)
#############################
.. automodule:: orangecanvas.application
.. toctree::
:maxdepth: 1
application.welcomedialog
application.canvasmain
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/application.welcomedialog.rst 0000664 0001750 0001750 00000001170 14625071541 027004 0 ustar 00marko marko ==================================
Welcome Dialog (``welcomedialog``)
==================================
.. currentmodule:: orangecanvas.application.welcomedialog
.. autoclass:: orangecanvas.application.welcomedialog.WelcomeDialog
:member-order: bysource
:show-inheritance:
.. method:: triggered(QAction)
Signal emitted when an action is triggered by the user
.. automethod:: setShowAtStartup(state: bool)
.. automethod:: showAtStartup() -> bool
.. automethod:: setFeedbackUrl(url: str)
.. automethod:: addRow(actions: List[QAction])
.. automethod:: buttonAt(i: int, j: int) -> QAbstractButton ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/canvas.items.annotationitem.rst 0000664 0001750 0001750 00000000736 14625071541 027321 0 ustar 00marko marko .. canvas-annotation-item:
=====================================
Annotation Items (``annotationitem``)
=====================================
.. automodule:: orangecanvas.canvas.items.annotationitem
.. autoclass:: Annotation
:members:
:member-order: bysource
:show-inheritance:
.. autoclass:: TextAnnotation
:members:
:member-order: bysource
:show-inheritance:
.. autoclass:: ArrowAnnotation
:members:
:member-order: bysource
:show-inheritance:
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/canvas.items.linkitem.rst 0000664 0001750 0001750 00000000355 14625071541 026101 0 ustar 00marko marko .. canvas-link-item:
========================
Link Item (``linkitem``)
========================
.. automodule:: orangecanvas.canvas.items.linkitem
.. autoclass:: LinkItem
:members:
:member-order: bysource
:show-inheritance:
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/canvas.items.nodeitem.rst 0000664 0001750 0001750 00000001473 14625071541 026073 0 ustar 00marko marko .. canvas-node-item:
========================
Node Item (``nodeitem``)
========================
.. automodule:: orangecanvas.canvas.items.nodeitem
.. autoclass:: NodeItem
:members:
:exclude-members:
from_node,
from_node_meta,
setupGraphics,
setProgressMessage,
positionChanged,
anchorGeometryChanged,
activated,
hovered
:member-order: bysource
:show-inheritance:
.. autoattribute:: positionChanged()
.. autoattribute:: anchorGeometryChanged()
.. autoattribute:: activated()
.. autoclass:: AnchorPoint
:members:
:exclude-members:
scenePositionChanged,
anchorDirectionChanged
:member-order: bysource
:show-inheritance:
.. autoattribute:: scenePositionChanged(QPointF)
.. autoattribute:: anchorDirectionChanged(QPointF)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/canvas.rst 0000664 0001750 0001750 00000000323 14625071541 023141 0 ustar 00marko marko ===================
Canvas (``canvas``)
===================
.. automodule:: orangecanvas.canvas
.. toctree::
canvas.scene
canvas.items.nodeitem
canvas.items.linkitem
canvas.items.annotationitem
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/canvas.scene.rst 0000664 0001750 0001750 00000002201 14625071541 024232 0 ustar 00marko marko .. canvas-scene:
========================
Canvas Scene (``scene``)
========================
.. automodule:: orangecanvas.canvas.scene
.. autoclass:: CanvasScene
:members:
:exclude-members:
node_item_added,
node_item_removed,
link_item_added,
link_item_removed,
annotation_added,
annotation_removed,
node_item_position_changed,
node_item_double_clicked,
node_item_activated,
node_item_hovered,
link_item_hovered
:member-order: bysource
:show-inheritance:
.. autoattribute:: node_item_added(NodeItem)
.. autoattribute:: node_item_removed(NodeItem)
.. autoattribute:: link_item_added(LinkItem)
.. autoattribute:: link_item_removed(LinkItem)
.. autoattribute:: annotation_added(Annotation)
.. autoattribute:: annotation_removed(Annotation)
.. autoattribute:: node_item_position_changed(NodeItem, QPointF)
.. autoattribute:: node_item_double_clicked(NodeItem)
.. autoattribute:: node_item_activated(NodeItem)
.. autoattribute:: node_item_hovered(NodeItem)
.. autoattribute:: link_item_hovered(LinkItem)
.. autofunction:: grab_svg
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/document.interactions.rst 0000664 0001750 0001750 00000001644 14625071541 026214 0 ustar 00marko marko ==================================
Interactions (:mod:`interactions`)
==================================
.. automodule:: orangecanvas.document.interactions
.. autoclass:: UserInteraction
:members:
:exclude-members:
started,
finished,
ended,
canceled
:member-order: bysource
:show-inheritance:
.. automethod:: started()
.. automethod:: finished()
.. automethod:: ended()
.. automethod:: canceled()
.. autoclass:: DropAction
:members:
:member-order: bysource
:show-inheritance:
.. autoclass:: DropHandler
:members:
:member-order: bysource
:show-inheritance:
.. autoclass:: DropHandlerAction
:members:
:member-order: bysource
:show-inheritance:
.. autoclass:: NodeFromMimeDataDropHandler
:members:
:member-order: bysource
:show-inheritance:
.. autoclass:: PluginDropHandler
:members:
:member-order: bysource
:show-inheritance:
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/document.quickmenu.rst 0000664 0001750 0001750 00000000753 14625071541 025513 0 ustar 00marko marko =============================
Quick Menu (:mod:`quickmenu`)
=============================
.. automodule:: orangecanvas.document.quickmenu
.. autoclass:: QuickMenu
:members:
:exclude-members:
triggered,
hovered
:member-order: bysource
:show-inheritance:
.. automethod:: triggered(QAction)
.. automethod:: hovered(QAction)
.. autoclass:: MenuPage
:members:
:exclude-members:
title_,
icon_
:member-order: bysource
:show-inheritance:
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/document.rst 0000664 0001750 0001750 00000000305 14625071541 023504 0 ustar 00marko marko =======================
Document (``document``)
=======================
.. automodule:: orangecanvas.document
.. toctree::
document.schemeedit
document.quickmenu
document.interactions
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/document.schemeedit.rst 0000664 0001750 0001750 00000001337 14625071541 025623 0 ustar 00marko marko =================================
Scheme Editor (:mod:`schemeedit`)
=================================
.. automodule:: orangecanvas.document.schemeedit
.. autoclass:: SchemeEditWidget
:members:
:exclude-members:
undoAvailable,
redoAvailable,
modificationChanged,
undoCommandAdded,
selectionChanged,
titleChanged,
pathChanged,
onNewLink
:member-order: bysource
:show-inheritance:
.. autoattribute:: undoAvailable(bool)
.. autoattribute:: redoAvailable(bool)
.. autoattribute:: modificationChanged(bool)
.. autoattribute:: undoCommandAdded()
.. autoattribute:: selectionChanged()
.. autoattribute:: titleChanged()
.. autoattribute:: pathChanged()
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/gui.dock.rst 0000664 0001750 0001750 00000000527 14625071541 023377 0 ustar 00marko marko ==================================
Collapsible Dock Widget (``dock``)
==================================
.. automodule:: orangecanvas.gui.dock
.. autoclass:: orangecanvas.gui.dock.CollapsibleDockWidget
:members:
:member-order: bysource
:show-inheritance:
:exclude-members:
setWidget, animationEnabled, setAnimationEnabled
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/gui.dropshadow.rst 0000664 0001750 0001750 00000000420 14625071541 024621 0 ustar 00marko marko ==================================
Drop Shadow Frame (``dropshadow``)
==================================
.. automodule:: orangecanvas.gui.dropshadow
.. autoclass:: orangecanvas.gui.dropshadow.DropShadowFrame
:members:
:member-order: bysource
:show-inheritance:
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/gui.framelesswindow.rst 0000664 0001750 0001750 00000000473 14625071541 025670 0 ustar 00marko marko =============================================
Frameless Window Widget (``framelesswindow``)
=============================================
.. automodule:: orangecanvas.gui.framelesswindow
.. autoclass:: orangecanvas.gui.framelesswindow.FramelessWindow
:members:
:member-order: bysource
:show-inheritance:
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/gui.lineedit.rst 0000664 0001750 0001750 00000000740 14625071541 024251 0 ustar 00marko marko ===============================
Line Edit Widget (``lineedit``)
===============================
.. automodule:: orangecanvas.gui.lineedit
.. autoclass:: orangecanvas.gui.lineedit.LineEdit
:members:
:member-order: bysource
:exclude-members: triggered, LeftPosition, RightPosition
:show-inheritance:
.. autoattribute:: LeftPosition
Left position flag
.. autoattribute:: RightPosition
Right position flag
.. autoattribute:: triggered(QAction)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/gui.quickhelp.rst 0000664 0001750 0001750 00000000360 14625071541 024437 0 ustar 00marko marko ==========================
Quick Help (``quickhelp``)
==========================
.. automodule:: orangecanvas.gui.quickhelp
.. autoclass:: orangecanvas.gui.quickhelp.QuickHelp
:members:
:member-order: bysource
:show-inheritance:
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/gui.rst 0000664 0001750 0001750 00000000467 14625071541 022463 0 ustar 00marko marko .. gui:
######################
GUI elements (``gui``)
######################
.. automodule:: orangecanvas.gui
.. toctree::
:maxdepth: 1
gui.dock
gui.dropshadow
gui.framelesswindow
gui.lineedit
gui.quickhelp
gui.splashscreen
gui.toolbar
gui.toolbox
gui.toolgrid
gui.tooltree
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/gui.splashscreen.rst 0000664 0001750 0001750 00000000413 14625071541 025143 0 ustar 00marko marko ================================
Splash Screen (``splashscreen``)
================================
.. automodule:: orangecanvas.gui.splashscreen
.. autoclass:: orangecanvas.gui.splashscreen.SplashScreen
:members:
:member-order: bysource
:show-inheritance:
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/gui.stackedwidget.rst 0000664 0001750 0001750 00000001226 14625071541 025276 0 ustar 00marko marko :orphan:
==================================
Stacked Widget (``stackedwidget``)
==================================
.. automodule:: orangecanvas.gui.stackedwidget
.. autoclass:: orangecanvas.gui.stackedwidget.AnimatedStackedWidget
:members:
:member-order: bysource
:show-inheritance:
.. autoattribute:: currentChanged(int)
Current widget has changed
.. autoattribute:: transitionStarted()
Transition animation has started
.. autoattribute:: transitionFinished()
Transition animation has finished
.. autoclass:: orangecanvas.gui.stackedwidget.StackLayout
:members:
:member-order: bysource
:show-inheritance:
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/gui.toolbar.rst 0000664 0001750 0001750 00000000353 14625071541 024116 0 ustar 00marko marko ======================
Tool Bar (``toolbar``)
======================
.. automodule:: orangecanvas.gui.toolbar
.. autoclass:: orangecanvas.gui.toolbar.DynamicResizeToolBar
:members:
:member-order: bysource
:show-inheritance:
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/gui.toolbox.rst 0000664 0001750 0001750 00000000546 14625071541 024146 0 ustar 00marko marko =============================
Tool Box Widget (``toolbox``)
=============================
.. automodule:: orangecanvas.gui.toolbox
.. autoclass:: orangecanvas.gui.toolbox.ToolBox
:members:
:member-order: bysource
:show-inheritance:
.. autoattribute:: tabToggled(index: int, state: bool)
Signal emitted when a tab at `index` is toggled.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/gui.toolgrid.rst 0000664 0001750 0001750 00000000776 14625071541 024310 0 ustar 00marko marko ===============================
Tool Grid Widget (``toolgrid``)
===============================
.. automodule:: orangecanvas.gui.toolgrid
.. autoclass:: orangecanvas.gui.toolgrid.ToolGrid
:members:
:member-order: bysource
:exclude-members:
actionTriggered,
actionHovered
:show-inheritance:
.. autoattribute:: actionTriggered(QAction)
Signal emitted when an action is triggered.
.. autoattribute:: actionHovered(QAction)
Signal emitted when an action is hovered.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/gui.tooltree.rst 0000664 0001750 0001750 00000000716 14625071541 024314 0 ustar 00marko marko ===============================
Tool Tree Widget (``tooltree``)
===============================
.. automodule:: orangecanvas.gui.tooltree
.. autoclass:: orangecanvas.gui.tooltree.ToolTree
:members:
:member-order: bysource
:show-inheritance:
.. autoattribute:: triggered(QAction)
Signal emitted when an action in the widget is triggered.
.. autoattribute:: hovered(QAction)
Signal emitted when an action in the widget is hovered.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/index.rst 0000664 0001750 0001750 00000000272 14625071541 023000 0 ustar 00marko marko #######################
Orange Canvas Reference
#######################
The Orange Canvas API reference
.. toctree::
gui
scheme
registry
canvas
document
application
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/overview.rst 0000664 0001750 0001750 00000004056 14625071541 023543 0 ustar 00marko marko .. _Overview:
Overview
########
.. currentmodule:: orangecanvas
Orange Canvas application is build around the a workflow model (scheme),
which is implemented in the :mod:`~orangecanvas.scheme` package. Briefly
speaking a workflow is a simple graph structure(a Directed Acyclic
Graph - DAG). The nodes in this graph represent some action/task to be
computed. A node in this graph has a set of inputs and outputs on which it
receives and sends objects.
The set of available node types for a workflow are kept in a
(:class:`~orangecanvas.registry.WidgetRegistry`).
:class:`~orangecanvas.registry.WidgetDiscovery` can be used (but not
required) to populate the registry.
Common reusable gui elements used for building the user interface
reside in the :mod:`~orangecanvas.gui` package.
Workflow Model
**************
The workflow model is implemented by :class:`~scheme.scheme.Scheme`.
It is composed by a set of node (:class:`~scheme.node.SchemeNode`)
instances and links (:class:`~scheme.link.SchemeLink`) between them.
Every node has a corresponding :class:`~registry.WidgetDescription`
defining its inputs and outputs (restricting the node's connectivity).
In addition, it can also contain workflow annotations. These are only
used when displaying the workflow in a GUI.
Widget Description
------------------
* :class:`~registry.WidgetDescription`
* :class:`~registry.CategoryDescription`
Workflow Execution
------------------
The runtime execution (propagation of node's outputs to dependent
node inputs) is handled by the signal manager.
* :class:`~scheme.signalmanager.SignalManager`
Workflow Node GUI
-----------------
A WidgetManager is responsible for managing GUI corresponsing to individual
nodes in the workflow.
* :class:`~scheme.widgetmanager.WidgetManager`
Workflow View
*************
* The workflow view (:class:`~canvas.scene.CanvasScene`)
* The workflow editor (:class:`~document.schemeedit.SchemeEditWidget`)
Application
***********
Joining everything together, the final application (main window, ...)
is implemented in :mod:`orangecanvas.application`.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/registry.rst 0000664 0001750 0001750 00000001373 14625071541 023544 0 ustar 00marko marko #######################
Registry (``registry``)
#######################
.. automodule:: orangecanvas.registry
:member-order: bysource
WidgetRegistry
--------------
.. autoclass:: WidgetRegistry
:members:
:member-order: bysource
WidgetDescription
-----------------
.. autoclass:: WidgetDescription
:members:
:member-order: bysource
CategoryDescription
-------------------
.. autoclass:: CategoryDescription
:members:
:member-order: bysource
InputSignal
-----------
.. autoclass:: InputSignal
:members:
:member-order: bysource
OutputSignal
------------
.. autoclass:: OutputSignal
:members:
:member-order: bysource
WidgetDiscovery
---------------
.. autoclass:: WidgetDiscovery
:members:
:member-order: bysource
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/scheme.annotation.rst 0000664 0001750 0001750 00000001260 14625071541 025304 0 ustar 00marko marko .. schemeannotation:
====================================
Scheme Annotations (``annotations``)
====================================
.. automodule:: orangecanvas.scheme.annotations
.. autoclass:: BaseSchemeAnnotation
:members:
:member-order: bysource
:show-inheritance:
.. autoattribute:: geometry_changed()
Signal emitted when the geometry of the annotation changes
.. autoclass:: SchemeArrowAnnotation
:members:
:member-order: bysource
:show-inheritance:
.. autoclass:: SchemeTextAnnotation
:members:
:member-order: bysource
:show-inheritance:
.. autoattribute:: text_changed(str)
Signal emitted when the annotation text changes.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/scheme.events.rst 0000664 0001750 0001750 00000004355 14625071541 024446 0 ustar 00marko marko .. workflow-events:
============================
Workflow Events (``events``)
============================
.. py:currentmodule:: orangecanvas.scheme.events
.. autoclass:: orangecanvas.scheme.events.WorkflowEvent
:show-inheritance:
.. autoattribute:: NodeAdded
:annotation: = QEvent.Type(...)
.. autoattribute:: NodeRemoved
:annotation: = QEvent.Type(...)
.. autoattribute:: LinkAdded
:annotation: = QEvent.Type(...)
.. autoattribute:: LinkRemoved
:annotation: = QEvent.Type(...)
.. autoattribute:: InputLinkAdded
:annotation: = QEvent.Type(...)
.. autoattribute:: OutputLinkAdded
:annotation: = QEvent.Type(...)
.. autoattribute:: InputLinkRemoved
:annotation: = QEvent.Type(...)
.. autoattribute:: OutputLinkRemoved
:annotation: = QEvent.Type(...)
.. autoattribute:: NodeStateChange
:annotation: = QEvent.Type(...)
.. autoattribute:: LinkStateChange
:annotation: = QEvent.Type(...)
.. autoattribute:: InputLinkStateChange
:annotation: = QEvent.Type(...)
.. autoattribute:: OutputLinkStateChange
:annotation: = QEvent.Type(...)
.. autoattribute:: NodeActivateRequest
:annotation: = QEvent.Type(...)
.. autoattribute:: WorkflowEnvironmentChange
:annotation: = QEvent.Type(...)
.. autoattribute:: AnnotationAdded
:annotation: = QEvent.Type(...)
.. autoattribute:: AnnotationRemoved
:annotation: = QEvent.Type(...)
.. autoattribute:: AnnotationChange
:annotation: = QEvent.Type(...)
.. autoattribute:: ActivateParentRequest
:annotation: = QEvent.Type(...)
.. autoclass:: orangecanvas.scheme.events.NodeEvent
:show-inheritance:
.. automethod:: node() -> SchemeNode
.. automethod:: pos() -> int
.. autoclass:: orangecanvas.scheme.events.LinkEvent
:show-inheritance:
.. automethod:: link() -> SchemeLink
.. automethod:: pos() -> int
.. autoclass:: orangecanvas.scheme.events.AnnotationEvent
:show-inheritance:
.. automethod:: annotation() -> BaseSchemeAnnotation
.. automethod:: pos() -> int
.. autoclass:: orangecanvas.scheme.events.WorkflowEnvChanged
:show-inheritance:
.. automethod:: name() -> str
.. automethod:: oldValue() -> Any
.. automethod:: newValue() -> Any
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/scheme.link.rst 0000664 0001750 0001750 00000000613 14625071541 024070 0 ustar 00marko marko .. schemelink:
======================
Scheme Link (``link``)
======================
.. automodule:: orangecanvas.scheme.link
.. autoclass:: SchemeLink
:members:
:exclude-members:
enabled_changed,
dynamic_enabled_changed
:member-order: bysource
:show-inheritance:
.. autoattribute:: enabled_changed(enabled)
.. autoattribute:: dynamic_enabled_changed(enabled)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/scheme.node.rst 0000664 0001750 0001750 00000001030 14625071541 024052 0 ustar 00marko marko .. scheme-node:
======================
Scheme Node (``node``)
======================
.. automodule:: orangecanvas.scheme.node
.. autoclass:: SchemeNode
:members:
:exclude-members:
title_changed,
position_changed,
progress_changed,
processing_state_changed
:member-order: bysource
:show-inheritance:
.. autoattribute:: title_changed(title)
.. autoattribute:: position_changed((x, y))
.. autoattribute:: progress_changed(progress)
.. autoattribute:: processing_state_changed(state)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/scheme.readwrite.rst 0000664 0001750 0001750 00000000301 14625071541 025113 0 ustar 00marko marko .. schemereadwrite:
====================================
Scheme Serialization (``readwrite``)
====================================
.. automodule:: orangecanvas.scheme.readwrite
:members:
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/scheme.rst 0000664 0001750 0001750 00000000427 14625071541 023137 0 ustar 00marko marko .. scheme:
###################
Scheme (``scheme``)
###################
.. automodule:: orangecanvas.scheme
.. toctree::
scheme.scheme
scheme.node
scheme.link
scheme.annotation
scheme.readwrite
scheme.widgetmanager
scheme.signalmanager
scheme.events
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/scheme.scheme.rst 0000664 0001750 0001750 00000002660 14625071541 024403 0 ustar 00marko marko .. scheme:
===================
Scheme (``scheme``)
===================
.. automodule:: orangecanvas.scheme.scheme
.. autoclass:: Scheme
:members:
:exclude-members: runtime_env_changed
:member-order: bysource
:show-inheritance:
.. autoattribute:: title_changed(title)
Signal emitted when the title of scheme changes.
.. autoattribute:: description_changed(description)
Signal emitted when the description of scheme changes.
.. autoattribute:: node_added(node)
Signal emitted when a `node` is added to the scheme.
.. autoattribute:: node_removed(node)
Signal emitted when a `node` is removed from the scheme.
.. autoattribute:: link_added(link)
Signal emitted when a `link` is added to the scheme.
.. autoattribute:: link_removed(link)
Signal emitted when a `link` is removed from the scheme.
.. autoattribute:: annotation_added(annotation)
Signal emitted when a `annotation` is added to the scheme.
.. autoattribute:: annotation_removed(annotation)
Signal emitted when a `annotation` is removed from the scheme.
.. autoattribute:: runtime_env_changed(key: str, newvalue: Optional[str], oldvalue: Optional[str])
.. autoclass:: SchemeCycleError
:show-inheritance:
.. autoclass:: IncompatibleChannelTypeError
:show-inheritance:
.. autoclass:: SinkChannelError
:show-inheritance:
.. autoclass:: DuplicatedLinkError
:show-inheritance:
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/scheme.signalmanager.rst 0000664 0001750 0001750 00000001110 14625071541 025734 0 ustar 00marko marko .. signalmanager:
.. automodule:: orangecanvas.scheme.signalmanager
.. autoclass:: SignalManager
:members:
:member-order: bysource
:exclude-members:
stateChanged,
updatesPending,
processingStarted,
processingFinished,
runtimeStateChanged
:show-inheritance:
.. autoattribute:: stateChanged(State)
.. autoattribute:: updatesPending()
.. autoattribute:: processingStarted(SchemeNode)
.. autoattribute:: processingFinished(SchemeNode)
.. autoattribute:: runtimeStateChanged(RuntimeState)
.. autoclass:: Signal
:members:
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/docs/source/orangecanvas/scheme.widgetmanager.rst 0000664 0001750 0001750 00000001152 14625071541 025750 0 ustar 00marko marko .. widgetmanager:
=================================
WidgetManager (``widgetmanager``)
=================================
.. automodule:: orangecanvas.scheme.widgetmanager
.. autoclass:: WidgetManager
:members:
:exclude-members:
widget_for_node_added, widget_for_node_removed
:member-order: bysource
:show-inheritance:
.. autoattribute:: widget_for_node_added(SchemeNode, QWidget)
Signal emitted when a QWidget was created and added by the manager.
.. autoattribute:: widget_for_node_removed(SchemeNode, QWidget)
Signal emitted when a QWidget was removed and will be deleted.
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1716810829.772581
orange-canvas-core-0.2.1/orange_canvas_core.egg-info/ 0000775 0001750 0001750 00000000000 14625072116 021546 5 ustar 00marko marko ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810829.0
orange-canvas-core-0.2.1/orange_canvas_core.egg-info/PKG-INFO 0000664 0001750 0001750 00000003100 14625072115 022634 0 ustar 00marko marko Metadata-Version: 2.1
Name: orange-canvas-core
Version: 0.2.1
Summary: Core component of Orange Canvas
Home-page: http://orange.biolab.si/
Author: Bioinformatics Laboratory, FRI UL
Author-email: contact@orange.biolab.si
License: GPLv3
Project-URL: Bug Reports, https://github.com/biolab/orange-canvas-core/issues
Project-URL: Source, https://github.com/biolab/orange-canvas-core/
Project-URL: Documentation, https://orange-canvas-core.readthedocs.io/en/latest/
Requires-Python: >=3.6
Description-Content-Type: text/x-rst
Provides-Extra: DOCBUILD
License-File: LICENSE.txt
Orange Canvas Core
==================
.. image:: https://github.com/biolab/orange-canvas-core/workflows/Run%20tests/badge.svg
:target: https://github.com/biolab/orange-canvas-core/actions?query=workflow%3A%22Run+tests%22
:alt: Github Actions CI Build Status
.. image:: https://readthedocs.org/projects/orange-canvas-core/badge/?version=latest
:target: https://orange-canvas-core.readthedocs.io/en/latest/?badge=latest
:alt: Documentation Status
Orange Canvas Core is a framework for building graphical user
interfaces for editing workflows. It is a component used to build
the Orange Canvas (http://orange.biolab.si) data-mining application
(for which it was developed in the first place).
Installation
------------
Orange Canvas Core is pip installable (https://pip.pypa.io/), simply run::
pip install orange-canvas-core
Or use the::
pip install ./
to install from the sources.
Documentation
-------------
Some incomplete documentation is available at https://orange-canvas-core.readthedocs.io
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810829.0
orange-canvas-core-0.2.1/orange_canvas_core.egg-info/SOURCES.txt 0000664 0001750 0001750 00000023262 14625072115 023436 0 ustar 00marko marko LICENSE.txt
MANIFEST.in
README.rst
setup.cfg
setup.py
docs/make.bat
docs/requirements-rtd.txt
docs/source/conf.py
docs/source/index.rst
docs/source/orangecanvas/application.canvasmain.rst
docs/source/orangecanvas/application.rst
docs/source/orangecanvas/application.welcomedialog.rst
docs/source/orangecanvas/canvas.items.annotationitem.rst
docs/source/orangecanvas/canvas.items.linkitem.rst
docs/source/orangecanvas/canvas.items.nodeitem.rst
docs/source/orangecanvas/canvas.rst
docs/source/orangecanvas/canvas.scene.rst
docs/source/orangecanvas/document.interactions.rst
docs/source/orangecanvas/document.quickmenu.rst
docs/source/orangecanvas/document.rst
docs/source/orangecanvas/document.schemeedit.rst
docs/source/orangecanvas/gui.dock.rst
docs/source/orangecanvas/gui.dropshadow.rst
docs/source/orangecanvas/gui.framelesswindow.rst
docs/source/orangecanvas/gui.lineedit.rst
docs/source/orangecanvas/gui.quickhelp.rst
docs/source/orangecanvas/gui.rst
docs/source/orangecanvas/gui.splashscreen.rst
docs/source/orangecanvas/gui.stackedwidget.rst
docs/source/orangecanvas/gui.toolbar.rst
docs/source/orangecanvas/gui.toolbox.rst
docs/source/orangecanvas/gui.toolgrid.rst
docs/source/orangecanvas/gui.tooltree.rst
docs/source/orangecanvas/index.rst
docs/source/orangecanvas/overview.rst
docs/source/orangecanvas/registry.rst
docs/source/orangecanvas/scheme.annotation.rst
docs/source/orangecanvas/scheme.events.rst
docs/source/orangecanvas/scheme.link.rst
docs/source/orangecanvas/scheme.node.rst
docs/source/orangecanvas/scheme.readwrite.rst
docs/source/orangecanvas/scheme.rst
docs/source/orangecanvas/scheme.scheme.rst
docs/source/orangecanvas/scheme.signalmanager.rst
docs/source/orangecanvas/scheme.widgetmanager.rst
orange_canvas_core.egg-info/PKG-INFO
orange_canvas_core.egg-info/SOURCES.txt
orange_canvas_core.egg-info/dependency_links.txt
orange_canvas_core.egg-info/requires.txt
orange_canvas_core.egg-info/top_level.txt
orangecanvas/__init__.py
orangecanvas/__main__.py
orangecanvas/config.py
orangecanvas/main.py
orangecanvas/resources.py
orangecanvas/application/__init__.py
orangecanvas/application/aboutdialog.py
orangecanvas/application/addons.py
orangecanvas/application/application.py
orangecanvas/application/canvasmain.py
orangecanvas/application/canvastooldock.py
orangecanvas/application/examples.py
orangecanvas/application/outputview.py
orangecanvas/application/schemeinfo.py
orangecanvas/application/settings.py
orangecanvas/application/welcomedialog.py
orangecanvas/application/widgettoolbox.py
orangecanvas/application/tests/__init__.py
orangecanvas/application/tests/test_addons.py
orangecanvas/application/tests/test_addons_utils.py
orangecanvas/application/tests/test_application.py
orangecanvas/application/tests/test_canvastooldock.py
orangecanvas/application/tests/test_main.py
orangecanvas/application/tests/test_mainwindow.py
orangecanvas/application/tests/test_outputview.py
orangecanvas/application/tests/test_schemeinfo.py
orangecanvas/application/tests/test_settings.py
orangecanvas/application/tests/test_welcomedialog.py
orangecanvas/application/tests/test_widgettoolbox.py
orangecanvas/application/utils/__init__.py
orangecanvas/application/utils/addons.py
orangecanvas/canvas/__init__.py
orangecanvas/canvas/layout.py
orangecanvas/canvas/scene.py
orangecanvas/canvas/view.py
orangecanvas/canvas/items/__init__.py
orangecanvas/canvas/items/annotationitem.py
orangecanvas/canvas/items/controlpoints.py
orangecanvas/canvas/items/graphicspathobject.py
orangecanvas/canvas/items/graphicstextitem.py
orangecanvas/canvas/items/linkitem.py
orangecanvas/canvas/items/nodeitem.py
orangecanvas/canvas/items/utils.py
orangecanvas/canvas/items/tests/__init__.py
orangecanvas/canvas/items/tests/test_annotationitem.py
orangecanvas/canvas/items/tests/test_controlpoints.py
orangecanvas/canvas/items/tests/test_graphicspathobject.py
orangecanvas/canvas/items/tests/test_graphicstextitem.py
orangecanvas/canvas/items/tests/test_linkitem.py
orangecanvas/canvas/items/tests/test_nodeitem.py
orangecanvas/canvas/items/tests/test_utils.py
orangecanvas/canvas/tests/__init__.py
orangecanvas/canvas/tests/test_layout.py
orangecanvas/canvas/tests/test_scene.py
orangecanvas/canvas/tests/test_view.py
orangecanvas/document/__init__.py
orangecanvas/document/commands.py
orangecanvas/document/editlinksdialog.py
orangecanvas/document/interactions.py
orangecanvas/document/quickmenu.py
orangecanvas/document/schemeedit.py
orangecanvas/document/suggestions.py
orangecanvas/document/usagestatistics.py
orangecanvas/document/tests/__init__.py
orangecanvas/document/tests/test_editlinksdialog.py
orangecanvas/document/tests/test_quickmenu.py
orangecanvas/document/tests/test_schemeedit.py
orangecanvas/document/tests/test_usagestatistics.py
orangecanvas/gui/__init__.py
orangecanvas/gui/dock.py
orangecanvas/gui/dropshadow.py
orangecanvas/gui/framelesswindow.py
orangecanvas/gui/iconengine.py
orangecanvas/gui/iconview.py
orangecanvas/gui/itemmodels.py
orangecanvas/gui/lineedit.py
orangecanvas/gui/quickhelp.py
orangecanvas/gui/splashscreen.py
orangecanvas/gui/stackedwidget.py
orangecanvas/gui/svgiconengine.py
orangecanvas/gui/test.py
orangecanvas/gui/textlabel.py
orangecanvas/gui/toolbar.py
orangecanvas/gui/toolbox.py
orangecanvas/gui/toolgrid.py
orangecanvas/gui/tooltree.py
orangecanvas/gui/utils.py
orangecanvas/gui/windowlistmanager.py
orangecanvas/gui/tests/__init__.py
orangecanvas/gui/tests/test_dock.py
orangecanvas/gui/tests/test_dropshadow.py
orangecanvas/gui/tests/test_framelesswindow.py
orangecanvas/gui/tests/test_iconengine.py
orangecanvas/gui/tests/test_lineedit.py
orangecanvas/gui/tests/test_splashscreen.py
orangecanvas/gui/tests/test_stackedwidget.py
orangecanvas/gui/tests/test_toolbar.py
orangecanvas/gui/tests/test_toolbox.py
orangecanvas/gui/tests/test_toolgrid.py
orangecanvas/gui/tests/test_tooltree.py
orangecanvas/help/__init__.py
orangecanvas/help/intersphinx.py
orangecanvas/help/manager.py
orangecanvas/help/provider.py
orangecanvas/help/tests/__init__.py
orangecanvas/help/tests/test_manager.py
orangecanvas/help/tests/test_provider.py
orangecanvas/icons/Arrow.svg
orangecanvas/icons/Back.svg
orangecanvas/icons/Document Info.svg
orangecanvas/icons/Documentation.svg
orangecanvas/icons/Dropdown.svg
orangecanvas/icons/Examples.svg
orangecanvas/icons/Get Started.svg
orangecanvas/icons/Grid.svg
orangecanvas/icons/Info.svg
orangecanvas/icons/Maximize Toolbar.svg
orangecanvas/icons/Minimize Toolbar.svg
orangecanvas/icons/New.svg
orangecanvas/icons/Open.svg
orangecanvas/icons/Pause.svg
orangecanvas/icons/Recent.svg
orangecanvas/icons/Search.svg
orangecanvas/icons/Text Size.svg
orangecanvas/icons/Tutorials.svg
orangecanvas/icons/YouTube.svg
orangecanvas/icons/arrow-right.svg
orangecanvas/icons/default-category.svg
orangecanvas/icons/default-widget.svg
orangecanvas/icons/orange-canvas-core-splash.svg
orangecanvas/icons/orange-canvas.svg
orangecanvas/icons/orange-splash-screen.png
orangecanvas/preview/__init__.py
orangecanvas/preview/previewbrowser.py
orangecanvas/preview/previewdialog.py
orangecanvas/preview/previewmodel.py
orangecanvas/preview/scanner.py
orangecanvas/preview/tests/__init__.py
orangecanvas/preview/tests/test_previewbrowser.py
orangecanvas/preview/tests/test_previewdialog.py
orangecanvas/preview/tests/test_scanner.py
orangecanvas/registry/__init__.py
orangecanvas/registry/base.py
orangecanvas/registry/cache.py
orangecanvas/registry/description.py
orangecanvas/registry/discovery.py
orangecanvas/registry/qt.py
orangecanvas/registry/utils.py
orangecanvas/registry/tests/__init__.py
orangecanvas/registry/tests/test_base.py
orangecanvas/registry/tests/test_discovery.py
orangecanvas/scheme/__init__.py
orangecanvas/scheme/annotations.py
orangecanvas/scheme/errors.py
orangecanvas/scheme/events.py
orangecanvas/scheme/link.py
orangecanvas/scheme/node.py
orangecanvas/scheme/readwrite.py
orangecanvas/scheme/scheme.py
orangecanvas/scheme/signalmanager.py
orangecanvas/scheme/widgetmanager.py
orangecanvas/scheme/tests/__init__.py
orangecanvas/scheme/tests/test_annotations.py
orangecanvas/scheme/tests/test_links.py
orangecanvas/scheme/tests/test_nodes.py
orangecanvas/scheme/tests/test_readwrite.py
orangecanvas/scheme/tests/test_scheme.py
orangecanvas/scheme/tests/test_signalmanager.py
orangecanvas/scheme/tests/test_widgetmanager.py
orangecanvas/styles/__init__.py
orangecanvas/styles/darkorange.qss
orangecanvas/styles/orange.qss
orangecanvas/styles/orange/Arrow.svg
orangecanvas/styles/orange/Document Info.svg
orangecanvas/styles/orange/Dropdown.svg
orangecanvas/styles/orange/Grid.svg
orangecanvas/styles/orange/Info.svg
orangecanvas/styles/orange/Pause.svg
orangecanvas/styles/orange/Search.svg
orangecanvas/styles/orange/Text Size.svg
orangecanvas/utils/__init__.py
orangecanvas/utils/after_exit.py
orangecanvas/utils/asyncutils.py
orangecanvas/utils/graph.py
orangecanvas/utils/image.py
orangecanvas/utils/markup.py
orangecanvas/utils/overlay.py
orangecanvas/utils/pickle.py
orangecanvas/utils/pkgmeta.py
orangecanvas/utils/propertybindings.py
orangecanvas/utils/qinvoke.py
orangecanvas/utils/qobjref.py
orangecanvas/utils/qtcompat.py
orangecanvas/utils/redirect.py
orangecanvas/utils/settings.py
orangecanvas/utils/shtools.py
orangecanvas/utils/localization/__init__.py
orangecanvas/utils/localization/tests/__init__.py
orangecanvas/utils/localization/tests/test_localization.py
orangecanvas/utils/tests/__init__.py
orangecanvas/utils/tests/test_after_exit.py
orangecanvas/utils/tests/test_graph.py
orangecanvas/utils/tests/test_markup.py
orangecanvas/utils/tests/test_overlay.py
orangecanvas/utils/tests/test_pkgmeta.py
orangecanvas/utils/tests/test_propertybindings.py
orangecanvas/utils/tests/test_qinvoke.py
orangecanvas/utils/tests/test_qobjref.py
orangecanvas/utils/tests/test_resources.py
orangecanvas/utils/tests/test_settings.py
orangecanvas/utils/tests/test_shtools.py
orangecanvas/utils/tests/test_utils.py ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810829.0
orange-canvas-core-0.2.1/orange_canvas_core.egg-info/dependency_links.txt 0000664 0001750 0001750 00000000001 14625072115 025613 0 ustar 00marko marko
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810829.0
orange-canvas-core-0.2.1/orange_canvas_core.egg-info/requires.txt 0000664 0001750 0001750 00000000366 14625072115 024152 0 ustar 00marko marko AnyQt>=0.2.0
docutils
commonmark>=0.8.1
requests
requests-cache
pip>=18.0
dictdiffer
qasync>=0.10.0
packaging
numpy
[:python_version < "3.10"]
importlib_metadata
[:python_version < "3.9"]
importlib_resources
[DOCBUILD]
sphinx
sphinx-rtd-theme
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810829.0
orange-canvas-core-0.2.1/orange_canvas_core.egg-info/top_level.txt 0000664 0001750 0001750 00000000015 14625072115 024273 0 ustar 00marko marko orangecanvas
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1716810829.772581
orange-canvas-core-0.2.1/orangecanvas/ 0000775 0001750 0001750 00000000000 14625072116 016705 5 ustar 00marko marko ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/__init__.py 0000664 0001750 0001750 00000000000 14625071541 021005 0 ustar 00marko marko ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/__main__.py 0000664 0001750 0001750 00000000150 14625071541 020774 0 ustar 00marko marko import sys
from orangecanvas.main import main
if __name__ == "__main__":
sys.exit(main(sys.argv))
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1716810829.7765813
orange-canvas-core-0.2.1/orangecanvas/application/ 0000775 0001750 0001750 00000000000 14625072116 021210 5 ustar 00marko marko ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/__init__.py 0000664 0001750 0001750 00000000100 14625071541 023311 0 ustar 00marko marko """
Main Orange Canvas Application and supporting classes.
"""
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/aboutdialog.py 0000664 0001750 0001750 00000002614 14625071541 024060 0 ustar 00marko marko """
Application about dialog.
-------------------------
"""
import sys
from xml.sax.saxutils import escape
from AnyQt.QtWidgets import (
QDialog, QDialogButtonBox, QVBoxLayout, QLabel, QApplication
)
from AnyQt.QtCore import Qt
from .. import config
ABOUT_TEMPLATE = """\
{name}
Version: {version}
"""
class AboutDialog(QDialog):
def __init__(self, parent=None, **kwargs):
super().__init__(parent, **kwargs)
if sys.platform == "darwin":
self.setAttribute(Qt.WA_MacSmallSize, True)
self.__setupUi()
def __setupUi(self):
layout = QVBoxLayout()
label = QLabel(self)
pixmap, _ = config.splash_screen()
label.setPixmap(pixmap)
layout.addWidget(label, Qt.AlignCenter)
name = QApplication.applicationName()
version = QApplication.applicationVersion()
text = ABOUT_TEMPLATE.format(
name=escape(name),
version=escape(version),
)
# TODO: Also list all known add-on versions??.
text_label = QLabel(text)
layout.addWidget(text_label, Qt.AlignCenter)
buttons = QDialogButtonBox(
QDialogButtonBox.Close, Qt.Horizontal, self)
layout.addWidget(buttons)
buttons.rejected.connect(self.accept)
layout.setSizeConstraint(QVBoxLayout.SetFixedSize)
self.setLayout(layout)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/addons.py 0000664 0001750 0001750 00000105317 14625071541 023042 0 ustar 00marko marko import sys
import os
import logging
import traceback
import typing
from xml.sax.saxutils import escape
from concurrent.futures import ThreadPoolExecutor, Future
from typing import List, Any, Optional, Tuple
from packaging.requirements import Requirement
from AnyQt.QtWidgets import (
QDialog, QLineEdit, QTreeView, QHeaderView,
QTextBrowser, QDialogButtonBox, QProgressDialog, QVBoxLayout,
QPushButton, QFormLayout, QHBoxLayout, QMessageBox,
QStyledItemDelegate, QStyle, QApplication, QStyleOptionViewItem,
QShortcut
)
from AnyQt.QtGui import (
QStandardItemModel, QStandardItem, QTextOption, QDropEvent, QDragEnterEvent,
QKeySequence
)
from AnyQt.QtCore import (
QSortFilterProxyModel, QItemSelectionModel,
Qt, QSize, QTimer, QThread, QEvent, QAbstractItemModel, QModelIndex,
)
from AnyQt.QtCore import pyqtSignal as Signal, pyqtSlot as Slot
from AnyQt import sip
from orangecanvas.application.utils.addons import (
Installed,
prettify_name,
is_updatable,
Available,
Install,
Upgrade,
Uninstall,
installable_items,
list_available_versions,
Installable,
Item,
query_pypi,
get_meta_from_archive,
Installer,
)
from orangecanvas.utils import name_lookup, markup, qualified_name, enum_as_int
from ..utils.pkgmeta import get_dist_meta
from ..utils.qinvoke import qinvoke
from ..gui.utils import message_warning, message_critical as message_error
from .. import config
from ..config import Config
from ..utils.pkgmeta import Distribution
log = logging.getLogger(__name__)
HasConstraintRole = Qt.UserRole + 0xf45
DetailedText = HasConstraintRole + 1
def description_rich_text(item): # type: (Item) -> str
if isinstance(item, Installed):
remote, dist = item.installable, item.local
if remote is None:
meta = get_dist_meta(dist)
description = meta.get("Description", "") or \
meta.get('Summary', "")
content_type = meta.get("Description-Content-Type")
else:
description = remote.description
content_type = remote.description_content_type
else:
description = item.installable.description
content_type = item.installable.description_content_type
if not content_type:
# if not defined try rst and fallback to plain text
content_type = "text/x-rst"
try:
html = markup.render_as_rich_text(description, content_type)
except Exception:
html = markup.render_as_rich_text(description, "text/plain")
return html
class ActionItem(QStandardItem):
def data(self, role=Qt.UserRole + 1) -> Any:
if role == Qt.DisplayRole:
model = self.model()
modelindex = self._sibling(PluginsModel.StateColumn)
item = model.data(modelindex, Qt.UserRole)
state = model.data(modelindex, Qt.CheckStateRole)
flags = model.flags(modelindex)
if flags & Qt.ItemIsUserTristate and state == Qt.Checked:
return "Update"
elif isinstance(item, Available) and state == Qt.Checked:
return "Install"
elif isinstance(item, Installed) and state == Qt.Unchecked:
return "Uninstall"
else:
return ""
elif role == DetailedText:
item = self.data(Qt.UserRole)
if isinstance(item, (Available, Installed)):
return description_rich_text(item)
return super().data(role)
def _sibling(self, column) -> QModelIndex:
model = self.model()
if model is None:
return QModelIndex()
index = model.indexFromItem(self)
return index.sibling(self.row(), column)
def _siblingData(self, column: int, role: int):
return self._sibling(column).data(role)
class StateItem(QStandardItem):
def setData(self, value: Any, role: int = Qt.UserRole + 1) -> None:
if role == Qt.CheckStateRole:
super().setData(value, role)
# emit the dependent ActionColumn's data changed
sib = self.index().sibling(self.row(), PluginsModel.ActionColumn)
if sib.isValid():
self.model().dataChanged.emit(sib, sib, (Qt.DisplayRole,))
return
return super().setData(value, role)
def data(self, role=Qt.UserRole + 1):
if role == DetailedText:
item = self.data(Qt.UserRole)
if isinstance(item, (Available, Installed)):
return description_rich_text(item)
return super().data(role)
class PluginsModel(QStandardItemModel):
StateColumn, NameColumn, VersionColumn, ActionColumn = range(4)
def __init__(self, parent=None, **kwargs):
super().__init__(parent, **kwargs)
self.setHorizontalHeaderLabels(
["", self.tr("Name"), self.tr("Version"), self.tr("Action")]
)
@staticmethod
def createRow(item):
# type: (Item) -> List[QStandardItem]
dist = None # type: Optional[Distribution]
if isinstance(item, Installed):
installed = True
ins, dist = item.installable, item.local
name = prettify_name(dist.name)
summary = get_dist_meta(dist).get("Summary", "")
version = dist.version
item_is_core = item.required
else:
installed = False
ins = item.installable
dist = None
name = prettify_name(ins.name)
summary = ins.summary
version = ins.version
item_is_core = False
updatable = is_updatable(item)
item1 = StateItem()
item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable |
Qt.ItemIsUserCheckable |
(Qt.ItemIsUserTristate if updatable else Qt.NoItemFlags))
item1.setEnabled(not (item_is_core and not updatable))
item1.setData(item_is_core, HasConstraintRole)
if installed and updatable:
item1.setCheckState(Qt.PartiallyChecked)
elif installed:
item1.setCheckState(Qt.Checked)
else:
item1.setCheckState(Qt.Unchecked)
item1.setData(item, Qt.UserRole)
item2 = QStandardItem(name)
item2.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
item2.setToolTip(summary)
item2.setData(item, Qt.UserRole)
if updatable:
assert dist is not None
assert ins is not None
comp = "<" if not ins.force else "->"
version = "{} {} {}".format(dist.version, comp, ins.version)
item3 = QStandardItem(version)
item3.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
item4 = ActionItem()
item4.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
return [item1, item2, item3, item4]
def itemState(self):
# type: () -> List['Action']
"""
Return the current `items` state encoded as a list of actions to be
performed.
Return
------
actions : List['Action']
For every item that is has been changed in the GUI interface
return a tuple of (command, item) where Command is one of
`Install`, `Uninstall`, `Upgrade`.
"""
steps = []
for i in range(self.rowCount()):
modelitem = self.item(i, 0)
item = modelitem.data(Qt.UserRole)
state = modelitem.checkState()
if modelitem.flags() & Qt.ItemIsUserTristate and state == Qt.Checked:
steps.append((Upgrade, item))
elif isinstance(item, Available) and state == Qt.Checked:
steps.append((Install, item))
elif isinstance(item, Installed) and state == Qt.Unchecked:
steps.append((Uninstall, item))
return steps
def setItemState(self, steps):
# type: (List['Action']) -> None
"""
Set the current state as a list of actions to perform.
i.e. `w.setItemState([(Install, item1), (Uninstall, item2)])`
will mark item1 for installation and item2 for uninstallation, all
other items will be reset to their default state
Parameters
----------
steps : List[Tuple[Command, Item]]
State encoded as a list of commands.
"""
if self.rowCount() == 0:
return
for row in range(self.rowCount()):
modelitem = self.item(row, 0) # type: QStandardItem
item = modelitem.data(Qt.UserRole) # type: Item
# Find the action command in the steps list for the item
cmd = None # type: Optional[Command]
for cmd_, item_ in steps:
if item == item_:
cmd = cmd_
break
if isinstance(item, Available):
modelitem.setCheckState(
Qt.Checked if cmd == Install else Qt.Unchecked
)
elif isinstance(item, Installed):
if cmd == Upgrade:
modelitem.setCheckState(Qt.Checked)
elif cmd == Uninstall:
modelitem.setCheckState(Qt.Unchecked)
elif is_updatable(item):
modelitem.setCheckState(Qt.PartiallyChecked)
else:
modelitem.setCheckState(Qt.Checked)
else:
assert False
class TristateCheckItemDelegate(QStyledItemDelegate):
"""
A QStyledItemDelegate with customizable Qt.CheckStateRole state toggle
on user interaction.
"""
def editorEvent(self, event, model, option, index):
# type: (QEvent, QAbstractItemModel, QStyleOptionViewItem, QModelIndex) -> bool
"""
Reimplemented.
"""
flags = model.flags(index)
if not flags & Qt.ItemIsUserCheckable or \
not option.state & QStyle.State_Enabled or \
not flags & Qt.ItemIsEnabled:
return False
checkstate = model.data(index, Qt.CheckStateRole)
if checkstate is None:
return False
widget = option.widget
style = widget.style() if widget is not None else QApplication.style()
if event.type() in {QEvent.MouseButtonPress, QEvent.MouseButtonRelease,
QEvent.MouseButtonDblClick}:
pos = event.pos()
opt = QStyleOptionViewItem(option)
self.initStyleOption(opt, index)
rect = style.subElementRect(
QStyle.SE_ItemViewItemCheckIndicator, opt, widget)
if event.button() != Qt.LeftButton or not rect.contains(pos):
return False
if event.type() in {QEvent.MouseButtonPress,
QEvent.MouseButtonDblClick}:
return True
elif event.type() == QEvent.KeyPress:
if event.key() != Qt.Key_Space and event.key() != Qt.Key_Select:
return False
else:
return False
checkstate = self.nextCheckState(checkstate, index)
return model.setData(index, checkstate, Qt.CheckStateRole)
def nextCheckState(self, state, index):
# type: (Qt.CheckState, QModelIndex) -> Qt.CheckState
"""
Return the next check state for index.
"""
constraint = index.data(HasConstraintRole)
flags = index.flags()
if flags & Qt.ItemIsUserTristate and constraint:
return Qt.PartiallyChecked if state == Qt.Checked else Qt.Checked
elif flags & Qt.ItemIsUserTristate:
return Qt.CheckState((enum_as_int(state) + 1) % 3)
else:
return Qt.Unchecked if state == Qt.Checked else Qt.Checked
class AddonManagerDialog(QDialog):
"""
A add-on manager dialog.
"""
#: cached packages list.
__packages = None # type: List[Installable]
__f_pypi_addons = None
__config = None # type: Optional[Config]
stateChanged = Signal()
def __init__(self, parent=None, acceptDrops=True, *,
enableFilterAndAdd=True, **kwargs):
super().__init__(parent, acceptDrops=acceptDrops, **kwargs)
layout = QVBoxLayout()
self.setLayout(layout)
self.__tophlayout = tophlayout = QHBoxLayout(
objectName="top-hbox-layout"
)
tophlayout.setContentsMargins(0, 0, 0, 0)
self.__search = QLineEdit(
objectName="filter-edit",
placeholderText=self.tr("Filter...")
)
self.__addmore = QPushButton(
self.tr("Add more..."),
toolTip=self.tr("Add an add-on not listed below"),
autoDefault=False
)
self.__view = view = QTreeView(
objectName="add-ons-view",
rootIsDecorated=False,
editTriggers=QTreeView.NoEditTriggers,
selectionMode=QTreeView.SingleSelection,
alternatingRowColors=True
)
view.setItemDelegateForColumn(0, TristateCheckItemDelegate(view))
self.__details = QTextBrowser(
objectName="description-text-area",
readOnly=True,
lineWrapMode=QTextBrowser.WidgetWidth,
openExternalLinks=True,
)
self.__details.setWordWrapMode(QTextOption.WordWrap)
self.__buttons = buttons = QDialogButtonBox(
orientation=Qt.Horizontal,
standardButtons=QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
)
self.__model = model = PluginsModel()
model.dataChanged.connect(self.__data_changed)
proxy = QSortFilterProxyModel(
filterKeyColumn=1,
filterCaseSensitivity=Qt.CaseInsensitive
)
proxy.setSourceModel(model)
self.__search.textChanged.connect(proxy.setFilterFixedString)
view.setModel(proxy)
view.selectionModel().selectionChanged.connect(
self.__update_details
)
header = self.__view.header()
header.setSectionResizeMode(0, QHeaderView.Fixed)
header.setSectionResizeMode(2, QHeaderView.ResizeToContents)
self.__addmore.clicked.connect(self.__run_add_package_dialog)
buttons.accepted.connect(self.__accepted)
buttons.rejected.connect(self.reject)
tophlayout.addWidget(self.__search)
tophlayout.addWidget(self.__addmore)
layout.addLayout(tophlayout)
layout.addWidget(self.__view)
layout.addWidget(self.__details)
layout.addWidget(self.__buttons)
self.__progress = None # type: Optional[QProgressDialog]
self.__executor = ThreadPoolExecutor(max_workers=1)
# The installer thread
self.__thread = None
# The installer object
self.__installer = None
self.__add_package_by_name_dialog = None # type: Optional[QDialog]
sh = QShortcut(QKeySequence.Find, self.__search)
sh.activated.connect(self.__search.setFocus)
self.__updateTopLayout(enableFilterAndAdd)
def sizeHint(self):
return super().sizeHint().expandedTo(QSize(620, 540))
def __updateTopLayout(self, enabled):
layout = self.__tophlayout
if not enabled and layout.parentWidget() is self:
for i in range(layout.count()):
item = layout.itemAt(i)
if item.widget() is not None:
item.widget().hide()
self.layout().removeItem(layout)
elif enabled and layout.parentWidget() is not self:
for i in range(layout.count()):
item = layout.itemAt(i)
if item.widget() is not None:
item.widget().show()
self.layout().insertLayout(0, layout)
def __data_changed(
self, topleft: QModelIndex, bottomright: QModelIndex, roles=()
) -> None:
if topleft.column() <= 0 <= bottomright.column():
if roles and Qt.CheckStateRole in roles:
self.stateChanged.emit()
else:
self.stateChanged.emit()
def __update_details(self):
selmodel = self.__view.selectionModel()
idcs = selmodel.selectedRows(PluginsModel.StateColumn)
if idcs:
text = idcs[0].data(DetailedText)
if not isinstance(text, str):
text = ""
else:
text = ""
self.__details.setText(text)
def setConfig(self, config):
self.__config = config
def config(self):
# type: () -> Config
if self.__config is None:
return config.default
else:
return self.__config
@Slot()
def start(self, config):
# type: (Config) -> None
"""
Initialize the dialog/manager for the specified configuration namespace.
Calling this method will start an async query of ...
At the end the found items will be set using `setItems` overriding any
previously set items.
Parameters
----------
config : config.Config
"""
self.__config = config
if self.__packages is not None:
# method_queued(self.setItems, (object,))(self.__packages)
installed = [ep.dist for ep in config.addon_entry_points()
if ep.dist is not None]
items = installable_items(self.__packages, installed)
self.setItems(items)
return
progress = self.progressDialog()
self.show()
progress.show()
progress.setLabelText(
self.tr("Retrieving package list")
)
self.__f_pypi_addons = self.__executor.submit(
lambda config=config: (config, list_available_versions(config)),
)
self.__f_pypi_addons.add_done_callback(
qinvoke(self.__on_query_done, context=self)
)
@Slot(object)
def __on_query_done(self, f):
# type: (Future[Tuple[Config, List[Installable]]]) -> None
assert f.done()
if self.__progress is not None:
self.__progress.hide()
def network_warning(exc):
etype, tb = type(exc), exc.__traceback__
log.error(
"Error fetching package list",
exc_info=(etype, exc, tb)
)
message_warning(
"There's an issue with the internet connection.",
title="Error",
informative_text=
"Please check you are connected to the internet.\n\n"
"If you are behind a proxy, please set it in Preferences "
"- Network.",
details=
"".join(traceback.format_exception(etype, exc, tb)),
parent=self
)
if f.exception() is not None:
exc = typing.cast(BaseException, f.exception())
network_warning(exc)
self.__f_pypi_addons = None
return
config, (packages, exc) = f.result()
if len(exc):
network_warning(exc[0])
assert all(isinstance(p, Installable) for p in packages)
AddonManagerDialog.__packages = packages
installed = [ep.dist for ep in config.addon_entry_points()
if ep.dist is not None]
items = installable_items(packages, installed)
core_constraints = {
r.name.casefold(): r
for r in map(Requirement, config.core_packages())
}
def constrain(item): # type: (Item) -> Item
"""Include constraint in Installed when in core_constraint"""
if isinstance(item, Installed):
name = item.local.name.casefold()
if name in core_constraints:
return item._replace(
required=True, constraint=core_constraints[name]
)
return item
self.setItems([constrain(item) for item in items])
@Slot(object)
def setItems(self, items):
# type: (List[Item]) -> None
"""
Set items
Parameters
----------
items: List[Items]
"""
model = self.__model
model.setRowCount(0)
for item in items:
row = model.createRow(item)
model.appendRow(row)
self.__view.resizeColumnToContents(0)
self.__view.setColumnWidth(
1, max(150, self.__view.sizeHintForColumn(1))
)
if self.__view.model().rowCount():
self.__view.selectionModel().select(
self.__view.model().index(0, 0),
QItemSelectionModel.Select | QItemSelectionModel.Rows
)
self.stateChanged.emit()
def items(self) -> List[Item]:
"""
Return a list of items.
Return
------
items: List[Item]
"""
model = self.__model
data, index = model.data, model.index
return [data(index(i, 1), Qt.UserRole) for i in range(model.rowCount())]
def itemState(self) -> List['Action']:
"""
Return the current `items` state encoded as a list of actions to be
performed.
Return
------
actions : List['Action']
For every item that is has been changed in the GUI interface
return a tuple of (command, item) where Command is one of
`Install`, `Uninstall`, `Upgrade`.
"""
return self.__model.itemState()
def setItemState(self, steps: List['Action']) -> None:
"""
Set the current state as a list of actions to perform.
i.e. `w.setItemState([(Install, item1), (Uninstall, item2)])`
will mark item1 for installation and item2 for uninstallation, all
other items will be reset to their default state.
Parameters
----------
steps : List[Tuple[Command, Item]]
State encoded as a list of commands.
"""
self.__model.setItemState(steps)
def runQueryAndAddResults(
self, names: List[str]
) -> 'Future[List[_QueryResult]]':
"""
Run a background query for the specified names and add results to
the model.
Parameters
----------
names: List[str]
List of package names to query.
"""
f = self.__executor.submit(query_pypi, names)
f.add_done_callback(
qinvoke(self.__on_add_query_finish, context=self)
)
progress = self.progressDialog()
progress.setLabelText("Running query")
progress.setMinimumDuration(1000)
# make sure self is also visible, when progress dialog is, so it is
# clear from where it came.
self.show()
progress.show()
f.add_done_callback(
qinvoke(lambda f: progress.hide(), context=progress)
)
return f
@Slot(object)
def addInstallable(self, installable):
# type: (Installable) -> None
"""
Add/append a single Installable item.
Parameters
----------
installable: Installable
"""
items = self.items()
installed = [ep.dist for ep in self.config().addon_entry_points()]
new_ = installable_items([installable], filter(None, installed))
def match(item):
# type: (Item) -> bool
if isinstance(item, Available):
return item.installable.name == installable.name
elif item.installable is not None:
return item.installable.name == installable.name
else:
return item.local.name.lower() == installable.name.lower()
new = next(filter(match, new_), None)
assert new is not None
state = self.itemState()
replace = next(filter(match, items), None)
if replace is not None:
items[items.index(replace)] = new
self.setItems(items)
# the state for the replaced item will be removed by setItemState
else:
self.setItems(items + [new])
self.setItemState(state) # restore state
def addItems(self, items: List[Item]):
state = self.itemState()
items = self.items() + items
self.setItems(items)
self.setItemState(state) # restore state
def __run_add_package_dialog(self):
self.__add_package_by_name_dialog = dlg = QDialog(
self, windowTitle="Add add-on by name",
)
dlg.setAttribute(Qt.WA_DeleteOnClose)
vlayout = QVBoxLayout()
form = QFormLayout()
form.setContentsMargins(0, 0, 0, 0)
nameentry = QLineEdit(
placeholderText="Package name",
toolTip="Enter a package name as displayed on "
"PyPI (capitalization is not important)")
nameentry.setMinimumWidth(250)
form.addRow("Name:", nameentry)
vlayout.addLayout(form)
buttons = QDialogButtonBox(
standardButtons=QDialogButtonBox.Ok | QDialogButtonBox.Cancel
)
okb = buttons.button(QDialogButtonBox.Ok)
okb.setEnabled(False)
okb.setText("Add")
def changed(name):
okb.setEnabled(bool(name))
nameentry.textChanged.connect(changed)
vlayout.addWidget(buttons)
vlayout.setSizeConstraint(QVBoxLayout.SetFixedSize)
dlg.setLayout(vlayout)
def query():
name = nameentry.text()
okb.setDisabled(True)
self.runQueryAndAddResults([name])
dlg.accept()
buttons.accepted.connect(query)
buttons.rejected.connect(dlg.reject)
dlg.exec()
@Slot(str, str)
def __show_error_for_query(self, text, error_details):
message_error(text, title="Error", details=error_details)
@Slot(object)
def __on_add_query_finish(self, f):
# type: (Future[List[_QueryResult]]) -> None
error_text = ""
error_details = ""
result = None
try:
result = f.result()
except Exception:
log.error("Query error:", exc_info=True)
error_text = "Failed to query package index"
error_details = traceback.format_exc()
else:
not_found = [r.queryname for r in result if r.installable is None]
if not_found:
error_text = "".join([
"The following packages were not found:
",
*["
{}
".format(escape(n)) for n in not_found],
"
"
])
if result:
for r in result:
if r.installable is not None:
self.addInstallable(r.installable)
if error_text:
self.__show_error_for_query(error_text, error_details)
def progressDialog(self):
# type: () -> QProgressDialog
if self.__progress is None:
self.__progress = QProgressDialog(
self,
minimum=0, maximum=0,
labelText=self.tr("Retrieving package list"),
sizeGripEnabled=False,
windowTitle="Progress"
)
self.__progress.setWindowModality(Qt.WindowModal)
self.__progress.hide()
self.__progress.canceled.connect(self.reject)
return self.__progress
def done(self, retcode):
super().done(retcode)
if self.__thread is not None:
self.__thread.quit()
self.__thread = None
def closeEvent(self, event):
super().closeEvent(event)
if self.__thread is not None:
self.__thread.quit()
self.__thread = None
ADDON_EXTENSIONS = ('.zip', '.whl', '.tar.gz')
def dragEnterEvent(self, event):
# type: (QDragEnterEvent) -> None
"""Reimplemented."""
urls = event.mimeData().urls()
if any(url.toLocalFile().endswith(self.ADDON_EXTENSIONS)
for url in urls):
event.acceptProposedAction()
def dropEvent(self, event):
# type: (QDropEvent) -> None
"""
Reimplemented.
Allow dropping add-ons (zip or wheel archives) on this dialog to
install them.
"""
packages = []
names = []
for url in event.mimeData().urls():
path = url.toLocalFile()
if path.endswith(self.ADDON_EXTENSIONS):
meta = get_meta_from_archive(path) or {}
name = meta.get("Name", os.path.basename(path))
vers = meta.get("Version", "")
summary = meta.get("Summary", "")
descr = meta.get("Description", "")
content_type = meta.get("Description-Content-Type", None)
requirements = meta.get("Requires-Dist", "")
names.append(name)
packages.append(
Installable(name, vers, summary,
descr or summary, path, [path], requirements,
content_type, True)
)
for installable in packages:
self.addInstallable(installable)
items = self.items()
# lookup items for the new entries
new_items = [item for item in items if item.installable in packages]
state_new = [(Install, item) if isinstance(item, Available) else
(Upgrade, item) for item in new_items]
state = self.itemState()
self.setItemState(state + state_new)
event.acceptProposedAction()
def __accepted(self):
steps = self.itemState()
# warn about implicit upgrades of required core packages
core_required = {}
for item in self.items():
if isinstance(item, Installed) and item.required:
core_required[item.local.name] = item.local.version
core_upgrade = set()
for step in steps:
if step[0] in [Upgrade, Install]:
inst = step[1].installable
if inst.name in core_required: # direct upgrade of a core package
core_upgrade.add(inst.name)
if inst.requirements: # indirect upgrade of a core package as a requirement
for req in map(Requirement, inst.requirements):
if req.name in core_required and not req.specifier.contains(core_required[req.name], prereleases=True):
core_upgrade.add(req.name) # current doesn't meet requirements
if core_upgrade:
icon = QMessageBox.Warning
buttons = QMessageBox.Ok | QMessageBox.Cancel
title = "Warning"
text = "This action will upgrade some core packages:\n"
text += "\n".join(sorted(core_upgrade))
msg_box = QMessageBox(icon, title, text, buttons, self)
msg_box.setInformativeText("Do you want to continue?")
msg_box.setDefaultButton(QMessageBox.Ok)
if msg_box.exec() != QMessageBox.Ok:
steps = []
if steps:
# Move all uninstall steps to the front
steps = sorted(
steps, key=lambda step: 0 if step[0] == Uninstall else 1
)
self.__installer = Installer(steps=steps)
self.__thread = QThread(
objectName=qualified_name(type(self)) + "::InstallerThread",
)
# transfer ownership to c++; the instance is (deferred) deleted
# from the finished signal (keep alive until then).
sip.transferto(self.__thread, None)
self.__thread.finished.connect(self.__thread.deleteLater)
self.__installer.moveToThread(self.__thread)
self.__installer.finished.connect(self.__on_installer_finished)
self.__installer.error.connect(self.__on_installer_error)
self.__thread.start()
progress = self.progressDialog()
self.__installer.installStatusChanged.connect(progress.setLabelText)
progress.show()
progress.setLabelText("Installing")
self.__installer.start()
else:
self.accept()
def __on_installer_finished_common(self):
if self.__progress is not None:
self.__progress.close()
self.__progress = None
if self.__thread is not None:
self.__thread.quit()
self.__thread = None
def __on_installer_error(self, command, pkg, retcode, output):
self.__on_installer_finished_common()
message_error(
"An error occurred while running a subprocess", title="Error",
informative_text="{} exited with non zero status.".format(command),
details="".join(output),
parent=self
)
self.reject()
def __on_installer_finished(self):
self.__on_installer_finished_common()
name = QApplication.applicationName() or 'Orange'
def message_restart(parent):
icon = QMessageBox.Information
buttons = QMessageBox.Ok | QMessageBox.Cancel
title = 'Information'
text = ('{} needs to be restarted for the changes to take effect.'
.format(name))
msg_box = QMessageBox(icon, title, text, buttons, parent)
msg_box.setDefaultButton(QMessageBox.Ok)
msg_box.setInformativeText('Press OK to restart {} now.'
.format(name))
msg_box.button(QMessageBox.Cancel).setText('Close later')
return msg_box.exec()
if QMessageBox.Ok == message_restart(self):
self.accept()
def restart():
quit_temp_val = QApplication.quitOnLastWindowClosed()
QApplication.setQuitOnLastWindowClosed(False)
QApplication.closeAllWindows()
windows = QApplication.topLevelWindows()
if any(w.isVisible() for w in windows): # if a window close was cancelled
QApplication.setQuitOnLastWindowClosed(quit_temp_val)
QMessageBox(
text="Restart Cancelled",
informativeText="Changes will be applied on {}'s next restart"
.format(name),
icon=QMessageBox.Information
).exec()
else:
QApplication.exit(96)
QTimer.singleShot(0, restart)
else:
self.reject()
def main(argv=None): # noqa
import argparse
from AnyQt.QtWidgets import QApplication
app = QApplication(argv if argv is not None else [])
argv = app.arguments()
parser = argparse.ArgumentParser()
parser.add_argument(
"--config", metavar="CLASSNAME",
default="orangecanvas.config.default",
help="The configuration namespace to use"
)
args = parser.parse_args(argv[1:])
config_ = name_lookup(args.config)
config_ = config_()
config_.init()
config.set_default(config_)
dlg = AddonManagerDialog()
dlg.start(config_)
dlg.show()
dlg.raise_()
return app.exec()
if __name__ == "__main__":
sys.exit(main(sys.argv))
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/application.py 0000664 0001750 0001750 00000022737 14625071541 024101 0 ustar 00marko marko """
"""
import atexit
import sys
import os
import argparse
import logging
from typing import Optional, List, Sequence
import AnyQt
from AnyQt.QtWidgets import QApplication
from AnyQt.QtGui import QPixmapCache
from AnyQt.QtCore import (
Qt, QUrl, QEvent, QSettings, QLibraryInfo, pyqtSignal as Signal,
QT_VERSION_INFO
)
from orangecanvas.utils.after_exit import run_after_exit
from orangecanvas.utils.asyncutils import get_event_loop
from orangecanvas.gui.utils import macos_set_nswindow_tabbing
def fix_qt_plugins_path():
"""
Attempt to fix qt plugins path if it is invalid.
https://www.riverbankcomputing.com/pipermail/pyqt/2018-November/041089.html
"""
# PyQt5 loads a runtime generated qt.conf file into qt's resource system
# but does not correctly (INI) encode non-latin1 characters in paths
# (https://www.riverbankcomputing.com/pipermail/pyqt/2018-November/041089.html)
# Need to be careful not to mess the plugins path when not installed as
# a (delocated) wheel.
s = QSettings(":qt/etc/qt.conf", QSettings.IniFormat)
path = s.value("Paths/Prefix", type=str)
# does the ':qt/etc/qt.conf' exist and has prefix path that does not exist
if path and os.path.exists(path):
return
# Use QLibraryInfo.location to resolve the plugins dir
pluginspath = QLibraryInfo.path(QLibraryInfo.PluginsPath)
# Check effective library paths. Someone might already set the search
# paths (including via QT_PLUGIN_PATH). QApplication.libraryPaths() returns
# existing paths only.
paths = QApplication.libraryPaths()
if paths:
return
if AnyQt.USED_API == "pyqt5":
import PyQt5.QtCore as qc
if AnyQt.USED_API == "pyqt6":
import PyQt6.QtCore as qc
elif AnyQt.USED_API == "pyside2":
import PySide2.QtCore as qc
elif AnyQt.USED_API == "pyside6":
import PySide6.QtCore as qc
else:
return
def normpath(path):
return os.path.normcase(os.path.normpath(path))
# guess the appropriate path relative to the installation dir based on the
# PyQt5 installation dir and the 'recorded' plugins path. I.e. match the
# 'PyQt5' directory name in the recorded path and replace the 'invalid'
# prefix with the real PyQt5 install dir.
def maybe_match_prefix(prefix: str, path: str) -> Optional[str]:
"""
>>> maybe_match_prefix("aa/bb/cc", "/a/b/cc/a/b")
"aa/bb/cc/a/b"
>>> maybe_match_prefix("aa/bb/dd", "/a/b/cc/a/b")
None
"""
prefix = normpath(prefix)
path = normpath(path)
basename = os.path.basename(prefix)
path_components = path.split(os.sep)
# find the (rightmost) basename in the prefix_components
idx = None
try:
start = 0
while True:
idx = path_components.index(basename, start)
start = idx + 1
except ValueError:
pass
if idx is None:
return None
return os.path.join(prefix, *path_components[idx + 1:])
newpath = maybe_match_prefix(
os.path.dirname(qc.__file__), pluginspath
)
if newpath is not None and os.path.exists(newpath):
QApplication.addLibraryPath(newpath)
if hasattr(QApplication, "setHighDpiScaleFactorRoundingPolicy"):
HighDpiScaleFactorRoundingPolicyLookup = {
"Round": Qt.HighDpiScaleFactorRoundingPolicy.Round,
"Ceil": Qt.HighDpiScaleFactorRoundingPolicy.Ceil,
"Floor": Qt.HighDpiScaleFactorRoundingPolicy.Floor,
"RoundPreferFloor": Qt.HighDpiScaleFactorRoundingPolicy.RoundPreferFloor,
"PassThrough": Qt.HighDpiScaleFactorRoundingPolicy.PassThrough,
"Unset": None
}
else:
HighDpiScaleFactorRoundingPolicyLookup = {}
class CanvasApplication(QApplication):
fileOpenRequest = Signal(QUrl)
applicationPaletteChanged = Signal()
__args = None
def __init__(self, argv):
CanvasApplication.__args, argv_ = self.parseArguments(argv)
ns = CanvasApplication.__args
fix_qt_plugins_path()
self.__fileOpenUrls = []
self.__in_exec = False
if ns.enable_high_dpi_scaling \
and hasattr(Qt, "AA_EnableHighDpiScaling"):
# Turn on HighDPI support when available
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
if ns.use_high_dpi_pixmaps \
and hasattr(Qt, "AA_UseHighDpiPixmaps"):
QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
if hasattr(QApplication, "setHighDpiScaleFactorRoundingPolicy") \
and ns.scale_factor_rounding_policy is not None:
QApplication.setHighDpiScaleFactorRoundingPolicy(
ns.scale_factor_rounding_policy
)
if ns.style:
argv_ = argv_ + ["-style", self.__args.style]
super().__init__(argv_)
# Make sure there is an asyncio event loop that runs on the
# Qt event loop.
_ = get_event_loop()
argv[:] = argv_
self.setAttribute(Qt.AA_DontShowIconsInMenus, True)
if hasattr(self, "styleHints"):
sh = self.styleHints()
if hasattr(sh, 'setShowShortcutsInContextMenus'):
# PyQt5.13 and up
sh.setShowShortcutsInContextMenus(True)
if QT_VERSION_INFO < (5, 15): # QTBUG-61707
macos_set_nswindow_tabbing(False)
self.configureStyle()
def event(self, event):
if event.type() == QEvent.FileOpen:
if not self.__in_exec:
self.__fileOpenUrls.append(event.url())
else:
self.fileOpenRequest.emit(event.url())
elif event.type() == QEvent.PolishRequest:
self.configureStyle()
elif event.type() == QEvent.Type.ApplicationPaletteChange:
self.applicationPaletteChanged.emit()
return super().event(event)
def exec(self) -> int:
while self.__fileOpenUrls:
self.fileOpenRequest.emit(self.__fileOpenUrls.pop(0))
self.__in_exec = True
try:
return super().exec()
finally:
self.__in_exec = False
exec_ = exec
@staticmethod
def argumentParser():
parser = argparse.ArgumentParser()
parser.add_argument("-style", type=str, default=None)
parser.add_argument("-colortheme", type=str, default=None)
parser.add_argument("-enable-high-dpi-scaling", type=bool, default=True)
if hasattr(QApplication, "setHighDpiScaleFactorRoundingPolicy"):
default = HighDpiScaleFactorRoundingPolicyLookup.get(
os.environ.get("QT_SCALE_FACTOR_ROUNDING_POLICY"),
Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
)
def converter(value):
# dict.get wrapper due to https://bugs.python.org/issue16516
return HighDpiScaleFactorRoundingPolicyLookup.get(value)
parser.add_argument(
"-scale-factor-rounding-policy",
type=converter,
choices=[*HighDpiScaleFactorRoundingPolicyLookup.values(), None],
default=default,
)
parser.add_argument("-use-high-dpi-pixmaps", type=bool, default=True)
return parser
@staticmethod
def parseArguments(argv):
parser = CanvasApplication.argumentParser()
ns, rest = parser.parse_known_args(argv)
if ns.style is not None:
if ":" in ns.style:
ns.style, colortheme = ns.style.split(":", 1)
if ns.colortheme is None:
ns.colortheme = colortheme
return ns, rest
@staticmethod
def configureStyle():
from orangecanvas import styles
args = CanvasApplication.__args
settings = QSettings()
settings.beginGroup("application-style")
name = settings.value("style-name", "", type=str)
if args is not None and args.style:
# command line params take precedence
name = args.style
if name != "":
inst = QApplication.instance()
if inst is not None:
if inst.style().objectName().lower() != name.lower():
QApplication.setStyle(name)
theme = settings.value("palette", "", type=str)
if args is not None and args.colortheme:
theme = args.colortheme
if theme and theme in styles.colorthemes:
palette = styles.colorthemes[theme]()
QApplication.setPalette(palette)
QPixmapCache.setCacheLimit(64 * (2 ** 10))
__restart_command: Optional[List[str]] = None
def set_restart_command(cmd: Optional[Sequence[str]]):
"""
Set or unset the restart command.
This command will be run after this process exits.
Pass cmd=None to unset the current command.
"""
global __restart_command
log = logging.getLogger(__name__)
atexit.unregister(__restart)
if cmd is None:
__restart_command = None
log.info("Disabling application restart")
else:
__restart_command = list(cmd)
atexit.register(__restart)
log.info("Enabling application restart with: %r", cmd)
def restart_command() -> Optional[List[str]]:
"""Return the current set restart command."""
return __restart_command
def restart_cancel() -> None:
set_restart_command(None)
def default_restart_command():
"""Return the default restart command."""
return [sys.executable, sys.argv[0]]
def __restart():
if __restart_command:
run_after_exit(__restart_command)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/canvasmain.py 0000664 0001750 0001750 00000304116 14625071541 023710 0 ustar 00marko marko """
Orange Canvas Main Window
"""
import os
import sys
import logging
import operator
import io
import traceback
from concurrent import futures
from contextlib import contextmanager
from xml.sax.saxutils import escape
from functools import partial, reduce
from types import SimpleNamespace
from typing import (
Optional, List, Union, Any, cast, Dict, Callable, IO, Sequence, Iterable,
Tuple, TypeVar, Awaitable,
)
from AnyQt.QtWidgets import (
QMainWindow, QWidget, QAction, QActionGroup, QMenu, QMenuBar, QDialog,
QFileDialog, QMessageBox, QVBoxLayout, QSizePolicy, QToolBar, QToolButton,
QDockWidget, QApplication, QShortcut, QFileIconProvider
)
from AnyQt.QtGui import (
QColor, QDesktopServices, QKeySequence,
QWhatsThisClickedEvent, QShowEvent, QCloseEvent
)
from AnyQt.QtCore import (
Qt, QObject, QEvent, QSize, QUrl, QByteArray, QFileInfo,
QSettings, QStandardPaths, QAbstractItemModel, QMimeData, QT_VERSION)
try:
from AnyQt.QtWebEngineWidgets import QWebEngineView
except ImportError:
QWebEngineView = None # type: ignore
try:
from AnyQt.QtWebKitWidgets import QWebView
from AnyQt.QtNetwork import QNetworkDiskCache
except ImportError:
QWebView = None # type: ignore
from AnyQt.QtCore import (
pyqtProperty as Property, pyqtSignal as Signal
)
from ..scheme import Scheme, IncompatibleChannelTypeError, SchemeNode
from ..scheme import readwrite
from ..scheme.readwrite import UnknownWidgetDefinition
from ..gui.dropshadow import DropShadowFrame
from ..gui.dock import CollapsibleDockWidget
from ..gui.quickhelp import QuickHelpTipEvent
from ..gui.utils import message_critical, message_question, \
message_warning, message_information
from ..document.usagestatistics import UsageStatistics
from ..help import HelpManager
from .canvastooldock import CanvasToolDock, QuickCategoryToolbar, \
CategoryPopupMenu, popup_position_from_source
from .aboutdialog import AboutDialog
from .schemeinfo import SchemeInfoDialog
from .outputview import OutputView, TextStream
from .settings import UserSettingsDialog, category_state
from .utils.addons import normalize_name, is_requirement_available
from ..document.schemeedit import SchemeEditWidget
from ..document.quickmenu import QuickMenu
from ..document.commands import UndoCommand
from ..document import interactions
from ..gui.itemmodels import FilterProxyModel
from ..gui.windowlistmanager import WindowListManager
from ..registry import WidgetRegistry, WidgetDescription, CategoryDescription
from ..registry.qt import QtWidgetRegistry
from ..utils.settings import QSettings_readArray, QSettings_writeArray
from ..utils.qinvoke import qinvoke
from ..utils.pickle import Pickler, Unpickler, glob_scratch_swps, swp_name, \
canvas_scratch_name_memo, register_loaded_swp
from ..utils import unique, group_by_all, set_flag, findf
from ..utils.asyncutils import get_event_loop
from ..utils.qobjref import qobjref
from . import welcomedialog
from . import addons
from ..preview import previewdialog, previewmodel
from .. import config
from . import examples
from ..resources import load_styled_svg_icon
from ..canvas import scene
log = logging.getLogger(__name__)
def user_documents_path():
"""
Return the users 'Documents' folder path.
"""
return QStandardPaths.writableLocation(QStandardPaths.DocumentsLocation)
class FakeToolBar(QToolBar):
"""A Toolbar with no contents (used to reserve top and bottom margins
on the main window).
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFloatable(False)
self.setMovable(False)
# Don't show the tool bar action in the main window's
# context menu.
self.toggleViewAction().setVisible(False)
def paintEvent(self, event):
# Do nothing.
pass
class DockWidget(QDockWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
shortcuts = [
QKeySequence(QKeySequence.Close),
QKeySequence(QKeySequence(Qt.Key_Escape)),
]
for kseq in shortcuts:
QShortcut(kseq, self, self.close,
context=Qt.WidgetWithChildrenShortcut)
class CanvasMainWindow(QMainWindow):
SETTINGS_VERSION = 3
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__scheme_margins_enabled = True
self.__document_title = "untitled"
self.__first_show = True
self.__is_transient = True
self.widget_registry = None # type: Optional[WidgetRegistry]
self.__registry_model = None # type: Optional[QAbstractItemModel]
# Proxy widget registry model
self.__proxy_model = None # type: Optional[FilterProxyModel]
# TODO: Help view and manager to separate singleton instance.
self.help = None # type: HelpManager
self.help_view = None
self.help_dock = None
# TODO: Log view to separate singleton instance.
self.output_dock = None
# TODO: sync between CanvasMainWindow instances?.
settings = QSettings()
recent = QSettings_readArray(
settings, "mainwindow/recent-items",
{"title": str, "path": str}
)
recent = [RecentItem(**item) for item in recent]
recent = [item for item in recent if os.path.exists(item.path)]
self.recent_schemes = recent
self.num_recent_schemes = 15
self.help = HelpManager(self)
self.setup_actions()
self.setup_ui()
self.setup_menu()
windowmanager = WindowListManager.instance()
windowmanager.addWindow(self)
self.window_menu.addSeparator()
self.window_menu.addActions(windowmanager.actions())
windowmanager.windowAdded.connect(self.__window_added)
windowmanager.windowRemoved.connect(self.__window_removed)
self.restore()
def setup_ui(self):
"""Setup main canvas ui
"""
# Two dummy tool bars to reserve space
self.__dummy_top_toolbar = FakeToolBar(
objectName="__dummy_top_toolbar")
self.__dummy_bottom_toolbar = FakeToolBar(
objectName="__dummy_bottom_toolbar")
self.__dummy_top_toolbar.setFixedHeight(20)
self.__dummy_bottom_toolbar.setFixedHeight(20)
self.addToolBar(Qt.TopToolBarArea, self.__dummy_top_toolbar)
self.addToolBar(Qt.BottomToolBarArea, self.__dummy_bottom_toolbar)
self.setCorner(Qt.BottomLeftCorner, Qt.LeftDockWidgetArea)
self.setCorner(Qt.BottomRightCorner, Qt.RightDockWidgetArea)
self.setDockOptions(QMainWindow.AnimatedDocks)
# Create an empty initial scheme inside a container with fixed
# margins.
w = QWidget()
w.setLayout(QVBoxLayout())
w.layout().setContentsMargins(20, 0, 10, 0)
self.scheme_widget = SchemeEditWidget()
self.scheme_widget.setDropHandlers([interactions.PluginDropHandler(),])
self.set_scheme(config.workflow_constructor(parent=self))
# Save crash recovery swap file on changes to workflow
self.scheme_widget.undoCommandAdded.connect(self.save_swp)
dropfilter = UrlDropEventFilter(self)
dropfilter.urlDropped.connect(self.open_scheme_file)
self.scheme_widget.setAcceptDrops(True)
self.scheme_widget.view().viewport().installEventFilter(dropfilter)
w.layout().addWidget(self.scheme_widget)
self.setCentralWidget(w)
# Drop shadow around the scheme document
frame = DropShadowFrame(radius=15)
frame.setColor(QColor(0, 0, 0, 100))
frame.setWidget(self.scheme_widget)
# Window 'title'
self.__update_window_title()
self.setWindowFilePath(self.scheme_widget.path())
self.scheme_widget.pathChanged.connect(self.__update_window_title)
self.scheme_widget.modificationChanged.connect(self.setWindowModified)
# QMainWindow's Dock widget
self.dock_widget = CollapsibleDockWidget(objectName="main-area-dock")
self.dock_widget.setFeatures(QDockWidget.DockWidgetMovable |
QDockWidget.DockWidgetClosable)
self.dock_widget.setAllowedAreas(Qt.LeftDockWidgetArea |
Qt.RightDockWidgetArea)
# Main canvas tool dock (with widget toolbox, common actions.
# This is the widget that is shown when the dock is expanded.
canvas_tool_dock = CanvasToolDock(objectName="canvas-tool-dock")
canvas_tool_dock.setSizePolicy(QSizePolicy.Fixed,
QSizePolicy.MinimumExpanding)
# Bottom tool bar
self.canvas_toolbar = canvas_tool_dock.toolbar
self.canvas_toolbar.setIconSize(QSize(24, 24))
self.canvas_toolbar.setMinimumHeight(28)
self.canvas_toolbar.layout().setSpacing(1)
# Widgets tool box
self.widgets_tool_box = canvas_tool_dock.toolbox
self.widgets_tool_box.setObjectName("canvas-toolbox")
self.widgets_tool_box.setTabButtonHeight(30)
self.widgets_tool_box.setTabIconSize(QSize(26, 26))
self.widgets_tool_box.setButtonSize(QSize(68, 84))
self.widgets_tool_box.setIconSize(QSize(48, 48))
self.widgets_tool_box.triggered.connect(
self.on_tool_box_widget_activated
)
self.dock_help = canvas_tool_dock.help
self.dock_help.setMaximumHeight(150)
self.dock_help.document().setDefaultStyleSheet("h3, a {color: orange;}")
self.dock_help.setDefaultText(
"Select a widget to show its description."
"
"
"See workflow examples, "
"YouTube tutorials, "
"or open the welcome screen."
)
self.dock_help_action = canvas_tool_dock.toggleQuickHelpAction()
self.dock_help_action.setText(self.tr("Show Help"))
self.dock_help_action.setIcon(load_styled_svg_icon("Info.svg", self.canvas_toolbar))
self.canvas_tool_dock = canvas_tool_dock
# Dock contents when collapsed (a quick category tool bar, ...)
dock2 = QWidget(objectName="canvas-quick-dock")
dock2.setLayout(QVBoxLayout())
dock2.layout().setContentsMargins(0, 0, 0, 0)
dock2.layout().setSpacing(0)
dock2.layout().setSizeConstraint(QVBoxLayout.SetFixedSize)
self.quick_category = QuickCategoryToolbar()
self.quick_category.setButtonSize(QSize(38, 30))
self.quick_category.setIconSize(QSize(26, 26))
self.quick_category.actionTriggered.connect(
self.on_quick_category_action
)
tool_actions = self.current_document().toolbarActions()
(self.zoom_in_action, self.zoom_out_action, self.zoom_reset_action,
self.canvas_align_to_grid_action,
self.canvas_text_action, self.canvas_arrow_action,) = tool_actions
self.canvas_align_to_grid_action.setIcon(load_styled_svg_icon("Grid.svg", self.canvas_toolbar))
self.canvas_text_action.setIcon(load_styled_svg_icon("Text Size.svg", self.canvas_toolbar))
self.canvas_arrow_action.setIcon(load_styled_svg_icon("Arrow.svg", self.canvas_toolbar))
self.freeze_action.setIcon(load_styled_svg_icon('Pause.svg', self.canvas_toolbar))
self.show_properties_action.setIcon(load_styled_svg_icon("Document Info.svg", self.canvas_toolbar))
dock_actions = [
self.show_properties_action,
self.canvas_align_to_grid_action,
self.canvas_text_action,
self.canvas_arrow_action,
self.freeze_action,
self.dock_help_action
]
# Tool bar in the collapsed dock state (has the same actions as
# the tool bar in the CanvasToolDock
actions_toolbar = QToolBar(orientation=Qt.Vertical)
actions_toolbar.setFixedWidth(38)
actions_toolbar.layout().setSpacing(0)
actions_toolbar.setToolButtonStyle(Qt.ToolButtonIconOnly)
for action in dock_actions:
self.canvas_toolbar.addAction(action)
button = self.canvas_toolbar.widgetForAction(action)
button.setPopupMode(QToolButton.DelayedPopup)
actions_toolbar.addAction(action)
button = actions_toolbar.widgetForAction(action)
button.setFixedSize(38, 30)
button.setPopupMode(QToolButton.DelayedPopup)
dock2.layout().addWidget(self.quick_category)
dock2.layout().addWidget(actions_toolbar)
self.dock_widget.setAnimationEnabled(False)
self.dock_widget.setExpandedWidget(self.canvas_tool_dock)
self.dock_widget.setCollapsedWidget(dock2)
self.dock_widget.setExpanded(True)
self.dock_widget.expandedChanged.connect(self._on_tool_dock_expanded)
self.addDockWidget(Qt.LeftDockWidgetArea, self.dock_widget)
self.dock_widget.dockLocationChanged.connect(
self._on_dock_location_changed
)
self.output_dock = DockWidget(
self.tr("Log"), self, objectName="output-dock",
allowedAreas=Qt.BottomDockWidgetArea,
visible=self.show_output_action.isChecked(),
)
self.output_dock.setWidget(OutputView())
self.output_dock.visibilityChanged[bool].connect(
self.show_output_action.setChecked
)
self.addDockWidget(Qt.BottomDockWidgetArea, self.output_dock)
self.help_dock = DockWidget(
self.tr("Help"), self, objectName="help-dock",
allowedAreas=Qt.NoDockWidgetArea,
visible=False,
floating=True,
)
if QWebEngineView is not None:
self.help_view = QWebEngineView()
elif QWebView is not None:
self.help_view = QWebView()
manager = self.help_view.page().networkAccessManager()
cache = QNetworkDiskCache()
cachedir = os.path.join(
QStandardPaths.writableLocation(QStandardPaths.CacheLocation),
"help", "help-view-cache"
)
cache.setCacheDirectory(cachedir)
manager.setCache(cache)
self.help_dock.setWidget(self.help_view)
self.setMinimumSize(600, 500)
def setup_actions(self):
"""Initialize main window actions.
"""
self.new_action = QAction(
self.tr("New"), self,
objectName="action-new",
toolTip=self.tr("Open a new workflow."),
triggered=self.new_workflow_window,
shortcut=QKeySequence.New,
icon=load_styled_svg_icon("New.svg")
)
self.open_action = QAction(
self.tr("Open"), self,
objectName="action-open",
toolTip=self.tr("Open a workflow."),
triggered=self.open_scheme,
shortcut=QKeySequence.Open,
icon=load_styled_svg_icon("Open.svg")
)
self.open_and_freeze_action = QAction(
self.tr("Open and Freeze"), self,
objectName="action-open-and-freeze",
toolTip=self.tr("Open a new workflow and freeze signal "
"propagation."),
triggered=self.open_and_freeze_scheme
)
self.open_and_freeze_action.setShortcut(
QKeySequence("Ctrl+Alt+O")
)
self.close_window_action = QAction(
self.tr("Close Window"), self,
objectName="action-close-window",
toolTip=self.tr("Close the window"),
shortcut=QKeySequence.Close,
triggered=self.close,
)
self.save_action = QAction(
self.tr("Save"), self,
objectName="action-save",
toolTip=self.tr("Save current workflow."),
triggered=self.save_scheme,
shortcut=QKeySequence.Save,
)
self.save_as_action = QAction(
self.tr("Save As ..."), self,
objectName="action-save-as",
toolTip=self.tr("Save current workflow as."),
triggered=self.save_scheme_as,
shortcut=QKeySequence.SaveAs,
)
self.save_as_svg_action = QAction(
self.tr("Save Workflow Image as SVG ..."), self,
objectName="action-save-to-svg.",
toolTip=self.tr("Save workflow image as SVG."),
triggered=self.save_as_svg,
)
self.quit_action = QAction(
self.tr("Quit"), self,
objectName="quit-action",
triggered=QApplication.closeAllWindows,
menuRole=QAction.QuitRole,
shortcut=QKeySequence.Quit,
)
self.welcome_action = QAction(
self.tr("Welcome"), self,
objectName="welcome-action",
toolTip=self.tr("Show welcome screen."),
triggered=self.welcome_dialog,
)
def open_url_for(name):
url = config.default.APPLICATION_URLS.get(name)
if url is not None:
QDesktopServices.openUrl(QUrl(url))
def has_url_for(name):
# type: (str) -> bool
url = config.default.APPLICATION_URLS.get(name)
return url is not None and QUrl(url).isValid()
def config_url_action(action, role):
# type: (QAction, str) -> None
enabled = has_url_for(role)
action.setVisible(enabled)
action.setEnabled(enabled)
if enabled:
action.triggered.connect(lambda: open_url_for(role))
self.get_started_action = QAction(
self.tr("Get Started"), self,
objectName="get-started-action",
toolTip=self.tr("View a 'Get Started' introduction."),
icon=load_styled_svg_icon("Documentation.svg")
)
config_url_action(self.get_started_action, "Quick Start")
self.get_started_screencasts_action = QAction(
self.tr("Video Tutorials"), self,
objectName="screencasts-action",
toolTip=self.tr("View video tutorials"),
icon=load_styled_svg_icon("YouTube.svg"),
)
config_url_action(self.get_started_screencasts_action, "Screencasts")
self.documentation_action = QAction(
self.tr("Documentation"), self,
objectName="documentation-action",
toolTip=self.tr("View reference documentation."),
icon=load_styled_svg_icon("Documentation.svg"),
)
config_url_action(self.documentation_action, "Documentation")
self.examples_action = QAction(
self.tr("Example Workflows"), self,
objectName="examples-action",
toolTip=self.tr("Browse example workflows."),
triggered=self.examples_dialog,
icon=load_styled_svg_icon("Examples.svg")
)
self.about_action = QAction(
self.tr("About"), self,
objectName="about-action",
toolTip=self.tr("Show about dialog."),
triggered=self.open_about,
menuRole=QAction.AboutRole,
)
# Action group for for recent scheme actions
self.recent_scheme_action_group = QActionGroup(
self, objectName="recent-action-group",
triggered=self._on_recent_scheme_action
)
self.recent_scheme_action_group.setExclusive(False)
self.recent_action = QAction(
self.tr("Browse Recent"), self,
objectName="recent-action",
toolTip=self.tr("Browse and open a recent workflow."),
triggered=self.recent_scheme,
shortcut=QKeySequence("Ctrl+Shift+R"),
icon=load_styled_svg_icon("Recent.svg")
)
self.reload_last_action = QAction(
self.tr("Reload Last Workflow"), self,
objectName="reload-last-action",
toolTip=self.tr("Reload last open workflow."),
triggered=self.reload_last,
shortcut=QKeySequence("Ctrl+R")
)
self.clear_recent_action = QAction(
self.tr("Clear Menu"), self,
objectName="clear-recent-menu-action",
toolTip=self.tr("Clear recent menu."),
triggered=self.clear_recent_schemes
)
self.show_properties_action = QAction(
self.tr("Workflow Info"), self,
objectName="show-properties-action",
toolTip=self.tr("Show workflow properties."),
triggered=self.show_scheme_properties,
shortcut=QKeySequence("Ctrl+I"),
icon=load_styled_svg_icon("Document Info.svg")
)
self.canvas_settings_action = QAction(
self.tr("Settings"), self,
objectName="canvas-settings-action",
toolTip=self.tr("Set application settings."),
triggered=self.open_canvas_settings,
menuRole=QAction.PreferencesRole,
shortcut=QKeySequence.Preferences
)
self.canvas_addons_action = QAction(
self.tr("&Add-ons..."), self,
objectName="canvas-addons-action",
toolTip=self.tr("Manage add-ons."),
triggered=self.open_addons,
)
self.show_output_action = QAction(
self.tr("&Log"), self,
toolTip=self.tr("Show application standard output."),
checkable=True,
triggered=lambda checked: self.output_dock.setVisible(
checked),
)
# Actions for native Mac OSX look and feel.
self.minimize_action = QAction(
self.tr("Minimize"), self,
triggered=self.showMinimized,
shortcut=QKeySequence("Ctrl+M"),
visible=sys.platform == "darwin",
)
self.zoom_action = QAction(
self.tr("Zoom"), self,
objectName="application-zoom",
triggered=self.toggleMaximized,
visible=sys.platform == "darwin",
)
self.freeze_action = QAction(
self.tr("Freeze"), self,
shortcut=QKeySequence("Shift+F"),
objectName="signal-freeze-action",
checkable=True,
toolTip=self.tr("Freeze signal propagation (Shift+F)"),
toggled=self.set_signal_freeze,
icon=load_styled_svg_icon("Pause.svg")
)
self.toggle_tool_dock_expand = QAction(
self.tr("Expand Tool Dock"), self,
objectName="toggle-tool-dock-expand",
checkable=True,
shortcut=QKeySequence("Ctrl+Shift+D"),
triggered=self.set_tool_dock_expanded
)
self.toggle_tool_dock_expand.setChecked(True)
# Gets assigned in setup_ui (the action is defined in CanvasToolDock)
# TODO: This is bad (should be moved here).
self.dock_help_action = None
self.toogle_margins_action = QAction(
self.tr("Show Workflow Margins"), self,
checkable=True,
toolTip=self.tr("Show margins around the workflow view."),
)
self.toogle_margins_action.setChecked(True)
self.toogle_margins_action.toggled.connect(
self.set_scheme_margins_enabled)
self.float_widgets_on_top_action = QAction(
self.tr("Display Widgets on Top"), self,
checkable=True,
toolTip=self.tr("Widgets are always displayed above other windows.")
)
self.float_widgets_on_top_action.toggled.connect(
self.set_float_widgets_on_top_enabled)
def setup_menu(self):
# QTBUG - 51480
if sys.platform == "darwin" and QT_VERSION >= 0x50000:
self.__menu_glob = QMenuBar(None)
menu_bar = QMenuBar(self)
# File menu
file_menu = QMenu(
self.tr("&File"), menu_bar, objectName="file-menu"
)
file_menu.addAction(self.new_action)
file_menu.addAction(self.open_action)
file_menu.addAction(self.open_and_freeze_action)
file_menu.addAction(self.reload_last_action)
# File -> Open Recent submenu
self.recent_menu = QMenu(
self.tr("Open Recent"), file_menu, objectName="recent-menu",
)
file_menu.addMenu(self.recent_menu)
# An invisible hidden separator action indicating the end of the
# actions that with 'open' (new window/document) disposition
sep = QAction(
"", file_menu, objectName="open-actions-separator",
visible=False, enabled=False
)
# qt/cocoa native menu bar menu displays hidden separators
# sep.setSeparator(True)
file_menu.addAction(sep)
file_menu.addAction(self.close_window_action)
sep = file_menu.addSeparator()
sep.setObjectName("close-window-actions-separator")
file_menu.addAction(self.save_action)
file_menu.addAction(self.save_as_action)
file_menu.addAction(self.save_as_svg_action)
sep = file_menu.addSeparator()
sep.setObjectName("save-actions-separator")
file_menu.addAction(self.show_properties_action)
file_menu.addAction(self.quit_action)
self.recent_menu.addAction(self.recent_action)
# Store the reference to separator for inserting recent
# schemes into the menu in `add_recent_scheme`.
self.recent_menu_begin = self.recent_menu.addSeparator()
icons = QFileIconProvider()
# Add recent items.
for item in self.recent_schemes:
text = os.path.basename(item.path)
if item.title:
text = "{} ('{}')".format(text, item.title)
icon = icons.icon(QFileInfo(item.path))
action = QAction(
icon, text, self, toolTip=item.path, iconVisibleInMenu=True
)
action.setData(item.path)
self.recent_menu.addAction(action)
self.recent_scheme_action_group.addAction(action)
self.recent_menu.addSeparator()
self.recent_menu.addAction(self.clear_recent_action)
menu_bar.addMenu(file_menu)
editor_menus = self.scheme_widget.menuBarActions()
# WARNING: Hard coded order, should lookup the action text
# and determine the proper order
self.edit_menu = editor_menus[0].menu()
self.widget_menu = editor_menus[1].menu()
# Edit menu
menu_bar.addMenu(self.edit_menu)
# View menu
self.view_menu = QMenu(
self.tr("&View"), menu_bar, objectName="view-menu"
)
# find and insert window group presets submenu
window_groups = self.scheme_widget.findChild(
QAction, "window-groups-action"
)
if window_groups is not None:
self.view_menu.addAction(window_groups)
sep = self.view_menu.addSeparator()
sep.setObjectName("workflow-window-groups-actions-separator")
# Actions that toggle visibility of editor views
self.view_menu.addAction(self.toggle_tool_dock_expand)
self.view_menu.addAction(self.show_output_action)
sep = self.view_menu.addSeparator()
sep.setObjectName("view-visible-actions-separator")
self.view_menu.addAction(self.zoom_in_action)
self.view_menu.addAction(self.zoom_out_action)
self.view_menu.addAction(self.zoom_reset_action)
sep = self.view_menu.addSeparator()
sep.setObjectName("view-zoom-actions-separator")
self.view_menu.addAction(self.toogle_margins_action)
menu_bar.addMenu(self.view_menu)
# Options menu
self.options_menu = QMenu(
self.tr("&Options"), menu_bar, objectName="options-menu"
)
self.options_menu.addAction(self.canvas_settings_action)
self.options_menu.addAction(self.canvas_addons_action)
# Widget menu
menu_bar.addMenu(self.widget_menu)
# Mac OS X native look and feel.
self.window_menu = QMenu(
self.tr("Window"), menu_bar, objectName="window-menu"
)
self.window_menu.addAction(self.minimize_action)
self.window_menu.addAction(self.zoom_action)
self.window_menu.addSeparator()
raise_widgets_action = self.scheme_widget.findChild(
QAction, "bring-widgets-to-front-action"
)
if raise_widgets_action is not None:
self.window_menu.addAction(raise_widgets_action)
self.window_menu.addAction(self.float_widgets_on_top_action)
menu_bar.addMenu(self.window_menu)
menu_bar.addMenu(self.options_menu)
# Help menu.
self.help_menu = QMenu(
self.tr("&Help"), menu_bar, objectName="help-menu",
)
self.help_menu.addActions([
self.about_action,
self.welcome_action,
self.get_started_screencasts_action,
self.examples_action,
self.documentation_action
])
menu_bar.addMenu(self.help_menu)
self.setMenuBar(menu_bar)
def restore(self):
"""Restore the main window state from saved settings.
"""
QSettings.setDefaultFormat(QSettings.IniFormat)
settings = QSettings()
settings.beginGroup("mainwindow")
self.dock_widget.setExpanded(
settings.value("canvasdock/expanded", True, type=bool)
)
floatable = settings.value("toolbox-dock-floatable", False, type=bool)
if floatable:
self.dock_widget.setFeatures(
self.dock_widget.features() | QDockWidget.DockWidgetFloatable
)
self.widgets_tool_box.setExclusive(
settings.value("toolbox-dock-exclusive", False, type=bool)
)
self.toogle_margins_action.setChecked(
settings.value("scheme-margins-enabled", False, type=bool)
)
self.show_output_action.setChecked(
settings.value("output-dock/is-visible", False, type=bool))
self.canvas_tool_dock.setQuickHelpVisible(
settings.value("quick-help/visible", True, type=bool)
)
self.float_widgets_on_top_action.setChecked(
settings.value("widgets-float-on-top", False, type=bool)
)
self.__update_from_settings()
def __window_added(self, _, action: QAction) -> None:
self.window_menu.addAction(action)
def __window_removed(self, _, action: QAction) -> None:
self.window_menu.removeAction(action)
def __update_window_title(self):
path = self.current_document().path()
if path:
self.setWindowTitle("")
self.setWindowFilePath(path)
else:
self.setWindowFilePath("")
self.setWindowTitle(self.tr("Untitled [*]"))
def setWindowFilePath(self, filePath): # type: (str) -> None
def icon_for_path(path: str) -> 'QIcon':
iconprovider = QFileIconProvider()
finfo = QFileInfo(path)
if finfo.exists():
return iconprovider.icon(finfo)
else:
return iconprovider.icon(QFileIconProvider.File)
if sys.platform == "darwin":
super().setWindowFilePath(filePath)
# If QApplication.windowIcon() is not null then it is used instead
# of the file type specific one. This is wrong so we set it
# explicitly.
if not QApplication.windowIcon().isNull() and filePath:
self.setWindowIcon(icon_for_path(filePath))
else:
# use non-empty path to 'force' Qt to add '[*]' modified marker
# in the displayed title.
if not filePath:
filePath = " "
super().setWindowFilePath(filePath)
def set_document_title(self, title):
"""Set the document title (and the main window title). If `title`
is an empty string a default 'untitled' placeholder will be used.
"""
if self.__document_title != title:
self.__document_title = title
if not title:
# TODO: should the default name be platform specific
title = self.tr("untitled")
self.setWindowTitle(title + "[*]")
def document_title(self):
"""Return the document title.
"""
return self.__document_title
def set_widget_registry(self, widget_registry):
# type: (WidgetRegistry) -> None
"""
Set widget registry.
Parameters
----------
widget_registry : WidgetRegistry
"""
if self.widget_registry is not None:
# Clear the dock widget and popup.
self.widgets_tool_box.setModel(None)
self.quick_category.setModel(None)
self.scheme_widget.setRegistry(None)
self.help.set_registry(None)
if self.__proxy_model is not None:
self.__proxy_model.deleteLater()
self.__proxy_model = None
self.widget_registry = WidgetRegistry(widget_registry)
qreg = QtWidgetRegistry(self.widget_registry, parent=self)
self.__registry_model = qreg.model()
# Restore category hidden/sort order state
proxy = FilterProxyModel(self)
proxy.setSourceModel(qreg.model())
self.__proxy_model = proxy
self.__update_registry_filters()
self.widgets_tool_box.setModel(proxy)
self.quick_category.setModel(proxy)
self.scheme_widget.setRegistry(qreg)
self.scheme_widget.quickMenu().setModel(proxy)
self.help.set_registry(widget_registry)
# Restore possibly saved widget toolbox tab states
settings = QSettings()
state = settings.value("mainwindow/widgettoolbox/state",
defaultValue=QByteArray(),
type=QByteArray)
if state:
self.widgets_tool_box.restoreState(state)
def set_quick_help_text(self, text):
# type: (str) -> None
self.canvas_tool_dock.help.setText(text)
def current_document(self):
# type: () -> SchemeEditWidget
return self.scheme_widget
def on_tool_box_widget_activated(self, action):
"""A widget action in the widget toolbox has been activated.
"""
widget_desc = action.data()
if isinstance(widget_desc, WidgetDescription):
scheme_widget = self.current_document()
if scheme_widget:
statistics = scheme_widget.usageStatistics()
statistics.begin_action(UsageStatistics.ToolboxClick)
scheme_widget.createNewNode(widget_desc)
scheme_widget.view().setFocus(Qt.OtherFocusReason)
def on_quick_category_action(self, action):
"""The quick category menu action triggered.
"""
category = action.text()
settings = QSettings()
use_popover = settings.value(
"mainwindow/toolbox-dock-use-popover-menu",
defaultValue=True, type=bool)
if use_popover:
# Show a popup menu with the widgets in the category
popup = CategoryPopupMenu(self.quick_category)
popup.setActionRole(QtWidgetRegistry.WIDGET_ACTION_ROLE)
model = self.__registry_model
assert model is not None
i = index(self.widget_registry.categories(), category,
predicate=lambda name, cat: cat.name == name)
if i != -1:
popup.setModel(model)
popup.setRootIndex(model.index(i, 0))
popup.adjustSize()
button = self.quick_category.buttonForAction(action)
pos = popup_position_from_source(popup, button)
action = popup.exec(pos)
if action is not None:
self.on_tool_box_widget_activated(action)
else:
# Expand the dock and open the category under the triggered button
for i in range(self.widgets_tool_box.count()):
cat_act = self.widgets_tool_box.tabAction(i)
cat_act.setChecked(cat_act.text() == category)
self.dock_widget.expand()
def set_scheme_margins_enabled(self, enabled):
# type: (bool) -> None
"""Enable/disable the margins around the scheme document.
"""
if self.__scheme_margins_enabled != enabled:
self.__scheme_margins_enabled = enabled
self.__update_scheme_margins()
def _scheme_margins_enabled(self):
# type: () -> bool
return self.__scheme_margins_enabled
scheme_margins_enabled: bool
scheme_margins_enabled = Property( # type: ignore
bool, _scheme_margins_enabled, set_scheme_margins_enabled)
def __update_scheme_margins(self):
"""Update the margins around the scheme document.
"""
enabled = self.__scheme_margins_enabled
self.__dummy_top_toolbar.setVisible(enabled)
self.__dummy_bottom_toolbar.setVisible(enabled)
central = self.centralWidget()
margin = 20 if enabled else 0
if self.dockWidgetArea(self.dock_widget) == Qt.LeftDockWidgetArea:
margins = (margin // 2, 0, margin, 0)
else:
margins = (margin, 0, margin // 2, 0)
central.layout().setContentsMargins(*margins)
def is_transient(self):
# type: () -> bool
"""
Is this window a transient window.
I.e. a window that was created empty and does not contain any modified
contents. In particular it can be reused to load a workflow model
without any detrimental effects (like lost information).
"""
return self.__is_transient
# All instances created through the create_new_window below.
# They are removed on `destroyed`
_instances = [] # type: List[CanvasMainWindow]
def create_new_window(self):
# type: () -> CanvasMainWindow
"""
Create a new top level CanvasMainWindow instance.
The window is positioned slightly offset to the originating window
(`self`).
Note
----
The window has `Qt.WA_DeleteOnClose` flag set. If this flag is unset
it is the callers responsibility to explicitly delete the widget (via
`deleteLater` or `sip.delete`).
Returns
-------
window: CanvasMainWindow
"""
window = type(self)() # 'preserve' subclass type
window.setAttribute(Qt.WA_DeleteOnClose)
window.setGeometry(self.geometry().translated(20, 20))
window.setStyleSheet(self.styleSheet())
window.setWindowIcon(self.windowIcon())
if self.widget_registry is not None:
window.set_widget_registry(self.widget_registry)
window.restoreState(self.saveState(self.SETTINGS_VERSION),
self.SETTINGS_VERSION)
window.set_tool_dock_expanded(self.dock_widget.expanded())
window.set_float_widgets_on_top_enabled(self.float_widgets_on_top_action.isChecked())
output = window.output_view() # type: OutputView
doc = self.output_view().document()
doc = doc.clone(output)
output.setDocument(doc)
def is_connected(stream: TextStream) -> bool:
item = findf(doc.connectedStreams(), lambda s: s is stream)
return item is not None
# # route the stdout/err if possible
# TODO: Deprecate and remove this behaviour (use connectStream)
stdout, stderr = sys.stdout, sys.stderr
if isinstance(stdout, TextStream) and not is_connected(stdout):
doc.connectStream(stdout)
if isinstance(stderr, TextStream) and not is_connected(stderr):
doc.connectStream(stderr, color=Qt.red)
CanvasMainWindow._instances.append(window)
window.destroyed.connect(
lambda: CanvasMainWindow._instances.remove(window))
return window
def new_workflow_window(self):
# type: () -> None
"""
Create and show a new CanvasMainWindow instance.
"""
newwindow = self.create_new_window()
newwindow.ask_load_swp_if_exists()
newwindow.raise_()
newwindow.show()
newwindow.activateWindow()
settings = QSettings()
show = settings.value("schemeinfo/show-at-new-scheme", False,
type=bool)
if show:
newwindow.show_scheme_properties()
def open_scheme_file(self, filename, **kwargs):
# type: (Union[str, QUrl], Any) -> None
"""
Open and load a scheme file.
"""
if isinstance(filename, QUrl):
filename = filename.toLocalFile()
if self.is_transient():
window = self
else:
window = self.create_new_window()
window.show()
window.raise_()
window.activateWindow()
if kwargs.get("freeze", False):
window.freeze_action.setChecked(True)
window.load_scheme(filename)
def open_example_scheme(self, path): # type: (str) -> None
# open an workflow without filename/directory tracking.
if self.is_transient():
window = self
else:
window = self.create_new_window()
window.show()
window.raise_()
window.activateWindow()
new_scheme = window.new_scheme_from(path)
if new_scheme is not None:
window.set_scheme(new_scheme)
def _open_workflow_dialog(self):
# type: () -> QFileDialog
"""
Create and return an initialized QFileDialog for opening a workflow
file.
The dialog is a child of this window and has the `Qt.WA_DeleteOnClose`
flag set.
"""
settings = QSettings()
settings.beginGroup("mainwindow")
start_dir = settings.value("last-scheme-dir", "", type=str)
if not os.path.isdir(start_dir):
start_dir = user_documents_path()
dlg = QFileDialog(
self, windowTitle=self.tr("Open Orange Workflow File"),
acceptMode=QFileDialog.AcceptOpen,
fileMode=QFileDialog.ExistingFile,
)
dlg.setAttribute(Qt.WA_DeleteOnClose)
dlg.setDirectory(start_dir)
dlg.setNameFilters(["Orange Workflow (*.ows)"])
def record_last_dir():
path = dlg.directory().canonicalPath()
settings.setValue("last-scheme-dir", path)
dlg.accepted.connect(record_last_dir)
return dlg
def open_scheme(self):
# type: () -> None
"""
Open a user selected workflow in a new window.
"""
dlg = self._open_workflow_dialog()
dlg.fileSelected.connect(self.open_scheme_file)
dlg.exec()
def open_and_freeze_scheme(self):
# type: () -> None
"""
Open a user selected workflow file in a new window and freeze
signal propagation.
"""
dlg = self._open_workflow_dialog()
dlg.fileSelected.connect(partial(self.open_scheme_file, freeze=True))
dlg.exec()
def load_scheme(self, filename):
# type: (str) -> None
"""
Load a scheme from a file (`filename`) into the current
document, updates the recent scheme list and the loaded scheme path
property.
"""
new_scheme = None # type: Optional[Scheme]
try:
with open(filename, "rb") as f:
res = self.check_requires(f)
if not res:
return
f.seek(0, os.SEEK_SET)
new_scheme = self.new_scheme_from_contents_and_path(f, filename)
except readwrite.UnsupportedFormatVersionError:
mb = QMessageBox(
self, windowTitle=self.tr("Error"),
icon=QMessageBox.Critical,
text=self.tr("Unsupported format version"),
informativeText=self.tr(
"The file was saved in a format not supported by this "
"application."
),
detailedText="".join(traceback.format_exc()),
)
mb.setAttribute(Qt.WA_DeleteOnClose)
mb.setWindowModality(Qt.WindowModal)
mb.open()
except Exception as err:
mb = QMessageBox(
parent=self, windowTitle=self.tr("Error"),
icon=QMessageBox.Critical,
text=self.tr("Could not open: '{}'")
.format(os.path.basename(filename)),
informativeText=self.tr("Error was: {}").format(err),
detailedText="".join(traceback.format_exc())
)
mb.setAttribute(Qt.WA_DeleteOnClose)
mb.setWindowModality(Qt.WindowModal)
mb.open()
if new_scheme is not None:
self.set_scheme(new_scheme, freeze_creation=True)
scheme_doc_widget = self.current_document()
scheme_doc_widget.setPath(filename)
self.add_recent_scheme(new_scheme.title, filename)
if not self.freeze_action.isChecked():
# activate the default window group.
scheme_doc_widget.activateDefaultWindowGroup()
self.ask_load_swp_if_exists()
wm = getattr(new_scheme, "widget_manager", None)
if wm is not None:
wm.set_creation_policy(wm.Normal)
def new_scheme_from(self, filename):
# type: (str) -> Optional[Scheme]
"""
Create and return a new :class:`scheme.Scheme` from a saved
`filename`. Return `None` if an error occurs.
"""
f = None # type: Optional[IO]
try:
f = open(filename, "rb")
except OSError as err:
mb = QMessageBox(
parent=self, windowTitle="Error", icon=QMessageBox.Critical,
text=self.tr("Could not open: '{}'")
.format(os.path.basename(filename)),
informativeText=self.tr("Error was: {}").format(err),
)
mb.setAttribute(Qt.WA_DeleteOnClose)
mb.setWindowModality(Qt.WindowModal)
mb.open()
return None
else:
return self.new_scheme_from_contents_and_path(f, filename)
finally:
if f is not None:
f.close()
def new_scheme_from_contents_and_path(
self, fileobj: IO, path: str) -> Optional[Scheme]:
"""
Create and return a new :class:`scheme.Scheme` from contents of
`fileobj`. Return `None` if an error occurs.
In case of an error show an error message dialog and return `None`.
Parameters
----------
fileobj: IO
An open readable IO stream.
path: str
Associated filesystem path.
Returns
-------
workflow: Optional[Scheme]
"""
new_scheme = config.workflow_constructor(parent=self)
new_scheme.set_runtime_env(
"basedir", os.path.abspath(os.path.dirname(path)))
errors = [] # type: List[Exception]
try:
new_scheme.load_from(
fileobj, registry=self.widget_registry,
error_handler=errors.append
)
except Exception: # pylint: disable=broad-except
log.exception("")
message_critical(
self.tr("Could not load an Orange Workflow file."),
title=self.tr("Error"),
informative_text=self.tr("An unexpected error occurred "
"while loading '%s'.") % path,
exc_info=True,
parent=self)
return None
if errors:
details = render_error_details(errors)
message_warning(
self.tr("Could not load the full workflow."),
title=self.tr("Workflow Partially Loaded"),
informative_text=self.tr(
"Some of the nodes/links could not be reconstructed "
"and were omitted from the workflow."
),
details=details,
parent=self,
)
return new_scheme
def check_requires(self, fileobj: IO) -> bool:
requires = scheme_requires(fileobj, self.widget_registry)
requires = [req for req in requires if not is_requirement_available(req)]
if requires:
details_ = [
"
Required packages:
",
*["
{}
".format(escape(r)) for r in requires],
"
"
]
details = "".join(details_)
mb = QMessageBox(
parent=self,
objectName="install-requirements-message-box",
icon=QMessageBox.Question,
windowTitle="Install Additional Packages",
text="Workflow you are trying to load contains widgets "
"from missing add-ons."
" " + details + " "
"Would you like to install them now?",
standardButtons=QMessageBox.Ok | QMessageBox.Abort |
QMessageBox.Ignore,
informativeText=(
"After installation you will have to restart the "
"application and reopen the workflow."),
)
mb.setDefaultButton(QMessageBox.Ok)
bok = mb.button(QMessageBox.Ok)
bok.setText("Install add-ons")
bignore = mb.button(QMessageBox.Ignore)
bignore.setText("Ignore missing widgets")
bignore.setToolTip(
"Load partial workflow by omitting missing nodes and links."
)
mb.setWindowModality(Qt.WindowModal)
mb.setAttribute(Qt.WA_DeleteOnClose, True)
status = mb.exec()
if status == QMessageBox.Abort:
return False
elif status == QMessageBox.Ignore:
return True
status = self.install_requirements(requires)
if status == QDialog.Rejected:
return False
else:
message_information(
title="Please Restart",
text="Please restart and reopen the file.",
parent=self
)
return False
return True
def install_requirements(self, requires: Sequence[str]) -> int:
dlg = addons.AddonManagerDialog(
parent=self, windowTitle="Install required packages",
enableFilterAndAdd=False,
modal=True
)
dlg.setStyle(QApplication.style())
dlg.setConfig(config.default)
req = addons.Requirement
names = [req(r).name for r in requires]
normalized_names = {normalize_name(r) for r in names}
def set_state(*args):
# select all query items for installation
# TODO: What if some of the `names` failed.
items = dlg.items()
state = dlg.itemState()
for item in items:
if item.normalized_name in normalized_names:
normalized_names.remove(item.normalized_name)
state.append((addons.Install, item))
dlg.setItemState(state)
f = dlg.runQueryAndAddResults(names)
f.add_done_callback(qinvoke(set_state, context=dlg))
return dlg.exec()
def reload_last(self):
# type: () -> None
"""
Reload last opened scheme.
"""
settings = QSettings()
recent = QSettings_readArray(
settings, "mainwindow/recent-items", {"path": str}
) # type: List[Dict[str, str]]
if recent:
path = recent[0]["path"]
self.open_scheme_file(path)
def set_scheme(self, new_scheme: Scheme, freeze_creation=False):
"""
Set new_scheme as the current shown scheme in this window.
The old scheme will be deleted.
"""
scheme_doc = self.current_document()
old_scheme = scheme_doc.scheme()
if old_scheme:
self.__is_transient = False
freeze_signals = self.freeze_action.isChecked()
manager = getattr(new_scheme, "signal_manager", None)
if freeze_signals and manager is not None:
manager.pause()
wm = getattr(new_scheme, "widget_manager", None)
if wm is not None:
wm.set_float_widgets_on_top(
self.float_widgets_on_top_action.isChecked()
)
wm.set_creation_policy(
wm.OnDemand if freeze_creation else wm.Normal
)
scheme_doc.setScheme(new_scheme)
if old_scheme is not None:
# Send a close event to the Scheme, it is responsible for
# closing/clearing all resources (widgets).
QApplication.sendEvent(old_scheme, QEvent(QEvent.Close))
old_scheme.deleteLater()
def __title_for_scheme(self, scheme):
# type: (Optional[Scheme]) -> str
title = self.tr("untitled")
if scheme is not None:
title = scheme.title or title
return title
def ask_save_changes(self):
# type: () -> int
"""Ask the user to save the changes to the current scheme.
Return QDialog.Accepted if the scheme was successfully saved
or the user selected to discard the changes. Otherwise return
QDialog.Rejected.
"""
document = self.current_document()
scheme = document.scheme()
path = document.path()
if path:
filename = os.path.basename(document.path())
message = self.tr('Do you want to save changes made to %s?') % filename
else:
message = self.tr('Do you want to save this workflow?')
selected = message_question(
message,
self.tr("Save Changes?"),
self.tr("Your changes will be lost if you do not save them."),
buttons=QMessageBox.Save | QMessageBox.Cancel | \
QMessageBox.Discard,
default_button=QMessageBox.Save,
parent=self)
if selected == QMessageBox.Save:
return self.save_scheme()
elif selected == QMessageBox.Discard:
return QDialog.Accepted
elif selected == QMessageBox.Cancel:
return QDialog.Rejected
else:
assert False
def save_scheme(self):
# type: () -> int
"""Save the current scheme. If the scheme does not have an associated
path then prompt the user to select a scheme file. Return
QDialog.Accepted if the scheme was successfully saved and
QDialog.Rejected if the user canceled the file selection.
"""
document = self.current_document()
curr_scheme = document.scheme()
if curr_scheme is None:
return QDialog.Rejected
assert curr_scheme is not None
path = document.path()
if path:
if self.save_scheme_to(curr_scheme, path):
document.setModified(False)
self.add_recent_scheme(curr_scheme.title, document.path())
return QDialog.Accepted
else:
return QDialog.Rejected
else:
return self.save_scheme_as()
def save_scheme_as(self):
# type: () -> int
"""
Save the current scheme by asking the user for a filename. Return
`QFileDialog.Accepted` if the scheme was saved successfully and
`QFileDialog.Rejected` if not.
"""
document = self.current_document()
curr_scheme = document.scheme()
assert curr_scheme is not None
title = self.__title_for_scheme(curr_scheme)
settings = self._settings()
if document.path():
start_dir = document.path()
else:
start_dir = settings.value("last-scheme-dir", "", type=str)
if not os.path.isdir(start_dir):
start_dir = user_documents_path()
start_dir = os.path.join(start_dir, title + ".ows")
dialog = QFileDialog(
self,
windowTitle=self.tr("Save Orange Workflow File"),
directory=start_dir,
fileMode=QFileDialog.AnyFile,
acceptMode=QFileDialog.AcceptSave,
windowModality=Qt.WindowModal,
objectName="save-as-ows-filedialog",
)
dialog.setNameFilter(self.tr("Orange Workflow (*.ows)"))
dialog.exec()
files = dialog.selectedFiles()
dialog.deleteLater()
if files:
filename = files[0]
settings.setValue("last-scheme-dir", os.path.dirname(filename))
if self.save_scheme_to(curr_scheme, filename):
document.setPath(filename)
document.setModified(False)
self.add_recent_scheme(curr_scheme.title, document.path())
return QFileDialog.Accepted
return QFileDialog.Rejected
def save_scheme_to(self, scheme, filename):
# type: (Scheme, str) -> bool
"""
Save a Scheme instance `scheme` to `filename`. On success return
`True`, else show a message to the user explaining the error and
return `False`.
"""
dirname, basename = os.path.split(filename)
title = scheme.title or "untitled"
# First write the scheme to a buffer so we don't truncate an
# existing scheme file if `scheme.save_to` raises an error.
buffer = io.BytesIO()
try:
scheme.set_runtime_env("basedir", os.path.abspath(dirname))
scheme.save_to(buffer, pretty=True, pickle_fallback=True)
except Exception:
log.error("Error saving %r to %r", scheme, filename, exc_info=True)
message_critical(
self.tr('An error occurred while trying to save workflow '
'"%s" to "%s"') % (title, basename),
title=self.tr("Error saving %s") % basename,
exc_info=True,
parent=self
)
return False
try:
with open(filename, "wb") as f:
f.write(buffer.getvalue())
self.clear_swp()
return True
except FileNotFoundError as ex:
log.error("%s saving '%s'", type(ex).__name__, filename,
exc_info=True)
message_warning(
self.tr('Workflow "%s" could not be saved. The path does '
'not exist') % title,
title="",
informative_text=self.tr("Choose another location."),
parent=self
)
return False
except PermissionError as ex:
log.error("%s saving '%s'", type(ex).__name__, filename,
exc_info=True)
message_warning(
self.tr('Workflow "%s" could not be saved. You do not '
'have write permissions.') % title,
title="",
informative_text=self.tr(
"Change the file system permissions or choose "
"another location."),
parent=self
)
return False
except OSError as ex:
log.error("%s saving '%s'", type(ex).__name__, filename,
exc_info=True)
message_warning(
self.tr('Workflow "%s" could not be saved.') % title,
title="",
informative_text=os.strerror(ex.errno),
exc_info=True,
parent=self
)
return False
except Exception: # pylint: disable=broad-except
log.error("Error saving %r to %r", scheme, filename, exc_info=True)
message_critical(
self.tr('An error occurred while trying to save workflow '
'"%s" to "%s"') % (title, basename),
title=self.tr("Error saving %s") % basename,
exc_info=True,
parent=self
)
return False
def save_swp(self):
"""
Save a difference of node properties and the undostack to
'..swp.p' in the same directory.
If the workflow has not yet been saved, save to
'scratch.ows.p' in configdir/scratch-crashes.
"""
document = self.current_document()
undoStack = document.undoStack()
if not document.isModifiedStrict() and undoStack.isClean():
return
swpname = swp_name(self)
if swpname is not None:
self.save_swp_to(swpname)
def save_swp_to(self, filename):
"""
Save a tuple of properties diff and undostack diff to a file.
"""
document = self.current_document()
undoStack = document.undoStack()
propertiesDiff = document.uncleanProperties()
undoDiff = [UndoCommand.from_QUndoCommand(undoStack.command(i))
for i in
range(undoStack.cleanIndex(), undoStack.count())]
diff = (propertiesDiff, undoDiff)
try:
with open(filename, "wb") as f:
Pickler(f, document).dump(diff)
except Exception:
log.error("Could not write swp file %r.", filename, exc_info=True)
def clear_swp(self):
"""
Delete the document's swp file, should it exist.
"""
document = self.current_document()
path = document.path()
def remove(filename: str) -> None:
try:
os.remove(filename)
except FileNotFoundError:
pass
except OSError as e:
log.warning("Could not delete swp file: %s", e)
if path or self in canvas_scratch_name_memo:
remove(swp_name(self))
else:
swpnames = glob_scratch_swps()
for swpname in swpnames:
remove(swpname)
def ask_load_swp_if_exists(self):
"""
Should a swp file for this canvas exist,
ask the user if they wish to restore changes,
loading on yes, discarding on no.
Returns True if swp was loaded, False if not.
"""
document = self.current_document()
path = document.path()
if path:
swpname = swp_name(self)
if not os.path.exists(swpname):
return False
else:
if not QSettings().value('startup/load-crashed-workflows', True, type=bool):
return False
swpnames = glob_scratch_swps()
if not swpnames or \
all([s in canvas_scratch_name_memo.values() for s in swpnames]):
return False
return self.ask_load_swp()
def ask_load_swp(self):
"""
Ask to restore changes, loading swp file on yes,
clearing swp file on no.
"""
title = self.tr('Restore unsaved changes from crash?')
name = QApplication.applicationName() or "Orange"
selected = message_information(
title,
self.tr("Restore Changes?"),
self.tr("{} seems to have crashed at some point.\n"
"Changes will be discarded if not restored now.").format(name),
buttons=QMessageBox.Yes | QMessageBox.No,
default_button=QMessageBox.Yes,
parent=self)
if selected == QMessageBox.Yes:
self.load_swp()
return True
elif selected == QMessageBox.No:
self.clear_swp()
return False
else:
assert False
def load_swp(self):
"""
Load and restore the undostack and widget properties from
'..swp.p' in the same directory, or
'scratch.ows.p' in configdir/scratch-crashes
if the workflow has not yet been saved.
"""
document = self.scheme_widget
undoStack = document.undoStack()
if document.path():
# load hidden file in same directory
swpname = swp_name(self)
if not os.path.exists(swpname):
return
self.load_swp_from(swpname)
else:
# load scratch files in config directory
swpnames = [name for name in glob_scratch_swps()
if name not in canvas_scratch_name_memo.values()]
if not swpnames:
return
self.load_swp_from(swpnames[0])
for swpname in swpnames[1:]:
w = self.create_new_window()
w.load_swp_from(swpname)
w.raise_()
w.show()
w.activateWindow()
def load_swp_from(self, filename):
"""
Load a diff of node properties and UndoCommands from a file
"""
document = self.current_document()
undoStack = document.undoStack()
try:
with open(filename, "rb") as f:
loaded: Tuple[Dict[SchemeNode, dict], List[UndoCommand]]
loaded = Unpickler(f, document.scheme()).load()
except Exception:
log.error("Could not load swp file: %r", filename, exc_info=True)
message_critical(
"Could not load restore data.", title="Error", exc_info=True,
)
# delete corrupted swp file
try:
os.remove(filename)
except OSError:
pass
return
register_loaded_swp(self, filename)
document.undoCommandAdded.disconnect(self.save_swp)
commands = loaded[1]
for c in commands:
undoStack.push(c)
properties = loaded[0]
document.restoreProperties(properties)
document.undoCommandAdded.connect(self.save_swp)
def load_diff(self, properties_and_commands):
"""
Load a diff of node properties and UndoCommands
Parameters
---------
properties_and_commands : ({SchemeNode : {}}, [UndoCommand])
"""
document = self.scheme_widget
undoStack = document.undoStack()
commands = properties_and_commands[1]
for c in commands:
undoStack.push(c)
properties = properties_and_commands[0]
document.restoreProperties(properties)
def _settings(self) -> QSettings:
s = QSettings()
s.beginGroup("mainwindow")
return s
def save_as_svg(self):
settings = self._settings()
settings.beginGroup("save-as-svg-filedialog")
path = settings.value("path", defaultValue="", type=str)
if path:
directory = os.path.dirname(path)
else:
directory = user_documents_path()
document_path = self.current_document().path()
if document_path:
document_basename = os.path.basename(document_path)
basename, _ = os.path.splitext(document_basename)
basename = basename + ".svg"
else:
basename = self.tr("untitled.svg")
dialog = QFileDialog(
self,
acceptMode=QFileDialog.AcceptSave,
fileMode=QFileDialog.AnyFile,
directory=directory,
windowModality=Qt.WindowModal,
objectName="save-as-svg-filedialog",
)
dialog.setAttribute(Qt.WA_DeleteOnClose)
dialog.setNameFilter(self.tr("Scalable Vector Graphics (*.svg)"))
dialog.selectFile(os.path.join(directory, basename))
def save():
files = dialog.selectedFiles()
if files:
self.__save_as_svg(files[0])
settings.setValue("path", files[0])
dialog.accepted.connect(save)
dialog.exec()
def __save_as_svg(self, path):
doc = self.current_document()
content = scene.grab_svg(doc.scene())
with self._handle_os_write_error():
with open(path, "wt", encoding="utf-8") as f:
f.write(content)
@contextmanager
def _handle_os_write_error(self):
try:
yield
except PermissionError as ex:
log.error("Write error", exc_info=True)
message_warning(
self.tr('"%(path)s" could not be saved. You do not '
'have write permissions (%(strerror)s).') %
{"path": ex.filename, "strerror": ex.strerror},
title="",
informative_text=self.tr(
"Change the file system permissions or choose "
"another location."),
parent=self
)
except OSError as ex:
log.error("Write error", exc_info=True)
message_warning(
self.tr('"%(path)s" could not be saved.') %
{"path": ex.filename},
title="",
informative_text=ex.strerror
)
def recent_scheme(self):
# type: () -> int
"""
Browse recent schemes.
Return QDialog.Rejected if the user canceled the operation and
QDialog.Accepted otherwise.
"""
settings = QSettings()
recent_items = QSettings_readArray(
settings, "mainwindow/recent-items", {
"title": (str, ""), "path": (str, "")
}
) # type: List[Dict[str, str]]
recent = [RecentItem(**item) for item in recent_items]
recent = [item for item in recent if os.path.exists(item.path)]
items = [previewmodel.PreviewItem(name=item.title, path=item.path)
for item in recent]
dialog = previewdialog.PreviewDialog(self)
model = previewmodel.PreviewModel(dialog, items=items)
title = self.tr("Recent Workflows")
dialog.setWindowTitle(title)
template = ('
\n'
#'\n'
'{0}\n'
'
')
dialog.setHeading(template.format(title))
dialog.setModel(model)
model.delayedScanUpdate()
status = dialog.exec()
index = dialog.currentIndex()
dialog.deleteLater()
model.deleteLater()
if status == QDialog.Accepted:
selected = model.item(index)
self.open_scheme_file(selected.path())
return status
def examples_dialog(self):
# type: () -> int
"""
Browse a collection of tutorial/example schemes.
Returns QDialog.Rejected if the user canceled the dialog else loads
the selected scheme into the canvas and returns QDialog.Accepted.
"""
tutors = examples.workflows(config.default)
items = [previewmodel.PreviewItem(path=t.abspath()) for t in tutors]
dialog = previewdialog.PreviewDialog(self)
model = previewmodel.PreviewModel(dialog, items=items)
title = self.tr("Example Workflows")
dialog.setWindowTitle(title)
template = ('
\n'
'{0}\n'
'
')
dialog.setHeading(template.format(title))
dialog.setModel(model)
model.delayedScanUpdate()
status = dialog.exec()
index = dialog.currentIndex()
dialog.deleteLater()
if status == QDialog.Accepted:
selected = model.item(index)
self.open_example_scheme(selected.path())
return status
def welcome_dialog(self):
# type: () -> int
"""Show a modal welcome dialog for Orange Canvas.
"""
name = QApplication.applicationName()
if name:
title = self.tr("Welcome to {}").format(name)
else:
title = self.tr("Welcome")
dialog = welcomedialog.WelcomeDialog(self, windowTitle=title)
feedback = config.default.APPLICATION_URLS.get("Feedback", "")
if feedback:
dialog.setFeedbackUrl(feedback)
def new_scheme():
if not self.is_transient():
self.new_workflow_window()
dialog.accept()
def open_scheme():
dlg = self._open_workflow_dialog()
dlg.setParent(dialog, Qt.Dialog)
dlg.fileSelected.connect(self.open_scheme_file)
dlg.accepted.connect(dialog.accept)
dlg.exec()
def open_recent():
if self.recent_scheme() == QDialog.Accepted:
dialog.accept()
def browse_examples():
if self.examples_dialog() == QDialog.Accepted:
dialog.accept()
new_action = QAction(
self.tr("New"), dialog,
toolTip=self.tr("Open a new workflow."),
triggered=new_scheme,
shortcut=QKeySequence.New,
icon=load_styled_svg_icon("New.svg")
)
open_action = QAction(
self.tr("Open"), dialog,
objectName="welcome-action-open",
toolTip=self.tr("Open a workflow."),
triggered=open_scheme,
shortcut=QKeySequence.Open,
icon=load_styled_svg_icon("Open.svg")
)
recent_action = QAction(
self.tr("Recent"), dialog,
objectName="welcome-recent-action",
toolTip=self.tr("Browse and open a recent workflow."),
triggered=open_recent,
shortcut=QKeySequence("Ctrl+Shift+R"),
icon=load_styled_svg_icon("Recent.svg")
)
examples_action = QAction(
self.tr("Examples"), dialog,
objectName="welcome-examples-action",
toolTip=self.tr("Browse example workflows."),
triggered=browse_examples,
icon=load_styled_svg_icon("Examples.svg")
)
bottom_row = [self.get_started_action, examples_action,
self.documentation_action]
if self.get_started_screencasts_action.isEnabled():
bottom_row.insert(0, self.get_started_screencasts_action)
self.new_action.triggered.connect(dialog.accept)
top_row = [new_action, open_action, recent_action]
dialog.addRow(top_row, background="light-grass")
dialog.addRow(bottom_row, background="light-orange")
settings = QSettings()
dialog.setShowAtStartup(
settings.value("startup/show-welcome-screen", True, type=bool)
)
status = dialog.exec()
settings.setValue("startup/show-welcome-screen",
dialog.showAtStartup())
dialog.deleteLater()
return status
def scheme_properties_dialog(self):
# type: () -> SchemeInfoDialog
"""Return an empty `SchemeInfo` dialog instance.
"""
settings = QSettings()
value_key = "schemeinfo/show-at-new-scheme"
dialog = SchemeInfoDialog(
self, windowTitle=self.tr("Workflow Info"),
)
dialog.setFixedSize(725, 450)
dialog.setShowAtNewScheme(settings.value(value_key, False, type=bool))
def onfinished():
# type: () -> None
settings.setValue(value_key, dialog.showAtNewScheme())
dialog.finished.connect(onfinished)
return dialog
def show_scheme_properties(self):
# type: () -> int
"""
Show current scheme properties.
"""
current_doc = self.current_document()
scheme = current_doc.scheme()
assert scheme is not None
dlg = self.scheme_properties_dialog()
dlg.setAutoCommit(False)
dlg.setScheme(scheme)
status = dlg.exec()
if status == QDialog.Accepted:
editor = dlg.editor
stack = current_doc.undoStack()
stack.beginMacro(self.tr("Change Info"))
current_doc.setTitle(editor.title())
current_doc.setDescription(editor.description())
stack.endMacro()
return status
def set_signal_freeze(self, freeze):
# type: (bool) -> None
scheme = self.current_document().scheme()
manager = getattr(scheme, "signal_manager", None)
if manager is not None:
if freeze:
manager.pause()
else:
manager.resume()
wm = getattr(scheme, "widget_manager", None)
if wm is not None:
wm.set_creation_policy(
wm.OnDemand if freeze else wm.Normal
)
def remove_selected(self):
# type: () -> None
"""Remove current scheme selection.
"""
self.current_document().removeSelected()
def select_all(self):
# type: () -> None
self.current_document().selectAll()
def open_widget(self):
# type: () -> None
"""Open/raise selected widget's GUI.
"""
self.current_document().openSelected()
def rename_widget(self):
# type: () -> None
"""Rename the current focused widget.
"""
doc = self.current_document()
nodes = doc.selectedNodes()
if len(nodes) == 1:
doc.editNodeTitle(nodes[0])
def open_canvas_settings(self):
# type: () -> None
"""Open canvas settings/preferences dialog
"""
dlg = UserSettingsDialog(self)
dlg.setWindowTitle(self.tr("Preferences"))
dlg.show()
status = dlg.exec()
if status == 0:
self.user_preferences_changed_notify_all()
@staticmethod
def user_preferences_changed_notify_all():
# type: () -> None
"""
Notify all top level `CanvasMainWindow` instances of user
preferences change.
"""
for w in QApplication.topLevelWidgets():
if isinstance(w, CanvasMainWindow) or isinstance(w, QuickMenu):
w.update_from_settings()
def open_addons(self):
# type: () -> int
"""Open the add-on manager dialog.
"""
name = QApplication.applicationName() or "Orange"
from orangecanvas.application.utils.addons import have_install_permissions
if not have_install_permissions():
QMessageBox(QMessageBox.Warning,
"Add-ons: insufficient permissions",
"Insufficient permissions to install add-ons. Try starting {name} "
"as a system administrator or install {name} in user folders."
.format(name=name),
parent=self).exec()
dlg = addons.AddonManagerDialog(
self, windowTitle=self.tr("Installer"), modal=True
)
dlg.setStyle(QApplication.style())
dlg.setAttribute(Qt.WA_DeleteOnClose)
dlg.start(config.default)
return dlg.exec()
def set_float_widgets_on_top_enabled(self, enabled):
# type: (bool) -> None
if self.float_widgets_on_top_action.isChecked() != enabled:
self.float_widgets_on_top_action.setChecked(enabled)
wm = self.current_document().widgetManager()
if wm is not None:
wm.set_float_widgets_on_top(enabled)
def output_view(self):
# type: () -> OutputView
"""Return the output text widget.
"""
return self.output_dock.widget()
def open_about(self):
# type: () -> None
"""Open the about dialog.
"""
dlg = AboutDialog(self)
dlg.setAttribute(Qt.WA_DeleteOnClose)
dlg.exec()
def add_recent_scheme(self, title, path):
# type: (str, str) -> None
"""Add an entry (`title`, `path`) to the list of recent schemes.
"""
if not path:
# No associated persistent path so we can't do anything.
return
text = os.path.basename(path)
if title:
text = "{} ('{}')".format(text, title)
settings = QSettings()
settings.beginGroup("mainwindow")
recent_ = QSettings_readArray(
settings, "recent-items", {"title": str, "path": str}
) # type: List[Dict[str, str]]
recent = [RecentItem(**d) for d in recent_]
filename = os.path.abspath(os.path.realpath(path))
filename = os.path.normpath(filename)
actions_by_filename = {}
for action in self.recent_scheme_action_group.actions():
path = action.data()
if isinstance(path, str):
actions_by_filename[path] = action
if filename in actions_by_filename:
# reuse/update the existing action
action = actions_by_filename[filename]
self.recent_menu.removeAction(action)
self.recent_scheme_action_group.removeAction(action)
action.setText(text)
else:
icons = QFileIconProvider()
icon = icons.icon(QFileInfo(filename))
action = QAction(
icon, text, self, toolTip=filename, iconVisibleInMenu=True
)
action.setData(filename)
# Find the separator action in the menu (after 'Browse Recent')
recent_actions = self.recent_menu.actions()
begin_index = index(recent_actions, self.recent_menu_begin)
action_before = recent_actions[begin_index + 1]
self.recent_menu.insertAction(action_before, action)
self.recent_scheme_action_group.addAction(action)
recent.insert(0, RecentItem(title=title, path=filename))
for i in reversed(range(1, len(recent))):
try:
same = os.path.samefile(recent[i].path, filename)
except OSError:
same = False
if same:
del recent[i]
recent = recent[:self.num_recent_schemes]
QSettings_writeArray(
settings, "recent-items",
[{"title": item.title, "path": item.path} for item in recent]
)
def clear_recent_schemes(self):
# type: () -> None
"""Clear list of recent schemes
"""
actions = self.recent_scheme_action_group.actions()
for action in actions:
self.recent_menu.removeAction(action)
self.recent_scheme_action_group.removeAction(action)
settings = QSettings()
QSettings_writeArray(settings, "mainwindow/recent-items", [])
def _on_recent_scheme_action(self, action):
# type: (QAction) -> None
"""
A recent scheme action was triggered by the user
"""
filename = str(action.data())
self.open_scheme_file(filename)
def _on_dock_location_changed(self, location):
# type: (Qt.DockWidgetArea) -> None
"""Location of the dock_widget has changed, fix the margins
if necessary.
"""
self.__update_scheme_margins()
def set_tool_dock_expanded(self, expanded):
# type: (bool) -> None
"""
Set the dock widget expanded state.
"""
self.dock_widget.setExpanded(expanded)
def _on_tool_dock_expanded(self, expanded):
# type: (bool) -> None
"""
'dock_widget' widget was expanded/collapsed.
"""
if expanded != self.toggle_tool_dock_expand.isChecked():
self.toggle_tool_dock_expand.setChecked(expanded)
def createPopupMenu(self):
# Override the default context menu popup (we don't want the user to
# be able to hide the tool dock widget).
return None
def changeEvent(self, event):
# type: (QEvent) -> None
if event.type() == QEvent.ModifiedChange:
# clear transient flag on any change
self.__is_transient = False
super().changeEvent(event)
def closeEvent(self, event):
# type: (QCloseEvent) -> None
"""
Close the main window.
"""
document = self.current_document()
if document.isModifiedStrict():
if self.ask_save_changes() == QDialog.Rejected:
# Reject the event
event.ignore()
return
self.clear_swp()
old_scheme = document.scheme()
# Set an empty scheme to clear the document
document.setScheme(config.workflow_constructor(parent=self))
if old_scheme is not None:
QApplication.sendEvent(old_scheme, QEvent(QEvent.Close))
old_scheme.deleteLater()
document.usageStatistics().close()
geometry = self.saveGeometry()
state = self.saveState(version=self.SETTINGS_VERSION)
settings = QSettings()
settings.beginGroup("mainwindow")
settings.setValue("geometry", geometry)
settings.setValue("state", state)
settings.setValue("canvasdock/expanded",
self.dock_widget.expanded())
settings.setValue("scheme-margins-enabled",
self.scheme_margins_enabled)
settings.setValue("widgettoolbox/state",
self.widgets_tool_box.saveState())
settings.setValue("quick-help/visible",
self.canvas_tool_dock.quickHelpVisible())
settings.setValue("widgets-float-on-top",
self.float_widgets_on_top_action.isChecked())
settings.endGroup()
self.help_dock.close()
self.output_dock.close()
super().closeEvent(event)
windowlist = WindowListManager.instance()
windowlist.removeWindow(self)
__did_restore = False
def restoreState(self, state, version=0):
# type: (Union[QByteArray, bytes, bytearray], int) -> bool
restored = super().restoreState(state, version)
self.__did_restore = self.__did_restore or restored
return restored
def showEvent(self, event):
# type: (QShowEvent) -> None
if self.__first_show:
settings = QSettings()
settings.beginGroup("mainwindow")
# Restore geometry if not already positioned
if not (self.testAttribute(Qt.WA_Moved) or
self.testAttribute(Qt.WA_Resized)):
geom_data = settings.value("geometry", QByteArray(),
type=QByteArray)
if geom_data:
self.restoreGeometry(geom_data)
state = settings.value("state", QByteArray(), type=QByteArray)
# Restore dock/toolbar state if not already done so
if state and not self.__did_restore:
self.restoreState(state, version=self.SETTINGS_VERSION)
self.__first_show = False
super().showEvent(event)
def quickHelpEvent(self, event: QuickHelpTipEvent) -> None:
if event.priority() == QuickHelpTipEvent.Normal:
self.dock_help.showHelp(event.html())
elif event.priority() == QuickHelpTipEvent.Temporary:
self.dock_help.showHelp(event.html(), event.timeout())
elif event.priority() == QuickHelpTipEvent.Permanent:
self.dock_help.showPermanentHelp(event.html())
event.accept()
def __handle_help_query_response(self, res: Optional[QUrl]):
if res is None:
mb = QMessageBox(
text=self.tr("There is no documentation for this widget."),
windowTitle=self.tr("No help found"),
icon=QMessageBox.Information,
parent=self,
objectName="no-help-found-message-box"
)
mb.setAttribute(Qt.WA_DeleteOnClose)
mb.setWindowModality(Qt.ApplicationModal)
mb.show()
else:
self.show_help(res)
def whatsThisClickedEvent(self, event: QWhatsThisClickedEvent) -> None:
url = QUrl(event.href())
if url.scheme() == "help" and url.authority() == "search":
loop = get_event_loop()
qself = qobjref(self)
async def run(query_coro: Awaitable[QUrl], query: QUrl):
url: Optional[QUrl] = None
try:
url = await query_coro
except (KeyError, futures.TimeoutError):
log.info("No help topic found for %r", query)
self_ = qself()
if self_ is not None:
self_.__handle_help_query_response(url)
loop.create_task(run(self.help.search_async(url), url))
elif url.scheme() == "action" and url.path():
action = self.findChild(QAction, url.path())
if action is not None:
action.trigger()
else:
log.warning("No target action found for %r", url.toString())
def event(self, event):
# type: (QEvent) -> bool
if event.type() == QEvent.StatusTip and \
isinstance(event, QuickHelpTipEvent):
self.quickHelpEvent(event)
if event.isAccepted():
return True
elif event.type() == QEvent.WhatsThisClicked:
event = cast(QWhatsThisClickedEvent, event)
self.whatsThisClickedEvent(event)
return True
return super().event(event)
def show_help(self, url):
# type: (QUrl) -> None
"""
Show `url` in a help window.
"""
log.info("Setting help to url: %r", url)
settings = QSettings()
use_external = settings.value(
"help/open-in-external-browser", defaultValue=False, type=bool)
if use_external or self.help_view is None:
url = QUrl(url)
QDesktopServices.openUrl(url)
else:
self.help_view.load(QUrl(url))
self.help_dock.show()
self.help_dock.raise_()
def toggleMaximized(self) -> None:
"""Toggle normal/maximized window state.
"""
if self.isMinimized(): # Do nothing if window is minimized
return
if self.isMaximized():
self.showNormal()
else:
self.showMaximized()
def sizeHint(self):
# type: () -> QSize
"""
Reimplemented from QMainWindow.sizeHint
"""
hint = super().sizeHint()
return hint.expandedTo(QSize(1024, 720))
def update_from_settings(self):
# type: () -> None
"""
Update the state from changed user preferences.
This method is called on all top level windows (that are subclasses
of CanvasMainWindow) after the preferences dialog is closed.
"""
self.__update_from_settings()
def __update_from_settings(self):
# type: () -> None
settings = QSettings()
settings.beginGroup("mainwindow")
toolbox_floatable = settings.value("toolbox-dock-floatable",
defaultValue=False,
type=bool)
features = self.dock_widget.features()
features = updated_flags(features, QDockWidget.DockWidgetFloatable,
toolbox_floatable)
self.dock_widget.setFeatures(features)
toolbox_exclusive = settings.value("toolbox-dock-exclusive",
defaultValue=False,
type=bool)
self.widgets_tool_box.setExclusive(toolbox_exclusive)
self.num_recent_schemes = settings.value("num-recent-schemes",
defaultValue=15,
type=int)
float_widgets_on_top = settings.value("widgets-float-on-top",
defaultValue=False,
type=bool)
self.set_float_widgets_on_top_enabled(float_widgets_on_top)
settings.endGroup()
settings.beginGroup("quickmenu")
triggers = 0
dbl_click = settings.value("trigger-on-double-click",
defaultValue=True,
type=bool)
if dbl_click:
triggers |= SchemeEditWidget.DoubleClicked
right_click = settings.value("trigger-on-right-click",
defaultValue=True,
type=bool)
if right_click:
triggers |= SchemeEditWidget.RightClicked
space_press = settings.value("trigger-on-space-key",
defaultValue=True,
type=bool)
if space_press:
triggers |= SchemeEditWidget.SpaceKey
any_press = settings.value("trigger-on-any-key",
defaultValue=False,
type=bool)
if any_press:
triggers |= SchemeEditWidget.AnyKey
self.scheme_widget.setQuickMenuTriggers(triggers)
settings.endGroup()
settings.beginGroup("schemeedit")
show_channel_names = settings.value("show-channel-names",
defaultValue=True,
type=bool)
self.scheme_widget.setChannelNamesVisible(show_channel_names)
open_anchors_ = settings.value(
"open-anchors-on-hover", defaultValue=False, type=bool
)
if open_anchors_:
open_anchors = SchemeEditWidget.OpenAnchors.Always
else:
open_anchors = SchemeEditWidget.OpenAnchors.OnShift
self.scheme_widget.setOpenAnchorsMode(open_anchors)
node_animations = settings.value("enable-node-animations",
defaultValue=False,
type=bool)
self.scheme_widget.setNodeAnimationEnabled(node_animations)
settings.endGroup()
self.__update_registry_filters()
def __update_registry_filters(self):
# type: () -> None
if self.widget_registry is None:
return
settings = QSettings()
visible_state = {}
for cat in self.widget_registry.categories():
visible, _ = category_state(cat, settings)
visible_state[cat.name] = visible
if self.__proxy_model is not None:
self.__proxy_model.setFilters([
FilterProxyModel.Filter(
0, QtWidgetRegistry.CATEGORY_DESC_ROLE,
category_filter_function(visible_state))
])
def connect_output_stream(self, stream: TextStream):
"""
Connect a :class:`TextStream` instance to this window's output view.
The `stream` will be 'inherited' by new windows created by
`create_new_window`.
"""
doc = self.output_view().document()
doc.connectStream(stream)
def disconnect_output_stream(self, stream: TextStream):
"""
Disconnect a :class:`TextStream` instance from this window's
output view.
"""
doc = self.output_view().document()
doc.disconnectStream(stream)
def updated_flags(flags, mask, state):
return set_flag(flags, mask, state)
def identity(item):
return item
def index(sequence, *what, **kwargs):
"""index(sequence, what, [key=None, [predicate=None]])
Return index of `what` in `sequence`.
"""
what = what[0]
key = kwargs.get("key", identity)
predicate = kwargs.get("predicate", operator.eq)
for i, item in enumerate(sequence):
item_key = key(item)
if predicate(what, item_key):
return i
raise ValueError("%r not in sequence" % what)
def category_filter_function(state):
# type: (Dict[str, bool]) -> Callable[[Any], bool]
def category_filter(desc):
if not isinstance(desc, CategoryDescription):
# Is not a category item
return True
return state.get(desc.name, not desc.hidden)
return category_filter
class UrlDropEventFilter(QObject):
urlDropped = Signal(QUrl)
def acceptsDrop(self, mime: QMimeData) -> bool:
if mime.hasUrls() and len(mime.urls()) == 1:
url = mime.urls()[0]
if url.scheme() == "file":
filename = url.toLocalFile()
_, ext = os.path.splitext(filename)
if ext == ".ows":
return True
return False
def eventFilter(self, obj, event):
etype = event.type()
if etype == QEvent.DragEnter or etype == QEvent.DragMove:
if self.acceptsDrop(event.mimeData()):
event.acceptProposedAction()
return True
elif etype == QEvent.Drop:
if self.acceptsDrop(event.mimeData()):
urls = event.mimeData().urls()
if urls:
url = urls[0]
self.urlDropped.emit(url)
return True
return super().eventFilter(obj, event)
class RecentItem(SimpleNamespace):
title = "" # type: str
path = "" # type: str
def scheme_requires(
stream: IO, registry: Optional[WidgetRegistry] = None
) -> List[str]:
"""
Inspect the given ows workflow `stream` and return a list of project names
recorded as implementers of the contained nodes.
Nodes are first mapped through any `replaces` entries in `registry` first.
"""
# parse to 'intermediate' form and run replacements with registry.
desc = readwrite.parse_ows_stream(stream)
if registry is not None:
desc = readwrite.resolve_replaced(desc, registry)
return list(unique(m.project_name for m in desc.nodes if m.project_name))
K = TypeVar("K")
V = TypeVar("V")
def render_error_details(errors: Iterable[Exception]) -> str:
"""
Render a detailed error report for observed errors during workflow load.
Parameters
----------
errors : Iterable[Exception]
Returns
-------
text: str
"""
def collectall(
items: Iterable[Tuple[K, Iterable[V]]], pred: Callable[[K], bool]
) -> Sequence[V]:
return reduce(
list.__iadd__, (v for k, v in items if pred(k)),
[]
)
errors_by_type = group_by_all(errors, key=type)
missing_node_defs = collectall(
errors_by_type, lambda k: issubclass(k, UnknownWidgetDefinition)
)
link_type_erors = collectall(
errors_by_type, lambda k: issubclass(k, IncompatibleChannelTypeError)
)
other = collectall(
errors_by_type,
lambda k: not issubclass(k, (UnknownWidgetDefinition,
IncompatibleChannelTypeError))
)
contents = []
if missing_node_defs is not None:
contents.extend([
"Missing node definitions:",
*[" \N{BULLET} " + e.args[0] for e in missing_node_defs],
"",
# "(possibly due to missing install requirements)"
])
if link_type_erors:
contents.extend([
"Incompatible connection types:",
*[" \N{BULLET} " + e.args[0] for e in link_type_erors],
""
])
if other:
def format_exception(e: BaseException):
return "".join(traceback.format_exception_only(type(e), e))
contents.extend([
"Unqualified errors:",
*[" \N{BULLET} " + format_exception(e) for e in other]
])
return "\n".join(contents)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/canvastooldock.py 0000664 0001750 0001750 00000056536 14625071541 024614 0 ustar 00marko marko """
Orange Canvas Tool Dock widget
"""
import sys
import warnings
from typing import Optional, Any
from AnyQt.QtWidgets import (
QWidget, QSplitter, QVBoxLayout, QAction, QSizePolicy, QApplication,
QToolButton, QTreeView
)
from AnyQt.QtGui import (
QPalette, QBrush, QDrag, QResizeEvent, QHideEvent, QPaintEvent
)
from AnyQt.QtCore import (
Qt, QSize, QObject, QPropertyAnimation, QEvent, QRect, QPoint,
QAbstractItemModel, QModelIndex, QPersistentModelIndex, QEventLoop,
QMimeData
)
from AnyQt.QtCore import pyqtProperty as Property, pyqtSignal as Signal
from .. import styles
from ..gui.iconengine import StyledIconEngine
from ..gui.toolgrid import ToolGrid, ToolGridButton
from ..gui.toolbar import DynamicResizeToolBar
from ..gui.quickhelp import QuickHelp
from ..gui.framelesswindow import FramelessWindow
from ..gui.utils import create_css_gradient, available_screen_geometry
from ..document.quickmenu import MenuPage
from .widgettoolbox import WidgetToolBox, iter_index, item_text, item_icon, item_tooltip
from ..registry.qt import QtWidgetRegistry
class SplitterResizer(QObject):
"""
An object able to control the size of a widget in a QSplitter instance.
"""
def __init__(self, parent=None, **kwargs):
# type: (Optional[QObject], Any) -> None
super().__init__(parent, **kwargs)
self.__splitter = None # type: Optional[QSplitter]
self.__widget = None # type: Optional[QWidget]
self.__updateOnShow = True # Need __update on next show event
self.__animationEnabled = True
self.__size = -1
self.__expanded = False
self.__animation = QPropertyAnimation(
self, b"size_", self, duration=200
)
self.__action = QAction("toggle-expanded", self, checkable=True)
self.__action.triggered[bool].connect(self.setExpanded)
def setSize(self, size):
# type: (int) -> None
"""
Set the size of the controlled widget (either width or height
depending on the orientation).
.. note::
The controlled widget's size is only updated when it it is shown.
"""
if self.__size != size:
self.__size = size
self.__update()
def size(self):
# type: () -> int
"""
Return the size of the widget in the splitter (either height of
width) depending on the splitter orientation.
"""
if self.__splitter and self.__widget:
index = self.__splitter.indexOf(self.__widget)
sizes = self.__splitter.sizes()
return sizes[index]
else:
return -1
size_ = Property(int, fget=size, fset=setSize)
def setAnimationEnabled(self, enable):
# type: (bool) -> None
"""Enable/disable animation."""
self.__animation.setDuration(0 if enable else 200)
def animationEnabled(self):
# type: () -> bool
return self.__animation.duration() == 0
def setSplitterAndWidget(self, splitter, widget):
# type: (QSplitter, QWidget) -> None
"""Set the QSplitter and QWidget instance the resizer should control.
.. note:: the widget must be in the splitter.
"""
if splitter and widget and not splitter.indexOf(widget) > 0:
raise ValueError("Widget must be in a splitter.")
if self.__widget is not None:
self.__widget.removeEventFilter(self)
if self.__splitter is not None:
self.__splitter.removeEventFilter(self)
self.__splitter = splitter
self.__widget = widget
if widget is not None:
widget.installEventFilter(self)
if splitter is not None:
splitter.installEventFilter(self)
self.__update()
size = self.size()
if self.__expanded and size == 0:
self.open()
elif not self.__expanded and size > 0:
self.close()
def toggleExpandedAction(self):
# type: () -> QAction
"""Return a QAction that can be used to toggle expanded state.
"""
return self.__action
def toogleExpandedAction(self):
warnings.warn(
"'toogleExpandedAction is deprecated, use 'toggleExpandedAction' "
"instead.", DeprecationWarning, stacklevel=2
)
return self.toggleExpandedAction()
def open(self):
# type: () -> None
"""Open the controlled widget (expand it to sizeHint).
"""
self.__expanded = True
self.__action.setChecked(True)
if self.__splitter is None or self.__widget is None:
return
hint = self.__widget.sizeHint()
if self.__splitter.orientation() == Qt.Vertical:
end = hint.height()
else:
end = hint.width()
self.__animation.setStartValue(0)
self.__animation.setEndValue(end)
self.__animation.start()
def close(self):
# type: () -> None
"""Close the controlled widget (shrink to size 0).
"""
self.__expanded = False
self.__action.setChecked(False)
if self.__splitter is None or self.__widget is None:
return
self.__animation.setStartValue(self.size())
self.__animation.setEndValue(0)
self.__animation.start()
def setExpanded(self, expanded):
# type: (bool) -> None
"""Set the expanded state."""
if self.__expanded != expanded:
if expanded:
self.open()
else:
self.close()
def expanded(self):
# type: () -> bool
"""Return the expanded state."""
return self.__expanded
def __update(self):
# type: () -> None
"""Update the splitter sizes."""
if self.__splitter and self.__widget:
if sum(self.__splitter.sizes()) == 0:
# schedule update on next show event
self.__updateOnShow = True
return
splitter = self.__splitter
index = splitter.indexOf(self.__widget)
sizes = splitter.sizes()
current = sizes[index]
diff = current - self.__size
sizes[index] = self.__size
sizes[index - 1] = sizes[index - 1] + diff
self.__splitter.setSizes(sizes)
def eventFilter(self, obj, event):
# type: (QObject, QEvent) -> bool
if event.type() == QEvent.Resize and obj is self.__widget and \
self.__animation.state() == QPropertyAnimation.Stopped:
# Update the expanded state when the user opens/closes the widget
# by dragging the splitter handle.
assert self.__splitter is not None
assert isinstance(event, QResizeEvent)
if self.__splitter.orientation() == Qt.Vertical:
size = event.size().height()
else:
size = event.size().width()
if self.__expanded and size == 0:
self.__action.setChecked(False)
self.__expanded = False
elif not self.__expanded and size > 0:
self.__action.setChecked(True)
self.__expanded = True
if event.type() == QEvent.Show and obj is self.__splitter and \
self.__updateOnShow:
# Update the splitter state after receiving valid geometry
self.__updateOnShow = False
self.__update()
return super().eventFilter(obj, event)
class QuickHelpWidget(QuickHelp):
def minimumSizeHint(self):
# type: () -> QSize
"""Reimplemented to allow the Splitter to resize the widget
with a continuous animation.
"""
hint = super().minimumSizeHint()
return QSize(hint.width(), 0)
class CanvasToolDock(QWidget):
"""Canvas dock widget with widget toolbox, quick help and
canvas actions.
"""
def __init__(self, parent=None, **kwargs):
# type: (Optional[QWidget], Any) -> None
super().__init__(parent, **kwargs)
self.__setupUi()
def __setupUi(self):
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.toolbox = WidgetToolBox()
self.help = QuickHelpWidget(objectName="quick-help")
self.__splitter = QSplitter()
self.__splitter.setOrientation(Qt.Vertical)
self.__splitter.addWidget(self.toolbox)
self.__splitter.addWidget(self.help)
self.toolbar = DynamicResizeToolBar()
self.toolbar.setMovable(False)
self.toolbar.setFloatable(False)
self.toolbar.setSizePolicy(QSizePolicy.Ignored,
QSizePolicy.Preferred)
layout.addWidget(self.__splitter, 10)
layout.addWidget(self.toolbar)
self.setLayout(layout)
self.__splitterResizer = SplitterResizer(self)
self.__splitterResizer.setSplitterAndWidget(self.__splitter, self.help)
def setQuickHelpVisible(self, state):
# type: (bool) -> None
"""Set the quick help box visibility status."""
self.__splitterResizer.setExpanded(state)
def quickHelpVisible(self):
# type: () -> bool
return self.__splitterResizer.expanded()
def setQuickHelpAnimationEnabled(self, enabled):
# type: (bool) -> None
"""Enable/disable the quick help animation."""
self.__splitterResizer.setAnimationEnabled(enabled)
def toggleQuickHelpAction(self):
# type: () -> QAction
"""Return a checkable QAction for help show/hide."""
return self.__splitterResizer.toggleExpandedAction()
def toogleQuickHelpAction(self):
warnings.warn(
"'toogleQuickHelpAction' is deprecated, use "
"'toggleQuickHelpAction' instead.", DeprecationWarning,
stacklevel=2
)
return self.toggleQuickHelpAction()
class _ToolGridButton(ToolGridButton):
def paintEvent(self, event: QPaintEvent) -> None:
with StyledIconEngine.setOverridePalette(styles.breeze_light()):
super().paintEvent(event)
class QuickCategoryToolbar(ToolGrid):
"""A toolbar with category buttons."""
def __init__(self, parent=None, buttonSize=QSize(), iconSize=QSize(),
**kwargs):
# type: (Optional[QWidget], QSize, QSize, Any) -> None
super().__init__(parent, 1, buttonSize, iconSize,
Qt.ToolButtonIconOnly, **kwargs)
self.__model = None # type: Optional[QAbstractItemModel]
def setColumnCount(self, count):
raise Exception("Cannot set the column count on a Toolbar")
def setModel(self, model):
# type: (Optional[QAbstractItemModel]) -> None
"""
Set the registry model.
"""
if self.__model is not None:
self.__model.dataChanged.disconnect(self.__on_dataChanged)
self.__model.rowsInserted.disconnect(self.__on_rowsInserted)
self.__model.rowsRemoved.disconnect(self.__on_rowsRemoved)
self.clear()
self.__model = model
if model is not None:
model.dataChanged.connect(self.__on_dataChanged)
model.rowsInserted.connect(self.__on_rowsInserted)
model.rowsRemoved.connect(self.__on_rowsRemoved)
self.__initFromModel(model)
def __initFromModel(self, model):
# type: (QAbstractItemModel) -> None
"""
Initialize the toolbar from the model.
"""
for index in iter_index(model, QModelIndex()):
action = self.createActionForItem(index)
self.addAction(action)
def createActionForItem(self, index):
# type: (QModelIndex) -> QAction
"""
Create the QAction instance for item at `index` (`QModelIndex`).
"""
action = QAction(
item_icon(index), item_text(index), self,
toolTip=item_tooltip(index)
)
action.setData(QPersistentModelIndex(index))
return action
def createButtonForAction(self, action):
# type: (QAction) -> QToolButton
"""
Create a button for the action.
"""
button = _ToolGridButton(
self,
toolButtonStyle=self.toolButtonStyle(),
iconSize=self.iconSize(),
)
button.setDefaultAction(action)
if self.buttonSize().isValid():
button.setFixedSize(self.buttonSize())
item = action.data() # QPersistentModelIndex
assert isinstance(item, QPersistentModelIndex)
brush = item.data(Qt.BackgroundRole)
if not isinstance(brush, QBrush):
brush = item.data(QtWidgetRegistry.BACKGROUND_ROLE)
if not isinstance(brush, QBrush):
brush = self.palette().brush(QPalette.Button)
palette = button.palette()
palette.setColor(QPalette.Button, brush.color())
palette.setColor(QPalette.Window, brush.color())
button.setPalette(palette)
button.setProperty("quick-category-toolbutton", True)
style_sheet = ("QToolButton {\n"
" background: %s;\n"
" border: none;\n"
" border-bottom: 1px solid palette(mid);\n"
"}")
button.setStyleSheet(style_sheet % create_css_gradient(brush.color()))
return button
def __on_dataChanged(self, topLeft, bottomRight):
# type: (QModelIndex, QModelIndex) -> None
assert self.__model is not None
parent = topLeft.parent()
if not parent.isValid():
for row in range(topLeft.row(), bottomRight.row() + 1):
item = self.__model.index(row, 0)
action = self.actions()[row]
action.setText(item_text(item))
action.setIcon(item_icon(item))
action.setToolTip(item_tooltip(item))
def __on_rowsInserted(self, parent, start, end):
# type: (QModelIndex, int, int) -> None
assert self.__model is not None
if not parent.isValid():
for row in range(start, end + 1):
item = self.__model.index(row, 0)
self.insertAction(row, self.createActionForItem(item))
def __on_rowsRemoved(self, parent, start, end):
# type: (QModelIndex, int, int) -> None
assert self.__model is not None
if not parent.isValid():
for row in range(end, start - 1, -1):
action = self.actions()[row]
self.removeAction(action)
# This implements the (single category) node selection popup when the
# tooldock is not expanded.
class CategoryPopupMenu(FramelessWindow):
"""
A menu popup from which nodes can be dragged or clicked/activated.
"""
triggered = Signal(QAction)
hovered = Signal(QAction)
def __init__(self, parent=None, **kwargs):
# type: (Optional[QWidget], Any) -> None
super().__init__(parent, **kwargs)
self.setWindowFlags(self.windowFlags() | Qt.Popup)
layout = QVBoxLayout()
layout.setContentsMargins(6, 6, 6, 6)
self.__menu = MenuPage()
self.__menu.setActionRole(QtWidgetRegistry.WIDGET_ACTION_ROLE)
if sys.platform == "darwin":
self.__menu.view().setAttribute(Qt.WA_MacShowFocusRect, False)
self.__menu.triggered.connect(self.__onTriggered)
self.__menu.hovered.connect(self.hovered)
self.__dragListener = ItemViewDragStartEventListener(self)
self.__dragListener.dragStarted.connect(self.__onDragStarted)
self.__menu.view().viewport().installEventFilter(self.__dragListener)
self.__menu.view().installEventFilter(self)
layout.addWidget(self.__menu)
self.setLayout(layout)
self.__action = None # type: Optional[QAction]
self.__loop = None # type: Optional[QEventLoop]
def setCategoryItem(self, item):
"""
Set the category root item (:class:`QStandardItem`).
"""
warnings.warn(
"setCategoryItem is deprecated. Use the more general 'setModel'"
"and setRootIndex", DeprecationWarning, stacklevel=2
)
model = item.model()
self.__menu.setModel(model)
self.__menu.setRootIndex(item.index())
def setModel(self, model):
# type: (QAbstractItemModel) -> None
"""
Set the model.
Parameters
----------
model : QAbstractItemModel
"""
self.__menu.setModel(model)
def setRootIndex(self, index):
# type: (QModelIndex) -> None
"""
Set the root index in `model`.
Parameters
----------
index : QModelIndex
"""
self.__menu.setRootIndex(index)
def setActionRole(self, role):
# type: (Qt.ItemDataRole) -> None
"""
Set the action role in model.
This is an item role in `model` that returns a QAction for the item.
Parameters
----------
role : Qt.ItemDataRole
"""
self.__menu.setActionRole(role)
def popup(self, pos=None):
# type: (Optional[QPoint]) -> None
"""
Show the popup at `pos`.
Parameters
----------
pos : Optional[QPoint]
The position in global screen coordinates
"""
if pos is None:
pos = self.pos()
self.adjustSize()
geom = widget_popup_geometry(pos, self)
self.setGeometry(geom)
self.show()
self.__menu.view().setFocus()
def exec(self, pos=None):
# type: (Optional[QPoint]) -> Optional[QAction]
self.popup(pos)
self.__loop = QEventLoop()
self.__action = None
self.__loop.exec()
self.__loop = None
if self.__action is not None:
action = self.__action
else:
action = None
return action
def exec_(self, *args, **kwargs):
warnings.warn(
"exec_ is deprecated, use exec", DeprecationWarning, stacklevel=2
)
return self.exec(*args, **kwargs)
def hideEvent(self, event):
# type: (QHideEvent) -> None
if self.__loop is not None:
self.__loop.exit(0)
super().hideEvent(event)
def __onTriggered(self, action):
# type: (QAction) -> None
self.__action = action
self.triggered.emit(action)
self.hide()
if self.__loop:
self.__loop.exit(0)
def __onDragStarted(self, index):
# type: (QModelIndex) -> None
desc = index.data(QtWidgetRegistry.WIDGET_DESC_ROLE)
icon = index.data(Qt.DecorationRole)
drag_data = QMimeData()
drag_data.setData(
"application/vnd.orange-canvas.registry.qualified-name",
desc.qualified_name.encode('utf-8')
)
drag = QDrag(self)
drag.setPixmap(icon.pixmap(38))
drag.setMimeData(drag_data)
# TODO: Should animate (accept) hide.
self.hide()
# When a drag is started and the menu hidden the item's tool tip
# can still show for a short time UNDER the cursor preventing a
# drop.
viewport = self.__menu.view().viewport()
filter = ToolTipEventFilter()
viewport.installEventFilter(filter)
drag.exec(Qt.CopyAction)
viewport.removeEventFilter(filter)
def eventFilter(self, obj, event):
if isinstance(obj, QTreeView) and event.type() == QEvent.KeyPress:
key = event.key()
if key in [Qt.Key_Return, Qt.Key_Enter]:
curr = obj.currentIndex()
if curr.isValid():
obj.activated.emit(curr)
return True
return super().eventFilter(obj, event)
class ItemViewDragStartEventListener(QObject):
dragStarted = Signal(QModelIndex)
def __init__(self, parent=None, **kwargs):
# type: (Optional[QObject], Any) -> None
super().__init__(parent, **kwargs)
self._pos = None # type: Optional[QPoint]
self._index = None # type: Optional[QPersistentModelIndex]
def eventFilter(self, viewport, event):
# type: (QObject, QEvent) -> bool
view = viewport.parent()
if event.type() == QEvent.MouseButtonPress and \
event.button() == Qt.LeftButton:
index = view.indexAt(event.pos())
if index is not None:
self._pos = event.pos()
self._index = QPersistentModelIndex(index)
elif event.type() == QEvent.MouseMove and self._pos is not None and \
((self._pos - event.pos()).manhattanLength() >=
QApplication.startDragDistance()):
assert self._index is not None
if self._index.isValid():
# Map to a QModelIndex in the model.
index = QModelIndex(self._index)
self._pos = None
self._index = None
self.dragStarted.emit(index)
return super().eventFilter(view, event)
class ToolTipEventFilter(QObject):
def eventFilter(self, receiver, event):
# type: (QObject, QEvent) -> bool
if event.type() == QEvent.ToolTip:
return True
return super().eventFilter(receiver, event)
def widget_popup_geometry(pos, widget):
# type: (QPoint, QWidget) -> QRect
widget.ensurePolished()
if widget.testAttribute(Qt.WA_Resized):
size = widget.size()
else:
size = widget.sizeHint()
screen = QApplication.screenAt(pos)
if screen is None:
screen = QApplication.primaryScreen()
screen_geom = screen.availableGeometry()
size = size.boundedTo(screen_geom.size())
geom = QRect(pos, size)
if geom.top() < screen_geom.top():
geom.moveTop(screen_geom.top())
if geom.left() < screen_geom.left():
geom.moveLeft(screen_geom.left())
bottom_margin = screen_geom.bottom() - geom.bottom()
right_margin = screen_geom.right() - geom.right()
if bottom_margin < 0:
# Falls over the bottom of the screen, move it up.
geom.translate(0, bottom_margin)
# TODO: right to left locale
if right_margin < 0:
# Falls over the right screen edge, move the menu to the
# other side of pos.
geom.translate(-size.width(), 0)
return geom
def popup_position_from_source(popup, source, orientation=Qt.Vertical):
# type: (QWidget, QWidget, Qt.Orientation) -> QPoint
popup.ensurePolished()
source.ensurePolished()
if popup.testAttribute(Qt.WA_Resized):
size = popup.size()
else:
size = popup.sizeHint()
screen_geom = available_screen_geometry(source)
source_rect = QRect(source.mapToGlobal(QPoint(0, 0)), source.size())
if orientation == Qt.Vertical:
if source_rect.right() + size.width() < screen_geom.right():
x = source_rect.right()
else:
x = source_rect.left() - size.width()
# bottom overflow
dy = source_rect.top() + size.height() - screen_geom.bottom()
if dy < 0:
y = source_rect.top()
else:
y = max(screen_geom.top(), source_rect.top() - dy)
else:
# right overflow
dx = source_rect.left() + size.width() - screen_geom.right()
if dx < 0:
x = source_rect.left()
else:
x = max(source_rect.left() - dx, screen_geom.left())
if source_rect.bottom() + size.height() < screen_geom.bottom():
y = source_rect.bottom()
else:
y = source_rect.top() - size.height()
return QPoint(x, y)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/examples.py 0000664 0001750 0001750 00000006645 14625071541 023414 0 ustar 00marko marko """
Example workflows discovery.
"""
import os
import logging
import pathlib
import types
from typing import List, Optional, IO
from orangecanvas import config as _config
from orangecanvas.utils.pkgmeta import Distribution
try:
from importlib.resources import files as _files
except ImportError:
from importlib_resources import files as _files
log = logging.getLogger(__name__)
def list_workflows(package):
# type: (types.ModuleType) -> List[str]
"""
Return a list of .ows files in the located next to `package`.
"""
def is_ows(filename):
# type: (str) -> bool
return filename.endswith(".ows")
resources = _files(package.__name__).iterdir()
return sorted(filter(is_ows, (r.name for r in resources)))
def workflows(config=None):
# type: (Optional[_config.Config]) -> List[ExampleWorkflow]
"""
Return all known example workflows.
"""
if config is None:
config = _config.default
workflows = [] # type: List[ExampleWorkflow]
if hasattr(config, "tutorials_entry_points") and \
callable(config.tutorials_entry_points):
# back compatibility
examples_entry_points = config.tutorials_entry_points
else:
examples_entry_points = config.examples_entry_points
for ep in examples_entry_points():
try:
examples = ep.load()
except Exception:
log.error("Could not load examples from %r",
ep.dist, exc_info=True)
continue
if isinstance(examples, types.ModuleType):
package = examples
examples = [ExampleWorkflow(t, package, ep.dist)
for t in list_workflows(package)]
elif isinstance(examples, (types.FunctionType, types.MethodType)):
try:
examples = examples()
except Exception as ex:
log.error("A callable entry point (%r) raised an "
"unexpected error.",
ex, exc_info=True)
continue
examples = [ExampleWorkflow(t, package=None, distribution=ep.dist)
for t in examples]
workflows.extend(examples)
return workflows
class ExampleWorkflow:
def __init__(self, resource, package=None, distribution=None):
# type: (str, Optional[types.ModuleType], Optional[Distribution]) -> None
self.resource = resource
self.package = package
self.distribution = distribution
def abspath(self) -> str:
"""
Return absolute filename for the workflow if possible else
raise an ValueError.
"""
if self.package is not None:
item = _files(self.package) / self.resource
if isinstance(item, pathlib.Path):
return str(item)
elif isinstance(self.resource, str):
if os.path.isabs(self.resource):
return self.resource
raise ValueError("cannot resolve resource to an absolute name")
def stream(self) -> IO[bytes]:
"""
Return the example file as an open stream.
"""
if self.package is not None:
item = _files(self.package) / self.resource
return item.open('rb')
elif isinstance(self.resource, str):
if os.path.isabs(self.resource) and os.path.exists(self.resource):
return open(self.resource, "rb")
raise ValueError
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/outputview.py 0000664 0001750 0001750 00000034404 14625071541 024023 0 ustar 00marko marko """
"""
import io
import sys
import warnings
import traceback
from types import TracebackType
from typing import Any, Optional, List, Type, Iterable, Tuple, Union, Mapping
from AnyQt.QtWidgets import (
QWidget, QPlainTextEdit, QVBoxLayout, QSizePolicy, QPlainTextDocumentLayout
)
from AnyQt.QtGui import (
QTextCursor, QTextCharFormat, QTextOption, QFontDatabase, QTextDocument,
QTextDocumentFragment
)
from AnyQt.QtCore import Qt, QObject, QCoreApplication, QThread, QSize
from AnyQt.QtCore import pyqtSignal as Signal, pyqtSlot as Slot
from orangecanvas.gui.utils import update_char_format
from orangecanvas.utils import findf
class TerminalView(QPlainTextEdit):
def __init__(self, *args, **kwargs):
# type: (Any, Any) -> None
super().__init__(*args, **kwargs)
self.setFrameStyle(QPlainTextEdit.NoFrame)
self.setTextInteractionFlags(Qt.TextBrowserInteraction)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
font = QFontDatabase.systemFont(QFontDatabase.FixedFont)
self.setFont(font)
self.setAttribute(Qt.WA_SetFont, False)
def sizeHint(self):
# type: () -> QSize
metrics = self.fontMetrics()
width = metrics.boundingRect("X" * 81).width()
height = metrics.lineSpacing()
scroll_width = self.verticalScrollBar().width()
size = QSize(width + scroll_width, height * 25)
return size
class TerminalTextDocument(QTextDocument):
def __init__(self, parent=None, **kwargs):
super().__init__(parent, **kwargs)
self.setDocumentLayout(QPlainTextDocumentLayout(self))
self.__currentCharFormat = QTextCharFormat()
if 'defaultFont' not in kwargs:
defaultFont = QFontDatabase.systemFont(QFontDatabase.FixedFont)
self.setDefaultFont(defaultFont)
self.__streams = []
def setCurrentCharFormat(self, charformat: QTextCharFormat) -> None:
"""Set the QTextCharFormat to be used when writing."""
assert QThread.currentThread() is self.thread()
if self.__currentCharFormat != charformat:
self.__currentCharFormat = QTextCharFormat(charformat)
def currentCharFormat(self) -> QTextCharFormat:
"""Return the current char format."""
return QTextCharFormat(self.__currentCharFormat)
def textCursor(self) -> QTextCursor:
"""Return a text cursor positioned at the end of the document."""
cursor = QTextCursor(self)
cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)
cursor.setCharFormat(self.__currentCharFormat)
return cursor
# ----------------------
# A file like interface.
# ----------------------
@Slot(str)
def write(self, string: str) -> None:
assert QThread.currentThread() is self.thread()
cursor = self.textCursor()
cursor.insertText(string)
@Slot(object)
def writelines(self, lines: Iterable[str]) -> None:
assert QThread.currentThread() is self.thread()
self.write("".join(lines))
@Slot()
def flush(self) -> None:
assert QThread.currentThread() is self.thread()
def writeWithFormat(self, string: str, charformat: QTextCharFormat) -> None:
assert QThread.currentThread() is self.thread()
cursor = self.textCursor()
cursor.setCharFormat(charformat)
cursor.insertText(string)
def writelinesWithFormat(self, lines, charformat):
# type: (List[str], QTextCharFormat) -> None
self.writeWithFormat("".join(lines), charformat)
def formatted(self, color=None, background=None, weight=None,
italic=None, underline=None, font=None):
# type: (...) -> Formatter
"""
Return a formatted file like object proxy.
"""
charformat = update_char_format(
self.currentCharFormat(), color, background, weight,
italic, underline, font
)
return Formatter(self, charformat)
__streams: List[Tuple['TextStream', Optional['Formatter']]]
def connectedStreams(self) -> List['TextStream']:
"""Return all streams connected using `connectStream`."""
return [s for s, _ in self.__streams]
def connectStream(
self, stream: 'TextStream',
charformat: Optional[QTextCharFormat] = None,
**kwargs
) -> None:
"""
Connect a :class:`TextStream` instance to this document.
The `stream` connection will be 'inherited' by `clone()`
"""
if kwargs and charformat is not None:
raise TypeError("'charformat' and kwargs cannot be used together")
if kwargs:
charformat = update_char_format(QTextCharFormat(), **kwargs)
writer: Optional[Formatter] = None
if charformat is not None:
writer = Formatter(self, charformat)
self.__streams.append((stream, writer))
if writer is not None:
stream.stream.connect(writer.write)
else:
stream.stream.connect(self.write)
def disconnectStream(self, stream: 'TextStream'):
"""
Disconnect a :class:`TextStream` instance from this document.
"""
item = findf(self.__streams, lambda t: t[0] is stream)
if item is not None:
self.__streams.remove(item)
_, writer = item
if writer is not None:
stream.stream.disconnect(writer.write)
else:
stream.stream.disconnect(self.write)
def clone(self, parent=None) -> 'TerminalTextDocument':
"""Create a new TerminalTextDocument that is a copy of this document."""
clone = type(self)()
clone.setParent(parent)
clone.setDocumentLayout(QPlainTextDocumentLayout(clone))
cursor = QTextCursor(clone)
cursor.insertFragment(QTextDocumentFragment(self))
clone.rootFrame().setFrameFormat(self.rootFrame().frameFormat())
clone.setDefaultStyleSheet(self.defaultStyleSheet())
clone.setDefaultFont(self.defaultFont())
clone.setDefaultTextOption(self.defaultTextOption())
clone.setCurrentCharFormat(self.currentCharFormat())
for s, w in self.__streams:
clone.connectStream(s, w.charformat if w is not None else None)
return clone
class OutputView(QWidget):
def __init__(self, parent=None, **kwargs):
# type: (Optional[QWidget], Any) -> None
super().__init__(parent, **kwargs)
self.__lines = 5000
self.setLayout(QVBoxLayout())
self.layout().setContentsMargins(0, 0, 0, 0)
self.__text = TerminalView()
self.__text.setDocument(TerminalTextDocument(self.__text))
self.__text.setWordWrapMode(QTextOption.NoWrap)
self.__text.setMaximumBlockCount(self.__lines)
self.layout().addWidget(self.__text)
def setMaximumLines(self, lines):
# type: (int) -> None
"""
Set the maximum number of lines to keep displayed.
"""
if self.__lines != lines:
self.__lines = lines
self.__text.setMaximumBlockCount(lines)
def maximumLines(self):
# type: () -> int
"""
Return the maximum number of lines in the display.
"""
return self.__lines
def clear(self):
# type: () -> None
"""
Clear the displayed text.
"""
assert QThread.currentThread() is self.thread()
self.__text.clear()
def setCurrentCharFormat(self, charformat):
# type: (QTextCharFormat) -> None
"""Set the QTextCharFormat to be used when writing.
"""
assert QThread.currentThread() is self.thread()
self.document().setCurrentCharFormat(charformat)
def currentCharFormat(self):
# type: () -> QTextCharFormat
return QTextCharFormat(self.document().currentCharFormat())
def toPlainText(self):
# type: () -> str
"""
Return the full contents of the output view.
"""
return self.__text.toPlainText()
# A file like interface.
@Slot(str)
def write(self, string):
# type: (str) -> None
assert QThread.currentThread() is self.thread()
doc = self.document()
doc.write(string)
@Slot(object)
def writelines(self, lines):
# type: (List[str]) -> None
assert QThread.currentThread() is self.thread()
self.write("".join(lines))
@Slot()
def flush(self):
# type: () -> None
assert QThread.currentThread() is self.thread()
def writeWithFormat(self, string, charformat):
# type: (str, QTextCharFormat) -> None
assert QThread.currentThread() is self.thread()
doc = self.document()
doc.writeWithFormat(string, charformat)
def writelinesWithFormat(self, lines, charformat):
# type: (List[str], QTextCharFormat) -> None
assert QThread.currentThread() is self.thread()
self.writeWithFormat("".join(lines), charformat)
def formatted(self, color=None, background=None, weight=None,
italic=None, underline=None, font=None):
# type: (...) -> Formatter
"""
Return a formatted file like object proxy.
"""
charformat = update_char_format(
self.currentCharFormat(), color, background, weight,
italic, underline, font
)
return Formatter(self, charformat)
def document(self) -> TerminalTextDocument:
return self.__text.document()
def setDocument(self, document: TerminalTextDocument) -> None:
document.setMaximumBlockCount(self.__lines)
document.setDefaultFont(self.__text.font())
self.__text.setDocument(document)
def formated(self, *args, **kwargs):
warnings.warn(
"'Use 'formatted'", DeprecationWarning, stacklevel=2
)
return self.formatted(*args, **kwargs)
class Formatter(QObject):
def __init__(self, outputview, charformat):
# type: (Union[TerminalTextDocument, OutputView], QTextCharFormat) -> None
# Parent to the output view. Ensure the formatter does not outlive it.
super().__init__(outputview)
self.outputview = outputview
self.charformat = charformat
@Slot(str)
def write(self, string):
# type: (str) -> None
self.outputview.writeWithFormat(string, self.charformat)
@Slot(object)
def writelines(self, lines):
# type: (List[str]) -> None
self.outputview.writelinesWithFormat(lines, self.charformat)
@Slot()
def flush(self):
# type: () -> None
self.outputview.flush()
def formatted(self, color=None, background=None, weight=None,
italic=None, underline=None, font=None):
# type: (...) -> Formatter
charformat = update_char_format(self.charformat, color, background,
weight, italic, underline, font)
return Formatter(self.outputview, charformat)
def __enter__(self):
return self
def __exit__(self, *args):
self.outputview = None
self.charformat = None
self.setParent(None)
def formated(self, *args, **kwargs):
warnings.warn(
"Use 'formatted'", DeprecationWarning, stacklevel=2
)
return self.formatted(*args, **kwargs)
class formater(Formatter):
def __init__(self, *args, **kwargs):
warnings.warn(
"Deprecated: Renamed to Formatter.",
DeprecationWarning, stacklevel=2
)
super().__init__(*args, **kwargs)
class TextStream(QObject):
stream = Signal(str)
flushed = Signal()
__closed = False
def close(self):
# type: () -> None
self.__closed = True
def closed(self):
# type: () -> bool
return self.__closed
def isatty(self):
# type: () -> bool
return False
def write(self, string):
# type: (str) -> None
if self.__closed:
raise ValueError("write operation on a closed stream.")
self.stream.emit(string)
def writelines(self, lines):
# type: (List[str]) -> None
if self.__closed:
raise ValueError("write operation on a closed stream.")
self.stream.emit("".join(lines))
def flush(self):
# type: () -> None
if self.__closed:
raise ValueError("write operation on a closed stream.")
self.flushed.emit()
def writeable(self):
# type: () -> bool
return True
def readable(self):
# type: () -> bool
return False
def seekable(self):
# type: () -> bool
return False
encoding = None
errors = None
newlines = None
buffer = None
def detach(self):
raise io.UnsupportedOperation("detach")
def read(self, size=-1):
raise io.UnsupportedOperation("read")
def readline(self, size=-1):
raise io.UnsupportedOperation("readline")
def readlines(self):
raise io.UnsupportedOperation("readlines")
def fileno(self):
raise io.UnsupportedOperation("fileno")
def seek(self, offset, whence=io.SEEK_SET):
raise io.UnsupportedOperation("seek")
def tell(self):
raise io.UnsupportedOperation("tell")
class ExceptHook(QObject):
# Signal emitted with the `sys.exc_info` tuple.
handledException = Signal(tuple)
def __init__(self, parent=None, stream=None, **kwargs):
super().__init__(parent, **kwargs)
self.stream = stream
def __call__(self, exc_type, exc_value, tb):
# type: (Type[BaseException], BaseException, TracebackType) -> None
if self.stream is None:
stream = sys.stderr
else:
stream = self.stream
if stream is not None:
header = exc_type.__name__ + ' Exception'
if QThread.currentThread() != QCoreApplication.instance().thread():
header += " (in non-GUI thread)"
text = traceback.format_exception(exc_type, exc_value, tb)
text.insert(0, '{:-^79}\n'.format(' ' + header + ' '))
text.append('-' * 79 + '\n')
try:
stream.writelines(text)
stream.flush()
except Exception:
pass
self.handledException.emit((exc_type, exc_value, tb))
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/schemeinfo.py 0000664 0001750 0001750 00000013477 14625071541 023717 0 ustar 00marko marko """
Scheme Info editor widget.
"""
import typing
from typing import Optional
from AnyQt.QtWidgets import (
QWidget, QDialog, QLabel, QTextEdit, QCheckBox, QFormLayout,
QVBoxLayout, QHBoxLayout, QDialogButtonBox, QSizePolicy
)
from AnyQt.QtCore import Qt
from ..gui.lineedit import LineEdit
from ..gui.utils import StyledWidget_paintEvent, StyledWidget
if typing.TYPE_CHECKING:
from ..scheme import Scheme
class SchemeInfoEdit(QWidget):
"""Scheme info editor widget.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.scheme = None # type: Optional[Scheme]
self.__schemeIsUntitled = True
self.__setupUi()
def __setupUi(self):
layout = QFormLayout()
layout.setRowWrapPolicy(QFormLayout.WrapAllRows)
layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow)
self.name_edit = LineEdit(self)
self.name_edit.setPlaceholderText(self.tr("untitled"))
self.name_edit.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Fixed)
self.desc_edit = QTextEdit(self)
self.desc_edit.setTabChangesFocus(True)
layout.addRow(self.tr("Title"), self.name_edit)
layout.addRow(self.tr("Description"), self.desc_edit)
self.setLayout(layout)
def setScheme(self, scheme):
# type: (Scheme) -> None
"""Set the scheme to display/edit
"""
self.scheme = scheme
if not scheme.title:
self.name_edit.setText(self.tr("untitled"))
self.name_edit.selectAll()
self.__schemeIsUntitled = True
else:
self.name_edit.setText(scheme.title)
self.__schemeIsUntitled = False
self.desc_edit.setPlainText(scheme.description or "")
def commit(self):
# type: () -> None
"""
Commit the current contents of the editor widgets back to the scheme.
"""
if self.scheme is None:
return
if self.__schemeIsUntitled and \
self.name_edit.text() == self.tr("untitled"):
# 'untitled' text was not changed
name = ""
else:
name = self.name_edit.text().strip()
description = self.desc_edit.toPlainText().strip()
self.scheme.title = name
self.scheme.description = description
def paintEvent(self, event):
return StyledWidget_paintEvent(self, event)
def title(self):
# type: () -> str
return self.name_edit.text().strip()
def description(self):
# type: () -> str
return self.desc_edit.toPlainText().strip()
class SchemeInfoDialog(QDialog):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.scheme = None # type: Optional[Scheme]
self.__autoCommit = True
self.__setupUi()
def __setupUi(self):
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.editor = SchemeInfoEdit(self)
self.editor.layout().setContentsMargins(20, 20, 20, 20)
self.editor.layout().setSpacing(15)
self.editor.setSizePolicy(QSizePolicy.MinimumExpanding,
QSizePolicy.MinimumExpanding)
heading = self.tr("Workflow Info")
heading = "
{0}
".format(heading)
self.heading = QLabel(heading, self, objectName="heading")
# Insert heading
self.editor.layout().insertRow(0, self.heading)
self.buttonbox = QDialogButtonBox(
QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
Qt.Horizontal,
self
)
# Insert button box
self.editor.layout().addRow(self.buttonbox)
widget = StyledWidget(self, objectName="auto-show-container")
check_layout = QHBoxLayout()
check_layout.setContentsMargins(20, 10, 20, 10)
self.__showAtNewSchemeCheck = \
QCheckBox(self.tr("Show when I make a New Workflow."),
self,
objectName="auto-show-check",
checked=False,
)
check_layout.addWidget(self.__showAtNewSchemeCheck)
check_layout.addWidget(
QLabel(self.tr("You can also edit Workflow Info later "
"(File -> Workflow Info)."),
self,
objectName="auto-show-info"),
alignment=Qt.AlignRight)
widget.setLayout(check_layout)
widget.setSizePolicy(QSizePolicy.MinimumExpanding,
QSizePolicy.Fixed)
if self.__autoCommit:
self.buttonbox.accepted.connect(self.editor.commit)
self.buttonbox.accepted.connect(self.accept)
self.buttonbox.rejected.connect(self.reject)
layout.addWidget(self.editor, stretch=10)
layout.addWidget(widget)
self.setLayout(layout)
def setShowAtNewScheme(self, checked):
# type: (bool) -> None
"""
Set the 'Show at new scheme' check state.
"""
self.__showAtNewSchemeCheck.setChecked(checked)
def showAtNewScheme(self):
# type: () -> bool
"""
Return the check state of the 'Show at new scheme' check box.
"""
return self.__showAtNewSchemeCheck.isChecked()
def setAutoCommit(self, auto):
# type: (bool) -> None
if self.__autoCommit != auto:
self.__autoCommit = auto
if auto:
self.buttonbox.accepted.connect(self.editor.commit)
else:
self.buttonbox.accepted.disconnect(self.editor.commit)
def setScheme(self, scheme):
# type: (Scheme) -> None
"""Set the scheme to display/edit.
"""
self.scheme = scheme
self.editor.setScheme(scheme)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/settings.py 0000664 0001750 0001750 00000057713 14625071541 023440 0 ustar 00marko marko """
User settings/preference dialog
===============================
"""
import sys
import logging
import warnings
from functools import cmp_to_key
from collections import namedtuple
from AnyQt.QtWidgets import (
QWidget, QMainWindow, QComboBox, QCheckBox, QListView, QTabWidget,
QToolBar, QAction, QStackedWidget, QVBoxLayout, QHBoxLayout,
QFormLayout, QSizePolicy, QDialogButtonBox, QLineEdit, QLabel,
QStyleFactory, QLayout)
from AnyQt.QtGui import QStandardItemModel, QStandardItem
from AnyQt.QtCore import (
Qt, QEventLoop, QAbstractItemModel, QModelIndex, QSettings,
Property,
Signal)
from .. import config
from ..utils.settings import SettingChangedEvent
from ..utils.propertybindings import (
AbstractBoundProperty, PropertyBinding, BindingManager
)
log = logging.getLogger(__name__)
def refresh_proxies():
from orangecanvas.main import fix_set_proxy_env
fix_set_proxy_env()
class UserDefaultsPropertyBinding(AbstractBoundProperty):
"""
A Property binding for a setting in a
:class:`orangecanvas.utility.settings.Settings` instance.
"""
def __init__(self, obj, propertyName, parent=None):
super().__init__(obj, propertyName, parent)
obj.installEventFilter(self)
def get(self):
return self.obj.get(self.propertyName)
def set(self, value):
self.obj[self.propertyName] = value
def eventFilter(self, obj, event):
if event.type() == SettingChangedEvent.SettingChanged and \
event.key() == self.propertyName:
self.notifyChanged()
return super().eventFilter(obj, event)
class UserSettingsModel(QAbstractItemModel):
"""
An Item Model for user settings presenting a list of
key, setting value entries along with it's status and type.
"""
def __init__(self, parent=None, settings=None):
super().__init__(parent)
self.__settings = settings
self.__headers = ["Name", "Status", "Type", "Value"]
def setSettings(self, settings):
if self.__settings != settings:
self.__settings = settings
self.reset()
def settings(self):
return self.__settings
def rowCount(self, parent=QModelIndex()):
if parent.isValid():
return 0
elif self.__settings:
return len(self.__settings)
else:
return 0
def columnCount(self, parent=QModelIndex()):
if parent.isValid():
return 0
else:
return len(self.__headers)
def parent(self, index):
return QModelIndex()
def index(self, row, column=0, parent=QModelIndex()):
if parent.isValid() or \
column < 0 or column >= self.columnCount() or \
row < 0 or row >= self.rowCount():
return QModelIndex()
return self.createIndex(row, column, row)
def headerData(self, section, orientation, role=Qt.DisplayRole):
if section >= 0 and section < 4 and orientation == Qt.Horizontal:
if role == Qt.DisplayRole:
return self.__headers[section]
return super().headerData(section, orientation, role)
def data(self, index, role=Qt.DisplayRole):
if self._valid(index):
key = self._keyFromIndex(index)
column = index.column()
if role == Qt.DisplayRole:
if column == 0:
return key
elif column == 1:
default = self.__settings.isdefault(key)
return "Default" if default else "User"
elif column == 2:
return type(self.__settings.get(key)).__name__
elif column == 3:
return self.__settings.get(key)
return self
return None
def flags(self, index):
if self._valid(index):
flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable
if index.column() == 3:
return Qt.ItemIsEditable | flags
else:
return flags
return Qt.NoItemFlags
def setData(self, index, value, role=Qt.EditRole):
if self._valid(index) and index.column() == 3:
key = self._keyFromIndex(index)
try:
self.__settings[key] = value
except (TypeError, ValueError) as ex:
log.error("Failed to set value (%r) for key %r", value, key,
exc_info=True)
else:
self.dataChanged.emit(index, index)
return True
return False
def _valid(self, index):
row = index.row()
return row >= 0 and row < self.rowCount()
def _keyFromIndex(self, index):
row = index.row()
return list(self.__settings.keys())[row]
def container_widget_helper(orientation=Qt.Vertical, spacing=None, margin=0):
widget = QWidget()
if orientation == Qt.Vertical:
layout = QVBoxLayout()
widget.setSizePolicy(QSizePolicy.Fixed,
QSizePolicy.MinimumExpanding)
else:
layout = QHBoxLayout()
if spacing is not None:
layout.setSpacing(spacing)
if margin is not None:
layout.setContentsMargins(0, 0, 0, 0)
widget.setLayout(layout)
return widget
_State = namedtuple("_State", ["visible", "position"])
class FormLayout(QFormLayout):
"""
When adding a row to a QFormLayout, wherein the field is a layout
(or a widget with a layout), the label's height is too large to look pretty.
This subclass sets the label a fixed height to match the first item in
the layout.
"""
def addRow(self, *args):
if len(args) != 2:
return super().addRow(*args)
label, field = args
if not isinstance(field, QLayout) and field.layout() is None:
return super().addRow(label, field)
layout = field if isinstance(field, QLayout) else field.layout()
widget = layout.itemAt(0).widget()
height = widget.sizeHint().height()
if isinstance(label, str):
label = QLabel(label)
label.setFixedHeight(height)
return super().addRow(label, field)
class UserSettingsDialog(QMainWindow):
"""
A User Settings/Defaults dialog.
"""
MAC_UNIFIED = True
def __init__(self, parent=None, **kwargs):
super().__init__(parent, **kwargs)
self.setWindowFlags(Qt.Dialog)
self.setWindowModality(Qt.ApplicationModal)
self.layout().setSizeConstraint(QVBoxLayout.SetFixedSize)
self.__macUnified = sys.platform == "darwin" and self.MAC_UNIFIED
self._manager = BindingManager(self,
submitPolicy=BindingManager.AutoSubmit)
self.__loop = None
self.__settings = config.settings()
self.__setupUi()
def __setupUi(self):
"""Set up the UI.
"""
if self.__macUnified:
self.tab = QToolBar(
floatable=False, movable=False, allowedAreas=Qt.TopToolBarArea,
)
self.addToolBar(Qt.TopToolBarArea, self.tab)
self.setUnifiedTitleAndToolBarOnMac(True)
# This does not seem to work
self.setWindowFlags(self.windowFlags() & \
~Qt.MacWindowToolBarButtonHint)
self.tab.actionTriggered[QAction].connect(
self.__macOnToolBarAction
)
central = QStackedWidget()
central.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
else:
self.tab = central = QTabWidget(self)
# Add a close button to the bottom of the dialog
# (to satisfy GNOME 3 which shows the dialog without a title bar).
container = container_widget_helper()
container.layout().addWidget(central)
buttonbox = QDialogButtonBox(QDialogButtonBox.Close)
buttonbox.rejected.connect(self.close)
container.layout().addWidget(buttonbox)
self.setCentralWidget(container)
self.stack = central
# General Tab
tab = QWidget()
self.addTab(tab, self.tr("General"),
toolTip=self.tr("General Options"))
form = FormLayout()
tab.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
nodes = QWidget(self, objectName="nodes")
nodes.setLayout(QVBoxLayout())
nodes.layout().setContentsMargins(0, 0, 0, 0)
cb_anim = QCheckBox(
self.tr("Enable node animations"),
objectName="enable-node-animations",
toolTip=self.tr("Enable shadow and ping animations for nodes "
"in the workflow.")
)
cb_anchors = QCheckBox(
self.tr("Open anchors on hover"),
objectName="open-anchors-on-hover",
toolTip=self.tr(
"Open/expand node anchors on mouse hover (if unchecked the "
"anchors are expanded when Shift key is pressed)."
),
)
self.bind(cb_anim, "checked", "schemeedit/enable-node-animations")
self.bind(cb_anchors, "checked", "schemeedit/open-anchors-on-hover")
nodes.layout().addWidget(cb_anim)
nodes.layout().addWidget(cb_anchors)
form.addRow(self.tr("Nodes"), nodes)
links = QWidget(self, objectName="links")
links.setLayout(QVBoxLayout())
links.layout().setContentsMargins(0, 0, 0, 0)
cb_show = QCheckBox(
self.tr("Show channel names between widgets"),
objectName="show-channel-names",
toolTip=self.tr("Show source and sink channel names "
"over the links.")
)
self.bind(cb_show, "checked", "schemeedit/show-channel-names")
links.layout().addWidget(cb_show)
form.addRow(self.tr("Links"), links)
quickmenu = QWidget(self, objectName="quickmenu-options")
quickmenu.setLayout(QVBoxLayout())
quickmenu.layout().setContentsMargins(0, 0, 0, 0)
cb1 = QCheckBox(self.tr("Open on double click"),
toolTip=self.tr("Open quick menu on a double click "
"on an empty spot in the canvas"))
cb2 = QCheckBox(self.tr("Open on right click"),
toolTip=self.tr("Open quick menu on a right click "
"on an empty spot in the canvas"))
cb3 = QCheckBox(self.tr("Open on space key press"),
toolTip=self.tr("Open quick menu on Space key press "
"while the mouse is hovering over the canvas."))
cb4 = QCheckBox(self.tr("Open on any key press"),
toolTip=self.tr("Open quick menu on any key press "
"while the mouse is hovering over the canvas."))
cb5 = QCheckBox(self.tr("Show categories"),
toolTip=self.tr("In addition to searching, allow filtering "
"by categories."))
self.bind(cb1, "checked", "quickmenu/trigger-on-double-click")
self.bind(cb2, "checked", "quickmenu/trigger-on-right-click")
self.bind(cb3, "checked", "quickmenu/trigger-on-space-key")
self.bind(cb4, "checked", "quickmenu/trigger-on-any-key")
self.bind(cb5, "checked", "quickmenu/show-categories")
quickmenu.layout().addWidget(cb1)
quickmenu.layout().addWidget(cb2)
quickmenu.layout().addWidget(cb3)
quickmenu.layout().addWidget(cb4)
quickmenu.layout().addWidget(cb5)
form.addRow(self.tr("Quick menu"), quickmenu)
startup = QWidget(self, objectName="startup-group")
startup.setLayout(QVBoxLayout())
startup.layout().setContentsMargins(0, 0, 0, 0)
cb_splash = QCheckBox(self.tr("Show splash screen"), self,
objectName="show-splash-screen")
cb_welcome = QCheckBox(self.tr("Show welcome screen"), self,
objectName="show-welcome-screen")
cb_crash = QCheckBox(self.tr("Load crashed scratch workflows"), self,
objectName="load-crashed-workflows")
self.bind(cb_splash, "checked", "startup/show-splash-screen")
self.bind(cb_welcome, "checked", "startup/show-welcome-screen")
self.bind(cb_crash, "checked", "startup/load-crashed-workflows")
startup.layout().addWidget(cb_splash)
startup.layout().addWidget(cb_welcome)
startup.layout().addWidget(cb_crash)
form.addRow(self.tr("On startup"), startup)
toolbox = QWidget(self, objectName="toolbox-group")
toolbox.setLayout(QVBoxLayout())
toolbox.layout().setContentsMargins(0, 0, 0, 0)
exclusive = QCheckBox(self.tr("Only one tab can be open at a time"))
self.bind(exclusive, "checked", "mainwindow/toolbox-dock-exclusive")
toolbox.layout().addWidget(exclusive)
form.addRow(self.tr("Tool box"), toolbox)
tab.setLayout(form)
# Style tab
tab = StyleConfigWidget()
self.addTab(tab, self.tr("&Style"), toolTip="Application style")
self.bind(tab, "selectedStyle_", "application-style/style-name")
self.bind(tab, "selectedPalette_", "application-style/palette")
# Output Tab
tab = QWidget()
self.addTab(tab, self.tr("Output"),
toolTip="Output Redirection")
form = FormLayout()
combo = QComboBox()
combo.addItems([self.tr("Critical"),
self.tr("Error"),
self.tr("Warn"),
self.tr("Info"),
self.tr("Debug")])
self.bind(combo, "currentIndex", "logging/level")
form.addRow(self.tr("Logging"), combo)
box = QWidget()
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
cb1 = QCheckBox(self.tr("Open in external browser"),
objectName="open-in-external-browser")
self.bind(cb1, "checked", "help/open-in-external-browser")
layout.addWidget(cb1)
box.setLayout(layout)
form.addRow(self.tr("Help window"), box)
tab.setLayout(form)
# Categories Tab
tab = QWidget()
layout = QVBoxLayout()
view = QListView(
editTriggers=QListView.NoEditTriggers
)
from .. import registry
reg = registry.global_registry()
model = QStandardItemModel()
settings = QSettings()
for cat in reg.categories():
item = QStandardItem()
item.setText(cat.name)
item.setCheckable(True)
visible, _ = category_state(cat, settings)
item.setCheckState(Qt.Checked if visible else Qt.Unchecked)
model.appendRow([item])
view.setModel(model)
layout.addWidget(view)
tab.setLayout(layout)
model.itemChanged.connect(
lambda item:
save_category_state(
reg.category(str(item.text())),
_State(item.checkState() == Qt.Checked, -1),
settings
)
)
self.addTab(tab, "Categories")
# Add-ons Tab
tab = QWidget()
self.addTab(tab, self.tr("Add-ons"),
toolTip="Settings related to add-on installation")
form = FormLayout()
conda = QWidget(self, objectName="conda-group")
conda.setLayout(QVBoxLayout())
conda.layout().setContentsMargins(0, 0, 0, 0)
cb_conda_install = QCheckBox(self.tr("Install add-ons with conda"), self,
objectName="allow-conda")
self.bind(cb_conda_install, "checked", "add-ons/allow-conda")
conda.layout().addWidget(cb_conda_install)
form.addRow(self.tr("Conda"), conda)
form.addRow(self.tr("Pip"), QLabel("Pip install arguments:"))
line_edit_pip = QLineEdit()
self.bind(line_edit_pip, "text", "add-ons/pip-install-arguments")
form.addRow("", line_edit_pip)
tab.setLayout(form)
# Network Tab
tab = QWidget()
self.addTab(tab, self.tr("Network"),
toolTip="Settings related to networking")
form = FormLayout()
line_edit_http_proxy = QLineEdit()
self.bind(line_edit_http_proxy, "text", "network/http-proxy")
form.addRow("HTTP proxy:", line_edit_http_proxy)
line_edit_https_proxy = QLineEdit()
self.bind(line_edit_https_proxy, "text", "network/https-proxy")
form.addRow("HTTPS proxy:", line_edit_https_proxy)
tab.setLayout(form)
if self.__macUnified:
# Need some sensible size otherwise mac unified toolbar 'takes'
# the space that should be used for layout of the contents
self.adjustSize()
def addTab(self, widget, text, toolTip=None, icon=None):
if self.__macUnified:
action = QAction(text, self)
if toolTip:
action.setToolTip(toolTip)
if icon:
action.setIcon(toolTip)
action.setData(len(self.tab.actions()))
self.tab.addAction(action)
self.stack.addWidget(widget)
else:
i = self.tab.addTab(widget, text)
if toolTip:
self.tab.setTabToolTip(i, toolTip)
if icon:
self.tab.setTabIcon(i, icon)
def setCurrentIndex(self, index: int):
if self.__macUnified:
self.stack.setCurrentIndex(index)
else:
self.tab.setCurrentIndex(index)
def widget(self, index):
if self.__macUnified:
return self.stack.widget(index)
else:
return self.tab.widget(index)
def keyPressEvent(self, event):
if event.key() == Qt.Key_Escape:
self.hide()
self.deleteLater()
def bind(self, source, source_property, key, transformer=None):
target = UserDefaultsPropertyBinding(self.__settings, key)
source = PropertyBinding(source, source_property)
source.set(target.get())
self._manager.bind(target, source)
def commit(self):
self._manager.commit()
def revert(self):
self._manager.revert()
def reset(self):
for target, source in self._manager.bindings():
try:
source.reset()
except NotImplementedError:
# Cannot reset.
pass
except Exception:
log.error("Error reseting %r", source.propertyName,
exc_info=True)
def exec(self):
self.__loop = QEventLoop()
self.show()
status = self.__loop.exec()
self.__loop = None
refresh_proxies()
return status
def exec_(self, *args, **kwargs):
warnings.warn(
"exec_ is deprecated, use exec", DeprecationWarning, stacklevel=2
)
return self.exec(*args, **kwargs)
def hideEvent(self, event):
super().hideEvent(event)
if self.__loop is not None:
self.__loop.exit(0)
self.__loop = None
def __macOnToolBarAction(self, action):
index = action.data()
self.stack.setCurrentIndex(index)
class StyleConfigWidget(QWidget):
DisplayNames = {
"windowsvista": "Windows (default)",
"macintosh": "macOS (default)",
"windows": "MS Windows 9x",
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._current_palette = ""
form = FormLayout()
styles = QStyleFactory.keys()
styles = sorted(styles, key=cmp_to_key(
lambda a, b:
1 if a.lower() == "windows" and b.lower() == "fusion" else
(-1 if a.lower() == "fusion" and b.lower() == "windows" else 0)
))
styles = [
(self.DisplayNames.get(st.lower(), st.capitalize()), st)
for st in styles
]
# Default style with empty userData key so it cleared in
# persistent settings, allowing for default style resolution
# on application star.
styles = [("Default", "")] + styles
self.style_cb = style_cb = QComboBox(objectName="style-cb")
for name, key in styles:
self.style_cb.addItem(name, userData=key)
style_cb.currentIndexChanged.connect(self._style_changed)
self.colors_cb = colors_cb = QComboBox(objectName="palette-cb")
colors_cb.addItem("Default", userData="")
colors_cb.addItem("Breeze Light", userData="breeze-light")
colors_cb.addItem("Breeze Dark", userData="breeze-dark")
colors_cb.addItem("Zion Reversed", userData="zion-reversed")
colors_cb.addItem("Dark", userData="dark")
form.addRow("Style", style_cb)
form.addRow("Color theme", colors_cb)
label = QLabel(
"Changes will be applied on next application startup.",
enabled=False,
)
label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
form.addRow(label)
self.setLayout(form)
self._update_colors_enabled_state()
style_cb.currentIndexChanged.connect(self.selectedStyleChanged)
colors_cb.currentIndexChanged.connect(self.selectedPaletteChanged)
def _style_changed(self):
self._update_colors_enabled_state()
def _update_colors_enabled_state(self):
current = self.style_cb.currentData(Qt.UserRole)
enable = current is not None and current.lower() in ("fusion", "windows")
self._set_palette_enabled(enable)
def _set_palette_enabled(self, state: bool):
cb = self.colors_cb
if cb.isEnabled() != state:
cb.setEnabled(state)
if not state:
current = cb.currentData(Qt.UserRole)
self._current_palette = current
cb.setCurrentIndex(-1)
else:
index = cb.findData(self._current_palette, Qt.UserRole)
if index == -1:
index = 0
cb.setCurrentIndex(index)
def selectedStyle(self) -> str:
"""Return the current selected style key."""
key = self.style_cb.currentData()
return key if key is not None else ""
def setSelectedStyle(self, style: str) -> None:
"""Set the current selected style key."""
idx = self.style_cb.findData(style, Qt.DisplayRole, Qt.MatchFixedString)
if idx == -1:
idx = 0 # select the default style
self.style_cb.setCurrentIndex(idx)
selectedStyleChanged = Signal()
selectedStyle_ = Property(
str, selectedStyle, setSelectedStyle,
notify=selectedStyleChanged
)
def selectedPalette(self) -> str:
"""The current selected palette key."""
key = self.colors_cb.currentData(Qt.UserRole)
return key if key is not None else ""
def setSelectedPalette(self, key: str) -> None:
"""Set the current selected palette key."""
if not self.colors_cb.isEnabled():
self._current_palette = key
return
idx = self.colors_cb.findData(key, Qt.UserRole, Qt.MatchFixedString)
if idx == -1:
idx = 0 # select the default color theme
self.colors_cb.setCurrentIndex(idx)
selectedPaletteChanged = Signal()
selectedPalette_ = Property(
str, selectedPalette, setSelectedPalette,
notify=selectedPaletteChanged
)
def category_state(cat, settings):
visible = settings.value(
"mainwindow/categories/{0}/visible".format(cat.name),
defaultValue=not cat.hidden,
type=bool
)
position = settings.value(
"mainwindow/categories/{0}/position".format(cat.name),
defaultValue=-1,
type=int
)
return (visible, position)
def save_category_state(cat, state, settings):
settings.setValue(
"mainwindow/categories/{0}/visible".format(cat.name),
state.visible
)
settings.setValue(
"mainwindow/categories/{0}/position".format(cat.name),
state.position
)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1716810829.7765813
orange-canvas-core-0.2.1/orangecanvas/application/tests/ 0000775 0001750 0001750 00000000000 14625072116 022352 5 ustar 00marko marko ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/tests/__init__.py 0000664 0001750 0001750 00000000000 14625071541 024452 0 ustar 00marko marko ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/tests/test_addons.py 0000664 0001750 0001750 00000015556 14625071541 025250 0 ustar 00marko marko import os
import tempfile
import unittest
from contextlib import contextmanager
from unittest.mock import patch
from zipfile import ZipFile
from AnyQt.QtCore import QEventLoop, QMimeData, QPointF, Qt, QUrl
from AnyQt.QtGui import QDropEvent
from AnyQt.QtTest import QTest
from AnyQt.QtWidgets import QDialogButtonBox, QMessageBox, QTreeView, QStyle
from orangecanvas.application import addons
from orangecanvas.application.addons import AddonManagerDialog
from orangecanvas.application.utils.addons import (
Available,
CondaInstaller,
Install,
Installable,
Installed,
PipInstaller,
Uninstall,
Upgrade,
_QueryResult,
)
from orangecanvas.gui.test import QAppTestCase
from orangecanvas.utils.qinvoke import qinvoke
from orangecanvas.utils.pkgmeta import Distribution, EntryPoint
@contextmanager
def addon_archive(pkginfo):
file = tempfile.NamedTemporaryFile("wb", delete=False, suffix=".zip")
name = file.name
file.close()
with ZipFile(name, 'w') as myzip:
myzip.writestr('PKG-INFO', pkginfo)
try:
yield name
finally:
os.remove(name)
class FakeDistribution(Distribution):
def locate_file(self, path):
pass
def read_text(self, filename):
pass
def __init__(self, name, version):
super().__init__()
self._name = name
self._version = version
@property
def name(self):
return self._name
@property
def version(self):
return self._version
class FakeEntryPoint(EntryPoint):
def for_(self, dist):
vars(self).update(dist=dist)
return self
class TestAddonManagerDialog(QAppTestCase):
def test_widget(self):
items = [
Installed(
Installable("foo", "1.1", "", "", "", []),
FakeDistribution(name="foo", version="1.0"),
),
Available(
Installable("q", "1.2", "", "", "", [])
),
Installed(
None,
FakeDistribution(name="a", version="0.0")
),
]
w = AddonManagerDialog()
w.setItems(items)
_ = w.items()
state = w.itemState()
self.assertSequenceEqual(state, [])
state = [(Install, items[1])]
w.setItemState(state)
self.assertSequenceEqual(state, w.itemState())
state = state + [(Upgrade, items[0])]
w.setItemState(state)
self.assertSequenceEqual(state, w.itemState()[::-1])
state = [(Uninstall, items[0])]
w.setItemState(state)
self.assertSequenceEqual(state, w.itemState())
updateTopLayout = w._AddonManagerDialog__updateTopLayout
updateTopLayout(False)
updateTopLayout(True)
w.setItemState([])
# toggle install state
view = w.findChild(QTreeView, "add-ons-view")
index = view.model().index(0, 0)
delegate = view.itemDelegateForColumn(0)
style = view.style()
opt = view.viewOptions()
opt.rect = view.visualRect(index)
delegate.initStyleOption(opt, index)
rect = style.subElementRect(
QStyle.SE_ItemViewItemCheckIndicator, opt, view
)
def check_state_equal(left, right):
self.assertEqual(Qt.CheckState(left), Qt.CheckState(right))
check_state_equal(index.data(Qt.CheckStateRole), Qt.PartiallyChecked)
QTest.mouseClick(view.viewport(), Qt.LeftButton, pos=rect.center())
check_state_equal(index.data(Qt.CheckStateRole), Qt.Checked)
QTest.mouseClick(view.viewport(), Qt.LeftButton, pos=rect.center())
check_state_equal(index.data(Qt.CheckStateRole), Qt.Unchecked)
@patch("orangecanvas.config.default.addon_entry_points",
return_value=[
FakeEntryPoint(
"a", "b", "g").for_(FakeDistribution(name="foo", version="1.0"))])
def test_drop(self, p1):
items = [
Installed(
Installable("foo", "1.1", "", "", "", []),
FakeDistribution(name="foo", version="1.0"),
),
]
w = AddonManagerDialog()
w.setItems(items)
# drop an addon already in the list
pkginfo = "Metadata-Version: 1.0\nName: foo\nVersion: 0.9"
with addon_archive(pkginfo) as fn:
event = self._drop_event(QUrl.fromLocalFile(fn))
w.dropEvent(event)
items = w.items()
self.assertEqual(1, len(items))
self.assertEqual("0.9", items[0].installable.version)
self.assertEqual(True, items[0].installable.force)
state = [(Upgrade, items[0])]
self.assertSequenceEqual(state, w.itemState())
# drop a new addon
pkginfo = "Metadata-Version: 1.0\nName: foo2\nVersion: 0.8"
with addon_archive(pkginfo) as fn:
event = self._drop_event(QUrl.fromLocalFile(fn))
w.dropEvent(event)
items = w.items()
self.assertEqual(2, len(items))
self.assertEqual("0.8", items[1].installable.version)
self.assertEqual(True, items[1].installable.force)
state = state + [(Install, items[1])]
self.assertSequenceEqual(state, w.itemState())
def _drop_event(self, url):
# make sure data does not get garbage collected before it used
# pylint: disable=attribute-defined-outside-init
self.event_data = data = QMimeData()
data.setUrls([QUrl(url)])
return QDropEvent(
QPointF(0, 0), Qt.MoveAction, data,
Qt.NoButton, Qt.NoModifier, QDropEvent.Drop)
def test_run_query(self):
w = AddonManagerDialog()
query_res = [
_QueryResult("uber-pkg", None),
_QueryResult("unter-pkg", Installable("unter-pkg", "0.0.0", "", "", "", []))
]
def query(names):
return query_res
with patch.object(QMessageBox, "exec", return_value=QMessageBox.Cancel), \
patch.object(addons, "query_pypi", query):
f = w.runQueryAndAddResults(
["uber-pkg", "unter-pkg"],
)
loop = QEventLoop()
f.add_done_callback(qinvoke(lambda f: loop.quit(), loop))
loop.exec()
items = w.items()
self.assertEqual(items, [Available(query_res[1].installable)])
def test_install(self):
w = AddonManagerDialog()
foo = Available(Installable("foo", "1.1", "", "", "", []))
w.setItems([foo])
w.setItemState([(Install, foo)])
with patch.object(PipInstaller, "install", lambda self, pkg: None), \
patch.object(CondaInstaller, "install", lambda self, pkg: None), \
patch.object(QMessageBox, "exec", return_value=QMessageBox.Cancel):
b = w.findChild(QDialogButtonBox)
b.accepted.emit()
QTest.qWait(1)
w.reject()
QTest.qWait(1)
w.deleteLater()
if __name__ == "__main__":
unittest.main()
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/tests/test_addons_utils.py 0000664 0001750 0001750 00000010122 14625071541 026450 0 ustar 00marko marko import os
import stat
import unittest
from tempfile import mkdtemp
from requests import Session
from requests_cache import CachedSession
from packaging.requirements import Requirement
from orangecanvas.application.utils.addons import (
Available,
Installable,
Installed,
installable_from_json_response,
installable_items,
is_updatable,
prettify_name, _session,
)
from orangecanvas.application.tests.test_addons import FakeDistribution
class TestUtils(unittest.TestCase):
def test_items_1(self):
inst = Installable("foo", "1.0", "a foo", "", "", [])
dist = FakeDistribution(name="foo", version="1.0")
item = Available(inst)
self.assertFalse(is_updatable(item))
self.assertEqual(item.name, "foo")
self.assertEqual(item.normalized_name, "foo")
item = Installed(None, dist)
self.assertFalse(is_updatable(item))
self.assertEqual(item.name, dist.name)
self.assertEqual(item.normalized_name, dist.name)
item = Installed(inst, dist)
self.assertFalse(is_updatable(item))
self.assertEqual(item.name, inst.name)
item = Installed(inst._replace(version="0.9"), dist)
self.assertFalse(is_updatable(item))
item = Installed(inst._replace(version="1.1"), dist)
self.assertTrue(is_updatable(item))
item = Installed(inst._replace(version="2.0"), dist,
constraint=Requirement("foo<1.99"))
self.assertFalse(is_updatable(item))
item = Installed(inst._replace(version="2.0"), dist,
constraint=Requirement("foo<2.99"))
self.assertTrue(is_updatable(item))
def test_items_2(self):
inst1 = Installable("foo", "1.0", "a foo", "", "", [])
inst2 = Installable("bar", "1.0", "a bar", "", "", [])
dist2 = FakeDistribution(name="bar", version="0.9")
dist3 = FakeDistribution(name="quack", version="1.0")
items = installable_items([inst1, inst2], [dist2, dist3])
self.assertIn(Available(inst1), items)
self.assertIn(Installed(inst2, dist2), items)
self.assertIn(Installed(None, dist3), items)
def test_installable_from_json_response(self):
inst = installable_from_json_response({
"info": {
"name": "foo",
"version": "1.0",
},
"releases": {
"1.0": [
{
"filename": "aa.tar.gz",
"url": "https://examples.com",
"size": 100,
"packagetype": "sdist",
}
]
},
})
self.assertTrue(inst.name, "foo")
self.assertEqual(inst.version, "1.0")
def test_prettify_name(self):
names = [
'AFooBar', 'FooBar', 'Foo-Bar', 'Foo-Bar-FOOBAR',
'Foo-bar-foobar', 'Foo', 'FOOBar', 'A4FooBar',
'4Foo', 'Foo3Bar'
]
pretty_names = [
'A Foo Bar', 'Foo Bar', 'Foo Bar', 'Foo Bar FOOBAR',
'Foo bar foobar', 'Foo', 'FOO Bar', 'A4Foo Bar',
'4Foo', 'Foo3Bar'
]
for name, pretty_name in zip(names, pretty_names):
self.assertEqual(pretty_name, prettify_name(name))
# test if orange prefix is handled
self.assertEqual('Orange', prettify_name('Orange'))
self.assertEqual('Orange3', prettify_name('Orange3'))
self.assertEqual('Some Addon', prettify_name('Orange-SomeAddon'))
self.assertEqual('Text', prettify_name('Orange3-Text'))
self.assertEqual('Image Analytics', prettify_name('Orange3-ImageAnalytics'))
self.assertEqual('Survival Analysis', prettify_name('Orange3-Survival-Analysis'))
def test_session(self):
# when permissions - use CachedSession
self.assertIsInstance(_session(), CachedSession)
# when no permissions - use request's Session
temp_dir = mkdtemp()
os.chmod(temp_dir, stat.S_IRUSR)
self.assertIsInstance(_session(temp_dir), Session)
if __name__ == "__main__":
unittest.main()
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/tests/test_application.py 0000664 0001750 0001750 00000003777 14625071541 026305 0 ustar 00marko marko import os
import sys
import time
import unittest
from AnyQt.QtGui import QPalette
from AnyQt.QtTest import QSignalSpy
from orangecanvas.utils import shtools as sh
from orangecanvas.application import application as appmod
from orangecanvas.utils.shtools import temp_named_file
def application_test_helper():
app = appmod.CanvasApplication([])
p = app.palette()
spy = QSignalSpy(app.applicationPaletteChanged)
p.setColor(QPalette.Base, p.color(QPalette.Text))
app.setPalette(p)
assert list(spy) == [[]]
app.quit()
return
class TestApplication(unittest.TestCase):
def test_application(self):
res = sh.python_run([
"-c",
f"import {__name__} as m\n"
f"m.application_test_helper()\n"
])
self.assertEqual(res.returncode, 0)
def test_application_help(self):
res = sh.python_run([
"-m", "orangecanvas", "--help"
])
self.assertEqual(res.returncode, 0)
def remove_after_exit(fname):
appmod.run_after_exit([
sys.executable, '-c', f'import os, sys; os.remove(sys.argv[1])', fname
])
def restart_command_test_helper(fname):
cmd = [
sys.executable, '-c', f'import os, sys; os.remove(sys.argv[1])', fname
]
appmod.set_restart_command(cmd)
assert appmod.restart_command() == cmd
appmod.restart_cancel()
assert appmod.restart_command() is None
appmod.set_restart_command(cmd)
class TestApplicationRestart(unittest.TestCase):
def test_restart_command(self):
with temp_named_file('', delete=False) as fname:
res = sh.python_run([
"-c",
f"import sys, {__name__} as m\n"
f"m.restart_command_test_helper(sys.argv[1])\n",
fname
])
start = time.perf_counter()
while os.path.exists(fname) and time.perf_counter() - start < 5:
pass
self.assertFalse(os.path.exists(fname))
self.assertEqual(res.returncode, 0)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/tests/test_canvastooldock.py 0000664 0001750 0001750 00000006472 14625071541 027007 0 ustar 00marko marko """
Test for canvas toolbox.
"""
from AnyQt.QtWidgets import (
QWidget, QToolBar, QTextEdit, QSplitter, QApplication
)
from AnyQt.QtCore import Qt, QTimer, QPoint
from ...registry import tests as registry_tests
from ...registry.qt import QtWidgetRegistry
from ...gui.dock import CollapsibleDockWidget
from ..canvastooldock import (
WidgetToolBox, CanvasToolDock, SplitterResizer, QuickCategoryToolbar,
CategoryPopupMenu, popup_position_from_source, widget_popup_geometry
)
from ...gui import test
class TestCanvasDockWidget(test.QAppTestCase):
def test_dock(self):
reg = registry_tests.small_testing_registry()
reg = QtWidgetRegistry(reg, parent=self.app)
toolbox = WidgetToolBox()
toolbox.setObjectName("widgets-toolbox")
toolbox.setModel(reg.model())
text = QTextEdit()
splitter = QSplitter()
splitter.setOrientation(Qt.Vertical)
splitter.addWidget(toolbox)
splitter.addWidget(text)
dock = CollapsibleDockWidget()
dock.setExpandedWidget(splitter)
toolbar = QToolBar()
toolbar.addAction("1")
toolbar.setOrientation(Qt.Vertical)
toolbar.setMovable(False)
toolbar.setFloatable(False)
dock.setCollapsedWidget(toolbar)
dock.show()
self.qWait()
def test_canvas_tool_dock(self):
reg = registry_tests.small_testing_registry()
reg = QtWidgetRegistry(reg, parent=self.app)
dock = CanvasToolDock()
dock.toolbox.setModel(reg.model())
dock.show()
self.qWait()
def test_splitter_resizer(self):
w = QSplitter(orientation=Qt.Vertical)
w.addWidget(QWidget())
text = QTextEdit()
w.addWidget(text)
resizer = SplitterResizer(parent=None)
resizer.setSplitterAndWidget(w, text)
def toogle():
if resizer.size() == 0:
resizer.open()
else:
resizer.close()
w.show()
timer = QTimer(resizer, interval=100)
timer.timeout.connect(toogle)
timer.start()
toogle()
self.qWait()
timer.stop()
def test_category_toolbar(self):
reg = registry_tests.small_testing_registry()
reg = QtWidgetRegistry(reg, parent=self.app)
w = QuickCategoryToolbar()
w.setModel(reg.model())
w.show()
self.qWait()
class TestPopupMenu(test.QAppTestCase):
def test(self):
reg = registry_tests.small_testing_registry()
reg = QtWidgetRegistry(reg, parent=self.app)
model = reg.model()
w = CategoryPopupMenu()
w.setModel(model)
w.setRootIndex(model.index(0, 0))
w.popup()
self.qWait()
def test_popup_position(self):
popup = CategoryPopupMenu()
screen = popup.screen()
screen_geom = screen.availableGeometry()
popup.setMinimumHeight(screen_geom.height() + 20)
w = QWidget()
w.setGeometry(
screen_geom.left() + 100, screen_geom.top() + 100, 20, 20
)
pos = popup_position_from_source(popup, w)
self.assertTrue(screen_geom.contains(pos))
pos = QPoint(screen_geom.top() - 100, screen_geom.left() - 100)
geom = widget_popup_geometry(pos, popup)
self.assertEqual(screen_geom.intersected(geom), geom)
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/tests/test_main.py 0000664 0001750 0001750 00000012072 14625071541 024712 0 ustar 00marko marko import logging
import unittest
from contextlib import contextmanager
from functools import wraps
from typing import Iterable
from unittest.mock import patch, Mock
from AnyQt.QtCore import Qt
from AnyQt.QtGui import QPalette
from orangecanvas import config
from orangecanvas.application.canvasmain import CanvasMainWindow
from orangecanvas.config import Config
from orangecanvas.gui.test import QAppTestCase
from orangecanvas.main import Main
from orangecanvas.registry import WidgetDiscovery
from orangecanvas.registry.tests import set_up_modules, tear_down_modules
from orangecanvas.scheme import Scheme
from orangecanvas.utils.shtools import temp_named_file
from orangecanvas.utils.pkgmeta import EntryPoint
class TestMain(unittest.TestCase):
def test_params(self):
m = Main()
m.parse_arguments(["-", "--config", "foo.bar", "that"])
self.assertEqual(m.arguments, ["that"])
self.assertEqual(m.options.config, "foo.bar")
m = Main()
m.parse_arguments(["-", "-l3"])
self.assertEqual(m.options.log_level, logging.WARNING)
m = Main()
m.parse_arguments(["-", "-l", "warn"])
self.assertEqual(m.options.log_level, logging.WARNING)
def test_style_param_compat(self):
# test old '--style' parameter handling
m = Main()
m.parse_arguments(["-", "--style", "windows"])
self.assertEqual(m.arguments, ["-style", "windows"])
m = Main()
m.parse_arguments(["-", "--qt", "-stylesheet path.qss"])
self.assertEqual(m.arguments, ["-stylesheet", "path.qss"])
def test_main_argument_parser(self):
class Main2(Main):
def argument_parser(self):
p = super().argument_parser()
p.add_argument("--foo", type=str, default=None)
return p
m = Main2()
m.parse_arguments(["-", "-l", "warn", "--foo", "bar"])
self.assertEqual(m.options.foo, "bar")
@contextmanager
def patch_main_application(app):
def setup_application(self: Main):
self.application = app
with patch.object(Main, "setup_application", setup_application):
yield
def with_patched_main_application(f):
@wraps(f)
def wrapped(self: QAppTestCase, *args, **kwargs):
with patch_main_application(self.app):
return f(self, *args, **kwargs)
return wrapped
class TestConfig(Config):
def init(self):
return
def widget_discovery(self, *args, **kwargs):
return WidgetDiscovery(*args, **kwargs)
def widgets_entry_points(self): # type: () -> Iterable[EntryPoint]
pkg = "orangecanvas.registry.tests"
return (
EntryPoint("add", f"{pkg}.operators.add", "w"),
EntryPoint("sub", f"{pkg}.operators.sub", "w")
)
def workflow_constructor(self, *args, **kwargs):
return Scheme(*args, **kwargs)
def splash_screen(self):
return config.Default.splash_screen()
class TestMainGuiCase(QAppTestCase):
def setUp(self):
super().setUp()
self.app.fileOpenRequest = Mock()
self._config = config.default
set_up_modules()
def tearDown(self):
tear_down_modules()
config.default = self._config
del self.app.fileOpenRequest
del self._config
super().tearDown()
@with_patched_main_application
def test_main_show_splash_screen(self):
m = Main()
m.parse_arguments(["-", "--config", f"{__name__}.TestConfig"])
m.activate_default_config()
m.show_splash_message("aa")
m.close_splash_screen()
@with_patched_main_application
def test_discovery(self):
m = Main()
m.parse_arguments(["-", "--config", f"{__name__}.TestConfig"])
m.activate_default_config()
m.run_discovery()
self.assertTrue(bool(m.registry.widgets()))
self.assertTrue(bool(m.registry.categories()))
@with_patched_main_application
def test_run(self):
m = Main()
with patch.object(self.app, "exec", lambda: 42):
res = m.run(["-", "--no-welcome", "--no-splash"])
self.assertEqual(res, 42)
@with_patched_main_application
def test_run_with_file(self):
m = Main()
with patch.object(self.app, "exec", lambda: 42), \
patch.object(CanvasMainWindow, "open_scheme_file", Mock()), \
temp_named_file('') as fname:
res = m.run(["-", "--no-welcome", "--no-splash", fname])
CanvasMainWindow.open_scheme_file.assert_called_with(fname)
self.assertEqual(res, 42)
@with_patched_main_application
def test_run_stylesheet_reconfigure(self):
m = Main()
m.parse_arguments(["-", "--config", f"{__name__}.TestConfig"])
m.window = m.create_main_window()
m.application = self.app
def setpalette(color):
self.app.setPalette(QPalette(color))
m._Main__reconfigure_stylesheet()
setpalette(Qt.white)
sheet = m.window.styleSheet()
setpalette(Qt.black)
self.assertNotEqual(sheet, m.window.styleSheet())
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1716810593.0
orange-canvas-core-0.2.1/orangecanvas/application/tests/test_mainwindow.py 0000664 0001750 0001750 00000032232 14625071541 026142 0 ustar 00marko marko import io
import os
import tempfile
from unittest.mock import patch
from AnyQt.QtGui import QWhatsThisClickedEvent
from AnyQt.QtWidgets import (
QToolButton, QDialog, QMessageBox, QApplication, QFileDialog
)
from .. import addons
from ..outputview import TextStream
from ..utils.addons import _QueryResult, Installable
from ...scheme import SchemeTextAnnotation, SchemeLink
from ...gui.quickhelp import QuickHelpTipEvent, QuickHelp
from ...utils.shtools import temp_named_file
from ...utils.pickle import swp_name
from ...gui.test import QAppTestCase
from ..canvasmain import CanvasMainWindow
from ..widgettoolbox import WidgetToolBox
from ...registry import tests as registry_tests
class MainWindow(CanvasMainWindow):
_instances = []
def create_new_window(self): # type: () -> CanvasMainWindow
inst = super().create_new_window()
MainWindow._instances.append(inst)
return inst
class TestMainWindowBase(QAppTestCase):
def setUp(self):
super().setUp()
self.w = MainWindow()
self.registry = registry_tests.small_testing_registry()
self.w.set_widget_registry(self.registry)
def tearDown(self):
self.w.clear_swp()
self.w.deleteLater()
for w in MainWindow._instances:
w.deleteLater()
MainWindow._instances.clear()
del self.w
del self.registry
self.qWait(1)
super().tearDown()
class TestMainWindow(TestMainWindowBase):
def test_create_new_window(self):
w = self.w
new = w.create_new_window()
self.assertIsInstance(new, MainWindow)
r1 = new.widget_registry
self.assertEqual(r1.widgets(), self.registry.widgets())
w.show()
new.show()
w.set_scheme_margins_enabled(True)
new.deleteLater()
stream = TextStream()
w.connect_output_stream(stream)
def test_connect_output_stream(self):
w = self.w
stream = TextStream()
w.connect_output_stream(stream)
stream.write("Hello")
self.assertEqual(w.output_view().toPlainText(), "Hello")
w.disconnect_output_stream(stream)
stream.write("Bye")
self.assertEqual(w.output_view().toPlainText(), "Hello")
def test_create_new_window_streams(self):
w = self.w
stream = TextStream()
w.connect_output_stream(stream)
new = w.create_new_window()
stream.write("Hello")
self.assertEqual(w.output_view().toPlainText(), "Hello")
self.assertEqual(new.output_view().toPlainText(), "Hello")
def test_new_window(self):
w = self.w
with patch(
"orangecanvas.application.schemeinfo.SchemeInfoDialog.exec",
):
w.new_workflow_window()
def test_examples_dialog(self):
w = self.w
with patch(
"orangecanvas.preview.previewdialog.PreviewDialog.exec",
return_value=QDialog.Rejected,
):
w.examples_dialog()
def test_create_toolbox(self):
w = self.w
toolbox = w.findChild(WidgetToolBox)
assert isinstance(toolbox, WidgetToolBox)
wf = w.current_document().scheme()
grid = toolbox.widget(0)
button = grid.findChild(QToolButton) # type: QToolButton
self.assertEqual(len(wf.nodes), 0)
button.click()
self.assertEqual(len(wf.nodes), 1)
def test_create_category_toolbar(self):
w = self.w
dock = w.dock_widget
dock.setExpanded(False)
a = w.quick_category.actions()[0]
with patch(
"orangecanvas.application.canvastooldock.CategoryPopupMenu.exec",
return_value=None,
):
w.on_quick_category_action(a)
def test_recent_list(self):
w = self.w
w.clear_recent_schemes()
w.add_recent_scheme("This one", __file__)
new = w.create_new_window()
self.assertEqual(len(new.recent_schemes), 1)
w.clear_recent_schemes()
def test_quick_help_events(self):
w = self.w
help: QuickHelp = w.dock_help
html = "
HELLO
"
ev = QuickHelpTipEvent("", html, priority=QuickHelpTipEvent.Normal)
QApplication.sendEvent(w, ev)
self.assertEqual(help.currentText(), "
HELLO
")
def test_help_requests(self):
w = self.w
ev = QWhatsThisClickedEvent('help://search?id=one')
QApplication.sendEvent(w, ev)
class TestMainWindowLoad(TestMainWindowBase):
filename = ""
def setUp(self):
super().setUp()
fd, filename = tempfile.mkstemp()
self.file = os.fdopen(fd, "w+b")
self.filename = filename
def tearDown(self):
self.file.close()
os.remove(self.filename)
super().tearDown()
def test_open_example_scheme(self):
self.file.write(TEST_OWS)
self.file.flush()
self.w.open_example_scheme(self.filename)
def test_open_scheme_file(self):
self.file.write(TEST_OWS)
self.file.flush()
self.w.open_scheme_file(self.filename)
def test_save(self):
w = self.w
w.current_document().setPath(self.filename)
with patch.object(w, "save_scheme_as") as f:
w.save_scheme()
f.assert_not_called()
w.current_document().setPath("")
def exec(myself):
myself.setOption(QFileDialog.DontUseNativeDialog)
myself.setOption(QFileDialog.DontConfirmOverwrite)
myself.selectFile(self.filename)
myself.accept()
with patch("AnyQt.QtWidgets.QFileDialog.exec", exec):
w.save_scheme()
self.assertTrue(os.path.samefile(w.current_document().path(), self.filename))
def test_save_svg_image(self):
w = self.w
scheme = w.current_document().scheme()
scheme.load_from(io.BytesIO(TEST_OWS), registry=w.widget_registry)
with patch("AnyQt.QtWidgets.QFileDialog.exec"):
w.save_as_svg()
dialog = w.findChild(QFileDialog, "save-as-svg-filedialog")
dialog.setOption(QFileDialog.DontUseNativeDialog)
dialog.setOption(QFileDialog.DontConfirmOverwrite)
dialog.selectFile(self.filename)
dialog.accept()
with open(self.filename, "rb") as f:
contents = f.read()
self.assertIn(b"