Merge remote-tracking branch 'refs/remotes/Ultimaker/master'

This commit is contained in:
Brecht Nuyttens 2017-10-20 15:18:17 +02:00
commit 33e42493fd
634 changed files with 27217 additions and 23598 deletions

9
.gitignore vendored
View File

@ -5,11 +5,12 @@ __pycache__
*.mo
docs/html
*.log
resources/i18n/en
resources/i18n/7s
resources/i18n/en_US
resources/i18n/en_7S
resources/i18n/x-test
resources/firmware
resources/materials
CuraEngine.exe
LC_MESSAGES
.cache
*.qmlc
@ -32,6 +33,7 @@ cura.desktop
.settings
#Externally located plug-ins.
plugins/CuraSolidWorksPlugin
plugins/Doodle3D-cura-plugin
plugins/GodMode
plugins/PostProcessingPlugin
@ -40,6 +42,7 @@ plugins/FlatProfileExporter
plugins/ProfileFlattener
plugins/cura-god-mode-plugin
plugins/cura-big-flame-graph
plugins/cura-siemensnx-plugin
#Build stuff
CMakeCache.txt
@ -55,4 +58,6 @@ cmake_install.cmake
#Debug
*.gcode
run.sh
.scannerwork/
CuraEngine

View File

@ -45,17 +45,25 @@ if(NOT APPLE AND NOT WIN32)
DESTINATION ${CMAKE_INSTALL_BINDIR}
PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
RENAME cura)
install(DIRECTORY cura
if(EXISTS /etc/debian_version)
install(DIRECTORY cura
DESTINATION lib/python${PYTHON_VERSION_MAJOR}/dist-packages
FILES_MATCHING PATTERN *.py)
install(FILES ${CMAKE_BINARY_DIR}/CuraVersion.py
install(FILES ${CMAKE_BINARY_DIR}/CuraVersion.py
DESTINATION lib/python${PYTHON_VERSION_MAJOR}/dist-packages/cura)
else()
install(DIRECTORY cura
DESTINATION lib/python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}/site-packages
FILES_MATCHING PATTERN *.py)
install(FILES ${CMAKE_BINARY_DIR}/CuraVersion.py
DESTINATION lib/python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}/site-packages/cura)
endif()
install(FILES ${CMAKE_BINARY_DIR}/cura.desktop
DESTINATION ${CMAKE_INSTALL_DATADIR}/applications)
install(FILES ${CMAKE_SOURCE_DIR}/resources/images/cura-icon.png
DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/128x128/apps/)
install(FILES cura.appdata.xml
DESTINATION ${CMAKE_INSTALL_DATADIR}/appdata)
DESTINATION ${CMAKE_INSTALL_DATADIR}/metainfo)
install(FILES cura.sharedmimeinfo
DESTINATION ${CMAKE_INSTALL_DATADIR}/mime/packages/
RENAME cura.xml )

816
LICENSE
View File

@ -1,661 +1,165 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

View File

@ -34,9 +34,11 @@ Dependencies
Configuring Cura
----------------
* Link your CuraEngine backend by inserting the following line in home/.config/cura/config.cfg :
Link your CuraEngine backend by inserting the following lines in `$HOME/.config/cura/config.cfg` :
```
[backend]
location = /[path_to_the..]/CuraEngine/build/CuraEngine
```
Build scripts
-------------

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
enable_testing()
include(CMakeParseArguments)

View File

@ -10,6 +10,6 @@ TryExec=@CMAKE_INSTALL_FULL_BINDIR@/cura
Icon=cura-icon
Terminal=false
Type=Application
MimeType=application/sla;application/vnd.ms-3mfdocument;application/prs.wavefront-obj;image/bmp;image/gif;image/jpeg;image/png;
MimeType=application/sla;application/vnd.ms-3mfdocument;application/prs.wavefront-obj;image/bmp;image/gif;image/jpeg;image/png;model/x3d+xml;
Categories=Graphics;
Keywords=3D;Printing;

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Job import Job
from UM.Scene.SceneNode import SceneNode
@ -27,7 +27,11 @@ class ArrangeObjectsJob(Job):
self._min_offset = min_offset
def run(self):
status_message = Message(i18n_catalog.i18nc("@info:status", "Finding new location for objects"), lifetime = 0, dismissable=False, progress = 0)
status_message = Message(i18n_catalog.i18nc("@info:status", "Finding new location for objects"),
lifetime = 0,
dismissable=False,
progress = 0,
title = i18n_catalog.i18nc("@info:title", "Finding Location"))
status_message.show()
arranger = Arrange.create(fixed_nodes = self._fixed_nodes)
@ -82,5 +86,6 @@ class ArrangeObjectsJob(Job):
status_message.hide()
if not found_solution_for_all:
no_full_solution_message = Message(i18n_catalog.i18nc("@info:status", "Unable to find a location within the build volume for all objects"))
no_full_solution_message = Message(i18n_catalog.i18nc("@info:status", "Unable to find a location within the build volume for all objects"),
title = i18n_catalog.i18nc("@info:title", "Can't Find Location"))
no_full_solution_message.show()

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from cura.Settings.ExtruderManager import ExtruderManager
from UM.Settings.ContainerRegistry import ContainerRegistry
@ -27,9 +27,8 @@ import math
from typing import List
PRIME_CLEARANCE = 6.5 #Setting for clearance around the prime.
MAJOR_GRID_SIZE = 10 #Size of the grid cells.
MINOR_GRID_SIZE = 1
# Setting for clearance around the prime
PRIME_CLEARANCE = 6.5
## Build volume is a special kind of node that is responsible for rendering the printable area & disallowed areas.
@ -45,8 +44,6 @@ class BuildVolume(SceneNode):
self._z_axis_color = None
self._disallowed_area_color = None
self._error_area_color = None
self._grid_color = None
self._grid_minor_color = None
self._width = 0
self._height = 0
@ -59,9 +56,8 @@ class BuildVolume(SceneNode):
self._origin_line_length = 20
self._origin_line_width = 0.5
self._plate_mesh = None
self._grid_mesh = None
self._plate_shader = None
self._grid_shader = None
self._disallowed_areas = []
self._disallowed_area_mesh = None
@ -90,29 +86,38 @@ class BuildVolume(SceneNode):
#Objects loaded at the moment. We are connected to the property changed events of these objects.
self._scene_objects = set()
self._change_timer = QTimer()
self._change_timer.setInterval(100)
self._change_timer.setSingleShot(True)
self._change_timer.timeout.connect(self._onChangeTimerFinished)
self._scene_change_timer = QTimer()
self._scene_change_timer.setInterval(100)
self._scene_change_timer.setSingleShot(True)
self._scene_change_timer.timeout.connect(self._onSceneChangeTimerFinished)
self._setting_change_timer = QTimer()
self._setting_change_timer.setInterval(150)
self._setting_change_timer.setSingleShot(True)
self._setting_change_timer.timeout.connect(self._onSettingChangeTimerFinished)
self._build_volume_message = Message(catalog.i18nc("@info:status",
"The build volume height has been reduced due to the value of the"
" \"Print Sequence\" setting to prevent the gantry from colliding"
" with printed models."))
" with printed models."), title = catalog.i18nc("@info:title","Build Volume"))
# Must be after setting _build_volume_message, apparently that is used in getMachineManager.
# activeQualityChanged is always emitted after setActiveVariant, setActiveMaterial and setActiveQuality.
# Therefore this works.
Application.getInstance().getMachineManager().activeQualityChanged.connect(self._onStackChanged)
# This should also ways work, and it is semantically more correct,
# but it does not update the disallowed areas after material change
Application.getInstance().getMachineManager().activeStackChanged.connect(self._onStackChanged)
# list of settings which were updated
self._changed_settings_since_last_rebuild = []
def _onSceneChanged(self, source):
if self._global_container_stack:
self._change_timer.start()
self._scene_change_timer.start()
def _onChangeTimerFinished(self):
def _onSceneChangeTimerFinished(self):
root = Application.getInstance().getController().getScene().getRoot()
new_scene_objects = set(node for node in BreadthFirstIterator(root) if node.callDecoration("isSliceable"))
if new_scene_objects != self._scene_objects:
@ -171,15 +176,15 @@ class BuildVolume(SceneNode):
if not self._shader:
self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "default.shader"))
self._plate_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "color.shader"))
self._grid_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "grid.shader"))
theme = Application.getInstance().getTheme()
self._plate_shader.setUniformValue("u_color", Color(*theme.getColor("buildplate").getRgb()))
self._plate_shader.setUniformValue("u_z_bias", 0.000001)
self._grid_shader.setUniformValue("u_plateColor", Color(*theme.getColor("buildplate").getRgb()))
self._grid_shader.setUniformValue("u_gridColor0", Color(*theme.getColor("buildplate_grid").getRgb()))
self._grid_shader.setUniformValue("u_gridColor1", Color(*theme.getColor("buildplate_grid_minor").getRgb()))
renderer.queueNode(self, mode = RenderBatch.RenderMode.Lines)
renderer.queueNode(self, mesh = self._origin_mesh)
renderer.queueNode(self, mesh = self._plate_mesh, shader = self._plate_shader, backface_cull = True)
renderer.queueNode(self, mesh = self._grid_mesh, mode = RenderBatch.RenderMode.Lines, transparent = True)
renderer.queueNode(self, mesh = self._grid_mesh, shader = self._grid_shader, backface_cull = True)
if self._disallowed_area_mesh:
renderer.queueNode(self, mesh = self._disallowed_area_mesh, shader = self._shader, transparent = True, backface_cull = True, sort = -9)
@ -252,8 +257,6 @@ class BuildVolume(SceneNode):
self._z_axis_color = Color(*theme.getColor("z_axis").getRgb())
self._disallowed_area_color = Color(*theme.getColor("disallowed_area").getRgb())
self._error_area_color = Color(*theme.getColor("error_area").getRgb())
self._grid_color = Color(*theme.getColor("buildplate_grid").getRgb())
self._grid_minor_color = Color(*theme.getColor("buildplate_grid_minor").getRgb())
min_w = -self._width / 2
max_w = self._width / 2
@ -284,7 +287,7 @@ class BuildVolume(SceneNode):
self.setMeshData(mb.build())
# Build plate surface.
# Build plate grid mesh
mb = MeshBuilder()
mb.addQuad(
Vector(min_w, min_h - z_fight_distance, min_d),
@ -296,30 +299,6 @@ class BuildVolume(SceneNode):
for n in range(0, 6):
v = mb.getVertex(n)
mb.setVertexUVCoordinates(n, v[0], v[2])
self._plate_mesh = mb.build()
#Build plate grid mesh.
mb = MeshBuilder()
for x in range(0, int(math.ceil(max_w)), MAJOR_GRID_SIZE):
mb.addLine(Vector(x, min_h, min_d), Vector(x, min_h, max_d), color = self._grid_color)
#Start from 0 in both cases, so you need to do this in two for loops.
mb.addLine(Vector(-x, min_h, min_d), Vector(-x, min_h, max_d), color = self._grid_color)
for y in range(0, int(math.ceil(max_d)), MAJOR_GRID_SIZE):
mb.addLine(Vector(min_w, min_h, y), Vector(max_w, min_h, y), color = self._grid_color)
mb.addLine(Vector(min_w, min_h, -y), Vector(max_w, min_h, -y), color = self._grid_color)
#More fine grained grid.
for x in range(0, int(math.ceil(max_w)), MINOR_GRID_SIZE):
if x % MAJOR_GRID_SIZE == 0: #Don't overlap with the major grid.
pass
mb.addLine(Vector(x, min_h, min_d), Vector(x, min_h, max_d), color = self._grid_minor_color)
mb.addLine(Vector(-x, min_h, min_d), Vector(-x, min_h, max_d), color = self._grid_minor_color)
for y in range(0, int(math.ceil(max_d)), MINOR_GRID_SIZE):
if y % MAJOR_GRID_SIZE == 0:
pass
mb.addLine(Vector(min_w, min_h, y), Vector(max_w, min_h, y), color = self._grid_minor_color)
mb.addLine(Vector(min_w, min_h, -y), Vector(max_w, min_h, -y), color = self._grid_minor_color)
self._grid_mesh = mb.build()
else:
@ -335,7 +314,7 @@ class BuildVolume(SceneNode):
mb.addArc(max_w, Vector.Unit_Y, center = (0, max_h, 0), color = self._volume_outline_color)
self.setMeshData(mb.build().getTransformed(scale_matrix))
# Build plate surface.
# Build plate grid mesh
mb = MeshBuilder()
mb.addVertex(0, min_h - z_fight_distance, 0)
mb.addArc(max_w, Vector.Unit_Y, center = Vector(0, min_h - z_fight_distance, 0))
@ -349,40 +328,7 @@ class BuildVolume(SceneNode):
for n in range(0, mb.getVertexCount()):
v = mb.getVertex(n)
mb.setVertexUVCoordinates(n, v[0], v[2] * aspect)
self._plate_mesh = mb.build().getTransformed(scale_matrix)
#Build plate grid mesh.
#We need to constrain the length of the lines to the build plate ellipsis. Time to get out the calculator!
mb = MeshBuilder()
for x in range(0, int(math.ceil(max_w)), MAJOR_GRID_SIZE):
#x / max_w is the fraction along the build plate we have progressed, counting from the centre.
#So x / max_w is sin(a), where a is the angle towards an endpoint of the grid line from the centre.
#So math.asin(x / max_w) is a.
#So math.cos(math.asin(x / max_w)) is half of the length of the grid line on a unit circle, which scales between 0 and 1.
length_factor = math.cos(math.asin(x / max_w))
mb.addLine(Vector(x, min_h, min_d * length_factor), Vector(x, min_h, max_d * length_factor), color = self._grid_color)
#Start from 0 in both cases, so you need to do this in two for loops.
mb.addLine(Vector(-x, min_h, min_d * length_factor), Vector(-x, min_h, max_d * length_factor), color = self._grid_color)
for y in range(0, int(math.ceil(max_d)), MAJOR_GRID_SIZE):
length_factor = math.sin(math.acos(y / max_d))
mb.addLine(Vector(min_w * length_factor, min_h, y), Vector(max_w * length_factor, min_h, y), color = self._grid_color)
mb.addLine(Vector(min_w * length_factor, min_h, -y), Vector(max_w * length_factor, min_h, -y), color = self._grid_color)
#More fine grained grid.
for x in range(0, int(math.ceil(max_w)), MINOR_GRID_SIZE):
if x % MAJOR_GRID_SIZE == 0: #Don't overlap with the major grid.
pass
length_factor = math.cos(math.asin(x / max_w))
mb.addLine(Vector(x, min_h, min_d * length_factor), Vector(x, min_h, max_d * length_factor), color = self._grid_minor_color)
mb.addLine(Vector(-x, min_h, min_d * length_factor), Vector(-x, min_h, max_d * length_factor), color = self._grid_minor_color)
for y in range(0, int(math.ceil(max_d)), MINOR_GRID_SIZE):
if y % MAJOR_GRID_SIZE == 0:
pass
length_factor = math.sin(math.acos(y / max_d))
mb.addLine(Vector(min_w * length_factor, min_h, y), Vector(max_w * length_factor, min_h, y), color = self._grid_minor_color)
mb.addLine(Vector(min_w * length_factor, min_h, -y), Vector(max_w * length_factor, min_h, -y), color = self._grid_minor_color)
self._grid_mesh = mb.build()
self._grid_mesh = mb.build().getTransformed(scale_matrix)
# Indication of the machine origin
if self._global_container_stack.getProperty("machine_center_is_zero", "value"):
@ -562,42 +508,67 @@ class BuildVolume(SceneNode):
self._engine_ready = True
self.rebuild()
def _onSettingChangeTimerFinished(self):
rebuild_me = False
update_disallowed_areas = False
update_raft_thickness = False
update_extra_z_clearance = True
for setting_key in self._changed_settings_since_last_rebuild:
if setting_key == "print_sequence":
machine_height = self._global_container_stack.getProperty("machine_height", "value")
if Application.getInstance().getGlobalContainerStack().getProperty("print_sequence",
"value") == "one_at_a_time" and len(
self._scene_objects) > 1:
self._height = min(self._global_container_stack.getProperty("gantry_height", "value"),
machine_height)
if self._height < machine_height:
self._build_volume_message.show()
else:
self._build_volume_message.hide()
else:
self._height = self._global_container_stack.getProperty("machine_height", "value")
self._build_volume_message.hide()
rebuild_me = True
if setting_key in self._skirt_settings or setting_key in self._prime_settings or setting_key in self._tower_settings or setting_key == "print_sequence" or setting_key in self._ooze_shield_settings or setting_key in self._distance_settings or setting_key in self._extruder_settings:
update_disallowed_areas = True
rebuild_me = True
if setting_key in self._raft_settings:
update_raft_thickness = True
rebuild_me = True
if setting_key in self._extra_z_settings:
update_extra_z_clearance = True
rebuild_me = True
if setting_key in self._limit_to_extruder_settings:
update_disallowed_areas = True
rebuild_me = True
# We only want to update all of them once.
if update_disallowed_areas:
self._updateDisallowedAreas()
if update_raft_thickness:
self._updateRaftThickness()
if update_extra_z_clearance:
self._updateExtraZClearance()
if rebuild_me:
self.rebuild()
# We just did a rebuild, reset the list.
self._changed_settings_since_last_rebuild = []
def _onSettingPropertyChanged(self, setting_key: str, property_name: str):
if property_name != "value":
return
rebuild_me = False
if setting_key == "print_sequence":
machine_height = self._global_container_stack.getProperty("machine_height", "value")
if Application.getInstance().getGlobalContainerStack().getProperty("print_sequence", "value") == "one_at_a_time" and len(self._scene_objects) > 1:
self._height = min(self._global_container_stack.getProperty("gantry_height", "value"), machine_height)
if self._height < machine_height:
self._build_volume_message.show()
else:
self._build_volume_message.hide()
else:
self._height = self._global_container_stack.getProperty("machine_height", "value")
self._build_volume_message.hide()
rebuild_me = True
if setting_key in self._skirt_settings or setting_key in self._prime_settings or setting_key in self._tower_settings or setting_key == "print_sequence" or setting_key in self._ooze_shield_settings or setting_key in self._distance_settings or setting_key in self._extruder_settings:
self._updateDisallowedAreas()
rebuild_me = True
if setting_key in self._raft_settings:
self._updateRaftThickness()
rebuild_me = True
if setting_key in self._extra_z_settings:
self._updateExtraZClearance()
rebuild_me = True
if setting_key in self._limit_to_extruder_settings:
self._updateDisallowedAreas()
rebuild_me = True
if rebuild_me:
self.rebuild()
if setting_key not in self._changed_settings_since_last_rebuild:
self._changed_settings_since_last_rebuild.append(setting_key)
self._setting_change_timer.start()
def hasErrors(self) -> bool:
return self._has_errors
@ -985,14 +956,14 @@ class BuildVolume(SceneNode):
if adhesion_type == "skirt":
skirt_distance = self._getSettingFromAdhesionExtruder("skirt_gap")
skirt_line_count = self._getSettingFromAdhesionExtruder("skirt_line_count")
bed_adhesion_size = skirt_distance + (skirt_line_count * self._getSettingFromAdhesionExtruder("skirt_brim_line_width")) * self._getSettingFromAdhesionExtruder("initial_layer_line_width_factor") / 100.0
bed_adhesion_size = skirt_distance + (self._getSettingFromAdhesionExtruder("skirt_brim_line_width") * skirt_line_count) * self._getSettingFromAdhesionExtruder("initial_layer_line_width_factor") / 100.0
if len(used_extruders) > 1:
for extruder_stack in used_extruders:
bed_adhesion_size += extruder_stack.getProperty("skirt_brim_line_width", "value") * extruder_stack.getProperty("initial_layer_line_width_factor", "value") / 100.0
#We don't create an additional line for the extruder we're printing the skirt with.
bed_adhesion_size -= self._getSettingFromAdhesionExtruder("skirt_brim_line_width", "value") * self._getSettingFromAdhesionExtruder("initial_layer_line_width_factor", "value") / 100.0
elif adhesion_type == "brim":
bed_adhesion_size = self._getSettingFromAdhesionExtruder("brim_line_count") * self._getSettingFromAdhesionExtruder("skirt_brim_line_width") * self._getSettingFromAdhesionExtruder("initial_layer_line_width_factor") / 100.0
bed_adhesion_size = self._getSettingFromAdhesionExtruder("skirt_brim_line_width") * self._getSettingFromAdhesionExtruder("brim_line_count") * self._getSettingFromAdhesionExtruder("initial_layer_line_width_factor") / 100.0
if self._global_container_stack.getProperty("machine_extruder_count", "value") > 1:
for extruder_stack in used_extruders:
bed_adhesion_size += extruder_stack.getProperty("skirt_brim_line_width", "value") * extruder_stack.getProperty("initial_layer_line_width_factor", "value") / 100.0

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import QVariantAnimation, QEasingCurve

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Application import Application
from UM.Math.Polygon import Polygon
@ -266,7 +266,7 @@ class ConvexHullDecorator(SceneNodeDecorator):
if self._getSettingProperty("mold_enabled", "value"):
mold_width = self._getSettingProperty("mold_width", "value")
hull_offset = horizontal_expansion + mold_width
if hull_offset != 0:
if hull_offset > 0: #TODO: Implement Minkowski subtraction for if the offset < 0.
expansion_polygon = Polygon(numpy.array([
[-hull_offset, -hull_offset],
[-hull_offset, hull_offset],

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Application import Application
from UM.Scene.SceneNode import SceneNode

View File

@ -1,18 +1,28 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
import sys
import platform
import traceback
import webbrowser
import faulthandler
import tempfile
import os
import urllib
import os.path
import time
import json
import ssl
import urllib.request
import urllib.error
from PyQt5.QtCore import QT_VERSION_STR, PYQT_VERSION_STR, Qt, QCoreApplication
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QHBoxLayout, QVBoxLayout, QLabel, QTextEdit
from PyQt5.QtCore import QT_VERSION_STR, PYQT_VERSION_STR, QCoreApplication
from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QVBoxLayout, QLabel, QTextEdit, QGroupBox
from UM.Application import Application
from UM.Logger import Logger
from UM.View.GL.OpenGL import OpenGL
from UM.i18n import i18nCatalog
from UM.Platform import Platform
catalog = i18nCatalog("cura")
MYPY = False
@ -35,83 +45,240 @@ fatal_exception_types = [
SystemError,
]
def show(exception_type, value, tb):
Logger.log("c", "An uncaught exception has occurred!")
for line in traceback.format_exception(exception_type, value, tb):
for part in line.rstrip("\n").split("\n"):
Logger.log("c", part)
if not CuraDebugMode and exception_type not in fatal_exception_types:
return
class CrashHandler:
crash_url = "https://stats.ultimaker.com/api/cura"
application = QCoreApplication.instance()
if not application:
sys.exit(1)
def __init__(self, exception_type, value, tb):
self.exception_type = exception_type
self.value = value
self.traceback = tb
dialog = QDialog()
dialog.setMinimumWidth(640)
dialog.setMinimumHeight(640)
dialog.setWindowTitle(catalog.i18nc("@title:window", "Crash Report"))
# While we create the GUI, the information will be stored for sending afterwards
self.data = dict()
self.data["time_stamp"] = time.time()
layout = QVBoxLayout(dialog)
Logger.log("c", "An uncaught exception has occurred!")
for line in traceback.format_exception(exception_type, value, tb):
for part in line.rstrip("\n").split("\n"):
Logger.log("c", part)
#label = QLabel(dialog)
#pixmap = QPixmap()
#try:
# data = urllib.request.urlopen("http://www.randomkittengenerator.com/cats/rotator.php").read()
# pixmap.loadFromData(data)
#except:
# try:
# from UM.Resources import Resources
# path = Resources.getPath(Resources.Images, "kitten.jpg")
# pixmap.load(path)
# except:
# pass
#pixmap = pixmap.scaled(150, 150)
#label.setPixmap(pixmap)
#label.setAlignment(Qt.AlignCenter)
#layout.addWidget(label)
if not CuraDebugMode and exception_type not in fatal_exception_types:
return
label = QLabel(dialog)
layout.addWidget(label)
application = QCoreApplication.instance()
if not application:
sys.exit(1)
#label.setScaledContents(True)
label.setText(catalog.i18nc("@label", """<p>A fatal exception has occurred that we could not recover from!</p>
<p>Please use the information below to post a bug report at <a href=\"http://github.com/Ultimaker/Cura/issues\">http://github.com/Ultimaker/Cura/issues</a></p>
"""))
self._createDialog()
textarea = QTextEdit(dialog)
layout.addWidget(textarea)
## Creates a modal dialog.
def _createDialog(self):
self.dialog = QDialog()
self.dialog.setMinimumWidth(640)
self.dialog.setMinimumHeight(640)
self.dialog.setWindowTitle(catalog.i18nc("@title:window", "Crash Report"))
try:
from UM.Application import Application
version = Application.getInstance().getVersion()
except:
version = "Unknown"
layout = QVBoxLayout(self.dialog)
trace = "".join(traceback.format_exception(exception_type, value, tb))
layout.addWidget(self._messageWidget())
layout.addWidget(self._informationWidget())
layout.addWidget(self._exceptionInfoWidget())
layout.addWidget(self._logInfoWidget())
layout.addWidget(self._userDescriptionWidget())
layout.addWidget(self._buttonsWidget())
crash_info = "Version: {0}\nPlatform: {1}\nQt: {2}\nPyQt: {3}\n\nException:\n{4}"
crash_info = crash_info.format(version, platform.platform(), QT_VERSION_STR, PYQT_VERSION_STR, trace)
def _messageWidget(self):
label = QLabel()
label.setText(catalog.i18nc("@label crash message", """<p><b>A fatal exception has occurred. Please send us this Crash Report to fix the problem</p></b>
<p>Please use the "Send report" button to post a bug report automatically to our servers</p>
"""))
tmp_file_fd, tmp_file_path = tempfile.mkstemp(prefix = "cura-crash", text = True)
os.close(tmp_file_fd)
with open(tmp_file_path, "w") as f:
faulthandler.dump_traceback(f, all_threads=True)
with open(tmp_file_path, "r") as f:
data = f.read()
return label
msg = "-------------------------\n"
msg += data
crash_info += "\n\n" + msg
def _informationWidget(self):
group = QGroupBox()
group.setTitle(catalog.i18nc("@title:groupbox", "System information"))
layout = QVBoxLayout()
label = QLabel()
textarea.setText(crash_info)
try:
from UM.Application import Application
self.cura_version = Application.getInstance().getVersion()
except:
self.cura_version = catalog.i18nc("@label unknown version of Cura", "Unknown")
buttons = QDialogButtonBox(QDialogButtonBox.Close, dialog)
layout.addWidget(buttons)
buttons.addButton(catalog.i18nc("@action:button", "Open Web Page"), QDialogButtonBox.HelpRole)
buttons.rejected.connect(dialog.close)
buttons.helpRequested.connect(lambda: webbrowser.open("http://github.com/Ultimaker/Cura/issues"))
crash_info = catalog.i18nc("@label Cura version", "<b>Cura version:</b> {version}<br/>").format(version = self.cura_version)
crash_info += catalog.i18nc("@label Platform", "<b>Platform:</b> {platform}<br/>").format(platform = platform.platform())
crash_info += catalog.i18nc("@label Qt version", "<b>Qt version:</b> {qt}<br/>").format(qt = QT_VERSION_STR)
crash_info += catalog.i18nc("@label PyQt version", "<b>PyQt version:</b> {pyqt}<br/>").format(pyqt = PYQT_VERSION_STR)
crash_info += catalog.i18nc("@label OpenGL", "<b>OpenGL:</b> {opengl}<br/>").format(opengl = self._getOpenGLInfo())
label.setText(crash_info)
dialog.exec_()
sys.exit(1)
layout.addWidget(label)
group.setLayout(layout)
self.data["cura_version"] = self.cura_version
self.data["os"] = {"type": platform.system(), "version": platform.version()}
self.data["qt_version"] = QT_VERSION_STR
self.data["pyqt_version"] = PYQT_VERSION_STR
return group
def _getOpenGLInfo(self):
info = "<ul>"
info += catalog.i18nc("@label OpenGL version", "<li>OpenGL Version: {version}</li>").format(version = OpenGL.getInstance().getOpenGLVersion())
info += catalog.i18nc("@label OpenGL vendor", "<li>OpenGL Vendor: {vendor}</li>").format(vendor = OpenGL.getInstance().getGPUVendorName())
info += catalog.i18nc("@label OpenGL renderer", "<li>OpenGL Renderer: {renderer}</li>").format(renderer = OpenGL.getInstance().getGPUType())
info += "</ul>"
self.data["opengl"] = {"version": OpenGL.getInstance().getOpenGLVersion(), "vendor": OpenGL.getInstance().getGPUVendorName(), "type": OpenGL.getInstance().getGPUType()}
return info
def _exceptionInfoWidget(self):
group = QGroupBox()
group.setTitle(catalog.i18nc("@title:groupbox", "Exception traceback"))
layout = QVBoxLayout()
text_area = QTextEdit()
trace_dict = traceback.format_exception(self.exception_type, self.value, self.traceback)
trace = "".join(trace_dict)
text_area.setText(trace)
text_area.setReadOnly(True)
layout.addWidget(text_area)
group.setLayout(layout)
# Parsing all the information to fill the dictionary
summary = trace_dict[len(trace_dict)-1].rstrip("\n")
module = trace_dict[len(trace_dict)-2].rstrip("\n").split("\n")
module_split = module[0].split(", ")
filepath = module_split[0].split("\"")[1]
directory, filename = os.path.split(filepath)
line = int(module_split[1].lstrip("line "))
function = module_split[2].lstrip("in ")
code = module[1].lstrip(" ")
# Using this workaround for a cross-platform path splitting
split_path = []
folder_name = ""
# Split until reach folder "cura"
while folder_name != "cura":
directory, folder_name = os.path.split(directory)
if not folder_name:
break
split_path.append(folder_name)
# Look for plugins. If it's not a plugin, the current cura version is set
isPlugin = False
module_version = self.cura_version
module_name = "Cura"
if split_path.__contains__("plugins"):
isPlugin = True
# Look backwards until plugin.json is found
directory, name = os.path.split(filepath)
while not os.listdir(directory).__contains__("plugin.json"):
directory, name = os.path.split(directory)
json_metadata_file = os.path.join(directory, "plugin.json")
try:
with open(json_metadata_file, "r") as f:
try:
metadata = json.loads(f.read())
module_version = metadata["version"]
module_name = metadata["name"]
except json.decoder.JSONDecodeError:
# Not throw new exceptions
Logger.logException("e", "Failed to parse plugin.json for plugin %s", name)
except:
# Not throw new exceptions
pass
exception_dict = dict()
exception_dict["traceback"] = {"summary": summary, "full_trace": trace}
exception_dict["location"] = {"path": filepath, "file": filename, "function": function, "code": code, "line": line,
"module_name": module_name, "version": module_version, "is_plugin": isPlugin}
self.data["exception"] = exception_dict
return group
def _logInfoWidget(self):
group = QGroupBox()
group.setTitle(catalog.i18nc("@title:groupbox", "Logs"))
layout = QVBoxLayout()
text_area = QTextEdit()
tmp_file_fd, tmp_file_path = tempfile.mkstemp(prefix = "cura-crash", text = True)
os.close(tmp_file_fd)
with open(tmp_file_path, "w") as f:
faulthandler.dump_traceback(f, all_threads=True)
with open(tmp_file_path, "r") as f:
logdata = f.read()
text_area.setText(logdata)
text_area.setReadOnly(True)
layout.addWidget(text_area)
group.setLayout(layout)
self.data["log"] = logdata
return group
def _userDescriptionWidget(self):
group = QGroupBox()
group.setTitle(catalog.i18nc("@title:groupbox", "User description"))
layout = QVBoxLayout()
# When sending the report, the user comments will be collected
self.user_description_text_area = QTextEdit()
self.user_description_text_area.setFocus(True)
layout.addWidget(self.user_description_text_area)
group.setLayout(layout)
return group
def _buttonsWidget(self):
buttons = QDialogButtonBox()
buttons.addButton(QDialogButtonBox.Close)
buttons.addButton(catalog.i18nc("@action:button", "Send report"), QDialogButtonBox.AcceptRole)
buttons.rejected.connect(self.dialog.close)
buttons.accepted.connect(self._sendCrashReport)
return buttons
def _sendCrashReport(self):
# Before sending data, the user comments are stored
self.data["user_info"] = self.user_description_text_area.toPlainText()
# Convert data to bytes
binary_data = json.dumps(self.data).encode("utf-8")
# Submit data
kwoptions = {"data": binary_data, "timeout": 5}
if Platform.isOSX():
kwoptions["context"] = ssl._create_unverified_context()
Logger.log("i", "Sending crash report info to [%s]...", self.crash_url)
try:
f = urllib.request.urlopen(self.crash_url, **kwoptions)
Logger.log("i", "Sent crash report info.")
f.close()
except urllib.error.HTTPError:
Logger.logException("e", "An HTTP error occurred while trying to send crash report")
except Exception: # We don't want any exception to cause problems
Logger.logException("e", "An exception occurred while trying to send crash report")
os._exit(1)
def show(self):
# must run the GUI code on the Qt thread, otherwise the widgets on the dialog won't react correctly.
Application.getInstance().callLater(self._show)
def _show(self):
self.dialog.exec_()
os._exit(1)

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import QObject, QUrl
from PyQt5.QtGui import QDesktopServices
@ -36,6 +36,15 @@ class CuraActions(QObject):
event = CallFunctionEvent(self._openUrl, [QUrl("http://github.com/Ultimaker/Cura/issues")], {})
Application.getInstance().functionEvent(event)
## Reset camera position and direction to default
@pyqtSlot()
def homeCamera(self) -> None:
scene = Application.getInstance().getController().getScene()
camera = scene.getActiveCamera()
camera.setPosition(Vector(-80, 250, 700))
camera.setPerspective(True)
camera.lookAt(Vector(0, 0, 0))
## Center all objects in the selection
@pyqtSlot()
def centerSelection(self) -> None:

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtNetwork import QLocalServer
from PyQt5.QtNetwork import QLocalSocket
@ -51,6 +51,7 @@ from cura.Settings.MaterialsModel import MaterialsModel
from cura.Settings.QualityAndUserProfilesModel import QualityAndUserProfilesModel
from cura.Settings.SettingInheritanceManager import SettingInheritanceManager
from cura.Settings.UserProfilesModel import UserProfilesModel
from cura.Settings.SimpleModeSettingsManager import SimpleModeSettingsManager
from . import PlatformPhysics
from . import BuildVolume
@ -104,7 +105,7 @@ class CuraApplication(QtApplication):
# SettingVersion represents the set of settings available in the machine/extruder definitions.
# You need to make sure that this version number needs to be increased if there is any non-backwards-compatible
# changes of the settings.
SettingVersion = 2
SettingVersion = 3
class ResourceTypes:
QmlFiles = Resources.UserType + 1
@ -125,6 +126,8 @@ class CuraApplication(QtApplication):
# Cura will always show the Add Machine Dialog upon start.
stacksValidationFinished = pyqtSignal() # Emitted whenever a validation is finished
projectFileLoaded = pyqtSignal(str) # Emitted whenever a project file is loaded
def __init__(self):
# this list of dir names will be used by UM to detect an old cura directory
for dir_name in ["extruders", "machine_instances", "materials", "plugins", "quality", "user", "variants"]:
@ -199,6 +202,7 @@ class CuraApplication(QtApplication):
self._machine_manager = None # This is initialized on demand.
self._material_manager = None
self._setting_inheritance_manager = None
self._simple_mode_settings_manager = None
self._additional_components = {} # Components to add to certain areas in the interface
@ -211,7 +215,7 @@ class CuraApplication(QtApplication):
self.setRequiredPlugins([
"CuraEngineBackend",
"MeshView",
"SolidView",
"LayerView",
"STLReader",
"SelectionTool",
@ -220,7 +224,8 @@ class CuraApplication(QtApplication):
"LocalFileOutputDevice",
"TranslateTool",
"FileLogger",
"XmlMaterialProfile"
"XmlMaterialProfile",
"PluginBrowser"
])
self._physics = None
self._volume = None
@ -399,6 +404,8 @@ class CuraApplication(QtApplication):
# ALWAYS ask whether to keep or discard the profile
self.showDiscardOrKeepProfileChanges.emit()
#sidebarSimpleDiscardOrKeepProfileChanges = pyqtSignal()
@pyqtSlot(str)
def discardOrKeepProfileChangesClosed(self, option):
if option == "discard":
@ -488,7 +495,7 @@ class CuraApplication(QtApplication):
f.write(data)
@pyqtSlot(str, result=QUrl)
@pyqtSlot(str, result = QUrl)
def getDefaultPath(self, key):
default_path = Preferences.getInstance().getValue("local_file/%s" % key)
return QUrl.fromLocalFile(default_path)
@ -665,7 +672,9 @@ class CuraApplication(QtApplication):
qmlRegisterSingletonType(MachineManager, "Cura", 1, 0, "MachineManager", self.getMachineManager)
qmlRegisterSingletonType(MaterialManager, "Cura", 1, 0, "MaterialManager", self.getMaterialManager)
qmlRegisterSingletonType(SettingInheritanceManager, "Cura", 1, 0, "SettingInheritanceManager",
self.getSettingInheritanceManager)
self.getSettingInheritanceManager)
qmlRegisterSingletonType(SimpleModeSettingsManager, "Cura", 1, 2, "SimpleModeSettingsManager",
self.getSimpleModeSettingsManager)
qmlRegisterSingletonType(MachineActionManager.MachineActionManager, "Cura", 1, 0, "MachineActionManager", self.getMachineActionManager)
self.setMainQml(Resources.getPath(self.ResourceTypes.QmlFiles, "Cura.qml"))
@ -705,6 +714,11 @@ class CuraApplication(QtApplication):
def getMachineActionManager(self, *args):
return self._machine_action_manager
def getSimpleModeSettingsManager(self, *args):
if self._simple_mode_settings_manager is None:
self._simple_mode_settings_manager = SimpleModeSettingsManager()
return self._simple_mode_settings_manager
## Handle Qt events
def event(self, event):
if event.type() == QEvent.FileOpen:
@ -1128,7 +1142,7 @@ class CuraApplication(QtApplication):
expandedCategoriesChanged = pyqtSignal()
@pyqtProperty("QStringList", notify=expandedCategoriesChanged)
@pyqtProperty("QStringList", notify = expandedCategoriesChanged)
def expandedCategories(self):
return Preferences.getInstance().getValue("cura/categories_expanded").split(";")
@ -1182,6 +1196,7 @@ class CuraApplication(QtApplication):
group_node = SceneNode()
group_decorator = GroupDecorator()
group_node.addDecorator(group_decorator)
group_node.addDecorator(ConvexHullDecorator())
group_node.setParent(self.getController().getScene().getRoot())
group_node.setSelectable(True)
center = Selection.getSelectionCenter()
@ -1292,7 +1307,7 @@ class CuraApplication(QtApplication):
message = Message(
self._i18n_catalog.i18nc("@info:status",
"Only one G-code file can be loaded at a time. Skipped importing {0}",
filename))
filename), title = self._i18n_catalog.i18nc("@info:title", "Warning"))
message.show()
return
# If file being loaded is non-slicable file, then prevent loading of any other files
@ -1301,7 +1316,7 @@ class CuraApplication(QtApplication):
message = Message(
self._i18n_catalog.i18nc("@info:status",
"Can't open any other file if G-code is loading. Skipped importing {0}",
filename))
filename), title = self._i18n_catalog.i18nc("@info:title", "Error"))
message.show()
return
@ -1357,6 +1372,12 @@ class CuraApplication(QtApplication):
# Find node location
offset_shape_arr, hull_shape_arr = ShapeArray.fromNode(node, min_offset = min_offset)
# If a model is to small then it will not contain any points
if offset_shape_arr is None and hull_shape_arr is None:
Message(self._i18n_catalog.i18nc("@info:status", "The selected model was too small to load."),
title=self._i18n_catalog.i18nc("@info:title", "Warning")).show()
return
# Step is for skipping tests to make it a lot faster. it also makes the outcome somewhat rougher
node, _ = arranger.findNodePlacement(node, offset_shape_arr, hull_shape_arr, step = 10)

