Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
692166f067 | ||
|
|
69dca5b58c | ||
|
|
6305c4d2eb | ||
|
|
b5cf20a1de | ||
|
|
5807b606f0 | ||
|
|
398eaf58a9 | ||
|
|
4a933228c7 | ||
|
|
56caa7750c | ||
|
|
38a47bb2a8 | ||
|
|
e6f9003549 | ||
|
|
5cadf85401 | ||
|
|
baab1ce70a | ||
|
|
cbaf848711 | ||
|
|
85060b972a | ||
|
|
29aefdec08 | ||
|
|
6e01a361c5 | ||
|
|
542ccb5421 | ||
|
|
6d8eb682c1 | ||
|
|
d701c261c3 | ||
|
|
7b16f38ba3 | ||
|
|
337329eda0 | ||
|
|
47b7552f91 | ||
|
|
6736224962 | ||
|
|
c9009496f6 | ||
|
|
d393a6730c | ||
|
|
069bfdd9f8 | ||
|
|
23d2cdec76 | ||
|
|
1a308a1bc7 | ||
|
|
13098dde00 | ||
|
|
27d1a6ca37 | ||
|
|
1616fb4de8 | ||
|
|
07d8d4b88d | ||
|
|
2a3d9c291d | ||
|
|
b36290a1f2 | ||
|
|
48d74ef2fd | ||
|
|
35e20162ec | ||
|
|
c82ec3d3af | ||
|
|
5c06bd5036 | ||
|
|
21034b381c | ||
|
|
beb5850361 | ||
|
|
1ea0cf9213 | ||
|
|
4081a25f48 | ||
|
|
718a102d44 | ||
|
|
49f4a0c5b0 | ||
|
|
d267a752cd | ||
|
|
632724a023 | ||
|
|
eb48a50139 | ||
|
|
0a3dc4b354 | ||
|
|
fe134e7986 | ||
|
|
b5f40cfd69 | ||
|
|
3fb9248d2a | ||
|
|
3dd0ace076 | ||
|
|
abe68adac8 | ||
|
|
99c65b8cf4 | ||
|
|
742818c2ca | ||
|
|
d4072a3afd | ||
|
|
92c65cb21c | ||
|
|
d20a9f64a2 | ||
|
|
ed82488c5b | ||
|
|
5955d3d32e | ||
|
|
682c3dd8e3 | ||
|
|
56f2dc9d8e | ||
|
|
71941f337d | ||
|
|
b347e96748 | ||
|
|
8069d08d3b | ||
|
|
4b7552e56e | ||
|
|
c4a1ed2590 | ||
|
|
e443c7df2f | ||
|
|
b9372d7300 | ||
|
|
9e8b5312d5 | ||
|
|
f79d496c7c | ||
|
|
73a587b3e4 | ||
|
|
fac4aad05f | ||
|
|
c53c263805 | ||
|
|
4e31ccf4c5 | ||
|
|
c4e2a8982f | ||
|
|
42dafd7565 | ||
|
|
6ce82ceb00 | ||
|
|
6583691e85 | ||
|
|
2f44f10eb0 | ||
|
|
0e817d43cc | ||
|
|
7f1394a8d6 | ||
|
|
caaf1d229c | ||
|
|
36ae6dd6b9 | ||
|
|
bcd7bb4d20 | ||
|
|
8151e617cc | ||
|
|
1e429606e1 | ||
|
|
7fbfaadc21 | ||
|
|
814355e281 | ||
|
|
c720cc3a4a | ||
|
|
660de61997 | ||
|
|
f4b3206d49 | ||
|
|
4abfa6c3b3 | ||
|
|
2a059cf0cb | ||
|
|
7743372ee4 | ||
|
|
59027d349f | ||
|
|
9fd8b09e34 | ||
|
|
450e24bbc2 | ||
|
|
c020c7afe0 | ||
|
|
0d7965ebf1 | ||
|
|
34ceb93509 | ||
|
|
c120261e2b | ||
|
|
f0acacec6a | ||
|
|
9fbe130169 | ||
|
|
b96d1b51e0 | ||
|
|
570c66b6f3 | ||
|
|
ccd2ddc056 | ||
|
|
54f24b43f0 | ||
|
|
eae68f04ca | ||
|
|
7fcd04ae61 | ||
|
|
1a4920fc36 | ||
|
|
8149a3b4a8 | ||
|
|
e8bd29ef99 | ||
|
|
8a7d234571 | ||
|
|
c5c5383e0e | ||
|
|
b4d25db9c8 | ||
|
|
ef876cfd35 | ||
|
|
547dcdd725 | ||
|
|
dedadbc9ac | ||
|
|
cda399f11a | ||
|
|
ec42c45204 | ||
|
|
c98d3d1655 | ||
|
|
5e96bd8b6a | ||
|
|
2b4a985d85 | ||
|
|
56a51a3800 | ||
|
|
0982c8cc62 | ||
|
|
682e78c256 | ||
|
|
d90a9e7fc4 | ||
|
|
9d6b6cf103 | ||
|
|
bad88da2fe | ||
|
|
090671a044 | ||
|
|
1e9ea8e85e | ||
|
|
c5bc000b56 | ||
|
|
42d288c0e2 | ||
|
|
935c1da30f | ||
|
|
c0774d0dd8 | ||
|
|
612005c4f6 | ||
|
|
ee1f9029d1 | ||
|
|
1d8cf86215 | ||
|
|
fbc0b8af91 | ||
|
|
b8283b2499 | ||
|
|
da0f1fa3c8 | ||
|
|
0d18ca421b | ||
|
|
48dd2657e9 | ||
|
|
62f2d11f8b | ||
|
|
93bbedae86 | ||
|
|
40fe74ef45 | ||
|
|
043b213a96 | ||
|
|
63d095ab00 | ||
|
|
6db57122b4 | ||
|
|
c595d02f22 | ||
|
|
2e23cd39a4 | ||
|
|
3de4f91f50 | ||
|
|
6473937b75 | ||
|
|
fab5fc4899 | ||
|
|
d0eca800fb | ||
|
|
a6c24e174d | ||
|
|
a52a5ca338 | ||
|
|
acc85127c5 | ||
|
|
454f16a7c3 | ||
|
|
a731f748d9 | ||
|
|
9a7bddd530 | ||
|
|
83f66e133e | ||
|
|
ab97abf13e | ||
|
|
7820c17d08 | ||
|
|
9ed79adb8d | ||
|
|
b98348de02 | ||
|
|
a5094d403a | ||
|
|
6b0dee26e5 | ||
|
|
a44eb43f0f | ||
|
|
b6a5cb47a1 | ||
|
|
65efcec008 | ||
|
|
37730616c1 | ||
|
|
a53195d2a0 | ||
|
|
084fd8d433 | ||
|
|
33306b6787 | ||
|
|
b4cb0dec87 | ||
|
|
063251fe03 | ||
|
|
9b3ef8b693 | ||
|
|
a5ce071939 | ||
|
|
e8fa2e44e0 | ||
|
|
e223341ece | ||
|
|
5c8d9007f6 | ||
|
|
91163dc4f4 | ||
|
|
2a8e084b51 | ||
|
|
ce00a069fa | ||
|
|
bdadab6993 | ||
|
|
05d6cac67a | ||
|
|
528192b3c0 | ||
|
|
729d23b2c0 | ||
|
|
2e566c5ee1 | ||
|
|
e875d042a7 | ||
|
|
f05f850175 | ||
|
|
9ce9af28c3 | ||
|
|
57bf457d97 | ||
|
|
adf39cdf21 | ||
|
|
6c622f7c43 | ||
|
|
d34790e74e | ||
|
|
aa5099340e | ||
|
|
693633bd1d | ||
|
|
758062133c | ||
|
|
c55fea666d | ||
|
|
c932e496fa | ||
|
|
bbbdb3dde6 | ||
|
|
b9460b4890 | ||
|
|
947f4c89cc | ||
|
|
5f982ec6c8 | ||
|
|
dcf2e51b21 | ||
|
|
85e6ae8e82 | ||
|
|
859ea0d0e4 | ||
|
|
9cf21aa036 | ||
|
|
637adc3095 | ||
|
|
548f976d35 | ||
|
|
45c92cb1f4 | ||
|
|
f83d5aa89f | ||
|
|
abf073340f | ||
|
|
918ffa2557 | ||
|
|
5cc8ec5cc3 | ||
|
|
fce7b40b51 | ||
|
|
1178fe9e95 | ||
|
|
2f24e73fcb | ||
|
|
9ff5c36370 | ||
|
|
1b4ea75466 | ||
|
|
b4b5689bc4 | ||
|
|
fd4271a962 | ||
|
|
65bc28a03e | ||
|
|
c26515c13d | ||
|
|
25a4d4b79b | ||
|
|
43ca4d8252 | ||
|
|
b56ba6589c | ||
|
|
5c9b507cb7 | ||
|
|
cd7ac032f4 | ||
|
|
a2e5fc0c5c | ||
|
|
536bb31965 | ||
|
|
ef46a49430 | ||
|
|
8e28ddd6a4 | ||
|
|
ab8b0230bd | ||
|
|
754ef428a0 | ||
|
|
455474841e | ||
|
|
ae4e4f22c4 | ||
|
|
96fc70bdb2 | ||
|
|
8ed0befd62 | ||
|
|
766c0c21d4 | ||
|
|
7d50563666 | ||
|
|
4011f60ff9 | ||
|
|
37950cb466 | ||
|
|
2824b967ff | ||
|
|
7b8bf2cf5c | ||
|
|
9299cb54a4 | ||
|
|
b965d4cbde | ||
|
|
7d922f3c77 | ||
|
|
7e894d2ac2 | ||
|
|
948e20b269 | ||
|
|
0e863ad776 | ||
|
|
13d7d5f2f6 | ||
|
|
ac8faf7910 | ||
|
|
bf049ddee4 | ||
|
|
e435d55cb1 | ||
|
|
2c50237699 | ||
|
|
93763a5563 | ||
|
|
7a74f5348d | ||
|
|
b25c2220d1 | ||
|
|
57161dd9c3 | ||
|
|
1343a4a253 | ||
|
|
6de7eabca2 | ||
|
|
2247f30c87 | ||
|
|
ba6a6723a6 | ||
|
|
f9a0cb94f7 | ||
|
|
e689a2c733 | ||
|
|
d07c81f312 | ||
|
|
32f4f8d95b | ||
|
|
7f2e0161a8 | ||
|
|
59993bfca4 | ||
|
|
0782dda20f | ||
|
|
8c1a79558b | ||
|
|
0705a7054c | ||
|
|
54bd7766b9 | ||
|
|
ed215fc5fa | ||
|
|
5f53b704dd | ||
|
|
e8ef0ba8a4 | ||
|
|
49f62bc655 | ||
|
|
0ff43def3a | ||
|
|
cc14b77487 | ||
|
|
7f10c317f1 | ||
|
|
ba1f8c58b4 | ||
|
|
273bb45741 | ||
|
|
e33f69917f | ||
|
|
4b8bdd244e | ||
|
|
202f93426a | ||
|
|
c538604cd5 | ||
|
|
0c44762f6f | ||
|
|
6df57bc1d1 | ||
|
|
e328695100 | ||
|
|
738c699a6e | ||
|
|
8a28220e63 | ||
|
|
5808c1bd8a | ||
|
|
8bbb642a56 | ||
|
|
1f0dbf8f7f | ||
|
|
9a6099ffc2 | ||
|
|
25de95dc93 | ||
|
|
57f6e1e1bc | ||
|
|
edf9c40941 | ||
|
|
4dd4a2cc9c | ||
|
|
81bc8c784a | ||
|
|
294e7fc2db | ||
|
|
6e632d02a0 | ||
|
|
50ff0d810f | ||
|
|
d4be7f18e2 | ||
|
|
6d24a46e88 | ||
|
|
db866d2310 | ||
|
|
bb7e15be84 | ||
|
|
7a007a6417 | ||
|
|
96aad9d34f | ||
|
|
4d3334caf1 | ||
|
|
2745f49d28 | ||
|
|
5470aaaa3a | ||
|
|
f89cbc9133 | ||
|
|
5dfffc36e3 |
No files matched your search
@@ -0,0 +1,60 @@
|
||||
Please read the "guidelines for contributing" that are linked ^-- just
|
||||
up there. Also read the FAQ: https://github.com/foosel/OctoPrint/wiki/FAQ.
|
||||
|
||||
This is a bug and feature tracker, please only use it to report bugs
|
||||
or request features within OctoPrint (not OctoPi, not any OctoPrint
|
||||
plugins and not unofficial OctoPrint versions). Mark requests with
|
||||
a [Request] prefix in the title please. Fully fill out the bug reporting
|
||||
template for bug reports.
|
||||
|
||||
Do not seek support here ("I need help with ..."), that belongs on
|
||||
the mailing list or the G+ community (both linked in the "guidelines
|
||||
for contributing" linked above, read it!), NOT here.
|
||||
|
||||
Thank you!
|
||||
|
||||
----
|
||||
|
||||
#### What were you doing?
|
||||
|
||||
[Please be as specific as possible here. The maintainers will need to reproduce
|
||||
your issue in order to fix it and that is not possible if they don't know
|
||||
what you did to get it to happen in the first place. If you encountered
|
||||
a problem with specific files of any sorts, make sure to also include a link to a file
|
||||
with which to reproduce the problem.]
|
||||
|
||||
#### What did you expect to happen?
|
||||
|
||||
#### What happened instead?
|
||||
|
||||
#### Branch & Commit or Version of OctoPrint
|
||||
|
||||
[Can be found in the lower left corner of the web interface.]
|
||||
|
||||
#### Printer model & used firmware incl. version
|
||||
|
||||
[If applicable, always include if unsure.]
|
||||
|
||||
#### Browser and Version of Browser, Operating System running Browser
|
||||
|
||||
[If applicable, always include if unsure.]
|
||||
|
||||
#### Link to octoprint.log
|
||||
|
||||
[On gist.github.com or pastebin.com. Always include and never truncate.]
|
||||
|
||||
#### Link to contents of terminal tab or serial.log
|
||||
|
||||
[On gist.github.com or pastebin.com. If applicable, always include if unsure or
|
||||
reporting communication issues. Never truncate.]
|
||||
|
||||
#### Link to contents of Javascript console in the browser
|
||||
|
||||
[On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
|
||||
always include if unsure or reporting UI issues.]
|
||||
|
||||
#### Screenshot(s) showing the problem:
|
||||
|
||||
[If applicable. Always include if unsure or reporting UI issues.]
|
||||
|
||||
I have read the FAQ.
|
||||
@@ -0,0 +1,50 @@
|
||||
Thank you for your interest into contributing to OctoPrint, it's
|
||||
highly appreciated!
|
||||
|
||||
Please make sure you have read the "guidelines for contributing" as
|
||||
linked just above this form, there's a section on Pull Requests in there
|
||||
as well that contains important information.
|
||||
|
||||
As a summary, please make sure you have ticked all points on this
|
||||
checklist:
|
||||
|
||||
* [ ] Your changes are not possible to do through a plugin and relevant
|
||||
to a large audience (ideally all users of OctoPrint)
|
||||
* [ ] If your changes are large or otherwise disruptive: You have
|
||||
made sure your changes don't interfere with current development by
|
||||
talking it through with the maintainers, e.g. through a
|
||||
Brainstorming ticket
|
||||
* [ ] Your PR targets OctoPrint's devel branch (not master,
|
||||
maintenance or anything else)
|
||||
* [ ] Your PR was opened from a custom branch on your repository
|
||||
(no PRs from your version of master, maintenance or devel please),
|
||||
e.g. dev/my_new_feature
|
||||
* [ ] Your PR only contains relevant changes: no unrelated files,
|
||||
no dead code, ideally only one commit - rebase your PR if necessary!
|
||||
* [ ] Your changes follow the coding style
|
||||
* [ ] If your changes include style sheets: You have modified the
|
||||
.less source files, not the .css files (those are generated with
|
||||
lessc)
|
||||
* [ ] You have tested your changes (please state how!) - ideally you
|
||||
have added unit tests
|
||||
* [ ] You have run the existing unit tests against your changes and
|
||||
nothing broke
|
||||
* [ ] You have added yourself to the AUTHORS.md file :)
|
||||
|
||||
Feel free to delete all this help text, then describe
|
||||
your PR further. You may use the template provided below to do that.
|
||||
The more details the better!
|
||||
|
||||
----
|
||||
|
||||
#### What does this PR do and why is it necessary?
|
||||
|
||||
#### How was it tested? How can it be tested by the reviewer?
|
||||
|
||||
#### Any background context you want to provide?
|
||||
|
||||
#### What are the relevant tickets if any?
|
||||
|
||||
#### Screenshots (if appropriate)
|
||||
|
||||
#### Further notes
|
||||
+4
-1
@@ -6,4 +6,7 @@ python:
|
||||
install:
|
||||
- pip install -e .[develop]
|
||||
script:
|
||||
- nosetests tests/
|
||||
- nosetests --with-doctest
|
||||
sudo: false
|
||||
git:
|
||||
depth: 250
|
||||
+10
-5
@@ -10,10 +10,15 @@
|
||||
# master shall not use the lookup table, only tags
|
||||
master
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.2.3
|
||||
# so are any fix/... branches
|
||||
maintenance 1.2.3-dev 1c6b0554c796f03ed539397daa4b13c44d05a99d
|
||||
fix/.* 1.2.3-dev 1c6b0554c796f03ed539397daa4b13c44d05a99d
|
||||
# neither should disconnected checkouts, e.g. 'git checkout <tag>'
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.2.10
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.2.10 abe68adac8f465a31bf4f3f3933190c1fc242cda pep440-dev
|
||||
fix/.* 1.2.10 abe68adac8f465a31bf4f3f3933190c1fc242cda pep440-dev
|
||||
improve/.* 1.2.10 abe68adac8f465a31bf4f3f3933190c1fc242cda pep440-dev
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.3.0-dev for now
|
||||
.* 1.3.0-dev 198d3450d94be1a2
|
||||
.* 1.3.0 198d3450d94be1a2 pep440-dev
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
# Authors
|
||||
|
||||
The following people have contributed to OctoPrint's code base (ordered by
|
||||
date of first contribution):
|
||||
|
||||
* [Gina Häußge](https://github.com/foosel)
|
||||
* [Thomas Sanladerer](https://github.com/imitation)
|
||||
* [Alex Ustyantsev](https://github.com/hudbrog)
|
||||
* [Andrew Dalgleish](https://github.com/ajd4096)
|
||||
* [Dale Price](https://github.com/daprice)
|
||||
* [Václav "ax" Hůla](https://github.com/AxTheB)
|
||||
* [Tom Perry](https://github.com/daftscience)
|
||||
* [Andreas Gohr](https://github.com/splitbrain)
|
||||
* [Lars Norpchen](https://github.com/norpchen)
|
||||
* [Marlon Wünnemann](https://github.com/marwue)
|
||||
* ["algspd"](https://github.com/algspd)
|
||||
* [Peter Uithoven](https://github.com/peteruithoven)
|
||||
* [Bryan Mayland](https://github.com/CapnBry)
|
||||
* [Ross Hendrickson](https://github.com/savorywatt)
|
||||
* [Dan Lipsitt](https://github.com/DanLipsitt)
|
||||
* [James Gao](https://github.com/jamesgao)
|
||||
* [Tonnerre Lombard](https://github.com/tonnerre)
|
||||
* [Marc Hannappel](https://github.com/Salandora)
|
||||
* [Brad Pitcher](https://github.com/brad)
|
||||
* [Gabe Rosenhouse](https://github.com/rosenhouse)
|
||||
* [chriskoz](https://github.com/chriskoz)
|
||||
* [Ilya Novoselov](https://github.com/nullie)
|
||||
* [Corey C](https://github.com/C-o-r-E)
|
||||
* [Jarek Szczepanski](https://github.com/imrahil)
|
||||
* [Jon Nordby](https://github.com/jonnor)
|
||||
* [Aaron Bieber](https://github.com/qbit)
|
||||
* [Guy Sheffer](https://github.com/guysoft)
|
||||
* [Dattas Moonchaser](https://github.com/dattas)
|
||||
* [Pim Rutgers](https://github.com/Booli)
|
||||
* [Koen Kooi](https://github.com/koenkooi)
|
||||
* [Colin Wallace](https://github.com/Wallacoloo)
|
||||
* [Michael Ang](https://github.com/mangtronix)
|
||||
* [Philipp Engel](https://github.com/nosyjoe)
|
||||
* [Giles Hall](https://github.com/vishnubob)
|
||||
* [Bevaz](https://github.com/Bevaz)
|
||||
* [Bortek](https://github.com/bortek)
|
||||
* [Rob Speed](https://github.com/rspeed)
|
||||
* [Renha](https://github.com/Renha)
|
||||
* [Antoine Bertin](https://github.com/Diaoul)
|
||||
* [Teja Philipp](https://github.com/hungerpirat)
|
||||
* ["matobago"](https://github.com/matobago)
|
||||
* ["nophead"](https://github.com/nophead)
|
||||
* [Bob Clough](https://github.com/thinkl33t)
|
||||
* [Mikk Kiilaspää](https://github.com/Mikk36)
|
||||
* [Jack Minardi](https://github.com/jminardi)
|
||||
* [Mark Walker](https://github.com/markwal)
|
||||
* [Lucas Clemente](https://github.com/lucas-clemente)
|
||||
* [Andrew Erickson](https://github.com/aerickson)
|
||||
* [Nicanor Romero Venier](https://github.com/nicanor-romero)
|
||||
* [Thomas Hou](https://github.com/masterhou)
|
||||
* [Mark Bastiaans](https://github.com/markbastiaans)
|
||||
* [Kevin Murphy](https://github.com/kevingelion)
|
||||
* [Richard Joyce](https://github.com/richjoyce)
|
||||
* ["bwgan"](https://github.com/bwgan)
|
||||
* [Siim Raud](https://github.com/2ndalpha)
|
||||
* ["geoporalis"](https://github.com/geoporalis)
|
||||
* [Andrew Malota](https://github.com/2bitoperations)
|
||||
|
||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||
the server side GCODE interpreter are still based on Cura's code base from
|
||||
December 2012 and hence on the work of its authors up until then.
|
||||
+369
-1
@@ -1,5 +1,373 @@
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.2.10 (2016-03-16)
|
||||
|
||||
### Improvements
|
||||
|
||||
* Improved performance of console output during plugin installation/deinstallation
|
||||
* Slight performance improvements in the communication layer
|
||||
* Log small log excerpt to `octoprint.log` upon encountering a communication error.
|
||||
* Changed wording in "firmware error" notifications to better reflect that there was an error while communicating with the printer, since the error condition can also be triggered by serial errors while trying to establish a connection to the printer or when already connected.
|
||||
* Support downloading ".mp4" timelapse files. You'll need a [custom wrapper script for timelapse rendering](https://github.com/guysoft/OctoPi/issues/184) for this to be relevant to you. See also [#1255](https://github.com/foosel/OctoPrint/pull/1255)
|
||||
* The communication layer will now wait up to 10s after clicking disconnect in order to send any left-over lines from its buffers.
|
||||
* Moved less commonly used configuration options in Serial settings into "Advanced options" roll-out.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#1224](https://github.com/foosel/OctoPrint/issues/1224) - Fixed an issue introduced by the fix for [#1196](https://github.com/foosel/OctoPrint/issues/1196) that had the "Upload to SD" button stop working correctly.
|
||||
* [#1226](https://github.com/foosel/OctoPrint/issues/1226) - Fixed an issue causing an error on disconnect after or cancelling of an SD print, caused by the unsuccessful attempt to record print recovery data for the file on the printer's SD card.
|
||||
* [#1268](https://github.com/foosel/OctoPrint/issues/1268) - Only add bed temperature line to temperature management specific start gcode in CuraEngine invocation if a bed temperature is actually set in the slicing profile.
|
||||
* [#1271](https://github.com/foosel/OctoPrint/issues/1271) - If a communication timeout occurs during an active resend request, OctoPrint will now not send an `M105` with an increased line number anymore but repeat the last resent command instead.
|
||||
* [#1272](https://github.com/foosel/OctoPrint/issues/1272) - Don't add an extra `ok` for `M28` response.
|
||||
* [#1273](https://github.com/foosel/OctoPrint/issues/1273) - Add an extra `ok` for `M29` response, but only if configured such in "Settings" > "Serial" > "Advanced options" > "Generate additional ok for M29"
|
||||
* [#1274](https://github.com/foosel/OctoPrint/issues/1274) - Trigger `M20` only once after finishing uploading to SD
|
||||
* [#1275](https://github.com/foosel/OctoPrint/issues/1275) - Prevent `M105` "cascade" due to communication timeouts
|
||||
* Fixed wrong tracking of extruder heating up for `M109 Tn` commands in multi-extruder setups.
|
||||
* Fixed start of SD file uploads not sending an `M110`.
|
||||
* Fixed job data not being reset when disconnecting while printing.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.9...1.2.10))
|
||||
|
||||
## 1.2.9 (2016-02-10)
|
||||
|
||||
### Improvements
|
||||
|
||||
* [#318](https://github.com/foosel/OctoPrint/issues/318) - Snapshots for timelapses are now named in a non-colliding, job-based way, allowing a new timelapse to start while the other is still being rendered (although printing with an active timelapse rendering job is not recommended and will be solved with a proper render job queue in a later version). Timelapses that were not successfully rendered are kept for 7 days (configurable, although not via the UI so far) and can be manually rendered or deleted through a new UI component within the timelapse tab that shows up if unrendered timelapses are detected.
|
||||
* [#485](https://github.com/foosel/OctoPrint/issues/485) - "Timelapse rendering" notification is now persistent, even across reloads/client switches. That should make it easier to see that a rendering job is currently in progress.
|
||||
* [#939](https://github.com/foosel/OctoPrint/issues/939) - Updated to Knockout 3.4.0
|
||||
* [#1204](https://github.com/foosel/OctoPrint/issues/1204) - Display total print time as estimated by GCODE viewer on GCODE viewer tab. That will allow access to an estimate even if the server hadn't yet calculated that when a print started. Note that due to slightly different implementation server and client side the resulting estimate might differ.
|
||||
* OctoPrint now serves an intermediary page upon start that informs the user about the server still starting up. Once the server is detected as running, the page automatically switches to the standard interface.
|
||||
* OctoPrint now displays a link to the release notes of an updated component in the update notification, the update confirmation and the version overview in the settings dialog. Please always make sure to at least skim over the release notes for new OctoPrint releases, they might contain important information that you need to know before updating.
|
||||
* Improved initial page loading speeds by introducing a preemptive cache. OctoPrint will now record how you access it and on server start pre-render the page so it's ideally available in the server-side cache when you try to access it.
|
||||
* Initialize login user name and password with an empty string and clear both on successful login (see [#1175](https://github.com/foosel/OctoPrint/pull/1175)).
|
||||
* Added a "Refresh" button to the file list for people who modify the stored files externally (doing this is not encouraged however due to reasons of book keeping, e.g. metadata tracking etc).
|
||||
* "Save" button on settings dialog is now disabled while background tasks (getting or receiving config data from the backend) are in progress.
|
||||
* Improved performance of terminal tab on lower powered clients. Adaptive rate limiting now ensures the server backs off with log updates if the client can't process them fast enough. If the client is really slow, log updates get disabled automatically during printing. This behaviour can be disabled with override buttons in the terminal tab's advanced options if necessary.
|
||||
* Added option to ignore any unhandled errors reported by the firmware and another option to only cancel ongoing prints on unhandled errors from the firmware (instead of instant disconnect that so far was the default).
|
||||
* Made version compatibility check PEP440 compliant (important for plugin authors).
|
||||
* Do not hiccup on manually sent `M28` commands.
|
||||
* Persist print recovery data on print failures (origin and name of printed file, position in file when print was aborted, time and date of print failure). Currently this data isn't used anywhere, but it [can be accessed from plugins in order to add recovery functionality](https://github.com/foosel/OctoPrint-PrintRecoveryPoc) to OctoPrint.
|
||||
* Small performance improvements in update checks.
|
||||
* The file upload dialog will now only display files having an extension that's supported for upload (if the browser supports it, also see [#1196](https://github.com/foosel/OctoPrint/issues/1196)).
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#1007](https://github.com/foosel/OctoPrint/issues/1007) - Don't enable the "Print" button if no print job is selected.
|
||||
* [#1181](https://github.com/foosel/OctoPrint/issues/1181) - Properly slugify UTF-8 only file names.
|
||||
* [#1196](https://github.com/foosel/OctoPrint/issues/1196) - Do not show drag-n-drop overlay if server is offline.
|
||||
* [#1208](https://github.com/foosel/OctoPrint/issues/1208) - Fixed `retraction_combing` profile setting being incorrectly used by bundled Cura plugin (see [#1209](https://github.com/foosel/OctoPrint/pull/1209))
|
||||
* Fixed OctoPrint compatibility check in the plugin manager, could report `False` for development versions against certain versions of Python's `setuptools` (thanks to @ignaworm who stumbled over this).
|
||||
* Fixed a missing parameter in `PluginSettings.remove` call (see [#1177](https://github.com/foosel/OctoPrint/pull/1177)).
|
||||
* Docs: Fixed the example for a custom `M114` control to also match negative coordinates.
|
||||
* Reset scroll position in settings dialog properly when re-opening it or switching tabs.
|
||||
* Fixed an issue that prevented system menu entries that were added to a so far empty system menu make the menu show up.
|
||||
* Fixed an issue that made requests to restricted resources fail even though the first run wizard had been completed successfully.
|
||||
* Fixed an issue where an unknown command or the suppression of a command could cause the communication to stall until a communication timeout was triggered.
|
||||
* Strip [unwanted ANSI characters](https://github.com/pypa/pip/issues/3418) from output produced by pip versions 8.0.0, 8.0.1 and 8.0.3 that prevents our plugin installation detection from working correctly.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.8...1.2.9))
|
||||
|
||||
## 1.2.8 (2015-12-07)
|
||||
|
||||
### Notes for Upgraders
|
||||
|
||||
#### A bug in 1.2.7 prevents directly updating to 1.2.8, here's what to do
|
||||
|
||||
A bug in OctoPrint 1.2.7 (fixed in 1.2.8) prevents updating OctoPrint to version
|
||||
1.2.8. If you try to perform the update, you will simply be told that "the update
|
||||
was successful", but the update won't actually have taken place. To solve this
|
||||
hen-egg-problem, a plugin has been made available that fixes said bug (through
|
||||
monkey patching).
|
||||
|
||||
The plugin is called "Updatefix 1.2.7" and can be found
|
||||
[in the plugin repository](http://plugins.octoprint.org/plugins/updatefix127/)
|
||||
and [on Github](https://github.com/OctoPrint/OctoPrint-Updatefix-1.2.7/).
|
||||
|
||||
Before attempting to update your installation from version 1.2.7 to version 1.2.8,
|
||||
please install the plugin via your plugin manager and restart your server. Note that
|
||||
you will only see it in the Plugin Manager if you need it, since it's only compatible with
|
||||
OctoPrint version 1.2.7. After you installed the plugin and restarted your server
|
||||
you can update as usual. The plugin will self-uninstall once it detects that it's
|
||||
running under OctoPrint 1.2.8. After the self-uninstall another restart of your server
|
||||
will be triggered (if you have setup your server's restart command, defaults to
|
||||
`sudo service octoprint restart` on OctoPi) in order to really get rid of any
|
||||
left-overs, so don't be alarmed when that happens, it is intentional.
|
||||
|
||||
**If you cannot or don't want to use the plugin**, alternatively you can switch
|
||||
OctoPrint to "Commit" based tracking via the settings of the Software Update plugin,
|
||||
update, then switch back to "Release" based tracking (see [this screenshot](https://i.imgur.com/wvkgiGJ.png)).
|
||||
|
||||
#### Bed temperatures are now only displayed if printer profile has a heated bed configured
|
||||
|
||||
This release fixes a [bug](https://github.com/foosel/OctoPrint/issues/1125)
|
||||
that caused bed temperature display and controls to be available even if the
|
||||
selected printer profile didn't have a heated bed configured.
|
||||
|
||||
If your printer does have a heated bed but you are not seeing its temperature
|
||||
in the "Temperature" tab after updating to 1.2.8, please make sure to check
|
||||
the "Heated Bed" option in your printer profile (under Settings > Printer Profiles)
|
||||
as shown [in this short GIF](http://i.imgur.com/wp1j9bs.gif).
|
||||
|
||||
### Improvements
|
||||
|
||||
* Version numbering now follows [PEP440](https://www.python.org/dev/peps/pep-0440/).
|
||||
* Prepared some things for publishing OctoPrint on [PyPi](https://pypi.python.org/pypi)
|
||||
in the future.
|
||||
* [BlueprintPlugin mixin](http://docs.octoprint.org/en/master/plugins/mixins.html#blueprintplugin)
|
||||
now has an `errorhandler` decorator that serves the same purpose as
|
||||
[Flask's](http://flask.pocoo.org/docs/0.10/patterns/errorpages/#error-handlers)
|
||||
([#1059](https://github.com/foosel/OctoPrint/pull/1059))
|
||||
* Interpret `M25` in a GCODE file that is being streamed from OctoPrint as
|
||||
indication to pause, like `M0` and `M1`.
|
||||
* Cache rendered page and translation files indefinitely. That should
|
||||
significantly improve performance on reloads of the web interface.
|
||||
* Added the string "unknown command" to the list of ignored printer errors.
|
||||
This should help with general firmware compatibility in case a firmware
|
||||
lacks features.
|
||||
* Added the strings "cannot open" and "cannot enter" to the list of ignored
|
||||
printer errors. Those are errors that Marlin may report if there is an issue
|
||||
with the printer's SD card.
|
||||
* The "CuraEngine" plugin now makes it more obvious that it only targets
|
||||
CuraEngine versions up to and including 15.04 and also links to the plugin's
|
||||
homepage with more information right within the settings dialog.
|
||||
* Browser tab visibility is now tracked by the web interface, disabling the
|
||||
webcam and the GCODE viewer if the tab containing OctoPrint is not active.
|
||||
That should reduce the amount of resource utilized by the web interface on
|
||||
the client when it is not actively monitored. Might also help to mitigate
|
||||
[#1065](https://github.com/foosel/OctoPrint/issues/1065), the final verdict
|
||||
on that one is still out though.
|
||||
* The printer log in the terminal tab will now be cut off after 3000 lines
|
||||
even if autoscroll is disabled. If the limit is reached, no more log lines
|
||||
will be added to the client's buffer. That ensures that the log will not
|
||||
scroll and the current log excerpt will stay put while also not causing
|
||||
the browser to run into memory errors due to trying to buffer an endless
|
||||
amount of log lines.
|
||||
* Increased timeout of "waiting for restart" after an update from 20 to 60sec
|
||||
(20sec turned out to be too little for OctoPi for whatever reason).
|
||||
* Added a couple of unit tests
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#1120](https://github.com/foosel/OctoPrint/issues/1120) - Made the watchdog
|
||||
that monitors and handles the `watched` folder more resilient towards errors.
|
||||
* [#1125](https://github.com/foosel/OctoPrint/issues/1125) - Fixed OctoPrint
|
||||
displaying bed temperature and controls and allowing the sending of GCODE
|
||||
commands targeting the bed (`M140`, `M190`) if the printer profile doesn't
|
||||
have a heated bed configured.
|
||||
* Fixed an issue that stopped the software updater working for OctoPrint. The
|
||||
updater reports success updating, but no update has actually taken place. A
|
||||
fix can be applied for this issue to OctoPrint version 1.2.7 via
|
||||
[the Updatefix 1.2.7 plugin](https://github.com/OctoPrint/OctoPrint-Updatefix-1.2.7).
|
||||
For more information please refer to the [Important information for people updating from version 1.2.7](#important-information-for-people-updating-from-version-127)
|
||||
above.
|
||||
* Fix: Current filename in job data should never be prefixed with `/`
|
||||
* Only persist plugin settings that differ from the defaults. This way the
|
||||
`config.yaml` won't be filled with lots of redundant data. It's the
|
||||
responsibility of the plugin authors to responsibly handle changes in default
|
||||
settings of their plugins and add data migration where necessary.
|
||||
* Fixed a documentation bug ([#1067](https://github.com/foosel/OctoPrint/pull/1067))
|
||||
* Fixed a conflict with bootstrap-responsive, e.g. when using the
|
||||
[ScreenSquish Plugin](http://plugins.octoprint.org/plugins/screensquish/)
|
||||
([#1103](https://github.com/foosel/OctoPrint/pull/1067))
|
||||
* Fixed OctoPrint still sending SD card related commands to the printer even
|
||||
if SD card support is disabled (e.g. `M21`).
|
||||
* Hidden files are no longer visible to the template engine, neither as (GCODE)
|
||||
scripts nor as interface templates.
|
||||
* The hostname and URL prefix via which the OctoPrint web interface is accessed
|
||||
is now part of the cache key. Without that being the case the cache could
|
||||
be created referring to something like `/octoprint/prefix/api/` for its API
|
||||
endpoint (if accessed via `http://somehost:someport/octoprint/prefix/` first
|
||||
time), which would then cause the interface to not work if accessed later
|
||||
via another route (e.g. `http://someotherhost/`).
|
||||
* Fixed a JavaScript error on finishing streaming of a file to SD.
|
||||
* Fixed version reporting on detached HEADs (when the branch detection
|
||||
reported "HEAD" instead of "(detached"
|
||||
* Fixed some path checks for systems with symlinked paths
|
||||
([#1051](https://github.com/foosel/OctoPrint/pull/1051))
|
||||
* Fixed a bug causing the "Server Offline" overlay to pop _under_ the
|
||||
"Please reload" overlay, which could lead to "Connection refused" browser
|
||||
messages when clicking "Reload now" in the wrong moment.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.7...1.2.8))
|
||||
|
||||
## 1.2.7 (2015-10-20)
|
||||
|
||||
### Improvements
|
||||
|
||||
* [#1062](https://github.com/foosel/OctoPrint/issues/1062) - Plugin Manager
|
||||
now has a configuration dialog that among other things allows defining the
|
||||
used `pip` command if auto detection proves to be insufficient here.
|
||||
* Allow defining additional `pip` parameters in Plugin Manager. That might
|
||||
make `sudo`-less installation of plugins possible in situations where it's
|
||||
tricky otherwise.
|
||||
* Improved timelapse processing (backported from `devel` branch):
|
||||
* Individually captured frames cannot "overtake" each other anymore through
|
||||
usage of a capture queue.
|
||||
* Notifications will now be shown when the capturing of the timelapse's
|
||||
post roll happens, including an approximation of how long that will take.
|
||||
* Usage of `requests` instead of `urllib` for fetching the snapshot,
|
||||
appears to also have [positive effects on webcam compatibility](https://github.com/foosel/OctoPrint/issues/1078).
|
||||
* Some more defensive escaping for various settings in the UI (e.g. webcam URL)
|
||||
* Switch to more error resilient saving of configuration files and other files
|
||||
modified during runtime (save to temporary file & move). Should reduce risk
|
||||
of file corruption.
|
||||
* Downloading GCODE and STL files should now set more fitting `Content-Type`
|
||||
headers (`text/plain` and `application/sla`) for better client side support
|
||||
for "Open with" like usage scenarios.
|
||||
* Selecting z-triggered timelapse mode will now inform about that not working
|
||||
when printing from SD card.
|
||||
* Software Update Plugin: Removed "The web interface will now be reloaded"
|
||||
notification after successful update since that became obsolete with
|
||||
introduction of the "Reload Now" overlay.
|
||||
* Updated required version of `psutil` and `netifaces` dependencies.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#1057](https://github.com/foosel/OctoPrint/issues/1057) - Better error
|
||||
resilience of the Software Update plugin against broken/incomplete update
|
||||
configurations.
|
||||
* [#1075](https://github.com/foosel/OctoPrint/issues/1075) - Fixed support
|
||||
of `sudo` for installing plugins, but added big visible warning about it
|
||||
as it's **not** recommended.
|
||||
* [#1077](https://github.com/foosel/OctoPrint/issues/1077) - Do not hiccup
|
||||
on [UTF-8 BOMs](https://en.wikipedia.org/wiki/Byte_order_mark) (or other
|
||||
BOMs for that matter) at the beginning of GCODE files.
|
||||
* Fixed an issue that caused user sessions to not be properly associated,
|
||||
leading to Sessions getting duplicated, wrongly saved etc.
|
||||
* Fixed internal server error (HTTP 500) response on REST API calls with
|
||||
unset `Content-Type` header.
|
||||
* Fixed an issue leading to drag-and-drop file uploads to trigger frontend
|
||||
processing in various other file upload widgets.
|
||||
* Fixed a documentation error.
|
||||
* Fixed caching behaviour on GCODE/STL downloads, was setting the `ETag`
|
||||
header improperly.
|
||||
* Fixed GCODE viewer not properly detecting change of currently visualized
|
||||
file on Windows systems.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.6...1.2.7))
|
||||
|
||||
## 1.2.6 (2015-09-02)
|
||||
|
||||
### Improvements
|
||||
|
||||
* Added support for version reporting on detached checkouts
|
||||
(see [#1041](https://github.com/foosel/OctoPrint/pull/1041))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Pinned requirement for [psutil](https://pypi.python.org/pypi/psutil)
|
||||
dependency to version 3.1.1 of that library due to an issue when
|
||||
installing version 3.2.0 of that library released on 2015-09-02 through
|
||||
a `python setup.py install` on OctoPrint. Also pinned all other requirements
|
||||
to definitive versions that definitely work while at it to keep that from
|
||||
happening again.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.5...1.2.6))
|
||||
|
||||
## 1.2.5 (2015-08-31)
|
||||
|
||||
### Improvements
|
||||
|
||||
* [#986](https://github.com/foosel/OctoPrint/issues/986) - Added tooltip for
|
||||
"additional data" button in file list.
|
||||
* [#1028](https://github.com/foosel/OctoPrint/issues/1028) - Hint about why
|
||||
timelapse configuration is disabled.
|
||||
* New central configuration option for commands to restart OctoPrint and to
|
||||
restart and shut down the system OctoPrint is running on. This allows plugins
|
||||
(like the Software Update Plugin or the Plugin Manager) and core functionality
|
||||
to perform these common administrative tasks without the user needing to define
|
||||
everything redundantly.
|
||||
* Settings dialog now visualizes when settings are saving and when they being
|
||||
retrieved. Also the Send/Cancel buttons are disabled while settings are saving
|
||||
to prevent duplicated requests and concurrent retrieval of the settings by
|
||||
multiple viewmodels is disabled as well.
|
||||
* Better protection against rendering errors from templates provided by third
|
||||
party plugins.
|
||||
* Better protection against corrupting the configuration by using a temporary
|
||||
file as intermediate buffer.
|
||||
* Added warning to UI regarding Z timelapses and spiralized objects.
|
||||
* Better compatibility with Repetier firmware:
|
||||
* Added "Format Error" to whitelisted recoverable communication errors
|
||||
(see also [#1032](https://github.com/foosel/OctoPrint/pull/1032)).
|
||||
* Added option to ignore repeated resend requests for the same line (see
|
||||
also discussion in [#1015](https://github.com/foosel/OctoPrint/pull/1015)).
|
||||
* Software Update Plugin:
|
||||
* Adjusted to utilize new centralized restart commands (see above).
|
||||
* Allow configuration of checkout folder and version tracking type via
|
||||
Plugin Configuration.
|
||||
* Display message to user if OctoPrint's checkout folder is not configured
|
||||
or a non-release version is running and version tracking against releases
|
||||
is enabled.
|
||||
* Clear version cache when a change in the check configuration is detected.
|
||||
* Mark check configurations for which an update is not possible.
|
||||
* Made disk space running low a bit more obvious through visual warning on
|
||||
configurable thresholds.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* [#985](https://github.com/foosel/OctoPrint/issues/985) - Do not hiccup on
|
||||
unset `Content-Type` part headers for multipart file uploads.
|
||||
* [#1001](https://github.com/foosel/OctoPrint/issues/1001) - Fixed connection
|
||||
tab not unfolding properly (see also [#1002](https://github.com/foosel/OctoPrint/pull/1002)).
|
||||
* [#1012](https://github.com/foosel/OctoPrint/issues/1012) - All API
|
||||
responses now set no-cache headers, making the Edge browser behave a bit better
|
||||
* [#1019](https://github.com/foosel/OctoPrint/issues/1019) - Better error
|
||||
handling of problems when trying to write the webassets cache.
|
||||
* [#1021](https://github.com/foosel/OctoPrint/issues/1021) - Properly handle
|
||||
serial close on Macs.
|
||||
* [#1031](https://github.com/foosel/OctoPrint/issues/1031) - Special
|
||||
handling of `M112` (emergency stop) command:
|
||||
* Jump send queue
|
||||
* In case the printer's firmware doesn't understand it yet, at least
|
||||
shutdown all of the heaters
|
||||
* Disconnect
|
||||
* Properly reset job progress to 0% when restarting a previously completed
|
||||
printjob (see [#998](https://github.com/foosel/OctoPrint/pull/998)).
|
||||
* Report an update as failed if the `pip` command returns a return code that
|
||||
indicates failure.
|
||||
* Fixed sorting of templates: could only be sorted by name, individual
|
||||
configurations were ignored (see [#1022](https://github.com/foosel/OctoPrint/pull/1022)).
|
||||
* Fixed positioning of custom context menus: were offset due to changes in
|
||||
overall positioning settings (see [#1023](https://github.com/foosel/OctoPrint/pull/1023)).
|
||||
* Software Update: Don't use display version for comparison of git commit
|
||||
hashs.
|
||||
* Fixed temperature parsing for multi extruder setups.
|
||||
* Fixed nested vertical and horizontal custom control layouts.
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.4...1.2.5))
|
||||
|
||||
## 1.2.4 (2015-07-23)
|
||||
|
||||
### Improvements
|
||||
|
||||
* `RepeatedTimer` now defaults to `daemon` set to `True`. This makes sure
|
||||
plugins using it don't have to remember to set that flag themselves in
|
||||
order for the server to properly shut down when timers are still active.
|
||||
* Fixed a typo in the docs about `logging.yaml` (top level element is
|
||||
`loggers`, not `logger`).
|
||||
* Support for plugins with external dependencies (`dependency_links` in
|
||||
setuptools), interesting for plugin authors who need to depend on Python
|
||||
libraries that are (not yet) available on PyPI.
|
||||
* Better resilience against errors within plugins.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Do not cache web page when running for the first time, to avoid caching
|
||||
the first run dialog popup along side with it. This should solve issues
|
||||
people were having when configuring OctoPrint for the first time, then
|
||||
reloading the page without clearing the cache, being again prompted with
|
||||
the dialog with no chance to clear it.
|
||||
* Fix/workaround for occasional white panes in settings dialog on Safari 8,
|
||||
which appears to have an issue with fixed positioning.
|
||||
* Fixed form field truncation in upload requests that could lead to problems
|
||||
when trying to import Cura profiles with names longer than 28 characters.
|
||||
* Fixed webcam rotation for timelapse rendering.
|
||||
* Fixed user settings not reaching the editor in the frontend.
|
||||
* Notifications that are in process of being closed don't open again on
|
||||
mouse over (that was actually more of an unwanted feature).
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.3...1.2.4))
|
||||
|
||||
## 1.2.3 (2015-07-09)
|
||||
|
||||
### Improvements
|
||||
@@ -208,7 +576,7 @@
|
||||
changed under "Temperatures" in the Settings ([#343](https://github.com/foosel/OctoPrint/issues/343)).
|
||||
* High-DPI support for the GCode viewer ([#837](https://github.com/foosel/OctoPrint/issues/837)).
|
||||
* Stop websocket connections from multiplying ([#888](https://github.com/foosel/OctoPrint/pull/888)).
|
||||
* New setting to rotate webcam by 90° counter clockwise ([#895](https://github.com/foosel/OctoPrint/issues/895) and
|
||||
* New setting to rotate webcam by 90° counter clockwise ([#895](https://github.com/foosel/OctoPrint/issues/895) and
|
||||
[#906](https://github.com/foosel/OctoPrint/pull/906))
|
||||
* System commands now be set to a) run asynchronized by setting their `async` property to `true` and b) to ignore their
|
||||
result by setting their `ignore` property to `true`.
|
||||
|
||||
+372
-41
@@ -1,49 +1,380 @@
|
||||
Issues, Tickets, however you may call them
|
||||
------------------------------------------
|
||||
# Contribution Guidelines
|
||||
|
||||
Read the following short instructions **fully** and **follow them** if you want your ticket to be taken care of and not closed again directly! They are linked on top of every new issue form, so don't say nobody warned you afterwards.
|
||||
This document outlines what you need to know before **[creating tickets](#issues-tickets-however-you-may-call-them)**
|
||||
or **[creating pull requests](#pull-requests)**.
|
||||
|
||||
- **Read the [FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)**
|
||||
- Always create **one ticket for one purpose**. So don't mix two or more feature requests, support requests, bugs etc into one ticket. If you do, your ticket will be closed!
|
||||
- If you want to report a bug, **READ AND FOLLOW [How to file a bug report](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)!** Tickets will be automatically checked if they comply with the requirements outlined in that wiki node! Other then what's written in there (**and really EVERYTHING that is written in there!**) you don't have to do anything special with your ticket. Listen to what GitIssueBot might have to say to you!
|
||||
- If you want to post a **request** of any kind (feature request, documentation request, ...), **add [Request] to your issue's title!**
|
||||
- If you need **support** with a problem of your installation (e.g. if you have problems getting the webcam to work) or have a general **question**, the issue tracker is not the right place. Consult the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741) instead!
|
||||
- If you are a developer that wants to brainstorm a pull request or possible changes to the plugin system, **add [Brainstorming] to your issue's title!** (see below).
|
||||
- If you have another reason for creating a ticket that doesn't fit any of the above categories, it's something better suited for the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741).
|
||||
## Contents
|
||||
|
||||
Following these guidelines (**especially EVERYTHING mentioned in ["How to file a bug report"](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)**) is necessary so the tickets stay manageable - you are not the only one with an open issue, so please respect that you have to **play by the rules** so that your problem can be taken care of. Tickets not playing by the rules **will be closed without further investigation!**.
|
||||
* [Issues, Tickets, however you may call them](#issues-tickets-however-you-may-call-them)
|
||||
* [How to file a bug report](#how-to-file-a-bug-report)
|
||||
* [What should I do before submitting a bug report?](#what-should-i-do-before-submitting-a-bug-report)
|
||||
* [What should I include in a bug report?](#what-should-i-include-in-a-bug-report)
|
||||
* [Where can I find which version and branch I'm on?](#where-can-i-find-which-version-and-branch-im-on)
|
||||
* [Where can I find those log files you keep talking about?](#where-can-i-find-those-log-files-you-keep-talking-about)
|
||||
* [Where can I find my browser's error console?](#where-can-i-find-my-browsers-error-console)
|
||||
* [Pull requests](#pull-requests)
|
||||
* [What do the branches mean?](#what-do-the-branches-mean)
|
||||
* [How OctoPrint is versioned](#how-octoprint-is-versioned)
|
||||
* [History](#history)
|
||||
* [Footnotes](#footnotes)
|
||||
|
||||
Pull Requests
|
||||
-------------
|
||||
## Issues, Tickets, however you may call them
|
||||
|
||||
1. If you want to add a new feature to OctoPrint, **please always first consider if it wouldn't be better suited for a
|
||||
plugin.** As a general rule of thumb, any feature that is only of interest to a small sub group should be moved into a
|
||||
plugin. If the current plugin system doesn't allow you to implement your feature as a plugin, create a "Brainstorming"
|
||||
ticket to get the discussion going how best to solve *this* in OctoPrint's plugin system - maybe that's the actual PR
|
||||
you have been waiting for to contribute :)
|
||||
2. If you plan to make **any large changes to the code or appearance, please open a "Brainstorming" ticket first** so that
|
||||
we can determine if it's a good time for your specific pull request. It might be that I'm currently in the process of
|
||||
making heavy changes to the code locations you'd target as well, or your approach doesn't fit the general "project
|
||||
vision", and that would just cause unnecessary work and frustration for everyone or possibly get the PR rejected.
|
||||
3. When adding code to OctoPrint, make sure you **follow the current coding style**. That means tabs instead of spaces in the
|
||||
python files (yes, I know that this goes against PEP-8, I don't care) and space instead of tabs in the Javascript sources,
|
||||
english language (that means code, variables, comments!), comments where necessary (tell why the code does something like
|
||||
it does it, structure your code), following the general architecture. If your PR needs to make changes to the Stylesheets,
|
||||
change the ``.less`` files from which the CSS is compiled. PRs that contain direct changes to the compiled
|
||||
CSS will be closed.
|
||||
4. **Test your changes thoroughly**. That also means testing with usage scenarios you don't normally use, e.g. if you only
|
||||
use access control, test without and vice versa. If you only test with your printer, test with the virtual printer and
|
||||
vice versa. State in your pull request how your tested your changes.
|
||||
5. Please create all pull requests **against the `devel` branch**.
|
||||
6. Create **one pull request per feature/bug fix**.
|
||||
7. Create a **custom branch** for your feature/bug fix and use that as base for your pull request. Pull requests directly
|
||||
against your version of `devel` will be closed.
|
||||
7. In your pull request's description, **state what your pull request is doing**, as in, what feature does it implement, what
|
||||
bug does it fix. The more thoroughly you explain your intent behind the PR here, the higher the chances it will get merged
|
||||
fast.
|
||||
Please read the following short instructions fully and follow them. You can
|
||||
help the project tremendously this way: not only do you help the maintainers
|
||||
to **address problems in a timely manner** but also keep it possible for them
|
||||
to **fix bugs, add new and improve on existing functionality** instead of doing
|
||||
nothing but ticket management.
|
||||
|
||||
History
|
||||
-------
|
||||

|
||||
|
||||
* 2015-01-23: More guidelines for creating pull requests, support/questions redirected to Mailinglist/G+ community
|
||||
- **[Read the FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)**
|
||||
- If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report)
|
||||
and *[use the provided template](#what-should-i-include-in-a-ticket)*.
|
||||
You do not need to do anything else with your ticket.
|
||||
- If you want to post a **feature request** or a **documentation request**, add `[Request]`
|
||||
to your issue's title (e.g. `[Request] Awesome new feature`). A question on how to run/change/setup
|
||||
something is **not** what qualifies as a request here, use the
|
||||
[Mailinglist](https://groups.google.com/group/octoprint) or the
|
||||
[Google+ Community](https://plus.google.com/communities/102771308349328485741) for
|
||||
such support issues.
|
||||
- If you are a **developer** that wants to brainstorm a pull request or possible
|
||||
changes to the plugin system, add [Brainstorming] to your issue's title (e.g.
|
||||
`[Brainstorming] New plugin hook for doing some cool stuff`).
|
||||
- If you need **support**, have a **question** or some **other reason** that
|
||||
doesn't fit any of the above categories, the issue tracker is not the right place.
|
||||
Consult the [Mailinglist](https://groups.google.com/group/octoprint) or the
|
||||
[Google+ Community](https://plus.google.com/communities/102771308349328485741) instead.
|
||||
|
||||
No matter what kind of ticket you create, never mix two or more "ticket reasons"
|
||||
into one ticket: One ticket per bug, request, brainstorming thread please.
|
||||
|
||||
----
|
||||
|
||||
**Note**: A bot is in place that monitors new tickets, automatically
|
||||
categorizes them and checks new bug reports for usage of the provided template.
|
||||
That bot will only bother you if you open a ticket that appears to be a bug (no
|
||||
`[Request]` or `[Brainstorming]` in the title) without the template, and it
|
||||
will do that only to ensure that all information needed to solve the issue is
|
||||
available for the maintainers to directly start tackling that problem.
|
||||
|
||||
----
|
||||
|
||||
## How to file a bug report
|
||||
|
||||
If you encounter an issue with OctoPrint, you are welcome to
|
||||
[submit a bug report](https://goo.gl/GzkGv9).
|
||||
|
||||
Before you do that for the first time though please take a moment to read the
|
||||
following section *completely*. Thank you! :)
|
||||
|
||||
### What should I do before submitting a bug report?
|
||||
|
||||
1. **Make sure you are at the right location**. This is the Github repository
|
||||
of the official version of OctoPrint, which is the 3D print server and
|
||||
corresponding web interface itself.
|
||||
|
||||
**This is not the Github respository of OctoPi**, which is the preconfigured
|
||||
Raspberry Pi image including OctoPrint among other things - that one can be found
|
||||
[here](https://github.com/guysoft/OctoPi). Please note that while we do have
|
||||
some entries regarding OctoPi in the FAQ, any bugs should be reported in the
|
||||
[proper bug tracker](https://github.com/guysoft/OctoPi/issues) which - again -
|
||||
is not here.
|
||||
|
||||
**This is also not the Github repository of any OctoPrint Plugins you
|
||||
might have installed**. Report any issues with those in their corresponding
|
||||
bug tracker (probably linked to from the plugin's homepage).
|
||||
|
||||
Finally, **this is also not the right issue tracker if you are running an
|
||||
forked version of OctoPrint**. Seek help for such unofficial versions from
|
||||
the people maintaining them instead.
|
||||
|
||||
2. Please make sure to **test out the current version** of OctoPrint to see
|
||||
whether the problem you are encountering still exists, and **test without
|
||||
any non-bundled plugins enabled** to make sure it's not a misbehaving
|
||||
plugin causing the issue at hand.
|
||||
|
||||
If you are feeling up to it you might also want to try the current development
|
||||
version of OctoPrint (if you aren't already). Refer to the [FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)
|
||||
for information on how to do this.
|
||||
|
||||
3. The problem still exists? Then please **look through the
|
||||
[existing tickets](https://github.com/foosel/OctoPrint/issues?state=open)
|
||||
(use the [search](https://github.com/foosel/OctoPrint/search?q=&ref=cmdform&type=Issues))**
|
||||
to check if there already exists a report of the issue you are encountering.
|
||||
Sorting through duplicates of the same issue sometimes causes more work than
|
||||
fixing it. Take the time to filter through possible duplicates and be really
|
||||
sure that your problem definitely is a new one. Try more than one search query
|
||||
(e.g. do not only search for "webcam" if you happen to run into an issue
|
||||
with your webcam, also search for "timelapse" etc). Do not only read the subject lines
|
||||
of tickets that look like they might be related, but also read the ticket itself!
|
||||
|
||||
**Very important:** Please make absolutely sure that if you find a bug that looks like
|
||||
it is the same as your's, it actually behaves the same as your's. E.g. if someone gives steps
|
||||
to reproduce his bug that looks like your's, reproduce the bug like that if possible,
|
||||
and only add a "me too" if you actually can reproduce the same
|
||||
issue. Also **provide all information** as [described below](#what-should-i-include-in-a-bug-report)
|
||||
and whatever was additionally requested over the course of the ticket
|
||||
even if you "only" add to an existing ticket. The more information available regarding a bug, the higher
|
||||
the chances of reproducing and solving it. But "me too" on an actually unrelated ticket
|
||||
makes it more difficult due to on top of having to figure out the original problem
|
||||
there's now also a [red herring](https://en.wikipedia.org/wiki/Red_herring) interfering - so please be
|
||||
very diligent here!
|
||||
|
||||
### What should I include in a bug report?
|
||||
|
||||
Always use the following template (you can remove what's within `[...]`, that's
|
||||
only provided here as some additional information for you), **even if only adding a
|
||||
"me too" to an existing ticket**:
|
||||
|
||||
#### What were you doing?
|
||||
|
||||
[Please be as specific as possible here. The maintainers will need to reproduce
|
||||
your issue in order to fix it and that is not possible if they don't know
|
||||
what you did to get it to happen in the first place. If you encountered
|
||||
a problem with specific files of any sorts, make sure to also include a link to a file
|
||||
with which to reproduce the problem.]
|
||||
|
||||
#### What did you expect to happen?
|
||||
|
||||
#### What happened instead?
|
||||
|
||||
#### Branch & Commit or Version of OctoPrint
|
||||
|
||||
[Can be found in the lower left corner of the web interface.]
|
||||
|
||||
#### Printer model & used firmware incl. version
|
||||
|
||||
[If applicable, always include if unsure.]
|
||||
|
||||
#### Browser and Version of Browser, Operating System running Browser
|
||||
|
||||
[If applicable, always include if unsure.]
|
||||
|
||||
#### Link to octoprint.log
|
||||
|
||||
[On gist.github.com or pastebin.com. Always include and never truncate.]
|
||||
|
||||
#### Link to contents of terminal tab or serial.log
|
||||
|
||||
[On gist.github.com or pastebin.com. If applicable, always include if unsure or
|
||||
reporting communication issues. Never truncate.]
|
||||
|
||||
#### Link to contents of Javascript console in the browser
|
||||
|
||||
[On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
|
||||
always include if unsure or reporting UI issues.]
|
||||
|
||||
#### Screenshot(s) showing the problem:
|
||||
|
||||
[If applicable. Always include if unsure or reporting UI issues.]
|
||||
|
||||
I have read the FAQ.
|
||||
|
||||
Copy-paste this template **completely**. Do not skip any lines!
|
||||
|
||||
### Where can I find which version and branch I'm on?
|
||||
|
||||
You can find out all of them by taking a look into the lower left corner of the
|
||||
OctoPrint UI:
|
||||
|
||||

|
||||
|
||||
If you don't have access to the UI you can find out that information via the
|
||||
command line as well. Either `octoprint --version` or `python setup.py version`
|
||||
in OctoPrint's folder will tell you the version of OctoPrint you are running
|
||||
(note: if it doesn't then you are running a version older than 1.1.0,
|
||||
*upgrade now*). A `git branch` in your OctoPrint installation folder will mark
|
||||
the branch you are on with a little *. `git rev-parse HEAD` will tell you the
|
||||
current commit.
|
||||
|
||||
### Where can I find those log files you keep talking about?
|
||||
|
||||
OctoPrint by default provides two log outputs, a third one can be enabled if
|
||||
more information is needed.
|
||||
|
||||
One is contained in the **"Terminal" tab** within OctoPrint's UI and is a log
|
||||
of the last 300 lines of communication with the printer. Please copy-paste
|
||||
this somewhere (disable auto scroll to make copying the contents easier) -
|
||||
e.g. http://pastebin.com or http://gist.github.com - and include a link in
|
||||
your bug report.
|
||||
|
||||
There is also **OctoPrint's application log file** or in short `octoprint.log`,
|
||||
which is by default located at `~/.octoprint/logs/octoprint.log` on Linux,
|
||||
`%APPDATA%\OctoPrint\logs\octoprint.log` on Windows and
|
||||
`~/Library/Application Support/OctoPrint/logs/octoprint.log` on MacOS. Please
|
||||
copy-paste this to pastebin or gist as well and include a link in your bug
|
||||
report.
|
||||
|
||||
It might happen that you are asked to provide a more **thorough log of the
|
||||
communication with the printer** if you haven't already done so, the `serial.log`.
|
||||
This is not written by default due to performance reasons, but you can enable
|
||||
it in the settings dialog. After enabling that log, please reproduce the problem
|
||||
again (connect to the printer, do whatever triggers it), then copy-paste
|
||||
`~/.octoprint/logs/serial.log` (Windows: `%APPDATA%\OctoPrint\logs\serial.log`,
|
||||
MacOS: `~/Library/Application Support/OctoPrint/logs/serial.log`) to pastebin
|
||||
or gist and include the link in the bug report.
|
||||
|
||||
You might also be asked to provide a log with an increased log level. You can
|
||||
find information on how to do just that in the
|
||||
[docs](http://docs.octoprint.org/en/master/configuration/logging_yaml.html).
|
||||
|
||||
### Where can I find my browser's error console?
|
||||
|
||||
See [How to open the Javascript Console in different browsers](https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers)
|
||||
|
||||
## Pull requests
|
||||
|
||||
1. If you want to add a new feature to OctoPrint, **please always first
|
||||
consider if it wouldn't be better suited for a plugin.** As a general rule
|
||||
of thumb, any feature that is only of interest to a small sub group should
|
||||
be moved into a plugin. If the current plugin system doesn't allow you to
|
||||
implement your feature as a plugin, create a "Brainstorming" ticket to get
|
||||
the discussion going on how best to solve *this* in OctoPrint's plugin
|
||||
system - maybe that's the actual PR you have been waiting for to contribute :)
|
||||
2. If you plan to make **any large or otherwise disruptive changes to the
|
||||
code or appearance, please open a "Brainstorming" ticket first** so
|
||||
that we can determine if it's a good time for your specific pull
|
||||
request. It might be that we're currently in the process of making
|
||||
heavy changes to the code locations you'd target as well, or your
|
||||
approach doesn't fit the general "project vision", and that would
|
||||
just cause unnecessary work and frustration for everyone or
|
||||
possibly get the PR rejected.
|
||||
3. Create your pull request **from a custom branch** on your end (e.g.
|
||||
`dev/myNewFeature`)[1] **against the `devel` branch**. Create **one pull request
|
||||
per feature/bug fix**. If your PR contains an important bug fix, we will
|
||||
make sure to backport it to the `maintenance` branch to also include it in
|
||||
the next release.
|
||||
4. Make sure there are **only relevant changes** included in your PR. No
|
||||
changes to unrelated files, no additional files that don't belong (e.g.
|
||||
commits of your full virtual environment). Make sure your PR consists
|
||||
**ideally of only one commit** (use git's rebase and squash functionality).
|
||||
5. Make sure you **follow the current coding style**. This means:
|
||||
* Tabs instead of spaces in the Python files[2]
|
||||
* Spaces instead of tabs in the Javascript sources
|
||||
* English language (code, variables, comments, ...)
|
||||
* Comments where necessary: Tell *why* the code does something like it does
|
||||
it, structure your code
|
||||
* Following the general architecture
|
||||
* If your PR needs to make changes to the Stylesheets, change the
|
||||
``.less`` files from which the CSS is compiled.
|
||||
* Make sure you do not add dead code (e.g. commented out left-overs
|
||||
from experiments).
|
||||
6. Ensure your changes **pass the existing unit tests**. PRs that break
|
||||
those cannot be accepted.
|
||||
7. **Test your changes thoroughly**. That also means testing with usage
|
||||
scenarios you don't normally use, e.g. if you only use access control, test
|
||||
without and vice versa. If you only test with your printer, test with the
|
||||
virtual printer and vice versa. State in your pull request how your tested
|
||||
your changes. Ideally **add unit tests** - OctoPrint severly lacks in that
|
||||
department, but we are trying to change that, so any new code already covered
|
||||
with a test suite helps a lot!
|
||||
8. In your pull request's description, **state what your pull request does**,
|
||||
as in, what feature does it implement, what bug does it fix. The more
|
||||
thoroughly you explain your intent behind the PR here, the higher the
|
||||
chances it will get merged fast. There is a template provided below
|
||||
that can help you here.
|
||||
9. Don't forget to **add yourself to the [AUTHORS](./AUTHORS.md)
|
||||
file** :)
|
||||
|
||||
Template to use for Pull Request descriptions:
|
||||
|
||||
```
|
||||
#### What does this PR do and why is it necessary?
|
||||
|
||||
#### How was it tested? How can it be tested by the reviewer?
|
||||
|
||||
#### Any background context you want to provide?
|
||||
|
||||
#### What are the relevant tickets if any?
|
||||
|
||||
#### Screenshots (if appropriate)
|
||||
|
||||
#### Further notes
|
||||
```
|
||||
|
||||
## What do the branches mean?
|
||||
|
||||
There are three main branches in OctoPrint:
|
||||
|
||||
* `master`: The master branch always contains the current stable release. It
|
||||
is *only* updated on new releases. Will have a version number following
|
||||
the scheme `x.y.z` (e.g. `1.2.9`) or - if it's absolutely necessary to
|
||||
add a commit after release to this branch - `x.y.z.post<commits since x.y.z>`
|
||||
(e.g. `1.2.9.post1`).
|
||||
* `maintenance`: Improvements and fixes of the current release that make up
|
||||
the next release go here. More or less continously updated. You can consider
|
||||
this a preview of the next release version. It should be very stable at all
|
||||
times. Anything you spot in here helps tremendously with getting a rock solid
|
||||
next stable release, so if you want to help out development, running the
|
||||
`maintenance` branch and reporting back anything you find is a very good way
|
||||
to do that. Will usually have a version number following the scheme
|
||||
`x.y.z+1.dev.<commits since increase of z>` for an OctoPrint version of `x.y.z`
|
||||
(e.g. `1.2.10.dev12`).
|
||||
* `devel`: Ongoing development of new features that will go into the next bigger
|
||||
release (MINOR version number increases) will happen on this branch. Usually
|
||||
kept stable, sometimes stuff can break though or lose backwards compatibility
|
||||
temporarily. Can be considered the "bleeding edge". All PRs should target
|
||||
*this* branch. Important improvements and fixes from PRs here are backported to
|
||||
`maintenance` as needed. Will usually have a version number following the
|
||||
scheme `x.y+1.0.dev<commits since increase of y>` for an OctoPrint version
|
||||
of `x.y.z` (e.g. `1.3.0.dev123`).
|
||||
|
||||
Additionally, from time to time you might see other branches pop up in the repository.
|
||||
Those usually have one of the following prefixes:
|
||||
|
||||
* `fix/...`: Fixes under development that are to be merged into the `maintenance`
|
||||
and `devel` branches.
|
||||
* `improve/...`: Improvements under development that are to be merged into the
|
||||
`maintenance` and `devel` branches.
|
||||
* `dev/...` or `feature/...`: New functionality under development that is to be merged
|
||||
into the `devel` branch.
|
||||
|
||||
There is also the `gh-pages` branch, which holds OctoPrint's web page, and a couple of
|
||||
older development branches that are slowly being migrated or deleted.
|
||||
|
||||
## How OctoPrint is versioned
|
||||
|
||||
OctoPrint follows the [semantic versioning scheme](http://semver.org/) of **MAJOR.MINOR.PATCH**.
|
||||
|
||||
The **PATCH** version number is the one increasing most often due to OctoPrint's maintenance releases.
|
||||
Releases that only change the patch number indicate that they contain bug fixes and small improvements
|
||||
of existing functionality. Example: 1.2.8 to 1.2.9.
|
||||
|
||||
The **MINOR** version number increases with releases that add a lot of new functionality and
|
||||
large features. Example: 1.2.x to 1.3.0.
|
||||
|
||||
Finally, the **MAJOR** version number increases if there are breaking API changes that concern any of the
|
||||
documented interfaces (REST API, plugin interfaces, ...). So far this hasn't happened. Example: 1.x.y to 2.0.0.
|
||||
|
||||
OctoPrint's version numbers are automatically generated using [versioneer](https://github.com/warner/python-versioneer)
|
||||
and depend on the selected git branch, nearest git tag and commits. The generated version number
|
||||
should always be [PEP440](https://www.python.org/dev/peps/pep-0440/) compatible. Unless a git tag
|
||||
is used for version number determination, the version number will also contain the git hash within
|
||||
the local version identifier to allow for an exact determination of the active code base
|
||||
(e.g. `1.2.9.dev68+g46c7a9c`). Additionally, instances with active uncommitted changes will contain
|
||||
`.dirty` in the local version identifier.
|
||||
|
||||
## History
|
||||
|
||||
* 2015-01-23: More guidelines for creating pull requests, support/questions
|
||||
redirected to Mailinglist/G+ community
|
||||
* 2015-01-27: Added another explicit link to the FAQ
|
||||
* 2015-07-07: Added step to add yourself to AUTHORS when creating a PR :)
|
||||
* 2015-12-01: Heavily reworked to include examples, better structure and
|
||||
all information in one document.
|
||||
* 2016-02-10: Added information about branch structure and versioning.
|
||||
* 2016-02-16: Added requirement to add information from template to existing
|
||||
tickets as well, explained issue with "me too" red herrings.
|
||||
* 2016-03-14: Some more requirements for PRs, and a PR template.
|
||||
|
||||
## Footnotes
|
||||
* [1] - If you are wondering why, the problem is that anything that you add
|
||||
to your PR's branch will also become part of your PR, so if you create a
|
||||
PR from your version of `devel` chances are high you'll add changes to the
|
||||
PR that do not belong to the PR.
|
||||
* [2] - Yes, we know that this goes against PEP-8. OctoPrint started out as
|
||||
a fork of Cura and hence stuck to the coding style found therein. Changing
|
||||
it now would make the history and especially `git blame` completely
|
||||
unusable, so for now we'll have to deal with it (this decision might be
|
||||
revisited in the future).
|
||||
@@ -1,26 +1,68 @@
|
||||
OctoPrint
|
||||
=========
|
||||
|
||||
[](https://flattr.com/submit/auto?user_id=foosel&url=https://github.com/foosel/OctoPrint&title=OctoPrint&language=&tags=github&category=software)
|
||||
|
||||
OctoPrint provides a responsive web interface for controlling a 3D printer (RepRap, Ultimaker, ...). It is Free Software
|
||||
OctoPrint provides a snappy web interface for controlling a 3D printer (RepRap, Ultimaker, ...). It is Free Software
|
||||
and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html).
|
||||
|
||||
Its website can be found at [octoprint.org](http://octoprint.org).
|
||||
|
||||
The documentation is located at [docs.octoprint.org](http://docs.octoprint.org).
|
||||
|
||||
The official plugin repository can be reached at [plugins.octoprint.org](http://plugins.octoprint.org).
|
||||
|
||||

|
||||
|
||||
You are currently looking at the source code repository of OctoPrint. If you already installed it
|
||||
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
|
||||
want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki)
|
||||
might be of more interest for you. You might also want to subscribe to [the mailing list](https://groups.google.com/group/octoprint)
|
||||
or the [G+ Community](https://plus.google.com/communities/102771308349328485741) where there are other active users who might be
|
||||
able to help you with any questions you might have.
|
||||
|
||||
Contributing
|
||||
------------
|
||||
|
||||
Please see the project's [Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md).
|
||||
Contributions of all kinds are welcome, not only in the form of code but also with regards to the
|
||||
[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), support
|
||||
of other users in the [bug tracker](https://github.com/foosel/OctoPrint/issues),
|
||||
[the Mailinglist](https://groups.google.com/group/octoprint) or
|
||||
[the G+ Community](https://plus.google.com/communities/102771308349328485741).
|
||||
|
||||
If you think something is bad as it is about OctoPrint or its documentation the way it is, please help
|
||||
in any way to make it better instead of just complaining about it -- this is an Open Source Project
|
||||
after all :)
|
||||
|
||||
For information about how to go about contributions of any kind, please see the project's
|
||||
[Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md).
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
Installation instructions for installing from source for different operating systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
|
||||
Installation instructions for installing from source for different operating
|
||||
systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides).
|
||||
|
||||
If you want to run OctoPrint on a Raspberry Pi you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi)
|
||||
which is a custom SD card image that includes OctoPrint plus dependencies.
|
||||
|
||||
The generic steps that should basically be done regardless of operating system
|
||||
and runtime environment are the following (as *regular
|
||||
user*, please keep your hands *off* of the `sudo` command here!) - this assumes
|
||||
you already have Python 2.7, pip and virtualenv set up on your system:
|
||||
|
||||
1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git`
|
||||
2. Change into the OctoPrint folder: `cd OctoPrint`
|
||||
3. Create a user-owned virtual environment therein: `virtualenv venv`
|
||||
4. Install OctoPrint *into that virtual environment*: `./venv/bin/python setup.py install`
|
||||
|
||||
You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage)
|
||||
for details.
|
||||
|
||||
After installation, please make sure you follow the first-run wizard and set up
|
||||
access control as necessary. If you want to not only be notified about new
|
||||
releases but also be able to automatically upgrade to them from within
|
||||
OctoPrint, take a look [at the documentation of the Software Update Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update#making-octoprint-updateable-on-existing-installations)
|
||||
and at its settings.
|
||||
|
||||
Dependencies
|
||||
------------
|
||||
|
||||
@@ -36,7 +78,11 @@ OctoPrint currently only supports Python 2.7.
|
||||
Usage
|
||||
-----
|
||||
|
||||
Running the `setup.py` script installs the `octoprint` script in your Python installation's scripts folder
|
||||
Running the `setup.py` script via
|
||||
|
||||
python setup.py install
|
||||
|
||||
installs the `octoprint` script in your Python installation's scripts folder
|
||||
(which depending on whether you installed OctoPrint globally or into a virtual env will be on your `PATH` or not). The
|
||||
following usage examples assume that said `octoprint` script is on your `PATH`.
|
||||
|
||||
@@ -77,5 +123,13 @@ which is located at `~/.octoprint` on Linux, at `%APPDATA%/OctoPrint` on Windows
|
||||
at `~/Library/Application Support/OctoPrint` on MacOS.
|
||||
|
||||
A comprehensive overview of all available configuration settings can be found
|
||||
[on the wiki](https://github.com/foosel/OctoPrint/wiki/Configuration). Please note that the most commonly used
|
||||
configuration settings can also easily be edited from OctoPrint's settings dialog.
|
||||
[in the docs](http://docs.octoprint.org/en/master/configuration/config_yaml.html).
|
||||
Please note that the most commonly used configuration settings can also easily
|
||||
be edited from OctoPrint's settings dialog.
|
||||
|
||||
Special Thanks
|
||||
--------------
|
||||
|
||||
The development of OctoPrint is sponsored and maintained by [BQ](http://www.bq.com/).
|
||||
Cross-browser testing services are kindly provided by [BrowserStack](http://www.browserstack.com/).
|
||||
Profiling is done with the help of [PyVmMonitor](http://www.pyvmmonitor.com).
|
||||
+4
-4
@@ -37,7 +37,7 @@ Issue a job command
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
POST /api/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
@@ -54,7 +54,7 @@ Issue a job command
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
POST /api/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
@@ -71,7 +71,7 @@ Issue a job command
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
POST /api/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
@@ -88,7 +88,7 @@ Issue a job command
|
||||
|
||||
.. sourcecode:: http
|
||||
|
||||
POST /api/control/job HTTP/1.1
|
||||
POST /api/job HTTP/1.1
|
||||
Host: example.com
|
||||
Content-Type: application/json
|
||||
X-Api-Key: abcdef...
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ Log file management
|
||||
Retrieve a list of available log files
|
||||
======================================
|
||||
|
||||
.. http:post:: /api/logs
|
||||
.. http:get:: /api/logs
|
||||
|
||||
Retrieve information regarding all log files currently available and regarding the disk space still available
|
||||
in the system on the location the log files are being stored.
|
||||
|
||||
+15
-5
@@ -25,7 +25,8 @@ Tool
|
||||
See :ref:`sec-api-printer-toolcommand`.
|
||||
Bed
|
||||
Bed commands allow setting the temperature and temperature offset for the printer's heated bed. Querying the
|
||||
corresponding resource returns temperature information including an optional history.
|
||||
corresponding resource returns temperature information including an optional history. Note that Bed commands
|
||||
are only available if the currently selected printer profile has a heated bed.
|
||||
See :ref:`sec-api-printer-bedcommand`.
|
||||
SD card
|
||||
SD commands allow initialization, refresh and release of the printer's SD card (if available). Querying the
|
||||
@@ -564,6 +565,9 @@ Issue a bed command
|
||||
|
||||
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
|
||||
|
||||
If no heated bed is configured for the currently selected printer profile, the resource will return
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
**Example Target Temperature Request**
|
||||
|
||||
Set the target temperature for the printer's heated bed to 75°C.
|
||||
@@ -610,7 +614,8 @@ Issue a bed command
|
||||
:statuscode 204: No error
|
||||
:statuscode 400: If ``target`` or ``offset`` is not a valid number or outside of the supported range, or if the
|
||||
request is otherwise invalid.
|
||||
:statuscode 409: If the printer is not operational.
|
||||
:statuscode 409: If the printer is not operational or the selected printer profile
|
||||
does not have a heated bed.
|
||||
|
||||
.. _sec-api-printer-bedstate:
|
||||
|
||||
@@ -627,6 +632,9 @@ Retrieve the current bed state
|
||||
|
||||
Returns a :http:statuscode:`200` with a Temperature Response in the body upon success.
|
||||
|
||||
If no heated bed is configured for the currently selected printer profile, the resource will return
|
||||
an :http:statuscode:`409`.
|
||||
|
||||
.. note::
|
||||
If you want both tool and bed temperature information at the same time, take a look at
|
||||
:ref:`Retrieve the current printer state <sec-api-printer-state>`.
|
||||
@@ -675,7 +683,8 @@ Retrieve the current bed state
|
||||
:query limit: If set to an integer (``n``), only the last ``n`` data points from the printer's temperature history
|
||||
will be returned. Will be ignored if ``history`` is not enabled.
|
||||
:statuscode 200: No error
|
||||
:statuscode 409: If the printer is not operational.
|
||||
:statuscode 409: If the printer is not operational or the selected printer profile
|
||||
does not have a heated bed.
|
||||
|
||||
.. _sec-api-printer-sdcommand:
|
||||
|
||||
@@ -856,7 +865,7 @@ Send an arbitrary command to the printer
|
||||
.. sourcecode:: http
|
||||
|
||||
HTTP/1.1 204 No Content
|
||||
|
||||
|
||||
:json string command: Single command to send to the printer, mutually exclusive with ``commands``.
|
||||
:json string commands: List of commands to send to the printer, mutually exclusive with ``command``.
|
||||
:statuscode 204: No error
|
||||
@@ -913,7 +922,8 @@ Temperature State
|
||||
* - ``bed``
|
||||
- 0..1
|
||||
- :ref:`Temperature Data <sec-api-datamodel-printer-tempdata>`
|
||||
- Current temperature stats for the printer's heated bed. Not included if querying only tool state.
|
||||
- Current temperature stats for the printer's heated bed. Not included if querying only tool state or if
|
||||
the currently selected printer profile does not have a heated bed.
|
||||
* - ``history``
|
||||
- 0..1
|
||||
- List of :ref:`Historic Temperature Datapoint <sec-api-datamodel-printer-temphistory>`
|
||||
|
||||
+19
-1
@@ -12,7 +12,7 @@ Push updates
|
||||
|
||||
.. contents::
|
||||
|
||||
To enable real time information exchange between client and server, OctoPrint uses
|
||||
To enable real time information exchange between client and server, OctoPrint uses
|
||||
`SockJS <https://github.com/sockjs/sockjs-protocol>`_ to push
|
||||
status updates, temperature changes etc to connected web interface instances.
|
||||
|
||||
@@ -43,6 +43,24 @@ Clients must ignore any unknown messages.
|
||||
|
||||
The data model of the attached payloads is described further below.
|
||||
|
||||
OctoPrint's SockJS socket also accepts one command from the client to the server,
|
||||
the ``throttle`` command. Usually, OctoPrint will push the general state update
|
||||
in the ``current`` message twice per second. For some clients that might still
|
||||
be too fast, so they can signal a different factor to OctoPrint utilizing the
|
||||
``throttle`` message. OctoPrint expects a single integer here which represents
|
||||
the multiplier for the base rate limit of one message every 500ms. A value of
|
||||
1 hence will produce the default behaviour of getting every update. A value of
|
||||
2 will set the rate limit to maximally one message every 1s, 3 to maximally one
|
||||
message every 1.5s and so on.
|
||||
|
||||
Example for a ``throttle`` client-server-message:
|
||||
|
||||
.. sourcecode:: javascript
|
||||
|
||||
{
|
||||
"throttle": 2
|
||||
}
|
||||
|
||||
.. _sec-api-push-datamodel:
|
||||
|
||||
Datamodel
|
||||
|
||||
@@ -611,6 +611,27 @@ Use the following settings to configure the serial connection to the printer:
|
||||
additionalPorts:
|
||||
- /dev/myPrinterSymlink
|
||||
|
||||
# Commands which are known to take a long time to be acknowledged by the firmware. E.g.
|
||||
# homing, dwelling, auto leveling etc. Defaults to the below commands.
|
||||
longRunningCommands:
|
||||
- G4
|
||||
- G28
|
||||
- G29
|
||||
- G30
|
||||
- G32
|
||||
- M400
|
||||
- M226
|
||||
|
||||
# Commands which need to always be send with a checksum. Defaults to only M110
|
||||
checksumRequiringCommands:
|
||||
- M110
|
||||
|
||||
# Command to send in order to initiate a handshake with the printer.
|
||||
# Defaults to "M110 N0" which simply resets the line numbers in the firmware and which
|
||||
# should be acknowledged with a simple "ok".
|
||||
helloCommand:
|
||||
- M110 N0
|
||||
|
||||
.. _sec-configuration-config_yaml-server:
|
||||
|
||||
Server
|
||||
@@ -621,7 +642,8 @@ Use the following settings to configure the server:
|
||||
.. code-block:: yaml
|
||||
|
||||
server:
|
||||
# Use this option to define the host to which to bind the server, defaults to "0.0.0.0" (= all interfaces)
|
||||
# Use this option to define the host to which to bind the server, defaults to "0.0.0.0" (= all
|
||||
# interfaces)
|
||||
host: 0.0.0.0
|
||||
|
||||
# Use this option to define the port to which to bind the server, defaults to 5000
|
||||
@@ -691,6 +713,18 @@ Use the following settings to configure the server:
|
||||
# Maximum size of requests other than file uploads in bytes, defaults to 100KB.
|
||||
maxSize: 102400
|
||||
|
||||
# Commands to restart/shutdown octoprint or the system it's running on
|
||||
commands:
|
||||
|
||||
# Command to restart OctoPrint, defaults to being unset
|
||||
serverRestartCommand: sudo service octoprint restart
|
||||
|
||||
# Command to restart the system OctoPrint is running on, defaults to being unset
|
||||
systemRestartCommand: sudo shutdown -r now
|
||||
|
||||
# Command to shut down the system OctoPrint is running on, defaults to being unset
|
||||
systemShutdownCommand: sudo shutdown -h now
|
||||
|
||||
|
||||
.. note::
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ Changing log levels
|
||||
If you need to change the default logging level within OctoPrint, create the file with a text editor of your choice
|
||||
(it's usually not there). The general format is this::
|
||||
|
||||
logger:
|
||||
loggers:
|
||||
<component>:
|
||||
level: <loglevel>
|
||||
|
||||
@@ -27,7 +27,7 @@ new log level to set. An example for increasing the log level of the events and
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
logger:
|
||||
loggers:
|
||||
octoprint.events:
|
||||
level: DEBUG
|
||||
octoprint.filemanager:
|
||||
@@ -97,4 +97,4 @@ expressed in YAML as follows:
|
||||
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
|
||||
The possible keys for the logging format can be found in the
|
||||
`Python documentation on LogRecord attributes <https://docs.python.org/2/library/logging.html#logrecord-attributes>`_.
|
||||
`Python documentation on LogRecord attributes <https://docs.python.org/2/library/logging.html#logrecord-attributes>`_.
|
||||
@@ -65,7 +65,7 @@ a GCODE script including user input.
|
||||
children:
|
||||
- name: Get Position
|
||||
command: M114
|
||||
regex: "X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)"
|
||||
regex: "X:([-+]?[0-9.]+) Y:([-+]?[0-9.]+) Z:([-+]?[0-9.]+) E:([-+]?[0-9.]+)"
|
||||
template: "Position: X={0}, Y={1}, Z={2}, E={3}"
|
||||
- name: Fun stuff
|
||||
children:
|
||||
|
||||
@@ -86,7 +86,7 @@ Out of the box, OctoPrint defaults to the following script setup for ``afterPrin
|
||||
|
||||
;disable all heaters
|
||||
{% snippet 'disable_hotends' %}
|
||||
M140 S0
|
||||
[% snippet 'disable_bed' %}
|
||||
|
||||
;disable fan
|
||||
M106 S0
|
||||
@@ -100,8 +100,19 @@ The ``disable_hotends`` snippet is defined as follows:
|
||||
M104 T{{ tool }} S0
|
||||
{% endfor %}
|
||||
|
||||
As you can see, the ``disable_hotends`` snippet utilizes the ``printer_profile`` context variable in order to
|
||||
iterate through all available extruders and set their temperature to 0.
|
||||
The ``disable_bed`` snippet is defined as follows:
|
||||
|
||||
.. code-block:: jinja
|
||||
:caption: Default ``disable_bed`` snippet
|
||||
|
||||
{% if printer_profile.heatedBed %}
|
||||
M140 S0
|
||||
{% endif %}
|
||||
|
||||
As you can see, the ``disable_hotends`` and ``disable_bed`` snippets utilize the
|
||||
``printer_profile`` context variable in order to iterate through all available
|
||||
extruders and set their temperature to 0, and to also set the bed temperature
|
||||
to 0 if a heated bed is configured.
|
||||
|
||||
.. seealso::
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
[metadata]
|
||||
description-file = README.md
|
||||
|
||||
[versioneer]
|
||||
VCS = git
|
||||
style = pep440-post
|
||||
versionfile_source = src/octoprint/_version.py
|
||||
versionfile_build = octoprint/_version.py
|
||||
tag_prefix =
|
||||
parentdir_prefix =
|
||||
lookupfile = .versioneer-lookup
|
||||
@@ -16,22 +16,24 @@ INSTALL_REQUIRES = [
|
||||
"flask>=0.9,<0.11",
|
||||
"werkzeug==0.8.3",
|
||||
"tornado==4.0.1",
|
||||
"sockjs-tornado>=1.0.0",
|
||||
"sockjs-tornado==1.0.1",
|
||||
"PyYAML==3.10",
|
||||
"Flask-Login==0.2.2",
|
||||
"Flask-Principal==0.3.5",
|
||||
"Flask-Babel==0.9",
|
||||
"Flask-Assets==0.10",
|
||||
"pyserial",
|
||||
"netaddr",
|
||||
"watchdog",
|
||||
"sarge>=0.1.4",
|
||||
"netifaces",
|
||||
"pylru",
|
||||
"rsa",
|
||||
"pkginfo",
|
||||
"requests",
|
||||
"semantic_version"
|
||||
"pyserial==2.7",
|
||||
"netaddr==0.7.17",
|
||||
"watchdog==0.8.3",
|
||||
"sarge==0.1.4",
|
||||
"netifaces==0.10",
|
||||
"pylru==1.0.9",
|
||||
"rsa==3.2",
|
||||
"pkginfo==1.2.1",
|
||||
"requests==2.7.0",
|
||||
"semantic_version==2.4.2",
|
||||
"psutil==3.2.1",
|
||||
"awesome-slugify>=1.6.5,<1.7"
|
||||
]
|
||||
|
||||
# Additional requirements for optional install options
|
||||
@@ -46,7 +48,10 @@ EXTRA_REQUIRES = dict(
|
||||
# Documentation dependencies
|
||||
"sphinx>=1.3",
|
||||
"sphinxcontrib-httpdomain",
|
||||
"sphinx_rtd_theme"
|
||||
"sphinx_rtd_theme",
|
||||
|
||||
# PyPi upload related
|
||||
"pypandoc"
|
||||
],
|
||||
|
||||
# Dependencies for developing OctoPrint plugins
|
||||
@@ -55,17 +60,12 @@ EXTRA_REQUIRES = dict(
|
||||
]
|
||||
)
|
||||
|
||||
# Additional requirements for setup
|
||||
SETUP_REQUIRES = []
|
||||
|
||||
# Dependency links for any of the aforementioned dependencies
|
||||
DEPENDENCY_LINKS = []
|
||||
|
||||
# Versioneer configuration
|
||||
versioneer.VCS = 'git'
|
||||
versioneer.versionfile_source = 'src/octoprint/_version.py'
|
||||
versioneer.versionfile_build = 'octoprint/_version.py'
|
||||
versioneer.tag_prefix = ''
|
||||
versioneer.parentdir_prefix = ''
|
||||
versioneer.lookupfile = '.versioneer-lookup'
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------------------------
|
||||
# Anything below here is just command setup and general setup configuration
|
||||
|
||||
@@ -89,8 +89,22 @@ def params():
|
||||
version = versioneer.get_version()
|
||||
cmdclass = get_cmdclass()
|
||||
|
||||
description = "A responsive web interface for 3D printers"
|
||||
description = "A snappy web interface for 3D printers"
|
||||
long_description = open("README.md").read()
|
||||
|
||||
install_requires = INSTALL_REQUIRES
|
||||
extras_require = EXTRA_REQUIRES
|
||||
dependency_links = DEPENDENCY_LINKS
|
||||
setup_requires = SETUP_REQUIRES
|
||||
|
||||
try:
|
||||
import pypandoc
|
||||
setup_requires += ["setuptools-markdown"]
|
||||
long_description_markdown_filename = "README.md"
|
||||
del pypandoc
|
||||
except:
|
||||
pass
|
||||
|
||||
classifiers = [
|
||||
"Development Status :: 4 - Beta",
|
||||
"Environment :: Web Environment",
|
||||
@@ -125,9 +139,6 @@ def params():
|
||||
|
||||
include_package_data = True
|
||||
zip_safe = False
|
||||
install_requires = INSTALL_REQUIRES
|
||||
extras_require = EXTRA_REQUIRES
|
||||
dependency_links = DEPENDENCY_LINKS
|
||||
|
||||
if os.environ.get('READTHEDOCS', None) == 'True':
|
||||
# we can't tell read the docs to please perform a pip install -e .[develop], so we help
|
||||
|
||||
+539
-157
@@ -1,28 +1,81 @@
|
||||
|
||||
# This file helps to compute a version number in source trees obtained from
|
||||
# git-archive tarball (such as those provided by githubs download-from-tag
|
||||
# feature). Distribution tarballs (build by setup.py sdist) and build
|
||||
# feature). Distribution tarballs (built by setup.py sdist) and build
|
||||
# directories (produced by setup.py build) will contain a much shorter file
|
||||
# that just contains the computed version number.
|
||||
|
||||
# This file is released into the public domain. Generated by
|
||||
# versioneer-0.10 (https://github.com/warner/python-versioneer)
|
||||
|
||||
# these strings will be replaced by git during git-archive
|
||||
git_refnames = "$Format:%d$"
|
||||
git_full = "$Format:%H$"
|
||||
# versioneer-0.15+dev (https://github.com/warner/python-versioneer)
|
||||
|
||||
"""Git implementation of _version.py."""
|
||||
|
||||
import errno
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import errno
|
||||
|
||||
|
||||
def get_keywords():
|
||||
"""Get the keywords needed to look up the version information."""
|
||||
# these strings will be replaced by git during git-archive.
|
||||
# setup.py/versioneer.py will grep for the variable names, so they must
|
||||
# each be defined on a line of their own. _version.py will just call
|
||||
# get_keywords().
|
||||
git_refnames = "$Format:%d$"
|
||||
git_full = "$Format:%H$"
|
||||
keywords = {"refnames": git_refnames, "full": git_full}
|
||||
return keywords
|
||||
|
||||
|
||||
class VersioneerConfig:
|
||||
|
||||
"""Container for Versioneer configuration parameters."""
|
||||
|
||||
|
||||
def get_config():
|
||||
"""Create, populate and return the VersioneerConfig() object."""
|
||||
# these strings are filled in when 'setup.py versioneer' creates
|
||||
# _version.py
|
||||
cfg = VersioneerConfig()
|
||||
cfg.VCS = "git"
|
||||
cfg.style = "pep440"
|
||||
cfg.tag_prefix = ""
|
||||
cfg.parentdir_prefix = ""
|
||||
cfg.versionfile_source = "src/octoprint/_version.py"
|
||||
cfg.lookupfile = None
|
||||
cfg.verbose = False
|
||||
return cfg
|
||||
|
||||
|
||||
class NotThisMethod(Exception):
|
||||
|
||||
"""Exception raised if a method is not valid for the current scenario."""
|
||||
|
||||
|
||||
LONG_VERSION_PY = {}
|
||||
HANDLERS = {}
|
||||
|
||||
|
||||
def register_vcs_handler(vcs, method): # decorator
|
||||
"""Decorator to mark a method as the handler for a particular VCS."""
|
||||
def decorate(f):
|
||||
"""Store f in HANDLERS[vcs][method]."""
|
||||
if vcs not in HANDLERS:
|
||||
HANDLERS[vcs] = {}
|
||||
HANDLERS[vcs][method] = f
|
||||
return f
|
||||
return decorate
|
||||
|
||||
|
||||
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
|
||||
"""Call the given command(s)."""
|
||||
assert isinstance(commands, list)
|
||||
p = None
|
||||
for c in commands:
|
||||
try:
|
||||
dispcmd = str([c] + args)
|
||||
# remember shell=False, so use git.cmd on windows, not just git
|
||||
p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
|
||||
stderr=(subprocess.PIPE if hide_stderr
|
||||
@@ -33,7 +86,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
|
||||
if e.errno == errno.ENOENT:
|
||||
continue
|
||||
if verbose:
|
||||
print("unable to run %s" % args[0])
|
||||
print("unable to run %s" % dispcmd)
|
||||
print(e)
|
||||
return None
|
||||
else:
|
||||
@@ -41,59 +94,67 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
|
||||
print("unable to find command, tried %s" % (commands,))
|
||||
return None
|
||||
stdout = p.communicate()[0].strip()
|
||||
if sys.version >= '3':
|
||||
if sys.version_info[0] >= 3:
|
||||
stdout = stdout.decode()
|
||||
if p.returncode != 0:
|
||||
if verbose:
|
||||
print("unable to run %s (error)" % args[0])
|
||||
print("unable to run %s (error)" % dispcmd)
|
||||
return None
|
||||
return stdout
|
||||
|
||||
|
||||
import sys
|
||||
import re
|
||||
import os.path
|
||||
def versions_from_parentdir(parentdir_prefix, root, verbose):
|
||||
"""Try to determine the version from the parent directory name.
|
||||
|
||||
def get_gits(root, verbose=False):
|
||||
if not os.path.exists(os.path.join(root, ".git")):
|
||||
Source tarballs conventionally unpack into a directory that includes
|
||||
both the project name and a version string.
|
||||
"""
|
||||
dirname = os.path.basename(root)
|
||||
if not dirname.startswith(parentdir_prefix):
|
||||
if verbose:
|
||||
print("no .git in %s" % root)
|
||||
return None
|
||||
|
||||
GITS = ["git"]
|
||||
if sys.platform == "win32":
|
||||
GITS = ["git.cmd", "git.exe"]
|
||||
return GITS
|
||||
print("guessing rootdir is '%s', but '%s' doesn't start with "
|
||||
"prefix '%s'" % (root, dirname, parentdir_prefix))
|
||||
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
|
||||
return {"version": dirname[len(parentdir_prefix):],
|
||||
"full-revisionid": None,
|
||||
"dirty": False, "error": None}
|
||||
|
||||
|
||||
def get_expanded_variables(versionfile_abs):
|
||||
@register_vcs_handler("git", "get_keywords")
|
||||
def git_get_keywords(versionfile_abs):
|
||||
"""Extract version information from the given file."""
|
||||
# the code embedded in _version.py can just fetch the value of these
|
||||
# variables. When used from setup.py, we don't want to import
|
||||
# _version.py, so we do it with a regexp instead. This function is not
|
||||
# used from _version.py.
|
||||
variables = {}
|
||||
# keywords. When used from setup.py, we don't want to import _version.py,
|
||||
# so we do it with a regexp instead. This function is not used from
|
||||
# _version.py.
|
||||
keywords = {}
|
||||
try:
|
||||
f = open(versionfile_abs,"r")
|
||||
f = open(versionfile_abs, "r")
|
||||
for line in f.readlines():
|
||||
if line.strip().startswith("git_refnames ="):
|
||||
mo = re.search(r'=\s*"(.*)"', line)
|
||||
if mo:
|
||||
variables["refnames"] = mo.group(1)
|
||||
keywords["refnames"] = mo.group(1)
|
||||
if line.strip().startswith("git_full ="):
|
||||
mo = re.search(r'=\s*"(.*)"', line)
|
||||
if mo:
|
||||
variables["full"] = mo.group(1)
|
||||
keywords["full"] = mo.group(1)
|
||||
f.close()
|
||||
except EnvironmentError:
|
||||
pass
|
||||
return variables
|
||||
return keywords
|
||||
|
||||
def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
|
||||
refnames = variables["refnames"].strip()
|
||||
|
||||
@register_vcs_handler("git", "keywords")
|
||||
def git_versions_from_keywords(keywords, tag_prefix, verbose):
|
||||
"""Get version information from git keywords."""
|
||||
if not keywords:
|
||||
raise NotThisMethod("no keywords at all, weird")
|
||||
refnames = keywords["refnames"].strip()
|
||||
if refnames.startswith("$Format"):
|
||||
if verbose:
|
||||
print("variables are unexpanded, not using")
|
||||
return {} # unexpanded, so not in an unpacked git-archive tarball
|
||||
print("keywords are unexpanded, not using")
|
||||
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
|
||||
refs = set([r.strip() for r in refnames.strip("()").split(",")])
|
||||
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
|
||||
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
|
||||
@@ -110,6 +171,15 @@ def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
|
||||
tags = set([r for r in refs if re.search(r'\d', r)])
|
||||
if verbose:
|
||||
print("discarding '%s', no digits" % ",".join(refs-tags))
|
||||
|
||||
branches = [r for r in refs if not r.startswith(TAG)
|
||||
and r != "HEAD" and not r.startswith("refs/")]
|
||||
if verbose:
|
||||
print("likely branches: %s" % ",".join(sorted(branches)))
|
||||
branch = None
|
||||
if branches:
|
||||
branch = branches[0]
|
||||
|
||||
if verbose:
|
||||
print("likely tags: %s" % ",".join(sorted(tags)))
|
||||
for ref in sorted(tags):
|
||||
@@ -118,161 +188,473 @@ def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
|
||||
r = ref[len(tag_prefix):]
|
||||
if verbose:
|
||||
print("picking %s" % r)
|
||||
return { "version": r,
|
||||
"full": variables["full"].strip() }
|
||||
# no suitable tags, so we use the full revision id
|
||||
|
||||
result = {"version": r,
|
||||
"full-revisionid": keywords["full"].strip(),
|
||||
"dirty": False, "error": None}
|
||||
if branch is not None:
|
||||
result["branch"] = branch
|
||||
return result
|
||||
# no suitable tags, so version is "0+unknown", but full hex is still there
|
||||
if verbose:
|
||||
print("no suitable tags, using full revision id")
|
||||
return { "version": variables["full"].strip(),
|
||||
"full": variables["full"].strip() }
|
||||
print("no suitable tags, using unknown + full revision id")
|
||||
return {"version": "0+unknown",
|
||||
"full-revisionid": keywords["full"].strip(),
|
||||
"dirty": False, "error": "no suitable tags"}
|
||||
|
||||
def versions_from_lookup(lookup, root, verbose=False):
|
||||
GITS = get_gits(root, verbose=verbose)
|
||||
if GITS is None:
|
||||
return {}
|
||||
|
||||
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
@register_vcs_handler("git", "pieces_from_vcs")
|
||||
def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
|
||||
"""Get version from 'git describe' in the root of the source tree.
|
||||
|
||||
current_branch = stdout.strip()
|
||||
for matcher, tag, ref_commit in lookup:
|
||||
if matcher.match(current_branch):
|
||||
if tag is None or ref_commit is None:
|
||||
return {}
|
||||
|
||||
stdout = run_command(GITS, ["rev-list", "%s..HEAD" % ref_commit, "--count"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
num_commits = stdout.strip()
|
||||
|
||||
stdout =run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
short_hash = stdout.strip()
|
||||
|
||||
stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
dirty = stdout.strip().endswith("-dirty")
|
||||
|
||||
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
full = stdout.strip()
|
||||
|
||||
version = "%s-%s-g%s" % (tag, num_commits, short_hash)
|
||||
if dirty:
|
||||
version += "-dirty"
|
||||
full += "-dirty"
|
||||
return {"version": version, "full": full, "branch": current_branch}
|
||||
|
||||
return {}
|
||||
|
||||
def versions_from_vcs(tag_prefix, root, verbose=False):
|
||||
# this runs 'git' from the root of the source tree. This only gets called
|
||||
# if the git-archive 'subst' variables were *not* expanded, and
|
||||
# _version.py hasn't already been rewritten with a short version string,
|
||||
# meaning we're inside a checked out source tree.
|
||||
|
||||
GITS = get_gits(root, verbose=verbose)
|
||||
if GITS is None:
|
||||
return {}
|
||||
|
||||
stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
if not stdout.startswith(tag_prefix):
|
||||
This only gets called if the git-archive 'subst' keywords were *not*
|
||||
expanded, and _version.py hasn't already been rewritten with a short
|
||||
version string, meaning we're inside a checked out source tree.
|
||||
"""
|
||||
if not os.path.exists(os.path.join(root, ".git")):
|
||||
if verbose:
|
||||
print("tag '%s' doesn't start with prefix '%s'" % (stdout, tag_prefix))
|
||||
return {}
|
||||
tag = stdout[len(tag_prefix):]
|
||||
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
|
||||
if stdout is None:
|
||||
return {}
|
||||
full = stdout.strip()
|
||||
if tag.endswith("-dirty"):
|
||||
full += "-dirty"
|
||||
print("no .git in %s" % root)
|
||||
raise NotThisMethod("no .git directory")
|
||||
|
||||
GITS = ["git"]
|
||||
if sys.platform == "win32":
|
||||
GITS = ["git.cmd", "git.exe"]
|
||||
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
|
||||
# if there isn't one, this yields HEX[-dirty] (no NUM)
|
||||
describe_out = run_command(GITS, ["describe", "--tags", "--dirty",
|
||||
"--always", "--long",
|
||||
"--match", "%s*" % tag_prefix],
|
||||
cwd=root)
|
||||
# --long was added in git-1.5.5
|
||||
if describe_out is None:
|
||||
raise NotThisMethod("'git describe' failed")
|
||||
describe_out = describe_out.strip()
|
||||
full_out = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
|
||||
if full_out is None:
|
||||
raise NotThisMethod("'git rev-parse' failed")
|
||||
full_out = full_out.strip()
|
||||
|
||||
pieces = {}
|
||||
pieces["long"] = full_out
|
||||
pieces["short"] = full_out[:7] # maybe improved later
|
||||
pieces["error"] = None
|
||||
|
||||
# parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
|
||||
# TAG might have hyphens.
|
||||
git_describe = describe_out
|
||||
|
||||
# look for -dirty suffix
|
||||
dirty = git_describe.endswith("-dirty")
|
||||
pieces["dirty"] = dirty
|
||||
if dirty:
|
||||
git_describe = git_describe[:git_describe.rindex("-dirty")]
|
||||
|
||||
# figure out our branch
|
||||
abbrev_ref_out = run_command(GITS,
|
||||
["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
cwd=root)
|
||||
if abbrev_ref_out is not None:
|
||||
pieces["branch"] = abbrev_ref_out.strip()
|
||||
|
||||
# now we have TAG-NUM-gHEX or HEX
|
||||
|
||||
if "-" in git_describe:
|
||||
# TAG-NUM-gHEX
|
||||
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
|
||||
if not mo:
|
||||
# unparseable. Maybe git-describe is misbehaving?
|
||||
pieces["error"] = ("unable to parse git-describe output: '%s'"
|
||||
% describe_out)
|
||||
return pieces
|
||||
|
||||
# tag
|
||||
full_tag = mo.group(1)
|
||||
if not full_tag.startswith(tag_prefix):
|
||||
if verbose:
|
||||
fmt = "tag '%s' doesn't start with prefix '%s'"
|
||||
print(fmt % (full_tag, tag_prefix))
|
||||
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
|
||||
% (full_tag, tag_prefix))
|
||||
return pieces
|
||||
pieces["closest-tag"] = full_tag[len(tag_prefix):]
|
||||
|
||||
# distance: number of commits since tag
|
||||
pieces["distance"] = int(mo.group(2))
|
||||
|
||||
# commit: short hex revision ID
|
||||
pieces["short"] = mo.group(3)
|
||||
|
||||
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
branch = None
|
||||
else:
|
||||
branch = stdout.strip()
|
||||
return {"version": tag, "full": full, "branch": branch}
|
||||
# HEX: no tags
|
||||
pieces["closest-tag"] = None
|
||||
count_out = run_command(GITS, ["rev-list", "HEAD", "--count"],
|
||||
cwd=root)
|
||||
pieces["distance"] = int(count_out) # total number of commits
|
||||
|
||||
return pieces
|
||||
|
||||
|
||||
def versions_from_parentdir(parentdir_prefix, root, verbose=False):
|
||||
# Source tarballs conventionally unpack into a directory that includes
|
||||
# both the project name and a version string.
|
||||
dirname = os.path.basename(root)
|
||||
if not dirname.startswith(parentdir_prefix):
|
||||
if verbose:
|
||||
print("guessing rootdir is '%s', but '%s' doesn't start with prefix '%s'" %
|
||||
(root, dirname, parentdir_prefix))
|
||||
return None
|
||||
return {"version": dirname[len(parentdir_prefix):], "full": "", "branch": ""}
|
||||
@register_vcs_handler("git", "parse_lookup_file")
|
||||
def git_parse_lookup_file(path):
|
||||
"""Parse a versioneer lookup file.
|
||||
|
||||
tag_prefix = ""
|
||||
parentdir_prefix = ""
|
||||
versionfile_source = "src/octoprint/_version.py"
|
||||
lookupfile = ".versioneer-lookup"
|
||||
|
||||
def parse_lookup_file(root, lookup_path=None):
|
||||
if not lookup_path:
|
||||
lookup_path = lookupfile
|
||||
if not lookup_path:
|
||||
return []
|
||||
|
||||
path = os.path.join(root, lookup_path)
|
||||
This file allows definition of branch specific data like virtual tags or
|
||||
custom styles to use for version rendering.
|
||||
"""
|
||||
if not os.path.exists(path):
|
||||
return []
|
||||
|
||||
import re
|
||||
lookup = []
|
||||
with open(os.path.join(root, lookup_path), "r") as f:
|
||||
with open(path, "r") as f:
|
||||
for line in f:
|
||||
if '#' in line:
|
||||
line = line[:line.rindex('#')]
|
||||
line = line[:line.rindex("#")]
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
|
||||
try:
|
||||
split_line = line.split()
|
||||
if len(split_line) == 3:
|
||||
pattern, tag, ref_commit = split_line
|
||||
lookup.append([re.compile(pattern), tag, ref_commit])
|
||||
elif len(split_line) >= 1:
|
||||
lookup.append([re.compile(split_line[0]), None, None])
|
||||
split_line = map(lambda x: x.strip(), line.split())
|
||||
if not len(split_line):
|
||||
continue
|
||||
|
||||
matcher = re.compile(split_line[0])
|
||||
|
||||
if len(split_line) == 1:
|
||||
entry = [matcher, None, None, None]
|
||||
elif len(split_line) == 2:
|
||||
render = split_line[1]
|
||||
entry = [matcher, render, None, None]
|
||||
elif len(split_line) == 3:
|
||||
tag, ref_commit = split_line[1:]
|
||||
entry = [matcher, None, tag, ref_commit]
|
||||
elif len(split_line) == 4:
|
||||
tag, ref_commit, render = split_line[1:]
|
||||
entry = [matcher, render, tag, ref_commit]
|
||||
else:
|
||||
continue
|
||||
|
||||
lookup.append(entry)
|
||||
except:
|
||||
break
|
||||
return lookup
|
||||
|
||||
def get_versions(default={"version": "unknown", "full": "", "branch": "unknown"}, lookup_path=None, verbose=False):
|
||||
|
||||
@register_vcs_handler("git", "pieces_from_lookup")
|
||||
def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
|
||||
"""Extract version information based on provided lookup data."""
|
||||
GITS = ["git"]
|
||||
if sys.platform == "win32":
|
||||
GITS = ["git.cmd", "git.exe"]
|
||||
|
||||
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
raise NotThisMethod("git rev-parse --abbrev-ref HEAD failed")
|
||||
|
||||
current_branch = stdout.strip()
|
||||
for matcher, render, tag, ref_commit in lookup:
|
||||
if matcher.match(current_branch):
|
||||
if tag is None or ref_commit is None:
|
||||
raise NotThisMethod("tag or ref_commit is unset for "
|
||||
"this branch")
|
||||
|
||||
stdout = run_command(GITS,
|
||||
["rev-list", "%s..HEAD" % ref_commit,
|
||||
"--count"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
raise NotThisMethod("git rev-list %s..HEAD "
|
||||
"--count failed" % ref_commit)
|
||||
try:
|
||||
num_commits = int(stdout.strip())
|
||||
except ValueError:
|
||||
raise NotThisMethod("git rev-list %s..HEAD --count didn't "
|
||||
"return a valid number" % ref_commit)
|
||||
|
||||
stdout = run_command(GITS,
|
||||
["rev-parse", "--short", "HEAD"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
raise NotThisMethod("git describe rev-parse "
|
||||
"--short HEAD failed")
|
||||
short_hash = stdout.strip()
|
||||
|
||||
stdout = run_command(GITS,
|
||||
["describe", "--tags",
|
||||
"--dirty", "--always"],
|
||||
cwd=root)
|
||||
if stdout is None:
|
||||
raise NotThisMethod("git describe --tags --dirty "
|
||||
"--always failed")
|
||||
dirty = stdout.strip().endswith("-dirty")
|
||||
|
||||
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
|
||||
if stdout is None:
|
||||
raise NotThisMethod("git rev-parse HEAD failed")
|
||||
full = stdout.strip()
|
||||
|
||||
return {
|
||||
"long": full,
|
||||
"short": short_hash,
|
||||
"dirty": dirty,
|
||||
"branch": current_branch,
|
||||
"closest-tag": tag,
|
||||
"distance": num_commits,
|
||||
"error": None,
|
||||
"render": render
|
||||
}
|
||||
|
||||
raise NotThisMethod("no matching lookup definition found")
|
||||
|
||||
|
||||
def plus_or_dot(pieces):
|
||||
"""Return a + if we don't already have one, else return a ."""
|
||||
if "+" in pieces.get("closest-tag", ""):
|
||||
return "."
|
||||
return "+"
|
||||
|
||||
|
||||
def render_pep440(pieces):
|
||||
"""Build up version string, with post-release "local version identifier".
|
||||
|
||||
Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
|
||||
get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
|
||||
|
||||
Exceptions:
|
||||
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
|
||||
"""
|
||||
if pieces["closest-tag"]:
|
||||
rendered = pieces["closest-tag"]
|
||||
if pieces["distance"] or pieces["dirty"]:
|
||||
rendered += plus_or_dot(pieces)
|
||||
rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
|
||||
if pieces["dirty"]:
|
||||
rendered += ".dirty"
|
||||
else:
|
||||
# exception #1
|
||||
rendered = "0+untagged.%d.g%s" % (pieces["distance"],
|
||||
pieces["short"])
|
||||
if pieces["dirty"]:
|
||||
rendered += ".dirty"
|
||||
return rendered
|
||||
|
||||
|
||||
def render_pep440_pre(pieces):
|
||||
"""TAG[.post.devDISTANCE] -- No -dirty.
|
||||
|
||||
Exceptions:
|
||||
1: no tags. 0.post.devDISTANCE
|
||||
"""
|
||||
if pieces["closest-tag"]:
|
||||
rendered = pieces["closest-tag"]
|
||||
if pieces["distance"]:
|
||||
rendered += ".post.dev%d" % pieces["distance"]
|
||||
else:
|
||||
# exception #1
|
||||
rendered = "0.post.dev%d" % pieces["distance"]
|
||||
return rendered
|
||||
|
||||
|
||||
def render_pep440_post(pieces):
|
||||
"""TAG[.postDISTANCE[.dev0]+gHEX] .
|
||||
|
||||
The ".dev0" means dirty. Note that .dev0 sorts backwards
|
||||
(a dirty tree will appear "older" than the corresponding clean one),
|
||||
but you shouldn't be releasing software with -dirty anyways.
|
||||
|
||||
Exceptions:
|
||||
1: no tags. 0.postDISTANCE[.dev0]
|
||||
"""
|
||||
if pieces["closest-tag"]:
|
||||
rendered = pieces["closest-tag"]
|
||||
if pieces["distance"] or pieces["dirty"]:
|
||||
rendered += ".post%d" % pieces["distance"]
|
||||
if pieces["dirty"]:
|
||||
rendered += ".dev0"
|
||||
rendered += plus_or_dot(pieces)
|
||||
rendered += "g%s" % pieces["short"]
|
||||
else:
|
||||
# exception #1
|
||||
rendered = "0.post%d" % pieces["distance"]
|
||||
if pieces["dirty"]:
|
||||
rendered += ".dev0"
|
||||
rendered += "+g%s" % pieces["short"]
|
||||
return rendered
|
||||
|
||||
|
||||
def render_pep440_dev(pieces):
|
||||
"""TAG[.devDISTANCE]+gHEX[.dirty] .
|
||||
|
||||
Exceptions:
|
||||
1: no tags. 0.devDISTANCE+gHEX[.dirty]
|
||||
"""
|
||||
if pieces["closest-tag"]:
|
||||
rendered = pieces["closest-tag"]
|
||||
if pieces["distance"]:
|
||||
rendered += ".dev%d" % pieces["distance"]
|
||||
rendered += plus_or_dot(pieces)
|
||||
else:
|
||||
# exception #1
|
||||
rendered = "0.dev%d" % pieces["distance"]
|
||||
rendered += "+"
|
||||
rendered += "g%s" % pieces["short"]
|
||||
if pieces["dirty"]:
|
||||
rendered += ".dirty"
|
||||
return rendered
|
||||
|
||||
|
||||
def render_pep440_old(pieces):
|
||||
"""TAG[.postDISTANCE[.dev0]] .
|
||||
|
||||
The ".dev0" means dirty.
|
||||
|
||||
Eexceptions:
|
||||
1: no tags. 0.postDISTANCE[.dev0]
|
||||
"""
|
||||
if pieces["closest-tag"]:
|
||||
rendered = pieces["closest-tag"]
|
||||
if pieces["distance"] or pieces["dirty"]:
|
||||
rendered += ".post%d" % pieces["distance"]
|
||||
if pieces["dirty"]:
|
||||
rendered += ".dev0"
|
||||
else:
|
||||
# exception #1
|
||||
rendered = "0.post%d" % pieces["distance"]
|
||||
if pieces["dirty"]:
|
||||
rendered += ".dev0"
|
||||
return rendered
|
||||
|
||||
|
||||
def render_git_describe(pieces):
|
||||
"""TAG[-DISTANCE-gHEX][-dirty].
|
||||
|
||||
Like 'git describe --tags --dirty --always'.
|
||||
|
||||
Exceptions:
|
||||
1: no tags. HEX[-dirty] (note: no 'g' prefix)
|
||||
"""
|
||||
if pieces["closest-tag"]:
|
||||
rendered = pieces["closest-tag"]
|
||||
if pieces["distance"]:
|
||||
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
|
||||
else:
|
||||
# exception #1
|
||||
rendered = pieces["short"]
|
||||
if pieces["dirty"]:
|
||||
rendered += "-dirty"
|
||||
return rendered
|
||||
|
||||
|
||||
def render_git_describe_long(pieces):
|
||||
"""TAG-DISTANCE-gHEX[-dirty].
|
||||
|
||||
Like 'git describe --tags --dirty --always -long'.
|
||||
The distance/hash is unconditional.
|
||||
|
||||
Exceptions:
|
||||
1: no tags. HEX[-dirty] (note: no 'g' prefix)
|
||||
"""
|
||||
if pieces["closest-tag"]:
|
||||
rendered = pieces["closest-tag"]
|
||||
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
|
||||
else:
|
||||
# exception #1
|
||||
rendered = pieces["short"]
|
||||
if pieces["dirty"]:
|
||||
rendered += "-dirty"
|
||||
return rendered
|
||||
|
||||
|
||||
def render(pieces, style):
|
||||
"""Render the given version pieces into the requested style."""
|
||||
if pieces["error"]:
|
||||
return {"version": "unknown",
|
||||
"full-revisionid": pieces.get("long"),
|
||||
"dirty": None,
|
||||
"error": pieces["error"]}
|
||||
|
||||
if "render" in pieces and pieces["render"] is not None:
|
||||
style = pieces["render"]
|
||||
|
||||
if not style or style == "default":
|
||||
style = "pep440" # the default
|
||||
|
||||
if style == "pep440":
|
||||
rendered = render_pep440(pieces)
|
||||
elif style == "pep440-pre":
|
||||
rendered = render_pep440_pre(pieces)
|
||||
elif style == "pep440-post":
|
||||
rendered = render_pep440_post(pieces)
|
||||
elif style == "pep440-old":
|
||||
rendered = render_pep440_old(pieces)
|
||||
elif style == "pep440-dev":
|
||||
rendered = render_pep440_dev(pieces)
|
||||
elif style == "git-describe":
|
||||
rendered = render_git_describe(pieces)
|
||||
elif style == "git-describe-long":
|
||||
rendered = render_git_describe_long(pieces)
|
||||
else:
|
||||
raise ValueError("unknown style '%s'" % style)
|
||||
|
||||
result = {"version": rendered, "full-revisionid": pieces["long"],
|
||||
"dirty": pieces["dirty"], "error": None}
|
||||
if "branch" in pieces and pieces["branch"] is not None:
|
||||
result["branch"] = pieces["branch"]
|
||||
return result
|
||||
|
||||
|
||||
def get_versions():
|
||||
"""Get version information or return default if unable to do so."""
|
||||
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
|
||||
# __file__, we can work backwards from there to the root. Some
|
||||
# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
|
||||
# case we can only use expanded variables.
|
||||
# case we can only use expanded keywords.
|
||||
|
||||
variables = { "refnames": git_refnames, "full": git_full }
|
||||
ver = versions_from_expanded_variables(variables, tag_prefix, verbose)
|
||||
if ver:
|
||||
return ver
|
||||
cfg = get_config()
|
||||
verbose = cfg.verbose
|
||||
|
||||
try:
|
||||
root = os.path.abspath(__file__)
|
||||
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
|
||||
verbose)
|
||||
except NotThisMethod:
|
||||
pass
|
||||
|
||||
try:
|
||||
root = os.path.realpath(__file__)
|
||||
# versionfile_source is the relative path from the top of the source
|
||||
# tree (where the .git directory might live) to this file. Invert
|
||||
# this to find the root from __file__.
|
||||
for i in range(len(versionfile_source.split("/"))):
|
||||
for i in cfg.versionfile_source.split('/'):
|
||||
root = os.path.dirname(root)
|
||||
except NameError:
|
||||
return default
|
||||
return {"version": "0+unknown", "full-revisionid": None,
|
||||
"dirty": None,
|
||||
"error": "unable to find root of source tree"}
|
||||
|
||||
lookup = parse_lookup_file(root, lookup_path=lookup_path)
|
||||
return (versions_from_lookup(lookup, root, verbose)
|
||||
or versions_from_vcs(tag_prefix, root, verbose)
|
||||
or versions_from_parentdir(parentdir_prefix, root, verbose)
|
||||
or default)
|
||||
lookupfile = cfg.lookupfile if cfg.lookupfile is not None else ".versioneer-lookup"
|
||||
lookuppath = os.path.join(root, lookupfile)
|
||||
if os.path.exists(lookuppath):
|
||||
try:
|
||||
lookup_data = git_parse_lookup_file(lookuppath)
|
||||
pieces = git_pieces_from_lookup(lookup_data, root, verbose)
|
||||
return render(pieces, cfg.style)
|
||||
except NotThisMethod:
|
||||
pass
|
||||
|
||||
try:
|
||||
pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
|
||||
return render(pieces, cfg.style)
|
||||
except NotThisMethod:
|
||||
pass
|
||||
|
||||
try:
|
||||
if cfg.parentdir_prefix:
|
||||
return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
|
||||
except NotThisMethod:
|
||||
pass
|
||||
|
||||
return {"version": "0+unknown", "full-revisionid": None,
|
||||
"dirty": None,
|
||||
"error": "unable to compute version"}
|
||||
@@ -74,6 +74,9 @@ class Events(object):
|
||||
# Timelapse
|
||||
CAPTURE_START = "CaptureStart"
|
||||
CAPTURE_DONE = "CaptureDone"
|
||||
CAPTURE_FAILED = "CaptureFailed"
|
||||
POSTROLL_START = "PostRollStart"
|
||||
POSTROLL_END = "PostRollEnd"
|
||||
MOVIE_RENDERING = "MovieRendering"
|
||||
MOVIE_DONE = "MovieDone"
|
||||
MOVIE_FAILED = "MovieFailed"
|
||||
|
||||
@@ -18,6 +18,11 @@ from .analysis import QueueEntry, AnalysisQueue
|
||||
from .storage import LocalFileStorage
|
||||
from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
|
||||
ContentTypeDetector = namedtuple("ContentTypeDetector", "extensions, detector")
|
||||
|
||||
extensions = dict(
|
||||
)
|
||||
|
||||
@@ -25,11 +30,11 @@ def full_extension_tree():
|
||||
result = dict(
|
||||
# extensions for 3d model files
|
||||
model=dict(
|
||||
stl=["stl"]
|
||||
stl=ContentTypeMapping(["stl"], "application/sla")
|
||||
),
|
||||
# extensions for printable machine code
|
||||
machinecode=dict(
|
||||
gcode=["gcode", "gco", "g"]
|
||||
gcode=ContentTypeMapping(["gcode", "gco", "g"], "text/plain")
|
||||
)
|
||||
)
|
||||
|
||||
@@ -68,8 +73,12 @@ def get_all_extensions(subtree=None):
|
||||
for key, value in subtree.items():
|
||||
if isinstance(value, dict):
|
||||
result += get_all_extensions(value)
|
||||
elif isinstance(value, (ContentTypeMapping, ContentTypeDetector)):
|
||||
result += value.extensions
|
||||
elif isinstance(value, (list, tuple)):
|
||||
result += value
|
||||
elif isinstance(subtree, (ContentTypeMapping, ContentTypeDetector)):
|
||||
result = subtree.extensions
|
||||
elif isinstance(subtree, (list, tuple)):
|
||||
result = subtree
|
||||
return result
|
||||
@@ -79,7 +88,9 @@ def get_path_for_extension(extension, subtree=None):
|
||||
subtree = full_extension_tree()
|
||||
|
||||
for key, value in subtree.items():
|
||||
if isinstance(value, (list, tuple)) and extension in value:
|
||||
if isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value.extensions:
|
||||
return [key]
|
||||
elif isinstance(value, (list, tuple)) and extension in value:
|
||||
return [key]
|
||||
elif isinstance(value, dict):
|
||||
path = get_path_for_extension(extension, subtree=value)
|
||||
@@ -88,6 +99,23 @@ def get_path_for_extension(extension, subtree=None):
|
||||
|
||||
return None
|
||||
|
||||
def get_content_type_mapping_for_extension(extension, subtree=None):
|
||||
if not subtree:
|
||||
subtree = full_extension_tree()
|
||||
|
||||
for key, value in subtree.items():
|
||||
content_extension_matches = isinstance(value, (ContentTypeMapping, ContentTypeDetector)) and extension in value. extensions
|
||||
list_extension_matches = isinstance(value, (list, tuple)) and extension in value
|
||||
|
||||
if content_extension_matches or list_extension_matches:
|
||||
return value
|
||||
elif isinstance(value, dict):
|
||||
result = get_content_type_mapping_for_extension(extension, subtree=value)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
return None
|
||||
|
||||
def valid_extension(extension, type=None):
|
||||
if not type:
|
||||
return extension in get_all_extensions()
|
||||
@@ -106,6 +134,19 @@ def get_file_type(filename):
|
||||
extension = extension[1:].lower()
|
||||
return get_path_for_extension(extension)
|
||||
|
||||
def get_mime_type(filename):
|
||||
_, extension = os.path.splitext(filename)
|
||||
extension = extension[1:].lower()
|
||||
mapping = get_content_type_mapping_for_extension(extension)
|
||||
if mapping:
|
||||
if isinstance(mapping, ContentTypeMapping) and mapping.content_type is not None:
|
||||
return mapping.content_type
|
||||
elif isinstance(mapping, ContentTypeDetector) and callable(mapping.detector):
|
||||
result = mapping.detector(filename)
|
||||
if result is not None:
|
||||
return result
|
||||
return "application/octet-stream"
|
||||
|
||||
|
||||
class NoSuchStorage(Exception):
|
||||
pass
|
||||
@@ -134,6 +175,9 @@ class FileManager(object):
|
||||
self._progress_plugins = []
|
||||
self._preprocessor_hooks = dict()
|
||||
|
||||
import octoprint.settings
|
||||
self._recovery_file = os.path.join(octoprint.settings.settings().getBaseFolder("data"), "print_recovery_data.yaml")
|
||||
|
||||
def initialize(self):
|
||||
self.reload_plugins()
|
||||
|
||||
@@ -155,7 +199,11 @@ class FileManager(object):
|
||||
self._slicing_progress_callbacks.append(callback)
|
||||
|
||||
def unregister_slicingprogress_callback(self, callback):
|
||||
self._slicing_progress_callbacks.remove(callback)
|
||||
try:
|
||||
self._slicing_progress_callbacks.remove(callback)
|
||||
except ValueError:
|
||||
# callback was not registered
|
||||
pass
|
||||
|
||||
def _determine_analysis_backlog(self, storage_type, storage_manager):
|
||||
counter = 0
|
||||
@@ -314,7 +362,12 @@ class FileManager(object):
|
||||
printer_profile = self._printer_profile_manager.get_current_or_default()
|
||||
|
||||
for hook in self._preprocessor_hooks.values():
|
||||
hook_file_object = hook(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
try:
|
||||
hook_file_object = hook(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
except:
|
||||
self._logger.exception("Error when calling preprocessor hook {}, ignoring".format(hook))
|
||||
continue
|
||||
|
||||
if hook_file_object is not None:
|
||||
file_object = hook_file_object
|
||||
file_path = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
|
||||
@@ -364,6 +417,43 @@ class FileManager(object):
|
||||
# if there's no storage configured where to log the print, we'll just not log it
|
||||
pass
|
||||
|
||||
def save_recovery_data(self, origin, path, pos):
|
||||
import time
|
||||
import yaml
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
data = dict(origin=origin,
|
||||
path=self.path_in_storage(origin, path),
|
||||
pos=pos,
|
||||
date=time.time())
|
||||
try:
|
||||
with atomic_write(self._recovery_file) as f:
|
||||
yaml.safe_dump(data, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
except:
|
||||
self._logger.exception("Could not write recovery data to file {}".format(self._recovery_file))
|
||||
|
||||
def delete_recovery_data(self):
|
||||
if not os.path.isfile(self._recovery_file):
|
||||
return
|
||||
|
||||
try:
|
||||
os.remove(self._recovery_file)
|
||||
except:
|
||||
self._logger.exception("Error deleting recovery data file {}".format(self._recovery_file))
|
||||
|
||||
def get_recovery_data(self):
|
||||
if not os.path.isfile(self._recovery_file):
|
||||
return None
|
||||
|
||||
import yaml
|
||||
try:
|
||||
with open(self._recovery_file) as f:
|
||||
data = yaml.safe_load(f)
|
||||
return data
|
||||
except:
|
||||
self._logger.exception("Could not read recovery data from file {}".format(self._recovery_file))
|
||||
self.delete_recovery_data()
|
||||
|
||||
def set_additional_metadata(self, destination, path, key, data, overwrite=False, merge=False):
|
||||
self._storage(destination).set_additional_metadata(path, key, data, overwrite=overwrite, merge=merge)
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ import tempfile
|
||||
|
||||
import octoprint.filemanager
|
||||
|
||||
from octoprint.util import is_hidden_path
|
||||
|
||||
class StorageInterface(object):
|
||||
"""
|
||||
Interface of storage adapters for OctoPrint.
|
||||
@@ -309,6 +311,10 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
self._metadata_cache = pylru.lrucache(10)
|
||||
|
||||
from slugify import Slugify
|
||||
self._slugify = Slugify()
|
||||
self._slugify.safe_chars = "-_.() "
|
||||
|
||||
self._old_metadata = None
|
||||
self._initialize_metadata()
|
||||
|
||||
@@ -357,7 +363,7 @@ class LocalFileStorage(StorageInterface):
|
||||
if not metadata:
|
||||
metadata = dict()
|
||||
for entry in os.listdir(path):
|
||||
if entry.startswith(".") or not octoprint.filemanager.valid_file_type(entry):
|
||||
if is_hidden_path(entry) or not octoprint.filemanager.valid_file_type(entry):
|
||||
continue
|
||||
|
||||
absolute_path = os.path.join(path, entry)
|
||||
@@ -584,24 +590,6 @@ class LocalFileStorage(StorageInterface):
|
||||
Note that for a ``path`` without a trailing slash the last part will be considered a file name and
|
||||
hence be returned at second position. If you only need to convert a folder path, be sure to
|
||||
include a trailing slash for a string ``path`` or an empty last element for a list ``path``.
|
||||
|
||||
Examples::
|
||||
|
||||
>>> storage = LocalFileStorage("/some/base/folder")
|
||||
>>> storage.sanitize("some/folder/and/some file.gco")
|
||||
("/some/base/folder/some/folder/and", "some_file.gco")
|
||||
>>> storage.sanitize(("some", "folder", "and", "some file.gco"))
|
||||
("/some/base/folder/some/folder/and", "some_file.gco")
|
||||
>>> storage.sanitize("some file.gco")
|
||||
("/some/base/folder", "some_file.gco")
|
||||
>>> storage.sanitize(("some file.gco",))
|
||||
("/some/base/folder", "some_file.gco")
|
||||
>>> storage.sanitize("")
|
||||
("/some/base/folder", "")
|
||||
>>> storage.sanitize("some/folder/with/trailing/slash/")
|
||||
("/some/base/folder/some/folder/with/trailing/slash", "")
|
||||
>>> storage.sanitize("some", "folder", "")
|
||||
("/some/base/folder/some/folder", "")
|
||||
"""
|
||||
name = None
|
||||
if isinstance(path, (str, unicode, basestring)):
|
||||
@@ -625,27 +613,9 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
def sanitize_name(self, name):
|
||||
"""
|
||||
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise strips any characters from the
|
||||
given ``name`` that are not any of the ASCII characters, digits, ``-``, ``_``, ``.``, ``(``, ``)`` or space and
|
||||
replaces and spaces with ``_``.
|
||||
|
||||
Examples::
|
||||
|
||||
>>> storage = LocalFileStorage("/some/base/folder")
|
||||
>>> storage.sanitize_name("some_file.gco")
|
||||
"some_file.gco"
|
||||
>>> storage.sanitize_name("some_file with (parentheses) and ümläuts and digits 123.gco")
|
||||
"some_file_with_(parentheses)_and_mluts_and_digits_123.gco"
|
||||
>>> storage.sanitize_name("pengüino pequeño.stl")
|
||||
"pengino_pequeo.stl"
|
||||
>>> storage.sanitize_name("some/folder/still/left.gco")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: name must not contain / or \
|
||||
>>> storage.sanitize_name("also\\no\\backslashes.gco")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: name must not contain / or \
|
||||
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise
|
||||
slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``,
|
||||
``(``, and ``)`` as is.
|
||||
"""
|
||||
if name is None:
|
||||
return None
|
||||
@@ -653,33 +623,13 @@ class LocalFileStorage(StorageInterface):
|
||||
if "/" in name or "\\" in name:
|
||||
raise ValueError("name must not contain / or \\")
|
||||
|
||||
import string
|
||||
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
|
||||
sanitized_name = ''.join(c for c in name if c in valid_chars)
|
||||
sanitized_name = sanitized_name.replace(" ", "_")
|
||||
return sanitized_name
|
||||
return self._slugify(name).replace(" ", "_")
|
||||
|
||||
def sanitize_path(self, path):
|
||||
"""
|
||||
Ensures that the on disk representation of ``path`` is located under the configured basefolder. Resolves all
|
||||
relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the
|
||||
absolute path including leading ``basefolder`` path.
|
||||
|
||||
Examples::
|
||||
|
||||
>>> storage = LocalFileStorage("/some/base/folder")
|
||||
>>> storage.sanitize_path("folder/with/subfolder")
|
||||
"/some/base/folder/folder/with/subfolder"
|
||||
>>> storage.sanitize_path("folder/with/subfolder/../other/folder")
|
||||
"/some/base/folder/folder/with/other/folder"
|
||||
>>> storage.sanitize_path("/folder/with/leading/slash")
|
||||
"/some/base/folder/folder/with/leading/slash"
|
||||
>>> storage.sanitize_path(".folder/with/leading/dot")
|
||||
"/some/base/folder/folder/with/leading/dot
|
||||
>>> storage.sanitize_path("../../folder/out/of/the/basefolder")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: path not contained in base folder: /some/folder/out/of/the/basefolder
|
||||
"""
|
||||
if path[0] == "/" or path[0] == ".":
|
||||
path = path[1:]
|
||||
@@ -939,7 +889,7 @@ class LocalFileStorage(StorageInterface):
|
||||
|
||||
result = dict()
|
||||
for entry in os.listdir(path):
|
||||
if entry.startswith("."):
|
||||
if is_hidden_path(entry):
|
||||
# no hidden files and folders
|
||||
continue
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
|
||||
import io
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
class AbstractFileWrapper(object):
|
||||
"""
|
||||
Wrapper for file representations to save to storages.
|
||||
@@ -85,7 +87,7 @@ class StreamWrapper(AbstractFileWrapper):
|
||||
"""
|
||||
import shutil
|
||||
|
||||
with open(path, "wb") as dest:
|
||||
with atomic_write(path, "wb") as dest:
|
||||
with self.stream() as source:
|
||||
shutil.copyfileobj(source, dest)
|
||||
|
||||
|
||||
@@ -293,19 +293,16 @@ class PluginSettings(object):
|
||||
self.set_preprocessors = dict(plugins=dict())
|
||||
self.set_preprocessors["plugins"][plugin_key] = set_preprocessors
|
||||
|
||||
def prefix_path(path):
|
||||
return ['plugins', self.plugin_key] + path
|
||||
|
||||
def prefix_path_in_args(args, index=0):
|
||||
result = []
|
||||
if index == 0:
|
||||
result.append(prefix_path(args[0]))
|
||||
result.append(self._prefix_path(args[0]))
|
||||
result.extend(args[1:])
|
||||
else:
|
||||
args_before = args[:index - 1]
|
||||
args_after = args[index + 1:]
|
||||
result.extend(args_before)
|
||||
result.append(prefix_path(args[index]))
|
||||
result.append(self._prefix_path(args[index]))
|
||||
result.extend(args_after)
|
||||
return result
|
||||
|
||||
@@ -324,6 +321,7 @@ class PluginSettings(object):
|
||||
return kwargs
|
||||
|
||||
self.access_methods = dict(
|
||||
has =("has", prefix_path_in_args, add_getter_kwargs),
|
||||
get =("get", prefix_path_in_args, add_getter_kwargs),
|
||||
get_int =("getInt", prefix_path_in_args, add_getter_kwargs),
|
||||
get_float =("getFloat", prefix_path_in_args, add_getter_kwargs),
|
||||
@@ -331,7 +329,8 @@ class PluginSettings(object):
|
||||
set =("set", prefix_path_in_args, add_setter_kwargs),
|
||||
set_int =("setInt", prefix_path_in_args, add_setter_kwargs),
|
||||
set_float =("setFloat", prefix_path_in_args, add_setter_kwargs),
|
||||
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs)
|
||||
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs),
|
||||
remove =("remove", prefix_path_in_args, lambda x: x)
|
||||
)
|
||||
self.deprecated_access_methods = dict(
|
||||
getInt ="get_int",
|
||||
@@ -342,6 +341,17 @@ class PluginSettings(object):
|
||||
setBoolean="set_boolean"
|
||||
)
|
||||
|
||||
def _prefix_path(self, path=None):
|
||||
if path is None:
|
||||
path = list()
|
||||
return ['plugins', self.plugin_key] + path
|
||||
|
||||
def global_has(self, path, **kwargs):
|
||||
return self.settings.has(path, **kwargs)
|
||||
|
||||
def global_remove(self, path, **kwargs):
|
||||
return self.settings.remove(path, **kwargs)
|
||||
|
||||
def global_get(self, path, **kwargs):
|
||||
"""
|
||||
Getter for retrieving settings not managed by the plugin itself from the core settings structure. Use this
|
||||
@@ -435,6 +445,24 @@ class PluginSettings(object):
|
||||
os.makedirs(path)
|
||||
return path
|
||||
|
||||
def get_all_data(self, **kwargs):
|
||||
merged = kwargs.get("merged", True)
|
||||
asdict = kwargs.get("asdict", True)
|
||||
defaults = kwargs.get("defaults", self.defaults)
|
||||
preprocessors = kwargs.get("preprocessors", self.get_preprocessors)
|
||||
|
||||
kwargs.update(dict(
|
||||
merged=merged,
|
||||
asdict=asdict,
|
||||
defaults=defaults,
|
||||
preprocessors=preprocessors
|
||||
))
|
||||
|
||||
return self.settings.get(self._prefix_path(), **kwargs)
|
||||
|
||||
def clean_all_data(self):
|
||||
self.settings.remove(self._prefix_path())
|
||||
|
||||
def __getattr__(self, item):
|
||||
all_access_methods = self.access_methods.keys() + self.deprecated_access_methods.keys()
|
||||
if item in all_access_methods:
|
||||
|
||||
@@ -861,7 +861,7 @@ class PluginManager(object):
|
||||
additional_pre_inits=additional_pre_inits,
|
||||
additional_post_inits=additional_post_inits)
|
||||
|
||||
self.logger.info("Initialized {count} plugin(s)".format(count=len(self.plugin_implementations)))
|
||||
self.logger.info("Initialized {count} plugin implementation(s)".format(count=len(self.plugin_implementations)))
|
||||
|
||||
def initialize_implementation_of_plugin(self, name, plugin, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
|
||||
if plugin.implementation is None:
|
||||
@@ -955,15 +955,13 @@ class PluginManager(object):
|
||||
self.logger.info("No plugins available")
|
||||
else:
|
||||
self.logger.info("{count} plugin(s) registered with the system:\n{plugins}".format(count=len(all_plugins), plugins="\n".join(
|
||||
sorted(
|
||||
map(lambda x: "| " + x.long_str(show_bundled=show_bundled,
|
||||
bundled_strs=bundled_str,
|
||||
show_location=show_location,
|
||||
location_str=location_str,
|
||||
show_enabled=show_enabled,
|
||||
enabled_strs=enabled_str),
|
||||
self.enabled_plugins.values())
|
||||
)
|
||||
map(lambda x: "| " + x.long_str(show_bundled=show_bundled,
|
||||
bundled_strs=bundled_str,
|
||||
show_location=show_location,
|
||||
location_str=location_str,
|
||||
show_enabled=show_enabled,
|
||||
enabled_strs=enabled_str),
|
||||
sorted(self.plugins.values(), key=lambda x: str(x).lower()))
|
||||
)))
|
||||
|
||||
def get_plugin(self, identifier, require_enabled=True):
|
||||
|
||||
@@ -651,6 +651,24 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
return f
|
||||
return decorator
|
||||
|
||||
@staticmethod
|
||||
def errorhandler(code_or_exception):
|
||||
"""
|
||||
A decorator to mark errorhandlings methods in your BlueprintPlugin subclass. Works just the same as Flask's
|
||||
own ``errorhandler`` decorator available on blueprints.
|
||||
|
||||
See `the documentation for flask.Blueprint.errorhandler <http://flask.pocoo.org/docs/0.10/api/#flask.Blueprint.errorhandler>`_
|
||||
and `the documentation for flask.Flask.errorhandler <http://flask.pocoo.org/docs/0.10/api/#flask.Flask.errorhandler>`_ for more
|
||||
information.
|
||||
"""
|
||||
from collections import defaultdict
|
||||
def decorator(f):
|
||||
if not hasattr(f, "_blueprint_error_handler") or f._blueprint_error_handler is None:
|
||||
f._blueprint_error_handler = defaultdict(list)
|
||||
f._blueprint_error_handler[f.__name__].append(code_or_exception)
|
||||
return f
|
||||
return decorator
|
||||
|
||||
def get_blueprint(self):
|
||||
"""
|
||||
Creates and returns the blueprint for your plugin. Override this if you want to define and handle your blueprint yourself.
|
||||
@@ -660,15 +678,34 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
|
||||
:return: the blueprint ready to be registered with Flask
|
||||
"""
|
||||
|
||||
if hasattr(self, "_blueprint"):
|
||||
# if we already constructed the blueprint and hence have it cached,
|
||||
# return that instance - we don't want to instance it multiple times
|
||||
return self._blueprint
|
||||
|
||||
import flask
|
||||
kwargs = self.get_blueprint_kwargs()
|
||||
blueprint = flask.Blueprint("plugin." + self._identifier, self._identifier, **kwargs)
|
||||
|
||||
# we now iterate over all members of ourselves and look if we find an attribute
|
||||
# that has data originating from one of our decorators - we ignore anything
|
||||
# starting with a _ to only handle public stuff
|
||||
for member in [member for member in dir(self) if not member.startswith("_")]:
|
||||
f = getattr(self, member)
|
||||
|
||||
if hasattr(f, "_blueprint_rules") and member in f._blueprint_rules:
|
||||
# this attribute was annotated with our @route decorator
|
||||
for blueprint_rule in f._blueprint_rules[member]:
|
||||
rule, options = blueprint_rule
|
||||
blueprint.add_url_rule(rule, options.pop("endpoint", f.__name__), view_func=f, **options)
|
||||
|
||||
if hasattr(f, "_blueprint_error_handler") and member in f._blueprint_error_handler:
|
||||
# this attribute was annotated with our @error_handler decorator
|
||||
for code_or_exception in f._blueprint_error_handler[member]:
|
||||
blueprint.errorhandler(code_or_exception)(f)
|
||||
|
||||
# cache and return the blueprint object
|
||||
self._blueprint = blueprint
|
||||
return blueprint
|
||||
|
||||
def get_blueprint_kwargs(self):
|
||||
@@ -764,6 +801,9 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
the plugin core system upon initialization of the implementation.
|
||||
"""
|
||||
|
||||
config_version_key = "_config_version"
|
||||
"""Key of the field in the settings that holds the configuration format version."""
|
||||
|
||||
def on_settings_load(self):
|
||||
"""
|
||||
Loads the settings for the plugin, called by the Settings API view in order to retrieve all settings from
|
||||
@@ -781,9 +821,9 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
|
||||
:return: the current settings of the plugin, as a dictionary
|
||||
"""
|
||||
data = self._settings.get([], asdict=True, merged=True)
|
||||
if "_config_version" in data:
|
||||
del data["_config_version"]
|
||||
data = self._settings.get_all_data()
|
||||
if self.config_version_key in data:
|
||||
del data[self.config_version_key]
|
||||
return data
|
||||
|
||||
def on_settings_save(self, data):
|
||||
@@ -795,7 +835,8 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
.. note::
|
||||
|
||||
The default implementation will persist your plugin's settings as is, so just in the structure and in the
|
||||
types that were received by the Settings API view.
|
||||
types that were received by the Settings API view. Values identical to the default settings values
|
||||
will *not* be persisted.
|
||||
|
||||
If you need more granular control here, e.g. over the used data types, you'll need to override this method
|
||||
and iterate yourself over all your settings, retrieving them (if set) from the supplied received ``data``
|
||||
@@ -803,15 +844,38 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
|
||||
Arguments:
|
||||
data (dict): The settings dictionary to be saved for the plugin
|
||||
|
||||
Returns:
|
||||
dict: The settings that differed from the defaults and were actually saved.
|
||||
"""
|
||||
import octoprint.util
|
||||
|
||||
if "_config_version" in data:
|
||||
del data["_config_version"]
|
||||
# get the current data
|
||||
current = self._settings.get_all_data()
|
||||
if current is None:
|
||||
current = dict()
|
||||
|
||||
current = self._settings.get([], asdict=True, merged=True)
|
||||
merged = octoprint.util.dict_merge(current, data)
|
||||
self._settings.set([], merged)
|
||||
# merge our new data on top of it
|
||||
new_current = octoprint.util.dict_merge(current, data)
|
||||
if self.config_version_key in new_current:
|
||||
del new_current[self.config_version_key]
|
||||
|
||||
# determine diff dict that contains minimal set of changes against the
|
||||
# default settings - we only want to persist that, not everything
|
||||
diff = octoprint.util.dict_minimal_mergediff(self.get_settings_defaults(), new_current)
|
||||
|
||||
version = self.get_settings_version()
|
||||
|
||||
to_persist = dict(diff)
|
||||
if version:
|
||||
to_persist[self.config_version_key] = version
|
||||
|
||||
if to_persist:
|
||||
self._settings.set([], to_persist)
|
||||
else:
|
||||
self._settings.clean_all_data()
|
||||
|
||||
return diff
|
||||
|
||||
def get_settings_defaults(self):
|
||||
"""
|
||||
@@ -894,6 +958,49 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_settings_cleanup(self):
|
||||
"""
|
||||
Called after migration and initialization but before call to :func:`on_settings_initialized`.
|
||||
|
||||
Plugins may overwrite this method to perform additional clean up tasks.
|
||||
|
||||
The default implementation just minimizes the data persisted on disk to only contain
|
||||
the differences to the defaults (in case the current data was persisted with an older
|
||||
version of OctoPrint that still duplicated default data).
|
||||
"""
|
||||
import octoprint.util
|
||||
from octoprint.settings import NoSuchSettingsPath
|
||||
|
||||
try:
|
||||
# let's fetch the current persisted config (so only the data on disk,
|
||||
# without the defaults)
|
||||
config = self._settings.get_all_data(merged=False, incl_defaults=False, error_on_path=True)
|
||||
except NoSuchSettingsPath:
|
||||
# no config persisted, nothing to do => get out of here
|
||||
return
|
||||
|
||||
if config is None:
|
||||
# config is set to None, that doesn't make sense, kill it and leave
|
||||
self._settings.clean_all_data()
|
||||
return
|
||||
|
||||
if self.config_version_key in config and config[self.config_version_key] is None:
|
||||
# delete None entries for config version - it's the default, no need
|
||||
del config[self.config_version_key]
|
||||
|
||||
# calculate a minimal diff between the settings and the current config -
|
||||
# anything already in the settings will be removed from the persisted
|
||||
# config, no need to duplicate it
|
||||
defaults = self.get_settings_defaults()
|
||||
diff = octoprint.util.dict_minimal_mergediff(defaults, config)
|
||||
|
||||
if not diff:
|
||||
# no diff to defaults, no need to have anything persisted
|
||||
self._settings.clean_all_data()
|
||||
else:
|
||||
# diff => persist only that
|
||||
self._settings.set([], diff)
|
||||
|
||||
def on_settings_initialized(self):
|
||||
"""
|
||||
Called after the settings have been initialized and - if necessary - also been migrated through a call to
|
||||
|
||||
@@ -37,11 +37,10 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
##~~ TemplatePlugin API
|
||||
|
||||
def get_template_configs(self):
|
||||
from flask.ext.babel import gettext
|
||||
return [
|
||||
dict(type="settings", name=gettext("CuraEngine"))
|
||||
]
|
||||
def get_template_vars(self):
|
||||
return dict(
|
||||
homepage=__plugin_url__
|
||||
)
|
||||
|
||||
##~~ StartupPlugin API
|
||||
|
||||
@@ -393,7 +392,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
def _save_profile(self, path, profile, allow_overwrite=True):
|
||||
import yaml
|
||||
with open(path, "wb") as f:
|
||||
with octoprint.util.atomic_write(path, "wb") as f:
|
||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
|
||||
def _convert_to_engine(self, profile_path, printer_profile, posX, posY):
|
||||
@@ -413,9 +412,9 @@ def _sanitize_name(name):
|
||||
sanitized_name = sanitized_name.replace(" ", "_")
|
||||
return sanitized_name.lower()
|
||||
|
||||
__plugin_name__ = "CuraEngine"
|
||||
__plugin_name__ = "CuraEngine (<= 15.04)"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura"
|
||||
__plugin_description__ = "Adds support for slicing via CuraEngine from within OctoPrint"
|
||||
__plugin_description__ = "Adds support for slicing via CuraEngine versions up to and including version 15.04 from within OctoPrint"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = CuraPlugin()
|
||||
@@ -31,6 +31,11 @@ class MachineShapeTypes(object):
|
||||
SQUARE = "square"
|
||||
CIRCULAR = "circular"
|
||||
|
||||
class RetractionCombingTypes(object):
|
||||
OFF = "off"
|
||||
ALL = "all"
|
||||
NO_SKIN = "no skin"
|
||||
|
||||
class GcodeFlavors(object):
|
||||
REPRAP = "reprap"
|
||||
REPRAP_VOLUME = "reprap_volume"
|
||||
@@ -45,7 +50,7 @@ defaults = dict(
|
||||
wall_thickness=0.8,
|
||||
solid_layer_thickness=0.6,
|
||||
print_temperature=[220, 0, 0, 0],
|
||||
print_bed_temperature=70,
|
||||
print_bed_temperature=0,
|
||||
platform_adhesion=PlatformAdhesionTypes.NONE,
|
||||
filament_diameter=[2.85, 0, 0, 0],
|
||||
filament_flow=100.0,
|
||||
@@ -390,6 +395,11 @@ class Profile(object):
|
||||
"Both": SupportDualTypes.BOTH,
|
||||
"First extruder": SupportDualTypes.FIRST,
|
||||
"Second extruder": SupportDualTypes.SECOND
|
||||
},
|
||||
retraction_combing={
|
||||
"Off": RetractionCombingTypes.OFF,
|
||||
"All": RetractionCombingTypes.ALL,
|
||||
"No Skin": RetractionCombingTypes.NO_SKIN
|
||||
}
|
||||
)
|
||||
|
||||
@@ -865,7 +875,7 @@ class Profile(object):
|
||||
"retractionAmountExtruderSwitch": self.get_microns("retraction_dual_amount"),
|
||||
"retractionZHop": self.get_microns("retraction_hop"),
|
||||
"minimalExtrusionBeforeRetraction": self.get_microns("retraction_minimal_extrusion"),
|
||||
"enableCombing": 1 if self.get_boolean("retraction_combing") else 0,
|
||||
"enableCombing": 1 if self.get("retraction_combing") == RetractionCombingTypes.ALL else (2 if self.get("retraction_combing") == RetractionCombingTypes.NO_SKIN else 0),
|
||||
"multiVolumeOverlap": self.get_microns("overlap_dual"),
|
||||
"objectSink": max(0, self.get_microns("object_sink")),
|
||||
"minimalLayerTime": self.get_int("cool_min_layer_time"),
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
<h4>{{ _('General') }}</h4>
|
||||
|
||||
<p>{% trans %}
|
||||
Specify the path to the CuraEngine binary. Note that only
|
||||
<strong>versions up to and including 15.04</strong> are supported.
|
||||
CuraEngine version 15.06 or newer is <strong>not</strong>
|
||||
compatible with this plugin.
|
||||
{% endtrans %}</p>
|
||||
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-cura-path">{{ _('Path to CuraEngine') }}</label>
|
||||
@@ -10,7 +17,7 @@
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.cura.debug_logging"> {{ _('Log the output of CuraEngine to plugin_cura_engine.log') }}
|
||||
<input type="checkbox" data-bind="checked: settings.plugins.cura.debug_logging"> {{ _('Log the output of CuraEngine to <code>plugin_cura_engine.log</code>') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
@@ -53,6 +60,10 @@
|
||||
|
||||
<button class="btn pull-right" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
|
||||
|
||||
<div style="clear: both">
|
||||
<small>{% trans %}For more information on configuration and usage please <a href="{{ plugin_cura_homepage }}" target="_blank">see the Plugin's homepage</a>.{% endtrans %}</small>
|
||||
</div>
|
||||
|
||||
<div id="settings_plugin_cura_import" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
@@ -98,6 +109,13 @@
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<small>{% trans %}
|
||||
You can import your existing profile <code>.ini</code> files from Cura (version up to and
|
||||
including 15.04) here. Please be aware that neither the <code>.json</code> profile format
|
||||
from Cura versions starting with 15.06 is supported, nor are the custom Cura profile formats
|
||||
that third party tools like e.g. Repetier create.
|
||||
{% endtrans %}</small>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
|
||||
@@ -11,7 +11,7 @@ import octoprint.plugin.core
|
||||
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server import admin_permission
|
||||
from octoprint.server import admin_permission, VERSION
|
||||
from octoprint.util.pip import PipCaller, UnknownPip
|
||||
|
||||
from flask import jsonify, make_response
|
||||
@@ -39,6 +39,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._pending_uninstall = set()
|
||||
|
||||
self._pip_caller = None
|
||||
self._pip_version_dependency_links = pkg_resources.parse_version("1.5")
|
||||
|
||||
self._repository_available = False
|
||||
self._repository_plugins = []
|
||||
@@ -80,13 +81,24 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return dict(
|
||||
repository="http://plugins.octoprint.org/plugins.json",
|
||||
repository_ttl=24*60,
|
||||
pip=None
|
||||
pip=None,
|
||||
pip_args=None,
|
||||
dependency_links=False,
|
||||
hidden=[]
|
||||
)
|
||||
|
||||
def on_settings_save(self, data):
|
||||
old_pip = self._settings.get(["pip"])
|
||||
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
|
||||
new_pip = self._settings.get(["pip"])
|
||||
|
||||
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
|
||||
self._pip_caller.refresh = True
|
||||
if old_pip != new_pip:
|
||||
self._pip_caller.configured = new_pip
|
||||
try:
|
||||
self._pip_caller.trigger_refresh()
|
||||
except:
|
||||
self._pip_caller
|
||||
|
||||
##~~ AssetPlugin
|
||||
|
||||
@@ -166,7 +178,20 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
if "refresh_repository" in request.values and request.values["refresh_repository"] in valid_boolean_trues:
|
||||
self._repository_available = self._refresh_repository()
|
||||
|
||||
return jsonify(plugins=result, repository=dict(available=self._repository_available, plugins=self._repository_plugins), os=self._get_os(), octoprint=self._get_octoprint_version())
|
||||
return jsonify(plugins=result,
|
||||
repository=dict(
|
||||
available=self._repository_available,
|
||||
plugins=self._repository_plugins
|
||||
),
|
||||
os=self._get_os(),
|
||||
octoprint=VERSION,
|
||||
pip=dict(
|
||||
available=self._pip_caller.available,
|
||||
command=self._pip_caller.command,
|
||||
version=self._pip_caller.version_string,
|
||||
use_sudo=self._pip_caller.use_sudo,
|
||||
additional_args=self._settings.get(["pip_args"])
|
||||
))
|
||||
|
||||
def on_api_command(self, command, data):
|
||||
if not admin_permission.can():
|
||||
@@ -181,6 +206,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
plugin_name = data["plugin"] if "plugin" in data else None
|
||||
return self.command_install(url=url,
|
||||
force="force" in data and data["force"] in valid_boolean_trues,
|
||||
dependency_links="dependency_links" in data and data["dependency_links"] in valid_boolean_trues,
|
||||
reinstall=plugin_name)
|
||||
|
||||
elif command == "uninstall":
|
||||
@@ -199,7 +225,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
plugin = self._plugin_manager.plugins[plugin_name]
|
||||
return self.command_toggle(plugin, command)
|
||||
|
||||
def command_install(self, url=None, path=None, force=False, reinstall=None):
|
||||
def command_install(self, url=None, path=None, force=False, reinstall=None, dependency_links=False):
|
||||
if url is not None:
|
||||
pip_args = ["install", sarge.shell_quote(url)]
|
||||
elif path is not None:
|
||||
@@ -207,6 +233,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
else:
|
||||
raise ValueError("Either url or path must be provided")
|
||||
|
||||
if dependency_links or self._settings.get_boolean(["dependency_links"]):
|
||||
pip_args.append("--process-dependency-links")
|
||||
|
||||
all_plugins_before = self._plugin_manager.find_plugins()
|
||||
|
||||
success_string = "Successfully installed"
|
||||
@@ -415,8 +444,21 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
def _call_pip(self, args):
|
||||
if self._pip_caller is None or not self._pip_caller.available:
|
||||
raise RuntimeError(u"No pip available, can't operate".format(**locals()))
|
||||
|
||||
if "--process-dependency-links" in args:
|
||||
self._log_message(u"Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version")
|
||||
if self._pip_caller < self._pip_version_dependency_links:
|
||||
args.remove("--process-dependency-links")
|
||||
|
||||
additional_args = self._settings.get(["pip_args"])
|
||||
if additional_args:
|
||||
args.append(additional_args)
|
||||
|
||||
return self._pip_caller.execute(*args)
|
||||
|
||||
def _log_message(self, *lines):
|
||||
self._log(lines, prefix=u"*", stream="message")
|
||||
|
||||
def _log_call(self, *lines):
|
||||
self._log(lines, prefix=u" ", stream="call")
|
||||
|
||||
@@ -494,7 +536,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
try:
|
||||
import json
|
||||
with open(self._repository_cache_path, "w+b") as f:
|
||||
with octoprint.util.atomic_write(self._repository_cache_path, "wb") as f:
|
||||
json.dump(repo_data, f)
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, str(e)))
|
||||
@@ -508,13 +550,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return False
|
||||
|
||||
current_os = self._get_os()
|
||||
octoprint_version = self._get_octoprint_version()
|
||||
if "-" in octoprint_version:
|
||||
octoprint_version = octoprint_version[:octoprint_version.find("-")]
|
||||
octoprint_version = self._get_octoprint_version(base=True)
|
||||
|
||||
def map_repository_entry(entry):
|
||||
result = dict(entry)
|
||||
|
||||
if not "follow_dependency_links" in result:
|
||||
result["follow_dependency_links"] = False
|
||||
|
||||
result["is_compatible"] = dict(
|
||||
octoprint=True,
|
||||
os=True
|
||||
@@ -532,12 +575,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._repository_plugins = map(map_repository_entry, repo_data)
|
||||
return True
|
||||
|
||||
def _is_octoprint_compatible(self, octoprint_version_string, compatibility_entries):
|
||||
def _is_octoprint_compatible(self, octoprint_version, compatibility_entries):
|
||||
"""
|
||||
Tests if the current ``octoprint_version`` is compatible to any of the provided ``compatibility_entries``.
|
||||
"""
|
||||
|
||||
octoprint_version = pkg_resources.parse_version(octoprint_version_string)
|
||||
for octo_compat in compatibility_entries:
|
||||
if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")):
|
||||
octo_compat = ">={}".format(octo_compat)
|
||||
@@ -566,9 +608,30 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
else:
|
||||
return "unknown"
|
||||
|
||||
def _get_octoprint_version(self):
|
||||
from octoprint._version import get_versions
|
||||
return get_versions()["version"]
|
||||
def _get_octoprint_version_string(self):
|
||||
return VERSION
|
||||
|
||||
def _get_octoprint_version(self, base=False):
|
||||
octoprint_version_string = self._get_octoprint_version_string()
|
||||
|
||||
if "-" in octoprint_version_string:
|
||||
octoprint_version_string = octoprint_version_string[:octoprint_version_string.find("-")]
|
||||
|
||||
octoprint_version = pkg_resources.parse_version(octoprint_version_string)
|
||||
if base:
|
||||
if isinstance(octoprint_version, tuple):
|
||||
# old setuptools
|
||||
base_version = []
|
||||
for part in octoprint_version:
|
||||
if part.startswith("*"):
|
||||
break
|
||||
base_version.append(part)
|
||||
base_version.append("*final")
|
||||
octoprint_version = tuple(base_version)
|
||||
else:
|
||||
# new setuptools
|
||||
octoprint_version = pkg_resources.parse_version(octoprint_version.base_version)
|
||||
return octoprint_version
|
||||
|
||||
def _to_external_representation(self, plugin):
|
||||
return dict(
|
||||
@@ -584,7 +647,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
pending_enable=(not plugin.enabled and plugin.key in self._pending_enable),
|
||||
pending_disable=(plugin.enabled and plugin.key in self._pending_disable),
|
||||
pending_install=(plugin.key in self._pending_install),
|
||||
pending_uninstall=(plugin.key in self._pending_uninstall)
|
||||
pending_uninstall=(plugin.key in self._pending_uninstall),
|
||||
origin=plugin.origin.type
|
||||
)
|
||||
|
||||
__plugin_name__ = "Plugin Manager"
|
||||
|
||||
@@ -6,6 +6,13 @@ $(function() {
|
||||
self.settingsViewModel = parameters[1];
|
||||
self.printerState = parameters[2];
|
||||
|
||||
self.config_repositoryUrl = ko.observable();
|
||||
self.config_repositoryTtl = ko.observable();
|
||||
self.config_pipCommand = ko.observable();
|
||||
self.config_pipAdditionalArgs = ko.observable();
|
||||
|
||||
self.configurationDialog = $("#settings_plugin_pluginmanager_configurationdialog");
|
||||
|
||||
self.plugins = new ItemListHelper(
|
||||
"plugin.pluginmanager.installedplugins",
|
||||
{
|
||||
@@ -70,12 +77,20 @@ $(function() {
|
||||
self.loglines = ko.observableArray([]);
|
||||
self.installedPlugins = ko.observableArray([]);
|
||||
|
||||
self.followDependencyLinks = ko.observable(false);
|
||||
|
||||
self.pipAvailable = ko.observable(false);
|
||||
self.pipCommand = ko.observable();
|
||||
self.pipVersion = ko.observable();
|
||||
self.pipUseSudo = ko.observable();
|
||||
self.pipAdditionalArgs = ko.observable();
|
||||
|
||||
self.working = ko.observable(false);
|
||||
self.workingTitle = ko.observable();
|
||||
self.workingDialog = undefined;
|
||||
self.workingOutput = undefined;
|
||||
|
||||
self.enableManagement = ko.computed(function() {
|
||||
self.enableManagement = ko.pureComputed(function() {
|
||||
return !self.printerState.isPrinting();
|
||||
});
|
||||
|
||||
@@ -84,31 +99,35 @@ $(function() {
|
||||
};
|
||||
|
||||
self.enableUninstall = function(data) {
|
||||
return self.enableManagement() && !data.bundled && data.key != 'pluginmanager' && !data.pending_uninstall;
|
||||
return self.enableManagement()
|
||||
&& (data.origin != "entry_point" || self.pipAvailable())
|
||||
&& !data.bundled
|
||||
&& data.key != 'pluginmanager'
|
||||
&& !data.pending_uninstall;
|
||||
};
|
||||
|
||||
self.enableRepoInstall = function(data) {
|
||||
return self.enableManagement() && self.isCompatible(data);
|
||||
return self.enableManagement() && self.pipAvailable() && self.isCompatible(data);
|
||||
};
|
||||
|
||||
self.invalidUrl = ko.computed(function() {
|
||||
self.invalidUrl = ko.pureComputed(function() {
|
||||
var url = self.installUrl();
|
||||
return url !== undefined && url.trim() != "" && !(_.startsWith(url.toLocaleLowerCase(), "http://") || _.startsWith(url.toLocaleLowerCase(), "https://"));
|
||||
});
|
||||
|
||||
self.enableUrlInstall = ko.computed(function() {
|
||||
self.enableUrlInstall = ko.pureComputed(function() {
|
||||
var url = self.installUrl();
|
||||
return self.enableManagement() && url !== undefined && url.trim() != "" && !self.invalidUrl();
|
||||
return self.enableManagement() && self.pipAvailable() && url !== undefined && url.trim() != "" && !self.invalidUrl();
|
||||
});
|
||||
|
||||
self.invalidArchive = ko.computed(function() {
|
||||
self.invalidArchive = ko.pureComputed(function() {
|
||||
var name = self.uploadFilename();
|
||||
return name !== undefined && !(_.endsWith(name.toLocaleLowerCase(), ".zip") || _.endsWith(name.toLocaleLowerCase(), ".tar.gz") || _.endsWith(name.toLocaleLowerCase(), ".tgz") || _.endsWith(name.toLocaleLowerCase(), ".tar"));
|
||||
});
|
||||
|
||||
self.enableArchiveInstall = ko.computed(function() {
|
||||
self.enableArchiveInstall = ko.pureComputed(function() {
|
||||
var name = self.uploadFilename();
|
||||
return self.enableManagement() && name !== undefined && name.trim() != "" && !self.invalidArchive();
|
||||
return self.enableManagement() && self.pipAvailable() && name !== undefined && name.trim() != "" && !self.invalidArchive();
|
||||
});
|
||||
|
||||
self.uploadElement.fileupload({
|
||||
@@ -125,6 +144,9 @@ $(function() {
|
||||
self.uploadButton.unbind("click");
|
||||
self.uploadButton.bind("click", function() {
|
||||
self._markWorking(gettext("Installing plugin..."), gettext("Installing plugin from uploaded archive..."));
|
||||
data.formData = {
|
||||
dependency_links: self.followDependencyLinks()
|
||||
};
|
||||
data.submit();
|
||||
return false;
|
||||
});
|
||||
@@ -162,7 +184,8 @@ $(function() {
|
||||
|
||||
self.fromResponse = function(data) {
|
||||
self._fromPluginsResponse(data.plugins);
|
||||
self._fromRepositoryResponse(data.repository)
|
||||
self._fromRepositoryResponse(data.repository);
|
||||
self._fromPipResponse(data.pip);
|
||||
};
|
||||
|
||||
self._fromPluginsResponse = function(data) {
|
||||
@@ -183,6 +206,21 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self._fromPipResponse = function(data) {
|
||||
self.pipAvailable(data.available);
|
||||
if (data.available) {
|
||||
self.pipCommand(data.command);
|
||||
self.pipVersion(data.version);
|
||||
self.pipUseSudo(data.use_sudo);
|
||||
self.pipAdditionalArgs(data.additional_args);
|
||||
} else {
|
||||
self.pipCommand(undefined);
|
||||
self.pipVersion(undefined);
|
||||
self.pipUseSudo(undefined);
|
||||
self.pipAdditionalArgs(undefined);
|
||||
}
|
||||
};
|
||||
|
||||
self.requestData = function(includeRepo) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
return;
|
||||
@@ -240,13 +278,13 @@ $(function() {
|
||||
}
|
||||
|
||||
if (self.installed(data)) {
|
||||
self.installPlugin(data.archive, data.title, data.id);
|
||||
self.installPlugin(data.archive, data.title, data.id, data.follow_dependency_links || self.followDependencyLinks());
|
||||
} else {
|
||||
self.installPlugin(data.archive, data.title, undefined);
|
||||
self.installPlugin(data.archive, data.title, undefined, data.follow_dependency_links || self.followDependencyLinks());
|
||||
}
|
||||
};
|
||||
|
||||
self.installPlugin = function(url, name, reinstall) {
|
||||
self.installPlugin = function(url, name, reinstall, followDependencyLinks) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
return;
|
||||
}
|
||||
@@ -260,6 +298,10 @@ $(function() {
|
||||
}
|
||||
if (!url) return;
|
||||
|
||||
if (followDependencyLinks === undefined) {
|
||||
followDependencyLinks = self.followDependencyLinks();
|
||||
}
|
||||
|
||||
var workTitle, workText;
|
||||
if (!reinstall) {
|
||||
workTitle = gettext("Installing plugin...");
|
||||
@@ -275,7 +317,7 @@ $(function() {
|
||||
self._markWorking(workTitle, workText);
|
||||
|
||||
var command = "install";
|
||||
var payload = {url: url};
|
||||
var payload = {url: url, dependency_links: followDependencyLinks};
|
||||
if (reinstall) {
|
||||
payload["plugin"] = reinstall;
|
||||
payload["force"] = true;
|
||||
@@ -334,6 +376,58 @@ $(function() {
|
||||
self.requestData(true);
|
||||
};
|
||||
|
||||
self.showPluginSettings = function() {
|
||||
self._copyConfig();
|
||||
self.configurationDialog.modal();
|
||||
};
|
||||
|
||||
self.savePluginSettings = function() {
|
||||
var pipCommand = self.config_pipCommand();
|
||||
if (pipCommand != undefined && pipCommand.trim() == "") {
|
||||
pipCommand = null;
|
||||
}
|
||||
|
||||
var repository = self.config_repositoryUrl();
|
||||
if (repository != undefined && repository.trim() == "") {
|
||||
repository = null;
|
||||
}
|
||||
|
||||
var repositoryTtl;
|
||||
try {
|
||||
repositoryTtl = parseInt(self.config_repositoryTtl());
|
||||
} catch (ex) {
|
||||
repositoryTtl = null;
|
||||
}
|
||||
|
||||
var pipArgs = self.config_pipAdditionalArgs();
|
||||
if (pipArgs != undefined && pipArgs.trim() == "") {
|
||||
pipArgs = null;
|
||||
}
|
||||
|
||||
var data = {
|
||||
plugins: {
|
||||
pluginmanager: {
|
||||
repository: repository,
|
||||
repository_ttl: repositoryTtl,
|
||||
pip: pipCommand,
|
||||
pip_args: pipArgs
|
||||
}
|
||||
}
|
||||
};
|
||||
self.settingsViewModel.saveData(data, function() {
|
||||
self.configurationDialog.modal("hide");
|
||||
self._copyConfig();
|
||||
self.refreshRepository();
|
||||
});
|
||||
};
|
||||
|
||||
self._copyConfig = function() {
|
||||
self.config_repositoryUrl(self.settingsViewModel.settings.plugins.pluginmanager.repository());
|
||||
self.config_repositoryTtl(self.settingsViewModel.settings.plugins.pluginmanager.repository_ttl());
|
||||
self.config_pipCommand(self.settingsViewModel.settings.plugins.pluginmanager.pip());
|
||||
self.config_pipAdditionalArgs(self.settingsViewModel.settings.plugins.pluginmanager.pip_args());
|
||||
};
|
||||
|
||||
self.installed = function(data) {
|
||||
return _.includes(self.installedPlugins(), data.id);
|
||||
};
|
||||
|
||||
@@ -4,7 +4,31 @@
|
||||
</div>
|
||||
{% endmacro %}
|
||||
|
||||
{% macro pluginmanager_nopip() %}
|
||||
<div class="alert" data-bind="visible: !pipAvailable()">{% trans %}
|
||||
The <code>pip</code> command could not be found.
|
||||
Please configure it manually. No installation and uninstallation of plugin
|
||||
packages is possible while <code>pip</code> is unavailable.
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{% macro pluginmanager_sudopip() %}
|
||||
<div class="alert alert-error" data-bind="visible: pipUseSudo()">{% trans %}
|
||||
The <code>pip</code> command is configured to use <code>sudo</code>. This
|
||||
is <strong>not</strong> recommended due to security reasons. It is <strong>strongly</strong>
|
||||
suggested you install OctoPrint under a
|
||||
<a href="https://github.com/foosel/OctoPrint/#installation">user-owned virtual environment</a>
|
||||
so that the use of <code>sudo</code> is not needed for plugin management.
|
||||
{% endtrans %}</div>
|
||||
{% endmacro %}
|
||||
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_sudopip() }}
|
||||
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Installed Plugins') }}</h3>
|
||||
|
||||
@@ -47,6 +71,10 @@
|
||||
|
||||
<button class="btn btn-block" data-bind="click: $root.showRepository">{{ _('Get More...') }}</button>
|
||||
|
||||
<p class="muted" data-bind="visible: pipAvailable()">
|
||||
<small>Using pip at "<span data-bind="text: pipCommand"></span>" (Version <span data-bind="text: pipVersion"></span><span data-bind="visible: pipAdditionalArgs">, additional arguments: <span data-bind="text: pipAdditionalArgs"></span></span>)</small>
|
||||
</p>
|
||||
|
||||
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
@@ -67,6 +95,8 @@
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
{{ pluginmanager_printing() }}
|
||||
{{ pluginmanager_nopip() }}
|
||||
{{ pluginmanager_sudopip() }}
|
||||
<h4 style="position: relative">
|
||||
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
|
||||
<a class="dropdown-toggle pull-right" data-toggle="dropdown" href="#">
|
||||
@@ -147,8 +177,67 @@
|
||||
</div>
|
||||
<span class="help-block" data-bind="visible: invalidArchive">{{ _('This does not look like a valid plugin archive. Valid plugin archives should be either zip files or tarballs and have the extension ".zip", ".tar.gz", ".tgz" or ".tar"') }}</span>
|
||||
</form>
|
||||
|
||||
<div>
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: followDependencyLinks"> {{ _('Use <code>--process-dependency-links</code> with <code>pip install</code>') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="settings_plugin_pluginmanager_configurationdialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Plugin Configuration') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group" title="{{ _('pip command to use for managing plugins. You might have to configure this if auto detection fails.') }}">
|
||||
<label class="control-label">{{ _('pip command') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_pipCommand" placeholder="{{ _('Autodetect') }}">
|
||||
<span class="help-inline">{{ _('<strong>Only</strong> set this if OctoPrint cannot autodetect the path to <code>pip</code> to use for managing plugins.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Additional arguments for pip command. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Additional pip arguments') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_pipAdditionalArgs">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('URL of the Plugin Repository to use. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Repository URL') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_repositoryUrl">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('How long to cache repository data, in minutes. You should normally not have to change this.') }}">
|
||||
<label class="control-label">{{ _('Repository cache TTL') }}</label>
|
||||
<div class="controls">
|
||||
<div class="input-append">
|
||||
<input type="number" class="input-mini" data-bind="value: config_repositoryTtl">
|
||||
<span class="add-on">min</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: savePluginSettings" aria-hidden="true">{{ _('Save') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -12,12 +12,13 @@ import flask
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import hashlib
|
||||
|
||||
from . import version_checks, updaters, exceptions, util
|
||||
|
||||
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server import admin_permission
|
||||
from octoprint.server import admin_permission, VERSION, REVISION
|
||||
from octoprint.util import dict_merge
|
||||
import octoprint.settings
|
||||
|
||||
@@ -58,6 +59,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._refresh_configured_checks = False
|
||||
self._configured_checks = self._settings.get(["checks"], merged=True)
|
||||
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
|
||||
check_providers = self._settings.get(["check_providers"], merged=True)
|
||||
for name, hook in update_check_hooks.items():
|
||||
try:
|
||||
hook_checks = hook()
|
||||
@@ -65,9 +67,23 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._logger.exception("Error while retrieving update information from plugin {name}".format(**locals()))
|
||||
else:
|
||||
for key, data in hook_checks.items():
|
||||
check_providers[key] = name
|
||||
if key in self._configured_checks:
|
||||
data = dict_merge(data, self._configured_checks[key])
|
||||
self._configured_checks[key] = data
|
||||
self._settings.set(["check_providers"], check_providers)
|
||||
self._settings.save()
|
||||
|
||||
# we only want to process checks that came from plugins for
|
||||
# which the plugins are still installed and enabled
|
||||
config_checks = self._settings.get(["checks"])
|
||||
plugin_and_not_enabled = lambda k: k in check_providers and \
|
||||
not check_providers[k] in self._plugin_manager.enabled_plugins
|
||||
obsolete_plugin_checks = filter(plugin_and_not_enabled,
|
||||
config_checks.keys())
|
||||
for key in obsolete_plugin_checks:
|
||||
self._logger.debug("Check for key {} was provided by plugin {} that's no longer available, ignoring it".format(key, check_providers[key]))
|
||||
del self._configured_checks[key]
|
||||
|
||||
return self._configured_checks
|
||||
|
||||
@@ -83,8 +99,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._logger.exception("Error while loading version cache from disk")
|
||||
else:
|
||||
try:
|
||||
if "octoprint" in data and len(data["octoprint"]) == 4 and "local" in data["octoprint"][1] and "value" in data["octoprint"][1]["local"]:
|
||||
data_version = data["octoprint"][1]["local"]["value"]
|
||||
if not isinstance(data, dict):
|
||||
self._logger.info("Version cache was created in a different format, not using it")
|
||||
return
|
||||
|
||||
if "__version" in data:
|
||||
data_version = data["__version"]
|
||||
else:
|
||||
self._logger.info("Can't determine version of OctoPrint version cache was created for, not using it")
|
||||
return
|
||||
@@ -102,24 +122,18 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._logger.exception("Error parsing in version cache data")
|
||||
|
||||
def _save_version_cache(self):
|
||||
import tempfile
|
||||
import yaml
|
||||
import shutil
|
||||
from octoprint.util import atomic_write
|
||||
from octoprint._version import get_versions
|
||||
|
||||
file_obj = tempfile.NamedTemporaryFile(delete=False)
|
||||
try:
|
||||
octoprint_version = get_versions()["version"]
|
||||
self._version_cache["__version"] = octoprint_version
|
||||
|
||||
with atomic_write(self._version_cache_path) as file_obj:
|
||||
yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
file_obj.close()
|
||||
shutil.move(file_obj.name, self._version_cache_path)
|
||||
|
||||
self._version_cache_dirty = False
|
||||
self._logger.info("Saved version cache to disk")
|
||||
finally:
|
||||
try:
|
||||
if os.path.exists(file_obj.name):
|
||||
os.remove(file_obj.name)
|
||||
except Exception as e:
|
||||
self._logger.warn("Could not delete file {}: {}".format(file_obj.name, str(e)))
|
||||
self._version_cache_dirty = False
|
||||
self._logger.info("Saved version cache to disk")
|
||||
|
||||
#~~ SettingsPlugin API
|
||||
|
||||
@@ -134,10 +148,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
"restart": "octoprint"
|
||||
},
|
||||
},
|
||||
|
||||
"octoprint_restart_command": None,
|
||||
"environment_restart_command": None,
|
||||
"pip_command": None,
|
||||
"check_providers": {},
|
||||
|
||||
"cache_ttl": 24 * 60,
|
||||
}
|
||||
@@ -146,28 +158,92 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
data = dict(octoprint.plugin.SettingsPlugin.on_settings_load(self))
|
||||
if "checks" in data:
|
||||
del data["checks"]
|
||||
|
||||
checks = self._get_configured_checks()
|
||||
if "octoprint" in checks:
|
||||
if "checkout_folder" in checks["octoprint"]:
|
||||
data["octoprint_checkout_folder"] = checks["octoprint"]["checkout_folder"]
|
||||
elif "update_folder" in checks["octoprint"]:
|
||||
data["octoprint_checkout_folder"] = checks["octoprint"]["update_folder"]
|
||||
else:
|
||||
data["octoprint_checkout_folder"] = None
|
||||
data["octoprint_type"] = checks["octoprint"].get("type", None)
|
||||
else:
|
||||
data["octoprint_checkout_folder"] = None
|
||||
data["octoprint_type"] = None
|
||||
|
||||
return data
|
||||
|
||||
def on_settings_save(self, data):
|
||||
for key in self.get_settings_defaults():
|
||||
if key == "checks" or key == "cache_ttl":
|
||||
if key == "checks" or key == "cache_ttl" or key == "octoprint_checkout_folder" or key == "octoprint_type":
|
||||
continue
|
||||
if key in data:
|
||||
self._settings.set([key], data[key])
|
||||
|
||||
if "cache_ttl" in data:
|
||||
self._settings.set_int(["cache_ttl"], data["cache_ttl"])
|
||||
|
||||
self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60
|
||||
|
||||
checks = self._get_configured_checks()
|
||||
if "octoprint" in checks:
|
||||
check = checks["octoprint"]
|
||||
update_type = check.get("type", None)
|
||||
checkout_folder = check.get("checkout_folder", None)
|
||||
update_folder = check.get("update_folder", None)
|
||||
|
||||
defaults = dict(
|
||||
plugins=dict(softwareupdate=dict(
|
||||
checks=dict(
|
||||
octoprint=dict(
|
||||
type=update_type,
|
||||
checkout_folder=checkout_folder,
|
||||
update_folder=update_folder
|
||||
)
|
||||
)
|
||||
))
|
||||
)
|
||||
|
||||
if "octoprint_checkout_folder" in data:
|
||||
self._settings.set(["checks", "octoprint", "checkout_folder"], data["octoprint_checkout_folder"], defaults=defaults, force=True)
|
||||
if update_folder and data["octoprint_checkout_folder"]:
|
||||
self._settings.set(["checks", "octoprint", "update_folder"], None, defaults=defaults, force=True)
|
||||
self._refresh_configured_checks = True
|
||||
|
||||
if "octoprint_type" in data and data["octoprint_type"] in ("github_release", "git_commit"):
|
||||
self._settings.set(["checks", "octoprint", "type"], data["octoprint_type"], defaults=defaults, force=True)
|
||||
self._refresh_configured_checks = True
|
||||
|
||||
def get_settings_version(self):
|
||||
return 3
|
||||
return 4
|
||||
|
||||
def on_settings_migrate(self, target, current=None):
|
||||
|
||||
if current is None or current < 4:
|
||||
# config version 4 and higher moves octoprint_restart_command and
|
||||
# environment_restart_command to the core configuration
|
||||
|
||||
# current plugin commands
|
||||
configured_octoprint_restart_command = self._settings.get(["octoprint_restart_command"])
|
||||
configured_environment_restart_command = self._settings.get(["environment_restart_command"])
|
||||
|
||||
# current global commands
|
||||
configured_system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
|
||||
configured_server_restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||
|
||||
# only set global commands if they are not yet set
|
||||
if configured_system_restart_command is None and configured_environment_restart_command is not None:
|
||||
self._settings.global_set(["server", "commands", "systemRestartCommand"], configured_environment_restart_command)
|
||||
if configured_server_restart_command is None and configured_octoprint_restart_command is not None:
|
||||
self._settings.global_set(["server", "commands", "serverRestartCommand"], configured_octoprint_restart_command)
|
||||
|
||||
# delete current plugin commands from config
|
||||
self._settings.set(["environment_restart_command"], None)
|
||||
self._settings.set(["octoprint_restart_command"], None)
|
||||
|
||||
if current is None or current == 2:
|
||||
# there might be some left over data from the time we still persisted everything to settings,
|
||||
# even the stuff that shouldn't be persisted but always provided by the hook - let's
|
||||
# clean up
|
||||
# No config version and config version 2 need the same fix, stripping
|
||||
# accidentally persisted data off the checks
|
||||
|
||||
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
||||
if configured_checks is None:
|
||||
@@ -213,6 +289,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._settings.set(["checks", key], None, defaults=dummy_defaults)
|
||||
|
||||
elif current == 1:
|
||||
# config version 1 had the error that the octoprint check got accidentally
|
||||
# included in checks["octoprint"], leading to recursion and hence to
|
||||
# yaml parser errors
|
||||
|
||||
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
||||
if configured_checks is None:
|
||||
return
|
||||
@@ -223,7 +303,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
dummy_defaults["plugins"][self._identifier] = dict(checks=dict())
|
||||
dummy_defaults["plugins"][self._identifier]["checks"]["octoprint"] = None
|
||||
self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults)
|
||||
self._settings.save()
|
||||
|
||||
def _clean_settings_check(self, key, data, defaults, delete=None, save=True):
|
||||
if delete is None:
|
||||
@@ -256,7 +335,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
@restricted_access
|
||||
def check_for_update(self):
|
||||
if "check" in flask.request.values:
|
||||
check_targets = map(str.strip, flask.request.values["check"].split(","))
|
||||
check_targets = map(lambda x: x.strip(), flask.request.values["check"].split(","))
|
||||
else:
|
||||
check_targets = None
|
||||
|
||||
@@ -286,7 +365,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
json_data = flask.request.json
|
||||
|
||||
if "check" in json_data:
|
||||
check_targets = map(str.strip, json_data["check"])
|
||||
check_targets = map(lambda x: x.strip(), json_data["check"])
|
||||
else:
|
||||
check_targets = None
|
||||
|
||||
@@ -338,43 +417,62 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
continue
|
||||
|
||||
try:
|
||||
target_information, target_update_available, target_update_possible = self._get_current_version(target, check, force=force)
|
||||
populated_check = self._populated_check(target, check)
|
||||
target_information, target_update_available, target_update_possible = self._get_current_version(target, populated_check, force=force)
|
||||
if target_information is None:
|
||||
continue
|
||||
target_information = dict()
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.warn("Unknown update check type for %s" % target)
|
||||
self._logger.warn("Unknown update check type for target {}: {}".format(target, check.get("type", "<n/a>")))
|
||||
continue
|
||||
|
||||
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown")), target_information)
|
||||
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown", release_notes=None)), target_information)
|
||||
|
||||
update_available = update_available or target_update_available
|
||||
update_possible = update_possible or (target_update_possible and target_update_available)
|
||||
information[target] = dict(updateAvailable=target_update_available, updatePossible=target_update_possible, information=target_information)
|
||||
|
||||
if "displayName" in check:
|
||||
information[target]["displayName"] = check["displayName"]
|
||||
local_name = target_information["local"]["name"]
|
||||
local_value = target_information["local"]["value"]
|
||||
|
||||
if "displayVersion" in check:
|
||||
from octoprint._version import get_versions
|
||||
octoprint_version = get_versions()["version"]
|
||||
local_name = target_information["local"]["name"]
|
||||
local_value = target_information["local"]["value"]
|
||||
information[target]["displayVersion"] = check["displayVersion"].format(octoprint_version=octoprint_version, local_name=local_name, local_value=local_value)
|
||||
release_notes = None
|
||||
if target_information and target_information["remote"] and target_information["remote"]["value"]:
|
||||
if "release_notes" in populated_check and populated_check["release_notes"]:
|
||||
release_notes = populated_check["release_notes"]
|
||||
elif "release_notes" in target_information["remote"]:
|
||||
release_notes = target_information["remote"]["release_notes"]
|
||||
|
||||
if release_notes:
|
||||
release_notes = release_notes.format(octoprint_version=VERSION,
|
||||
target_name=target_information["remote"]["name"],
|
||||
target_version=target_information["remote"]["value"])
|
||||
|
||||
information[target] = dict(updateAvailable=target_update_available,
|
||||
updatePossible=target_update_possible,
|
||||
information=target_information,
|
||||
displayName=populated_check["displayName"],
|
||||
displayVersion=populated_check["displayVersion"].format(octoprint_version=VERSION, local_name=local_name, local_value=local_value),
|
||||
check=populated_check,
|
||||
releaseNotes=release_notes)
|
||||
|
||||
if self._version_cache_dirty:
|
||||
self._save_version_cache()
|
||||
return information, update_available, update_possible
|
||||
|
||||
def _get_check_hash(self, check):
|
||||
hash = hashlib.md5()
|
||||
hash.update(repr(check))
|
||||
return hash.hexdigest()
|
||||
|
||||
def _get_current_version(self, target, check, force=False):
|
||||
"""
|
||||
Determines the current version information for one target based on its check configuration.
|
||||
"""
|
||||
|
||||
current_hash = self._get_check_hash(check)
|
||||
if target in self._version_cache and not force:
|
||||
timestamp, information, update_available, update_possible = self._version_cache[target]
|
||||
if timestamp + self._version_cache_ttl >= time.time() > timestamp:
|
||||
data = self._version_cache[target]
|
||||
if data["hash"] == current_hash and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"]:
|
||||
# we also check that timestamp < now to not get confused too much by clock changes
|
||||
return information, update_available, update_possible
|
||||
return data["information"], data["available"], data["possible"]
|
||||
|
||||
information = dict()
|
||||
update_available = False
|
||||
@@ -397,7 +495,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
except:
|
||||
update_possible = False
|
||||
|
||||
self._version_cache[target] = (time.time(), information, update_available, update_possible)
|
||||
self._version_cache[target] = dict(timestamp=time.time(),
|
||||
hash=current_hash,
|
||||
information=information,
|
||||
available=update_available,
|
||||
possible=update_possible)
|
||||
self._version_cache_dirty = True
|
||||
return information, update_available, update_possible
|
||||
|
||||
@@ -412,19 +514,28 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
"""
|
||||
|
||||
checks = self._get_configured_checks()
|
||||
populated_checks = dict()
|
||||
for target, check in checks.items():
|
||||
try:
|
||||
populated_checks[target] = self._populated_check(target, check)
|
||||
except exceptions.UnknownCheckType:
|
||||
self._logger.debug("Ignoring unknown check type for target {}".format(target))
|
||||
except:
|
||||
self._logger.exception("Error while populating check prior to update for target {}".format(target))
|
||||
|
||||
if check_targets is None:
|
||||
check_targets = checks.keys()
|
||||
to_be_updated = sorted(set(check_targets) & set(checks.keys()))
|
||||
check_targets = populated_checks.keys()
|
||||
to_be_updated = sorted(set(check_targets) & set(populated_checks.keys()))
|
||||
if "octoprint" in to_be_updated:
|
||||
to_be_updated.remove("octoprint")
|
||||
tmp = ["octoprint"] + to_be_updated
|
||||
to_be_updated = tmp
|
||||
|
||||
updater_thread = threading.Thread(target=self._update_worker, args=(checks, to_be_updated, force))
|
||||
updater_thread = threading.Thread(target=self._update_worker, args=(populated_checks, to_be_updated, force))
|
||||
updater_thread.daemon = False
|
||||
updater_thread.start()
|
||||
|
||||
return to_be_updated, dict((key, check["displayName"] if "displayName" in check else key) for key, check in checks.items() if key in to_be_updated)
|
||||
return to_be_updated, dict((key, check["displayName"] if "displayName" in check else key) for key, check in populated_checks.items() if key in to_be_updated)
|
||||
|
||||
def _update_worker(self, checks, check_targets, force):
|
||||
|
||||
@@ -481,7 +592,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if restart_type is not None and restart_type in ("octoprint", "environment"):
|
||||
# one of our updates requires a restart of either type "octoprint" or "environment". Let's see if
|
||||
# we can actually perform that
|
||||
restart_command = self._settings.get(["%s_restart_command" % restart_type])
|
||||
|
||||
if restart_type == "octoprint":
|
||||
restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||
elif restart_type == "environment":
|
||||
restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
|
||||
|
||||
if restart_command is not None:
|
||||
self._send_client_message("restarting", dict(restart_type=restart_type, results=target_results))
|
||||
@@ -574,6 +689,31 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._logger.warn("Restart stderr:\n%s" % e.stderr)
|
||||
raise exceptions.RestartFailed()
|
||||
|
||||
def _populated_check(self, target, check):
|
||||
if not "type" in check:
|
||||
raise exceptions.UnknownCheckType()
|
||||
|
||||
result = dict(check)
|
||||
|
||||
if target == "octoprint":
|
||||
from flask.ext.babel import gettext
|
||||
result["displayName"] = check.get("displayName", gettext("OctoPrint"))
|
||||
result["displayVersion"] = check.get("displayVersion", "{octoprint_version}")
|
||||
|
||||
if check["type"] == "github_commit":
|
||||
result["current"] = REVISION if REVISION else "unknown"
|
||||
else:
|
||||
result["current"] = VERSION
|
||||
else:
|
||||
result["displayName"] = check.get("displayName", target)
|
||||
result["displayVersion"] = check.get("displayVersion", check.get("current", "unknown"))
|
||||
if check["type"] in ("github_commit"):
|
||||
result["current"] = check.get("current", None)
|
||||
else:
|
||||
result["current"] = check.get("current", check.get("displayVersion", None))
|
||||
|
||||
return result
|
||||
|
||||
def _get_version_checker(self, target, check):
|
||||
"""
|
||||
Retrieves the version checker to use for given target and check configuration. Will raise an UnknownCheckType
|
||||
@@ -583,13 +723,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if not "type" in check:
|
||||
raise exceptions.ConfigurationInvalid("no check type defined")
|
||||
|
||||
if target == "octoprint":
|
||||
from octoprint._version import get_versions
|
||||
from flask.ext.babel import gettext
|
||||
check["displayName"] = gettext("OctoPrint")
|
||||
check["displayVersion"] = "{octoprint_version}"
|
||||
check["current"] = get_versions()["version"]
|
||||
|
||||
check_type = check["type"]
|
||||
if check_type == "github_release":
|
||||
return version_checks.github_release
|
||||
|
||||
@@ -1 +1 @@
|
||||
td.settings_plugin_softwareupdate_column_update{width:16px}
|
||||
td.settings_plugin_softwareupdate_column_update{width:16px}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
|
||||
@@ -7,17 +7,30 @@ $(function() {
|
||||
self.settings = parameters[2];
|
||||
self.popup = undefined;
|
||||
|
||||
self.forceUpdate = false;
|
||||
|
||||
self.updateInProgress = false;
|
||||
self.waitingForRestart = false;
|
||||
self.restartTimeout = undefined;
|
||||
|
||||
self.currentlyBeingUpdated = [];
|
||||
|
||||
self.config_restartCommand = ko.observable();
|
||||
self.config_rebootCommand = ko.observable();
|
||||
self.octoprintUnconfigured = ko.observable();
|
||||
self.octoprintUnreleased = ko.observable();
|
||||
|
||||
self.config_cacheTtl = ko.observable();
|
||||
self.config_checkoutFolder = ko.observable();
|
||||
self.config_checkType = ko.observable();
|
||||
|
||||
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
|
||||
self.confirmationDialog = $("#softwareupdate_confirmation_dialog");
|
||||
|
||||
self.config_availableCheckTypes = [
|
||||
{"key": "github_release", "name": gettext("Release")},
|
||||
{"key": "git_commit", "name": gettext("Commit")}
|
||||
];
|
||||
|
||||
self.reloadOverlay = $("#reloadui_overlay");
|
||||
|
||||
self.versions = new ItemListHelper(
|
||||
"plugin.softwareupdate.versions",
|
||||
@@ -39,6 +52,10 @@ $(function() {
|
||||
5
|
||||
);
|
||||
|
||||
self.availableAndPossible = ko.computed(function() {
|
||||
return _.filter(self.versions.items(), function(info) { return info.updateAvailable && info.updatePossible; });
|
||||
});
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
self.performCheck();
|
||||
};
|
||||
@@ -78,19 +95,23 @@ $(function() {
|
||||
var data = {
|
||||
plugins: {
|
||||
softwareupdate: {
|
||||
octoprint_restart_command: self.config_restartCommand(),
|
||||
environment_restart_command: self.config_rebootCommand(),
|
||||
cache_ttl: parseInt(self.config_cacheTtl())
|
||||
cache_ttl: parseInt(self.config_cacheTtl()),
|
||||
octoprint_checkout_folder: self.config_checkoutFolder(),
|
||||
octoprint_type: self.config_checkType()
|
||||
}
|
||||
}
|
||||
};
|
||||
self.settings.saveData(data, function() { self.configurationDialog.modal("hide"); self._copyConfig(); });
|
||||
self.settings.saveData(data, function() {
|
||||
self.configurationDialog.modal("hide");
|
||||
self._copyConfig();
|
||||
self.performCheck();
|
||||
});
|
||||
};
|
||||
|
||||
self._copyConfig = function() {
|
||||
self.config_restartCommand(self.settings.settings.plugins.softwareupdate.octoprint_restart_command());
|
||||
self.config_rebootCommand(self.settings.settings.plugins.softwareupdate.environment_restart_command());
|
||||
self.config_cacheTtl(self.settings.settings.plugins.softwareupdate.cache_ttl());
|
||||
self.config_checkoutFolder(self.settings.settings.plugins.softwareupdate.octoprint_checkout_folder());
|
||||
self.config_checkType(self.settings.settings.plugins.softwareupdate.octoprint_type());
|
||||
};
|
||||
|
||||
self.fromCheckResponse = function(data, ignoreSeen, showIfNothingNew) {
|
||||
@@ -104,28 +125,61 @@ $(function() {
|
||||
if (!value.hasOwnProperty("displayVersion") || value.displayVersion == "") {
|
||||
value.displayVersion = value.information.local.name;
|
||||
}
|
||||
if (!value.hasOwnProperty("releaseNotes") || value.releaseNotes == "") {
|
||||
value.releaseNotes = undefined;
|
||||
}
|
||||
|
||||
var fullNameTemplate = gettext("%(name)s: %(version)s");
|
||||
value.fullNameLocal = _.sprintf(fullNameTemplate, {name: value.displayName, version: value.displayVersion});
|
||||
|
||||
var fullNameRemoteVars = {name: value.displayName, version: gettext("unknown")};
|
||||
if (value.hasOwnProperty("information") && value.information.hasOwnProperty("remote") && value.information.remote.hasOwnProperty("name")) {
|
||||
fullNameRemoteVars.version = value.information.remote.name;
|
||||
}
|
||||
value.fullNameRemote = _.sprintf(fullNameTemplate, fullNameRemoteVars);
|
||||
|
||||
versions.push(value);
|
||||
});
|
||||
self.versions.updateItems(versions);
|
||||
|
||||
if (data.status == "updateAvailable" || data.status == "updatePossible") {
|
||||
var text = gettext("There are updates available for the following components:");
|
||||
var octoprint = data.information["octoprint"];
|
||||
if (octoprint && octoprint.hasOwnProperty("check")) {
|
||||
var check = octoprint.check;
|
||||
if (BRANCH != "master" && check["type"] == "github_release") {
|
||||
self.octoprintUnreleased(true);
|
||||
} else {
|
||||
self.octoprintUnreleased(false);
|
||||
}
|
||||
|
||||
text += "<ul>";
|
||||
var checkoutFolder = (check["checkout_folder"] || "").trim();
|
||||
var updateFolder = (check["update_folder"] || "").trim();
|
||||
var checkType = check["type"] || "";
|
||||
if ((checkType == "github_release" || checkType == "git_commit") && checkoutFolder == "" && updateFolder == "") {
|
||||
self.octoprintUnconfigured(true);
|
||||
} else {
|
||||
self.octoprintUnconfigured(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (data.status == "updateAvailable" || data.status == "updatePossible") {
|
||||
var text = "<div class='softwareupdate_notification'>" + gettext("There are updates available for the following components:");
|
||||
|
||||
text += "<ul class='icons-ul'>";
|
||||
_.each(self.versions.items(), function(update_info) {
|
||||
if (update_info.updateAvailable) {
|
||||
var displayName = update_info.key;
|
||||
if (update_info.hasOwnProperty("displayName")) {
|
||||
displayName = update_info.displayName;
|
||||
}
|
||||
text += "<li>" + displayName + (update_info.updatePossible ? " <i class=\"icon-ok\"></i>" : "") + "</li>";
|
||||
text += "<li>"
|
||||
+ "<i class='icon-li " + (update_info.updatePossible ? "icon-ok" : "icon-remove")+ "'></i>"
|
||||
+ "<span class='name' title='" + update_info.fullNameRemote + "'>" + update_info.fullNameRemote + "</span>"
|
||||
+ (update_info.releaseNotes ? "<a href=\"" + update_info.releaseNotes + "\" target=\"_blank\">" + gettext("Release Notes") + "</a>" : "")
|
||||
+ "</li>";
|
||||
}
|
||||
});
|
||||
text += "</ul>";
|
||||
|
||||
text += "<small>" + gettext("Those components marked with <i class=\"icon-ok\"></i> can be updated directly.") + "</small>";
|
||||
|
||||
text += "</div>";
|
||||
|
||||
var options = {
|
||||
title: gettext("Update Available"),
|
||||
text: text,
|
||||
@@ -224,7 +278,7 @@ $(function() {
|
||||
return result;
|
||||
};
|
||||
|
||||
self.performUpdate = function(force) {
|
||||
self.performUpdate = function(force, items) {
|
||||
self.updateInProgress = true;
|
||||
|
||||
var options = {
|
||||
@@ -239,12 +293,19 @@ $(function() {
|
||||
};
|
||||
self._showPopup(options);
|
||||
|
||||
var postData = {
|
||||
force: (force == true)
|
||||
};
|
||||
if (items != undefined) {
|
||||
postData.check = items;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: PLUGIN_BASEURL + "softwareupdate/update",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify({force: (force == true)}),
|
||||
data: JSON.stringify(postData),
|
||||
error: function() {
|
||||
self.updateInProgress = false;
|
||||
self._showPopup({
|
||||
@@ -267,8 +328,6 @@ $(function() {
|
||||
if (self.updateInProgress) return;
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
|
||||
force = (force == true);
|
||||
|
||||
if (self.printerState.isPrinting()) {
|
||||
self._showPopup({
|
||||
title: gettext("Can't update while printing"),
|
||||
@@ -276,18 +335,18 @@ $(function() {
|
||||
type: "error"
|
||||
});
|
||||
} else {
|
||||
$("#confirmation_dialog .confirmation_dialog_message").text(gettext("This will update your OctoPrint installation and restart the server."));
|
||||
$("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click");
|
||||
$("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) {
|
||||
e.preventDefault();
|
||||
$("#confirmation_dialog").modal("hide");
|
||||
self.performUpdate(force);
|
||||
});
|
||||
$("#confirmation_dialog").modal("show");
|
||||
self.forceUpdate = (force == true);
|
||||
self.confirmationDialog.modal("show");
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
self.confirmUpdate = function() {
|
||||
self.confirmationDialog.hide();
|
||||
self.performUpdate(self.forceUpdate,
|
||||
_.map(self.availableAndPossible(), function(info) { return info.key }));
|
||||
};
|
||||
|
||||
self.onServerDisconnect = function() {
|
||||
if (self.restartTimeout !== undefined) {
|
||||
clearTimeout(self.restartTimeout);
|
||||
@@ -298,18 +357,10 @@ $(function() {
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
if (self.waitingForRestart) {
|
||||
self.waitingForRestart = false;
|
||||
|
||||
var options = {
|
||||
title: gettext("Restart successful!"),
|
||||
text: gettext("The server was restarted successfully. The page will now reload automatically."),
|
||||
type: "success",
|
||||
hide: false
|
||||
};
|
||||
self._showPopup(options);
|
||||
self.updateInProgress = false;
|
||||
|
||||
var delay = 5 + Math.floor(Math.random() * 5) + 1;
|
||||
setTimeout(function() {location.reload(true);}, delay * 1000);
|
||||
if (!self.reloadOverlay.is(":visible")) {
|
||||
self.reloadOverlay.show();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -362,7 +413,7 @@ $(function() {
|
||||
}
|
||||
});
|
||||
self.waitingForRestart = false;
|
||||
}, 20000);
|
||||
}, 60000);
|
||||
|
||||
break;
|
||||
}
|
||||
@@ -447,5 +498,9 @@ $(function() {
|
||||
}
|
||||
|
||||
// view model class, parameters for constructor, container to bind to
|
||||
ADDITIONAL_VIEWMODELS.push([SoftwareUpdateViewModel, ["loginStateViewModel", "printerStateViewModel", "settingsViewModel"], document.getElementById("settings_plugin_softwareupdate")]);
|
||||
ADDITIONAL_VIEWMODELS.push([
|
||||
SoftwareUpdateViewModel,
|
||||
["loginStateViewModel", "printerStateViewModel", "settingsViewModel"],
|
||||
["#settings_plugin_softwareupdate", "#softwareupdate_confirmation_dialog"]
|
||||
]);
|
||||
});
|
||||
@@ -1,3 +1,17 @@
|
||||
td.settings_plugin_softwareupdate_column_update {
|
||||
width: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.softwareupdate_notification {
|
||||
ul {
|
||||
margin: 10px 0 10px 25px;
|
||||
|
||||
.name {
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<div id="softwareupdate_confirmation_dialog" class="modal hide fade">
|
||||
<div class="modal-header">
|
||||
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">×</a>
|
||||
<h3>{{ _('Are you sure you want to update now?') }}</h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p>
|
||||
{{ _('This will update the following components and restart the server:') }}
|
||||
</p>
|
||||
<ul>
|
||||
<!-- ko foreach: availableAndPossible -->
|
||||
<li>
|
||||
<span class="name" data-bind="text: fullNameRemote, attr: {title: fullNameRemote}"></span>
|
||||
<div class="releaseNotes" data-bind="visible: releaseNotes"><a data-bind="attr: {href: releaseNotes}">{{ _('Release Notes') }}</a></div>
|
||||
</li>
|
||||
<!-- /ko -->
|
||||
</ul>
|
||||
<p>
|
||||
{{ _('Be sure to read through any linked release notes, especially those for OctoPrint since they might contain important information you need to know <strong>before</strong> upgrading.') }}
|
||||
</p>
|
||||
<p>
|
||||
{{ _('Are you sure you want to proceed?') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<a href="#" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</a>
|
||||
<a href="#" class="btn btn-danger" data-bind="click: function() { $root.confirmUpdate(); }">{{ _('Proceed') }}</a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,3 +1,21 @@
|
||||
<div class="alert" data-bind="visible: octoprintUnconfigured()">{% trans %}
|
||||
Please configure the <strong>checkout folder</strong> of OctoPrint, otherwise
|
||||
this plugin won't be able to update it. Click on the <i class="icon-wrench"></i> button
|
||||
to do this. Also refer to the <a href="https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update" target="_blank">Documentation</a>.
|
||||
{% endtrans %}</div>
|
||||
<div class="alert" data-bind="visible: !octoprintUnconfigured() && octoprintUnreleased()">{% trans %}
|
||||
<p>
|
||||
<strong>You are running a non-release version of OctoPrint but are tracking OctoPrint
|
||||
releases.</strong>
|
||||
</p><p>
|
||||
You probably want OctoPrint to track the matching development version instead.
|
||||
If you have a local OctoPrint checkout folder switched to another branch,
|
||||
<strong>simply switching over to "Commit" tracking</strong> will already
|
||||
take care of that. Otherwise please take a look at the
|
||||
<a href="https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update" target="_blank">Documentation</a>.
|
||||
</p>
|
||||
{% endtrans %}</div>
|
||||
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
|
||||
</div>
|
||||
@@ -11,10 +29,11 @@
|
||||
<span data-bind="invisible: !updateAvailable"><i class="icon-bell" title="{{ _('Update available') }}"></i></span>
|
||||
</td>
|
||||
<td class="settings_plugin_softwareupdate_column_information">
|
||||
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span><br>
|
||||
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="icon-exclamation-sign" title="{{ _('Update not possible, configuration ok?') }}"></i></span><br>
|
||||
<small class="muted">
|
||||
{{ _('Installed:') }} <span data-bind="text: information.local.name"></span><br>
|
||||
{{ _('Available:') }} <span data-bind="text: information.remote.name"></span>
|
||||
{{ _('Available:') }} <span data-bind="text: information.remote.name"></span><br>
|
||||
<span data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank"></a></span>
|
||||
</small>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -44,7 +63,7 @@
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }">{{ _('Force check for update (overrides cache used for update checks)') }}</button>
|
||||
<button class="btn btn-block btn-danger" data-bind="click: function() { $root.update(true); }">{{ _('Force update now (even if no new versions are available)') }}</button>
|
||||
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.update(true); }">{{ _('Force update now (even if no new versions are available)') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -56,15 +75,15 @@
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Restart Command') }}</label>
|
||||
<label class="control-label">{{ _('OctoPrint checkout folder') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_restartCommand">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_checkoutFolder">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Reboot Command') }}</label>
|
||||
<label class="control-label">{{ _('OctoPrint version tracking') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_rebootCommand">
|
||||
<select data-bind="value: config_checkType, options: config_availableCheckTypes, optionsText: 'name', optionsValue: 'key'"></select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
|
||||
@@ -7,13 +7,16 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
|
||||
import logging
|
||||
import pkg_resources
|
||||
|
||||
from octoprint.util.pip import PipCaller, UnknownPip
|
||||
from .. import exceptions
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip")
|
||||
console_logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip.console")
|
||||
|
||||
_pip_callers = dict()
|
||||
_pip_version_dependency_links = pkg_resources.parse_version("1.5")
|
||||
|
||||
def can_perform_update(target, check):
|
||||
pip_caller = _get_pip_caller(command=check["pip_command"] if "pip_command" in check else None)
|
||||
@@ -42,19 +45,26 @@ def perform_update(target, check, target_version):
|
||||
|
||||
pip_caller = _get_pip_caller(command=pip_command)
|
||||
if pip_caller is None:
|
||||
raise RuntimeError("Can't run pip")
|
||||
raise exceptions.UpdateError("Can't run pip", None)
|
||||
|
||||
install_arg = check["pip"].format(target_version=target_version)
|
||||
|
||||
logger.debug(u"Target: %s, executing pip install %s" % (target, install_arg))
|
||||
pip_args = ["install", check["pip"].format(target_version=target_version, target=target_version)]
|
||||
|
||||
pip_caller.execute(*pip_args)
|
||||
if "dependency_links" in check and check["dependency_links"] and pip_caller >= _pip_version_dependency_links:
|
||||
pip_args += ["--process-dependency-links"]
|
||||
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args)
|
||||
if returncode != 0:
|
||||
raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr))
|
||||
|
||||
logger.debug(u"Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg))
|
||||
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
|
||||
|
||||
pip_caller.execute(*pip_args)
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args)
|
||||
if returncode != 0:
|
||||
raise exceptions.UpdateError("Error while executing pip install --force-reinstall", (stdout, stderr))
|
||||
|
||||
return "ok"
|
||||
|
||||
|
||||
@@ -13,7 +13,17 @@ from ..util import execute
|
||||
|
||||
|
||||
def can_perform_update(target, check):
|
||||
return "update_script" in check and ("checkout_folder" in check or "update_folder" in check)
|
||||
import os
|
||||
script_configured = bool("update_script" in check and check["update_script"])
|
||||
|
||||
folder = None
|
||||
if "update_folder" in check:
|
||||
folder = check["update_folder"]
|
||||
elif "checkout_folder" in check:
|
||||
folder = check["checkout_folder"]
|
||||
folder_configured = bool(folder and os.path.isdir(folder))
|
||||
|
||||
return script_configured and folder_configured
|
||||
|
||||
|
||||
def perform_update(target, check, target_version):
|
||||
|
||||
@@ -65,7 +65,7 @@ def get_latest(target, check):
|
||||
if returncode != 0:
|
||||
return None, True
|
||||
|
||||
return_code, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder)
|
||||
returncode, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder)
|
||||
if returncode != 0:
|
||||
return None, True
|
||||
|
||||
|
||||
@@ -15,33 +15,40 @@ RELEASE_URL = "https://api.github.com/repos/{user}/{repo}/releases"
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_release")
|
||||
|
||||
def _get_latest_release(user, repo, include_prerelease=False):
|
||||
nothing = None, None, None
|
||||
r = requests.get(RELEASE_URL.format(user=user, repo=repo))
|
||||
|
||||
from . import log_github_ratelimit
|
||||
log_github_ratelimit(logger, r)
|
||||
|
||||
if not r.status_code == requests.codes.ok:
|
||||
return None, None
|
||||
return nothing
|
||||
|
||||
releases = r.json()
|
||||
|
||||
# sanitize
|
||||
required_fields = {"name", "tag_name", "html_url", "draft", "prerelease", "published_at"}
|
||||
releases = filter(lambda rel: set(rel.keys()) & required_fields == required_fields,
|
||||
releases)
|
||||
|
||||
# filter out prereleases and drafts
|
||||
if include_prerelease:
|
||||
releases = filter(lambda rel: not rel["draft"], releases)
|
||||
else:
|
||||
releases = filter(lambda rel: not rel["prerelease"] and not rel["draft"], releases)
|
||||
releases = filter(lambda rel: not rel["prerelease"] and not rel["draft"],
|
||||
releases)
|
||||
|
||||
if not releases:
|
||||
return None, None
|
||||
return nothing
|
||||
|
||||
# sort by date
|
||||
comp = lambda a, b: cmp(a["published_at"], b["published_at"])
|
||||
comp = lambda a, b: cmp(a.get("published_at", None), b["published_at"])
|
||||
releases = sorted(releases, cmp=comp)
|
||||
|
||||
# latest release = last in list
|
||||
latest = releases[-1]
|
||||
|
||||
return latest["name"], latest["tag_name"]
|
||||
return latest["name"], latest["tag_name"], latest.get("html_url", None)
|
||||
|
||||
|
||||
def _get_sanitized_version(version_string):
|
||||
@@ -122,14 +129,14 @@ def get_latest(target, check, custom_compare=None):
|
||||
include_prerelease = check.get("prerelease", False)
|
||||
force_base = check.get("force_base", True)
|
||||
|
||||
remote_name, remote_tag = _get_latest_release(check["user"],
|
||||
check["repo"],
|
||||
include_prerelease=include_prerelease)
|
||||
remote_name, remote_tag, release_notes = _get_latest_release(check["user"],
|
||||
check["repo"],
|
||||
include_prerelease=include_prerelease)
|
||||
compare_type = check["release_compare"] if "release_compare" in check else "python"
|
||||
|
||||
information =dict(
|
||||
local=dict(name=current, value=current),
|
||||
remote=dict(name=remote_name, value=remote_tag)
|
||||
remote=dict(name=remote_name, value=remote_tag, release_notes=release_notes)
|
||||
)
|
||||
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag))
|
||||
|
||||
@@ -61,14 +61,20 @@ class VirtualPrinter():
|
||||
self._selectedSdFileSize = None
|
||||
self._selectedSdFilePos = None
|
||||
self._writingToSd = False
|
||||
self._writingToSdHandle = None
|
||||
self._newSdFilePos = None
|
||||
self._heatupThread = None
|
||||
|
||||
self._okBeforeCommandOutput = settings().getBoolean(["devel", "virtualPrinter", "okBeforeCommandOutput"])
|
||||
self._supportM112 = settings().getBoolean(["devel", "virtualPrinter", "supportM112"])
|
||||
|
||||
self._sendWait = settings().getBoolean(["devel", "virtualPrinter", "sendWait"])
|
||||
self._waitInterval = settings().getFloat(["devel", "virtualPrinter", "waitInterval"])
|
||||
|
||||
self._echoOnM117 = settings().getBoolean(["devel", "virtualPrinter", "echoOnM117"])
|
||||
|
||||
self._brokenM29 = settings().getBoolean(["devel", "virtualPrinter", "brokenM29"])
|
||||
|
||||
self.currentLine = 0
|
||||
self.lastN = 0
|
||||
|
||||
@@ -83,6 +89,11 @@ class VirtualPrinter():
|
||||
|
||||
self._action_hooks = plugin_manager().get_hooks("octoprint.plugin.virtual_printer.custom_action")
|
||||
|
||||
self._killed = False
|
||||
|
||||
self._triggerResendAt100 = True
|
||||
self._triggerResendWithTimeoutAt105 = True
|
||||
self._triggeredResendWithTimeoutAt105 = False
|
||||
|
||||
waitThread = threading.Thread(target=self._sendWaitAfterTimeout)
|
||||
waitThread.start()
|
||||
@@ -106,7 +117,7 @@ class VirtualPrinter():
|
||||
|
||||
def _processIncoming(self):
|
||||
next_wait_timeout = time.time() + self._waitInterval
|
||||
while self.incoming is not None:
|
||||
while self.incoming is not None and not self._killed:
|
||||
self._simulateTemps()
|
||||
|
||||
try:
|
||||
@@ -141,6 +152,10 @@ class VirtualPrinter():
|
||||
linenumber = int(re.search("N([0-9]+)", data).group(1))
|
||||
self.lastN = linenumber
|
||||
self.currentLine = linenumber
|
||||
|
||||
self._triggerResendAt100 = True
|
||||
self._triggerResendWithTimeoutAt105 = True
|
||||
|
||||
self._sendOk()
|
||||
continue
|
||||
elif data.startswith("N"):
|
||||
@@ -149,10 +164,18 @@ class VirtualPrinter():
|
||||
if linenumber != expected:
|
||||
self._triggerResend(actual=linenumber)
|
||||
continue
|
||||
elif self.currentLine == 101:
|
||||
elif linenumber == 100 and self._triggerResendAt100:
|
||||
# simulate a resend at line 100
|
||||
self._triggerResendAt100 = False
|
||||
self._triggerResend(expected=100)
|
||||
continue
|
||||
elif linenumber == 105 and self._triggerResendWithTimeoutAt105 and not self._writingToSd:
|
||||
# simulate a resend with timeout at line 105
|
||||
self._triggerResendWithTimeoutAt105 = False
|
||||
self._triggerResend(expected=105)
|
||||
self._dont_answer = True
|
||||
self.lastN = linenumber
|
||||
continue
|
||||
else:
|
||||
self.lastN = linenumber
|
||||
data = data.split(None, 1)[1].strip()
|
||||
@@ -160,9 +183,8 @@ class VirtualPrinter():
|
||||
data += "\n"
|
||||
|
||||
# shortcut for writing to SD
|
||||
if self._writingToSd and not self._selectedSdFile is None and not "M29" in data:
|
||||
with open(self._selectedSdFile, "a") as f:
|
||||
f.write(data)
|
||||
if self._writingToSdHandle is not None and not "M29" in data:
|
||||
self._writingToSdHandle.write(data)
|
||||
self._sendOk()
|
||||
continue
|
||||
|
||||
@@ -219,6 +241,8 @@ class VirtualPrinter():
|
||||
elif 'M29' in data:
|
||||
if self._sdCardReady:
|
||||
self._finishSdFile()
|
||||
if self._brokenM29:
|
||||
continue
|
||||
elif 'M30' in data:
|
||||
if self._sdCardReady:
|
||||
filename = data.split(None, 1)[1].strip()
|
||||
@@ -232,7 +256,8 @@ class VirtualPrinter():
|
||||
continue
|
||||
elif "M117" in data:
|
||||
# we'll just use this to echo a message, to allow playing around with pause triggers
|
||||
self.outgoing.put("echo:%s" % re.search("M117\s+(.*)", data).group(1))
|
||||
if self._echoOnM117:
|
||||
self.outgoing.put("echo:%s" % re.search("M117\s+(.*)", data).group(1))
|
||||
elif "M999" in data:
|
||||
# mirror Marlin behaviour
|
||||
self.outgoing.put("Resend: 1")
|
||||
@@ -266,9 +291,10 @@ class VirtualPrinter():
|
||||
elif "G92" in data:
|
||||
self._setPosition(data)
|
||||
|
||||
elif data.startswith("G0") or data.startswith("G1") or data.startswith("G2") or data.startswith("G3") \
|
||||
or data.startswith("G28") or data.startswith("G29") or data.startswith("G30") \
|
||||
or data.startswith("G31") or data.startswith("G32"):
|
||||
elif data.startswith("G28"):
|
||||
self._performMove(data)
|
||||
|
||||
elif data.startswith("G0") or data.startswith("G1") or data.startswith("G2") or data.startswith("G3"):
|
||||
# simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves
|
||||
self.buffered.put(data)
|
||||
|
||||
@@ -291,6 +317,12 @@ class VirtualPrinter():
|
||||
if len(data.strip()) > 0 and not self._okBeforeCommandOutput:
|
||||
self._sendOk()
|
||||
|
||||
def _kill(self):
|
||||
if not self._supportM112:
|
||||
return
|
||||
self._killed = True
|
||||
self.outgoing.put("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.")
|
||||
|
||||
def _triggerResend(self, expected=None, actual=None):
|
||||
with self._incoming_lock:
|
||||
if expected is None:
|
||||
@@ -303,8 +335,13 @@ class VirtualPrinter():
|
||||
else:
|
||||
self.outgoing.put("Error: expected line %d got %d" % (expected, actual))
|
||||
|
||||
self.outgoing.put("Resend:%d" % expected)
|
||||
self.outgoing.put("ok")
|
||||
def request_resend():
|
||||
self.outgoing.put("Resend:%d" % expected)
|
||||
self.outgoing.put("ok")
|
||||
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleResends"]):
|
||||
request_resend()
|
||||
request_resend()
|
||||
|
||||
def _debugTrigger(self, data):
|
||||
if data == "action_pause":
|
||||
@@ -321,6 +358,8 @@ class VirtualPrinter():
|
||||
self._triggerResend(expected=self.lastN)
|
||||
elif data == "drop_connection":
|
||||
self._debug_drop_connection = True
|
||||
elif data == "maxtemp_error":
|
||||
self.outgoing.put("Error: MAXTEMP triggered!")
|
||||
else:
|
||||
try:
|
||||
sleep_match = VirtualPrinter.sleep_regex.match(data)
|
||||
@@ -516,14 +555,10 @@ class VirtualPrinter():
|
||||
pass
|
||||
|
||||
if duration:
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "waitOnLongMoves"]):
|
||||
slept = 0
|
||||
while duration - slept > self._read_timeout:
|
||||
time.sleep(self._read_timeout)
|
||||
self.outgoing.put("wait")
|
||||
slept += self._read_timeout
|
||||
else:
|
||||
time.sleep(duration)
|
||||
slept = 0
|
||||
while duration - slept > self._read_timeout and not self._killed:
|
||||
time.sleep(self._read_timeout)
|
||||
slept += self._read_timeout
|
||||
|
||||
def _setPosition(self, line):
|
||||
matchX = re.search("X([0-9.]+)", line)
|
||||
@@ -565,56 +600,89 @@ class VirtualPrinter():
|
||||
else:
|
||||
self.outgoing.put("error writing to file")
|
||||
|
||||
handle = None
|
||||
try:
|
||||
handle = open(file, "w")
|
||||
except:
|
||||
self.outgoing.put("error writing to file")
|
||||
if handle is not None:
|
||||
try:
|
||||
handle.close()
|
||||
except:
|
||||
pass
|
||||
self._writingToSdHandle = handle
|
||||
self._writingToSd = True
|
||||
self._selectedSdFile = file
|
||||
self.outgoing.put("Writing to file: %s" % filename)
|
||||
|
||||
def _finishSdFile(self):
|
||||
try:
|
||||
self._writingToSdHandle.close()
|
||||
except:
|
||||
pass
|
||||
finally:
|
||||
self._writingToSdHandle = None
|
||||
self._writingToSd = False
|
||||
self._selectedSdFile = None
|
||||
self.outgoing.put("Done saving file")
|
||||
|
||||
def _sdPrintingWorker(self):
|
||||
self._selectedSdFilePos = 0
|
||||
with open(self._selectedSdFile, "r") as f:
|
||||
for line in iter(f.readline, ""):
|
||||
# reset position if requested by client
|
||||
if self._newSdFilePos is not None:
|
||||
f.seek(self._newSdFilePos)
|
||||
self._newSdFilePos = None
|
||||
try:
|
||||
with open(self._selectedSdFile, "r") as f:
|
||||
for line in iter(f.readline, ""):
|
||||
if self._killed:
|
||||
break
|
||||
|
||||
# read current file position
|
||||
self._selectedSdFilePos = f.tell()
|
||||
# reset position if requested by client
|
||||
if self._newSdFilePos is not None:
|
||||
f.seek(self._newSdFilePos)
|
||||
self._newSdFilePos = None
|
||||
|
||||
# if we are paused, wait for unpausing
|
||||
self._sdPrintingSemaphore.wait()
|
||||
# read current file position
|
||||
self._selectedSdFilePos = f.tell()
|
||||
|
||||
# set target temps
|
||||
if 'M104' in line or 'M109' in line:
|
||||
self._parseHotendCommand(line)
|
||||
if 'M140' in line or 'M190' in line:
|
||||
self._parseBedCommand(line)
|
||||
# if we are paused, wait for unpausing
|
||||
self._sdPrintingSemaphore.wait()
|
||||
|
||||
time.sleep(settings().getFloat(["devel", "virtualPrinter", "throttle"]))
|
||||
# set target temps
|
||||
if 'M104' in line or 'M109' in line:
|
||||
self._parseHotendCommand(line)
|
||||
elif 'M140' in line or 'M190' in line:
|
||||
self._parseBedCommand(line)
|
||||
elif line.startswith("G0") or line.startswith("G1") or line.startswith("G2") or line.startswith("G3"):
|
||||
# simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves
|
||||
self.buffered.put(line)
|
||||
|
||||
self._sdPrintingSemaphore.clear()
|
||||
self._selectedSdFilePos = 0
|
||||
self._sdPrinter = None
|
||||
self.outgoing.put("Done printing file")
|
||||
except AttributeError:
|
||||
if self.outgoing is not None:
|
||||
raise
|
||||
|
||||
if not self._killed:
|
||||
self._sdPrintingSemaphore.clear()
|
||||
self._selectedSdFilePos = 0
|
||||
self._sdPrinter = None
|
||||
self.outgoing.put("Done printing file")
|
||||
|
||||
def _waitForHeatup(self, heater):
|
||||
delta = 1
|
||||
delay = 1
|
||||
if heater.startswith("tool"):
|
||||
toolNum = int(heater[len("tool"):])
|
||||
while self.temp[toolNum] < self.targetTemp[toolNum] - delta or self.temp[toolNum] > self.targetTemp[toolNum] + delta:
|
||||
self._simulateTemps(delta=delta)
|
||||
self.outgoing.put("T:%0.2f" % self.temp[toolNum])
|
||||
time.sleep(delay)
|
||||
elif heater == "bed":
|
||||
while self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta:
|
||||
self._simulateTemps(delta=delta)
|
||||
self.outgoing.put("B:%0.2f" % self.bedTemp)
|
||||
time.sleep(delay)
|
||||
|
||||
try:
|
||||
if heater.startswith("tool"):
|
||||
toolNum = int(heater[len("tool"):])
|
||||
while not self._killed and (self.temp[toolNum] < self.targetTemp[toolNum] - delta or self.temp[toolNum] > self.targetTemp[toolNum] + delta):
|
||||
self._simulateTemps(delta=delta)
|
||||
self.outgoing.put("T:%0.2f" % self.temp[toolNum])
|
||||
time.sleep(delay)
|
||||
elif heater == "bed":
|
||||
while not self._killed and (self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta):
|
||||
self._simulateTemps(delta=delta)
|
||||
self.outgoing.put("B:%0.2f" % self.bedTemp)
|
||||
time.sleep(delay)
|
||||
except AttributeError:
|
||||
if self.outgoing is not None:
|
||||
raise
|
||||
|
||||
def _deleteSdFile(self, filename):
|
||||
if filename.startswith("/"):
|
||||
@@ -662,6 +730,11 @@ class VirtualPrinter():
|
||||
with self._incoming_lock:
|
||||
if self.incoming is None or self.outgoing is None:
|
||||
return
|
||||
|
||||
if "M112" in data and self._supportM112:
|
||||
self._kill()
|
||||
return
|
||||
|
||||
try:
|
||||
self.incoming.put(data, timeout=self._write_timeout)
|
||||
except Queue.Full:
|
||||
@@ -674,17 +747,20 @@ class VirtualPrinter():
|
||||
|
||||
try:
|
||||
line = self.outgoing.get(timeout=self._read_timeout)
|
||||
time.sleep(settings().getFloat(["devel", "virtualPrinter", "throttle"]))
|
||||
return line
|
||||
except Queue.Empty:
|
||||
return ""
|
||||
|
||||
def close(self):
|
||||
self._killed = True
|
||||
self.incoming = None
|
||||
self.outgoing = None
|
||||
self.buffered = None
|
||||
|
||||
def _sendOk(self):
|
||||
if self.outgoing is None:
|
||||
return
|
||||
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "okWithLinenumber"]):
|
||||
self.outgoing.put("ok %d" % self.lastN)
|
||||
else:
|
||||
|
||||
@@ -214,7 +214,7 @@ class PrinterInterface(object):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def select_file(self, path, sd, printAfterSelect=False):
|
||||
def select_file(self, path, sd, printAfterSelect=False, pos=None):
|
||||
"""
|
||||
Selects the specified ``path`` for printing, specifying if the file is to be found on the ``sd`` or not.
|
||||
Optionally can also directly start the print after selecting the file.
|
||||
|
||||
@@ -12,7 +12,7 @@ import re
|
||||
import logging
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import dict_merge, dict_clean, dict_contains_keys
|
||||
from octoprint.util import dict_merge, dict_sanitize, dict_contains_keys, is_hidden_path
|
||||
|
||||
class SaveError(Exception):
|
||||
pass
|
||||
@@ -151,7 +151,7 @@ class PrinterProfileManager(object):
|
||||
formFactor = BedTypes.RECTANGULAR,
|
||||
origin = BedOrigin.LOWERLEFT
|
||||
),
|
||||
heatedBed = False,
|
||||
heatedBed = True,
|
||||
extruder=dict(
|
||||
count = 1,
|
||||
offsets = [
|
||||
@@ -214,7 +214,7 @@ class PrinterProfileManager(object):
|
||||
|
||||
identifier = self._sanitize(identifier)
|
||||
profile["id"] = identifier
|
||||
profile = dict_clean(profile, self.__class__.default)
|
||||
profile = dict_sanitize(profile, self.__class__.default)
|
||||
|
||||
if identifier == "_default":
|
||||
default_profile = dict_merge(self._load_default(), profile)
|
||||
@@ -289,7 +289,7 @@ class PrinterProfileManager(object):
|
||||
def _load_all_identifiers(self):
|
||||
results = dict(_default=None)
|
||||
for entry in os.listdir(self._folder):
|
||||
if entry.startswith(".") or not entry.endswith(".profile") or entry == "_default.profile":
|
||||
if is_hidden_path(entry) or not entry.endswith(".profile") or entry == "_default.profile":
|
||||
continue
|
||||
|
||||
path = os.path.join(self._folder, entry)
|
||||
@@ -329,12 +329,14 @@ class PrinterProfileManager(object):
|
||||
if os.path.exists(path) and not allow_overwrite:
|
||||
raise SaveError("Profile %s already exists and not allowed to overwrite" % profile["id"])
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
import yaml
|
||||
with open(path, "wb") as f:
|
||||
try:
|
||||
try:
|
||||
with atomic_write(path, "wb") as f:
|
||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
except Exception as e:
|
||||
raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e)))
|
||||
except Exception as e:
|
||||
self._logger.exception("Error while trying to save profile %s" % profile["id"])
|
||||
raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e)))
|
||||
|
||||
def _remove_from_path(self, path):
|
||||
try:
|
||||
@@ -406,7 +408,7 @@ class PrinterProfileManager(object):
|
||||
for path in (("volume", "width"), ("volume", "depth"), ("volume", "height"), ("extruder", "nozzleDiameter")):
|
||||
try:
|
||||
convert_value(profile, path, float)
|
||||
except:
|
||||
except Exception as e:
|
||||
self._logger.warn("Profile has invalid value for path {path!r}: {msg}".format(path=".".join(path), msg=str(e)))
|
||||
return False
|
||||
|
||||
@@ -414,7 +416,7 @@ class PrinterProfileManager(object):
|
||||
for path in (("axes", "x", "inverted"), ("axes", "y", "inverted"), ("axes", "z", "inverted")):
|
||||
try:
|
||||
convert_value(profile, path, bool)
|
||||
except:
|
||||
except Exception as e:
|
||||
self._logger.warn("Profile has invalid value for path {path!r}: {msg}".format(path=".".join(path), msg=str(e)))
|
||||
return False
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ import time
|
||||
|
||||
from octoprint import util as util
|
||||
from octoprint.events import eventManager, Events
|
||||
from octoprint.filemanager import FileDestinations
|
||||
from octoprint.filemanager import FileDestinations, NoSuchStorage
|
||||
from octoprint.plugin import plugin_manager, ProgressPlugin
|
||||
from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript
|
||||
from octoprint.printer.estimation import TimeEstimationHelper
|
||||
@@ -62,11 +62,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
self._currentZ = None
|
||||
|
||||
self._progress = None
|
||||
self._printTime = None
|
||||
self._printTimeLeft = None
|
||||
|
||||
self._printAfterSelect = False
|
||||
self._posAfterSelect = None
|
||||
|
||||
# sd handling
|
||||
self._sdPrinting = False
|
||||
@@ -92,7 +89,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
on_update=self._sendCurrentDataCallbacks,
|
||||
on_add_temperature=self._sendAddTemperatureCallbacks,
|
||||
on_add_log=self._sendAddLogCallbacks,
|
||||
on_add_message=self._sendAddMessageCallbacks
|
||||
on_add_message=self._sendAddMessageCallbacks,
|
||||
on_get_progress=self._updateProgressDataCallback
|
||||
)
|
||||
self._stateMonitor.reset(
|
||||
state={"text": self.get_state_string(), "flags": self._getStateFlags()},
|
||||
@@ -345,14 +343,25 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
factor = self._convert_rate_value(factor, min=75, max=125)
|
||||
self.commands("M221 S%d" % factor)
|
||||
|
||||
def select_file(self, path, sd, printAfterSelect=False):
|
||||
def select_file(self, path, sd, printAfterSelect=False, pos=None):
|
||||
if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()):
|
||||
self._logger.info("Cannot load file: printer not connected or currently busy")
|
||||
return
|
||||
|
||||
recovery_data = self._fileManager.get_recovery_data()
|
||||
if recovery_data:
|
||||
# clean up recovery data if we just selected a different file than is logged in that
|
||||
expected_origin = FileDestinations.SDCARD if sd else FileDestinations.LOCAL
|
||||
actual_origin = recovery_data.get("origin", None)
|
||||
actual_path = recovery_data.get("path", None)
|
||||
|
||||
if actual_origin is None or actual_path is None or actual_origin != expected_origin or actual_path != path:
|
||||
self._fileManager.delete_recovery_data()
|
||||
|
||||
self._printAfterSelect = printAfterSelect
|
||||
self._posAfterSelect = pos
|
||||
self._comm.selectFile("/" + path if sd else path, sd)
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setProgressData(completion=0)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def unselect_file(self):
|
||||
@@ -360,10 +369,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
return
|
||||
|
||||
self._comm.unselectFile()
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setProgressData(completion=0)
|
||||
self._setCurrentZ(None)
|
||||
|
||||
def start_print(self):
|
||||
def start_print(self, pos=None):
|
||||
"""
|
||||
Starts the currently loaded print job.
|
||||
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
|
||||
@@ -388,9 +397,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
countdown = rolling_window
|
||||
self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window, threshold=threshold, countdown=countdown)
|
||||
|
||||
self._fileManager.delete_recovery_data()
|
||||
|
||||
self._lastProgressReport = None
|
||||
self._setProgressData(completion=0)
|
||||
self._setCurrentZ(None)
|
||||
self._comm.startPrint()
|
||||
self._comm.startPrint(pos=pos)
|
||||
|
||||
def toggle_pause_print(self):
|
||||
"""
|
||||
@@ -412,7 +424,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
# reset progress, height, print time
|
||||
self._setCurrentZ(None)
|
||||
self._setProgressData(None, None, None, None)
|
||||
self._setProgressData()
|
||||
|
||||
# mark print as failure
|
||||
if self._selectedFile is not None:
|
||||
@@ -582,7 +594,24 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
return result
|
||||
|
||||
def _setProgressData(self, progress, filepos, printTime, cleanedPrintTime):
|
||||
def _setProgressData(self, completion=None, filepos=None, printTime=None, printTimeLeft=None):
|
||||
self._stateMonitor.set_progress(dict(completion=int(completion * 100) if completion is not None else None,
|
||||
filepos=filepos,
|
||||
printTime=int(printTime) if printTime is not None else None,
|
||||
printTimeLeft=int(printTimeLeft) if printTimeLeft is not None else None))
|
||||
|
||||
def _updateProgressDataCallback(self):
|
||||
if self._comm is None:
|
||||
progress = None
|
||||
filepos = None
|
||||
printTime = None
|
||||
cleanedPrintTime = None
|
||||
else:
|
||||
progress = self._comm.getPrintProgress()
|
||||
filepos = self._comm.getPrintFilepos()
|
||||
printTime = self._comm.getPrintTime()
|
||||
cleanedPrintTime = self._comm.getCleanedPrintTime()
|
||||
|
||||
estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime)
|
||||
totalPrintTime = estimatedTotalPrintTime
|
||||
|
||||
@@ -598,16 +627,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
sub_progress = 1.0
|
||||
totalPrintTime = (1 - sub_progress) * statisticalTotalPrintTime + sub_progress * estimatedTotalPrintTime
|
||||
|
||||
self._progress = progress
|
||||
self._printTime = printTime
|
||||
self._printTimeLeft = totalPrintTime - cleanedPrintTime if (totalPrintTime is not None and cleanedPrintTime is not None) else None
|
||||
|
||||
self._stateMonitor.set_progress({
|
||||
"completion": self._progress * 100 if self._progress is not None else None,
|
||||
"filepos": filepos,
|
||||
"printTime": int(self._printTime) if self._printTime is not None else None,
|
||||
"printTimeLeft": int(self._printTimeLeft) if self._printTimeLeft is not None else None
|
||||
})
|
||||
printTimeLeft = totalPrintTime - cleanedPrintTime if (totalPrintTime is not None and cleanedPrintTime is not None) else None
|
||||
|
||||
if progress:
|
||||
progress_int = int(progress * 100)
|
||||
@@ -615,6 +635,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._lastProgressReport = progress_int
|
||||
self._reportPrintProgressToPlugins(progress_int)
|
||||
|
||||
return dict(completion=progress * 100 if progress is not None else None,
|
||||
filepos=filepos,
|
||||
printTime=int(printTime) if printTime is not None else None,
|
||||
printTimeLeft=int(printTimeLeft) if printTimeLeft is not None else None)
|
||||
|
||||
def _addTemperatureData(self, temp, bedTemp):
|
||||
currentTimeUtc = int(time.time())
|
||||
@@ -644,6 +668,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if filename is not None:
|
||||
if sd:
|
||||
path_in_storage = filename
|
||||
if path_in_storage.startswith("/"):
|
||||
path_in_storage = path_in_storage[1:]
|
||||
path_on_disk = None
|
||||
else:
|
||||
path_in_storage = self._fileManager.path_in_storage(FileDestinations.LOCAL, filename)
|
||||
@@ -679,7 +705,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
# Use a string for mtime because it could be float and the
|
||||
# javascript needs to exact match
|
||||
if not sd:
|
||||
date = int(os.stat(path_on_disk).st_ctime)
|
||||
date = int(os.stat(path_on_disk).st_mtime)
|
||||
|
||||
try:
|
||||
fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, path_on_disk)
|
||||
@@ -767,11 +793,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._analysisQueue.resume() # printing done, put those cpu cycles to good use
|
||||
elif state == comm.MachineCom.STATE_PRINTING:
|
||||
self._analysisQueue.pause() # do not analyse files while printing
|
||||
elif state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR:
|
||||
|
||||
if state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR:
|
||||
if self._comm is not None:
|
||||
self._comm = None
|
||||
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setProgressData(completion=0)
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
|
||||
@@ -790,7 +817,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
Triggers storage of new values for printTime, printTimeLeft and the current progress.
|
||||
"""
|
||||
|
||||
self._setProgressData(self._comm.getPrintProgress(), self._comm.getPrintFilepos(), self._comm.getPrintTime(), self._comm.getCleanedPrintTime())
|
||||
self._stateMonitor.trigger_progress_update()
|
||||
|
||||
def on_comm_z_change(self, newZ):
|
||||
"""
|
||||
@@ -816,18 +843,19 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
if self._printAfterSelect:
|
||||
self.start_print()
|
||||
self.start_print(pos=self._posAfterSelect)
|
||||
|
||||
def on_comm_print_job_done(self):
|
||||
self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), True, self._printerProfileManager.get_current_or_default()["id"])
|
||||
self._setProgressData(1.0, self._selectedFile["filesize"], self._comm.getPrintTime(), 0)
|
||||
self._setProgressData(completion=1.0, filepos=self._selectedFile["filesize"], printTime=self._comm.getPrintTime(), printTimeLeft=0)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
self._fileManager.delete_recovery_data()
|
||||
|
||||
def on_comm_file_transfer_started(self, filename, filesize):
|
||||
self._sdStreaming = True
|
||||
|
||||
self._setJobData(filename, filesize, True)
|
||||
self._setProgressData(0.0, 0, 0, None)
|
||||
self._setProgressData(completion=0.0, filepos=0, printTime=0)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def on_comm_file_transfer_done(self, filename):
|
||||
@@ -840,20 +868,28 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
self._setProgressData(None, None, None, None)
|
||||
self._setProgressData()
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def on_comm_force_disconnect(self):
|
||||
self.disconnect()
|
||||
|
||||
def on_comm_record_fileposition(self, origin, name, pos):
|
||||
try:
|
||||
self._fileManager.save_recovery_data(origin, name, pos)
|
||||
except NoSuchStorage:
|
||||
pass
|
||||
except:
|
||||
self._logger.exception("Error while trying to persist print recovery data")
|
||||
|
||||
class StateMonitor(object):
|
||||
def __init__(self, interval=0.5, on_update=None, on_add_temperature=None, on_add_log=None, on_add_message=None):
|
||||
def __init__(self, interval=0.5, on_update=None, on_add_temperature=None, on_add_log=None, on_add_message=None, on_get_progress=None):
|
||||
self._interval = interval
|
||||
self._update_callback = on_update
|
||||
self._on_add_temperature = on_add_temperature
|
||||
self._on_add_log = on_add_log
|
||||
self._on_add_message = on_add_message
|
||||
self._on_get_progress = on_get_progress
|
||||
|
||||
self._state = None
|
||||
self._job_data = None
|
||||
@@ -862,16 +898,24 @@ class StateMonitor(object):
|
||||
self._current_z = None
|
||||
self._progress = None
|
||||
|
||||
self._progress_dirty = False
|
||||
|
||||
self._offsets = {}
|
||||
|
||||
self._change_event = threading.Event()
|
||||
self._state_lock = threading.Lock()
|
||||
self._progress_lock = threading.Lock()
|
||||
|
||||
self._last_update = time.time()
|
||||
self._worker = threading.Thread(target=self._work)
|
||||
self._worker.daemon = True
|
||||
self._worker.start()
|
||||
|
||||
def _get_current_progress(self):
|
||||
if callable(self._on_get_progress):
|
||||
return self._on_get_progress()
|
||||
return self._progress
|
||||
|
||||
def reset(self, state=None, job_data=None, progress=None, current_z=None):
|
||||
self.set_state(state)
|
||||
self.set_job_data(job_data)
|
||||
@@ -903,9 +947,16 @@ class StateMonitor(object):
|
||||
self._job_data = job_data
|
||||
self._change_event.set()
|
||||
|
||||
def trigger_progress_update(self):
|
||||
with self._progress_lock:
|
||||
self._progress_dirty = True
|
||||
self._change_event.set()
|
||||
|
||||
def set_progress(self, progress):
|
||||
self._progress = progress
|
||||
self._change_event.set()
|
||||
with self._progress_lock:
|
||||
self._progress_dirty = False
|
||||
self._progress = progress
|
||||
self._change_event.set()
|
||||
|
||||
def set_temp_offsets(self, offsets):
|
||||
self._offsets = offsets
|
||||
@@ -915,19 +966,24 @@ class StateMonitor(object):
|
||||
while True:
|
||||
self._change_event.wait()
|
||||
|
||||
with self._state_lock:
|
||||
now = time.time()
|
||||
delta = now - self._last_update
|
||||
additional_wait_time = self._interval - delta
|
||||
if additional_wait_time > 0:
|
||||
time.sleep(additional_wait_time)
|
||||
now = time.time()
|
||||
delta = now - self._last_update
|
||||
additional_wait_time = self._interval - delta
|
||||
if additional_wait_time > 0:
|
||||
time.sleep(additional_wait_time)
|
||||
|
||||
with self._state_lock:
|
||||
data = self.get_current_data()
|
||||
self._update_callback(data)
|
||||
self._last_update = time.time()
|
||||
self._change_event.clear()
|
||||
|
||||
def get_current_data(self):
|
||||
with self._progress_lock:
|
||||
if self._progress_dirty:
|
||||
self._progress = self._get_current_progress()
|
||||
self._progress_dirty = False
|
||||
|
||||
return {
|
||||
"state": self._state,
|
||||
"job": self._job_data,
|
||||
|
||||
@@ -22,9 +22,11 @@ import logging
|
||||
import logging.config
|
||||
import atexit
|
||||
import signal
|
||||
import base64
|
||||
|
||||
SUCCESS = {}
|
||||
NO_CONTENT = ("", 204)
|
||||
NOT_MODIFIED = ("Not Modified", 304)
|
||||
|
||||
app = Flask("octoprint")
|
||||
assets = None
|
||||
@@ -42,6 +44,7 @@ loginManager = None
|
||||
pluginManager = None
|
||||
appSessionManager = None
|
||||
pluginLifecycleManager = None
|
||||
preemptiveCache = None
|
||||
|
||||
principals = Principal(app)
|
||||
admin_permission = Permission(RoleNeed("admin"))
|
||||
@@ -61,6 +64,7 @@ import octoprint.util
|
||||
import octoprint.filemanager.storage
|
||||
import octoprint.filemanager.analysis
|
||||
import octoprint.slicing
|
||||
from octoprint.server.util.flask import PreemptiveCache
|
||||
|
||||
from . import util
|
||||
|
||||
@@ -68,8 +72,9 @@ UI_API_KEY = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)
|
||||
|
||||
versions = octoprint._version.get_versions()
|
||||
VERSION = versions['version']
|
||||
BRANCH = versions['branch'] if 'branch' in versions else None
|
||||
BRANCH = versions.get('branch', None)
|
||||
DISPLAY_VERSION = "%s (%s branch)" % (VERSION, BRANCH) if BRANCH else VERSION
|
||||
REVISION = versions.get('full-revision-id', versions.get('full', None))
|
||||
del versions
|
||||
|
||||
LOCALES = []
|
||||
@@ -81,7 +86,7 @@ def on_identity_loaded(sender, identity):
|
||||
if user is None:
|
||||
return
|
||||
|
||||
identity.provides.add(UserNeed(user.get_name()))
|
||||
identity.provides.add(UserNeed(user.get_id()))
|
||||
if user.is_user():
|
||||
identity.provides.add(RoleNeed("user"))
|
||||
if user.is_admin():
|
||||
@@ -96,11 +101,11 @@ def load_user(id):
|
||||
else:
|
||||
sessionid = None
|
||||
|
||||
if userManager is not None:
|
||||
if userManager.enabled:
|
||||
if sessionid:
|
||||
return userManager.findUser(username=id, session=sessionid)
|
||||
return userManager.findUser(userid=id, session=sessionid)
|
||||
else:
|
||||
return userManager.findUser(username=id)
|
||||
return userManager.findUser(userid=id)
|
||||
return users.DummyUser()
|
||||
|
||||
|
||||
@@ -124,6 +129,8 @@ class Server():
|
||||
|
||||
self._template_searchpaths = []
|
||||
|
||||
self._intermediary_server = None
|
||||
|
||||
def run(self):
|
||||
if not self._allowRoot:
|
||||
self._check_for_root()
|
||||
@@ -142,6 +149,7 @@ class Server():
|
||||
global pluginManager
|
||||
global appSessionManager
|
||||
global pluginLifecycleManager
|
||||
global preemptiveCache
|
||||
global debug
|
||||
|
||||
from tornado.ioloop import IOLoop
|
||||
@@ -172,6 +180,9 @@ class Server():
|
||||
sys.excepthook = exception_logger
|
||||
self._logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)
|
||||
|
||||
# start the intermediary server
|
||||
self._start_intermediary_server(s)
|
||||
|
||||
# then initialize the plugin manager
|
||||
pluginManager = octoprint.plugin.plugin_manager(init=True)
|
||||
|
||||
@@ -185,6 +196,7 @@ class Server():
|
||||
printer = Printer(fileManager, analysisQueue, printerProfileManager)
|
||||
appSessionManager = util.flask.AppSessionManager()
|
||||
pluginLifecycleManager = LifecycleManager(pluginManager)
|
||||
preemptiveCache = PreemptiveCache(os.path.join(s.getBaseFolder("data"), "preemptive_cache_config.yaml"))
|
||||
|
||||
def octoprint_plugin_inject_factory(name, implementation):
|
||||
if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin):
|
||||
@@ -199,7 +211,8 @@ class Server():
|
||||
printer=printer,
|
||||
app_session_manager=appSessionManager,
|
||||
plugin_lifecycle_manager=pluginLifecycleManager,
|
||||
data_folder=os.path.join(settings().getBaseFolder("data"), name)
|
||||
data_folder=os.path.join(settings().getBaseFolder("data"), name),
|
||||
preemptive_cache=preemptiveCache
|
||||
)
|
||||
|
||||
def settings_plugin_inject_factory(name, implementation):
|
||||
@@ -213,7 +226,7 @@ class Server():
|
||||
set_preprocessors=set_preprocessors)
|
||||
return dict(settings=plugin_settings)
|
||||
|
||||
def settings_plugin_config_migration(name, implementation):
|
||||
def settings_plugin_config_migration_and_cleanup(name, implementation):
|
||||
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
|
||||
return
|
||||
|
||||
@@ -221,11 +234,13 @@ class Server():
|
||||
settings_migrator = implementation.on_settings_migrate
|
||||
|
||||
if settings_version is not None and settings_migrator is not None:
|
||||
stored_version = implementation._settings.get_int(["_config_version"])
|
||||
stored_version = implementation._settings.get_int([octoprint.plugin.SettingsPlugin.config_version_key])
|
||||
if stored_version is None or stored_version < settings_version:
|
||||
settings_migrator(settings_version, stored_version)
|
||||
implementation._settings.set_int(["_config_version"], settings_version)
|
||||
implementation._settings.save()
|
||||
implementation._settings.set_int([octoprint.plugin.SettingsPlugin.config_version_key], settings_version)
|
||||
|
||||
implementation.on_settings_cleanup()
|
||||
implementation._settings.save()
|
||||
|
||||
implementation.on_settings_initialized()
|
||||
|
||||
@@ -234,9 +249,12 @@ class Server():
|
||||
|
||||
settingsPlugins = pluginManager.get_implementations(octoprint.plugin.SettingsPlugin)
|
||||
for implementation in settingsPlugins:
|
||||
settings_plugin_config_migration(implementation._identifier, implementation)
|
||||
try:
|
||||
settings_plugin_config_migration_and_cleanup(implementation._identifier, implementation)
|
||||
except:
|
||||
self._logger.exception("Error while trying to migrate settings for plugin {}, ignoring it".format(implementation._identifier))
|
||||
|
||||
pluginManager.implementation_post_inits=[settings_plugin_config_migration]
|
||||
pluginManager.implementation_post_inits=[settings_plugin_config_migration_and_cleanup]
|
||||
|
||||
pluginManager.log_all_plugins()
|
||||
|
||||
@@ -265,7 +283,7 @@ class Server():
|
||||
self._setup_assets()
|
||||
|
||||
# configure timelapse
|
||||
octoprint.timelapse.configureTimelapse()
|
||||
octoprint.timelapse.configure_timelapse()
|
||||
|
||||
# setup command triggers
|
||||
events.CommandTrigger(printer)
|
||||
@@ -273,13 +291,15 @@ class Server():
|
||||
events.DebugEventListener()
|
||||
|
||||
# setup access control
|
||||
if s.getBoolean(["accessControl", "enabled"]):
|
||||
userManagerName = s.get(["accessControl", "userManager"])
|
||||
try:
|
||||
clazz = octoprint.util.get_class(userManagerName)
|
||||
userManager = clazz()
|
||||
except AttributeError, e:
|
||||
self._logger.exception("Could not instantiate user manager %s, will run with accessControl disabled!" % userManagerName)
|
||||
userManagerName = s.get(["accessControl", "userManager"])
|
||||
try:
|
||||
clazz = octoprint.util.get_class(userManagerName)
|
||||
userManager = clazz()
|
||||
except AttributeError, e:
|
||||
self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName))
|
||||
userManager = octoprint.users.FilebasedUserManager()
|
||||
finally:
|
||||
userManager.enabled = s.getBoolean(["accessControl", "enabled"])
|
||||
|
||||
app.wsgi_app = util.ReverseProxied(
|
||||
app.wsgi_app,
|
||||
@@ -303,7 +323,7 @@ class Server():
|
||||
loginManager = LoginManager()
|
||||
loginManager.session_protection = "strong"
|
||||
loginManager.user_callback = load_user
|
||||
if userManager is None:
|
||||
if not userManager.enabled:
|
||||
loginManager.anonymous_user = users.DummyUser
|
||||
principals.identity_loaders.appendleft(users.dummy_identity_loader)
|
||||
loginManager.init_app(app)
|
||||
@@ -327,15 +347,39 @@ class Server():
|
||||
|
||||
upload_suffixes = dict(name=s.get(["server", "uploads", "nameSuffix"]), path=s.get(["server", "uploads", "pathSuffix"]))
|
||||
|
||||
def mime_type_guesser(path):
|
||||
from octoprint.filemanager import get_mime_type
|
||||
return get_mime_type(path)
|
||||
|
||||
download_handler_kwargs = dict(
|
||||
as_attachment=True,
|
||||
allow_client_caching=False
|
||||
)
|
||||
additional_mime_types=dict(mime_type_guesser=mime_type_guesser)
|
||||
admin_validator = dict(access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))
|
||||
no_hidden_files_validator = dict(path_validation=util.tornado.path_validation_factory(lambda path: not octoprint.util.is_hidden_path(path), status_code=404))
|
||||
|
||||
def joined_dict(*dicts):
|
||||
if not len(dicts):
|
||||
return dict()
|
||||
|
||||
joined = dict()
|
||||
for d in dicts:
|
||||
joined.update(d)
|
||||
return joined
|
||||
|
||||
server_routes = self._router.urls + [
|
||||
# various downloads
|
||||
(r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, dict(path=s.getBaseFolder("timelapse"), as_attachment=True)),
|
||||
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, dict(path=s.getBaseFolder("uploads"), as_attachment=True, path_validation=util.tornado.path_validation_factory(lambda path: not os.path.basename(path).startswith("."), status_code=404))),
|
||||
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, dict(path=s.getBaseFolder("logs"), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))),
|
||||
(r"/downloads/timelapse/([^/]*\.mp[g4])", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("timelapse")), download_handler_kwargs, no_hidden_files_validator)),
|
||||
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("uploads")), download_handler_kwargs, no_hidden_files_validator, additional_mime_types)),
|
||||
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("logs")), download_handler_kwargs, admin_validator)),
|
||||
# camera snapshot
|
||||
(r"/downloads/camera/current", util.tornado.UrlForwardHandler, dict(url=s.get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
|
||||
(r"/downloads/camera/current", util.tornado.UrlProxyHandler, dict(url=s.get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
|
||||
# generated webassets
|
||||
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(s.getBaseFolder("generated"), "webassets")))
|
||||
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(s.getBaseFolder("generated"), "webassets"))),
|
||||
# online indicators - text file with "online" as content and a transparent gif
|
||||
(r"/online.txt", util.tornado.StaticDataHandler, dict(data="online\n")),
|
||||
(r"/online.gif", util.tornado.StaticDataHandler, dict(data=bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")), content_type="image/gif"))
|
||||
]
|
||||
for name, hook in pluginManager.get_hooks("octoprint.server.http.routes").items():
|
||||
try:
|
||||
@@ -388,6 +432,8 @@ class Server():
|
||||
self._logger.debug("Adding maximum body size of {size}B for {method} requests to {route})".format(**locals()))
|
||||
max_body_sizes.append((method, route, size))
|
||||
|
||||
self._stop_intermediary_server()
|
||||
|
||||
self._server = util.tornado.CustomHTTPServer(self._tornado_app, max_body_sizes=max_body_sizes, default_max_body_size=s.getInt(["server", "maxSize"]))
|
||||
self._server.listen(self._port, address=self._host)
|
||||
|
||||
@@ -441,6 +487,10 @@ class Server():
|
||||
implementation.on_after_startup()
|
||||
pluginLifecycleManager.add_callback("enabled", call_on_after_startup)
|
||||
|
||||
# when we are through with that we also run our preemptive cache
|
||||
if settings().getBoolean(["devel", "cache", "preemptive"]):
|
||||
self._execute_preemptive_flask_caching(preemptiveCache)
|
||||
|
||||
import threading
|
||||
threading.Thread(target=work).start()
|
||||
ioloop.add_callback(on_after_startup)
|
||||
@@ -487,7 +537,7 @@ class Server():
|
||||
if "l10n" in request.values:
|
||||
return Locale.negotiate([request.values["l10n"]], LANGUAGES)
|
||||
|
||||
if hasattr(g, "identity") and g.identity and userManager is not None:
|
||||
if hasattr(g, "identity") and g.identity and userManager.enabled:
|
||||
userid = g.identity.id
|
||||
try:
|
||||
user_language = userManager.getUserSetting(userid, ("interface", "language"))
|
||||
@@ -500,7 +550,7 @@ class Server():
|
||||
if default_language is not None and not default_language == "_default" and default_language in LANGUAGES:
|
||||
return Locale.negotiate([default_language], LANGUAGES)
|
||||
|
||||
return request.accept_languages.best_match(LANGUAGES)
|
||||
return Locale.parse(request.accept_languages.best_match(LANGUAGES))
|
||||
|
||||
def _setup_logging(self, debug, logConf=None):
|
||||
defaultConfig = {
|
||||
@@ -623,7 +673,9 @@ class Server():
|
||||
|
||||
# configure additional template folders for jinja2
|
||||
import jinja2
|
||||
filesystem_loader = jinja2.FileSystemLoader([])
|
||||
import octoprint.util.jinja
|
||||
filesystem_loader = octoprint.util.jinja.FilteredFileSystemLoader([],
|
||||
path_filter=lambda x: not octoprint.util.is_hidden_path(x))
|
||||
filesystem_loader.searchpath = self._template_searchpaths
|
||||
|
||||
jinja_loader = jinja2.ChoiceLoader([
|
||||
@@ -635,10 +687,53 @@ class Server():
|
||||
|
||||
self._register_template_plugins()
|
||||
|
||||
def _execute_preemptive_flask_caching(self, preemptive_cache):
|
||||
from werkzeug.test import EnvironBuilder
|
||||
import time
|
||||
|
||||
# we clean up entries from our preemptive cache settings that haven't been
|
||||
# accessed longer than server.preemptiveCache.until days
|
||||
preemptive_cache_timeout = settings().getInt(["server", "preemptiveCache", "until"])
|
||||
cutoff_timestamp = time.time() - preemptive_cache_timeout * 24 * 60 * 60
|
||||
|
||||
def filter_old_entries(entry):
|
||||
return "_timestamp" in entry and entry["_timestamp"] > cutoff_timestamp
|
||||
|
||||
cache_data = preemptive_cache.clean_all_data(lambda root, entries: filter(filter_old_entries, entries))
|
||||
if not cache_data:
|
||||
return
|
||||
|
||||
def execute_caching():
|
||||
for route in sorted(cache_data.keys(), key=lambda x: (x.count("/"), x)):
|
||||
entries = reversed(sorted(cache_data[route], key=lambda x: x.get("_count", 0)))
|
||||
for kwargs in entries:
|
||||
plugin = kwargs.get("plugin", None)
|
||||
additional_request_data = kwargs.get("_additional_request_data", dict())
|
||||
kwargs = dict((k, v) for k, v in kwargs.items() if not k.startswith("_") and not k == "plugin")
|
||||
kwargs.update(additional_request_data)
|
||||
try:
|
||||
if plugin:
|
||||
self._logger.info("Preemptively caching {} (plugin {}) for {!r}".format(route, plugin, kwargs))
|
||||
else:
|
||||
self._logger.info("Preemptively caching {} for {!r}".format(route, kwargs))
|
||||
builder = EnvironBuilder(**kwargs)
|
||||
with preemptive_cache.disable_access_logging():
|
||||
app(builder.get_environ(), lambda *a, **kw: None)
|
||||
except:
|
||||
self._logger.exception("Error while trying to preemptively cache {} for {!r}".format(route, kwargs))
|
||||
|
||||
import threading
|
||||
cache_thread = threading.Thread(target=execute_caching, name="Preemptive Cache Worker")
|
||||
cache_thread.daemon = True
|
||||
cache_thread.start()
|
||||
|
||||
def _register_template_plugins(self):
|
||||
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
|
||||
for plugin in template_plugins:
|
||||
self._register_additional_template_plugin(plugin)
|
||||
try:
|
||||
self._register_additional_template_plugin(plugin)
|
||||
except:
|
||||
self._logger.exception("Error while trying to register templates of plugin {}, ignoring it".format(plugin._identifier))
|
||||
|
||||
def _register_additional_template_plugin(self, plugin):
|
||||
folder = plugin.get_template_folder()
|
||||
@@ -673,14 +768,22 @@ class Server():
|
||||
def _register_blueprint_plugins(self):
|
||||
blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.BlueprintPlugin)
|
||||
for plugin in blueprint_plugins:
|
||||
self._register_blueprint_plugin(plugin)
|
||||
try:
|
||||
self._register_blueprint_plugin(plugin)
|
||||
except:
|
||||
self._logger.exception("Error while registering blueprint of plugin {}, ignoring it".format(plugin._identifier))
|
||||
continue
|
||||
|
||||
def _register_asset_plugins(self):
|
||||
asset_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.AssetPlugin)
|
||||
for plugin in asset_plugins:
|
||||
if isinstance(plugin, octoprint.plugin.BlueprintPlugin):
|
||||
continue
|
||||
self._register_asset_plugin(plugin)
|
||||
try:
|
||||
self._register_asset_plugin(plugin)
|
||||
except:
|
||||
self._logger.exception("Error while registering assets of plugin {}, ignoring it".format(plugin._identifier))
|
||||
continue
|
||||
|
||||
def _register_blueprint_plugin(self, plugin):
|
||||
name = plugin._identifier
|
||||
@@ -722,16 +825,58 @@ class Server():
|
||||
# clean the folder
|
||||
if settings().getBoolean(["devel", "webassets", "clean_on_startup"]):
|
||||
import shutil
|
||||
import errno
|
||||
import sys
|
||||
|
||||
for entry in ("webassets", ".webassets-cache"):
|
||||
path = os.path.join(base_folder, entry)
|
||||
self._logger.debug("Deleting {path}...".format(**locals()))
|
||||
|
||||
# delete path if it exists
|
||||
if os.path.isdir(path):
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
elif os.path.isfile(path):
|
||||
try:
|
||||
os.remove(path)
|
||||
self._logger.debug("Deleting {path}...".format(**locals()))
|
||||
shutil.rmtree(path)
|
||||
except:
|
||||
self._logger.exception("Exception while trying to delete {entry} from {base_folder}".format(**locals()))
|
||||
self._logger.exception("Error while trying to delete {path}, leaving it alone".format(**locals()))
|
||||
continue
|
||||
|
||||
# re-create path
|
||||
self._logger.debug("Creating {path}...".format(**locals()))
|
||||
error_text = "Error while trying to re-create {path}, that might cause errors with the webassets cache".format(**locals())
|
||||
try:
|
||||
os.makedirs(path)
|
||||
except OSError as e:
|
||||
if e.errno == errno.EACCES:
|
||||
# that might be caused by the user still having the folder open somewhere, let's try again after
|
||||
# waiting a bit
|
||||
import time
|
||||
for n in xrange(3):
|
||||
time.sleep(0.5)
|
||||
self._logger.debug("Creating {path}: Retry #{retry} after {time}s".format(path=path, retry=n+1, time=(n + 1)*0.5))
|
||||
try:
|
||||
os.makedirs(path)
|
||||
break
|
||||
except:
|
||||
if self._logger.isEnabledFor(logging.DEBUG):
|
||||
self._logger.exception("Ignored error while creating directory {path}".format(**locals()))
|
||||
pass
|
||||
else:
|
||||
# this will only get executed if we never did
|
||||
# successfully execute makedirs above
|
||||
self._logger.exception(error_text)
|
||||
continue
|
||||
else:
|
||||
# not an access error, so something we don't understand
|
||||
# went wrong -> log an error and stop
|
||||
self._logger.exception(error_text)
|
||||
continue
|
||||
except:
|
||||
# not an OSError, so something we don't understand
|
||||
# went wrong -> log an error and stop
|
||||
self._logger.exception(error_text)
|
||||
continue
|
||||
|
||||
self._logger.info("Reset webasset folder {path}...".format(**locals()))
|
||||
|
||||
AdjustedEnvironment = type(Environment)(Environment.__name__, (Environment,), dict(
|
||||
resolver_class=util.flask.PluginAssetResolver
|
||||
@@ -750,12 +895,10 @@ class Server():
|
||||
assets.updater = UpdaterType
|
||||
|
||||
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
|
||||
enable_timelapse = (settings().get(["webcam", "snapshot"]) and settings().get(["webcam", "ffmpeg"]))
|
||||
preferred_stylesheet = settings().get(["devel", "stylesheet"])
|
||||
|
||||
dynamic_assets = util.flask.collect_plugin_assets(
|
||||
enable_gcodeviewer=enable_gcodeviewer,
|
||||
enable_timelapse=enable_timelapse,
|
||||
preferred_stylesheet=preferred_stylesheet
|
||||
)
|
||||
|
||||
@@ -764,7 +907,7 @@ class Server():
|
||||
"js/lib/modernizr.custom.js",
|
||||
"js/lib/lodash.min.js",
|
||||
"js/lib/sprintf.min.js",
|
||||
"js/lib/knockout.js",
|
||||
"js/lib/knockout-3.4.0.js",
|
||||
"js/lib/knockout.mapping-latest.js",
|
||||
"js/lib/babel.js",
|
||||
"js/lib/avltree.js",
|
||||
@@ -859,6 +1002,90 @@ class Server():
|
||||
assets.register("css_app", css_app_bundle)
|
||||
assets.register("less_app", all_less_bundle)
|
||||
|
||||
def _start_intermediary_server(self, s):
|
||||
import BaseHTTPServer
|
||||
import SimpleHTTPServer
|
||||
import threading
|
||||
|
||||
host = self._host
|
||||
port = self._port
|
||||
if host is None:
|
||||
host = s.get(["server", "host"])
|
||||
if port is None:
|
||||
port = s.getInt(["server", "port"])
|
||||
|
||||
self._logger.debug("Starting intermediary server on {}:{}".format(host, port))
|
||||
|
||||
class IntermediaryServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
|
||||
def __init__(self, rules=None, *args, **kwargs):
|
||||
if rules is None:
|
||||
rules = []
|
||||
self.rules = rules
|
||||
SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, *args, **kwargs)
|
||||
|
||||
def do_GET(self):
|
||||
request_path = self.path
|
||||
if "?" in request_path:
|
||||
request_path = request_path[0:request_path.find("?")]
|
||||
|
||||
for rule in self.rules:
|
||||
path, data, content_type = rule
|
||||
if request_path == path:
|
||||
self.send_response(200)
|
||||
if content_type:
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
break
|
||||
else:
|
||||
self.send_response(404)
|
||||
self.wfile.write("Not found")
|
||||
|
||||
base_path = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "static"))
|
||||
rules = [
|
||||
("/", ["intermediary.html",], "text/html"),
|
||||
("/favicon.ico", ["img", "tentacle-20x20.png"], "image/png"),
|
||||
("/intermediary.gif", bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")), "image/gif")
|
||||
]
|
||||
|
||||
def contents(args):
|
||||
path = os.path.join(base_path, *args)
|
||||
if not os.path.isfile(path):
|
||||
return ""
|
||||
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
return data
|
||||
|
||||
def process(rule):
|
||||
if len(rule) == 2:
|
||||
path, data = rule
|
||||
content_type = None
|
||||
else:
|
||||
path, data, content_type = rule
|
||||
|
||||
if isinstance(data, (list, tuple)):
|
||||
data = contents(data)
|
||||
|
||||
return path, data, content_type
|
||||
|
||||
rules = map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules))
|
||||
|
||||
self._intermediary_server = BaseHTTPServer.HTTPServer((host, port), lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs))
|
||||
|
||||
thread = threading.Thread(target=self._intermediary_server.serve_forever)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
self._logger.debug("Intermediary server started")
|
||||
|
||||
def _stop_intermediary_server(self):
|
||||
if self._intermediary_server is None:
|
||||
return
|
||||
self._logger.debug("Shutting down intermediary server...")
|
||||
self._intermediary_server.shutdown()
|
||||
self._intermediary_server.server_close()
|
||||
self._logger.debug("Intermediary server shut down")
|
||||
|
||||
class LifecycleManager(object):
|
||||
def __init__(self, plugin_manager):
|
||||
|
||||
@@ -19,7 +19,7 @@ import octoprint.server
|
||||
import octoprint.plugin
|
||||
from octoprint.server import admin_permission, NO_CONTENT
|
||||
from octoprint.settings import settings as s, valid_boolean_trues
|
||||
from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler
|
||||
from octoprint.server.util import noCachingResponseHandler, apiKeyRequestHandler, corsResponseHandler
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login
|
||||
|
||||
|
||||
@@ -42,6 +42,8 @@ from . import languages as api_languages
|
||||
|
||||
VERSION = "0.1"
|
||||
|
||||
api.after_request(noCachingResponseHandler)
|
||||
|
||||
api.before_request(apiKeyRequestHandler)
|
||||
api.after_request(corsResponseHandler)
|
||||
|
||||
@@ -109,6 +111,7 @@ def firstRunSetup():
|
||||
"pass2" in request.values.keys() and request.values["pass1"] == request.values["pass2"]:
|
||||
# configure access control
|
||||
s().setBoolean(["accessControl", "enabled"], True)
|
||||
octoprint.server.userManager.enable()
|
||||
octoprint.server.userManager.addUser(request.values["user"], request.values["pass1"], True, ["user", "admin"])
|
||||
s().setBoolean(["server", "firstRun"], False)
|
||||
elif "ac" in request.values.keys() and not request.values["ac"] in valid_boolean_trues:
|
||||
@@ -118,6 +121,7 @@ def firstRunSetup():
|
||||
|
||||
octoprint.server.loginManager.anonymous_user = octoprint.users.DummyUser
|
||||
octoprint.server.principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader)
|
||||
octoprint.server.userManager.disable()
|
||||
|
||||
s().save()
|
||||
return NO_CONTENT
|
||||
@@ -179,7 +183,7 @@ def performSystemAction():
|
||||
|
||||
@api.route("/login", methods=["POST"])
|
||||
def login():
|
||||
if octoprint.server.userManager is not None and "user" in request.values.keys() and "pass" in request.values.keys():
|
||||
if octoprint.server.userManager.enabled and "user" in request.values.keys() and "pass" in request.values.keys():
|
||||
username = request.values["user"]
|
||||
password = request.values["pass"]
|
||||
|
||||
@@ -194,7 +198,7 @@ def login():
|
||||
user = octoprint.server.userManager.findUser(username)
|
||||
if user is not None:
|
||||
if octoprint.server.userManager.checkPassword(username, password):
|
||||
if octoprint.server.userManager is not None:
|
||||
if octoprint.server.userManager.enabled:
|
||||
user = octoprint.server.userManager.login_user(user)
|
||||
session["usersession.id"] = user.get_session()
|
||||
g.user = user
|
||||
|
||||
@@ -7,7 +7,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
from flask import request, jsonify, make_response, url_for
|
||||
|
||||
import octoprint.util as util
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT
|
||||
@@ -18,6 +17,8 @@ import octoprint.filemanager
|
||||
import octoprint.filemanager.util
|
||||
import octoprint.slicing
|
||||
|
||||
import psutil
|
||||
|
||||
|
||||
#~~ GCODE file handling
|
||||
|
||||
@@ -29,7 +30,8 @@ def readGcodeFiles():
|
||||
filter = request.values["filter"]
|
||||
files = _getFileList(FileDestinations.LOCAL, filter=filter)
|
||||
files.extend(_getFileList(FileDestinations.SDCARD))
|
||||
return jsonify(files=files, free=util.get_free_bytes(settings().getBaseFolder("uploads")))
|
||||
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
|
||||
return jsonify(files=files, free=usage.free, total=usage.total)
|
||||
|
||||
|
||||
@api.route("/files/<string:origin>", methods=["GET"])
|
||||
@@ -40,7 +42,8 @@ def readGcodeFilesForOrigin(origin):
|
||||
files = _getFileList(origin)
|
||||
|
||||
if origin == FileDestinations.LOCAL:
|
||||
return jsonify(files=files, free=util.get_free_bytes(settings().getBaseFolder("uploads")))
|
||||
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
|
||||
return jsonify(files=files, free=usage.free, total=usage.total)
|
||||
else:
|
||||
return jsonify(files=files)
|
||||
|
||||
|
||||
@@ -15,15 +15,18 @@ from octoprint.settings import settings
|
||||
from octoprint.server import NO_CONTENT, admin_permission
|
||||
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
|
||||
from octoprint.server.api import api
|
||||
from octoprint.util import get_free_bytes
|
||||
|
||||
|
||||
@api.route("/logs", methods=["GET"])
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def getLogFiles():
|
||||
import psutil
|
||||
usage = psutil.disk_usage(settings().getBaseFolder("logs"))
|
||||
|
||||
files = _getLogFiles()
|
||||
return jsonify(files=files, free=get_free_bytes(settings().getBaseFolder("logs")))
|
||||
|
||||
return jsonify(files=files, free=usage.free, total=usage.total)
|
||||
|
||||
|
||||
@api.route("/logs/<path:filename>", methods=["GET"])
|
||||
|
||||
@@ -10,10 +10,9 @@ from werkzeug.exceptions import BadRequest
|
||||
import re
|
||||
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
from octoprint.server import printer, NO_CONTENT
|
||||
from octoprint.server import printer, printerProfileManager, NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
|
||||
import octoprint.util as util
|
||||
|
||||
from octoprint.printer import UnknownScript
|
||||
|
||||
@@ -34,9 +33,13 @@ def printerState():
|
||||
|
||||
result = {}
|
||||
|
||||
processor = lambda x: x
|
||||
if not printerProfileManager.get_current_or_default()["heatedBed"]:
|
||||
processor = _delete_bed
|
||||
|
||||
# add temperature information
|
||||
if not "temperature" in excludes:
|
||||
result.update({"temperature": _getTemperatureData(lambda x: x)})
|
||||
result.update({"temperature": _get_temperature_data(processor)})
|
||||
|
||||
# add sd information
|
||||
if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]):
|
||||
@@ -145,14 +148,7 @@ def printerToolState():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
def deleteBed(x):
|
||||
data = dict(x)
|
||||
|
||||
if "bed" in data.keys():
|
||||
del data["bed"]
|
||||
return data
|
||||
|
||||
return jsonify(_getTemperatureData(deleteBed))
|
||||
return jsonify(_get_temperature_data(_delete_bed))
|
||||
|
||||
|
||||
##~~ Heated bed
|
||||
@@ -164,6 +160,9 @@ def printerBedCommand():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
if not printerProfileManager.get_current_or_default()["heatedBed"]:
|
||||
return make_response("Printer does not have a heated bed", 409)
|
||||
|
||||
valid_commands = {
|
||||
"target": ["target"],
|
||||
"offset": ["offset"]
|
||||
@@ -204,15 +203,10 @@ def printerBedState():
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
def deleteTools(x):
|
||||
data = dict(x)
|
||||
if not printerProfileManager.get_current_or_default()["heatedBed"]:
|
||||
return make_response("Printer does not have a heated bed", 409)
|
||||
|
||||
for k in data.keys():
|
||||
if k.startswith("tool"):
|
||||
del data[k]
|
||||
return data
|
||||
|
||||
data = _getTemperatureData(deleteTools)
|
||||
data = _get_temperature_data(_delete_tools)
|
||||
if isinstance(data, Response):
|
||||
return data
|
||||
else:
|
||||
@@ -382,7 +376,7 @@ def getCustomControls():
|
||||
return jsonify(controls=customControls)
|
||||
|
||||
|
||||
def _getTemperatureData(filter):
|
||||
def _get_temperature_data(preprocessor):
|
||||
if not printer.is_operational():
|
||||
return make_response("Printer is not operational", 409)
|
||||
|
||||
@@ -399,8 +393,23 @@ def _getTemperatureData(filter):
|
||||
limit = min(limit, len(history))
|
||||
|
||||
tempData.update({
|
||||
"history": map(lambda x: filter(x), history[-limit:])
|
||||
"history": map(lambda x: preprocessor(x), history[-limit:])
|
||||
})
|
||||
|
||||
return filter(tempData)
|
||||
return preprocessor(tempData)
|
||||
|
||||
|
||||
def _delete_tools(x):
|
||||
return _delete_from_data(x, lambda k: k.startswith("tool"))
|
||||
|
||||
|
||||
def _delete_bed(x):
|
||||
return _delete_from_data(x, lambda k: k == "bed")
|
||||
|
||||
|
||||
def _delete_from_data(x, key_matcher):
|
||||
data = dict(x)
|
||||
for k in data.keys():
|
||||
if key_matcher(k):
|
||||
del data[k]
|
||||
return data
|
||||
@@ -69,7 +69,8 @@ def getSettings():
|
||||
"repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"]),
|
||||
"externalHeatupDetection": s.getBoolean(["feature", "externalHeatupDetection"]),
|
||||
"keyboardControl": s.getBoolean(["feature", "keyboardControl"]),
|
||||
"pollWatched": s.getBoolean(["feature", "pollWatched"])
|
||||
"pollWatched": s.getBoolean(["feature", "pollWatched"]),
|
||||
"ignoreIdenticalResends": s.getBoolean(["feature", "ignoreIdenticalResends"])
|
||||
},
|
||||
"serial": {
|
||||
"port": connectionOptions["portPreference"],
|
||||
@@ -84,7 +85,12 @@ def getSettings():
|
||||
"timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]),
|
||||
"log": s.getBoolean(["serial", "log"]),
|
||||
"additionalPorts": s.get(["serial", "additionalPorts"]),
|
||||
"longRunningCommands": s.get(["serial", "longRunningCommands"])
|
||||
"longRunningCommands": s.get(["serial", "longRunningCommands"]),
|
||||
"checksumRequiringCommands": s.get(["serial", "checksumRequiringCommands"]),
|
||||
"helloCommand": s.get(["serial", "helloCommand"]),
|
||||
"ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
|
||||
"disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]),
|
||||
"triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"])
|
||||
},
|
||||
"folder": {
|
||||
"uploads": s.getBaseFolder("uploads"),
|
||||
@@ -112,6 +118,17 @@ def getSettings():
|
||||
"afterPrintResumed": None,
|
||||
"snippets": dict()
|
||||
}
|
||||
},
|
||||
"server": {
|
||||
"commands": {
|
||||
"systemShutdownCommand": s.get(["server", "commands", "systemShutdownCommand"]),
|
||||
"systemRestartCommand": s.get(["server", "commands", "systemRestartCommand"]),
|
||||
"serverRestartCommand": s.get(["server", "commands", "serverRestartCommand"])
|
||||
},
|
||||
"diskspace": {
|
||||
"warning": s.getInt(["server", "diskspace", "warning"]),
|
||||
"critical": s.getInt(["server", "diskspace", "critical"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,6 +218,7 @@ def setSettings():
|
||||
if "externalHeatupDetection" in data["feature"].keys(): s.setBoolean(["feature", "externalHeatupDetection"], data["feature"]["externalHeatupDetection"])
|
||||
if "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
|
||||
if "pollWatched" in data["feature"]: s.setBoolean(["feature", "pollWatched"], data["feature"]["pollWatched"])
|
||||
if "ignoreIdenticalResends" in data["feature"]: s.setBoolean(["feature", "ignoreIdenticalResends"], data["feature"]["ignoreIdenticalResends"])
|
||||
|
||||
if "serial" in data.keys():
|
||||
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
|
||||
@@ -213,6 +231,11 @@ def setSettings():
|
||||
if "timeoutSdStatus" in data["serial"].keys(): s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
|
||||
if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"])
|
||||
if "longRunningCommands" in data["serial"] and isinstance(data["serial"]["longRunningCommands"], (list, tuple)): s.set(["serial", "longRunningCommands"], data["serial"]["longRunningCommands"])
|
||||
if "checksumRequiringCommands" in data["serial"] and isinstance(data["serial"]["checksumRequiringCommands"], (list, tuple)): s.set(["serial", "checksumRequiringCommands"], data["serial"]["checksumRequiringCommands"])
|
||||
if "helloCommand" in data["serial"]: s.set(["serial", "helloCommand"], data["serial"]["helloCommand"])
|
||||
if "ignoreErrorsFromFirmware" in data["serial"]: s.setBoolean(["serial", "ignoreErrorsFromFirmware"], data["serial"]["ignoreErrorsFromFirmware"])
|
||||
if "disconnectOnErrors" in data["serial"]: s.setBoolean(["serial", "disconnectOnErrors"], data["serial"]["disconnectOnErrors"])
|
||||
if "triggerOkForM29" in data["serial"]: s.setBoolean(["serial", "triggerOkForM29"], data["serial"]["triggerOkForM29"])
|
||||
|
||||
oldLog = s.getBoolean(["serial", "log"])
|
||||
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
|
||||
@@ -250,6 +273,15 @@ def setSettings():
|
||||
continue
|
||||
s.saveScript("gcode", name, script.replace("\r\n", "\n").replace("\r", "\n"))
|
||||
|
||||
if "server" in data:
|
||||
if "commands" in data["server"]:
|
||||
if "systemShutdownCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemShutdownCommand"], data["server"]["commands"]["systemShutdownCommand"])
|
||||
if "systemRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemRestartCommand"], data["server"]["commands"]["systemRestartCommand"])
|
||||
if "serverRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "serverRestartCommand"], data["server"]["commands"]["serverRestartCommand"])
|
||||
if "diskspace" in data["server"]:
|
||||
if "warning" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "warning"], data["server"]["diskspace"]["warning"])
|
||||
if "critical" in data["server"]["diskspace"]: s.setInt(["server", "diskspace", "critical"], data["server"]["diskspace"]["critical"])
|
||||
|
||||
if "plugins" in data:
|
||||
for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin):
|
||||
plugin_id = plugin._identifier
|
||||
|
||||
@@ -14,10 +14,12 @@ import octoprint.timelapse
|
||||
import octoprint.util as util
|
||||
from octoprint.settings import settings, valid_boolean_trues
|
||||
|
||||
from octoprint.server import admin_permission
|
||||
from octoprint.server.util.flask import redirect_to_tornado, restricted_access
|
||||
from octoprint.server import admin_permission, printer
|
||||
from octoprint.server.util.flask import redirect_to_tornado, restricted_access, get_json_command_from_request
|
||||
from octoprint.server.api import api
|
||||
|
||||
from octoprint.server import NO_CONTENT
|
||||
|
||||
|
||||
#~~ timelapse handling
|
||||
|
||||
@@ -29,24 +31,27 @@ def getTimelapseData():
|
||||
config = {"type": "off"}
|
||||
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
|
||||
config["type"] = "zchange"
|
||||
config["postRoll"] = timelapse.postRoll()
|
||||
config["fps"] = timelapse.fps()
|
||||
config["postRoll"] = timelapse.post_roll
|
||||
config["fps"] = timelapse.fps
|
||||
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
|
||||
config["type"] = "timed"
|
||||
config["postRoll"] = timelapse.postRoll()
|
||||
config["fps"] = timelapse.fps()
|
||||
config["postRoll"] = timelapse.post_roll
|
||||
config["fps"] = timelapse.fps
|
||||
config.update({
|
||||
"interval": timelapse.interval()
|
||||
"interval": timelapse.interval
|
||||
})
|
||||
|
||||
files = octoprint.timelapse.getFinishedTimelapses()
|
||||
files = octoprint.timelapse.get_finished_timelapses()
|
||||
for file in files:
|
||||
file["url"] = url_for("index") + "downloads/timelapse/" + file["name"]
|
||||
|
||||
return jsonify({
|
||||
"config": config,
|
||||
"files": files
|
||||
})
|
||||
result = dict(config=config,
|
||||
files=files)
|
||||
|
||||
if "unrendered" in request.values and request.values["unrendered"] in valid_boolean_trues:
|
||||
result.update(unrendered=octoprint.timelapse.get_unrendered_timelapses())
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@api.route("/timelapse/<filename>", methods=["GET"])
|
||||
@@ -57,7 +62,7 @@ def downloadTimelapse(filename):
|
||||
@api.route("/timelapse/<filename>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def deleteTimelapse(filename):
|
||||
if util.is_allowed_file(filename, {"mpg"}):
|
||||
if util.is_allowed_file(filename, ["mpg"]):
|
||||
timelapse_folder = settings().getBaseFolder("timelapse")
|
||||
full_path = os.path.realpath(os.path.join(timelapse_folder, filename))
|
||||
if full_path.startswith(timelapse_folder) and os.path.exists(full_path):
|
||||
@@ -65,6 +70,33 @@ def deleteTimelapse(filename):
|
||||
return getTimelapseData()
|
||||
|
||||
|
||||
@api.route("/timelapse/unrendered/<name>", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def deleteUnrenderedTimelapse(name):
|
||||
octoprint.timelapse.delete_unrendered_timelapse(name)
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/timelapse/unrendered/<name>", methods=["POST"])
|
||||
@restricted_access
|
||||
def processUnrenderedTimelapseCommand(name):
|
||||
# valid file commands, dict mapping command name to mandatory parameters
|
||||
valid_commands = {
|
||||
"render": []
|
||||
}
|
||||
|
||||
command, data, response = get_json_command_from_request(request, valid_commands)
|
||||
if response is not None:
|
||||
return response
|
||||
|
||||
if command == "render":
|
||||
if printer.is_printing() or printer.is_paused():
|
||||
return make_response("Printer is currently printing, cannot render timelapse", 409)
|
||||
octoprint.timelapse.render_unrendered_timelapse(name)
|
||||
|
||||
return NO_CONTENT
|
||||
|
||||
|
||||
@api.route("/timelapse", methods=["POST"])
|
||||
@restricted_access
|
||||
def setTimelapseConfig():
|
||||
@@ -114,9 +146,9 @@ def setTimelapseConfig():
|
||||
return make_response("Invalid value for interval: %d" % interval)
|
||||
|
||||
if admin_permission.can() and "save" in request.values and request.values["save"] in valid_boolean_trues:
|
||||
octoprint.timelapse.configureTimelapse(config, True)
|
||||
octoprint.timelapse.configure_timelapse(config, True)
|
||||
else:
|
||||
octoprint.timelapse.configureTimelapse(config)
|
||||
octoprint.timelapse.configure_timelapse(config)
|
||||
|
||||
return getTimelapseData()
|
||||
|
||||
@@ -23,7 +23,7 @@ from octoprint.server.util.flask import restricted_access
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def getUsers():
|
||||
if userManager is None:
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
return jsonify({"users": userManager.getAllUsers()})
|
||||
@@ -33,7 +33,7 @@ def getUsers():
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def addUser():
|
||||
if userManager is None:
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
@@ -62,7 +62,7 @@ def addUser():
|
||||
@api.route("/users/<username>", methods=["GET"])
|
||||
@restricted_access
|
||||
def getUser(username):
|
||||
if userManager is None:
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
|
||||
@@ -79,7 +79,7 @@ def getUser(username):
|
||||
@restricted_access
|
||||
@admin_permission.require(403)
|
||||
def updateUser(username):
|
||||
if userManager is None:
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
user = userManager.findUser(username)
|
||||
@@ -110,7 +110,7 @@ def updateUser(username):
|
||||
@restricted_access
|
||||
@admin_permission.require(http_exception=403)
|
||||
def removeUser(username):
|
||||
if userManager is None:
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
try:
|
||||
@@ -123,7 +123,7 @@ def removeUser(username):
|
||||
@api.route("/users/<username>/password", methods=["PUT"])
|
||||
@restricted_access
|
||||
def changePasswordForUser(username):
|
||||
if userManager is None:
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
|
||||
@@ -151,7 +151,7 @@ def changePasswordForUser(username):
|
||||
@api.route("/users/<username>/settings", methods=["GET"])
|
||||
@restricted_access
|
||||
def getSettingsForUser(username):
|
||||
if userManager is None:
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is None or current_user.is_anonymous() or (current_user.get_name() != username and not current_user.is_admin()):
|
||||
@@ -165,7 +165,7 @@ def getSettingsForUser(username):
|
||||
@api.route("/users/<username>/settings", methods=["PATCH"])
|
||||
@restricted_access
|
||||
def changeSettingsForUser(username):
|
||||
if userManager is None:
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is None or current_user.is_anonymous() or (current_user.get_name() != username and not current_user.is_admin()):
|
||||
@@ -185,7 +185,7 @@ def changeSettingsForUser(username):
|
||||
@api.route("/users/<username>/apikey", methods=["DELETE"])
|
||||
@restricted_access
|
||||
def deleteApikeyForUser(username):
|
||||
if userManager is None:
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
|
||||
@@ -201,7 +201,7 @@ def deleteApikeyForUser(username):
|
||||
@api.route("/users/<username>/apikey", methods=["POST"])
|
||||
@restricted_access
|
||||
def generateApikeyForUser(username):
|
||||
if userManager is None:
|
||||
if not userManager.enabled:
|
||||
return jsonify(SUCCESS)
|
||||
|
||||
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
|
||||
|
||||
@@ -10,10 +10,15 @@ from flask import Blueprint, request, make_response, jsonify
|
||||
|
||||
import octoprint.server
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.server.util import noCachingResponseHandler, corsResponseHandler
|
||||
from octoprint.settings import settings as s
|
||||
|
||||
apps = Blueprint("apps", __name__)
|
||||
|
||||
apps.after_request(noCachingResponseHandler)
|
||||
apps.after_request(corsResponseHandler)
|
||||
|
||||
@apps.route("/auth", methods=["GET"])
|
||||
def getSessionKey():
|
||||
unverified_key, valid_until = octoprint.server.appSessionManager.create()
|
||||
|
||||
@@ -80,6 +80,18 @@ def corsResponseHandler(resp):
|
||||
return resp
|
||||
|
||||
|
||||
def noCachingResponseHandler(resp):
|
||||
"""
|
||||
``after_request`` handler for blueprints which shall set no caching headers
|
||||
on their responses.
|
||||
|
||||
Sets ``Cache-Control``, ``Pragma`` and ``Expires`` headers accordingly
|
||||
to prevent all client side caching from taking place.
|
||||
"""
|
||||
|
||||
return flask.add_non_caching_response_headers(resp)
|
||||
|
||||
|
||||
def optionsAllowOrigin(request):
|
||||
"""
|
||||
Shortcut for request handling for CORS OPTIONS requests to set CORS headers.
|
||||
@@ -108,7 +120,7 @@ def get_user_for_apikey(apikey):
|
||||
if apikey == settings().get(["api", "key"]) or octoprint.server.appSessionManager.validate(apikey):
|
||||
# master key or an app session key was used
|
||||
return ApiUser()
|
||||
elif octoprint.server.userManager is not None:
|
||||
elif octoprint.server.userManager.enabled:
|
||||
# user key might have been used
|
||||
return octoprint.server.userManager.findUser(apikey=apikey)
|
||||
return None
|
||||
@@ -131,6 +143,20 @@ def get_api_key(request):
|
||||
return None
|
||||
|
||||
|
||||
def get_plugin_hash():
|
||||
from octoprint.plugin import plugin_manager
|
||||
|
||||
plugin_signature = lambda impl: "{}:{}".format(impl._identifier, impl._plugin_version)
|
||||
template_plugins = map(plugin_signature, plugin_manager().get_implementations(octoprint.plugin.TemplatePlugin))
|
||||
asset_plugins = map(plugin_signature, plugin_manager().get_implementations(octoprint.plugin.AssetPlugin))
|
||||
ui_plugins = sorted(set(template_plugins + asset_plugins))
|
||||
|
||||
import hashlib
|
||||
plugin_hash = hashlib.sha1()
|
||||
plugin_hash.update(",".join(ui_plugins))
|
||||
return plugin_hash.hexdigest()
|
||||
|
||||
|
||||
#~~ reverse proxy compatible WSGI middleware
|
||||
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import flask.ext.assets
|
||||
import webassets.updater
|
||||
import webassets.utils
|
||||
import functools
|
||||
import contextlib
|
||||
import time
|
||||
import uuid
|
||||
import threading
|
||||
@@ -26,7 +27,7 @@ import octoprint.server
|
||||
import octoprint.users
|
||||
import octoprint.plugin
|
||||
|
||||
from werkzeug.contrib.cache import SimpleCache
|
||||
from werkzeug.contrib.cache import BaseCache
|
||||
|
||||
|
||||
#~~ monkey patching
|
||||
@@ -123,12 +124,19 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
|
||||
|
||||
def fix_webassets_cache():
|
||||
from webassets import cache
|
||||
import os
|
||||
import tempfile
|
||||
import pickle
|
||||
import shutil
|
||||
|
||||
error_logger = logging.getLogger(__name__ + ".fix_webassets_cache")
|
||||
|
||||
def fixed_set(self, key, data):
|
||||
import os
|
||||
import tempfile
|
||||
import pickle
|
||||
import shutil
|
||||
|
||||
if not os.path.exists(self.directory):
|
||||
error_logger.warn("Cache directory {} doesn't exist, not going "
|
||||
"to attempt to write cache file".format(self.directory))
|
||||
|
||||
md5 = '%s' % cache.make_md5(self.V, key)
|
||||
filename = os.path.join(self.directory, md5)
|
||||
fd, temp_filename = tempfile.mkstemp(prefix='.' + md5,
|
||||
@@ -148,6 +156,11 @@ def fix_webassets_cache():
|
||||
import warnings
|
||||
from webassets.cache import make_md5
|
||||
|
||||
if not os.path.exists(self.directory):
|
||||
error_logger.warn("Cache directory {} doesn't exist, not going "
|
||||
"to attempt to read cache file".format(self.directory))
|
||||
return None
|
||||
|
||||
try:
|
||||
hash = make_md5(self.V, key)
|
||||
except IOError as e:
|
||||
@@ -194,26 +207,31 @@ def fix_webassets_filtertool():
|
||||
try:
|
||||
content = func().getvalue()
|
||||
if self.cache:
|
||||
log.debug('Storing result in cache with key %s', key,)
|
||||
self.cache.set(key, content)
|
||||
try:
|
||||
log.debug('Storing result in cache with key %s', key,)
|
||||
self.cache.set(key, content)
|
||||
except:
|
||||
error_logger.exception("Got an exception while trying to save file to cache, not caching")
|
||||
return MemoryHunk(content)
|
||||
except:
|
||||
error_logger.exception("Got an exception while trying to apply filter, ignoring file")
|
||||
return MemoryHunk("")
|
||||
return MemoryHunk(u"")
|
||||
|
||||
FilterTool._wrap_cache = fixed_wrap_cache
|
||||
|
||||
#~~ passive login helper
|
||||
|
||||
def passive_login():
|
||||
if octoprint.server.userManager is not None:
|
||||
if octoprint.server.userManager.enabled:
|
||||
user = octoprint.server.userManager.login_user(flask.ext.login.current_user)
|
||||
else:
|
||||
user = flask.ext.login.current_user
|
||||
|
||||
if user is not None and not user.is_anonymous():
|
||||
flask.g.user = user
|
||||
flask.ext.principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask.ext.principal.Identity(user.get_id()))
|
||||
if hasattr(user, "get_session"):
|
||||
flask.session["usersession.id"] = user.get_session()
|
||||
flask.g.user = user
|
||||
return flask.jsonify(user.asDict())
|
||||
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
|
||||
and settings().get(["accessControl", "autologinAs"]) is not None \
|
||||
@@ -237,14 +255,66 @@ def passive_login():
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.exception("Could not autologin user %s for networks %r" % (autologinAs, localNetworks))
|
||||
|
||||
return ("", 204)
|
||||
return "", 204
|
||||
|
||||
|
||||
#~~ cache decorator for cacheable views
|
||||
|
||||
_cache = SimpleCache()
|
||||
class LessSimpleCache(BaseCache):
|
||||
"""
|
||||
Slightly improved version of :class:`SimpleCache`.
|
||||
|
||||
def cached(timeout=5 * 60, key=lambda: "view/%s" % flask.request.path, unless=None, refreshif=None):
|
||||
Setting ``default_timeout`` or ``timeout`` to ``-1`` will have no timeout be applied at all.
|
||||
"""
|
||||
|
||||
def __init__(self, threshold=500, default_timeout=300):
|
||||
BaseCache.__init__(self, default_timeout=default_timeout)
|
||||
self._cache = {}
|
||||
self.clear = self._cache.clear
|
||||
self._threshold = threshold
|
||||
|
||||
def _prune(self):
|
||||
if self.over_threshold():
|
||||
now = time.time()
|
||||
for idx, (key, (expires, _)) in enumerate(self._cache.items()):
|
||||
if expires is not None and expires <= now or idx % 3 == 0:
|
||||
self._cache.pop(key, None)
|
||||
|
||||
def get(self, key):
|
||||
import pickle
|
||||
now = time.time()
|
||||
expires, value = self._cache.get(key, (0, None))
|
||||
if expires is None or expires > now:
|
||||
return pickle.loads(value)
|
||||
|
||||
def set(self, key, value, timeout=None):
|
||||
import pickle
|
||||
self._prune()
|
||||
self._cache[key] = (self.calculate_timeout(timeout=timeout),
|
||||
pickle.dumps(value, pickle.HIGHEST_PROTOCOL))
|
||||
|
||||
def add(self, key, value, timeout=None):
|
||||
self.set(key, value, timeout=None)
|
||||
self._cache.setdefault(key, self._cache[key])
|
||||
|
||||
def delete(self, key):
|
||||
self._cache.pop(key, None)
|
||||
|
||||
def calculate_timeout(self, timeout=None):
|
||||
if timeout is None:
|
||||
timeout = self.default_timeout
|
||||
if timeout is -1:
|
||||
return None
|
||||
return time.time() + timeout
|
||||
|
||||
def over_threshold(self):
|
||||
if self._threshold is None:
|
||||
return False
|
||||
return len(self._cache) > self._threshold
|
||||
|
||||
_cache = LessSimpleCache()
|
||||
|
||||
def cached(timeout=5 * 60, key=lambda: "view:%s" % flask.request.path, unless=None, refreshif=None, unless_response=None):
|
||||
def decorator(f):
|
||||
@functools.wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
@@ -261,18 +331,24 @@ def cached(timeout=5 * 60, key=lambda: "view/%s" % flask.request.path, unless=No
|
||||
return f(*args, **kwargs)
|
||||
|
||||
cache_key = key()
|
||||
rv = _cache.get(cache_key)
|
||||
|
||||
# only take the value from the cache if we are not required to refresh it from the wrapped function
|
||||
if not callable(refreshif) or not refreshif():
|
||||
rv = _cache.get(cache_key)
|
||||
if rv is not None:
|
||||
logger.debug("Serving entry for {path} from cache".format(path=flask.request.path))
|
||||
return rv
|
||||
if rv is not None and (not callable(refreshif) or not refreshif(rv)):
|
||||
logger.debug("Serving entry for {path} from cache".format(path=flask.request.path))
|
||||
if not "X-From-Cache" in rv.headers:
|
||||
rv.headers["X-From-Cache"] = "true"
|
||||
return rv
|
||||
|
||||
# get value from wrapped function
|
||||
logger.debug("No cache entry or refreshing cache for {path}, calling wrapped function".format(path=flask.request.path))
|
||||
logger.debug("No cache entry or refreshing cache for {path} (key: {key}), calling wrapped function".format(path=flask.request.path, key=cache_key))
|
||||
rv = f(*args, **kwargs)
|
||||
|
||||
# do not store if the "unless_response" condition is true
|
||||
if callable(unless_response) and unless_response(rv):
|
||||
logger.debug("Not caching result for {path}, bypassed".format(path=flask.request.path))
|
||||
return rv
|
||||
|
||||
# store it in the cache
|
||||
_cache.set(cache_key, rv, timeout=timeout)
|
||||
|
||||
@@ -285,6 +361,247 @@ def cached(timeout=5 * 60, key=lambda: "view/%s" % flask.request.path, unless=No
|
||||
def cache_check_headers():
|
||||
return "no-cache" in flask.request.cache_control or "no-cache" in flask.request.pragma
|
||||
|
||||
def cache_check_response_headers(response):
|
||||
if not isinstance(response, flask.Response):
|
||||
return False
|
||||
|
||||
headers = response.headers
|
||||
|
||||
if "Cache-Control" in headers and "no-cache" in headers["Cache-Control"]:
|
||||
return True
|
||||
|
||||
if "Pragma" in headers and "no-cache" in headers["Pragma"]:
|
||||
return True
|
||||
|
||||
if "Expires" in headers and headers["Expires"] in ("0", "-1"):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
class PreemptiveCache(object):
|
||||
|
||||
def __init__(self, cachefile):
|
||||
self.cachefile = cachefile
|
||||
|
||||
self._lock = threading.RLock()
|
||||
self._logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
|
||||
self._log_access = True
|
||||
|
||||
def record(self, data, unless=None):
|
||||
if callable(unless) and unless():
|
||||
return
|
||||
|
||||
entry_data = data
|
||||
if callable(entry_data):
|
||||
entry_data = entry_data()
|
||||
|
||||
if entry_data is not None:
|
||||
from flask import request
|
||||
self.add_data(request.path, entry_data)
|
||||
|
||||
@contextlib.contextmanager
|
||||
def disable_access_logging(self):
|
||||
with self._lock:
|
||||
self._log_access = False
|
||||
yield
|
||||
self._log_access = True
|
||||
|
||||
def clean_all_data(self, cleanup_function):
|
||||
assert callable(cleanup_function)
|
||||
|
||||
with self._lock:
|
||||
all_data = self.get_all_data()
|
||||
for root, entries in all_data.items():
|
||||
old_count = len(entries)
|
||||
entries = cleanup_function(root, entries)
|
||||
if not entries:
|
||||
del all_data[root]
|
||||
self._logger.debug("Removed root {} from preemptive cache".format(root))
|
||||
elif len(entries) < old_count:
|
||||
all_data[root] = entries
|
||||
self._logger.debug("Removed {} from preemptive cache for root {}".format(old_count - len(entries), root))
|
||||
self.set_all_data(all_data)
|
||||
|
||||
return all_data
|
||||
|
||||
def get_all_data(self):
|
||||
import yaml
|
||||
|
||||
cache_data = None
|
||||
with self._lock:
|
||||
try:
|
||||
with open(self.cachefile, "r") as f:
|
||||
cache_data = yaml.safe_load(f)
|
||||
except IOError as e:
|
||||
import errno
|
||||
if e.errno != errno.ENOENT:
|
||||
raise
|
||||
except:
|
||||
self._logger.exception("Error while reading {}".format(self.cachefile))
|
||||
|
||||
if cache_data is None:
|
||||
cache_data = dict()
|
||||
|
||||
return cache_data
|
||||
|
||||
def get_data(self, root):
|
||||
cache_data = self.get_all_data()
|
||||
return cache_data.get(root, dict())
|
||||
|
||||
def set_all_data(self, data):
|
||||
from octoprint.util import atomic_write
|
||||
import yaml
|
||||
|
||||
with self._lock:
|
||||
try:
|
||||
with atomic_write(self.cachefile, "wb") as handle:
|
||||
yaml.safe_dump(data, handle,default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
except:
|
||||
self._logger.exception("Error while writing {}".format(self.cachefile))
|
||||
|
||||
def set_data(self, root, data):
|
||||
with self._lock:
|
||||
all_data = self.get_all_data()
|
||||
all_data[root] = data
|
||||
self.set_all_data(all_data)
|
||||
|
||||
def add_data(self, root, data):
|
||||
from octoprint.util import dict_filter
|
||||
|
||||
def strip_ignored(d):
|
||||
return dict_filter(d, lambda k, v: not k.startswith("_"))
|
||||
|
||||
def compare(a, b):
|
||||
return set(strip_ignored(a).items()) == set(strip_ignored(b).items())
|
||||
|
||||
def split_matched_and_unmatched(entry, entries):
|
||||
matched = []
|
||||
unmatched = []
|
||||
|
||||
for e in entries:
|
||||
if compare(e, entry):
|
||||
matched.append(e)
|
||||
else:
|
||||
unmatched.append(e)
|
||||
|
||||
return matched, unmatched
|
||||
|
||||
with self._lock:
|
||||
cache_data = self.get_all_data()
|
||||
|
||||
if not root in cache_data:
|
||||
cache_data[root] = []
|
||||
|
||||
existing, other = split_matched_and_unmatched(data, cache_data[root])
|
||||
|
||||
def get_newest(entries):
|
||||
result = None
|
||||
for entry in entries:
|
||||
if "_timestamp" in entry and (result is None or ("_timestamp" in entry and result["_timestamp"] < entry["_timestamp"])):
|
||||
result = entry
|
||||
return result
|
||||
|
||||
to_persist = get_newest(existing)
|
||||
if not to_persist:
|
||||
import copy
|
||||
to_persist = copy.deepcopy(data)
|
||||
to_persist["_timestamp"] = time.time()
|
||||
to_persist["_count"] = 1
|
||||
self._logger.info("Adding entry for {} and {!r}".format(root, to_persist))
|
||||
elif self._log_access:
|
||||
to_persist["_timestamp"] = time.time()
|
||||
to_persist["_count"] = to_persist.get("_count", 0) + 1
|
||||
self._logger.debug("Updating timestamp and counter for {} and {!r}".format(root, data))
|
||||
else:
|
||||
self._logger.debug("Not updating timestamp and counter for {} and {!r}, currently flagged as disabled".format(root, data))
|
||||
|
||||
self.set_data(root, [to_persist] + other)
|
||||
|
||||
|
||||
def preemptively_cached(cache, data, unless=None):
|
||||
def decorator(f):
|
||||
@functools.wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
cache.record(data, unless=unless)
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
return decorator
|
||||
|
||||
|
||||
def etagged(etag):
|
||||
def decorator(f):
|
||||
@functools.wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
rv = f(*args, **kwargs)
|
||||
if isinstance(rv, flask.Response):
|
||||
result = etag
|
||||
if callable(result):
|
||||
result = result(rv)
|
||||
if result:
|
||||
rv.set_etag(result)
|
||||
return rv
|
||||
return decorated_function
|
||||
return decorator
|
||||
|
||||
|
||||
def lastmodified(date):
|
||||
def decorator(f):
|
||||
@functools.wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
rv = f(*args, **kwargs)
|
||||
if not "Last-Modified" in rv.headers:
|
||||
result = date
|
||||
if callable(result):
|
||||
result = result(rv)
|
||||
|
||||
if not isinstance(result, basestring):
|
||||
from werkzeug.http import http_date
|
||||
result = http_date(result)
|
||||
|
||||
if result:
|
||||
rv.headers["Last-Modified"] = result
|
||||
return rv
|
||||
return decorated_function
|
||||
return decorator
|
||||
|
||||
|
||||
def conditional(condition, met):
|
||||
def decorator(f):
|
||||
@functools.wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if callable(condition) and condition():
|
||||
# condition has been met, return met-response
|
||||
rv = met
|
||||
if callable(met):
|
||||
rv = met()
|
||||
return rv
|
||||
|
||||
# condition hasn't been met, call decorated function
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
return decorator
|
||||
|
||||
|
||||
def check_etag(etag):
|
||||
return flask.request.method in ("GET", "HEAD") and \
|
||||
flask.request.if_none_match and \
|
||||
etag in flask.request.if_none_match
|
||||
|
||||
|
||||
def check_lastmodified(lastmodified):
|
||||
return flask.request.method in ("GET", "HEAD") and \
|
||||
flask.request.if_modified_since and \
|
||||
lastmodified >= flask.request.if_modified_since
|
||||
|
||||
|
||||
def add_non_caching_response_headers(response):
|
||||
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0"
|
||||
response.headers["Pragma"] = "no-cache"
|
||||
response.headers["Expires"] = "-1"
|
||||
return response
|
||||
|
||||
|
||||
#~~ access validators for use with tornado
|
||||
|
||||
|
||||
@@ -383,7 +700,7 @@ def restricted_access(func):
|
||||
@functools.wraps(func)
|
||||
def decorated_view(*args, **kwargs):
|
||||
# if OctoPrint hasn't been set up yet, abort
|
||||
if settings().getBoolean(["server", "firstRun"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
|
||||
if settings().getBoolean(["server", "firstRun"]) and settings().getBoolean(["accessControl", "enabled"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
|
||||
return flask.make_response("OctoPrint isn't setup yet", 403)
|
||||
|
||||
apikey = octoprint.server.util.get_api_key(flask.request)
|
||||
@@ -483,7 +800,8 @@ def get_remote_address(request):
|
||||
|
||||
|
||||
def get_json_command_from_request(request, valid_commands):
|
||||
if not "application/json" in request.headers["Content-Type"]:
|
||||
content_type = request.headers.get("Content-Type", None)
|
||||
if content_type is None or not "application/json" in content_type:
|
||||
return None, None, make_response("Expected content-type JSON", 400)
|
||||
|
||||
data = request.json
|
||||
@@ -563,7 +881,7 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater):
|
||||
|
||||
##~~ plugin assets collector
|
||||
|
||||
def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, preferred_stylesheet="css"):
|
||||
def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
logger = logging.getLogger(__name__ + ".collect_plugin_assets")
|
||||
|
||||
supported_stylesheets = ("css", "less")
|
||||
@@ -586,6 +904,7 @@ def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, prefer
|
||||
'js/app/viewmodels/slicing.js',
|
||||
'js/app/viewmodels/temperature.js',
|
||||
'js/app/viewmodels/terminal.js',
|
||||
'js/app/viewmodels/timelapse.js',
|
||||
'js/app/viewmodels/users.js',
|
||||
'js/app/viewmodels/log.js',
|
||||
'js/app/viewmodels/usersettings.js'
|
||||
@@ -597,8 +916,6 @@ def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, prefer
|
||||
'gcodeviewer/js/gCodeReader.js',
|
||||
'gcodeviewer/js/renderer.js'
|
||||
]
|
||||
if enable_timelapse:
|
||||
assets["js"].append('js/app/viewmodels/timelapse.js')
|
||||
|
||||
if preferred_stylesheet == "less":
|
||||
assets["less"].append('less/octoprint.less')
|
||||
@@ -608,8 +925,12 @@ def collect_plugin_assets(enable_gcodeviewer=True, enable_timelapse=True, prefer
|
||||
asset_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.AssetPlugin)
|
||||
for implementation in asset_plugins:
|
||||
name = implementation._identifier
|
||||
all_assets = implementation.get_assets()
|
||||
basefolder = implementation.get_asset_folder()
|
||||
try:
|
||||
all_assets = implementation.get_assets()
|
||||
basefolder = implementation.get_asset_folder()
|
||||
except:
|
||||
logger.exception("Got an error while trying to collect assets from {}, ignoring assets from the plugin".format(name))
|
||||
continue
|
||||
|
||||
def asset_exists(category, asset):
|
||||
exists = os.path.exists(os.path.join(basefolder, asset))
|
||||
|
||||
@@ -39,6 +39,10 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
|
||||
|
||||
self._remoteAddress = None
|
||||
|
||||
self._throttleFactor = 1
|
||||
self._lastCurrent = 0
|
||||
self._baseRateLimit = 0.5
|
||||
|
||||
def _getRemoteAddress(self, info):
|
||||
forwardedFor = info.headers.get("X-Forwarded-For")
|
||||
if forwardedFor is not None:
|
||||
@@ -59,24 +63,41 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
|
||||
plugin_hash.update(",".join(ui_plugins))
|
||||
|
||||
# connected => update the API key, might be necessary if the client was left open while the server restarted
|
||||
self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION, "display_version": octoprint.server.DISPLAY_VERSION, "plugin_hash": plugin_hash.hexdigest()})
|
||||
self._emit("connected", {
|
||||
"apikey": octoprint.server.UI_API_KEY,
|
||||
"version": octoprint.server.VERSION,
|
||||
"display_version": octoprint.server.DISPLAY_VERSION,
|
||||
"branch": octoprint.server.BRANCH,
|
||||
"plugin_hash": plugin_hash.hexdigest()
|
||||
})
|
||||
|
||||
self._printer.register_callback(self)
|
||||
self._fileManager.register_slicingprogress_callback(self)
|
||||
octoprint.timelapse.registerCallback(self)
|
||||
octoprint.timelapse.register_callback(self)
|
||||
self._pluginManager.register_message_receiver(self.on_plugin_message)
|
||||
|
||||
self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress})
|
||||
for event in octoprint.events.all_events():
|
||||
self._eventManager.subscribe(event, self._onEvent)
|
||||
|
||||
octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current)
|
||||
octoprint.timelapse.notify_callbacks(octoprint.timelapse.current)
|
||||
|
||||
# This is a horrible hack for now to allow displaying a notification that a render job is still
|
||||
# active in the backend on a fresh connect of a client. This needs to be substituted with a proper
|
||||
# job management for timelapse rendering, analysis stuff etc that also gets cancelled when prints
|
||||
# start and so on.
|
||||
#
|
||||
# For now this is the easiest way though to at least inform the user that a timelapse is still ongoing.
|
||||
#
|
||||
# TODO remove when central job management becomes available and takes care of this for us
|
||||
if octoprint.timelapse.current_render_job is not None:
|
||||
self._emit("event", {"type": Events.MOVIE_RENDERING, "payload": octoprint.timelapse.current_render_job})
|
||||
|
||||
def on_close(self):
|
||||
self._logger.info("Client connection closed: %s" % self._remoteAddress)
|
||||
self._printer.unregister_callback(self)
|
||||
self._fileManager.unregister_slicingprogress_callback(self)
|
||||
octoprint.timelapse.unregisterCallback(self)
|
||||
octoprint.timelapse.unregister_callback(self)
|
||||
self._pluginManager.unregister_message_receiver(self.on_plugin_message)
|
||||
|
||||
self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress})
|
||||
@@ -84,9 +105,31 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
|
||||
self._eventManager.unsubscribe(event, self._onEvent)
|
||||
|
||||
def on_message(self, message):
|
||||
pass
|
||||
try:
|
||||
import json
|
||||
message = json.loads(message)
|
||||
except:
|
||||
self._logger.warn("Invalid JSON received from client {}, ignoring: {!r}".format(self._remoteAddress, message))
|
||||
return
|
||||
|
||||
if "throttle" in message:
|
||||
try:
|
||||
throttle = int(message["throttle"])
|
||||
if throttle < 1:
|
||||
raise ValueError()
|
||||
except ValueError:
|
||||
self._logger.warn("Got invalid throttle factor from client {}, ignoring: {!r}".format(self._remoteAddress, message["throttle"]))
|
||||
else:
|
||||
self._throttleFactor = throttle
|
||||
self._logger.debug("Set throttle factor for client {} to {}".format(self._remoteAddress, self._throttleFactor))
|
||||
|
||||
def on_printer_send_current_data(self, data):
|
||||
# make sure we rate limit the updates according to our throttle factor
|
||||
now = time.time()
|
||||
if now < self._lastCurrent + self._baseRateLimit * self._throttleFactor:
|
||||
return
|
||||
self._lastCurrent = now
|
||||
|
||||
# add current temperature, log and message backlogs to sent data
|
||||
with self._temperatureBacklogMutex:
|
||||
temperatures = self._temperatureBacklog
|
||||
|
||||
@@ -245,7 +245,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
|
||||
self._on_part_header(self._buffer[delimiter_len+2:end_of_header])
|
||||
self._buffer = self._buffer[end_of_header + 4:]
|
||||
|
||||
if delimiter_loc != -1 and self._buffer[delimiter_len:delimiter_len+2] == "--":
|
||||
if delimiter_loc != -1 and self._buffer.strip() == delimiter + "--":
|
||||
# we saw the last boundary and are at the end of our request
|
||||
if self._current_part:
|
||||
self._on_part_finish(self._current_part)
|
||||
@@ -360,13 +360,24 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
|
||||
for name, part in self._parts.iteritems():
|
||||
if "filename" in part:
|
||||
# add form fields for filename, path, size and content_type for all files contained in the request
|
||||
fields = dict((self._suffixes[key], value) for (key, value) in dict(name=part["filename"], path=part["path"], size=str(os.stat(part["path"]).st_size), content_type=part["content_type"]).iteritems())
|
||||
if not "path" in part:
|
||||
continue
|
||||
|
||||
parameters = dict(
|
||||
name=part["filename"],
|
||||
path=part["path"],
|
||||
size=str(os.stat(part["path"]).st_size)
|
||||
)
|
||||
if "content_type" in part:
|
||||
parameters["content_type"] = part["content_type"]
|
||||
|
||||
fields = dict((self._suffixes[key], value) for (key, value) in parameters.iteritems())
|
||||
for n, p in fields.iteritems():
|
||||
key = name + "." + n
|
||||
self._new_body += b"--%s\r\n" % self._multipart_boundary
|
||||
self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % key
|
||||
self._new_body += b"\r\n"
|
||||
self._new_body += p + b"\r\n"
|
||||
self._new_body += b"%s\r\n" % p
|
||||
elif "data" in part:
|
||||
self._new_body += b"--%s\r\n" % self._multipart_boundary
|
||||
value = part["data"]
|
||||
@@ -757,6 +768,8 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
:class:``~tornado.web.StaticFileHandler`` as the ``default_filename`` keyword parameter). Defaults to ``None``.
|
||||
as_attachment (bool): Whether to serve requested files with ``Content-Disposition: attachment`` header (``True``)
|
||||
or not. Defaults to ``False``.
|
||||
allow_client_caching (bool): Whether to allow the client to cache (by not setting any ``Cache-Control`` or
|
||||
``Expires`` headers on the response) or not.
|
||||
access_validation (function): Callback to call in the ``get`` method to validate access to the resource. Will
|
||||
be called with ``self.request`` as parameter which contains the full tornado request object. Should raise
|
||||
a ``tornado.web.HTTPError`` if access is not allowed in which case the request will not be further processed.
|
||||
@@ -765,13 +778,22 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
with the requested path as parameter. Should raise a ``tornado.web.HTTPError`` (e.g. an 404) if the requested
|
||||
path does not pass validation in which case the request will not be further processed.
|
||||
Defaults to ``None`` and hence no path validation being performed.
|
||||
etag_generator (function): Callback to call for generating the value of the ETag response header. Will be
|
||||
called with the response handler as parameter. May return ``None`` to prevent the ETag response header
|
||||
from being set. If not provided the last modified time of the file in question will be used as returned
|
||||
by ``get_content_version``.
|
||||
"""
|
||||
|
||||
def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None, path_validation=None):
|
||||
def initialize(self, path, default_filename=None, as_attachment=False, allow_client_caching=True,
|
||||
access_validation=None, path_validation=None, etag_generator=None,
|
||||
mime_type_guesser=None):
|
||||
tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename)
|
||||
self._as_attachment = as_attachment
|
||||
self._allow_client_caching = allow_client_caching
|
||||
self._access_validation = access_validation
|
||||
self._path_validation = path_validation
|
||||
self._etag_generator = etag_generator
|
||||
self._mime_type_guesser = mime_type_guesser
|
||||
|
||||
def get(self, path, include_body=True):
|
||||
if self._access_validation is not None:
|
||||
@@ -785,6 +807,24 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
if self._as_attachment:
|
||||
self.set_header("Content-Disposition", "attachment")
|
||||
|
||||
if not self._allow_client_caching:
|
||||
self.set_header("Cache-Control", "max-age=0, must-revalidate, private")
|
||||
self.set_header("Expires", "-1")
|
||||
|
||||
def compute_etag(self):
|
||||
if self._etag_generator is not None:
|
||||
return self._etag_generator(self)
|
||||
else:
|
||||
return self.get_content_version(self.absolute_path)
|
||||
|
||||
def get_content_type(self):
|
||||
if self._mime_type_guesser is not None:
|
||||
type = self._mime_type_guesser(self.absolute_path)
|
||||
if type is not None:
|
||||
return type
|
||||
|
||||
return tornado.web.StaticFileHandler.get_content_type(self)
|
||||
|
||||
@classmethod
|
||||
def get_content_version(cls, abspath):
|
||||
import os
|
||||
@@ -794,7 +834,7 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
|
||||
##~~ URL Forward Handler for forwarding requests to a preconfigured static URL
|
||||
|
||||
|
||||
class UrlForwardHandler(tornado.web.RequestHandler):
|
||||
class UrlProxyHandler(tornado.web.RequestHandler):
|
||||
"""
|
||||
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that proxies
|
||||
requests to a preconfigured url and returns the response. Allows delivery of the requested content as attachment
|
||||
@@ -804,7 +844,7 @@ class UrlForwardHandler(tornado.web.RequestHandler):
|
||||
for making the request to the configured endpoint and return the body of the client response with the status code
|
||||
from the client response and the following headers:
|
||||
|
||||
* ``Date``, ``Cache-Control``, ``Server``, ``Content-Type`` and ``Location`` will be copied over.
|
||||
* ``Date``, ``Cache-Control``, ``Expires``, ``ETag``, ``Server``, ``Content-Type`` and ``Location`` will be copied over.
|
||||
* If ``as_attachment`` is set to True, ``Content-Disposition`` will be set to ``attachment``. If ``basename`` is
|
||||
set including the attachement's ``filename`` attribute will be set to the base name followed by the extension
|
||||
guessed based on the MIME type from the ``Content-Type`` header of the response. If no extension can be guessed
|
||||
@@ -854,7 +894,7 @@ class UrlForwardHandler(tornado.web.RequestHandler):
|
||||
filename = None
|
||||
|
||||
self.set_status(response.code)
|
||||
for name in ("Date", "Cache-Control", "Server", "Content-Type", "Location"):
|
||||
for name in ("Date", "Cache-Control", "Server", "Content-Type", "Location", "Expires", "ETag"):
|
||||
value = response.headers.get(name)
|
||||
if value:
|
||||
self.set_header(name, value)
|
||||
@@ -887,6 +927,19 @@ class UrlForwardHandler(tornado.web.RequestHandler):
|
||||
return "%s%s" % (self._basename, extension)
|
||||
|
||||
|
||||
class StaticDataHandler(tornado.web.RequestHandler):
|
||||
def initialize(self, data="", content_type="text/plain"):
|
||||
self.data = data
|
||||
self.content_type = content_type
|
||||
|
||||
def get(self, *args, **kwargs):
|
||||
self.set_status(200)
|
||||
self.set_header("Content-Type", self.content_type)
|
||||
self.write(self.data)
|
||||
self.flush()
|
||||
self.finish()
|
||||
|
||||
|
||||
#~~ Factory method for creating Flask access validation wrappers from the Tornado request context
|
||||
|
||||
|
||||
@@ -924,4 +977,4 @@ def path_validation_factory(path_filter, status_code=404):
|
||||
def f(path):
|
||||
if not path_filter(path):
|
||||
raise tornado.web.HTTPError(status_code)
|
||||
return f
|
||||
return f
|
||||
@@ -6,6 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
import os
|
||||
import watchdog.events
|
||||
|
||||
import octoprint.filemanager
|
||||
@@ -14,6 +15,7 @@ import octoprint.util
|
||||
|
||||
|
||||
class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
|
||||
"""
|
||||
Takes care of automatically "uploading" files that get added to the watched folder.
|
||||
"""
|
||||
@@ -27,40 +29,42 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
|
||||
self._printer = printer
|
||||
|
||||
def _upload(self, path):
|
||||
import os
|
||||
file_wrapper = octoprint.filemanager.util.DiskFileWrapper(os.path.basename(path), path)
|
||||
|
||||
# determine current job
|
||||
currentFilename = None
|
||||
currentOrigin = None
|
||||
currentJob = self._printer.get_current_job()
|
||||
if currentJob is not None and "file" in currentJob.keys():
|
||||
currentJobFile = currentJob["file"]
|
||||
if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys():
|
||||
currentFilename = currentJobFile["name"]
|
||||
currentOrigin = currentJobFile["origin"]
|
||||
|
||||
# determine future filename of file to be uploaded, abort if it can't be uploaded
|
||||
try:
|
||||
futureFilename = self._file_manager.sanitize_name(octoprint.filemanager.FileDestinations.LOCAL, file_wrapper.filename)
|
||||
except:
|
||||
futureFilename = None
|
||||
if futureFilename is None or (len(self._file_manager.registered_slicers) == 0 and not octoprint.filemanager.valid_file_type(futureFilename)):
|
||||
return
|
||||
file_wrapper = octoprint.filemanager.util.DiskFileWrapper(os.path.basename(path), path)
|
||||
|
||||
# prohibit overwriting currently selected file while it's being printed
|
||||
if futureFilename == currentFilename and currentOrigin == octoprint.filemanager.FileDestinations.LOCAL and self._printer.is_printing() or self._printer.is_paused():
|
||||
return
|
||||
# determine current job
|
||||
currentFilename = None
|
||||
currentOrigin = None
|
||||
currentJob = self._printer.get_current_job()
|
||||
if currentJob is not None and "file" in currentJob.keys():
|
||||
currentJobFile = currentJob["file"]
|
||||
if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys():
|
||||
currentFilename = currentJobFile["name"]
|
||||
currentOrigin = currentJobFile["origin"]
|
||||
|
||||
self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL,
|
||||
file_wrapper.filename,
|
||||
file_wrapper,
|
||||
allow_overwrite=True)
|
||||
if os.path.exists(path):
|
||||
# determine future filename of file to be uploaded, abort if it can't be uploaded
|
||||
try:
|
||||
os.remove(path)
|
||||
futureFilename = self._file_manager.sanitize_name(octoprint.filemanager.FileDestinations.LOCAL, file_wrapper.filename)
|
||||
except:
|
||||
self._logger.exception("Error while trying to clear a file from the watched folder")
|
||||
futureFilename = None
|
||||
if futureFilename is None or (len(self._file_manager.registered_slicers) == 0 and not octoprint.filemanager.valid_file_type(futureFilename)):
|
||||
return
|
||||
|
||||
# prohibit overwriting currently selected file while it's being printed
|
||||
if futureFilename == currentFilename and currentOrigin == octoprint.filemanager.FileDestinations.LOCAL and self._printer.is_printing() or self._printer.is_paused():
|
||||
return
|
||||
|
||||
self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL,
|
||||
file_wrapper.filename,
|
||||
file_wrapper,
|
||||
allow_overwrite=True)
|
||||
if os.path.exists(path):
|
||||
try:
|
||||
os.remove(path)
|
||||
except:
|
||||
self._logger.exception("Error while trying to clear a file from the watched folder")
|
||||
except:
|
||||
self._logger.exception("There was an error while processing the file {} in the watched folder".format(path))
|
||||
|
||||
def on_created(self, event):
|
||||
self._upload(event.src_path)
|
||||
+271
-78
@@ -12,24 +12,40 @@ from flask import request, g, url_for, make_response, render_template, send_from
|
||||
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.server import app, userManager, pluginManager, gettext, debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY
|
||||
from octoprint.server import app, userManager, pluginManager, gettext, \
|
||||
debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY, BRANCH, preemptiveCache, \
|
||||
NOT_MODIFIED
|
||||
from octoprint.settings import settings
|
||||
from octoprint.filemanager import get_all_extensions
|
||||
|
||||
import re
|
||||
|
||||
from . import util
|
||||
|
||||
import logging
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
@app.route("/")
|
||||
@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values, key=lambda: "view/%s/%s" % (request.path, g.locale))
|
||||
def index():
|
||||
_valid_id_re = re.compile("[a-z_]+")
|
||||
_valid_div_re = re.compile("[a-zA-Z_-]+")
|
||||
|
||||
@app.route("/")
|
||||
@util.flask.preemptively_cached(cache=preemptiveCache,
|
||||
data=lambda: dict(path=request.path, base_url=request.url_root, query_string="l10n={}".format(g.locale.language) if g.locale else "en"),
|
||||
unless=lambda: request.url_root in settings().get(["server", "preemptiveCache", "exceptions"]))
|
||||
@util.flask.conditional(lambda: _check_etag_and_lastmodified_for_index(), NOT_MODIFIED)
|
||||
@util.flask.cached(timeout=-1,
|
||||
refreshif=lambda cached: _validate_cache_for_index(cached),
|
||||
key=lambda: "view:{}:{}".format(request.base_url, g.locale.language if g.locale else "en"),
|
||||
unless_response=lambda response: util.flask.cache_check_response_headers(response))
|
||||
@util.flask.etagged(lambda _: _compute_etag_for_index())
|
||||
@util.flask.lastmodified(lambda _: _compute_date_for_index())
|
||||
def index():
|
||||
#~~ a bunch of settings
|
||||
|
||||
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
|
||||
enable_timelapse = (settings().get(["webcam", "snapshot"]) and settings().get(["webcam", "ffmpeg"]))
|
||||
enable_systemmenu = settings().get(["system"]) is not None and settings().get(["system", "actions"]) is not None and len(settings().get(["system", "actions"])) > 0
|
||||
enable_accesscontrol = userManager is not None
|
||||
enable_systemmenu = settings().get(["system"]) is not None and settings().get(["system", "actions"]) is not None
|
||||
enable_accesscontrol = userManager.enabled
|
||||
preferred_stylesheet = settings().get(["devel", "stylesheet"])
|
||||
locales = dict((l.language, dict(language=l.language, display=l.display_name, english=l.english_name)) for l in LOCALES)
|
||||
|
||||
@@ -148,6 +164,7 @@ def index():
|
||||
folders=(gettext("Folders"), dict(template="dialogs/settings/folders.jinja2", _div="settings_folders", custom_bindings=False)),
|
||||
appearance=(gettext("Appearance"), dict(template="dialogs/settings/appearance.jinja2", _div="settings_appearance", custom_bindings=False)),
|
||||
logs=(gettext("Logs"), dict(template="dialogs/settings/logs.jinja2", _div="settings_logs")),
|
||||
server=(gettext("Server"), dict(template="dialogs/settings/server.jinja2", _div="settings_server", custom_bindings=False)),
|
||||
)
|
||||
if enable_accesscontrol:
|
||||
templates["settings"]["entries"]["accesscontrol"] = (gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False))
|
||||
@@ -170,17 +187,21 @@ def index():
|
||||
name = implementation._identifier
|
||||
plugin_names.add(name)
|
||||
|
||||
vars = implementation.get_template_vars()
|
||||
try:
|
||||
vars = implementation.get_template_vars()
|
||||
configs = implementation.get_template_configs()
|
||||
except:
|
||||
_logger.exception("Error while retrieving template data for plugin {}, ignoring it".format(name))
|
||||
continue
|
||||
|
||||
if not isinstance(vars, dict):
|
||||
vars = dict()
|
||||
if not isinstance(configs, (list, tuple)):
|
||||
configs = []
|
||||
|
||||
for var_name, var_value in vars.items():
|
||||
plugin_vars["plugin_" + name + "_" + var_name] = var_value
|
||||
|
||||
configs = implementation.get_template_configs()
|
||||
if not isinstance(configs, (list, tuple)):
|
||||
configs = []
|
||||
|
||||
includes = _process_template_configs(name, implementation, configs, template_rules)
|
||||
|
||||
for t in template_types:
|
||||
@@ -223,9 +244,30 @@ def index():
|
||||
# finally add anything that's not included in our order yet
|
||||
sorted_missing = list(missing_in_order)
|
||||
if template_sorting[t]["key"] is not None:
|
||||
# anything but navbar and generic components get sorted by their name
|
||||
if template_sorting[t]["key"] == "name":
|
||||
sorted_missing = sorted(missing_in_order, key=lambda x: templates[t]["entries"][x][0])
|
||||
# default extractor: works with entries that are dicts and entries that are 2-tuples with the
|
||||
# entry data at index 1
|
||||
def extractor(item, key):
|
||||
if isinstance(item, dict) and key in item:
|
||||
return item[key]
|
||||
elif isinstance(item, tuple) and len(item) > 1 and isinstance(item[1], dict) and key in item[1]:
|
||||
return item[1][key]
|
||||
|
||||
return None
|
||||
|
||||
# if template type provides custom extractor, make sure its exceptions are handled
|
||||
if "key_extractor" in template_sorting[t] and callable(template_sorting[t]["key_extractor"]):
|
||||
def create_safe_extractor(extractor):
|
||||
def f(x, k):
|
||||
try:
|
||||
return extractor(x, k)
|
||||
except:
|
||||
_logger.exception("Error while extracting sorting keys for template {}".format(t))
|
||||
return None
|
||||
return f
|
||||
extractor = create_safe_extractor(template_sorting[t]["key_extractor"])
|
||||
|
||||
sort_key = template_sorting[t]["key"]
|
||||
sorted_missing = sorted(missing_in_order, key=lambda x: extractor(templates[t]["entries"][x], sort_key))
|
||||
|
||||
if template_sorting[t]["add"] == "prepend":
|
||||
templates[t]["order"] = sorted_missing + templates[t]["order"]
|
||||
@@ -240,30 +282,38 @@ def index():
|
||||
|
||||
#~~ prepare full set of template vars for rendering
|
||||
|
||||
first_run = settings().getBoolean(["server", "firstRun"]) and userManager.enabled and not userManager.hasBeenCustomized()
|
||||
render_kwargs = dict(
|
||||
webcamStream=settings().get(["webcam", "stream"]),
|
||||
enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]),
|
||||
enableAccessControl=userManager is not None,
|
||||
enableAccessControl=userManager.enabled,
|
||||
enableSdSupport=settings().get(["feature", "sdSupport"]),
|
||||
firstRun=settings().getBoolean(["server", "firstRun"]) and (userManager is None or not userManager.hasBeenCustomized()),
|
||||
firstRun=first_run,
|
||||
debug=debug,
|
||||
version=VERSION,
|
||||
display_version=DISPLAY_VERSION,
|
||||
branch=BRANCH,
|
||||
gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]),
|
||||
gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"]),
|
||||
uiApiKey=UI_API_KEY,
|
||||
templates=templates,
|
||||
pluginNames=plugin_names,
|
||||
locales=locales
|
||||
locales=locales,
|
||||
supportedExtensions=map(lambda ext: ".{}".format(ext), get_all_extensions())
|
||||
)
|
||||
render_kwargs.update(plugin_vars)
|
||||
|
||||
#~~ render!
|
||||
|
||||
return render_template(
|
||||
response = make_response(render_template(
|
||||
"index.jinja2",
|
||||
**render_kwargs
|
||||
)
|
||||
))
|
||||
|
||||
if first_run:
|
||||
response = util.flask.add_non_caching_response_headers(response)
|
||||
|
||||
return response
|
||||
|
||||
|
||||
def _process_template_configs(name, implementation, configs, rules):
|
||||
@@ -302,11 +352,14 @@ def _process_template_configs(name, implementation, configs, rules):
|
||||
app.jinja_env.get_or_select_template(data["template"])
|
||||
except TemplateNotFound:
|
||||
pass
|
||||
except:
|
||||
_logger.exception("Error in template {}, not going to include it".format(data["template"]))
|
||||
else:
|
||||
includes[template_type].append(rule["to_entry"](data))
|
||||
|
||||
return includes
|
||||
|
||||
|
||||
def _process_template_config(name, implementation, rule, config=None, counter=1):
|
||||
if "mandatory" in rule:
|
||||
for mandatory in rule["mandatory"]:
|
||||
@@ -326,6 +379,9 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
|
||||
data["_div"] = rule["div"](name)
|
||||
if "suffix" in data:
|
||||
data["_div"] = data["_div"] + data["suffix"]
|
||||
if not _valid_div_re.match(data["_div"]):
|
||||
_logger.warn("Template config {} contains invalid div identifier {}, skipping it".format(name, data["_div"]))
|
||||
return None
|
||||
|
||||
if not "template" in data:
|
||||
data["template"] = rule["template"](name)
|
||||
@@ -337,6 +393,7 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
|
||||
data_bind = "allowBindings: true"
|
||||
if "data_bind" in data:
|
||||
data_bind = data_bind + ", " + data["data_bind"]
|
||||
data_bind = data_bind.replace("\"", "\\\"")
|
||||
data["data_bind"] = data_bind
|
||||
|
||||
data["_key"] = "plugin_" + name
|
||||
@@ -345,76 +402,23 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
|
||||
|
||||
return data
|
||||
|
||||
|
||||
@app.route("/robots.txt")
|
||||
@util.flask.cached(timeout=-1)
|
||||
def robotsTxt():
|
||||
return send_from_directory(app.static_folder, "robots.txt")
|
||||
|
||||
|
||||
@app.route("/i18n/<string:locale>/<string:domain>.js")
|
||||
@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values, key=lambda: "view/%s/%s" % (request.path, g.locale))
|
||||
@util.flask.conditional(lambda: _check_etag_and_lastmodified_for_i18n(), NOT_MODIFIED)
|
||||
@util.flask.etagged(lambda _: _compute_etag_for_i18n(request.view_args["locale"], request.view_args["domain"]))
|
||||
@util.flask.lastmodified(lambda _: _compute_date_for_i18n(request.view_args["locale"], request.view_args["domain"]))
|
||||
def localeJs(locale, domain):
|
||||
messages = dict()
|
||||
plural_expr = None
|
||||
|
||||
if locale != "en":
|
||||
from flask import _request_ctx_stack
|
||||
from babel.messages.pofile import read_po
|
||||
|
||||
def messages_from_po(base_path, locale, domain):
|
||||
path = os.path.join(base_path, locale)
|
||||
if not os.path.isdir(path):
|
||||
return None, None
|
||||
|
||||
path = os.path.join(path, "LC_MESSAGES", "{domain}.po".format(**locals()))
|
||||
if not os.path.isfile(path):
|
||||
return None, None
|
||||
|
||||
messages = dict()
|
||||
with file(path) as f:
|
||||
catalog = read_po(f, locale=locale, domain=domain)
|
||||
|
||||
for message in catalog:
|
||||
message_id = message.id
|
||||
if isinstance(message_id, (list, tuple)):
|
||||
message_id = message_id[0]
|
||||
messages[message_id] = message.string
|
||||
|
||||
return messages, catalog.plural_expr
|
||||
|
||||
user_base_path = os.path.join(settings().getBaseFolder("translations"))
|
||||
user_plugin_path = os.path.join(user_base_path, "_plugins")
|
||||
|
||||
# plugin translations
|
||||
plugins = octoprint.plugin.plugin_manager().enabled_plugins
|
||||
for name, plugin in plugins.items():
|
||||
dirs = [os.path.join(user_plugin_path, name), os.path.join(plugin.location, 'translations')]
|
||||
for dirname in dirs:
|
||||
if not os.path.isdir(dirname):
|
||||
continue
|
||||
|
||||
plugin_messages, _ = messages_from_po(dirname, locale, domain)
|
||||
|
||||
if plugin_messages is not None:
|
||||
messages = octoprint.util.dict_merge(messages, plugin_messages)
|
||||
_logger.debug("Using translation folder {dirname} for locale {locale} of plugin {name}".format(**locals()))
|
||||
break
|
||||
else:
|
||||
_logger.debug("No translations for locale {locale} for plugin {name}".format(**locals()))
|
||||
|
||||
# core translations
|
||||
ctx = _request_ctx_stack.top
|
||||
base_path = os.path.join(ctx.app.root_path, "translations")
|
||||
|
||||
dirs = [user_base_path, base_path]
|
||||
for dirname in dirs:
|
||||
core_messages, plural_expr = messages_from_po(dirname, locale, domain)
|
||||
|
||||
if core_messages is not None:
|
||||
messages = octoprint.util.dict_merge(messages, core_messages)
|
||||
_logger.debug("Using translation folder {dirname} for locale {locale} of core translations".format(**locals()))
|
||||
break
|
||||
else:
|
||||
_logger.debug("No core translations for locale {locale}".format(**locals()))
|
||||
messages, plural_expr = _get_translations(locale, domain)
|
||||
|
||||
catalog = dict(
|
||||
messages=messages,
|
||||
@@ -432,3 +436,192 @@ def plugin_assets(name, filename):
|
||||
return redirect(url_for("plugin." + name + ".static", filename=filename))
|
||||
|
||||
|
||||
def _compute_etag_for_index(files=None, lastmodified=None):
|
||||
if files is None:
|
||||
files = _files_for_index()
|
||||
if lastmodified is None:
|
||||
lastmodified = _compute_date(files)
|
||||
if lastmodified and not isinstance(lastmodified, basestring):
|
||||
from werkzeug.http import http_date
|
||||
lastmodified = http_date(lastmodified)
|
||||
|
||||
from octoprint import __version__
|
||||
from octoprint.server import UI_API_KEY
|
||||
|
||||
import hashlib
|
||||
hash = hashlib.sha1()
|
||||
hash.update(__version__)
|
||||
hash.update(UI_API_KEY)
|
||||
hash.update(",".join(sorted(files)))
|
||||
if lastmodified:
|
||||
hash.update(lastmodified)
|
||||
return hash.hexdigest()
|
||||
|
||||
|
||||
def _compute_etag_for_i18n(locale, domain, files=None, lastmodified=None):
|
||||
if files is None:
|
||||
files = _get_all_translationfiles(locale, domain)
|
||||
if lastmodified is None:
|
||||
lastmodified = _compute_date(files)
|
||||
if lastmodified and not isinstance(lastmodified, basestring):
|
||||
from werkzeug.http import http_date
|
||||
lastmodified = http_date(lastmodified)
|
||||
|
||||
import hashlib
|
||||
hash = hashlib.sha1()
|
||||
hash.update(",".join(sorted(files)))
|
||||
if lastmodified:
|
||||
hash.update(lastmodified)
|
||||
return hash.hexdigest()
|
||||
|
||||
|
||||
def _compute_date_for_i18n(locale, domain):
|
||||
return _compute_date(_get_all_translationfiles(locale, domain))
|
||||
|
||||
|
||||
def _compute_date_for_index():
|
||||
return _compute_date(_files_for_index())
|
||||
|
||||
|
||||
def _validate_cache_for_index(cached):
|
||||
no_cache_headers = util.flask.cache_check_headers()
|
||||
refresh_flag = "_refresh" in request.values
|
||||
etag_different = _compute_etag_for_index() != cached.get_etag()[0]
|
||||
|
||||
return no_cache_headers or refresh_flag or etag_different
|
||||
|
||||
|
||||
def _files_for_index():
|
||||
"""
|
||||
Collects all paths of files that the index page depends on.
|
||||
|
||||
The relevant files are:
|
||||
|
||||
* all jinja2 templates: they might be used within the index page, so
|
||||
any changes here change the rendering outcome
|
||||
* all defined assets: if one of them changes, the webassets bundle will
|
||||
be regenerated and hence the URL included in the cached page won't be
|
||||
valid anymore
|
||||
* all translation files used for our current locale: if any of those change
|
||||
we also need to re-render
|
||||
"""
|
||||
|
||||
templates = _get_all_templates()
|
||||
assets = _get_all_assets()
|
||||
translations = _get_all_translationfiles(g.locale.language if g.locale else "en", "messages")
|
||||
return sorted(set(templates + assets + translations))
|
||||
|
||||
|
||||
def _compute_date(files):
|
||||
from datetime import datetime
|
||||
timestamps = map(lambda path: os.stat(path).st_mtime, files)
|
||||
max_timestamp = max(*timestamps) if timestamps else None
|
||||
if max_timestamp:
|
||||
# we set the micros to 0 since microseconds are not speced for HTTP
|
||||
max_timestamp = datetime.fromtimestamp(max_timestamp).replace(microsecond=0)
|
||||
return max_timestamp
|
||||
|
||||
|
||||
def _check_etag_and_lastmodified_for_index():
|
||||
files = _files_for_index()
|
||||
lastmodified = _compute_date(files)
|
||||
lastmodified_ok = util.flask.check_lastmodified(lastmodified)
|
||||
etag_ok = util.flask.check_etag(_compute_etag_for_index(files, lastmodified))
|
||||
return etag_ok and lastmodified_ok
|
||||
|
||||
|
||||
def _check_etag_and_lastmodified_for_i18n():
|
||||
locale = request.view_args["locale"]
|
||||
domain = request.view_args["domain"]
|
||||
|
||||
etag_ok = util.flask.check_etag(_compute_etag_for_i18n(request.view_args["locale"], request.view_args["domain"]))
|
||||
|
||||
lastmodified = _compute_date_for_i18n(locale, domain)
|
||||
lastmodified_ok = lastmodified is None or util.flask.check_lastmodified(lastmodified)
|
||||
|
||||
return etag_ok and lastmodified_ok
|
||||
|
||||
|
||||
def _get_all_templates():
|
||||
from octoprint.util.jinja import get_all_template_paths
|
||||
return get_all_template_paths(app.jinja_loader)
|
||||
|
||||
|
||||
def _get_all_assets():
|
||||
from octoprint.util.jinja import get_all_asset_paths
|
||||
return get_all_asset_paths(app.jinja_env.assets_environment)
|
||||
|
||||
|
||||
def _get_all_translationfiles(locale, domain):
|
||||
from flask import _request_ctx_stack
|
||||
|
||||
def get_po_path(basedir, locale, domain):
|
||||
path = os.path.join(basedir, locale)
|
||||
if not os.path.isdir(path):
|
||||
return None
|
||||
|
||||
path = os.path.join(path, "LC_MESSAGES", "{domain}.po".format(**locals()))
|
||||
if not os.path.isfile(path):
|
||||
return None
|
||||
|
||||
return path
|
||||
|
||||
po_files = []
|
||||
|
||||
user_base_path = os.path.join(settings().getBaseFolder("translations"))
|
||||
user_plugin_path = os.path.join(user_base_path, "_plugins")
|
||||
|
||||
# plugin translations
|
||||
plugins = octoprint.plugin.plugin_manager().enabled_plugins
|
||||
for name, plugin in plugins.items():
|
||||
dirs = [os.path.join(user_plugin_path, name), os.path.join(plugin.location, 'translations')]
|
||||
for dirname in dirs:
|
||||
if not os.path.isdir(dirname):
|
||||
continue
|
||||
|
||||
po_file = get_po_path(dirname, locale, domain)
|
||||
if po_file:
|
||||
po_files.append(po_file)
|
||||
break
|
||||
|
||||
# core translations
|
||||
ctx = _request_ctx_stack.top
|
||||
base_path = os.path.join(ctx.app.root_path, "translations")
|
||||
|
||||
dirs = [user_base_path, base_path]
|
||||
for dirname in dirs:
|
||||
po_file = get_po_path(dirname, locale, domain)
|
||||
if po_file:
|
||||
po_files.append(po_file)
|
||||
break
|
||||
|
||||
return po_files
|
||||
|
||||
|
||||
def _get_translations(locale, domain):
|
||||
from babel.messages.pofile import read_po
|
||||
from octoprint.util import dict_merge
|
||||
|
||||
messages = dict()
|
||||
plural_expr = None
|
||||
|
||||
def messages_from_po(path, locale, domain):
|
||||
messages = dict()
|
||||
with file(path) as f:
|
||||
catalog = read_po(f, locale=locale, domain=domain)
|
||||
|
||||
for message in catalog:
|
||||
message_id = message.id
|
||||
if isinstance(message_id, (list, tuple)):
|
||||
message_id = message_id[0]
|
||||
messages[message_id] = message.string
|
||||
|
||||
return messages, catalog.plural_expr
|
||||
|
||||
po_files = _get_all_translationfiles(locale, domain)
|
||||
for po_file in po_files:
|
||||
po_messages, plural_expr = messages_from_po(po_file, locale, domain)
|
||||
if po_messages is not None:
|
||||
messages = dict_merge(messages, po_messages)
|
||||
|
||||
return messages, plural_expr
|
||||
+135
-43
@@ -30,6 +30,8 @@ import logging
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from octoprint.util import atomic_write, is_hidden_path
|
||||
|
||||
_APPNAME = "OctoPrint"
|
||||
|
||||
_instance = None
|
||||
@@ -83,7 +85,15 @@ default_settings = {
|
||||
"sdStatus": 1
|
||||
},
|
||||
"additionalPorts": [],
|
||||
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32"]
|
||||
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226"],
|
||||
"checksumRequiringCommands": ["M110"],
|
||||
"helloCommand": "M110 N0",
|
||||
"disconnectOnErrors": True,
|
||||
"ignoreErrorsFromFirmware": False,
|
||||
"logResends": False,
|
||||
|
||||
# command specific flags
|
||||
"triggerOkForM29": True
|
||||
},
|
||||
"server": {
|
||||
"host": "0.0.0.0",
|
||||
@@ -104,6 +114,19 @@ default_settings = {
|
||||
"pathSuffix": "path"
|
||||
},
|
||||
"maxSize": 100 * 1024, # 100 KB
|
||||
"commands": {
|
||||
"systemShutdownCommand": None,
|
||||
"systemRestartCommand": None,
|
||||
"serverRestartCommand": None
|
||||
},
|
||||
"diskspace": {
|
||||
"warning": 500 * 1024 * 1024, # 500 MB
|
||||
"critical": 200 * 1024 * 1024, # 200 MB
|
||||
},
|
||||
"preemptiveCache": {
|
||||
"exceptions": [],
|
||||
"until": 7
|
||||
}
|
||||
},
|
||||
"webcam": {
|
||||
"stream": None,
|
||||
@@ -120,7 +143,8 @@ default_settings = {
|
||||
"options": {},
|
||||
"postRoll": 0,
|
||||
"fps": 25
|
||||
}
|
||||
},
|
||||
"cleanTmpAfterDays": 7
|
||||
},
|
||||
"gcodeViewer": {
|
||||
"enabled": True,
|
||||
@@ -143,7 +167,9 @@ default_settings = {
|
||||
"externalHeatupDetection": True,
|
||||
"supportWait": True,
|
||||
"keyboardControl": True,
|
||||
"pollWatched": False
|
||||
"pollWatched": False,
|
||||
"ignoreIdenticalResends": False,
|
||||
"identicalResendsCountdown": 7
|
||||
},
|
||||
"folder": {
|
||||
"uploads": None,
|
||||
@@ -188,7 +214,7 @@ default_settings = {
|
||||
"settings": [
|
||||
"section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts",
|
||||
"section_features", "features", "webcam", "accesscontrol", "api",
|
||||
"section_octoprint", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate"
|
||||
"section_octoprint", "server", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate"
|
||||
],
|
||||
"usersettings": ["access", "interface"],
|
||||
"generic": []
|
||||
@@ -240,16 +266,18 @@ default_settings = {
|
||||
},
|
||||
"scripts": {
|
||||
"gcode": {
|
||||
"afterPrintCancelled": "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\nM140 S0\n\n;disable fan\nM106 S0",
|
||||
"afterPrintCancelled": "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\n{% snippet 'disable_bed' %}\n;disable fan\nM106 S0",
|
||||
"snippets": {
|
||||
"disable_hotends": "{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}"
|
||||
"disable_hotends": "{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}",
|
||||
"disable_bed": "{% if printer_profile.heatedBed %}M140 S0\n{% endif %}"
|
||||
}
|
||||
}
|
||||
},
|
||||
"devel": {
|
||||
"stylesheet": "css",
|
||||
"cache": {
|
||||
"enabled": True
|
||||
"enabled": True,
|
||||
"preemptive": True
|
||||
},
|
||||
"webassets": {
|
||||
"minify": False,
|
||||
@@ -271,6 +299,7 @@ default_settings = {
|
||||
},
|
||||
"hasBed": True,
|
||||
"repetierStyleTargetTemperature": False,
|
||||
"repetierStyleResends": False,
|
||||
"okBeforeCommandOutput": False,
|
||||
"smoothieTemperatureReporting": False,
|
||||
"extendedSdFileList": False,
|
||||
@@ -280,7 +309,10 @@ default_settings = {
|
||||
"txBuffer": 40,
|
||||
"commandBuffer": 4,
|
||||
"sendWait": True,
|
||||
"waitInterval": 1.0
|
||||
"waitInterval": 1.0,
|
||||
"supportM112": True,
|
||||
"echoOnM117": True,
|
||||
"brokenM29": True
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -289,6 +321,11 @@ default_settings = {
|
||||
valid_boolean_trues = [True, "true", "yes", "y", "1"]
|
||||
""" Values that are considered to be equivalent to the boolean ``True`` value, used for type conversion in various places."""
|
||||
|
||||
|
||||
class NoSuchSettingsPath(BaseException):
|
||||
pass
|
||||
|
||||
|
||||
class Settings(object):
|
||||
"""
|
||||
The :class:`Settings` class allows managing all of OctoPrint's settings. It takes care of initializing the settings
|
||||
@@ -321,14 +358,14 @@ class Settings(object):
|
||||
|
||||
"/dev/ttyACM0"
|
||||
|
||||
``["serial", "timeouts"]`` ::
|
||||
``["serial", "timeout"]`` ::
|
||||
|
||||
communication: 20.0
|
||||
temperature: 5.0
|
||||
sdStatus: 1.0
|
||||
connection: 10.0
|
||||
|
||||
``["serial", "timeouts", "temperature"]`` ::
|
||||
``["serial", "timeout", "temperature"]`` ::
|
||||
|
||||
5.0
|
||||
|
||||
@@ -385,10 +422,12 @@ class Settings(object):
|
||||
return folder
|
||||
|
||||
def _init_script_templating(self):
|
||||
from jinja2 import Environment, BaseLoader, FileSystemLoader, ChoiceLoader, TemplateNotFound
|
||||
from jinja2.nodes import Include, Const
|
||||
from jinja2 import Environment, BaseLoader, ChoiceLoader, TemplateNotFound
|
||||
from jinja2.nodes import Include
|
||||
from jinja2.ext import Extension
|
||||
|
||||
from octoprint.util.jinja import FilteredFileSystemLoader
|
||||
|
||||
class SnippetExtension(Extension):
|
||||
tags = {"snippet"}
|
||||
fields = Include.fields
|
||||
@@ -477,10 +516,14 @@ class Settings(object):
|
||||
else:
|
||||
return template
|
||||
|
||||
file_system_loader = FileSystemLoader(self.getBaseFolder("scripts"))
|
||||
path_filter = lambda path: not is_hidden_path(path)
|
||||
file_system_loader = FilteredFileSystemLoader(self.getBaseFolder("scripts"),
|
||||
path_filter=path_filter)
|
||||
settings_loader = SettingsScriptLoader(self)
|
||||
choice_loader = ChoiceLoader([file_system_loader, settings_loader])
|
||||
select_loader = SelectLoader(choice_loader, dict(bundled=settings_loader, file=file_system_loader))
|
||||
select_loader = SelectLoader(choice_loader,
|
||||
dict(bundled=settings_loader,
|
||||
file=file_system_loader))
|
||||
return RelEnvironment(loader=select_loader, extensions=[SnippetExtension])
|
||||
|
||||
def _get_script_template(self, script_type, name, source=False):
|
||||
@@ -774,11 +817,17 @@ class Settings(object):
|
||||
if not self._dirty and not force:
|
||||
return False
|
||||
|
||||
with open(self._configfile, "wb") as configFile:
|
||||
yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
self._dirty = False
|
||||
self.load()
|
||||
return True
|
||||
from octoprint.util import atomic_write
|
||||
try:
|
||||
with atomic_write(self._configfile, "wb", prefix="octoprint-config-", suffix=".yaml") as configFile:
|
||||
yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
self._dirty = False
|
||||
except:
|
||||
self._logger.exception("Error while saving config.yaml!")
|
||||
raise
|
||||
else:
|
||||
self.load()
|
||||
return True
|
||||
|
||||
@property
|
||||
def last_modified(self):
|
||||
@@ -789,13 +838,13 @@ class Settings(object):
|
||||
stat = os.stat(self._configfile)
|
||||
return stat.st_mtime
|
||||
|
||||
#~~ getter
|
||||
##~~ Internal getter
|
||||
|
||||
def get(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True):
|
||||
def _get_value(self, path, asdict=False, config=None, defaults=None, preprocessors=None, merged=False, incl_defaults=True):
|
||||
import octoprint.util as util
|
||||
|
||||
if len(path) == 0:
|
||||
return None
|
||||
raise NoSuchSettingsPath()
|
||||
|
||||
if config is None:
|
||||
config = self._config
|
||||
@@ -813,7 +862,7 @@ class Settings(object):
|
||||
config = {}
|
||||
defaults = defaults[key]
|
||||
else:
|
||||
return None
|
||||
raise NoSuchSettingsPath()
|
||||
|
||||
if preprocessors and isinstance(preprocessors, dict) and key in preprocessors:
|
||||
preprocessors = preprocessors[key]
|
||||
@@ -837,7 +886,7 @@ class Settings(object):
|
||||
elif incl_defaults and key in defaults:
|
||||
value = defaults[key]
|
||||
else:
|
||||
value = None
|
||||
raise NoSuchSettingsPath()
|
||||
|
||||
if preprocessors and isinstance(preprocessors, dict) and key in preprocessors and callable(preprocessors[key]):
|
||||
value = preprocessors[key](value)
|
||||
@@ -855,8 +904,34 @@ class Settings(object):
|
||||
else:
|
||||
return results
|
||||
|
||||
def getInt(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True):
|
||||
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults)
|
||||
#~~ has
|
||||
|
||||
def has(self, path, **kwargs):
|
||||
try:
|
||||
self._get_value(path, **kwargs)
|
||||
except NoSuchSettingsPath:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
#~~ getter
|
||||
|
||||
def get(self, path, **kwargs):
|
||||
error_on_path = kwargs.get("error_on_path", False)
|
||||
new_kwargs = dict(kwargs)
|
||||
if "error_on_path" in new_kwargs:
|
||||
del new_kwargs["error_on_path"]
|
||||
|
||||
try:
|
||||
return self._get_value(path, **new_kwargs)
|
||||
except NoSuchSettingsPath:
|
||||
if error_on_path:
|
||||
raise
|
||||
else:
|
||||
return None
|
||||
|
||||
def getInt(self, path, **kwargs):
|
||||
value = self.get(path, **kwargs)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
@@ -866,8 +941,8 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
|
||||
return None
|
||||
|
||||
def getFloat(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True):
|
||||
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults)
|
||||
def getFloat(self, path, **kwargs):
|
||||
value = self.get(path, **kwargs)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
@@ -877,8 +952,8 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
|
||||
return None
|
||||
|
||||
def getBoolean(self, path, config=None, defaults=None, preprocessors=None, incl_defaults=True):
|
||||
value = self.get(path, config=config, defaults=defaults, preprocessors=preprocessors, incl_defaults=incl_defaults)
|
||||
def getBoolean(self, path, **kwargs):
|
||||
value = self.get(path, **kwargs)
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool):
|
||||
@@ -931,6 +1006,23 @@ class Settings(object):
|
||||
|
||||
return script
|
||||
|
||||
#~~ remove
|
||||
|
||||
def remove(self, path, config=None):
|
||||
if config is None:
|
||||
config = self._config
|
||||
|
||||
while len(path) > 1:
|
||||
key = path.pop(0)
|
||||
if not isinstance(config, dict) or key not in config:
|
||||
return
|
||||
config = config[key]
|
||||
|
||||
key = path.pop(0)
|
||||
if isinstance(config, dict) and key in config:
|
||||
del config[key]
|
||||
self._dirty = True
|
||||
|
||||
#~~ setter
|
||||
|
||||
def set(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
|
||||
@@ -970,16 +1062,16 @@ class Settings(object):
|
||||
if not force and key in defaults and key in config and defaults[key] == value:
|
||||
del config[key]
|
||||
self._dirty = True
|
||||
elif force or (not key in config and defaults[key] != value) or (key in config and config[key] != value):
|
||||
elif force or (not key in config and key in defaults and defaults[key] != value) or (key in config and config[key] != value):
|
||||
if value is None and key in config:
|
||||
del config[key]
|
||||
else:
|
||||
config[key] = value
|
||||
self._dirty = True
|
||||
|
||||
def setInt(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
|
||||
def setInt(self, path, value, **kwargs):
|
||||
if value is None:
|
||||
self.set(path, None, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, None, **kwargs)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -988,11 +1080,11 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
|
||||
return
|
||||
|
||||
self.set(path, intValue, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, intValue, **kwargs)
|
||||
|
||||
def setFloat(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
|
||||
def setFloat(self, path, value, **kwargs):
|
||||
if value is None:
|
||||
self.set(path, None, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, None, **kwargs)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -1001,15 +1093,15 @@ class Settings(object):
|
||||
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
|
||||
return
|
||||
|
||||
self.set(path, floatValue, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, floatValue, **kwargs)
|
||||
|
||||
def setBoolean(self, path, value, force=False, defaults=None, config=None, preprocessors=None):
|
||||
def setBoolean(self, path, value, **kwargs):
|
||||
if value is None or isinstance(value, bool):
|
||||
self.set(path, value, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, value, **kwargs)
|
||||
elif value.lower() in valid_boolean_trues:
|
||||
self.set(path, True, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, True, **kwargs)
|
||||
else:
|
||||
self.set(path, False, config=config, force=force, defaults=defaults, preprocessors=preprocessors)
|
||||
self.set(path, False, **kwargs)
|
||||
|
||||
def setBaseFolder(self, type, path, force=False):
|
||||
if type not in default_settings["folder"].keys():
|
||||
@@ -1031,14 +1123,14 @@ class Settings(object):
|
||||
def saveScript(self, script_type, name, script):
|
||||
script_folder = self.getBaseFolder("scripts")
|
||||
filename = os.path.realpath(os.path.join(script_folder, script_type, name))
|
||||
if not filename.startswith(script_folder):
|
||||
if not filename.startswith(os.path.realpath(script_folder)):
|
||||
# oops, jail break, that shouldn't happen
|
||||
raise ValueError("Invalid script path to save to: {filename} (from {script_type}:{name})".format(**locals()))
|
||||
|
||||
path, _ = os.path.split(filename)
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
with open(filename, "w+") as f:
|
||||
with atomic_write(filename, "wb") as f:
|
||||
f.write(script)
|
||||
|
||||
def _default_basedir(applicationName):
|
||||
|
||||
@@ -22,8 +22,11 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import os
|
||||
import octoprint.plugin
|
||||
import octoprint.events
|
||||
import octoprint.util
|
||||
from octoprint.settings import settings
|
||||
|
||||
import logging
|
||||
|
||||
from .exceptions import *
|
||||
|
||||
|
||||
@@ -102,6 +105,8 @@ class SlicingManager(object):
|
||||
"""
|
||||
|
||||
def __init__(self, profile_path, printer_profile_manager):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
self._profile_path = profile_path
|
||||
self._printer_profile_manager = printer_profile_manager
|
||||
|
||||
@@ -123,7 +128,11 @@ class SlicingManager(object):
|
||||
plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin)
|
||||
slicers = dict()
|
||||
for plugin in plugins:
|
||||
slicers[plugin.get_slicer_properties()["type"]] = plugin
|
||||
try:
|
||||
slicers[plugin.get_slicer_properties()["type"]] = plugin
|
||||
except:
|
||||
self._logger.exception("Error while getting properties from slicer {}, ignoring it".format(plugin._identifier))
|
||||
continue
|
||||
self._slicers = slicers
|
||||
|
||||
@property
|
||||
@@ -470,7 +479,7 @@ class SlicingManager(object):
|
||||
profiles = dict()
|
||||
slicer_profile_path = self.get_slicer_profile_path(slicer)
|
||||
for entry in os.listdir(slicer_profile_path):
|
||||
if not entry.endswith(".profile") or entry.startswith("."):
|
||||
if not entry.endswith(".profile") or octoprint.util.is_hidden_path(entry):
|
||||
# we are only interested in profiles and no hidden files
|
||||
continue
|
||||
|
||||
@@ -531,7 +540,7 @@ class SlicingManager(object):
|
||||
name = self._sanitize(name)
|
||||
|
||||
path = os.path.join(self.get_slicer_profile_path(slicer), "{name}.profile".format(name=name))
|
||||
if not os.path.realpath(path).startswith(self._profile_path):
|
||||
if not os.path.realpath(path).startswith(os.path.realpath(self._profile_path)):
|
||||
raise IOError("Path to profile {name} tried to break out of allows sub path".format(**locals()))
|
||||
if must_exist and not (os.path.exists(path) and os.path.isfile(path)):
|
||||
raise UnknownProfile(slicer, name)
|
||||
|
||||
@@ -1 +1 @@
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:aLine truncated
|
||||
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
|
||||
@@ -379,7 +379,7 @@ GCODE.renderer = (function(){
|
||||
};
|
||||
|
||||
var drawLayer = function(layerNum, fromProgress, toProgress, isNotCurrentLayer){
|
||||
console.log("Drawing layer " + layerNum + " from " + fromProgress + " to " + toProgress + " (current: " + !isNotCurrentLayer + ")");
|
||||
log.trace("Drawing layer " + layerNum + " from " + fromProgress + " to " + toProgress + " (current: " + !isNotCurrentLayer + ")");
|
||||
|
||||
var i;
|
||||
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>OctoPrint is still starting</title>
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
|
||||
font-size: 14px;
|
||||
line-height: 20px;
|
||||
color: #333333;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
|
||||
#startup-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 10000;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.background {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.wrapper {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
}
|
||||
|
||||
.wrapper .outer {
|
||||
display: table;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.wrapper .outer .inner {
|
||||
display: table-cell;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.wrapper .outer .inner .content {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.green {
|
||||
color: #169300;
|
||||
}
|
||||
|
||||
.red {
|
||||
color: #990000;
|
||||
}
|
||||
|
||||
.pulsate3 {
|
||||
-webkit-animation: pulsate 3s ease-out;
|
||||
-webkit-animation-iteration-count: infinite;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.pulsate1 {
|
||||
-webkit-animation: pulsate 1s ease-out;
|
||||
-webkit-animation-iteration-count: infinite;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
@-webkit-keyframes pulsate {
|
||||
0% {
|
||||
opacity: 0.5;
|
||||
}
|
||||
50% {
|
||||
opacity: 1.0;
|
||||
}
|
||||
100% {
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<script>
|
||||
if (!String.prototype.endsWith) {
|
||||
String.prototype.endsWith = function(searchString, position) {
|
||||
var subjectString = this.toString();
|
||||
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
|
||||
position = subjectString.length;
|
||||
}
|
||||
position -= searchString.length;
|
||||
var lastIndex = subjectString.indexOf(searchString, position);
|
||||
return lastIndex !== -1 && lastIndex === position;
|
||||
};
|
||||
}
|
||||
|
||||
function ping(url, timeout, callback) {
|
||||
var img = new Image();
|
||||
var calledBack = false;
|
||||
|
||||
var urlToUse = url;
|
||||
var postfix = "_=" + Date.now();
|
||||
if (url.indexOf("?") > -1) {
|
||||
urlToUse += "&" + postfix;
|
||||
} else {
|
||||
urlToUse += "?" + postfix;
|
||||
}
|
||||
|
||||
console.log("Pinging " + url);
|
||||
|
||||
img.onload = function() {
|
||||
callback("load");
|
||||
calledBack = true;
|
||||
};
|
||||
img.onerror = function() {
|
||||
if (!calledBack) {
|
||||
callback("error");
|
||||
calledBack = true;
|
||||
}
|
||||
};
|
||||
|
||||
img.src = urlToUse;
|
||||
setTimeout(function() {
|
||||
if (!calledBack) {
|
||||
callback("timeout");
|
||||
calledBack = true;
|
||||
}
|
||||
}, timeout);
|
||||
}
|
||||
|
||||
window.onload = function() {
|
||||
var intervals = [1, 1, 2, 3, 5, 8];
|
||||
var timeout = 1500;
|
||||
|
||||
var baseUrl = window.location.href;
|
||||
if (baseUrl.indexOf("#") > -1) {
|
||||
baseUrl = baseUrl.substring(0, baseUrl.indexOf("#"));
|
||||
}
|
||||
if (baseUrl.indexOf("/static") > -1) {
|
||||
baseUrl = baseUrl.substring(0, baseUrl.indexOf("/static"));
|
||||
}
|
||||
if (baseUrl[baseUrl.length - 1] != "/") {
|
||||
baseUrl += "/";
|
||||
}
|
||||
var serverOnlineUrl = baseUrl + "online.gif";
|
||||
var backendOnlineUrl = baseUrl + "intermediary.gif";
|
||||
|
||||
var serverTimeout;
|
||||
|
||||
var message = window.document.getElementById("message");
|
||||
|
||||
var serverIsOnline = false;
|
||||
var serverOnlineCallback = function(result) {
|
||||
if (result == "load") {
|
||||
// our online.gif loaded, so the server is up, let's reload
|
||||
serverIsOnline = true;
|
||||
message.className = "pulsate1 green";
|
||||
message.innerText = "OctoPrint server online, reloading page...";
|
||||
window.location = baseUrl;
|
||||
} else {
|
||||
// online.gif still not available, let's look at
|
||||
var interval = 15;
|
||||
if (intervals.length) {
|
||||
interval = intervals.shift();
|
||||
}
|
||||
serverTimeout = setTimeout(function() {
|
||||
ping(serverOnlineUrl, timeout, serverOnlineCallback);
|
||||
}, interval * 1000)
|
||||
}
|
||||
};
|
||||
|
||||
var backendOfflineCounter = 0;
|
||||
var backendOnlineCallback = function(result) {
|
||||
if (serverIsOnline) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (result == "load") {
|
||||
setTimeout(function() {
|
||||
ping(backendOnlineUrl, timeout, backendOnlineCallback);
|
||||
}, 1000);
|
||||
return;
|
||||
}
|
||||
|
||||
backendOfflineCounter++;
|
||||
if (backendOfflineCounter > 10) {
|
||||
if (serverTimeout) {
|
||||
window.clearTimeout(serverTimeout);
|
||||
}
|
||||
|
||||
message.className = "red";
|
||||
message.innerHTML = "Looks like something went wrong during startup, the server is gone again. You should check <code>octoprint.log</code>.";
|
||||
} else {
|
||||
setTimeout(function() {
|
||||
ping(backendOnlineUrl, timeout, backendOnlineCallback);
|
||||
}, 1000);
|
||||
}
|
||||
};
|
||||
|
||||
ping(backendOnlineUrl, timeout, backendOnlineCallback);
|
||||
ping(serverOnlineUrl, timeout, serverOnlineCallback);
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="startup-overlay">
|
||||
<div class="background"></div>
|
||||
<div class="wrapper">
|
||||
<div class="outer">
|
||||
<div class="inner">
|
||||
<div class="content">
|
||||
<h1 id="message" class="pulsate3">OctoPrint is still starting up, please wait...</h1>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -11,8 +11,12 @@ function DataUpdater(allViewModels) {
|
||||
|
||||
self._pluginHash = undefined;
|
||||
|
||||
self.reloadOverlay = $("#reloadui_overlay");
|
||||
$("#reloadui_overlay_reload").click(function() { location.reload(true); });
|
||||
self._throttleFactor = 1;
|
||||
self._baseProcessingLimit = 500.0;
|
||||
self._lastProcessingTimes = [];
|
||||
self._lastProcessingTimesSize = 20;
|
||||
|
||||
self._timelapse_popup = undefined;
|
||||
|
||||
self.connect = function() {
|
||||
var options = {};
|
||||
@@ -32,6 +36,30 @@ function DataUpdater(allViewModels) {
|
||||
self.connect();
|
||||
};
|
||||
|
||||
self.increaseThrottle = function() {
|
||||
self.setThrottle(self._throttleFactor + 1);
|
||||
};
|
||||
|
||||
self.decreaseThrottle = function() {
|
||||
if (self._throttleFactor <= 1) {
|
||||
return;
|
||||
}
|
||||
self.setThrottle(self._throttleFactor - 1);
|
||||
};
|
||||
|
||||
self.setThrottle = function(throttle) {
|
||||
self._throttleFactor = throttle;
|
||||
|
||||
self._send("throttle", self._throttleFactor);
|
||||
log.debug("DataUpdater: New SockJS throttle factor:", self._throttleFactor, " new processing limit:", self._baseProcessingLimit * self._throttleFactor);
|
||||
};
|
||||
|
||||
self._send = function(message, data) {
|
||||
var payload = {};
|
||||
payload[message] = data;
|
||||
self._socket.send(JSON.stringify(payload));
|
||||
};
|
||||
|
||||
self._onconnect = function() {
|
||||
self._autoReconnecting = false;
|
||||
self._autoReconnectTrial = 0;
|
||||
@@ -51,7 +79,8 @@ function DataUpdater(allViewModels) {
|
||||
}
|
||||
|
||||
if (viewModel.hasOwnProperty("onServerDisconnect")) {
|
||||
if (!viewModel.onServerDisconnect()) {
|
||||
var result = viewModel.onServerDisconnect();
|
||||
if (result !== undefined && !result) {
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
@@ -86,7 +115,8 @@ function DataUpdater(allViewModels) {
|
||||
}
|
||||
|
||||
if (viewModel.hasOwnProperty("onServerDisconnect")) {
|
||||
if (!viewModel.onServerDisconnect()) {
|
||||
var result = viewModel.onServerDisconnect();
|
||||
if (result !== undefined && !result) {
|
||||
handled = true;
|
||||
}
|
||||
}
|
||||
@@ -111,6 +141,7 @@ function DataUpdater(allViewModels) {
|
||||
var gcodeUploadProgress = $("#gcode_upload_progress");
|
||||
var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);
|
||||
|
||||
var start = new Date().getTime();
|
||||
switch (prop) {
|
||||
case "connected": {
|
||||
// update the current UI API key and send it with any request
|
||||
@@ -122,6 +153,7 @@ function DataUpdater(allViewModels) {
|
||||
var oldVersion = VERSION;
|
||||
VERSION = data["version"];
|
||||
DISPLAY_VERSION = data["display_version"];
|
||||
BRANCH = data["branch"];
|
||||
$("span.version").text(DISPLAY_VERSION);
|
||||
|
||||
var oldPluginHash = self._pluginHash;
|
||||
@@ -130,7 +162,9 @@ function DataUpdater(allViewModels) {
|
||||
if ($("#offline_overlay").is(":visible")) {
|
||||
hideOfflineOverlay();
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onDataUpdaterReconnect")) {
|
||||
if (viewModel.hasOwnProperty("onServerReconnect")) {
|
||||
viewModel.onServerReconnect();
|
||||
} else if (viewModel.hasOwnProperty("onDataUpdaterReconnect")) {
|
||||
viewModel.onDataUpdaterReconnect();
|
||||
}
|
||||
});
|
||||
@@ -138,12 +172,20 @@ function DataUpdater(allViewModels) {
|
||||
if ($('#tabs li[class="active"] a').attr("href") == "#control") {
|
||||
$("#webcam_image").attr("src", CONFIG_WEBCAM_STREAM + "?" + new Date().getTime());
|
||||
}
|
||||
} else {
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onServerConnect")) {
|
||||
viewModel.onServerConnect();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (oldVersion != VERSION || (oldPluginHash != undefined && oldPluginHash != self._pluginHash)) {
|
||||
self.reloadOverlay.show();
|
||||
showReloadOverlay();
|
||||
}
|
||||
|
||||
self.setThrottle(1);
|
||||
|
||||
break;
|
||||
}
|
||||
case "history": {
|
||||
@@ -176,17 +218,95 @@ function DataUpdater(allViewModels) {
|
||||
var type = data["type"];
|
||||
var payload = data["payload"];
|
||||
var html = "";
|
||||
var format = {};
|
||||
|
||||
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
|
||||
|
||||
if (type == "MovieRendering") {
|
||||
new PNotify({title: gettext("Rendering timelapse"), text: _.sprintf(gettext("Now rendering timelapse %(movie_basename)s"), payload)});
|
||||
if (self._timelapse_popup !== undefined) {
|
||||
self._timelapse_popup.remove();
|
||||
}
|
||||
self._timelapse_popup = new PNotify({
|
||||
title: gettext("Rendering timelapse"),
|
||||
text: _.sprintf(gettext("Now rendering timelapse %(movie_basename)s. Due to performance reasons it is not recommended to start a print job while a movie is still rendering."), payload),
|
||||
hide: false,
|
||||
callbacks: {
|
||||
before_close: function() {
|
||||
self._timelapse_popup = undefined;
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if (type == "MovieDone") {
|
||||
new PNotify({title: gettext("Timelapse ready"), text: _.sprintf(gettext("New timelapse %(movie_basename)s is done rendering."), payload)});
|
||||
if (self._timelapse_popup !== undefined) {
|
||||
self._timelapse_popup.remove();
|
||||
}
|
||||
self._timelapse_popup = new PNotify({
|
||||
title: gettext("Timelapse ready"),
|
||||
text: _.sprintf(gettext("New timelapse %(movie_basename)s is done rendering."), payload),
|
||||
type: "success",
|
||||
callbacks: {
|
||||
before_close: function(notice) {
|
||||
if (self._timelapse_popup == notice) {
|
||||
self._timelapse_popup = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if (type == "MovieFailed") {
|
||||
html = "<p>" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s"), payload) + "</p>";
|
||||
html += pnotifyAdditionalInfo('<pre style="overflow: auto">' + payload.error + '</pre>');
|
||||
new PNotify({title: gettext("Rendering failed"), text: html, type: "error", hide: false});
|
||||
|
||||
if (self._timelapse_popup !== undefined) {
|
||||
self._timelapse_popup.remove();
|
||||
}
|
||||
self._timelapse_popup = new PNotify({
|
||||
title: gettext("Rendering failed"),
|
||||
text: html,
|
||||
type: "error",
|
||||
hide: false,
|
||||
callbacks: {
|
||||
before_close: function(notice) {
|
||||
if (self._timelapse_popup == notice) {
|
||||
self._timelapse_popup = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if (type == "PostRollStart") {
|
||||
var title = gettext("Capturing timelapse postroll");
|
||||
|
||||
var text;
|
||||
if (!payload.postroll_duration) {
|
||||
text = _.sprintf(gettext("Now capturing timelapse post roll, this will take only a moment..."), format);
|
||||
} else {
|
||||
format = {
|
||||
time: moment().add(payload.postroll_duration, "s").format("LT")
|
||||
};
|
||||
|
||||
if (payload.postroll_duration > 60) {
|
||||
format.duration = _.sprintf(gettext("%(minutes)d min"), {minutes: payload.postroll_duration / 60});
|
||||
text = _.sprintf(gettext("Now capturing timelapse post roll, this will take approximately %(duration)s (so until %(time)s)..."), format);
|
||||
} else {
|
||||
format.duration = _.sprintf(gettext("%(seconds)d sec"), {seconds: payload.postroll_duration});
|
||||
text = _.sprintf(gettext("Now capturing timelapse post roll, this will take approximately %(duration)s..."), format);
|
||||
}
|
||||
}
|
||||
|
||||
if (self._timelapse_popup !== undefined) {
|
||||
self._timelapse_popup.remove();
|
||||
}
|
||||
self._timelapse_popup = new PNotify({
|
||||
title: title,
|
||||
text: text,
|
||||
hide: false,
|
||||
callbacks: {
|
||||
before_close: function(notice) {
|
||||
if (self._timelapse_popup == notice) {
|
||||
self._timelapse_popup = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if (type == "SlicingStarted") {
|
||||
gcodeUploadProgress.addClass("progress-striped").addClass("active");
|
||||
gcodeUploadProgressBar.css("width", "100%");
|
||||
@@ -224,7 +344,22 @@ function DataUpdater(allViewModels) {
|
||||
text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload),
|
||||
type: "success"
|
||||
});
|
||||
gcodeFilesViewModel.requestData(payload.remote, "sdcard");
|
||||
} else if (type == "PrintCancelled") {
|
||||
if (payload.firmwareError) {
|
||||
new PNotify({
|
||||
title: gettext("Unhandled communication error"),
|
||||
text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
} else if (type == "Error") {
|
||||
new PNotify({
|
||||
title: gettext("Unhandled communication error"),
|
||||
text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
|
||||
var legacyEventHandlers = {
|
||||
@@ -264,6 +399,27 @@ function DataUpdater(allViewModels) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var end = new Date().getTime();
|
||||
var difference = end - start;
|
||||
|
||||
while (self._lastProcessingTimes.length >= self._lastProcessingTimesSize) {
|
||||
self._lastProcessingTimes.shift();
|
||||
}
|
||||
self._lastProcessingTimes.push(difference);
|
||||
|
||||
var processingLimit = self._throttleFactor * self._baseProcessingLimit;
|
||||
if (difference > processingLimit) {
|
||||
self.increaseThrottle();
|
||||
log.debug("We are slow (" + difference + " > " + processingLimit + "), reducing refresh rate");
|
||||
} else if (self._throttleFactor > 1) {
|
||||
var maxProcessingTime = Math.max.apply(null, self._lastProcessingTimes);
|
||||
var lowerProcessingLimit = (self._throttleFactor - 1) * self._baseProcessingLimit;
|
||||
if (maxProcessingTime < lowerProcessingLimit) {
|
||||
self.decreaseThrottle();
|
||||
log.debug("We are fast (" + maxProcessingTime + " < " + lowerProcessingLimit + "), increasing refresh rate");
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -333,6 +333,34 @@ function formatSize(bytes) {
|
||||
return _.sprintf("%.1f%s", bytes, "TB");
|
||||
}
|
||||
|
||||
function bytesFromSize(size) {
|
||||
if (size == undefined || size.trim() == "") return undefined;
|
||||
|
||||
var parsed = size.match(/^([+]?[0-9]*\.?[0-9]+)(?:\s*)?(.*)$/);
|
||||
var number = parsed[1];
|
||||
var unit = parsed[2].trim();
|
||||
|
||||
if (unit == "") return parseFloat(number);
|
||||
|
||||
var units = {
|
||||
b: 1,
|
||||
byte: 1,
|
||||
bytes: 1,
|
||||
kb: 1024,
|
||||
mb: Math.pow(1024, 2),
|
||||
gb: Math.pow(1024, 3),
|
||||
tb: Math.pow(1024, 4)
|
||||
};
|
||||
unit = unit.toLowerCase();
|
||||
|
||||
if (!units.hasOwnProperty(unit)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
var factor = units[unit];
|
||||
return number * factor;
|
||||
}
|
||||
|
||||
function formatDuration(seconds) {
|
||||
if (!seconds) return "-";
|
||||
if (seconds < 0) return "00:00:00";
|
||||
@@ -448,6 +476,10 @@ function showConfirmationDialog(message, onacknowledge) {
|
||||
confirmationDialog.modal("show");
|
||||
}
|
||||
|
||||
function showReloadOverlay() {
|
||||
$("#reloadui_overlay").show();
|
||||
}
|
||||
|
||||
function commentableLinesToArray(lines) {
|
||||
return splitTextToArray(lines, "\n", true, function(item) {return !_.startsWith(item, "#")});
|
||||
}
|
||||
@@ -461,3 +493,17 @@ function splitTextToArray(text, sep, stripEmpty, filter) {
|
||||
function(item) { return (stripEmpty ? item : true) && (filter ? filter(item) : true); }
|
||||
);
|
||||
}
|
||||
|
||||
var sizeObservable = function(observable) {
|
||||
return ko.computed({
|
||||
read: function() {
|
||||
return formatSize(observable());
|
||||
},
|
||||
write: function(value) {
|
||||
var result = bytesFromSize(value);
|
||||
if (result != undefined) {
|
||||
observable(result);
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
@@ -7,6 +7,72 @@ $(function() {
|
||||
|
||||
log.setLevel(CONFIG_DEBUG ? "debug" : "info");
|
||||
|
||||
//~~ setup browser and internal tab tracking (in 1.3.0 that will be
|
||||
// much nicer with the global OctoPrint object...)
|
||||
|
||||
var tabTracking = (function() {
|
||||
var exports = {
|
||||
browserTabVisibility: undefined,
|
||||
selectedTab: undefined
|
||||
};
|
||||
|
||||
var browserVisibilityCallbacks = [];
|
||||
|
||||
var getHiddenProp = function() {
|
||||
var prefixes = ["webkit", "moz", "ms", "o"];
|
||||
|
||||
// if "hidden" is natively supported just return it
|
||||
if ("hidden" in document) {
|
||||
return "hidden"
|
||||
}
|
||||
|
||||
// otherwise loop over all the known prefixes until we find one
|
||||
var vendorPrefix = _.find(prefixes, function(prefix) {
|
||||
return (prefix + "Hidden" in document);
|
||||
});
|
||||
if (vendorPrefix !== undefined) {
|
||||
return vendorPrefix + "Hidden";
|
||||
}
|
||||
|
||||
// nothing found
|
||||
return undefined;
|
||||
};
|
||||
|
||||
var isHidden = function() {
|
||||
var prop = getHiddenProp();
|
||||
if (!prop) return false;
|
||||
|
||||
return document[prop];
|
||||
};
|
||||
|
||||
var updateBrowserVisibility = function() {
|
||||
var visible = !isHidden();
|
||||
exports.browserTabVisible = visible;
|
||||
_.each(browserVisibilityCallbacks, function(callback) {
|
||||
callback(visible);
|
||||
})
|
||||
};
|
||||
|
||||
// register for browser visibility tracking
|
||||
|
||||
var prop = getHiddenProp();
|
||||
if (!prop) return undefined;
|
||||
|
||||
var eventName = prop.replace(/[H|h]idden/, "") + "visibilitychange";
|
||||
document.addEventListener(eventName, updateBrowserVisibility);
|
||||
|
||||
updateBrowserVisibility();
|
||||
|
||||
// exports
|
||||
|
||||
exports.isVisible = function() { return !isHidden() };
|
||||
exports.onBrowserVisibilityChange = function(callback) {
|
||||
browserVisibilityCallbacks.push(callback);
|
||||
};
|
||||
|
||||
return exports;
|
||||
})();
|
||||
|
||||
//~~ AJAX setup
|
||||
|
||||
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
|
||||
@@ -21,6 +87,15 @@ $(function() {
|
||||
headers: {"X-Api-Key": UI_API_KEY}
|
||||
});
|
||||
|
||||
//~~ Initialize file upload plugin
|
||||
|
||||
$.widget("blueimp.fileupload", $.blueimp.fileupload, {
|
||||
options: {
|
||||
dropZone: null,
|
||||
pasteZone: null
|
||||
}
|
||||
});
|
||||
|
||||
//~~ Initialize i18n
|
||||
|
||||
var catalog = window["BABEL_TO_LOAD_" + LOCALE];
|
||||
@@ -51,14 +126,27 @@ $(function() {
|
||||
//~~ Initialize PNotify
|
||||
|
||||
PNotify.prototype.options.styling = "bootstrap2";
|
||||
PNotify.prototype.options.mouse_reset = false;
|
||||
|
||||
//~~ Initialize view models
|
||||
|
||||
// the view model map is our basic look up table for dependencies that may be injected into other view models
|
||||
var viewModelMap = {};
|
||||
|
||||
// We put our tabTracking into the viewModelMap as a workaround until
|
||||
// our global OctoPrint object becomes available in 1.3.0. This way
|
||||
// we'll still be able to access it in our view models.
|
||||
//
|
||||
// NOTE TO DEVELOPERS: Do NOT depend on this dependency in your custom
|
||||
// view models. It is ONLY provided for the core application to be able
|
||||
// to backport a fix from the 1.3.0 development branch and WILL BE
|
||||
// REMOVED once 1.3.0 gets released without any fallback!
|
||||
//
|
||||
// TODO: Remove with release of 1.3.0
|
||||
viewModelMap.tabTracking = tabTracking;
|
||||
|
||||
// Fix Function#name on browsers that do not support it (IE):
|
||||
// see: http://stackoverflow.com/questions/6903762/function-name-not-supported-in-ie
|
||||
// see: http://stackoverflow.com/questions/6903762/function-name-not-supported-in-ie
|
||||
if (!(function f() {}).name) {
|
||||
Object.defineProperty(Function.prototype, 'name', {
|
||||
get: function() {
|
||||
@@ -275,6 +363,30 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
// Originally from Knockstrap
|
||||
// https://github.com/faulknercs/Knockstrap/blob/master/src/bindings/toggleBinding.js
|
||||
// License: MIT
|
||||
ko.bindingHandlers.toggle = {
|
||||
init: function (element, valueAccessor) {
|
||||
var value = valueAccessor();
|
||||
|
||||
if (!ko.isObservable(value)) {
|
||||
throw new Error('toggle binding should be used only with observable values');
|
||||
}
|
||||
|
||||
$(element).on('click', function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
var previousValue = ko.utils.unwrapObservable(value);
|
||||
value(!previousValue);
|
||||
});
|
||||
},
|
||||
|
||||
update: function (element, valueAccessor) {
|
||||
ko.utils.toggleDomNodeCssClass(element, 'active', ko.utils.unwrapObservable(valueAccessor()));
|
||||
}
|
||||
};
|
||||
|
||||
//~~ some additional hooks and initializations
|
||||
|
||||
// make sure modals max out at the window height
|
||||
@@ -320,7 +432,7 @@ $(function() {
|
||||
.data("contextParent", $(this))
|
||||
.show()
|
||||
.css({
|
||||
position: "absolute",
|
||||
position: "fixed",
|
||||
left: getMenuPosition(e.clientX, 'width', 'scrollLeft'),
|
||||
top: getMenuPosition(e.clientY, 'height', 'scrollTop'),
|
||||
"z-index": 9999
|
||||
@@ -361,16 +473,22 @@ $(function() {
|
||||
$('.nav-pills, .nav-tabs').tabdrop();
|
||||
|
||||
// Allow components to react to tab change
|
||||
var tabs = $('#tabs a[data-toggle="tab"]');
|
||||
tabs.on('show', function (e) {
|
||||
var current = e.target.hash;
|
||||
var previous = e.relatedTarget.hash;
|
||||
var onTabChange = function(current, previous) {
|
||||
log.debug("Selected OctoPrint tab changed: previous = " + previous + ", current = " + current);
|
||||
tabTracking.selectedTab = current;
|
||||
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onTabChange")) {
|
||||
viewModel.onTabChange(current, previous);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
var tabs = $('#tabs a[data-toggle="tab"]');
|
||||
tabs.on('show', function (e) {
|
||||
var current = e.target.hash;
|
||||
var previous = e.relatedTarget.hash;
|
||||
onTabChange(current, previous);
|
||||
});
|
||||
|
||||
tabs.on('shown', function (e) {
|
||||
@@ -384,6 +502,8 @@ $(function() {
|
||||
});
|
||||
});
|
||||
|
||||
onTabChange(OCTOPRINT_INITIAL_TAB);
|
||||
|
||||
// Fix input element click problems on dropdowns
|
||||
$(".dropdown input, .dropdown label").click(function(e) {
|
||||
e.stopPropagation();
|
||||
@@ -394,6 +514,9 @@ $(function() {
|
||||
e.preventDefault();
|
||||
});
|
||||
|
||||
// reload overlay
|
||||
$("#reloadui_overlay_reload").click(function() { location.reload(); });
|
||||
|
||||
//~~ Starting up the app
|
||||
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
@@ -475,11 +598,22 @@ $(function() {
|
||||
});
|
||||
log.info("... binding done");
|
||||
|
||||
// startup complete
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onStartupComplete")) {
|
||||
viewModel.onStartupComplete();
|
||||
}
|
||||
});
|
||||
|
||||
// make sure we can track the browser tab visibility
|
||||
tabTracking.onBrowserVisibilityChange(function(status) {
|
||||
log.debug("Browser tab is now " + (status ? "visible" : "hidden"));
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (viewModel.hasOwnProperty("onBrowserTabVisibilityChange")) {
|
||||
viewModel.onBrowserTabVisibilityChange(status);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
if (!_.has(viewModelMap, "settingsViewModel")) {
|
||||
|
||||
@@ -6,14 +6,14 @@ $(function() {
|
||||
self.color = parameters[0].appearance_color;
|
||||
self.colorTransparent = parameters[0].appearance_colorTransparent;
|
||||
|
||||
self.brand = ko.computed(function() {
|
||||
self.brand = ko.pureComputed(function() {
|
||||
if (self.name())
|
||||
return gettext("OctoPrint") + ": " + self.name();
|
||||
else
|
||||
return gettext("OctoPrint");
|
||||
});
|
||||
|
||||
self.title = ko.computed(function() {
|
||||
self.title = ko.pureComputed(function() {
|
||||
if (self.name())
|
||||
return self.name() + " [" + gettext("OctoPrint") + "]";
|
||||
else
|
||||
|
||||
@@ -37,7 +37,7 @@ $(function() {
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
self.buttonText = ko.computed(function() {
|
||||
self.buttonText = ko.pureComputed(function() {
|
||||
if (self.isErrorOrClosed())
|
||||
return gettext("Connect");
|
||||
else
|
||||
@@ -86,6 +86,15 @@ $(function() {
|
||||
self._processStateData(data.state);
|
||||
};
|
||||
|
||||
self.openOrCloseOnStateChange = function() {
|
||||
var connectionTab = $("#connection");
|
||||
if (self.isOperational() && connectionTab.hasClass("in")) {
|
||||
connectionTab.collapse("hide");
|
||||
} else if (!self.isOperational() && !connectionTab.hasClass("in")) {
|
||||
connectionTab.collapse("show");
|
||||
}
|
||||
}
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self.previousIsOperational = self.isOperational();
|
||||
|
||||
@@ -97,15 +106,10 @@ $(function() {
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.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");
|
||||
}
|
||||
if (self.loginState.isAdmin() && self.previousIsOperational != self.isOperational()) {
|
||||
// only open or close if the panel is visible (for admins) and
|
||||
// the state just changed to avoid thwarting manual open/close
|
||||
self.openOrCloseOnStateChange();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -147,6 +151,16 @@ $(function() {
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
|
||||
// when isAdmin becomes true the first time, set the panel open or
|
||||
// closed based on the connection state
|
||||
var subscription = self.loginState.isAdmin.subscribe(function(newValue) {
|
||||
if (newValue) {
|
||||
// wait until after the isAdmin state has run through all subscriptions
|
||||
setTimeout(self.openOrCloseOnStateChange, 0);
|
||||
subscription.dispose();
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,9 @@ $(function() {
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
|
||||
// TODO remove with release of 1.3.0 and switch to OctoPrint.coreui usage
|
||||
self.tabTracking = parameters[2];
|
||||
|
||||
self._createToolEntry = function () {
|
||||
return {
|
||||
name: ko.observable(),
|
||||
@@ -37,10 +40,10 @@ $(function() {
|
||||
|
||||
self.keycontrolActive = ko.observable(false);
|
||||
self.keycontrolHelpActive = ko.observable(false);
|
||||
self.keycontrolPossible = ko.computed(function () {
|
||||
self.keycontrolPossible = ko.pureComputed(function () {
|
||||
return self.isOperational() && !self.isPrinting() && self.loginState.isUser() && !$.browser.mobile;
|
||||
});
|
||||
self.showKeycontrols = ko.computed(function () {
|
||||
self.showKeycontrols = ko.pureComputed(function () {
|
||||
return self.keycontrolActive() && self.keycontrolPossible();
|
||||
});
|
||||
|
||||
@@ -415,31 +418,51 @@ $(function() {
|
||||
|
||||
self.onSettingsBeforeSave = self.updateRotatorWidth;
|
||||
|
||||
self._disableWebcam = function() {
|
||||
// only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause
|
||||
// more load by the constant connection creation than by the actual webcam stream
|
||||
self.webcamDisableTimeout = setTimeout(function () {
|
||||
$("#webcam_image").attr("src", "");
|
||||
}, 5000);
|
||||
};
|
||||
|
||||
self._enableWebcam = function() {
|
||||
if (self.tabTracking.selectedTab != "#control" || !self.tabTracking.browserTabVisible) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.webcamDisableTimeout != undefined) {
|
||||
clearTimeout(self.webcamDisableTimeout);
|
||||
}
|
||||
var webcamImage = $("#webcam_image");
|
||||
var currentSrc = webcamImage.attr("src");
|
||||
if (currentSrc === undefined || currentSrc.trim() == "") {
|
||||
var newSrc = CONFIG_WEBCAM_STREAM;
|
||||
if (CONFIG_WEBCAM_STREAM.lastIndexOf("?") > -1) {
|
||||
newSrc += "&";
|
||||
} else {
|
||||
newSrc += "?";
|
||||
}
|
||||
newSrc += new Date().getTime();
|
||||
|
||||
self.updateRotatorWidth();
|
||||
webcamImage.attr("src", newSrc);
|
||||
}
|
||||
};
|
||||
|
||||
self.onTabChange = function (current, previous) {
|
||||
if (current == "#control") {
|
||||
if (self.webcamDisableTimeout != undefined) {
|
||||
clearTimeout(self.webcamDisableTimeout);
|
||||
}
|
||||
var webcamImage = $("#webcam_image");
|
||||
var currentSrc = webcamImage.attr("src");
|
||||
if (currentSrc === undefined || currentSrc.trim() == "") {
|
||||
var newSrc = CONFIG_WEBCAM_STREAM;
|
||||
if (CONFIG_WEBCAM_STREAM.lastIndexOf("?") > -1) {
|
||||
newSrc += "&";
|
||||
} else {
|
||||
newSrc += "?";
|
||||
}
|
||||
newSrc += new Date().getTime();
|
||||
|
||||
self.updateRotatorWidth();
|
||||
webcamImage.attr("src", newSrc);
|
||||
}
|
||||
self._enableWebcam();
|
||||
} else if (previous == "#control") {
|
||||
// only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause
|
||||
// more load by the constant connection creation than by the actual webcam stream
|
||||
self.webcamDisableTimeout = setTimeout(function () {
|
||||
$("#webcam_image").attr("src", "");
|
||||
}, 5000);
|
||||
self._disableWebcam();
|
||||
}
|
||||
};
|
||||
|
||||
self.onBrowserTabVisibilityChange = function(status) {
|
||||
if (status) {
|
||||
self._enableWebcam();
|
||||
} else {
|
||||
self._disableWebcam();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -565,7 +588,7 @@ $(function() {
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
ControlViewModel,
|
||||
["loginStateViewModel", "settingsViewModel"],
|
||||
["loginStateViewModel", "settingsViewModel", "tabTracking"],
|
||||
"#control"
|
||||
]);
|
||||
});
|
||||
@@ -2,9 +2,10 @@ $(function() {
|
||||
function GcodeFilesViewModel(parameters) {
|
||||
var self = this;
|
||||
|
||||
self.printerState = parameters[0];
|
||||
self.settingsViewModel = parameters[0];
|
||||
self.loginState = parameters[1];
|
||||
self.slicing = parameters[2];
|
||||
self.printerState = parameters[2];
|
||||
self.slicing = parameters[3];
|
||||
|
||||
self.isErrorOrClosed = ko.observable(undefined);
|
||||
self.isOperational = ko.observable(undefined);
|
||||
@@ -21,13 +22,41 @@ $(function() {
|
||||
});
|
||||
|
||||
self.freeSpace = ko.observable(undefined);
|
||||
self.freeSpaceString = ko.computed(function() {
|
||||
self.totalSpace = ko.observable(undefined);
|
||||
self.freeSpaceString = ko.pureComputed(function() {
|
||||
if (!self.freeSpace())
|
||||
return "-";
|
||||
return formatSize(self.freeSpace());
|
||||
});
|
||||
self.totalSpaceString = ko.pureComputed(function() {
|
||||
if (!self.totalSpace())
|
||||
return "-";
|
||||
return formatSize(self.totalSpace());
|
||||
});
|
||||
|
||||
self.diskusageWarning = ko.pureComputed(function() {
|
||||
return self.freeSpace() != undefined
|
||||
&& self.freeSpace() < self.settingsViewModel.server_diskspace_warning();
|
||||
});
|
||||
self.diskusageCritical = ko.pureComputed(function() {
|
||||
return self.freeSpace() != undefined
|
||||
&& self.freeSpace() < self.settingsViewModel.server_diskspace_critical();
|
||||
});
|
||||
self.diskusageString = ko.pureComputed(function() {
|
||||
if (self.diskusageCritical()) {
|
||||
return gettext("Your available free disk space is critically low.");
|
||||
} else if (self.diskusageWarning()) {
|
||||
return gettext("Your available free disk space is starting to run low.");
|
||||
} else {
|
||||
return gettext("Your current disk usage.");
|
||||
}
|
||||
});
|
||||
|
||||
self.uploadButton = undefined;
|
||||
self.sdUploadButton = undefined;
|
||||
self.uploadProgressBar = undefined;
|
||||
self.localTarget = undefined;
|
||||
self.sdTarget = undefined;
|
||||
|
||||
// initialize list helper
|
||||
self.listHelper = new ItemListHelper(
|
||||
@@ -75,11 +104,11 @@ $(function() {
|
||||
0
|
||||
);
|
||||
|
||||
self.isLoadActionPossible = ko.computed(function() {
|
||||
self.isLoadActionPossible = ko.pureComputed(function() {
|
||||
return self.loginState.isUser() && !self.isPrinting() && !self.isPaused() && !self.isLoading();
|
||||
});
|
||||
|
||||
self.isLoadAndPrintActionPossible = ko.computed(function() {
|
||||
self.isLoadAndPrintActionPossible = ko.pureComputed(function() {
|
||||
return self.loginState.isUser() && self.isOperational() && self.isLoadActionPossible();
|
||||
});
|
||||
|
||||
@@ -155,10 +184,14 @@ $(function() {
|
||||
}
|
||||
}
|
||||
|
||||
if (response.free) {
|
||||
if (response.free != undefined) {
|
||||
self.freeSpace(response.free);
|
||||
}
|
||||
|
||||
if (response.total != undefined) {
|
||||
self.totalSpace(response.total);
|
||||
}
|
||||
|
||||
self.highlightFilename(self.printerState.filename());
|
||||
};
|
||||
|
||||
@@ -322,10 +355,6 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onDataUpdaterReconnect = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function(user) {
|
||||
self.uploadButton.fileupload("enable");
|
||||
};
|
||||
@@ -358,199 +387,35 @@ $(function() {
|
||||
//~~ Gcode upload
|
||||
|
||||
self.uploadButton = $("#gcode_upload");
|
||||
function gcode_upload_done(e, data) {
|
||||
var filename = undefined;
|
||||
var location = undefined;
|
||||
if (data.result.files.hasOwnProperty("sdcard")) {
|
||||
filename = data.result.files.sdcard.name;
|
||||
location = "sdcard";
|
||||
} else if (data.result.files.hasOwnProperty("local")) {
|
||||
filename = data.result.files.local.name;
|
||||
location = "local";
|
||||
}
|
||||
self.requestData(filename, location);
|
||||
self.sdUploadButton = $("#gcode_upload_sd");
|
||||
|
||||
if (_.endsWith(filename.toLowerCase(), ".stl")) {
|
||||
self.slicing.show(location, filename);
|
||||
}
|
||||
self.uploadProgress = $("#gcode_upload_progress");
|
||||
self.uploadProgressBar = $(".bar", self.uploadProgress);
|
||||
|
||||
if (data.result.done) {
|
||||
$("#gcode_upload_progress .bar").css("width", "0%");
|
||||
$("#gcode_upload_progress").removeClass("progress-striped").removeClass("active");
|
||||
$("#gcode_upload_progress .bar").text("");
|
||||
}
|
||||
}
|
||||
|
||||
function gcode_upload_fail(e, data) {
|
||||
var error = "<p>" + gettext("Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\".") + "</p>";
|
||||
error += pnotifyAdditionalInfo("<pre>" + data.jqXHR.responseText + "</pre>");
|
||||
new PNotify({
|
||||
title: "Upload failed",
|
||||
text: error,
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
$("#gcode_upload_progress .bar").css("width", "0%");
|
||||
$("#gcode_upload_progress").removeClass("progress-striped").removeClass("active");
|
||||
$("#gcode_upload_progress .bar").text("");
|
||||
}
|
||||
|
||||
function gcode_upload_progress(e, data) {
|
||||
var progress = parseInt(data.loaded / data.total * 100, 10);
|
||||
$("#gcode_upload_progress .bar").css("width", progress + "%");
|
||||
$("#gcode_upload_progress .bar").text(gettext("Uploading ..."));
|
||||
if (progress >= 100) {
|
||||
$("#gcode_upload_progress").addClass("progress-striped").addClass("active");
|
||||
$("#gcode_upload_progress .bar").text(gettext("Saving ..."));
|
||||
}
|
||||
}
|
||||
|
||||
function enable_local_dropzone() {
|
||||
$("#gcode_upload").fileupload({
|
||||
url: API_BASEURL + "files/local",
|
||||
dataType: "json",
|
||||
dropZone: localTarget,
|
||||
done: gcode_upload_done,
|
||||
fail: gcode_upload_fail,
|
||||
progressall: gcode_upload_progress
|
||||
});
|
||||
}
|
||||
|
||||
function disable_local_dropzone() {
|
||||
$("#gcode_upload").fileupload({
|
||||
url: API_BASEURL + "files/local",
|
||||
dataType: "json",
|
||||
dropZone: null,
|
||||
done: gcode_upload_done,
|
||||
fail: gcode_upload_fail,
|
||||
progressall: gcode_upload_progress
|
||||
});
|
||||
}
|
||||
|
||||
function enable_sd_dropzone() {
|
||||
$("#gcode_upload_sd").fileupload({
|
||||
url: API_BASEURL + "files/sdcard",
|
||||
dataType: "json",
|
||||
dropZone: $("#drop_sd"),
|
||||
done: gcode_upload_done,
|
||||
fail: gcode_upload_fail,
|
||||
progressall: gcode_upload_progress
|
||||
});
|
||||
}
|
||||
|
||||
function disable_sd_dropzone() {
|
||||
$("#gcode_upload_sd").fileupload({
|
||||
url: API_BASEURL + "files/sdcard",
|
||||
dataType: "json",
|
||||
dropZone: null,
|
||||
done: gcode_upload_done,
|
||||
fail: gcode_upload_fail,
|
||||
progressall: gcode_upload_progress
|
||||
});
|
||||
}
|
||||
|
||||
var localTarget;
|
||||
if (CONFIG_SD_SUPPORT) {
|
||||
localTarget = $("#drop_locally");
|
||||
self.localTarget = $("#drop_locally");
|
||||
} else {
|
||||
localTarget = $("#drop");
|
||||
self.localTarget = $("#drop");
|
||||
}
|
||||
self.sdTarget = $("#drop_sd");
|
||||
|
||||
self.loginState.isUser.subscribe(function(newValue) {
|
||||
if (newValue === true) {
|
||||
enable_local_dropzone();
|
||||
} else {
|
||||
disable_local_dropzone();
|
||||
}
|
||||
self._enableLocalDropzone(newValue);
|
||||
});
|
||||
|
||||
if (self.loginState.isUser()) {
|
||||
enable_local_dropzone();
|
||||
} else {
|
||||
disable_local_dropzone();
|
||||
}
|
||||
self._enableLocalDropzone(self.loginState.isUser());
|
||||
|
||||
if (CONFIG_SD_SUPPORT) {
|
||||
self.printerState.isSdReady.subscribe(function(newValue) {
|
||||
if (newValue === true && self.loginState.isUser()) {
|
||||
enable_sd_dropzone();
|
||||
} else {
|
||||
disable_sd_dropzone();
|
||||
}
|
||||
self._enableSdDropzone(newValue === true && self.loginState.isUser());
|
||||
});
|
||||
|
||||
self.loginState.isUser.subscribe(function(newValue) {
|
||||
if (newValue === true && self.printerState.isSdReady()) {
|
||||
enable_sd_dropzone();
|
||||
} else {
|
||||
disable_sd_dropzone();
|
||||
}
|
||||
self._enableSdDropzone(newValue === true && self.printerState.isSdReady());
|
||||
});
|
||||
|
||||
if (self.printerState.isSdReady() && self.loginState.isUser()) {
|
||||
enable_sd_dropzone();
|
||||
} else {
|
||||
disable_sd_dropzone();
|
||||
}
|
||||
self._enableSdDropzone(self.printerState.isSdReady() && self.loginState.isUser());
|
||||
}
|
||||
|
||||
$(document).bind("dragover", function (e) {
|
||||
var dropOverlay = $("#drop_overlay");
|
||||
var dropZone = $("#drop");
|
||||
var dropZoneLocal = $("#drop_locally");
|
||||
var dropZoneSd = $("#drop_sd");
|
||||
var dropZoneBackground = $("#drop_background");
|
||||
var dropZoneLocalBackground = $("#drop_locally_background");
|
||||
var dropZoneSdBackground = $("#drop_sd_background");
|
||||
var timeout = window.dropZoneTimeout;
|
||||
|
||||
if (!timeout) {
|
||||
dropOverlay.addClass('in');
|
||||
} else {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
|
||||
var foundLocal = false;
|
||||
var foundSd = false;
|
||||
var found = false;
|
||||
var node = e.target;
|
||||
do {
|
||||
if (dropZoneLocal && node === dropZoneLocal[0]) {
|
||||
foundLocal = true;
|
||||
break;
|
||||
} else if (dropZoneSd && node === dropZoneSd[0]) {
|
||||
foundSd = true;
|
||||
break;
|
||||
} else if (dropZone && node === dropZone[0]) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
node = node.parentNode;
|
||||
} while (node != null);
|
||||
|
||||
if (foundLocal) {
|
||||
dropZoneLocalBackground.addClass("hover");
|
||||
dropZoneSdBackground.removeClass("hover");
|
||||
} else if (foundSd && self.printerState.isSdReady()) {
|
||||
dropZoneSdBackground.addClass("hover");
|
||||
dropZoneLocalBackground.removeClass("hover");
|
||||
} else if (found) {
|
||||
dropZoneBackground.addClass("hover");
|
||||
} else {
|
||||
if (dropZoneLocalBackground) dropZoneLocalBackground.removeClass("hover");
|
||||
if (dropZoneSdBackground) dropZoneSdBackground.removeClass("hover");
|
||||
if (dropZoneBackground) dropZoneBackground.removeClass("hover");
|
||||
}
|
||||
|
||||
window.dropZoneTimeout = setTimeout(function () {
|
||||
window.dropZoneTimeout = null;
|
||||
dropOverlay.removeClass("in");
|
||||
if (dropZoneLocal) dropZoneLocalBackground.removeClass("hover");
|
||||
if (dropZoneSd) dropZoneSdBackground.removeClass("hover");
|
||||
if (dropZone) dropZoneBackground.removeClass("hover");
|
||||
}, 100);
|
||||
});
|
||||
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
@@ -571,11 +436,179 @@ $(function() {
|
||||
self.onEventMetadataStatisticsUpdated = function(payload) {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onEventTransferDone = function(payload) {
|
||||
self.requestData(payload.remote, "sdcard");
|
||||
};
|
||||
|
||||
self.onServerConnect = function(payload) {
|
||||
self._enableDragNDrop(true);
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onServerReconnect = function(payload) {
|
||||
self._enableDragNDrop(true);
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onServerDisconnect = function(payload) {
|
||||
self._enableDragNDrop(false);
|
||||
};
|
||||
|
||||
self._enableLocalDropzone = function(enable) {
|
||||
var options = {
|
||||
url: API_BASEURL + "files/local",
|
||||
dataType: "json",
|
||||
dropZone: enable ? self.localTarget : null,
|
||||
done: self._handleUploadDone,
|
||||
fail: self._handleUploadFail,
|
||||
progressall: self._handleUploadProgress
|
||||
};
|
||||
self.uploadButton.fileupload(options);
|
||||
};
|
||||
|
||||
self._enableSdDropzone = function(enable) {
|
||||
var options = {
|
||||
url: API_BASEURL + "files/sdcard",
|
||||
dataType: "json",
|
||||
dropZone: enable ? self.sdTarget : null,
|
||||
done: self._handleUploadDone,
|
||||
fail: self._handleUploadFail,
|
||||
progressall: self._handleUploadProgress
|
||||
};
|
||||
self.sdUploadButton.fileupload(options);
|
||||
};
|
||||
|
||||
self._enableDragNDrop = function(enable) {
|
||||
if (enable) {
|
||||
$(document).bind("dragover", self._handleDragNDrop);
|
||||
log.debug("Enabled drag-n-drop");
|
||||
} else {
|
||||
$(document).unbind("dragover", self._handleDragNDrop);
|
||||
log.debug("Disabled drag-n-drop");
|
||||
}
|
||||
};
|
||||
|
||||
self._handleUploadDone = function(e, data) {
|
||||
var filename = undefined;
|
||||
var location = undefined;
|
||||
if (data.result.files.hasOwnProperty("sdcard")) {
|
||||
filename = data.result.files.sdcard.name;
|
||||
location = "sdcard";
|
||||
} else if (data.result.files.hasOwnProperty("local")) {
|
||||
filename = data.result.files.local.name;
|
||||
location = "local";
|
||||
}
|
||||
self.requestData(filename, location);
|
||||
|
||||
if (_.endsWith(filename.toLowerCase(), ".stl")) {
|
||||
self.slicing.show(location, filename);
|
||||
}
|
||||
|
||||
if (data.result.done) {
|
||||
self.uploadProgressBar
|
||||
.css("width", "0%")
|
||||
.text("");
|
||||
self.uploadProgress
|
||||
.removeClass("progress-striped")
|
||||
.removeClass("active");
|
||||
}
|
||||
};
|
||||
|
||||
self._handleUploadFail = function(e, data) {
|
||||
var error = "<p>" + gettext("Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\".") + "</p>";
|
||||
error += pnotifyAdditionalInfo("<pre>" + data.jqXHR.responseText + "</pre>");
|
||||
new PNotify({
|
||||
title: "Upload failed",
|
||||
text: error,
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
self.uploadProgressBar
|
||||
.css("width", "0%")
|
||||
.text("");
|
||||
self.uploadProgress
|
||||
.removeClass("progress-striped")
|
||||
.removeClass("active");
|
||||
};
|
||||
|
||||
self._handleUploadProgress = function(e, data) {
|
||||
var progress = parseInt(data.loaded / data.total * 100, 10);
|
||||
|
||||
self.uploadProgressBar
|
||||
.css("width", progress + "%")
|
||||
.text(gettext("Uploading ..."));
|
||||
|
||||
if (progress >= 100) {
|
||||
self.uploadProgress
|
||||
.addClass("progress-striped")
|
||||
.addClass("active");
|
||||
self.uploadProgressBar
|
||||
.text(gettext("Saving ..."));
|
||||
}
|
||||
};
|
||||
|
||||
self._handleDragNDrop = function (e) {
|
||||
var dropOverlay = $("#drop_overlay");
|
||||
var dropZone = $("#drop");
|
||||
var dropZoneLocal = $("#drop_locally");
|
||||
var dropZoneSd = $("#drop_sd");
|
||||
var dropZoneBackground = $("#drop_background");
|
||||
var dropZoneLocalBackground = $("#drop_locally_background");
|
||||
var dropZoneSdBackground = $("#drop_sd_background");
|
||||
var timeout = window.dropZoneTimeout;
|
||||
|
||||
if (!timeout) {
|
||||
dropOverlay.addClass('in');
|
||||
} else {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
|
||||
var foundLocal = false;
|
||||
var foundSd = false;
|
||||
var found = false;
|
||||
var node = e.target;
|
||||
do {
|
||||
if (dropZoneLocal && node === dropZoneLocal[0]) {
|
||||
foundLocal = true;
|
||||
break;
|
||||
} else if (dropZoneSd && node === dropZoneSd[0]) {
|
||||
foundSd = true;
|
||||
break;
|
||||
} else if (dropZone && node === dropZone[0]) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
node = node.parentNode;
|
||||
} while (node != null);
|
||||
|
||||
if (foundLocal) {
|
||||
dropZoneLocalBackground.addClass("hover");
|
||||
dropZoneSdBackground.removeClass("hover");
|
||||
} else if (foundSd && self.printerState.isSdReady()) {
|
||||
dropZoneSdBackground.addClass("hover");
|
||||
dropZoneLocalBackground.removeClass("hover");
|
||||
} else if (found) {
|
||||
dropZoneBackground.addClass("hover");
|
||||
} else {
|
||||
if (dropZoneLocalBackground) dropZoneLocalBackground.removeClass("hover");
|
||||
if (dropZoneSdBackground) dropZoneSdBackground.removeClass("hover");
|
||||
if (dropZoneBackground) dropZoneBackground.removeClass("hover");
|
||||
}
|
||||
|
||||
window.dropZoneTimeout = setTimeout(function () {
|
||||
window.dropZoneTimeout = null;
|
||||
dropOverlay.removeClass("in");
|
||||
if (dropZoneLocal) dropZoneLocalBackground.removeClass("hover");
|
||||
if (dropZoneSd) dropZoneSdBackground.removeClass("hover");
|
||||
if (dropZone) dropZoneBackground.removeClass("hover");
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
GcodeFilesViewModel,
|
||||
["printerStateViewModel", "loginStateViewModel", "slicingViewModel"],
|
||||
["settingsViewModel", "loginStateViewModel", "printerStateViewModel", "slicingViewModel"],
|
||||
"#files_wrapper"
|
||||
]);
|
||||
});
|
||||
@@ -6,19 +6,19 @@ $(function() {
|
||||
self.password = ko.observable(undefined);
|
||||
self.confirmedPassword = ko.observable(undefined);
|
||||
|
||||
self.passwordMismatch = ko.computed(function() {
|
||||
self.passwordMismatch = ko.pureComputed(function() {
|
||||
return self.password() != self.confirmedPassword();
|
||||
});
|
||||
|
||||
self.validUsername = ko.computed(function() {
|
||||
self.validUsername = ko.pureComputed(function() {
|
||||
return self.username() && self.username().trim() != "";
|
||||
});
|
||||
|
||||
self.validPassword = ko.computed(function() {
|
||||
self.validPassword = ko.pureComputed(function() {
|
||||
return self.password() && self.password().trim() != "";
|
||||
});
|
||||
|
||||
self.validData = ko.computed(function() {
|
||||
self.validData = ko.pureComputed(function() {
|
||||
return !self.passwordMismatch() && self.validUsername() && self.validPassword();
|
||||
});
|
||||
|
||||
@@ -46,7 +46,7 @@ $(function() {
|
||||
};
|
||||
self._sendData(data, function() {
|
||||
// if the user indeed disables access control, we'll need to reload the page for this to take effect
|
||||
//location.reload(true); // TODO: clear cache doesn't work properly, needs a better way, same issue with reloading plugins
|
||||
showReloadOverlay();
|
||||
});
|
||||
});
|
||||
$("#confirmation_dialog").modal("show");
|
||||
|
||||
@@ -5,9 +5,12 @@ $(function() {
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
|
||||
// TODO remove with release of 1.3.0 and switch to OctoPrint.coreui usage
|
||||
self.tabTracking = parameters[2];
|
||||
|
||||
self.ui_progress_percentage = ko.observable();
|
||||
self.ui_progress_type = ko.observable();
|
||||
self.ui_progress_text = ko.computed(function() {
|
||||
self.ui_progress_text = ko.pureComputed(function() {
|
||||
var text = "";
|
||||
switch (self.ui_progress_type()) {
|
||||
case "loading": {
|
||||
@@ -339,6 +342,21 @@ $(function() {
|
||||
self._processData(data);
|
||||
};
|
||||
|
||||
self._renderPercentage = function(percentage) {
|
||||
var cmdIndex = GCODE.gCodeReader.getCmdIndexForPercentage(percentage);
|
||||
if (!cmdIndex) return;
|
||||
|
||||
GCODE.renderer.render(cmdIndex.layer, 0, cmdIndex.cmd);
|
||||
GCODE.ui.updateLayerInfo(cmdIndex.layer);
|
||||
|
||||
if (self.layerSlider != undefined) {
|
||||
self.layerSlider.slider("setValue", cmdIndex.layer);
|
||||
}
|
||||
if (self.layerCommandSlider != undefined) {
|
||||
self.layerCommandSlider.slider("setValue", [0, cmdIndex.cmd]);
|
||||
}
|
||||
};
|
||||
|
||||
self._processData = function(data) {
|
||||
if (!data.job.file || !data.job.file.name && (self.loadedFilename || self.loadedFileDate)) {
|
||||
self.waitForApproval(false);
|
||||
@@ -358,19 +376,8 @@ $(function() {
|
||||
if(self.loadedFilename
|
||||
&& self.loadedFilename == data.job.file.name
|
||||
&& self.loadedFileDate == data.job.file.date) {
|
||||
if (self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) {
|
||||
var cmdIndex = GCODE.gCodeReader.getCmdIndexForPercentage(data.progress.completion);
|
||||
if(cmdIndex){
|
||||
GCODE.renderer.render(cmdIndex.layer, 0, cmdIndex.cmd);
|
||||
GCODE.ui.updateLayerInfo(cmdIndex.layer);
|
||||
|
||||
if (self.layerSlider != undefined) {
|
||||
self.layerSlider.slider("setValue", cmdIndex.layer);
|
||||
}
|
||||
if (self.layerCommandSlider != undefined) {
|
||||
self.layerCommandSlider.slider("setValue", [0, cmdIndex.cmd]);
|
||||
}
|
||||
}
|
||||
if (self.tabTracking.browserTabVisible && self.tabActive && self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) {
|
||||
self._renderPercentage(data.progress.completion);
|
||||
}
|
||||
self.errorCount = 0
|
||||
} else {
|
||||
@@ -394,6 +401,12 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.onEventPrintDone = function() {
|
||||
if (self.renderer_syncProgress() && !self.waitForApproval()) {
|
||||
self._renderPercentage(100.0);
|
||||
}
|
||||
};
|
||||
|
||||
self.approveLargeFile = function() {
|
||||
self.waitForApproval(false);
|
||||
self.loadFile(self.selectedFile.name(), self.selectedFile.date());
|
||||
@@ -416,6 +429,7 @@ $(function() {
|
||||
} else {
|
||||
var output = [];
|
||||
output.push(gettext("Model size") + ": " + model.width.toFixed(2) + "mm × " + model.depth.toFixed(2) + "mm × " + model.height.toFixed(2) + "mm");
|
||||
output.push(gettext("Estimated total print time") + ": " + formatDuration(model.printTime));
|
||||
output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm"));
|
||||
output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext("printed") + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited"));
|
||||
|
||||
@@ -504,13 +518,16 @@ $(function() {
|
||||
|
||||
self.onBeforeBinding = function() {
|
||||
self.initialize();
|
||||
}
|
||||
};
|
||||
|
||||
self.onTabChange = function(current, previous) {
|
||||
self.tabActive = current == "#gcode";
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
GcodeViewModel,
|
||||
["loginStateViewModel", "settingsViewModel"],
|
||||
["loginStateViewModel", "settingsViewModel", "tabTracking"],
|
||||
"#gcode"
|
||||
]);
|
||||
});
|
||||
@@ -2,8 +2,8 @@ $(function() {
|
||||
function LoginStateViewModel() {
|
||||
var self = this;
|
||||
|
||||
self.loginUser = ko.observable();
|
||||
self.loginPass = ko.observable();
|
||||
self.loginUser = ko.observable("");
|
||||
self.loginPass = ko.observable("");
|
||||
self.loginRemember = ko.observable(false);
|
||||
|
||||
self.loggedIn = ko.observable(false);
|
||||
@@ -15,7 +15,7 @@ $(function() {
|
||||
|
||||
self.currentUser = ko.observable(undefined);
|
||||
|
||||
self.userMenuText = ko.computed(function() {
|
||||
self.userMenuText = ko.pureComputed(function() {
|
||||
if (self.loggedIn()) {
|
||||
return self.username();
|
||||
} else {
|
||||
@@ -79,10 +79,6 @@ $(function() {
|
||||
var password = self.loginPass();
|
||||
var remember = self.loginRemember();
|
||||
|
||||
self.loginUser("");
|
||||
self.loginPass("");
|
||||
self.loginRemember(false);
|
||||
|
||||
$.ajax({
|
||||
url: API_BASEURL + "login",
|
||||
type: "POST",
|
||||
@@ -90,6 +86,10 @@ $(function() {
|
||||
success: function(response) {
|
||||
new PNotify({title: gettext("Login successful"), text: _.sprintf(gettext('You are now logged in as "%(username)s"'), {username: response.name}), type: "success"});
|
||||
self.fromResponse(response);
|
||||
|
||||
self.loginUser("");
|
||||
self.loginPass("");
|
||||
self.loginRemember(false);
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
new PNotify({title: gettext("Login failed"), text: gettext("User unknown or wrong password"), type: "error"});
|
||||
@@ -138,4 +138,4 @@ $(function() {
|
||||
[],
|
||||
[]
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,7 @@ $(function() {
|
||||
|
||||
self.systemActions = self.settings.system_actions;
|
||||
|
||||
self.appearanceClasses = ko.computed(function() {
|
||||
self.appearanceClasses = ko.pureComputed(function() {
|
||||
var classes = self.appearance.color();
|
||||
if (self.appearance.colorTransparent()) {
|
||||
classes += " transparent";
|
||||
|
||||
@@ -15,7 +15,7 @@ $(function() {
|
||||
height: 200,
|
||||
origin: "lowerleft"
|
||||
},
|
||||
heatedBed: false,
|
||||
heatedBed: true,
|
||||
axes: {
|
||||
x: {speed: 6000, inverted: false},
|
||||
y: {speed: 6000, inverted: false},
|
||||
@@ -101,7 +101,7 @@ $(function() {
|
||||
{key: "black", name: gettext("black")}
|
||||
]);
|
||||
|
||||
self.availableOrigins = ko.computed(function() {
|
||||
self.availableOrigins = ko.pureComputed(function() {
|
||||
var formFactor = self.editorVolumeFormFactor();
|
||||
|
||||
var possibleOrigins = {
|
||||
@@ -123,7 +123,7 @@ $(function() {
|
||||
return result;
|
||||
});
|
||||
|
||||
self.koEditorExtruderOffsets = ko.computed(function() {
|
||||
self.koEditorExtruderOffsets = ko.pureComputed(function() {
|
||||
var extruderOffsets = self.editorExtruderOffsets();
|
||||
var numExtruders = self.editorExtruders();
|
||||
if (!numExtruders) {
|
||||
@@ -144,11 +144,11 @@ $(function() {
|
||||
return extruderOffsets.slice(0, numExtruders - 1);
|
||||
});
|
||||
|
||||
self.editorNameInvalid = ko.computed(function() {
|
||||
self.editorNameInvalid = ko.pureComputed(function() {
|
||||
return !self.editorName();
|
||||
});
|
||||
|
||||
self.editorIdentifierInvalid = ko.computed(function() {
|
||||
self.editorIdentifierInvalid = ko.pureComputed(function() {
|
||||
var identifier = self.editorIdentifier();
|
||||
var placeholder = self.editorIdentifierPlaceholder();
|
||||
var data = identifier;
|
||||
@@ -162,7 +162,7 @@ $(function() {
|
||||
return !data || !validCharacters || (self.editorNew() && existingProfile != undefined);
|
||||
});
|
||||
|
||||
self.editorIdentifierInvalidText = ko.computed(function() {
|
||||
self.editorIdentifierInvalidText = ko.pureComputed(function() {
|
||||
if (!self.editorIdentifierInvalid()) {
|
||||
return "";
|
||||
}
|
||||
@@ -176,7 +176,7 @@ $(function() {
|
||||
}
|
||||
});
|
||||
|
||||
self.enableEditorSubmitButton = ko.computed(function() {
|
||||
self.enableEditorSubmitButton = ko.pureComputed(function() {
|
||||
return !self.editorNameInvalid() && !self.editorIdentifierInvalid() && !self.requestInProgress();
|
||||
});
|
||||
|
||||
|
||||
@@ -14,6 +14,16 @@ $(function() {
|
||||
self.isLoading = ko.observable(undefined);
|
||||
self.isSdReady = ko.observable(undefined);
|
||||
|
||||
self.enablePrint = ko.pureComputed(function() {
|
||||
return self.isOperational() && self.isReady() && !self.isPrinting() && self.loginState.isUser() && self.filename() != undefined;
|
||||
});
|
||||
self.enablePause = ko.pureComputed(function() {
|
||||
return self.isOperational() && (self.isPrinting() || self.isPaused()) && self.loginState.isUser();
|
||||
});
|
||||
self.enableCancel = ko.pureComputed(function() {
|
||||
return self.isOperational() && (self.isPrinting() || self.isPaused()) && self.loginState.isUser();
|
||||
});
|
||||
|
||||
self.filename = ko.observable(undefined);
|
||||
self.progress = ko.observable(undefined);
|
||||
self.filesize = ko.observable(undefined);
|
||||
@@ -39,30 +49,30 @@ $(function() {
|
||||
self.titlePrintButton = ko.observable(self.TITLE_PRINT_BUTTON_UNPAUSED);
|
||||
self.titlePauseButton = ko.observable(self.TITLE_PAUSE_BUTTON_UNPAUSED);
|
||||
|
||||
self.estimatedPrintTimeString = ko.computed(function() {
|
||||
self.estimatedPrintTimeString = ko.pureComputed(function() {
|
||||
if (self.lastPrintTime())
|
||||
return formatDuration(self.lastPrintTime());
|
||||
if (self.estimatedPrintTime())
|
||||
return formatDuration(self.estimatedPrintTime());
|
||||
return "-";
|
||||
});
|
||||
self.byteString = ko.computed(function() {
|
||||
self.byteString = ko.pureComputed(function() {
|
||||
if (!self.filesize())
|
||||
return "-";
|
||||
var filepos = self.filepos() ? formatSize(self.filepos()) : "-";
|
||||
return filepos + " / " + formatSize(self.filesize());
|
||||
});
|
||||
self.heightString = ko.computed(function() {
|
||||
self.heightString = ko.pureComputed(function() {
|
||||
if (!self.currentHeight())
|
||||
return "-";
|
||||
return _.sprintf("%.02fmm", self.currentHeight());
|
||||
});
|
||||
self.printTimeString = ko.computed(function() {
|
||||
self.printTimeString = ko.pureComputed(function() {
|
||||
if (!self.printTime())
|
||||
return "-";
|
||||
return formatDuration(self.printTime());
|
||||
});
|
||||
self.printTimeLeftString = ko.computed(function() {
|
||||
self.printTimeLeftString = ko.pureComputed(function() {
|
||||
if (self.printTimeLeft() == undefined) {
|
||||
if (!self.printTime() || !(self.isPrinting() || self.isPaused())) {
|
||||
return "-";
|
||||
@@ -73,19 +83,19 @@ $(function() {
|
||||
return formatFuzzyEstimation(self.printTimeLeft());
|
||||
}
|
||||
});
|
||||
self.progressString = ko.computed(function() {
|
||||
self.progressString = ko.pureComputed(function() {
|
||||
if (!self.progress())
|
||||
return 0;
|
||||
return self.progress();
|
||||
});
|
||||
self.pauseString = ko.computed(function() {
|
||||
self.pauseString = ko.pureComputed(function() {
|
||||
if (self.isPaused())
|
||||
return gettext("Continue");
|
||||
else
|
||||
return gettext("Pause");
|
||||
});
|
||||
|
||||
self.timelapseString = ko.computed(function() {
|
||||
self.timelapseString = ko.pureComputed(function() {
|
||||
var timelapse = self.timelapse();
|
||||
|
||||
if (!timelapse || !timelapse.hasOwnProperty("type"))
|
||||
@@ -242,4 +252,4 @@ $(function() {
|
||||
["loginStateViewModel"],
|
||||
["#state_wrapper", "#drop_overlay"]
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,13 @@ $(function() {
|
||||
self.users = parameters[1];
|
||||
self.printerProfiles = parameters[2];
|
||||
|
||||
self.receiving = ko.observable(false);
|
||||
self.sending = ko.observable(false);
|
||||
self.exchanging = ko.pureComputed(function() {
|
||||
return self.receiving() || self.sending();
|
||||
});
|
||||
self.callbacks = [];
|
||||
|
||||
self.api_enabled = ko.observable(undefined);
|
||||
self.api_key = ko.observable(undefined);
|
||||
self.api_allowCrossOrigin = ko.observable(undefined);
|
||||
@@ -21,11 +28,11 @@ $(function() {
|
||||
self.translationUploadButton = $("#settings_appearance_managelanguagesdialog_upload_start");
|
||||
|
||||
self.translationUploadFilename = ko.observable();
|
||||
self.invalidTranslationArchive = ko.computed(function() {
|
||||
self.invalidTranslationArchive = ko.pureComputed(function() {
|
||||
var name = self.translationUploadFilename();
|
||||
return name !== undefined && !(_.endsWith(name.toLocaleLowerCase(), ".zip") || _.endsWith(name.toLocaleLowerCase(), ".tar.gz") || _.endsWith(name.toLocaleLowerCase(), ".tgz") || _.endsWith(name.toLocaleLowerCase(), ".tar"));
|
||||
});
|
||||
self.enableTranslationUpload = ko.computed(function() {
|
||||
self.enableTranslationUpload = ko.pureComputed(function() {
|
||||
var name = self.translationUploadFilename();
|
||||
return name !== undefined && name.trim() != "" && !self.invalidTranslationArchive();
|
||||
});
|
||||
@@ -114,6 +121,7 @@ $(function() {
|
||||
self.feature_disableExternalHeatupDetection = ko.observable(undefined);
|
||||
self.feature_keyboardControl = ko.observable(undefined);
|
||||
self.feature_pollWatched = ko.observable(undefined);
|
||||
self.feature_ignoreIdenticalResends = ko.observable(undefined);
|
||||
|
||||
self.serial_port = ko.observable();
|
||||
self.serial_baudrate = ko.observable();
|
||||
@@ -128,6 +136,11 @@ $(function() {
|
||||
self.serial_log = ko.observable(undefined);
|
||||
self.serial_additionalPorts = ko.observable(undefined);
|
||||
self.serial_longRunningCommands = ko.observable(undefined);
|
||||
self.serial_checksumRequiringCommands = ko.observable(undefined);
|
||||
self.serial_helloCommand = ko.observable(undefined);
|
||||
self.serial_ignoreErrorsFromFirmware = ko.observable(undefined);
|
||||
self.serial_disconnectOnErrors = ko.observable(undefined);
|
||||
self.serial_triggerOkForM29 = ko.observable(undefined);
|
||||
|
||||
self.folder_uploads = ko.observable(undefined);
|
||||
self.folder_timelapse = ko.observable(undefined);
|
||||
@@ -149,6 +162,15 @@ $(function() {
|
||||
|
||||
self.terminalFilters = ko.observableArray([]);
|
||||
|
||||
self.server_commands_systemShutdownCommand = ko.observable(undefined);
|
||||
self.server_commands_systemRestartCommand = ko.observable(undefined);
|
||||
self.server_commands_serverRestartCommand = ko.observable(undefined);
|
||||
|
||||
self.server_diskspace_warning = ko.observable();
|
||||
self.server_diskspace_critical = ko.observable();
|
||||
self.server_diskspace_warning_str = sizeObservable(self.server_diskspace_warning);
|
||||
self.server_diskspace_critical_str = sizeObservable(self.server_diskspace_critical);
|
||||
|
||||
self.settings = undefined;
|
||||
|
||||
self.addTemperatureProfile = function() {
|
||||
@@ -233,9 +255,20 @@ $(function() {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// reset scroll position on tab change
|
||||
$('ul.nav-list a[data-toggle="tab"]', self.settingsDialog).on("show", function() {
|
||||
self._resetScrollPosition();
|
||||
});
|
||||
};
|
||||
|
||||
self.show = function() {
|
||||
self.show = function(tab) {
|
||||
// select first or specified tab
|
||||
self.selectTab(tab);
|
||||
|
||||
// reset scroll position
|
||||
self._resetScrollPosition();
|
||||
|
||||
// show settings, ensure centered position
|
||||
self.settingsDialog.modal({
|
||||
minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); }
|
||||
@@ -257,13 +290,42 @@ $(function() {
|
||||
};
|
||||
|
||||
self.requestData = function(callback) {
|
||||
if (self.receiving()) {
|
||||
if (callback) {
|
||||
self.callbacks.push(callback);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
self.receiving(true);
|
||||
$.ajax({
|
||||
url: API_BASEURL + "settings",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
if (callback) callback();
|
||||
if (callback) {
|
||||
self.callbacks.push(callback);
|
||||
}
|
||||
|
||||
try {
|
||||
self.fromResponse(response);
|
||||
|
||||
var cb;
|
||||
while (self.callbacks.length) {
|
||||
cb = self.callbacks.shift();
|
||||
try {
|
||||
cb();
|
||||
} catch(exc) {
|
||||
log.error("Error calling settings callback", cb, ":", (exc.stack || exc));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
self.receiving(false);
|
||||
self.callbacks = [];
|
||||
}
|
||||
},
|
||||
error: function(xhr) {
|
||||
self.receiving(false);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -322,7 +384,7 @@ $(function() {
|
||||
return item.display + ((item.english != undefined) ? ' (' + item.english + ')' : '');
|
||||
};
|
||||
|
||||
self.languagePacksAvailable = ko.computed(function() {
|
||||
self.languagePacksAvailable = ko.pureComputed(function() {
|
||||
return self.translations.allSize() > 0;
|
||||
});
|
||||
|
||||
@@ -393,6 +455,11 @@ $(function() {
|
||||
self.serial_log(response.serial.log);
|
||||
self.serial_additionalPorts(response.serial.additionalPorts.join("\n"));
|
||||
self.serial_longRunningCommands(response.serial.longRunningCommands.join(", "));
|
||||
self.serial_checksumRequiringCommands(response.serial.checksumRequiringCommands.join(", "));
|
||||
self.serial_helloCommand(response.serial.helloCommand);
|
||||
self.serial_ignoreErrorsFromFirmware(response.serial.ignoreErrorsFromFirmware);
|
||||
self.serial_disconnectOnErrors(response.serial.disconnectOnErrors);
|
||||
self.serial_triggerOkForM29(response.serial.triggerOkForM29);
|
||||
|
||||
self.folder_uploads(response.folder.uploads);
|
||||
self.folder_timelapse(response.folder.timelapse);
|
||||
@@ -415,12 +482,18 @@ $(function() {
|
||||
self.system_actions(response.system.actions);
|
||||
|
||||
self.terminalFilters(response.terminalFilters);
|
||||
|
||||
self.server_commands_systemShutdownCommand(response.server.commands.systemShutdownCommand);
|
||||
self.server_commands_systemRestartCommand(response.server.commands.systemRestartCommand);
|
||||
self.server_commands_serverRestartCommand(response.server.commands.serverRestartCommand);
|
||||
};
|
||||
|
||||
self.saveData = function (data, successCallback) {
|
||||
self.settingsDialog.trigger("beforeSave");
|
||||
|
||||
if (data == undefined) {
|
||||
// we only set sending to true when we didn't include data
|
||||
self.sending(true);
|
||||
data = ko.mapping.toJS(self.settings);
|
||||
|
||||
data = _.extend(data, {
|
||||
@@ -473,7 +546,12 @@ $(function() {
|
||||
"timeoutSdStatus": self.serial_timeoutSdStatus(),
|
||||
"log": self.serial_log(),
|
||||
"additionalPorts": commentableLinesToArray(self.serial_additionalPorts()),
|
||||
"longRunningCommands": splitTextToArray(self.serial_longRunningCommands(), ",", true)
|
||||
"longRunningCommands": splitTextToArray(self.serial_longRunningCommands(), ",", true),
|
||||
"checksumRequiringCommands": splitTextToArray(self.serial_checksumRequiringCommands(), ",", true),
|
||||
"helloCommand": self.serial_helloCommand(),
|
||||
"ignoreErrorsFromFirmware": self.serial_ignoreErrorsFromFirmware(),
|
||||
"disconnectOnErrors": self.serial_disconnectOnErrors(),
|
||||
"triggerOkForM29": self.serial_triggerOkForM29()
|
||||
},
|
||||
"folder": {
|
||||
"uploads": self.folder_uploads(),
|
||||
@@ -499,6 +577,13 @@ $(function() {
|
||||
"beforePrintResumed": self.scripts_gcode_beforePrintResumed(),
|
||||
"afterPrinterConnected": self.scripts_gcode_afterPrinterConnected()
|
||||
}
|
||||
},
|
||||
"server": {
|
||||
"commands": {
|
||||
"systemShutdownCommand": self.server_commands_systemShutdownCommand(),
|
||||
"systemRestartCommand": self.server_commands_systemRestartCommand(),
|
||||
"serverRestartCommand": self.server_commands_serverRestartCommand()
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -510,11 +595,39 @@ $(function() {
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(data),
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
if (successCallback) successCallback(response);
|
||||
self.receiving(true);
|
||||
self.sending(false);
|
||||
try {
|
||||
self.fromResponse(response);
|
||||
if (successCallback) successCallback(response);
|
||||
} finally {
|
||||
self.receiving(false);
|
||||
}
|
||||
},
|
||||
error: function(xhr) {
|
||||
self.sending(false);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.onEventSettingsUpdated = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self._resetScrollPosition = function() {
|
||||
$('.scrollable', self.settingsDialog).scrollTop(0);
|
||||
};
|
||||
|
||||
self.selectTab = function(tab) {
|
||||
if (tab != undefined) {
|
||||
if (!_.startsWith(tab, "#")) {
|
||||
tab = "#" + tab;
|
||||
}
|
||||
$('ul.nav-list a[href="' + tab + '"]', self.settingsDialog).tab("show");
|
||||
} else {
|
||||
$('ul.nav-list a:first', self.settingsDialog).tab("show");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
|
||||
@@ -21,7 +21,7 @@ $(function() {
|
||||
self.profiles = ko.observableArray();
|
||||
self.printerProfile = ko.observable();
|
||||
|
||||
self.configured_slicers = ko.computed(function() {
|
||||
self.configured_slicers = ko.pureComputed(function() {
|
||||
return _.filter(self.slicers(), function(slicer) {
|
||||
return slicer.configured;
|
||||
});
|
||||
@@ -53,11 +53,11 @@ $(function() {
|
||||
self.profilesForSlicer(newValue);
|
||||
});
|
||||
|
||||
self.enableSlicingDialog = ko.computed(function() {
|
||||
self.enableSlicingDialog = ko.pureComputed(function() {
|
||||
return self.configured_slicers().length > 0;
|
||||
});
|
||||
|
||||
self.enableSliceButton = ko.computed(function() {
|
||||
self.enableSliceButton = ko.pureComputed(function() {
|
||||
return self.gcodeFilename() != undefined
|
||||
&& self.gcodeFilename().trim() != ""
|
||||
&& self.slicer() != undefined
|
||||
@@ -196,4 +196,4 @@ $(function() {
|
||||
["loginStateViewModel", "printerProfilesViewModel"],
|
||||
"#slicing_configuration_dialog"
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -36,7 +36,7 @@ $(function() {
|
||||
|
||||
self.heaterOptions = ko.observable({});
|
||||
|
||||
self._numExtrudersUpdated = function() {
|
||||
self._printerProfileUpdated = function() {
|
||||
var graphColors = ["red", "orange", "green", "brown", "purple"];
|
||||
var heaterOptions = {};
|
||||
var tools = self.tools();
|
||||
@@ -69,15 +69,21 @@ $(function() {
|
||||
}
|
||||
|
||||
// print bed
|
||||
heaterOptions["bed"] = {name: gettext("Bed"), color: "blue"};
|
||||
if (self.settingsViewModel.printerProfiles.currentProfileData().heatedBed()) {
|
||||
self.hasBed(true);
|
||||
heaterOptions["bed"] = {name: gettext("Bed"), color: "blue"};
|
||||
} else {
|
||||
self.hasBed(false);
|
||||
}
|
||||
|
||||
// write back
|
||||
self.heaterOptions(heaterOptions);
|
||||
self.tools(tools);
|
||||
};
|
||||
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
|
||||
self._numExtrudersUpdated();
|
||||
self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(self._numExtrudersUpdated);
|
||||
self._printerProfileUpdated();
|
||||
self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(self._printerProfileUpdated);
|
||||
self.settingsViewModel.printerProfiles.currentProfileData().heatedBed.subscribe(self._printerProfileUpdated());
|
||||
});
|
||||
|
||||
self.temperatures = [];
|
||||
@@ -152,11 +158,8 @@ $(function() {
|
||||
}
|
||||
|
||||
if (lastData.hasOwnProperty("bed")) {
|
||||
self.hasBed(true);
|
||||
self.bedTemp["actual"](lastData.bed.actual);
|
||||
self.bedTemp["target"](lastData.bed.target);
|
||||
} else {
|
||||
self.hasBed(false);
|
||||
}
|
||||
|
||||
if (!CONFIG_TEMPERATURE_GRAPH) return;
|
||||
@@ -208,8 +211,6 @@ $(function() {
|
||||
if (!d[type]) return;
|
||||
result[type].actual.push([time, d[type].actual]);
|
||||
result[type].target.push([time, d[type].target]);
|
||||
|
||||
self.hasBed(self.hasBed() || (type == "bed"));
|
||||
})
|
||||
});
|
||||
|
||||
@@ -375,4 +376,4 @@ $(function() {
|
||||
["loginStateViewModel", "settingsViewModel"],
|
||||
"#temp"
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -5,8 +5,18 @@ $(function() {
|
||||
self.loginState = parameters[0];
|
||||
self.settings = parameters[1];
|
||||
|
||||
// TODO remove with release of 1.3.0 and switch to OctoPrint.coreui usage
|
||||
self.tabTracking = parameters[2];
|
||||
|
||||
self.tabActive = false;
|
||||
|
||||
self.log = ko.observableArray([]);
|
||||
self.log.extend({ throttle: 500 });
|
||||
self.plainLogLines = ko.observableArray([]);
|
||||
self.plainLogLines.extend({ throttle: 500 });
|
||||
|
||||
self.buffer = ko.observable(300);
|
||||
self.upperLimit = ko.observable(1499);
|
||||
|
||||
self.command = ko.observable(undefined);
|
||||
|
||||
@@ -26,7 +36,26 @@ $(function() {
|
||||
self.cmdHistory = [];
|
||||
self.cmdHistoryIdx = -1;
|
||||
|
||||
self.displayedLines = ko.computed(function() {
|
||||
self.enableFancyFunctionality = ko.observable(true);
|
||||
self.disableTerminalLogDuringPrinting = ko.observable(false);
|
||||
self.acceptableTime = 500;
|
||||
self.acceptableUnfancyTime = 300;
|
||||
|
||||
self.forceFancyFunctionality = ko.observable(false);
|
||||
self.forceTerminalLogDuringPrinting = ko.observable(false);
|
||||
|
||||
self.fancyFunctionality = ko.pureComputed(function() {
|
||||
return self.enableFancyFunctionality() || self.forceFancyFunctionality();
|
||||
});
|
||||
self.terminalLogDuringPrinting = ko.pureComputed(function() {
|
||||
return !self.disableTerminalLogDuringPrinting() || self.forceTerminalLogDuringPrinting();
|
||||
});
|
||||
|
||||
self.displayedLines = ko.pureComputed(function() {
|
||||
if (!self.enableFancyFunctionality()) {
|
||||
return self.log();
|
||||
}
|
||||
|
||||
var regex = self.filterRegex();
|
||||
var lineVisible = function(entry) {
|
||||
return regex == undefined || !entry.line.match(regex);
|
||||
@@ -34,7 +63,8 @@ $(function() {
|
||||
|
||||
var filtered = false;
|
||||
var result = [];
|
||||
_.each(self.log(), function(entry) {
|
||||
var lines = self.log();
|
||||
_.each(lines, function(entry) {
|
||||
if (lineVisible(entry)) {
|
||||
result.push(entry);
|
||||
filtered = false;
|
||||
@@ -46,19 +76,41 @@ $(function() {
|
||||
|
||||
return result;
|
||||
});
|
||||
self.displayedLines.subscribe(function() {
|
||||
self.updateOutput();
|
||||
|
||||
self.plainLogOutput = ko.pureComputed(function() {
|
||||
if (self.fancyFunctionality()) {
|
||||
return;
|
||||
}
|
||||
return self.plainLogLines().join("\n");
|
||||
});
|
||||
|
||||
self.lineCount = ko.computed(function() {
|
||||
var total = self.log().length;
|
||||
var displayed = _.filter(self.displayedLines(), function(entry) { return entry.type == "line" }).length;
|
||||
self.lineCount = ko.pureComputed(function() {
|
||||
if (!self.fancyFunctionality()) {
|
||||
return;
|
||||
}
|
||||
|
||||
var regex = self.filterRegex();
|
||||
var lineVisible = function(entry) {
|
||||
return regex == undefined || !entry.line.match(regex);
|
||||
};
|
||||
|
||||
var lines = self.log();
|
||||
var total = lines.length;
|
||||
var displayed = _.filter(lines, lineVisible).length;
|
||||
var filtered = total - displayed;
|
||||
|
||||
if (total == displayed) {
|
||||
return _.sprintf(gettext("showing %(displayed)d lines"), {displayed: displayed});
|
||||
if (filtered > 0) {
|
||||
if (total > self.upperLimit()) {
|
||||
return _.sprintf(gettext("showing %(displayed)d lines (%(filtered)d of %(total)d total lines filtered, buffer full)"), {displayed: displayed, total: total, filtered: filtered});
|
||||
} else {
|
||||
return _.sprintf(gettext("showing %(displayed)d lines (%(filtered)d of %(total)d total lines filtered)"), {displayed: displayed, total: total, filtered: filtered});
|
||||
}
|
||||
} else {
|
||||
return _.sprintf(gettext("showing %(displayed)d lines (%(filtered)d of %(total)d total lines filtered)"), {displayed: displayed, total: total, filtered: filtered});
|
||||
if (total > self.upperLimit()) {
|
||||
return _.sprintf(gettext("showing %(displayed)d lines (buffer full)"), {displayed: displayed});
|
||||
} else {
|
||||
return _.sprintf(gettext("showing %(displayed)d lines"), {displayed: displayed});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -75,7 +127,23 @@ $(function() {
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
|
||||
var start = new Date().getTime();
|
||||
self._processCurrentLogData(data.logs);
|
||||
var end = new Date().getTime();
|
||||
|
||||
var difference = end - start;
|
||||
if (self.enableFancyFunctionality()) {
|
||||
if (difference > self.acceptableTime) {
|
||||
self.enableFancyFunctionality(false);
|
||||
log.warn("Terminal: Detected slow client (needed " + difference + "ms for processing new log data), disabling fancy terminal functionality");
|
||||
}
|
||||
} else {
|
||||
if (!self.disableTerminalLogDuringPrinting() && difference > self.acceptableUnfancyTime) {
|
||||
self.disableTerminalLogDuringPrinting(true);
|
||||
log.warn("Terminal: Detected very slow client (needed " + difference + "ms for processing new log data), completely disabling terminal output during printing");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.fromHistoryData = function(data) {
|
||||
@@ -84,14 +152,52 @@ $(function() {
|
||||
};
|
||||
|
||||
self._processCurrentLogData = function(data) {
|
||||
self.log(self.log().concat(_.map(data, function(line) { return self._toInternalFormat(line) })));
|
||||
if (self.autoscrollEnabled()) {
|
||||
self.log(self.log.slice(-300));
|
||||
var length = self.log().length;
|
||||
if (length >= self.upperLimit()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!self.terminalLogDuringPrinting() && self.isPrinting()) {
|
||||
var last = self.plainLogLines()[self.plainLogLines().length - 1];
|
||||
var disabled = "--- client too slow, log output disabled while printing ---";
|
||||
if (last != disabled) {
|
||||
self.plainLogLines.push(disabled);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var newData = (data.length + length > self.upperLimit())
|
||||
? data.slice(0, self.upperLimit() - length)
|
||||
: data;
|
||||
if (!newData) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!self.fancyFunctionality()) {
|
||||
// lite version of the terminal - text output only
|
||||
self.plainLogLines(self.plainLogLines().concat(newData).slice(-self.buffer()));
|
||||
self.updateOutput();
|
||||
return;
|
||||
}
|
||||
|
||||
var newLog = self.log().concat(_.map(newData, function(line) { return self._toInternalFormat(line) }));
|
||||
if (newData.length != data.length) {
|
||||
var cutoff = "--- too many lines to buffer, cut off ---";
|
||||
newLog.push(self._toInternalFormat(cutoff, "cut"));
|
||||
}
|
||||
|
||||
if (self.autoscrollEnabled()) {
|
||||
// we only keep the last <buffer> entries
|
||||
newLog = newLog.slice(-self.buffer());
|
||||
}
|
||||
self.log(newLog);
|
||||
self.updateOutput();
|
||||
};
|
||||
|
||||
self._processHistoryLogData = function(data) {
|
||||
self.plainLogLines(data);
|
||||
self.log(_.map(data, function(line) { return self._toInternalFormat(line) }));
|
||||
self.updateOutput();
|
||||
};
|
||||
|
||||
self._toInternalFormat = function(line, type) {
|
||||
@@ -122,7 +228,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.updateOutput = function() {
|
||||
if (self.autoscrollEnabled()) {
|
||||
if (self.tabActive && self.tabTracking.browserTabVisible && self.autoscrollEnabled()) {
|
||||
self.scrollToEnd();
|
||||
}
|
||||
};
|
||||
@@ -132,16 +238,16 @@ $(function() {
|
||||
};
|
||||
|
||||
self.selectAll = function() {
|
||||
var container = $("#terminal-output");
|
||||
var container = self.fancyFunctionality() ? $("#terminal-output") : $("#terminal-output-lowfi");
|
||||
if (container.length) {
|
||||
container.selectText();
|
||||
}
|
||||
};
|
||||
|
||||
self.scrollToEnd = function() {
|
||||
var container = $("#terminal-output");
|
||||
var container = self.fancyFunctionality() ? $("#terminal-output") : $("#terminal-output-lowfi");
|
||||
if (container.length) {
|
||||
container.scrollTop(container[0].scrollHeight - container.height())
|
||||
container.scrollTop(container[0].scrollHeight);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -217,19 +323,15 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onAfterTabChange = function(current, previous) {
|
||||
if (current != "#term") {
|
||||
return;
|
||||
}
|
||||
if (self.autoscrollEnabled()) {
|
||||
self.scrollToEnd();
|
||||
}
|
||||
self.tabActive = current == "#term";
|
||||
self.updateOutput();
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
TerminalViewModel,
|
||||
["loginStateViewModel", "settingsViewModel"],
|
||||
["loginStateViewModel", "settingsViewModel", "tabTracking"],
|
||||
"#term"
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -24,13 +24,17 @@ $(function() {
|
||||
self.isReady = ko.observable(undefined);
|
||||
self.isLoading = ko.observable(undefined);
|
||||
|
||||
self.timelapseTypeSelected = ko.computed(function() {
|
||||
self.isBusy = ko.pureComputed(function() {
|
||||
return self.isPrinting() || self.isPaused();
|
||||
});
|
||||
|
||||
self.timelapseTypeSelected = ko.pureComputed(function() {
|
||||
return ("off" != self.timelapseType());
|
||||
});
|
||||
self.intervalInputEnabled = ko.computed(function() {
|
||||
self.intervalInputEnabled = ko.pureComputed(function() {
|
||||
return ("timed" == self.timelapseType());
|
||||
});
|
||||
self.saveButtonEnabled = ko.computed(function() {
|
||||
self.saveButtonEnabled = ko.pureComputed(function() {
|
||||
return self.isDirty() && self.isOperational() && !self.isPrinting() && self.loginState.isUser();
|
||||
});
|
||||
|
||||
@@ -82,9 +86,40 @@ $(function() {
|
||||
CONFIG_TIMELAPSEFILESPERPAGE
|
||||
);
|
||||
|
||||
// initialize list helper for unrendered timelapses
|
||||
self.unrenderedListHelper = new ItemListHelper(
|
||||
"unrenderedTimelapseFiles",
|
||||
{
|
||||
"name": function(a, b) {
|
||||
// sorts ascending
|
||||
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
|
||||
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
|
||||
return 0;
|
||||
},
|
||||
"creation": function(a, b) {
|
||||
// sorts descending
|
||||
if (a["date"] > b["date"]) return -1;
|
||||
if (a["date"] < b["date"]) return 1;
|
||||
return 0;
|
||||
},
|
||||
"size": function(a, b) {
|
||||
// sorts descending
|
||||
if (a["bytes"] > b["bytes"]) return -1;
|
||||
if (a["bytes"] < b["bytes"]) return 1;
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
{
|
||||
},
|
||||
"name",
|
||||
[],
|
||||
[],
|
||||
CONFIG_TIMELAPSEFILESPERPAGE
|
||||
);
|
||||
|
||||
self.requestData = function() {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "timelapse",
|
||||
url: API_BASEURL + "timelapse?unrendered=true",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: self.fromResponse
|
||||
@@ -97,6 +132,9 @@ $(function() {
|
||||
|
||||
self.timelapseType(config.type);
|
||||
self.listHelper.updateItems(response.files);
|
||||
if (response.unrendered) {
|
||||
self.unrenderedListHelper.updateItems(response.unrendered);
|
||||
}
|
||||
|
||||
if (config.type == "timed") {
|
||||
if (config.interval != undefined && config.interval > 0) {
|
||||
@@ -149,6 +187,25 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
self.removeUnrendered = function(name) {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "timelapse/unrendered/" + name,
|
||||
type: "DELETE",
|
||||
dataType: "json",
|
||||
success: self.requestData
|
||||
});
|
||||
};
|
||||
|
||||
self.renderUnrendered = function(name) {
|
||||
$.ajax({
|
||||
url: API_BASEURL + "timelapse/unrendered/" + name,
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify({command: "render"})
|
||||
});
|
||||
};
|
||||
|
||||
self.save = function(data, event) {
|
||||
var payload = {
|
||||
"type": self.timelapseType(),
|
||||
|
||||
@@ -53,7 +53,7 @@ $(function() {
|
||||
self.editorRepeatedPassword(undefined);
|
||||
});
|
||||
|
||||
self.editorPasswordMismatch = ko.computed(function() {
|
||||
self.editorPasswordMismatch = ko.pureComputed(function() {
|
||||
return self.editorPassword() != self.editorRepeatedPassword();
|
||||
});
|
||||
|
||||
@@ -275,4 +275,4 @@ $(function() {
|
||||
["loginStateViewModel"],
|
||||
[]
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -33,7 +33,7 @@ $(function() {
|
||||
}
|
||||
});
|
||||
|
||||
self.passwordMismatch = ko.computed(function() {
|
||||
self.passwordMismatch = ko.pureComputed(function() {
|
||||
return self.access_password() != self.access_repeatedPassword();
|
||||
});
|
||||
|
||||
@@ -112,4 +112,4 @@ $(function() {
|
||||
["loginStateViewModel", "usersViewModel"],
|
||||
["#usersettings_dialog"]
|
||||
]);
|
||||
});
|
||||
});
|
||||
+4
-3
@@ -726,8 +726,9 @@
|
||||
selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
|
||||
}
|
||||
|
||||
$parent = $(selector)
|
||||
$parent.length || ($parent = $this.parent())
|
||||
$parent = selector && (selector != "#") && $(selector)
|
||||
|
||||
if (!$parent || !$parent.length) $parent = $this.parent()
|
||||
|
||||
return $parent
|
||||
}
|
||||
@@ -2156,4 +2157,4 @@
|
||||
})
|
||||
|
||||
|
||||
}(window.jQuery);
|
||||
}(window.jQuery);
|
||||
@@ -1,6 +0,0 @@
|
||||
/*!
|
||||
* 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
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
/*!
|
||||
* Knockout JavaScript library v3.4.0
|
||||
* (c) Steven Sanderson - http://knockoutjs.com/
|
||||
* License: MIT (http://www.opensource.org/licenses/mit-license.php)
|
||||
*/
|
||||
|
||||
(function() {(function(n){var x=this||(0,eval)("this"),u=x.document,M=x.navigator,v=x.jQuery,F=x.JSON;(function(n){"function"===typeof define&&define.amd?define(["exports","require"],n):"object"===typeof exports&&"object"===typeof module?n(module.exports||exports):n(x.ko={})})(function(N,O){function J(a,c){return null===a||typeof a in T?a===c:!1}function U(b,c){var d;return function(){d||(d=a.a.setTimeout(function(){d=n;b()},c))}}function V(b,c){var d;return function(){clearTimeout(d);d=a.a.setTimeout(b,c)}}function W(a,
|
||||
c){c&&c!==I?"beforeChange"===c?this.Kb(a):this.Ha(a,c):this.Lb(a)}function X(a,c){null!==c&&c.k&&c.k()}function Y(a,c){var d=this.Hc,e=d[s];e.R||(this.lb&&this.Ma[c]?(d.Pb(c,a,this.Ma[c]),this.Ma[c]=null,--this.lb):e.r[c]||d.Pb(c,a,e.s?{ia:a}:d.uc(a)))}function K(b,c,d,e){a.d[b]={init:function(b,g,k,l,m){var h,r;a.m(function(){var q=a.a.c(g()),p=!d!==!q,A=!r;if(A||c||p!==h)A&&a.va.Aa()&&(r=a.a.ua(a.f.childNodes(b),!0)),p?(A||a.f.da(b,a.a.ua(r)),a.eb(e?e(m,q):m,b)):a.f.xa(b),h=p},null,{i:b});return{controlsDescendantBindings:!0}}};
|
||||
a.h.ta[b]=!1;a.f.Z[b]=!0}var a="undefined"!==typeof N?N:{};a.b=function(b,c){for(var d=b.split("."),e=a,f=0;f<d.length-1;f++)e=e[d[f]];e[d[d.length-1]]=c};a.G=function(a,c,d){a[c]=d};a.version="3.4.0";a.b("version",a.version);a.options={deferUpdates:!1,useOnlyNativeEvents:!1};a.a=function(){function b(a,b){for(var c in a)a.hasOwnProperty(c)&&b(c,a[c])}function c(a,b){if(b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}function d(a,b){a.__proto__=b;return a}function e(b,c,d,e){var h=b[c].match(r)||
|
||||
[];a.a.q(d.match(r),function(b){a.a.pa(h,b,e)});b[c]=h.join(" ")}var f={__proto__:[]}instanceof Array,g="function"===typeof Symbol,k={},l={};k[M&&/Firefox\/2/i.test(M.userAgent)?"KeyboardEvent":"UIEvents"]=["keyup","keydown","keypress"];k.MouseEvents="click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave".split(" ");b(k,function(a,b){if(b.length)for(var c=0,d=b.length;c<d;c++)l[b[c]]=a});var m={propertychange:!0},h=u&&function(){for(var a=3,b=u.createElement("div"),c=
|
||||
b.getElementsByTagName("i");b.innerHTML="\x3c!--[if gt IE "+ ++a+"]><i></i><![endif]--\x3e",c[0];);return 4<a?a:n}(),r=/\S+/g;return{cc:["authenticity_token",/^__RequestVerificationToken(_.*)?$/],q:function(a,b){for(var c=0,d=a.length;c<d;c++)b(a[c],c)},o:function(a,b){if("function"==typeof Array.prototype.indexOf)return Array.prototype.indexOf.call(a,b);for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1},Sb:function(a,b,c){for(var d=0,e=a.length;d<e;d++)if(b.call(c,a[d],d))return a[d];
|
||||
return null},La:function(b,c){var d=a.a.o(b,c);0<d?b.splice(d,1):0===d&&b.shift()},Tb:function(b){b=b||[];for(var c=[],d=0,e=b.length;d<e;d++)0>a.a.o(c,b[d])&&c.push(b[d]);return c},fb:function(a,b){a=a||[];for(var c=[],d=0,e=a.length;d<e;d++)c.push(b(a[d],d));return c},Ka:function(a,b){a=a||[];for(var c=[],d=0,e=a.length;d<e;d++)b(a[d],d)&&c.push(a[d]);return c},ra:function(a,b){if(b instanceof Array)a.push.apply(a,b);else for(var c=0,d=b.length;c<d;c++)a.push(b[c]);return a},pa:function(b,c,d){var e=
|
||||
a.a.o(a.a.zb(b),c);0>e?d&&b.push(c):d||b.splice(e,1)},ka:f,extend:c,Xa:d,Ya:f?d:c,D:b,Ca:function(a,b){if(!a)return a;var c={},d;for(d in a)a.hasOwnProperty(d)&&(c[d]=b(a[d],d,a));return c},ob:function(b){for(;b.firstChild;)a.removeNode(b.firstChild)},jc:function(b){b=a.a.V(b);for(var c=(b[0]&&b[0].ownerDocument||u).createElement("div"),d=0,e=b.length;d<e;d++)c.appendChild(a.$(b[d]));return c},ua:function(b,c){for(var d=0,e=b.length,h=[];d<e;d++){var m=b[d].cloneNode(!0);h.push(c?a.$(m):m)}return h},
|
||||
da:function(b,c){a.a.ob(b);if(c)for(var d=0,e=c.length;d<e;d++)b.appendChild(c[d])},qc:function(b,c){var d=b.nodeType?[b]:b;if(0<d.length){for(var e=d[0],h=e.parentNode,m=0,l=c.length;m<l;m++)h.insertBefore(c[m],e);m=0;for(l=d.length;m<l;m++)a.removeNode(d[m])}},za:function(a,b){if(a.length){for(b=8===b.nodeType&&b.parentNode||b;a.length&&a[0].parentNode!==b;)a.splice(0,1);for(;1<a.length&&a[a.length-1].parentNode!==b;)a.length--;if(1<a.length){var c=a[0],d=a[a.length-1];for(a.length=0;c!==d;)a.push(c),
|
||||
c=c.nextSibling;a.push(d)}}return a},sc:function(a,b){7>h?a.setAttribute("selected",b):a.selected=b},$a:function(a){return null===a||a===n?"":a.trim?a.trim():a.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")},nd:function(a,b){a=a||"";return b.length>a.length?!1:a.substring(0,b.length)===b},Mc:function(a,b){if(a===b)return!0;if(11===a.nodeType)return!1;if(b.contains)return b.contains(3===a.nodeType?a.parentNode:a);if(b.compareDocumentPosition)return 16==(b.compareDocumentPosition(a)&16);for(;a&&a!=
|
||||
b;)a=a.parentNode;return!!a},nb:function(b){return a.a.Mc(b,b.ownerDocument.documentElement)},Qb:function(b){return!!a.a.Sb(b,a.a.nb)},A:function(a){return a&&a.tagName&&a.tagName.toLowerCase()},Wb:function(b){return a.onError?function(){try{return b.apply(this,arguments)}catch(c){throw a.onError&&a.onError(c),c;}}:b},setTimeout:function(b,c){return setTimeout(a.a.Wb(b),c)},$b:function(b){setTimeout(function(){a.onError&&a.onError(b);throw b;},0)},p:function(b,c,d){var e=a.a.Wb(d);d=h&&m[c];if(a.options.useOnlyNativeEvents||
|
||||
d||!v)if(d||"function"!=typeof b.addEventListener)if("undefined"!=typeof b.attachEvent){var l=function(a){e.call(b,a)},f="on"+c;b.attachEvent(f,l);a.a.F.oa(b,function(){b.detachEvent(f,l)})}else throw Error("Browser doesn't support addEventListener or attachEvent");else b.addEventListener(c,e,!1);else v(b).bind(c,e)},Da:function(b,c){if(!b||!b.nodeType)throw Error("element must be a DOM node when calling triggerEvent");var d;"input"===a.a.A(b)&&b.type&&"click"==c.toLowerCase()?(d=b.type,d="checkbox"==
|
||||
d||"radio"==d):d=!1;if(a.options.useOnlyNativeEvents||!v||d)if("function"==typeof u.createEvent)if("function"==typeof b.dispatchEvent)d=u.createEvent(l[c]||"HTMLEvents"),d.initEvent(c,!0,!0,x,0,0,0,0,0,!1,!1,!1,!1,0,b),b.dispatchEvent(d);else throw Error("The supplied element doesn't support dispatchEvent");else if(d&&b.click)b.click();else if("undefined"!=typeof b.fireEvent)b.fireEvent("on"+c);else throw Error("Browser doesn't support triggering events");else v(b).trigger(c)},c:function(b){return a.H(b)?
|
||||
b():b},zb:function(b){return a.H(b)?b.t():b},bb:function(b,c,d){var h;c&&("object"===typeof b.classList?(h=b.classList[d?"add":"remove"],a.a.q(c.match(r),function(a){h.call(b.classList,a)})):"string"===typeof b.className.baseVal?e(b.className,"baseVal",c,d):e(b,"className",c,d))},Za:function(b,c){var d=a.a.c(c);if(null===d||d===n)d="";var e=a.f.firstChild(b);!e||3!=e.nodeType||a.f.nextSibling(e)?a.f.da(b,[b.ownerDocument.createTextNode(d)]):e.data=d;a.a.Rc(b)},rc:function(a,b){a.name=b;if(7>=h)try{a.mergeAttributes(u.createElement("<input name='"+
|
||||
a.name+"'/>"),!1)}catch(c){}},Rc:function(a){9<=h&&(a=1==a.nodeType?a:a.parentNode,a.style&&(a.style.zoom=a.style.zoom))},Nc:function(a){if(h){var b=a.style.width;a.style.width=0;a.style.width=b}},hd:function(b,c){b=a.a.c(b);c=a.a.c(c);for(var d=[],e=b;e<=c;e++)d.push(e);return d},V:function(a){for(var b=[],c=0,d=a.length;c<d;c++)b.push(a[c]);return b},Yb:function(a){return g?Symbol(a):a},rd:6===h,sd:7===h,C:h,ec:function(b,c){for(var d=a.a.V(b.getElementsByTagName("input")).concat(a.a.V(b.getElementsByTagName("textarea"))),
|
||||
e="string"==typeof c?function(a){return a.name===c}:function(a){return c.test(a.name)},h=[],m=d.length-1;0<=m;m--)e(d[m])&&h.push(d[m]);return h},ed:function(b){return"string"==typeof b&&(b=a.a.$a(b))?F&&F.parse?F.parse(b):(new Function("return "+b))():null},Eb:function(b,c,d){if(!F||!F.stringify)throw 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 F.stringify(a.a.c(b),c,d)},fd:function(c,d,e){e=e||{};var h=e.params||{},m=e.includeFields||this.cc,l=c;if("object"==typeof c&&"form"===a.a.A(c))for(var l=c.action,f=m.length-1;0<=f;f--)for(var g=a.a.ec(c,m[f]),k=g.length-1;0<=k;k--)h[g[k].name]=g[k].value;d=a.a.c(d);var r=u.createElement("form");r.style.display="none";r.action=l;r.method="post";for(var n in d)c=u.createElement("input"),c.type="hidden",c.name=n,c.value=a.a.Eb(a.a.c(d[n])),r.appendChild(c);b(h,function(a,b){var c=u.createElement("input");
|
||||
c.type="hidden";c.name=a;c.value=b;r.appendChild(c)});u.body.appendChild(r);e.submitter?e.submitter(r):r.submit();setTimeout(function(){r.parentNode.removeChild(r)},0)}}}();a.b("utils",a.a);a.b("utils.arrayForEach",a.a.q);a.b("utils.arrayFirst",a.a.Sb);a.b("utils.arrayFilter",a.a.Ka);a.b("utils.arrayGetDistinctValues",a.a.Tb);a.b("utils.arrayIndexOf",a.a.o);a.b("utils.arrayMap",a.a.fb);a.b("utils.arrayPushAll",a.a.ra);a.b("utils.arrayRemoveItem",a.a.La);a.b("utils.extend",a.a.extend);a.b("utils.fieldsIncludedWithJsonPost",
|
||||
a.a.cc);a.b("utils.getFormFields",a.a.ec);a.b("utils.peekObservable",a.a.zb);a.b("utils.postJson",a.a.fd);a.b("utils.parseJson",a.a.ed);a.b("utils.registerEventHandler",a.a.p);a.b("utils.stringifyJson",a.a.Eb);a.b("utils.range",a.a.hd);a.b("utils.toggleDomNodeCssClass",a.a.bb);a.b("utils.triggerEvent",a.a.Da);a.b("utils.unwrapObservable",a.a.c);a.b("utils.objectForEach",a.a.D);a.b("utils.addOrRemoveItem",a.a.pa);a.b("utils.setTextContent",a.a.Za);a.b("unwrap",a.a.c);Function.prototype.bind||(Function.prototype.bind=
|
||||
function(a){var c=this;if(1===arguments.length)return function(){return c.apply(a,arguments)};var d=Array.prototype.slice.call(arguments,1);return function(){var e=d.slice(0);e.push.apply(e,arguments);return c.apply(a,e)}});a.a.e=new function(){function a(b,g){var k=b[d];if(!k||"null"===k||!e[k]){if(!g)return n;k=b[d]="ko"+c++;e[k]={}}return e[k]}var c=0,d="__ko__"+(new Date).getTime(),e={};return{get:function(c,d){var e=a(c,!1);return e===n?n:e[d]},set:function(c,d,e){if(e!==n||a(c,!1)!==n)a(c,!0)[d]=
|
||||
e},clear:function(a){var b=a[d];return b?(delete e[b],a[d]=null,!0):!1},I:function(){return c++ +d}}};a.b("utils.domData",a.a.e);a.b("utils.domData.clear",a.a.e.clear);a.a.F=new function(){function b(b,c){var e=a.a.e.get(b,d);e===n&&c&&(e=[],a.a.e.set(b,d,e));return e}function c(d){var e=b(d,!1);if(e)for(var e=e.slice(0),l=0;l<e.length;l++)e[l](d);a.a.e.clear(d);a.a.F.cleanExternalData(d);if(f[d.nodeType])for(e=d.firstChild;d=e;)e=d.nextSibling,8===d.nodeType&&c(d)}var d=a.a.e.I(),e={1:!0,8:!0,9:!0},
|
||||
f={1:!0,9:!0};return{oa:function(a,c){if("function"!=typeof c)throw Error("Callback must be a function");b(a,!0).push(c)},pc:function(c,e){var l=b(c,!1);l&&(a.a.La(l,e),0==l.length&&a.a.e.set(c,d,n))},$:function(b){if(e[b.nodeType]&&(c(b),f[b.nodeType])){var d=[];a.a.ra(d,b.getElementsByTagName("*"));for(var l=0,m=d.length;l<m;l++)c(d[l])}return b},removeNode:function(b){a.$(b);b.parentNode&&b.parentNode.removeChild(b)},cleanExternalData:function(a){v&&"function"==typeof v.cleanData&&v.cleanData([a])}}};
|
||||
a.$=a.a.F.$;a.removeNode=a.a.F.removeNode;a.b("cleanNode",a.$);a.b("removeNode",a.removeNode);a.b("utils.domNodeDisposal",a.a.F);a.b("utils.domNodeDisposal.addDisposeCallback",a.a.F.oa);a.b("utils.domNodeDisposal.removeDisposeCallback",a.a.F.pc);(function(){var b=[0,"",""],c=[1,"<table>","</table>"],d=[3,"<table><tbody><tr>","</tr></tbody></table>"],e=[1,"<select multiple='multiple'>","</select>"],f={thead:c,tbody:c,tfoot:c,tr:[2,"<table><tbody>","</tbody></table>"],td:d,th:d,option:e,optgroup:e},
|
||||
g=8>=a.a.C;a.a.ma=function(c,d){var e;if(v)if(v.parseHTML)e=v.parseHTML(c,d)||[];else{if((e=v.clean([c],d))&&e[0]){for(var h=e[0];h.parentNode&&11!==h.parentNode.nodeType;)h=h.parentNode;h.parentNode&&h.parentNode.removeChild(h)}}else{(e=d)||(e=u);var h=e.parentWindow||e.defaultView||x,r=a.a.$a(c).toLowerCase(),q=e.createElement("div"),p;p=(r=r.match(/^<([a-z]+)[ >]/))&&f[r[1]]||b;r=p[0];p="ignored<div>"+p[1]+c+p[2]+"</div>";"function"==typeof h.innerShiv?q.appendChild(h.innerShiv(p)):(g&&e.appendChild(q),
|
||||
q.innerHTML=p,g&&q.parentNode.removeChild(q));for(;r--;)q=q.lastChild;e=a.a.V(q.lastChild.childNodes)}return e};a.a.Cb=function(b,c){a.a.ob(b);c=a.a.c(c);if(null!==c&&c!==n)if("string"!=typeof c&&(c=c.toString()),v)v(b).html(c);else for(var d=a.a.ma(c,b.ownerDocument),e=0;e<d.length;e++)b.appendChild(d[e])}})();a.b("utils.parseHtmlFragment",a.a.ma);a.b("utils.setHtml",a.a.Cb);a.M=function(){function b(c,e){if(c)if(8==c.nodeType){var f=a.M.lc(c.nodeValue);null!=f&&e.push({Lc:c,cd:f})}else if(1==c.nodeType)for(var f=
|
||||
0,g=c.childNodes,k=g.length;f<k;f++)b(g[f],e)}var c={};return{wb:function(a){if("function"!=typeof a)throw 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);c[b]=a;return"\x3c!--[ko_memo:"+b+"]--\x3e"},xc:function(a,b){var f=c[a];if(f===n)throw Error("Couldn't find any memo with ID "+a+". Perhaps it's already been unmemoized.");try{return f.apply(null,b||[]),
|
||||
!0}finally{delete c[a]}},yc:function(c,e){var f=[];b(c,f);for(var g=0,k=f.length;g<k;g++){var l=f[g].Lc,m=[l];e&&a.a.ra(m,e);a.M.xc(f[g].cd,m);l.nodeValue="";l.parentNode&&l.parentNode.removeChild(l)}},lc:function(a){return(a=a.match(/^\[ko_memo\:(.*?)\]$/))?a[1]:null}}}();a.b("memoization",a.M);a.b("memoization.memoize",a.M.wb);a.b("memoization.unmemoize",a.M.xc);a.b("memoization.parseMemoText",a.M.lc);a.b("memoization.unmemoizeDomNodeAndDescendants",a.M.yc);a.Y=function(){function b(){if(e)for(var b=
|
||||
e,c=0,m;g<e;)if(m=d[g++]){if(g>b){if(5E3<=++c){g=e;a.a.$b(Error("'Too much recursion' after processing "+c+" task groups."));break}b=e}try{m()}catch(h){a.a.$b(h)}}}function c(){b();g=e=d.length=0}var d=[],e=0,f=1,g=0;return{scheduler:x.MutationObserver?function(a){var b=u.createElement("div");(new MutationObserver(a)).observe(b,{attributes:!0});return function(){b.classList.toggle("foo")}}(c):u&&"onreadystatechange"in u.createElement("script")?function(a){var b=u.createElement("script");b.onreadystatechange=
|
||||
function(){b.onreadystatechange=null;u.documentElement.removeChild(b);b=null;a()};u.documentElement.appendChild(b)}:function(a){setTimeout(a,0)},Wa:function(b){e||a.Y.scheduler(c);d[e++]=b;return f++},cancel:function(a){a-=f-e;a>=g&&a<e&&(d[a]=null)},resetForTesting:function(){var a=e-g;g=e=d.length=0;return a},md:b}}();a.b("tasks",a.Y);a.b("tasks.schedule",a.Y.Wa);a.b("tasks.runEarly",a.Y.md);a.ya={throttle:function(b,c){b.throttleEvaluation=c;var d=null;return a.B({read:b,write:function(e){clearTimeout(d);
|
||||
d=a.a.setTimeout(function(){b(e)},c)}})},rateLimit:function(a,c){var d,e,f;"number"==typeof c?d=c:(d=c.timeout,e=c.method);a.cb=!1;f="notifyWhenChangesStop"==e?V:U;a.Ta(function(a){return f(a,d)})},deferred:function(b,c){if(!0!==c)throw Error("The 'deferred' extender only accepts the value 'true', because it is not supported to turn deferral off once enabled.");b.cb||(b.cb=!0,b.Ta(function(c){var e;return function(){a.Y.cancel(e);e=a.Y.Wa(c);b.notifySubscribers(n,"dirty")}}))},notify:function(a,c){a.equalityComparer=
|
||||
"always"==c?null:J}};var T={undefined:1,"boolean":1,number:1,string:1};a.b("extenders",a.ya);a.vc=function(b,c,d){this.ia=b;this.gb=c;this.Kc=d;this.R=!1;a.G(this,"dispose",this.k)};a.vc.prototype.k=function(){this.R=!0;this.Kc()};a.J=function(){a.a.Ya(this,D);D.rb(this)};var I="change",D={rb:function(a){a.K={};a.Nb=1},X:function(b,c,d){var e=this;d=d||I;var f=new a.vc(e,c?b.bind(c):b,function(){a.a.La(e.K[d],f);e.Ia&&e.Ia(d)});e.sa&&e.sa(d);e.K[d]||(e.K[d]=[]);e.K[d].push(f);return f},notifySubscribers:function(b,
|
||||
c){c=c||I;c===I&&this.zc();if(this.Pa(c))try{a.l.Ub();for(var d=this.K[c].slice(0),e=0,f;f=d[e];++e)f.R||f.gb(b)}finally{a.l.end()}},Na:function(){return this.Nb},Uc:function(a){return this.Na()!==a},zc:function(){++this.Nb},Ta:function(b){var c=this,d=a.H(c),e,f,g;c.Ha||(c.Ha=c.notifySubscribers,c.notifySubscribers=W);var k=b(function(){c.Mb=!1;d&&g===c&&(g=c());e=!1;c.tb(f,g)&&c.Ha(f=g)});c.Lb=function(a){c.Mb=e=!0;g=a;k()};c.Kb=function(a){e||(f=a,c.Ha(a,"beforeChange"))}},Pa:function(a){return this.K[a]&&
|
||||
this.K[a].length},Sc:function(b){if(b)return this.K[b]&&this.K[b].length||0;var c=0;a.a.D(this.K,function(a,b){"dirty"!==a&&(c+=b.length)});return c},tb:function(a,c){return!this.equalityComparer||!this.equalityComparer(a,c)},extend:function(b){var c=this;b&&a.a.D(b,function(b,e){var f=a.ya[b];"function"==typeof f&&(c=f(c,e)||c)});return c}};a.G(D,"subscribe",D.X);a.G(D,"extend",D.extend);a.G(D,"getSubscriptionsCount",D.Sc);a.a.ka&&a.a.Xa(D,Function.prototype);a.J.fn=D;a.hc=function(a){return null!=
|
||||
a&&"function"==typeof a.X&&"function"==typeof a.notifySubscribers};a.b("subscribable",a.J);a.b("isSubscribable",a.hc);a.va=a.l=function(){function b(a){d.push(e);e=a}function c(){e=d.pop()}var d=[],e,f=0;return{Ub:b,end:c,oc:function(b){if(e){if(!a.hc(b))throw Error("Only subscribable things can act as dependencies");e.gb.call(e.Gc,b,b.Cc||(b.Cc=++f))}},w:function(a,d,e){try{return b(),a.apply(d,e||[])}finally{c()}},Aa:function(){if(e)return e.m.Aa()},Sa:function(){if(e)return e.Sa}}}();a.b("computedContext",
|
||||
a.va);a.b("computedContext.getDependenciesCount",a.va.Aa);a.b("computedContext.isInitial",a.va.Sa);a.b("ignoreDependencies",a.qd=a.l.w);var E=a.a.Yb("_latestValue");a.N=function(b){function c(){if(0<arguments.length)return c.tb(c[E],arguments[0])&&(c.ga(),c[E]=arguments[0],c.fa()),this;a.l.oc(c);return c[E]}c[E]=b;a.a.ka||a.a.extend(c,a.J.fn);a.J.fn.rb(c);a.a.Ya(c,B);a.options.deferUpdates&&a.ya.deferred(c,!0);return c};var B={equalityComparer:J,t:function(){return this[E]},fa:function(){this.notifySubscribers(this[E])},
|
||||
ga:function(){this.notifySubscribers(this[E],"beforeChange")}};a.a.ka&&a.a.Xa(B,a.J.fn);var H=a.N.gd="__ko_proto__";B[H]=a.N;a.Oa=function(b,c){return null===b||b===n||b[H]===n?!1:b[H]===c?!0:a.Oa(b[H],c)};a.H=function(b){return a.Oa(b,a.N)};a.Ba=function(b){return"function"==typeof b&&b[H]===a.N||"function"==typeof b&&b[H]===a.B&&b.Vc?!0:!1};a.b("observable",a.N);a.b("isObservable",a.H);a.b("isWriteableObservable",a.Ba);a.b("isWritableObservable",a.Ba);a.b("observable.fn",B);a.G(B,"peek",B.t);a.G(B,
|
||||
"valueHasMutated",B.fa);a.G(B,"valueWillMutate",B.ga);a.la=function(b){b=b||[];if("object"!=typeof b||!("length"in b))throw Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");b=a.N(b);a.a.Ya(b,a.la.fn);return b.extend({trackArrayChanges:!0})};a.la.fn={remove:function(b){for(var c=this.t(),d=[],e="function"!=typeof b||a.H(b)?function(a){return a===b}:b,f=0;f<c.length;f++){var g=c[f];e(g)&&(0===d.length&&this.ga(),d.push(g),c.splice(f,1),f--)}d.length&&
|
||||
this.fa();return d},removeAll:function(b){if(b===n){var c=this.t(),d=c.slice(0);this.ga();c.splice(0,c.length);this.fa();return d}return b?this.remove(function(c){return 0<=a.a.o(b,c)}):[]},destroy:function(b){var c=this.t(),d="function"!=typeof b||a.H(b)?function(a){return a===b}:b;this.ga();for(var e=c.length-1;0<=e;e--)d(c[e])&&(c[e]._destroy=!0);this.fa()},destroyAll:function(b){return b===n?this.destroy(function(){return!0}):b?this.destroy(function(c){return 0<=a.a.o(b,c)}):[]},indexOf:function(b){var c=
|
||||
this();return a.a.o(c,b)},replace:function(a,c){var d=this.indexOf(a);0<=d&&(this.ga(),this.t()[d]=c,this.fa())}};a.a.ka&&a.a.Xa(a.la.fn,a.N.fn);a.a.q("pop push reverse shift sort splice unshift".split(" "),function(b){a.la.fn[b]=function(){var a=this.t();this.ga();this.Vb(a,b,arguments);var d=a[b].apply(a,arguments);this.fa();return d===a?this:d}});a.a.q(["slice"],function(b){a.la.fn[b]=function(){var a=this();return a[b].apply(a,arguments)}});a.b("observableArray",a.la);a.ya.trackArrayChanges=function(b,
|
||||
c){function d(){if(!e){e=!0;var c=b.notifySubscribers;b.notifySubscribers=function(a,b){b&&b!==I||++k;return c.apply(this,arguments)};var d=[].concat(b.t()||[]);f=null;g=b.X(function(c){c=[].concat(c||[]);if(b.Pa("arrayChange")){var e;if(!f||1<k)f=a.a.ib(d,c,b.hb);e=f}d=c;f=null;k=0;e&&e.length&&b.notifySubscribers(e,"arrayChange")})}}b.hb={};c&&"object"==typeof c&&a.a.extend(b.hb,c);b.hb.sparse=!0;if(!b.Vb){var e=!1,f=null,g,k=0,l=b.sa,m=b.Ia;b.sa=function(a){l&&l.call(b,a);"arrayChange"===a&&d()};
|
||||
b.Ia=function(a){m&&m.call(b,a);"arrayChange"!==a||b.Pa("arrayChange")||(g.k(),e=!1)};b.Vb=function(b,c,d){function m(a,b,c){return l[l.length]={status:a,value:b,index:c}}if(e&&!k){var l=[],g=b.length,t=d.length,G=0;switch(c){case "push":G=g;case "unshift":for(c=0;c<t;c++)m("added",d[c],G+c);break;case "pop":G=g-1;case "shift":g&&m("deleted",b[G],G);break;case "splice":c=Math.min(Math.max(0,0>d[0]?g+d[0]:d[0]),g);for(var g=1===t?g:Math.min(c+(d[1]||0),g),t=c+t-2,G=Math.max(g,t),P=[],n=[],Q=2;c<G;++c,
|
||||
++Q)c<g&&n.push(m("deleted",b[c],c)),c<t&&P.push(m("added",d[Q],c));a.a.dc(n,P);break;default:return}f=l}}}};var s=a.a.Yb("_state");a.m=a.B=function(b,c,d){function e(){if(0<arguments.length){if("function"===typeof f)f.apply(g.pb,arguments);else throw 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.");return this}a.l.oc(e);(g.S||g.s&&e.Qa())&&e.aa();return g.T}"object"===typeof b?d=b:(d=d||{},b&&(d.read=
|
||||
b));if("function"!=typeof d.read)throw Error("Pass a function that returns the value of the ko.computed");var f=d.write,g={T:n,S:!0,Ra:!1,Fb:!1,R:!1,Va:!1,s:!1,jd:d.read,pb:c||d.owner,i:d.disposeWhenNodeIsRemoved||d.i||null,wa:d.disposeWhen||d.wa,mb:null,r:{},L:0,bc:null};e[s]=g;e.Vc="function"===typeof f;a.a.ka||a.a.extend(e,a.J.fn);a.J.fn.rb(e);a.a.Ya(e,z);d.pure?(g.Va=!0,g.s=!0,a.a.extend(e,$)):d.deferEvaluation&&a.a.extend(e,aa);a.options.deferUpdates&&a.ya.deferred(e,!0);g.i&&(g.Fb=!0,g.i.nodeType||
|
||||
(g.i=null));g.s||d.deferEvaluation||e.aa();g.i&&e.ba()&&a.a.F.oa(g.i,g.mb=function(){e.k()});return e};var z={equalityComparer:J,Aa:function(){return this[s].L},Pb:function(a,c,d){if(this[s].Va&&c===this)throw Error("A 'pure' computed must not be called recursively");this[s].r[a]=d;d.Ga=this[s].L++;d.na=c.Na()},Qa:function(){var a,c,d=this[s].r;for(a in d)if(d.hasOwnProperty(a)&&(c=d[a],c.ia.Uc(c.na)))return!0},bd:function(){this.Fa&&!this[s].Ra&&this.Fa()},ba:function(){return this[s].S||0<this[s].L},
|
||||
ld:function(){this.Mb||this.ac()},uc:function(a){if(a.cb&&!this[s].i){var c=a.X(this.bd,this,"dirty"),d=a.X(this.ld,this);return{ia:a,k:function(){c.k();d.k()}}}return a.X(this.ac,this)},ac:function(){var b=this,c=b.throttleEvaluation;c&&0<=c?(clearTimeout(this[s].bc),this[s].bc=a.a.setTimeout(function(){b.aa(!0)},c)):b.Fa?b.Fa():b.aa(!0)},aa:function(b){var c=this[s],d=c.wa;if(!c.Ra&&!c.R){if(c.i&&!a.a.nb(c.i)||d&&d()){if(!c.Fb){this.k();return}}else c.Fb=!1;c.Ra=!0;try{this.Qc(b)}finally{c.Ra=!1}c.L||
|
||||
this.k()}},Qc:function(b){var c=this[s],d=c.Va?n:!c.L,e={Hc:this,Ma:c.r,lb:c.L};a.l.Ub({Gc:e,gb:Y,m:this,Sa:d});c.r={};c.L=0;e=this.Pc(c,e);this.tb(c.T,e)&&(c.s||this.notifySubscribers(c.T,"beforeChange"),c.T=e,c.s?this.zc():b&&this.notifySubscribers(c.T));d&&this.notifySubscribers(c.T,"awake")},Pc:function(b,c){try{var d=b.jd;return b.pb?d.call(b.pb):d()}finally{a.l.end(),c.lb&&!b.s&&a.a.D(c.Ma,X),b.S=!1}},t:function(){var a=this[s];(a.S&&!a.L||a.s&&this.Qa())&&this.aa();return a.T},Ta:function(b){a.J.fn.Ta.call(this,
|
||||
b);this.Fa=function(){this.Kb(this[s].T);this[s].S=!0;this.Lb(this)}},k:function(){var b=this[s];!b.s&&b.r&&a.a.D(b.r,function(a,b){b.k&&b.k()});b.i&&b.mb&&a.a.F.pc(b.i,b.mb);b.r=null;b.L=0;b.R=!0;b.S=!1;b.s=!1;b.i=null}},$={sa:function(b){var c=this,d=c[s];if(!d.R&&d.s&&"change"==b){d.s=!1;if(d.S||c.Qa())d.r=null,d.L=0,d.S=!0,c.aa();else{var e=[];a.a.D(d.r,function(a,b){e[b.Ga]=a});a.a.q(e,function(a,b){var e=d.r[a],l=c.uc(e.ia);l.Ga=b;l.na=e.na;d.r[a]=l})}d.R||c.notifySubscribers(d.T,"awake")}},
|
||||
Ia:function(b){var c=this[s];c.R||"change"!=b||this.Pa("change")||(a.a.D(c.r,function(a,b){b.k&&(c.r[a]={ia:b.ia,Ga:b.Ga,na:b.na},b.k())}),c.s=!0,this.notifySubscribers(n,"asleep"))},Na:function(){var b=this[s];b.s&&(b.S||this.Qa())&&this.aa();return a.J.fn.Na.call(this)}},aa={sa:function(a){"change"!=a&&"beforeChange"!=a||this.t()}};a.a.ka&&a.a.Xa(z,a.J.fn);var R=a.N.gd;a.m[R]=a.N;z[R]=a.m;a.Xc=function(b){return a.Oa(b,a.m)};a.Yc=function(b){return a.Oa(b,a.m)&&b[s]&&b[s].Va};a.b("computed",a.m);
|
||||
a.b("dependentObservable",a.m);a.b("isComputed",a.Xc);a.b("isPureComputed",a.Yc);a.b("computed.fn",z);a.G(z,"peek",z.t);a.G(z,"dispose",z.k);a.G(z,"isActive",z.ba);a.G(z,"getDependenciesCount",z.Aa);a.nc=function(b,c){if("function"===typeof b)return a.m(b,c,{pure:!0});b=a.a.extend({},b);b.pure=!0;return a.m(b,c)};a.b("pureComputed",a.nc);(function(){function b(a,f,g){g=g||new d;a=f(a);if("object"!=typeof a||null===a||a===n||a instanceof RegExp||a instanceof Date||a instanceof String||a instanceof
|
||||
Number||a instanceof Boolean)return a;var k=a instanceof Array?[]:{};g.save(a,k);c(a,function(c){var d=f(a[c]);switch(typeof d){case "boolean":case "number":case "string":case "function":k[c]=d;break;case "object":case "undefined":var h=g.get(d);k[c]=h!==n?h:b(d,f,g)}});return k}function c(a,b){if(a instanceof Array){for(var c=0;c<a.length;c++)b(c);"function"==typeof a.toJSON&&b("toJSON")}else for(c in a)b(c)}function d(){this.keys=[];this.Ib=[]}a.wc=function(c){if(0==arguments.length)throw Error("When calling ko.toJS, pass the object you want to convert.");
|
||||
return b(c,function(b){for(var c=0;a.H(b)&&10>c;c++)b=b();return b})};a.toJSON=function(b,c,d){b=a.wc(b);return a.a.Eb(b,c,d)};d.prototype={save:function(b,c){var d=a.a.o(this.keys,b);0<=d?this.Ib[d]=c:(this.keys.push(b),this.Ib.push(c))},get:function(b){b=a.a.o(this.keys,b);return 0<=b?this.Ib[b]:n}}})();a.b("toJS",a.wc);a.b("toJSON",a.toJSON);(function(){a.j={u:function(b){switch(a.a.A(b)){case "option":return!0===b.__ko__hasDomDataOptionValue__?a.a.e.get(b,a.d.options.xb):7>=a.a.C?b.getAttributeNode("value")&&
|
||||
b.getAttributeNode("value").specified?b.value:b.text:b.value;case "select":return 0<=b.selectedIndex?a.j.u(b.options[b.selectedIndex]):n;default:return b.value}},ha:function(b,c,d){switch(a.a.A(b)){case "option":switch(typeof c){case "string":a.a.e.set(b,a.d.options.xb,n);"__ko__hasDomDataOptionValue__"in b&&delete b.__ko__hasDomDataOptionValue__;b.value=c;break;default:a.a.e.set(b,a.d.options.xb,c),b.__ko__hasDomDataOptionValue__=!0,b.value="number"===typeof c?c:""}break;case "select":if(""===c||
|
||||
null===c)c=n;for(var e=-1,f=0,g=b.options.length,k;f<g;++f)if(k=a.j.u(b.options[f]),k==c||""==k&&c===n){e=f;break}if(d||0<=e||c===n&&1<b.size)b.selectedIndex=e;break;default:if(null===c||c===n)c="";b.value=c}}}})();a.b("selectExtensions",a.j);a.b("selectExtensions.readValue",a.j.u);a.b("selectExtensions.writeValue",a.j.ha);a.h=function(){function b(b){b=a.a.$a(b);123===b.charCodeAt(0)&&(b=b.slice(1,-1));var c=[],d=b.match(e),r,k=[],p=0;if(d){d.push(",");for(var A=0,y;y=d[A];++A){var t=y.charCodeAt(0);
|
||||
if(44===t){if(0>=p){c.push(r&&k.length?{key:r,value:k.join("")}:{unknown:r||k.join("")});r=p=0;k=[];continue}}else if(58===t){if(!p&&!r&&1===k.length){r=k.pop();continue}}else 47===t&&A&&1<y.length?(t=d[A-1].match(f))&&!g[t[0]]&&(b=b.substr(b.indexOf(y)+1),d=b.match(e),d.push(","),A=-1,y="/"):40===t||123===t||91===t?++p:41===t||125===t||93===t?--p:r||k.length||34!==t&&39!==t||(y=y.slice(1,-1));k.push(y)}}return c}var c=["true","false","null","undefined"],d=/^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i,
|
||||
e=RegExp("\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'|/(?:[^/\\\\]|\\\\.)*/w*|[^\\s:,/][^,\"'{}()/:[\\]]*[^\\s,\"'{}()/:[\\]]|[^\\s]","g"),f=/[\])"'A-Za-z0-9_$]+$/,g={"in":1,"return":1,"typeof":1},k={};return{ta:[],ea:k,yb:b,Ua:function(e,m){function h(b,e){var m;if(!A){var l=a.getBindingHandler(b);if(l&&l.preprocess&&!(e=l.preprocess(e,b,h)))return;if(l=k[b])m=e,0<=a.a.o(c,m)?m=!1:(l=m.match(d),m=null===l?!1:l[1]?"Object("+l[1]+")"+l[2]:m),l=m;l&&g.push("'"+b+"':function(_z){"+m+"=_z}")}p&&(e=
|
||||
"function(){return "+e+" }");f.push("'"+b+"':"+e)}m=m||{};var f=[],g=[],p=m.valueAccessors,A=m.bindingParams,y="string"===typeof e?b(e):e;a.a.q(y,function(a){h(a.key||a.unknown,a.value)});g.length&&h("_ko_property_writers","{"+g.join(",")+" }");return f.join(",")},ad:function(a,b){for(var c=0;c<a.length;c++)if(a[c].key==b)return!0;return!1},Ea:function(b,c,d,e,f){if(b&&a.H(b))!a.Ba(b)||f&&b.t()===e||b(e);else if((b=c.get("_ko_property_writers"))&&b[d])b[d](e)}}}();a.b("expressionRewriting",a.h);a.b("expressionRewriting.bindingRewriteValidators",
|
||||
a.h.ta);a.b("expressionRewriting.parseObjectLiteral",a.h.yb);a.b("expressionRewriting.preProcessBindings",a.h.Ua);a.b("expressionRewriting._twoWayBindings",a.h.ea);a.b("jsonExpressionRewriting",a.h);a.b("jsonExpressionRewriting.insertPropertyAccessorsIntoJson",a.h.Ua);(function(){function b(a){return 8==a.nodeType&&g.test(f?a.text:a.nodeValue)}function c(a){return 8==a.nodeType&&k.test(f?a.text:a.nodeValue)}function d(a,d){for(var e=a,f=1,l=[];e=e.nextSibling;){if(c(e)&&(f--,0===f))return l;l.push(e);
|
||||
b(e)&&f++}if(!d)throw Error("Cannot find closing comment tag to match: "+a.nodeValue);return null}function e(a,b){var c=d(a,b);return c?0<c.length?c[c.length-1].nextSibling:a.nextSibling:null}var f=u&&"\x3c!--test--\x3e"===u.createComment("test").text,g=f?/^\x3c!--\s*ko(?:\s+([\s\S]+))?\s*--\x3e$/:/^\s*ko(?:\s+([\s\S]+))?\s*$/,k=f?/^\x3c!--\s*\/ko\s*--\x3e$/:/^\s*\/ko\s*$/,l={ul:!0,ol:!0};a.f={Z:{},childNodes:function(a){return b(a)?d(a):a.childNodes},xa:function(c){if(b(c)){c=a.f.childNodes(c);for(var d=
|
||||
0,e=c.length;d<e;d++)a.removeNode(c[d])}else a.a.ob(c)},da:function(c,d){if(b(c)){a.f.xa(c);for(var e=c.nextSibling,f=0,l=d.length;f<l;f++)e.parentNode.insertBefore(d[f],e)}else a.a.da(c,d)},mc:function(a,c){b(a)?a.parentNode.insertBefore(c,a.nextSibling):a.firstChild?a.insertBefore(c,a.firstChild):a.appendChild(c)},gc:function(c,d,e){e?b(c)?c.parentNode.insertBefore(d,e.nextSibling):e.nextSibling?c.insertBefore(d,e.nextSibling):c.appendChild(d):a.f.mc(c,d)},firstChild:function(a){return b(a)?!a.nextSibling||
|
||||
c(a.nextSibling)?null:a.nextSibling:a.firstChild},nextSibling:function(a){b(a)&&(a=e(a));return a.nextSibling&&c(a.nextSibling)?null:a.nextSibling},Tc:b,pd:function(a){return(a=(f?a.text:a.nodeValue).match(g))?a[1]:null},kc:function(d){if(l[a.a.A(d)]){var h=d.firstChild;if(h){do if(1===h.nodeType){var f;f=h.firstChild;var g=null;if(f){do if(g)g.push(f);else if(b(f)){var k=e(f,!0);k?f=k:g=[f]}else c(f)&&(g=[f]);while(f=f.nextSibling)}if(f=g)for(g=h.nextSibling,k=0;k<f.length;k++)g?d.insertBefore(f[k],
|
||||
g):d.appendChild(f[k])}while(h=h.nextSibling)}}}}})();a.b("virtualElements",a.f);a.b("virtualElements.allowedBindings",a.f.Z);a.b("virtualElements.emptyNode",a.f.xa);a.b("virtualElements.insertAfter",a.f.gc);a.b("virtualElements.prepend",a.f.mc);a.b("virtualElements.setDomNodeChildren",a.f.da);(function(){a.Q=function(){this.Fc={}};a.a.extend(a.Q.prototype,{nodeHasBindings:function(b){switch(b.nodeType){case 1:return null!=b.getAttribute("data-bind")||a.g.getComponentNameForNode(b);case 8:return a.f.Tc(b);
|
||||
default:return!1}},getBindings:function(b,c){var d=this.getBindingsString(b,c),d=d?this.parseBindingsString(d,c,b):null;return a.g.Ob(d,b,c,!1)},getBindingAccessors:function(b,c){var d=this.getBindingsString(b,c),d=d?this.parseBindingsString(d,c,b,{valueAccessors:!0}):null;return a.g.Ob(d,b,c,!0)},getBindingsString:function(b){switch(b.nodeType){case 1:return b.getAttribute("data-bind");case 8:return a.f.pd(b);default:return null}},parseBindingsString:function(b,c,d,e){try{var f=this.Fc,g=b+(e&&e.valueAccessors||
|
||||
""),k;if(!(k=f[g])){var l,m="with($context){with($data||{}){return{"+a.h.Ua(b,e)+"}}}";l=new Function("$context","$element",m);k=f[g]=l}return k(c,d)}catch(h){throw h.message="Unable to parse bindings.\nBindings value: "+b+"\nMessage: "+h.message,h;}}});a.Q.instance=new a.Q})();a.b("bindingProvider",a.Q);(function(){function b(a){return function(){return a}}function c(a){return a()}function d(b){return a.a.Ca(a.l.w(b),function(a,c){return function(){return b()[c]}})}function e(c,e,h){return"function"===
|
||||
typeof c?d(c.bind(null,e,h)):a.a.Ca(c,b)}function f(a,b){return d(this.getBindings.bind(this,a,b))}function g(b,c,d){var e,h=a.f.firstChild(c),f=a.Q.instance,m=f.preprocessNode;if(m){for(;e=h;)h=a.f.nextSibling(e),m.call(f,e);h=a.f.firstChild(c)}for(;e=h;)h=a.f.nextSibling(e),k(b,e,d)}function k(b,c,d){var e=!0,h=1===c.nodeType;h&&a.f.kc(c);if(h&&d||a.Q.instance.nodeHasBindings(c))e=m(c,null,b,d).shouldBindDescendants;e&&!r[a.a.A(c)]&&g(b,c,!h)}function l(b){var c=[],d={},e=[];a.a.D(b,function Z(h){if(!d[h]){var f=
|
||||
a.getBindingHandler(h);f&&(f.after&&(e.push(h),a.a.q(f.after,function(c){if(b[c]){if(-1!==a.a.o(e,c))throw Error("Cannot combine the following bindings, because they have a cyclic dependency: "+e.join(", "));Z(c)}}),e.length--),c.push({key:h,fc:f}));d[h]=!0}});return c}function m(b,d,e,h){var m=a.a.e.get(b,q);if(!d){if(m)throw Error("You cannot apply bindings multiple times to the same element.");a.a.e.set(b,q,!0)}!m&&h&&a.tc(b,e);var g;if(d&&"function"!==typeof d)g=d;else{var k=a.Q.instance,r=k.getBindingAccessors||
|
||||
f,p=a.B(function(){(g=d?d(e,b):r.call(k,b,e))&&e.P&&e.P();return g},null,{i:b});g&&p.ba()||(p=null)}var u;if(g){var v=p?function(a){return function(){return c(p()[a])}}:function(a){return g[a]},s=function(){return a.a.Ca(p?p():g,c)};s.get=function(a){return g[a]&&c(v(a))};s.has=function(a){return a in g};h=l(g);a.a.q(h,function(c){var d=c.fc.init,h=c.fc.update,f=c.key;if(8===b.nodeType&&!a.f.Z[f])throw Error("The binding '"+f+"' cannot be used with virtual elements");try{"function"==typeof d&&a.l.w(function(){var a=
|
||||
d(b,v(f),s,e.$data,e);if(a&&a.controlsDescendantBindings){if(u!==n)throw Error("Multiple bindings ("+u+" and "+f+") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");u=f}}),"function"==typeof h&&a.B(function(){h(b,v(f),s,e.$data,e)},null,{i:b})}catch(m){throw m.message='Unable to process binding "'+f+": "+g[f]+'"\nMessage: '+m.message,m;}})}return{shouldBindDescendants:u===n}}function h(b){return b&&b instanceof a.U?b:new a.U(b)}
|
||||
a.d={};var r={script:!0,textarea:!0,template:!0};a.getBindingHandler=function(b){return a.d[b]};a.U=function(b,c,d,e){var h=this,f="function"==typeof b&&!a.H(b),m,g=a.B(function(){var m=f?b():b,l=a.a.c(m);c?(c.P&&c.P(),a.a.extend(h,c),g&&(h.P=g)):(h.$parents=[],h.$root=l,h.ko=a);h.$rawData=m;h.$data=l;d&&(h[d]=l);e&&e(h,c,l);return h.$data},null,{wa:function(){return m&&!a.a.Qb(m)},i:!0});g.ba()&&(h.P=g,g.equalityComparer=null,m=[],g.Ac=function(b){m.push(b);a.a.F.oa(b,function(b){a.a.La(m,b);m.length||
|
||||
(g.k(),h.P=g=n)})})};a.U.prototype.createChildContext=function(b,c,d){return new a.U(b,this,c,function(a,b){a.$parentContext=b;a.$parent=b.$data;a.$parents=(b.$parents||[]).slice(0);a.$parents.unshift(a.$parent);d&&d(a)})};a.U.prototype.extend=function(b){return new a.U(this.P||this.$data,this,null,function(c,d){c.$rawData=d.$rawData;a.a.extend(c,"function"==typeof b?b():b)})};var q=a.a.e.I(),p=a.a.e.I();a.tc=function(b,c){if(2==arguments.length)a.a.e.set(b,p,c),c.P&&c.P.Ac(b);else return a.a.e.get(b,
|
||||
p)};a.Ja=function(b,c,d){1===b.nodeType&&a.f.kc(b);return m(b,c,h(d),!0)};a.Dc=function(b,c,d){d=h(d);return a.Ja(b,e(c,d,b),d)};a.eb=function(a,b){1!==b.nodeType&&8!==b.nodeType||g(h(a),b,!0)};a.Rb=function(a,b){!v&&x.jQuery&&(v=x.jQuery);if(b&&1!==b.nodeType&&8!==b.nodeType)throw Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");b=b||x.document.body;k(h(a),b,!0)};a.kb=function(b){switch(b.nodeType){case 1:case 8:var c=a.tc(b);if(c)return c;
|
||||
if(b.parentNode)return a.kb(b.parentNode)}return n};a.Jc=function(b){return(b=a.kb(b))?b.$data:n};a.b("bindingHandlers",a.d);a.b("applyBindings",a.Rb);a.b("applyBindingsToDescendants",a.eb);a.b("applyBindingAccessorsToNode",a.Ja);a.b("applyBindingsToNode",a.Dc);a.b("contextFor",a.kb);a.b("dataFor",a.Jc)})();(function(b){function c(c,e){var m=f.hasOwnProperty(c)?f[c]:b,h;m?m.X(e):(m=f[c]=new a.J,m.X(e),d(c,function(b,d){var e=!(!d||!d.synchronous);g[c]={definition:b,Zc:e};delete f[c];h||e?m.notifySubscribers(b):
|
||||
a.Y.Wa(function(){m.notifySubscribers(b)})}),h=!0)}function d(a,b){e("getConfig",[a],function(c){c?e("loadComponent",[a,c],function(a){b(a,c)}):b(null,null)})}function e(c,d,f,h){h||(h=a.g.loaders.slice(0));var g=h.shift();if(g){var q=g[c];if(q){var p=!1;if(q.apply(g,d.concat(function(a){p?f(null):null!==a?f(a):e(c,d,f,h)}))!==b&&(p=!0,!g.suppressLoaderExceptions))throw Error("Component loaders must supply values by invoking the callback, not by returning values synchronously.");}else e(c,d,f,h)}else f(null)}
|
||||
var f={},g={};a.g={get:function(d,e){var f=g.hasOwnProperty(d)?g[d]:b;f?f.Zc?a.l.w(function(){e(f.definition)}):a.Y.Wa(function(){e(f.definition)}):c(d,e)},Xb:function(a){delete g[a]},Jb:e};a.g.loaders=[];a.b("components",a.g);a.b("components.get",a.g.get);a.b("components.clearCachedDefinition",a.g.Xb)})();(function(){function b(b,c,d,e){function g(){0===--y&&e(k)}var k={},y=2,t=d.template;d=d.viewModel;t?f(c,t,function(c){a.g.Jb("loadTemplate",[b,c],function(a){k.template=a;g()})}):g();d?f(c,d,function(c){a.g.Jb("loadViewModel",
|
||||
[b,c],function(a){k[l]=a;g()})}):g()}function c(a,b,d){if("function"===typeof b)d(function(a){return new b(a)});else if("function"===typeof b[l])d(b[l]);else if("instance"in b){var e=b.instance;d(function(){return e})}else"viewModel"in b?c(a,b.viewModel,d):a("Unknown viewModel value: "+b)}function d(b){switch(a.a.A(b)){case "script":return a.a.ma(b.text);case "textarea":return a.a.ma(b.value);case "template":if(e(b.content))return a.a.ua(b.content.childNodes)}return a.a.ua(b.childNodes)}function e(a){return x.DocumentFragment?
|
||||
a instanceof DocumentFragment:a&&11===a.nodeType}function f(a,b,c){"string"===typeof b.require?O||x.require?(O||x.require)([b.require],c):a("Uses require, but no AMD loader is present"):c(b)}function g(a){return function(b){throw Error("Component '"+a+"': "+b);}}var k={};a.g.register=function(b,c){if(!c)throw Error("Invalid configuration for "+b);if(a.g.ub(b))throw Error("Component "+b+" is already registered");k[b]=c};a.g.ub=function(a){return k.hasOwnProperty(a)};a.g.od=function(b){delete k[b];
|
||||
a.g.Xb(b)};a.g.Zb={getConfig:function(a,b){b(k.hasOwnProperty(a)?k[a]:null)},loadComponent:function(a,c,d){var e=g(a);f(e,c,function(c){b(a,e,c,d)})},loadTemplate:function(b,c,f){b=g(b);if("string"===typeof c)f(a.a.ma(c));else if(c instanceof Array)f(c);else if(e(c))f(a.a.V(c.childNodes));else if(c.element)if(c=c.element,x.HTMLElement?c instanceof HTMLElement:c&&c.tagName&&1===c.nodeType)f(d(c));else if("string"===typeof c){var l=u.getElementById(c);l?f(d(l)):b("Cannot find element with ID "+c)}else b("Unknown element type: "+
|
||||
c);else b("Unknown template value: "+c)},loadViewModel:function(a,b,d){c(g(a),b,d)}};var l="createViewModel";a.b("components.register",a.g.register);a.b("components.isRegistered",a.g.ub);a.b("components.unregister",a.g.od);a.b("components.defaultLoader",a.g.Zb);a.g.loaders.push(a.g.Zb);a.g.Bc=k})();(function(){function b(b,e){var f=b.getAttribute("params");if(f){var f=c.parseBindingsString(f,e,b,{valueAccessors:!0,bindingParams:!0}),f=a.a.Ca(f,function(c){return a.m(c,null,{i:b})}),g=a.a.Ca(f,function(c){var e=
|
||||
c.t();return c.ba()?a.m({read:function(){return a.a.c(c())},write:a.Ba(e)&&function(a){c()(a)},i:b}):e});g.hasOwnProperty("$raw")||(g.$raw=f);return g}return{$raw:{}}}a.g.getComponentNameForNode=function(b){var c=a.a.A(b);if(a.g.ub(c)&&(-1!=c.indexOf("-")||"[object HTMLUnknownElement]"==""+b||8>=a.a.C&&b.tagName===c))return c};a.g.Ob=function(c,e,f,g){if(1===e.nodeType){var k=a.g.getComponentNameForNode(e);if(k){c=c||{};if(c.component)throw Error('Cannot use the "component" binding on a custom element matching a component');
|
||||
var l={name:k,params:b(e,f)};c.component=g?function(){return l}:l}}return c};var c=new a.Q;9>a.a.C&&(a.g.register=function(a){return function(b){u.createElement(b);return a.apply(this,arguments)}}(a.g.register),u.createDocumentFragment=function(b){return function(){var c=b(),f=a.g.Bc,g;for(g in f)f.hasOwnProperty(g)&&c.createElement(g);return c}}(u.createDocumentFragment))})();(function(b){function c(b,c,d){c=c.template;if(!c)throw Error("Component '"+b+"' has no template");b=a.a.ua(c);a.f.da(d,b)}
|
||||
function d(a,b,c,d){var e=a.createViewModel;return e?e.call(a,d,{element:b,templateNodes:c}):d}var e=0;a.d.component={init:function(f,g,k,l,m){function h(){var a=r&&r.dispose;"function"===typeof a&&a.call(r);q=r=null}var r,q,p=a.a.V(a.f.childNodes(f));a.a.F.oa(f,h);a.m(function(){var l=a.a.c(g()),k,t;"string"===typeof l?k=l:(k=a.a.c(l.name),t=a.a.c(l.params));if(!k)throw Error("No component name specified");var n=q=++e;a.g.get(k,function(e){if(q===n){h();if(!e)throw Error("Unknown component '"+k+
|
||||
"'");c(k,e,f);var g=d(e,f,p,t);e=m.createChildContext(g,b,function(a){a.$component=g;a.$componentTemplateNodes=p});r=g;a.eb(e,f)}})},null,{i:f});return{controlsDescendantBindings:!0}}};a.f.Z.component=!0})();var S={"class":"className","for":"htmlFor"};a.d.attr={update:function(b,c){var d=a.a.c(c())||{};a.a.D(d,function(c,d){d=a.a.c(d);var g=!1===d||null===d||d===n;g&&b.removeAttribute(c);8>=a.a.C&&c in S?(c=S[c],g?b.removeAttribute(c):b[c]=d):g||b.setAttribute(c,d.toString());"name"===c&&a.a.rc(b,
|
||||
g?"":d.toString())})}};(function(){a.d.checked={after:["value","attr"],init:function(b,c,d){function e(){var e=b.checked,f=p?g():e;if(!a.va.Sa()&&(!l||e)){var m=a.l.w(c);if(h){var k=r?m.t():m;q!==f?(e&&(a.a.pa(k,f,!0),a.a.pa(k,q,!1)),q=f):a.a.pa(k,f,e);r&&a.Ba(m)&&m(k)}else a.h.Ea(m,d,"checked",f,!0)}}function f(){var d=a.a.c(c());b.checked=h?0<=a.a.o(d,g()):k?d:g()===d}var g=a.nc(function(){return d.has("checkedValue")?a.a.c(d.get("checkedValue")):d.has("value")?a.a.c(d.get("value")):b.value}),k=
|
||||
"checkbox"==b.type,l="radio"==b.type;if(k||l){var m=c(),h=k&&a.a.c(m)instanceof Array,r=!(h&&m.push&&m.splice),q=h?g():n,p=l||h;l&&!b.name&&a.d.uniqueName.init(b,function(){return!0});a.m(e,null,{i:b});a.a.p(b,"click",e);a.m(f,null,{i:b});m=n}}};a.h.ea.checked=!0;a.d.checkedValue={update:function(b,c){b.value=a.a.c(c())}}})();a.d.css={update:function(b,c){var d=a.a.c(c());null!==d&&"object"==typeof d?a.a.D(d,function(c,d){d=a.a.c(d);a.a.bb(b,c,d)}):(d=a.a.$a(String(d||"")),a.a.bb(b,b.__ko__cssValue,
|
||||
!1),b.__ko__cssValue=d,a.a.bb(b,d,!0))}};a.d.enable={update:function(b,c){var d=a.a.c(c());d&&b.disabled?b.removeAttribute("disabled"):d||b.disabled||(b.disabled=!0)}};a.d.disable={update:function(b,c){a.d.enable.update(b,function(){return!a.a.c(c())})}};a.d.event={init:function(b,c,d,e,f){var g=c()||{};a.a.D(g,function(g){"string"==typeof g&&a.a.p(b,g,function(b){var m,h=c()[g];if(h){try{var r=a.a.V(arguments);e=f.$data;r.unshift(e);m=h.apply(e,r)}finally{!0!==m&&(b.preventDefault?b.preventDefault():
|
||||
b.returnValue=!1)}!1===d.get(g+"Bubble")&&(b.cancelBubble=!0,b.stopPropagation&&b.stopPropagation())}})})}};a.d.foreach={ic:function(b){return function(){var c=b(),d=a.a.zb(c);if(!d||"number"==typeof d.length)return{foreach:c,templateEngine:a.W.sb};a.a.c(c);return{foreach:d.data,as:d.as,includeDestroyed:d.includeDestroyed,afterAdd:d.afterAdd,beforeRemove:d.beforeRemove,afterRender:d.afterRender,beforeMove:d.beforeMove,afterMove:d.afterMove,templateEngine:a.W.sb}}},init:function(b,c){return a.d.template.init(b,
|
||||
a.d.foreach.ic(c))},update:function(b,c,d,e,f){return a.d.template.update(b,a.d.foreach.ic(c),d,e,f)}};a.h.ta.foreach=!1;a.f.Z.foreach=!0;a.d.hasfocus={init:function(b,c,d){function e(e){b.__ko_hasfocusUpdating=!0;var f=b.ownerDocument;if("activeElement"in f){var g;try{g=f.activeElement}catch(h){g=f.body}e=g===b}f=c();a.h.Ea(f,d,"hasfocus",e,!0);b.__ko_hasfocusLastValue=e;b.__ko_hasfocusUpdating=!1}var f=e.bind(null,!0),g=e.bind(null,!1);a.a.p(b,"focus",f);a.a.p(b,"focusin",f);a.a.p(b,"blur",g);a.a.p(b,
|
||||
"focusout",g)},update:function(b,c){var d=!!a.a.c(c());b.__ko_hasfocusUpdating||b.__ko_hasfocusLastValue===d||(d?b.focus():b.blur(),!d&&b.__ko_hasfocusLastValue&&b.ownerDocument.body.focus(),a.l.w(a.a.Da,null,[b,d?"focusin":"focusout"]))}};a.h.ea.hasfocus=!0;a.d.hasFocus=a.d.hasfocus;a.h.ea.hasFocus=!0;a.d.html={init:function(){return{controlsDescendantBindings:!0}},update:function(b,c){a.a.Cb(b,c())}};K("if");K("ifnot",!1,!0);K("with",!0,!1,function(a,c){return a.createChildContext(c)});var L={};
|
||||
a.d.options={init:function(b){if("select"!==a.a.A(b))throw Error("options binding applies only to SELECT elements");for(;0<b.length;)b.remove(0);return{controlsDescendantBindings:!0}},update:function(b,c,d){function e(){return a.a.Ka(b.options,function(a){return a.selected})}function f(a,b,c){var d=typeof b;return"function"==d?b(a):"string"==d?a[b]:c}function g(c,e){if(A&&h)a.j.ha(b,a.a.c(d.get("value")),!0);else if(p.length){var f=0<=a.a.o(p,a.j.u(e[0]));a.a.sc(e[0],f);A&&!f&&a.l.w(a.a.Da,null,[b,
|
||||
"change"])}}var k=b.multiple,l=0!=b.length&&k?b.scrollTop:null,m=a.a.c(c()),h=d.get("valueAllowUnset")&&d.has("value"),r=d.get("optionsIncludeDestroyed");c={};var q,p=[];h||(k?p=a.a.fb(e(),a.j.u):0<=b.selectedIndex&&p.push(a.j.u(b.options[b.selectedIndex])));m&&("undefined"==typeof m.length&&(m=[m]),q=a.a.Ka(m,function(b){return r||b===n||null===b||!a.a.c(b._destroy)}),d.has("optionsCaption")&&(m=a.a.c(d.get("optionsCaption")),null!==m&&m!==n&&q.unshift(L)));var A=!1;c.beforeRemove=function(a){b.removeChild(a)};
|
||||
m=g;d.has("optionsAfterRender")&&"function"==typeof d.get("optionsAfterRender")&&(m=function(b,c){g(0,c);a.l.w(d.get("optionsAfterRender"),null,[c[0],b!==L?b:n])});a.a.Bb(b,q,function(c,e,g){g.length&&(p=!h&&g[0].selected?[a.j.u(g[0])]:[],A=!0);e=b.ownerDocument.createElement("option");c===L?(a.a.Za(e,d.get("optionsCaption")),a.j.ha(e,n)):(g=f(c,d.get("optionsValue"),c),a.j.ha(e,a.a.c(g)),c=f(c,d.get("optionsText"),g),a.a.Za(e,c));return[e]},c,m);a.l.w(function(){h?a.j.ha(b,a.a.c(d.get("value")),
|
||||
!0):(k?p.length&&e().length<p.length:p.length&&0<=b.selectedIndex?a.j.u(b.options[b.selectedIndex])!==p[0]:p.length||0<=b.selectedIndex)&&a.a.Da(b,"change")});a.a.Nc(b);l&&20<Math.abs(l-b.scrollTop)&&(b.scrollTop=l)}};a.d.options.xb=a.a.e.I();a.d.selectedOptions={after:["options","foreach"],init:function(b,c,d){a.a.p(b,"change",function(){var e=c(),f=[];a.a.q(b.getElementsByTagName("option"),function(b){b.selected&&f.push(a.j.u(b))});a.h.Ea(e,d,"selectedOptions",f)})},update:function(b,c){if("select"!=
|
||||
a.a.A(b))throw Error("values binding applies only to SELECT elements");var d=a.a.c(c()),e=b.scrollTop;d&&"number"==typeof d.length&&a.a.q(b.getElementsByTagName("option"),function(b){var c=0<=a.a.o(d,a.j.u(b));b.selected!=c&&a.a.sc(b,c)});b.scrollTop=e}};a.h.ea.selectedOptions=!0;a.d.style={update:function(b,c){var d=a.a.c(c()||{});a.a.D(d,function(c,d){d=a.a.c(d);if(null===d||d===n||!1===d)d="";b.style[c]=d})}};a.d.submit={init:function(b,c,d,e,f){if("function"!=typeof c())throw Error("The value for a submit binding must be a function");
|
||||
a.a.p(b,"submit",function(a){var d,e=c();try{d=e.call(f.$data,b)}finally{!0!==d&&(a.preventDefault?a.preventDefault():a.returnValue=!1)}})}};a.d.text={init:function(){return{controlsDescendantBindings:!0}},update:function(b,c){a.a.Za(b,c())}};a.f.Z.text=!0;(function(){if(x&&x.navigator)var b=function(a){if(a)return parseFloat(a[1])},c=x.opera&&x.opera.version&&parseInt(x.opera.version()),d=x.navigator.userAgent,e=b(d.match(/^(?:(?!chrome).)*version\/([^ ]*) safari/i)),f=b(d.match(/Firefox\/([^ ]*)/));
|
||||
if(10>a.a.C)var g=a.a.e.I(),k=a.a.e.I(),l=function(b){var c=this.activeElement;(c=c&&a.a.e.get(c,k))&&c(b)},m=function(b,c){var d=b.ownerDocument;a.a.e.get(d,g)||(a.a.e.set(d,g,!0),a.a.p(d,"selectionchange",l));a.a.e.set(b,k,c)};a.d.textInput={init:function(b,d,g){function l(c,d){a.a.p(b,c,d)}function k(){var c=a.a.c(d());if(null===c||c===n)c="";v!==n&&c===v?a.a.setTimeout(k,4):b.value!==c&&(u=c,b.value=c)}function y(){s||(v=b.value,s=a.a.setTimeout(t,4))}function t(){clearTimeout(s);v=s=n;var c=
|
||||
b.value;u!==c&&(u=c,a.h.Ea(d(),g,"textInput",c))}var u=b.value,s,v,x=9==a.a.C?y:t;10>a.a.C?(l("propertychange",function(a){"value"===a.propertyName&&x(a)}),8==a.a.C&&(l("keyup",t),l("keydown",t)),8<=a.a.C&&(m(b,x),l("dragend",y))):(l("input",t),5>e&&"textarea"===a.a.A(b)?(l("keydown",y),l("paste",y),l("cut",y)):11>c?l("keydown",y):4>f&&(l("DOMAutoComplete",t),l("dragdrop",t),l("drop",t)));l("change",t);a.m(k,null,{i:b})}};a.h.ea.textInput=!0;a.d.textinput={preprocess:function(a,b,c){c("textInput",
|
||||
a)}}})();a.d.uniqueName={init:function(b,c){if(c()){var d="ko_unique_"+ ++a.d.uniqueName.Ic;a.a.rc(b,d)}}};a.d.uniqueName.Ic=0;a.d.value={after:["options","foreach"],init:function(b,c,d){if("input"!=b.tagName.toLowerCase()||"checkbox"!=b.type&&"radio"!=b.type){var e=["change"],f=d.get("valueUpdate"),g=!1,k=null;f&&("string"==typeof f&&(f=[f]),a.a.ra(e,f),e=a.a.Tb(e));var l=function(){k=null;g=!1;var e=c(),f=a.j.u(b);a.h.Ea(e,d,"value",f)};!a.a.C||"input"!=b.tagName.toLowerCase()||"text"!=b.type||
|
||||
"off"==b.autocomplete||b.form&&"off"==b.form.autocomplete||-1!=a.a.o(e,"propertychange")||(a.a.p(b,"propertychange",function(){g=!0}),a.a.p(b,"focus",function(){g=!1}),a.a.p(b,"blur",function(){g&&l()}));a.a.q(e,function(c){var d=l;a.a.nd(c,"after")&&(d=function(){k=a.j.u(b);a.a.setTimeout(l,0)},c=c.substring(5));a.a.p(b,c,d)});var m=function(){var e=a.a.c(c()),f=a.j.u(b);if(null!==k&&e===k)a.a.setTimeout(m,0);else if(e!==f)if("select"===a.a.A(b)){var g=d.get("valueAllowUnset"),f=function(){a.j.ha(b,
|
||||
e,g)};f();g||e===a.j.u(b)?a.a.setTimeout(f,0):a.l.w(a.a.Da,null,[b,"change"])}else a.j.ha(b,e)};a.m(m,null,{i:b})}else a.Ja(b,{checkedValue:c})},update:function(){}};a.h.ea.value=!0;a.d.visible={update:function(b,c){var d=a.a.c(c()),e="none"!=b.style.display;d&&!e?b.style.display="":!d&&e&&(b.style.display="none")}};(function(b){a.d[b]={init:function(c,d,e,f,g){return a.d.event.init.call(this,c,function(){var a={};a[b]=d();return a},e,f,g)}}})("click");a.O=function(){};a.O.prototype.renderTemplateSource=
|
||||
function(){throw Error("Override renderTemplateSource");};a.O.prototype.createJavaScriptEvaluatorBlock=function(){throw Error("Override createJavaScriptEvaluatorBlock");};a.O.prototype.makeTemplateSource=function(b,c){if("string"==typeof b){c=c||u;var d=c.getElementById(b);if(!d)throw Error("Cannot find template with ID "+b);return new a.v.n(d)}if(1==b.nodeType||8==b.nodeType)return new a.v.qa(b);throw Error("Unknown template type: "+b);};a.O.prototype.renderTemplate=function(a,c,d,e){a=this.makeTemplateSource(a,
|
||||
e);return this.renderTemplateSource(a,c,d,e)};a.O.prototype.isTemplateRewritten=function(a,c){return!1===this.allowTemplateRewriting?!0:this.makeTemplateSource(a,c).data("isRewritten")};a.O.prototype.rewriteTemplate=function(a,c,d){a=this.makeTemplateSource(a,d);c=c(a.text());a.text(c);a.data("isRewritten",!0)};a.b("templateEngine",a.O);a.Gb=function(){function b(b,c,d,k){b=a.h.yb(b);for(var l=a.h.ta,m=0;m<b.length;m++){var h=b[m].key;if(l.hasOwnProperty(h)){var r=l[h];if("function"===typeof r){if(h=
|
||||
r(b[m].value))throw Error(h);}else if(!r)throw Error("This template engine does not support the '"+h+"' binding within its templates");}}d="ko.__tr_ambtns(function($context,$element){return(function(){return{ "+a.h.Ua(b,{valueAccessors:!0})+" } })()},'"+d.toLowerCase()+"')";return k.createJavaScriptEvaluatorBlock(d)+c}var c=/(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'|[^>]*))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi,d=/\x3c!--\s*ko\b\s*([\s\S]*?)\s*--\x3e/g;return{Oc:function(b,
|
||||
c,d){c.isTemplateRewritten(b,d)||c.rewriteTemplate(b,function(b){return a.Gb.dd(b,c)},d)},dd:function(a,f){return a.replace(c,function(a,c,d,e,h){return b(h,c,d,f)}).replace(d,function(a,c){return b(c,"\x3c!-- ko --\x3e","#comment",f)})},Ec:function(b,c){return a.M.wb(function(d,k){var l=d.nextSibling;l&&l.nodeName.toLowerCase()===c&&a.Ja(l,b,k)})}}}();a.b("__tr_ambtns",a.Gb.Ec);(function(){a.v={};a.v.n=function(b){if(this.n=b){var c=a.a.A(b);this.ab="script"===c?1:"textarea"===c?2:"template"==c&&
|
||||
b.content&&11===b.content.nodeType?3:4}};a.v.n.prototype.text=function(){var b=1===this.ab?"text":2===this.ab?"value":"innerHTML";if(0==arguments.length)return this.n[b];var c=arguments[0];"innerHTML"===b?a.a.Cb(this.n,c):this.n[b]=c};var b=a.a.e.I()+"_";a.v.n.prototype.data=function(c){if(1===arguments.length)return a.a.e.get(this.n,b+c);a.a.e.set(this.n,b+c,arguments[1])};var c=a.a.e.I();a.v.n.prototype.nodes=function(){var b=this.n;if(0==arguments.length)return(a.a.e.get(b,c)||{}).jb||(3===this.ab?
|
||||
b.content:4===this.ab?b:n);a.a.e.set(b,c,{jb:arguments[0]})};a.v.qa=function(a){this.n=a};a.v.qa.prototype=new a.v.n;a.v.qa.prototype.text=function(){if(0==arguments.length){var b=a.a.e.get(this.n,c)||{};b.Hb===n&&b.jb&&(b.Hb=b.jb.innerHTML);return b.Hb}a.a.e.set(this.n,c,{Hb:arguments[0]})};a.b("templateSources",a.v);a.b("templateSources.domElement",a.v.n);a.b("templateSources.anonymousTemplate",a.v.qa)})();(function(){function b(b,c,d){var e;for(c=a.f.nextSibling(c);b&&(e=b)!==c;)b=a.f.nextSibling(e),
|
||||
d(e,b)}function c(c,d){if(c.length){var e=c[0],f=c[c.length-1],g=e.parentNode,k=a.Q.instance,n=k.preprocessNode;if(n){b(e,f,function(a,b){var c=a.previousSibling,d=n.call(k,a);d&&(a===e&&(e=d[0]||b),a===f&&(f=d[d.length-1]||c))});c.length=0;if(!e)return;e===f?c.push(e):(c.push(e,f),a.a.za(c,g))}b(e,f,function(b){1!==b.nodeType&&8!==b.nodeType||a.Rb(d,b)});b(e,f,function(b){1!==b.nodeType&&8!==b.nodeType||a.M.yc(b,[d])});a.a.za(c,g)}}function d(a){return a.nodeType?a:0<a.length?a[0]:null}function e(b,
|
||||
e,f,k,q){q=q||{};var p=(b&&d(b)||f||{}).ownerDocument,n=q.templateEngine||g;a.Gb.Oc(f,n,p);f=n.renderTemplate(f,k,q,p);if("number"!=typeof f.length||0<f.length&&"number"!=typeof f[0].nodeType)throw Error("Template engine must return an array of DOM nodes");p=!1;switch(e){case "replaceChildren":a.f.da(b,f);p=!0;break;case "replaceNode":a.a.qc(b,f);p=!0;break;case "ignoreTargetNode":break;default:throw Error("Unknown renderMode: "+e);}p&&(c(f,k),q.afterRender&&a.l.w(q.afterRender,null,[f,k.$data]));
|
||||
return f}function f(b,c,d){return a.H(b)?b():"function"===typeof b?b(c,d):b}var g;a.Db=function(b){if(b!=n&&!(b instanceof a.O))throw Error("templateEngine must inherit from ko.templateEngine");g=b};a.Ab=function(b,c,h,k,q){h=h||{};if((h.templateEngine||g)==n)throw Error("Set a template engine before calling renderTemplate");q=q||"replaceChildren";if(k){var p=d(k);return a.B(function(){var g=c&&c instanceof a.U?c:new a.U(a.a.c(c)),n=f(b,g.$data,g),g=e(k,q,n,g,h);"replaceNode"==q&&(k=g,p=d(k))},null,
|
||||
{wa:function(){return!p||!a.a.nb(p)},i:p&&"replaceNode"==q?p.parentNode:p})}return a.M.wb(function(d){a.Ab(b,c,h,d,"replaceNode")})};a.kd=function(b,d,g,k,q){function p(a,b){c(b,s);g.afterRender&&g.afterRender(b,a);s=null}function u(a,c){s=q.createChildContext(a,g.as,function(a){a.$index=c});var d=f(b,a,s);return e(null,"ignoreTargetNode",d,s,g)}var s;return a.B(function(){var b=a.a.c(d)||[];"undefined"==typeof b.length&&(b=[b]);b=a.a.Ka(b,function(b){return g.includeDestroyed||b===n||null===b||!a.a.c(b._destroy)});
|
||||
a.l.w(a.a.Bb,null,[k,b,u,g,p])},null,{i:k})};var k=a.a.e.I();a.d.template={init:function(b,c){var d=a.a.c(c());if("string"==typeof d||d.name)a.f.xa(b);else{if("nodes"in d){if(d=d.nodes||[],a.H(d))throw Error('The "nodes" option must be a plain, non-observable array.');}else d=a.f.childNodes(b);d=a.a.jc(d);(new a.v.qa(b)).nodes(d)}return{controlsDescendantBindings:!0}},update:function(b,c,d,e,f){var g=c(),s;c=a.a.c(g);d=!0;e=null;"string"==typeof c?c={}:(g=c.name,"if"in c&&(d=a.a.c(c["if"])),d&&"ifnot"in
|
||||
c&&(d=!a.a.c(c.ifnot)),s=a.a.c(c.data));"foreach"in c?e=a.kd(g||b,d&&c.foreach||[],c,b,f):d?(f="data"in c?f.createChildContext(s,c.as):f,e=a.Ab(g||b,f,c,b)):a.f.xa(b);f=e;(s=a.a.e.get(b,k))&&"function"==typeof s.k&&s.k();a.a.e.set(b,k,f&&f.ba()?f:n)}};a.h.ta.template=function(b){b=a.h.yb(b);return 1==b.length&&b[0].unknown||a.h.ad(b,"name")?null:"This template engine does not support anonymous templates nested within its templates"};a.f.Z.template=!0})();a.b("setTemplateEngine",a.Db);a.b("renderTemplate",
|
||||
a.Ab);a.a.dc=function(a,c,d){if(a.length&&c.length){var e,f,g,k,l;for(e=f=0;(!d||e<d)&&(k=a[f]);++f){for(g=0;l=c[g];++g)if(k.value===l.value){k.moved=l.index;l.moved=k.index;c.splice(g,1);e=g=0;break}e+=g}}};a.a.ib=function(){function b(b,d,e,f,g){var k=Math.min,l=Math.max,m=[],h,n=b.length,q,p=d.length,s=p-n||1,u=n+p+1,t,v,x;for(h=0;h<=n;h++)for(v=t,m.push(t=[]),x=k(p,h+s),q=l(0,h-1);q<=x;q++)t[q]=q?h?b[h-1]===d[q-1]?v[q-1]:k(v[q]||u,t[q-1]||u)+1:q+1:h+1;k=[];l=[];s=[];h=n;for(q=p;h||q;)p=m[h][q]-
|
||||
1,q&&p===m[h][q-1]?l.push(k[k.length]={status:e,value:d[--q],index:q}):h&&p===m[h-1][q]?s.push(k[k.length]={status:f,value:b[--h],index:h}):(--q,--h,g.sparse||k.push({status:"retained",value:d[q]}));a.a.dc(s,l,!g.dontLimitMoves&&10*n);return k.reverse()}return function(a,d,e){e="boolean"===typeof e?{dontLimitMoves:e}:e||{};a=a||[];d=d||[];return a.length<d.length?b(a,d,"added","deleted",e):b(d,a,"deleted","added",e)}}();a.b("utils.compareArrays",a.a.ib);(function(){function b(b,c,d,k,l){var m=[],
|
||||
h=a.B(function(){var h=c(d,l,a.a.za(m,b))||[];0<m.length&&(a.a.qc(m,h),k&&a.l.w(k,null,[d,h,l]));m.length=0;a.a.ra(m,h)},null,{i:b,wa:function(){return!a.a.Qb(m)}});return{ca:m,B:h.ba()?h:n}}var c=a.a.e.I(),d=a.a.e.I();a.a.Bb=function(e,f,g,k,l){function m(b,c){w=q[c];v!==c&&(D[b]=w);w.qb(v++);a.a.za(w.ca,e);u.push(w);z.push(w)}function h(b,c){if(b)for(var d=0,e=c.length;d<e;d++)c[d]&&a.a.q(c[d].ca,function(a){b(a,d,c[d].ja)})}f=f||[];k=k||{};var r=a.a.e.get(e,c)===n,q=a.a.e.get(e,c)||[],p=a.a.fb(q,
|
||||
function(a){return a.ja}),s=a.a.ib(p,f,k.dontLimitMoves),u=[],t=0,v=0,x=[],z=[];f=[];for(var D=[],p=[],w,C=0,B,E;B=s[C];C++)switch(E=B.moved,B.status){case "deleted":E===n&&(w=q[t],w.B&&(w.B.k(),w.B=n),a.a.za(w.ca,e).length&&(k.beforeRemove&&(u.push(w),z.push(w),w.ja===d?w=null:f[C]=w),w&&x.push.apply(x,w.ca)));t++;break;case "retained":m(C,t++);break;case "added":E!==n?m(C,E):(w={ja:B.value,qb:a.N(v++)},u.push(w),z.push(w),r||(p[C]=w))}a.a.e.set(e,c,u);h(k.beforeMove,D);a.a.q(x,k.beforeRemove?a.$:
|
||||
a.removeNode);for(var C=0,r=a.f.firstChild(e),F;w=z[C];C++){w.ca||a.a.extend(w,b(e,g,w.ja,l,w.qb));for(t=0;s=w.ca[t];r=s.nextSibling,F=s,t++)s!==r&&a.f.gc(e,s,F);!w.Wc&&l&&(l(w.ja,w.ca,w.qb),w.Wc=!0)}h(k.beforeRemove,f);for(C=0;C<f.length;++C)f[C]&&(f[C].ja=d);h(k.afterMove,D);h(k.afterAdd,p)}})();a.b("utils.setDomNodeChildrenFromArrayMapping",a.a.Bb);a.W=function(){this.allowTemplateRewriting=!1};a.W.prototype=new a.O;a.W.prototype.renderTemplateSource=function(b,c,d,e){if(c=(9>a.a.C?0:b.nodes)?
|
||||
b.nodes():null)return a.a.V(c.cloneNode(!0).childNodes);b=b.text();return a.a.ma(b,e)};a.W.sb=new a.W;a.Db(a.W.sb);a.b("nativeTemplateEngine",a.W);(function(){a.vb=function(){var a=this.$c=function(){if(!v||!v.tmpl)return 0;try{if(0<=v.tmpl.tag.tmpl.open.toString().indexOf("__"))return 2}catch(a){}return 1}();this.renderTemplateSource=function(b,e,f,g){g=g||u;f=f||{};if(2>a)throw Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");var k=b.data("precompiled");
|
||||
k||(k=b.text()||"",k=v.template(null,"{{ko_with $item.koBindingContext}}"+k+"{{/ko_with}}"),b.data("precompiled",k));b=[e.$data];e=v.extend({koBindingContext:e},f.templateOptions);e=v.tmpl(k,b,e);e.appendTo(g.createElement("div"));v.fragments={};return e};this.createJavaScriptEvaluatorBlock=function(a){return"{{ko_code ((function() { return "+a+" })()) }}"};this.addTemplate=function(a,b){u.write("<script type='text/html' id='"+a+"'>"+b+"\x3c/script>")};0<a&&(v.tmpl.tag.ko_code={open:"__.push($1 || '');"},
|
||||
v.tmpl.tag.ko_with={open:"with($1) {",close:"} "})};a.vb.prototype=new a.O;var b=new a.vb;0<b.$c&&a.Db(b);a.b("jqueryTmplTemplateEngine",a.vb)})()})})();})();
|
||||
@@ -1,85 +0,0 @@
|
||||
// Knockout JavaScript library v2.2.1
|
||||
// (c) Steven Sanderson - http://knockoutjs.com/
|
||||
// License: MIT (http://www.opensource.org/licenses/mit-license.php)
|
||||
|
||||
(function() {function j(w){throw w;}var m=!0,p=null,r=!1;function u(w){return function(){return w}};var x=window,y=document,ga=navigator,F=window.jQuery,I=void 0;
|
||||
function L(w){function ha(a,d,c,e,f){var g=[];a=b.j(function(){var a=d(c,f)||[];0<g.length&&(b.a.Ya(M(g),a),e&&b.r.K(e,p,[c,a,f]));g.splice(0,g.length);b.a.P(g,a)},p,{W:a,Ka:function(){return 0==g.length||!b.a.X(g[0])}});return{M:g,j:a.pa()?a:I}}function M(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 S(a,b,c,e,f){var g=Math.min,
|
||||
h=Math.max,k=[],l,n=a.length,q,s=b.length,v=s-n||1,G=n+s+1,J,A,z;for(l=0;l<=n;l++){A=J;k.push(J=[]);z=g(s,l+v);for(q=h(0,l-1);q<=z;q++)J[q]=q?l?a[l-1]===b[q-1]?A[q-1]:g(A[q]||G,J[q-1]||G)+1:q+1:l+1}g=[];h=[];v=[];l=n;for(q=s;l||q;)s=k[l][q]-1,q&&s===k[l][q-1]?h.push(g[g.length]={status:c,value:b[--q],index:q}):l&&s===k[l-1][q]?v.push(g[g.length]={status:e,value:a[--l],index:l}):(g.push({status:"retained",value:b[--q]}),--l);if(h.length&&v.length){a=10*n;var t;for(b=c=0;(f||b<a)&&(t=h[c]);c++){for(e=
|
||||
0;k=v[e];e++)if(t.value===k.value){t.moved=k.index;k.moved=t.index;v.splice(e,1);b=e=0;break}b+=e}}return g.reverse()}function T(a,d,c,e,f){f=f||{};var g=a&&N(a),g=g&&g.ownerDocument,h=f.templateEngine||O;b.za.vb(c,h,g);c=h.renderTemplate(c,e,f,g);("number"!=typeof c.length||0<c.length&&"number"!=typeof c[0].nodeType)&&j(Error("Template engine must return an array of DOM nodes"));g=r;switch(d){case "replaceChildren":b.e.N(a,c);g=m;break;case "replaceNode":b.a.Ya(a,c);g=m;break;case "ignoreTargetNode":break;
|
||||
default:j(Error("Unknown renderMode: "+d))}g&&(U(c,e),f.afterRender&&b.r.K(f.afterRender,p,[c,e.$data]));return c}function N(a){return a.nodeType?a:0<a.length?a[0]:p}function U(a,d){if(a.length){var c=a[0],e=a[a.length-1];V(c,e,function(a){b.Da(d,a)});V(c,e,function(a){b.s.ib(a,[d])})}}function V(a,d,c){var e;for(d=b.e.nextSibling(d);a&&(e=a)!==d;)a=b.e.nextSibling(e),(1===e.nodeType||8===e.nodeType)&&c(e)}function W(a,d,c){a=b.g.aa(a);for(var 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))&&j(Error(g)):h||j(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 X(a,d,c,e){function f(a){return function(){return k[a]}}function g(){return k}var h=0,k,l;b.j(function(){var n=c&&c instanceof b.z?c:new b.z(b.a.d(c)),q=n.$data;e&&b.eb(a,n);if(k=("function"==typeof d?
|
||||
d(n,a):d)||b.J.instance.getBindings(a,n)){if(0===h){h=1;for(var s in k){var v=b.c[s];v&&8===a.nodeType&&!b.e.I[s]&&j(Error("The binding '"+s+"' cannot be used with virtual elements"));if(v&&"function"==typeof v.init&&(v=(0,v.init)(a,f(s),g,q,n))&&v.controlsDescendantBindings)l!==I&&j(Error("Multiple bindings ("+l+" and "+s+") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.")),l=s}h=2}if(2===h)for(s in k)(v=b.c[s])&&"function"==
|
||||
typeof v.update&&(0,v.update)(a,f(s),g,q,n)}},p,{W:a});return{Nb:l===I}}function Y(a,d,c){var e=m,f=1===d.nodeType;f&&b.e.Ta(d);if(f&&c||b.J.instance.nodeHasBindings(d))e=X(d,p,a,c).Nb;e&&Z(a,d,!f)}function Z(a,d,c){for(var e=b.e.firstChild(d);d=e;)e=b.e.nextSibling(d),Y(a,d,c)}function $(a,b){var c=aa(a,b);return c?0<c.length?c[c.length-1].nextSibling:a.nextSibling:p}function aa(a,b){for(var c=a,e=1,f=[];c=c.nextSibling;){if(H(c)&&(e--,0===e))return f;f.push(c);B(c)&&e++}b||j(Error("Cannot find closing comment tag to match: "+
|
||||
a.nodeValue));return p}function H(a){return 8==a.nodeType&&(K?a.text:a.nodeValue).match(ia)}function B(a){return 8==a.nodeType&&(K?a.text:a.nodeValue).match(ja)}function P(a,b){for(var c=p;a!=c;)c=a,a=a.replace(ka,function(a,c){return b[c]});return a}function la(){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]:I}}function ba(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!==I?h:ba(g,b,c)}}c=c||new la;a=b(a);if(!("object"==typeof a&&a!==p&&a!==I&&!(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 ca(a,d){if(a)if(8==a.nodeType){var c=b.s.Ua(a.nodeValue);c!=p&&d.push({sb:a,Fb:c})}else if(1==a.nodeType)for(var c=0,e=a.childNodes,f=e.length;c<f;c++)ca(e[c],
|
||||
d)}function Q(a,d,c,e){b.c[a]={init:function(a){b.a.f.set(a,da,{});return{controlsDescendantBindings:m}},update:function(a,g,h,k,l){h=b.a.f.get(a,da);g=b.a.d(g());k=!c!==!g;var n=!h.Za;if(n||d||k!==h.qb)n&&(h.Za=b.a.Ia(b.e.childNodes(a),m)),k?(n||b.e.N(a,b.a.Ia(h.Za)),b.Ea(e?e(l,g):l,a)):b.e.Y(a),h.qb=k}};b.g.Q[a]=r;b.e.I[a]=m}function ea(a,d,c){c&&d!==b.k.q(a)&&b.k.T(a,d);d!==b.k.q(a)&&b.r.K(b.a.Ba,p,[a,"change"])}var b="undefined"!==typeof w?w:{};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.1";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 r;var c=a.type;return"checkbox"==c||"radio"==c}var d=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,c={},e={};c[/Firefox\/2/i.test(ga.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,k=g.length;h<k;h++)e[g[h]]=f}var l={propertychange:m},n,c=3;f=y.createElement("div");for(g=f.getElementsByTagName("i");f.innerHTML="\x3c!--[if gt IE "+ ++c+"]><i></i><![endif]--\x3e",g[0];);n=4<c?c:I;return{Na:["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},lb:function(a,b,d){for(var c=0,e=a.length;c<e;c++)if(b.call(d,a[c]))return a[c];return p},ga:function(a,d){var c=b.a.i(a,d);0<=c&&a.splice(c,1)},Ga:function(a){a=a||[];for(var 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){a=a||[];for(var d=[],c=0,e=a.length;c<e;c++)d.push(b(a[c]));return d},fa:function(a,b){a=a||[];for(var 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)},Hb:function(a){a=b.a.L(a);for(var d=y.createElement("div"),c=0,e=a.length;c<e;c++)d.appendChild(b.A(a[c]));return d},Ia:function(a,d){for(var c=0,e=a.length,g=[];c<e;c++){var f=a[c].cloneNode(m);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])},
|
||||
Ya: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])}},bb:function(a,b){7>n?a.setAttribute("selected",b):a.selected=b},D:function(a){return(a||"").replace(d,"")},Rb: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},Ob:function(a,b){a=a||"";return b.length>a.length?r:a.substring(0,b.length)===b},tb:function(a,b){if(b.compareDocumentPosition)return 16==
|
||||
(b.compareDocumentPosition(a)&16);for(;a!=p;){if(a==b)return m;a=a.parentNode}return r},X:function(a){return b.a.tb(a,a.ownerDocument)},u:function(a){return a&&a.tagName&&a.tagName.toLowerCase()},n:function(b,d,c){var e=n&&l[d];if(!e&&"undefined"!=typeof F){if(a(b,d)){var f=c;c=function(a,b){var d=this.checked;b&&(this.checked=b.nb!==m);f.call(this,a);this.checked=d}}F(b).bind(d,c)}else!e&&"function"==typeof b.addEventListener?b.addEventListener(d,c,r):"undefined"!=typeof b.attachEvent?b.attachEvent("on"+
|
||||
d,function(a){c.call(b,a)}):j(Error("Browser doesn't support addEventListener or attachEvent"))},Ba:function(b,d){(!b||!b.nodeType)&&j(Error("element must be a DOM node when calling triggerEvent"));if("undefined"!=typeof F){var c=[];a(b,d)&&c.push({nb:b.checked});F(b).trigger(d,c)}else"function"==typeof y.createEvent?"function"==typeof b.dispatchEvent?(c=y.createEvent(e[d]||"HTMLEvents"),c.initEvent(d,m,m,x,0,0,0,0,0,r,r,r,r,0,b),b.dispatchEvent(c)):j(Error("The supplied element doesn't support dispatchEvent")):
|
||||
"undefined"!=typeof b.fireEvent?(a(b,d)&&(b.checked=b.checked!==m),b.fireEvent("on"+d)):j(Error("Browser doesn't support triggering events"))},d:function(a){return b.$(a)?a():a},ua: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(" ")}},cb:function(a,d){var c=b.a.d(d);if(c===p||c===I)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,[y.createTextNode(c)]):e.data=c;b.a.wb(a)}},ab:function(a,b){a.name=b;if(7>=n)try{a.mergeAttributes(y.createElement("<input name='"+a.name+"'/>"),r)}catch(d){}},wb:function(a){9<=n&&(a=1==a.nodeType?a:a.parentNode,a.style&&(a.style.zoom=a.style.zoom))},ub:function(a){if(9<=n){var b=a.style.width;a.style.width=0;a.style.width=b}},Lb:function(a,d){a=b.a.d(a);d=b.a.d(d);for(var 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},Pb:6===n,Qb:7===n,Z:n,Oa: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},Ib:function(a){return"string"==typeof a&&(a=b.a.D(a))?x.JSON&&x.JSON.parse?x.JSON.parse(a):(new Function("return "+a))():p},xa:function(a,d,c){("undefined"==typeof JSON||"undefined"==typeof JSON.stringify)&&
|
||||
j(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)},Jb:function(a,d,c){c=c||{};var e=c.params||{},f=c.includeFields||this.Na,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 k=b.a.Oa(a,f[h]),l=k.length-1;0<=l;l--)e[k[l].name]=k[l].value;d=b.a.d(d);var n=y.createElement("form");
|
||||
n.style.display="none";n.action=g;n.method="post";for(var w in d)a=y.createElement("input"),a.name=w,a.value=b.a.xa(b.a.d(d[w])),n.appendChild(a);for(w in e)a=y.createElement("input"),a.name=w,a.value=e[w],n.appendChild(a);y.body.appendChild(n);c.submitter?c.submitter(n):n.submit();setTimeout(function(){n.parentNode.removeChild(n)},0)}}};b.b("utils",b.a);b.b("utils.arrayForEach",b.a.o);b.b("utils.arrayFirst",b.a.lb);b.b("utils.arrayFilter",b.a.fa);b.b("utils.arrayGetDistinctValues",b.a.Ga);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.Na);b.b("utils.getFormFields",b.a.Oa);b.b("utils.peekObservable",b.a.ua);b.b("utils.postJson",b.a.Jb);b.b("utils.parseJson",b.a.Ib);b.b("utils.registerEventHandler",b.a.n);b.b("utils.stringifyJson",b.a.xa);b.b("utils.range",b.a.Lb);b.b("utils.toggleDomNodeCssClass",b.a.da);b.b("utils.triggerEvent",b.a.Ba);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.la(a,r);return c===I?I:c[d]},set:function(a,d,c){c===I&&b.a.f.la(a,r)===I||(b.a.f.la(a,m)[d]=c)},la:function(b,f){var g=b[d];if(!g||!("null"!==g&&c[g])){if(!f)return I;g=b[d]="ko"+
|
||||
a++;c[g]={}}return c[g]},clear:function(a){var b=a[d];return b?(delete c[b],a[d]=p,m):r}}};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===I&&d&&(e=[],b.a.f.set(a,c,e));return e}function d(c){var e=a(c,r);if(e)for(var e=e.slice(0),k=0;k<e.length;k++)e[k](c);b.a.f.clear(c);"function"==typeof F&&"function"==typeof F.cleanData&&F.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:m,8:m,9:m},f={1:m,9:m};return{Ca:function(b,d){"function"!=typeof d&&j(Error("Callback must be a function"));a(b,m).push(d)},Xa:function(d,e){var f=a(d,r);f&&(b.a.ga(f,e),0==f.length&&b.a.f.set(d,c,I))},A:function(a){if(e[a.nodeType]&&(d(a),f[a.nodeType])){var c=[];b.a.P(c,a.getElementsByTagName("*"));for(var k=0,l=c.length;k<l;k++)d(c[k])}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.Ca);b.b("utils.domNodeDisposal.removeDisposeCallback",b.a.F.Xa);b.a.ta=function(a){var d;if("undefined"!=typeof F)if(F.parseHTML)d=F.parseHTML(a);else{if((d=F.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=y.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 x.innerShiv?d.appendChild(x.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!==p&&d!==I)if("string"!=typeof d&&(d=d.toString()),
|
||||
"undefined"!=typeof F)F(a).html(d);else for(var c=b.a.ta(d),e=0;e<c.length;e++)a.appendChild(c[e])};b.b("utils.parseHtmlFragment",b.a.ta);b.b("utils.setHtml",b.a.ca);var R={};b.s={ra:function(a){"function"!=typeof a&&j(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);R[b]=a;return"\x3c!--[ko_memo:"+b+"]--\x3e"},hb:function(a,b){var c=R[a];c===I&&j(Error("Couldn't find any memo with ID "+
|
||||
a+". Perhaps it's already been unmemoized."));try{return c.apply(p,b||[]),m}finally{delete R[a]}},ib:function(a,d){var c=[];ca(a,c);for(var e=0,f=c.length;e<f;e++){var g=c[e].sb,h=[g];d&&b.a.P(h,d);b.s.hb(c[e].Fb,h);g.nodeValue="";g.parentNode&&g.parentNode.removeChild(g)}},Ua:function(a){return(a=a.match(/^\[ko_memo\:(.*?)\]$/))?a[1]:p}};b.b("memoization",b.s);b.b("memoization.memoize",b.s.ra);b.b("memoization.unmemoize",b.s.hb);b.b("memoization.parseMemoText",b.s.Ua);b.b("memoization.unmemoizeDomNodeAndDescendants",
|
||||
b.s.ib);b.Ma={throttle:function(a,d){a.throttleEvaluation=d;var c=p;return b.j({read:a,write:function(b){clearTimeout(c);c=setTimeout(function(){a(b)},d)}})},notify:function(a,d){a.equalityComparer="always"==d?u(r):b.m.fn.equalityComparer;return a}};b.b("extenders",b.Ma);b.fb=function(a,d,c){this.target=a;this.ha=d;this.rb=c;b.p(this,"dispose",this.B)};b.fb.prototype.B=function(){this.Cb=m;this.rb()};b.S=function(){this.w={};b.a.extend(this,b.S.fn);b.p(this,"subscribe",this.ya);b.p(this,"extend",
|
||||
this.extend);b.p(this,"getSubscriptionsCount",this.yb)};b.S.fn={ya:function(a,d,c){c=c||"change";var e=new b.fb(this,d?a.bind(d):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.Cb!==m&&b.ha(a)})},this)},yb: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.Ma[c];"function"==typeof e&&(d=e(d,a[c]))}return d}};b.Qa=function(a){return"function"==typeof a.ya&&"function"==typeof a.notifySubscribers};b.b("subscribable",b.S);b.b("isSubscribable",b.Qa);var C=[];b.r={mb:function(a){C.push({ha:a,La:[]})},end:function(){C.pop()},Wa:function(a){b.Qa(a)||j(Error("Only subscribable things can act as dependencies"));if(0<C.length){var d=C[C.length-1];d&&!(0<=b.a.i(d.La,a))&&(d.La.push(a),d.ha(a))}},K:function(a,b,c){try{return C.push(p),a.apply(b,c||[])}finally{C.pop()}}};
|
||||
var ma={undefined:m,"boolean":m,number:m,string:m};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.Wa(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===p||typeof a in ma?a===b:r}};var E=b.m.Kb="__ko_proto__";b.m.fn[E]=b.m;b.ma=function(a,d){return a===p||a===I||a[E]===I?r:a[E]===d?m:b.ma(a[E],d)};b.$=function(a){return b.ma(a,b.m)};b.Ra=function(a){return"function"==typeof a&&a[E]===b.m||"function"==typeof a&&a[E]===b.j&&a.zb?m:r};b.b("observable",b.m);b.b("isObservable",b.$);b.b("isWriteableObservable",b.Ra);b.R=function(a){0==arguments.length&&(a=[]);a!==p&&(a!==I&&!("length"in a))&&j(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===I){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=m);this.G()},destroyAll:function(a){return a===I?this.destroy(u(m)):!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(z,function(a){a.B()});z=[]}function f(){var a=h.throttleEvaluation;a&&0<=a?(clearTimeout(t),t=setTimeout(g,a)):g()}function g(){if(!q)if(n&&w())A();else{q=m;try{var a=b.a.V(z,function(a){return a.target});b.r.mb(function(c){var d;0<=(d=b.a.i(a,c))?a[d]=I:z.push(c.ya(f))});for(var c=s.call(d),e=a.length-1;0<=e;e--)a[e]&&z.splice(e,1)[0].B();n=m;h.notifySubscribers(l,
|
||||
"beforeChange");l=c}finally{b.r.end()}h.notifySubscribers(l);q=r;z.length||A()}}function h(){if(0<arguments.length)return"function"===typeof v?v.apply(d,arguments):j(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;n||g();b.r.Wa(h);return l}function k(){return!n||0<z.length}var l,n=r,q=r,s=a;s&&"object"==typeof s?(c=s,s=c.read):(c=c||{},s||(s=c.read));"function"!=typeof s&&j(Error("Pass a function that returns the value of the ko.computed"));
|
||||
var v=c.write,G=c.disposeWhenNodeIsRemoved||c.W||p,w=c.disposeWhen||c.Ka||u(r),A=e,z=[],t=p;d||(d=c.owner);h.t=function(){n||g();return l};h.xb=function(){return z.length};h.zb="function"===typeof c.write;h.B=function(){A()};h.pa=k;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.pa);b.p(h,"getDependenciesCount",h.xb);c.deferEvaluation!==m&&g();if(G&&k()){A=function(){b.a.F.Xa(G,arguments.callee);e()};b.a.F.Ca(G,A);var D=w,w=function(){return!b.a.X(G)||D()}}return h};
|
||||
b.Bb=function(a){return b.ma(a,b.j)};w=b.m.Kb;b.j[w]=b.m;b.j.fn={};b.j.fn[w]=b.j;b.b("dependentObservable",b.j);b.b("computed",b.j);b.b("isComputed",b.Bb);b.gb=function(a){0==arguments.length&&j(Error("When calling ko.toJS, pass the object you want to convert."));return ba(a,function(a){for(var c=0;b.$(a)&&10>c;c++)a=a();return a})};b.toJSON=function(a,d,c){a=b.gb(a);return b.a.xa(a,d,c)};b.b("toJS",b.gb);b.b("toJSON",b.toJSON);b.k={q:function(a){switch(b.a.u(a)){case "option":return a.__ko__hasDomDataOptionValue__===
|
||||
m?b.a.f.get(a,b.c.options.sa):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]):I;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.sa,I);"__ko__hasDomDataOptionValue__"in a&&delete a.__ko__hasDomDataOptionValue__;a.value=d;break;default:b.a.f.set(a,b.c.options.sa,d),a.__ko__hasDomDataOptionValue__=m,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===p||d===I)d="";a.value=d}}};b.b("selectExtensions",b.k);b.b("selectExtensions.readValue",b.k.q);b.b("selectExtensions.writeValue",b.k.T);var ka=/\@ko_token_(\d+)\@/g,na=["true","false"],oa=/^(?:[$_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));a=[];for(var c=
|
||||
p,e,f=0;f<d.length;f++){var g=d.charAt(f);if(c===p)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=p}}e=c=p;for(var k=0,l=p,f=0;f<d.length;f++){g=d.charAt(f);if(c===p)switch(g){case "{":c=f;l=g;e="}";break;case "(":c=f;l=g;e=")";break;case "[":c=f,l=g,e="]"}g===l?k++:g===e&&(k--,0===k&&(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=p))}e=[];d=d.split(",");c=0;for(f=d.length;c<f;c++)k=d[c],l=k.indexOf(":"),0<l&&l<k.length-1?(g=k.substring(l+1),e.push({key:P(k.substring(0,l),a),value:P(g,a)})):e.push({unknown:P(k,a)});return e},ba:function(a){var d="string"===typeof a?b.g.aa(a):a,c=[];a=[];for(var 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(na,b.a.D(e).toLowerCase())?e=r:(h=e.match(oa),e=h===p?r: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},Eb:function(a,d){for(var c=0;c<a.length;c++)if(b.a.D(a[c].key)==d)return m;return r},ea:function(a,d,c,e,f){if(!a||!b.Ra(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 K="\x3c!--test--\x3e"===y.createComment("test").text,ja=K?/^\x3c!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*--\x3e$/:/^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/,ia=K?/^\x3c!--\s*\/ko\s*--\x3e$/:
|
||||
/^\s*\/ko\s*$/,pa={ul:m,ol:m};b.e={I:{},childNodes:function(a){return B(a)?aa(a):a.childNodes},Y:function(a){if(B(a)){a=b.e.childNodes(a);for(var d=0,c=a.length;d<c;d++)b.removeNode(a[d])}else b.a.ka(a)},N:function(a,d){if(B(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)},Va:function(a,b){B(a)?a.parentNode.insertBefore(b,a.nextSibling):a.firstChild?a.insertBefore(b,a.firstChild):a.appendChild(b)},Pa:function(a,d,c){c?B(a)?a.parentNode.insertBefore(d,
|
||||
c.nextSibling):c.nextSibling?a.insertBefore(d,c.nextSibling):a.appendChild(d):b.e.Va(a,d)},firstChild:function(a){return!B(a)?a.firstChild:!a.nextSibling||H(a.nextSibling)?p:a.nextSibling},nextSibling:function(a){B(a)&&(a=$(a));return a.nextSibling&&H(a.nextSibling)?p:a.nextSibling},jb:function(a){return(a=B(a))?a[1]:p},Ta:function(a){if(pa[b.a.u(a)]){var d=a.firstChild;if(d){do if(1===d.nodeType){var c;c=d.firstChild;var e=p;if(c){do if(e)e.push(c);else if(B(c)){var f=$(c,m);f?c=f:e=[c]}else H(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.Pa);b.b("virtualElements.prepend",b.e.Va);b.b("virtualElements.setDomNodeChildren",b.e.N);b.J=function(){this.Ha={}};b.a.extend(b.J.prototype,{nodeHasBindings:function(a){switch(a.nodeType){case 1:return a.getAttribute("data-bind")!=
|
||||
p;case 8:return b.e.jb(a)!=p;default:return r}},getBindings:function(a,b){var c=this.getBindingsString(a,b);return c?this.parseBindingsString(c,b,a):p},getBindingsString:function(a){switch(a.nodeType){case 1:return a.getAttribute("data-bind");case 8:return b.e.jb(a);default:return p}},parseBindingsString:function(a,d,c){try{var e;if(!(e=this.Ha[a])){var f=this.Ha,g,h="with($context){with($data||{}){return{"+b.g.ba(a)+"}}}";g=new Function("$context","$element",h);e=f[a]=g}return e(d,c)}catch(k){j(Error("Unable to parse bindings.\nMessage: "+
|
||||
k+";\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.eb=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.Fa=function(a,d,c){1===a.nodeType&&b.e.Ta(a);return X(a,d,c,m)};b.Ea=function(a,b){(1===b.nodeType||8===b.nodeType)&&Z(a,b,m)};b.Da=function(a,b){b&&(1!==b.nodeType&&8!==b.nodeType)&&j(Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node"));b=b||x.document.body;Y(a,b,m)};b.ja=function(a){switch(a.nodeType){case 1:case 8:var d=b.eb(a);if(d)return d;
|
||||
if(a.parentNode)return b.ja(a.parentNode)}return I};b.pb=function(a){return(a=b.ja(a))?a.$data:I};b.b("bindingHandlers",b.c);b.b("applyBindings",b.Da);b.b("applyBindingsToDescendants",b.Ea);b.b("applyBindingsToNode",b.Fa);b.b("contextFor",b.ja);b.b("dataFor",b.pb);var fa={"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===r||f===p||f===I;g&&a.removeAttribute(e);8>=b.a.Z&&e in fa?(e=fa[e],g?a.removeAttribute(e):
|
||||
a[e]=f):g||a.setAttribute(e,f.toString());"name"===e&&b.a.ab(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,m)});"radio"==a.type&&!a.name&&b.c.uniqueName.init(a,u(m))},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,r),a.__ko__cssValue=c,b.a.da(a,c,m)}};b.c.enable={update:function(a,d){var c=b.a.d(d());c&&a.disabled?a.removeAttribute("disabled"):!c&&!a.disabled&&(a.disabled=m)}};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,n=d()[f];if(n){var q=c();try{var s=b.a.L(arguments);s.unshift(e);g=n.apply(e,s)}finally{g!==m&&(a.preventDefault?a.preventDefault():a.returnValue=r)}q[f+"Bubble"]===r&&(a.cancelBubble=m,a.stopPropagation&&a.stopPropagation())}})})()}};b.c.foreach={Sa:function(a){return function(){var d=a(),c=b.a.ua(d);if(!c||"number"==typeof c.length)return{foreach:d,templateEngine:b.C.oa};
|
||||
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.oa}}},init:function(a,d){return b.c.template.init(a,b.c.foreach.Sa(d))},update:function(a,d,c,e,f){return b.c.template.update(a,b.c.foreach.Sa(d),c,e,f)}};b.g.Q.foreach=r;b.e.I.foreach=m;b.c.hasfocus={init:function(a,d,c){function e(e){a.__ko_hasfocusUpdating=m;var f=a.ownerDocument;"activeElement"in
|
||||
f&&(e=f.activeElement===a);f=d();b.g.ea(f,c,"hasfocus",e,m);a.__ko_hasfocusUpdating=r}var f=e.bind(p,m),g=e.bind(p,r);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.Ba,p,[a,c?"focusin":"focusout"]))}};b.c.html={init:function(){return{controlsDescendantBindings:m}},update:function(a,d){b.a.ca(a,d())}};var da="__ko_withIfBindingData";Q("if");Q("ifnot",r,m);Q("with",m,r,function(a,
|
||||
b){return a.createChildContext(b)});b.c.options={update:function(a,d,c){"select"!==b.a.u(a)&&j(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){c=c();var k=c.optionsIncludeDestroyed;"number"!=typeof h.length&&(h=[h]);if(c.optionsCaption){var l=y.createElement("option");
|
||||
b.a.ca(l,c.optionsCaption);b.k.T(l,I);a.appendChild(l)}d=0;for(var n=h.length;d<n;d++){var q=h[d];if(!q||!q._destroy||k){var l=y.createElement("option"),s=function(a,b,c){var d=typeof b;return"function"==d?b(a):"string"==d?a[b]:c},v=s(q,c.optionsValue,q);b.k.T(l,b.a.d(v));q=s(q,c.optionsText,v);b.a.cb(l,q);a.appendChild(l)}}h=a.getElementsByTagName("option");d=k=0;for(n=h.length;d<n;d++)0<=b.a.i(f,b.k.q(h[d]))&&(b.a.bb(h[d],m),k++);a.scrollTop=g;e&&"value"in c&&ea(a,b.a.ua(c.value),m);b.a.ub(a)}}};
|
||||
b.c.options.sa="__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)&&j(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.bb(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()&&j(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!==m&&(b.preventDefault?b.preventDefault():b.returnValue=r)}})}};b.c.text={update:function(a,d){b.a.cb(a,d())}};b.e.I.text=m;b.c.uniqueName={init:function(a,d){if(d()){var c="ko_unique_"+ ++b.c.uniqueName.ob;b.a.ab(a,
|
||||
c)}}};b.c.uniqueName.ob=0;b.c.value={init:function(a,d,c){function e(){h=r;var e=d(),f=b.k.q(a);b.g.ea(e,c,"value",f)}var f=["change"],g=c().valueUpdate,h=r;g&&("string"==typeof g&&(g=[g]),b.a.P(f,g),f=b.a.Ga(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=m}),b.a.n(a,"blur",function(){h&&e()});b.a.o(f,function(c){var d=e;b.a.Ob(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=m);g&&(f=function(){b.k.T(a,e)},f(),c&&setTimeout(f,0));c&&0<a.length&&ea(a,e,r)}};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(){j(Error("Override renderTemplateSource"))};b.v.prototype.createJavaScriptEvaluatorBlock=function(){j(Error("Override createJavaScriptEvaluatorBlock"))};b.v.prototype.makeTemplateSource=function(a,d){if("string"==typeof a){d=d||y;var c=d.getElementById(a);c||j(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);j(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===r?m: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",m)};b.b("templateEngine",b.v);var qa=/(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi,ra=/\x3c!--\s*ko\b\s*([\s\S]*?)\s*--\x3e/g;b.za={vb:function(a,
|
||||
d,c){d.isTemplateRewritten(a,c)||d.rewriteTemplate(a,function(a){return b.za.Gb(a,d)},c)},Gb:function(a,b){return a.replace(qa,function(a,e,f,g,h,k,l){return W(l,e,b)}).replace(ra,function(a,e){return W(e,"\x3c!-- ko --\x3e",b)})},kb:function(a){return b.s.ra(function(d,c){d.nextSibling&&b.Fa(d.nextSibling,a,c)})}};b.b("__tr_ambtns",b.za.kb);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.Aa===I&&a.ia&&(a.Aa=a.ia.innerHTML);return a.Aa}b.a.f.set(this.h,"__ko_anon_template__",{Aa: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 O;b.wa=function(a){a!=I&&!(a instanceof b.v)&&j(Error("templateEngine must inherit from ko.templateEngine"));O=a};b.va=function(a,d,c,e,f){c=c||{};(c.templateEngine||O)==I&&j(Error("Set a template engine before calling renderTemplate"));
|
||||
f=f||"replaceChildren";if(e){var g=N(e);return b.j(function(){var h=d&&d instanceof b.z?d:new b.z(b.a.d(d)),k="function"==typeof a?a(h.$data,h):a,h=T(e,f,k,h,c);"replaceNode"==f&&(e=h,g=N(e))},p,{Ka:function(){return!g||!b.a.X(g)},W:g&&"replaceNode"==f?g.parentNode:g})}return b.s.ra(function(e){b.va(a,d,c,e,"replaceNode")})};b.Mb=function(a,d,c,e,f){function g(a,b){U(b,k);c.afterRender&&c.afterRender(b,a)}function h(d,e){k=f.createChildContext(b.a.d(d),c.as);k.$index=e;var g="function"==typeof a?
|
||||
a(d,k):a;return T(p,"ignoreTargetNode",g,k,c)}var k;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===I||a===p||!b.a.d(a._destroy)});b.r.K(b.a.$a,p,[e,a,h,c,g])},p,{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.Hb(c),(new b.l.O(a)).nodes(c);return{controlsDescendantBindings:m}},update:function(a,
|
||||
d,c,e,f){d=b.a.d(d());c={};e=m;var g,h=p;"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.Mb(d||a,e&&c.foreach||[],c,a,f):e?(f="data"in c?f.createChildContext(g,c.as):f,h=b.va(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.pa()?f:I)}};b.g.Q.template=function(a){a=b.g.aa(a);return 1==a.length&&a[0].unknown||
|
||||
b.g.Eb(a,"name")?p:"This template engine does not support anonymous templates nested within its templates"};b.e.I.template=m;b.b("setTemplateEngine",b.wa);b.b("renderTemplate",b.va);b.a.Ja=function(a,b,c){a=a||[];b=b||[];return a.length<=b.length?S(a,b,"added","deleted",c):S(b,a,"deleted","added",c)};b.b("utils.compareArrays",b.a.Ja);b.a.$a=function(a,d,c,e,f){function g(a,b){t=l[b];w!==b&&(z[a]=t);t.na(w++);M(t.M);s.push(t);A.push(t)}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)})}d=d||[];e=e||{};var k=b.a.f.get(a,"setDomNodeChildrenFromArrayMapping_lastMappingResult")===I,l=b.a.f.get(a,"setDomNodeChildrenFromArrayMapping_lastMappingResult")||[],n=b.a.V(l,function(a){return a.U}),q=b.a.Ja(n,d),s=[],v=0,w=0,B=[],A=[];d=[];for(var z=[],n=[],t,D=0,C,E;C=q[D];D++)switch(E=C.moved,C.status){case "deleted":E===I&&(t=l[v],t.j&&t.j.B(),B.push.apply(B,M(t.M)),e.beforeRemove&&(d[D]=t,A.push(t)));v++;break;case "retained":g(D,v++);break;case "added":E!==I?
|
||||
g(D,E):(t={U:C.value,na:b.m(w++)},s.push(t),A.push(t),k||(n[D]=t))}h(e.beforeMove,z);b.a.o(B,e.beforeRemove?b.A:b.removeNode);for(var D=0,k=b.e.firstChild(a),H;t=A[D];D++){t.M||b.a.extend(t,ha(a,c,t.U,f,t.na));for(v=0;q=t.M[v];k=q.nextSibling,H=q,v++)q!==k&&b.e.Pa(a,q,H);!t.Ab&&f&&(f(t.U,t.M,t.na),t.Ab=m)}h(e.beforeRemove,d);h(e.afterMove,z);h(e.afterAdd,n);b.a.f.set(a,"setDomNodeChildrenFromArrayMapping_lastMappingResult",s)};b.b("utils.setDomNodeChildrenFromArrayMapping",b.a.$a);b.C=function(){this.allowTemplateRewriting=
|
||||
r};b.C.prototype=new b.v;b.C.prototype.renderTemplateSource=function(a){var d=!(9>b.a.Z)&&a.nodes?a.nodes():p;if(d)return b.a.L(d.cloneNode(m).childNodes);a=a.text();return b.a.ta(a)};b.C.oa=new b.C;b.wa(b.C.oa);b.b("nativeTemplateEngine",b.C);b.qa=function(){var a=this.Db=function(){if("undefined"==typeof F||!F.tmpl)return 0;try{if(0<=F.tmpl.tag.tmpl.open.toString().indexOf("__"))return 2}catch(a){}return 1}();this.renderTemplateSource=function(b,c,e){e=e||{};2>a&&j(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=F.template(p,"{{ko_with $item.koBindingContext}}"+f+"{{/ko_with}}"),b.data("precompiled",f));b=[c.$data];c=F.extend({koBindingContext:c},e.templateOptions);c=F.tmpl(f,b,c);c.appendTo(y.createElement("div"));F.fragments={};return c};this.createJavaScriptEvaluatorBlock=function(a){return"{{ko_code ((function() { return "+a+" })()) }}"};this.addTemplate=function(a,b){y.write("<script type='text/html' id='"+a+"'>"+b+"\x3c/script>")};0<a&&(F.tmpl.tag.ko_code=
|
||||
{open:"__.push($1 || '');"},F.tmpl.tag.ko_with={open:"with($1) {",close:"} "})};b.qa.prototype=new b.v;w=new b.qa;0<w.Db&&b.wa(w);b.b("jqueryTmplTemplateEngine",b.qa)}"function"===typeof require&&"object"===typeof exports&&"object"===typeof module?L(module.exports||exports):"function"===typeof define&&define.amd?define(["exports"],L):L(x.ko={});m;
|
||||
})();
|
||||
@@ -282,7 +282,8 @@ table {
|
||||
}
|
||||
|
||||
// timelapse files
|
||||
&.timelapse_files_name {
|
||||
&.timelapse_files_name,
|
||||
&.timelapse_unrendered_name {
|
||||
text-overflow: ellipsis;
|
||||
text-align: left;
|
||||
}
|
||||
@@ -292,7 +293,18 @@ table {
|
||||
width: 55px;
|
||||
}
|
||||
|
||||
&.timelapse_files_action {
|
||||
&.timelapse_unrendered_size {
|
||||
text-align: right;
|
||||
width: 55px;
|
||||
}
|
||||
|
||||
&.timelapse_unrendered_count {
|
||||
text-align: right;
|
||||
width: 45px;
|
||||
}
|
||||
|
||||
&.timelapse_files_action,
|
||||
&.timelapse_unrendered_action {
|
||||
width: 45px;
|
||||
.actioncol;
|
||||
}
|
||||
@@ -396,10 +408,17 @@ ul.dropdown-menu li a {
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 10001;
|
||||
display: none;
|
||||
}
|
||||
|
||||
#offline_overlay {
|
||||
z-index: 10002;
|
||||
}
|
||||
|
||||
#reloadui_overlay {
|
||||
z-index: 10001;
|
||||
}
|
||||
|
||||
#offline_overlay_background,
|
||||
#reloadui_overlay_background {
|
||||
position: fixed;
|
||||
@@ -611,11 +630,11 @@ ul.dropdown-menu li a {
|
||||
}
|
||||
}
|
||||
|
||||
.custom_section_horizontal .custom_control {
|
||||
.custom_section_horizontal > .custom_control {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.custom_section_vertical .custom_control {
|
||||
.custom_section_vertical > .custom_control {
|
||||
display:block;
|
||||
}
|
||||
|
||||
@@ -672,7 +691,7 @@ ul.dropdown-menu li a {
|
||||
|
||||
#term {
|
||||
.terminal {
|
||||
#terminal-output {
|
||||
#terminal-output, #terminal-output-lowfi {
|
||||
min-height: 340px;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
@@ -910,6 +929,10 @@ textarea.block {
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.ui-pnotify a {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/** Styles for Bootstrap Slider */
|
||||
|
||||
.slider {
|
||||
@@ -975,6 +998,20 @@ textarea.block {
|
||||
}
|
||||
}
|
||||
|
||||
// Special delivery for Safari browsers... because Safari >= 8 sometimes just
|
||||
// shows us white panes on the settings dialog when the full-sized-box has
|
||||
// an absolute position (which it needs for both scrollbars to work), at least
|
||||
// until the page is resized or otherwise a rerender is triggered, we'll have
|
||||
// our styling resolve to static positioning on that browser for now.
|
||||
//
|
||||
// This btw also means that the dialog will change in size. Yay.
|
||||
//
|
||||
// Better use something else if you have the option, that thing is really
|
||||
// weird.
|
||||
_::-webkit-full-page-media, _:future, :root .full-sized-box {
|
||||
position: static;
|
||||
}
|
||||
|
||||
.scrollable {
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<div id="settings_dialog" class="modal hide fade large" tabindex="-1" role="dialog" aria-labelledby="settings_dialog_label" aria-hidden="true">
|
||||
<div class="modal-header">
|
||||
<button type="button" class="close" data-dismiss="modal">×</button>
|
||||
<h3 id="settings_dialog_label">{{ _('OctoPrint Settings') }}</h3>
|
||||
<h3 id="settings_dialog_label">{{ _('OctoPrint Settings') }} <i class="icon-spinner icon-spin" data-bind="visible: receiving"></i></h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="full-sized-box">
|
||||
@@ -20,7 +20,7 @@
|
||||
class="{% if mark_active %}active{% set mark_active = False %}{% endif %} {% if "classes_link" in data %}{{ data.classes_link|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
|
||||
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
|
||||
>
|
||||
<a href="#{{ data._div }}" data-toggle="tab">{{ entry }}</a>
|
||||
<a href="#{{ data._div }}" data-toggle="tab">{{ entry|e }}</a>
|
||||
</li>
|
||||
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
|
||||
{% endif %}
|
||||
@@ -49,6 +49,6 @@
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { saveData(undefined, $root.hide) }">{{ _('Save') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { saveData(undefined, $root.hide) }, enable: !exchanging(), css: {disabled: exchanging()}"><i class="icon-spinner icon-spin" data-bind="visible: sending"></i> {{ _('Save') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -48,6 +48,13 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_ignoreIdenticalResends" id="settings-ignoreIdenticalResends"> {{ _('Ignore consecutive resend requests for the same line') }} <span class="label">{{ _('Repetier') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
@@ -62,11 +69,4 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: feature_swallowOkAfterResend" id="settings-swallowOkAfterResend"> {{ _('Swallow the first "ok" after a resend response') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -1,4 +1,6 @@
|
||||
<form class="form-horizontal">
|
||||
<h3>{{ _('Folders') }}</h3>
|
||||
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-folderUploads">{{ _('Upload Folder') }}</label>
|
||||
<div class="controls">
|
||||
@@ -36,4 +38,21 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Disk space thresholds') }}</h3>
|
||||
|
||||
<p>{{ _('If the free disk space falls below these thresholds, OctoPrint will warn the user.') }}</p>
|
||||
|
||||
<div class="control-group" title="{{ ('Threshold after which to warn about the remaining free space on disk.') }}">
|
||||
<label class="control-label" for="settings.serverDiskusageWarning">{{ _('Warning') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_warning_str">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ ('Threshold after which to consider remaining free space on disk as critical.') }}">
|
||||
<label class="control-label" for="settings.serverDiskusageCritical">{{ _('Critical') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_critical_str">
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -70,13 +70,6 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-serialLongRunningCommands">{{ _('Long running commands') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-serialLongRunningCommands" data-bind="value: serial_longRunningCommands">
|
||||
<span class="help-inline">{{ _('Use this to specify the commands known to take a long time to complete without output from your printer and hence might cause timeout issues. Just the G or M code, comma separated.')|format(glob_url="http://docs.python.org/2/library/glob.html") }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-serialAdditionalPorts">{{ _('Additional serial ports') }}</label>
|
||||
<div class="controls">
|
||||
@@ -84,4 +77,51 @@
|
||||
<span class="help-inline">{{ _('Use this to define additional <a href="%%(glob_url)s">glob patterns</a> matching serial ports to list for connecting against, e.g. <code>/dev/ttyAMA*</code>. One entry per line.')|format(glob_url="http://docs.python.org/2/library/glob.html") }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: serial_disconnectOnErrors" id="settings-disconnectOnErrors"> {{ _('Not only cancel ongoing prints but also disconnect on unhandled errors from the firmware.') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: serial_ignoreErrorsFromFirmware" id="settings-ignoreErrorsFromFirmware"> {{ _('Ignore any unhandled errors from the firmware. Only use this if your firmware sends stuff prefixed with "Error" that is not an actual error. Might mask printer issues, be careful!') }} <span class="label label-important">{{ _('Warning') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<div class="control-group" title="{{ _('Command to send to the firmware on first handshake attempt.') }}">
|
||||
<label class="control-label" for="settings-serialHelloCommand">{{ _('"Hello" command') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-serialHelloCommand" data-bind="value: serial_helloCommand">
|
||||
<span class="help-inline">{{ _('Use this to specify a different command than the default <code>M110</code> to send to the printer on initial connection to trigger a communication handshake.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Commands that are know to run long and hence should suppress communication timeouts from being triggered.') }}">
|
||||
<label class="control-label" for="settings-serialLongRunningCommands">{{ _('Long running commands') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-serialLongRunningCommands" data-bind="value: serial_longRunningCommands">
|
||||
<span class="help-inline">{{ _('Use this to specify the commands known to take a long time to complete without output from your printer and hence might cause timeout issues. Just the G or M code, comma separated.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Commands that always require a line number and checksum to be sent with them.') }}">
|
||||
<label class="control-label" for="settings-serialChecksumRequiringCommands">{{ _('Commands that always require a checksum') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-serialChecksumRequiringCommands" data-bind="value: serial_checksumRequiringCommands">
|
||||
<span class="help-inline">{{ _('Use this to specify which commands <strong>always</strong> need to be sent with a checksum. Comma separated list.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: serial_triggerOkForM29" id="settings-triggerOkForM29"> {{ _('Generate additional <code>ok</code> for <code>M29</code>') }} <span class="label">{{ _('Most Marlin < v1.1.0') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
@@ -0,0 +1,22 @@
|
||||
<form class="form-horizontal">
|
||||
<h3>{{ _('Commands') }}</h3>
|
||||
|
||||
<div class="control-group" title="{{ _('Command to restart the OctoPrint server') }}">
|
||||
<label class="control-label" for="settings-serverRestartCommand">{{ _('Restart OctoPrint') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: server_commands_serverRestartCommand" id="settings-serverRestartCommand">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Command to restart the system OctoPrint is running on') }}">
|
||||
<label class="control-label" for="settings-systemRestartCommand">{{ _('Restart system') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: server_commands_systemRestartCommand" id="settings-systemRestartCommand">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Command to shut down the system OctoPrint is running on') }}">
|
||||
<label class="control-label" for="settings-systemShutdownCommand">{{ _('Shutdown system') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: server_commands_systemShutdownCommand" id="settings-systemShutdownCommand">
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -17,7 +17,7 @@
|
||||
class="{% if mark_active %}active{% set mark_active = False %}{% endif %} {% if "classes_link" in data %}{{ data.classes_link|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
|
||||
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
|
||||
>
|
||||
<a href="#{{ data._div }}" data-toggle="tab">{{ entry }}</a>
|
||||
<a href="#{{ data._div }}" data-toggle="tab">{{ entry|e }}</a>
|
||||
</li>
|
||||
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
|
||||
{% endif %}
|
||||
|
||||
@@ -55,7 +55,7 @@
|
||||
>
|
||||
<div class="accordion-heading">
|
||||
<a class="accordion-toggle" data-toggle="collapse" data-target="#{{ data._div }}">
|
||||
{% if "icon" in data %}<i class="icon-{{ data.icon }}"></i> {% endif %}{{ entry }}
|
||||
{% if "icon" in data %}<i class="icon-{{ data.icon }}"></i> {% endif %}{{ entry|e }}
|
||||
</a>
|
||||
{% if "template_header" in data %}
|
||||
{% include data.template_header ignore missing %}
|
||||
@@ -87,7 +87,7 @@
|
||||
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% endif %}
|
||||
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
|
||||
>
|
||||
<a href="#{{ data._div }}" data-toggle="tab">{{ entry }}</a>
|
||||
<a href="#{{ data._div }}" data-toggle="tab">{{ entry|e }}</a>
|
||||
</li>
|
||||
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- /ko -->{% endif %}
|
||||
{% endfor %}
|
||||
@@ -112,7 +112,7 @@
|
||||
</div>
|
||||
<div class="footer">
|
||||
<ul class="pull-left muted">
|
||||
<li><small>{{ _('Version') }}: <span class="version">{{ display_version }}</span></small></li>
|
||||
<li><small>{{ _('Version') }}: <span class="version">{{ display_version|e }}</span></small></li>
|
||||
</ul>
|
||||
<ul class="pull-right">
|
||||
<li><a href="http://octoprint.org"><i class="icon-home"></i> {{ _('Homepage') }}</a></li>
|
||||
|
||||
@@ -10,26 +10,35 @@
|
||||
var CONFIG_TIMELAPSEFILESPERPAGE = 10;
|
||||
var CONFIG_LOGFILESPERPAGE = 10;
|
||||
var CONFIG_USERSPERPAGE = 10;
|
||||
var CONFIG_WEBCAM_STREAM = "{{ webcamStream }}";
|
||||
var CONFIG_WEBCAM_STREAM = "{{ webcamStream|e }}";
|
||||
var CONFIG_ACCESS_CONTROL = {% if enableAccessControl -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_SD_SUPPORT = {% if enableSdSupport -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_FIRST_RUN = {% if firstRun -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_TEMPERATURE_GRAPH = {% if enableTemperatureGraph -%} true; {% else %} false; {%- endif %}
|
||||
var CONFIG_GCODE_SIZE_THRESHOLD = {{ gcodeThreshold }};
|
||||
var CONFIG_GCODE_MOBILE_SIZE_THRESHOLD = {{ gcodeMobileThreshold }};
|
||||
var CONFIG_GCODE_SIZE_THRESHOLD = {{ gcodeThreshold|e }};
|
||||
var CONFIG_GCODE_MOBILE_SIZE_THRESHOLD = {{ gcodeMobileThreshold|e }};
|
||||
|
||||
var SOCKJS_URI = "{{ url_for('index') }}" + "sockjs";
|
||||
var SOCKJS_DEBUG = CONFIG_DEBUG;
|
||||
// sockjs should define CLOSE_NORMAL for us, but they don't (from ws spec)
|
||||
var SOCKJS_CLOSE_NORMAL = 1000
|
||||
var SOCKJS_CLOSE_NORMAL = 1000;
|
||||
|
||||
var UI_API_KEY = "{{ uiApiKey }}";
|
||||
var VERSION = "{{ version }}";
|
||||
var DISPLAY_VERSION = "{{ display_version }}";
|
||||
var LOCALE = "{{ g.locale }}";
|
||||
var UI_API_KEY = "{{ uiApiKey|e }}";
|
||||
var VERSION = "{{ version|e }}";
|
||||
var DISPLAY_VERSION = "{{ display_version|e }}";
|
||||
var BRANCH = "{{ branch|e }}";
|
||||
var LOCALE = "{{ g.locale|e }}";
|
||||
var AVAILABLE_LOCALES = {{ locales|tojson }};
|
||||
|
||||
var OCTOPRINT_VIEWMODELS = [];
|
||||
var ADDITIONAL_VIEWMODELS = [];
|
||||
var OCTOPRINT_ADDITIONAL_BINDINGS = [];
|
||||
|
||||
{% if templates.tab.order %}
|
||||
{% set first_tab = templates.tab.order[0] %}
|
||||
{% set entry, data = templates.tab.entries[first_tab] %}
|
||||
var OCTOPRINT_INITIAL_TAB = "#{{ data._div }}";
|
||||
{% else %}
|
||||
var OCTOPRINT_INITIAL_TAB = undefined;
|
||||
{% endif %}
|
||||
</script>
|
||||
@@ -10,7 +10,7 @@
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="login_remember" data-bind="checked: loginState.loginRemember"> {{ _('Remember me') }}
|
||||
</label>
|
||||
<button class="btn btn-block btn-primary" id="login_button" data-bind="click: loginState.login">{{ _('Login') }}</button>
|
||||
<button class="btn btn-block btn-primary" id="login_button" data-bind="click: function() { loginState.login(); }">{{ _('Login') }}</button>
|
||||
</div>
|
||||
<ul id="login_dropdown_loggedin" class="hide" data-bind="css: {hide: !loginState.loggedIn(), 'dropdown-menu': loginState.loggedIn()}">
|
||||
<li><a href="#" id="usersettings_button" data-bind="click: function() { usersettings.show(); }">{{ _('User Settings') }}</a></li>
|
||||
|
||||
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user