Major reorganization to only include the communication stack from Cura.
This commit is contained in:
1 parent
f12cc26fbb
commit
a0cac835b5
404 files changed
+98
-59145
No files matched your search
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
Whitespace-only changes.
@@ -0,0 +1,371 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
|
||||
import time
|
||||
import os
|
||||
from threading import Thread
|
||||
import datetime
|
||||
|
||||
import printer_webui.util.comm as comm
|
||||
from printer_webui.util import gcodeInterpreter
|
||||
from printer_webui.util import profile
|
||||
|
||||
def getConnectionOptions():
|
||||
"""
|
||||
Retrieves the available ports, baudrates, prefered port and baudrate for connecting to the printer.
|
||||
"""
|
||||
baudratePref = None
|
||||
try:
|
||||
baudratePref = int(profile.getPreference('serial_baud_auto'))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return {
|
||||
"ports": comm.serialList(),
|
||||
"baudrates": comm.baudrateList(),
|
||||
"portPreference": profile.getPreference('serial_port_auto'),
|
||||
"baudratePreference": baudratePref
|
||||
}
|
||||
|
||||
def _getFormattedTimeDelta(d):
|
||||
hours = d.seconds // 3600
|
||||
minutes = (d.seconds % 3600) // 60
|
||||
seconds = d.seconds % 60
|
||||
return "%02d:%02d:%02d" % (hours, minutes, seconds)
|
||||
|
||||
class Printer():
|
||||
def __init__(self):
|
||||
# state
|
||||
self.temps = {
|
||||
"actual": [],
|
||||
"target": [],
|
||||
"actualBed": [],
|
||||
"targetBed": []
|
||||
}
|
||||
self.messages = []
|
||||
self.log = []
|
||||
self.state = None
|
||||
self.currentZ = None
|
||||
self.progress = None
|
||||
self.printTime = None
|
||||
self.printTimeLeft = None
|
||||
self.currentTemp = None
|
||||
self.currentBedTemp = None
|
||||
self.currentTargetTemp = None
|
||||
self.currentBedTargetTemp = None
|
||||
|
||||
self.gcode = None
|
||||
self.gcodeList = None
|
||||
self.filename = None
|
||||
|
||||
self.gcodeLoader = None
|
||||
|
||||
self.feedrateModifierMapping = {"outerWall": "WALL-OUTER", "innerWall": "WALL_INNER", "fill": "FILL", "support": "SUPPORT"}
|
||||
|
||||
# comm
|
||||
self.comm = None
|
||||
|
||||
def connect(self, port=None, baudrate=None):
|
||||
"""
|
||||
Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection
|
||||
will be attempted.
|
||||
"""
|
||||
if self.comm is not None:
|
||||
self.comm.close()
|
||||
self.comm = comm.MachineCom(port, baudrate, callbackObject=self)
|
||||
|
||||
def disconnect(self):
|
||||
"""
|
||||
Closes the connection to the printer.
|
||||
"""
|
||||
if self.comm is not None:
|
||||
self.comm.close()
|
||||
self.comm = None
|
||||
|
||||
def command(self, command):
|
||||
"""
|
||||
Sends a single gcode command to the printer.
|
||||
"""
|
||||
self.commands([command])
|
||||
|
||||
def commands(self, commands):
|
||||
"""
|
||||
Sends multiple gcode commands (provided as a list) to the printer.
|
||||
"""
|
||||
for command in commands:
|
||||
self.comm.sendCommand(command)
|
||||
|
||||
def setFeedrateModifier(self, structure, percentage):
|
||||
if (not self.feedrateModifierMapping.has_key(structure)) or percentage < 0:
|
||||
return
|
||||
|
||||
self.comm.setFeedrateModifier(self.feedrateModifierMapping[structure], percentage / 100.0)
|
||||
|
||||
def mcLog(self, message):
|
||||
"""
|
||||
Callback method for the comm object, called upon log output.
|
||||
Log line is stored in internal buffer, which is truncated to the last 300 lines.
|
||||
"""
|
||||
self.log.append(message)
|
||||
self.log = self.log[-300:]
|
||||
|
||||
def mcTempUpdate(self, temp, bedTemp, targetTemp, bedTargetTemp):
|
||||
"""
|
||||
Callback method for the comm object, called upon receiving new temperature information.
|
||||
Temperature information (actual and target) for print head and print bed is stored in corresponding
|
||||
temperature history (including timestamp), history is truncated to 300 entries.
|
||||
"""
|
||||
currentTime = int(time.time() * 1000)
|
||||
|
||||
self.temps["actual"].append((currentTime, temp))
|
||||
self.temps["actual"] = self.temps["actual"][-300:]
|
||||
|
||||
self.temps["target"].append((currentTime, targetTemp))
|
||||
self.temps["target"] = self.temps["target"][-300:]
|
||||
|
||||
self.temps["actualBed"].append((currentTime, bedTemp))
|
||||
self.temps["actualBed"] = self.temps["actualBed"][-300:]
|
||||
|
||||
self.temps["targetBed"].append((currentTime, bedTargetTemp))
|
||||
self.temps["targetBed"] = self.temps["targetBed"][-300:]
|
||||
|
||||
self.currentTemp = temp
|
||||
self.currentTargetTemp = targetTemp
|
||||
self.currentBedTemp = bedTemp
|
||||
self.currentBedTargetTemp = bedTargetTemp
|
||||
|
||||
def mcStateChange(self, state):
|
||||
"""
|
||||
Callback method for the comm object, called if the connection state changes.
|
||||
New state is stored for retrieval by the frontend.
|
||||
"""
|
||||
self.state = state
|
||||
|
||||
def mcMessage(self, message):
|
||||
"""
|
||||
Callback method for the comm object, called upon message exchanges via serial.
|
||||
Stores the message in the message buffer, truncates buffer to the last 300 lines.
|
||||
"""
|
||||
self.messages.append(message)
|
||||
self.messages = self.messages[-300:]
|
||||
|
||||
def mcProgress(self, lineNr):
|
||||
"""
|
||||
Callback method for the comm object, called upon any change in progress of the printjob.
|
||||
Triggers storage of new values for printTime, printTimeLeft and the current line.
|
||||
"""
|
||||
self.printTime = self.comm.getPrintTime()
|
||||
self.printTimeLeft = self.comm.getPrintTimeRemainingEstimate()
|
||||
self.progress = self.comm.getPrintPos()
|
||||
|
||||
def mcZChange(self, newZ):
|
||||
"""
|
||||
Callback method for the comm object, called upon change of the z-layer.
|
||||
"""
|
||||
self.currentZ = newZ
|
||||
|
||||
def onGcodeLoaded(self, gcodeLoader):
|
||||
"""
|
||||
Callback method for the gcode loader, gets called when the gcode for the new printjob has finished loading.
|
||||
Takes care to set filename, gcode and commandlist from the gcode loader and reset print job progress.
|
||||
"""
|
||||
self.filename = gcodeLoader.filename
|
||||
self.gcode = gcodeLoader.gcode
|
||||
self.gcodeList = gcodeLoader.gcodeList
|
||||
self.currentZ = None
|
||||
self.progress = None
|
||||
self.printTime = None
|
||||
self.printTimeLeft = None
|
||||
|
||||
self.gcodeLoader = None
|
||||
|
||||
def jobData(self):
|
||||
"""
|
||||
Returns statistics regarding the currently loaded printjob, or None if no printjob is loaded.
|
||||
"""
|
||||
if self.gcode is not None:
|
||||
formattedPrintTime = None
|
||||
if (self.printTime):
|
||||
formattedPrintTime = _getFormattedTimeDelta(datetime.timedelta(seconds=self.printTime))
|
||||
|
||||
formattedPrintTimeLeft = None
|
||||
if (self.printTimeLeft):
|
||||
formattedPrintTimeLeft = _getFormattedTimeDelta(datetime.timedelta(minutes=self.printTimeLeft))
|
||||
|
||||
formattedPrintTimeEstimation = None
|
||||
formattedFilament = None
|
||||
if self.gcode:
|
||||
if self.gcode.totalMoveTimeMinute:
|
||||
formattedPrintTimeEstimation = _getFormattedTimeDelta(datetime.timedelta(minutes=self.gcode.totalMoveTimeMinute))
|
||||
if self.gcode.extrusionAmount:
|
||||
formattedFilament = "%.2fm %.2fg" % (self.gcode.extrusionAmount / 1000, self.gcode.calculateWeight() * 1000)
|
||||
|
||||
formattedCurrentZ = None
|
||||
if self.currentZ:
|
||||
formattedCurrentZ = "%.2f mm" % (self.currentZ)
|
||||
|
||||
data = {
|
||||
"filename": self.filename,
|
||||
"currentZ": formattedCurrentZ,
|
||||
"line": self.progress,
|
||||
"totalLines": len(self.gcodeList),
|
||||
"printTime": formattedPrintTime,
|
||||
"printTimeLeft": formattedPrintTimeLeft,
|
||||
"filament": formattedFilament,
|
||||
"estimatedPrintTime": formattedPrintTimeEstimation
|
||||
}
|
||||
else:
|
||||
data = None
|
||||
return data
|
||||
|
||||
def gcodeState(self):
|
||||
if self.gcodeLoader is not None:
|
||||
return {
|
||||
"filename": self.gcodeLoader.filename,
|
||||
"progress": self.gcodeLoader.progress
|
||||
}
|
||||
else:
|
||||
return None
|
||||
|
||||
def feedrateState(self):
|
||||
if self.comm is not None:
|
||||
feedrateModifiers = self.comm.getFeedrateModifiers()
|
||||
result = {}
|
||||
for structure in self.feedrateModifierMapping.keys():
|
||||
if (feedrateModifiers.has_key(self.feedrateModifierMapping[structure])):
|
||||
result[structure] = int(round(feedrateModifiers[self.feedrateModifierMapping[structure]] * 100))
|
||||
else:
|
||||
result[structure] = 100
|
||||
return result
|
||||
else:
|
||||
return None
|
||||
|
||||
def getStateString(self):
|
||||
"""
|
||||
Returns a human readable string corresponding to the current communication state.
|
||||
"""
|
||||
if self.comm is None:
|
||||
return "Offline"
|
||||
else:
|
||||
return self.comm.getStateString()
|
||||
|
||||
def isClosedOrError(self):
|
||||
return self.comm is None or self.comm.isClosedOrError()
|
||||
|
||||
def isOperational(self):
|
||||
return self.comm is not None and self.comm.isOperational()
|
||||
|
||||
def isPrinting(self):
|
||||
return self.comm is not None and self.comm.isPrinting()
|
||||
|
||||
def isPaused(self):
|
||||
return self.comm is not None and self.comm.isPaused()
|
||||
|
||||
def isError(self):
|
||||
return self.comm is not None and self.comm.isError()
|
||||
|
||||
def isReady(self):
|
||||
return self.gcodeLoader is None and self.gcodeList and len(self.gcodeList) > 0
|
||||
|
||||
def isLoading(self):
|
||||
return self.gcodeLoader is not None
|
||||
|
||||
def loadGcode(self, file):
|
||||
"""
|
||||
Loads the gcode from the given file as the new print job.
|
||||
Aborts if the printer is currently printing or another gcode file is currently being loaded.
|
||||
"""
|
||||
if (self.comm is not None and self.comm.isPrinting()) or (self.gcodeLoader is not None):
|
||||
return
|
||||
|
||||
self.filename = None
|
||||
self.gcode = None
|
||||
self.gcodeList = None
|
||||
|
||||
self.gcodeLoader = GcodeLoader(file, self)
|
||||
self.gcodeLoader.start()
|
||||
|
||||
def startPrint(self):
|
||||
"""
|
||||
Starts the currently loaded print job.
|
||||
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
|
||||
"""
|
||||
if self.comm is None or not self.comm.isOperational():
|
||||
return
|
||||
if self.gcodeList is None:
|
||||
return
|
||||
if self.comm.isPrinting():
|
||||
return
|
||||
self.currentZ = -1
|
||||
self.comm.printGCode(self.gcodeList)
|
||||
|
||||
def togglePausePrint(self):
|
||||
"""
|
||||
Pause the current printjob.
|
||||
"""
|
||||
if self.comm is None:
|
||||
return
|
||||
self.comm.setPause(not self.comm.isPaused())
|
||||
|
||||
def cancelPrint(self, disableMotorsAndHeater=True):
|
||||
"""
|
||||
Cancel the current printjob.
|
||||
"""
|
||||
if self.comm is None:
|
||||
return
|
||||
self.comm.cancelPrint()
|
||||
if disableMotorsAndHeater:
|
||||
self.commands(["M84", "M104 S0", "M140 S0"]) # disable motors, switch off heaters
|
||||
|
||||
# reset line, height, print time
|
||||
self.currentZ = None
|
||||
self.progress = None
|
||||
self.printTime = None
|
||||
self.printTimeLeft = None
|
||||
|
||||
class GcodeLoader(Thread):
|
||||
"""
|
||||
The GcodeLoader takes care of loading a gcode-File from disk and parsing it into a gcode object in a separate
|
||||
thread while constantly notifying interested listeners about the current progress.
|
||||
The progress is returned as a float value between 0 and 1 which is to be interpreted as the percentage of completion.
|
||||
"""
|
||||
|
||||
def __init__(self, filename, printerCallback):
|
||||
Thread.__init__(self);
|
||||
|
||||
self.printerCallback = printerCallback;
|
||||
|
||||
self.filename = filename
|
||||
self.progress = None
|
||||
|
||||
self.gcode = None
|
||||
self.gcodeList = None
|
||||
|
||||
def run(self):
|
||||
#Send an initial M110 to reset the line counter to zero.
|
||||
prevLineType = lineType = "CUSTOM"
|
||||
gcodeList = ["M110"]
|
||||
with open(self.filename, "r") as file:
|
||||
for line in file:
|
||||
if line.startswith(";TYPE:"):
|
||||
lineType = line[6:].strip()
|
||||
if ";" in line:
|
||||
line = line[0:line.find(";")]
|
||||
line = line.strip()
|
||||
if len(line) > 0:
|
||||
if prevLineType != lineType:
|
||||
gcodeList.append((line, lineType, ))
|
||||
else:
|
||||
gcodeList.append(line)
|
||||
prevLineType = lineType
|
||||
|
||||
self.gcodeList = gcodeList
|
||||
self.gcode = gcodeInterpreter.gcode()
|
||||
self.gcode.progressCallback = self.onProgress
|
||||
self.gcode.loadList(self.gcodeList)
|
||||
|
||||
self.printerCallback.onGcodeLoaded(self)
|
||||
|
||||
def onProgress(self, progress):
|
||||
self.progress = progress
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
# coding=utf-8
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
|
||||
from flask import Flask, request, render_template, jsonify, make_response
|
||||
from werkzeug import secure_filename
|
||||
|
||||
from printer import Printer, getConnectionOptions
|
||||
|
||||
import sys
|
||||
import os
|
||||
import fnmatch
|
||||
|
||||
APPNAME="PrinterWebUI"
|
||||
BASEURL="/ajax/"
|
||||
SUCCESS={}
|
||||
|
||||
# taken from http://stackoverflow.com/questions/1084697/how-do-i-store-desktop-application-data-in-a-cross-platform-way-for-python
|
||||
if sys.platform == "darwin":
|
||||
from AppKit import NSSearchPathForDirectoriesInDomains
|
||||
# http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSSearchPathForDirectoriesInDomains
|
||||
# NSApplicationSupportDirectory = 14
|
||||
# NSUserDomainMask = 1
|
||||
# True for expanding the tilde into a fully qualified path
|
||||
appdata = os.path.join(NSSearchPathForDirectoriesInDomains(14, 1, True)[0], APPNAME)
|
||||
elif sys.platform == "win32":
|
||||
appdata = os.path.join(os.environ["APPDATA"], APPNAME)
|
||||
else:
|
||||
appdata = os.path.expanduser(os.path.join("~", "." + APPNAME.lower()))
|
||||
|
||||
UPLOAD_FOLDER = appdata + os.sep + "uploads"
|
||||
if not os.path.isdir(UPLOAD_FOLDER):
|
||||
os.makedirs(UPLOAD_FOLDER)
|
||||
ALLOWED_EXTENSIONS = set(["gcode"])
|
||||
|
||||
app = Flask("printer_webui")
|
||||
printer = Printer()
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
return render_template("index.html")
|
||||
|
||||
#~~ Printer state
|
||||
|
||||
@app.route(BASEURL + "state", methods=["GET"])
|
||||
def printerState():
|
||||
temp = printer.currentTemp
|
||||
bedTemp = printer.currentBedTemp
|
||||
targetTemp = printer.currentTargetTemp
|
||||
bedTargetTemp = printer.currentBedTargetTemp
|
||||
jobData = printer.jobData()
|
||||
gcodeState = printer.gcodeState()
|
||||
feedrateState = printer.feedrateState()
|
||||
|
||||
result = {
|
||||
"state": printer.getStateString(),
|
||||
"temp": temp,
|
||||
"bedTemp": bedTemp,
|
||||
"targetTemp": targetTemp,
|
||||
"targetBedTemp": bedTargetTemp,
|
||||
"operational": printer.isOperational(),
|
||||
"closedOrError": printer.isClosedOrError(),
|
||||
"error": printer.isError(),
|
||||
"printing": printer.isPrinting(),
|
||||
"paused": printer.isPaused(),
|
||||
"ready": printer.isReady(),
|
||||
"loading": printer.isLoading()
|
||||
}
|
||||
|
||||
if jobData is not None:
|
||||
jobData["filename"] = jobData["filename"].replace(UPLOAD_FOLDER + os.sep, "")
|
||||
result["job"] = jobData
|
||||
|
||||
if gcodeState is not None:
|
||||
gcodeState["filename"] = gcodeState["filename"].replace(UPLOAD_FOLDER + os.sep, "")
|
||||
result["gcode"] = gcodeState
|
||||
|
||||
if feedrateState is not None:
|
||||
result["feedrate"] = feedrateState
|
||||
|
||||
if request.values.has_key("temperatures"):
|
||||
result["temperatures"] = printer.temps
|
||||
|
||||
if request.values.has_key("log"):
|
||||
result["log"] = printer.log
|
||||
|
||||
if request.values.has_key("messages"):
|
||||
result["messages"] = printer.messages
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
@app.route(BASEURL + "state/messages", methods=["GET"])
|
||||
def printerMessages():
|
||||
return jsonify(messages=printer.messages)
|
||||
|
||||
@app.route(BASEURL + "state/log", methods=["GET"])
|
||||
def printerLogs():
|
||||
return jsonify(log=printer.log)
|
||||
|
||||
@app.route(BASEURL + "state/temperatures", methods=["GET"])
|
||||
def printerTemperatures():
|
||||
return jsonify(temperatures = printer.temps)
|
||||
|
||||
#~~ Printer control
|
||||
|
||||
@app.route(BASEURL + "control/connectionOptions", methods=["GET"])
|
||||
def connectionOptions():
|
||||
return jsonify(getConnectionOptions())
|
||||
|
||||
@app.route(BASEURL + "control/connect", methods=["POST"])
|
||||
def connect():
|
||||
port = None
|
||||
baudrate = None
|
||||
if request.values.has_key("port"):
|
||||
port = request.values["port"]
|
||||
if request.values.has_key("baudrate"):
|
||||
baudrate = request.values["baudrate"]
|
||||
printer.connect(port=port, baudrate=baudrate)
|
||||
return jsonify(state="Connecting")
|
||||
|
||||
@app.route(BASEURL + "control/disconnect", methods=["POST"])
|
||||
def disconnect():
|
||||
printer.disconnect()
|
||||
return jsonify(state="Offline")
|
||||
|
||||
@app.route(BASEURL + "control/command", methods=["POST"])
|
||||
def printerCommand():
|
||||
command = request.form["command"]
|
||||
printer.command(command)
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
@app.route(BASEURL + "control/print", methods=["POST"])
|
||||
def printGcode():
|
||||
printer.startPrint()
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
@app.route(BASEURL + "control/pause", methods=["POST"])
|
||||
def pausePrint():
|
||||
printer.togglePausePrint()
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
@app.route(BASEURL + "control/cancel", methods=["POST"])
|
||||
def cancelPrint():
|
||||
printer.cancelPrint()
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
@app.route(BASEURL + "control/temperature", methods=["POST"])
|
||||
def setTargetTemperature():
|
||||
if not printer.isOperational():
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if request.values.has_key("temp"):
|
||||
# set target temperature
|
||||
temp = request.values["temp"];
|
||||
printer.command("M104 S" + temp)
|
||||
|
||||
if request.values.has_key("bedTemp"):
|
||||
# set target bed temperature
|
||||
bedTemp = request.values["bedTemp"]
|
||||
printer.command("M140 S" + bedTemp)
|
||||
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
@app.route(BASEURL + "control/jog", methods=["POST"])
|
||||
def jog():
|
||||
if not printer.isOperational() or printer.isPrinting():
|
||||
# do not jog when a print job is running or we don"t have a connection
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if request.values.has_key("x"):
|
||||
# jog x
|
||||
x = request.values["x"]
|
||||
printer.commands(["G91", "G1 X" + x + " F6000", "G90"])
|
||||
if request.values.has_key("y"):
|
||||
# jog y
|
||||
y = request.values["y"]
|
||||
printer.commands(["G91", "G1 Y" + y + " F6000", "G90"])
|
||||
if request.values.has_key("z"):
|
||||
# jog z
|
||||
z = request.values["z"]
|
||||
printer.commands(["G91", "G1 Z" + z + " F200", "G90"])
|
||||
if request.values.has_key("homeXY"):
|
||||
# home x/y
|
||||
printer.command("G28 X0 Y0")
|
||||
if request.values.has_key("homeZ"):
|
||||
# home z
|
||||
printer.command("G28 Z0")
|
||||
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
@app.route(BASEURL + "control/speed", methods=["POST"])
|
||||
def speed():
|
||||
if not printer.isOperational():
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
for key in ["outerWall", "innerWall", "fill", "support"]:
|
||||
if request.values.has_key(key):
|
||||
value = int(request.values[key])
|
||||
printer.setFeedrateModifier(key, value)
|
||||
|
||||
return jsonify(feedrate = printer.feedrateState())
|
||||
|
||||
#~~ GCODE file handling
|
||||
|
||||
@app.route(BASEURL + "gcodefiles", methods=["GET"])
|
||||
def readGcodeFiles():
|
||||
files = []
|
||||
for osFile in os.listdir(UPLOAD_FOLDER):
|
||||
if not fnmatch.fnmatch(osFile, "*.gcode"):
|
||||
continue
|
||||
files.append({
|
||||
"name": osFile,
|
||||
"size": sizeof_fmt(os.stat(os.path.join(UPLOAD_FOLDER, osFile)).st_size)
|
||||
})
|
||||
return jsonify(files=files)
|
||||
|
||||
@app.route(BASEURL + "gcodefiles/upload", methods=["POST"])
|
||||
def uploadGcodeFile():
|
||||
file = request.files["gcode_file"]
|
||||
if file and allowed_file(file.filename):
|
||||
secure = secure_filename(file.filename)
|
||||
filename = os.path.join(UPLOAD_FOLDER, secure)
|
||||
file.save(filename)
|
||||
return readGcodeFiles()
|
||||
|
||||
@app.route(BASEURL + "gcodefiles/load", methods=["POST"])
|
||||
def loadGcodeFile():
|
||||
filename = request.values["filename"]
|
||||
printer.loadGcode(os.path.join(UPLOAD_FOLDER, filename))
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
@app.route(BASEURL + "gcodefiles/delete", methods=["POST"])
|
||||
def deleteGcodeFile():
|
||||
if request.values.has_key("filename"):
|
||||
filename = request.values["filename"]
|
||||
if allowed_file(filename):
|
||||
secure = os.path.join(UPLOAD_FOLDER, secure_filename(filename))
|
||||
if os.path.exists(secure):
|
||||
os.remove(secure)
|
||||
return readGcodeFiles()
|
||||
|
||||
def sizeof_fmt(num):
|
||||
"""
|
||||
Taken from http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
|
||||
"""
|
||||
for x in ["bytes","KB","MB","GB"]:
|
||||
if num < 1024.0:
|
||||
return "%3.1f%s" % (num, x)
|
||||
num /= 1024.0
|
||||
return "%3.1f%s" % (num, "TB")
|
||||
|
||||
def allowed_file(filename):
|
||||
return "." in filename and filename.rsplit(".", 1)[1] in ALLOWED_EXTENSIONS
|
||||
|
||||
def run(host = "0.0.0.0", port = 5000, debug = False):
|
||||
app.debug = debug
|
||||
app.run(host=host, port=port, use_reloader=False)
|
||||
|
||||
def main():
|
||||
from optparse import OptionParser
|
||||
|
||||
parser = OptionParser(usage="usage: %prog [options]")
|
||||
parser.add_option("-d", "--debug", action="store_true", dest="debug",
|
||||
help="Enable debug mode")
|
||||
parser.add_option("--host", action="store", type="string", default="0.0.0.0", dest="host",
|
||||
help="Specify the host on which to bind the server, defaults to 0.0.0.0 (all interfaces) if not set")
|
||||
parser.add_option("--port", action="store", type="int", default=5000, dest="port",
|
||||
help="Specify the port on which to bind the server, defaults to 5000 if not set")
|
||||
(options, args) = parser.parse_args()
|
||||
|
||||
run(host=options.host, port=options.port, debug=options.debug)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+1092
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,9 @@
|
||||
/*!
|
||||
* Bootstrap Responsive v2.2.2
|
||||
*
|
||||
* Copyright 2012 Twitter, Inc
|
||||
* Licensed under the Apache License v2.0
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Designed and built with all the love in the world @twitter by @mdo and @fat.
|
||||
*/@-ms-viewport{width:device-width}.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;line-height:0;content:""}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.hidden{display:none;visibility:hidden}.visible-phone{display:none!important}.visible-tablet{display:none!important}.hidden-desktop{display:none!important}.visible-desktop{display:inherit!important}@media(min-width:768px) and (max-width:979px){.hidden-desktop{display:inherit!important}.visible-desktop{display:none!important}.visible-tablet{display:inherit!important}.hidden-tablet{display:none!important}}@media(max-width:767px){.hidden-desktop{display:inherit!important}.visible-desktop{display:none!important}.visible-phone{display:inherit!important}.hidden-phone{display:none!important}}@media(min-width:1200px){.row{margin-left:-30px;*zoom:1}.row:before,.row:after{display:table;line-height:0;content:""}.row:after{clear:both}[class*="span"]{float:left;min-height:1px;margin-left:30px}.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:1170px}.span12{width:1170px}.span11{width:1070px}.span10{width:970px}.span9{width:870px}.span8{width:770px}.span7{width:670px}.span6{width:570px}.span5{width:470px}.span4{width:370px}.span3{width:270px}.span2{width:170px}.span1{width:70px}.offset12{margin-left:1230px}.offset11{margin-left:1130px}.offset10{margin-left:1030px}.offset9{margin-left:930px}.offset8{margin-left:830px}.offset7{margin-left:730px}.offset6{margin-left:630px}.offset5{margin-left:530px}.offset4{margin-left:430px}.offset3{margin-left:330px}.offset2{margin-left:230px}.offset1{margin-left:130px}.row-fluid{width:100%;*zoom:1}.row-fluid:before,.row-fluid:after{display:table;line-height:0;content:""}.row-fluid:after{clear:both}.row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.564102564102564%;*margin-left:2.5109110747408616%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="span"]:first-child{margin-left:0}.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.564102564102564%}.row-fluid .span12{width:100%;*width:99.94680851063829%}.row-fluid .span11{width:91.45299145299145%;*width:91.39979996362975%}.row-fluid .span10{width:82.90598290598291%;*width:82.8527914166212%}.row-fluid .span9{width:74.35897435897436%;*width:74.30578286961266%}.row-fluid .span8{width:65.81196581196582%;*width:65.75877432260411%}.row-fluid .span7{width:57.26495726495726%;*width:57.21176577559556%}.row-fluid .span6{width:48.717948717948715%;*width:48.664757228587014%}.row-fluid .span5{width:40.17094017094017%;*width:40.11774868157847%}.row-fluid .span4{width:31.623931623931625%;*width:31.570740134569924%}.row-fluid .span3{width:23.076923076923077%;*width:23.023731587561375%}.row-fluid .span2{width:14.52991452991453%;*width:14.476723040552828%}.row-fluid .span1{width:5.982905982905983%;*width:5.929714493544281%}.row-fluid .offset12{margin-left:105.12820512820512%;*margin-left:105.02182214948171%}.row-fluid .offset12:first-child{margin-left:102.56410256410257%;*margin-left:102.45771958537915%}.row-fluid .offset11{margin-left:96.58119658119658%;*margin-left:96.47481360247316%}.row-fluid .offset11:first-child{margin-left:94.01709401709402%;*margin-left:93.91071103837061%}.row-fluid .offset10{margin-left:88.03418803418803%;*margin-left:87.92780505546462%}.row-fluid .offset10:first-child{margin-left:85.47008547008548%;*margin-left:85.36370249136206%}.row-fluid .offset9{margin-left:79.48717948717949%;*margin-left:79.38079650845607%}.row-fluid .offset9:first-child{margin-left:76.92307692307693%;*margin-left:76.81669394435352%}.row-fluid .offset8{margin-left:70.94017094017094%;*margin-left:70.83378796144753%}.row-fluid .offset8:first-child{margin-left:68.37606837606839%;*margin-left:68.26968539734497%}.row-fluid .offset7{margin-left:62.393162393162385%;*margin-left:62.28677941443899%}.row-fluid .offset7:first-child{margin-left:59.82905982905982%;*margin-left:59.72267685033642%}.row-fluid .offset6{margin-left:53.84615384615384%;*margin-left:53.739770867430444%}.row-fluid .offset6:first-child{margin-left:51.28205128205128%;*margin-left:51.175668303327875%}.row-fluid .offset5{margin-left:45.299145299145295%;*margin-left:45.1927623204219%}.row-fluid .offset5:first-child{margin-left:42.73504273504273%;*margin-left:42.62865975631933%}.row-fluid .offset4{margin-left:36.75213675213675%;*margin-left:36.645753773413354%}.row-fluid .offset4:first-child{margin-left:34.18803418803419%;*margin-left:34.081651209310785%}.row-fluid .offset3{margin-left:28.205128205128204%;*margin-left:28.0987452264048%}.row-fluid .offset3:first-child{margin-left:25.641025641025642%;*margin-left:25.53464266230224%}.row-fluid .offset2{margin-lefLine truncated
|
||||
+6039
File diff suppressed because it is too large.
Load diff
+9
@@ -0,0 +1,9 @@
|
||||
/*!
|
||||
* Bootstrap v2.2.2
|
||||
*
|
||||
* Copyright 2012 Twitter, Inc
|
||||
* Licensed under the Apache License v2.0
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Designed and built with all the love in the world @twitter by @mdo and @fat.
|
||||
*/article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}audio:not([controls]){display:none}html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}a:hover,a:active{outline:0}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{width:auto\9;height:auto;max-width:100%;vertical-align:middle;border:0;-ms-interpolation-mode:bicubic}#map_canvas img,.google-maps img{max-width:none}button,input,select,textarea{margin:0;font-size:100%;vertical-align:middle}button,input{*overflow:visible;line-height:normal}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}label,select,button,input[type="button"],input[type="reset"],input[type="submit"],input[type="radio"],input[type="checkbox"]{cursor:pointer}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-decoration,input[type="search"]::-webkit-search-cancel-button{-webkit-appearance:none}textarea{overflow:auto;vertical-align:top}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:.5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}}.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;line-height:0;content:""}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}body{margin:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:20px;color:#333;background-color:#fff}a{color:#08c;text-decoration:none}a:hover{color:#005580;text-decoration:underline}.img-rounded{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.img-polaroid{padding:4px;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.1);-moz-box-shadow:0 1px 3px rgba(0,0,0,0.1);box-shadow:0 1px 3px rgba(0,0,0,0.1)}.img-circle{-webkit-border-radius:500px;-moz-border-radius:500px;border-radius:500px}.row{margin-left:-20px;*zoom:1}.row:before,.row:after{display:table;line-height:0;content:""}.row:after{clear:both}[class*="span"]{float:left;min-height:1px;margin-left:20px}.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px}.span12{width:940px}.span11{width:860px}.span10{width:780px}.span9{width:700px}.span8{width:620px}.span7{width:540px}.span6{width:460px}.span5{width:380px}.span4{width:300px}.span3{width:220px}.span2{width:140px}.span1{width:60px}.offset12{margin-left:980px}.offset11{margin-left:900px}.offset10{margin-left:820px}.offset9{margin-left:740px}.offset8{margin-left:660px}.offset7{margin-left:580px}.offset6{margin-left:500px}.offset5{margin-left:420px}.offset4{margin-left:340px}.offset3{margin-left:260px}.offset2{margin-left:180px}.offset1{margin-left:100px}.row-fluid{width:100%;*zoom:1}.row-fluid:before,.row-fluid:after{display:table;line-height:0;content:""}.row-fluid:after{clear:both}.row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.127659574468085%;*margin-left:2.074468085106383%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="span"]:first-child{margin-left:0}.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.127659574468085%}.row-fluid .span12{width:100%;*width:99.94680851063829%}.row-fluid .span11{width:91.48936170212765%;*width:91.43617021276594%}.row-fluid .span10{width:82.97872340425532%;*width:82.92553191489361%}.row-fluid .span9{width:74.46808510638297%;*width:74.41489361702126%}.row-fluid .span8{width:65.95744680851064%;*width:65.90425531914893%}.row-fluid .span7{width:57.44680851063829%;*width:57.39361702127659%}.row-fluid .span6{width:48.93617021276595%;*width:48.88297872340425%}.row-fluid .span5{width:40.42553191489362%;*width:40.37234042553192%}.row-fluid .span4{width:31.914893617021278%;*width:31.861702127659576%}.row-fluid .span3{width:23.404255319148934%;*width:23.351063829787233%}.row-fluid .span2{width:14.893617021276595%;*width:14.840425531914894%Line truncated
|
||||
@@ -0,0 +1,84 @@
|
||||
@charset "UTF-8";
|
||||
/*
|
||||
* jQuery File Upload UI Plugin CSS 6.10
|
||||
* https://github.com/blueimp/jQuery-File-Upload
|
||||
*
|
||||
* Copyright 2010, Sebastian Tschan
|
||||
* https://blueimp.net
|
||||
*
|
||||
* Licensed under the MIT license:
|
||||
* http://www.opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
.fileinput-button {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
float: left;
|
||||
margin-right: 4px;
|
||||
}
|
||||
.fileinput-button input {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
margin: 0;
|
||||
opacity: 0;
|
||||
filter: alpha(opacity=0);
|
||||
transform: translate(-300px, 0) scale(4);
|
||||
font-size: 23px;
|
||||
direction: ltr;
|
||||
cursor: pointer;
|
||||
}
|
||||
.fileupload-buttonbar .btn,
|
||||
.fileupload-buttonbar .toggle {
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
.files .progress {
|
||||
width: 200px;
|
||||
}
|
||||
.progress-animated .bar {
|
||||
background: url(../img/progressbar.gif) !important;
|
||||
filter: none;
|
||||
}
|
||||
.fileupload-loading {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
width: 128px;
|
||||
height: 128px;
|
||||
background: url(../img/loading.gif) center no-repeat;
|
||||
display: none;
|
||||
}
|
||||
.fileupload-processing .fileupload-loading {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* Fix for IE 6: */
|
||||
* html .fileinput-button {
|
||||
line-height: 24px;
|
||||
margin: 1px -3px 0 0;
|
||||
}
|
||||
|
||||
/* Fix for IE 7: */
|
||||
* + html .fileinput-button {
|
||||
padding: 2px 15px;
|
||||
margin: 1px 0 0 0;
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.files .btn span {
|
||||
display: none;
|
||||
}
|
||||
.files .preview * {
|
||||
width: 40px;
|
||||
}
|
||||
.files .name * {
|
||||
width: 80px;
|
||||
display: inline-block;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
.files .progress {
|
||||
width: 20px;
|
||||
}
|
||||
.files .delete {
|
||||
width: 60px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
body {
|
||||
padding-top: 60px;
|
||||
}
|
||||
|
||||
.tab-content {
|
||||
padding: 9px 15px;
|
||||
border-left: 1px solid #DDD;
|
||||
border-right: 1px solid #DDD;
|
||||
border-bottom: 1px solid #DDD;
|
||||
|
||||
-webkit-border-bottom-right-radius: 4px;
|
||||
-webkit-border-bottom-left-radius: 4px;
|
||||
-moz-border-radius-bottomright: 4px;
|
||||
-moz-border-radius-bottomleft: 4px;
|
||||
border-bottom-right-radius: 4px;
|
||||
border-bottom-left-radius: 4px;
|
||||
}
|
||||
|
||||
.nav {
|
||||
margin-bottom: 0px;
|
||||
}
|
||||
|
||||
table {
|
||||
table-layout: fixed;
|
||||
}
|
||||
|
||||
table th, table td {
|
||||
overflow: hidden
|
||||
}
|
||||
|
||||
table th.gcode_files_name, table td.gcode_files_name {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
width: 55%;
|
||||
}
|
||||
|
||||
table th.gcode_files_size, table td.gcode_files_size {
|
||||
text-align: right;
|
||||
width: 25%;
|
||||
}
|
||||
|
||||
table th.gcode_files_action, table td.gcode_files_action {
|
||||
text-align: center;
|
||||
width: 20%;
|
||||
}
|
||||
|
||||
#temp {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#temp_newTemp, #temp_newBedTemp, #speed_innerWall, #speed_outerWall, #speed_fill, #speed_support {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
|
||||
#connection_ports, #connection_baudrates {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#offline_overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: block;
|
||||
z-index: 10000;
|
||||
display: none;
|
||||
}
|
||||
|
||||
#offline_overlay_background {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: #000000;
|
||||
filter:alpha(opacity=50);
|
||||
-moz-opacity:0.5;
|
||||
-khtml-opacity: 0.5;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
#offline_overlay_wrapper {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
padding-top: 60px;
|
||||
}
|
||||
|
||||
#offline_overlay_wrapper .container {
|
||||
margin: auto;
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 345 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 8.6 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
Vendored
+2159
File diff suppressed because it is too large.
Load diff
+6
@@ -0,0 +1,6 @@
|
||||
/*!
|
||||
* Bootstrap.js by @fat & @mdo
|
||||
* Copyright 2012 Twitter, Inc.
|
||||
* http://www.apache.org/licenses/LICENSE-2.0.txt
|
||||
*/
|
||||
!function($){"use strict";$(function(){$.support.transition=function(){var transitionEnd=function(){var name,el=document.createElement("bootstrap"),transEndEventNames={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(name in transEndEventNames)if(void 0!==el.style[name])return transEndEventNames[name]}();return transitionEnd&&{end:transitionEnd}}()})}(window.jQuery),!function($){"use strict";var dismiss='[data-dismiss="alert"]',Alert=function(el){$(el).on("click",dismiss,this.close)};Alert.prototype.close=function(e){function removeElement(){$parent.trigger("closed").remove()}var $parent,$this=$(this),selector=$this.attr("data-target");selector||(selector=$this.attr("href"),selector=selector&&selector.replace(/.*(?=#[^\s]*$)/,"")),$parent=$(selector),e&&e.preventDefault(),$parent.length||($parent=$this.hasClass("alert")?$this:$this.parent()),$parent.trigger(e=$.Event("close")),e.isDefaultPrevented()||($parent.removeClass("in"),$.support.transition&&$parent.hasClass("fade")?$parent.on($.support.transition.end,removeElement):removeElement())};var old=$.fn.alert;$.fn.alert=function(option){return this.each(function(){var $this=$(this),data=$this.data("alert");data||$this.data("alert",data=new Alert(this)),"string"==typeof option&&data[option].call($this)})},$.fn.alert.Constructor=Alert,$.fn.alert.noConflict=function(){return $.fn.alert=old,this},$(document).on("click.alert.data-api",dismiss,Alert.prototype.close)}(window.jQuery),!function($){"use strict";var Button=function(element,options){this.$element=$(element),this.options=$.extend({},$.fn.button.defaults,options)};Button.prototype.setState=function(state){var d="disabled",$el=this.$element,data=$el.data(),val=$el.is("input")?"val":"html";state+="Text",data.resetText||$el.data("resetText",$el[val]()),$el[val](data[state]||this.options[state]),setTimeout(function(){"loadingText"==state?$el.addClass(d).attr(d,d):$el.removeClass(d).removeAttr(d)},0)},Button.prototype.toggle=function(){var $parent=this.$element.closest('[data-toggle="buttons-radio"]');$parent&&$parent.find(".active").removeClass("active"),this.$element.toggleClass("active")};var old=$.fn.button;$.fn.button=function(option){return this.each(function(){var $this=$(this),data=$this.data("button"),options="object"==typeof option&&option;data||$this.data("button",data=new Button(this,options)),"toggle"==option?data.toggle():option&&data.setState(option)})},$.fn.button.defaults={loadingText:"loading..."},$.fn.button.Constructor=Button,$.fn.button.noConflict=function(){return $.fn.button=old,this},$(document).on("click.button.data-api","[data-toggle^=button]",function(e){var $btn=$(e.target);$btn.hasClass("btn")||($btn=$btn.closest(".btn")),$btn.button("toggle")})}(window.jQuery),!function($){"use strict";var Carousel=function(element,options){this.$element=$(element),this.options=options,"hover"==this.options.pause&&this.$element.on("mouseenter",$.proxy(this.pause,this)).on("mouseleave",$.proxy(this.cycle,this))};Carousel.prototype={cycle:function(e){return e||(this.paused=!1),this.options.interval&&!this.paused&&(this.interval=setInterval($.proxy(this.next,this),this.options.interval)),this},to:function(pos){var $active=this.$element.find(".item.active"),children=$active.parent().children(),activePos=children.index($active),that=this;if(!(pos>children.length-1||0>pos))return this.sliding?this.$element.one("slid",function(){that.to(pos)}):activePos==pos?this.pause().cycle():this.slide(pos>activePos?"next":"prev",$(children[pos]))},pause:function(e){return e||(this.paused=!0),this.$element.find(".next, .prev").length&&$.support.transition.end&&(this.$element.trigger($.support.transition.end),this.cycle()),clearInterval(this.interval),this.interval=null,this},next:function(){return this.sliding?void 0:this.slide("next")},prev:function(){return this.sliding?void 0:this.slide("prev")},slide:function(type,next){var e,$active=this.$element.find(".item.active"),$next=next||$active[type](),isCycling=this.interval,direction="next"==type?"left":"right",fallback="next"==type?"first":"last",that=this;if(this.sliding=!0,isCycling&&this.pause(),$next=$next.length?$next:this.$element.find(".item")[fallback](),e=$.Event("slide",{relatedTarget:$next[0]}),!$next.hasClass("active")){if($.support.transition&&this.$element.hasClass("slide")){if(this.$element.trigger(e),e.isDefaultPrevented())return;$next.addClass(type),$next[0].offsetWidth,$active.addClass(direction),$next.addClass(direction),this.$element.one($.support.transition.end,function(){$next.removeClass([type,direction].join(" ")).addClass("active"),$active.removeClass(["active",direction].join(" ")),that.sliding=!1,setTimeout(function(){that.$element.trigger("slid")},0)})}else{if(this.$element.trigger(e),e.isDefaultPrevented())return;$active.removeClass("active"),$next.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return isCycling&&this.cycle()Line truncated
|
||||
+1113
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,172 @@
|
||||
/*
|
||||
* jQuery Iframe Transport Plugin 1.5
|
||||
* https://github.com/blueimp/jQuery-File-Upload
|
||||
*
|
||||
* Copyright 2011, Sebastian Tschan
|
||||
* https://blueimp.net
|
||||
*
|
||||
* Licensed under the MIT license:
|
||||
* http://www.opensource.org/licenses/MIT
|
||||
*/
|
||||
|
||||
/*jslint unparam: true, nomen: true */
|
||||
/*global define, window, document */
|
||||
|
||||
(function (factory) {
|
||||
'use strict';
|
||||
if (typeof define === 'function' && define.amd) {
|
||||
// Register as an anonymous AMD module:
|
||||
define(['jquery'], factory);
|
||||
} else {
|
||||
// Browser globals:
|
||||
factory(window.jQuery);
|
||||
}
|
||||
}(function ($) {
|
||||
'use strict';
|
||||
|
||||
// Helper variable to create unique names for the transport iframes:
|
||||
var counter = 0;
|
||||
|
||||
// The iframe transport accepts three additional options:
|
||||
// options.fileInput: a jQuery collection of file input fields
|
||||
// options.paramName: the parameter name for the file form data,
|
||||
// overrides the name property of the file input field(s),
|
||||
// can be a string or an array of strings.
|
||||
// options.formData: an array of objects with name and value properties,
|
||||
// equivalent to the return data of .serializeArray(), e.g.:
|
||||
// [{name: 'a', value: 1}, {name: 'b', value: 2}]
|
||||
$.ajaxTransport('iframe', function (options) {
|
||||
if (options.async && (options.type === 'POST' || options.type === 'GET')) {
|
||||
var form,
|
||||
iframe;
|
||||
return {
|
||||
send: function (_, completeCallback) {
|
||||
form = $('<form style="display:none;"></form>');
|
||||
form.attr('accept-charset', options.formAcceptCharset);
|
||||
// javascript:false as initial iframe src
|
||||
// prevents warning popups on HTTPS in IE6.
|
||||
// IE versions below IE8 cannot set the name property of
|
||||
// elements that have already been added to the DOM,
|
||||
// so we set the name along with the iframe HTML markup:
|
||||
iframe = $(
|
||||
'<iframe src="javascript:false;" name="iframe-transport-' +
|
||||
(counter += 1) + '"></iframe>'
|
||||
).bind('load', function () {
|
||||
var fileInputClones,
|
||||
paramNames = $.isArray(options.paramName) ?
|
||||
options.paramName : [options.paramName];
|
||||
iframe
|
||||
.unbind('load')
|
||||
.bind('load', function () {
|
||||
var response;
|
||||
// Wrap in a try/catch block to catch exceptions thrown
|
||||
// when trying to access cross-domain iframe contents:
|
||||
try {
|
||||
response = iframe.contents();
|
||||
// Google Chrome and Firefox do not throw an
|
||||
// exception when calling iframe.contents() on
|
||||
// cross-domain requests, so we unify the response:
|
||||
if (!response.length || !response[0].firstChild) {
|
||||
throw new Error();
|
||||
}
|
||||
} catch (e) {
|
||||
response = undefined;
|
||||
}
|
||||
// The complete callback returns the
|
||||
// iframe content document as response object:
|
||||
completeCallback(
|
||||
200,
|
||||
'success',
|
||||
{'iframe': response}
|
||||
);
|
||||
// Fix for IE endless progress bar activity bug
|
||||
// (happens on form submits to iframe targets):
|
||||
$('<iframe src="javascript:false;"></iframe>')
|
||||
.appendTo(form);
|
||||
form.remove();
|
||||
});
|
||||
form
|
||||
.prop('target', iframe.prop('name'))
|
||||
.prop('action', options.url)
|
||||
.prop('method', options.type);
|
||||
if (options.formData) {
|
||||
$.each(options.formData, function (index, field) {
|
||||
$('<input type="hidden"/>')
|
||||
.prop('name', field.name)
|
||||
.val(field.value)
|
||||
.appendTo(form);
|
||||
});
|
||||
}
|
||||
if (options.fileInput && options.fileInput.length &&
|
||||
options.type === 'POST') {
|
||||
fileInputClones = options.fileInput.clone();
|
||||
// Insert a clone for each file input field:
|
||||
options.fileInput.after(function (index) {
|
||||
return fileInputClones[index];
|
||||
});
|
||||
if (options.paramName) {
|
||||
options.fileInput.each(function (index) {
|
||||
$(this).prop(
|
||||
'name',
|
||||
paramNames[index] || options.paramName
|
||||
);
|
||||
});
|
||||
}
|
||||
// Appending the file input fields to the hidden form
|
||||
// removes them from their original location:
|
||||
form
|
||||
.append(options.fileInput)
|
||||
.prop('enctype', 'multipart/form-data')
|
||||
// enctype must be set as encoding for IE:
|
||||
.prop('encoding', 'multipart/form-data');
|
||||
}
|
||||
form.submit();
|
||||
// Insert the file input fields at their original location
|
||||
// by replacing the clones with the originals:
|
||||
if (fileInputClones && fileInputClones.length) {
|
||||
options.fileInput.each(function (index, input) {
|
||||
var clone = $(fileInputClones[index]);
|
||||
$(input).prop('name', clone.prop('name'));
|
||||
clone.replaceWith(input);
|
||||
});
|
||||
}
|
||||
});
|
||||
form.append(iframe).appendTo(document.body);
|
||||
},
|
||||
abort: function () {
|
||||
if (iframe) {
|
||||
// javascript:false as iframe src aborts the request
|
||||
// and prevents warning popups on HTTPS in IE6.
|
||||
// concat is used to avoid the "Script URL" JSLint error:
|
||||
iframe
|
||||
.unbind('load')
|
||||
.prop('src', 'javascript'.concat(':false;'));
|
||||
}
|
||||
if (form) {
|
||||
form.remove();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// The iframe transport returns the iframe content document as response.
|
||||
// The following adds converters from iframe to text, json, html, and script:
|
||||
$.ajaxSetup({
|
||||
converters: {
|
||||
'iframe text': function (iframe) {
|
||||
return $(iframe[0].body).text();
|
||||
},
|
||||
'iframe json': function (iframe) {
|
||||
return $.parseJSON($(iframe[0].body).text());
|
||||
},
|
||||
'iframe html': function (iframe) {
|
||||
return $(iframe[0].body).html();
|
||||
},
|
||||
'iframe script': function (iframe) {
|
||||
return $.globalEval($(iframe[0].body).text());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}));
|
||||
+528
@@ -0,0 +1,528 @@
|
||||
/*
|
||||
* jQuery UI Widget 1.9.1+amd
|
||||
* https://github.com/blueimp/jQuery-File-Upload
|
||||
*
|
||||
* Copyright 2012 jQuery Foundation and other contributors
|
||||
* Released under the MIT license.
|
||||
* http://jquery.org/license
|
||||
*
|
||||
* http://api.jqueryui.com/jQuery.widget/
|
||||
*/
|
||||
|
||||
(function (factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
// Register as an anonymous AMD module:
|
||||
define(["jquery"], factory);
|
||||
} else {
|
||||
// Browser globals:
|
||||
factory(jQuery);
|
||||
}
|
||||
}(function( $, undefined ) {
|
||||
|
||||
var uuid = 0,
|
||||
slice = Array.prototype.slice,
|
||||
_cleanData = $.cleanData;
|
||||
$.cleanData = function( elems ) {
|
||||
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
|
||||
try {
|
||||
$( elem ).triggerHandler( "remove" );
|
||||
// http://bugs.jquery.com/ticket/8235
|
||||
} catch( e ) {}
|
||||
}
|
||||
_cleanData( elems );
|
||||
};
|
||||
|
||||
$.widget = function( name, base, prototype ) {
|
||||
var fullName, existingConstructor, constructor, basePrototype,
|
||||
namespace = name.split( "." )[ 0 ];
|
||||
|
||||
name = name.split( "." )[ 1 ];
|
||||
fullName = namespace + "-" + name;
|
||||
|
||||
if ( !prototype ) {
|
||||
prototype = base;
|
||||
base = $.Widget;
|
||||
}
|
||||
|
||||
// create selector for plugin
|
||||
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
|
||||
return !!$.data( elem, fullName );
|
||||
};
|
||||
|
||||
$[ namespace ] = $[ namespace ] || {};
|
||||
existingConstructor = $[ namespace ][ name ];
|
||||
constructor = $[ namespace ][ name ] = function( options, element ) {
|
||||
// allow instantiation without "new" keyword
|
||||
if ( !this._createWidget ) {
|
||||
return new constructor( options, element );
|
||||
}
|
||||
|
||||
// allow instantiation without initializing for simple inheritance
|
||||
// must use "new" keyword (the code above always passes args)
|
||||
if ( arguments.length ) {
|
||||
this._createWidget( options, element );
|
||||
}
|
||||
};
|
||||
// extend with the existing constructor to carry over any static properties
|
||||
$.extend( constructor, existingConstructor, {
|
||||
version: prototype.version,
|
||||
// copy the object used to create the prototype in case we need to
|
||||
// redefine the widget later
|
||||
_proto: $.extend( {}, prototype ),
|
||||
// track widgets that inherit from this widget in case this widget is
|
||||
// redefined after a widget inherits from it
|
||||
_childConstructors: []
|
||||
});
|
||||
|
||||
basePrototype = new base();
|
||||
// we need to make the options hash a property directly on the new instance
|
||||
// otherwise we'll modify the options hash on the prototype that we're
|
||||
// inheriting from
|
||||
basePrototype.options = $.widget.extend( {}, basePrototype.options );
|
||||
$.each( prototype, function( prop, value ) {
|
||||
if ( $.isFunction( value ) ) {
|
||||
prototype[ prop ] = (function() {
|
||||
var _super = function() {
|
||||
return base.prototype[ prop ].apply( this, arguments );
|
||||
},
|
||||
_superApply = function( args ) {
|
||||
return base.prototype[ prop ].apply( this, args );
|
||||
};
|
||||
return function() {
|
||||
var __super = this._super,
|
||||
__superApply = this._superApply,
|
||||
returnValue;
|
||||
|
||||
this._super = _super;
|
||||
this._superApply = _superApply;
|
||||
|
||||
returnValue = value.apply( this, arguments );
|
||||
|
||||
this._super = __super;
|
||||
this._superApply = __superApply;
|
||||
|
||||
return returnValue;
|
||||
};
|
||||
})();
|
||||
}
|
||||
});
|
||||
constructor.prototype = $.widget.extend( basePrototype, {
|
||||
// TODO: remove support for widgetEventPrefix
|
||||
// always use the name + a colon as the prefix, e.g., draggable:start
|
||||
// don't prefix for widgets that aren't DOM-based
|
||||
widgetEventPrefix: basePrototype.widgetEventPrefix || name
|
||||
}, prototype, {
|
||||
constructor: constructor,
|
||||
namespace: namespace,
|
||||
widgetName: name,
|
||||
// TODO remove widgetBaseClass, see #8155
|
||||
widgetBaseClass: fullName,
|
||||
widgetFullName: fullName
|
||||
});
|
||||
|
||||
// If this widget is being redefined then we need to find all widgets that
|
||||
// are inheriting from it and redefine all of them so that they inherit from
|
||||
// the new version of this widget. We're essentially trying to replace one
|
||||
// level in the prototype chain.
|
||||
if ( existingConstructor ) {
|
||||
$.each( existingConstructor._childConstructors, function( i, child ) {
|
||||
var childPrototype = child.prototype;
|
||||
|
||||
// redefine the child widget using the same prototype that was
|
||||
// originally used, but inherit from the new version of the base
|
||||
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
|
||||
});
|
||||
// remove the list of existing child constructors from the old constructor
|
||||
// so the old child constructors can be garbage collected
|
||||
delete existingConstructor._childConstructors;
|
||||
} else {
|
||||
base._childConstructors.push( constructor );
|
||||
}
|
||||
|
||||
$.widget.bridge( name, constructor );
|
||||
};
|
||||
|
||||
$.widget.extend = function( target ) {
|
||||
var input = slice.call( arguments, 1 ),
|
||||
inputIndex = 0,
|
||||
inputLength = input.length,
|
||||
key,
|
||||
value;
|
||||
for ( ; inputIndex < inputLength; inputIndex++ ) {
|
||||
for ( key in input[ inputIndex ] ) {
|
||||
value = input[ inputIndex ][ key ];
|
||||
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
|
||||
// Clone objects
|
||||
if ( $.isPlainObject( value ) ) {
|
||||
target[ key ] = $.isPlainObject( target[ key ] ) ?
|
||||
$.widget.extend( {}, target[ key ], value ) :
|
||||
// Don't extend strings, arrays, etc. with objects
|
||||
$.widget.extend( {}, value );
|
||||
// Copy everything else by reference
|
||||
} else {
|
||||
target[ key ] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return target;
|
||||
};
|
||||
|
||||
$.widget.bridge = function( name, object ) {
|
||||
var fullName = object.prototype.widgetFullName;
|
||||
$.fn[ name ] = function( options ) {
|
||||
var isMethodCall = typeof options === "string",
|
||||
args = slice.call( arguments, 1 ),
|
||||
returnValue = this;
|
||||
|
||||
// allow multiple hashes to be passed on init
|
||||
options = !isMethodCall && args.length ?
|
||||
$.widget.extend.apply( null, [ options ].concat(args) ) :
|
||||
options;
|
||||
|
||||
if ( isMethodCall ) {
|
||||
this.each(function() {
|
||||
var methodValue,
|
||||
instance = $.data( this, fullName );
|
||||
if ( !instance ) {
|
||||
return $.error( "cannot call methods on " + name + " prior to initialization; " +
|
||||
"attempted to call method '" + options + "'" );
|
||||
}
|
||||
if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
|
||||
return $.error( "no such method '" + options + "' for " + name + " widget instance" );
|
||||
}
|
||||
methodValue = instance[ options ].apply( instance, args );
|
||||
if ( methodValue !== instance && methodValue !== undefined ) {
|
||||
returnValue = methodValue && methodValue.jquery ?
|
||||
returnValue.pushStack( methodValue.get() ) :
|
||||
methodValue;
|
||||
return false;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this.each(function() {
|
||||
var instance = $.data( this, fullName );
|
||||
if ( instance ) {
|
||||
instance.option( options || {} )._init();
|
||||
} else {
|
||||
new object( options, this );
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return returnValue;
|
||||
};
|
||||
};
|
||||
|
||||
$.Widget = function( /* options, element */ ) {};
|
||||
$.Widget._childConstructors = [];
|
||||
|
||||
$.Widget.prototype = {
|
||||
widgetName: "widget",
|
||||
widgetEventPrefix: "",
|
||||
defaultElement: "<div>",
|
||||
options: {
|
||||
disabled: false,
|
||||
|
||||
// callbacks
|
||||
create: null
|
||||
},
|
||||
_createWidget: function( options, element ) {
|
||||
element = $( element || this.defaultElement || this )[ 0 ];
|
||||
this.element = $( element );
|
||||
this.uuid = uuid++;
|
||||
this.eventNamespace = "." + this.widgetName + this.uuid;
|
||||
this.options = $.widget.extend( {},
|
||||
this.options,
|
||||
this._getCreateOptions(),
|
||||
options );
|
||||
|
||||
this.bindings = $();
|
||||
this.hoverable = $();
|
||||
this.focusable = $();
|
||||
|
||||
if ( element !== this ) {
|
||||
// 1.9 BC for #7810
|
||||
// TODO remove dual storage
|
||||
$.data( element, this.widgetName, this );
|
||||
$.data( element, this.widgetFullName, this );
|
||||
this._on( this.element, {
|
||||
remove: function( event ) {
|
||||
if ( event.target === element ) {
|
||||
this.destroy();
|
||||
}
|
||||
}
|
||||
});
|
||||
this.document = $( element.style ?
|
||||
// element within the document
|
||||
element.ownerDocument :
|
||||
// element is window or document
|
||||
element.document || element );
|
||||
this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
|
||||
}
|
||||
|
||||
this._create();
|
||||
this._trigger( "create", null, this._getCreateEventData() );
|
||||
this._init();
|
||||
},
|
||||
_getCreateOptions: $.noop,
|
||||
_getCreateEventData: $.noop,
|
||||
_create: $.noop,
|
||||
_init: $.noop,
|
||||
|
||||
destroy: function() {
|
||||
this._destroy();
|
||||
// we can probably remove the unbind calls in 2.0
|
||||
// all event bindings should go through this._on()
|
||||
this.element
|
||||
.unbind( this.eventNamespace )
|
||||
// 1.9 BC for #7810
|
||||
// TODO remove dual storage
|
||||
.removeData( this.widgetName )
|
||||
.removeData( this.widgetFullName )
|
||||
// support: jquery <1.6.3
|
||||
// http://bugs.jquery.com/ticket/9413
|
||||
.removeData( $.camelCase( this.widgetFullName ) );
|
||||
this.widget()
|
||||
.unbind( this.eventNamespace )
|
||||
.removeAttr( "aria-disabled" )
|
||||
.removeClass(
|
||||
this.widgetFullName + "-disabled " +
|
||||
"ui-state-disabled" );
|
||||
|
||||
// clean up events and states
|
||||
this.bindings.unbind( this.eventNamespace );
|
||||
this.hoverable.removeClass( "ui-state-hover" );
|
||||
this.focusable.removeClass( "ui-state-focus" );
|
||||
},
|
||||
_destroy: $.noop,
|
||||
|
||||
widget: function() {
|
||||
return this.element;
|
||||
},
|
||||
|
||||
option: function( key, value ) {
|
||||
var options = key,
|
||||
parts,
|
||||
curOption,
|
||||
i;
|
||||
|
||||
if ( arguments.length === 0 ) {
|
||||
// don't return a reference to the internal hash
|
||||
return $.widget.extend( {}, this.options );
|
||||
}
|
||||
|
||||
if ( typeof key === "string" ) {
|
||||
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
|
||||
options = {};
|
||||
parts = key.split( "." );
|
||||
key = parts.shift();
|
||||
if ( parts.length ) {
|
||||
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
|
||||
for ( i = 0; i < parts.length - 1; i++ ) {
|
||||
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
|
||||
curOption = curOption[ parts[ i ] ];
|
||||
}
|
||||
key = parts.pop();
|
||||
if ( value === undefined ) {
|
||||
return curOption[ key ] === undefined ? null : curOption[ key ];
|
||||
}
|
||||
curOption[ key ] = value;
|
||||
} else {
|
||||
if ( value === undefined ) {
|
||||
return this.options[ key ] === undefined ? null : this.options[ key ];
|
||||
}
|
||||
options[ key ] = value;
|
||||
}
|
||||
}
|
||||
|
||||
this._setOptions( options );
|
||||
|
||||
return this;
|
||||
},
|
||||
_setOptions: function( options ) {
|
||||
var key;
|
||||
|
||||
for ( key in options ) {
|
||||
this._setOption( key, options[ key ] );
|
||||
}
|
||||
|
||||
return this;
|
||||
},
|
||||
_setOption: function( key, value ) {
|
||||
this.options[ key ] = value;
|
||||
|
||||
if ( key === "disabled" ) {
|
||||
this.widget()
|
||||
.toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
|
||||
.attr( "aria-disabled", value );
|
||||
this.hoverable.removeClass( "ui-state-hover" );
|
||||
this.focusable.removeClass( "ui-state-focus" );
|
||||
}
|
||||
|
||||
return this;
|
||||
},
|
||||
|
||||
enable: function() {
|
||||
return this._setOption( "disabled", false );
|
||||
},
|
||||
disable: function() {
|
||||
return this._setOption( "disabled", true );
|
||||
},
|
||||
|
||||
_on: function( element, handlers ) {
|
||||
var delegateElement,
|
||||
instance = this;
|
||||
// no element argument, shuffle and use this.element
|
||||
if ( !handlers ) {
|
||||
handlers = element;
|
||||
element = this.element;
|
||||
delegateElement = this.widget();
|
||||
} else {
|
||||
// accept selectors, DOM elements
|
||||
element = delegateElement = $( element );
|
||||
this.bindings = this.bindings.add( element );
|
||||
}
|
||||
|
||||
$.each( handlers, function( event, handler ) {
|
||||
function handlerProxy() {
|
||||
// allow widgets to customize the disabled handling
|
||||
// - disabled as an array instead of boolean
|
||||
// - disabled class as method for disabling individual parts
|
||||
if ( instance.options.disabled === true ||
|
||||
$( this ).hasClass( "ui-state-disabled" ) ) {
|
||||
return;
|
||||
}
|
||||
return ( typeof handler === "string" ? instance[ handler ] : handler )
|
||||
.apply( instance, arguments );
|
||||
}
|
||||
|
||||
// copy the guid so direct unbinding works
|
||||
if ( typeof handler !== "string" ) {
|
||||
handlerProxy.guid = handler.guid =
|
||||
handler.guid || handlerProxy.guid || $.guid++;
|
||||
}
|
||||
|
||||
var match = event.match( /^(\w+)\s*(.*)$/ ),
|
||||
eventName = match[1] + instance.eventNamespace,
|
||||
selector = match[2];
|
||||
if ( selector ) {
|
||||
delegateElement.delegate( selector, eventName, handlerProxy );
|
||||
} else {
|
||||
element.bind( eventName, handlerProxy );
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
_off: function( element, eventName ) {
|
||||
eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
|
||||
element.unbind( eventName ).undelegate( eventName );
|
||||
},
|
||||
|
||||
_delay: function( handler, delay ) {
|
||||
function handlerProxy() {
|
||||
return ( typeof handler === "string" ? instance[ handler ] : handler )
|
||||
.apply( instance, arguments );
|
||||
}
|
||||
var instance = this;
|
||||
return setTimeout( handlerProxy, delay || 0 );
|
||||
},
|
||||
|
||||
_hoverable: function( element ) {
|
||||
this.hoverable = this.hoverable.add( element );
|
||||
this._on( element, {
|
||||
mouseenter: function( event ) {
|
||||
$( event.currentTarget ).addClass( "ui-state-hover" );
|
||||
},
|
||||
mouseleave: function( event ) {
|
||||
$( event.currentTarget ).removeClass( "ui-state-hover" );
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
_focusable: function( element ) {
|
||||
this.focusable = this.focusable.add( element );
|
||||
this._on( element, {
|
||||
focusin: function( event ) {
|
||||
$( event.currentTarget ).addClass( "ui-state-focus" );
|
||||
},
|
||||
focusout: function( event ) {
|
||||
$( event.currentTarget ).removeClass( "ui-state-focus" );
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
_trigger: function( type, event, data ) {
|
||||
var prop, orig,
|
||||
callback = this.options[ type ];
|
||||
|
||||
data = data || {};
|
||||
event = $.Event( event );
|
||||
event.type = ( type === this.widgetEventPrefix ?
|
||||
type :
|
||||
this.widgetEventPrefix + type ).toLowerCase();
|
||||
// the original event may come from any element
|
||||
// so we need to reset the target on the new event
|
||||
event.target = this.element[ 0 ];
|
||||
|
||||
// copy original event properties over to the new event
|
||||
orig = event.originalEvent;
|
||||
if ( orig ) {
|
||||
for ( prop in orig ) {
|
||||
if ( !( prop in event ) ) {
|
||||
event[ prop ] = orig[ prop ];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.element.trigger( event, data );
|
||||
return !( $.isFunction( callback ) &&
|
||||
callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
|
||||
event.isDefaultPrevented() );
|
||||
}
|
||||
};
|
||||
|
||||
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
|
||||
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
|
||||
if ( typeof options === "string" ) {
|
||||
options = { effect: options };
|
||||
}
|
||||
var hasOptions,
|
||||
effectName = !options ?
|
||||
method :
|
||||
options === true || typeof options === "number" ?
|
||||
defaultEffect :
|
||||
options.effect || defaultEffect;
|
||||
options = options || {};
|
||||
if ( typeof options === "number" ) {
|
||||
options = { duration: options };
|
||||
}
|
||||
hasOptions = !$.isEmptyObject( options );
|
||||
options.complete = callback;
|
||||
if ( options.delay ) {
|
||||
element.delay( options.delay );
|
||||
}
|
||||
if ( hasOptions && $.effects && ( $.effects.effect[ effectName ] || $.uiBackCompat !== false && $.effects[ effectName ] ) ) {
|
||||
element[ method ]( options );
|
||||
} else if ( effectName !== method && element[ effectName ] ) {
|
||||
element[ effectName ]( options.duration, options.easing, callback );
|
||||
} else {
|
||||
element.queue(function( next ) {
|
||||
$( this )[ method ]();
|
||||
if ( callback ) {
|
||||
callback.call( element[ 0 ] );
|
||||
}
|
||||
next();
|
||||
});
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
// DEPRECATED
|
||||
if ( $.uiBackCompat !== false ) {
|
||||
$.Widget.prototype._getCreateOptions = function() {
|
||||
return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ];
|
||||
};
|
||||
}
|
||||
|
||||
}));
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
// Knockout JavaScript library v2.2.0
|
||||
// (c) Steven Sanderson - http://knockoutjs.com/
|
||||
// License: MIT (http://www.opensource.org/licenses/mit-license.php)
|
||||
|
||||
(function() {function i(v){throw v;}var l=!0,n=null,q=!1;function t(v){return function(){return v}};var w=window,x=document,fa=navigator,E=window.jQuery,H=void 0;
|
||||
function K(v){function ga(a,d,c,e,f){var g=[],a=b.j(function(){var a=d(c,f)||[];0<g.length&&(b.a.Xa(L(g),a),e&&b.r.K(e,n,[c,a,f]));g.splice(0,g.length);b.a.P(g,a)},n,{W:a,Ja:function(){return 0==g.length||!b.a.X(g[0])}});return{M:g,j:a.oa()?a:H}}function L(a){for(;a.length&&!b.a.X(a[0]);)a.splice(0,1);if(1<a.length){for(var d=a[0],c=a[a.length-1],e=[d];d!==c;){d=d.nextSibling;if(!d)return;e.push(d)}Array.prototype.splice.apply(a,[0,a.length].concat(e))}return a}function R(a,b,c,e,f){var g=Math.min,
|
||||
h=Math.max,j=[],k,m=a.length,p,r=b.length,u=r-m||1,F=m+r+1,I,z,y;for(k=0;k<=m;k++){z=I;j.push(I=[]);y=g(r,k+u);for(p=h(0,k-1);p<=y;p++)I[p]=p?k?a[k-1]===b[p-1]?z[p-1]:g(z[p]||F,I[p-1]||F)+1:p+1:k+1}g=[];h=[];u=[];k=m;for(p=r;k||p;)r=j[k][p]-1,p&&r===j[k][p-1]?h.push(g[g.length]={status:c,value:b[--p],index:p}):k&&r===j[k-1][p]?u.push(g[g.length]={status:e,value:a[--k],index:k}):(g.push({status:"retained",value:b[--p]}),--k);if(h.length&&u.length)for(var a=10*m,s,b=c=0;(f||b<a)&&(s=h[c]);c++){for(e=
|
||||
0;j=u[e];e++)if(s.value===j.value){s.moved=j.index;j.moved=s.index;u.splice(e,1);b=e=0;break}b+=e}return g.reverse()}function S(a,d,c,e,f){var f=f||{},g=a&&M(a),g=g&&g.ownerDocument,h=f.templateEngine||N;b.ya.ub(c,h,g);c=h.renderTemplate(c,e,f,g);("number"!=typeof c.length||0<c.length&&"number"!=typeof c[0].nodeType)&&i(Error("Template engine must return an array of DOM nodes"));g=q;switch(d){case "replaceChildren":b.e.N(a,c);g=l;break;case "replaceNode":b.a.Xa(a,c);g=l;break;case "ignoreTargetNode":break;
|
||||
default:i(Error("Unknown renderMode: "+d))}g&&(T(c,e),f.afterRender&&b.r.K(f.afterRender,n,[c,e.$data]));return c}function M(a){return a.nodeType?a:0<a.length?a[0]:n}function T(a,d){if(a.length){var c=a[0],e=a[a.length-1];U(c,e,function(a){b.Ca(d,a)});U(c,e,function(a){b.s.hb(a,[d])})}}function U(a,d,c){for(var e,d=b.e.nextSibling(d);a&&(e=a)!==d;)a=b.e.nextSibling(e),(1===e.nodeType||8===e.nodeType)&&c(e)}function V(a,d,c){for(var a=b.g.aa(a),e=b.g.Q,f=0;f<a.length;f++){var g=a[f].key;if(e.hasOwnProperty(g)){var h=
|
||||
e[g];"function"===typeof h?(g=h(a[f].value))&&i(Error(g)):h||i(Error("This template engine does not support the '"+g+"' binding within its templates"))}}a="ko.__tr_ambtns(function($context,$element){return(function(){return{ "+b.g.ba(a)+" } })()})";return c.createJavaScriptEvaluatorBlock(a)+d}function W(a,d,c,e){function f(a){return function(){return j[a]}}function g(){return j}var h=0,j,k;b.j(function(){var m=c&&c instanceof b.z?c:new b.z(b.a.d(c)),p=m.$data;e&&b.cb(a,m);if(j=("function"==typeof d?
|
||||
d(m,a):d)||b.J.instance.getBindings(a,m)){if(0===h){h=1;for(var r in j){var u=b.c[r];u&&8===a.nodeType&&!b.e.I[r]&&i(Error("The binding '"+r+"' cannot be used with virtual elements"));if(u&&"function"==typeof u.init&&(u=(0,u.init)(a,f(r),g,p,m))&&u.controlsDescendantBindings)k!==H&&i(Error("Multiple bindings ("+k+" and "+r+") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.")),k=r}h=2}if(2===h)for(r in j)(u=b.c[r])&&"function"==
|
||||
typeof u.update&&(0,u.update)(a,f(r),g,p,m)}},n,{W:a});return{Mb:k===H}}function X(a,d,c){var e=l,f=1===d.nodeType;f&&b.e.Sa(d);if(f&&c||b.J.instance.nodeHasBindings(d))e=W(d,n,a,c).Mb;e&&Y(a,d,!f)}function Y(a,d,c){for(var e=b.e.firstChild(d);d=e;)e=b.e.nextSibling(d),X(a,d,c)}function Z(a,b){var c=$(a,b);return c?0<c.length?c[c.length-1].nextSibling:a.nextSibling:n}function $(a,b){for(var c=a,e=1,f=[];c=c.nextSibling;){if(G(c)&&(e--,0===e))return f;f.push(c);A(c)&&e++}b||i(Error("Cannot find closing comment tag to match: "+
|
||||
a.nodeValue));return n}function G(a){return 8==a.nodeType&&(J?a.text:a.nodeValue).match(ha)}function A(a){return 8==a.nodeType&&(J?a.text:a.nodeValue).match(ia)}function O(a,b){for(var c=n;a!=c;)c=a,a=a.replace(ja,function(a,c){return b[c]});return a}function ka(){var a=[],d=[];this.save=function(c,e){var f=b.a.i(a,c);0<=f?d[f]=e:(a.push(c),d.push(e))};this.get=function(c){c=b.a.i(a,c);return 0<=c?d[c]:H}}function aa(a,b,c){function e(e){var g=b(a[e]);switch(typeof g){case "boolean":case "number":case "string":case "function":f[e]=
|
||||
g;break;case "object":case "undefined":var h=c.get(g);f[e]=h!==H?h:aa(g,b,c)}}c=c||new ka;a=b(a);if(!("object"==typeof a&&a!==n&&a!==H&&!(a instanceof Date)))return a;var f=a instanceof Array?[]:{};c.save(a,f);var g=a;if(g instanceof Array){for(var h=0;h<g.length;h++)e(h);"function"==typeof g.toJSON&&e("toJSON")}else for(h in g)e(h);return f}function ba(a,d){if(a)if(8==a.nodeType){var c=b.s.Ta(a.nodeValue);c!=n&&d.push({rb:a,Eb:c})}else if(1==a.nodeType)for(var c=0,e=a.childNodes,f=e.length;c<f;c++)ba(e[c],
|
||||
d)}function P(a,d,c,e){b.c[a]={init:function(a){b.a.f.set(a,ca,{});return{controlsDescendantBindings:l}},update:function(a,g,h,j,k){var h=b.a.f.get(a,ca),g=b.a.d(g()),j=!c!==!g,m=!h.Ya;if(m||d||j!==h.pb)m&&(h.Ya=b.a.Ha(b.e.childNodes(a),l)),j?(m||b.e.N(a,b.a.Ha(h.Ya)),b.Da(e?e(k,g):k,a)):b.e.Y(a),h.pb=j}};b.g.Q[a]=q;b.e.I[a]=l}function da(a,d,c){c&&d!==b.k.q(a)&&b.k.T(a,d);d!==b.k.q(a)&&b.r.K(b.a.Aa,n,[a,"change"])}var b="undefined"!==typeof v?v:{};b.b=function(a,d){for(var c=a.split("."),e=b,f=0;f<
|
||||
c.length-1;f++)e=e[c[f]];e[c[c.length-1]]=d};b.p=function(a,b,c){a[b]=c};b.version="2.2.0";b.b("version",b.version);b.a=new function(){function a(a,d){if("input"!==b.a.u(a)||!a.type||"click"!=d.toLowerCase())return q;var c=a.type;return"checkbox"==c||"radio"==c}var d=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,c={},e={};c[/Firefox\/2/i.test(fa.userAgent)?"KeyboardEvent":"UIEvents"]=["keyup","keydown","keypress"];c.MouseEvents="click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave".split(" ");
|
||||
for(var f in c){var g=c[f];if(g.length)for(var h=0,j=g.length;h<j;h++)e[g[h]]=f}var k={propertychange:l},m,c=3;f=x.createElement("div");for(g=f.getElementsByTagName("i");f.innerHTML="<\!--[if gt IE "+ ++c+"]><i></i><![endif]--\>",g[0];);m=4<c?c:H;return{Ma:["authenticity_token",/^__RequestVerificationToken(_.*)?$/],o:function(a,b){for(var d=0,c=a.length;d<c;d++)b(a[d])},i:function(a,b){if("function"==typeof Array.prototype.indexOf)return Array.prototype.indexOf.call(a,b);for(var d=0,c=a.length;d<
|
||||
c;d++)if(a[d]===b)return d;return-1},kb:function(a,b,d){for(var c=0,e=a.length;c<e;c++)if(b.call(d,a[c]))return a[c];return n},ga:function(a,d){var c=b.a.i(a,d);0<=c&&a.splice(c,1)},Fa:function(a){for(var a=a||[],d=[],c=0,e=a.length;c<e;c++)0>b.a.i(d,a[c])&&d.push(a[c]);return d},V:function(a,b){for(var a=a||[],d=[],c=0,e=a.length;c<e;c++)d.push(b(a[c]));return d},fa:function(a,b){for(var a=a||[],d=[],c=0,e=a.length;c<e;c++)b(a[c])&&d.push(a[c]);return d},P:function(a,b){if(b instanceof Array)a.push.apply(a,
|
||||
b);else for(var d=0,c=b.length;d<c;d++)a.push(b[d]);return a},extend:function(a,b){if(b)for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);return a},ka:function(a){for(;a.firstChild;)b.removeNode(a.firstChild)},Gb:function(a){for(var a=b.a.L(a),d=x.createElement("div"),c=0,e=a.length;c<e;c++)d.appendChild(b.A(a[c]));return d},Ha:function(a,d){for(var c=0,e=a.length,g=[];c<e;c++){var f=a[c].cloneNode(l);g.push(d?b.A(f):f)}return g},N:function(a,d){b.a.ka(a);if(d)for(var c=0,e=d.length;c<e;c++)a.appendChild(d[c])},
|
||||
Xa:function(a,d){var c=a.nodeType?[a]:a;if(0<c.length){for(var e=c[0],g=e.parentNode,f=0,h=d.length;f<h;f++)g.insertBefore(d[f],e);f=0;for(h=c.length;f<h;f++)b.removeNode(c[f])}},ab:function(a,b){7>m?a.setAttribute("selected",b):a.selected=b},D:function(a){return(a||"").replace(d,"")},Qb:function(a,d){for(var c=[],e=(a||"").split(d),f=0,g=e.length;f<g;f++){var h=b.a.D(e[f]);""!==h&&c.push(h)}return c},Nb:function(a,b){a=a||"";return b.length>a.length?q:a.substring(0,b.length)===b},sb:function(a,b){if(b.compareDocumentPosition)return 16==
|
||||
(b.compareDocumentPosition(a)&16);for(;a!=n;){if(a==b)return l;a=a.parentNode}return q},X:function(a){return b.a.sb(a,a.ownerDocument)},u:function(a){return a&&a.tagName&&a.tagName.toLowerCase()},n:function(b,d,c){var e=m&&k[d];if(!e&&"undefined"!=typeof E){if(a(b,d))var f=c,c=function(a,b){var d=this.checked;b&&(this.checked=b.mb!==l);f.call(this,a);this.checked=d};E(b).bind(d,c)}else!e&&"function"==typeof b.addEventListener?b.addEventListener(d,c,q):"undefined"!=typeof b.attachEvent?b.attachEvent("on"+
|
||||
d,function(a){c.call(b,a)}):i(Error("Browser doesn't support addEventListener or attachEvent"))},Aa:function(b,d){(!b||!b.nodeType)&&i(Error("element must be a DOM node when calling triggerEvent"));if("undefined"!=typeof E){var c=[];a(b,d)&&c.push({mb:b.checked});E(b).trigger(d,c)}else"function"==typeof x.createEvent?"function"==typeof b.dispatchEvent?(c=x.createEvent(e[d]||"HTMLEvents"),c.initEvent(d,l,l,w,0,0,0,0,0,q,q,q,q,0,b),b.dispatchEvent(c)):i(Error("The supplied element doesn't support dispatchEvent")):
|
||||
"undefined"!=typeof b.fireEvent?(a(b,d)&&(b.checked=b.checked!==l),b.fireEvent("on"+d)):i(Error("Browser doesn't support triggering events"))},d:function(a){return b.$(a)?a():a},ta:function(a){return b.$(a)?a.t():a},da:function(a,d,c){if(d){var e=/[\w-]+/g,f=a.className.match(e)||[];b.a.o(d.match(e),function(a){var d=b.a.i(f,a);0<=d?c||f.splice(d,1):c&&f.push(a)});a.className=f.join(" ")}},bb:function(a,d){var c=b.a.d(d);if(c===n||c===H)c="";if(3===a.nodeType)a.data=c;else{var e=b.e.firstChild(a);
|
||||
!e||3!=e.nodeType||b.e.nextSibling(e)?b.e.N(a,[x.createTextNode(c)]):e.data=c;b.a.vb(a)}},$a:function(a,b){a.name=b;if(7>=m)try{a.mergeAttributes(x.createElement("<input name='"+a.name+"'/>"),q)}catch(d){}},vb:function(a){9<=m&&(a=1==a.nodeType?a:a.parentNode,a.style&&(a.style.zoom=a.style.zoom))},tb:function(a){if(9<=m){var b=a.style.width;a.style.width=0;a.style.width=b}},Kb:function(a,d){for(var a=b.a.d(a),d=b.a.d(d),c=[],e=a;e<=d;e++)c.push(e);return c},L:function(a){for(var b=[],d=0,c=a.length;d<
|
||||
c;d++)b.push(a[d]);return b},Ob:6===m,Pb:7===m,Z:m,Na:function(a,d){for(var c=b.a.L(a.getElementsByTagName("input")).concat(b.a.L(a.getElementsByTagName("textarea"))),e="string"==typeof d?function(a){return a.name===d}:function(a){return d.test(a.name)},f=[],g=c.length-1;0<=g;g--)e(c[g])&&f.push(c[g]);return f},Hb:function(a){return"string"==typeof a&&(a=b.a.D(a))?w.JSON&&w.JSON.parse?w.JSON.parse(a):(new Function("return "+a))():n},wa:function(a,d,c){("undefined"==typeof JSON||"undefined"==typeof JSON.stringify)&&
|
||||
i(Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js"));return JSON.stringify(b.a.d(a),d,c)},Ib:function(a,d,c){var c=c||{},e=c.params||{},f=c.includeFields||this.Ma,g=a;if("object"==typeof a&&"form"===b.a.u(a))for(var g=a.action,h=f.length-1;0<=h;h--)for(var j=b.a.Na(a,f[h]),k=j.length-1;0<=k;k--)e[j[k].name]=j[k].value;var d=b.a.d(d),m=x.createElement("form");
|
||||
m.style.display="none";m.action=g;m.method="post";for(var v in d)a=x.createElement("input"),a.name=v,a.value=b.a.wa(b.a.d(d[v])),m.appendChild(a);for(v in e)a=x.createElement("input"),a.name=v,a.value=e[v],m.appendChild(a);x.body.appendChild(m);c.submitter?c.submitter(m):m.submit();setTimeout(function(){m.parentNode.removeChild(m)},0)}}};b.b("utils",b.a);b.b("utils.arrayForEach",b.a.o);b.b("utils.arrayFirst",b.a.kb);b.b("utils.arrayFilter",b.a.fa);b.b("utils.arrayGetDistinctValues",b.a.Fa);b.b("utils.arrayIndexOf",
|
||||
b.a.i);b.b("utils.arrayMap",b.a.V);b.b("utils.arrayPushAll",b.a.P);b.b("utils.arrayRemoveItem",b.a.ga);b.b("utils.extend",b.a.extend);b.b("utils.fieldsIncludedWithJsonPost",b.a.Ma);b.b("utils.getFormFields",b.a.Na);b.b("utils.peekObservable",b.a.ta);b.b("utils.postJson",b.a.Ib);b.b("utils.parseJson",b.a.Hb);b.b("utils.registerEventHandler",b.a.n);b.b("utils.stringifyJson",b.a.wa);b.b("utils.range",b.a.Kb);b.b("utils.toggleDomNodeCssClass",b.a.da);b.b("utils.triggerEvent",b.a.Aa);b.b("utils.unwrapObservable",
|
||||
b.a.d);Function.prototype.bind||(Function.prototype.bind=function(a){var b=this,c=Array.prototype.slice.call(arguments),a=c.shift();return function(){return b.apply(a,c.concat(Array.prototype.slice.call(arguments)))}});b.a.f=new function(){var a=0,d="__ko__"+(new Date).getTime(),c={};return{get:function(a,d){var c=b.a.f.getAll(a,q);return c===H?H:c[d]},set:function(a,d,c){c===H&&b.a.f.getAll(a,q)===H||(b.a.f.getAll(a,l)[d]=c)},getAll:function(b,f){var g=b[d];if(!g||!("null"!==g&&c[g])){if(!f)return H;
|
||||
g=b[d]="ko"+a++;c[g]={}}return c[g]},clear:function(a){var b=a[d];return b?(delete c[b],a[d]=n,l):q}}};b.b("utils.domData",b.a.f);b.b("utils.domData.clear",b.a.f.clear);b.a.F=new function(){function a(a,d){var e=b.a.f.get(a,c);e===H&&d&&(e=[],b.a.f.set(a,c,e));return e}function d(c){var e=a(c,q);if(e)for(var e=e.slice(0),j=0;j<e.length;j++)e[j](c);b.a.f.clear(c);"function"==typeof E&&"function"==typeof E.cleanData&&E.cleanData([c]);if(f[c.nodeType])for(e=c.firstChild;c=e;)e=c.nextSibling,8===c.nodeType&&
|
||||
d(c)}var c="__ko_domNodeDisposal__"+(new Date).getTime(),e={1:l,8:l,9:l},f={1:l,9:l};return{Ba:function(b,d){"function"!=typeof d&&i(Error("Callback must be a function"));a(b,l).push(d)},Wa:function(d,e){var f=a(d,q);f&&(b.a.ga(f,e),0==f.length&&b.a.f.set(d,c,H))},A:function(a){if(e[a.nodeType]&&(d(a),f[a.nodeType])){var c=[];b.a.P(c,a.getElementsByTagName("*"));for(var j=0,k=c.length;j<k;j++)d(c[j])}return a},removeNode:function(a){b.A(a);a.parentNode&&a.parentNode.removeChild(a)}}};b.A=b.a.F.A;
|
||||
b.removeNode=b.a.F.removeNode;b.b("cleanNode",b.A);b.b("removeNode",b.removeNode);b.b("utils.domNodeDisposal",b.a.F);b.b("utils.domNodeDisposal.addDisposeCallback",b.a.F.Ba);b.b("utils.domNodeDisposal.removeDisposeCallback",b.a.F.Wa);b.a.sa=function(a){var d;if("undefined"!=typeof E){if((d=E.clean([a]))&&d[0]){for(a=d[0];a.parentNode&&11!==a.parentNode.nodeType;)a=a.parentNode;a.parentNode&&a.parentNode.removeChild(a)}}else{var c=b.a.D(a).toLowerCase();d=x.createElement("div");c=c.match(/^<(thead|tbody|tfoot)/)&&
|
||||
[1,"<table>","</table>"]||!c.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!c.indexOf("<td")||!c.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||[0,"",""];a="ignored<div>"+c[1]+a+c[2]+"</div>";for("function"==typeof w.innerShiv?d.appendChild(w.innerShiv(a)):d.innerHTML=a;c[0]--;)d=d.lastChild;d=b.a.L(d.lastChild.childNodes)}return d};b.a.ca=function(a,d){b.a.ka(a);d=b.a.d(d);if(d!==n&&d!==H)if("string"!=typeof d&&(d=d.toString()),"undefined"!=typeof E)E(a).html(d);else for(var c=
|
||||
b.a.sa(d),e=0;e<c.length;e++)a.appendChild(c[e])};b.b("utils.parseHtmlFragment",b.a.sa);b.b("utils.setHtml",b.a.ca);var Q={};b.s={qa:function(a){"function"!=typeof a&&i(Error("You can only pass a function to ko.memoization.memoize()"));var b=(4294967296*(1+Math.random())|0).toString(16).substring(1)+(4294967296*(1+Math.random())|0).toString(16).substring(1);Q[b]=a;return"<\!--[ko_memo:"+b+"]--\>"},gb:function(a,b){var c=Q[a];c===H&&i(Error("Couldn't find any memo with ID "+a+". Perhaps it's already been unmemoized."));
|
||||
try{return c.apply(n,b||[]),l}finally{delete Q[a]}},hb:function(a,d){var c=[];ba(a,c);for(var e=0,f=c.length;e<f;e++){var g=c[e].rb,h=[g];d&&b.a.P(h,d);b.s.gb(c[e].Eb,h);g.nodeValue="";g.parentNode&&g.parentNode.removeChild(g)}},Ta:function(a){return(a=a.match(/^\[ko_memo\:(.*?)\]$/))?a[1]:n}};b.b("memoization",b.s);b.b("memoization.memoize",b.s.qa);b.b("memoization.unmemoize",b.s.gb);b.b("memoization.parseMemoText",b.s.Ta);b.b("memoization.unmemoizeDomNodeAndDescendants",b.s.hb);b.La={throttle:function(a,
|
||||
d){a.throttleEvaluation=d;var c=n;return b.j({read:a,write:function(b){clearTimeout(c);c=setTimeout(function(){a(b)},d)}})},notify:function(a,d){a.equalityComparer="always"==d?t(q):b.m.fn.equalityComparer;return a}};b.b("extenders",b.La);b.eb=function(a,d,c){this.target=a;this.ha=d;this.qb=c;b.p(this,"dispose",this.B)};b.eb.prototype.B=function(){this.Bb=l;this.qb()};b.S=function(){this.w={};b.a.extend(this,b.S.fn);b.p(this,"subscribe",this.xa);b.p(this,"extend",this.extend);b.p(this,"getSubscriptionsCount",
|
||||
this.xb)};b.S.fn={xa:function(a,d,c){var c=c||"change",a=d?a.bind(d):a,e=new b.eb(this,a,function(){b.a.ga(this.w[c],e)}.bind(this));this.w[c]||(this.w[c]=[]);this.w[c].push(e);return e},notifySubscribers:function(a,d){d=d||"change";this.w[d]&&b.r.K(function(){b.a.o(this.w[d].slice(0),function(b){b&&b.Bb!==l&&b.ha(a)})},this)},xb:function(){var a=0,b;for(b in this.w)this.w.hasOwnProperty(b)&&(a+=this.w[b].length);return a},extend:function(a){var d=this;if(a)for(var c in a){var e=b.La[c];"function"==
|
||||
typeof e&&(d=e(d,a[c]))}return d}};b.Pa=function(a){return"function"==typeof a.xa&&"function"==typeof a.notifySubscribers};b.b("subscribable",b.S);b.b("isSubscribable",b.Pa);var B=[];b.r={lb:function(a){B.push({ha:a,Ka:[]})},end:function(){B.pop()},Va:function(a){b.Pa(a)||i(Error("Only subscribable things can act as dependencies"));if(0<B.length){var d=B[B.length-1];d&&!(0<=b.a.i(d.Ka,a))&&(d.Ka.push(a),d.ha(a))}},K:function(a,b,c){try{return B.push(n),a.apply(b,c||[])}finally{B.pop()}}};var la={undefined:l,
|
||||
"boolean":l,number:l,string:l};b.m=function(a){function d(){if(0<arguments.length){if(!d.equalityComparer||!d.equalityComparer(c,arguments[0]))d.H(),c=arguments[0],d.G();return this}b.r.Va(d);return c}var c=a;b.S.call(d);d.t=function(){return c};d.G=function(){d.notifySubscribers(c)};d.H=function(){d.notifySubscribers(c,"beforeChange")};b.a.extend(d,b.m.fn);b.p(d,"peek",d.t);b.p(d,"valueHasMutated",d.G);b.p(d,"valueWillMutate",d.H);return d};b.m.fn={equalityComparer:function(a,b){return a===n||typeof a in
|
||||
la?a===b:q}};var D=b.m.Jb="__ko_proto__";b.m.fn[D]=b.m;b.la=function(a,d){return a===n||a===H||a[D]===H?q:a[D]===d?l:b.la(a[D],d)};b.$=function(a){return b.la(a,b.m)};b.Qa=function(a){return"function"==typeof a&&a[D]===b.m||"function"==typeof a&&a[D]===b.j&&a.yb?l:q};b.b("observable",b.m);b.b("isObservable",b.$);b.b("isWriteableObservable",b.Qa);b.R=function(a){0==arguments.length&&(a=[]);a!==n&&(a!==H&&!("length"in a))&&i(Error("The argument passed when initializing an observable array must be an array, or null, or undefined."));
|
||||
var d=b.m(a);b.a.extend(d,b.R.fn);return d};b.R.fn={remove:function(a){for(var b=this.t(),c=[],e="function"==typeof a?a:function(b){return b===a},f=0;f<b.length;f++){var g=b[f];e(g)&&(0===c.length&&this.H(),c.push(g),b.splice(f,1),f--)}c.length&&this.G();return c},removeAll:function(a){if(a===H){var d=this.t(),c=d.slice(0);this.H();d.splice(0,d.length);this.G();return c}return!a?[]:this.remove(function(d){return 0<=b.a.i(a,d)})},destroy:function(a){var b=this.t(),c="function"==typeof a?a:function(b){return b===
|
||||
a};this.H();for(var e=b.length-1;0<=e;e--)c(b[e])&&(b[e]._destroy=l);this.G()},destroyAll:function(a){return a===H?this.destroy(t(l)):!a?[]:this.destroy(function(d){return 0<=b.a.i(a,d)})},indexOf:function(a){var d=this();return b.a.i(d,a)},replace:function(a,b){var c=this.indexOf(a);0<=c&&(this.H(),this.t()[c]=b,this.G())}};b.a.o("pop push reverse shift sort splice unshift".split(" "),function(a){b.R.fn[a]=function(){var b=this.t();this.H();b=b[a].apply(b,arguments);this.G();return b}});b.a.o(["slice"],
|
||||
function(a){b.R.fn[a]=function(){var b=this();return b[a].apply(b,arguments)}});b.b("observableArray",b.R);b.j=function(a,d,c){function e(){b.a.o(y,function(a){a.B()});y=[]}function f(){var a=h.throttleEvaluation;a&&0<=a?(clearTimeout(s),s=setTimeout(g,a)):g()}function g(){if(!p)if(m&&v())z();else{p=l;try{var a=b.a.V(y,function(a){return a.target});b.r.lb(function(c){var d;0<=(d=b.a.i(a,c))?a[d]=H:y.push(c.xa(f))});for(var c=r.call(d),e=a.length-1;0<=e;e--)a[e]&&y.splice(e,1)[0].B();m=l;h.notifySubscribers(k,
|
||||
"beforeChange");k=c}finally{b.r.end()}h.notifySubscribers(k);p=q;y.length||z()}}function h(){if(0<arguments.length)return"function"===typeof u?u.apply(d,arguments):i(Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.")),this;m||g();b.r.Va(h);return k}function j(){return!m||0<y.length}var k,m=q,p=q,r=a;r&&"object"==typeof r?(c=r,r=c.read):(c=c||{},r||(r=c.read));"function"!=typeof r&&i(Error("Pass a function that returns the value of the ko.computed"));
|
||||
var u=c.write,F=c.disposeWhenNodeIsRemoved||c.W||n,v=c.disposeWhen||c.Ja||t(q),z=e,y=[],s=n;d||(d=c.owner);h.t=function(){m||g();return k};h.wb=function(){return y.length};h.yb="function"===typeof c.write;h.B=function(){z()};h.oa=j;b.S.call(h);b.a.extend(h,b.j.fn);b.p(h,"peek",h.t);b.p(h,"dispose",h.B);b.p(h,"isActive",h.oa);b.p(h,"getDependenciesCount",h.wb);c.deferEvaluation!==l&&g();if(F&&j()){z=function(){b.a.F.Wa(F,arguments.callee);e()};b.a.F.Ba(F,z);var C=v,v=function(){return!b.a.X(F)||C()}}return h};
|
||||
b.Ab=function(a){return b.la(a,b.j)};v=b.m.Jb;b.j[v]=b.m;b.j.fn={};b.j.fn[v]=b.j;b.b("dependentObservable",b.j);b.b("computed",b.j);b.b("isComputed",b.Ab);b.fb=function(a){0==arguments.length&&i(Error("When calling ko.toJS, pass the object you want to convert."));return aa(a,function(a){for(var c=0;b.$(a)&&10>c;c++)a=a();return a})};b.toJSON=function(a,d,c){a=b.fb(a);return b.a.wa(a,d,c)};b.b("toJS",b.fb);b.b("toJSON",b.toJSON);b.k={q:function(a){switch(b.a.u(a)){case "option":return a.__ko__hasDomDataOptionValue__===
|
||||
l?b.a.f.get(a,b.c.options.ra):7>=b.a.Z?a.getAttributeNode("value").specified?a.value:a.text:a.value;case "select":return 0<=a.selectedIndex?b.k.q(a.options[a.selectedIndex]):H;default:return a.value}},T:function(a,d){switch(b.a.u(a)){case "option":switch(typeof d){case "string":b.a.f.set(a,b.c.options.ra,H);"__ko__hasDomDataOptionValue__"in a&&delete a.__ko__hasDomDataOptionValue__;a.value=d;break;default:b.a.f.set(a,b.c.options.ra,d),a.__ko__hasDomDataOptionValue__=l,a.value="number"===typeof d?
|
||||
d:""}break;case "select":for(var c=a.options.length-1;0<=c;c--)if(b.k.q(a.options[c])==d){a.selectedIndex=c;break}break;default:if(d===n||d===H)d="";a.value=d}}};b.b("selectExtensions",b.k);b.b("selectExtensions.readValue",b.k.q);b.b("selectExtensions.writeValue",b.k.T);var ja=/\@ko_token_(\d+)\@/g,ma=["true","false"],na=/^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;b.g={Q:[],aa:function(a){var d=b.a.D(a);if(3>d.length)return[];"{"===d.charAt(0)&&(d=d.substring(1,d.length-1));for(var a=[],
|
||||
c=n,e,f=0;f<d.length;f++){var g=d.charAt(f);if(c===n)switch(g){case '"':case "'":case "/":c=f,e=g}else if(g==e&&"\\"!==d.charAt(f-1)){g=d.substring(c,f+1);a.push(g);var h="@ko_token_"+(a.length-1)+"@",d=d.substring(0,c)+h+d.substring(f+1),f=f-(g.length-h.length),c=n}}e=c=n;for(var j=0,k=n,f=0;f<d.length;f++){g=d.charAt(f);if(c===n)switch(g){case "{":c=f;k=g;e="}";break;case "(":c=f;k=g;e=")";break;case "[":c=f,k=g,e="]"}g===k?j++:g===e&&(j--,0===j&&(g=d.substring(c,f+1),a.push(g),h="@ko_token_"+(a.length-
|
||||
1)+"@",d=d.substring(0,c)+h+d.substring(f+1),f-=g.length-h.length,c=n))}e=[];d=d.split(",");c=0;for(f=d.length;c<f;c++)j=d[c],k=j.indexOf(":"),0<k&&k<j.length-1?(g=j.substring(k+1),e.push({key:O(j.substring(0,k),a),value:O(g,a)})):e.push({unknown:O(j,a)});return e},ba:function(a){for(var d="string"===typeof a?b.g.aa(a):a,c=[],a=[],e,f=0;e=d[f];f++)if(0<c.length&&c.push(","),e.key){var g;a:{g=e.key;var h=b.a.D(g);switch(h.length&&h.charAt(0)){case "'":case '"':break a;default:g="'"+h+"'"}}e=e.value;
|
||||
c.push(g);c.push(":");c.push(e);e=b.a.D(e);0<=b.a.i(ma,b.a.D(e).toLowerCase())?e=q:(h=e.match(na),e=h===n?q:h[1]?"Object("+h[1]+")"+h[2]:e);e&&(0<a.length&&a.push(", "),a.push(g+" : function(__ko_value) { "+e+" = __ko_value; }"))}else e.unknown&&c.push(e.unknown);d=c.join("");0<a.length&&(d=d+", '_ko_property_writers' : { "+a.join("")+" } ");return d},Db:function(a,d){for(var c=0;c<a.length;c++)if(b.a.D(a[c].key)==d)return l;return q},ea:function(a,d,c,e,f){if(!a||!b.Qa(a)){if((a=d()._ko_property_writers)&&
|
||||
a[c])a[c](e)}else(!f||a.t()!==e)&&a(e)}};b.b("expressionRewriting",b.g);b.b("expressionRewriting.bindingRewriteValidators",b.g.Q);b.b("expressionRewriting.parseObjectLiteral",b.g.aa);b.b("expressionRewriting.preProcessBindings",b.g.ba);b.b("jsonExpressionRewriting",b.g);b.b("jsonExpressionRewriting.insertPropertyAccessorsIntoJson",b.g.ba);var J="<\!--test--\>"===x.createComment("test").text,ia=J?/^<\!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*--\>$/:/^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/,ha=J?/^<\!--\s*\/ko\s*--\>$/:
|
||||
/^\s*\/ko\s*$/,oa={ul:l,ol:l};b.e={I:{},childNodes:function(a){return A(a)?$(a):a.childNodes},Y:function(a){if(A(a))for(var a=b.e.childNodes(a),d=0,c=a.length;d<c;d++)b.removeNode(a[d]);else b.a.ka(a)},N:function(a,d){if(A(a)){b.e.Y(a);for(var c=a.nextSibling,e=0,f=d.length;e<f;e++)c.parentNode.insertBefore(d[e],c)}else b.a.N(a,d)},Ua:function(a,b){A(a)?a.parentNode.insertBefore(b,a.nextSibling):a.firstChild?a.insertBefore(b,a.firstChild):a.appendChild(b)},Oa:function(a,d,c){c?A(a)?a.parentNode.insertBefore(d,
|
||||
c.nextSibling):c.nextSibling?a.insertBefore(d,c.nextSibling):a.appendChild(d):b.e.Ua(a,d)},firstChild:function(a){return!A(a)?a.firstChild:!a.nextSibling||G(a.nextSibling)?n:a.nextSibling},nextSibling:function(a){A(a)&&(a=Z(a));return a.nextSibling&&G(a.nextSibling)?n:a.nextSibling},ib:function(a){return(a=A(a))?a[1]:n},Sa:function(a){if(oa[b.a.u(a)]){var d=a.firstChild;if(d){do if(1===d.nodeType){var c;c=d.firstChild;var e=n;if(c){do if(e)e.push(c);else if(A(c)){var f=Z(c,l);f?c=f:e=[c]}else G(c)&&
|
||||
(e=[c]);while(c=c.nextSibling)}if(c=e){e=d.nextSibling;for(f=0;f<c.length;f++)e?a.insertBefore(c[f],e):a.appendChild(c[f])}}while(d=d.nextSibling)}}}};b.b("virtualElements",b.e);b.b("virtualElements.allowedBindings",b.e.I);b.b("virtualElements.emptyNode",b.e.Y);b.b("virtualElements.insertAfter",b.e.Oa);b.b("virtualElements.prepend",b.e.Ua);b.b("virtualElements.setDomNodeChildren",b.e.N);b.J=function(){this.Ga={}};b.a.extend(b.J.prototype,{nodeHasBindings:function(a){switch(a.nodeType){case 1:return a.getAttribute("data-bind")!=
|
||||
n;case 8:return b.e.ib(a)!=n;default:return q}},getBindings:function(a,b){var c=this.getBindingsString(a,b);return c?this.parseBindingsString(c,b,a):n},getBindingsString:function(a){switch(a.nodeType){case 1:return a.getAttribute("data-bind");case 8:return b.e.ib(a);default:return n}},parseBindingsString:function(a,d,c){try{var e;if(!(e=this.Ga[a])){var f=this.Ga,g="with($context){with($data||{}){return{"+b.g.ba(a)+"}}}";e=f[a]=new Function("$context","$element",g)}return e(d,c)}catch(h){i(Error("Unable to parse bindings.\nMessage: "+
|
||||
h+";\nBindings value: "+a))}}});b.J.instance=new b.J;b.b("bindingProvider",b.J);b.c={};b.z=function(a,d,c){d?(b.a.extend(this,d),this.$parentContext=d,this.$parent=d.$data,this.$parents=(d.$parents||[]).slice(0),this.$parents.unshift(this.$parent)):(this.$parents=[],this.$root=a,this.ko=b);this.$data=a;c&&(this[c]=a)};b.z.prototype.createChildContext=function(a,d){return new b.z(a,this,d)};b.z.prototype.extend=function(a){var d=b.a.extend(new b.z,this);return b.a.extend(d,a)};b.cb=function(a,d){if(2==
|
||||
arguments.length)b.a.f.set(a,"__ko_bindingContext__",d);else return b.a.f.get(a,"__ko_bindingContext__")};b.Ea=function(a,d,c){1===a.nodeType&&b.e.Sa(a);return W(a,d,c,l)};b.Da=function(a,b){(1===b.nodeType||8===b.nodeType)&&Y(a,b,l)};b.Ca=function(a,b){b&&(1!==b.nodeType&&8!==b.nodeType)&&i(Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node"));b=b||w.document.body;X(a,b,l)};b.ja=function(a){switch(a.nodeType){case 1:case 8:var d=b.cb(a);if(d)return d;
|
||||
if(a.parentNode)return b.ja(a.parentNode)}return H};b.ob=function(a){return(a=b.ja(a))?a.$data:H};b.b("bindingHandlers",b.c);b.b("applyBindings",b.Ca);b.b("applyBindingsToDescendants",b.Da);b.b("applyBindingsToNode",b.Ea);b.b("contextFor",b.ja);b.b("dataFor",b.ob);var ea={"class":"className","for":"htmlFor"};b.c.attr={update:function(a,d){var c=b.a.d(d())||{},e;for(e in c)if("string"==typeof e){var f=b.a.d(c[e]),g=f===q||f===n||f===H;g&&a.removeAttribute(e);8>=b.a.Z&&e in ea?(e=ea[e],g?a.removeAttribute(e):
|
||||
a[e]=f):g||a.setAttribute(e,f.toString());"name"===e&&b.a.$a(a,g?"":f.toString())}}};b.c.checked={init:function(a,d,c){b.a.n(a,"click",function(){var e;if("checkbox"==a.type)e=a.checked;else if("radio"==a.type&&a.checked)e=a.value;else return;var f=d(),g=b.a.d(f);"checkbox"==a.type&&g instanceof Array?(e=b.a.i(g,a.value),a.checked&&0>e?f.push(a.value):!a.checked&&0<=e&&f.splice(e,1)):b.g.ea(f,c,"checked",e,l)});"radio"==a.type&&!a.name&&b.c.uniqueName.init(a,t(l))},update:function(a,d){var c=b.a.d(d());
|
||||
"checkbox"==a.type?a.checked=c instanceof Array?0<=b.a.i(c,a.value):c:"radio"==a.type&&(a.checked=a.value==c)}};b.c.css={update:function(a,d){var c=b.a.d(d());if("object"==typeof c)for(var e in c){var f=b.a.d(c[e]);b.a.da(a,e,f)}else c=String(c||""),b.a.da(a,a.__ko__cssValue,q),a.__ko__cssValue=c,b.a.da(a,c,l)}};b.c.enable={update:function(a,d){var c=b.a.d(d());c&&a.disabled?a.removeAttribute("disabled"):!c&&!a.disabled&&(a.disabled=l)}};b.c.disable={update:function(a,d){b.c.enable.update(a,function(){return!b.a.d(d())})}};
|
||||
b.c.event={init:function(a,d,c,e){var f=d()||{},g;for(g in f)(function(){var f=g;"string"==typeof f&&b.a.n(a,f,function(a){var g,m=d()[f];if(m){var p=c();try{var r=b.a.L(arguments);r.unshift(e);g=m.apply(e,r)}finally{g!==l&&(a.preventDefault?a.preventDefault():a.returnValue=q)}p[f+"Bubble"]===q&&(a.cancelBubble=l,a.stopPropagation&&a.stopPropagation())}})})()}};b.c.foreach={Ra:function(a){return function(){var d=a(),c=b.a.ta(d);if(!c||"number"==typeof c.length)return{foreach:d,templateEngine:b.C.na};
|
||||
b.a.d(d);return{foreach:c.data,as:c.as,includeDestroyed:c.includeDestroyed,afterAdd:c.afterAdd,beforeRemove:c.beforeRemove,afterRender:c.afterRender,beforeMove:c.beforeMove,afterMove:c.afterMove,templateEngine:b.C.na}}},init:function(a,d){return b.c.template.init(a,b.c.foreach.Ra(d))},update:function(a,d,c,e,f){return b.c.template.update(a,b.c.foreach.Ra(d),c,e,f)}};b.g.Q.foreach=q;b.e.I.foreach=l;b.c.hasfocus={init:function(a,d,c){function e(e){a.__ko_hasfocusUpdating=l;var f=a.ownerDocument;"activeElement"in
|
||||
f&&(e=f.activeElement===a);f=d();b.g.ea(f,c,"hasfocus",e,l);a.__ko_hasfocusUpdating=q}var f=e.bind(n,l),g=e.bind(n,q);b.a.n(a,"focus",f);b.a.n(a,"focusin",f);b.a.n(a,"blur",g);b.a.n(a,"focusout",g)},update:function(a,d){var c=b.a.d(d());a.__ko_hasfocusUpdating||(c?a.focus():a.blur(),b.r.K(b.a.Aa,n,[a,c?"focusin":"focusout"]))}};b.c.html={init:function(){return{controlsDescendantBindings:l}},update:function(a,d){b.a.ca(a,d())}};var ca="__ko_withIfBindingData";P("if");P("ifnot",q,l);P("with",l,q,function(a,
|
||||
b){return a.createChildContext(b)});b.c.options={update:function(a,d,c){"select"!==b.a.u(a)&&i(Error("options binding applies only to SELECT elements"));for(var e=0==a.length,f=b.a.V(b.a.fa(a.childNodes,function(a){return a.tagName&&"option"===b.a.u(a)&&a.selected}),function(a){return b.k.q(a)||a.innerText||a.textContent}),g=a.scrollTop,h=b.a.d(d());0<a.length;)b.A(a.options[0]),a.remove(0);if(h){var c=c(),j=c.optionsIncludeDestroyed;"number"!=typeof h.length&&(h=[h]);if(c.optionsCaption){var k=x.createElement("option");
|
||||
b.a.ca(k,c.optionsCaption);b.k.T(k,H);a.appendChild(k)}for(var d=0,m=h.length;d<m;d++){var p=h[d];if(!p||!p._destroy||j){var k=x.createElement("option"),r=function(a,b,c){var d=typeof b;return"function"==d?b(a):"string"==d?a[b]:c},u=r(p,c.optionsValue,p);b.k.T(k,b.a.d(u));p=r(p,c.optionsText,u);b.a.bb(k,p);a.appendChild(k)}}h=a.getElementsByTagName("option");d=j=0;for(m=h.length;d<m;d++)0<=b.a.i(f,b.k.q(h[d]))&&(b.a.ab(h[d],l),j++);a.scrollTop=g;e&&"value"in c&&da(a,b.a.ta(c.value),l);b.a.tb(a)}}};
|
||||
b.c.options.ra="__ko.optionValueDomData__";b.c.selectedOptions={init:function(a,d,c){b.a.n(a,"change",function(){var e=d(),f=[];b.a.o(a.getElementsByTagName("option"),function(a){a.selected&&f.push(b.k.q(a))});b.g.ea(e,c,"value",f)})},update:function(a,d){"select"!=b.a.u(a)&&i(Error("values binding applies only to SELECT elements"));var c=b.a.d(d());c&&"number"==typeof c.length&&b.a.o(a.getElementsByTagName("option"),function(a){var d=0<=b.a.i(c,b.k.q(a));b.a.ab(a,d)})}};b.c.style={update:function(a,
|
||||
d){var c=b.a.d(d()||{}),e;for(e in c)if("string"==typeof e){var f=b.a.d(c[e]);a.style[e]=f||""}}};b.c.submit={init:function(a,d,c,e){"function"!=typeof d()&&i(Error("The value for a submit binding must be a function"));b.a.n(a,"submit",function(b){var c,h=d();try{c=h.call(e,a)}finally{c!==l&&(b.preventDefault?b.preventDefault():b.returnValue=q)}})}};b.c.text={update:function(a,d){b.a.bb(a,d())}};b.e.I.text=l;b.c.uniqueName={init:function(a,d){if(d()){var c="ko_unique_"+ ++b.c.uniqueName.nb;b.a.$a(a,
|
||||
c)}}};b.c.uniqueName.nb=0;b.c.value={init:function(a,d,c){function e(){h=q;var e=d(),f=b.k.q(a);b.g.ea(e,c,"value",f)}var f=["change"],g=c().valueUpdate,h=q;g&&("string"==typeof g&&(g=[g]),b.a.P(f,g),f=b.a.Fa(f));if(b.a.Z&&("input"==a.tagName.toLowerCase()&&"text"==a.type&&"off"!=a.autocomplete&&(!a.form||"off"!=a.form.autocomplete))&&-1==b.a.i(f,"propertychange"))b.a.n(a,"propertychange",function(){h=l}),b.a.n(a,"blur",function(){h&&e()});b.a.o(f,function(c){var d=e;b.a.Nb(c,"after")&&(d=function(){setTimeout(e,
|
||||
0)},c=c.substring(5));b.a.n(a,c,d)})},update:function(a,d){var c="select"===b.a.u(a),e=b.a.d(d()),f=b.k.q(a),g=e!=f;0===e&&(0!==f&&"0"!==f)&&(g=l);g&&(f=function(){b.k.T(a,e)},f(),c&&setTimeout(f,0));c&&0<a.length&&da(a,e,q)}};b.c.visible={update:function(a,d){var c=b.a.d(d()),e="none"!=a.style.display;c&&!e?a.style.display="":!c&&e&&(a.style.display="none")}};b.c.click={init:function(a,d,c,e){return b.c.event.init.call(this,a,function(){var a={};a.click=d();return a},c,e)}};b.v=function(){};b.v.prototype.renderTemplateSource=
|
||||
function(){i(Error("Override renderTemplateSource"))};b.v.prototype.createJavaScriptEvaluatorBlock=function(){i(Error("Override createJavaScriptEvaluatorBlock"))};b.v.prototype.makeTemplateSource=function(a,d){if("string"==typeof a){var d=d||x,c=d.getElementById(a);c||i(Error("Cannot find template with ID "+a));return new b.l.h(c)}if(1==a.nodeType||8==a.nodeType)return new b.l.O(a);i(Error("Unknown template type: "+a))};b.v.prototype.renderTemplate=function(a,b,c,e){a=this.makeTemplateSource(a,e);
|
||||
return this.renderTemplateSource(a,b,c)};b.v.prototype.isTemplateRewritten=function(a,b){return this.allowTemplateRewriting===q?l:this.makeTemplateSource(a,b).data("isRewritten")};b.v.prototype.rewriteTemplate=function(a,b,c){a=this.makeTemplateSource(a,c);b=b(a.text());a.text(b);a.data("isRewritten",l)};b.b("templateEngine",b.v);var pa=/(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi,qa=/<\!--\s*ko\b\s*([\s\S]*?)\s*--\>/g;b.ya={ub:function(a,
|
||||
d,c){d.isTemplateRewritten(a,c)||d.rewriteTemplate(a,function(a){return b.ya.Fb(a,d)},c)},Fb:function(a,b){return a.replace(pa,function(a,e,f,g,h,j,k){return V(k,e,b)}).replace(qa,function(a,e){return V(e,"<\!-- ko --\>",b)})},jb:function(a){return b.s.qa(function(d,c){d.nextSibling&&b.Ea(d.nextSibling,a,c)})}};b.b("__tr_ambtns",b.ya.jb);b.l={};b.l.h=function(a){this.h=a};b.l.h.prototype.text=function(){var a=b.a.u(this.h),a="script"===a?"text":"textarea"===a?"value":"innerHTML";if(0==arguments.length)return this.h[a];
|
||||
var d=arguments[0];"innerHTML"===a?b.a.ca(this.h,d):this.h[a]=d};b.l.h.prototype.data=function(a){if(1===arguments.length)return b.a.f.get(this.h,"templateSourceData_"+a);b.a.f.set(this.h,"templateSourceData_"+a,arguments[1])};b.l.O=function(a){this.h=a};b.l.O.prototype=new b.l.h;b.l.O.prototype.text=function(){if(0==arguments.length){var a=b.a.f.get(this.h,"__ko_anon_template__")||{};a.za===H&&a.ia&&(a.za=a.ia.innerHTML);return a.za}b.a.f.set(this.h,"__ko_anon_template__",{za:arguments[0]})};b.l.h.prototype.nodes=
|
||||
function(){if(0==arguments.length)return(b.a.f.get(this.h,"__ko_anon_template__")||{}).ia;b.a.f.set(this.h,"__ko_anon_template__",{ia:arguments[0]})};b.b("templateSources",b.l);b.b("templateSources.domElement",b.l.h);b.b("templateSources.anonymousTemplate",b.l.O);var N;b.va=function(a){a!=H&&!(a instanceof b.v)&&i(Error("templateEngine must inherit from ko.templateEngine"));N=a};b.ua=function(a,d,c,e,f){c=c||{};(c.templateEngine||N)==H&&i(Error("Set a template engine before calling renderTemplate"));
|
||||
f=f||"replaceChildren";if(e){var g=M(e);return b.j(function(){var h=d&&d instanceof b.z?d:new b.z(b.a.d(d)),j="function"==typeof a?a(h.$data,h):a,h=S(e,f,j,h,c);"replaceNode"==f&&(e=h,g=M(e))},n,{Ja:function(){return!g||!b.a.X(g)},W:g&&"replaceNode"==f?g.parentNode:g})}return b.s.qa(function(e){b.ua(a,d,c,e,"replaceNode")})};b.Lb=function(a,d,c,e,f){function g(a,b){T(b,j);c.afterRender&&c.afterRender(b,a)}function h(d,e){j=f.createChildContext(b.a.d(d),c.as);j.$index=e;var g="function"==typeof a?
|
||||
a(d,j):a;return S(n,"ignoreTargetNode",g,j,c)}var j;return b.j(function(){var a=b.a.d(d)||[];"undefined"==typeof a.length&&(a=[a]);a=b.a.fa(a,function(a){return c.includeDestroyed||a===H||a===n||!b.a.d(a._destroy)});b.r.K(b.a.Za,n,[e,a,h,c,g])},n,{W:e})};b.c.template={init:function(a,d){var c=b.a.d(d());if("string"!=typeof c&&!c.name&&(1==a.nodeType||8==a.nodeType))c=1==a.nodeType?a.childNodes:b.e.childNodes(a),c=b.a.Gb(c),(new b.l.O(a)).nodes(c);return{controlsDescendantBindings:l}},update:function(a,
|
||||
d,c,e,f){var d=b.a.d(d()),c={},e=l,g,h=n;"string"!=typeof d&&(c=d,d=c.name,"if"in c&&(e=b.a.d(c["if"])),e&&"ifnot"in c&&(e=!b.a.d(c.ifnot)),g=b.a.d(c.data));"foreach"in c?h=b.Lb(d||a,e&&c.foreach||[],c,a,f):e?(f="data"in c?f.createChildContext(g,c.as):f,h=b.ua(d||a,f,c,a)):b.e.Y(a);f=h;(g=b.a.f.get(a,"__ko__templateComputedDomDataKey__"))&&"function"==typeof g.B&&g.B();b.a.f.set(a,"__ko__templateComputedDomDataKey__",f&&f.oa()?f:H)}};b.g.Q.template=function(a){a=b.g.aa(a);return 1==a.length&&a[0].unknown||
|
||||
b.g.Db(a,"name")?n:"This template engine does not support anonymous templates nested within its templates"};b.e.I.template=l;b.b("setTemplateEngine",b.va);b.b("renderTemplate",b.ua);b.a.Ia=function(a,b,c){a=a||[];b=b||[];return a.length<=b.length?R(a,b,"added","deleted",c):R(b,a,"deleted","added",c)};b.b("utils.compareArrays",b.a.Ia);b.a.Za=function(a,d,c,e,f){function g(a,b){s=k[b];v!==b&&(y[a]=s);s.ma(v++);L(s.M);r.push(s);z.push(s)}function h(a,c){if(a)for(var d=0,e=c.length;d<e;d++)c[d]&&b.a.o(c[d].M,
|
||||
function(b){a(b,d,c[d].U)})}for(var d=d||[],e=e||{},j=b.a.f.get(a,"setDomNodeChildrenFromArrayMapping_lastMappingResult")===H,k=b.a.f.get(a,"setDomNodeChildrenFromArrayMapping_lastMappingResult")||[],m=b.a.V(k,function(a){return a.U}),p=b.a.Ia(m,d),r=[],u=0,v=0,A=[],z=[],d=[],y=[],m=[],s,C=0,B,D;B=p[C];C++)switch(D=B.moved,B.status){case "deleted":D===H&&(s=k[u],s.j&&s.j.B(),A.push.apply(A,L(s.M)),e.beforeRemove&&(d[C]=s,z.push(s)));u++;break;case "retained":g(C,u++);break;case "added":D!==H?g(C,
|
||||
D):(s={U:B.value,ma:b.m(v++)},r.push(s),z.push(s),j||(m[C]=s))}h(e.beforeMove,y);b.a.o(A,e.beforeRemove?b.A:b.removeNode);for(var C=0,j=b.e.firstChild(a),G;s=z[C];C++){s.M||b.a.extend(s,ga(a,c,s.U,f,s.ma));for(u=0;p=s.M[u];j=p.nextSibling,G=p,u++)p!==j&&b.e.Oa(a,p,G);!s.zb&&f&&(f(s.U,s.M,s.ma),s.zb=l)}h(e.beforeRemove,d);h(e.afterMove,y);h(e.afterAdd,m);b.a.f.set(a,"setDomNodeChildrenFromArrayMapping_lastMappingResult",r)};b.b("utils.setDomNodeChildrenFromArrayMapping",b.a.Za);b.C=function(){this.allowTemplateRewriting=
|
||||
q};b.C.prototype=new b.v;b.C.prototype.renderTemplateSource=function(a){var d=!(9>b.a.Z)&&a.nodes?a.nodes():n;if(d)return b.a.L(d.cloneNode(l).childNodes);a=a.text();return b.a.sa(a)};b.C.na=new b.C;b.va(b.C.na);b.b("nativeTemplateEngine",b.C);b.pa=function(){var a=this.Cb=function(){if("undefined"==typeof E||!E.tmpl)return 0;try{if(0<=E.tmpl.tag.tmpl.open.toString().indexOf("__"))return 2}catch(a){}return 1}();this.renderTemplateSource=function(b,c,e){e=e||{};2>a&&i(Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later."));
|
||||
var f=b.data("precompiled");f||(f=b.text()||"",f=E.template(n,"{{ko_with $item.koBindingContext}}"+f+"{{/ko_with}}"),b.data("precompiled",f));b=[c.$data];c=E.extend({koBindingContext:c},e.templateOptions);c=E.tmpl(f,b,c);c.appendTo(x.createElement("div"));E.fragments={};return c};this.createJavaScriptEvaluatorBlock=function(a){return"{{ko_code ((function() { return "+a+" })()) }}"};this.addTemplate=function(a,b){x.write("<script type='text/html' id='"+a+"'>"+b+"<\/script>")};0<a&&(E.tmpl.tag.ko_code=
|
||||
{open:"__.push($1 || '');"},E.tmpl.tag.ko_with={open:"with($1) {",close:"} "})};b.pa.prototype=new b.v;v=new b.pa;0<v.Cb&&b.va(v);b.b("jqueryTmplTemplateEngine",b.pa)}"function"===typeof require&&"object"===typeof exports&&"object"===typeof module?K(module.exports||exports):"function"===typeof define&&define.amd?define(["exports"],K):K(w.ko={});l;
|
||||
})();
|
||||
@@ -0,0 +1,566 @@
|
||||
function ConnectionViewModel() {
|
||||
var self = this;
|
||||
|
||||
self.portOptions = ko.observableArray(undefined);
|
||||
self.baudrateOptions = ko.observableArray(undefined);
|
||||
self.selectedPort = ko.observable(undefined);
|
||||
self.selectedBaudrate = ko.observable(undefined);
|
||||
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
self.buttonText = ko.computed(function() {
|
||||
if (self.isErrorOrClosed())
|
||||
return "Connect";
|
||||
else
|
||||
return "Disconnect";
|
||||
})
|
||||
|
||||
self.previousIsOperational = undefined;
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.portOptions(response.ports);
|
||||
self.baudrateOptions(response.baudrates);
|
||||
|
||||
if (!self.selectedPort() && response.ports && response.ports.indexOf(response.portPreference) >= 0)
|
||||
self.selectedPort(response.portPreference);
|
||||
if (!self.selectedBaudrate() && response.baudrates && response.baudrates.indexOf(response.baudratePreference) >= 0)
|
||||
self.selectedBaudrate(response.baudratePreference);
|
||||
}
|
||||
|
||||
self.fromStateResponse = function(response) {
|
||||
self.previousIsOperational = self.isOperational();
|
||||
|
||||
self.isErrorOrClosed(response.closedOrError);
|
||||
self.isOperational(response.operational);
|
||||
self.isPaused(response.paused);
|
||||
self.isPrinting(response.printing);
|
||||
self.isError(response.error);
|
||||
self.isReady(response.ready);
|
||||
self.isLoading(response.loading);
|
||||
|
||||
var connectionTab = $("#connection");
|
||||
if (self.previousIsOperational != self.isOperational()) {
|
||||
if (self.isOperational() && connectionTab.hasClass("in")) {
|
||||
// connection just got established, close connection tab for now
|
||||
connectionTab.collapse("hide");
|
||||
} else if (!connectionTab.hasClass("in")) {
|
||||
// connection just dropped, make sure connection tab is open
|
||||
connectionTab.collapse("show");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.connect = function() {
|
||||
if (self.isErrorOrClosed()) {
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "control/connect",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: { "port": self.selectedPort(), "baudrate": self.selectedBaudrate() }
|
||||
})
|
||||
} else {
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "control/disconnect",
|
||||
type: "POST",
|
||||
dataType: "json"
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
var connectionViewModel = new ConnectionViewModel();
|
||||
|
||||
function PrinterStateViewModel() {
|
||||
var self = this;
|
||||
|
||||
self.stateString = ko.observable(undefined);
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
self.filename = ko.observable(undefined);
|
||||
self.filament = ko.observable(undefined);
|
||||
self.estimatedPrintTime = ko.observable(undefined);
|
||||
self.printTime = ko.observable(undefined);
|
||||
self.printTimeLeft = ko.observable(undefined);
|
||||
self.currentLine = ko.observable(undefined);
|
||||
self.totalLines = ko.observable(undefined);
|
||||
self.currentHeight = ko.observable(undefined);
|
||||
|
||||
self.lineString = ko.computed(function() {
|
||||
if (!self.totalLines())
|
||||
return "-";
|
||||
var currentLine = self.currentLine() ? self.currentLine() : "-";
|
||||
return currentLine + " / " + self.totalLines();
|
||||
});
|
||||
self.progress = ko.computed(function() {
|
||||
if (!self.currentLine() || !self.totalLines())
|
||||
return 0;
|
||||
return Math.round(self.currentLine() * 100 / self.totalLines());
|
||||
});
|
||||
self.pauseString = ko.computed(function() {
|
||||
if (self.isPaused())
|
||||
return "Continue";
|
||||
else
|
||||
return "Pause";
|
||||
});
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.stateString(response.state);
|
||||
self.isErrorOrClosed(response.closedOrError);
|
||||
self.isOperational(response.operational);
|
||||
self.isPaused(response.paused);
|
||||
self.isPrinting(response.printing);
|
||||
self.isError(response.error);
|
||||
self.isReady(response.ready);
|
||||
self.isLoading(response.loading);
|
||||
|
||||
if (response.job) {
|
||||
self.filename(response.job.filename);
|
||||
self.filament(response.job.filament);
|
||||
self.estimatedPrintTime(response.job.estimatedPrintTime);
|
||||
self.printTime(response.job.printTime);
|
||||
self.printTimeLeft(response.job.printTimeLeft);
|
||||
self.currentLine(response.job.line ? response.job.line : 0);
|
||||
self.totalLines(response.job.totalLines ? response.job.totalLines : 0);
|
||||
self.currentHeight(response.job.currentZ);
|
||||
} else {
|
||||
if (response.loading && response.gcode) {
|
||||
self.filename("Loading... (" + Math.round(response.gcode.progress * 100) + "%)");
|
||||
} else {
|
||||
self.filename(undefined);
|
||||
}
|
||||
self.filament(undefined);
|
||||
self.estimatedPrintTime(undefined);
|
||||
self.printTime(undefined);
|
||||
self.printTimeLeft(undefined);
|
||||
self.currentLine(undefined);
|
||||
self.totalLines(undefined);
|
||||
self.currentHeight(undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
var printerStateViewModel = new PrinterStateViewModel();
|
||||
|
||||
function TemperatureViewModel() {
|
||||
var self = this;
|
||||
|
||||
self.temp = ko.observable(undefined);
|
||||
self.bedTemp = ko.observable(undefined);
|
||||
self.targetTemp = ko.observable(undefined);
|
||||
self.bedTargetTemp = ko.observable(undefined);
|
||||
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
self.tempString = ko.computed(function() {
|
||||
if (!self.temp())
|
||||
return "-";
|
||||
return self.temp() + " °C";
|
||||
});
|
||||
self.bedTempString = ko.computed(function() {
|
||||
if (!self.bedTemp())
|
||||
return "-";
|
||||
return self.bedTemp() + " °C";
|
||||
});
|
||||
self.targetTempString = ko.computed(function() {
|
||||
if (!self.targetTemp())
|
||||
return "-";
|
||||
return self.targetTemp() + " °C";
|
||||
});
|
||||
self.bedTargetTempString = ko.computed(function() {
|
||||
if (!self.bedTargetTemp())
|
||||
return "-";
|
||||
return self.bedTargetTemp() + " °C";
|
||||
});
|
||||
|
||||
self.temperatures = [];
|
||||
self.plotOptions = {
|
||||
yaxis: {
|
||||
min: 0,
|
||||
max: 310,
|
||||
ticks: 10
|
||||
},
|
||||
xaxis: {
|
||||
mode: "time",
|
||||
minTickSize: [2, "minute"],
|
||||
tickFormatter: function(val, axis) {
|
||||
var now = new Date();
|
||||
var diff = now.getTime() - val;
|
||||
var diffInMins = Math.round(diff / (60000));
|
||||
if (diffInMins == 0)
|
||||
return "just now";
|
||||
else
|
||||
return "- " + diffInMins + " min";
|
||||
}
|
||||
},
|
||||
legend: {
|
||||
noColumns: 4
|
||||
}
|
||||
}
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.temp(response.temp);
|
||||
self.bedTemp(response.bedTemp);
|
||||
self.targetTemp(response.targetTemp);
|
||||
self.bedTargetTemp(response.bedTargetTemp);
|
||||
self.temperatures = (response.temperatures);
|
||||
|
||||
self.isErrorOrClosed(response.closedOrError);
|
||||
self.isOperational(response.operational);
|
||||
self.isPaused(response.paused);
|
||||
self.isPrinting(response.printing);
|
||||
self.isError(response.error);
|
||||
self.isReady(response.ready);
|
||||
self.isLoading(response.loading);
|
||||
|
||||
self.updatePlot();
|
||||
}
|
||||
|
||||
self.updatePlot = function() {
|
||||
var data = [
|
||||
{label: "Actual", color: "#FF4040", data: self.temperatures.actual},
|
||||
{label: "Target", color: "#FFA0A0", data: self.temperatures.target},
|
||||
{label: "Bed Actual", color: "#4040FF", data: self.temperatures.actualBed},
|
||||
{label: "Bed Target", color: "#A0A0FF", data: self.temperatures.targetBed}
|
||||
]
|
||||
$.plot($("#temperature-graph"), data, self.plotOptions);
|
||||
}
|
||||
}
|
||||
var temperatureViewModel = new TemperatureViewModel();
|
||||
|
||||
function SpeedViewModel() {
|
||||
var self = this;
|
||||
|
||||
self.outerWall = ko.observable(undefined);
|
||||
self.innerWall = ko.observable(undefined);
|
||||
self.fill = ko.observable(undefined);
|
||||
self.support = ko.observable(undefined);
|
||||
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
self.isPrinting = ko.observable(undefined);
|
||||
self.isPaused = ko.observable(undefined);
|
||||
self.isError = ko.observable(undefined);
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.isErrorOrClosed(response.closedOrError);
|
||||
self.isOperational(response.operational);
|
||||
self.isPaused(response.paused);
|
||||
self.isPrinting(response.printing);
|
||||
self.isError(response.error);
|
||||
self.isReady(response.ready);
|
||||
self.isLoading(response.loading);
|
||||
|
||||
if (response.feedrate) {
|
||||
self.outerWall(response.feedrate.outerWall);
|
||||
self.innerWall(response.feedrate.innerWall);
|
||||
self.fill(response.feedrate.fill);
|
||||
self.support(response.feedrate.support);
|
||||
} else {
|
||||
self.outerWall(undefined);
|
||||
self.innerWall(undefined);
|
||||
self.fill(undefined);
|
||||
self.support(undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
var speedViewModel = new SpeedViewModel();
|
||||
|
||||
function TerminalViewModel() {
|
||||
var self = this;
|
||||
|
||||
self.log = undefined;
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.log = response.log;
|
||||
|
||||
self.updateOutput();
|
||||
}
|
||||
|
||||
self.updateOutput = function() {
|
||||
var output = "";
|
||||
for (var i = 0; i < self.log.length; i++) {
|
||||
output += self.log[i] + "\n";
|
||||
}
|
||||
|
||||
var container = $("#terminal-output");
|
||||
var autoscroll = (container.scrollTop() == container[0].scrollHeight - container.height);
|
||||
|
||||
container.text(output);
|
||||
|
||||
if (autoscroll) {
|
||||
container.scrollTop(container[0].scrollHeight - container.height())
|
||||
}
|
||||
}
|
||||
|
||||
self.sendCommand = function(command) {
|
||||
|
||||
}
|
||||
}
|
||||
var terminalViewModel = new TerminalViewModel();
|
||||
|
||||
function GcodeFilesViewModel() {
|
||||
var self = this;
|
||||
|
||||
self.files = ko.observableArray([]);
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
self.files(response.files);
|
||||
}
|
||||
|
||||
self.loadFile = function() {
|
||||
var filename = this.name;
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "gcodefiles/load",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: {filename: filename}
|
||||
})
|
||||
}
|
||||
|
||||
self.removeFile = function() {
|
||||
var filename = this.name;
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "gcodefiles/delete",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: {filename: filename},
|
||||
success: self.fromResponse
|
||||
})
|
||||
}
|
||||
}
|
||||
var gcodeFilesViewModel = new GcodeFilesViewModel();
|
||||
|
||||
function DataUpdater(connectionViewModel, printerStateViewModel, temperatureViewModel, speedViewModel, terminalViewModel) {
|
||||
var self = this;
|
||||
|
||||
self.updateInterval = 500;
|
||||
self.updateIntervalOnError = 10000;
|
||||
self.includeTemperatures = true;
|
||||
self.includeLogs = true;
|
||||
|
||||
self.connectionViewModel = connectionViewModel;
|
||||
self.printerStateViewModel = printerStateViewModel;
|
||||
self.temperatureViewModel = temperatureViewModel;
|
||||
self.terminalViewModel = terminalViewModel;
|
||||
self.speedViewModel = speedViewModel;
|
||||
|
||||
self.requestData = function() {
|
||||
var parameters = {};
|
||||
|
||||
if (self.includeTemperatures)
|
||||
parameters.temperatures = true;
|
||||
if (self.includeLogs)
|
||||
parameters.log = true;
|
||||
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "state",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
data: parameters,
|
||||
success: function(response) {
|
||||
if ($("#offline_overlay").is(":visible"))
|
||||
$("#offline_overlay").hide();
|
||||
|
||||
self.printerStateViewModel.fromResponse(response);
|
||||
self.connectionViewModel.fromStateResponse(response);
|
||||
self.speedViewModel.fromResponse(response);
|
||||
|
||||
if (response.temperatures)
|
||||
self.temperatureViewModel.fromResponse(response);
|
||||
|
||||
if (response.log)
|
||||
self.terminalViewModel.fromResponse(response);
|
||||
|
||||
setTimeout(self.requestData, self.updateInterval);
|
||||
},
|
||||
error: function(jqXHR, textState, errorThrows) {
|
||||
// if the updated fails to communicate with the backend, we interpret this as a missing backend
|
||||
if (!$("#offline_overlay").is(":visible"))
|
||||
$("#offline_overlay").show();
|
||||
setTimeout(self.requestData, self.updateIntervalOnError);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
var dataUpdater = new DataUpdater(connectionViewModel, printerStateViewModel, temperatureViewModel, speedViewModel, terminalViewModel);
|
||||
|
||||
$(function() {
|
||||
|
||||
//~~ Print job control
|
||||
|
||||
$("#job_print").click(function() {
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "control/print",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
success: function(){}
|
||||
})
|
||||
})
|
||||
$("#job_pause").click(function() {
|
||||
$("#job_pause").button("toggle");
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "control/pause",
|
||||
type: "POST",
|
||||
dataType: "json"
|
||||
})
|
||||
})
|
||||
$("#job_cancel").click(function() {
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "control/cancel",
|
||||
type: "POST",
|
||||
dataType: "json"
|
||||
})
|
||||
})
|
||||
|
||||
//~~ Temperature control
|
||||
|
||||
$("#temp_newTemp_set").click(function() {
|
||||
var newTemp = $("#temp_newTemp").val();
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "control/temperature",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: { temp: newTemp },
|
||||
success: function() {$("#temp_newTemp").val("")}
|
||||
})
|
||||
})
|
||||
$("#temp_newBedTemp_set").click(function() {
|
||||
var newBedTemp = $("#temp_newBedTemp").val();
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "control/temperature",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: { bedTemp: newBedTemp },
|
||||
success: function() {$("#temp_newBedTemp").val("")}
|
||||
})
|
||||
})
|
||||
|
||||
//~~ Jog controls
|
||||
|
||||
function jogCommand(axis, distance) {
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "control/jog",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: axis + "=" + distance
|
||||
})
|
||||
}
|
||||
function homeCommand(axis) {
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "control/jog",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: "home" + axis
|
||||
})
|
||||
}
|
||||
$("#jog_x_inc").click(function() {jogCommand("x", "10")});
|
||||
$("#jog_x_dec").click(function() {jogCommand("x", "-10")});
|
||||
$("#jog_y_inc").click(function() {jogCommand("y", "10")});
|
||||
$("#jog_y_dec").click(function() {jogCommand("y", "-10")});
|
||||
$("#jog_z_inc").click(function() {jogCommand("z", "10")});
|
||||
$("#jog_z_dec").click(function() {jogCommand("z", "-10")});
|
||||
$("#jog_xy_home").click(function() {homeCommand("XY")});
|
||||
$("#jog_z_home").click(function() {homeCommand("Z")});
|
||||
|
||||
//~~ Speed controls
|
||||
|
||||
function speedCommand(structure) {
|
||||
var speedSetting = $("#speed_" + structure).val();
|
||||
if (speedSetting) {
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "control/speed",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: structure + "=" + speedSetting,
|
||||
success: function(response) {
|
||||
$("#speed_" + structure).val("")
|
||||
speedViewModel.fromResponse(response);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
$("#speed_outerWall_set").click(function() {speedCommand("outerWall")});
|
||||
$("#speed_innerWall_set").click(function() {speedCommand("innerWall")});
|
||||
$("#speed_support_set").click(function() {speedCommand("support")});
|
||||
$("#speed_fill_set").click(function() {speedCommand("fill")});
|
||||
|
||||
//~~ Terminal
|
||||
|
||||
$("#terminal-send").click(function () {
|
||||
var command = $("#terminal-command").val();
|
||||
if (command) {
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "control/command",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: "command=" + command
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
//~~ Gcode upload
|
||||
|
||||
$("#gcode_upload").fileupload({
|
||||
dataType: "json",
|
||||
done: function (e, data) {
|
||||
gcodeFilesViewModel.fromResponse(data.result);
|
||||
},
|
||||
progressall: function (e, data) {
|
||||
var progress = parseInt(data.loaded / data.total * 100, 10);
|
||||
$("#gcode_upload_progress .bar").css("width", progress + "%");
|
||||
}
|
||||
});
|
||||
|
||||
//~~ Offline overlay
|
||||
$("#offline_overlay_reconnect").click(function() {dataUpdater.requestData()});
|
||||
|
||||
//~~ knockout.js bindings
|
||||
|
||||
ko.applyBindings(connectionViewModel, document.getElementById("connection"));
|
||||
ko.applyBindings(printerStateViewModel, document.getElementById("state"));
|
||||
ko.applyBindings(gcodeFilesViewModel, document.getElementById("files"));
|
||||
ko.applyBindings(temperatureViewModel, document.getElementById("temp"));
|
||||
ko.applyBindings(printerStateViewModel, document.getElementById("jog"));
|
||||
ko.applyBindings(terminalViewModel, document.getElementById("term"));
|
||||
ko.applyBindings(speedViewModel, document.getElementById("speed"));
|
||||
|
||||
//~~ startup commands
|
||||
|
||||
dataUpdater.requestData();
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "gcodefiles",
|
||||
method: "GET",
|
||||
dataType: "json",
|
||||
success: function(response) {
|
||||
self.gcodeFilesViewModel.fromResponse(response);
|
||||
}
|
||||
});
|
||||
$.ajax({
|
||||
url: AJAX_BASEURL + "control/connectionOptions",
|
||||
method: "GET",
|
||||
dataType: "json",
|
||||
success: function(response) {
|
||||
connectionViewModel.fromResponse(response);
|
||||
}
|
||||
})
|
||||
}
|
||||
);
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Printer WebUI</title>
|
||||
|
||||
<link rel="shortcut icon" href="{{ url_for('static', filename='img/favicon.ico') }}">
|
||||
|
||||
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet" media="screen">
|
||||
<link href="{{ url_for('static', filename='css/jquery.fileupload-ui.css') }}" rel="stylesheet" media="screen">
|
||||
<link href="{{ url_for('static', filename='css/ui.css') }}" rel="stylesheet" media="screen">
|
||||
|
||||
<script src="http://code.jquery.com/jquery-latest.js"></script>
|
||||
<script src="{{ url_for('static', filename='js/knockout-2.2.0.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/bootstrap.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/jquery.ui.widget.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/jquery.flot.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/jquery.iframe-transport.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/jquery.fileupload.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/ui.js') }}"></script>
|
||||
<script lang="javascript">
|
||||
var AJAX_BASEURL = '/ajax/';
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="navbar navbar-fixed-top">
|
||||
<div class="navbar-inner">
|
||||
<div class="container">
|
||||
<a class="brand" href="#">Printer WebUI</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="accordion span4">
|
||||
<div class="accordion-group">
|
||||
<div class="accordion-heading">
|
||||
<a class="accordion-toggle" data-toggle="collapse" href="#connection"><i class="icon-signal"></i> Connection</a>
|
||||
</div>
|
||||
<div class="accordion-body collapse in" id="connection">
|
||||
<div class="accordion-inner">
|
||||
<label for="connection_ports" data-bind="css: {disabled: !isErrorOrClosed}, enable: isErrorOrClosed">Serial Port</label>
|
||||
<select id="connection_ports" data-bind="options: portOptions, optionsCaption: 'AUTO', value: selectedPort, css: {disabled: !isErrorOrClosed}, enable: isErrorOrClosed"></select>
|
||||
<label for="connection_baudrates" data-bind="css: {disabled: !isErrorOrClosed}, enable: isErrorOrClosed">Baudrate</label>
|
||||
<select id="connection_baudrates" data-bind="options: baudrateOptions, optionsCaption: 'AUTO', value: selectedBaudrate, css: {disabled: !isErrorOrClosed}, enable: isErrorOrClosed"></select>
|
||||
<button class="btn btn-block" id="printer_connect" data-bind="click: connect, text: buttonText()">Connect</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="accordion-group">
|
||||
<div class="accordion-heading">
|
||||
<a class="accordion-toggle" data-toggle="collapse" href="#state"><i class="icon-info-sign"></i> State</a>
|
||||
</div>
|
||||
<div class="accordion-body collapse in" id="state">
|
||||
<div class="accordion-inner">
|
||||
Machine State: <strong data-bind="text: stateString"></strong><br>
|
||||
File: <strong data-bind="text: filename"></strong><br>
|
||||
Filament: <strong data-bind="text: filament"></strong><br>
|
||||
Estimated Print Time: <strong data-bind="text: estimatedPrintTime"></strong><br>
|
||||
Line: <strong data-bind="text: lineString"></strong><br>
|
||||
Height: <strong data-bind="text: currentHeight"></strong><br>
|
||||
Print Time: <strong data-bind="text: printTime"></strong><br>
|
||||
Print Time Left: <strong data-bind="text: printTimeLeft"></strong><br>
|
||||
|
||||
<div class="progress">
|
||||
<div class="bar" id="job_progressBar" data-bind="style: { width: progress() + '%' }"></div>
|
||||
</div>
|
||||
|
||||
<button class="btn btn-primary" data-bind="enable: isOperational() && isReady() && !isPrinting() && !isPaused()" id="job_print"><i class="icon-print icon-white"></i> <span>Print</span></button>
|
||||
<button class="btn" id="job_pause" data-bind="css: {active: isPaused}"><i class="icon-pause"></i> <span>Pause</span></button>
|
||||
<button class="btn" id="job_cancel"><i class="icon-stop"></i> Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="accordion-group">
|
||||
<div class="accordion-heading">
|
||||
<a class="accordion-toggle" data-toggle="collapse" href="#files"><i class="icon-list"></i> Files</a>
|
||||
</div>
|
||||
<div class="accordion-body collapse in" id="files">
|
||||
<div class="accordion-inner">
|
||||
<table class="table table-striped table-hover table-condensed table-hover" id="gcode_files">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="gcode_files_name">Name</th>
|
||||
<th class="gcode_files_size">Size</th>
|
||||
<th class="gcode_files_action">Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody data-bind="foreach: files">
|
||||
<tr data-bind="attr: {title: name}, event: {dblclick: $parent.loadFile}">
|
||||
<td class="gcode_files_name" data-bind="text: name"></td>
|
||||
<td class="gcode_files_size" data-bind="text: size"></td>
|
||||
<td class="gcode_files_action"><a href="#" class="icon-trash" data-bind="click: $parent.removeFile"></a> | <a href="#" class="icon-folder-open" data-bind="click: $parent.loadFile"></a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<span class="btn btn-primary btn-block fileinput-button" style="margin-bottom: 10px">
|
||||
<i class="icon-upload icon-white"></i>
|
||||
<span>Upload</span>
|
||||
<input id="gcode_upload" type="file" name="gcode_file" class="fileinput-button" data-url="/ajax/gcodefiles/upload">
|
||||
</span>
|
||||
<div id="gcode_upload_progress" class="progress" style="width: 100%;">
|
||||
<div class="bar" style="width: 0%"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="tabbable span8">
|
||||
<ul class="nav nav-tabs">
|
||||
<li class="active"><a href="#temp" data-toggle="tab">Temp</a></li>
|
||||
<li><a href="#jog" data-toggle="tab">Jog</a></li>
|
||||
<li><a href="#speed" data-toggle="tab">Speed</a></li>
|
||||
<li><a href="#term" data-toggle="tab">Term</a></li>
|
||||
<li><a href="#webcam" data-toggle="tab">Webcam</a></li>
|
||||
</ul>
|
||||
|
||||
<div class="tab-content">
|
||||
<div class="tab-pane active" id="temp">
|
||||
<div class="row" style="padding-left: 20px">
|
||||
<div id="temperature-graph" style="height: 350px; width: 100%"></div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="form-horizontal" style="width: 49%; float: left; margin-bottom: 20px;">
|
||||
<fieldset>
|
||||
<legend>Temperature</legend>
|
||||
|
||||
<label>Current: <strong data-bind="text: tempString"></strong></label>
|
||||
|
||||
<label>Target: <strong data-bind="text: targetTempString"></strong></label>
|
||||
|
||||
<label for="temp_newTemp">New Target</label>
|
||||
<div class="input-append">
|
||||
<input class="span1" type="text" id="temp_newTemp" data-bind="attr: {placeholder: targetTemp}">
|
||||
<span class="add-on">°C</span>
|
||||
</div>
|
||||
<button type="submit" class="btn" id="temp_newTemp_set">Set</button>
|
||||
</fieldset>
|
||||
</div>
|
||||
<div class="form-horizontal" style="width: 49%; margin-left: 2%; float: left; margin-bottom: 20px;">
|
||||
<fieldset>
|
||||
<legend>Bed Temperature</legend>
|
||||
|
||||
<label>Current: <strong data-bind="text: bedTempString"></strong></label>
|
||||
|
||||
<label>Target: <strong data-bind="text: bedTargetTempString"></strong></label>
|
||||
|
||||
<label for="temp_newBedTemp">New Target</label>
|
||||
<div class="input-append">
|
||||
<input class="span1" type="text" id="temp_newBedTemp" data-bind="attr: {placeholder: bedTargetTemp}">
|
||||
<span class="add-on">°C</span>
|
||||
</div>
|
||||
<button type="submit" class="btn" id="temp_newBedTemp_set">Set</button>
|
||||
</fieldset>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tab-pane" id="jog">
|
||||
<div style="width: 350px; height: 70px">
|
||||
<div style="width: 70px; float: left;"> </div>
|
||||
<div style="width: 70px; float: left;"><button class="btn btn-block" id="jog_y_inc" data-bind="enable: isOperational() && !isPrinting()">Up</button></div>
|
||||
<div style="width: 70px; float: left;"> </div>
|
||||
<div style="width: 70px; float: left; margin-left: 20px"><button class="btn btn-block" id="jog_z_inc" data-bind="enable: isOperational() && !isPrinting()">Z+</button></div>
|
||||
</div>
|
||||
<div style="width: 350px; height: 70px">
|
||||
<div style="width: 70px; float: left;"><button class="btn btn-block" id="jog_x_dec" data-bind="enable: isOperational() && !isPrinting()">Left</button></div>
|
||||
<div style="width: 70px; float: left;"><button class="btn btn-block" id="jog_xy_home" data-bind="enable: isOperational() && !isPrinting()">Home</button></div>
|
||||
<div style="width: 70px; float: left;"><button class="btn btn-block" id="jog_x_inc" data-bind="enable: isOperational() && !isPrinting()">Right</button></div>
|
||||
<div style="width: 70px; float: left; margin-left: 20px"><button class="btn btn-block" id="jog_z_home" data-bind="enable: isOperational() && !isPrinting()">Home</button></div>
|
||||
</div>
|
||||
<div style="width: 350px; height: 70px">
|
||||
<div style="width: 70px; float: left;"> </div>
|
||||
<div style="width: 70px; float: left;"><button class="btn btn-block" id="jog_y_dec" data-bind="enable: isOperational() && !isPrinting()">Down</button></div>
|
||||
<div style="width: 70px; float: left;"> </div>
|
||||
<div style="width: 70px; float: left; margin-left: 20px"><button class="btn btn-block" id="jog_z_dec" data-bind="enable: isOperational() && !isPrinting()">Z-</button></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tab-pane" id="speed">
|
||||
<div class="form-horizontal" style="margin-bottom: 20px">
|
||||
<label for="speed_outerWall">Outer Wall</label>
|
||||
<div class="input-append">
|
||||
<input type="text" id="speed_outerWall" class="input-mini" data-bind="enable: isOperational(), attr: {placeholder: outerWall}">
|
||||
<span class="add-on">%</span>
|
||||
<button type="submit" class="btn" id="speed_outerWall_set" data-bind="enable: isOperational()">Set</button>
|
||||
</div>
|
||||
|
||||
<label for="speed_innerWall">Inner Wall</label>
|
||||
<div class="input-append">
|
||||
<input type="text" id="speed_innerWall" class="input-mini" data-bind="enable: isOperational(), attr: {placeholder: innerWall}">
|
||||
<span class="add-on">%</span>
|
||||
<button type="submit" class="btn" id="speed_innerWall_set" data-bind="enable: isOperational()">Set</button>
|
||||
</div>
|
||||
|
||||
<label for="speed_fill">Fill</label>
|
||||
<div class="input-append">
|
||||
<input type="text" id="speed_fill" class="input-mini" data-bind="enable: isOperational(), attr: {placeholder: fill}">
|
||||
<span class="add-on">%</span>
|
||||
<button type="submit" class="btn" id="speed_fill_set" data-bind="enable: isOperational()">Set</button>
|
||||
</div>
|
||||
|
||||
<label for="speed_support">Support</label>
|
||||
<div class="input-append">
|
||||
<input type="text" id="speed_support" class="input-mini" data-bind="enable: isOperational(), attr: {placeholder: support}">
|
||||
<span class="add-on">%</span>
|
||||
<button type="submit" class="btn" id="speed_support_set" data-bind="enable: isOperational()">Set</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tab-pane" id="term">
|
||||
<pre id="terminal-output" class="pre-scrollable"></pre>
|
||||
<div class="input-append">
|
||||
<input type="text" id="terminal-command">
|
||||
<button class="btn" type="button" id="terminal-send">Send</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tab-pane" id="webcam">
|
||||
Here be webcam stuff
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="offline_overlay">
|
||||
<div id="offline_overlay_background"></div>
|
||||
<div id="offline_overlay_wrapper">
|
||||
<div class="container">
|
||||
<div class="hero-unit">
|
||||
<h1>Server is offline</h1>
|
||||
<p>
|
||||
The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect
|
||||
automatically <strong>every 10 seconds</strong>, however you are welcome to try a manual reconnect
|
||||
anytime using the button below.
|
||||
</p>
|
||||
<p>
|
||||
<a class="btn btn-primary btn-large" id="offline_overlay_reconnect">Attempt to reconnect</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,12 @@
|
||||
The code in this sub package originates from the Cura project (https://github.com/daid/Cura). It has been
|
||||
slightly reorganized. The mapping to the original Cura source is the following:
|
||||
|
||||
* avr_isp.* => Cura.avr_isp.*
|
||||
* comm => Cura.util.machineCom
|
||||
* gcodeInterpreter => Cura.util.gcodeInterpreter
|
||||
* profile => Cura.util.profile
|
||||
* resources => Cura.util.resources
|
||||
* util3d => Cura.util.util3d
|
||||
* version => Cura.util.version
|
||||
|
||||
In the future "profile" and "version" are to be replaced by custom implementations.
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,20 @@
|
||||
|
||||
avrChipDB = {
|
||||
'ATMega1280': {
|
||||
'signature': [0x1E, 0x97, 0x03],
|
||||
'pageSize': 128,
|
||||
'pageCount': 512,
|
||||
},
|
||||
'ATMega2560': {
|
||||
'signature': [0x1E, 0x98, 0x01],
|
||||
'pageSize': 128,
|
||||
'pageCount': 1024,
|
||||
},
|
||||
}
|
||||
|
||||
def getChipFromDB(sig):
|
||||
for chip in avrChipDB.values():
|
||||
if chip['signature'] == sig:
|
||||
return chip
|
||||
return False
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import io
|
||||
|
||||
def readHex(filename):
|
||||
data = []
|
||||
extraAddr = 0
|
||||
f = io.open(filename, "r")
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line[0] != ':':
|
||||
raise Exception("Hex file has a line not starting with ':'")
|
||||
recLen = int(line[1:3], 16)
|
||||
addr = int(line[3:7], 16) + extraAddr
|
||||
recType = int(line[7:9], 16)
|
||||
if len(line) != recLen * 2 + 11:
|
||||
raise Exception("Error in hex file: " + line)
|
||||
checkSum = 0
|
||||
for i in xrange(0, recLen + 5):
|
||||
checkSum += int(line[i*2+1:i*2+3], 16)
|
||||
checkSum &= 0xFF
|
||||
if checkSum != 0:
|
||||
raise Exception("Checksum error in hex file: " + line)
|
||||
|
||||
if recType == 0:#Data record
|
||||
while len(data) < addr + recLen:
|
||||
data.append(0)
|
||||
for i in xrange(0, recLen):
|
||||
data[addr + i] = int(line[i*2+9:i*2+11], 16)
|
||||
elif recType == 1: #End Of File record
|
||||
pass
|
||||
elif recType == 2: #Extended Segment Address Record
|
||||
extraAddr = int(line[9:13], 16) * 16
|
||||
else:
|
||||
print(recType, recLen, addr, checkSum, line)
|
||||
f.close()
|
||||
return data
|
||||
@@ -0,0 +1,35 @@
|
||||
import os, struct, sys, time
|
||||
|
||||
from serial import Serial
|
||||
|
||||
import chipDB
|
||||
|
||||
class IspBase():
|
||||
def programChip(self, flashData):
|
||||
self.curExtAddr = -1
|
||||
self.chip = chipDB.getChipFromDB(self.getSignature())
|
||||
if self.chip == False:
|
||||
raise IspError("Chip with signature: " + str(self.getSignature()) + "not found")
|
||||
self.chipErase()
|
||||
|
||||
print("Flashing %i bytes" % len(flashData))
|
||||
self.writeFlash(flashData)
|
||||
print("Verifying %i bytes" % len(flashData))
|
||||
self.verifyFlash(flashData)
|
||||
|
||||
#low level ISP commands
|
||||
def getSignature(self):
|
||||
sig = []
|
||||
sig.append(self.sendISP([0x30, 0x00, 0x00, 0x00])[3])
|
||||
sig.append(self.sendISP([0x30, 0x00, 0x01, 0x00])[3])
|
||||
sig.append(self.sendISP([0x30, 0x00, 0x02, 0x00])[3])
|
||||
return sig
|
||||
|
||||
def chipErase(self):
|
||||
self.sendISP([0xAC, 0x80, 0x00, 0x00])
|
||||
|
||||
class IspError():
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
def __str__(self):
|
||||
return repr(self.value)
|
||||
@@ -0,0 +1,154 @@
|
||||
import os, struct, sys, time
|
||||
|
||||
from serial import Serial
|
||||
from serial import SerialException
|
||||
|
||||
import ispBase, intelHex
|
||||
|
||||
class Stk500v2(ispBase.IspBase):
|
||||
def __init__(self):
|
||||
self.serial = None
|
||||
self.seq = 1
|
||||
self.lastAddr = -1
|
||||
self.progressCallback = None
|
||||
|
||||
def connect(self, port = 'COM22', speed = 115200):
|
||||
if self.serial != None:
|
||||
self.close()
|
||||
try:
|
||||
self.serial = Serial(str(port), speed, timeout=1, writeTimeout=10000)
|
||||
except SerialException as e:
|
||||
raise ispBase.IspError("Failed to open serial port")
|
||||
except:
|
||||
raise ispBase.IspError("Unexpected error while connecting to serial port:" + port + ":" + str(sys.exc_info()[0]))
|
||||
self.seq = 1
|
||||
|
||||
#Reset the controller
|
||||
self.serial.setDTR(1)
|
||||
time.sleep(0.1)
|
||||
self.serial.setDTR(0)
|
||||
time.sleep(0.2)
|
||||
|
||||
self.sendMessage([1])
|
||||
if self.sendMessage([0x10, 0xc8, 0x64, 0x19, 0x20, 0x00, 0x53, 0x03, 0xac, 0x53, 0x00, 0x00]) != [0x10, 0x00]:
|
||||
self.close()
|
||||
raise ispBase.IspError("Failed to enter programming mode")
|
||||
|
||||
def close(self):
|
||||
if self.serial != None:
|
||||
self.serial.close()
|
||||
self.serial = None
|
||||
|
||||
#Leave ISP does not reset the serial port, only resets the device, and returns the serial port after disconnecting it from the programming interface.
|
||||
# This allows you to use the serial port without opening it again.
|
||||
def leaveISP(self):
|
||||
if self.serial != None:
|
||||
if self.sendMessage([0x11]) != [0x11, 0x00]:
|
||||
raise ispBase.IspError("Failed to leave programming mode")
|
||||
ret = self.serial
|
||||
self.serial = None
|
||||
return ret
|
||||
return None
|
||||
|
||||
def isConnected(self):
|
||||
return self.serial != None
|
||||
|
||||
def sendISP(self, data):
|
||||
recv = self.sendMessage([0x1D, 4, 4, 0, data[0], data[1], data[2], data[3]])
|
||||
return recv[2:6]
|
||||
|
||||
def writeFlash(self, flashData):
|
||||
#Set load addr to 0, in case we have more then 64k flash we need to enable the address extension
|
||||
pageSize = self.chip['pageSize'] * 2
|
||||
flashSize = pageSize * self.chip['pageCount']
|
||||
if flashSize > 0xFFFF:
|
||||
self.sendMessage([0x06, 0x80, 0x00, 0x00, 0x00])
|
||||
else:
|
||||
self.sendMessage([0x06, 0x00, 0x00, 0x00, 0x00])
|
||||
|
||||
loadCount = (len(flashData) + pageSize - 1) / pageSize
|
||||
for i in xrange(0, loadCount):
|
||||
recv = self.sendMessage([0x13, pageSize >> 8, pageSize & 0xFF, 0xc1, 0x0a, 0x40, 0x4c, 0x20, 0x00, 0x00] + flashData[(i * pageSize):(i * pageSize + pageSize)])
|
||||
if self.progressCallback != None:
|
||||
self.progressCallback(i + 1, loadCount*2)
|
||||
|
||||
def verifyFlash(self, flashData):
|
||||
#Set load addr to 0, in case we have more then 64k flash we need to enable the address extension
|
||||
flashSize = self.chip['pageSize'] * 2 * self.chip['pageCount']
|
||||
if flashSize > 0xFFFF:
|
||||
self.sendMessage([0x06, 0x80, 0x00, 0x00, 0x00])
|
||||
else:
|
||||
self.sendMessage([0x06, 0x00, 0x00, 0x00, 0x00])
|
||||
|
||||
loadCount = (len(flashData) + 0xFF) / 0x100
|
||||
for i in xrange(0, loadCount):
|
||||
recv = self.sendMessage([0x14, 0x01, 0x00, 0x20])[2:0x102]
|
||||
if self.progressCallback != None:
|
||||
self.progressCallback(loadCount + i + 1, loadCount*2)
|
||||
for j in xrange(0, 0x100):
|
||||
if i * 0x100 + j < len(flashData) and flashData[i * 0x100 + j] != recv[j]:
|
||||
raise ispBase.IspError('Verify error at: 0x%x' % (i * 0x100 + j))
|
||||
|
||||
def sendMessage(self, data):
|
||||
message = struct.pack(">BBHB", 0x1B, self.seq, len(data), 0x0E)
|
||||
for c in data:
|
||||
message += struct.pack(">B", c)
|
||||
checksum = 0
|
||||
for c in message:
|
||||
checksum ^= ord(c)
|
||||
message += struct.pack(">B", checksum)
|
||||
try:
|
||||
self.serial.write(message)
|
||||
self.serial.flush()
|
||||
except SerialTimeoutException:
|
||||
raise ispBase.IspError('Serial send timeout')
|
||||
self.seq = (self.seq + 1) & 0xFF
|
||||
return self.recvMessage()
|
||||
|
||||
def recvMessage(self):
|
||||
state = 'Start'
|
||||
checksum = 0
|
||||
while True:
|
||||
s = self.serial.read()
|
||||
if len(s) < 1:
|
||||
raise ispBase.IspError("Timeout")
|
||||
b = struct.unpack(">B", s)[0]
|
||||
checksum ^= b
|
||||
#print(hex(b))
|
||||
if state == 'Start':
|
||||
if b == 0x1B:
|
||||
state = 'GetSeq'
|
||||
checksum = 0x1B
|
||||
elif state == 'GetSeq':
|
||||
state = 'MsgSize1'
|
||||
elif state == 'MsgSize1':
|
||||
msgSize = b << 8
|
||||
state = 'MsgSize2'
|
||||
elif state == 'MsgSize2':
|
||||
msgSize |= b
|
||||
state = 'Token'
|
||||
elif state == 'Token':
|
||||
if b != 0x0E:
|
||||
state = 'Start'
|
||||
else:
|
||||
state = 'Data'
|
||||
data = []
|
||||
elif state == 'Data':
|
||||
data.append(b)
|
||||
if len(data) == msgSize:
|
||||
state = 'Checksum'
|
||||
elif state == 'Checksum':
|
||||
if checksum != 0:
|
||||
state = 'Start'
|
||||
else:
|
||||
return data
|
||||
|
||||
|
||||
def main():
|
||||
programmer = Stk500v2()
|
||||
programmer.connect(port = sys.argv[1])
|
||||
programmer.programChip(intelHex.readHex(sys.argv[2]))
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,559 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import os
|
||||
import glob
|
||||
import sys
|
||||
import time
|
||||
import math
|
||||
import re
|
||||
import traceback
|
||||
import threading
|
||||
import Queue as queue
|
||||
|
||||
import serial
|
||||
|
||||
from printer_webui.util.avr_isp import stk500v2
|
||||
from printer_webui.util.avr_isp import ispBase
|
||||
|
||||
from printer_webui.util import profile
|
||||
|
||||
try:
|
||||
import _winreg
|
||||
except:
|
||||
pass
|
||||
|
||||
def isDevVersion():
|
||||
gitPath = os.path.abspath(os.path.join(os.path.split(os.path.abspath(__file__))[0], "../../.git"))
|
||||
return os.path.exists(gitPath)
|
||||
|
||||
def serialList():
|
||||
baselist=[]
|
||||
if os.name=="nt":
|
||||
try:
|
||||
key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"HARDWARE\\DEVICEMAP\\SERIALCOMM")
|
||||
i=0
|
||||
while(1):
|
||||
baselist+=[_winreg.EnumValue(key,i)[1]]
|
||||
i+=1
|
||||
except:
|
||||
pass
|
||||
baselist = baselist + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyACM*') + glob.glob("/dev/tty.usb*") + glob.glob("/dev/cu.*") + glob.glob("/dev/rfcomm*")
|
||||
prev = profile.getPreference('serial_port_auto')
|
||||
if prev in baselist:
|
||||
baselist.remove(prev)
|
||||
baselist.insert(0, prev)
|
||||
if isDevVersion():
|
||||
baselist.append('VIRTUAL')
|
||||
return baselist
|
||||
|
||||
def baudrateList():
|
||||
ret = [250000, 230400, 115200, 57600, 38400, 19200, 9600]
|
||||
if profile.getPreference('serial_baud_auto') != '':
|
||||
prev = int(profile.getPreference('serial_baud_auto'))
|
||||
if prev in ret:
|
||||
ret.remove(prev)
|
||||
ret.insert(0, prev)
|
||||
return ret
|
||||
|
||||
class VirtualPrinter():
|
||||
def __init__(self):
|
||||
self.readList = ['start\n', 'Marlin: Virtual Marlin!\n', '\x80\n']
|
||||
self.temp = 0.0
|
||||
self.targetTemp = 0.0
|
||||
self.lastTempAt = time.time()
|
||||
self.bedTemp = 1.0
|
||||
self.bedTargetTemp = 1.0
|
||||
|
||||
def write(self, data):
|
||||
if self.readList is None:
|
||||
return
|
||||
#print "Send: %s" % (data.rstrip())
|
||||
if 'M104' in data or 'M109' in data:
|
||||
try:
|
||||
self.targetTemp = float(re.search('S([0-9]+)', data).group(1))
|
||||
except:
|
||||
pass
|
||||
if 'M140' in data or 'M190' in data:
|
||||
try:
|
||||
self.bedTargetTemp = float(re.search('S([0-9]+)', data).group(1))
|
||||
except:
|
||||
pass
|
||||
if 'M105' in data:
|
||||
self.readList.append("ok T:%.2f /%.2f B:%.2f /%.2f @:64\n" % (self.temp, self.targetTemp, self.bedTemp, self.bedTargetTemp))
|
||||
elif len(data.strip()) > 0:
|
||||
self.readList.append("ok\n")
|
||||
|
||||
def readline(self):
|
||||
if self.readList is None:
|
||||
return ''
|
||||
n = 0
|
||||
timeDiff = self.lastTempAt - time.time()
|
||||
self.lastTempAt = time.time()
|
||||
if abs(self.temp - self.targetTemp) > 1:
|
||||
self.temp += math.copysign(timeDiff * 10, self.targetTemp - self.temp)
|
||||
if self.temp < 0:
|
||||
self.temp = 0
|
||||
if abs(self.bedTemp - self.bedTargetTemp) > 1:
|
||||
self.bedTemp += math.copysign(timeDiff * 10, self.bedTargetTemp - self.bedTemp)
|
||||
if self.bedTemp < 0:
|
||||
self.bedTemp = 0
|
||||
while len(self.readList) < 1:
|
||||
time.sleep(0.1)
|
||||
n += 1
|
||||
if n == 20:
|
||||
return ''
|
||||
if self.readList is None:
|
||||
return ''
|
||||
time.sleep(0.001)
|
||||
#print "Recv: %s" % (self.readList[0].rstrip())
|
||||
return self.readList.pop(0)
|
||||
|
||||
def close(self):
|
||||
self.readList = None
|
||||
|
||||
class MachineComPrintCallback(object):
|
||||
def mcLog(self, message):
|
||||
pass
|
||||
|
||||
def mcTempUpdate(self, temp, bedTemp, targetTemp, bedTargetTemp):
|
||||
pass
|
||||
|
||||
def mcStateChange(self, state):
|
||||
pass
|
||||
|
||||
def mcMessage(self, message):
|
||||
pass
|
||||
|
||||
def mcProgress(self, lineNr):
|
||||
pass
|
||||
|
||||
def mcZChange(self, newZ):
|
||||
pass
|
||||
|
||||
class MachineCom(object):
|
||||
STATE_NONE = 0
|
||||
STATE_OPEN_SERIAL = 1
|
||||
STATE_DETECT_SERIAL = 2
|
||||
STATE_DETECT_BAUDRATE = 3
|
||||
STATE_CONNECTING = 4
|
||||
STATE_OPERATIONAL = 5
|
||||
STATE_PRINTING = 6
|
||||
STATE_PAUSED = 7
|
||||
STATE_CLOSED = 8
|
||||
STATE_ERROR = 9
|
||||
STATE_CLOSED_WITH_ERROR = 10
|
||||
|
||||
def __init__(self, port = None, baudrate = None, callbackObject = None):
|
||||
if port == None:
|
||||
port = profile.getPreference('serial_port')
|
||||
if baudrate == None:
|
||||
if profile.getPreference('serial_baud') == 'AUTO':
|
||||
baudrate = 0
|
||||
else:
|
||||
baudrate = int(profile.getPreference('serial_baud'))
|
||||
if callbackObject == None:
|
||||
callbackObject = MachineComPrintCallback()
|
||||
|
||||
self._port = port
|
||||
self._baudrate = baudrate
|
||||
self._callback = callbackObject
|
||||
self._state = self.STATE_NONE
|
||||
self._serial = None
|
||||
self._baudrateDetectList = baudrateList()
|
||||
self._baudrateDetectRetry = 0
|
||||
self._temp = 0
|
||||
self._bedTemp = 0
|
||||
self._targetTemp = 0
|
||||
self._bedTargetTemp = 0
|
||||
self._gcodeList = None
|
||||
self._gcodePos = 0
|
||||
self._commandQueue = queue.Queue()
|
||||
self._logQueue = queue.Queue(256)
|
||||
self._feedRateModifier = {}
|
||||
self._currentZ = -1
|
||||
self._heatupWaitStartTime = 0
|
||||
self._heatupWaitTimeLost = 0.0
|
||||
self._printStartTime100 = None
|
||||
|
||||
self.thread = threading.Thread(target=self._monitor)
|
||||
self.thread.daemon = True
|
||||
self.thread.start()
|
||||
|
||||
def _changeState(self, newState):
|
||||
if self._state == newState:
|
||||
return
|
||||
oldState = self.getStateString()
|
||||
self._state = newState
|
||||
self._log('Changing monitoring state from \'%s\' to \'%s\'' % (oldState, self.getStateString()))
|
||||
self._callback.mcStateChange(newState)
|
||||
|
||||
def getState(self):
|
||||
return self._state
|
||||
|
||||
def getStateString(self):
|
||||
if self._state == self.STATE_NONE:
|
||||
return "Offline"
|
||||
if self._state == self.STATE_OPEN_SERIAL:
|
||||
return "Opening serial port"
|
||||
if self._state == self.STATE_DETECT_SERIAL:
|
||||
return "Detecting serial port"
|
||||
if self._state == self.STATE_DETECT_BAUDRATE:
|
||||
return "Detecting baudrate"
|
||||
if self._state == self.STATE_CONNECTING:
|
||||
return "Connecting"
|
||||
if self._state == self.STATE_OPERATIONAL:
|
||||
return "Operational"
|
||||
if self._state == self.STATE_PRINTING:
|
||||
return "Printing"
|
||||
if self._state == self.STATE_PAUSED:
|
||||
return "Paused"
|
||||
if self._state == self.STATE_CLOSED:
|
||||
return "Closed"
|
||||
if self._state == self.STATE_ERROR:
|
||||
return "Error: %s" % (self.getShortErrorString())
|
||||
if self._state == self.STATE_CLOSED_WITH_ERROR:
|
||||
return "Error: %s" % (self.getShortErrorString())
|
||||
return "?%d?" % (self._state)
|
||||
|
||||
def getShortErrorString(self):
|
||||
if len(self._errorValue) < 20:
|
||||
return self._errorValue
|
||||
return self._errorValue[:20] + "..."
|
||||
|
||||
def getErrorString(self):
|
||||
return self._errorValue
|
||||
|
||||
def isClosedOrError(self):
|
||||
return self._state == self.STATE_ERROR or self._state == self.STATE_CLOSED_WITH_ERROR or self._state == self.STATE_CLOSED
|
||||
|
||||
def isError(self):
|
||||
return self._state == self.STATE_ERROR or self._state == self.STATE_CLOSED_WITH_ERROR
|
||||
|
||||
def isOperational(self):
|
||||
return self._state == self.STATE_OPERATIONAL or self._state == self.STATE_PRINTING or self._state == self.STATE_PAUSED
|
||||
|
||||
def isPrinting(self):
|
||||
return self._state == self.STATE_PRINTING
|
||||
|
||||
def isPaused(self):
|
||||
return self._state == self.STATE_PAUSED
|
||||
|
||||
def getPrintPos(self):
|
||||
return self._gcodePos
|
||||
|
||||
def getPrintTime(self):
|
||||
return time.time() - self._printStartTime
|
||||
|
||||
def getPrintTimeRemainingEstimate(self):
|
||||
if self._printStartTime100 == None or self.getPrintPos() < 200:
|
||||
return None
|
||||
printTime = (time.time() - self._printStartTime100) / 60
|
||||
printTimeTotal = printTime * (len(self._gcodeList) - 100) / (self.getPrintPos() - 100)
|
||||
printTimeLeft = printTimeTotal - printTime
|
||||
return printTimeLeft
|
||||
|
||||
def getTemp(self):
|
||||
return self._temp
|
||||
|
||||
def getBedTemp(self):
|
||||
return self._bedTemp
|
||||
|
||||
def getLog(self):
|
||||
ret = []
|
||||
while not self._logQueue.empty():
|
||||
ret.append(self._logQueue.get())
|
||||
for line in ret:
|
||||
self._logQueue.put(line, False)
|
||||
return ret
|
||||
|
||||
def _monitor(self):
|
||||
#Open the serial port.
|
||||
if self._port == 'AUTO':
|
||||
self._changeState(self.STATE_DETECT_SERIAL)
|
||||
programmer = stk500v2.Stk500v2()
|
||||
self._log("Serial port list: %s" % (str(serialList())))
|
||||
for p in serialList():
|
||||
try:
|
||||
self._log("Connecting to: %s" % (p))
|
||||
programmer.connect(p)
|
||||
self._serial = programmer.leaveISP()
|
||||
profile.putPreference('serial_port_auto', p)
|
||||
break
|
||||
except ispBase.IspError as (e):
|
||||
self._log("Error while connecting to %s: %s" % (p, str(e)))
|
||||
pass
|
||||
except:
|
||||
self._log("Unexpected error while connecting to serial port: %s %s" % (p, getExceptionString()))
|
||||
programmer.close()
|
||||
elif self._port == 'VIRTUAL':
|
||||
self._changeState(self.STATE_OPEN_SERIAL)
|
||||
self._serial = VirtualPrinter()
|
||||
else:
|
||||
self._changeState(self.STATE_OPEN_SERIAL)
|
||||
try:
|
||||
self._log("Connecting to: %s" % (self._port))
|
||||
if self._baudrate == 0:
|
||||
self._serial = serial.Serial(str(self._port), 115200, timeout=0.1, writeTimeout=10000)
|
||||
else:
|
||||
self._serial = serial.Serial(str(self._port), self._baudrate, timeout=2, writeTimeout=10000)
|
||||
except:
|
||||
self._log("Unexpected error while connecting to serial port: %s %s" % (self._port, getExceptionString()))
|
||||
if self._serial == None:
|
||||
self._log("Failed to open serial port (%s)" % (self._port))
|
||||
self._errorValue = 'Failed to autodetect serial port.'
|
||||
self._changeState(self.STATE_ERROR)
|
||||
return
|
||||
self._log("Connected to: %s, starting monitor" % (self._serial))
|
||||
if self._baudrate == 0:
|
||||
self._changeState(self.STATE_DETECT_BAUDRATE)
|
||||
else:
|
||||
self._changeState(self.STATE_CONNECTING)
|
||||
|
||||
#Start monitoring the serial port.
|
||||
timeout = time.time() + 5
|
||||
tempRequestTimeout = timeout
|
||||
while True:
|
||||
line = self._readline()
|
||||
if line == None:
|
||||
break
|
||||
|
||||
#No matter the state, if we see an error, goto the error state and store the error for reference.
|
||||
if line.startswith('Error:'):
|
||||
#Oh YEAH, consistency.
|
||||
# Marlin reports an MIN/MAX temp error as "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
|
||||
# But a bed temp error is reported as "Error: Temperature heated bed switched off. MAXTEMP triggered !!"
|
||||
# So we can have an extra newline in the most common case. Awesome work people.
|
||||
if re.match('Error:[0-9]\n', line):
|
||||
line = line.rstrip() + self._readline()
|
||||
#Skip the communication errors, as those get corrected.
|
||||
if 'checksum mismatch' in line or 'Line Number is not Last Line Number' in line or 'No Line Number with checksum' in line:
|
||||
pass
|
||||
elif not self.isError():
|
||||
self._errorValue = line[6:]
|
||||
self._changeState(self.STATE_ERROR)
|
||||
if ' T:' in line or line.startswith('T:'):
|
||||
self._temp = float(re.search("[0-9\.]*", line.split('T:')[1]).group(0))
|
||||
if ' B:' in line:
|
||||
self._bedTemp = float(re.search("[0-9\.]*", line.split(' B:')[1]).group(0))
|
||||
self._callback.mcTempUpdate(self._temp, self._bedTemp, self._targetTemp, self._bedTargetTemp)
|
||||
#If we are waiting for an M109 or M190 then measure the time we lost during heatup, so we can remove that time from our printing time estimate.
|
||||
if not 'ok' in line and self._heatupWaitStartTime != 0:
|
||||
t = time.time()
|
||||
self._heatupWaitTimeLost = t - self._heatupWaitStartTime
|
||||
self._heatupWaitStartTime = t
|
||||
elif line.strip() != '' and line.strip() != 'ok' and not line.startswith('Resend:') and line != 'echo:Unknown command:""\n' and self.isOperational():
|
||||
self._callback.mcMessage(line)
|
||||
|
||||
if self._state == self.STATE_DETECT_BAUDRATE:
|
||||
if line == '' or time.time() > timeout:
|
||||
if len(self._baudrateDetectList) < 1:
|
||||
self.close()
|
||||
self._errorValue = "No more baudrates to test, and no suitable baudrate found."
|
||||
self._changeState(self.STATE_ERROR)
|
||||
elif self._baudrateDetectRetry > 0:
|
||||
self._baudrateDetectRetry -= 1
|
||||
self._serial.write('\n')
|
||||
self._log("Baudrate test retry: %d" % (self._baudrateDetectRetry))
|
||||
self._sendCommand("M105")
|
||||
self._testingBaudrate = True
|
||||
else:
|
||||
baudrate = self._baudrateDetectList.pop(0)
|
||||
try:
|
||||
self._serial.baudrate = baudrate
|
||||
self._serial.timeout = 0.5
|
||||
self._log("Trying baudrate: %d" % (baudrate))
|
||||
self._baudrateDetectRetry = 5
|
||||
self._baudrateDetectTestOk = 0
|
||||
timeout = time.time() + 5
|
||||
self._serial.write('\n')
|
||||
self._sendCommand("M105")
|
||||
self._testingBaudrate = True
|
||||
except:
|
||||
self._log("Unexpected error while setting baudrate: %d %s" % (baudrate, getExceptionString()))
|
||||
elif 'ok' in line and 'T:' in line:
|
||||
self._baudrateDetectTestOk += 1
|
||||
if self._baudrateDetectTestOk < 10:
|
||||
self._log("Baudrate test ok: %d" % (self._baudrateDetectTestOk))
|
||||
self._sendCommand("M105")
|
||||
else:
|
||||
self._sendCommand("M999")
|
||||
self._serial.timeout = 2
|
||||
profile.putPreference('serial_baud_auto', self._serial.baudrate)
|
||||
self._changeState(self.STATE_OPERATIONAL)
|
||||
else:
|
||||
self._testingBaudrate = False
|
||||
elif self._state == self.STATE_CONNECTING:
|
||||
if line == '':
|
||||
self._sendCommand("M105")
|
||||
elif 'ok' in line:
|
||||
self._changeState(self.STATE_OPERATIONAL)
|
||||
if time.time() > timeout:
|
||||
self.close()
|
||||
elif self._state == self.STATE_OPERATIONAL:
|
||||
#Request the temperature on comm timeout (every 2 seconds) when we are not printing.
|
||||
if line == '':
|
||||
self._sendCommand("M105")
|
||||
tempRequestTimeout = time.time() + 5
|
||||
elif self._state == self.STATE_PRINTING:
|
||||
if line == '' and time.time() > timeout:
|
||||
self._log("Communication timeout during printing, forcing a line")
|
||||
line = 'ok'
|
||||
#Even when printing request the temperture every 5 seconds.
|
||||
if time.time() > tempRequestTimeout:
|
||||
self._commandQueue.put("M105")
|
||||
tempRequestTimeout = time.time() + 5
|
||||
if 'ok' in line:
|
||||
timeout = time.time() + 5
|
||||
if not self._commandQueue.empty():
|
||||
self._sendCommand(self._commandQueue.get())
|
||||
else:
|
||||
self._sendNext()
|
||||
elif "resend" in line.lower() or "rs" in line:
|
||||
try:
|
||||
self._gcodePos = int(line.replace("N:"," ").replace("N"," ").replace(":"," ").split()[-1])
|
||||
except:
|
||||
if "rs" in line:
|
||||
self._gcodePos = int(line.split()[1])
|
||||
self._log("Connection closed, closing down monitor")
|
||||
|
||||
def _log(self, message):
|
||||
self._callback.mcLog(message)
|
||||
try:
|
||||
self._logQueue.put(message, False)
|
||||
except:
|
||||
#If the log queue is full, remove the first message and append the new message again
|
||||
self._logQueue.get()
|
||||
try:
|
||||
self._logQueue.put(message, False)
|
||||
except:
|
||||
pass
|
||||
|
||||
def _readline(self):
|
||||
if self._serial == None:
|
||||
return None
|
||||
try:
|
||||
ret = self._serial.readline()
|
||||
except:
|
||||
self._log("Unexpected error while reading serial port: %s" % (getExceptionString()))
|
||||
self._errorValue = getExceptionString()
|
||||
self.close(True)
|
||||
return None
|
||||
if ret == '':
|
||||
#self._log("Recv: TIMEOUT")
|
||||
return ''
|
||||
self._log("Recv: %s" % (unicode(ret, 'ascii', 'replace').encode('ascii', 'replace').rstrip()))
|
||||
return ret
|
||||
|
||||
def close(self, isError = False):
|
||||
if self._serial != None:
|
||||
self._serial.close()
|
||||
if isError:
|
||||
self._changeState(self.STATE_CLOSED_WITH_ERROR)
|
||||
else:
|
||||
self._changeState(self.STATE_CLOSED)
|
||||
self._serial = None
|
||||
|
||||
def __del__(self):
|
||||
self.close()
|
||||
|
||||
def _sendCommand(self, cmd):
|
||||
if self._serial is None:
|
||||
return
|
||||
if 'M109' in cmd or 'M190' in cmd:
|
||||
self._heatupWaitStartTime = time.time()
|
||||
if 'M104' in cmd or 'M109' in cmd:
|
||||
try:
|
||||
self._targetTemp = float(re.search('S([0-9]+)', cmd).group(1))
|
||||
except:
|
||||
pass
|
||||
if 'M140' in cmd or 'M190' in cmd:
|
||||
try:
|
||||
self._bedTargetTemp = float(re.search('S([0-9]+)').group(1))
|
||||
except:
|
||||
pass
|
||||
self._log('Send: %s' % (cmd))
|
||||
try:
|
||||
self._serial.write(cmd + '\n')
|
||||
except serial.SerialTimeoutException:
|
||||
self._log("Serial timeout while writing to serial port, trying again.")
|
||||
try:
|
||||
self._serial.write(cmd + '\n')
|
||||
except:
|
||||
self._log("Unexpected error while writing serial port: %s" % (getExceptionString()))
|
||||
self._errorValue = getExceptionString()
|
||||
self.close(True)
|
||||
except:
|
||||
self._log("Unexpected error while writing serial port: %s" % (getExceptionString()))
|
||||
self._errorValue = getExceptionString()
|
||||
self.close(True)
|
||||
|
||||
def _sendNext(self):
|
||||
if self._gcodePos >= len(self._gcodeList):
|
||||
self._changeState(self.STATE_OPERATIONAL)
|
||||
return
|
||||
if self._gcodePos == 100:
|
||||
self._printStartTime100 = time.time()
|
||||
line = self._gcodeList[self._gcodePos]
|
||||
if type(line) is tuple:
|
||||
self._printSection = line[1]
|
||||
line = line[0]
|
||||
try:
|
||||
if line == 'M0' or line == 'M1':
|
||||
self.setPause(True)
|
||||
line = 'M105' #Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
|
||||
if self._printSection in self._feedRateModifier:
|
||||
line = re.sub('F([0-9]*)', lambda m: 'F' + str(int(int(m.group(1)) * self._feedRateModifier[self._printSection])), line)
|
||||
if ('G0' in line or 'G1' in line) and 'Z' in line:
|
||||
z = float(re.search('Z([0-9\.]*)', line).group(1))
|
||||
if self._currentZ != z:
|
||||
self._currentZ = z
|
||||
self._callback.mcZChange(z)
|
||||
except:
|
||||
self._log("Unexpected error: %s" % (getExceptionString()))
|
||||
checksum = reduce(lambda x,y:x^y, map(ord, "N%d%s" % (self._gcodePos, line)))
|
||||
self._sendCommand("N%d%s*%d" % (self._gcodePos, line, checksum))
|
||||
self._gcodePos += 1
|
||||
self._callback.mcProgress(self._gcodePos)
|
||||
|
||||
def sendCommand(self, cmd):
|
||||
cmd = cmd.encode('ascii', 'replace')
|
||||
if self.isPrinting():
|
||||
self._commandQueue.put(cmd)
|
||||
elif self.isOperational():
|
||||
self._sendCommand(cmd)
|
||||
|
||||
def printGCode(self, gcodeList):
|
||||
if not self.isOperational() or self.isPrinting():
|
||||
return
|
||||
self._gcodeList = gcodeList
|
||||
self._gcodePos = 0
|
||||
self._printStartTime100 = None
|
||||
self._printSection = 'CUSTOM'
|
||||
self._changeState(self.STATE_PRINTING)
|
||||
self._printStartTime = time.time()
|
||||
for i in xrange(0, 6):
|
||||
self._sendNext()
|
||||
|
||||
def cancelPrint(self):
|
||||
if self.isOperational():
|
||||
self._changeState(self.STATE_OPERATIONAL)
|
||||
|
||||
def setPause(self, pause):
|
||||
if not pause and self.isPaused():
|
||||
self._changeState(self.STATE_PRINTING)
|
||||
for i in xrange(0, 6):
|
||||
self._sendNext()
|
||||
if pause and self.isPrinting():
|
||||
self._changeState(self.STATE_PAUSED)
|
||||
|
||||
def setFeedrateModifier(self, type, value):
|
||||
self._feedRateModifier[type] = value
|
||||
|
||||
def getFeedrateModifiers(self):
|
||||
result = {}
|
||||
result.update(self._feedRateModifier)
|
||||
return result
|
||||
|
||||
def getExceptionString():
|
||||
locationInfo = traceback.extract_tb(sys.exc_info()[2])[0]
|
||||
return "%s: '%s' @ %s:%s:%d" % (str(sys.exc_info()[0].__name__), str(sys.exc_info()[1]), os.path.basename(locationInfo[0]), locationInfo[2], locationInfo[1])
|
||||
@@ -0,0 +1,287 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import sys
|
||||
import math
|
||||
import re
|
||||
import os
|
||||
|
||||
from printer_webui.util import util3d
|
||||
from printer_webui.util import profile
|
||||
|
||||
class gcodePath(object):
|
||||
def __init__(self, newType, pathType, layerThickness, startPoint):
|
||||
self.type = newType
|
||||
self.pathType = pathType
|
||||
self.layerThickness = layerThickness
|
||||
self.list = [startPoint]
|
||||
|
||||
class gcode(object):
|
||||
def __init__(self):
|
||||
self.regMatch = {}
|
||||
self.layerList = []
|
||||
self.extrusionAmount = 0
|
||||
self.totalMoveTimeMinute = 0
|
||||
self.progressCallback = None
|
||||
|
||||
def load(self, filename):
|
||||
if os.path.isfile(filename):
|
||||
self._fileSize = os.stat(filename).st_size
|
||||
gcodeFile = open(filename, 'r')
|
||||
self._load(gcodeFile)
|
||||
gcodeFile.close()
|
||||
|
||||
def loadList(self, l):
|
||||
self._load(l)
|
||||
|
||||
def calculateWeight(self):
|
||||
#Calculates the weight of the filament in kg
|
||||
radius = float(profile.getProfileSetting('filament_diameter')) / 2
|
||||
volumeM3 = (self.extrusionAmount * (math.pi * radius * radius)) / (1000*1000*1000)
|
||||
return volumeM3 * profile.getPreferenceFloat('filament_density')
|
||||
|
||||
def calculateCost(self):
|
||||
cost_kg = profile.getPreferenceFloat('filament_cost_kg')
|
||||
cost_meter = profile.getPreferenceFloat('filament_cost_meter')
|
||||
if cost_kg > 0.0 and cost_meter > 0.0:
|
||||
return "%.2f / %.2f" % (self.calculateWeight() * cost_kg, self.extrusionAmount / 1000 * cost_meter)
|
||||
elif cost_kg > 0.0:
|
||||
return "%.2f" % (self.calculateWeight() * cost_kg)
|
||||
elif cost_meter > 0.0:
|
||||
return "%.2f" % (self.extrusionAmount / 1000 * cost_meter)
|
||||
return False
|
||||
|
||||
def _load(self, gcodeFile):
|
||||
filePos = 0
|
||||
pos = util3d.Vector3()
|
||||
posOffset = util3d.Vector3()
|
||||
currentE = 0.0
|
||||
totalExtrusion = 0.0
|
||||
maxExtrusion = 0.0
|
||||
currentExtruder = 0
|
||||
extrudeAmountMultiply = 1.0
|
||||
totalMoveTimeMinute = 0.0
|
||||
scale = 1.0
|
||||
posAbs = True
|
||||
feedRate = 3600
|
||||
layerThickness = 0.1
|
||||
pathType = 'CUSTOM';
|
||||
startCodeDone = False
|
||||
currentLayer = []
|
||||
currentPath = gcodePath('move', pathType, layerThickness, pos.copy())
|
||||
currentPath.list[0].e = totalExtrusion
|
||||
currentPath.list[0].extrudeAmountMultiply = extrudeAmountMultiply
|
||||
currentLayer.append(currentPath)
|
||||
for line in gcodeFile:
|
||||
if type(line) is tuple:
|
||||
line = line[0]
|
||||
if self.progressCallback != None:
|
||||
if isinstance(gcodeFile, (file)):
|
||||
self.progressCallback(float(filePos) / float(self._fileSize))
|
||||
elif isinstance(gcodeFile, (list)):
|
||||
self.progressCallback(float(filePos) / float(len(gcodeFile)))
|
||||
filePos += 1
|
||||
|
||||
#Parse Cura_SF comments
|
||||
if line.startswith(';TYPE:'):
|
||||
pathType = line[6:].strip()
|
||||
if pathType != "CUSTOM":
|
||||
startCodeDone = True
|
||||
|
||||
if ';' in line:
|
||||
#Slic3r GCode comment parser
|
||||
comment = line[line.find(';')+1:].strip()
|
||||
if comment == 'fill':
|
||||
pathType = 'FILL'
|
||||
elif comment == 'perimeter':
|
||||
pathType = 'WALL-INNER'
|
||||
elif comment == 'skirt':
|
||||
pathType = 'SKIRT'
|
||||
if comment.startswith('LAYER:'):
|
||||
self.layerList.append(currentLayer)
|
||||
currentLayer = []
|
||||
if pathType != "CUSTOM":
|
||||
startCodeDone = True
|
||||
line = line[0:line.find(';')]
|
||||
T = self.getCodeInt(line, 'T')
|
||||
if T is not None:
|
||||
if currentExtruder > 0:
|
||||
posOffset.x -= profile.getPreferenceFloat('extruder_offset_x%d' % (currentExtruder))
|
||||
posOffset.y -= profile.getPreferenceFloat('extruder_offset_y%d' % (currentExtruder))
|
||||
currentExtruder = T
|
||||
if currentExtruder > 0:
|
||||
posOffset.x += profile.getPreferenceFloat('extruder_offset_x%d' % (currentExtruder))
|
||||
posOffset.y += profile.getPreferenceFloat('extruder_offset_y%d' % (currentExtruder))
|
||||
|
||||
G = self.getCodeInt(line, 'G')
|
||||
if G is not None:
|
||||
if G == 0 or G == 1: #Move
|
||||
x = self.getCodeFloat(line, 'X')
|
||||
y = self.getCodeFloat(line, 'Y')
|
||||
z = self.getCodeFloat(line, 'Z')
|
||||
e = self.getCodeFloat(line, 'E')
|
||||
f = self.getCodeFloat(line, 'F')
|
||||
oldPos = pos.copy()
|
||||
if x is not None:
|
||||
if posAbs:
|
||||
pos.x = x * scale + posOffset.x
|
||||
else:
|
||||
pos.x += x * scale
|
||||
if y is not None:
|
||||
if posAbs:
|
||||
pos.y = y * scale + posOffset.y
|
||||
else:
|
||||
pos.y += y * scale
|
||||
if z is not None:
|
||||
if posAbs:
|
||||
pos.z = z * scale + posOffset.z
|
||||
else:
|
||||
pos.z += z * scale
|
||||
if f is not None:
|
||||
feedRate = f
|
||||
if x is not None or y is not None or z is not None:
|
||||
totalMoveTimeMinute += (oldPos - pos).vsize() / feedRate
|
||||
moveType = 'move'
|
||||
if e is not None:
|
||||
if posAbs:
|
||||
if e > currentE:
|
||||
moveType = 'extrude'
|
||||
if e < currentE:
|
||||
moveType = 'retract'
|
||||
else:
|
||||
if e > 0:
|
||||
moveType = 'extrude'
|
||||
if e < 0:
|
||||
moveType = 'retract'
|
||||
totalExtrusion += e - currentE
|
||||
currentE = e
|
||||
if totalExtrusion > maxExtrusion:
|
||||
maxExtrusion = totalExtrusion
|
||||
if moveType == 'move' and oldPos.z != pos.z:
|
||||
if oldPos.z > pos.z and abs(oldPos.z - pos.z) > 5.0 and pos.z < 1.0:
|
||||
oldPos.z = 0.0
|
||||
layerThickness = abs(oldPos.z - pos.z)
|
||||
if currentPath.type != moveType or currentPath.pathType != pathType:
|
||||
currentPath = gcodePath(moveType, pathType, layerThickness, currentPath.list[-1])
|
||||
currentLayer.append(currentPath)
|
||||
newPos = pos.copy()
|
||||
newPos.e = totalExtrusion
|
||||
newPos.extrudeAmountMultiply = extrudeAmountMultiply
|
||||
currentPath.list.append(newPos)
|
||||
elif G == 4: #Delay
|
||||
S = self.getCodeFloat(line, 'S')
|
||||
if S is not None:
|
||||
totalMoveTimeMinute += S / 60
|
||||
P = self.getCodeFloat(line, 'P')
|
||||
if P is not None:
|
||||
totalMoveTimeMinute += P / 60 / 1000
|
||||
elif G == 20: #Units are inches
|
||||
scale = 25.4
|
||||
elif G == 21: #Units are mm
|
||||
scale = 1.0
|
||||
elif G == 28: #Home
|
||||
x = self.getCodeFloat(line, 'X')
|
||||
y = self.getCodeFloat(line, 'Y')
|
||||
z = self.getCodeFloat(line, 'Z')
|
||||
if x is None and y is None and z is None:
|
||||
pos = util3d.Vector3()
|
||||
else:
|
||||
if x is not None:
|
||||
pos.x = 0.0
|
||||
if y is not None:
|
||||
pos.y = 0.0
|
||||
if z is not None:
|
||||
pos.z = 0.0
|
||||
elif G == 90: #Absolute position
|
||||
posAbs = True
|
||||
elif G == 91: #Relative position
|
||||
posAbs = False
|
||||
elif G == 92:
|
||||
x = self.getCodeFloat(line, 'X')
|
||||
y = self.getCodeFloat(line, 'Y')
|
||||
z = self.getCodeFloat(line, 'Z')
|
||||
e = self.getCodeFloat(line, 'E')
|
||||
if e is not None:
|
||||
currentE = e
|
||||
if x is not None:
|
||||
posOffset.x = pos.x - x
|
||||
if y is not None:
|
||||
posOffset.y = pos.y - y
|
||||
if z is not None:
|
||||
posOffset.z = pos.z - z
|
||||
else:
|
||||
print "Unknown G code:" + str(G)
|
||||
else:
|
||||
M = self.getCodeInt(line, 'M')
|
||||
if M is not None:
|
||||
if M == 1: #Message with possible wait (ignored)
|
||||
pass
|
||||
elif M == 80: #Enable power supply
|
||||
pass
|
||||
elif M == 81: #Suicide/disable power supply
|
||||
pass
|
||||
elif M == 84: #Disable step drivers
|
||||
pass
|
||||
elif M == 92: #Set steps per unit
|
||||
pass
|
||||
elif M == 101: #Enable extruder
|
||||
pass
|
||||
elif M == 103: #Disable extruder
|
||||
pass
|
||||
elif M == 104: #Set temperature, no wait
|
||||
pass
|
||||
elif M == 105: #Get temperature
|
||||
pass
|
||||
elif M == 106: #Enable fan
|
||||
pass
|
||||
elif M == 107: #Disable fan
|
||||
pass
|
||||
elif M == 108: #Extruder RPM (these should not be in the final GCode, but they are)
|
||||
pass
|
||||
elif M == 109: #Set temperature, wait
|
||||
pass
|
||||
elif M == 110: #Reset N counter
|
||||
pass
|
||||
elif M == 113: #Extruder PWM (these should not be in the final GCode, but they are)
|
||||
pass
|
||||
elif M == 140: #Set bed temperature
|
||||
pass
|
||||
elif M == 190: #Set bed temperature & wait
|
||||
pass
|
||||
elif M == 221: #Extrude amount multiplier
|
||||
s = self.getCodeFloat(line, 'S')
|
||||
if s != None:
|
||||
extrudeAmountMultiply = s / 100.0
|
||||
else:
|
||||
print "Unknown M code:" + str(M)
|
||||
self.layerList.append(currentLayer)
|
||||
self.extrusionAmount = maxExtrusion
|
||||
self.totalMoveTimeMinute = totalMoveTimeMinute
|
||||
#print "Extruded a total of: %d mm of filament" % (self.extrusionAmount)
|
||||
#print "Estimated print duration: %.2f minutes" % (self.totalMoveTimeMinute)
|
||||
|
||||
def getCodeInt(self, line, code):
|
||||
if code not in self.regMatch:
|
||||
self.regMatch[code] = re.compile(code + '([^\s]+)')
|
||||
m = self.regMatch[code].search(line)
|
||||
if m == None:
|
||||
return None
|
||||
try:
|
||||
return int(m.group(1))
|
||||
except:
|
||||
return None
|
||||
|
||||
def getCodeFloat(self, line, code):
|
||||
if code not in self.regMatch:
|
||||
self.regMatch[code] = re.compile(code + '([^\s]+)')
|
||||
m = self.regMatch[code].search(line)
|
||||
if m == None:
|
||||
return None
|
||||
try:
|
||||
return float(m.group(1))
|
||||
except:
|
||||
return None
|
||||
|
||||
if __name__ == '__main__':
|
||||
for filename in sys.argv[1:]:
|
||||
gcode().load(filename)
|
||||
|
||||
@@ -0,0 +1,651 @@
|
||||
from __future__ import absolute_import
|
||||
from __future__ import division
|
||||
|
||||
import os, traceback, math, re, zlib, base64, time, sys, platform, glob, string, stat
|
||||
import cPickle as pickle
|
||||
if sys.version_info[0] < 3:
|
||||
import ConfigParser
|
||||
else:
|
||||
import configparser as ConfigParser
|
||||
|
||||
from printer_webui.util import resources
|
||||
from printer_webui.util import version
|
||||
|
||||
#########################################################
|
||||
## Default settings when none are found.
|
||||
#########################################################
|
||||
|
||||
#Single place to store the defaults, so we have a consistent set of default settings.
|
||||
profileDefaultSettings = {
|
||||
'nozzle_size': '0.4',
|
||||
'layer_height': '0.2',
|
||||
'wall_thickness': '0.8',
|
||||
'solid_layer_thickness': '0.6',
|
||||
'fill_density': '20',
|
||||
'skirt_line_count': '1',
|
||||
'skirt_gap': '3.0',
|
||||
'print_speed': '50',
|
||||
'print_temperature': '220',
|
||||
'print_bed_temperature': '70',
|
||||
'support': 'None',
|
||||
'filament_diameter': '2.89',
|
||||
'filament_density': '1.00',
|
||||
'retraction_min_travel': '5.0',
|
||||
'retraction_enable': 'False',
|
||||
'retraction_speed': '40.0',
|
||||
'retraction_amount': '4.5',
|
||||
'retraction_extra': '0.0',
|
||||
'retract_on_jumps_only': 'True',
|
||||
'travel_speed': '150',
|
||||
'max_z_speed': '3.0',
|
||||
'bottom_layer_speed': '20',
|
||||
'cool_min_layer_time': '5',
|
||||
'fan_enabled': 'True',
|
||||
'fan_layer': '1',
|
||||
'fan_speed': '100',
|
||||
'fan_speed_max': '100',
|
||||
'model_scale': '1.0',
|
||||
'flip_x': 'False',
|
||||
'flip_y': 'False',
|
||||
'flip_z': 'False',
|
||||
'swap_xz': 'False',
|
||||
'swap_yz': 'False',
|
||||
'model_rotate_base': '0',
|
||||
'model_multiply_x': '1',
|
||||
'model_multiply_y': '1',
|
||||
'extra_base_wall_thickness': '0.0',
|
||||
'sequence': 'Loops > Perimeter > Infill',
|
||||
'force_first_layer_sequence': 'True',
|
||||
'infill_type': 'Line',
|
||||
'solid_top': 'True',
|
||||
'fill_overlap': '15',
|
||||
'support_rate': '50',
|
||||
'support_distance': '0.5',
|
||||
'support_dual_extrusion': 'False',
|
||||
'joris': 'False',
|
||||
'enable_skin': 'False',
|
||||
'enable_raft': 'False',
|
||||
'cool_min_feedrate': '10',
|
||||
'bridge_speed': '100',
|
||||
'raft_margin': '5',
|
||||
'raft_base_material_amount': '100',
|
||||
'raft_interface_material_amount': '100',
|
||||
'bottom_thickness': '0.3',
|
||||
'hop_on_move': 'False',
|
||||
'plugin_config': '',
|
||||
'object_center_x': '-1',
|
||||
'object_center_y': '-1',
|
||||
|
||||
'add_start_end_gcode': 'True',
|
||||
'gcode_extension': 'gcode',
|
||||
'alternative_center': '',
|
||||
'clear_z': '0.0',
|
||||
'extruder': '0',
|
||||
}
|
||||
alterationDefault = {
|
||||
#######################################################################################
|
||||
'start.gcode': """;Sliced {filename} at: {day} {date} {time}
|
||||
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
|
||||
;Print time: {print_time}
|
||||
;Filament used: {filament_amount}m {filament_weight}g
|
||||
;Filament cost: {filament_cost}
|
||||
G21 ;metric values
|
||||
G90 ;absolute positioning
|
||||
M107 ;start with the fan off
|
||||
|
||||
G28 X0 Y0 ;move X/Y to min endstops
|
||||
G28 Z0 ;move Z to min endstops
|
||||
G92 X0 Y0 Z0 E0 ;reset software position to front/left/z=0.0
|
||||
|
||||
G1 Z15.0 F{max_z_speed} ;move the platform down 15mm
|
||||
|
||||
G92 E0 ;zero the extruded length
|
||||
G1 F200 E3 ;extrude 3mm of feed stock
|
||||
G92 E0 ;zero the extruded length again
|
||||
G1 F{travel_speed}
|
||||
""",
|
||||
#######################################################################################
|
||||
'end.gcode': """;End GCode
|
||||
M104 S0 ;extruder heater off
|
||||
M140 S0 ;heated bed heater off (if you have it)
|
||||
|
||||
G91 ;relative positioning
|
||||
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
|
||||
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
|
||||
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
|
||||
|
||||
M84 ;steppers off
|
||||
G90 ;absolute positioning
|
||||
""",
|
||||
#######################################################################################
|
||||
'support_start.gcode': '',
|
||||
'support_end.gcode': '',
|
||||
'cool_start.gcode': '',
|
||||
'cool_end.gcode': '',
|
||||
'replace.csv': '',
|
||||
#######################################################################################
|
||||
'nextobject.gcode': """;Move to next object on the platform. clear_z is the minimal z height we need to make sure we do not hit any objects.
|
||||
G92 E0
|
||||
|
||||
G91 ;relative positioning
|
||||
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
|
||||
G1 Z+0.5 E-5 F{travel_speed} ;move Z up a bit and retract filament even more
|
||||
G90 ;absolute positioning
|
||||
|
||||
G1 Z{clear_z} F{max_z_speed}
|
||||
G92 E0
|
||||
G1 X{object_center_x} Y{object_center_x} F{travel_speed}
|
||||
G1 F200 E6
|
||||
G92 E0
|
||||
""",
|
||||
#######################################################################################
|
||||
'switchExtruder.gcode': """;Switch between the current extruder and the next extruder, when printing with multiple extruders.
|
||||
G92 E0
|
||||
G1 E-15 F5000
|
||||
G92 E0
|
||||
T{extruder}
|
||||
G1 E15 F5000
|
||||
G92 E0
|
||||
""",
|
||||
}
|
||||
preferencesDefaultSettings = {
|
||||
'startMode': 'Simple',
|
||||
'lastFile': os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'resources', 'example', 'UltimakerRobot_support.stl')),
|
||||
'machine_width': '205',
|
||||
'machine_depth': '205',
|
||||
'machine_height': '200',
|
||||
'machine_type': 'unknown',
|
||||
'ultimaker_extruder_upgrade': 'False',
|
||||
'has_heated_bed': 'False',
|
||||
'extruder_amount': '1',
|
||||
'extruder_offset_x1': '-22.0',
|
||||
'extruder_offset_y1': '0.0',
|
||||
'extruder_offset_x2': '0.0',
|
||||
'extruder_offset_y2': '0.0',
|
||||
'extruder_offset_x3': '0.0',
|
||||
'extruder_offset_y3': '0.0',
|
||||
'filament_density': '1300',
|
||||
'steps_per_e': '0',
|
||||
'serial_port': 'AUTO',
|
||||
'serial_port_auto': '',
|
||||
'serial_baud': 'AUTO',
|
||||
'serial_baud_auto': '',
|
||||
'slicer': 'Cura (Skeinforge based)',
|
||||
'save_profile': 'False',
|
||||
'filament_cost_kg': '0',
|
||||
'filament_cost_meter': '0',
|
||||
'sdpath': '',
|
||||
'sdshortnames': 'True',
|
||||
|
||||
'extruder_head_size_min_x': '70.0',
|
||||
'extruder_head_size_min_y': '18.0',
|
||||
'extruder_head_size_max_x': '18.0',
|
||||
'extruder_head_size_max_y': '35.0',
|
||||
'extruder_head_size_height': '80.0',
|
||||
|
||||
'model_colour': '#72CB30',
|
||||
'model_colour2': '#CB3030',
|
||||
'model_colour3': '#DDD93C',
|
||||
'model_colour4': '#4550D3',
|
||||
}
|
||||
|
||||
#########################################################
|
||||
## Profile and preferences functions
|
||||
#########################################################
|
||||
|
||||
## Profile functions
|
||||
def getDefaultProfilePath():
|
||||
if platform.system() == "Windows":
|
||||
basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
|
||||
#If we have a frozen python install, we need to step out of the library.zip
|
||||
if hasattr(sys, 'frozen'):
|
||||
basePath = os.path.normpath(os.path.join(basePath, ".."))
|
||||
else:
|
||||
basePath = os.path.expanduser('~/.cura/%s' % version.getVersion(False))
|
||||
if not os.path.isdir(basePath):
|
||||
os.makedirs(basePath)
|
||||
return os.path.join(basePath, 'current_profile.ini')
|
||||
|
||||
def loadGlobalProfile(filename):
|
||||
#Read a configuration file as global config
|
||||
global globalProfileParser
|
||||
globalProfileParser = ConfigParser.ConfigParser()
|
||||
globalProfileParser.read(filename)
|
||||
|
||||
def resetGlobalProfile():
|
||||
#Read a configuration file as global config
|
||||
global globalProfileParser
|
||||
globalProfileParser = ConfigParser.ConfigParser()
|
||||
|
||||
if getPreference('machine_type') == 'ultimaker':
|
||||
putProfileSetting('nozzle_size', '0.4')
|
||||
if getPreference('ultimaker_extruder_upgrade') == 'True':
|
||||
putProfileSetting('retraction_enable', 'True')
|
||||
else:
|
||||
putProfileSetting('nozzle_size', '0.5')
|
||||
|
||||
def saveGlobalProfile(filename):
|
||||
#Save the current profile to an ini file
|
||||
globalProfileParser.write(open(filename, 'w'))
|
||||
|
||||
def loadGlobalProfileFromString(options):
|
||||
global globalProfileParser
|
||||
globalProfileParser = ConfigParser.ConfigParser()
|
||||
globalProfileParser.add_section('profile')
|
||||
globalProfileParser.add_section('alterations')
|
||||
options = base64.b64decode(options)
|
||||
options = zlib.decompress(options)
|
||||
(profileOpts, alt) = options.split('\f', 1)
|
||||
for option in profileOpts.split('\b'):
|
||||
if len(option) > 0:
|
||||
(key, value) = option.split('=', 1)
|
||||
globalProfileParser.set('profile', key, value)
|
||||
for option in alt.split('\b'):
|
||||
if len(option) > 0:
|
||||
(key, value) = option.split('=', 1)
|
||||
globalProfileParser.set('alterations', key, value)
|
||||
|
||||
def getGlobalProfileString():
|
||||
global globalProfileParser
|
||||
if not globals().has_key('globalProfileParser'):
|
||||
loadGlobalProfile(getDefaultProfilePath())
|
||||
|
||||
p = []
|
||||
alt = []
|
||||
tempDone = []
|
||||
if globalProfileParser.has_section('profile'):
|
||||
for key in globalProfileParser.options('profile'):
|
||||
if key in tempOverride:
|
||||
p.append(key + "=" + tempOverride[key])
|
||||
tempDone.append(key)
|
||||
else:
|
||||
p.append(key + "=" + globalProfileParser.get('profile', key))
|
||||
if globalProfileParser.has_section('alterations'):
|
||||
for key in globalProfileParser.options('alterations'):
|
||||
if key in tempOverride:
|
||||
p.append(key + "=" + tempOverride[key])
|
||||
tempDone.append(key)
|
||||
else:
|
||||
alt.append(key + "=" + globalProfileParser.get('alterations', key))
|
||||
for key in tempOverride:
|
||||
if key not in tempDone:
|
||||
p.append(key + "=" + tempOverride[key])
|
||||
ret = '\b'.join(p) + '\f' + '\b'.join(alt)
|
||||
ret = base64.b64encode(zlib.compress(ret, 9))
|
||||
return ret
|
||||
|
||||
def getProfileSetting(name):
|
||||
if name in tempOverride:
|
||||
return unicode(tempOverride[name], "utf-8")
|
||||
#Check if we have a configuration file loaded, else load the default.
|
||||
if not globals().has_key('globalProfileParser'):
|
||||
loadGlobalProfile(getDefaultProfilePath())
|
||||
if not globalProfileParser.has_option('profile', name):
|
||||
if name in profileDefaultSettings:
|
||||
default = profileDefaultSettings[name]
|
||||
else:
|
||||
print("Missing default setting for: '" + name + "'")
|
||||
profileDefaultSettings[name] = ''
|
||||
default = ''
|
||||
if not globalProfileParser.has_section('profile'):
|
||||
globalProfileParser.add_section('profile')
|
||||
globalProfileParser.set('profile', name, str(default))
|
||||
#print(name + " not found in profile, so using default: " + str(default))
|
||||
return default
|
||||
return globalProfileParser.get('profile', name)
|
||||
|
||||
def getProfileSettingFloat(name):
|
||||
try:
|
||||
setting = getProfileSetting(name).replace(',', '.')
|
||||
return float(eval(setting, {}, {}))
|
||||
except (ValueError, SyntaxError, TypeError):
|
||||
return 0.0
|
||||
|
||||
def putProfileSetting(name, value):
|
||||
#Check if we have a configuration file loaded, else load the default.
|
||||
if not globals().has_key('globalProfileParser'):
|
||||
loadGlobalProfile(getDefaultProfilePath())
|
||||
if not globalProfileParser.has_section('profile'):
|
||||
globalProfileParser.add_section('profile')
|
||||
globalProfileParser.set('profile', name, str(value))
|
||||
|
||||
def isProfileSetting(name):
|
||||
if name in profileDefaultSettings:
|
||||
return True
|
||||
return False
|
||||
|
||||
## Preferences functions
|
||||
global globalPreferenceParser
|
||||
globalPreferenceParser = None
|
||||
|
||||
def getPreferencePath():
|
||||
if platform.system() == "Windows":
|
||||
basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
|
||||
#If we have a frozen python install, we need to step out of the library.zip
|
||||
if hasattr(sys, 'frozen'):
|
||||
basePath = os.path.normpath(os.path.join(basePath, ".."))
|
||||
else:
|
||||
basePath = os.path.expanduser('~/.cura/%s' % version.getVersion(False))
|
||||
if not os.path.isdir(basePath):
|
||||
os.makedirs(basePath)
|
||||
return os.path.join(basePath, 'preferences.ini')
|
||||
|
||||
def getPreferenceFloat(name):
|
||||
try:
|
||||
setting = getPreference(name).replace(',', '.')
|
||||
return float(eval(setting, {}, {}))
|
||||
except (ValueError, SyntaxError, TypeError):
|
||||
return 0.0
|
||||
|
||||
def getPreferenceColour(name):
|
||||
colorString = getPreference(name)
|
||||
return [float(int(colorString[1:3], 16)) / 255, float(int(colorString[3:5], 16)) / 255, float(int(colorString[5:7], 16)) / 255, 1.0]
|
||||
|
||||
def getPreference(name):
|
||||
if name in tempOverride:
|
||||
return unicode(tempOverride[name])
|
||||
global globalPreferenceParser
|
||||
if globalPreferenceParser == None:
|
||||
globalPreferenceParser = ConfigParser.ConfigParser()
|
||||
globalPreferenceParser.read(getPreferencePath())
|
||||
if not globalPreferenceParser.has_option('preference', name):
|
||||
if name in preferencesDefaultSettings:
|
||||
default = preferencesDefaultSettings[name]
|
||||
else:
|
||||
print("Missing default setting for: '" + name + "'")
|
||||
preferencesDefaultSettings[name] = ''
|
||||
default = ''
|
||||
if not globalPreferenceParser.has_section('preference'):
|
||||
globalPreferenceParser.add_section('preference')
|
||||
globalPreferenceParser.set('preference', name, str(default))
|
||||
#print(name + " not found in preferences, so using default: " + str(default))
|
||||
return default
|
||||
return unicode(globalPreferenceParser.get('preference', name), "utf-8")
|
||||
|
||||
def putPreference(name, value):
|
||||
#Check if we have a configuration file loaded, else load the default.
|
||||
global globalPreferenceParser
|
||||
if globalPreferenceParser == None:
|
||||
globalPreferenceParser = ConfigParser.ConfigParser()
|
||||
globalPreferenceParser.read(getPreferencePath())
|
||||
if not globalPreferenceParser.has_section('preference'):
|
||||
globalPreferenceParser.add_section('preference')
|
||||
globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))
|
||||
globalPreferenceParser.write(open(getPreferencePath(), 'w'))
|
||||
|
||||
def isPreference(name):
|
||||
if name in preferencesDefaultSettings:
|
||||
return True
|
||||
return False
|
||||
|
||||
## Temp overrides for multi-extruder slicing and the project planner.
|
||||
tempOverride = {}
|
||||
def setTempOverride(name, value):
|
||||
tempOverride[name] = unicode(value).encode("utf-8")
|
||||
def clearTempOverride(name):
|
||||
del tempOverride[name]
|
||||
def resetTempOverride():
|
||||
tempOverride.clear()
|
||||
|
||||
#########################################################
|
||||
## Utility functions to calculate common profile values
|
||||
#########################################################
|
||||
def calculateEdgeWidth():
|
||||
wallThickness = getProfileSettingFloat('wall_thickness')
|
||||
nozzleSize = getProfileSettingFloat('nozzle_size')
|
||||
|
||||
if wallThickness < nozzleSize:
|
||||
return wallThickness
|
||||
|
||||
lineCount = int(wallThickness / nozzleSize + 0.0001)
|
||||
lineWidth = wallThickness / lineCount
|
||||
lineWidthAlt = wallThickness / (lineCount + 1)
|
||||
if lineWidth > nozzleSize * 1.5:
|
||||
return lineWidthAlt
|
||||
return lineWidth
|
||||
|
||||
def calculateLineCount():
|
||||
wallThickness = getProfileSettingFloat('wall_thickness')
|
||||
nozzleSize = getProfileSettingFloat('nozzle_size')
|
||||
|
||||
if wallThickness < nozzleSize:
|
||||
return 1
|
||||
|
||||
lineCount = int(wallThickness / nozzleSize + 0.0001)
|
||||
lineWidth = wallThickness / lineCount
|
||||
lineWidthAlt = wallThickness / (lineCount + 1)
|
||||
if lineWidth > nozzleSize * 1.5:
|
||||
return lineCount + 1
|
||||
return lineCount
|
||||
|
||||
def calculateSolidLayerCount():
|
||||
layerHeight = getProfileSettingFloat('layer_height')
|
||||
solidThickness = getProfileSettingFloat('solid_layer_thickness')
|
||||
return int(math.ceil(solidThickness / layerHeight - 0.0001))
|
||||
|
||||
#########################################################
|
||||
## Alteration file functions
|
||||
#########################################################
|
||||
def replaceTagMatch(m):
|
||||
pre = m.group(1)
|
||||
tag = m.group(2)
|
||||
if tag == 'time':
|
||||
return pre + time.strftime('%H:%M:%S').encode('utf-8', 'replace')
|
||||
if tag == 'date':
|
||||
return pre + time.strftime('%d %b %Y').encode('utf-8', 'replace')
|
||||
if tag == 'day':
|
||||
return pre + time.strftime('%a').encode('utf-8', 'replace')
|
||||
if tag == 'print_time':
|
||||
return pre + '#P_TIME#'
|
||||
if tag == 'filament_amount':
|
||||
return pre + '#F_AMNT#'
|
||||
if tag == 'filament_weight':
|
||||
return pre + '#F_WGHT#'
|
||||
if tag == 'filament_cost':
|
||||
return pre + '#F_COST#'
|
||||
if pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:
|
||||
f = getProfileSettingFloat(tag) * 60
|
||||
elif isProfileSetting(tag):
|
||||
f = getProfileSettingFloat(tag)
|
||||
elif isPreference(tag):
|
||||
f = getProfileSettingFloat(tag)
|
||||
else:
|
||||
return '%s?%s?' % (pre, tag)
|
||||
if (f % 1) == 0:
|
||||
return pre + str(int(f))
|
||||
return pre + str(f)
|
||||
|
||||
def replaceGCodeTags(filename, gcodeInt):
|
||||
f = open(filename, 'r+')
|
||||
data = f.read(2048)
|
||||
data = data.replace('#P_TIME#', ('%5d:%02d' % (int(gcodeInt.totalMoveTimeMinute / 60), int(gcodeInt.totalMoveTimeMinute % 60)))[-8:])
|
||||
data = data.replace('#F_AMNT#', ('%8.2f' % (gcodeInt.extrusionAmount / 1000))[-8:])
|
||||
data = data.replace('#F_WGHT#', ('%8.2f' % (gcodeInt.calculateWeight() * 1000))[-8:])
|
||||
cost = gcodeInt.calculateCost()
|
||||
if cost == False:
|
||||
cost = 'Unknown'
|
||||
data = data.replace('#F_COST#', ('%8s' % (cost.split(' ')[0]))[-8:])
|
||||
f.seek(0)
|
||||
f.write(data)
|
||||
f.close()
|
||||
|
||||
### Get aleration raw contents. (Used internally in Cura)
|
||||
def getAlterationFile(filename):
|
||||
#Check if we have a configuration file loaded, else load the default.
|
||||
if not globals().has_key('globalProfileParser'):
|
||||
loadGlobalProfile(getDefaultProfilePath())
|
||||
|
||||
if not globalProfileParser.has_option('alterations', filename):
|
||||
if filename in alterationDefault:
|
||||
default = alterationDefault[filename]
|
||||
else:
|
||||
print("Missing default alteration for: '" + filename + "'")
|
||||
alterationDefault[filename] = ''
|
||||
default = ''
|
||||
if not globalProfileParser.has_section('alterations'):
|
||||
globalProfileParser.add_section('alterations')
|
||||
#print("Using default for: %s" % (filename))
|
||||
globalProfileParser.set('alterations', filename, default)
|
||||
return unicode(globalProfileParser.get('alterations', filename), "utf-8")
|
||||
|
||||
def setAlterationFile(filename, value):
|
||||
#Check if we have a configuration file loaded, else load the default.
|
||||
if not globals().has_key('globalProfileParser'):
|
||||
loadGlobalProfile(getDefaultProfilePath())
|
||||
if not globalProfileParser.has_section('alterations'):
|
||||
globalProfileParser.add_section('alterations')
|
||||
globalProfileParser.set('alterations', filename, value.encode("utf-8"))
|
||||
saveGlobalProfile(getDefaultProfilePath())
|
||||
|
||||
### Get the alteration file for output. (Used by Skeinforge)
|
||||
def getAlterationFileContents(filename):
|
||||
prefix = ''
|
||||
postfix = ''
|
||||
alterationContents = getAlterationFile(filename)
|
||||
if filename == 'start.gcode':
|
||||
#For the start code, hack the temperature and the steps per E value into it. So the temperature is reached before the start code extrusion.
|
||||
#We also set our steps per E here, if configured.
|
||||
eSteps = getPreferenceFloat('steps_per_e')
|
||||
if eSteps > 0:
|
||||
prefix += 'M92 E%f\n' % (eSteps)
|
||||
temp = getProfileSettingFloat('print_temperature')
|
||||
bedTemp = 0
|
||||
if getPreference('has_heated_bed') == 'True':
|
||||
bedTemp = getProfileSettingFloat('print_bed_temperature')
|
||||
|
||||
if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:
|
||||
prefix += 'M140 S%f\n' % (bedTemp)
|
||||
if temp > 0 and not '{print_temperature}' in alterationContents:
|
||||
prefix += 'M109 S%f\n' % (temp)
|
||||
if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:
|
||||
prefix += 'M190 S%f\n' % (bedTemp)
|
||||
elif filename == 'end.gcode':
|
||||
#Append the profile string to the end of the GCode, so we can load it from the GCode file later.
|
||||
postfix = ';CURA_PROFILE_STRING:%s\n' % (getGlobalProfileString())
|
||||
elif filename == 'replace.csv':
|
||||
#Always remove the extruder on/off M codes. These are no longer needed in 5D printing.
|
||||
prefix = 'M101\nM103\n'
|
||||
elif filename == 'support_start.gcode' or filename == 'support_end.gcode':
|
||||
#Add support start/end code
|
||||
if getProfileSetting('support_dual_extrusion') == 'True' and int(getPreference('extruder_amount')) > 1:
|
||||
if filename == 'support_start.gcode':
|
||||
setTempOverride('extruder', '1')
|
||||
else:
|
||||
setTempOverride('extruder', '0')
|
||||
alterationContents = getAlterationFileContents('switchExtruder.gcode')
|
||||
clearTempOverride('extruder')
|
||||
else:
|
||||
alterationContents = ''
|
||||
return unicode(prefix + re.sub("(.)\{([^\}]*)\}", replaceTagMatch, alterationContents).rstrip() + '\n' + postfix).strip().encode('utf-8')
|
||||
|
||||
###### PLUGIN #####
|
||||
|
||||
def getPluginConfig():
|
||||
try:
|
||||
return pickle.loads(getProfileSetting('plugin_config'))
|
||||
except:
|
||||
return []
|
||||
|
||||
def setPluginConfig(config):
|
||||
putProfileSetting('plugin_config', pickle.dumps(config))
|
||||
|
||||
def getPluginBasePaths():
|
||||
ret = []
|
||||
if platform.system() != "Windows":
|
||||
ret.append(os.path.expanduser('~/.cura/plugins/'))
|
||||
if platform.system() == "Darwin" and hasattr(sys, 'frozen'):
|
||||
ret.append(os.path.normpath(os.path.join(resources.resourceBasePath, "Cura/plugins")))
|
||||
else:
|
||||
ret.append(os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'plugins')))
|
||||
return ret
|
||||
|
||||
def getPluginList():
|
||||
ret = []
|
||||
for basePath in getPluginBasePaths():
|
||||
for filename in glob.glob(os.path.join(basePath, '*.py')):
|
||||
filename = os.path.basename(filename)
|
||||
if filename.startswith('_'):
|
||||
continue
|
||||
with open(os.path.join(basePath, filename), "r") as f:
|
||||
item = {'filename': filename, 'name': None, 'info': None, 'type': None, 'params': []}
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line.startswith('#'):
|
||||
break
|
||||
line = line[1:].split(':', 1)
|
||||
if len(line) != 2:
|
||||
continue
|
||||
if line[0].upper() == 'NAME':
|
||||
item['name'] = line[1].strip()
|
||||
elif line[0].upper() == 'INFO':
|
||||
item['info'] = line[1].strip()
|
||||
elif line[0].upper() == 'TYPE':
|
||||
item['type'] = line[1].strip()
|
||||
elif line[0].upper() == 'DEPEND':
|
||||
pass
|
||||
elif line[0].upper() == 'PARAM':
|
||||
m = re.match('([a-zA-Z]*)\(([a-zA-Z_]*)(?::([^\)]*))?\) +(.*)', line[1].strip())
|
||||
if m is not None:
|
||||
item['params'].append({'name': m.group(1), 'type': m.group(2), 'default': m.group(3), 'description': m.group(4)})
|
||||
else:
|
||||
print "Unknown item in effect meta data: %s %s" % (line[0], line[1])
|
||||
if item['name'] != None and item['type'] == 'postprocess':
|
||||
ret.append(item)
|
||||
return ret
|
||||
|
||||
def runPostProcessingPlugins(gcodefilename):
|
||||
pluginConfigList = getPluginConfig()
|
||||
pluginList = getPluginList()
|
||||
|
||||
for pluginConfig in pluginConfigList:
|
||||
plugin = None
|
||||
for pluginTest in pluginList:
|
||||
if pluginTest['filename'] == pluginConfig['filename']:
|
||||
plugin = pluginTest
|
||||
if plugin is None:
|
||||
continue
|
||||
|
||||
pythonFile = None
|
||||
for basePath in getPluginBasePaths():
|
||||
testFilename = os.path.join(basePath, pluginConfig['filename'])
|
||||
if os.path.isfile(testFilename):
|
||||
pythonFile = testFilename
|
||||
if pythonFile is None:
|
||||
continue
|
||||
|
||||
locals = {'filename': gcodefilename}
|
||||
for param in plugin['params']:
|
||||
value = param['default']
|
||||
if param['name'] in pluginConfig['params']:
|
||||
value = pluginConfig['params'][param['name']]
|
||||
|
||||
if param['type'] == 'float':
|
||||
try:
|
||||
value = float(value)
|
||||
except:
|
||||
value = float(param['default'])
|
||||
|
||||
locals[param['name']] = value
|
||||
try:
|
||||
execfile(pythonFile, locals)
|
||||
except:
|
||||
locationInfo = traceback.extract_tb(sys.exc_info()[2])[-1]
|
||||
return "%s: '%s' @ %s:%s:%d" % (str(sys.exc_info()[0].__name__), str(sys.exc_info()[1]), os.path.basename(locationInfo[0]), locationInfo[2], locationInfo[1])
|
||||
return None
|
||||
|
||||
def getSDcardDrives():
|
||||
drives = ['']
|
||||
if platform.system() == "Windows":
|
||||
from ctypes import windll
|
||||
bitmask = windll.kernel32.GetLogicalDrives()
|
||||
for letter in string.uppercase:
|
||||
if bitmask & 1:
|
||||
drives.append(letter + ':/')
|
||||
bitmask >>= 1
|
||||
if platform.system() == "Darwin":
|
||||
drives = []
|
||||
for volume in glob.glob('/Volumes/*'):
|
||||
if stat.S_ISLNK(os.lstat(volume).st_mode):
|
||||
continue
|
||||
drives.append(volume)
|
||||
return drives
|
||||
@@ -0,0 +1,34 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
import os
|
||||
import sys
|
||||
|
||||
__all__ = ['getPathForResource', 'getPathForImage', 'getPathForMesh']
|
||||
|
||||
|
||||
if sys.platform.startswith('darwin'):
|
||||
if hasattr(sys, 'frozen'):
|
||||
from Foundation import *
|
||||
resourceBasePath = NSBundle.mainBundle().resourcePath()
|
||||
else:
|
||||
resourceBasePath = os.path.join(os.path.dirname(__file__), "../resources")
|
||||
else:
|
||||
if hasattr(sys, 'frozen'):
|
||||
resourceBasePath = os.path.join(os.path.dirname(__file__), "../../resources")
|
||||
else:
|
||||
resourceBasePath = os.path.join(os.path.dirname(__file__), "../resources")
|
||||
|
||||
def getPathForResource(dir, subdir, resource_name):
|
||||
assert os.path.isdir(dir), "{p} is not a directory".format(p=dir)
|
||||
path = os.path.normpath(os.path.join(dir, subdir, resource_name))
|
||||
assert os.path.isfile(path), "{p} is not a file.".format(p=path)
|
||||
return path
|
||||
|
||||
def getPathForImage(name):
|
||||
return getPathForResource(resourceBasePath, 'images', name)
|
||||
|
||||
def getPathForMesh(name):
|
||||
return getPathForResource(resourceBasePath, 'meshes', name)
|
||||
|
||||
def getPathForFirmware(name):
|
||||
return getPathForResource(resourceBasePath, 'firmware', name)
|
||||
@@ -0,0 +1,317 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import math
|
||||
import numpy
|
||||
|
||||
class Vector3(object):
|
||||
def __init__(self, x=0.0, y=0.0, z=0.0):
|
||||
self.x = x
|
||||
self.y = y
|
||||
self.z = z
|
||||
|
||||
def __copy__(self):
|
||||
return Vector3(self.x, self.y, self.z)
|
||||
|
||||
def copy(self):
|
||||
return Vector3(self.x, self.y, self.z)
|
||||
|
||||
def __repr__(self):
|
||||
return 'V[%s, %s, %s]' % ( self.x, self.y, self.z )
|
||||
|
||||
def __add__(self, v):
|
||||
return Vector3( self.x + v.x, self.y + v.y, self.z + v.z )
|
||||
|
||||
def __sub__(self, v):
|
||||
return Vector3( self.x - v.x, self.y - v.y, self.z - v.z )
|
||||
|
||||
def __mul__(self, v):
|
||||
return Vector3( self.x * v, self.y * v, self.z * v )
|
||||
|
||||
def __div__(self, v):
|
||||
return Vector3( self.x / v, self.y / v, self.z / v )
|
||||
__truediv__ = __div__
|
||||
|
||||
def __neg__(self):
|
||||
return Vector3( - self.x, - self.y, - self.z )
|
||||
|
||||
def __iadd__(self, v):
|
||||
self.x += v.x
|
||||
self.y += v.y
|
||||
self.z += v.z
|
||||
return self
|
||||
|
||||
def __isub__(self, v):
|
||||
self.x += v.x
|
||||
self.y += v.y
|
||||
self.z += v.z
|
||||
return self
|
||||
|
||||
def __imul__(self, v):
|
||||
self.x *= v
|
||||
self.y *= v
|
||||
self.z *= v
|
||||
return self
|
||||
|
||||
def __idiv__(self, v):
|
||||
self.x /= v
|
||||
self.y /= v
|
||||
self.z /= v
|
||||
return self
|
||||
|
||||
def almostEqual(self, v):
|
||||
return (abs(self.x - v.x) + abs(self.y - v.y) + abs(self.z - v.z)) < 0.00001
|
||||
|
||||
def cross(self, v):
|
||||
return Vector3(self.y * v.z - self.z * v.y, -self.x * v.z + self.z * v.x, self.x * v.y - self.y * v.x)
|
||||
|
||||
def vsize(self):
|
||||
return math.sqrt( self.x * self.x + self.y * self.y + self.z * self.z )
|
||||
|
||||
def normalize(self):
|
||||
f = self.vsize()
|
||||
if f != 0.0:
|
||||
self.x /= f
|
||||
self.y /= f
|
||||
self.z /= f
|
||||
|
||||
def min(self, v):
|
||||
return Vector3(min(self.x, v.x), min(self.y, v.y), min(self.z, v.z))
|
||||
|
||||
def max(self, v):
|
||||
return Vector3(max(self.x, v.x), max(self.y, v.y), max(self.z, v.z))
|
||||
|
||||
class AABB(object):
|
||||
def __init__(self, vMin, vMax):
|
||||
self.vMin = vMin
|
||||
self.vMax = vMax
|
||||
self.perimeter = numpy.sum(self.vMax - self.vMin)
|
||||
|
||||
def combine(self, aabb):
|
||||
return AABB(numpy.minimum(self.vMin, aabb.vMin), numpy.maximum(self.vMax, aabb.vMax))
|
||||
|
||||
def overlap(self, aabb):
|
||||
if aabb.vMin[0] - self.vMax[0] > 0.0 or aabb.vMin[1] - self.vMax[1] > 0.0 or aabb.vMin[2] - self.vMax[2] > 0.0:
|
||||
return False
|
||||
if self.vMin[0] - aabb.vMax[0] > 0.0 or self.vMin[1] - aabb.vMax[1] > 0.0 or self.vMin[2] - aabb.vMax[2] > 0.0:
|
||||
return False
|
||||
return True
|
||||
|
||||
def __repr__(self):
|
||||
return "AABB:%s - %s" % (str(self.vMin), str(self.vMax))
|
||||
|
||||
class _AABBNode(object):
|
||||
def __init__(self, aabb):
|
||||
self.child1 = None
|
||||
self.child2 = None
|
||||
self.parent = None
|
||||
self.height = 0
|
||||
self.aabb = aabb
|
||||
|
||||
def isLeaf(self):
|
||||
return self.child1 == None
|
||||
|
||||
class AABBTree(object):
|
||||
def __init__(self):
|
||||
self.root = None
|
||||
|
||||
def insert(self, aabb):
|
||||
newNode = _AABBNode(aabb)
|
||||
if self.root == None:
|
||||
self.root = newNode
|
||||
return
|
||||
|
||||
node = self.root
|
||||
while not node.isLeaf():
|
||||
child1 = node.child1
|
||||
child2 = node.child2
|
||||
|
||||
area = node.aabb.perimeter
|
||||
combinedAABB = node.aabb.combine(aabb)
|
||||
combinedArea = combinedAABB.perimeter
|
||||
|
||||
cost = 2.0 * combinedArea
|
||||
inheritanceCost = 2.0 * (combinedArea - area)
|
||||
|
||||
if child1.isLeaf():
|
||||
cost1 = aabb.combine(child1.aabb).perimeter + inheritanceCost
|
||||
else:
|
||||
oldArea = child1.aabb.perimeter
|
||||
newArea = aabb.combine(child1.aabb).perimeter
|
||||
cost1 = (newArea - oldArea) + inheritanceCost
|
||||
|
||||
if child2.isLeaf():
|
||||
cost2 = aabb.combine(child1.aabb).perimeter + inheritanceCost
|
||||
else:
|
||||
oldArea = child2.aabb.perimeter
|
||||
newArea = aabb.combine(child2.aabb).perimeter
|
||||
cost2 = (newArea - oldArea) + inheritanceCost
|
||||
|
||||
if cost < cost1 and cost < cost2:
|
||||
break
|
||||
|
||||
if cost1 < cost2:
|
||||
node = child1
|
||||
else:
|
||||
node = child2
|
||||
|
||||
sibling = node
|
||||
|
||||
# Create a new parent.
|
||||
oldParent = sibling.parent
|
||||
newParent = _AABBNode(aabb.combine(sibling.aabb))
|
||||
newParent.parent = oldParent
|
||||
newParent.height = sibling.height + 1
|
||||
|
||||
if oldParent != None:
|
||||
# The sibling was not the root.
|
||||
if oldParent.child1 == sibling:
|
||||
oldParent.child1 = newParent
|
||||
else:
|
||||
oldParent.child2 = newParent
|
||||
|
||||
newParent.child1 = sibling
|
||||
newParent.child2 = newNode
|
||||
sibling.parent = newParent
|
||||
newNode.parent = newParent
|
||||
else:
|
||||
# The sibling was the root.
|
||||
newParent.child1 = sibling
|
||||
newParent.child2 = newNode
|
||||
sibling.parent = newParent
|
||||
newNode.parent = newParent
|
||||
self.root = newParent
|
||||
|
||||
# Walk back up the tree fixing heights and AABBs
|
||||
node = newNode.parent
|
||||
while node != None:
|
||||
node = self._balance(node)
|
||||
|
||||
child1 = node.child1
|
||||
child2 = node.child2
|
||||
|
||||
node.height = 1 + max(child1.height, child2.height)
|
||||
node.aabb = child1.aabb.combine(child2.aabb)
|
||||
|
||||
node = node.parent
|
||||
|
||||
def _balance(self, A):
|
||||
if A.isLeaf() or A.height < 2:
|
||||
return A
|
||||
|
||||
B = A.child1
|
||||
C = A.child2
|
||||
|
||||
balance = C.height - B.height
|
||||
|
||||
# Rotate C up
|
||||
if balance > 1:
|
||||
F = C.child1;
|
||||
G = C.child2;
|
||||
|
||||
# Swap A and C
|
||||
C.child1 = A;
|
||||
C.parent = A.parent;
|
||||
A.parent = C;
|
||||
|
||||
# A's old parent should point to C
|
||||
if C.parent != None:
|
||||
if C.parent.child1 == A:
|
||||
C.parent.child1 = C
|
||||
else:
|
||||
C.parent.child2 = C
|
||||
else:
|
||||
self.root = C
|
||||
|
||||
# Rotate
|
||||
if F.height > G.height:
|
||||
C.child2 = F
|
||||
A.child2 = G
|
||||
G.parent = A
|
||||
A.aabb = B.aabb.combine(G.aabb)
|
||||
C.aabb = A.aabb.combine(F.aabb)
|
||||
|
||||
A.height = 1 + max(B.height, G.height)
|
||||
C.height = 1 + max(A.height, F.height)
|
||||
else:
|
||||
C.child2 = G
|
||||
A.child2 = F
|
||||
F.parent = A
|
||||
A.aabb = B.aabb.combine(F.aabb)
|
||||
C.aabb = A.aabb.combine(G.aabb)
|
||||
|
||||
A.height = 1 + max(B.height, F.height)
|
||||
C.height = 1 + max(A.height, G.height)
|
||||
|
||||
return C;
|
||||
|
||||
# Rotate B up
|
||||
if balance < -1:
|
||||
D = B.child1
|
||||
E = B.child2
|
||||
|
||||
# Swap A and B
|
||||
B.child1 = A
|
||||
B.parent = A.parent
|
||||
A.parent = B
|
||||
|
||||
# A's old parent should point to B
|
||||
if B.parent != None:
|
||||
if B.parent.child1 == A:
|
||||
B.parent.child1 = B
|
||||
else:
|
||||
B.parent.child2 = B
|
||||
else:
|
||||
self.root = B
|
||||
|
||||
# Rotate
|
||||
if D.height > E.height:
|
||||
B.child2 = D
|
||||
A.child1 = E
|
||||
E.parent = A
|
||||
A.aabb = C.aabb.combine(E.aabb)
|
||||
B.aabb = A.aabb.combine(D.aabb)
|
||||
|
||||
A.height = 1 + max(C.height, E.height)
|
||||
B.height = 1 + max(A.height, D.height)
|
||||
else:
|
||||
B.child2 = E
|
||||
A.child1 = D
|
||||
D.parent = A
|
||||
A.aabb = C.aabb.combine(D.aabb)
|
||||
B.aabb = A.aabb.combine(E.aabb)
|
||||
|
||||
A.height = 1 + max(C.height, D.height)
|
||||
B.height = 1 + max(A.height, E.height)
|
||||
|
||||
return B
|
||||
|
||||
return A
|
||||
|
||||
def query(self, aabb):
|
||||
resultList = []
|
||||
if self.root != None:
|
||||
self._query(self.root, aabb, resultList)
|
||||
return resultList
|
||||
|
||||
def _query(self, node, aabb, resultList):
|
||||
if not aabb.overlap(node.aabb):
|
||||
return
|
||||
if node.isLeaf():
|
||||
resultList.append(node.aabb)
|
||||
else:
|
||||
self._query(node.child1, aabb, resultList)
|
||||
self._query(node.child2, aabb, resultList)
|
||||
|
||||
def __repr__(self):
|
||||
s = "AABBTree:\n"
|
||||
s += str(self.root.aabb)
|
||||
return s
|
||||
|
||||
if __name__ == '__main__':
|
||||
tree = AABBTree()
|
||||
tree.insert(AABB(Vector3(0,0,0), Vector3(0,0,0)))
|
||||
tree.insert(AABB(Vector3(1,1,1), Vector3(1,1,1)))
|
||||
tree.insert(AABB(Vector3(0.5,0.5,0.5), Vector3(0.5,0.5,0.5)))
|
||||
print(tree)
|
||||
print(tree.query(AABB(Vector3(0,0,0), Vector3(0,0,0))))
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import os
|
||||
import sys
|
||||
from printer_webui.util import resources
|
||||
|
||||
def getVersion(getGitVersion = True):
|
||||
gitPath = os.path.abspath(os.path.join(os.path.split(os.path.abspath(__file__))[0], "../../.git"))
|
||||
if hasattr(sys, 'frozen'):
|
||||
versionFile = os.path.normpath(os.path.join(resources.resourceBasePath, "version"))
|
||||
else:
|
||||
versionFile = os.path.abspath(os.path.join(os.path.split(os.path.abspath(__file__))[0], "../version"))
|
||||
if os.path.exists(gitPath):
|
||||
if not getGitVersion:
|
||||
return "dev"
|
||||
f = open(gitPath + "/refs/heads/master", "r")
|
||||
version = f.readline()
|
||||
f.close()
|
||||
return version.strip()
|
||||
if os.path.exists(versionFile):
|
||||
f = open(versionFile, "r")
|
||||
version = f.readline()
|
||||
f.close()
|
||||
return version.strip()
|
||||
return "?"
|
||||
|
||||
def isDevVersion():
|
||||
gitPath = os.path.abspath(os.path.join(os.path.split(os.path.abspath(__file__))[0], "../../.git"))
|
||||
return os.path.exists(gitPath)
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(getVersion())
|
||||
|
||||
Reference in new issue
Block a user