View File

@ -1,38 +1,106 @@
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
# Copyright (c) 2017 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import Qt, QCoreApplication
from PyQt5.QtGui import QPixmap, QColor, QFont, QFontMetrics
from PyQt5.QtCore import Qt, QCoreApplication, QTimer
from PyQt5.QtGui import QPixmap, QColor, QFont, QPen, QPainter
from PyQt5.QtWidgets import QSplashScreen
from UM.Resources import Resources
from UM.Application import Application
class CuraSplashScreen(QSplashScreen):
def __init__(self):
super().__init__()
self._scale = round(QFontMetrics(QCoreApplication.instance().font()).ascent() / 12)
self._scale = 0.7
splash_image = QPixmap(Resources.getPath(Resources.Images, "cura.png"))
self.setPixmap(splash_image.scaled(splash_image.size() * self._scale))
self.setPixmap(splash_image)
self._current_message = ""
self._loading_image_rotation_angle = 0
self._to_stop = False
self._change_timer = QTimer()
self._change_timer.setInterval(50)
self._change_timer.setSingleShot(False)
self._change_timer.timeout.connect(self.updateLoadingImage)
def show(self):
super().show()
self._change_timer.start()
def updateLoadingImage(self):
if self._to_stop:
return
self._loading_image_rotation_angle -= 10
self.repaint()
# Override the mousePressEvent so the splashscreen doesn't disappear when clicked
def mousePressEvent(self, mouse_event):
pass
def drawContents(self, painter):
if self._to_stop:
return
painter.save()
painter.setPen(QColor(0, 0, 0, 255))
painter.setPen(QColor(255, 255, 255, 255))
painter.setRenderHint(QPainter.Antialiasing)
painter.setRenderHint(QPainter.Antialiasing, True)
version = Application.getInstance().getVersion().split("-")
buildtype = Application.getInstance().getBuildType()
if buildtype:
version[0] += " (%s)" %(buildtype)
version[0] += " (%s)" % buildtype
font = QFont() # Using system-default font here
font.setPointSize(20)
# draw version text
font = QFont() # Using system-default font here
font.setPixelSize(37)
painter.setFont(font)
painter.drawText(0, 0, 330 * self._scale, 230 * self._scale, Qt.AlignHCenter | Qt.AlignBottom, version[0])
painter.drawText(215, 66, 330 * self._scale, 230 * self._scale, Qt.AlignLeft | Qt.AlignTop, version[0])
if len(version) > 1:
font.setPointSize(12)
font.setPixelSize(16)
painter.setFont(font)
painter.drawText(0, 0, 330 * self._scale, 255 * self._scale, Qt.AlignHCenter | Qt.AlignBottom, version[1])
painter.setPen(QColor(200, 200, 200, 255))
painter.drawText(247, 105, 330 * self._scale, 255 * self._scale, Qt.AlignLeft | Qt.AlignTop, version[1])
painter.setPen(QColor(255, 255, 255, 255))
# draw the loading image
pen = QPen()
pen.setWidth(6 * self._scale)
pen.setColor(QColor(32, 166, 219, 255))
painter.setPen(pen)
painter.drawArc(60, 150, 32 * self._scale, 32 * self._scale, self._loading_image_rotation_angle * 16, 300 * 16)
# draw message text
if self._current_message:
font = QFont() # Using system-default font here
font.setPixelSize(13)
pen = QPen()
pen.setColor(QColor(255, 255, 255, 255))
painter.setPen(pen)
painter.setFont(font)
painter.drawText(100, 128, 170, 64,
Qt.AlignLeft | Qt.AlignVCenter | Qt.TextWordWrap,
self._current_message)
painter.restore()
super().drawContents(painter)
def showMessage(self, message, *args, **kwargs):
if self._to_stop:
return
self._current_message = message
self.messageChanged.emit(message)
QCoreApplication.flush()
self.repaint()
def close(self):
# set stop flags
self._to_stop = True
self._change_timer.stop()
super().close()

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
CuraVersion = "@CURA_VERSION@"
CuraBuildType = "@CURA_BUILDTYPE@"

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Mesh.MeshData import MeshData

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from .Layer import Layer
from .LayerPolygon import LayerPolygon

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Application import Application
from typing import Any

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import QObject, pyqtSlot, pyqtProperty, pyqtSignal, QUrl
from PyQt5.QtQml import QQmlComponent, QQmlContext

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Logger import Logger
from UM.PluginRegistry import PluginRegistry # So MachineAction can be added as plugin type

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Job import Job
from UM.Scene.SceneNode import SceneNode
@ -32,7 +32,7 @@ class MultiplyObjectsJob(Job):
def run(self):
status_message = Message(i18n_catalog.i18nc("@info:status", "Multiplying and placing objects"), lifetime=0,
dismissable=False, progress=0)
dismissable=False, progress=0, title = i18n_catalog.i18nc("@info:title", "Placing Object"))
status_message.show()
scene = Application.getInstance().getController().getScene()
@ -80,5 +80,5 @@ class MultiplyObjectsJob(Job):
status_message.hide()
if not found_solution_for_all:
no_full_solution_message = Message(i18n_catalog.i18nc("@info:status", "Unable to find a location within the build volume for all objects"))
no_full_solution_message = Message(i18n_catalog.i18nc("@info:status", "Unable to find a location within the build volume for all objects"), title = i18n_catalog.i18nc("@info:title", "Placing Object"))
no_full_solution_message.show()

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Scene.Iterator import Iterator
from UM.Scene.SceneNode import SceneNode

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import QTimer
@ -41,7 +41,7 @@ class PlatformPhysics:
def _onSceneChanged(self, source):
self._change_timer.start()
def _onChangeTimerFinished(self):
def _onChangeTimerFinished(self, was_triggered_by_tool=False):
if not self._enabled:
return
@ -67,6 +67,7 @@ class PlatformPhysics:
# Move it downwards if bottom is above platform
move_vector = Vector()
if Preferences.getInstance().getValue("physics/automatic_drop_down") and not (node.getParent() and node.getParent().callDecoration("isGroup")) and node.isEnabled(): #If an object is grouped, don't move it down
z_offset = node.callDecoration("getZOffset") if node.getDecorator(ZOffsetDecorator.ZOffsetDecorator) else 0
move_vector = move_vector.set(y=-bbox.bottom + z_offset)
@ -159,4 +160,4 @@ class PlatformPhysics:
node.removeDecorator(ZOffsetDecorator.ZOffsetDecorator)
self._enabled = True
self._onChangeTimerFinished()
self._onChangeTimerFinished(True)

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Operations.Operation import Operation
from UM.Operations.GroupedOperation import GroupedOperation

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty
from UM.FlameProfiler import pyqtSlot
@ -51,20 +51,7 @@ class PrintInformation(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._current_print_time = Duration(None, self)
self._print_times_per_feature = {
"none": Duration(None, self),
"inset_0": Duration(None, self),
"inset_x": Duration(None, self),
"skin": Duration(None, self),
"support": Duration(None, self),
"skirt": Duration(None, self),
"infill": Duration(None, self),
"support_infill": Duration(None, self),
"travel": Duration(None, self),
"retract": Duration(None, self),
"support_interface": Duration(None, self)
}
self.initializeCuraMessagePrintTimeProperties()
self._material_lengths = []
self._material_weights = []
@ -76,12 +63,14 @@ class PrintInformation(QObject):
if self._backend:
self._backend.printDurationMessage.connect(self._onPrintDurationMessage)
self._job_name = ""
self._base_name = ""
self._abbr_machine = ""
self._job_name = ""
self._project_name = ""
Application.getInstance().globalContainerStackChanged.connect(self._setAbbreviatedMachineName)
Application.getInstance().fileLoaded.connect(self.setJobName)
Application.getInstance().globalContainerStackChanged.connect(self._updateJobName)
Application.getInstance().fileLoaded.connect(self.setBaseName)
Application.getInstance().projectFileLoaded.connect(self.setProjectName)
Preferences.getInstance().preferenceChanged.connect(self._onPreferencesChanged)
self._active_material_container = None
@ -90,6 +79,32 @@ class PrintInformation(QObject):
self._material_amounts = []
# Crate cura message translations and using translation keys initialize empty time Duration object for total time
# and time for each feature
def initializeCuraMessagePrintTimeProperties(self):
self._current_print_time = Duration(None, self)
self._print_time_message_translations = {
"inset_0": catalog.i18nc("@tooltip", "Outer Wall"),
"inset_x": catalog.i18nc("@tooltip", "Inner Walls"),
"skin": catalog.i18nc("@tooltip", "Skin"),
"infill": catalog.i18nc("@tooltip", "Infill"),
"support_infill": catalog.i18nc("@tooltip", "Support Infill"),
"support_interface": catalog.i18nc("@tooltip", "Support Interface"),
"support": catalog.i18nc("@tooltip", "Support"),
"skirt": catalog.i18nc("@tooltip", "Skirt"),
"travel": catalog.i18nc("@tooltip", "Travel"),
"retract": catalog.i18nc("@tooltip", "Retractions"),
"none": catalog.i18nc("@tooltip", "Other")
}
self._print_time_message_values = {}
# Full fill message values using keys from _print_time_message_translations
for key in self._print_time_message_translations.keys():
self._print_time_message_values[key] = Duration(None, self)
currentPrintTimeChanged = pyqtSignal()
preSlicedChanged = pyqtSignal()
@ -106,10 +121,6 @@ class PrintInformation(QObject):
def currentPrintTime(self):
return self._current_print_time
@pyqtProperty("QVariantMap", notify = currentPrintTimeChanged)
def printTimesPerFeature(self):
return self._print_times_per_feature
materialLengthsChanged = pyqtSignal()
@pyqtProperty("QVariantList", notify = materialLengthsChanged)
@ -128,22 +139,28 @@ class PrintInformation(QObject):
def materialCosts(self):
return self._material_costs
def _onPrintDurationMessage(self, time_per_feature, material_amounts):
total_time = 0
for feature, time in time_per_feature.items():
if time != time: # Check for NaN. Engine can sometimes give us weird values.
self._print_times_per_feature[feature].setDuration(0)
Logger.log("w", "Received NaN for print duration message")
continue
total_time += time
self._print_times_per_feature[feature].setDuration(time)
self._current_print_time.setDuration(total_time)
def _onPrintDurationMessage(self, print_time, material_amounts):
self._updateTotalPrintTimePerFeature(print_time)
self.currentPrintTimeChanged.emit()
self._material_amounts = material_amounts
self._calculateInformation()
def _updateTotalPrintTimePerFeature(self, print_time):
total_estimated_time = 0
for feature, time in print_time.items():
if time != time: # Check for NaN. Engine can sometimes give us weird values.
self._print_time_message_values.get(feature).setDuration(0)
Logger.log("w", "Received NaN for print duration message")
continue
total_estimated_time += time
self._print_time_message_values.get(feature).setDuration(time)
self._current_print_time.setDuration(total_estimated_time)
def _calculateInformation(self):
if Application.getInstance().getGlobalContainerStack() is None:
return
@ -221,16 +238,13 @@ class PrintInformation(QObject):
@pyqtSlot(str)
def setJobName(self, name):
# Ensure that we don't use entire path but only filename
name = os.path.basename(name)
self._job_name = name
self.jobNameChanged.emit()
# when a file is opened using the terminal; the filename comes from _onFileLoaded and still contains its
# extension. This cuts the extension off if necessary.
name = os.path.splitext(name)[0]
name = self.createJobName(name)
if self._job_name != name and (self._job_name == "" or name == ""):
self._job_name = name
self.jobNameChanged.emit()
@pyqtSlot(str)
def setProjectName(self, name):
self._project_name = name
self.setJobName(name)
jobNameChanged = pyqtSignal()
@ -238,21 +252,49 @@ class PrintInformation(QObject):
def jobName(self):
return self._job_name
@pyqtSlot(str, result = str)
def createJobName(self, base_name):
if base_name == "":
return ""
base_name = self._stripAccents(base_name)
def _updateJobName(self):
# if the project name is set, we use the project name as the job name, so the job name should not get updated
# if a model file is loaded after that.
if self._project_name != "":
return
if self._base_name == "":
self._job_name = ""
self.jobNameChanged.emit()
return
base_name = self._stripAccents(self._base_name)
self._setAbbreviatedMachineName()
if self._pre_sliced:
return catalog.i18nc("@label", "Pre-sliced file {0}", base_name)
self._job_name = catalog.i18nc("@label", "Pre-sliced file {0}", base_name)
elif Preferences.getInstance().getValue("cura/jobname_prefix"):
# Don't add abbreviation if it already has the exact same abbreviation.
if base_name.startswith(self._abbr_machine + "_"):
return base_name
return self._abbr_machine + "_" + base_name
self._job_name = base_name
else:
self._job_name = self._abbr_machine + "_" + base_name
else:
return base_name
self._job_name = base_name
self.jobNameChanged.emit()
@pyqtProperty(str)
def baseName(self):
return self._base_name
@pyqtSlot(str)
def setBaseName(self, base_name):
# Ensure that we don't use entire path but only filename
name = os.path.basename(base_name)
# when a file is opened using the terminal; the filename comes from _onFileLoaded and still contains its
# extension. This cuts the extension off if necessary.
name = os.path.splitext(name)[0]
# name is "" when I first had some meshes and afterwards I deleted them so the naming should start again
if name == "" or (self._base_name == "" and self._base_name != name):
self._base_name = name
self._updateJobName()
## Created an acronymn-like abbreviated machine name from the currently active machine name
# Called each time the global stack is switched
@ -277,4 +319,24 @@ class PrintInformation(QObject):
## Utility method that strips accents from characters (eg: â -> a)
def _stripAccents(self, str):
return ''.join(char for char in unicodedata.normalize('NFD', str) if unicodedata.category(char) != 'Mn')
return ''.join(char for char in unicodedata.normalize('NFD', str) if unicodedata.category(char) != 'Mn')
@pyqtSlot(result = "QVariantMap")
def getFeaturePrintTimes(self):
result = {}
for feature, time in self._print_time_message_values.items():
if feature in self._print_time_message_translations:
result[self._print_time_message_translations[feature]] = time
else:
result[feature] = time
return result
# Simulate message with zero time duration
def setToZeroPrintInformation(self):
temp_message = {}
for key in self._print_time_message_values.keys():
temp_message[key] = 0
temp_material_amounts = [0]
self._onPrintDurationMessage(temp_message, temp_material_amounts)

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.i18n import i18nCatalog
from UM.OutputDevice.OutputDevice import OutputDevice

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.PluginObject import PluginObject

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
# Uranium is released under the terms of the LGPLv3 or higher.
from UM.PluginObject import PluginObject

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
# This collects a lot of quality and quality changes related code which was split between ContainerManager
# and the MachineManager and really needs to usable from both.
@ -61,8 +61,6 @@ class QualityManager:
machine_definition = global_stack.definition
result = self.findAllQualityChangesForMachine(machine_definition)
for extruder in self.findAllExtruderDefinitionsForMachine(machine_definition):
result.extend(self.findAllQualityChangesForExtruder(extruder))
result = [quality_change for quality_change in result if quality_change.getName() == quality_changes_name]
return result
@ -82,6 +80,17 @@ class QualityManager:
return list(common_quality_types)
def findAllQualitiesForMachineAndMaterials(self, machine_definition: "DefinitionContainerInterface", material_containers: List[InstanceContainer]) -> List[InstanceContainer]:
# Determine the common set of quality types which can be
# applied to all of the materials for this machine.
quality_type_dict = self.__fetchQualityTypeDictForMaterial(machine_definition, material_containers[0])
qualities = set(quality_type_dict.values())
for material_container in material_containers[1:]:
next_quality_type_dict = self.__fetchQualityTypeDictForMaterial(machine_definition, material_container)
qualities.update(set(next_quality_type_dict.values()))
return list(qualities)
## Fetches a dict of quality types names to quality profiles for a combination of machine and material.
#
# \param machine_definition \type{DefinitionContainer} the machine definition.
@ -121,7 +130,7 @@ class QualityManager:
# \param material_container \type{InstanceContainer} the material.
# \return \type{List[InstanceContainer]} the list of suitable qualities.
def findAllQualitiesForMachineMaterial(self, machine_definition: "DefinitionContainerInterface", material_container: InstanceContainer) -> List[InstanceContainer]:
criteria = {"type": "quality" }
criteria = {"type": "quality"}
result = self._getFilteredContainersForStack(machine_definition, [material_container], **criteria)
if not result:
basic_materials = self._getBasicMaterials(material_container)
@ -140,7 +149,7 @@ class QualityManager:
else:
definition_id = "fdmprinter"
filter_dict = { "type": "quality_changes", "extruder": None, "definition": definition_id }
filter_dict = { "type": "quality_changes", "definition": definition_id }
quality_changes_list = ContainerRegistry.getInstance().findInstanceContainers(**filter_dict)
return quality_changes_list

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
# Uranium is released under the terms of the LGPLv3 or higher.
from UM.Scene.SceneNode import SceneNode
from UM.Operations import Operation

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
import os.path
import urllib

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Application import Application
from UM.Qt.ListModel import ListModel

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
import os
import os.path
@ -140,15 +140,20 @@ class CuraContainerRegistry(ContainerRegistry):
success = profile_writer.write(file_name, found_containers)
except Exception as e:
Logger.log("e", "Failed to export profile to %s: %s", file_name, str(e))
m = Message(catalog.i18nc("@info:status Don't translate the XML tags <filename> or <message>!", "Failed to export profile to <filename>{0}</filename>: <message>{1}</message>", file_name, str(e)), lifetime = 0)
m = Message(catalog.i18nc("@info:status Don't translate the XML tags <filename> or <message>!", "Failed to export profile to <filename>{0}</filename>: <message>{1}</message>", file_name, str(e)),
lifetime = 0,
title = catalog.i18nc("@info:title", "Error"))
m.show()
return
if not success:
Logger.log("w", "Failed to export profile to %s: Writer plugin reported failure.", file_name)
m = Message(catalog.i18nc("@info:status Don't translate the XML tag <filename>!", "Failed to export profile to <filename>{0}</filename>: Writer plugin reported failure.", file_name), lifetime = 0)
m = Message(catalog.i18nc("@info:status Don't translate the XML tag <filename>!", "Failed to export profile to <filename>{0}</filename>: Writer plugin reported failure.", file_name),
lifetime = 0,
title = catalog.i18nc("@info:title", "Error"))
m.show()
return
m = Message(catalog.i18nc("@info:status Don't translate the XML tag <filename>!", "Exported profile to <filename>{0}</filename>", file_name))
m = Message(catalog.i18nc("@info:status Don't translate the XML tag <filename>!", "Exported profile to <filename>{0}</filename>", file_name),
title = catalog.i18nc("@info:title", "Export succeeded"))
m.show()
## Gets the plugin object matching the criteria

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
import os.path

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Logger import Logger
@ -29,21 +29,24 @@ class CuraStackBuilder:
return None
machine_definition = definitions[0]
name = registry.createUniqueName("machine", "", name, machine_definition.name)
generated_name = registry.createUniqueName("machine", "", name, machine_definition.name)
# Make sure the new name does not collide with any definition or (quality) profile
# createUniqueName() only looks at other stacks, but not at definitions or quality profiles
# Note that we don't go for uniqueName() immediately because that function matches with ignore_case set to true
if registry.findContainers(id = name):
name = registry.uniqueName(name)
if registry.findContainers(id = generated_name):
generated_name = registry.uniqueName(generated_name)
new_global_stack = cls.createGlobalStack(
new_stack_id = name,
new_stack_id = generated_name,
definition = machine_definition,
quality = "default",
material = "default",
variant = "default",
)
new_global_stack.setName(generated_name)
for extruder_definition in registry.findDefinitionContainers(machine = machine_definition.id):
position = extruder_definition.getMetaDataEntry("position", None)
if not position:

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
## Raised when trying to perform an operation like add on a stack that does not allow that.

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import pyqtSignal, pyqtProperty, QObject, QVariant #For communicating data and events to Qt.
from UM.FlameProfiler import pyqtSlot
@ -16,6 +16,7 @@ from UM.Settings.InstanceContainer import InstanceContainer
from UM.Settings.SettingFunction import SettingFunction
from UM.Settings.ContainerStack import ContainerStack
from UM.Settings.Interfaces import DefinitionContainerInterface
from UM.Settings.PropertyEvaluationContext import PropertyEvaluationContext
from typing import Optional, List, TYPE_CHECKING, Union
if TYPE_CHECKING:
@ -41,7 +42,7 @@ class ExtruderManager(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._extruder_trains = { } #Per machine, a dictionary of extruder container stack IDs. Only for separately defined extruders.
self._active_extruder_index = 0
self._active_extruder_index = -1 # Indicates the index of the active extruder stack. -1 means no active extruder stack
self._selected_object_extruders = []
Application.getInstance().globalContainerStackChanged.connect(self.__globalContainerStackChanged)
self._global_container_stack_definition_id = None
@ -74,14 +75,18 @@ class ExtruderManager(QObject):
except KeyError:
return 0
## Gets a dict with the extruder stack ids with the extruder number as the key.
# The key "-1" indicates the global stack id.
#
@pyqtProperty("QVariantMap", notify = extrudersChanged)
def extruderIds(self):
map = {}
extruder_stack_ids = {}
global_stack_id = Application.getInstance().getGlobalContainerStack().getId()
extruder_stack_ids["-1"] = global_stack_id
if global_stack_id in self._extruder_trains:
for position in self._extruder_trains[global_stack_id]:
map[position] = self._extruder_trains[global_stack_id][position].getId()
return map
extruder_stack_ids[position] = self._extruder_trains[global_stack_id][position].getId()
return extruder_stack_ids
@pyqtSlot(str, result = str)
def getQualityChangesIdByExtruderStackId(self, id: str) -> str:
@ -506,23 +511,40 @@ class ExtruderManager(QObject):
result.extend(self.getActiveExtruderStacks())
return result
## Returns the list of active extruder stacks.
## Returns the list of active extruder stacks, taking into account the machine extruder count.
#
# \return \type{List[ContainerStack]} a list of
def getActiveExtruderStacks(self) -> List["ExtruderStack"]:
global_stack = Application.getInstance().getGlobalContainerStack()
result = []
machine_extruder_count = global_stack.getProperty("machine_extruder_count", "value")
# In case the printer is using one extruder, shouldn't exist active extruder stacks
if machine_extruder_count == 1:
return result
if global_stack and global_stack.getId() in self._extruder_trains:
for extruder in sorted(self._extruder_trains[global_stack.getId()]):
result.append(self._extruder_trains[global_stack.getId()][extruder])
return result
return result[:machine_extruder_count]
def __globalContainerStackChanged(self) -> None:
global_container_stack = Application.getInstance().getGlobalContainerStack()
if global_container_stack and global_container_stack.getBottom() and global_container_stack.getBottom().getId() != self._global_container_stack_definition_id:
self._global_container_stack_definition_id = global_container_stack.getBottom().getId()
self.globalContainerStackDefinitionChanged.emit()
# If the global container changed, the number of extruders could be changed and so the active_extruder_index is updated
extruder_count = global_container_stack.getProperty("machine_extruder_count", "value")
if extruder_count > 1:
if self._active_extruder_index == -1:
self.setActiveExtruderIndex(0)
else:
if self._active_extruder_index != -1:
self.setActiveExtruderIndex(-1)
self.activeExtruderChanged.emit()
self.resetSelectedObjectExtruders()
@ -566,6 +588,46 @@ class ExtruderManager(QObject):
return result
## Get all extruder values for a certain setting. This function will skip the user settings container.
#
# This is exposed to SettingFunction so it can be used in value functions.
#
# \param key The key of the setting to retrieve values for.
#
# \return A list of values for all extruders. If an extruder does not have a value, it will not be in the list.
# If no extruder has the value, the list will contain the global value.
@staticmethod
def getDefaultExtruderValues(key):
global_stack = Application.getInstance().getGlobalContainerStack()
context = PropertyEvaluationContext(global_stack)
context.context["evaluate_from_container_index"] = 1 # skip the user settings container
context.context["override_operators"] = {
"extruderValue": ExtruderManager.getDefaultExtruderValue,
"extruderValues": ExtruderManager.getDefaultExtruderValues,
"resolveOrValue": ExtruderManager.getDefaultResolveOrValue
}
result = []
for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
# only include values from extruders that are "active" for the current machine instance
if int(extruder.getMetaDataEntry("position")) >= global_stack.getProperty("machine_extruder_count", "value", context = context):
continue
value = extruder.getRawProperty(key, "value", context = context)
if value is None:
continue
if isinstance(value, SettingFunction):
value = value(extruder, context = context)
result.append(value)
if not result:
result.append(global_stack.getProperty(key, "value", context = context))
return result
## Get all extruder values for a certain setting.
#
# This is exposed to qml for display purposes
@ -599,6 +661,35 @@ class ExtruderManager(QObject):
return value
## Get the default value from the given extruder. This function will skip the user settings container.
#
# This is exposed to SettingFunction to use in value functions.
#
# \param extruder_index The index of the extruder to get the value from.
# \param key The key of the setting to get the value of.
#
# \return The value of the setting for the specified extruder or for the
# global stack if not found.
@staticmethod
def getDefaultExtruderValue(extruder_index, key):
extruder = ExtruderManager.getInstance().getExtruderStack(extruder_index)
context = PropertyEvaluationContext(extruder)
context.context["evaluate_from_container_index"] = 1 # skip the user settings container
context.context["override_operators"] = {
"extruderValue": ExtruderManager.getDefaultExtruderValue,
"extruderValues": ExtruderManager.getDefaultExtruderValues,
"resolveOrValue": ExtruderManager.getDefaultResolveOrValue
}
if extruder:
value = extruder.getRawProperty(key, "value", context = context)
if isinstance(value, SettingFunction):
value = value(extruder, context = context)
else: # Just a value from global.
value = Application.getInstance().getGlobalContainerStack().getProperty(key, "value", context = context)
return value
## Get the resolve value or value for a given key
#
# This is the effective value for a given key, it is used for values in the global stack.
@ -612,3 +703,25 @@ class ExtruderManager(QObject):
resolved_value = global_stack.getProperty(key, "value")
return resolved_value
## Get the resolve value or value for a given key without looking the first container (user container)
#
# This is the effective value for a given key, it is used for values in the global stack.
# This is exposed to SettingFunction to use in value functions.
# \param key The key of the setting to get the value of.
#
# \return The effective value
@staticmethod
def getDefaultResolveOrValue(key):
global_stack = Application.getInstance().getGlobalContainerStack()
context = PropertyEvaluationContext(global_stack)
context.context["evaluate_from_container_index"] = 1 # skip the user settings container
context.context["override_operators"] = {
"extruderValue": ExtruderManager.getDefaultExtruderValue,
"extruderValues": ExtruderManager.getDefaultExtruderValues,
"resolveOrValue": ExtruderManager.getDefaultResolveOrValue
}
resolved_value = global_stack.getProperty(key, "value", context = context)
return resolved_value

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from typing import Any, TYPE_CHECKING, Optional

View File

@ -1,15 +1,17 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import Qt, pyqtSignal, pyqtProperty, QTimer
from typing import Iterable
from UM.i18n import i18nCatalog
import UM.Qt.ListModel
from UM.Application import Application
import UM.FlameProfiler
from cura.Settings.ExtruderManager import ExtruderManager
from cura.Settings.ExtruderStack import ExtruderStack #To listen to changes on the extruders.
from cura.Settings.MachineManager import MachineManager #To listen to changes on the extruders of the currently active machine.
catalog = i18nCatalog("cura")
## Model that holds extruders.
#
@ -172,7 +174,7 @@ class ExtrudersModel(UM.Qt.ListModel.ListModel):
color = material.getMetaDataEntry("color_code", default = self.defaultColors[0]) if material else self.defaultColors[0]
item = {
"id": global_container_stack.getId(),
"name": "Global",
"name": catalog.i18nc("@menuitem", "Global"),
"color": color,
"index": -1,
"definition": ""
@ -215,7 +217,7 @@ class ExtrudersModel(UM.Qt.ListModel.ListModel):
if self._add_optional_extruder:
item = {
"id": "",
"name": "Not overridden",
"name": catalog.i18nc("@menuitem", "Not overridden"),
"color": "#ffffff",
"index": -1,
"definition": ""

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from typing import Any, Dict, Optional
@ -96,18 +96,18 @@ class GlobalStack(CuraContainerStack):
if not self.definition.findDefinitions(key = key):
return None
if context is None:
context = PropertyEvaluationContext()
context.pushContainer(self)
# Handle the "resolve" property.
if self._shouldResolve(key, property_name):
if self._shouldResolve(key, property_name, context):
self._resolving_settings.add(key)
resolve = super().getProperty(key, "resolve", context)
self._resolving_settings.remove(key)
if resolve is not None:
return resolve
if context is None:
context = PropertyEvaluationContext()
context.pushContainer(self)
# Handle the "limit_to_extruder" property.
limit_to_extruder = super().getProperty(key, "limit_to_extruder", context)
if limit_to_extruder is not None:
@ -151,7 +151,7 @@ class GlobalStack(CuraContainerStack):
# Determine whether or not we should try to get the "resolve" property instead of the
# requested property.
def _shouldResolve(self, key: str, property_name: str) -> bool:
def _shouldResolve(self, key: str, property_name: str, context: Optional[PropertyEvaluationContext] = None) -> bool:
if property_name is not "value":
# Do not try to resolve anything but the "value" property
return False
@ -163,7 +163,7 @@ class GlobalStack(CuraContainerStack):
# track all settings that are being resolved.
return False
setting_state = super().getProperty(key, "state")
setting_state = super().getProperty(key, "state", context = context)
if setting_state is not None and setting_state != InstanceState.Default:
# When the user has explicitly set a value, we should ignore any resolve and
# just return that value.

View File

@ -1,6 +1,9 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from typing import Union
# Cura is released under the terms of the LGPLv3 or higher.
#Type hinting.
from typing import Union, List, Dict
from UM.Signal import Signal
from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal, QTimer
from UM.FlameProfiler import pyqtSlot
@ -36,8 +39,6 @@ if TYPE_CHECKING:
from cura.Settings.CuraContainerStack import CuraContainerStack
from cura.Settings.GlobalStack import GlobalStack
import os
class MachineManager(QObject):
def __init__(self, parent = None):
@ -105,7 +106,8 @@ class MachineManager(QObject):
self._auto_hotends_changed = {}
self._material_incompatible_message = Message(catalog.i18nc("@info:status",
"The selected material is incompatible with the selected machine or configuration."))
"The selected material is incompatible with the selected machine or configuration."),
title = catalog.i18nc("@info:title", "Incompatible Material"))
globalContainerChanged = pyqtSignal() # Emitted whenever the global stack is changed (ie: when changing between printers, changing a global profile, but not when changing a value)
activeMaterialChanged = pyqtSignal()
@ -267,7 +269,6 @@ class MachineManager(QObject):
extruder_stack.containersChanged.disconnect(self._onInstanceContainersChanged)
self._global_container_stack = Application.getInstance().getGlobalContainerStack()
self._active_container_stack = self._global_container_stack
self.globalContainerChanged.emit()
@ -299,6 +300,10 @@ class MachineManager(QObject):
quality = self._global_container_stack.quality
quality.nameChanged.connect(self._onQualityNameChanged)
self._active_container_stack = self._global_container_stack
self.activeStackChanged.emit()
self._error_check_timer.start()
## Update self._stacks_valid according to _checkStacksForErrors and emit if change.
@ -348,11 +353,14 @@ class MachineManager(QObject):
if containers:
Application.getInstance().setGlobalContainerStack(containers[0])
self.__onInstanceContainersChanged()
@pyqtSlot(str, str)
def addMachine(self, name: str, definition_id: str) -> None:
new_stack = CuraStackBuilder.createMachine(name, definition_id)
if new_stack:
Application.getInstance().setGlobalContainerStack(new_stack)
# Instead of setting the global container stack here, we set the active machine and so the signals are emitted
self.setActiveMachine(new_stack.getId())
else:
Logger.log("w", "Failed creating a new machine!")
@ -365,7 +373,7 @@ class MachineManager(QObject):
def _createUniqueName(self, container_type: str, current_name: str, new_name: str, fallback_name: str) -> str:
return ContainerRegistry.getInstance().createUniqueName(container_type, current_name, new_name, fallback_name)
def _checkStacksHaveErrors(self):
def _checkStacksHaveErrors(self) -> bool:
if self._global_container_stack is None: #No active machine.
return False
@ -389,7 +397,7 @@ class MachineManager(QObject):
## Check if the global_container has instances in the user container
@pyqtProperty(bool, notify = activeStackValueChanged)
def hasUserSettings(self):
def hasUserSettings(self) -> bool:
if not self._global_container_stack:
return False
@ -404,7 +412,7 @@ class MachineManager(QObject):
return False
@pyqtProperty(int, notify = activeStackValueChanged)
def numUserSettings(self):
def numUserSettings(self) -> int:
if not self._global_container_stack:
return 0
num_user_settings = 0
@ -449,7 +457,7 @@ class MachineManager(QObject):
# Note that the _stacks_have_errors is cached due to performance issues
# Calling _checkStack(s)ForErrors on every change is simply too expensive
@pyqtProperty(bool, notify = stacksValidationChanged)
def stacksHaveErrors(self):
def stacksHaveErrors(self) -> bool:
return bool(self._stacks_have_errors)
@pyqtProperty(str, notify = activeStackChanged)
@ -474,7 +482,7 @@ class MachineManager(QObject):
return ""
@pyqtProperty(QObject, notify = globalContainerChanged)
def activeMachine(self) -> "GlobalStack":
def activeMachine(self) -> Optional["GlobalStack"]:
return self._global_container_stack
@pyqtProperty(str, notify = activeStackChanged)
@ -494,10 +502,11 @@ class MachineManager(QObject):
return ""
@pyqtProperty("QVariantList", notify=activeVariantChanged)
def activeVariantNames(self):
def activeVariantNames(self) -> List[str]:
result = []
if ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks() is not None:
for stack in ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
active_stacks = ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks()
if active_stacks is not None:
for stack in active_stacks:
variant_container = stack.variant
if variant_container and variant_container != self._empty_variant_container:
result.append(variant_container.getName())
@ -505,10 +514,11 @@ class MachineManager(QObject):
return result
@pyqtProperty("QVariantList", notify = activeMaterialChanged)
def activeMaterialNames(self):
def activeMaterialNames(self) -> List[str]:
result = []
if ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks() is not None:
for stack in ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
active_stacks = ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks()
if active_stacks is not None:
for stack in active_stacks:
material_container = stack.material
if material_container and material_container != self._empty_material_container:
result.append(material_container.getName())
@ -524,34 +534,36 @@ class MachineManager(QObject):
return ""
@pyqtProperty("QVariantMap", notify = activeVariantChanged)
def allActiveVariantIds(self):
if not self._global_container_stack:
return {}
def allActiveVariantIds(self) -> Dict[str, str]:
result = {}
active_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
if active_stacks is not None: #If we have a global stack.
for stack in active_stacks:
variant_container = stack.variant
if not variant_container:
continue
for stack in ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
variant_container = stack.variant
if not variant_container:
continue
result[stack.getId()] = variant_container.getId()
result[stack.getId()] = variant_container.getId()
return result
## Gets a dict with the active materials ids set in all extruder stacks and the global stack
# (when there is one extruder, the material is set in the global stack)
#
# \return The material ids in all stacks
@pyqtProperty("QVariantMap", notify = activeMaterialChanged)
def allActiveMaterialIds(self):
if not self._global_container_stack:
return {}
def allActiveMaterialIds(self) -> Dict[str, str]:
result = {}
active_stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
for stack in ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
material_container = stack.material
if not material_container:
continue
result[self._global_container_stack.getId()] = self._global_container_stack.material.getId()
result[stack.getId()] = material_container.getId()
if active_stacks is not None: # If we have extruder stacks
for stack in active_stacks:
material_container = stack.material
if not material_container:
continue
result[stack.getId()] = material_container.getId()
return result
@ -861,7 +873,7 @@ class MachineManager(QObject):
# \param quality_name \type{str} the name of the quality.
# \return \type{List[Dict]} with keys "stack", "quality" and "quality_changes".
@UM.FlameProfiler.profile
def determineQualityAndQualityChangesForQualityType(self, quality_type: str):
def determineQualityAndQualityChangesForQualityType(self, quality_type: str) -> List[Dict[str, Union["CuraContainerStack", InstanceContainer]]]:
quality_manager = QualityManager.getInstance()
result = []
empty_quality_changes = self._empty_quality_changes_container
@ -898,7 +910,7 @@ class MachineManager(QObject):
#
# \param quality_changes_name \type{str} the name of the quality changes.
# \return \type{List[Dict]} with keys "stack", "quality" and "quality_changes".
def _determineQualityAndQualityChangesForQualityChanges(self, quality_changes_name: str):
def _determineQualityAndQualityChangesForQualityChanges(self, quality_changes_name: str) -> Optional[List[Dict[str, Union["CuraContainerStack", InstanceContainer]]]]:
result = []
quality_manager = QualityManager.getInstance()
@ -964,7 +976,7 @@ class MachineManager(QObject):
if container_type == "quality":
stack.quality.nameChanged.disconnect(self._onQualityNameChanged)
stack.setQuality(container, postpone_emit = postpone_emit)
stack.qualityChanges.nameChanged.connect(self._onQualityNameChanged)
stack.quality.nameChanged.connect(self._onQualityNameChanged)
elif container_type == "quality_changes" or container_type is None:
# If the container is an empty container, we need to change the quality_changes.
# Quality can never be set to empty.
@ -1082,7 +1094,7 @@ class MachineManager(QObject):
machine_stacks = ContainerRegistry.getInstance().findContainerStacks(type = "machine")
other_machine_stacks = [s for s in machine_stacks if s.getId() != machine_id]
if other_machine_stacks:
Application.getInstance().setGlobalContainerStack(other_machine_stacks[0])
self.setActiveMachine(other_machine_stacks[0].getId())
ExtruderManager.getInstance().removeMachineExtruders(machine_id)
containers = ContainerRegistry.getInstance().findInstanceContainers(type = "user", machine = machine_id)
@ -1135,7 +1147,7 @@ class MachineManager(QObject):
return MachineManager()
@deprecated("Use ExtruderStack.material = ... and it won't be necessary", "2.7")
def _updateMaterialContainer(self, definition: "DefinitionContainer", stack: "ContainerStack", variant_container: Optional["InstanceContainer"] = None, preferred_material_name: Optional[str] = None):
def _updateMaterialContainer(self, definition: "DefinitionContainer", stack: "ContainerStack", variant_container: Optional["InstanceContainer"] = None, preferred_material_name: Optional[str] = None) -> InstanceContainer:
if not definition.getMetaDataEntry("has_materials"):
return self._empty_material_container
@ -1181,7 +1193,7 @@ class MachineManager(QObject):
def _onQualityNameChanged(self):
self.activeQualityChanged.emit()
def _getContainerChangedSignals(self):
def _getContainerChangedSignals(self) -> List[Signal]:
stacks = ExtruderManager.getInstance().getActiveExtruderStacks()
stacks.append(self._global_container_stack)
return [ s.containersChanged for s in stacks ]

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import pyqtSlot, pyqtProperty, QObject, pyqtSignal, QRegExp
from PyQt5.QtGui import QValidator

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import QObject, pyqtSlot #To expose data to QML.
@ -21,7 +21,7 @@ class MaterialManager(QObject):
#Material diameter changed warning message.
self._material_diameter_warning_message = Message(catalog.i18nc("@info:status Has a cancel button next to it.",
"The selected material diameter causes the material to become incompatible with the current printer."))
"The selected material diameter causes the material to become incompatible with the current printer."), title = catalog.i18nc("@info:title", "Incompatible Material"))
self._material_diameter_warning_message.addAction("Undo", catalog.i18nc("@action:button", "Undo"), None, catalog.i18nc("@action", "Undo changing the material diameter."))
self._material_diameter_warning_message.actionTriggered.connect(self._materialWarningMessageAction)

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
import UM.Settings.Models.SettingVisibilityHandler
@ -11,6 +11,7 @@ class MaterialSettingsVisibilityHandler(UM.Settings.Models.SettingVisibilityHand
"default_material_print_temperature",
"material_bed_temperature",
"material_standby_temperature",
#"material_flow_temp_graph",
"cool_fan_speed",
"retraction_amount",
"retraction_speed",

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Settings.ContainerRegistry import ContainerRegistry #To listen for changes to the materials.
from UM.Settings.Models.InstanceContainersModel import InstanceContainersModel #We're extending this class.

View File

@ -1,5 +1,7 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from collections import OrderedDict
from PyQt5.QtCore import Qt
@ -10,14 +12,19 @@ from UM.Settings.Models.InstanceContainersModel import InstanceContainersModel
from cura.QualityManager import QualityManager
from cura.Settings.ExtruderManager import ExtruderManager
## QML Model for listing the current list of valid quality profiles.
#
class ProfilesModel(InstanceContainersModel):
LayerHeightRole = Qt.UserRole + 1001
LayerHeightWithoutUnitRole = Qt.UserRole + 1002
AvailableRole = Qt.UserRole + 1003
def __init__(self, parent = None):
super().__init__(parent)
self.addRoleName(self.LayerHeightRole, "layer_height")
self.addRoleName(self.LayerHeightWithoutUnitRole, "layer_height_without_unit")
self.addRoleName(self.AvailableRole, "available")
Application.getInstance().globalContainerStackChanged.connect(self._update)
@ -47,19 +54,36 @@ class ProfilesModel(InstanceContainersModel):
global_container_stack = Application.getInstance().getGlobalContainerStack()
if global_container_stack is None:
return []
global_stack_definition = global_container_stack.getBottom()
# Get the list of extruders and place the selected extruder at the front of the list.
# Get the list of extruders and place the selected extruder at the front of the list.
extruder_manager = ExtruderManager.getInstance()
active_extruder = extruder_manager.getActiveExtruderStack()
extruder_stacks = extruder_manager.getActiveExtruderStacks()
materials = [global_container_stack.material]
if active_extruder in extruder_stacks:
extruder_stacks.remove(active_extruder)
extruder_stacks = [active_extruder] + extruder_stacks
materials = [extruder.material for extruder in extruder_stacks]
# Fetch the list of useable qualities across all extruders.
# Fetch the list of usable qualities across all extruders.
# The actual list of quality profiles come from the first extruder in the extruder list.
return QualityManager.getInstance().findAllUsableQualitiesForMachineAndExtruders(global_container_stack,
extruder_stacks)
result = QualityManager.getInstance().findAllUsableQualitiesForMachineAndExtruders(global_container_stack, extruder_stacks)
# The usable quality types are set
quality_type_set = set([x.getMetaDataEntry("quality_type") for x in result])
# Fetch all qualities available for this machine and the materials selected in extruders
all_qualities = QualityManager.getInstance().findAllQualitiesForMachineAndMaterials(global_stack_definition, materials)
# If in the all qualities there is some of them that are not available due to incompatibility with materials
# we also add it so that they will appear in the slide quality bar. However in recomputeItems will be marked as
# not available so they will be shown in gray
for quality in all_qualities:
if quality.getMetaDataEntry("quality_type") not in quality_type_set:
result.append(quality)
return result
## Re-computes the items in this model, and adds the layer height role.
def _recomputeItems(self):
@ -67,6 +91,29 @@ class ProfilesModel(InstanceContainersModel):
global_container_stack = Application.getInstance().getGlobalContainerStack()
if global_container_stack is None:
return
# Detecting if the machine has multiple extrusion
multiple_extrusion = global_container_stack.getProperty("machine_extruder_count", "value") > 1
# Get the list of extruders and place the selected extruder at the front of the list.
extruder_manager = ExtruderManager.getInstance()
active_extruder = extruder_manager.getActiveExtruderStack()
extruder_stacks = extruder_manager.getActiveExtruderStacks()
if multiple_extrusion:
# Place the active extruder at the front of the list.
# This is a workaround checking if there is an active_extruder or not before moving it to the front of the list.
# Actually, when a printer has multiple extruders, should exist always an active_extruder. However, in some
# cases the active_extruder is still None.
if active_extruder in extruder_stacks:
extruder_stacks.remove(active_extruder)
new_extruder_stacks = []
if active_extruder is not None:
new_extruder_stacks = [active_extruder]
extruder_stacks = new_extruder_stacks + extruder_stacks
# Get a list of usable/available qualities for this machine and material
qualities = QualityManager.getInstance().findAllUsableQualitiesForMachineAndExtruders(global_container_stack,
extruder_stacks)
container_registry = ContainerRegistry.getInstance()
machine_manager = Application.getInstance().getMachineManager()
@ -74,21 +121,57 @@ class ProfilesModel(InstanceContainersModel):
if not unit:
unit = ""
# group all quality items according to quality_types, so we know which profile suits the currently
# active machine and material, and later yield the right ones.
tmp_all_quality_items = OrderedDict()
for item in super()._recomputeItems():
profile = container_registry.findContainers(id = item["id"])
profile = container_registry.findContainers(id=item["id"])
quality_type = profile[0].getMetaDataEntry("quality_type") if profile else ""
if quality_type not in tmp_all_quality_items:
tmp_all_quality_items[quality_type] = {"suitable_container": None, "all_containers": []}
tmp_all_quality_items[quality_type]["all_containers"].append(item)
if tmp_all_quality_items[quality_type]["suitable_container"] is None:
tmp_all_quality_items[quality_type]["suitable_container"] = item
# reverse the ordering (finest first, coarsest last)
all_quality_items = OrderedDict()
for key in reversed(tmp_all_quality_items.keys()):
all_quality_items[key] = tmp_all_quality_items[key]
# First the suitable containers are set in the model
containers = []
for data_item in all_quality_items.values():
suitable_item = data_item["suitable_container"]
if suitable_item is not None:
containers.append(suitable_item)
# Once the suitable containers are collected, the rest of the containers are appended
for data_item in all_quality_items.values():
for item in data_item["all_containers"]:
if item not in containers:
containers.append(item)
# Now all the containers are set
for item in containers:
profile = container_registry.findContainers(id=item["id"])
if not profile:
item["layer_height"] = "" #Can't update a profile that is unknown.
self._setItemLayerHeight(item, "", unit)
item["available"] = False
yield item
continue
#Easy case: This profile defines its own layer height.
profile = profile[0]
item["available"] = profile in qualities
# Easy case: This profile defines its own layer height.
if profile.hasProperty("layer_height", "value"):
item["layer_height"] = str(profile.getProperty("layer_height", "value")) + unit
self._setItemLayerHeight(item, profile.getProperty("layer_height", "value"), unit)
yield item
continue
#Quality-changes profile that has no value for layer height. Get the corresponding quality profile and ask that profile.
# Quality-changes profile that has no value for layer height. Get the corresponding quality profile and ask that profile.
quality_type = profile.getMetaDataEntry("quality_type", None)
if quality_type:
quality_results = machine_manager.determineQualityAndQualityChangesForQualityType(quality_type)
@ -102,7 +185,7 @@ class ProfilesModel(InstanceContainersModel):
else:
quality = None
if quality and quality.hasProperty("layer_height", "value"):
item["layer_height"] = str(quality.getProperty("layer_height", "value")) + unit
self._setItemLayerHeight(item, quality.getProperty("layer_height", "value"), unit)
yield item
continue
@ -112,5 +195,9 @@ class ProfilesModel(InstanceContainersModel):
skip_until_container = global_container_stack.variant
if not skip_until_container or skip_until_container == ContainerRegistry.getInstance().getEmptyInstanceContainer(): #No variant in stack.
skip_until_container = global_container_stack.getBottom()
item["layer_height"] = str(global_container_stack.getRawProperty("layer_height", "value", skip_until_container = skip_until_container.getId())) + unit #Fall through to the currently loaded material.
self._setItemLayerHeight(item, global_container_stack.getRawProperty("layer_height", "value", skip_until_container = skip_until_container.getId()), unit) # Fall through to the currently loaded material.
yield item
def _setItemLayerHeight(self, item, value, unit):
item["layer_height"] = str(value) + unit
item["layer_height_without_unit"] = str(value)

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Application import Application
from cura.QualityManager import QualityManager
@ -25,21 +25,44 @@ class QualityAndUserProfilesModel(ProfilesModel):
machine_definition = quality_manager.getParentMachineDefinition(global_container_stack.getBottom())
quality_changes_list = quality_manager.findAllQualityChangesForMachine(machine_definition)
# Get the list of extruders and place the selected extruder at the front of the list.
# Detecting if the machine has multiple extrusion
multiple_extrusion = global_container_stack.getProperty("machine_extruder_count", "value") > 1
# Get the list of extruders
extruder_manager = ExtruderManager.getInstance()
active_extruder = extruder_manager.getActiveExtruderStack()
extruder_stacks = extruder_manager.getActiveExtruderStacks()
if active_extruder in extruder_stacks:
extruder_stacks.remove(active_extruder)
extruder_stacks = [active_extruder] + extruder_stacks
if multiple_extrusion:
# Place the active extruder at the front of the list.
# This is a workaround checking if there is an active_extruder or not before moving it to the front of the list.
# Actually, when a printer has multiple extruders, should exist always an active_extruder. However, in some
# cases the active_extruder is still None.
if active_extruder in extruder_stacks:
extruder_stacks.remove(active_extruder)
new_extruder_stacks = []
if active_extruder is not None:
new_extruder_stacks = [active_extruder]
else:
# if there is no active extruder, use the first one in the active extruder stacks
active_extruder = extruder_stacks[0]
extruder_stacks = new_extruder_stacks + extruder_stacks
# Fetch the list of useable qualities across all extruders.
# The actual list of quality profiles come from the first extruder in the extruder list.
quality_list = QualityManager.getInstance().findAllUsableQualitiesForMachineAndExtruders(global_container_stack,
quality_list = quality_manager.findAllUsableQualitiesForMachineAndExtruders(global_container_stack,
extruder_stacks)
# Filter the quality_change by the list of available quality_types
quality_type_set = set([x.getMetaDataEntry("quality_type") for x in quality_list])
filtered_quality_changes = [qc for qc in quality_changes_list if qc.getMetaDataEntry("quality_type") in quality_type_set and qc.getMetaDataEntry("extruder") is None]
if multiple_extrusion:
# If the printer has multiple extruders then quality changes related to the current extruder are kept
filtered_quality_changes = [qc for qc in quality_changes_list if qc.getMetaDataEntry("quality_type") in quality_type_set and
qc.getMetaDataEntry("extruder") is not None and
(qc.getMetaDataEntry("extruder") == active_extruder.definition.getMetaDataEntry("quality_definition") or
qc.getMetaDataEntry("extruder") == active_extruder.definition.getId())]
else:
# If not, the quality changes of the global stack are selected
filtered_quality_changes = [qc for qc in quality_changes_list if qc.getMetaDataEntry("quality_type") in quality_type_set and
qc.getMetaDataEntry("extruder") is None]
return quality_list + filtered_quality_changes

View File

@ -1,11 +1,11 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
import collections
from PyQt5.QtCore import pyqtProperty, pyqtSignal, Qt
import UM.Logger
from UM.Logger import Logger
import UM.Qt
from UM.Application import Application
from UM.Settings.ContainerRegistry import ContainerRegistry
@ -97,7 +97,7 @@ class QualitySettingsModel(UM.Qt.ListModel.ListModel):
containers = self._container_registry.findInstanceContainers(id = self._quality_id)
if not containers:
UM.Logger.log("w", "Could not find a quality container with id %s", self._quality_id)
Logger.log("w", "Could not find a quality container with id %s", self._quality_id)
return
quality_container = None
@ -116,7 +116,7 @@ class QualitySettingsModel(UM.Qt.ListModel.ListModel):
quality_container = self._container_registry.findInstanceContainers(**criteria)
if not quality_container:
UM.Logger.log("w", "Could not find a quality container matching quality changes %s", quality_changes_container.getId())
Logger.log("w", "Could not find a quality container matching quality changes %s", quality_changes_container.getId())
return
quality_container = quality_container[0]
@ -160,7 +160,7 @@ class QualitySettingsModel(UM.Qt.ListModel.ListModel):
containers = self._container_registry.findInstanceContainers(**criteria)
if not containers:
UM.Logger.log("w", "Could not find any quality containers matching the search criteria %s" % str(criteria))
Logger.log("w", "Could not find any quality containers matching the search criteria %s" % str(criteria))
return
if quality_changes_container:

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Scene.SceneNode import SceneNode
from UM.Operations.Operation import Operation

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import QObject, pyqtProperty, pyqtSignal
from UM.FlameProfiler import pyqtSlot

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
import copy

View File

@ -0,0 +1,92 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty
from UM.Application import Application
class SimpleModeSettingsManager(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._machine_manager = Application.getInstance().getMachineManager()
self._is_profile_customized = False # True when default profile has user changes
self._is_profile_user_created = False # True when profile was custom created by user
self._machine_manager.activeStackValueChanged.connect(self._updateIsProfileCustomized)
self._machine_manager.activeQualityChanged.connect(self._updateIsProfileUserCreated)
# update on create as the activeQualityChanged signal is emitted before this manager is created when Cura starts
self._updateIsProfileCustomized()
self._updateIsProfileUserCreated()
isProfileCustomizedChanged = pyqtSignal()
isProfileUserCreatedChanged = pyqtSignal()
@pyqtProperty(bool, notify = isProfileCustomizedChanged)
def isProfileCustomized(self):
return self._is_profile_customized
def _updateIsProfileCustomized(self):
user_setting_keys = set()
if not self._machine_manager.activeMachine:
return False
global_stack = self._machine_manager.activeMachine
# check user settings in the global stack
user_setting_keys.update(set(global_stack.userChanges.getAllKeys()))
# check user settings in the extruder stacks
if global_stack.extruders:
for extruder_stack in global_stack.extruders.values():
user_setting_keys.update(set(extruder_stack.userChanges.getAllKeys()))
# remove settings that are visible in recommended (we don't show the reset button for those)
for skip_key in self.__ignored_custom_setting_keys:
if skip_key in user_setting_keys:
user_setting_keys.remove(skip_key)
has_customized_user_settings = len(user_setting_keys) > 0
if has_customized_user_settings != self._is_profile_customized:
self._is_profile_customized = has_customized_user_settings
self.isProfileCustomizedChanged.emit()
@pyqtProperty(bool, notify = isProfileUserCreatedChanged)
def isProfileUserCreated(self):
return self._is_profile_user_created
def _updateIsProfileUserCreated(self):
quality_changes_keys = set()
if not self._machine_manager.activeMachine:
return False
global_stack = self._machine_manager.activeMachine
# check quality changes settings in the global stack
quality_changes_keys.update(set(global_stack.qualityChanges.getAllKeys()))
# check quality changes settings in the extruder stacks
if global_stack.extruders:
for extruder_stack in global_stack.extruders.values():
quality_changes_keys.update(set(extruder_stack.qualityChanges.getAllKeys()))
# check if the qualityChanges container is not empty (meaning it is a user created profile)
has_quality_changes = len(quality_changes_keys) > 0
if has_quality_changes != self._is_profile_user_created:
self._is_profile_user_created = has_quality_changes
self.isProfileUserCreatedChanged.emit()
# These are the settings included in the Simple ("Recommended") Mode, so only when the other settings have been
# changed, we consider it as a user customized profile in the Simple ("Recommended") Mode.
__ignored_custom_setting_keys = ["support_enable",
"infill_sparse_density",
"gradual_infill_steps",
"adhesion_type",
"support_extruder_nr"]

View File

@ -6,6 +6,7 @@ from cura.Settings.ExtruderManager import ExtruderManager
from UM.Settings.ContainerRegistry import ContainerRegistry
from UM.i18n import i18nCatalog
from UM.Settings.SettingFunction import SettingFunction
from UM.Settings.PropertyEvaluationContext import PropertyEvaluationContext
from collections import OrderedDict
import os
@ -66,8 +67,15 @@ class UserChangesModel(ListModel):
containers.extend(latest_stack.getContainers())
latest_stack = latest_stack.getNextStack()
# Drop the user container.
# Override "getExtruderValue" with "getDefaultExtruderValue" so we can get the default values
user_changes = containers.pop(0)
default_value_resolve_context = PropertyEvaluationContext(stack)
default_value_resolve_context.context["evaluate_from_container_index"] = 1 # skip the user settings container
default_value_resolve_context.context["override_operators"] = {
"extruderValue": ExtruderManager.getDefaultExtruderValue,
"extruderValues": ExtruderManager.getDefaultExtruderValues,
"resolveOrValue": ExtruderManager.getDefaultResolveOrValue
}
for setting_key in user_changes.getAllKeys():
original_value = None
@ -90,16 +98,16 @@ class UserChangesModel(ListModel):
for container in containers:
if stack == global_stack:
resolve = global_stack.getProperty(setting_key, "resolve")
resolve = global_stack.getProperty(setting_key, "resolve", default_value_resolve_context)
if resolve is not None:
original_value = resolve
break
original_value = container.getProperty(setting_key, "value")
original_value = container.getProperty(setting_key, "value", default_value_resolve_context)
# If a value is a function, ensure it's called with the stack it's in.
if isinstance(original_value, SettingFunction):
original_value = original_value(stack)
original_value = original_value(stack, default_value_resolve_context)
if original_value is not None:
break

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Application import Application
from cura.QualityManager import QualityManager
@ -25,17 +25,44 @@ class UserProfilesModel(ProfilesModel):
machine_definition = quality_manager.getParentMachineDefinition(global_container_stack.getBottom())
quality_changes_list = quality_manager.findAllQualityChangesForMachine(machine_definition)
# Fetch the list of qualities
quality_list = QualityManager.getInstance().findAllUsableQualitiesForMachineAndExtruders(global_container_stack,
ExtruderManager.getInstance().getActiveExtruderStacks())
# Detecting if the machine has multiple extrusion
multiple_extrusion = global_container_stack.getProperty("machine_extruder_count", "value") > 1
# Get the list of extruders and place the selected extruder at the front of the list.
extruder_manager = ExtruderManager.getInstance()
active_extruder = extruder_manager.getActiveExtruderStack()
extruder_stacks = extruder_manager.getActiveExtruderStacks()
if multiple_extrusion:
# Place the active extruder at the front of the list.
# This is a workaround checking if there is an active_extruder or not before moving it to the front of the list.
# Actually, when a printer has multiple extruders, should exist always an active_extruder. However, in some
# cases the active_extruder is still None.
if active_extruder in extruder_stacks:
extruder_stacks.remove(active_extruder)
new_extruder_stacks = []
if active_extruder is not None:
new_extruder_stacks = [active_extruder]
else:
# if there is no active extruder, use the first one in the active extruder stacks
active_extruder = extruder_stacks[0]
extruder_stacks = new_extruder_stacks + extruder_stacks
# Fetch the list of useable qualities across all extruders.
# The actual list of quality profiles come from the first extruder in the extruder list.
quality_list = quality_manager.findAllUsableQualitiesForMachineAndExtruders(global_container_stack,
extruder_stacks)
# Filter the quality_change by the list of available quality_types
quality_type_set = set([x.getMetaDataEntry("quality_type") for x in quality_list])
filtered_quality_changes = [qc for qc in quality_changes_list if qc.getMetaDataEntry("quality_type") in quality_type_set]
#Only display the global quality changes.
#Otherwise you get multiple copies of every quality changes profile.
#The actual profile switching goes by profile name (not ID), and as long as the names are consistent, switching to any of the profiles will cause all stacks to switch.
filtered_quality_changes = list(filter(lambda quality_changes: quality_changes.getMetaDataEntry("extruder") is None, filtered_quality_changes))
if multiple_extrusion:
# If the printer has multiple extruders then quality changes related to the current extruder are kept
filtered_quality_changes = [qc for qc in quality_changes_list if qc.getMetaDataEntry("quality_type") in quality_type_set and
qc.getMetaDataEntry("extruder") is not None and
(qc.getMetaDataEntry("extruder") == active_extruder.definition.getMetaDataEntry("quality_definition") or
qc.getMetaDataEntry("extruder") == active_extruder.definition.getId())]
else:
# If not, the quality changes of the global stack are selected
filtered_quality_changes = [qc for qc in quality_changes_list if qc.getMetaDataEntry("quality_type") in quality_type_set and
qc.getMetaDataEntry("extruder") is None]
return filtered_quality_changes

View File

@ -1,2 +1,2 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.

View File

@ -46,6 +46,10 @@ class ShapeArray:
# For one_at_a_time printing you need the convex hull head.
hull_head_verts = node.callDecoration("getConvexHullHead") or hull_verts
# If a model is to small then it will not contain any points
if not hull_verts.getPoints().any():
return None, None
offset_verts = hull_head_verts.getMinkowskiHull(Polygon.approximatedCircle(min_offset))
offset_points = copy.deepcopy(offset_verts._points) # x, y
offset_points[:, 0] = numpy.add(offset_points[:, 0], -transform_x)

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python3
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
import os
import sys
import platform
@ -41,8 +41,9 @@ if "PYTHONPATH" in os.environ.keys(): # If PYTHONPATH is u
sys.path.insert(1, PATH_real) # Insert it at 1 after os.curdir, which is 0.
def exceptHook(hook_type, value, traceback):
import cura.CrashHandler
cura.CrashHandler.show(hook_type, value, traceback)
from cura.CrashHandler import CrashHandler
_crash_handler = CrashHandler(hook_type, value, traceback)
_crash_handler.show()
sys.excepthook = exceptHook

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
import os.path
import zipfile
@ -17,6 +17,7 @@ from cura.Settings.ExtruderManager import ExtruderManager
from cura.QualityManager import QualityManager
from UM.Scene.SceneNode import SceneNode
from cura.SliceableObjectDecorator import SliceableObjectDecorator
from cura.ZOffsetDecorator import ZOffsetDecorator
MYPY = False
@ -73,9 +74,8 @@ class ThreeMFReader(MeshReader):
return temp_mat
## Convenience function that converts a SceneNode object (as obtained from libSavitar) to a Uranium scenenode.
# \returns Uranium Scenen node.
## Convenience function that converts a SceneNode object (as obtained from libSavitar) to a Uranium scene node.
# \returns Uranium scene node.
def _convertSavitarNodeToUMNode(self, savitar_node):
um_node = SceneNode()
transformation = self._createMatrixFromTransformationString(savitar_node.getTransformation())
@ -196,7 +196,7 @@ class ThreeMFReader(MeshReader):
translation_matrix.setByTranslation(translation_vector)
transformation_matrix.multiply(translation_matrix)
# Third step: 3MF also defines a unit, wheras Cura always assumes mm.
# Third step: 3MF also defines a unit, whereas Cura always assumes mm.
scale_matrix = Matrix()
scale_matrix.setByScaleVector(self._getScaleFromUnit(self._unit))
transformation_matrix.multiply(scale_matrix)
@ -204,6 +204,13 @@ class ThreeMFReader(MeshReader):
# Pre multiply the transformation with the loaded transformation, so the data is handled correctly.
um_node.setTransformation(um_node.getLocalTransformation().preMultiply(transformation_matrix))
# Check if the model is positioned below the build plate and honor that when loading project files.
if um_node.getMeshData() is not None:
minimum_z_value = um_node.getMeshData().getExtents(um_node.getWorldTransformation()).minimum.y # y is z in transformation coordinates
if minimum_z_value < 0:
um_node.addDecorator(ZOffsetDecorator())
um_node.callDecoration("setZOffset", minimum_z_value)
result.append(um_node)
except Exception:

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Workspace.WorkspaceReader import WorkspaceReader
from UM.Application import Application
@ -26,6 +26,7 @@ from configparser import ConfigParser
import zipfile
import io
import configparser
import os
i18n_catalog = i18nCatalog("cura")
@ -222,10 +223,12 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
elif container_type == "definition_changes":
definition_name = instance_container.getName()
num_settings_overriden_by_definition_changes += len(instance_container._instances)
# Check if definition changes already exists.
definition_changes = self._container_registry.findInstanceContainers(id = container_id)
containers_found_dict["definition_changes"] = True
# Check if there is any difference the loaded settings from the project file and the settings in Cura.
if definition_changes:
containers_found_dict["definition_changes"] = True
# Check if there really is a conflict by comparing the values
if definition_changes[0] != instance_container:
definition_changes_conflict = True
elif container_type == "quality":
@ -300,11 +303,14 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
break
num_visible_settings = 0
has_visible_settings_string = False
try:
temp_preferences = Preferences()
temp_preferences.readFromFile(io.TextIOWrapper(archive.open("Cura/preferences.cfg"))) # We need to wrap it, else the archive parser breaks.
serialized = archive.open("Cura/preferences.cfg").read().decode("utf-8")
temp_preferences.deserialize(serialized)
visible_settings_string = temp_preferences.getValue("general/visible_settings")
has_visible_settings_string = visible_settings_string is not None
if visible_settings_string is not None:
num_visible_settings = len(visible_settings_string.split(";"))
active_mode = temp_preferences.getValue("cura/active_mode")
@ -331,6 +337,7 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
self._dialog.setQualityChangesConflict(quality_changes_conflict)
self._dialog.setDefinitionChangesConflict(definition_changes_conflict)
self._dialog.setMaterialConflict(material_conflict)
self._dialog.setHasVisibleSettingsField(has_visible_settings_string)
self._dialog.setNumVisibleSettings(num_visible_settings)
self._dialog.setQualityName(quality_name)
self._dialog.setQualityType(quality_type)
@ -357,7 +364,7 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
# - new: create a new container
# - override: override the existing container
# - None: There is no conflict, which means containers with the same IDs may or may not be there already.
# If there is an existing container, there is no conflict between the them, and default to "override"
# If there is an existing container, there is no conflict between them, and default to "override"
# If there is no existing container, default to "new"
#
# Default values
@ -370,7 +377,7 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
## Overrides an ExtruderStack in the given GlobalStack and returns the new ExtruderStack.
def _overrideExtruderStack(self, global_stack, extruder_file_content):
# get extruder position first
# Get extruder position first
extruder_config = configparser.ConfigParser()
extruder_config.read_string(extruder_file_content)
if not extruder_config.has_option("metadata", "position"):
@ -378,10 +385,13 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
Logger.log("e", "Could not find 'metadata/position' in extruder stack file")
raise RuntimeError(msg)
extruder_position = extruder_config.get("metadata", "position")
try:
extruder_stack = global_stack.extruders[extruder_position]
except KeyError:
Logger.log("w", "Could not find the matching extruder stack to override for position %s", extruder_position)
return None
extruder_stack = global_stack.extruders[extruder_position]
# override the given extruder stack
# Override the given extruder stack
extruder_stack.deserialize(extruder_file_content)
# return the new ExtruderStack
@ -402,7 +412,8 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
# Create a shadow copy of the preferences (we don't want all of the preferences, but we do want to re-use its
# parsing code.
temp_preferences = Preferences()
temp_preferences.readFromFile(io.TextIOWrapper(archive.open("Cura/preferences.cfg"))) # We need to wrap it, else the archive parser breaks.
serialized = archive.open("Cura/preferences.cfg").read().decode("utf-8")
temp_preferences.deserialize(serialized)
# Copy a number of settings from the temp preferences to the global
global_preferences = Preferences.getInstance()
@ -597,7 +608,9 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
if self._resolve_strategies["machine"] == "new":
# The machine is going to get a spiffy new name, so ensure that the id's of user settings match.
old_extruder_id = instance_container.getMetaDataEntry("extruder", None)
if old_extruder_id:
# Note that in case of a quality_changes extruder means the definition id of the extruder stack
# For the user settings, it means the actual extruder stack id it's assigned to.
if old_extruder_id and old_extruder_id in extruder_stack_id_map:
new_extruder_id = extruder_stack_id_map[old_extruder_id]
instance_container.setMetaDataEntry("extruder", new_extruder_id)
@ -693,54 +706,56 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
# --
# load extruder stack files
if extruder_count_from_global_stack > 1:
try:
for extruder_stack_file in extruder_stack_files:
container_id = self._stripFileToId(extruder_stack_file)
extruder_file_content = archive.open(extruder_stack_file, "r").read().decode("utf-8")
try:
for extruder_stack_file in extruder_stack_files:
container_id = self._stripFileToId(extruder_stack_file)
extruder_file_content = archive.open(extruder_stack_file, "r").read().decode("utf-8")
if self._resolve_strategies["machine"] == "override":
# deserialize new extruder stack over the current ones
if self._resolve_strategies["machine"] == "override":
if global_stack.getProperty("machine_extruder_count", "value") > 1:
# deserialize new extruder stack over the current ones (if any)
stack = self._overrideExtruderStack(global_stack, extruder_file_content)
if stack is None:
continue
elif self._resolve_strategies["machine"] == "new":
new_id = extruder_stack_id_map[container_id]
stack = ExtruderStack(new_id)
elif self._resolve_strategies["machine"] == "new":
new_id = extruder_stack_id_map[container_id]
stack = ExtruderStack(new_id)
# HACK: the global stack can have a new name, so we need to make sure that this extruder stack
# references to the new name instead of the old one. Normally, this can be done after
# deserialize() by setting the metadata, but in the case of ExtruderStack, deserialize()
# also does addExtruder() to its machine stack, so we have to make sure that it's pointing
# to the right machine BEFORE deserialization.
extruder_config = configparser.ConfigParser()
extruder_config.read_string(extruder_file_content)
extruder_config.set("metadata", "machine", global_stack_id_new)
tmp_string_io = io.StringIO()
extruder_config.write(tmp_string_io)
extruder_file_content = tmp_string_io.getvalue()
# HACK: the global stack can have a new name, so we need to make sure that this extruder stack
# references to the new name instead of the old one. Normally, this can be done after
# deserialize() by setting the metadata, but in the case of ExtruderStack, deserialize()
# also does addExtruder() to its machine stack, so we have to make sure that it's pointing
# to the right machine BEFORE deserialization.
extruder_config = configparser.ConfigParser()
extruder_config.read_string(extruder_file_content)
extruder_config.set("metadata", "machine", global_stack_id_new)
tmp_string_io = io.StringIO()
extruder_config.write(tmp_string_io)
extruder_file_content = tmp_string_io.getvalue()
stack.deserialize(extruder_file_content)
stack.deserialize(extruder_file_content)
# Ensure a unique ID and name
stack._id = new_id
# Ensure a unique ID and name
stack._id = new_id
self._container_registry.addContainer(stack)
extruder_stacks_added.append(stack)
containers_added.append(stack)
else:
Logger.log("w", "Unknown resolve strategy: %s", self._resolve_strategies["machine"])
# Create a new definition_changes container if it was empty
if stack.definitionChanges == self._container_registry.getEmptyInstanceContainer():
stack.setDefinitionChanges(CuraStackBuilder.createDefinitionChangesContainer(stack, stack._id + "_settings"))
self._container_registry.addContainer(stack)
extruder_stacks_added.append(stack)
containers_added.append(stack)
else:
Logger.log("w", "Unknown resolve strategy: %s", self._resolve_strategies["machine"])
# Create a new definition_changes container if it was empty
if stack.definitionChanges == self._container_registry.getEmptyInstanceContainer():
stack.setDefinitionChanges(CuraStackBuilder.createDefinitionChangesContainer(stack, stack._id + "_settings"))
if global_stack.getProperty("machine_extruder_count", "value") > 1:
extruder_stacks.append(stack)
except:
Logger.logException("w", "We failed to serialize the stack. Trying to clean up.")
# Something went really wrong. Try to remove any data that we added.
for container in containers_added:
self._container_registry.removeContainer(container.getId())
return
except:
Logger.logException("w", "We failed to serialize the stack. Trying to clean up.")
# Something went really wrong. Try to remove any data that we added.
for container in containers_added:
self._container_registry.removeContainer(container.getId())
return
#
# Replacing the old containers if resolve is "new".
@ -748,6 +763,7 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
# MUST get updated too.
#
if self._resolve_strategies["machine"] == "new":
# A new machine was made, but it was serialized with the wrong user container. Fix that now.
for container in user_instance_containers:
# replacing the container ID for user instance containers for the extruders
@ -861,6 +877,11 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
nodes = self._3mf_mesh_reader.read(file_name)
if nodes is None:
nodes = []
base_file_name = os.path.basename(file_name)
if base_file_name.endswith(".curaproject.3mf"):
base_file_name = base_file_name[:base_file_name.rfind(".curaproject.3mf")]
Application.getInstance().projectFileLoaded.emit(base_file_name)
return nodes
## HACK: Replaces the material container in the given stack with a newly created material container.

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import QUrl, pyqtSignal, QObject, pyqtProperty, QCoreApplication
from UM.FlameProfiler import pyqtSlot
@ -26,7 +26,7 @@ class WorkspaceDialog(QObject):
self._view = None
self._qml_url = "WorkspaceDialog.qml"
self._lock = threading.Lock()
self._default_strategy = "override"
self._default_strategy = None
self._result = {"machine": self._default_strategy,
"quality_changes": self._default_strategy,
"definition_changes": self._default_strategy,
@ -38,6 +38,7 @@ class WorkspaceDialog(QObject):
self._has_definition_changes_conflict = False
self._has_machine_conflict = False
self._has_material_conflict = False
self._has_visible_settings_field = False
self._num_visible_settings = 0
self._num_user_settings = 0
self._active_mode = ""
@ -58,6 +59,7 @@ class WorkspaceDialog(QObject):
numVisibleSettingsChanged = pyqtSignal()
activeModeChanged = pyqtSignal()
qualityNameChanged = pyqtSignal()
hasVisibleSettingsFieldChanged = pyqtSignal()
numSettingsOverridenByQualityChangesChanged = pyqtSignal()
qualityTypeChanged = pyqtSignal()
machineNameChanged = pyqtSignal()
@ -167,6 +169,14 @@ class WorkspaceDialog(QObject):
self._active_mode = i18n_catalog.i18nc("@title:tab", "Custom")
self.activeModeChanged.emit()
@pyqtProperty(int, notify = hasVisibleSettingsFieldChanged)
def hasVisibleSettingsField(self):
return self._has_visible_settings_field
def setHasVisibleSettingsField(self, has_visible_settings_field):
self._has_visible_settings_field = has_visible_settings_field
self.hasVisibleSettingsFieldChanged.emit()
@pyqtProperty(int, constant = True)
def totalNumberOfSettings(self):
return len(ContainerRegistry.getInstance().findDefinitionContainers(id="fdmprinter")[0].getAllKeys())
@ -235,6 +245,14 @@ class WorkspaceDialog(QObject):
self._result["definition_changes"] = None
if "material" in self._result and not self._has_material_conflict:
self._result["material"] = None
# If the machine needs to be re-created, the definition_changes should also be re-created.
# If the machine strategy is None, it means that there is no name conflict with existing ones. In this case
# new definitions changes are created
if "machine" in self._result:
if self._result["machine"] == "new" or self._result["machine"] is None and self._result["definition_changes"] is None:
self._result["definition_changes"] = "new"
return self._result
def _createViewFromQML(self):
@ -262,14 +280,28 @@ class WorkspaceDialog(QObject):
@pyqtSlot()
## Used to notify the dialog so the lock can be released.
def notifyClosed(self):
self._result = {}
self._result = {} # The result should be cleared before hide, because after it is released the main thread lock
self._visible = False
self._lock.release()
try:
self._lock.release()
except:
pass
def hide(self):
self._visible = False
self._lock.release()
self._view.hide()
try:
self._lock.release()
except:
pass
@pyqtSlot(bool)
def _onVisibilityChanged(self, visible):
if not visible:
try:
self._lock.release()
except:
pass
@pyqtSlot()
def onOkButtonClicked(self):
@ -278,9 +310,9 @@ class WorkspaceDialog(QObject):
@pyqtSlot()
def onCancelButtonClicked(self):
self._result = {}
self._view.hide()
self.hide()
self._result = {}
## Block thread until the dialog is closed.
def waitForClose(self):

View File

@ -1,5 +1,5 @@
// Copyright (c) 2016 Ultimaker B.V.
// Cura is released under the terms of the AGPLv3 or higher.
// Cura is released under the terms of the LGPLv3 or higher.
import QtQuick 2.1
import QtQuick.Controls 1.1
@ -10,13 +10,16 @@ import UM 1.1 as UM
UM.Dialog
{
id: base
title: catalog.i18nc("@title:window", "Open Project")
width: 500
height: 400
minimumWidth: 500 * screenScaleFactor
minimumHeight: 450 * screenScaleFactor
width: minimumWidth
height: minimumHeight
property int comboboxHeight: 15
property int spacerHeight: 10
property int comboboxHeight: 15 * screenScaleFactor
property int spacerHeight: 10 * screenScaleFactor
onClosing: manager.notifyClosed()
onVisibleChanged:
@ -28,10 +31,11 @@ UM.Dialog
materialResolveComboBox.currentIndex = 0
}
}
Item
{
anchors.fill: parent
anchors.margins: 20
anchors.margins: 20 * screenScaleFactor
UM.I18nCatalog
{
@ -59,7 +63,7 @@ UM.Dialog
Column
{
anchors.fill: parent
spacing: 2
spacing: 2 * screenScaleFactor
Label
{
id: titleLabel
@ -327,6 +331,7 @@ UM.Dialog
{
width: parent.width
height: childrenRect.height
visible: manager.hasVisibleSettingsField
Label
{
text: catalog.i18nc("@action:label", "Visible settings:")
@ -360,7 +365,7 @@ UM.Dialog
Label
{
id: warningLabel
text: catalog.i18nc("@action:warning", "Loading a project will clear all models on the buildplate")
text: catalog.i18nc("@action:warning", "Loading a project will clear all models on the build plate.")
wrapMode: Text.Wrap
}
}
@ -373,9 +378,9 @@ UM.Dialog
enabled: true
anchors.bottom: parent.bottom
anchors.right: ok_button.left
anchors.rightMargin:2
anchors.rightMargin: 2 * screenScaleFactor
}
Button
Button
{
id: ok_button
text: catalog.i18nc("@action:button","Open");
@ -384,4 +389,10 @@ UM.Dialog
anchors.right: parent.right
}
}
function reject() {
manager.onCancelButtonClicked();
base.visible = false;
base.rejected();
}
}

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from typing import Dict
import sys

View File

@ -1,3 +1,6 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Workspace.WorkspaceWriter import WorkspaceWriter
from UM.Application import Application
from UM.Preferences import Preferences
@ -42,9 +45,14 @@ class ThreeMFWorkspaceWriter(WorkspaceWriter):
self._writeContainerToArchive(container, archive)
# Write preferences to archive
preferences_file = zipfile.ZipInfo("Cura/preferences.cfg")
original_preferences = Preferences.getInstance() #Copy only the preferences that we use to the workspace.
temp_preferences = Preferences()
for preference in {"general/visible_settings", "cura/active_mode", "cura/categories_expanded"}:
temp_preferences.addPreference(preference, None)
temp_preferences.setValue(preference, original_preferences.getValue(preference))
preferences_string = StringIO()
Preferences.getInstance().writeToFile(preferences_string)
temp_preferences.writeToFile(preferences_string)
preferences_file = zipfile.ZipInfo("Cura/preferences.cfg")
archive.writestr(preferences_file, preferences_string.getvalue())
# Save Cura version

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
# Uranium is released under the terms of the LGPLv3 or higher.
from UM.Mesh.MeshWriter import MeshWriter
from UM.Math.Vector import Vector

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
# Uranium is released under the terms of the LGPLv3 or higher.
import sys
from UM.Logger import Logger

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import QTimer

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from . import AutoSave

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.i18n import i18nCatalog
from UM.Extension import Extension

View File

@ -1,5 +1,5 @@
// Copyright (c) 2015 Ultimaker B.V.
// Cura is released under the terms of the AGPLv3 or higher.
// Cura is released under the terms of the LGPLv3 or higher.
import QtQuick 2.1
import QtQuick.Controls 1.3

View File

@ -1,3 +1,83 @@
[3.0.0]
*Faster start-up
Start-up speed has been cut in half compared to the previous version.
*New color scheme
Color scheme has been updated to reflect Ultimaker Cura rebrand.
*Updated UX design
The Ultimaker Cura logo has moved from the bottom to the top of the interface. Print status icons have been updated and repositioned.
*Redesigned splash screen
A new splash screen on Ultimaker Cura startup has been added.
*Top navigation bar improvements
The width of tab functionality changes accordingly to the word space (multilingual).
*Print quality slider
A slider can now be used to control the quality profile in recommended mode.
*Infill slider
Model infill can now be changed using a slider in recommended mode.
*Changed layer view
Layer view icon, panel and slider have moved to top-right of interface.
*Rasterized build plate
The build plate now shows graduations of 10 mm and 1 mm for easy model positioning.
*Changed row of extruder buttons
Extruder tabs have become buttons and icons have been updated.
*Add an "Export to Cura" button in SOLIDWORKS
SOLIDWORKS plugin can now be installed using an automatic installer.
*Siemens NX macro
When a user updates models in Siemens NX and clicks the button, the updated models replace the models opened in Ultimaker Cura.
*Skin removal width
Remove thin strips of skin from a model to prevent print head zigzagging, in turn preventing vibrations.
*Skin expand distance
Cutting away skins on steep overhangs makes prints less sturdy. By expanding skins with the thickness of walls, features will be better supported. In addition, features such as towers on top of infill will be stronger.
*Extra skin wall count
Printing extra skin directly on top of infill can lead to gaps, curling and pillowing. This is reduced by printing a wall around the skin first, and also improves the printing speed.
*Minimum extrusion for skin
Will prevent filling small gaps that are probably filled already, resulting in less strings, better top details and faster prints.
*PVA retractions
PVA (switch) retraction length is increased, minimum travel distance for retraction is decreased and max count is slightly increased, this reduces stringing by a lot at the cost of slightly increased print time.
*Z seam options
Gives the user control over where to place the seam - hide it in convex corners or in easy to remove locations such as concave corners. Dont let corner angles influence the seam position.
*Quarter cubic infill
Similar to tetrahedral (octet) infill, but half of the lines are shifted half of the period up. This pattern sacrifices some rigidity of octet infill for greater toughness.
*Cross infill
A fractal pattern infill that requires fewer retractions than other infill types. This is useful for flexible materials as it causes less material elongation. The internal structure given by this infill also assists flexible models having more resistance, while retaining soft properties in all directions.
*Layer start negative position
Layer start X/Y values can be less than 0 when the machine centre is zero.
*PostProcessing stretch script
This new script performs "post stretch" algorithm to fix the problem of insufficient inner and outer diameters. Thanks to electrocbd for contributing.
*Ironing speed settings
Ironing speed settings have been moved to experimental category.
*Doodle3D plugin
Update Doodle3D plugin to connect with printers. Thanks to mith for contributing.
*Bug fixes
- Customized profiles are not sent when connecting to a printer
- Sync z-hop with layer changes, thanks to smartavionics for contributing
- Memory leaks on MacOS
- Printer name not loaded when project file is opened
- Doodle3D Wifi box was selected by default on non-UM3 printers
[2.7.0]
*Top surface skin
Specify print settings of the top-most layers separately in order to improve print duration and achieve higher quality top surfaces.

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from . import ChangeLog

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Backend.Backend import Backend, BackendState
from UM.Application import Application
@ -195,20 +195,8 @@ class CuraEngineBackend(QObject, Backend):
self.backendStateChange.emit(BackendState.Done)
Logger.log("w", "Slice unnecessary, nothing has changed that needs reslicing.")
return
self.printDurationMessage.emit({
"none": 0,
"inset_0": 0,
"inset_x": 0,
"skin": 0,
"support": 0,
"skirt": 0,
"infill": 0,
"support_infill": 0,
"travel": 0,
"retract": 0,
"support_interface": 0
}, [0])
if Application.getInstance().getPrintInformation():
Application.getInstance().getPrintInformation().setToZeroPrintInformation()
self._stored_layer_data = []
self._stored_optimized_layer_data = []
@ -278,7 +266,7 @@ class CuraEngineBackend(QObject, Backend):
if job.getResult() == StartSliceJob.StartJobResult.MaterialIncompatible:
if Application.getInstance().platformActivity:
self._error_message = Message(catalog.i18nc("@info:status",
"The selected material is incompatible with the selected machine or configuration."))
"Unable to slice with the current material as it is incompatible with the selected machine or configuration."), title = catalog.i18nc("@info:title", "Unable to slice"))
self._error_message.show()
self.backendStateChange.emit(BackendState.Error)
else:
@ -305,7 +293,8 @@ class CuraEngineBackend(QObject, Backend):
error_labels.add(definitions[0].label)
error_labels = ", ".join(error_labels)
self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice with the current settings. The following settings have errors: {0}".format(error_labels)))
self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice with the current settings. The following settings have errors: {0}".format(error_labels)),
title = catalog.i18nc("@info:title", "Unable to slice"))
self._error_message.show()
self.backendStateChange.emit(BackendState.Error)
else:
@ -314,7 +303,8 @@ class CuraEngineBackend(QObject, Backend):
if job.getResult() == StartSliceJob.StartJobResult.BuildPlateError:
if Application.getInstance().platformActivity:
self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice because the prime tower or prime position(s) are invalid."))
self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice because the prime tower or prime position(s) are invalid."),
title = catalog.i18nc("@info:title", "Unable to slice"))
self._error_message.show()
self.backendStateChange.emit(BackendState.Error)
else:
@ -322,7 +312,8 @@ class CuraEngineBackend(QObject, Backend):
if job.getResult() == StartSliceJob.StartJobResult.NothingToSlice:
if Application.getInstance().platformActivity:
self._error_message = Message(catalog.i18nc("@info:status", "Nothing to slice because none of the models fit the build volume. Please scale or rotate models to fit."))
self._error_message = Message(catalog.i18nc("@info:status", "Nothing to slice because none of the models fit the build volume. Please scale or rotate models to fit."),
title = catalog.i18nc("@info:title", "Unable to slice"))
self._error_message.show()
self.backendStateChange.emit(BackendState.Error)
else:
@ -450,7 +441,7 @@ class CuraEngineBackend(QObject, Backend):
def _onStackErrorCheckFinished(self):
self._is_error_check_scheduled = False
if self._need_slicing:
if not self._slicing and self._need_slicing:
self.needsSlicing()
self._onChanged()
@ -511,29 +502,6 @@ class CuraEngineBackend(QObject, Backend):
def _onGCodePrefixMessage(self, message):
self._scene.gcode_list.insert(0, message.data.decode("utf-8", "replace"))
## Called when a print time message is received from the engine.
#
# \param message The protobuf message containing the print time per feature and
# material amount per extruder
def _onPrintTimeMaterialEstimates(self, message):
material_amounts = []
for index in range(message.repeatedMessageCount("materialEstimates")):
material_amounts.append(message.getRepeatedMessage("materialEstimates", index).material_amount)
feature_times = {
"none": message.time_none,
"inset_0": message.time_inset_0,
"inset_x": message.time_inset_x,
"skin": message.time_skin,
"support": message.time_support,
"skirt": message.time_skirt,
"infill": message.time_infill,
"support_infill": message.time_support_infill,
"travel": message.time_travel,
"retract": message.time_retract,
"support_interface": message.time_support_interface
}
self.printDurationMessage.emit(feature_times, material_amounts)
## Creates a new socket connection.
def _createSocket(self):
super()._createSocket(os.path.abspath(os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), "Cura.proto")))
@ -552,6 +520,37 @@ class CuraEngineBackend(QObject, Backend):
else:
self._change_timer.start()
## Called when a print time message is received from the engine.
#
# \param message The protobuf message containing the print time per feature and
# material amount per extruder
def _onPrintTimeMaterialEstimates(self, message):
material_amounts = []
for index in range(message.repeatedMessageCount("materialEstimates")):
material_amounts.append(message.getRepeatedMessage("materialEstimates", index).material_amount)
times = self._parseMessagePrintTimes(message)
self.printDurationMessage.emit(times, material_amounts)
## Called for parsing message to retrieve estimated time per feature
#
# \param message The protobuf message containing the print time per feature
def _parseMessagePrintTimes(self, message):
result = {
"inset_0": message.time_inset_0,
"inset_x": message.time_inset_x,
"skin": message.time_skin,
"infill": message.time_infill,
"support_infill": message.time_support_infill,
"support_interface": message.time_support_interface,
"support": message.time_support,
"skirt": message.time_skirt,
"travel": message.time_travel,
"retract": message.time_retract,
"none": message.time_none
}
return result
## Called when the back-end connects to the front-end.
def _onBackendConnected(self):
if self._restart:

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Job import Job
from UM.Application import Application

