Merge branch 'master' into feature_xmlmaterials_cura_settings

# Conflicts:
#	plugins/XmlMaterialProfile/XmlMaterialProfile.py
This commit is contained in:
fieldOfView 2017-11-16 14:01:40 +01:00
commit 185c2834d2
824 changed files with 44240 additions and 27936 deletions

8
.gitignore vendored
View file

@ -5,10 +5,12 @@ __pycache__
*.mo
docs/html
*.log
resources/i18n/en
resources/i18n/en_US
resources/i18n/en_7S
resources/i18n/x-test
resources/firmware
resources/materials
CuraEngine.exe
LC_MESSAGES
.cache
*.qmlc
@ -31,6 +33,7 @@ cura.desktop
.settings
#Externally located plug-ins.
plugins/CuraSolidWorksPlugin
plugins/Doodle3D-cura-plugin
plugins/GodMode
plugins/PostProcessingPlugin
@ -39,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
@ -54,4 +58,6 @@ cmake_install.cmake
#Debug
*.gcode
run.sh
.scannerwork/
CuraEngine

View file

@ -45,15 +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)
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
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 )

810
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.
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
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.
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 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/>.
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
-------------
@ -50,12 +52,11 @@ Third party plugins
* [X3G Writer](https://github.com/Ghostkeeper/X3GWriter): Adds support for exporting X3G files.
* [Auto orientation](https://github.com/nallath/CuraOrientationPlugin): Calculate the optimal orientation for a model.
* [OctoPrint Plugin](https://github.com/fieldofview/OctoPrintPlugin): Send printjobs directly to OctoPrint and monitor their progress in Cura.
* [WirelessPrinting Plugin](https://github.com/probonopd/WirelessPrinting): Print wirelessly from Cura to your 3D printer connected to an ESP8266 module.
* [Electric Print Cost Calculator Plugin](https://github.com/zoff99/ElectricPrintCostCalculator): Calculate the electric costs of a print.
Making profiles for other printers
----------------------------------
There are two ways of doing it. You can either use the generator [here](http://quillford.github.io/CuraProfileMaker/) or you can use [this](https://github.com/Ultimaker/Cura/blob/master/resources/definitions/ultimaker_original.def.json) as a template.
If your make of printer is not in the list of supported printers, and using the "Custom FDM Printer" does not offer enough flexibility, you can use [this](https://github.com/Ultimaker/Cura/blob/master/resources/definitions/ultimaker_original.def.json) as a template.
* Change the machine ID to something unique
* Change the machine_name to your printer's name
@ -63,12 +64,12 @@ There are two ways of doing it. You can either use the generator [here](http://q
* Set your machine's dimensions with machine_width, machine_depth, and machine_height
* If your printer's origin is in the center of the bed, set machine_center_is_zero to true.
* Set your print head dimensions with the machine_head_shape parameters
* Set the nozzle offset with machine_nozzle_offset_x and machine_nozzle_offset_y
* Set the start and end gcode in machine_start_gcode and machine_end_gcode
* If your printer has a heated bed, set visible to true under material_bed_temperature
Once you are done, put the profile you have made into resources/definitions, or in definitions in your cura profile folder.
If you want to make a definition for a multi-extrusion printer, have a look at [this](https://github.com/Ultimaker/Cura/blob/master/resources/definitions/ultimaker_original_dual.def.json) as a template, along with the two extruder definitions it references [here](https://github.com/Ultimaker/Cura/blob/master/resources/extruders/ultimaker_original_dual_1st.def.json) and [here](https://github.com/Ultimaker/Cura/blob/master/resources/extruders/ultimaker_original_dual_2nd.def.json)
Translating Cura
----------------
If you'd like to contribute a translation of Cura, please first look for [any existing translation](https://github.com/Ultimaker/Cura/tree/master/resources/i18n). If your language is already there in the source code but not in Cura's interface, it may be partially translated.

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

@ -7,9 +7,9 @@ Comment=Cura converts 3D models into paths for a 3D printer. It prepares your pr
Comment[de]=Cura wandelt 3D-Modelle in Pfade für einen 3D-Drucker um. Es bereitet Ihren Druck für maximale Genauigkeit, minimale Druckzeit und guter Zuverlässigkeit mit vielen zusätzlichen Funktionen vor, damit Ihr Druck großartig wird.
Exec=@CMAKE_INSTALL_FULL_BINDIR@/cura %F
TryExec=@CMAKE_INSTALL_FULL_BINDIR@/cura
Icon=@CMAKE_INSTALL_FULL_DATADIR@/cura/resources/images/cura-icon.png
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) 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 cura.Settings.ExtruderManager import ExtruderManager
from UM.Settings.ContainerRegistry import ContainerRegistry
@ -86,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:
@ -169,8 +178,9 @@ class BuildVolume(SceneNode):
self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "default.shader"))
self._grid_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "grid.shader"))
theme = Application.getInstance().getTheme()
self._grid_shader.setUniformValue("u_gridColor0", Color(*theme.getColor("buildplate").getRgb()))
self._grid_shader.setUniformValue("u_gridColor1", Color(*theme.getColor("buildplate_alt").getRgb()))
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)
@ -498,15 +508,19 @@ class BuildVolume(SceneNode):
self._engine_ready = True
self.rebuild()
def _onSettingPropertyChanged(self, setting_key: str, property_name: str):
if property_name != "value":
return
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 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:
@ -517,24 +531,45 @@ class BuildVolume(SceneNode):
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()
update_disallowed_areas = True
rebuild_me = True
if setting_key in self._raft_settings:
self._updateRaftThickness()
update_raft_thickness = True
rebuild_me = True
if setting_key in self._extra_z_settings:
self._updateExtraZClearance()
update_extra_z_clearance = True
rebuild_me = True
if setting_key in self._limit_to_extruder_settings:
self._updateDisallowedAreas()
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
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
@ -921,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
@ -12,8 +12,8 @@ class CameraAnimation(QVariantAnimation):
def __init__(self, parent = None):
super().__init__(parent)
self._camera_tool = None
self.setDuration(500)
self.setEasingCurve(QEasingCurve.InOutQuad)
self.setDuration(300)
self.setEasingCurve(QEasingCurve.OutQuad)
def setCameraTool(self, camera_tool):
self._camera_tool = camera_tool

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,7 +45,20 @@ fatal_exception_types = [
SystemError,
]
def show(exception_type, value, tb):
class CrashHandler:
crash_url = "https://stats.ultimaker.com/api/cura"
def __init__(self, exception_type, value, tb):
self.exception_type = exception_type
self.value = value
self.traceback = tb
self.dialog = QDialog()
# While we create the GUI, the information will be stored for sending afterwards
self.data = dict()
self.data["time_stamp"] = time.time()
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"):
@ -48,70 +71,214 @@ def show(exception_type, value, tb):
if not application:
sys.exit(1)
dialog = QDialog()
dialog.setMinimumWidth(640)
dialog.setMinimumHeight(640)
dialog.setWindowTitle(catalog.i18nc("@title:window", "Crash Report"))
self._createDialog()
layout = QVBoxLayout(dialog)
## Creates a modal dialog.
def _createDialog(self):
self.dialog.setMinimumWidth(640)
self.dialog.setMinimumHeight(640)
self.dialog.setWindowTitle(catalog.i18nc("@title:window", "Crash Report"))
#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)
layout = QVBoxLayout(self.dialog)
label = QLabel(dialog)
layout.addWidget(label)
layout.addWidget(self._messageWidget())
layout.addWidget(self._informationWidget())
layout.addWidget(self._exceptionInfoWidget())
layout.addWidget(self._logInfoWidget())
layout.addWidget(self._userDescriptionWidget())
layout.addWidget(self._buttonsWidget())
#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>
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>
"""))
textarea = QTextEdit(dialog)
layout.addWidget(textarea)
return label
def _informationWidget(self):
group = QGroupBox()
group.setTitle(catalog.i18nc("@title:groupbox", "System information"))
layout = QVBoxLayout()
label = QLabel()
try:
from UM.Application import Application
version = Application.getInstance().getVersion()
self.cura_version = Application.getInstance().getVersion()
except:
version = "Unknown"
self.cura_version = catalog.i18nc("@label unknown version of Cura", "Unknown")
trace = "".join(traceback.format_exception(exception_type, value, tb))
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)
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)
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:
data = f.read()
logdata = f.read()
msg = "-------------------------\n"
msg += data
crash_info += "\n\n" + msg
text_area.setText(logdata)
text_area.setReadOnly(True)
textarea.setText(crash_info)
layout.addWidget(text_area)
group.setLayout(layout)
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"))
self.data["log"] = logdata
dialog.exec_()
sys.exit(1)
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 = 4
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,16 +202,21 @@ 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
super().__init__(name = "cura", version = CuraVersion, buildtype = CuraBuildType)
super().__init__(name = "cura", version = CuraVersion, buildtype = CuraBuildType,
tray_icon_name = "cura-icon-32.png")
self.default_theme = "cura-light"
self.setWindowIcon(QIcon(Resources.getPath(Resources.Images, "cura-icon.png")))
self.setRequiredPlugins([
"CuraEngineBackend",
"MeshView",
"UserAgreement",
"SolidView",
"LayerView",
"STLReader",
"SelectionTool",
@ -217,7 +225,8 @@ class CuraApplication(QtApplication):
"LocalFileOutputDevice",
"TranslateTool",
"FileLogger",
"XmlMaterialProfile"
"XmlMaterialProfile",
"PluginBrowser"
])
self._physics = None
self._volume = None
@ -262,8 +271,9 @@ class CuraApplication(QtApplication):
empty_quality_container = copy.deepcopy(empty_container)
empty_quality_container._id = "empty_quality"
empty_quality_container.setName("Not Supported")
empty_quality_container.addMetaDataEntry("quality_type", "normal")
empty_quality_container.addMetaDataEntry("quality_type", "not_supported")
empty_quality_container.addMetaDataEntry("type", "quality")
empty_quality_container.addMetaDataEntry("supported", False)
ContainerRegistry.getInstance().addContainer(empty_quality_container)
empty_quality_changes_container = copy.deepcopy(empty_container)
empty_quality_changes_container._id = "empty_quality_changes"
@ -295,6 +305,8 @@ class CuraApplication(QtApplication):
preferences.addPreference("view/invert_zoom", False)
self._need_to_show_user_agreement = not Preferences.getInstance().getValue("general/accepted_user_agreement")
for key in [
"dialog_load_path", # dialog_save_path is in LocalFileOutputDevicePlugin
"dialog_profile_path",
@ -367,6 +379,14 @@ class CuraApplication(QtApplication):
def _onEngineCreated(self):
self._engine.addImageProvider("camera", CameraImageProvider.CameraImageProvider())
@pyqtProperty(bool)
def needToShowUserAgreement(self):
return self._need_to_show_user_agreement
def setNeedToShowUserAgreement(self, set_value = True):
self._need_to_show_user_agreement = set_value
## The "Quit" button click event handler.
@pyqtSlot()
def closeApplication(self):
@ -385,6 +405,7 @@ class CuraApplication(QtApplication):
showDiscardOrKeepProfileChanges = pyqtSignal()
def discardOrKeepProfileChanges(self):
has_user_interaction = False
choice = Preferences.getInstance().getValue("cura/choice_on_profile_override")
if choice == "always_discard":
# don't show dialog and DISCARD the profile
@ -395,6 +416,10 @@ class CuraApplication(QtApplication):
else:
# ALWAYS ask whether to keep or discard the profile
self.showDiscardOrKeepProfileChanges.emit()
has_user_interaction = True
return has_user_interaction
onDiscardOrKeepProfileChangesClosed = pyqtSignal() # Used to notify other managers that the dialog was closed
@pyqtSlot(str)
def discardOrKeepProfileChangesClosed(self, option):
@ -402,9 +427,25 @@ class CuraApplication(QtApplication):
global_stack = self.getGlobalContainerStack()
for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
extruder.getTop().clear()
global_stack.getTop().clear()
# if the user decided to keep settings then the user settings should be re-calculated and validated for errors
# before slicing. To ensure that slicer uses right settings values
elif option == "keep":
global_stack = self.getGlobalContainerStack()
for extruder in ExtruderManager.getInstance().getMachineExtruders(global_stack.getId()):
user_extruder_container = extruder.getTop()
if user_extruder_container:
user_extruder_container.update()
user_global_container = global_stack.getTop()
if user_global_container:
user_global_container.update()
# notify listeners that quality has changed (after user selected discard or keep)
self.onDiscardOrKeepProfileChangesClosed.emit()
self.getMachineManager().activeQualityChanged.emit()
@pyqtSlot(int)
def messageBoxClosed(self, button):
if self._message_box_callback:
@ -521,6 +562,7 @@ class CuraApplication(QtApplication):
super().addCommandLineOptions(parser)
parser.add_argument("file", nargs="*", help="Files to load after starting the application.")
parser.add_argument("--single-instance", action="store_true", default=False)
parser.add_argument("--headless", action = "store_true", default=False)
# Set up a local socket server which listener which coordinates single instances Curas and accepts commands.
def _setUpSingleInstanceServer(self):
@ -663,17 +705,22 @@ class CuraApplication(QtApplication):
qmlRegisterSingletonType(MaterialManager, "Cura", 1, 0, "MaterialManager", self.getMaterialManager)
qmlRegisterSingletonType(SettingInheritanceManager, "Cura", 1, 0, "SettingInheritanceManager",
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"))
self._qml_import_paths.append(Resources.getPath(self.ResourceTypes.QmlFiles))
run_headless = self.getCommandLineOption("headless", False)
if not run_headless:
self.initializeEngine()
if self._engine.rootObjects:
if run_headless or self._engine.rootObjects:
self.closeSplash()
for file in self.getCommandLineOption("file", []):
self._openFile(file)
for file_name in self.getCommandLineOption("file", []):
self._openFile(file_name)
for file_name in self._open_file_queue: #Open all the files that were queued up while plug-ins were loading.
self._openFile(file_name)
@ -702,6 +749,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:
@ -1179,6 +1231,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()
@ -1214,6 +1267,9 @@ class CuraApplication(QtApplication):
# see GroupDecorator._onChildrenChanged
def _createSplashScreen(self):
run_headless = self.getCommandLineOption("headless", False)
if run_headless:
return None
return CuraSplashScreen.CuraSplashScreen()
def _onActiveMachineChanged(self):
@ -1289,7 +1345,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
@ -1298,7 +1354,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
@ -1354,6 +1410,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
# draw version text
font = QFont() # Using system-default font here
font.setPointSize(20)
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

57
cura/PreviewPass.py Normal file
View file

@ -0,0 +1,57 @@
# Copyright (c) 2017 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
from UM.Application import Application
from UM.Resources import Resources
from UM.View.RenderPass import RenderPass
from UM.View.GL.OpenGL import OpenGL
from UM.View.RenderBatch import RenderBatch
from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
from typing import Optional
MYPY = False
if MYPY:
from UM.Scene.Camera import Camera
## A render pass subclass that renders slicable objects with default parameters.
# It uses the active camera by default, but it can be overridden to use a different camera.
#
# This is useful to get a preview image of a scene taken from a different location as the active camera.
class PreviewPass(RenderPass):
def __init__(self, width: int, height: int):
super().__init__("preview", width, height, 0)
self._camera = None # type: Optional[Camera]
self._renderer = Application.getInstance().getRenderer()
self._shader = None
self._scene = Application.getInstance().getController().getScene()
# Set the camera to be used by this render pass
# if it's None, the active camera is used
def setCamera(self, camera: Optional["Camera"]):
self._camera = camera
def render(self) -> None:
if not self._shader:
self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "object.shader"))
# Create a new batch to be rendered
batch = RenderBatch(self._shader)
# Fill up the batch with objects that can be sliced. `
for node in DepthFirstIterator(self._scene.getRoot()):
if node.callDecoration("isSliceable") and node.getMeshData() and node.isVisible():
batch.addItem(node.getWorldTransformation(), node.getMeshData())
self.bind()
if self._camera is None:
batch.render(Application.getInstance().getController().getScene().getActiveCamera())
else:
batch.render(self._camera)
self.release()

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,24 +51,12 @@ 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 = []
self._material_costs = []
self._material_names = []
self._pre_sliced = False
@ -76,12 +64,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 +80,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 +122,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 +140,34 @@ 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)
materialNamesChanged = pyqtSignal()
@pyqtProperty("QVariantList", notify = materialNamesChanged)
def materialNames(self):
return self._material_names
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
@ -153,6 +177,7 @@ class PrintInformation(QObject):
self._material_lengths = []
self._material_weights = []
self._material_costs = []
self._material_names = []
material_preference_values = json.loads(Preferences.getInstance().getValue("cura/material_settings"))
@ -171,8 +196,10 @@ class PrintInformation(QObject):
weight = float(amount) * float(density) / 1000
cost = 0
material_name = catalog.i18nc("@label unknown material", "Unknown")
if material:
material_guid = material.getMetaDataEntry("GUID")
material_name = material.getName()
if material_guid in material_preference_values:
material_values = material_preference_values[material_guid]
@ -191,10 +218,12 @@ class PrintInformation(QObject):
self._material_weights.append(weight)
self._material_lengths.append(length)
self._material_costs.append(cost)
self._material_names.append(material_name)
self.materialLengthsChanged.emit()
self.materialWeightsChanged.emit()
self.materialCostsChanged.emit()
self.materialNamesChanged.emit()
def _onPreferencesChanged(self, preference):
if preference != "cura/material_settings":
@ -221,37 +250,63 @@ 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)
# 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]
if self._job_name != name:
self._job_name = name
self.jobNameChanged.emit()
@pyqtSlot(str)
def setProjectName(self, name):
self._project_name = name
self.setJobName(name)
jobNameChanged = pyqtSignal()
@pyqtProperty(str, notify = jobNameChanged)
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:
return base_name
self._job_name = self._abbr_machine + "_" + base_name
else:
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
@ -270,10 +325,34 @@ class PrintInformation(QObject):
elif word.isdigit():
abbr_machine += word
else:
abbr_machine += self._stripAccents(word.strip("()[]{}#").upper())[0]
stripped_word = self._stripAccents(word.strip("()[]{}#").upper())
# - use only the first character if the word is too long (> 3 characters)
# - use the whole word if it's not too long (<= 3 characters)
if len(stripped_word) > 3:
stripped_word = stripped_word[0]
abbr_machine += stripped_word
self._abbr_machine = abbr_machine
## 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')
@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
@ -71,6 +71,10 @@ class PrinterOutputDevice(QObject, OutputDevice):
self._control_item = None
self._qml_context = None
self._can_pause = True
self._can_abort = True
self._can_pre_heat_bed = True
self._can_control_manually = True
def requestWrite(self, nodes, file_name = None, filter_by_machine = False, file_handler = None):
raise NotImplementedError("requestWrite needs to be implemented")
@ -126,6 +130,26 @@ class PrinterOutputDevice(QObject, OutputDevice):
# Signal to be emitted when some drastic change occurs in the remaining time (not when the time just passes on normally).
preheatBedRemainingTimeChanged = pyqtSignal()
# Does the printer support pre-heating the bed at all
@pyqtProperty(bool, constant=True)
def canPreHeatBed(self):
return self._can_pre_heat_bed
# Does the printer support pause at all
@pyqtProperty(bool, constant=True)
def canPause(self):
return self._can_pause
# Does the printer support abort at all
@pyqtProperty(bool, constant=True)
def canAbort(self):
return self._can_abort
# Does the printer support manual control at all
@pyqtProperty(bool, constant=True)
def canControlManually(self):
return self._can_control_manually
@pyqtProperty(QObject, constant=True)
def monitorItem(self):
# Note that we specifically only check if the monitor component is created.
@ -144,6 +168,9 @@ class PrinterOutputDevice(QObject, OutputDevice):
return self._control_item
def _createControlViewFromQML(self):
if not self._control_view_qml_path:
return
path = QUrl.fromLocalFile(self._control_view_qml_path)
# Because of garbage collection we need to keep this referenced by python.
@ -160,6 +187,8 @@ class PrinterOutputDevice(QObject, OutputDevice):
Logger.log("e", "QQmlComponent error string %s", self._control_component.errorString())
def _createMonitorViewFromQML(self):
if not self._monitor_view_qml_path:
return
path = QUrl.fromLocalFile(self._monitor_view_qml_path)
# Because of garbage collection we need to keep this referenced by python.
@ -612,7 +641,7 @@ class PrinterOutputDevice(QObject, OutputDevice):
@pyqtSlot("long")
@pyqtSlot("long", "long")
def setHeadZ(self, z, speed = 3000):
self._setHeadY(z, speed)
self._setHeadZ(z, speed)
## Move the head of the printer.
# Note that this is a relative move. If you want to move the head to a specific position you can use

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.intersection_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.
@ -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
@ -169,12 +178,25 @@ class QualityManager:
def findAllUsableQualitiesForMachineAndExtruders(self, global_container_stack: "GlobalStack", extruder_stacks: List["ExtruderStack"]) -> List[InstanceContainer]:
global_machine_definition = global_container_stack.getBottom()
machine_manager = Application.getInstance().getMachineManager()
active_stack_id = machine_manager.activeStackId
materials = []
# TODO: fix this
if extruder_stacks:
# Multi-extruder machine detected.
materials = [stack.material for stack in extruder_stacks]
# Multi-extruder machine detected
for stack in extruder_stacks:
if stack.getId() == active_stack_id and machine_manager.newMaterial:
materials.append(machine_manager.newMaterial)
else:
# Machine with one extruder.
materials = [global_container_stack.material]
materials.append(stack.material)
else:
# Machine with one extruder
if global_container_stack.getId() == active_stack_id and machine_manager.newMaterial:
materials.append(machine_manager.newMaterial)
else:
materials.append(global_container_stack.material)
quality_types = self.findAllQualityTypesForMachineAndMaterials(global_machine_definition, materials)
@ -233,13 +255,16 @@ class QualityManager:
filter_by_material = False
machine_definition = self.getParentMachineDefinition(machine_definition)
criteria["definition"] = machine_definition.getId()
found_containers_with_machine_definition = ContainerRegistry.getInstance().findInstanceContainers(**criteria)
whole_machine_definition = self.getWholeMachineDefinition(machine_definition)
if whole_machine_definition.getMetaDataEntry("has_machine_quality"):
definition_id = machine_definition.getMetaDataEntry("quality_definition", whole_machine_definition.getId())
criteria["definition"] = definition_id
filter_by_material = whole_machine_definition.getMetaDataEntry("has_materials")
else:
# only fall back to "fdmprinter" when there is no container for this machine
elif not found_containers_with_machine_definition:
criteria["definition"] = "fdmprinter"
# Stick the material IDs in a set

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
@ -333,16 +333,15 @@ class ContainerManager(QObject):
@pyqtSlot(str, result = bool)
def isContainerUsed(self, container_id):
Logger.log("d", "Checking if container %s is currently used", container_id)
# check if this is a material container. If so, check if any material with the same GUID is being used by any
# check if this is a material container. If so, check if any material with the same base is being used by any
# stacks.
container_ids_to_check = [container_id]
container_results = self._container_registry.findInstanceContainers(id = container_id, type = "material")
if container_results:
this_container = container_results[0]
container_guid = this_container.getMetaDataEntry("GUID")
# check all material container IDs with the same GUID
material_containers = self._container_registry.findInstanceContainers(id = container_id,
GUID = container_guid,
material_base_file = this_container.getMetaDataEntry("base_file", this_container.getId())
# check all material container IDs with the same base
material_containers = self._container_registry.findInstanceContainers(base_file = material_base_file,
type = "material")
if material_containers:
container_ids_to_check = [container.getId() for container in material_containers]
@ -430,7 +429,7 @@ class ContainerManager(QObject):
if not Platform.isWindows():
if os.path.exists(file_url):
result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"),
catalog.i18nc("@label", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?").format(file_url))
catalog.i18nc("@label Don't translate the XML tag <filename>!", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?").format(file_url))
if result == QMessageBox.No:
return { "status": "cancelled", "message": "User cancelled"}

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
@ -110,7 +110,7 @@ class CuraContainerRegistry(ContainerRegistry):
if not Platform.isWindows():
if os.path.exists(file_name):
result = QMessageBox.question(None, catalog.i18nc("@title:window", "File Already Exists"),
catalog.i18nc("@label", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?").format(file_name))
catalog.i18nc("@label Don't translate the XML tag <filename>!", "The file <filename>{0}</filename> already exists. Are you sure you want to overwrite it?").format(file_name))
if result == QMessageBox.No:
return
found_containers = []
@ -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", "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", "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", "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
@ -174,7 +179,7 @@ class CuraContainerRegistry(ContainerRegistry):
def importProfile(self, file_name):
Logger.log("d", "Attempting to import profile %s", file_name)
if not file_name:
return { "status": "error", "message": catalog.i18nc("@info:status", "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>", file_name, "Invalid path")}
return { "status": "error", "message": catalog.i18nc("@info:status Don't translate the XML tags <filename> or <message>!", "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>", file_name, "Invalid path")}
plugin_registry = PluginRegistry.getInstance()
extension = file_name.split(".")[-1]
@ -196,7 +201,7 @@ class CuraContainerRegistry(ContainerRegistry):
except Exception as e:
# Note that this will fail quickly. That is, if any profile reader throws an exception, it will stop reading. It will only continue reading if the reader returned None.
Logger.log("e", "Failed to import profile from %s: %s while using profile reader. Got exception %s", file_name,profile_reader.getPluginId(), str(e))
return { "status": "error", "message": catalog.i18nc("@info:status", "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>", file_name, str(e))}
return { "status": "error", "message": catalog.i18nc("@info:status Don't translate the XML tags <filename> or <message>!", "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>", file_name, str(e))}
if profile_or_list: # Success!
name_seed = os.path.splitext(os.path.basename(file_name))[0]
new_name = self.uniqueName(name_seed)
@ -205,7 +210,7 @@ class CuraContainerRegistry(ContainerRegistry):
result = self._configureProfile(profile, name_seed, new_name)
if result is not None:
return {"status": "error", "message": catalog.i18nc("@info:status", "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>", file_name, result)}
return {"status": "error", "message": catalog.i18nc("@info:status Don't translate the XML tags <filename> or <message>!", "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>", file_name, result)}
return {"status": "ok", "message": catalog.i18nc("@info:status", "Successfully imported profile {0}", profile.getName())}
else:
@ -239,7 +244,7 @@ class CuraContainerRegistry(ContainerRegistry):
result = self._configureProfile(profile, profile_id, new_name)
if result is not None:
return {"status": "error", "message": catalog.i18nc("@info:status", "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>", file_name, result)}
return {"status": "error", "message": catalog.i18nc("@info:status Don't translate the XML tags <filename> or <message>!", "Failed to import profile from <filename>{0}</filename>: <message>{1}</message>", file_name, result)}
profile_index += 1
@ -298,6 +303,9 @@ class CuraContainerRegistry(ContainerRegistry):
if "material" in quality_type_criteria:
materials = ContainerRegistry.getInstance().findInstanceContainers(id = quality_type_criteria["material"])
del quality_type_criteria["material"]
# Do not filter quality containers here with materials because we are trying to import a profile, so it should
# NOT be restricted by the active materials on the current machine.
materials = None
# Check to make sure the imported profile actually makes sense in context of the current configuration.
# This prevents issues where importing a "draft" profile for a machine without "draft" qualities would report as

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
@ -432,6 +432,7 @@ class CuraContainerStack(ContainerStack):
# - If the machine definition has a metadata entry "has_machine_materials", the definition of the material should
# be the same as the machine definition for this stack. Otherwise, the definition should be "fdmprinter".
# - The container should have a metadata entry "type" with value "material".
# - The material should have an approximate diameter that matches the machine
# - If the machine definition has a metadata entry "has_variants" and set to True, the "variant" metadata entry of
# the material should be the same as the ID of the variant in the stack. Only applies if "has_machine_materials" is also True.
# - If the stack currently has a material set, try to find a material that matches the current material by name.
@ -460,6 +461,9 @@ class CuraContainerStack(ContainerStack):
if preferred_material:
search_criteria["id"] = preferred_material
approximate_material_diameter = str(round(self.getProperty("material_diameter", "value")))
search_criteria["approximate_diameter"] = approximate_material_diameter
materials = ContainerRegistry.getInstance().findInstanceContainers(**search_criteria)
if not materials:
Logger.log("w", "The preferred material \"{material}\" could not be found for stack {stack}", material = preferred_material, stack = self.id)

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:
@ -445,28 +450,18 @@ class ExtruderManager(QObject):
support_roof_enabled |= stack_to_use.getProperty("support_roof_enable", "value")
# Check limit to extruders
limit_to_extruder_feature_list = ["wall_extruder_nr",
"wall_0_extruder_nr",
limit_to_extruder_feature_list = ["wall_0_extruder_nr",
"wall_x_extruder_nr",
"roofing_extruder_nr",
"top_bottom_extruder_nr",
"infill_extruder_nr",
]
wall_extruder_nr = None
for extruder_nr_feature_name in limit_to_extruder_feature_list:
extruder_nr = int(global_stack.getProperty(extruder_nr_feature_name, "value"))
if extruder_nr == -1:
# outer and inner wall extruder numbers should first inherit from the wall extruder number
if extruder_nr_feature_name in ["wall_0_extruder_nr", "wall_x_extruder_nr"]:
extruder_nr = wall_extruder_nr
else:
extruder_nr = 0
continue
used_extruder_stack_ids.add(self.extruderIds[str(extruder_nr)])
if extruder_nr_feature_name == "wall_extruder_nr":
wall_extruder_nr = extruder_nr
# Check support extruders
if support_enabled:
used_extruder_stack_ids.add(self.extruderIds[str(global_stack.getProperty("support_infill_extruder_nr", "value"))])
@ -516,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()
@ -576,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
@ -609,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.
@ -622,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
@ -7,7 +7,7 @@ from UM.Decorators import override
from UM.MimeTypeDatabase import MimeType, MimeTypeDatabase
from UM.Settings.ContainerStack import ContainerStack
from UM.Settings.ContainerRegistry import ContainerRegistry
from UM.Settings.Interfaces import ContainerInterface
from UM.Settings.Interfaces import ContainerInterface, PropertyEvaluationContext
from . import Exceptions
from .CuraContainerStack import CuraContainerStack
@ -57,21 +57,32 @@ class ExtruderStack(CuraContainerStack):
# \throws Exceptions.NoGlobalStackError Raised when trying to get a property from an extruder without
# having a next stack set.
@override(ContainerStack)
def getProperty(self, key: str, property_name: str) -> Any:
def getProperty(self, key: str, property_name: str, context: Optional[PropertyEvaluationContext] = None) -> Any:
if not self._next_stack:
raise Exceptions.NoGlobalStackError("Extruder {id} is missing the next stack!".format(id = self.id))
if not super().getProperty(key, "settable_per_extruder"):
return self.getNextStack().getProperty(key, property_name)
if context is None:
context = PropertyEvaluationContext()
context.pushContainer(self)
limit_to_extruder = super().getProperty(key, "limit_to_extruder")
if (limit_to_extruder is not None and limit_to_extruder != "-1") and self.getMetaDataEntry("position") != str(limit_to_extruder):
if str(limit_to_extruder) in self.getNextStack().extruders:
result = self.getNextStack().extruders[str(limit_to_extruder)].getProperty(key, property_name)
if result is not None:
if not super().getProperty(key, "settable_per_extruder", context):
result = self.getNextStack().getProperty(key, property_name, context)
context.popContainer()
return result
return super().getProperty(key, property_name)
limit_to_extruder = super().getProperty(key, "limit_to_extruder", context)
if limit_to_extruder is not None:
limit_to_extruder = str(limit_to_extruder)
if (limit_to_extruder is not None and limit_to_extruder != "-1") and self.getMetaDataEntry("position") != str(limit_to_extruder):
if str(limit_to_extruder) in self.getNextStack().extruders:
result = self.getNextStack().extruders[str(limit_to_extruder)].getProperty(key, property_name, context)
if result is not None:
context.popContainer()
return result
result = super().getProperty(key, property_name, context)
context.popContainer()
return result
@override(CuraContainerStack)
def _getMachineDefinition(self) -> ContainerInterface:

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
@ -11,6 +11,7 @@ from UM.MimeTypeDatabase import MimeType, MimeTypeDatabase
from UM.Settings.ContainerStack import ContainerStack
from UM.Settings.SettingInstance import InstanceState
from UM.Settings.ContainerRegistry import ContainerRegistry
from UM.Settings.Interfaces import PropertyEvaluationContext
from UM.Logger import Logger
from . import Exceptions
@ -61,8 +62,10 @@ class GlobalStack(CuraContainerStack):
# already have the maximum number of extruders.
def addExtruder(self, extruder: ContainerStack) -> None:
extruder_count = self.getProperty("machine_extruder_count", "value")
if extruder_count and len(self._extruders) + 1 > extruder_count:
Logger.log("w", "Adding extruder {meta} to {id} but its extruder count is {count}".format(id = self.id, count = extruder_count, meta = str(extruder.getMetaData())))
if extruder_count <= 1:
Logger.log("i", "Not adding extruder[%s] to [%s] because it is a single-extrusion machine.",
extruder.id, self.id)
return
position = extruder.getMetaDataEntry("position")
@ -73,7 +76,9 @@ class GlobalStack(CuraContainerStack):
if any(item.getId() == extruder.id for item in self._extruders.values()):
Logger.log("w", "Extruder [%s] has already been added to this stack [%s]", extruder.id, self._id)
return
self._extruders[position] = extruder
Logger.log("i", "Extruder[%s] added to [%s] at position [%s]", extruder.id, self.id, position)
## Overridden from ContainerStack
#
@ -87,29 +92,38 @@ class GlobalStack(CuraContainerStack):
#
# \return The value of the property for the specified setting, or None if not found.
@override(ContainerStack)
def getProperty(self, key: str, property_name: str) -> Any:
def getProperty(self, key: str, property_name: str, context: Optional[PropertyEvaluationContext] = None) -> Any:
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")
resolve = super().getProperty(key, "resolve", context)
self._resolving_settings.remove(key)
if resolve is not None:
return resolve
# Handle the "limit_to_extruder" property.
limit_to_extruder = super().getProperty(key, "limit_to_extruder")
limit_to_extruder = super().getProperty(key, "limit_to_extruder", context)
if limit_to_extruder is not None:
limit_to_extruder = str(limit_to_extruder)
if limit_to_extruder is not None and limit_to_extruder != "-1" and limit_to_extruder in self._extruders:
if super().getProperty(key, "settable_per_extruder"):
result = self._extruders[str(limit_to_extruder)].getProperty(key, property_name)
if super().getProperty(key, "settable_per_extruder", context):
result = self._extruders[str(limit_to_extruder)].getProperty(key, property_name, context)
if result is not None:
context.popContainer()
return result
else:
Logger.log("e", "Setting {setting} has limit_to_extruder but is not settable per extruder!", setting = key)
return super().getProperty(key, property_name)
result = super().getProperty(key, property_name, context)
context.popContainer()
return result
## Overridden from ContainerStack
#
@ -137,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
@ -149,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):
@ -46,6 +47,11 @@ class MachineManager(QObject):
self._active_container_stack = None # type: CuraContainerStack
self._global_container_stack = None # type: GlobalStack
# Used to store the new containers until after confirming the dialog
self._new_variant_container = None
self._new_material_container = None
self._new_quality_containers = []
self._error_check_timer = QTimer()
self._error_check_timer.setInterval(250)
self._error_check_timer.setSingleShot(True)
@ -57,6 +63,7 @@ class MachineManager(QObject):
self._instance_container_timer.timeout.connect(self.__onInstanceContainersChanged)
Application.getInstance().globalContainerStackChanged.connect(self._onGlobalContainerChanged)
## When the global container is changed, active material probably needs to be updated.
self.globalContainerChanged.connect(self.activeMaterialChanged)
self.globalContainerChanged.connect(self.activeVariantChanged)
@ -64,10 +71,10 @@ class MachineManager(QObject):
self._stacks_have_errors = None
self._empty_variant_container = ContainerRegistry.getInstance().getEmptyInstanceContainer()
self._empty_material_container = ContainerRegistry.getInstance().getEmptyInstanceContainer()
self._empty_quality_container = ContainerRegistry.getInstance().getEmptyInstanceContainer()
self._empty_quality_changes_container = ContainerRegistry.getInstance().getEmptyInstanceContainer()
self._empty_variant_container = ContainerRegistry.getInstance().findContainers(id = "empty_variant")[0]
self._empty_material_container = ContainerRegistry.getInstance().findContainers(id = "empty_material")[0]
self._empty_quality_container = ContainerRegistry.getInstance().findContainers(id = "empty_quality")[0]
self._empty_quality_changes_container = ContainerRegistry.getInstance().findContainers(id = "empty_quality_changes")[0]
self._onGlobalContainerChanged()
@ -83,6 +90,9 @@ class MachineManager(QObject):
ExtruderManager.getInstance().activeExtruderChanged.connect(self.activeStackChanged)
self.activeStackChanged.connect(self.activeStackValueChanged)
# when a user closed dialog check if any delayed material or variant changes need to be applied
Application.getInstance().onDiscardOrKeepProfileChangesClosed.connect(self._executeDelayedActiveContainerStackChanges)
Preferences.getInstance().addPreference("cura/active_machine", "")
self._global_event_keys = set()
@ -105,7 +115,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()
@ -137,6 +148,14 @@ class MachineManager(QObject):
self.outputDevicesChanged.emit()
@property
def newVariant(self):
return self._new_variant_container
@property
def newMaterial(self):
return self._new_material_container
@pyqtProperty("QVariantList", notify = outputDevicesChanged)
def printerOutputDevices(self):
return self._printer_output_devices
@ -267,7 +286,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 +317,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.
@ -328,6 +350,7 @@ class MachineManager(QObject):
self.activeQualityChanged.emit()
self.activeVariantChanged.emit()
self.activeMaterialChanged.emit()
self._updateStacksHaveErrors() # Prevents unwanted re-slices after changing machine
self._error_check_timer.start()
def _onInstanceContainersChanged(self, container):
@ -344,15 +367,20 @@ class MachineManager(QObject):
@pyqtSlot(str)
def setActiveMachine(self, stack_id: str) -> None:
self.blurSettings.emit() # Ensure no-one has focus.
self._cancelDelayedActiveContainerStackChanges()
containers = ContainerRegistry.getInstance().findContainerStacks(id = stack_id)
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 +393,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 +417,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 +432,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 +477,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 +502,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,31 +522,23 @@ 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())
return result
@pyqtProperty("QVariantList", notify = activeVariantChanged)
def activeMaterialIds(self):
result = []
if ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks() is not None:
for stack in ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
if stack.variant and stack.variant != self._empty_variant_container:
result.append(stack.variant.getId())
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())
@ -534,13 +554,11 @@ 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 = {}
for stack in ExtruderManager.getInstance().getActiveGlobalAndExtruderStacks():
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
@ -549,18 +567,22 @@ class MachineManager(QObject):
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():
result[self._global_container_stack.getId()] = self._global_container_stack.material.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
@ -659,6 +681,23 @@ class MachineManager(QObject):
return Util.parseBool(quality.getMetaDataEntry("supported", True))
return False
## Returns whether there is anything unsupported in the current set-up.
#
# The current set-up signifies the global stack and all extruder stacks,
# so this indicates whether there is any container in any of the container
# stacks that is not marked as supported.
@pyqtProperty(bool, notify = activeQualityChanged)
def isCurrentSetupSupported(self) -> bool:
if not self._global_container_stack:
return False
for stack in [self._global_container_stack] + list(self._global_container_stack.extruders.values()):
for container in stack.getContainers():
if not container:
return False
if not Util.parseBool(container.getMetaDataEntry("supported", True)):
return False
return True
## Get the Quality ID associated with the currently active extruder
# Note that this only returns the "quality", not the "quality_changes"
# \returns QualityID (string) if found, empty string otherwise
@ -728,7 +767,7 @@ class MachineManager(QObject):
self.blurSettings.emit()
old_material.nameChanged.disconnect(self._onMaterialNameChanged)
self._active_container_stack.material = material_container
self._new_material_container = material_container # self._active_container_stack will be updated with a delay
Logger.log("d", "Active material changed")
material_container.nameChanged.connect(self._onMaterialNameChanged)
@ -782,13 +821,13 @@ class MachineManager(QObject):
old_material = self._active_container_stack.material
if old_variant:
self.blurSettings.emit()
self._active_container_stack.variant = containers[0]
self._new_variant_container = containers[0] # self._active_container_stack will be updated with a delay
Logger.log("d", "Active variant changed to {active_variant_id}".format(active_variant_id = containers[0].getId()))
preferred_material_name = None
if old_material:
preferred_material_name = old_material.getName()
self.setActiveMaterial(self._updateMaterialContainer(self._global_container_stack.getBottom(), self._global_container_stack, containers[0], preferred_material_name).id)
preferred_material_id = self._updateMaterialContainer(self._global_container_stack.getBottom(), self._global_container_stack, containers[0], preferred_material_name).id
self.setActiveMaterial(preferred_material_id)
else:
Logger.log("w", "While trying to set the active variant, no variant was found to replace.")
@ -803,8 +842,6 @@ class MachineManager(QObject):
if not containers or not self._global_container_stack:
return
Logger.log("d", "Attempting to change the active quality to %s", quality_id)
# Quality profile come in two flavours: type=quality and type=quality_changes
# If we found a quality_changes profile then look up its parent quality profile.
container_type = containers[0].getMetaDataEntry("type")
@ -824,37 +861,86 @@ class MachineManager(QObject):
if new_quality_settings_list is None:
return
name_changed_connect_stacks = [] # Connect these stacks to the name changed callback
# check if any of the stacks have a not supported profile
# if that is the case, all stacks should have a not supported state (otherwise it will show quality_type normal)
has_not_supported_quality = False
# check all stacks for not supported
for setting_info in new_quality_settings_list:
if setting_info["quality"].getMetaDataEntry("quality_type") == "not_supported":
has_not_supported_quality = True
break
# set all stacks to not supported if that's the case
if has_not_supported_quality:
for setting_info in new_quality_settings_list:
setting_info["quality"] = self._empty_quality_container
self._new_quality_containers.clear()
# store the upcoming quality profile changes per stack for later execution
# this prevents re-slicing before the user has made a choice in the discard or keep dialog
# (see _executeDelayedActiveContainerStackChanges)
for setting_info in new_quality_settings_list:
stack = setting_info["stack"]
stack_quality = setting_info["quality"]
stack_quality_changes = setting_info["quality_changes"]
name_changed_connect_stacks.append(stack_quality)
name_changed_connect_stacks.append(stack_quality_changes)
self._replaceQualityOrQualityChangesInStack(stack, stack_quality, postpone_emit=True)
self._replaceQualityOrQualityChangesInStack(stack, stack_quality_changes, postpone_emit=True)
self._new_quality_containers.append({
"stack": stack,
"quality": stack_quality,
"quality_changes": stack_quality_changes
})
# Send emits that are postponed in replaceContainer.
# Here the stacks are finished replacing and every value can be resolved based on the current state.
for setting_info in new_quality_settings_list:
setting_info["stack"].sendPostponedEmits()
# Connect to onQualityNameChanged
for stack in name_changed_connect_stacks:
stack.nameChanged.connect(self._onQualityNameChanged)
has_user_interaction = False
if self.hasUserSettings and Preferences.getInstance().getValue("cura/active_mode") == 1:
self._askUserToKeepOrClearCurrentSettings()
# Show the keep/discard user settings dialog
has_user_interaction = Application.getInstance().discardOrKeepProfileChanges()
self.activeQualityChanged.emit()
# If there is no interaction with the user (it means the dialog showing "keep" or "discard" was not shown)
# because either there are not user changes or because the used already decided to always keep or discard,
# then the quality instance container is replaced, in which case, the activeQualityChanged signal is emitted.
if not has_user_interaction:
self._executeDelayedActiveContainerStackChanges()
## Used to update material and variant in the active container stack with a delay.
# This delay prevents the stack from triggering a lot of signals (eventually resulting in slicing)
# before the user decided to keep or discard any of their changes using the dialog.
# The Application.onDiscardOrKeepProfileChangesClosed signal triggers this method.
def _executeDelayedActiveContainerStackChanges(self):
if self._new_variant_container is not None:
self._active_container_stack.variant = self._new_variant_container
self._new_variant_container = None
if self._new_material_container is not None:
self._active_container_stack.material = self._new_material_container
self._new_material_container = None
# apply the new quality to all stacks
if self._new_quality_containers:
for new_quality in self._new_quality_containers:
self._replaceQualityOrQualityChangesInStack(new_quality["stack"], new_quality["quality"], postpone_emit = True)
self._replaceQualityOrQualityChangesInStack(new_quality["stack"], new_quality["quality_changes"], postpone_emit = True)
for new_quality in self._new_quality_containers:
new_quality["stack"].nameChanged.connect(self._onQualityNameChanged)
new_quality["stack"].sendPostponedEmits() # Send the signals that were postponed in _replaceQualityOrQualityChangesInStack
self._new_quality_containers.clear()
## Cancel set changes for material and variant in the active container stack.
# Used for ignoring any changes when switching between printers (setActiveMachine)
def _cancelDelayedActiveContainerStackChanges(self):
self._new_material_container = None
self._new_variant_container = None
## Determine the quality and quality changes settings for the current machine for a quality name.
#
# \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
@ -871,8 +957,14 @@ class MachineManager(QObject):
for stack in stacks:
material = stack.material
# TODO: fix this
if self._new_material_container and stack.getId() == self._active_container_stack.getId():
material = self._new_material_container
quality = quality_manager.findQualityByQualityType(quality_type, global_machine_definition, [material])
if not quality: #No quality profile is found for this quality type.
if not quality:
# No quality profile is found for this quality type.
quality = self._empty_quality_container
result.append({"stack": stack, "quality": quality, "quality_changes": empty_quality_changes})
@ -891,7 +983,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()
@ -907,8 +999,12 @@ class MachineManager(QObject):
else:
Logger.log("e", "Could not find the global quality changes container with name %s", quality_changes_name)
return None
material = global_container_stack.material
if self._new_material_container and self._active_container_stack.getId() == global_container_stack.getId():
material = self._new_material_container
# For the global stack, find a quality which matches the quality_type in
# the quality changes profile and also satisfies any material constraints.
quality_type = global_quality_changes.getMetaDataEntry("quality_type")
@ -935,6 +1031,10 @@ class MachineManager(QObject):
quality_changes = self._empty_quality_changes_container
material = stack.material
if self._new_material_container and self._active_container_stack.getId() == stack.getId():
material = self._new_material_container
quality = quality_manager.findQualityByQualityType(quality_type, global_machine_definition, [material])
if not quality: #No quality profile found for this quality type.
quality = self._empty_quality_container
@ -957,7 +1057,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.
@ -966,9 +1066,6 @@ class MachineManager(QObject):
stack.qualityChanges.nameChanged.connect(self._onQualityNameChanged)
self._onQualityNameChanged()
def _askUserToKeepOrClearCurrentSettings(self):
Application.getInstance().discardOrKeepProfileChanges()
@pyqtProperty(str, notify = activeVariantChanged)
def activeVariantName(self) -> str:
if self._active_container_stack:
@ -1075,7 +1172,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)
@ -1128,7 +1225,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
@ -1174,7 +1271,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

@ -0,0 +1,65 @@
from typing import Any, Optional
from UM.Application import Application
from UM.Decorators import override
from UM.Settings.Interfaces import PropertyEvaluationContext
from UM.Settings.ContainerStack import ContainerStack
from UM.Settings.SettingInstance import InstanceState
class PerObjectContainerStack(ContainerStack):
@override(ContainerStack)
def getProperty(self, key: str, property_name: str, context: Optional[PropertyEvaluationContext] = None) -> Any:
if context is None:
context = PropertyEvaluationContext()
context.pushContainer(self)
global_stack = Application.getInstance().getGlobalContainerStack()
# Return the user defined value if present, otherwise, evaluate the value according to the default routine.
if self.getContainer(0).hasProperty(key, property_name):
if self.getContainer(0)._instances[key].state == InstanceState.User:
result = super().getProperty(key, property_name, context)
context.popContainer()
return result
# Handle the "limit_to_extruder" property.
limit_to_extruder = super().getProperty(key, "limit_to_extruder", context)
if limit_to_extruder is not None:
limit_to_extruder = str(limit_to_extruder)
# if this stack has the limit_to_extruder "not overriden", use the original limit_to_extruder as the current
# limit_to_extruder, so the values retrieved will be from the perspective of the original limit_to_extruder
# stack.
if limit_to_extruder == "-1":
if "original_limit_to_extruder" in context.context:
limit_to_extruder = context.context["original_limit_to_extruder"]
if limit_to_extruder is not None and limit_to_extruder != "-1" and limit_to_extruder in global_stack.extruders:
# set the original limit_to_extruder if this is the first stack that has a non-overriden limit_to_extruder
if "original_limit_to_extruder" not in context.context:
context.context["original_limit_to_extruder"] = limit_to_extruder
if super().getProperty(key, "settable_per_extruder", context):
result = global_stack.extruders[str(limit_to_extruder)].getProperty(key, property_name, context)
if result is not None:
context.popContainer()
return result
result = super().getProperty(key, property_name, context)
context.popContainer()
return result
@override(ContainerStack)
def setNextStack(self, stack: ContainerStack):
super().setNextStack(stack)
# trigger signal to re-evaluate all default settings
for key, instance in self.getContainer(0)._instances.items():
# only evaluate default settings
if instance.state != InstanceState.Default:
continue
self._collectPropertyChanges(key, "value")
self._emitCollectedPropertyChanges()

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,26 +54,75 @@ 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.
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)
# if still profiles are found, add a single empty_quality ("Not supported") instance to the drop down list
if len(result) == 0:
# If not qualities are found we dynamically create a not supported container for this machine + material combination
not_supported_container = ContainerRegistry.getInstance().findContainers(id = "empty_quality")[0]
result.append(not_supported_container)
return result
## Re-computes the items in this model, and adds the layer height role.
def _recomputeItems(self):
# Some globals that we can re-use.
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,17 +130,63 @@ 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"])
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"])
# When for some reason there is no profile container in the registry
if not profile:
item["layer_height"] = "" #Can't update a profile that is unknown.
self._setItemLayerHeight(item, "", "")
item["available"] = False
yield item
continue
#Easy case: This profile defines its own layer height.
profile = profile[0]
# When there is a profile but it's an empty quality should. It's shown in the list (they are "Not Supported" profiles)
if profile.getId() == "empty_quality":
self._setItemLayerHeight(item, "", "")
item["available"] = True
yield item
continue
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
@ -96,13 +198,14 @@ class ProfilesModel(InstanceContainersModel):
if quality_result["stack"] is global_container_stack:
quality = quality_result["quality"]
break
else: #No global container stack in the results:
else:
# No global container stack in the results:
if quality_results:
quality = quality_results[0]["quality"] # Take any of the extruders.
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 +215,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 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)
extruder_stacks = [active_extruder] + extruder_stacks
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,17 +1,17 @@
# 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
from UM.Scene.SceneNodeDecorator import SceneNodeDecorator
from UM.Signal import Signal, signalemitter
from UM.Settings.ContainerStack import ContainerStack
from UM.Settings.InstanceContainer import InstanceContainer
from UM.Settings.ContainerRegistry import ContainerRegistry
from UM.Logger import Logger
from UM.Application import Application
from cura.Settings.PerObjectContainerStack import PerObjectContainerStack
from cura.Settings.ExtruderManager import ExtruderManager
## A decorator that adds a container stack to a Node. This stack should be queried for all settings regarding
@ -24,7 +24,7 @@ class SettingOverrideDecorator(SceneNodeDecorator):
def __init__(self):
super().__init__()
self._stack = ContainerStack(stack_id = id(self))
self._stack = PerObjectContainerStack(stack_id = id(self))
self._stack.setDirty(False) # This stack does not need to be saved.
self._stack.addContainer(InstanceContainer(container_id = "SettingOverrideInstanceContainer"))

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
@ -54,8 +55,17 @@ import Arcus #@UnusedImport
import cura.CuraApplication
import cura.Settings.CuraContainerRegistry
def get_cura_dir_path():
if Platform.isWindows():
return os.path.expanduser("~/AppData/Local/cura/")
elif Platform.isLinux():
return os.path.expanduser("~/.local/share/cura")
elif Platform.isOSX():
return os.path.expanduser("~/Library/Logs/cura")
if hasattr(sys, "frozen"):
dirpath = os.path.expanduser("~/AppData/Local/cura/")
dirpath = get_cura_dir_path()
os.makedirs(dirpath, exist_ok = True)
sys.stdout = open(os.path.join(dirpath, "stdout.log"), "w")
sys.stderr = open(os.path.join(dirpath, "stderr.log"), "w")

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 scene node.
# \returns Uranium Scenen 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
@ -17,14 +17,18 @@ from .WorkspaceDialog import WorkspaceDialog
import xml.etree.ElementTree as ET
from cura.Settings.CuraStackBuilder import CuraStackBuilder
from cura.Settings.ExtruderManager import ExtruderManager
from cura.Settings.ExtruderStack import ExtruderStack
from cura.Settings.GlobalStack import GlobalStack
from cura.Settings.CuraContainerStack import _ContainerIndexes
from cura.QualityManager import QualityManager
from configparser import ConfigParser
import zipfile
import io
import configparser
import os
i18n_catalog = i18nCatalog("cura")
@ -221,9 +225,12 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
elif container_type == "definition_changes":
definition_name = instance_container.getName()
num_settings_overriden_by_definition_changes += len(instance_container._instances)
definition_changes = self._container_registry.findDefinitionContainers(id = container_id)
containers_found_dict["definition_changes"] = True
# Check if definition changes already exists.
definition_changes = self._container_registry.findInstanceContainers(id = container_id)
# 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":
@ -298,11 +305,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")
@ -329,6 +339,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)
@ -355,7 +366,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
@ -368,7 +379,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"):
@ -376,10 +387,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
# override the given extruder stack
# Override the given extruder stack
extruder_stack.deserialize(extruder_file_content)
# return the new ExtruderStack
@ -400,7 +414,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()
@ -436,6 +451,8 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
global_stack_id_original = self._stripFileToId(global_stack_file)
global_stack_id_new = global_stack_id_original
global_stack_name_original = self._getMachineNameFromSerializedStack(archive.open(global_stack_file).read().decode("utf-8"))
global_stack_name_new = global_stack_name_original
global_stack_need_rename = False
extruder_stack_id_map = {} # new and old ExtruderStack IDs map
@ -445,6 +462,8 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
global_stack_id_new = self.getNewId(global_stack_id_original)
global_stack_need_rename = True
global_stack_name_new = self._container_registry.uniqueName(global_stack_name_original)
for each_extruder_stack_file in extruder_stack_files:
old_container_id = self._stripFileToId(each_extruder_stack_file)
new_container_id = old_container_id
@ -591,7 +610,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)
@ -655,7 +676,7 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
stack.setMetaDataEntry("machine", global_stack_id_new)
# Only machines need a new name, stacks may be non-unique
stack.setName(global_stack_id_new)
stack.setName(global_stack_name_new)
container_stacks_added.append(stack)
self._container_registry.addContainer(stack)
@ -664,6 +685,9 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
Logger.log("e", "Resolve strategy of %s for machine is not supported",
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"))
global_stack = stack
Job.yieldThread()
except:
@ -673,6 +697,15 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
self._container_registry.removeContainer(container.getId())
return
#
# Use the number of extruders from the global stack instead of the number of extruder stacks this project file
# contains. The Custom FDM Printer can have multiple extruders, but the actual number of extruders in used is
# defined in the global stack.
# Because for single-extrusion machines, there won't be an extruder stack, so relying on the the extruder count
# in the global stack can avoid problems in those cases.
#
extruder_count_from_global_stack = global_stack.getProperty("machine_extruder_count", "value")
# --
# load extruder stack files
try:
@ -681,8 +714,11 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
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 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]
@ -711,6 +747,10 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
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.")
@ -719,6 +759,31 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
self._container_registry.removeContainer(container.getId())
return
# Check quality profiles to make sure that if one stack has the "not supported" quality profile,
# all others should have the same.
#
# This block code tries to fix the following problems in Cura 3.0 and earlier:
# 1. The upgrade script can rename all "Not Supported" quality profiles to "empty_quality", but it cannot fix
# the problem that the global stack the extruder stacks may have different quality profiles. The code
# below loops over all stacks and make sure that if there is one stack with "Not Supported" profile, the
# rest should also use the "Not Supported" profile.
# 2. In earlier versions (at least 2.7 and 3.0), a wrong quality profile could be assigned to a stack. For
# example, a UM3 can have a BB 0.8 variant with "aa04_pla_fast" quality profile enabled. To fix this,
# in the code below we also check the actual available quality profiles for the machine.
#
has_not_supported = False
for stack in [global_stack] + extruder_stacks:
if stack.quality.getId() == "empty_quality":
has_not_supported = True
break
if not has_not_supported:
available_quality = QualityManager.getInstance().findAllUsableQualitiesForMachineAndExtruders(global_stack, extruder_stacks)
has_not_supported = not available_quality
if has_not_supported:
empty_quality_container = self._container_registry.findInstanceContainers(id = "empty_quality")[0]
for stack in [global_stack] + extruder_stacks:
stack.replaceContainer(_ContainerIndexes.Quality, empty_quality_container)
#
# Replacing the old containers if resolve is "new".
# When resolve is "new", some containers will get renamed, so all the other containers that reference to those
@ -795,36 +860,31 @@ class ThreeMFWorkspaceReader(WorkspaceReader):
each_extruder_stack.definitionChanges = each_changes_container
if self._resolve_strategies["material"] == "new":
# the actual material instance container can have an ID such as
# <material>_<machine>_<variant>
# which cannot be determined immediately, so here we use a HACK to find the right new material
# instance ID:
# - get the old material IDs for all material
# - find the old material with the longest common prefix in ID, that's the old material
# - update the name by replacing the old prefix with the new
# - find the new material container and set it to the stack
old_to_new_material_dict = {}
for each_material in material_containers:
old_material = global_stack.material
# check if the old material container has been renamed to this material container ID
# if the container hasn't been renamed, we do nothing.
new_id = self._id_mapping.get(old_material.getId())
if new_id is None or new_id != each_material.getId():
continue
if old_material.getId() in self._id_mapping:
global_stack.material = each_material
# find the material's old name
for old_id, new_id in self._id_mapping.items():
if each_material.getId() == new_id:
old_to_new_material_dict[old_id] = each_material
break
# replace old material in global and extruder stacks with new
self._replaceStackMaterialWithNew(global_stack, old_to_new_material_dict)
if extruder_stacks:
for each_extruder_stack in extruder_stacks:
old_material = each_extruder_stack.material
# check if the old material container has been renamed to this material container ID
# if the container hasn't been renamed, we do nothing.
new_id = self._id_mapping.get(old_material.getId())
if new_id is None or new_id != each_material.getId():
continue
if old_material.getId() in self._id_mapping:
each_extruder_stack.material = each_material
self._replaceStackMaterialWithNew(each_extruder_stack, old_to_new_material_dict)
if extruder_stacks:
for stack in extruder_stacks:
ExtruderManager.getInstance().registerExtruder(stack, global_stack.getId())
else:
# Machine has no extruders, but it needs to be registered with the extruder manager.
ExtruderManager.getInstance().registerExtruder(None, global_stack.getId())
Logger.log("d", "Workspace loading is notifying rest of the code of changes...")
@ -843,8 +903,68 @@ 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.
# This function is used when the user chooses to resolve material conflicts by creating new ones.
def _replaceStackMaterialWithNew(self, stack, old_new_material_dict):
# The material containers in the project file are 'parent' material such as "generic_pla",
# but a material container used in a global/extruder stack is a 'child' material,
# such as "generic_pla_ultimaker3_AA_0.4", which can be formalised as the following:
#
# <material_name>_<machine_name>_<variant_name>
#
# In the project loading, when a user chooses to resolve material conflicts by creating new ones,
# the old 'parent' material ID and the new 'parent' material ID are known, but not the child material IDs.
# In this case, the global stack and the extruder stacks need to use the newly created material, but the
# material containers they use are 'child' material. So, here, we need to find the right 'child' material for
# the stacks.
#
# This hack approach works as follows:
# - No matter there is a child material or not, the actual material we are looking for has the prefix
# "<material_name>", which is the old material name. For the material in a stack, we know that the new
# material's ID will be "<new_material_name>_blabla..", so we just need to replace the old material ID
# with the new one to get the new 'child' material.
# - Because the material containers have IDs such as "m #nn", if we use simple prefix matching, there can
# be a problem in the following scenario:
# - there are two materials in the project file, namely "m #1" and "m #11"
# - the child materials in use are for example: "m #1_um3_aa04", "m #11_um3_aa04"
# - if we only check for a simple prefix match, then "m #11_um3_aa04" will match with "m #1", but they
# are not the same material
# To avoid this, when doing the prefix matching, we use the result with the longest mactching prefix.
# find the old material ID
old_material_id_in_stack = stack.material.getId()
best_matching_old_material_id = None
best_matching_old_meterial_prefix_length = -1
for old_parent_material_id in old_new_material_dict:
if len(old_parent_material_id) < best_matching_old_meterial_prefix_length:
continue
if len(old_parent_material_id) <= len(old_material_id_in_stack):
if old_parent_material_id == old_material_id_in_stack[0:len(old_parent_material_id)]:
best_matching_old_meterial_prefix_length = len(old_parent_material_id)
best_matching_old_material_id = old_parent_material_id
if best_matching_old_material_id is None:
Logger.log("w", "Cannot find any matching old material ID for stack [%s] material [%s]. Something can go wrong",
stack.getId(), old_material_id_in_stack)
return
# find the new material container
new_material_id = old_new_material_dict[best_matching_old_material_id].getId() + old_material_id_in_stack[len(best_matching_old_material_id):]
new_material_containers = self._container_registry.findInstanceContainers(id = new_material_id, type = "material")
if not new_material_containers:
Logger.log("e", "Cannot find new material container [%s]", new_material_id)
return
# replace the material in the given stack
stack.material = new_material_containers[0]
def _stripFileToId(self, file):
mime_type = MimeTypeDatabase.getMimeTypeForFile(file)
file = mime_type.stripExtension(file)

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
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,7 +378,7 @@ UM.Dialog
enabled: true
anchors.bottom: parent.bottom
anchors.right: ok_button.left
anchors.rightMargin:2
anchors.rightMargin: 2 * screenScaleFactor
}
Button
{
@ -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,12 +1,13 @@
# 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
from UM.Settings.ContainerRegistry import ContainerRegistry
from UM.Settings.ContainerStack import ContainerStack
from cura.Settings.ExtruderManager import ExtruderManager
import zipfile
from io import StringIO
import copy
import configparser
@ -44,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
@ -8,7 +8,6 @@ from UM.Application import Application
from UM.PluginRegistry import PluginRegistry
from UM.Version import Version
from PyQt5.QtQuick import QQuickView
from PyQt5.QtQml import QQmlComponent, QQmlContext
from PyQt5.QtCore import QUrl, pyqtSlot, QObject

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,93 @@
[3.0.4]
*Bug fixes
- Fixed OpenGL issue that prevents Cura from starting.
*License agreement on the first startup has been added
[3.0.3]
*Bug fixes
- Add missing libraries for the MakePrintable plugin.
[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.
@ -36,7 +126,7 @@ A dark theme for Cura. Select this theme to reduce eyestrain when working in dar
The top bar user interface been improved so that “Prepare” and “Print” have moved from the right side of the interface to the left side.
*New keyboard shortcuts
Models can now be manipulated on the build plate using hotkeys Q, A, Z, W, and tab keys. Q selects “move”, A selects “scale”, Z selects “rotate”, and W selects “mirror”. Use the tab key to navigate between interfaces.
Models can now be manipulated on the build plate using hotkeys Q, A, Z, W, and tab keys. Q selects “move”, A selects “scale”, Z selects “rotate”, and W selects “mirror”. Use the tab key to navigate between settings.
*Plugin browser
Easily download and install plugins using an integrated plugin browser. Go to “Extensions > Plugin Browser > Browse plugins” to select it.
@ -56,12 +146,15 @@ Extra tooltips have been added to clarify the machine settings.
*Polish now supported
Polish language support added. This can be selected in the preferences menu.
*Chinese now supported
Chinese language support added. This can be selected in the preferences menu.
*Bug fixes
- Cura project Mac extensions
- Crashes when adding printers
- Jerk fixes
- Z-hop over-extrusion
- Material diameter in machine settings
*3rd party printers
- Peopoly Moai

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:
@ -427,6 +418,7 @@ class CuraEngineBackend(QObject, Backend):
## Convenient function: set need_slicing, emit state and clear layer data
def needsSlicing(self):
self.stopSlicing()
self._need_slicing = True
self.processingProgress.emit(0.0)
self.backendStateChange.emit(BackendState.NotStarted)
@ -449,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()
@ -510,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")))
@ -551,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,11 @@ 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) 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.
import numpy
from string import Formatter
@ -224,7 +224,18 @@ class StartSliceJob(Job):
material_instance_container = stack.findContainer({"type": "material"})
settings = {}
for key in stack.getAllKeys():
settings[key] = stack.getProperty(key, "value")
Job.yieldThread()
settings["print_bed_temperature"] = settings["material_bed_temperature"] #Renamed settings.
settings["print_temperature"] = settings["material_print_temperature"]
settings["time"] = time.strftime("%H:%M:%S") #Some extra settings.
settings["date"] = time.strftime("%d-%m-%Y")
settings["day"] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][int(time.strftime("%w"))]
for key, value in settings.items():
# Do not send settings that are not settable_per_extruder.
if not stack.getProperty(key, "settable_per_extruder"):
continue
@ -233,6 +244,8 @@ class StartSliceJob(Job):
if key == "material_guid" and material_instance_container:
# Also send the material GUID. This is a setting in fdmprinter, but we have no interface for it.
setting.value = str(material_instance_container.getMetaDataEntry("GUID", "")).encode("utf-8")
elif key == "machine_extruder_start_code" or key == "machine_extruder_end_code":
setting.value = self._expandGcodeTokens(key, value, settings)
else:
setting.value = str(stack.getProperty(key, "value")).encode("utf-8")
Job.yieldThread()
@ -278,7 +291,7 @@ class StartSliceJob(Job):
for key, value in settings.items(): #Add all submessages for each individual setting.
setting_message = self._slice_message.getMessage("global_settings").addRepeatedMessage("settings")
setting_message.name = key
if key == "machine_start_gcode" or key == "machine_end_gcode" or key == "machine_extruder_start_code" or key == "machine_extruder_end_code": #If it's a g-code message, use special formatting.
if key == "machine_start_gcode" or key == "machine_end_gcode": #If it's a g-code message, use special formatting.
setting_message.value = self._expandGcodeTokens(key, value, settings)
else:
setting_message.value = str(value).encode("utf-8")
@ -306,16 +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")
# Check if the node has a stack attached to it and the stack has any settings in the top container.
if stack:
# Check all settings for relations, so we can also calculate the correct values for dependant settings.
changed_setting_keys = set(stack.getTop().getAllKeys())
for key in stack.getTop().getAllKeys():
instance = stack.getTop().getInstance(key)
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.
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")
@ -323,14 +342,23 @@ class StartSliceJob(Job):
for key in changed_setting_keys:
setting = message.addRepeatedMessage("settings")
setting.name = key
setting.value = str(stack.getProperty(key, "value")).encode("utf-8")
extruder = int(round(float(stack.getProperty(key, "limit_to_extruder"))))
# 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
setting.value = str(limited_stack.getProperty(key, "value")).encode("utf-8")
Job.yieldThread()
## 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):
for relation in filter(lambda r: r.role == "value", relations):
for relation in filter(lambda r: r.role == "value" or r.role == "limit_to_extruder", relations):
if relation.type == RelationType.RequiresTarget:
continue

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,65 @@
# Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QDesktopServices
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)
self._download_url = None
## Callback for the message that is spawned when there is a new version.
def _onActionTriggered(self, message, action):
if action == "download":
if self._download_url is not None:
QDesktopServices.openUrl(QUrl(self._download_url))
def _onSetDownloadUrl(self, download_url):
self._download_url = download_url
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,
callback = self._onActionTriggered,
set_download_url_callback = self._onSetDownloadUrl)
job.start()

View file

@ -0,0 +1,78 @@
# 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 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, callback = None, set_download_url_callback = None):
super().__init__()
self._container = container
self.silent = silent
self._url = url
self._callback = callback
self._set_download_url_callback = set_download_url_callback
def run(self):
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!", "New features are available for your {machine_name}! It is recommended to update the firmware on your printer.").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", "How to update"), "[no_icon]", "[no_description]")
# If we do this in a cool way, the download url should be available in the JSON file
if self._set_download_url_callback:
self._set_download_url_callback("https://ultimaker.com/en/resources/20500-upgrade-firmware")
message.actionTriggered.connect(self._callback)
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: Math.floor(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: Math.floor(UM.Theme.getSize("default_margin").width / 2)
verticalCenter: parent.verticalCenter
}
width: sliderLabelRoot.height
height: width
visible: sliderLabelRoot.busy
running: sliderLabelRoot.busy
}
}

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