View File

@ -1,5 +1,5 @@
#Copyright (c) 2017 Ultimaker B.V.
#Cura is released under the terms of the AGPLv3 or higher.
#Cura is released under the terms of the LGPLv3 or higher.
import gc
@ -47,7 +47,7 @@ class ProcessSlicedLayersJob(Job):
super().__init__()
self._layers = layers
self._scene = Application.getInstance().getController().getScene()
self._progress = None
self._progress_message = Message(catalog.i18nc("@info:status", "Processing Layers"), 0, False, -1)
self._abort_requested = False
## Aborts the processing of layers.
@ -62,12 +62,11 @@ class ProcessSlicedLayersJob(Job):
def run(self):
start_time = time()
if Application.getInstance().getController().getActiveView().getPluginId() == "LayerView":
self._progress = Message(catalog.i18nc("@info:status", "Processing Layers"), 0, False, -1)
self._progress.show()
self._progress_message.show()
Job.yieldThread()
if self._abort_requested:
if self._progress:
self._progress.hide()
if self._progress_message:
self._progress_message.hide()
return
Application.getInstance().getController().activeViewChanged.connect(self._onActiveViewChanged)
@ -80,8 +79,8 @@ class ProcessSlicedLayersJob(Job):
node.getParent().removeChild(node)
break
if self._abort_requested:
if self._progress:
self._progress.hide()
if self._progress_message:
self._progress_message.hide()
return
# Force garbage collection.
@ -159,11 +158,11 @@ class ProcessSlicedLayersJob(Job):
# This needs some work in LayerData so we can add the new layers instead of recreating the entire mesh.
if self._abort_requested:
if self._progress:
self._progress.hide()
if self._progress_message:
self._progress_message.hide()
return
if self._progress:
self._progress.setProgress(progress)
if self._progress_message:
self._progress_message.setProgress(progress)
# We are done processing all the layers we got from the engine, now create a mesh out of the data
@ -197,8 +196,8 @@ class ProcessSlicedLayersJob(Job):
layer_mesh = layer_data.build(material_color_map, line_type_brightness)
if self._abort_requested:
if self._progress:
self._progress.hide()
if self._progress_message:
self._progress_message.hide()
return
# Add LayerDataDecorator to scene node to indicate that the node has layer data
@ -216,15 +215,15 @@ class ProcessSlicedLayersJob(Job):
if not settings.getProperty("machine_center_is_zero", "value"):
new_node.setPosition(Vector(-settings.getProperty("machine_width", "value") / 2, 0.0, settings.getProperty("machine_depth", "value") / 2))
if self._progress:
self._progress.setProgress(100)
if self._progress_message:
self._progress_message.setProgress(100)
view = Application.getInstance().getController().getActiveView()
if view.getPluginId() == "LayerView":
view.resetLayerData()
if self._progress:
self._progress.hide()
if self._progress_message:
self._progress_message.hide()
# Clear the unparsed layers. This saves us a bunch of memory if the Job does not get destroyed.
self._layers = None
@ -234,10 +233,10 @@ class ProcessSlicedLayersJob(Job):
def _onActiveViewChanged(self):
if self.isRunning():
if Application.getInstance().getController().getActiveView().getPluginId() == "LayerView":
if not self._progress:
self._progress = Message(catalog.i18nc("@info:status", "Processing Layers"), 0, False, 0)
if self._progress.getProgress() != 100:
self._progress.show()
if not self._progress_message:
self._progress_message = Message(catalog.i18nc("@info:status", "Processing Layers"), 0, False, 0, catalog.i18nc("@info:title", "Information"))
if self._progress_message.getProgress() != 100:
self._progress_message.show()
else:
if self._progress:
self._progress.hide()
if self._progress_message:
self._progress_message.hide()

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
import numpy
from string import Formatter
@ -319,18 +319,22 @@ class StartSliceJob(Job):
# \param message object_lists message to put the per object settings in
def _handlePerObjectSettings(self, node, message):
stack = node.callDecoration("getStack")
if not stack: # Check if the node has a stack attached to it and the stack has any settings in the top container.
# Check if the node has a stack attached to it and the stack has any settings in the top container.
if not stack:
return
# Check all settings for relations, so we can also calculate the correct values for dependent settings.
top_of_stack = stack.getTop() #Cache for efficiency.
top_of_stack = stack.getTop() # Cache for efficiency.
changed_setting_keys = set(top_of_stack.getAllKeys())
# Add all relations to changed settings as well.
for key in top_of_stack.getAllKeys():
instance = top_of_stack.getInstance(key)
self._addRelations(changed_setting_keys, instance.definition.relations)
Job.yieldThread()
# Ensure that the engine is aware what the build extruder is
# Ensure that the engine is aware what the build extruder is.
if stack.getProperty("machine_extruder_count", "value") > 1:
changed_setting_keys.add("extruder_nr")
@ -339,14 +343,18 @@ class StartSliceJob(Job):
setting = message.addRepeatedMessage("settings")
setting.name = key
extruder = int(round(float(stack.getProperty(key, "limit_to_extruder"))))
if extruder >= 0 and key not in top_of_stack.getAllKeys(): #Limited to a specific extruder, but not overridden by per-object settings.
# Check if limited to a specific extruder, but not overridden by per-object settings.
if extruder >= 0 and key not in changed_setting_keys:
limited_stack = ExtruderManager.getInstance().getActiveExtruderStacks()[extruder]
else:
limited_stack = stack #Just take from the per-object settings itself.
limited_stack = stack
setting.value = str(limited_stack.getProperty(key, "value")).encode("utf-8")
Job.yieldThread()
## Recursive function to put all settings that require eachother for value changes in a list
## Recursive function to put all settings that require each other for value changes in a list
# \param relations_set \type{set} Set of keys (strings) of settings that are influenced
# \param relations list of relation objects that need to be checked.
def _addRelations(self, relations_set, relations):

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
#Shoopdawoop
from . import CuraEngineBackend

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
import configparser
from UM.PluginRegistry import PluginRegistry

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from . import CuraProfileReader

View File

@ -1,6 +1,6 @@
# Copyright (c) 2015 Ultimaker B.V.
# Copyright (c) 2013 David Braam
# Uranium is released under the terms of the AGPLv3 or higher.
# Uranium is released under the terms of the LGPLv3 or higher.
from UM.Logger import Logger
from UM.SaveFile import SaveFile

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
# Uranium is released under the terms of the LGPLv3 or higher.
from . import CuraProfileWriter

View File

@ -0,0 +1,49 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Extension import Extension
from UM.Preferences import Preferences
from UM.Logger import Logger
from UM.i18n import i18nCatalog
from cura.Settings.GlobalStack import GlobalStack
from .FirmwareUpdateCheckerJob import FirmwareUpdateCheckerJob
from UM.Settings.ContainerRegistry import ContainerRegistry
i18n_catalog = i18nCatalog("cura")
## This Extension checks for new versions of the firmware based on the latest checked version number.
# The plugin is currently only usable for applications maintained by Ultimaker. But it should be relatively easy
# to change it to work for other applications.
class FirmwareUpdateChecker(Extension):
JEDI_VERSION_URL = "http://software.ultimaker.com/jedi/releases/latest.version"
def __init__(self):
super().__init__()
# Initialize the Preference called `latest_checked_firmware` that stores the last version
# checked for the UM3. In the future if we need to check other printers' firmware
Preferences.getInstance().addPreference("info/latest_checked_firmware", "")
# Listen to a Signal that indicates a change in the list of printers, just if the user has enabled the
# 'check for updates' option
Preferences.getInstance().addPreference("info/automatic_update_check", True)
if Preferences.getInstance().getValue("info/automatic_update_check"):
ContainerRegistry.getInstance().containerAdded.connect(self._onContainerAdded)
def _onContainerAdded(self, container):
# Only take care when a new GlobalStack was added
if isinstance(container, GlobalStack):
Logger.log("i", "You have a '%s' in printer list. Let's check the firmware!", container.getId())
self.checkFirmwareVersion(container, True)
## Connect with software.ultimaker.com, load latest.version and check version info.
# If the version info is different from the current version, spawn a message to
# allow the user to download it.
#
# \param silent type(boolean) Suppresses messages other than "new version found" messages.
# This is used when checking for a new firmware version at startup.
def checkFirmwareVersion(self, container = None, silent = False):
job = FirmwareUpdateCheckerJob(container = container, silent = silent, url = self.JEDI_VERSION_URL)
job.start()

View File

@ -0,0 +1,86 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Preferences import Preferences
from UM.Application import Application
from UM.Message import Message
from UM.Logger import Logger
from UM.Job import Job
import urllib.request
import codecs
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QDesktopServices
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("cura")
## This job checks if there is an update available on the provided URL.
class FirmwareUpdateCheckerJob(Job):
def __init__(self, container = None, silent = False, url = None):
super().__init__()
self._container = container
self.silent = silent
self._url = url
self._download_url = None # If an update was found, the download_url will be set to the location of the new version.
## Callback for the message that is spawned when there is a new version.
def actionTriggered(self, message, action):
if action == "download":
if self._download_url is not None:
QDesktopServices.openUrl(QUrl(self._download_url))
def run(self):
self._download_url = None # Reset download ur.
if not self._url:
Logger.log("e", "Can not check for a new release. URL not set!")
return
try:
application_name = Application.getInstance().getApplicationName()
headers = {"User-Agent": "%s - %s" % (application_name, Application.getInstance().getVersion())}
request = urllib.request.Request(self._url, headers = headers)
current_version_file = urllib.request.urlopen(request)
reader = codecs.getreader("utf-8")
# get machine name from the definition container
machine_name = self._container.definition.getName()
machine_name_parts = machine_name.lower().split(" ")
# If it is not None, then we compare between the checked_version and the current_version
# Now we just do that if the active printer is Ultimaker 3 or Ultimaker 3 Extended or any
# other Ultimaker 3 that will come in the future
if len(machine_name_parts) >= 2 and machine_name_parts[:2] == ["ultimaker", "3"]:
# Nothing to parse, just get the string
# TODO: In the future may be done by parsing a JSON file with diferent version for each printer model
current_version = reader(current_version_file).readline().rstrip()
# If it is the first time the version is checked, the checked_version is ''
checked_version = Preferences.getInstance().getValue("info/latest_checked_firmware")
# If the checked_version is '', it's because is the first time we check firmware and in this case
# we will not show the notification, but we will store it for the next time
Preferences.getInstance().setValue("info/latest_checked_firmware", current_version)
Logger.log("i", "Reading firmware version of %s: checked = %s - latest = %s", machine_name, checked_version, current_version)
# The first time we want to store the current version, the notification will not be shown,
# because the new version of Cura will be release before the firmware and we don't want to
# notify the user when no new firmware version is available.
if (checked_version != "") and (checked_version != current_version):
Logger.log("i", "SHOWING FIRMWARE UPDATE MESSAGE")
message = Message(i18n_catalog.i18nc("@info Don't translate {machine_name}, since it gets replaced by a printer name!", "To ensure that your {machine_name} is equipped with the latest features it is recommended to update the firmware regularly. This can be done on the {machine_name} (when connected to the network) or via USB.").format(machine_name = machine_name),
title = i18n_catalog.i18nc("@info:title The %s gets replaced with the printer name.", "New %s firmware available") % machine_name)
message.addAction("download", i18n_catalog.i18nc("@action:button", "Download"), "[no_icon]", "[no_description]")
# If we do this in a cool way, the download url should be available in the JSON file
self._download_url = "https://ultimaker.com/en/resources/20500-upgrade-firmware"
message.actionTriggered.connect(self.actionTriggered)
message.show()
except Exception as e:
Logger.log("w", "Failed to check for new version: %s", e)
if not self.silent:
Message(i18n_catalog.i18nc("@info", "Could not access update information.")).show()
return

View File

@ -0,0 +1,16 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.i18n import i18nCatalog
from . import FirmwareUpdateChecker
i18n_catalog = i18nCatalog("cura")
def getMetaData():
return {}
def register(app):
return {"extension": FirmwareUpdateChecker.FirmwareUpdateChecker()}

View File

@ -0,0 +1,8 @@
{
"name": "Firmware Update Checker",
"author": "Ultimaker B.V.",
"version": "1.0.0",
"description": "Checks for firmware updates.",
"api": 4,
"i18n-catalog": "cura"
}

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
import re #Regular expressions for parsing escape characters in the settings.
import json

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from . import GCodeProfileReader

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Aleph Objects, Inc.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Application import Application
from UM.Backend import Backend
@ -251,7 +251,10 @@ class GCodeReader(MeshReader):
self._clearValues()
self._message = Message(catalog.i18nc("@info:status", "Parsing G-code"), lifetime=0)
self._message = Message(catalog.i18nc("@info:status", "Parsing G-code"),
lifetime=0,
title = catalog.i18nc("@info:title", "G-code Details"))
self._message.setProgress(0)
self._message.show()
@ -362,7 +365,9 @@ class GCodeReader(MeshReader):
if Preferences.getInstance().getValue("gcodereader/show_caution"):
caution_message = Message(catalog.i18nc(
"@info:generic",
"Make sure the g-code is suitable for your printer and printer configuration before sending the file to it. The g-code representation may not be accurate."), lifetime=0)
"Make sure the g-code is suitable for your printer and printer configuration before sending the file to it. The g-code representation may not be accurate."),
lifetime=0,
title = catalog.i18nc("@info:title", "G-code Details"))
caution_message.show()
# The "save/print" button's state is bound to the backend state.

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Aleph Objects, Inc.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from . import GCodeReader

View File

@ -1,5 +1,5 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Mesh.MeshWriter import MeshWriter
from UM.Logger import Logger

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from . import GCodeWriter

View File

@ -1,5 +1,5 @@
// Copyright (c) 2015 Ultimaker B.V.
// Cura is released under the terms of the AGPLv3 or higher.
// Cura is released under the terms of the LGPLv3 or higher.
import QtQuick 2.1
import QtQuick.Controls 1.1
@ -10,11 +10,11 @@ import UM 1.1 as UM
UM.Dialog
{
width: 350 * Screen.devicePixelRatio;
minimumWidth: 350 * Screen.devicePixelRatio;
width: minimumWidth;
minimumWidth: 350 * screenScaleFactor;
height: 250 * Screen.devicePixelRatio;
minimumHeight: 250 * Screen.devicePixelRatio;
height: minimumHeight;
minimumHeight: 250 * screenScaleFactor;
title: catalog.i18nc("@title:window", "Convert Image...")
@ -23,8 +23,8 @@ UM.Dialog
UM.I18nCatalog{id: catalog; name:"cura"}
anchors.fill: parent;
Layout.fillWidth: true
columnSpacing: 16
rowSpacing: 4
columnSpacing: 16 * screenScaleFactor
rowSpacing: 4 * screenScaleFactor
columns: 1
UM.TooltipArea {
@ -36,7 +36,7 @@ UM.Dialog
Label {
text: catalog.i18nc("@action:label","Height (mm)")
width: 150
width: 150 * screenScaleFactor
anchors.verticalCenter: parent.verticalCenter
}
@ -44,7 +44,7 @@ UM.Dialog
id: peak_height
objectName: "Peak_Height"
validator: DoubleValidator {notation: DoubleValidator.StandardNotation; bottom: -500; top: 500;}
width: 180
width: 180 * screenScaleFactor
onTextChanged: { manager.onPeakHeightChanged(text) }
}
}
@ -59,7 +59,7 @@ UM.Dialog
Label {
text: catalog.i18nc("@action:label","Base (mm)")
width: 150
width: 150 * screenScaleFactor
anchors.verticalCenter: parent.verticalCenter
}
@ -67,7 +67,7 @@ UM.Dialog
id: base_height
objectName: "Base_Height"
validator: DoubleValidator {notation: DoubleValidator.StandardNotation; bottom: 0; top: 500;}
width: 180
width: 180 * screenScaleFactor
onTextChanged: { manager.onBaseHeightChanged(text) }
}
}
@ -82,7 +82,7 @@ UM.Dialog
Label {
text: catalog.i18nc("@action:label","Width (mm)")
width: 150
width: 150 * screenScaleFactor
anchors.verticalCenter: parent.verticalCenter
}
@ -91,7 +91,7 @@ UM.Dialog
objectName: "Width"
focus: true
validator: DoubleValidator {notation: DoubleValidator.StandardNotation; bottom: 1; top: 500;}
width: 180
width: 180 * screenScaleFactor
onTextChanged: { manager.onWidthChanged(text) }
}
}
@ -106,7 +106,7 @@ UM.Dialog
Label {
text: catalog.i18nc("@action:label","Depth (mm)")
width: 150
width: 150 * screenScaleFactor
anchors.verticalCenter: parent.verticalCenter
}
TextField {
@ -114,7 +114,7 @@ UM.Dialog
objectName: "Depth"
focus: true
validator: DoubleValidator {notation: DoubleValidator.StandardNotation; bottom: 1; top: 500;}
width: 180
width: 180 * screenScaleFactor
onTextChanged: { manager.onDepthChanged(text) }
}
}
@ -130,14 +130,14 @@ UM.Dialog
//Empty label so 2 column layout works.
Label {
text: ""
width: 150
width: 150 * screenScaleFactor
anchors.verticalCenter: parent.verticalCenter
}
ComboBox {
id: image_color_invert
objectName: "Image_Color_Invert"
model: [ catalog.i18nc("@item:inlistbox","Lighter is higher"), catalog.i18nc("@item:inlistbox","Darker is higher") ]
width: 180
width: 180 * screenScaleFactor
onCurrentIndexChanged: { manager.onImageColorInvertChanged(currentIndex) }
}
}
@ -152,13 +152,13 @@ UM.Dialog
Label {
text: catalog.i18nc("@action:label","Smoothing")
width: 150
width: 150 * screenScaleFactor
anchors.verticalCenter: parent.verticalCenter
}
Item {
width: 180
height: 20
width: 180 * screenScaleFactor
height: 20 * screenScaleFactor
Layout.fillWidth: true
Slider {

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
import numpy

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
import os
import threading

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from . import ImageReader

View File

@ -1,5 +1,5 @@
# Copyright (c) 2016 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
from UM.Resources import Resources

View File

@ -0,0 +1,312 @@
// Copyright (c) 2017 Ultimaker B.V.
// Cura is released under the terms of the LGPLv3 or higher.
import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1
import QtQuick.Controls.Styles 1.1
import UM 1.0 as UM
import Cura 1.0 as Cura
Item {
id: sliderRoot
// handle properties
property real handleSize: 10
property real handleRadius: handleSize / 2
property real minimumRangeHandleSize: handleSize / 2
property color upperHandleColor: "black"
property color lowerHandleColor: "black"
property color rangeHandleColor: "black"
property real handleLabelWidth: width
property var activeHandle: upperHandle
// track properties
property real trackThickness: 4 // width of the slider track
property real trackRadius: trackThickness / 2
property color trackColor: "white"
property real trackBorderWidth: 1 // width of the slider track border
property color trackBorderColor: "black"
// value properties
property real maximumValue: 100
property real minimumValue: 0
property real minimumRange: 0 // minimum range allowed between min and max values
property bool roundValues: true
property real upperValue: maximumValue
property real lowerValue: minimumValue
property bool layersVisible: true
function getUpperValueFromSliderHandle () {
return upperHandle.getValue()
}
function setUpperValue (value) {
upperHandle.setValue(value)
updateRangeHandle()
}
function getLowerValueFromSliderHandle () {
return lowerHandle.getValue()
}
function setLowerValue (value) {
lowerHandle.setValue(value)
updateRangeHandle()
}
function updateRangeHandle () {
rangeHandle.height = lowerHandle.y - (upperHandle.y + upperHandle.height)
}
// set the active handle to show only one label at a time
function setActiveHandle (handle) {
activeHandle = handle
}
// slider track
Rectangle {
id: track
width: sliderRoot.trackThickness
height: sliderRoot.height - sliderRoot.handleSize
radius: sliderRoot.trackRadius
anchors.centerIn: sliderRoot
color: sliderRoot.trackColor
border.width: sliderRoot.trackBorderWidth
border.color: sliderRoot.trackBorderColor
visible: sliderRoot.layersVisible
}
// Range handle
Item {
id: rangeHandle
y: upperHandle.y + upperHandle.height
width: sliderRoot.handleSize
height: sliderRoot.minimumRangeHandleSize
anchors.horizontalCenter: sliderRoot.horizontalCenter
visible: sliderRoot.layersVisible
// set the new value when dragging
function onHandleDragged () {
upperHandle.y = y - upperHandle.height
lowerHandle.y = y + height
var upperValue = sliderRoot.getUpperValueFromSliderHandle()
var lowerValue = sliderRoot.getLowerValueFromSliderHandle()
// set both values after moving the handle position
UM.LayerView.setCurrentLayer(upperValue)
UM.LayerView.setMinimumLayer(lowerValue)
}
function setValue (value) {
var range = sliderRoot.upperValue - sliderRoot.lowerValue
value = Math.min(value, sliderRoot.maximumValue)
value = Math.max(value, sliderRoot.minimumValue + range)
UM.LayerView.setCurrentLayer(value)
UM.LayerView.setMinimumLayer(value - range)
}
Rectangle {
width: sliderRoot.trackThickness - 2 * sliderRoot.trackBorderWidth
height: parent.height + sliderRoot.handleSize
anchors.centerIn: parent
color: sliderRoot.rangeHandleColor
}
MouseArea {
anchors.fill: parent
drag {
target: parent
axis: Drag.YAxis
minimumY: upperHandle.height
maximumY: sliderRoot.height - (rangeHandle.height + lowerHandle.height)
}
onPositionChanged: parent.onHandleDragged()
onPressed: sliderRoot.setActiveHandle(rangeHandle)
}
LayerSliderLabel {
id: rangleHandleLabel
height: sliderRoot.handleSize + UM.Theme.getSize("default_margin").height
x: parent.x - width - UM.Theme.getSize("default_margin").width
anchors.verticalCenter: parent.verticalCenter
target: Qt.point(sliderRoot.width, y + height / 2)
visible: sliderRoot.activeHandle == parent
// custom properties
maximumValue: sliderRoot.maximumValue
value: sliderRoot.upperValue
busy: UM.LayerView.busy
setValue: rangeHandle.setValue // connect callback functions
}
}
// Upper handle
Rectangle {
id: upperHandle
y: sliderRoot.height - (sliderRoot.minimumRangeHandleSize + 2 * sliderRoot.handleSize)
width: sliderRoot.handleSize
height: sliderRoot.handleSize
anchors.horizontalCenter: sliderRoot.horizontalCenter
radius: sliderRoot.handleRadius
color: sliderRoot.upperHandleColor
visible: sliderRoot.layersVisible
function onHandleDragged () {
// don't allow the lower handle to be heigher than the upper handle
if (lowerHandle.y - (y + height) < sliderRoot.minimumRangeHandleSize) {
lowerHandle.y = y + height + sliderRoot.minimumRangeHandleSize
}
// update the range handle
sliderRoot.updateRangeHandle()
// set the new value after moving the handle position
UM.LayerView.setCurrentLayer(getValue())
}
// get the upper value based on the slider position
function getValue () {
var result = y / (sliderRoot.height - (2 * sliderRoot.handleSize + sliderRoot.minimumRangeHandleSize))
result = sliderRoot.maximumValue + result * (sliderRoot.minimumValue - (sliderRoot.maximumValue - sliderRoot.minimumValue))
result = sliderRoot.roundValues ? Math.round(result) : result
return result
}
// set the slider position based on the upper value
function setValue (value) {
UM.LayerView.setCurrentLayer(value)
var diff = (value - sliderRoot.maximumValue) / (sliderRoot.minimumValue - sliderRoot.maximumValue)
var newUpperYPosition = Math.round(diff * (sliderRoot.height - (2 * sliderRoot.handleSize + sliderRoot.minimumRangeHandleSize)))
y = newUpperYPosition
// update the range handle
sliderRoot.updateRangeHandle()
}
// dragging
MouseArea {
anchors.fill: parent
drag {
target: parent
axis: Drag.YAxis
minimumY: 0
maximumY: sliderRoot.height - (2 * sliderRoot.handleSize + sliderRoot.minimumRangeHandleSize)
}
onPositionChanged: parent.onHandleDragged()
onPressed: sliderRoot.setActiveHandle(upperHandle)
}
LayerSliderLabel {
id: upperHandleLabel
height: sliderRoot.handleSize + UM.Theme.getSize("default_margin").height
x: parent.x - width - UM.Theme.getSize("default_margin").width
anchors.verticalCenter: parent.verticalCenter
target: Qt.point(sliderRoot.width, y + height / 2)
visible: sliderRoot.activeHandle == parent
// custom properties
maximumValue: sliderRoot.maximumValue
value: sliderRoot.upperValue
busy: UM.LayerView.busy
setValue: upperHandle.setValue // connect callback functions
}
}
// Lower handle
Rectangle {
id: lowerHandle
y: sliderRoot.height - sliderRoot.handleSize
width: parent.handleSize
height: parent.handleSize
anchors.horizontalCenter: parent.horizontalCenter
radius: sliderRoot.handleRadius
color: sliderRoot.lowerHandleColor
visible: slider.layersVisible
function onHandleDragged () {
// don't allow the upper handle to be lower than the lower handle
if (y - (upperHandle.y + upperHandle.height) < sliderRoot.minimumRangeHandleSize) {
upperHandle.y = y - (upperHandle.heigth + sliderRoot.minimumRangeHandleSize)
}
// update the range handle
sliderRoot.updateRangeHandle()
// set the new value after moving the handle position
UM.LayerView.setMinimumLayer(getValue())
}
// get the lower value from the current slider position
function getValue () {
var result = (y - (sliderRoot.handleSize + sliderRoot.minimumRangeHandleSize)) / (sliderRoot.height - (2 * sliderRoot.handleSize + sliderRoot.minimumRangeHandleSize));
result = sliderRoot.maximumValue - sliderRoot.minimumRange + result * (sliderRoot.minimumValue - (sliderRoot.maximumValue - sliderRoot.minimumRange))
result = sliderRoot.roundValues ? Math.round(result) : result
return result
}
// set the slider position based on the lower value
function setValue (value) {
UM.LayerView.setMinimumLayer(value)
var diff = (value - sliderRoot.maximumValue) / (sliderRoot.minimumValue - sliderRoot.maximumValue)
var newLowerYPosition = Math.round((sliderRoot.handleSize + sliderRoot.minimumRangeHandleSize) + diff * (sliderRoot.height - (2 * sliderRoot.handleSize + sliderRoot.minimumRangeHandleSize)))
y = newLowerYPosition
// update the range handle
sliderRoot.updateRangeHandle()
}
// dragging
MouseArea {
anchors.fill: parent
drag {
target: parent
axis: Drag.YAxis
minimumY: upperHandle.height + sliderRoot.minimumRangeHandleSize
maximumY: sliderRoot.height - parent.height
}
onPositionChanged: parent.onHandleDragged()
onPressed: sliderRoot.setActiveHandle(lowerHandle)
}
LayerSliderLabel {
id: lowerHandleLabel
height: sliderRoot.handleSize + UM.Theme.getSize("default_margin").height
x: parent.x - width - UM.Theme.getSize("default_margin").width
anchors.verticalCenter: parent.verticalCenter
target: Qt.point(sliderRoot.width, y + height / 2)
visible: sliderRoot.activeHandle == parent
// custom properties
maximumValue: sliderRoot.maximumValue
value: sliderRoot.lowerValue
busy: UM.LayerView.busy
setValue: lowerHandle.setValue // connect callback functions
}
}
}

View File

@ -0,0 +1,103 @@
// Copyright (c) 2017 Ultimaker B.V.
// Cura is released under the terms of the LGPLv3 or higher.
import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1
import QtQuick.Controls.Styles 1.1
import UM 1.0 as UM
import Cura 1.0 as Cura
UM.PointingRectangle {
id: sliderLabelRoot
// custom properties
property real maximumValue: 100
property real value: 0
property var setValue // Function
property bool busy: false
target: Qt.point(parent.width, y + height / 2)
arrowSize: UM.Theme.getSize("default_arrow").width
height: parent.height
width: valueLabel.width + UM.Theme.getSize("default_margin").width
visible: false
// make sure the text field is focussed when pressing the parent handle
// needed to connect the key bindings when switching active handle
onVisibleChanged: if (visible) valueLabel.forceActiveFocus()
color: UM.Theme.getColor("tool_panel_background")
borderColor: UM.Theme.getColor("lining")
borderWidth: UM.Theme.getSize("default_lining").width
Behavior on height {
NumberAnimation {
duration: 50
}
}
// catch all mouse events so they're not handled by underlying 3D scene
MouseArea {
anchors.fill: parent
}
TextField {
id: valueLabel
anchors {
left: parent.left
leftMargin: UM.Theme.getSize("default_margin").width / 2
verticalCenter: parent.verticalCenter
}
width: 40 * screenScaleFactor
text: sliderLabelRoot.value + 1 // the current handle value, add 1 because layers is an array
horizontalAlignment: TextInput.AlignRight
// key bindings, work when label is currenctly focused (active handle in LayerSlider)
Keys.onUpPressed: sliderLabelRoot.setValue(sliderLabelRoot.value + ((event.modifiers & Qt.ShiftModifier) ? 10 : 1))
Keys.onDownPressed: sliderLabelRoot.setValue(sliderLabelRoot.value - ((event.modifiers & Qt.ShiftModifier) ? 10 : 1))
style: TextFieldStyle {
textColor: UM.Theme.getColor("setting_control_text")
font: UM.Theme.getFont("default")
background: Item { }
}
onEditingFinished: {
// Ensure that the cursor is at the first position. On some systems the text isn't fully visible
// Seems to have to do something with different dpi densities that QML doesn't quite handle.
// Another option would be to increase the size even further, but that gives pretty ugly results.
cursorPosition = 0
if (valueLabel.text != "") {
// -1 because we need to convert back to an array structure
sliderLabelRoot.setValue(parseInt(valueLabel.text) - 1)
}
}
validator: IntValidator {
bottom: 1
top: sliderLabelRoot.maximumValue + 1 // +1 because actual layers is an array
}
}
BusyIndicator {
id: busyIndicator
anchors {
left: parent.right
leftMargin: UM.Theme.getSize("default_margin").width / 2
verticalCenter: parent.verticalCenter
}
width: sliderLabelRoot.height
height: width
visible: sliderLabelRoot.busy
running: sliderLabelRoot.busy
}
}

View File

@ -1,5 +1,5 @@
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
# Cura is released under the terms of the LGPLv3 or higher.
import sys
@ -90,7 +90,8 @@ class LayerView(View):
self._only_show_top_layers = bool(Preferences.getInstance().getValue("view/only_show_top_layers"))
self._compatibility_mode = True # for safety
self._wireprint_warning_message = Message(catalog.i18nc("@info:status", "Cura does not accurately display layers when Wire Printing is enabled"))
self._wireprint_warning_message = Message(catalog.i18nc("@info:status", "Cura does not accurately display layers when Wire Printing is enabled"),
title = catalog.i18nc("@info:title", "Layer View"))
def _resetSettings(self):
self._layer_view_type = 0 # 0 is material color, 1 is color by linetype, 2 is speed

View File

@ -1,7 +1,7 @@
// Copyright (c) 2017 Ultimaker B.V.
// Cura is released under the terms of the AGPLv3 or higher.
// Cura is released under the terms of the LGPLv3 or higher.
import QtQuick 2.2
import QtQuick 2.4
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1
import QtQuick.Controls.Styles 1.1
@ -22,18 +22,27 @@ Item
height: {
if (UM.LayerView.compatibilityMode) {
return UM.Theme.getSize("layerview_menu_size_compatibility").height;
} else if (UM.Preferences.getValue("layerview/layer_view_type") == 0) {
return UM.Theme.getSize("layerview_menu_size_material_color_mode").height + UM.LayerView.extruderCount * (UM.Theme.getSize("layerview_row").height + UM.Theme.getSize("layerview_row_spacing").height)
} else {
return UM.Theme.getSize("layerview_menu_size").height + UM.LayerView.extruderCount * (UM.Theme.getSize("layerview_row").height + UM.Theme.getSize("layerview_row_spacing").height)
}
}
property var buttonTarget: {
var force_binding = parent.y; // ensure this gets reevaluated when the panel moves
return base.mapFromItem(parent.parent, parent.buttonTarget.x, parent.buttonTarget.y);
if(parent != null)
{
var force_binding = parent.y; // ensure this gets reevaluated when the panel moves
return base.mapFromItem(parent.parent, parent.buttonTarget.x, parent.buttonTarget.y)
}
return Qt.point(0,0)
}
visible: parent != null ? !parent.parent.monitoringPrint: true
UM.PointingRectangle {
id: layerViewMenu
anchors.left: parent.left
anchors.right: parent.right
anchors.top: parent.top
width: parent.width
height: parent.height
@ -41,9 +50,7 @@ Item
color: UM.Theme.getColor("tool_panel_background")
borderWidth: UM.Theme.getSize("default_lining").width
borderColor: UM.Theme.getColor("lining")
target: parent.buttonTarget
arrowSize: UM.Theme.getSize("default_arrow").width
arrowSize: 0 // hide arrow until weird issue with first time rendering is fixed
ColumnLayout {
id: view_settings
@ -64,26 +71,7 @@ Item
anchors.leftMargin: UM.Theme.getSize("default_margin").width
spacing: UM.Theme.getSize("layerview_row_spacing").height
anchors.right: parent.right
anchors.rightMargin: UM.Theme.getSize("default_margin").width * 2
Label
{
id: layersLabel
anchors.left: parent.left
text: catalog.i18nc("@label","View Mode: Layers")
font: UM.Theme.getFont("default_bold");
color: UM.Theme.getColor("text")
Layout.fillWidth: true
elide: Text.ElideMiddle;
}
Label
{
id: spaceLabel
anchors.left: parent.left
text: " "
font.pointSize: 0.5
}
anchors.rightMargin: UM.Theme.getSize("default_margin").width
Label
{
@ -93,7 +81,7 @@ Item
font: UM.Theme.getFont("default");
visible: !UM.LayerView.compatibilityMode
Layout.fillWidth: true
color: UM.Theme.getColor("text")
color: UM.Theme.getColor("setting_control_text")
}
ListModel // matches LayerView.py
@ -123,7 +111,7 @@ Item
visible: !UM.LayerView.compatibilityMode
style: UM.Theme.styles.combobox
anchors.right: parent.right
anchors.rightMargin: 10
anchors.rightMargin: 10 * screenScaleFactor
onActivated:
{
@ -199,6 +187,7 @@ Item
width: UM.Theme.getSize("layerview_legend_size").width
height: UM.Theme.getSize("layerview_legend_size").height
color: model.color
radius: width / 2
border.width: UM.Theme.getSize("default_lining").width
border.color: UM.Theme.getColor("lining")
visible: !view_settings.show_legend
@ -211,7 +200,7 @@ Item
{
text: model.name
elide: Text.ElideRight
color: UM.Theme.getColor("text")
color: UM.Theme.getColor("setting_control_text")
font: UM.Theme.getFont("default")
anchors.verticalCenter: parent.verticalCenter
anchors.left: extrudersModelCheckBox.left;
@ -280,7 +269,7 @@ Item
text: label
font: UM.Theme.getFont("default")
elide: Text.ElideRight
color: UM.Theme.getColor("text")
color: UM.Theme.getColor("setting_control_text")
anchors.verticalCenter: parent.verticalCenter
anchors.left: legendModelCheckBox.left;
anchors.right: legendModelCheckBox.right;
@ -343,301 +332,57 @@ Item
Layout.fillWidth: true
Layout.preferredHeight: UM.Theme.getSize("layerview_row").height + UM.Theme.getSize("default_lining").height
Layout.preferredWidth: UM.Theme.getSize("layerview_row").width
color: UM.Theme.getColor("text")
color: UM.Theme.getColor("setting_control_text")
font: UM.Theme.getFont("default")
}
}
}
Item
{
LayerSlider {
id: slider
width: handleSize
height: parent.height - 2*UM.Theme.getSize("slider_layerview_margin").height
anchors.top: parent.top
anchors.topMargin: UM.Theme.getSize("slider_layerview_margin").height
anchors.right: layerViewMenu.right
anchors.rightMargin: UM.Theme.getSize("slider_layerview_margin").width
property real handleSize: UM.Theme.getSize("slider_handle").width
property real handleRadius: handleSize / 2
property real minimumRangeHandleSize: UM.Theme.getSize("slider_handle").width / 2
property real trackThickness: UM.Theme.getSize("slider_groove").width
property real trackRadius: trackThickness / 2
property real trackBorderWidth: UM.Theme.getSize("default_lining").width
property color upperHandleColor: UM.Theme.getColor("slider_handle")
property color lowerHandleColor: UM.Theme.getColor("slider_handle")
property color rangeHandleColor: UM.Theme.getColor("slider_groove_fill")
property color trackColor: UM.Theme.getColor("slider_groove")
property color trackBorderColor: UM.Theme.getColor("slider_groove_border")
width: UM.Theme.getSize("slider_handle").width
height: UM.Theme.getSize("layerview_menu_size").height
property real maximumValue: UM.LayerView.numLayers
property real minimumValue: 0
property real minimumRange: 0
property bool roundValues: true
property var activeHandle: upperHandle
property bool layersVisible: UM.LayerView.layerActivity && CuraApplication.platformActivity ? true : false
function getUpperValueFromHandle()
{
var result = upperHandle.y / (height - (2 * handleSize + minimumRangeHandleSize));
result = maximumValue + result * (minimumValue - (maximumValue - minimumRange));
result = roundValues ? Math.round(result) | 0 : result;
return result;
anchors {
top: parent.bottom
topMargin: UM.Theme.getSize("slider_layerview_margin").height
right: layerViewMenu.right
rightMargin: UM.Theme.getSize("slider_layerview_margin").width
}
function getLowerValueFromHandle()
{
var result = (lowerHandle.y - (handleSize + minimumRangeHandleSize)) / (height - (2 * handleSize + minimumRangeHandleSize));
result = maximumValue - minimumRange + result * (minimumValue - (maximumValue - minimumRange));
result = roundValues ? Math.round(result) : result;
return result;
}
// custom properties
upperValue: UM.LayerView.currentLayer
lowerValue: UM.LayerView.minimumLayer
maximumValue: UM.LayerView.numLayers
handleSize: UM.Theme.getSize("slider_handle").width
trackThickness: UM.Theme.getSize("slider_groove").width
trackColor: UM.Theme.getColor("slider_groove")
trackBorderColor: UM.Theme.getColor("slider_groove_border")
upperHandleColor: UM.Theme.getColor("slider_handle")
lowerHandleColor: UM.Theme.getColor("slider_handle")
rangeHandleColor: UM.Theme.getColor("slider_groove_fill")
handleLabelWidth: UM.Theme.getSize("slider_layerview_background").width
layersVisible: UM.LayerView.layerActivity && CuraApplication.platformActivity ? true : false
function setUpperValue(value)
{
var value = (value - maximumValue) / (minimumValue - maximumValue);
var new_upper_y = Math.round(value * (height - (2 * handleSize + minimumRangeHandleSize)));
if(new_upper_y != upperHandle.y)
{
upperHandle.y = new_upper_y;
}
rangeHandle.height = lowerHandle.y - (upperHandle.y + upperHandle.height);
}
function setLowerValue(value)
{
var value = (value - maximumValue) / (minimumValue - maximumValue);
var new_lower_y = Math.round((handleSize + minimumRangeHandleSize) + value * (height - (2 * handleSize + minimumRangeHandleSize)));
if(new_lower_y != lowerHandle.y)
{
lowerHandle.y = new_lower_y;
}
rangeHandle.height = lowerHandle.y - (upperHandle.y + upperHandle.height);
}
Connections
{
// update values when layer data changes
Connections {
target: UM.LayerView
onMaxLayersChanged: slider.setUpperValue(UM.LayerView.currentLayer)
onMinimumLayerChanged: slider.setLowerValue(UM.LayerView.minimumLayer)
onCurrentLayerChanged: slider.setUpperValue(UM.LayerView.currentLayer)
}
Rectangle {
width: parent.trackThickness
height: parent.height - parent.handleSize
radius: parent.trackRadius
anchors.centerIn: parent
color: parent.trackColor
border.width: parent.trackBorderWidth;
border.color: parent.trackBorderColor;
}
Item {
id: rangeHandle
y: upperHandle.y + upperHandle.height
width: parent.handleSize
height: parent.minimumRangeHandleSize
anchors.horizontalCenter: parent.horizontalCenter
visible: slider.layersVisible
property real value: UM.LayerView.currentLayer
function setValue(value)
{
var range = upperHandle.value - lowerHandle.value;
value = Math.min(value, slider.maximumValue);
value = Math.max(value, slider.minimumValue + range);
UM.LayerView.setCurrentLayer(value);
UM.LayerView.setMinimumLayer(value - range);
}
Rectangle {
anchors.centerIn: parent
width: parent.parent.trackThickness - 2 * parent.parent.trackBorderWidth
height: parent.height + parent.parent.handleSize
color: parent.parent.rangeHandleColor
}
MouseArea {
anchors.fill: parent
drag.target: parent
drag.axis: Drag.YAxis
drag.minimumY: upperHandle.height
drag.maximumY: parent.parent.height - (parent.height + lowerHandle.height)
onPressed: parent.parent.activeHandle = rangeHandle
onPositionChanged:
{
upperHandle.y = parent.y - upperHandle.height
lowerHandle.y = parent.y + parent.height
var upper_value = slider.getUpperValueFromHandle();
var lower_value = upper_value - (upperHandle.value - lowerHandle.value);
UM.LayerView.setCurrentLayer(upper_value);
UM.LayerView.setMinimumLayer(lower_value);
}
}
}
Rectangle {
id: upperHandle
y: parent.height - (parent.minimumRangeHandleSize + 2 * parent.handleSize)
width: parent.handleSize
height: parent.handleSize
anchors.horizontalCenter: parent.horizontalCenter
radius: parent.handleRadius
color: parent.upperHandleColor
border.width: UM.Theme.getSize("default_lining").width
border.color: UM.Theme.getColor("slider_handle_border")
visible: slider.layersVisible
property real value: UM.LayerView.currentLayer
function setValue(value)
{
UM.LayerView.setCurrentLayer(value);
}
MouseArea {
anchors.fill: parent
drag.target: parent
drag.axis: Drag.YAxis
drag.minimumY: 0
drag.maximumY: parent.parent.height - (2 * parent.parent.handleSize + parent.parent.minimumRangeHandleSize)
onPressed: parent.parent.activeHandle = upperHandle
onPositionChanged:
{
if(lowerHandle.y - (upperHandle.y + upperHandle.height) < parent.parent.minimumRangeHandleSize)
{
lowerHandle.y = upperHandle.y + upperHandle.height + parent.parent.minimumRangeHandleSize;
}
rangeHandle.height = lowerHandle.y - (upperHandle.y + upperHandle.height);
UM.LayerView.setCurrentLayer(slider.getUpperValueFromHandle());
}
}
}
Rectangle {
id: lowerHandle
y: parent.height - parent.handleSize
width: parent.handleSize
height: parent.handleSize
anchors.horizontalCenter: parent.horizontalCenter
radius: parent.handleRadius
color: parent.lowerHandleColor
border.width: UM.Theme.getSize("default_lining").width
border.color: UM.Theme.getColor("slider_handle_border")
visible: slider.layersVisible
property real value: UM.LayerView.minimumLayer
function setValue(value)
{
UM.LayerView.setMinimumLayer(value);
}
MouseArea {
anchors.fill: parent
drag.target: parent
drag.axis: Drag.YAxis
drag.minimumY: upperHandle.height + parent.parent.minimumRangeHandleSize
drag.maximumY: parent.parent.height - parent.height
onPressed: parent.parent.activeHandle = lowerHandle
onPositionChanged:
{
if(lowerHandle.y - (upperHandle.y + upperHandle.height) < parent.parent.minimumRangeHandleSize)
{
upperHandle.y = lowerHandle.y - (upperHandle.height + parent.parent.minimumRangeHandleSize);
}
rangeHandle.height = lowerHandle.y - (upperHandle.y + upperHandle.height)
UM.LayerView.setMinimumLayer(slider.getLowerValueFromHandle());
}
}
}
UM.PointingRectangle
{
x: parent.width + UM.Theme.getSize("slider_layerview_background").width / 2;
y: Math.floor(slider.activeHandle.y + slider.activeHandle.height / 2 - height / 2);
target: Qt.point(0, slider.activeHandle.y + slider.activeHandle.height / 2)
arrowSize: UM.Theme.getSize("default_arrow").width
height: UM.Theme.getSize("slider_handle").height + UM.Theme.getSize("default_margin").height
width: valueLabel.width + UM.Theme.getSize("default_margin").width
Behavior on height { NumberAnimation { duration: 50; } }
color: UM.Theme.getColor("tool_panel_background")
borderColor: UM.Theme.getColor("lining")
borderWidth: UM.Theme.getSize("default_lining").width
visible: slider.layersVisible
MouseArea //Catch all mouse events (so scene doesnt handle them)
{
anchors.fill: parent
}
TextField
{
id: valueLabel
property string maxValue: slider.maximumValue + 1
text: slider.activeHandle.value + 1
horizontalAlignment: TextInput.AlignRight;
onEditingFinished:
{
// Ensure that the cursor is at the first position. On some systems the text isn't fully visible
// Seems to have to do something with different dpi densities that QML doesn't quite handle.
// Another option would be to increase the size even further, but that gives pretty ugly results.
cursorPosition = 0;
if(valueLabel.text != '')
{
slider.activeHandle.setValue(valueLabel.text - 1);
}
}
validator: IntValidator { bottom: 1; top: slider.maximumValue + 1; }
anchors.left: parent.left;
anchors.leftMargin: UM.Theme.getSize("default_margin").width / 2;
anchors.verticalCenter: parent.verticalCenter;
width: Math.max(UM.Theme.getSize("line").width * maxValue.length + 2, 20);
style: TextFieldStyle
{
textColor: UM.Theme.getColor("setting_control_text");
font: UM.Theme.getFont("default");
background: Item { }
}
Keys.onUpPressed: slider.activeHandle.setValue(slider.activeHandle.value + ((event.modifiers & Qt.ShiftModifier) ? 10 : 1))
Keys.onDownPressed: slider.activeHandle.setValue(slider.activeHandle.value - ((event.modifiers & Qt.ShiftModifier) ? 10 : 1))
}
BusyIndicator
{
id: busyIndicator;
anchors.left: parent.right;
anchors.leftMargin: UM.Theme.getSize("default_margin").width / 2;
anchors.verticalCenter: parent.verticalCenter;
width: UM.Theme.getSize("slider_handle").height;
height: width;
running: UM.LayerView.busy;
visible: UM.LayerView.busy;
}
// make sure the slider handlers show the correct value after switching views
Component.onCompleted: {
slider.setLowerValue(UM.LayerView.minimumLayer)
slider.setUpperValue(UM.LayerView.currentLayer)
}
}
}
FontMetrics {
id: fontMetrics
font: UM.Theme.getFont("default")
}
}

Some files were not shown because too many files have changed in this diff Show More