diff --git a/.gitignore b/.gitignore
index 1c96ad61b..472e38106 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,7 @@
+src/octoprint/templates/_data/AUTHORS.md
+src/octoprint/templates/_data/CHANGELOG.md
+src/octoprint/templates/_data/THIRDPARTYLICENSES.md
+
*.tar.bz2
*.tar.gz
*.7z
diff --git a/.travis.yml b/.travis.yml
index df4eb121f..dd3b081eb 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -6,4 +6,7 @@ python:
install:
- pip install -e .[develop]
script:
-- nosetests tests/
\ No newline at end of file
+- nosetests --with-doctest
+sudo: false
+git:
+ depth: 250
diff --git a/.versioneer-lookup b/.versioneer-lookup
index 0c8f361a3..0ffcdd877 100644
--- a/.versioneer-lookup
+++ b/.versioneer-lookup
@@ -10,10 +10,13 @@
# master shall not use the lookup table, only tags
master
-# maintenance is currently the branch for preparation of maintenance release 1.2.4
+# maintenance is currently the branch for preparation of maintenance release 1.2.8
# so are any fix/... branches
-maintenance 1.2.4 3761995aff94acf32495556730f133a1626245b3
-fix/.* 1.2.4 3761995aff94acf32495556730f133a1626245b3
+maintenance 1.2.8 6c622f7c4332b71c6ece59552ffc87c146155c84 pep440-dev
+fix/.* 1.2.8 6c622f7c4332b71c6ece59552ffc87c146155c84 pep440-dev
+
+# Special case disconnected checkouts, e.g. 'git checkout '
+\(detached.*
# every other branch is a development branch and thus gets resolved to 1.3.0-dev for now
-.* 1.3.0 198d3450d94be1a2 pep440-dev
+.* 1.3.0 198d3450d94be1a2 pep440-dev
diff --git a/AUTHORS.md b/AUTHORS.md
index 26198382f..412f90772 100644
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -51,6 +51,10 @@ date of first contribution):
* [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)
+ * [Marcel Hellwig](https://github.com/punkkeks)
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
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5563d0c47..bc5be0095 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,19 @@
## 1.3.0 (unreleased)
+### New Features
+
+* A new wizard dialog for system setups that can also be extended by plugins. Replaces the first run dialog
+ for setting up access control and can also be triggered in other cases than only the first run, e.g.
+ if Plugins necessitate user input to function properly.
+* An About dialog including licenses, authors, the changelog and more, extendable by plugins if necessary.
+* New features within the plugin system (TODO):
+ * New plugin mixin `UiPlugin` for plugins that want to provide an alternative web interface delivered by the
+ server.
+* Extracted a Javascript client library for utilizing the server's API, can be reused by `UiPlugin`s. (TODO)
+
+(TODO) = needs to be further described and documented
+
### Improvements
* Upgraded versioneer, generated version numbers are now PEP440 compatible (relevant
@@ -11,11 +24,228 @@
Manager install and uninstall dialog.
* Allow hiding plugins from Plugin Manager via ``config.yaml``.
* Cura Plugin: "Test" button to check if path to cura engine is valid.
+* Cura Plugin: Now also supports 15.06 version of CuraEngine.
+* 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.
+* `pip` helper now adjusts `pip install` parameters corresponding to detected
+ `pip` version:
+ * Removes `--process-dependency-links` when it's not needed
+ * Adds `--no-use-wheel` when it's needed
+ * Detects and reports on completely broken versions
+* Better tracking of printer connection state for plugins and scripts:
+ * Introduced three new Events `Connecting`, `Disconnecting` and
+ `PrinterStateChanged`.
+ * Introduced new GCODE script `beforePrinterDisconnected` which will get sent
+ before a (controlled) disconnect from the printer. This can be used to send
+ some final commands to the printer before the connection goes down, e.g.
+ `M117 Bye from OctoPrint`.
+ * The communication layer will now wait for the send queue to be fully processed
+ before disconnecting from the printer for good. This way it is ensured that
+ the `beforePrinterDisconnected` script or any further GCODE injected into it
+ will actually get sent.
+* Additional baud rates to allow for connecting can now be specified along side
+ additional serial ports via the settings dialog and the configuration file.
+* Option to never send checksums (e.g. if the printer firmware doesn't support it),
+ see [#949](https://github.com/foosel/OctoPrint/issues/949).
+* Added secondary temperature polling interval to use when printer is not printing
+ but a target temperature is set - this way the graph should be more responsive
+ while monitoring a manual heatup.
+* Documentation improvements
+* Test buttons for webcam snapshot & stream URL, ffmpeg path and some other settings
+ (see also [#183](https://github.com/foosel/OctoPrint/issues/183)).
+* Temperature graph automatically adjusts its Y axis range if necessary to
+ accomodate the plotted data (see also [#632](https://github.com/foosel/OctoPrint/issues/632)).
+* "Fan on" command now always sends `S255` parameter for better compatibility
+ across firmwares.
### Bug Fixes
* It's not possible anymore to select files that are not machinecode files (e.g.
GCODE) for printing on the file API.
+* Changes to a user's personal settings via the UI now propagate across sessions.
+* [#1047](https://github.com/foosel/OctoPrint/issues/1047) - Fixed 90 degree
+ webcam rotation for iOS Safari.
+
+## 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)
@@ -225,7 +455,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`.
diff --git a/MANIFEST.in b/MANIFEST.in
index 82ddf50b3..158333105 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -2,7 +2,11 @@ recursive-include src/octoprint/static *
recursive-include src/octoprint/templates *
recursive-include src/octoprint/plugins *
recursive-include src/octoprint/translations *
+include src/octoprint/util/piptestballoon/setup.py
include versioneer.py
include src/octoprint/_version.py
+include AUTHORS.md
+include CHANGELOG.md
+include LICENSE
include README.md
include requirements.txt
diff --git a/README.md b/README.md
index ac80de2e2..4d5a9ba0b 100644
--- a/README.md
+++ b/README.md
@@ -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:
+
+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 --system-site-packages 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).
diff --git a/THIRDPARTYLICENSES.md b/THIRDPARTYLICENSES.md
new file mode 100644
index 000000000..2ac46c7da
--- /dev/null
+++ b/THIRDPARTYLICENSES.md
@@ -0,0 +1,54 @@
+# Third Party Licenses
+
+## Web Interface
+
+ * [AVLTree](https://gist.github.com/viking/2424106) (modified): GPL, LGPL (dual licensed)
+ * [Babel JavaScript Support](https://github.com/mitsuhiko/babel/blob/master/contrib/babel.js): BSD
+ * [Bootstrap](http://getbootstrap.com/): Apache License 2.0
+ * [Bootstrap Modal](http://jschr.github.io/bootstrap-modal/): Apache License 2.0
+ * [Bootstrap Slider Knockout Bindings](https://github.com/cosminstefanxp/bootstrap-slider-knockout-binding): MIT
+ * [Bootstrap Slider](http://seiyria.com/bootstrap-slider/): Apache License 2.0
+ * [Bootstrap Tabdrop](http://www.eyecon.ro/bootstrap-tabdrop): Apache License 2.0
+ * [Detect Mobile Browser](http://detectmobilebrowsers.com/): Public Domain
+ * [Flot](http://www.flotcharts.org/): MIT
+ * [JavaScript MD5](https://github.com/blueimp/JavaScript-MD5): MIT
+ * [JQuery](http://jquery.com/): MIT
+ * [JQuery Bootstrap Wizard](http://github.com/VinceG/twitter-bootstrap-wizard): MIT, GPL (dual licensed)
+ * [JQuery File Upload](https://github.com/blueimp/jQuery-File-Upload): MIT
+ * [JQuery iframe transport](https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.iframe-transport.js): MIT
+ * [JQuery QRCode](http://larsjung.de/jquery-qrcode/): MIT
+ * [JQuery Slimscroll](http://rocha.la/jQuery-slimScroll): MIT, GPL (dual licensed)
+ * [JQuery UI Core, Mouse, Slider and Widget](http://jqueryui.com): MIT
+ * [Knockout](http://knockoutjs.com/): MIT
+ * [LESS](http://lesscss.org): Apache License 2.0
+ * [lodash](https://lodash.com): MIT
+ * [Loglevel](https://github.com/pimterry/loglevel): MIT
+ * [Modernizr](http://modernizr.com): MIT
+ * [Moment.js](http://momentjs.com/): MIT
+ * [PNotify](http://sciactive.com/pnotify/): GPL, LGPL, MPL (triple licensed)
+ * [pusher.color.js](http://cache.preserve.io/5g18q0pw/index.html) (original link dead): MIT
+ * [SockJS](https://github.com/sockjs/sockjs-client): MIT
+ * [sprintf-js](http://alexei.ro/): BSD
+
+## Server
+
+ * [Flask](http://flask.pocoo.org/): BSD
+ * [Flask-Assets](http://github.com/miracle2k/flask-assets): BSD
+ * [Flask-Babel](http://github.com/mitsuhiko/flask-babel): BSD
+ * [Flask-Login](https://flask-login.readthedocs.org/en/latest/https://github.com/maxcountryman/flask-login): MIT
+ * [Flask-Markdown](http://github.com/dcolish/flask-markdown): BSD
+ * [Flask-Principal](http://packages.python.org/Flask-Principal/): MIT
+ * [netaddr](https://github.com/drkjam/netaddr/): BSD
+ * [netifaces](https://bitbucket.org/al45tair/netifaces): MIT
+ * [pkginfo](http://pypi.python.org/pypi/pkginfo/): Python
+ * [psutil](https://github.com/giampaolo/psutil): BSD
+ * [pylru](https://github.com/jlhutch/pylru): GPLv2
+ * [pyserial](http://pyserial.sourceforge.net/): Python
+ * [PyYAML](http://pyyaml.org/wiki/PyYAML): MIT
+ * [requests](http://python-requests.org/): Apache License 2.0
+ * [rsa](http://stuvel.eu/rsa): Apache License 2.0
+ * [sarge](http://sarge.readthedocs.org/): BSD
+ * [semantic_version](https://github.com/rbarrois/python-semanticversion): BSD
+ * [SockJS-Tornado](http://github.com/mrjoes/sockjs-tornado/): MIT
+ * [Tornado](http://www.tornadoweb.org/): Apache License 2.0
+ * [watchdog](http://github.com/gorakhargosh/watchdog): Apache License 2.0
diff --git a/docs/api/job.rst b/docs/api/job.rst
index 3bcc1fde2..eeb3b0718 100644
--- a/docs/api/job.rst
+++ b/docs/api/job.rst
@@ -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...
diff --git a/docs/api/logs.rst b/docs/api/logs.rst
index b2759aadb..875427842 100644
--- a/docs/api/logs.rst
+++ b/docs/api/logs.rst
@@ -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.
diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst
index 15cfbbbf4..27a20352f 100644
--- a/docs/configuration/config_yaml.rst
+++ b/docs/configuration/config_yaml.rst
@@ -611,6 +611,32 @@ Use the following settings to configure the serial connection to the printer:
additionalPorts:
- /dev/myPrinterSymlink
+ # Use this to define additional baud rates to offer for connecting to serial ports. Must be a
+ # valid integer. Defaults to not set
+ additionalBaudrates:
+ - 123456
+
+ # 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 +647,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 +718,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::
diff --git a/docs/configuration/logging_yaml.rst b/docs/configuration/logging_yaml.rst
index daf8b462d..549611884 100644
--- a/docs/configuration/logging_yaml.rst
+++ b/docs/configuration/logging_yaml.rst
@@ -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:
:
level:
@@ -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 `_.
\ No newline at end of file
+`Python documentation on LogRecord attributes `_.
diff --git a/docs/events/index.rst b/docs/events/index.rst
index 1dfde9007..70aa5d2f9 100644
--- a/docs/events/index.rst
+++ b/docs/events/index.rst
@@ -106,6 +106,9 @@ ClientClosed
Printer communication
---------------------
+Connecting
+ The server is attempting to connect to the printer.
+
Connected
The server has connected to the printer.
@@ -114,6 +117,11 @@ Connected
* ``port``: the connected serial port
* ``baudrate``: the baud rate
+Disconnecting
+ The server is going to disconnect from the printer. Note that this
+ event might not always be sent when the server and printer get disconnected
+ from each other. Do not depend on this for critical life cycle management.
+
Disconnected
The server has disconnected from the printer
@@ -124,6 +132,15 @@ Error
* ``error``: the error string
+PrinterStateChanged
+ The state of the printer changed.
+
+ Payload:
+
+ * ``state_id``: Id of the new state. See
+ :func:`~octoprint.printer.PrinterInterface.get_state_id` for possible values.
+ * ``state_string``: Text representation of the new state.
+
File handling
-------------
diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst
index 011e15c36..22ad482b7 100644
--- a/docs/features/gcode_scripts.rst
+++ b/docs/features/gcode_scripts.rst
@@ -26,6 +26,10 @@ Predefined Scripts
The following GCODE scripts are sent by OctoPrint automatically:
* ``afterPrinterConnected``: Sent after OctoPrint successfully connected to a printer. Defaults to an empty script.
+ * ``beforePrinterDisconnected``: Sent just before OctoPrint (actively) closes the connection to the printer. Defaults
+ to an empty script. Note that this will *not* be sent for unexpected connection cut offs, e.g. in case of errors
+ on the serial line, only when the user clicks the "Disconnect" button or the printer requests a disconnect via an
+ :ref:`action command ` .
* ``beforePrintStarted``: Sent just before a print job is started. Defaults to an empty script.
* ``afterPrintCancelled``: Sent just after a print job was cancelled. Defaults to the
:ref:`bundled script listed below `.
diff --git a/docs/plugins/concepts.rst b/docs/plugins/concepts.rst
index 42b66d377..6170ae5d3 100644
--- a/docs/plugins/concepts.rst
+++ b/docs/plugins/concepts.rst
@@ -328,6 +328,8 @@ An overview of these properties follows.
OctoPrint's printer management object, an instance of :class:`octoprint.printer.PrinterInterface`.
``self._app_session_manager``
OctoPrint's application session manager, an instance of :class:`octoprint.server.util.flask.AppSessionManager`.
+``self._user_manager``
+ OctoPrint's user manager, an instance of :class:`octoprint.users.UserManager`.
.. seealso::
diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst
index 36a6e2c36..add3d78b4 100644
--- a/docs/plugins/hooks.rst
+++ b/docs/plugins/hooks.rst
@@ -159,6 +159,32 @@ This describes actually four hooks:
:param str gcode: Parsed GCODE command, e.g. ``G0`` or ``M110``, may also be None if no known command could be parsed
:return: None, 1-tuple, 2-tuple or string, see the description above for details.
+.. _sec-plugins-hook-comm-protocol-gcode-received:
+
+octoprint.comm.protocol.gcode.received
+--------------------------------------
+
+.. py:function:: hook(comm_instance, line, *args, **kwargs)
+
+ Get the returned lines sent by the printer. Handlers should return the received line or in any case, the modified
+ version of it. If the the handler returns None, processing will be aborted and the communication layer will get an
+ empty string as the received line. Note that Python functions will also automatically return ``None`` if an empty
+ ``return`` statement is used or just nothing is returned explicitely from the handler.
+
+ **Example:**
+
+ Looks for the response of a M115, which contains information about the MACHINE_TYPE, among other things.
+
+ .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/read_m115_response.py
+ :linenos:
+ :tab-width: 4
+ :caption: `read_m115_response.py `_
+
+ :param MachineCom comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
+ :param str line: The line received from the printer.
+ :return: The received line or in any case, a modified version of it.
+ :rtype: str
+
.. _sec-plugins-hook-comm-protocol-scripts:
octoprint.comm.protocol.scripts
diff --git a/docs/plugins/mixins.rst b/docs/plugins/mixins.rst
index b4063fd7f..791d2aa35 100644
--- a/docs/plugins/mixins.rst
+++ b/docs/plugins/mixins.rst
@@ -18,6 +18,7 @@ StartupPlugin
.. autoclass:: octoprint.plugin.StartupPlugin
:members:
+ :show-inheritance:
.. _sec-plugins-mixins-shutdownplugin:
@@ -26,6 +27,7 @@ ShutdownPlugin
.. autoclass:: octoprint.plugin.ShutdownPlugin
:members:
+ :show-inheritance:
.. _sec-plugins-mixins-settingsplugin:
@@ -34,6 +36,7 @@ SettingsPlugin
.. autoclass:: octoprint.plugin.SettingsPlugin
:members:
+ :show-inheritance:
.. _sec-plugins-mixins-assetplugin:
@@ -42,6 +45,7 @@ AssetPlugin
.. autoclass:: octoprint.plugin.AssetPlugin
:members:
+ :show-inheritance:
.. _sec-plugins-mixins-templateplugin:
@@ -50,6 +54,25 @@ TemplatePlugin
.. autoclass:: octoprint.plugin.TemplatePlugin
:members:
+ :show-inheritance:
+
+.. _sec-plugins-mixins-wizardplugin:
+
+WizardPlugin
+------------
+
+.. autoclass:: octoprint.plugin.WizardPlugin
+ :members:
+ :show-inheritance:
+
+.. _sec-plugins-mixins-uiplugin:
+
+UiPlugin
+--------
+
+.. autoclass:: octoprint.plugin.UiPlugin
+ :members:
+ :show-inheritance:
.. _sec-plugins-mixins-simpleapiplugin:
@@ -58,6 +81,7 @@ SimpleApiPlugin
.. autoclass:: octoprint.plugin.SimpleApiPlugin
:members:
+ :show-inheritance:
.. _sec-plugins-mixins-blueprintplugin:
@@ -66,6 +90,7 @@ BlueprintPlugin
.. autoclass:: octoprint.plugin.BlueprintPlugin
:members:
+ :show-inheritance:
.. _sec-plugins-mixins-eventhandlerplugin:
@@ -74,6 +99,7 @@ EventHandlerPlugin
.. autoclass:: octoprint.plugin.EventHandlerPlugin
:members:
+ :show-inheritance:
.. _sec-plugins-mixins-progressplugin:
@@ -82,6 +108,7 @@ ProgressPlugin
.. autoclass:: octoprint.plugin.ProgressPlugin
:members:
+ :show-inheritance:
.. _sec-plugins-mixins-slicerplugin:
@@ -90,4 +117,5 @@ SlicerPlugin
.. autoclass:: octoprint.plugin.SlicerPlugin
:members:
+ :show-inheritance:
diff --git a/docs/plugins/viewmodels.rst b/docs/plugins/viewmodels.rst
index d5b1ddccc..6d736e7d3 100644
--- a/docs/plugins/viewmodels.rst
+++ b/docs/plugins/viewmodels.rst
@@ -171,7 +171,7 @@ onAfterTabChange
getAdditionalControls
Your viewmodel may return additional custom control definitions for inclusion on the "Control" tab of OctoPrint's
- interface. See :ref:`the custom control feature`.
+ interface. See :ref:`the custom control feature`.
onSettingsShown
Called when the settings dialog is shown.
@@ -189,6 +189,27 @@ onUserSettingsShown
onUserSettingsHidden
Called when the user settings dialog is hidden.
+onWizardDetails
+ Called with the response from the wizard detail API call initiated before opening the wizard dialog. Will contain
+ the data from all :class:`~octoprint.plugin.WizardPlugin` implementations returned by their :meth:`~octoprint.plugin.WizardPlugin.get_wizard_details`
+ method, mapped by the plugin identifier.
+
+onWizardTabChange
+ Called before the wizard tab/step is changed, with the ids of the current and the next tab as parameters. Return false
+ in order to prevent the tab change, e.g. if the wizard step is mandatory and not yet completed by the user. Take a look at
+ the "Core Wizard" plugin bundled with OctoPrint and the ACL wizard step in particular for an example on how to use this.
+
+onAfterWizardTabChange
+ Called after the wizard tab/step is changed, with the id of the current tab as parameter.
+
+onBeforeWizardFinish
+ Called before executing the finishing of the wizard. Return false here to stop the actual finish, e.g. if some step is
+ still incomplete.
+
+onWizardFinish
+ Called after executing the finishing of the wizard and before closing the dialog. Return ``reload`` here in order to
+ instruct OctoPrint to reload the UI after the wizard closes.
+
In order to hook into any of those callbacks, just have your viewmodel define a function named accordingly, e.g.
to get called after all viewmodels have been bound during application startup, implement a function ``onAllBound``
on your viewmodel, taking a list of all bound viewmodels:
diff --git a/run b/run
index 0c51da39d..1145a24fd 100755
--- a/run
+++ b/run
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python2
import os
import sys
diff --git a/scripts/octoprint.init b/scripts/octoprint.init
index e1079b4e4..97601ebb4 100644
--- a/scripts/octoprint.init
+++ b/scripts/octoprint.init
@@ -133,6 +133,9 @@ case "$1" in
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
+ status)
+ status_of_proc -p $PIDFILE $DAEMON $NAME && exit 0 || exit $?
+ ;;
restart)
log_daemon_msg "Restarting $DESC" "$NAME"
do_stop
@@ -152,8 +155,7 @@ case "$1" in
esac
;;
*)
- echo "Usage: $SCRIPTNAME {start|stop|restart}" >&2
+ echo "Usage: $SCRIPTNAME {start|stop|status|restart}" >&2
exit 3
;;
esac
-
diff --git a/setup.cfg b/setup.cfg
index 2c516b270..cbda2efbf 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -1,7 +1,5 @@
-
-# See the docstring in versioneer.py for instructions. Note that you must
-# re-run 'versioneer.py setup' after changing this section, and commit the
-# resulting files.
+[metadata]
+description-file = README.md
[versioneer]
VCS = git
diff --git a/setup.py b/setup.py
index ed83e2675..c8ba6b727 100644
--- a/setup.py
+++ b/setup.py
@@ -1,7 +1,8 @@
-#!/usr/bin/env python
+#!/usr/bin/env python2
# coding=utf-8
from setuptools import setup, find_packages
+from distutils.command.build_py import build_py as _build_py
import os
import versioneer
@@ -15,23 +16,25 @@ import octoprint_setuptools
INSTALL_REQUIRES = [
"flask>=0.9,<0.11",
"werkzeug==0.8.3",
- "tornado==4.0.1",
- "sockjs-tornado>=1.0.0",
+ "tornado==4.0.2",
+ "sockjs-tornado==1.0.2",
"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",
+ "Flask-Markdown==0.3",
+ "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",
"Click"
]
@@ -47,7 +50,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
@@ -56,12 +62,41 @@ EXTRA_REQUIRES = dict(
]
)
+# Additional requirements for setup
+SETUP_REQUIRES = []
+
# Dependency links for any of the aforementioned dependencies
DEPENDENCY_LINKS = []
#-----------------------------------------------------------------------------------------------------------------------
# Anything below here is just command setup and general setup configuration
+def data_copy_build_py_factory(files, baseclass):
+ class data_copy_build_py(baseclass):
+ files = dict()
+
+ def run(self):
+ import shutil
+ if not self.dry_run:
+ for directory, files in self.__class__.files.items():
+ target_dir = os.path.join(self.build_lib, directory)
+ self.mkpath(target_dir)
+
+ for entry in files:
+ if isinstance(entry, tuple):
+ if len(entry) != 2:
+ continue
+ source, dest = entry
+ else:
+ source = dest = entry
+ shutil.copy(source, os.path.join(target_dir, dest))
+
+ baseclass.run(self)
+
+ return type(data_copy_build_py)(data_copy_build_py.__name__,
+ (data_copy_build_py,),
+ dict(files=files))
+
def get_cmdclass():
cmdclass = versioneer.get_cmdclass()
@@ -74,6 +109,14 @@ def get_cmdclass():
bundled_dir = os.path.join("src", "octoprint", "translations")
cmdclass.update(octoprint_setuptools.get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, pack_name_prefix="OctoPrint-i18n-", pack_path_prefix="", bundled_dir=bundled_dir))
+ cmdclass["build_py"] = data_copy_build_py_factory({
+ "octoprint/templates/_data": [
+ "AUTHORS.md",
+ "CHANGELOG.md",
+ "THIRDPARTYLICENSES.md",
+ ]
+ }, cmdclass["build_py"] if "build_py" in cmdclass else _build_py)
+
return cmdclass
@@ -82,8 +125,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",
@@ -110,17 +167,16 @@ def params():
packages = find_packages(where="src")
package_dir = {
- "": "src"
+ "": "src",
}
package_data = {
- "octoprint": octoprint_setuptools.package_data_dirs('src/octoprint', ['static', 'templates', 'plugins', 'translations'])
+ "octoprint": octoprint_setuptools.package_data_dirs('src/octoprint',
+ ['static', 'templates', 'plugins', 'translations'])
+ + ['util/piptestballoon/setup.py']
}
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
diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py
index b00e7646b..2643b9d7c 100644
--- a/src/octoprint/__init__.py
+++ b/src/octoprint/__init__.py
@@ -1,11 +1,7 @@
-#!/usr/bin/env python
+#!/usr/bin/env python2
# coding=utf-8
from __future__ import absolute_import, print_function
-__author__ = "Gina Häußge "
-__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
-__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
-
import sys
import click
diff --git a/src/octoprint/events.py b/src/octoprint/events.py
index 828862336..33fc04cbc 100644
--- a/src/octoprint/events.py
+++ b/src/octoprint/events.py
@@ -28,9 +28,14 @@ class Events(object):
STARTUP = "Startup"
# connect/disconnect to printer
+ CONNECTING = "Connecting"
CONNECTED = "Connected"
+ DISCONNECTING = "Disconnecting"
DISCONNECTED = "Disconnected"
+ # State changes
+ PRINTER_STATE_CHANGED = "PrinterStateChanged"
+
# connect/disconnect by client
CLIENT_OPENED = "ClientOpened"
CLIENT_CLOSED = "ClientClosed"
@@ -74,6 +79,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"
diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py
index dae5ed51d..34f31680c 100644
--- a/src/octoprint/filemanager/__init__.py
+++ b/src/octoprint/filemanager/__init__.py
@@ -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
@@ -155,7 +196,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
diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py
index 9f238cf93..1fe59e352 100644
--- a/src/octoprint/filemanager/storage.py
+++ b/src/octoprint/filemanager/storage.py
@@ -584,24 +584,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)):
@@ -628,24 +610,6 @@ class LocalFileStorage(StorageInterface):
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 "", line 1, in
- ValueError: name must not contain / or \
- >>> storage.sanitize_name("also\\no\\backslashes.gco")
- Traceback (most recent call last):
- File "", line 1, in
- ValueError: name must not contain / or \
"""
if name is None:
return None
@@ -664,22 +628,6 @@ class LocalFileStorage(StorageInterface):
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 "", line 1, in
- ValueError: path not contained in base folder: /some/folder/out/of/the/basefolder
"""
if path[0] == "/" or path[0] == ".":
path = path[1:]
diff --git a/src/octoprint/filemanager/util.py b/src/octoprint/filemanager/util.py
index 105987f37..f3fe20fb3 100644
--- a/src/octoprint/filemanager/util.py
+++ b/src/octoprint/filemanager/util.py
@@ -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)
diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py
index 6180a8a6e..e81966b32 100644
--- a/src/octoprint/plugin/__init__.py
+++ b/src/octoprint/plugin/__init__.py
@@ -106,7 +106,9 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
EventHandlerPlugin,
SlicerPlugin,
AppPlugin,
- ProgressPlugin]
+ ProgressPlugin,
+ WizardPlugin,
+ UiPlugin]
if plugin_entry_points is None:
plugin_entry_points = "octoprint.plugin"
if plugin_disabled_list is None:
@@ -159,7 +161,7 @@ def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_prepr
set_preprocessors=set_preprocessors)
-def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None):
+def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None):
"""
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
@@ -205,7 +207,7 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
if kwargs is None:
kwargs = dict()
- plugins = plugin_manager().get_implementations(*types)
+ plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
for plugin in plugins:
if hasattr(plugin, method):
try:
@@ -301,19 +303,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
@@ -332,6 +331,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),
@@ -339,7 +339,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)
)
self.deprecated_access_methods = dict(
getInt ="get_int",
@@ -350,6 +351,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
@@ -443,6 +455,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:
diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py
index 31a5bbd5f..a5c223f35 100644
--- a/src/octoprint/plugin/core.py
+++ b/src/octoprint/plugin/core.py
@@ -12,6 +12,12 @@ way and could be extracted into a separate Python module in the future.
.. autoclass:: Plugin
:members:
+.. autoclass:: RestartNeedingPlugin
+ :members:
+
+.. autoclass:: SortablePlugin
+ :members:
+
"""
from __future__ import absolute_import
@@ -23,7 +29,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import os
import imp
-from collections import defaultdict, namedtuple
+from collections import defaultdict, namedtuple, OrderedDict
import logging
import pkg_resources
@@ -127,6 +133,7 @@ class PluginInfo(object):
self.enabled = True
self.bundled = False
self.loaded = False
+ self.managable = True
self._name = name
self._version = version
@@ -449,10 +456,11 @@ class PluginManager(object):
self.enabled_plugins = dict()
self.disabled_plugins = dict()
- self.plugin_hooks = defaultdict(list)
self.plugin_implementations = dict()
self.plugin_implementations_by_type = defaultdict(list)
+ self._plugin_hooks = defaultdict(list)
+
self.implementation_injects = dict()
self.implementation_inject_factories = []
self.implementation_pre_inits = []
@@ -468,12 +476,35 @@ class PluginManager(object):
self.marked_plugins = defaultdict(list)
+ self._python_install_dir = None
+ self._python_virtual_env = False
+ self._detect_python_environment()
+
+ self.reload_plugins(startup=True, initialize_implementations=False)
+
+ def _detect_python_environment(self):
+ from distutils.command.install import install as cmd_install
+ from distutils.dist import Distribution
+ import sys
+
+ cmd = cmd_install(Distribution())
+ cmd.finalize_options()
+
+ self._python_install_dir = cmd.install_lib
+ self._python_prefix = sys.prefix
+ self._python_virtual_env = hasattr(sys, "real_prefix") \
+ or (hasattr(sys, "base_prefix") and sys.prefix != sys.base_prefix)
+
@property
def plugins(self):
plugins = dict(self.enabled_plugins)
plugins.update(self.disabled_plugins)
return plugins
+ @property
+ def plugin_hooks(self):
+ return {key: map(lambda v: (v[1], v[2]), value) for key, value in self._plugin_hooks.items()}
+
def find_plugins(self, existing=None, ignore_uninstalled=True):
if existing is None:
existing = dict(self.plugins)
@@ -490,12 +521,13 @@ class PluginManager(object):
result = dict()
for folder in folders:
- readonly = False
+ flagged_readonly = False
if isinstance(folder, (list, tuple)):
if len(folder) == 2:
- folder, readonly = folder
+ folder, flagged_readonly = folder
else:
continue
+ actual_readonly = not os.access(folder, os.W_OK)
if not os.path.exists(folder):
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
@@ -518,8 +550,8 @@ class PluginManager(object):
plugin = self._import_plugin_from_module(key, folder=folder)
if plugin:
plugin.origin = FolderOrigin("folder", folder)
- if readonly:
- plugin.bundled = True
+ plugin.managable = not flagged_readonly and not actual_readonly
+ plugin.bundled = flagged_readonly
plugin.enabled = False
@@ -530,9 +562,18 @@ class PluginManager(object):
def _find_plugins_from_entry_points(self, groups, existing, ignore_uninstalled=True):
result = dict()
- # let's make sure we have a current working set
+ # let's make sure we have a current working set ...
working_set = pkg_resources.WorkingSet()
+ # ... including the user's site packages
+ import site
+ import sys
+ if site.ENABLE_USER_SITE:
+ if not site.USER_SITE in working_set.entries:
+ working_set.add_entry(site.USER_SITE)
+ if not site.USER_SITE in sys.path:
+ site.addsitedir(site.USER_SITE)
+
if not isinstance(groups, (list, tuple)):
groups = [groups]
@@ -565,6 +606,16 @@ class PluginManager(object):
plugin = self._import_plugin_from_module(key, **kwargs)
if plugin:
plugin.origin = EntryPointOrigin("entry_point", group, module_name, package_name, version)
+
+ # plugin is manageable if its location is writable and OctoPrint
+ # is either not running from a virtual env or the plugin is
+ # installed in that virtual env - the virtual env's pip will not
+ # allow us to uninstall stuff that is installed outside
+ # of the virtual env, so this check is necessary
+ plugin.managable = os.access(plugin.location, os.W_OK) \
+ and (not self._python_virtual_env
+ or plugin.location.startswith(self._python_prefix))
+
plugin.enabled = False
result[key] = plugin
@@ -635,15 +686,24 @@ class PluginManager(object):
hooks=sum(map(lambda x: len(x), self.plugin_hooks.values()))
))
- def mark_plugin(self, name, uninstalled=None):
+ def mark_plugin(self, name, **kwargs):
if not name in self.plugins:
- self.logger.warn("Trying to mark an unknown plugin {name}".format(**locals()))
+ self.logger.debug("Trying to mark an unknown plugin {name}".format(**locals()))
- if uninstalled is not None:
- if uninstalled and not name in self.marked_plugins["uninstalled"]:
- self.marked_plugins["uninstalled"].append(name)
- elif not uninstalled and name in self.marked_plugins["uninstalled"]:
- self.marked_plugins["uninstalled"].remove(name)
+ for key, value in kwargs.items():
+ if value is None:
+ continue
+
+ if value and not name in self.marked_plugins[key]:
+ self.marked_plugins[key].append(name)
+ elif not value and name in self.marked_plugins[key]:
+ self.marked_plugins[key].remove(name)
+
+ def is_plugin_marked(self, name, key):
+ if not name in self.plugins:
+ return False
+
+ return name in self.marked_plugins[key]
def load_plugin(self, name, plugin=None, startup=False, initialize_implementation=True):
if not name in self.plugins:
@@ -777,8 +837,15 @@ class PluginManager(object):
plugin.hotchangeable = self.is_restart_needing_plugin(plugin)
# evaluate registered hooks
- for hook, callback in plugin.hooks.items():
- self.plugin_hooks[hook].append((name, callback))
+ for hook, definition in plugin.hooks.items():
+ try:
+ callback, order = self._get_callback_and_order(definition)
+ except ValueError as e:
+ self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
+ continue
+
+ self._plugin_hooks[hook].append((order, name, callback))
+ self._sort_hooks(hook)
# evaluate registered implementation
if plugin.implementation:
@@ -789,9 +856,16 @@ class PluginManager(object):
self.plugin_implementations[name] = plugin.implementation
def _deactivate_plugin(self, name, plugin):
- for hook, callback in plugin.hooks.items():
+ for hook, definition in plugin.hooks.items():
try:
- self.plugin_hooks[hook].remove((name, callback))
+ callback, order = self._get_callback_and_order(definition)
+ except ValueError as e:
+ self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
+ continue
+
+ try:
+ self._plugin_hooks[hook].remove((order, name, callback))
+ self._sort_hooks(hook)
except ValueError:
# that's ok, the plugin was just not registered for the hook
pass
@@ -859,7 +933,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:
@@ -959,8 +1033,8 @@ class PluginManager(object):
location_str=location_str,
show_enabled=show_enabled,
enabled_strs=enabled_str),
- sorted(self.enabled_plugins.values(), key=lambda x: x.name.lower()),
- ))))
+ sorted(self.plugins.values(), key=lambda x: str(x).lower()))
+ )))
def get_plugin(self, identifier, require_enabled=True):
"""
@@ -1015,9 +1089,13 @@ class PluginManager(object):
if not hook in self.plugin_hooks:
return dict()
- return {hook[0]: hook[1] for hook in self.plugin_hooks[hook]}
- def get_implementations(self, *types):
+ result = OrderedDict()
+ for h in self.plugin_hooks[hook]:
+ result[h[0]] = h[1]
+ return result
+
+ def get_implementations(self, *types, **kwargs):
"""
Get all mixin implementations that implement *all* of the provided ``types``.
@@ -1028,6 +1106,8 @@ class PluginManager(object):
list: A list of all found implementations
"""
+ sorting_context = kwargs.get("sorting_context", None)
+
result = None
for t in types:
@@ -1038,10 +1118,28 @@ class PluginManager(object):
result = result.intersection(implementations)
if result is None:
- return dict()
- return [impl[1] for impl in result]
+ return []
- def get_filtered_implementations(self, f, *types):
+ def sort_func(impl):
+ sorting_value = None
+ if sorting_context is not None and isinstance(impl[1], SortablePlugin):
+ try:
+ sorting_value = impl[1].get_sorting_key(sorting_context)
+ except:
+ self.logger.exception("Error while trying to retrieve sorting order for plugin {}".format(impl[0]))
+
+ if sorting_value is not None:
+ try:
+ int(sorting_value)
+ except ValueError:
+ self.logger.warn("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context))
+ sorting_value = None
+
+ return sorting_value is None, sorting_value, impl[0]
+
+ return [impl[1] for impl in sorted(result, key=sort_func)]
+
+ def get_filtered_implementations(self, f, *types, **kwargs):
"""
Get all mixin implementation that implementat *all* of the provided ``types`` and match the provided filter `f`.
@@ -1054,7 +1152,7 @@ class PluginManager(object):
"""
assert callable(f)
- implementations = self.get_implementations(*types)
+ implementations = self.get_implementations(*types, sorting_context=kwargs.get("sorting_context", None))
return filter(f, implementations)
def get_helpers(self, name, *helpers):
@@ -1114,6 +1212,32 @@ class PluginManager(object):
try: client(plugin, data)
except: self.logger.exception("Exception while sending plugin data to client")
+ def _sort_hooks(self, hook):
+ self._plugin_hooks[hook] = sorted(self._plugin_hooks[hook],
+ key=lambda x: (x[0] is None, x[0], x[1], x[2]))
+
+ def _get_callback_and_order(self, hook):
+ if callable(hook):
+ return hook, None
+
+ elif isinstance(hook, tuple) and len(hook) == 2:
+ callback, order = hook
+
+ # test that callback is a callable
+ if not callable(callback):
+ raise ValueError("Hook callback is not a callable")
+
+ # test that number is an int
+ try:
+ int(order)
+ except ValueError:
+ raise ValueError("Hook order is not a number")
+
+ return callback, order
+
+ else:
+ raise ValueError("Invalid hook definition, neither a callable nor a 2-tuple (callback, order): {!r}".format(hook))
+
class InstalledEntryPoint(pkginfo.Installed):
@@ -1207,7 +1331,35 @@ class Plugin(object):
pass
class RestartNeedingPlugin(Plugin):
- pass
+ """
+ Mixin for plugin types that need a restart in order to be enabled.
+ """
+
+class SortablePlugin(Plugin):
+ """
+ Mixin for plugin types that are sortable.
+ """
+
+ def get_sorting_key(self, context=None):
+ """
+ Returns the sorting key to use for the implementation in the specified ``context``.
+
+ May return ``None`` if order is irrelevant.
+
+ Implementations returning None will be ordered by plugin identifier
+ after all implementations which did return a sorting key value that was
+ not None sorted by that.
+
+ Arguments:
+ context (str): The sorting context for which to provide the
+ sorting key value.
+
+ Returns:
+ int or None: An integer signifying the sorting key value of the plugin
+ (sorting will be done ascending), or None if the implementation
+ doesn't care about calling order.
+ """
+ return None
class PluginNeedsRestart(Exception):
def __init__(self, name):
diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py
index bf702cb68..50f5be59d 100644
--- a/src/octoprint/plugin/types.py
+++ b/src/octoprint/plugin/types.py
@@ -9,6 +9,9 @@ Please note that the plugin implementation types are documented in the section
.. autoclass:: OctoPrintPlugin
:show-inheritance:
+.. autoclass:: ReloadNeedingPlugin
+ :show-inheritance:
+
"""
from __future__ import absolute_import
@@ -18,7 +21,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"
-from .core import (Plugin, RestartNeedingPlugin)
+from .core import (Plugin, RestartNeedingPlugin, SortablePlugin)
class OctoPrintPlugin(Plugin):
@@ -77,7 +80,7 @@ class OctoPrintPlugin(Plugin):
and if not creating it before returning it. Injected by the plugin core system upon initialization of the
implementation.
- .. automethod:: get_plugin_data_folder
+ .. automethod:: get_plugin_data_folder
"""
def get_plugin_data_folder(self):
@@ -97,12 +100,18 @@ class OctoPrintPlugin(Plugin):
class ReloadNeedingPlugin(Plugin):
- pass
+ """
+ Mixin for plugin types that need a reload of the UI in order to become usable.
+ """
-class StartupPlugin(OctoPrintPlugin):
+class StartupPlugin(OctoPrintPlugin, SortablePlugin):
"""
The ``StartupPlugin`` allows hooking into the startup of OctoPrint. It can be used to start up additional services
on or just after the startup of the server.
+
+ ``StartupPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin`. The
+ relevant sorting context for :meth:`on_startup` is ``StartupPlugin.on_startup``,
+ the one for :meth:`on_after_startup` will be ``StartupPlugin.on_after_startup``.
"""
def on_startup(self, host, port):
@@ -127,11 +136,14 @@ class StartupPlugin(OctoPrintPlugin):
pass
-class ShutdownPlugin(OctoPrintPlugin):
+class ShutdownPlugin(OctoPrintPlugin, SortablePlugin):
"""
The ``ShutdownPlugin`` allows hooking into the shutdown of OctoPrint. It's usually used in conjunction with the
:class:`StartupPlugin` mixin, to cleanly shut down additional services again that where started by the :class:`StartupPlugin`
part of the plugin.
+
+ ``ShutdownPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin`.
+ The relevant sorting context will be ``ShutdownPlugin.on_shutdown``.
"""
def on_shutdown(self):
@@ -149,6 +161,8 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin):
A typical usage of the ``AssetPlugin`` functionality is to embed a custom view model to be used by templates injected
through a :class:`TemplatePlugin`.
+
+ ``AssetPlugin`` is a :class:`~octoprint.plugins.core.RestartNeedingPlugin`.
"""
def get_asset_folder(self):
@@ -249,6 +263,30 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
wrapper div and the link in the navigation will have the additional classes and styles applied as defined via the
supplied configuration supplied through :func:`get_template_configs`.
+ Wizards
+ Plugins may define wizard dialogs to display to the user if necessary (e.g. in case of missing information that
+ needs to be queried from the user to make the plugin work). Note that with the current implementations, all
+ wizard dialogs will be will always be sorted by their ``mandatory`` attribute (which defaults to ``False``) and then
+ alphabetically by their ``name``. Hence, mandatory wizard steps will come first, sorted alphabetically, then the
+ optional steps will follow, also alphabetically. A wizard dialog provided through a plugin will only be displayed
+ if the plugin reports the wizard as being required through :meth:`~octoprint.plugin.WizardPlugin.is_wizard_required`.
+ Please also refer to the :class:`~octoprint.plugin.WizardPlugin` mixin for further details on this.
+
+ The included template must be called ``_wizard.jinja2`` (e.g. ``myplugin_wizard.jinja2``) unless
+ overridden by the configuration supplied through :func:`get_template_configs`.
+
+ The template will be already wrapped into the necessary structure, plugins just need to supply the pure content.
+ The wrapper div and the link in the wizard navigation will have the additional classes and styles applied as defined
+ via the supplied configuration supplied through :func:`get_template_configs`.
+
+ .. note::
+
+ A note about ``mandatory`` wizard steps: In the current implementation, marking a wizard step as
+ mandatory will *only* make it styled accordingly. It is the task of the :ref:`view model `
+ to actually prevent the user from skipping the dialog by implementing the ``onWizardTabChange``
+ callback and returning ``false`` there if it is detected that the user hasn't yet filled in the
+ wizard step.
+
Generic
Plugins may also inject arbitrary templates into the page of the web interface itself, e.g. in order to
add overlays or dialogs to be called from within the plugin's javascript code.
@@ -273,6 +311,8 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
responsibility to ensure that all core functionality is still maintained.
Plugins can also add additional template types by implementing the :ref:`octoprint.ui.web.templatetypes ` hook.
+
+ ``TemplatePlugin`` is a :class:`~octoprint.plugin.core.ReloadNeedingPlugin`.
"""
def get_template_configs(self):
@@ -396,6 +436,17 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
* - styles_content
- Like ``styles`` but only applied to the content pane itself.
+ ``wizard`` type
+
+ .. list-table::
+ :widths: 5 95
+
+ * - mandatory
+ - Whether the wizard step is mandatory (True) or not (False). Optional,
+ defaults to False. If set to True, OctoPrint will sort visually mark
+ the step as mandatory in the UI (bold in the navigation and a little
+ alert) and also sort it into the first half.
+
.. note::
As already outlined above, each template type has a default template name (i.e. the default navbar template
@@ -450,6 +501,357 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
return os.path.join(self._basefolder, "templates")
+class UiPlugin(OctoPrintPlugin, SortablePlugin):
+ """
+ The ``UiPlugin`` mixin allows plugins to completely replace the UI served
+ by OctoPrint when requesting the main page hosted at `/`.
+
+ OctoPrint will query whether your mixin implementation will handle a
+ provided request by calling :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` with the Flask
+ `Request `_ object as
+ parameter. If you plugin returns `True` here, OctoPrint will next call
+ :meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a couple of parameters like
+ - again - the Flask Request object and the render keyword arguments as
+ used by the default OctoPrint web interface. For more information see below.
+
+ There are two methods used in order to allow for caching of the actual
+ response sent to the client. Whatever a plugin implementation returns
+ from the call to its :meth:`~octoprint.plugin.UiPlugin.on_ui_render` method
+ will be cached server side. The cache will be emptied in case of explicit
+ no-cache headers sent by the client, or if the ``_refresh`` query parameter
+ on the request exists and is set to ``true``. To prevent caching of the
+ response altogether, a plugin may set no-cache headers on the returned
+ response as well.
+
+ ``UiPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin`. The
+ relevant sorting context when acting as a UiPlugin is ``UiPlugin.will_handle_ui``.
+ The first plugin to return ``True`` will be the one whose ui will be used,
+ no further calls to :meth:`~octoprint.plugin.UiPlugin.on_ui_render` will be performed.
+
+ If implementations want to serve custom templates in the :meth:`~octoprint.plugin.UiPlugin.on_ui_render`
+ method it is recommended to also implement the :class:`~octoprint.plugin.TemplatePlugin`
+ mixin.
+
+ **Example**
+
+ What follows is a very simple example that renders a different (non functional and
+ only exemplary) UI if the requesting client has a UserAgent string hinting
+ at it being a mobile device:
+
+ .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/dummy_mobile_ui/__init__.py
+ :linenos:
+ :tab-width: 4
+ :caption: `dummy_mobile_ui/__init__.py `_
+
+ .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2
+ :linenos:
+ :tab-width: 4
+ :caption: `dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2 `_
+
+ Try installing the above plugin ``dummy_mobile_ui`` (also available in the
+ `plugin examples repository `_)
+ into your OctoPrint instance. If you access it from a regular desktop browser,
+ you should still see the default UI. However if you access it from a mobile
+ device (make sure to not have that request the desktop version of pages!)
+ you should see the very simple dummy page defined above.
+ """
+
+ def will_handle_ui(self, request):
+ """
+ Called by OctoPrint to determine if the mixin implementation will be
+ able to handle the ``request`` provided as a parameter.
+
+ Return ``True`` here to signal that your implementation will handle
+ the request and that the result of its :meth:`~octoprint.plugin.UiPlugin.on_ui_render` method
+ is what should be served to the user.
+
+ Arguments:
+ request (flask.Request): A Flask `Request `_
+ object.
+
+ Returns:
+ bool: ``True`` if the the implementation will serve the request,
+ ``False`` otherwise.
+ """
+ return False
+
+ def on_ui_render(self, now, request, render_kwargs):
+ """
+ Called by OctoPrint to retrieve the response to send to the client
+ for the ``request`` to ``/``. Only called if :meth:`~octoprint.plugin.UiPlugin.will_handle_ui`
+ returned ``True``.
+
+ ``render_kwargs`` will be a dictionary (whose contents are cached) which
+ will contain the following key and value pairs (note that not all
+ key value pairs contained in the dictionary are listed here, only
+ those you should depend on as a plugin developer at the current time):
+
+ .. list-table::
+ :widths: 5 95
+
+ * - debug
+ - ``True`` if debug mode is enabled, ``False`` otherwise.
+ * - firstRun
+ - ``True`` if the server is being run for the first time (not
+ configured yet), ``False`` otherwise.
+ * - version
+ - OctoPrint's version information. This is a ``dict`` with the
+ following keys:
+
+ .. list-table::
+ :widths: 5 95
+
+ * - number
+ - The version number (e.g. ``x.y.z``)
+ * - branch
+ - The GIT branch from which the OctoPrint instance was built
+ (e.g. ``master``)
+ * - display
+ - The full human readable version string, including the
+ branch information (e.g. ``x.y.z (master branch)``
+
+ * - uiApiKey
+ - The UI API key to use for unauthorized API requests. This is
+ freshly generated on every server restart.
+ * - templates
+ - Template data to render in the UI. Will be a ``dict`` containing entries
+ for all known template types.
+
+ The sub structure for each key will be as follows:
+
+ .. list-table::
+ :widths: 5 95
+
+ * - order
+ - A list of template names in the order they should appear
+ in the final rendered page
+ * - entries
+ - The template entry definitions to render. Depending on the
+ template type those are either 2-tuples of a name and a ``dict``
+ or directly ``dicts`` with information regarding the
+ template to render.
+
+ For the possible contents of the data ``dicts`` see the
+ :class:`~octoprint.plugin.TemplatePlugin` mixin.
+
+ * - pluginNames
+ - A list of names of :class:`~octoprint.plugin.TemplatePlugin`
+ implementation that were enabled when creating the ``templates``
+ value.
+ * - locales
+ - The locales for which there are translations available.
+
+ On top of that all additional template variables as provided by :meth:`~octoprint.plugin.TemplatePlugin.get_template_vars`
+ will be contained in the dictionary as well.
+
+ Arguments:
+ now (datetime.datetime): The datetime instance representing "now"
+ for this request, in case your plugin implementation needs this
+ information.
+ request (flask.Request): A Flask `Request `_ object.
+ render_kwargs (dict): The (cached) render keyword arguments that
+ would usually be provided to the core UI render function.
+
+ Returns:
+ flask.Response: Should return a Flask `Response `_
+ object that can be served to the requesting client directly. May be
+ created with ``flask.make_response`` combined with something like
+ ``flask.render_template``.
+ """
+
+ return None
+
+
+class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
+ """
+ The ``WizardPlugin`` mixin allows plugins to report to OctoPrint whether
+ the ``wizard`` templates they define via the :class:`~octoprint.plugin.TemplatePlugin`
+ should be displayed to the user, what details to provide to their respective
+ wizard frontend components and what to do when the wizard is finished
+ by the user.
+
+ OctoPrint will only display such wizard dialogs to the user which belong
+ to plugins that
+
+ * report ``True`` in their :func:`is_wizard_required` method and
+ * have not yet been shown to the user in the version currently being reported
+ by the :meth:`~octoprint.plugin.WizardPlugin.get_wizard_version` method
+
+ Example: If a plugin with the identifier ``myplugin`` has a specific
+ setting ``some_key`` it needs to have filled by the user in order to be
+ able to work at all, it would probably test for that setting's value in
+ the :meth:`~octoprint.plugin.WizardPlugin.is_wizard_required` method and
+ return ``True`` if the value is unset:
+
+ .. code-block:: python
+
+ class MyPlugin(octoprint.plugin.SettingsPlugin,
+ octoprint.plugin.TemplatePlugin,
+ octoprint.plugin.WizardPlugin):
+
+ def get_default_settings(self):
+ return dict(some_key=None)
+
+ def is_wizard_required(self):
+ return self._settings.get(["some_key"]) is None
+
+ OctoPrint will then display the wizard dialog provided by the plugin through
+ the :class:`TemplatePlugin` mixin. Once the user finishes the wizard on the
+ frontend, OctoPrint will store that it already showed the wizard of ``myplugin``
+ in the version reported by :meth:`~octoprint.plugin.WizardPlugin.get_wizard_version`
+ - here ``None`` since that is the default value returned by that function
+ and the plugin did not override it.
+
+ If the plugin in a later version needs another setting from the user in order
+ to function, it will also need to change the reported version in order to
+ have OctoPrint reshow the dialog. E.g.
+
+ .. code-block:: python
+
+ class MyPlugin(octoprint.plugin.SettingsPlugin,
+ octoprint.plugin.TemplatePlugin,
+ octoprint.plugin.WizardPlugin):
+
+ def get_default_settings(self):
+ return dict(some_key=None, some_other_key=None)
+
+ def is_wizard_required(self):
+ some_key_unset = self._settings.get(["some_key"]) is None
+ some_other_key_unset = self._settings.get(["some_other_key"]) is None
+
+ return some_key_unset or some_other_key_unset
+
+ def get_wizard_version(self):
+ return 1
+
+ ``WizardPlugin`` is a :class:`~octoprint.plugin.core.ReloadNeedingPlugin`.
+ """
+
+ def is_wizard_required(self):
+ """
+ Allows the plugin to report whether it needs to display a wizard to the
+ user or not.
+
+ Defaults to ``False``.
+
+ OctoPrint will only include those wizards from plugins which are reporting
+ their wizards as being required through this method returning ``True``.
+ Still, if OctoPrint already displayed that wizard in the same version
+ to the user once it won't be displayed again regardless whether this
+ method returns ``True`` or not.
+ """
+ return False
+
+ def get_wizard_version(self):
+ """
+ The version of this plugin's wizard. OctoPrint will only display a wizard
+ of the same plugin and wizard version once to the user. After they
+ finish the wizard, OctoPrint will remember that it already showed this
+ wizard in this particular version and not reshow it.
+
+ If a plugin needs to show its wizard to the user again (e.g. because
+ of changes in the required settings), increasing this value is the
+ way to notify OctoPrint of these changes.
+
+ Returns:
+ int or None: an int signifying the current wizard version, should be incremented by plugins whenever there
+ are changes to the plugin that might necessitate reshowing the wizard if it is required. ``None``
+ will also be accepted and lead to the wizard always be ignored unless it has never been finished
+ so far
+ """
+ return None
+
+ def get_wizard_details(self):
+ """
+ Called by OctoPrint when the wizard wrapper dialog is shown. Allows the plugin to return data
+ that will then be made available to the view models via the view model callback ``onWizardDetails``.
+
+ Use this if your plugin's view model that handles your wizard dialog needs additional
+ data to perform its task.
+
+ Returns:
+ dict: a dictionary containig additional data to provide to the frontend. Whatever the plugin
+ returns here will be made available on the wizard API under the plugin's identifier
+ """
+ return dict()
+
+ def on_wizard_finish(self, handled):
+ """
+ Called by OctoPrint whenever the user finishes a wizard session is finished.
+
+ The ``handled`` parameter will indicate whether that plugin's wizard was
+ included in the wizard dialog presented to the user (so the plugin providing
+ it was reporting that the wizard was required and the wizard plus version was not
+ ignored/had already been seen).
+
+ Use this to do any clean up tasks necessary after wizard completion.
+
+ Arguments:
+ handled (bool): True if the plugin's wizard was previously reported as
+ required, not ignored and thus presented to the user,
+ False otherwise
+ """
+ pass
+
+ @classmethod
+ def is_wizard_ignored(cls, seen_wizards, implementation):
+ """
+ Determines whether the provided implementation is ignored based on the
+ provided information about already seen wizards and their versions or not.
+
+ A wizard is ignored if
+
+ * the current and seen versions are identical
+ * the current version is None and the seen version is not
+ * the current version is less or equal than the seen one
+
+ .. code-block:: none
+
+ | current |
+ | N | 1 | 2 | N = None
+ ----+---+---+---+ X = ignored
+ s N | X | | |
+ e --+---+---+---+
+ e 1 | X | X | |
+ n --+---+---+---+
+ 2 | X | X | X |
+ ----+---+---+---+
+
+ Arguments:
+ seen_wizards (dict): A dictionary with information about already seen
+ wizards and their versions. Mappings from the identifiers of
+ the plugin providing the wizard to the reported wizard
+ version (int or None) that was already seen by the user.
+ implementation (object): The plugin implementation to check.
+
+ Returns:
+ bool: False if the provided ``implementation`` is either not a :class:`WizardPlugin`
+ or has not yet been seen (in this version), True otherwise
+ """
+
+ if not isinstance(implementation, cls):
+ return False
+
+ name = implementation._identifier
+ if not name in seen_wizards:
+ return False
+
+ seen = seen_wizards[name]
+ wizard_version = implementation.get_wizard_version()
+
+ current = None
+ if wizard_version is not None:
+ try:
+ current = int(wizard_version)
+ except ValueError as e:
+ import logging
+ logging.getLogger(__name__).log("WizardPlugin {} returned invalid value {} for wizard version: {}".format(name, wizard_version, str(e)))
+
+ return (current == seen) \
+ or (current is None and seen is not None) \
+ or (current <= seen)
+
+
class SimpleApiPlugin(OctoPrintPlugin):
"""
Utilizing the ``SimpleApiPlugin`` mixin plugins may implement a simple API based around one GET resource and one
@@ -627,6 +1029,8 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
flask.url_for("plugin.myblueprintplugin.myEcho") # will return "/plugin/myblueprintplugin/echo"
+
+ ``BlueprintPlugin`` implements :class:`~octoprint.plugins.core.RestartNeedingPlugin`.
"""
@staticmethod
@@ -651,6 +1055,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 `_
+ and `the documentation for 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 +1082,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 +1205,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 +1225,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 +1239,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 +1248,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 +1362,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
diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py
new file mode 100644
index 000000000..e9cc114bd
--- /dev/null
+++ b/src/octoprint/plugins/corewizard/__init__.py
@@ -0,0 +1,145 @@
+# coding=utf-8
+from __future__ import absolute_import
+
+__author__ = "Gina Häußge "
+__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
+__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
+
+
+import octoprint.plugin
+
+
+class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
+ octoprint.plugin.TemplatePlugin,
+ octoprint.plugin.WizardPlugin,
+ octoprint.plugin.SettingsPlugin,
+ octoprint.plugin.BlueprintPlugin):
+
+ #~~ TemplatePlugin API
+
+ def get_template_configs(self):
+ required = self._get_subwizard_attrs("_is_", "_wizard_required")
+ names = self._get_subwizard_attrs("_get_", "_wizard_name")
+ additional = self._get_subwizard_attrs("_get_", "_additional_wizard_template_data")
+
+ result = list()
+ for key, method in required.iteritems():
+ if not method():
+ continue
+
+ if not key in names:
+ continue
+
+ name = names[key]()
+ if not name:
+ continue
+
+ config = dict(type="wizard", name=name, template="corewizard_{}_wizard.jinja2".format(key), div="wizard_plugin_corewizard_{}".format(key))
+ if key in additional:
+ additional_result = additional[key]()
+ if additional_result:
+ config.update(additional_result)
+ result.append(config)
+
+ return result
+
+ #~~ AssetPlugin API
+
+ def get_assets(self):
+ return dict(
+ js=["js/corewizard.js"]
+ )
+
+ #~~ WizardPlugin API
+
+ def is_wizard_required(self):
+ methods = self._get_subwizard_attrs("_is_", "_wizard_required")
+ return self._settings.global_get(["server", "firstRun"]) and any(map(lambda m: m(), methods.values()))
+
+ def get_wizard_details(self):
+ result = dict()
+
+ def add_result(key, method):
+ result[key] = method()
+ self._get_subwizard_attrs("_get_", "_wizard_details", add_result)
+
+ return result
+
+ #~~ ACL subwizard
+
+ def _is_acl_wizard_required(self):
+ return self._user_manager is not None and not self._user_manager.hasBeenCustomized()
+
+ def _get_acl_wizard_details(self):
+ return dict()
+
+ def _get_acl_wizard_name(self):
+ return "Access Control"
+
+ def _get_acl_additional_wizard_template_data(self):
+ return dict(mandatory=self._is_acl_wizard_required())
+
+ @octoprint.plugin.BlueprintPlugin.route("/acl", methods=["POST"])
+ def acl_wizard_api(self):
+ from flask import request
+ from octoprint.server.api import valid_boolean_trues, NO_CONTENT
+
+ data = request.values
+ if hasattr(request, "json") and request.json:
+ data = request.json
+
+ if "ac" in data and data["ac"] in valid_boolean_trues and \
+ "user" in data.keys() and "pass1" in data.keys() and \
+ "pass2" in data.keys() and data["pass1"] == data["pass2"]:
+ # configure access control
+ self._settings.global_set_boolean(["accessControl", "enabled"], True)
+ octoprint.server.userManager.addUser(data["user"], data["pass1"], True, ["user", "admin"], overwrite=True)
+ elif "ac" in data.keys() and not data["ac"] in valid_boolean_trues:
+ # disable access control
+ self._settings.global_set_boolean(["accessControl", "enabled"], False)
+
+ octoprint.server.loginManager.anonymous_user = octoprint.users.DummyUser
+ octoprint.server.principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader)
+
+ self._settings.save()
+ return NO_CONTENT
+
+ #~~ Webcam subwizard
+
+ def _is_webcam_wizard_required(self):
+ webcam_snapshot_url = self._settings.global_get(["webcam", "snapshotUrl"])
+ webcam_stream_url = self._settings.global_get(["webcam", "streamUrl"])
+ ffmpeg_path = self._settings.global_get(["webcam", "ffmpeg"])
+
+ return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path)
+
+ def _get_webcam_wizard_details(self):
+ return dict()
+
+ def _get_webcam_wizard_name(self):
+ return "Webcam & Timelapse"
+
+ #~~ helpers
+
+ def _get_subwizard_attrs(self, start, end, callback=None):
+ result = dict()
+
+ for item in dir(self):
+ if not item.startswith(start) or not item.endswith(end):
+ continue
+
+ key = item[len(start):-len(end)]
+ if not key:
+ continue
+
+ attr = getattr(self, item)
+ if callable(callback):
+ callback(key, attr)
+ result[key] = attr
+
+ return result
+
+
+__plugin_name__ = "Core Wizard"
+__plugin_description__ = "Provides wizard dialogs for core components"
+__plugin_implementation__ = CoreWizardPlugin()
diff --git a/src/octoprint/plugins/corewizard/static/js/corewizard.js b/src/octoprint/plugins/corewizard/static/js/corewizard.js
new file mode 100644
index 000000000..c4b587ede
--- /dev/null
+++ b/src/octoprint/plugins/corewizard/static/js/corewizard.js
@@ -0,0 +1,114 @@
+$(function() {
+ function CoreWizardAclViewModel(parameters) {
+ var self = this;
+
+ self.loginStateViewModel = parameters[0];
+
+ self.username = ko.observable(undefined);
+ self.password = ko.observable(undefined);
+ self.confirmedPassword = ko.observable(undefined);
+
+ self.setup = ko.observable(false);
+ self.decision = ko.observable();
+
+ self.passwordMismatch = ko.computed(function() {
+ return self.password() != self.confirmedPassword();
+ });
+
+ self.validUsername = ko.computed(function() {
+ return self.username() && self.username().trim() != "";
+ });
+
+ self.validPassword = ko.computed(function() {
+ return self.password() && self.password().trim() != "";
+ });
+
+ self.validData = ko.computed(function() {
+ return !self.passwordMismatch() && self.validUsername() && self.validPassword();
+ });
+
+ self.keepAccessControl = function() {
+ if (!self.validData()) return;
+
+ var data = {
+ "ac": true,
+ "user": self.username(),
+ "pass1": self.password(),
+ "pass2": self.confirmedPassword()
+ };
+ self._sendData(data);
+ };
+
+ self.disableAccessControl = function() {
+ var message = gettext("If you disable Access Control and your OctoPrint installation is accessible from the internet, your printer will be accessible by everyone - that also includes the bad guys!");
+ showConfirmationDialog({
+ message: message,
+ onproceed: function (e) {
+ var data = {
+ "ac": false
+ };
+ self._sendData(data);
+ }
+ });
+ };
+
+ self._sendData = function(data, callback) {
+ OctoPrint.postJson("plugin/corewizard/acl", data)
+ .done(function() {
+ self.setup(true);
+ self.decision(data.ac);
+ if (data.ac) {
+ // we now log the user in
+ var user = data.user;
+ var pass = data.pass1;
+ self.loginStateViewModel.login(user, pass, true)
+ .done(function() {
+ if (callback) callback();
+ });
+ } else {
+ if (callback) callback();
+ }
+ });
+ };
+
+ self.onWizardTabChange = function(current, next) {
+ if (!current || !_.startsWith(current, "wizard_plugin_corewizard_acl_") || self.setup()) {
+ return true;
+ }
+ showMessageDialog({
+ title: gettext("Please set up Access Control"),
+ message: gettext("You haven't yet set up access control. You need to either setup a username and password and click \"Keep Access Control Enabled\" or click \"Disable Access Control\" before continuing")
+ });
+ return false;
+ };
+
+ self.onWizardFinish = function() {
+ if (!self.decision()) {
+ return "reload";
+ }
+ };
+ }
+
+ function CoreWizardWebcamViewModel(parameters) {
+ var self = this;
+
+ self.settingsViewModel = parameters[0];
+
+ self.onWizardFinish = function() {
+ if (self.settingsViewModel.webcam_streamUrl()
+ || (self.settingsViewModel.webcam_snapshotUrl() && self.settingsViewModel.webcam_ffmpegPath())) {
+ return "reload";
+ }
+ }
+ }
+
+ OCTOPRINT_VIEWMODELS.push([
+ CoreWizardAclViewModel,
+ ["loginStateViewModel"],
+ "#wizard_plugin_corewizard_acl"
+ ], [
+ CoreWizardWebcamViewModel,
+ ["settingsViewModel"],
+ "#wizard_plugin_corewizard_webcam"
+ ]);
+});
diff --git a/src/octoprint/plugins/corewizard/templates/corewizard_acl_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_acl_wizard.jinja2
new file mode 100644
index 000000000..58cd4bfa7
--- /dev/null
+++ b/src/octoprint/plugins/corewizard/templates/corewizard_acl_wizard.jinja2
@@ -0,0 +1,59 @@
+
{{ _('Access Control') }}
+
+{% trans %}
+ Please read the following, it is very important for your printer's health!
+
+
+ OctoPrint by default ships with Access Control enabled, meaning you won't be able to do anything with the
+ printer unless you login first as a configured user. This is to prevent strangers - possibly with
+ malicious intent - to gain access to your printer via the internet or another untrustworthy network
+ and using it in such a way that it is damaged or worse (i.e. causes a fire).
+
+
+ It looks like you haven't configured access control yet. Please set up a username and password for the
+ initial administrator account who will have full access to both the printer and OctoPrint's settings, then click
+ on "Keep Access Control Enabled":
+
{% endtrans %}
+
+{% trans %}
+ Note: In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't
+ need Access Control for other reasons, you may alternatively disable Access Control. You should only
+ do this if you are absolutely certain that only people you know and trust will be able to connect to it.
+
+
+ Do NOT underestimate the risk of an unsecured access from the internet to your printer!
+
{% trans %}
+ Access control is enabled.
+ {% endtrans %}
+
{% trans %}
+ Access control is disabled.
+ {% endtrans %}
+
diff --git a/src/octoprint/plugins/corewizard/templates/corewizard_webcam_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_webcam_wizard.jinja2
new file mode 100644
index 000000000..aa5a8cf71
--- /dev/null
+++ b/src/octoprint/plugins/corewizard/templates/corewizard_webcam_wizard.jinja2
@@ -0,0 +1,42 @@
+
{{ _('Webcam & Timelapse Recordings') }}
+
+{% trans %}
+ If you have a webcam, you may now configure it here.
+
{% endtrans %}
+
+
{{ _('Webcam') }}
+
+{% trans %}
+ The Stream URL is the URL OctoPrint uses to embed the
+ actual webcam stream (which should be an MJPG stream) into the web
+ interface. This needs to be reachable from your browser.
+
+ It may be
+
+
a fully qualified URL (http://host:port/path),
+
a URL defaulting to the protocol used for accessing the web
+ interface (e.g. //host:port/path),
+
an absolute path on the same host as OctoPrint (e.g. /absolute/path) or
+
a relative path on the same host as OctoPrint (e.g. relative/path)
+
+
+ The Snapshot URL is the URL OctoPrint uses to fetch single
+ images from the webcam for creating timelapse recordings. This needs to be
+ a fully qualified URL reachable from the OctoPrint server.
+
{% endtrans %}
+
+
+
+
{{ _('Timelapse Recordings') }}
+
+{% trans %}
+ To render the snapshots into timelapse recordings, OctoPrint also needs to
+ know the correct path to FFMPEG.
+
{% endtrans %}
+
+
diff --git a/src/octoprint/plugins/cura/__init__.py b/src/octoprint/plugins/cura/__init__.py
index 4dab650ff..036530623 100644
--- a/src/octoprint/plugins/cura/__init__.py
+++ b/src/octoprint/plugins/cura/__init__.py
@@ -19,13 +19,16 @@ import octoprint.settings
from octoprint.util.paths import normalize as normalize_path
from .profile import Profile
+from .profile import GcodeFlavors
+from .profile import parse_gcode_flavor
class CuraPlugin(octoprint.plugin.SlicerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
- octoprint.plugin.StartupPlugin):
+ octoprint.plugin.StartupPlugin,
+ octoprint.plugin.WizardPlugin):
def __init__(self):
self._logger = logging.getLogger("octoprint.plugins.cura")
@@ -37,14 +40,34 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
self._cancelled_jobs = []
self._job_mutex = threading.Lock()
+ def _is_engine_configured(self, cura_engine=None):
+ if cura_engine is None:
+ cura_engine = normalize_path(self._settings.get(["cura_engine"]))
+ return cura_engine is not None and os.path.isfile(cura_engine) and os.access(cura_engine, os.X_OK)
+
+ def _is_profile_available(self):
+ return bool(self._slicing_manager.all_profiles("cura", require_configured=False))
+
##~~ TemplatePlugin API
def get_template_configs(self):
from flask.ext.babel import gettext
return [
- dict(type="settings", name=gettext("CuraEngine"))
+ dict(type="settings", name=gettext("CuraEngine")),
+ dict(type="wizard", name=gettext("CuraEngine"))
]
+ ##~~ WizardPlugin API
+
+ def is_wizard_required(self):
+ return not self._is_engine_configured() or not self._is_profile_available()
+
+ def get_wizard_details(self):
+ return dict(
+ engine=self._is_engine_configured(),
+ profile=self._is_profile_available()
+ )
+
##~~ StartupPlugin API
def on_startup(self, host, port):
@@ -62,9 +85,6 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
@octoprint.plugin.BlueprintPlugin.route("/import", methods=["POST"])
def import_cura_profile(self):
import datetime
- import tempfile
-
- from octoprint.server import slicingManager
input_name = "file"
input_upload_name = input_name + "." + self._settings.global_get(["server", "uploads", "nameSuffix"])
@@ -93,8 +113,10 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
profile_display_name = name
profile_description = "Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now()))
profile_allow_overwrite = False
+ profile_make_default = False
# overrides
+ from octoprint.server.api import valid_boolean_trues
if "name" in flask.request.values:
profile_name = flask.request.values["name"]
if "displayName" in flask.request.values:
@@ -102,22 +124,31 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
if "description" in flask.request.values:
profile_description = flask.request.values["description"]
if "allowOverwrite" in flask.request.values:
- from octoprint.server.api import valid_boolean_trues
profile_allow_overwrite = flask.request.values["allowOverwrite"] in valid_boolean_trues
+ if "default" in flask.request.values:
+ profile_make_default = flask.request.values["default"] in valid_boolean_trues
try:
- slicingManager.save_profile("cura",
- profile_name,
- profile_dict,
- allow_overwrite=profile_allow_overwrite,
- display_name=profile_display_name,
- description=profile_description)
+ self._slicing_manager.save_profile("cura",
+ profile_name,
+ profile_dict,
+ allow_overwrite=profile_allow_overwrite,
+ display_name=profile_display_name,
+ description=profile_description)
except octoprint.slicing.ProfileAlreadyExists:
self._logger.warn("Profile {profile_name} already exists, aborting".format(**locals()))
return flask.make_response("A profile named {profile_name} already exists for slicer cura".format(**locals()), 409)
+ if profile_make_default:
+ try:
+ self._slicing_manager.set_default_profile("cura", profile_name)
+ except octoprint.slicing.UnknownProfile:
+ self._logger.warn("Profile {profile_name} could not be set as default, aborting".format(**locals()))
+ return flask.make_response("The profile {profile_name} for slicer cura could not be set as default".format(**locals()), 500)
+
result = dict(
resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True),
+ name=profile_name,
displayName=profile_display_name,
description=profile_description
)
@@ -159,10 +190,11 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
def is_slicer_configured(self):
cura_engine = normalize_path(self._settings.get(["cura_engine"]))
- if cura_engine is not None and os.path.exists(cura_engine):
+ if self._is_engine_configured(cura_engine=cura_engine):
return True
else:
self._logger.info("Path to CuraEngine has not been configured yet or does not exist (currently set to %r), Cura will not be selectable for slicing" % cura_engine)
+ return False
def get_slicer_properties(self):
return dict(
@@ -230,15 +262,29 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
self._cura_logger.info(u"### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path))
- engine_settings = self._convert_to_engine(profile_path, printer_profile, posX, posY)
-
executable = normalize_path(self._settings.get(["cura_engine"]))
if not executable:
return False, "Path to CuraEngine is not configured "
- working_dir, _ = os.path.split(executable)
+ working_dir = os.path.dirname(executable)
+
+ # Start building the argument list for the CuraEngine command execution
args = [executable, '-v', '-p']
- for k, v in engine_settings.items():
+
+ # Get the CuraEngine version out of the "usage" line that is gotten when calling the CuraEngine with the -h argument
+ new_engine = self._is_new_engine_version(executable)
+
+ # If the CuraEngine is the new version, add the JSON file path as argument
+ if new_engine:
+ args += ['-j', os.path.join(self._basefolder, "profiles", "fdmprinter.json")]
+
+ profile = Profile(self._load_profile(profile_path), printer_profile, posX, posY)
+
+ engine_settings = self._convert_to_engine(profile, new_engine=new_engine)
+
+ # Add the settings (sorted alphabetically) to the command
+
+ for k, v in sorted(engine_settings.items(), key=lambda s: s[0]):
args += ["-s", "%s=%s" % (k, str(v))]
args += ["-o", machinecode_path, model_path]
@@ -321,6 +367,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
except:
pass
+ # Get the filament usage
+
elif line.startswith(u"Filament:") or line.startswith(u"Filament2:"):
if line.startswith(u"Filament:"):
filament_str = line[len(u"Filament:"):].strip()
@@ -331,17 +379,25 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
try:
filament = int(filament_str)
+
if analysis is None:
analysis = dict()
if not "filament" in analysis:
analysis["filament"] = dict()
if not tool_key in analysis["filament"]:
analysis["filament"][tool_key] = dict()
- analysis["filament"][tool_key]["length"] = filament
- if "filamentDiameter" in engine_settings:
- radius_in_cm = float(int(engine_settings["filamentDiameter"]) / 10000.0) / 2.0
- filament_in_cm = filament / 10.0
- analysis["filament"][tool_key]["volume"] = filament_in_cm * math.pi * radius_in_cm * radius_in_cm
+
+ if profile.get_float("filament_diameter") != None:
+ # The new CuraEngine outputs the "Filament" value as volume independently from the Gcode flavor
+ if new_engine:
+ analysis["filament"][tool_key] = _get_usage_from_volume(filament, profile.get_float("filament_diameter"))
+ # The old CuraEngine outputs the "Filament" value as volume only for ULTIGCODE and REPRAP_VOLUME
+ else:
+ if profile.get("gcode_flavor") == GcodeFlavors.ULTIGCODE or profile.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME:
+ analysis["filament"][tool_key] = _get_usage_from_volume(filament, profile.get_float("filament_diameter"))
+ else:
+ analysis["filament"][tool_key] = _get_usage_from_length(filament, profile.get_float("filament_diameter"))
+
except:
pass
finally:
@@ -391,16 +447,40 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
profile_dict = yaml.safe_load(f)
except:
raise IOError("Couldn't read profile from {path}".format(path=path))
+
+ if "gcode_flavor" in profile_dict and not isinstance(profile_dict["gcode_flavor"], (list, tuple)):
+ profile_dict["gcode_flavor"] = parse_gcode_flavor(profile_dict["gcode_flavor"])
+ self._save_profile(path, profile_dict)
+
return profile_dict
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):
- profile = Profile(self._load_profile(profile_path), printer_profile, posX, posY)
- return profile.convert_to_engine()
+ def _convert_to_engine(self, profile, new_engine):
+ if new_engine:
+ return profile.convert_to_new_engine()
+ else:
+ return profile.convert_to_engine()
+
+ def _is_new_engine_version(self, executable):
+ import sarge
+
+ command = [executable, "-j", os.path.join(self._basefolder, "profiles", "fdmprinter.json")]
+ p = sarge.run(command, stdout=sarge.Capture(), stderr=sarge.Capture())
+ if p.returncode != 0:
+ self._logger.warn("Could not run {} -j, returned {}".format(executable, p.returncode))
+ self._logger.info(u"Assuming pre 15.06 version of CuraEngine.")
+ return False
+
+ for line in p.stderr.read().split('\n'):
+ if "unknown option: j" in line.strip().lower():
+ self._logger.info(u"Using pre 15.06 version of CuraEngine.")
+ return False
+ self._logger.info(u"Using post 15.06 version of CuraEngine.")
+ return True
def _sanitize_name(name):
if name is None:
@@ -415,9 +495,39 @@ def _sanitize_name(name):
sanitized_name = sanitized_name.replace(" ", "_")
return sanitized_name.lower()
+def _get_usage_from_volume(filament_volume, filament_diameter):
+
+ # filament_volume is expressed in mm^3
+ # usage["volume"] is in cm^3 and usage["length"] is in mm
+
+ usage = dict()
+ usage["volume"] = filament_volume / 1000.0
+
+ radius_in_mm = filament_diameter / 2.0
+ usage["length"] = filament_volume / (math.pi * radius_in_mm * radius_in_mm)
+
+ return usage
+
+def _get_usage_from_length(filament_length, filament_diameter):
+
+ # filament_length is expressed in mm
+ # usage["volume"] is in cm^3 and usage["length"] is in mm
+
+ usage = dict()
+ usage["length"] = filament_length
+
+ radius_in_cm = (filament_diameter / 10.0) / 2.0
+ length_in_cm = filament_length / 10.0
+ usage["volume"] = length_in_cm * math.pi * radius_in_cm * radius_in_cm
+
+ return usage
+
__plugin_name__ = "CuraEngine"
__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_license__ = "AGPLv3"
__plugin_implementation__ = CuraPlugin()
+
+
+
diff --git a/src/octoprint/plugins/cura/profile.py b/src/octoprint/plugins/cura/profile.py
index 59a0ee152..6ab7b6b38 100644
--- a/src/octoprint/plugins/cura/profile.py
+++ b/src/octoprint/plugins/cura/profile.py
@@ -32,12 +32,12 @@ class MachineShapeTypes(object):
CIRCULAR = "circular"
class GcodeFlavors(object):
- REPRAP = "reprap"
- REPRAP_VOLUME = "reprap_volume"
- ULTIGCODE = "ultigcode"
- MAKERBOT = "makerbot"
- BFB = "bfb"
- MACH3 = "mach3"
+ REPRAP = (0, "reprap")
+ ULTIGCODE = (1, "ultigcode")
+ MAKERBOT = (2, "makerbot")
+ BFB = (3, "bfb")
+ MACH3 = (4, "mach3")
+ REPRAP_VOLUME = (5, "reprap_volume")
defaults = dict(
@@ -393,15 +393,45 @@ class Profile(object):
}
)
+ # Translation dict for new CuraEngine option names
+ new_engine_options = dict(
+ fill_sparse_density="fill_density",
+ machine_nozzle_size="nozzle_size",
+ material_print_temperature="print_temperature",
+ #support_type="support", # In conflict with "support_type" from old CuraEngine
+ support_pattern="support_type",
+ adhesion_type="platform_adhesion",
+ material_diameter="filament_diameter",
+ material_flow="filament_flow",
+ speed_travel="travel_speed",
+ speed_layer_0="bottom_layer_speed",
+ speed_print="print_speed",
+ speed_infill="infill_speed",
+ speed_wall_0="outer_shell_speed",
+ speed_wall_x="inner_shell_speed",
+ cool_fan_enabled="fan_enabled",
+ cool_fan_full_at_height="fan_full_height",
+ cool_fan_speed="fan_speed",
+ cool_fan_speed_max="fan_speed_max",
+ cool_lift_head="cool_head_lift",
+ cool_min_speed="cool_min_feedrate",
+ machine_start_gcode="start_gcode",
+ machine_end_gcode="end_gcode",
+ machine_gcode_flavor="gcode_flavor")
+
result = dict()
for section in config.sections():
- if not section in ("profile", "alterations"):
+
+ if not section in ("profile", "alterations", "machine"):
continue
for option in config.options(section):
ignored = False
key = option
+ if section == "machine" and key != "gcode_flavor":
+ continue
+
# try to fetch the value in the correct type
try:
value = config.getboolean(section, option)
@@ -438,9 +468,16 @@ class Profile(object):
# if the key has to be translated to a new value, do that now
key = translated_options[key]
+ if key in new_engine_options:
+ # if the key has to be translated from the new CuraEngine versions, do that now
+ key = new_engine_options[key]
+
if key in value_conversions and value in value_conversions[key]:
value = value_conversions[key][value]
+ if key == "gcode_flavor":
+ value = parse_gcode_flavor(value)
+
if index is not None:
# if we have an array to fill, make sure the target array exists and has the right size
if not key in result:
@@ -710,61 +747,70 @@ class Profile(object):
return pre + str(f)
- def get_gcode(self, key):
- extruder_count = self.get_int("extruder_amount")
-
+ def get_gcode(self, key, new_engine=False):
prefix = ""
postfix = ""
if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE:
if key == "end_gcode":
- return "M25 ;Stop reading from this point on.\n;CURA_PROFILE_STRING:%s\n" % (self.get_profile_string())
+ return "M25 ;Stop reading from this point on.\n;CURA_OCTO_PROFILE_STRING:%s\n" % (self.get_profile_string())
return ""
if key == "start_gcode":
contents = self.get_gcode_template("start_gcode")
- e_steps = self.get_float("steps_per_e")
- if e_steps > 0:
- prefix += "M92 E{e_steps}\n" % (e_steps)
- temp = self.get_float("print_temperature")
-
- bed_temp = 0
- if self.get_boolean("has_heated_bed"):
- bed_temp = self.get_float("print_bed_temperature")
- include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
-
- if include_bed_temp:
- prefix += "M140 S{bed_temp}\n".format(bed_temp=bed_temp)
-
- if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
- if extruder_count > 0:
- def temp_line(temp, extruder, template):
- t = temp
- if extruder > 0:
- print_temp = self.get_float("print_temperature%d" % (extruder + 1))
- if print_temp > 0:
- t = print_temp
- return template.format(extruder=extruder, temp=t)
-
- prefix_preheat = ""
- prefix_waitheat = ""
- for n in xrange(0, extruder_count):
- if n > 0:
- prefix_preheat += temp_line(temp, n, "M104 T{extruder} S{temp}\n")
- prefix_waitheat += temp_line(temp, n, "M109 T{extruder} S{temp}\n")
- prefix += prefix_preheat + prefix_waitheat + "T0\n"
- else:
- prefix += "M109 S{temp}\n".format(temp=temp)
-
- if include_bed_temp:
- prefix += "M190 S{bed_temp}\n".format(bed_temp=bed_temp)
+ # If using the new CuraEngine, there is no need to extend the start_gcode
+ if not new_engine:
+ prefix += self.get_start_gcode_prefix(contents)
else:
contents = self.get_gcode_template(key)
return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
+ def get_start_gcode_prefix(self, contents):
+ extruder_count = self.get_int("extruder_amount")
+
+ prefix = ""
+
+ e_steps = self.get_float("steps_per_e")
+ if e_steps > 0:
+ prefix += "M92 E{e_steps}\n" % (e_steps)
+ temp = self.get_float("print_temperature")
+
+ bed_temp = 0
+ if self.get_boolean("has_heated_bed"):
+ bed_temp = self.get_float("print_bed_temperature")
+ include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
+
+ if include_bed_temp:
+ prefix += "M140 S{bed_temp}\n".format(bed_temp=bed_temp)
+
+ if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
+ if extruder_count > 0:
+ def temp_line(temp, extruder, template):
+ t = temp
+ if extruder > 0:
+ print_temp = self.get_float("print_temperature%d" % (extruder + 1))
+ if print_temp > 0:
+ t = print_temp
+ return template.format(extruder=extruder, temp=t)
+
+ prefix_preheat = ""
+ prefix_waitheat = ""
+ for n in xrange(0, extruder_count):
+ if n > 0:
+ prefix_preheat += temp_line(temp, n, "M104 T{extruder} S{temp}\n")
+ prefix_waitheat += temp_line(temp, n, "M109 T{extruder} S{temp}\n")
+ prefix += prefix_preheat + prefix_waitheat + "T0\n"
+ else:
+ prefix += "M109 S{temp}\n".format(temp=temp)
+
+ if include_bed_temp:
+ prefix += "M190 S{bed_temp}\n".format(bed_temp=bed_temp)
+
+ return prefix
+
def calculate_edge_width_and_line_count(self):
wall_thickness = self.get_float("wall_thickness")
nozzle_size = self._printer_profile["extruder"]["nozzleDiameter"]
@@ -810,20 +856,20 @@ class Profile(object):
def get_pos_x(self):
if self._posX:
try:
- return int(float(self._posX) * 1000)
+ return int(float(self._posX))
except ValueError:
pass
- return int(self.get_float("machine_width") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0
+ return int(self.get_float("machine_width") / 2.0 ) if not self.get_boolean("machine_center_is_zero") else 0.0
def get_pos_y(self):
if self._posY:
try:
- return int(float(self._posY) * 1000)
+ return int(float(self._posY))
except ValueError:
pass
- return int(self.get_float("machine_depth") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0
+ return int(self.get_float("machine_depth") / 2.0) if not self.get_boolean("machine_center_is_zero") else 0.0
def convert_to_engine(self):
@@ -873,8 +919,8 @@ class Profile(object):
"coolHeadLift": 1 if self.get_boolean("cool_head_lift") else 0,
# model positioning
- "posx": self.get_pos_x(),
- "posy": self.get_pos_y(),
+ "posx": self.get_pos_x() * 1000, # in microns
+ "posy": self.get_pos_y() * 1000, # in microns
# gcodes
"startCode": self.get_gcode("start_gcode"),
@@ -953,16 +999,7 @@ class Profile(object):
settings["layerThickness"] = 1000
# gcode flavor
- if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE:
- settings["gcodeFlavor"] = 1
- elif self.get("gcode_flavor") == GcodeFlavors.MAKERBOT:
- settings["gcodeFlavor"] = 2
- elif self.get("gcode_flavor") == GcodeFlavors.BFB:
- settings["gcodeFlavor"] = 3
- elif self.get("gcode_flavor") == GcodeFlavors.MACH3:
- settings["gcodeFlavor"] = 4
- elif self.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME:
- settings["gcodeFlavor"] = 5
+ settings["gcodeFlavor"] = self.get("gcode_flavor")[0]
# extras
if self.get_boolean("spiralize"):
@@ -978,3 +1015,132 @@ class Profile(object):
settings["enableOozeShield"] = 1
return settings
+
+ def convert_to_new_engine(self):
+
+ settings = {
+ "layer_height": self.get_float("layer_height"),
+ "wall_thickness": self.get_float("wall_thickness"),
+ "retraction_enable": self.get_boolean("retraction_enable"),
+ "top_bottom_thickness": self.get_float("solid_layer_thickness"),
+ "fill_sparse_density": self.get_float("fill_density"),
+ "machine_nozzle_size": self.get_float("nozzle_size"),
+ "speed_print": self.get_float("print_speed"),
+ "material_print_temperature": self.get_float("print_temperature"),
+ "material_diameter": self.get_float("filament_diameter"),
+ "material_flow": self.get_float("filament_flow"),
+ "retraction_speed": self.get_float("retraction_speed"),
+ "retraction_amount": self.get_float("retraction_amount") if self.get_boolean("retraction_enable") else 0,
+ "retraction_min_travel": self.get_float("retraction_min_travel"),
+ "retraction_combing": self.get_boolean("retraction_combing"),
+ "retraction_hop": self.get_float("retraction_hop"),
+ "bottom_thickness": self.get_float("bottom_thickness"),
+ "top_layers": self.calculate_solid_layer_count(),
+ "bottom_layers": self.calculate_solid_layer_count(),
+ "speed_travel": self.get_float("travel_speed"),
+ "speed_layer_0": self.get_float("bottom_layer_speed"),
+ "speed_infill": self.get_float("infill_speed") if self.get_float("infill_speed") > 0 else self.get_float("print_speed"),
+ "speed_wall_0": self.get_float("outer_shell_speed") if self.get_float("outer_shell_speed") > 0 else self.get_float("print_speed"), # Translated from "inset0_speed"
+ "speed_wall_x": self.get_float("inner_shell_speed") if self.get_float("inner_shell_speed") > 0 else self.get_float("print_speed"), # Translated from "insetx_speed"
+ "cool_min_layer_time": self.get_float("cool_min_layer_time"),
+ "cool_fan_enabled": self.get_boolean("fan_enabled"),
+ "cool_fan_full_at_height": self.get_int("fan_full_height"),
+ "cool_fan_speed": self.get_float("fan_speed"),
+ "cool_fan_speed_max": self.get_float("fan_speed_max") if self.get_boolean("fan_enabled") else 0,
+ "cool_lift_head": self.get_boolean("cool_head_lift"),
+ "cool_min_speed": self.get_float("cool_min_feedrate"),
+ "skirt_line_count": self.get_int("skirt_line_count"),
+ "fill_overlap": self.get_float("fill_overlap"),
+ "magic_spiralize": self.get_boolean("spiralize"),
+
+ # machine settings
+
+ "machine_width": self.get_float("machine_width"),
+ "machine_depth": self.get_float("machine_depth"),
+ "machine_center_is_zero": self.get_boolean("machine_center_is_zero"),
+ "machine_heated_bed": self.get_boolean("has_heated_bed"),
+
+ # gcodes
+
+ "machine_start_gcode": self.get_gcode("start_gcode", new_engine=True),
+ "machine_end_gcode": self.get_gcode("end_gcode", new_engine=True),
+ }
+
+ # gcode flavor
+
+ settings["machine_gcode_flavor"] = self.get("gcode_flavor")[0]
+
+ # heated bed - The new CuraEngine uses the integer "material_bed_temperature" instead of the boolean "machine_heated_bed"
+
+ if self.get_boolean("has_heated_bed"):
+ settings["material_bed_temperature"] = self.get_float("print_bed_temperature")
+ else:
+ settings["material_bed_temperature"] = 0
+
+ # support
+
+ if self.get("support") == SupportLocationTypes.NONE:
+ settings["support_enable"] = False
+ else:
+ settings["support_enable"] = True
+ settings["support_angle"] = self.get_float("support_angle")
+ settings["support_fill_rate"] = self.get_float("support_fill_rate")
+ settings["support_xy_distance"] = self.get_float("support_xy_distance")
+ settings["support_z_distance"] = self.get_float("support_z_distance")
+
+ # support type
+
+ if self.get("support") == SupportLocationTypes.TOUCHING_BUILDPLATE:
+ settings["support_type"] = "Touching Buildplate"
+ elif self.get("support") == SupportLocationTypes.EVERYWHERE:
+ settings["support_type"] = "Everywhere"
+
+ # support pattern
+
+ if self.get("support_type") == SupportTypes.GRID:
+ settings["support_pattern"] = "Grid"
+ elif self.get("support_type") == SupportTypes.LINES:
+ settings["support_pattern"] = "Lines"
+
+ # adhesion type
+
+ if self.get("platform_adhesion") == PlatformAdhesionTypes.NONE:
+ settings["adhesion_type"] = "None"
+ elif self.get("platform_adhesion") == PlatformAdhesionTypes.BRIM:
+ settings["adhesion_type"] = "Brim"
+ settings["brim_line_count"] = self.get_int("brim_line_count")
+ elif self.get("platform_adhesion") == PlatformAdhesionTypes.RAFT:
+ settings["adhesion_type"] = "Raft"
+ settings["raft_margin"] = self.get_int("raft_margin")
+ settings["raft_line_spacing"] = self.get_float("raft_line_spacing")
+ settings["raft_base_thickness"] = self.get_float("raft_base_thickness")
+ settings["raft_base_linewidth"] = self.get_float("raft_base_linewidth")
+ settings["raft_interface_thickness"] = self.get_float("raft_interface_thickness")
+ settings["raft_interface_linewidth"] = self.get_float("raft_interface_linewidth")
+ settings["raft_airgap"] = self.get_float("raft_airgap")
+ settings["raft_surface_layers"] = self.get_int("raft_surface_layers")
+
+ # skirt
+
+ if self.get_int("skirt_line_count") != 0:
+ settings["skirt_gap"] = self.get_float("skirt_gap")
+ settings["skirt_minimal_length"] = self.get_float("skirt_minimal_length")
+
+ return settings
+
+def parse_gcode_flavor(value):
+
+ value = value.lower()
+
+ if "reprap" in value and ("volume" in value or "volumatric" in value):
+ return GcodeFlavors.REPRAP_VOLUME
+ elif "ultigcode" in value:
+ return GcodeFlavors.ULTIGCODE
+ elif "makerbot" in value:
+ return GcodeFlavors.MAKERBOT
+ elif "bfb" in value:
+ return GcodeFlavors.BFB
+ elif "mach3" in value:
+ return GcodeFlavors.MACH3
+ else:
+ return GcodeFlavors.REPRAP
diff --git a/src/octoprint/plugins/cura/profiles/fdmprinter.json b/src/octoprint/plugins/cura/profiles/fdmprinter.json
new file mode 100644
index 000000000..366149b9c
--- /dev/null
+++ b/src/octoprint/plugins/cura/profiles/fdmprinter.json
@@ -0,0 +1,1325 @@
+{
+ "visible": false,
+ "machine_settings": {
+ "machine_start_gcode": {
+ "default": "G28 ; Home\nG1 Z15.0 F6000 ;move the platform down 15mm\n;Prime the extruder\nG92 E0\nG1 F200 E3\nG92 E0"
+ },
+ "machine_end_gcode": {
+ "default": "M104 S0\nM140 S0\n;Retract the filament\nG92 E1\nG1 E-1 F300\nG28 X0 Y0\nM84"
+ },
+ "machine_width": { "default": 230 },
+ "machine_depth": { "default": 225 },
+ "machine_height": { "default": 205 },
+ "machine_heated_bed": { "default": true },
+
+ "machine_center_is_zero": { "default": false },
+ "machine_nozzle_size": { "default": 0.4 },
+ "machine_head_shape_min_x": { "default": 40 },
+ "machine_head_shape_min_y": { "default": 10 },
+ "machine_head_shape_max_x": { "default": 60 },
+ "machine_head_shape_max_y": { "default": 30 },
+ "machine_nozzle_gantry_distance": { "default": 55 },
+ "machine_nozzle_offset_x_1": { "default": 18.0 },
+ "machine_nozzle_offset_y_1": { "default": 0.0 },
+ "machine_gcode_flavor": { "default": "UltiGCode" },
+ "machine_disallowed_areas": { "default": [
+ [[-115.0, 112.5], [ -82.0, 112.5], [ -84.0, 104.5], [-115.0, 104.5]],
+ [[ 115.0, 112.5], [ 115.0, 104.5], [ 110.0, 104.5], [ 108.0, 112.5]],
+ [[-115.0, -112.5], [-115.0, -104.5], [ -84.0, -104.5], [ -82.0, -112.5]],
+ [[ 115.0, -112.5], [ 108.0, -112.5], [ 110.0, -104.5], [ 115.0, -104.5]]
+ ]},
+ "machine_platform_offset": { "default": [9.0, 0.0, 0.0] },
+
+ "machine_nozzle_tip_outer_diameter": { "default": 1.0 },
+ "machine_nozzle_head_distance": { "default": 3.0 },
+ "machine_nozzle_expansion_angle": { "default": 45 }
+ },
+ "categories": {
+ "resolution": {
+ "label": "Quality",
+ "visible": true,
+ "icon": "category_quality",
+ "settings": {
+ "layer_height": {
+ "label": "Layer Height",
+ "description": "The height of each layer, in mm. Normal quality prints are 0.1mm, high quality is 0.06mm. You can go up to 0.25mm with an Ultimaker for very fast prints at low quality. For most purposes, layer heights between 0.1 and 0.2mm give a good tradeoff of speed and surface finish.",
+ "unit": "mm",
+ "type": "float",
+ "default": 0.1,
+ "min_value": 0.06,
+ "max_value": 2.0,
+ "always_visible": true,
+ "children": {
+ "layer_height_0": {
+ "label": "Initial Layer Thickness",
+ "description": "The layer thickness of the bottom layer. A thicker bottom layer makes sticking to the bed easier.",
+ "unit": "mm",
+ "type": "float",
+ "default": 0.2,
+ "min_value": 0.06,
+ "max_value": 2.0,
+ "visible": false
+ }
+ }
+ },
+ "shell_thickness": {
+ "label": "Shell Thickness",
+ "description": "The thickness of the outside shell in the horizontal and vertical direction. This is used in combination with the nozzle size to define the number of perimeter lines and the thickness of those perimeter lines. This is also used to define the number of solid top and bottom layers.",
+ "unit": "mm",
+ "type": "float",
+ "default": 0.8,
+ "min_value": 0.0,
+ "max_value": 5.0,
+ "children": {
+ "wall_thickness": {
+ "label": "Wall Thickness",
+ "description": "The thickness of the outside walls in the horizontal direction. This is used in combination with the nozzle size to define the number of perimeter lines and the thickness of those perimeter lines.",
+ "unit": "mm",
+ "default": 0.8,
+ "min_value": 0.0,
+ "max_value": 5.0,
+ "min_value_warning": 0.4,
+ "max_value_warning": 2.0,
+ "type": "float",
+ "visible": false,
+
+ "children": {
+ "wall_line_count": {
+ "label": "Wall Line Count",
+ "description": "Number of shell lines. This these lines are called perimeter lines in other tools and impact the strength and structural integrity of your print.",
+ "default": 2,
+ "type": "int",
+ "visible": false,
+ "inherit_function": "max(1, (int(parent_value / (machine_nozzle_size - 0.0001) + 1) if (parent_value / max(1, int(parent_value / (machine_nozzle_size - 0.0001))) > machine_nozzle_size) * 1.5 else int(parent_value / (machine_nozzle_size - 0.0001))))"
+ },
+ "wall_line_width": {
+ "label": "Wall Line Width",
+ "description": "Width of a single shell line. Each line of the shell will be printed with this width in mind.",
+ "unit": "mm",
+ "default": 0.4,
+ "type": "float",
+ "visible": false,
+ "inherit_function": "max(machine_nozzle_size, (parent_value / (int(parent_value / (machine_nozzle_size - 0.0001) + 1))) if (parent_value / (int(parent_value / (machine_nozzle_size - 0.0001))) > machine_nozzle_size * 1.5) else (parent_value / int(parent_value / (machine_nozzle_size - 0.0001))))",
+
+ "children": {
+ "wall_line_width_0": {
+ "label": "First Wall Line Width",
+ "description": "Width of the outermost shell line. By printing a thinner outermost wall line you can print higher details with a larger nozzle.",
+ "unit": "mm",
+ "default": 0.4,
+ "type": "float",
+ "visible": false
+ },
+ "wall_line_width_x": {
+ "label": "Other Walls Line Width",
+ "description": "Width of a single shell line for all shell lines except the outermost one.",
+ "unit": "mm",
+ "default": 0.4,
+ "type": "float",
+ "visible": false
+ },
+ "skirt_line_width": {
+ "label": "Skirt line width",
+ "description": "Width of a single skirt line.",
+ "unit": "mm",
+ "default": 0.4,
+ "type": "float",
+ "visible": false
+ },
+ "skin_line_width": {
+ "label": "Top/bottom line width",
+ "description": "Width of a single top/bottom printed line. Which are used to fill up the top/bottom areas of a print.",
+ "unit": "mm",
+ "default": 0.4,
+ "type": "float",
+ "visible": false
+ },
+ "infill_line_width": {
+ "label": "Infill line width",
+ "description": "Width of the inner infill printed lines.",
+ "unit": "mm",
+ "default": 0.4,
+ "type": "float",
+ "visible": false
+ },
+ "support_line_width": {
+ "label": "Support line width",
+ "description": "Width of the printed support structures lines.",
+ "unit": "mm",
+ "default": 0.4,
+ "type": "float",
+ "visible": false
+ }
+ }
+ }
+ }
+ },
+ "alternate_extra_perimeter": {
+ "label": "Alternate Extra Wall",
+ "description": "Make an extra wall at every second layer, so that infill will be caught between an extra wall above and one below. This results in a better cohesion between infill and walls, but might have an impact on the surface quality.",
+ "type": "boolean",
+ "default": false,
+ "visible": false
+ },
+ "top_bottom_thickness": {
+ "label": "Bottom/Top Thickness",
+ "description": "This controls the thickness of the bottom and top layers, the amount of solid layers put down is calculated by the layer thickness and this value. Having this value a multiple of the layer thickness makes sense. And keep it near your wall thickness to make an evenly strong part.",
+ "unit": "mm",
+ "default": 0.8,
+ "min_value": 0.0,
+ "max_value": 5.0,
+ "min_value_warning": 0.4,
+ "max_value_warning": 1.0,
+ "type": "float",
+ "visible": false,
+
+ "children": {
+ "top_thickness": {
+ "label": "Top Thickness",
+ "description": "This controls the thickness of the top layers. The number of solid layers printed is calculated from the layer thickness and this value. Having this value be a multiple of the layer thickness makes sense. And keep it nearto your wall thickness to make an evenly strong part.",
+ "unit": "mm",
+ "default": 0.8,
+ "type": "float",
+ "visible": false,
+
+ "children": {
+ "top_layers": {
+ "label": "Top Layers",
+ "description": "This controls the amount of top layers.",
+ "default": 8,
+ "type": "int",
+ "visible": false,
+ "inherit_function": "math.ceil(parent_value / layer_height)"
+ }
+ }
+ },
+ "bottom_thickness": {
+ "label": "Bottom Thickness",
+ "description": "This controls the thickness of the bottom layers. The number of solid layers printed is calculated from the layer thickness and this value. Having this value be a multiple of the layer thickness makes sense. And keep it near to your wall thickness to make an evenly strong part.",
+ "unit": "mm",
+ "default": 0.8,
+ "type": "float",
+ "visible": false,
+
+ "children": {
+ "bottom_layers": {
+ "label": "Bottom Layers",
+ "description": "This controls the amount of bottom layers.",
+ "default": 8,
+ "type": "int",
+ "visible": false,
+ "inherit_function": "math.ceil(parent_value / layer_height)"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "wall_overlap_avoid_enabled": {
+ "label": "Avoid Overlapping Walls",
+ "description": "Remove parts of a wall which share an overlap which would result in overextrusion in some places. These overlaps occur in thin pieces in a model and sharp corners.",
+ "type": "boolean",
+ "default": true,
+ "visible": false
+ },
+ "fill_perimeter_gaps":{
+ "label": "Fill Gaps Between Walls",
+ "description": "Fill the gaps created by walls where they would otherwise be overlapping. This will also fill thin walls. Optionally only the gaps occurring within the top and bottom skin can be filled.",
+ "type": "enum",
+ "options": [
+ "Nowhere",
+ "Everywhere",
+ "Skin"
+ ],
+ "default": "Everywhere",
+ "visible": false,
+ "active_if": {
+ "setting": "wall_overlap_avoid_enabled",
+ "value": true
+ }
+ },
+ "top_bottom_pattern": {
+ "label": "Bottom/Top Pattern",
+ "description": "Pattern of the top/bottom solid fill. This normally is done with lines to get the best possible finish, but in some cases a concentric fill gives a nicer end result.",
+ "type": "enum",
+ "options": [
+ "Lines",
+ "Concentric"
+ ],
+ "default": "Lines",
+ "visible": false
+ },
+ "skin_outline_count": {
+ "label": "Skin Perimeter Line Count",
+ "description": "Number of lines around skin regions. Using one or two skin perimeter lines can greatly improve on roofs which would start in the middle of infill cells.",
+ "default": 0,
+ "type": "int",
+ "visible": false,
+ "active_if": {
+ "setting": "top_bottom_pattern",
+ "value": "Lines"
+ }
+ },
+ "xy_offset": {
+ "label": "Horizontal expansion",
+ "description": "Amount of offset applied all polygons in each layer. Positive values can compensate for too big holes; negative values can compensate for too small holes.",
+ "unit": "mm",
+ "type": "float",
+ "default": 0.0,
+ "visible": false
+
+ }
+ }
+ },
+
+ "material": {
+ "label": "Material",
+ "visible": true,
+ "icon": "category_material",
+ "settings": {
+ "material_print_temperature": {
+ "label": "Printing Temperature",
+ "description": "The temperature used for printing. Set at 0 to pre-heat yourself. For PLA a value of 210C is usually used.\nFor ABS a value of 230C or higher is required.",
+ "unit": "°C",
+ "type": "float",
+ "default": 220,
+ "min_value": 10,
+ "max_value": 340
+ },
+ "material_bed_temperature": {
+ "label": "Bed Temperature",
+ "description": "The temperature used for the heated printer bed. Set at 0 to pre-heat it yourself.",
+ "unit": "°C",
+ "type": "float",
+ "default": 70,
+ "min_value": 0,
+ "max_value": 340
+ },
+ "material_diameter": {
+ "label": "Diameter",
+ "description": "The diameter of your filament needs to be measured as accurately as possible.\nIf you cannot measure this value you will have to calibrate it, a higher number means less extrusion, a smaller number generates more extrusion.",
+ "unit": "mm",
+ "type": "float",
+ "default": 2.85,
+ "min_value": 0.4,
+ "max_value": 5.0
+ },
+ "material_flow": {
+ "label": "Flow",
+ "description": "Flow compensation: the amount of material extruded is multiplied by this value.",
+ "unit": "%",
+ "default": 100.0,
+ "type": "float",
+ "min_value": 5.0,
+ "max_value": 300.0
+ },
+ "retraction_enable": {
+ "label": "Enable Retraction",
+ "description": "Retract the filament when the nozzle is moving over a non-printed area. Details about the retraction can be configured in the advanced tab.",
+ "type": "boolean",
+ "default": true,
+
+ "children": {
+ "retraction_speed": {
+ "label": "Retraction Speed",
+ "description": "The speed at which the filament is retracted. A higher retraction speed works better, but a very high retraction speed can lead to filament grinding.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 25.0,
+ "visible": false,
+ "inherit": false,
+
+ "children": {
+ "retraction_retract_speed": {
+ "label": "Retraction Retract Speed",
+ "description": "The speed at which the filament is retracted. A higher retraction speed works better, but a very high retraction speed can lead to filament grinding.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 25.0,
+ "visible": false
+ },
+ "retraction_prime_speed": {
+ "label": "Retraction Prime Speed",
+ "description": "The speed at which the filament is pushed back after retraction.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 25.0,
+ "visible": false
+ }
+ }
+ },
+ "retraction_amount": {
+ "label": "Retraction Distance",
+ "description": "The amount of retraction: Set at 0 for no retraction at all. A value of 4.5mm seems to generate good results for 3mm filament in Bowden-tube fed printers.",
+ "unit": "mm",
+ "type": "float",
+ "default": 4.5,
+ "visible": false,
+ "inherit": false
+ },
+ "retraction_min_travel": {
+ "label": "Retraction Minimum Travel",
+ "description": "The minimum distance of travel needed for a retraction to happen at all. This helps ensure you do not get a lot of retractions in a small area.",
+ "unit": "mm",
+ "type": "float",
+ "default": 4.5,
+ "visible": false,
+ "inherit": false
+ },
+ "retraction_combing": {
+ "label": "Enable Combing",
+ "description": "Combing keeps the head within the interior of the print whenever possible when traveling from one part of the print to another, and does not use retraction. If combing is disabled the printer head moves straight from the start point to the end point and it will always retract.",
+ "type": "boolean",
+ "default": true,
+ "visible": false,
+ "inherit": false
+ },
+ "retraction_count_max": {
+ "label": "Maximal Retraction Count",
+ "description": "This settings limits the number of retractions occuring within the Minimal Extrusion Distance Window. Further retractions within this window will be ignored. This avoids retracting repeatedly on the same piece of filament as that can flatten the filament and cause grinding issues.",
+ "default": 6,
+ "type": "int",
+ "visible": false,
+ "inherit": false
+ },
+ "retraction_extrusion_window": {
+ "label": "Minimal Extrusion Distance Window",
+ "description": "The window in which the Maximal Retraction Count is enforced. This window should be approximately the size of the Retraction distance, so that effectively the number of times a retraction passes the same patch of material is limited.",
+ "unit": "mm",
+ "type": "float",
+ "default": 4.5,
+ "visible": false,
+ "inherit_function": "retraction_amount"
+ },
+ "retraction_hop": {
+ "label": "Z Hop when Retracting",
+ "description": "Whenever a retraction is done, the head is lifted by this amount to travel over the print. A value of 0.075 works well. This feature has a lot of positive effect on delta towers.",
+ "unit": "mm",
+ "type": "float",
+ "default": 0.0,
+ "visible": false,
+ "inherit": false
+ }
+ }
+ }
+ }
+ },
+ "speed": {
+ "label": "Speed",
+ "visible": true,
+ "icon": "category_speed",
+ "settings": {
+ "speed_print": {
+ "label": "Print Speed",
+ "description": "The speed at which printing happens. A well-adjusted Ultimaker can reach 150mm/s, but for good quality prints you will want to print slower. Printing speed depends on a lot of factors, so you will need to experiment with optimal settings for this.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 50.0,
+
+ "children": {
+ "speed_infill": {
+ "label": "Infill Speed",
+ "description": "The speed at which infill parts are printed. Printing the infill faster can greatly reduce printing time, but this can negatively affect print quality.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 50.0,
+ "visible": false
+ },
+ "speed_wall": {
+ "label": "Shell Speed",
+ "description": "The speed at which shell is printed. Printing the outer shell at a lower speed improves the final skin quality.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 50.0,
+ "visible": false,
+
+ "children": {
+ "speed_wall_0": {
+ "label": "Outer Shell Speed",
+ "description": "The speed at which outer shell is printed. Printing the outer shell at a lower speed improves the final skin quality. However, having a large difference between the inner shell speed and the outer shell speed will effect quality in a negative way.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 50.0,
+ "visible": false
+ },
+ "speed_wall_x": {
+ "label": "Inner Shell Speed",
+ "description": "The speed at which all inner shells are printed. Printing the inner shell fasster than the outer shell will reduce printing time. It is good to set this in between the outer shell speed and the infill speed.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 50.0,
+ "visible": false
+ }
+ }
+ },
+ "speed_topbottom": {
+ "label": "Top/Bottom Speed",
+ "description": "Speed at which top/bottom parts are printed. Printing the top/bottom faster can greatly reduce printing time, but this can negatively affect print quality.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 50.0,
+ "visible": false
+ },
+ "speed_support": {
+ "label": "Support Speed",
+ "description": "The speed at which exterior support is printed. Printing exterior supports at higher speeds can greatly improve printing time. And the surface quality of exterior support is usually not important, so higher speeds can be used.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 50.0,
+ "visible": false,
+ "inherit_function": "speed_wall_0"
+ }
+ }
+ },
+ "speed_travel": {
+ "label": "Travel Speed",
+ "description": "The speed at which travel moves are done. A well-built Ultimaker can reach speeds of 250mm/s. But some machines might have misaligned layers then.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 150.0
+ },
+ "speed_layer_0": {
+ "label": "Bottom Layer Speed",
+ "description": "The print speed for the bottom layer: You want to print the first layer slower so it sticks to the printer bed better.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 15.0,
+ "visible": false,
+
+ "children": {
+ "skirt_speed": {
+ "label": "Skirt Speed",
+ "description": "The speed at which the skirt and brim are printed. Normally this is done at the initial layer speed. But sometimes you want to print the skirt at a different speed.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 15.0,
+ "visible": false
+ }
+ }
+ },
+ "speed_slowdown_layers": {
+ "label": "Amount of Slower Layers",
+ "description": "The first few layers are printed slower then the rest of the object, this to get better adhesion to the printer bed and improve the overall success rate of prints. The speed is gradually increased over these layers. 4 layers of speed-up is generally right for most materials and printers.",
+ "type": "int",
+ "default": 4,
+ "visible": false
+ }
+ }
+ },
+ "infill": {
+ "label": "Infill",
+ "visible": true,
+ "icon": "category_infill",
+ "settings": {
+ "fill_sparse_density": {
+ "label": "Infill Density",
+ "description": "This controls how densely filled the insides of your print will be. For a solid part use 100%, for an hollow part use 0%. A value around 20% is usually enough. This won't affect the outside of the print and only adjusts how strong the part becomes.",
+ "unit": "%",
+ "type": "float",
+ "default": 20.0,
+
+ "children": {
+ "fill_pattern": {
+ "label": "Infill Pattern",
+ "description": "Cura defaults to switching between grid and line infill. But with this setting visible you can control this yourself. The line infill swaps direction on alternate layers of infill, while the grid prints the full cross-hatching on each layer of infill.",
+ "type": "enum",
+ "visible": false,
+ "options": [
+ "Grid",
+ "Lines",
+ "Concentric",
+ "ZigZag"
+ ],
+ "default": "Grid",
+ "inherit_function": "'Lines' if parent_value > 25 else 'Grid'"
+ },
+ "infill_line_distance": {
+ "label": "Line distance",
+ "description": "Distance between the printed infill lines.",
+ "unit": "mm",
+ "type": "float",
+ "default": 2.0,
+ "visible": false,
+ "inherit_function": "(infill_line_width * 100) / parent_value"
+ }
+ }
+ },
+ "fill_overlap": {
+ "label": "Infill Overlap",
+ "description": "The amount of overlap between the infill and the walls. A slight overlap allows the walls to connect firmly to the infill.",
+ "unit": "%",
+ "type": "float",
+ "default": 15.0,
+ "visible": false
+ },
+ "fill_sparse_thickness": {
+ "label": "Infill Thickness",
+ "description": "The thickness of the sparse infill. This is rounded to a multiple of the layerheight and used to print the sparse-infill in fewer, thicker layers to save printing time.",
+ "unit": "mm",
+ "type": "float",
+ "default": 0.1,
+ "visible": false,
+
+ "children": {
+ "fill_sparse_combine": {
+ "label": "Infill Layers",
+ "description": "Amount of layers that are combined together to form sparse infill.",
+ "type": "int",
+ "default": 1,
+ "visible": false,
+ "inherit_function": "math.floor((parent_value + 0.001) / layer_height)"
+ }
+ }
+ }
+ }
+ },
+ "cooling": {
+ "label": "Cooling",
+ "visible": true,
+ "icon": "category_cool",
+ "settings": {
+ "cool_fan_enabled": {
+ "label": "Enable Cooling Fan",
+ "description": "Enable the cooling fan during the print. The extra cooling from the cooling fan helps parts with small cross sections that print each layer quickly.",
+ "type": "boolean",
+ "default": true,
+
+ "children": {
+ "cool_fan_speed": {
+ "label": "Fan Speed",
+ "description": "Fan speed used for the print cooling fan on the printer head.",
+ "unit": "%",
+ "type": "float",
+ "default": 100.0,
+ "visible": false,
+ "inherit_function": "100.0 if parent_value else 0.0",
+
+ "children": {
+ "cool_fan_speed_min": {
+ "label": "Minimum Fan Speed",
+ "description": "Normally the fan runs at the minimum fan speed. If the layer is slowed down due to minimum layer time, the fan speed adjusts between minimum and maximum fan speed.",
+ "unit": "%",
+ "type": "float",
+ "default": 100.0,
+ "visible": false
+ },
+ "cool_fan_speed_max": {
+ "label": "Maximum Fan Speed",
+ "description": "Normally the fan runs at the minimum fan speed. If the layer is slowed down due to minimum layer time, the fan speed adjusts between minimum and maximum fan speed.",
+ "unit": "%",
+ "type": "float",
+ "default": 100.0,
+ "visible": false
+ }
+ }
+ }
+ }
+ },
+ "cool_fan_full_at_height": {
+ "label": "Fan Full on at Height",
+ "description": "The height at which the fan is turned on completely. For the layers below this the fan speed is scaled linearly with the fan off for the first layer.",
+ "unit": "mm",
+ "type": "float",
+ "default": 0.5,
+ "visible": false,
+
+ "children": {
+ "cool_fan_full_layer": {
+ "label": "Fan Full on at Layer",
+ "description": "The layer number at which the fan is turned on completely. For the layers below this the fan speed is scaled linearly with the fan off for the first layer.",
+ "type": "int",
+ "default": 4,
+ "visible": false,
+ "inherit_function": "int((parent_value - layer_height_0 + 0.001) / layer_height)"
+ }
+ }
+ },
+ "cool_min_layer_time": {
+ "label": "Minimal Layer Time",
+ "description": "The minimum time spent in a layer: Gives the layer time to cool down before the next one is put on top. If a layer would print in less time, then the printer will slow down to make sure it has spent at least this many seconds printing the layer.",
+ "unit": "sec",
+ "type": "float",
+ "default": 5.0,
+ "visible": false
+ },
+ "cool_min_layer_time_fan_speed_max": {
+ "label": "Minimal Layer Time Full Fan Speed",
+ "description": "The minimum time spent in a layer which will cause the fan to be at minmum speed. The fan speed increases linearly from maximal fan speed for layers taking minimal layer time to minimal fan speed for layers taking the time specified here.",
+ "unit": "sec",
+ "type": "float",
+ "default": 10.0,
+ "visible": false
+ },
+ "cool_min_speed": {
+ "label": "Minimum Speed",
+ "description": "The minimum layer time can cause the print to slow down so much it starts to droop. The minimum feedrate protects against this. Even if a print gets slowed down it will never be slower than this minimum speed.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 10.0,
+ "visible": false
+ },
+ "cool_lift_head": {
+ "label": "Lift Head",
+ "description": "Lift the head away from the print if the minimum speed is hit because of cool slowdown, and wait the extra time away from the print surface until the minimum layer time is used up.",
+ "type": "boolean",
+ "default": false,
+ "visible": false
+ }
+ }
+ },
+ "support": {
+ "label": "Support",
+ "visible": true,
+ "icon": "category_support",
+ "settings": {
+ "support_enable": {
+ "label": "Enable Support",
+ "description": "Enable exterior support structures. This will build up supporting structures below the model to prevent the model from sagging or printing in mid air.",
+ "type": "boolean",
+ "default": true
+ },
+ "support_type": {
+ "label": "Placement",
+ "description": "Where to place support structures. The placement can be restricted such that the support structures won't rest on the model, which could otherwise cause scarring.",
+ "type": "enum",
+ "options": [
+ "Touching Buildplate",
+ "Everywhere"
+ ],
+ "default": "Touching Buildplate",
+ "visible": true,
+ "inherit_function": "'Everywhere' if support_enable else 'None'",
+ "active_if": {
+ "setting": "support_enable",
+ "value": true
+ }
+ },
+ "support_angle": {
+ "label": "Overhang Angle",
+ "description": "The maximum angle of overhangs for which support will be added. With 0 degrees being horizontal, and 90 degrees being vertical.",
+ "unit": "°",
+ "type": "float",
+ "default": 60.0,
+ "visible": false,
+ "active_if": {
+ "setting": "support_enable",
+ "value": true
+ }
+ },
+ "support_xy_distance": {
+ "label": "X/Y Distance",
+ "description": "Distance of the support structure from the print, in the X/Y directions. 0.7mm typically gives a nice distance from the print so the support does not stick to the surface.",
+ "unit": "mm",
+ "type": "float",
+ "default": 0.7,
+ "visible": false,
+ "active_if": {
+ "setting": "support_enable",
+ "value": true
+ }
+ },
+ "support_z_distance": {
+ "label": "Z Distance",
+ "description": "Distance from the top/bottom of the support to the print. A small gap here makes it easier to remove the support but makes the print a bit uglier. 0.15mm allows for easier separation of the support structure.",
+ "unit": "mm",
+ "type": "float",
+ "default": 0.15,
+ "visible": false,
+ "active_if": {
+ "setting": "support_enable",
+ "value": true
+ },
+
+ "children": {
+ "support_top_distance": {
+ "label": "Top Distance",
+ "description": "Distance from the top of the support to the print.",
+ "unit": "mm",
+ "default": 0.15,
+ "type": "float",
+ "visible": false
+ },
+ "support_bottom_distance": {
+ "label": "Bottom Distance",
+ "description": "Distance from the print to the bottom of the support.",
+ "unit": "mm",
+ "default": 0.15,
+ "type": "float",
+ "visible": false
+ }
+ }
+ },
+ "support_bottom_stair_step_height": {
+ "label": "Stair Step Height",
+ "description": "The height of the steps of the stair-like bottom of support resting on the model. Small steps can cause the support to be hard to remove from the top of the model.",
+ "unit": "mm",
+ "type": "float",
+ "default": 0.5,
+ "visible": false,
+ "active_if": {
+ "setting": "support_type",
+ "value": "Everywhere"
+ }
+ },
+ "support_join_distance": {
+ "label": "Join Distance",
+ "description": "The maximum distance between support blocks, in the X/Y directions, such that the blocks will merge into a single block.",
+ "unit": "mm",
+ "type": "float",
+ "default": 0.7,
+ "visible": false
+ },
+ "support_area_smoothing": {
+ "label": "Area Smoothing",
+ "description": "Maximal distance in the X/Y directions of a line segment which is to be smoothed out. Ragged lines are introduced by the join distance and support bridge, which cause the machine to resonate. Smoothing the support areas won't cause them to break with the constraints, except it might change the overhang.",
+ "unit": "mm",
+ "type": "float",
+ "default": 0.6,
+ "visible": false
+ },
+ "support_use_towers": {
+ "label": "Use towers.",
+ "description": "Use specialized towers to support tiny overhang areas. These towers have a larger diameter than the region they support. Near the overhang the towers' diameter decreases, forming a roof.",
+ "type": "boolean",
+ "default": true,
+ "visible": true
+ },
+ "support_minimal_diameter": {
+ "label": "Minimal Diameter",
+ "description": "Maximal diameter in the X/Y directions of a small area which is to be supported by a specialized support tower. ",
+ "unit": "mm",
+ "type": "float",
+ "default": 1.0,
+ "visible": false,
+ "active_if": {
+ "setting": "support_use_towers",
+ "value": true
+ }
+ },
+ "support_tower_diameter": {
+ "label": "Tower Diameter",
+ "description": "The diameter of a special tower. ",
+ "unit": "mm",
+ "type": "float",
+ "default": 1.0,
+ "visible": false,
+ "active_if": {
+ "setting": "support_use_towers",
+ "value": true
+ }
+ },
+ "support_tower_roof_angle": {
+ "label": "Tower Roof Angle",
+ "description": "The angle of the rooftop of a tower. Larger angles mean more pointy towers. ",
+ "unit": "°",
+ "type": "int",
+ "default": 65,
+ "visible": false,
+ "active_if": {
+ "setting": "support_use_towers",
+ "value": true
+ }
+ },
+ "support_pattern": {
+ "label": "Pattern",
+ "description": "Cura supports 3 distinct types of support structure. First is a grid based support structure which is quite solid and can be removed as 1 piece. The second is a line based support structure which has to be peeled off line by line. The third is a structure in between the other two; it consists of lines which are connected in an accordeon fashion.",
+ "type": "enum",
+ "options": [
+ "Grid",
+ "Lines",
+ "ZigZag"
+ ],
+ "default": "ZigZag",
+ "visible": true,
+ "active_if": {
+ "setting": "support_enable",
+ "value": true
+ }
+ },
+ "support_connect_zigzags": {
+ "label": "Connect ZigZags",
+ "description": "Connect the ZigZags. Makes them harder to remove, but prevents stringing of disconnected zigzags.",
+ "type": "boolean",
+ "default": true,
+ "visible": false,
+ "active_if": {
+ "setting": "support_pattern",
+ "value": "ZigZag"
+ }
+ },
+ "support_fill_rate": {
+ "label": "Fill Amount",
+ "description": "The amount of infill structure in the support, less infill gives weaker support which is easier to remove.",
+ "unit": "%",
+ "type": "float",
+ "default": 15,
+ "visible": false,
+ "active_if": {
+ "setting": "support_enable",
+ "value": true
+ },
+
+ "children": {
+ "support_line_distance": {
+ "label": "Line distance",
+ "description": "Distance between the printed support lines.",
+ "unit": "mm",
+ "type": "float",
+ "default": 2.66,
+ "visible": false,
+ "active_if": {
+ "setting": "support_enable",
+ "value": true
+ },
+ "inherit_function": "(support_line_width * 100) / parent_value"
+ }
+ }
+ }
+ }
+ },
+ "platform_adhesion": {
+ "label": "Platform Adhesion",
+ "visible": true,
+ "icon": "category_adhesion",
+ "settings": {
+ "adhesion_type": {
+ "label": "Type",
+ "description": "Different options that help in preventing corners from lifting due to warping. Brim adds a single-layer-thick flat area around your object which is easy to cut off afterwards, and it is the recommended option. Raft adds a thick grid below the object and a thin interface between this and your object. (Note that enabling the brim or raft disables the skirt.)",
+ "type": "enum",
+ "options": [
+ "None",
+ "Brim",
+ "Raft"
+ ],
+ "default": "None"
+ },
+ "skirt_line_count": {
+ "label": "Skirt Line Count",
+ "description": "The skirt is a line drawn around the first layer of the. This helps to prime your extruder, and to see if the object fits on your platform. Setting this to 0 will disable the skirt. Multiple skirt lines can help to prime your extruder better for small objects.",
+ "type": "int",
+ "default": 1,
+ "active_if": {
+ "setting": "adhesion_type",
+ "value": "None"
+ }
+ },
+ "skirt_gap": {
+ "label": "Skirt Distance",
+ "description": "The horizontal distance between the skirt and the first layer of the print.\nThis is the minimum distance, multiple skirt lines will extend outwards from this distance.",
+ "unit": "mm",
+ "type": "float",
+ "default": 3.0,
+ "active_if": {
+ "setting": "adhesion_type",
+ "value": "None"
+ }
+ },
+ "skirt_minimal_length": {
+ "label": "Skirt Minimum Length",
+ "description": "The minimum length of the skirt. If this minimum length is not reached, more skirt lines will be added to reach this minimum length. Note: If the line count is set to 0 this is ignored.",
+ "unit": "mm",
+ "type": "float",
+ "default": 250,
+ "active_if": {
+ "setting": "adhesion_type",
+ "value": "None"
+ }
+ },
+ "brim_line_count": {
+ "label": "Brim Line Count",
+ "description": "The amount of lines used for a brim: More lines means a larger brim which sticks better, but this also makes your effective print area smaller.",
+ "type": "int",
+ "default": 1,
+ "active_if": {
+ "setting": "adhesion_type",
+ "value": "Brim"
+ }
+ },
+ "raft_margin": {
+ "label": "Raft Extra Margin",
+ "description": "If the raft is enabled, this is the extra raft area around the object which is also given a raft. Increasing this margin will create a stronger raft while using more material and leaving less area for your print.",
+ "unit": "mm",
+ "type": "float",
+ "default": 5.0,
+ "active_if": {
+ "setting": "adhesion_type",
+ "value": "Raft"
+ }
+ },
+ "raft_line_spacing": {
+ "label": "Raft Line Spacing",
+ "description": "The distance between the raft lines. The first 2 layers of the raft have this amount of spacing between the raft lines.",
+ "unit": "mm",
+ "type": "float",
+ "default": 5.0,
+ "active_if": {
+ "setting": "adhesion_type",
+ "value": "Raft"
+ }
+ },
+ "raft_base_thickness": {
+ "label": "Raft Base Thickness",
+ "description": "Layer thickness of the first raft layer. This should be a thick layer which sticks firmly to the printer bed.",
+ "unit": "mm",
+ "type": "float",
+ "default": 0.3,
+ "active_if": {
+ "setting": "adhesion_type",
+ "value": "Raft"
+ }
+ },
+ "raft_base_linewidth": {
+ "label": "Raft Base Line Width",
+ "description": "Width of the lines in the first raft layer. These should be thick lines to assist in bed adhesion.",
+ "unit": "mm",
+ "type": "float",
+ "default": 1.0,
+ "active_if": {
+ "setting": "adhesion_type",
+ "value": "Raft"
+ }
+ },
+ "raft_base_speed": {
+ "label": "Raft Base Print Speed",
+ "description": "The speed at which the first raft layer is printed. This should be printed quite slowly, as the amount of material coming out of the nozzle is quite high.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 15.0,
+ "active_if": {
+ "setting": "adhesion_type",
+ "value": "Raft"
+ }
+ },
+ "raft_interface_thickness": {
+ "label": "Raft Interface Thickness",
+ "description": "Thickness of the 2nd raft layer.",
+ "unit": "mm",
+ "type": "float",
+ "default": 0.27,
+ "active_if": {
+ "setting": "adhesion_type",
+ "value": "Raft"
+ }
+ },
+ "raft_interface_linewidth": {
+ "label": "Raft Interface Line Width",
+ "description": "Width of the 2nd raft layer lines. These lines should be thinner than the first layer, but strong enough to attach the object to.",
+ "unit": "mm",
+ "type": "float",
+ "default": 0.4,
+ "active_if": {
+ "setting": "adhesion_type",
+ "value": "Raft"
+ }
+ },
+ "raft_airgap": {
+ "label": "Raft Air-gap",
+ "description": "The gap between the final raft layer and the first layer of the object. Only the first layer is raised by this amount to lower the bonding between the raft layer and the object. Makes it easier to peel off the raft.",
+ "unit": "mm",
+ "type": "float",
+ "default": 0.22,
+ "active_if": {
+ "setting": "adhesion_type",
+ "value": "Raft"
+ }
+ },
+ "raft_surface_layers": {
+ "label": "Raft Surface Layers",
+ "description": "The number of surface layers on top of the 2nd raft layer. These are fully filled layers that the object sits on. 2 layers usually works fine.",
+ "type": "int",
+ "default": 2,
+ "active_if": {
+ "setting": "adhesion_type",
+ "value": "Raft"
+ }
+ }
+ }
+ },
+ "blackmagic": {
+ "label": "Fixes",
+ "visible": true,
+ "icon": "category_fixes",
+ "settings": {
+ "magic_spiralize": {
+ "label": "Spiralize the Outer Contour",
+ "description": "Spiralize smooths out the Z move of the outer edge. This will create a steady Z increase over the whole print. This feature turns a solid object into a single walled print with a solid bottom. This feature used to be called ‘Joris’ in older versions.",
+ "type": "boolean",
+ "default": false,
+ "visible": false
+ },
+ "wireframe_enabled": {
+ "label": "Wireframe Printing",
+ "description": "Print only the outside surface with a sparse webbed structure, printing 'in thin air'. This is realized by horizontally printing the contours of the model at given Z intervals which are connected via upward and diagonally downward lines.",
+ "type": "boolean",
+ "default": false,
+ "visible": false
+ },
+ "wireframe_printspeed": {
+ "label": "Printing speed",
+ "description": "Speed at which the nozzle moves when extruding material.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 5.0,
+ "visible": false,
+ "active_if": {
+ "setting": "wireframe",
+ "value": true
+ },
+ "children": {
+ "wireframe_printspeed_bottom": {
+ "label": "Bottom printing speed",
+ "description": "Speed of printing the first layer, which is the only layer touching the bluidplatform.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 5.0,
+ "visible": false,
+ "inherit":true
+ },
+ "wireframe_printspeed_up": {
+ "label": "Upward printing speed",
+ "description": "Speed of printing a line upward 'in thin air'.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 5.0,
+ "visible": false,
+ "inherit":true
+ },
+ "wireframe_printspeed_down": {
+ "label": "Downward printing speed",
+ "description": "Speed of printing a line diagonally downward.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 5.0,
+ "visible": false,
+ "inherit":true
+ },
+ "wireframe_printspeed_flat": {
+ "label": "Horizontal printing speed",
+ "description": "Speed of printing the horizontal contours of the object.",
+ "unit": "mm/s",
+ "type": "float",
+ "default": 5.0,
+ "visible": false,
+ "inherit":true
+ }
+ }
+ },
+ "wireframe_flow": {
+ "label": "Flow",
+ "description": "Flow compensation: the amount of material extruded is multiplied by this value.",
+ "unit": "%",
+ "default": 100.0,
+ "type": "float",
+ "visible": false,
+ "active_if": {
+ "setting": "wireframe",
+ "value": true
+ },
+ "children": {
+ "wireframe_flow_connection": {
+ "label": "Connection flow",
+ "description": "Flow compensation when going up or down.",
+ "unit": "%",
+ "default": 100.0,
+ "type": "float",
+ "visible": false
+ },
+ "wireframe_flow_flat": {
+ "label": "Flat flow",
+ "description": "Flow compensation when printing flat lines.",
+ "unit": "%",
+ "default": 100.0,
+ "type": "float",
+ "visible": false
+ }
+ }
+ },
+ "wireframe_top_delay": {
+ "label": "Top delay",
+ "description": "Delay time after an upward move, so that the upward line can harden.",
+ "unit": "sec",
+ "type": "float",
+ "default": 0.0,
+ "visible": false,
+ "active_if": {
+ "setting": "wireframe",
+ "value": true
+ }
+ },
+ "wireframe_bottom_delay": {
+ "label": "Bottom delay",
+ "description": "Delay time after a downward move.",
+ "unit": "sec",
+ "type": "float",
+ "default": 0.0,
+ "visible": false,
+ "active_if": {
+ "setting": "wireframe",
+ "value": true
+ }
+ },
+ "wireframe_flat_delay": {
+ "label": "Flat delay",
+ "description": "Delay time between two horizontal segments. Introducing such a delay can cause better adhesion to previous layers at the connection points, while too large delay times cause sagging.",
+ "unit": "sec",
+ "type": "float",
+ "default": 0.1,
+ "visible": false,
+ "active_if": {
+ "setting": "wireframe",
+ "value": true
+ }
+ },
+ "wireframe_up_half_speed": {
+ "label": "Ease upward",
+ "description": "Distance of an upward move which is extruded with half speed.\nThis can cause better adhesion to previous layers, while not heating the material in those layers too much.",
+ "type": "float",
+ "unit": "mm",
+ "default": 0.3,
+ "visible": false
+ },
+ "wireframe_top_jump": {
+ "label": "Knot size",
+ "description": "Creates a small knot at the top of an upward line, so that the consecutive horizontal layer has a better chance to connect to it.",
+ "type": "float",
+ "unit": "mm",
+ "default": 0.6,
+ "visible": false,
+ "active_if": {
+ "setting": "wireframe",
+ "value": true
+ }
+ },
+ "wireframe_fall_down": {
+ "label": "Fall down",
+ "description": "Distance with which the material falls down after an upward extrusion. This distance is compensated for.",
+ "type": "float",
+ "unit": "mm",
+ "default": 0.5,
+ "visible": false,
+ "active_if": {
+ "setting": "wireframe",
+ "value": true
+ }
+ },
+ "wireframe_drag_along": {
+ "label": "Drag along",
+ "description": "Distance with which the material of an upward extrusion is dragged along with the diagonally downward extrusion. This distance is compensated for.",
+ "type": "float",
+ "unit": "mm",
+ "default": 0.6,
+ "visible": false,
+ "active_if": {
+ "setting": "wireframe",
+ "value": true
+ }
+ },
+ "wireframe_strategy": {
+ "label": "Strategy",
+ "description": "Strategy for making sure two consecutive layers connect at each connection point. Retraction lets the upward lines harden in the right position, but may cause filament grinding. A knot can be made at the end of an upward line to heighten the chance of connecting to it and to let the line cool; however it may require slow printing speeds. Another strategy is to compensate for the sagging of the top of an upward line; however, the lines won't always fall down as predicted.",
+ "type": "enum",
+ "options": [
+ "Compensate",
+ "Knot",
+ "Retract"
+ ],
+ "default": "Compensate",
+ "visible": false,
+ "active_if": {
+ "setting": "wireframe",
+ "value": true
+ }
+ },
+ "wireframe_straight_before_down": {
+ "label": "Straighten downward lines",
+ "description": "Percentage of a diagonally downward line which is covered by a horizontal line piece. This can prevent sagging of the top most point of upward lines.",
+ "type": "float",
+ "unit": "%",
+ "default": 20.0,
+ "visible": false,
+ "active_if": {
+ "setting": "wireframe",
+ "value": true
+ }
+ },
+ "wireframe_roof_fall_down": {
+ "label": "Roof fall down",
+ "description": "The distance which horizontal roof lines printed 'in thin air' fall down when being printed. This distance is compensated for.",
+ "type": "float",
+ "unit": "mm",
+ "default": 2.0,
+ "visible": false,
+ "active_if": {
+ "setting": "wireframe",
+ "value": true
+ }
+ },
+ "wireframe_roof_drag_along": {
+ "label": "Roof drag along",
+ "description": "The distance of the end piece of an inward line which gets dragged along when going back to the outer outline of the roof. This distance is compensated for.",
+ "type": "float",
+ "unit": "mm",
+ "default": 0.8,
+ "visible": false,
+ "active_if": {
+ "setting": "wireframe",
+ "value": true
+ }
+ },
+ "wireframe_roof_outer_delay": {
+ "label": "Roof outer delay",
+ "description": "Time spent at the outer perimeters of hole which is to become a roof. Larger times can ensure a better connection.",
+ "type": "boolean",
+ "unit": "sec",
+ "type": "float",
+ "default": 0.2,
+ "visible": false,
+ "active_if": {
+ "setting": "wireframe",
+ "value": true
+ }
+ },
+ "wireframe_height": {
+ "label": "Connection height.",
+ "description": "The height of the upward and diagonally downward lines between two horizontal parts.",
+ "type": "float",
+ "unit": "mm",
+ "default": 3.0,
+ "visible": false,
+ "active_if": {
+ "setting": "wireframe",
+ "value": true
+ }
+ },
+ "wireframe_roof_inset": {
+ "label": "Roof inset distance",
+ "description": "The distance covered when making a connection from a roof outline inward.",
+ "type": "float",
+ "unit": "mm",
+ "default": 3.0,
+ "visible": false,
+ "active_if": {
+ "setting": "wireframe",
+ "value": true
+ },
+ "inherit_function": "wireframe_height"
+ },
+ "wireframe_nozzle_clearance": {
+ "label": "Nozzle clearance",
+ "description": "Distance between the nozzle and horizontally downward lines. Larger clearance results in diagonally downward lines with a less steep angle, which in turn results in less upward connections with the next layer.",
+ "type": "float",
+ "unit": "mm",
+ "default": 1.0,
+ "visible": false,
+ "active_if": {
+ "setting": "wireframe",
+ "value": true
+ }
+ }
+ }
+ }
+ }
+}
+
+
diff --git a/src/octoprint/plugins/cura/static/js/cura.js b/src/octoprint/plugins/cura/static/js/cura.js
index 99820e2e9..0d091ab3b 100644
--- a/src/octoprint/plugins/cura/static/js/cura.js
+++ b/src/octoprint/plugins/cura/static/js/cura.js
@@ -23,6 +23,10 @@ $(function() {
self.profileDisplayName = ko.observable();
self.profileDescription = ko.observable();
self.profileAllowOverwrite = ko.observable(true);
+ self.profileMakeDefault = ko.observable(false);
+
+ self.unconfiguredCuraEngine = ko.observable();
+ self.unconfiguredSlicingProfile = ko.observable();
self.uploadElement = $("#settings-cura-import");
self.uploadButton = $("#settings-cura-import-start");
@@ -66,6 +70,7 @@ $(function() {
dataType: "json",
maxNumberOfFiles: 1,
autoUpload: false,
+ headers: OctoPrint.getRequestHeaders(),
add: function(e, data) {
if (data.files.length == 0) {
return false;
@@ -93,6 +98,9 @@ $(function() {
if (self.profileDescription() !== undefined) {
form["description"] = self.profileDescription();
}
+ if (self.profileMakeDefault()) {
+ form["default"] = true;
+ }
data.formData = form;
data.submit();
@@ -107,6 +115,7 @@ $(function() {
self.profileDisplayName(undefined);
self.profileDescription(undefined);
self.profileAllowOverwrite(true);
+ self.profileMakeDefault(false);
$("#settings_plugin_cura_import").modal("hide");
self.requestData();
@@ -123,14 +132,11 @@ $(function() {
return (item.key == data.key);
});
- $.ajax({
- url: data.resource(),
- type: "DELETE",
- success: function() {
+ OctoPrint.slicing.deleteProfileForSlicer("cura", data.key, {url: data.resource()})
+ .done(function() {
self.requestData();
self.slicingViewModel.requestData();
- }
- });
+ });
};
self.makeProfileDefault = function(data) {
@@ -148,35 +154,23 @@ $(function() {
item.isdefault(true);
}
- $.ajax({
- url: data.resource(),
- type: "PATCH",
- dataType: "json",
- data: JSON.stringify({default: true}),
- contentType: "application/json; charset=UTF-8",
- success: function() {
+ OctoPrint.slicing.updateProfileForSlicer("cura", data.key, {default: true}, {url: data.resource()})
+ .done(function() {
self.requestData();
- }
- });
+ });
};
- self.showImportProfileDialog = function() {
+ self.showImportProfileDialog = function(makeDefault) {
+ if (makeDefault == undefined) {
+ makeDefault = _.filter(self.profiles.items(), function(profile) { profile.isdefault() }).length == 0;
+ }
+ self.profileMakeDefault(makeDefault);
$("#settings_plugin_cura_import").modal("show");
};
self.testEnginePath = function() {
- $.ajax({
- url: API_BASEURL + "util/test",
- type: "POST",
- dataType: "json",
- data: JSON.stringify({
- command: "path",
- path: self.settings.plugins.cura.cura_engine(),
- check_type: "file",
- check_access: "x"
- }),
- contentType: "application/json; charset=UTF-8",
- success: function(response) {
+ OctoPrint.util.testExecutable(self.settings.plugins.cura.cura_engine())
+ .done(function(response) {
if (!response.result) {
if (!response.exists) {
self.pathText(gettext("The path doesn't exist"));
@@ -190,17 +184,12 @@ $(function() {
}
self.pathOk(response.result);
self.pathBroken(!response.result);
- }
- })
+ });
};
self.requestData = function() {
- $.ajax({
- url: API_BASEURL + "slicing/cura/profiles",
- type: "GET",
- dataType: "json",
- success: self.fromResponse
- });
+ OctoPrint.slicing.listProfilesForSlicer("cura")
+ .done(self.fromResponse);
};
self.fromResponse = function(data) {
@@ -223,16 +212,35 @@ $(function() {
};
self.onSettingsHidden = function() {
+ self.resetPathTest();
+ };
+
+ self.resetPathTest = function() {
self.pathBroken(false);
self.pathOk(false);
self.pathText("");
};
+
+ self.onWizardDetails = function(response) {
+ if (!response.hasOwnProperty("cura") || !response.cura.required) return;
+
+ if (response.cura.details.hasOwnProperty("engine")) {
+ self.unconfiguredCuraEngine(!response.cura.details.engine);
+ }
+ if (response.cura.details.hasOwnProperty("profile")) {
+ self.unconfiguredSlicingProfile(!response.cura.details.profile);
+ }
+ };
+
+ self.onWizardFinish = function() {
+ self.resetPathTest();
+ };
}
// view model class, parameters for constructor, container to bind to
OCTOPRINT_VIEWMODELS.push([
CuraViewModel,
["loginStateViewModel", "settingsViewModel", "slicingViewModel"],
- "#settings_plugin_cura"
+ ["#settings_plugin_cura", "#wizard_plugin_cura"]
]);
});
diff --git a/src/octoprint/plugins/cura/templates/_snippets/settings/cura/engineLog.jinja2 b/src/octoprint/plugins/cura/templates/_snippets/settings/cura/engineLog.jinja2
new file mode 100644
index 000000000..690f1490d
--- /dev/null
+++ b/src/octoprint/plugins/cura/templates/_snippets/settings/cura/engineLog.jinja2
@@ -0,0 +1,7 @@
+
+
+
+
+
diff --git a/src/octoprint/plugins/cura/templates/_snippets/settings/cura/enginePath.jinja2 b/src/octoprint/plugins/cura/templates/_snippets/settings/cura/enginePath.jinja2
new file mode 100644
index 000000000..250c9e237
--- /dev/null
+++ b/src/octoprint/plugins/cura/templates/_snippets/settings/cura/enginePath.jinja2
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/src/octoprint/plugins/cura/templates/_snippets/settings/cura/profileImporter.jinja2 b/src/octoprint/plugins/cura/templates/_snippets/settings/cura/profileImporter.jinja2
new file mode 100644
index 000000000..219f474ab
--- /dev/null
+++ b/src/octoprint/plugins/cura/templates/_snippets/settings/cura/profileImporter.jinja2
@@ -0,0 +1,58 @@
+
-
+{% include "_snippets/settings/cura/profileImporter.jinja2" %}
diff --git a/src/octoprint/plugins/cura/templates/cura_wizard.jinja2 b/src/octoprint/plugins/cura/templates/cura_wizard.jinja2
new file mode 100644
index 000000000..f05e5f0c4
--- /dev/null
+++ b/src/octoprint/plugins/cura/templates/cura_wizard.jinja2
@@ -0,0 +1,34 @@
+
+
{{ _('Configure CuraEngine') }}
+
{% trans %}
+ The path to CuraEngine has not yet been set up, in order to be able to use
+ CuraEngine for slicing it needs to be specified.
+ {% endtrans %}
+
+
+
+
+
+
+
+
{{ _('Set up a slicing profile') }}
+
{% trans %}You haven't imported a slicing profile to use for slicing with CuraEngine
+ yet. You should do this now.{% endtrans %}
+
+
+ {% include "_snippets/settings/cura/profiles.jinja2" %}
+
+
+
+
+
+ {% trans %}
+ Don't know where to get a profile? In order to export
+ a slicing profile from the Cura desktop UI, open it, set up your
+ profile, then click on "File" and there on "Save Profile". You can
+ import the .ini-file this creates via the "Import Profile" button.
+ {% endtrans %}
+
{% trans %}
+ The pip command could not be found or does not work correctly
+ for this installation of OctoPrint - please consult the log file for details
+ and if necessary configure it manually. No installation and uninstallation of plugin
+ packages is possible while pip is unavailable.
+{% endtrans %}
{% trans %}
+ The pip command is configured to use sudo. This
+ is not recommended due to security reasons. It is strongly
+ suggested you install OctoPrint under a
+ user-owned virtual environment
+ so that the use of sudo is not needed for plugin management.
+{% endtrans %}
{{ _('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"') }}
+
+
+
diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py
index 5a0da551a..33451e575 100644
--- a/src/octoprint/plugins/softwareupdate/__init__.py
+++ b/src/octoprint/plugins/softwareupdate/__init__.py
@@ -14,6 +14,7 @@ import threading
import time
import logging
import logging.handlers
+import hashlib
from . import version_checks, updaters, exceptions, util
@@ -74,6 +75,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()
@@ -81,9 +83,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
@@ -99,8 +115,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
@@ -118,24 +138,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
@@ -150,10 +164,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,
}
@@ -162,28 +174,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:
@@ -229,6 +305,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
@@ -239,7 +319,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:
@@ -353,14 +432,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if not target in check_targets:
continue
- populated_check = self._populated_check(target, check)
-
try:
+ 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", "")))
continue
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown")), target_information)
@@ -377,22 +455,29 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
updatePossible=target_update_possible,
information=target_information,
displayName=populated_check["displayName"],
- displayVersion=populated_check["displayVersion"].format(octoprint_version=octoprint_version, local_name=local_name, local_value=local_value))
+ displayVersion=populated_check["displayVersion"].format(octoprint_version=octoprint_version, local_name=local_name, local_value=local_value),
+ check=populated_check)
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
@@ -415,7 +500,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
@@ -496,7 +585,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))
@@ -590,6 +683,33 @@ 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}")
+
+ from octoprint._version import get_versions
+ versions = get_versions()
+ if check["type"] == "github_commit":
+ result["current"] = versions.get("full-revisionid", versions.get("full", "unknown"))
+ else:
+ result["current"] = versions["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 _log(self, lines, prefix=None, stream=None, strip=True):
if strip:
lines = map(lambda x: x.strip(), lines)
@@ -601,22 +721,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
def _send_client_message(self, message_type, data=None):
self._plugin_manager.send_plugin_message(self._identifier, dict(type=message_type, data=data))
- def _populated_check(self, target, check):
- result = dict(check)
-
- if target == "octoprint":
- from octoprint._version import get_versions
- from flask.ext.babel import gettext
- result["displayName"] = check.get("displayName", gettext("OctoPrint"))
- result["displayVersion"] = check.get("displayVersion", "{octoprint_version}")
- result["current"] = get_versions()["version"]
- else:
- result["displayName"] = check.get("displayName", target)
- result["displayVersion"] = check.get("displayVersion", check.get("current", "unknown"))
- 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
diff --git a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py
index b12f1729e..54df463c8 100644
--- a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py
+++ b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py
@@ -93,7 +93,8 @@ def _git(args, cwd, verbose=False, git_executable=None):
for c in commands:
try:
- return _execute([c] + args, cwd=cwd)
+ returncode, stdout, stderr = _execute([c] + args, cwd=cwd)
+ return returncode, "\n".join(stdout), "\n".join(stderr)
except EnvironmentError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
diff --git a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js
index 1e192fe8a..c047bb859 100644
--- a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js
+++ b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js
@@ -1,3 +1,43 @@
+(function (global, factory) {
+ if (typeof define === "function" && define.amd) {
+ define(["OctoPrint"], factory);
+ } else {
+ factory(window.OctoPrint);
+ }
+})(window || this, function(OctoPrint) {
+ var exports = {};
+
+ var url = OctoPrint.getBlueprintUrl("softwareupdate");
+ var checkUrl = url + "check";
+ var updateUrl = url + "update";
+
+ exports.check = function(force, opts) {
+ return OctoPrint.get(checkUrl + ((!!force) ? "?force=true" : ""), opts);
+ };
+
+ exports.update = function(entries, force, opts) {
+ entries = entries || [];
+ if (typeof entries == "string") {
+ entries = [entries];
+ }
+
+ var data = {
+ entries: entries,
+ force: !!force
+ };
+ return OctoPrint.postJson(updateUrl, data, opts);
+ };
+
+ exports.updateAll = function(force, opts) {
+ var data = {
+ force: !!force
+ };
+ return OctoPrint.postJson(updateUrl, data, opts);
+ };
+
+ OctoPrint.plugins.softwareupdate = exports;
+});
+
$(function() {
function SoftwareUpdateViewModel(parameters) {
var self = this;
@@ -19,12 +59,22 @@ $(function() {
self.workingOutput = undefined;
self.loglines = ko.observableArray([]);
- 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.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",
{
@@ -80,23 +130,36 @@ $(function() {
self.configurationDialog.modal();
};
- self.savePluginSettings = function() {
+ self.savePluginSettings = function(viewModel, event) {
+ var target = $(event.target);
+ target.prepend(' ');
+
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, {
+ success: function() {
+ self.configurationDialog.modal("hide");
+ self._copyConfig();
+ self.performCheck();
+ },
+ complete: function() {
+ $("i.icon-spinner", target).remove();
+ },
+ sending: true
+ });
};
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) {
@@ -115,6 +178,25 @@ $(function() {
});
self.versions.updateItems(versions);
+ 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);
+ }
+
+ 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 = gettext("There are updates available for the following components:");
@@ -181,20 +263,10 @@ $(function() {
self.performCheck = function(showIfNothingNew, force, ignoreSeen) {
if (!self.loginState.isUser()) return;
-
- var url = PLUGIN_BASEURL + "softwareupdate/check";
- if (force) {
- url += "?force=true";
- }
-
- $.ajax({
- url: url,
- type: "GET",
- dataType: "json",
- success: function(data) {
+ OctoPrint.plugins.softwareupdate.check(force)
+ .done(function(data) {
self.fromCheckResponse(data, ignoreSeen, showIfNothingNew);
- }
- });
+ });
};
self._markNotificationAsSeen = function(data) {
@@ -245,13 +317,12 @@ $(function() {
};
self._showPopup(options);
- $.ajax({
- url: PLUGIN_BASEURL + "softwareupdate/update",
- type: "POST",
- dataType: "json",
- contentType: "application/json; charset=UTF-8",
- data: JSON.stringify({force: (force == true)}),
- error: function() {
+ OctoPrint.plugins.softwareupdate.updateAll(force)
+ .done(function(data) {
+ self.currentlyBeingUpdated = data.checks;
+ self._markWorking(gettext("Updating..."), gettext("Updating, please wait."));
+ })
+ .fail(function() {
self.updateInProgress = false;
self._showPopup({
title: gettext("Update not started!"),
@@ -262,12 +333,7 @@ $(function() {
sticker: false
}
});
- },
- success: function(data) {
- self.currentlyBeingUpdated = data.checks;
- self._markWorking(gettext("Updating..."), gettext("Updating, please wait."));
- }
- });
+ });
};
self.update = function(force) {
@@ -283,10 +349,11 @@ $(function() {
type: "error"
});
} else {
- showConfirmationDialog(gettext("This will update your OctoPrint installation and restart the server."), function(e) {
- e.preventDefault();
- $("#confirmation_dialog").modal("hide");
- self.performUpdate(force);
+ showConfirmationDialog({
+ message: gettext("This will update your OctoPrint installation and restart the server."),
+ onproceed: function(e) {
+ self.performUpdate(force);
+ }
});
}
@@ -342,18 +409,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();
+ }
}
};
@@ -438,7 +497,7 @@ $(function() {
self.waitingForRestart = false;
self._markDone(text, "message_error");
- }, 30000);
+ }, 60000);
break;
}
diff --git a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2
index cee302426..5f56ba6f1 100644
--- a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2
+++ b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2
@@ -1,3 +1,21 @@
+
{% trans %}
+ Please configure the checkout folder of OctoPrint, otherwise
+ this plugin won't be able to update it. Click on the button
+ to do this. Also refer to the Documentation.
+{% endtrans %}
+
{% trans %}
+
+ You are running a non-release version of OctoPrint but are tracking OctoPrint
+ releases.
+
+ You probably want OctoPrint to track the matching development version instead.
+ If you have a local OctoPrint checkout folder switched to another branch,
+ simply switching over to "Commit" tracking will already
+ take care of that. Otherwise please take a look at the
+ Documentation.
+
+ {{ _('Take note that timelapse configuration is disabled while your printer is printing.') }}
+
{{ _('Timelapse Configuration') }}
+ {{ _('Warning') }} {{ _('Do not use with spiralized ("Joris") vases or similar continuous Z models.') }}
+ {{ _('Note') }} {% trans %}Does not work when printing from the printer's SD Card (no way to detect the change in Z reliably). Use "Timed" mode for those prints instead.{% endtrans %}
diff --git a/src/octoprint/timelapse.py b/src/octoprint/timelapse.py
index 7f32076b4..4cb7eb791 100644
--- a/src/octoprint/timelapse.py
+++ b/src/octoprint/timelapse.py
@@ -6,13 +6,13 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
import logging
import os
import threading
-import urllib
import time
-import subprocess
import fnmatch
import datetime
import sys
import shutil
+import Queue
+import requests
import octoprint.util as util
@@ -58,7 +58,7 @@ def notifyCallbacks(timelapse):
if timelapse is None:
config = None
else:
- config = timelapse.configData()
+ config = timelapse.config_data()
for callback in updateCallbacks:
try: callback.sendTimelapseConfig(config)
except: logging.getLogger(__name__).exception("Exception while pushing timelapse configuration")
@@ -86,12 +86,12 @@ def configureTimelapse(config=None, persist=False):
if type is None or "off" == type:
current = None
elif "zchange" == type:
- current = ZTimelapse(postRoll=postRoll, fps=fps)
+ current = ZTimelapse(post_roll=postRoll, fps=fps)
elif "timed" == type:
interval = 10
if "options" in config and "interval" in config["options"] and config["options"]["interval"] > 0:
interval = config["options"]["interval"]
- current = TimedTimelapse(postRoll=postRoll, interval=interval, fps=fps)
+ current = TimedTimelapse(post_roll=postRoll, interval=interval, fps=fps)
notifyCallbacks(current)
@@ -101,72 +101,83 @@ def configureTimelapse(config=None, persist=False):
class Timelapse(object):
- def __init__(self, postRoll=0, fps=25):
+ QUEUE_ENTRY_TYPE_CAPTURE = "capture"
+ QUEUE_ENTRY_TYPE_CALLBACK = "callback"
+
+ def __init__(self, post_roll=0, fps=25):
self._logger = logging.getLogger(__name__)
- self._imageNumber = None
- self._inTimelapse = False
- self._gcodeFile = None
+ self._image_number = None
+ self._in_timelapse = False
+ self._gcode_file = None
- self._postRoll = postRoll
- self._postRollStart = None
- self._onPostRollDone = None
+ self._post_roll = post_roll
+ self._on_post_roll_done = None
- self._captureDir = settings().getBaseFolder("timelapse_tmp")
- self._movieDir = settings().getBaseFolder("timelapse")
- self._snapshotUrl = settings().get(["webcam", "snapshot"])
- self._ffmpegThreads = settings().get(["webcam", "ffmpegThreads"])
+ self._capture_dir = settings().getBaseFolder("timelapse_tmp")
+ self._movie_dir = settings().getBaseFolder("timelapse")
+ self._snapshot_url = settings().get(["webcam", "snapshot"])
+ self._ffmpeg_threads = settings().get(["webcam", "ffmpegThreads"])
self._fps = fps
- self._renderThread = None
- self._captureMutex = threading.Lock()
+ self._render_thread = None
+
+ self._capture_mutex = threading.Lock()
+ self._capture_queue = Queue.Queue()
+ self._capture_queue_active = True
+
+ self._capture_queue_thread = threading.Thread(target=self._capture_queue_worker)
+ self._capture_queue_thread.daemon = True
+ self._capture_queue_thread.start()
# subscribe events
- eventManager().subscribe(Events.PRINT_STARTED, self.onPrintStarted)
- eventManager().subscribe(Events.PRINT_FAILED, self.onPrintDone)
- eventManager().subscribe(Events.PRINT_DONE, self.onPrintDone)
- eventManager().subscribe(Events.PRINT_RESUMED, self.onPrintResumed)
- for (event, callback) in self.eventSubscriptions():
+ eventManager().subscribe(Events.PRINT_STARTED, self.on_print_started)
+ eventManager().subscribe(Events.PRINT_FAILED, self.on_print_done)
+ eventManager().subscribe(Events.PRINT_DONE, self.on_print_done)
+ eventManager().subscribe(Events.PRINT_RESUMED, self.on_print_resumed)
+ for (event, callback) in self.event_subscriptions():
eventManager().subscribe(event, callback)
- def postRoll(self):
- return self._postRoll
+ @property
+ def post_roll(self):
+ return self._post_roll
+ @property
def fps(self):
return self._fps
def unload(self):
- if self._inTimelapse:
- self.stopTimelapse(doCreateMovie=False)
+ if self._in_timelapse:
+ self.stop_timelapse(doCreateMovie=False)
# unsubscribe events
- eventManager().unsubscribe(Events.PRINT_STARTED, self.onPrintStarted)
- eventManager().unsubscribe(Events.PRINT_FAILED, self.onPrintDone)
- eventManager().unsubscribe(Events.PRINT_DONE, self.onPrintDone)
- eventManager().unsubscribe(Events.PRINT_RESUMED, self.onPrintResumed)
- for (event, callback) in self.eventSubscriptions():
+ eventManager().unsubscribe(Events.PRINT_STARTED, self.on_print_started)
+ eventManager().unsubscribe(Events.PRINT_FAILED, self.on_print_done)
+ eventManager().unsubscribe(Events.PRINT_DONE, self.on_print_done)
+ eventManager().unsubscribe(Events.PRINT_RESUMED, self.on_print_resumed)
+ for (event, callback) in self.event_subscriptions():
eventManager().unsubscribe(event, callback)
- def onPrintStarted(self, event, payload):
+ def on_print_started(self, event, payload):
"""
Override this to perform additional actions upon start of a print job.
"""
- self.startTimelapse(payload["file"])
+ self.start_timelapse(payload["file"])
- def onPrintDone(self, event, payload):
+ def on_print_done(self, event, payload):
"""
Override this to perform additional actions upon the stop of a print job.
"""
- self.stopTimelapse(success=(event==Events.PRINT_DONE))
+ self.stop_timelapse(success=(event==Events.PRINT_DONE))
- def onPrintResumed(self, event, payload):
+ def on_print_resumed(self, event, payload):
"""
Override this to perform additional actions upon the pausing of a print job.
"""
- if not self._inTimelapse:
- self.startTimelapse(payload["file"])
+ if not self._in_timelapse:
+ self.start_timelapse(payload["file"])
- def eventSubscriptions(self):
+ def event_subscriptions(self):
"""
Override this method to subscribe to additional events by returning an array of (event, callback) tuples.
@@ -178,7 +189,7 @@ class Timelapse(object):
"""
return []
- def configData(self):
+ def config_data(self):
"""
Override this method to return the current timelapse configuration data. The data should have the following
form:
@@ -188,105 +199,153 @@ class Timelapse(object):
"""
return None
- def startTimelapse(self, gcodeFile):
+ def start_timelapse(self, gcodeFile):
self._logger.debug("Starting timelapse for %s" % gcodeFile)
- self.cleanCaptureDir()
+ self.clean_capture_dir()
- self._imageNumber = 0
- self._inTimelapse = True
- self._gcodeFile = os.path.basename(gcodeFile)
+ self._image_number = 0
+ self._in_timelapse = True
+ self._gcode_file = os.path.basename(gcodeFile)
- def stopTimelapse(self, doCreateMovie=True, success=True):
+ def stop_timelapse(self, doCreateMovie=True, success=True):
self._logger.debug("Stopping timelapse")
- self._inTimelapse = False
+ self._in_timelapse = False
def resetImageNumber():
- self._imageNumber = None
+ self._image_number = None
def createMovie():
- self._renderThread = threading.Thread(target=self._createMovie, kwargs={"success": success})
- self._renderThread.daemon = True
- self._renderThread.start()
+ self._render_thread = threading.Thread(target=self._create_movie, kwargs={"success": success})
+ self._render_thread.daemon = True
+ self._render_thread.start()
def resetAndCreate():
resetImageNumber()
createMovie()
- if self._postRoll > 0:
- self._postRollStart = time.time()
+ def waitForCaptures(callback):
+ self._capture_queue.put(dict(type=self.__class__.QUEUE_ENTRY_TYPE_CALLBACK, callback=callback))
+
+ def getWaitForCaptures(callback):
+ def f():
+ waitForCaptures(callback)
+ return f
+
+ if self._post_roll > 0:
+ eventManager().fire(Events.POSTROLL_START, dict(postroll_duration=self.calculate_post_roll(), postroll_length=self.post_roll, postroll_fps=self.fps))
+ self._post_roll_start = time.time()
if doCreateMovie:
- self._onPostRollDone = resetAndCreate
+ self._on_post_roll_done = getWaitForCaptures(resetAndCreate)
else:
- self._onPostRollDone = resetImageNumber
- self.processPostRoll()
+ self._on_post_roll_done = resetImageNumber
+ self.process_post_roll()
else:
- self._postRollStart = None
+ self._post_roll_start = None
if doCreateMovie:
- resetAndCreate()
+ waitForCaptures(resetAndCreate)
else:
resetImageNumber()
- def processPostRoll(self):
- pass
+ def calculate_post_roll(self):
+ return None
+
+ def process_post_roll(self):
+ self.post_roll_finished()
+
+ def post_roll_finished(self):
+ if self.post_roll:
+ eventManager().fire(Events.POSTROLL_END)
+ if self._on_post_roll_done is not None:
+ self._on_post_roll_done()
def captureImage(self):
- if self._captureDir is None:
+ if self._capture_dir is None:
self._logger.warn("Cannot capture image, capture directory is unset")
return
- if self._imageNumber is None:
- self._logger.warn("Cannot capture image, image number is unset")
- return
+ with self._capture_mutex:
+ if self._image_number is None:
+ self._logger.warn("Cannot capture image, image number is unset")
+ return
+
+ filename = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
+ self._image_number += 1
- with self._captureMutex:
- filename = os.path.join(self._captureDir, "tmp_%05d.jpg" % self._imageNumber)
- self._imageNumber += 1
self._logger.debug("Capturing image to %s" % filename)
- captureThread = threading.Thread(target=self._captureWorker, kwargs={"filename": filename})
- captureThread.daemon = True
- captureThread.start()
+ entry = dict(type=self.__class__.QUEUE_ENTRY_TYPE_CAPTURE,
+ filename=filename,
+ onerror=self._on_capture_error)
+ self._capture_queue.put(entry)
return filename
- def _captureWorker(self, filename):
+ def _on_capture_error(self):
+ with self._capture_mutex:
+ if self._image_number is not None and self._image_number > 0:
+ self._image_number -= 1
+
+ def _capture_queue_worker(self):
+ while self._capture_queue_active:
+ entry = self._capture_queue.get(block=True)
+
+ if entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CAPTURE and "filename" in entry:
+ filename = entry["filename"]
+ onerror = entry.pop("onerror", None)
+ self._perform_capture(filename, onerror=onerror)
+
+ elif entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CALLBACK and "callback" in entry:
+ args = entry.pop("args", [])
+ kwargs = entry.pop("kwargs", dict())
+ entry["callback"](*args, **kwargs)
+
+ def _perform_capture(self, filename, onerror=None):
eventManager().fire(Events.CAPTURE_START, {"file": filename})
try:
- urllib.urlretrieve(self._snapshotUrl, filename)
- self._logger.debug("Image %s captured from %s" % (filename, self._snapshotUrl))
+ self._logger.debug("Going to capture %s from %s" % (filename, self._snapshot_url))
+ r = requests.get(self._snapshot_url, stream=True)
+ with open (filename, "wb") as f:
+ for chunk in r.iter_content(chunk_size=1024):
+ if chunk:
+ f.write(chunk)
+ f.flush()
+ self._logger.debug("Image %s captured from %s" % (filename, self._snapshot_url))
except:
- self._logger.exception("Could not capture image %s from %s, decreasing image counter again" % (filename, self._snapshotUrl))
- with self._captureMutex:
- if self._imageNumber is not None and self._imageNumber > 0:
- self._imageNumber -= 1
- eventManager().fire(Events.CAPTURE_DONE, {"file": filename})
+ self._logger.exception("Could not capture image %s from %s" % (filename, self._snapshot_url))
+ if callable(onerror):
+ onerror()
+ eventManager().fire(Events.CAPTURE_FAILED, {"file": filename})
+ return False
+ else:
+ eventManager().fire(Events.CAPTURE_DONE, {"file": filename})
+ return True
- def _createMovie(self, success=True):
+ def _create_movie(self, success=True):
ffmpeg = settings().get(["webcam", "ffmpeg"])
bitrate = settings().get(["webcam", "bitrate"])
if ffmpeg is None or bitrate is None:
self._logger.warn("Cannot create movie, path to ffmpeg or desired bitrate is unset")
return
- input = os.path.join(self._captureDir, "tmp_%05d.jpg")
+ input = os.path.join(self._capture_dir, "tmp_%05d.jpg")
if success:
- output = os.path.join(self._movieDir, "%s_%s.mpg" % (os.path.splitext(self._gcodeFile)[0], time.strftime("%Y%m%d%H%M%S")))
+ output = os.path.join(self._movie_dir, "%s_%s.mpg" % (os.path.splitext(self._gcode_file)[0], time.strftime("%Y%m%d%H%M%S")))
else:
- output = os.path.join(self._movieDir, "%s_%s-failed.mpg" % (os.path.splitext(self._gcodeFile)[0], time.strftime("%Y%m%d%H%M%S")))
+ output = os.path.join(self._movie_dir, "%s_%s-failed.mpg" % (os.path.splitext(self._gcode_file)[0], time.strftime("%Y%m%d%H%M%S")))
# prepare ffmpeg command
command = [
- ffmpeg, '-framerate', str(self._fps), '-loglevel', 'error', '-i', input, '-vcodec', 'mpeg2video', '-threads', str(self._ffmpegThreads), '-pix_fmt', 'yuv420p', '-r', str(self._fps), '-y', '-b', bitrate,
+ ffmpeg, '-framerate', str(self._fps), '-loglevel', 'error', '-i', input, '-vcodec', 'mpeg2video', '-threads', str(self._ffmpeg_threads), '-pix_fmt', 'yuv420p', '-r', str(self._fps), '-y', '-b', bitrate,
'-f', 'vob']
filters = []
# flip video if configured
- if settings().getBoolean(["webcam", "rotate90"]):
- filters.append('transpose=1')
if settings().getBoolean(["webcam", "flipH"]):
filters.append('hflip')
if settings().getBoolean(["webcam", "flipV"]):
filters.append('vflip')
+ if settings().getBoolean(["webcam", "rotate90"]):
+ filters.append('transpose=2')
# add watermark if configured
watermarkFilter = None
@@ -315,7 +374,7 @@ class Timelapse(object):
# finalize command with output file
self._logger.debug("Rendering movie to %s" % output)
command.append("\"" + output + "\"")
- eventManager().fire(Events.MOVIE_RENDERING, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)})
+ eventManager().fire(Events.MOVIE_RENDERING, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output)})
command_str = " ".join(command)
self._logger.debug("Executing command: %s" % command_str)
@@ -323,75 +382,74 @@ class Timelapse(object):
try:
p = sarge.run(command_str, stderr=sarge.Capture())
if p.returncode == 0:
- eventManager().fire(Events.MOVIE_DONE, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)})
+ eventManager().fire(Events.MOVIE_DONE, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output)})
else:
returncode = p.returncode
stderr_text = p.stderr.text
self._logger.warn("Could not render movie, got return code %r: %s" % (returncode, stderr_text))
- eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output), "returncode": returncode, "error": stderr_text})
+ eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output), "returncode": returncode, "error": stderr_text})
except:
self._logger.exception("Could not render movie due to unknown error")
- eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output), "returncode": 255, "error": "Unknown error"})
+ eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output), "returncode": 255, "error": "Unknown error"})
- def cleanCaptureDir(self):
- if not os.path.isdir(self._captureDir):
+ def clean_capture_dir(self):
+ if not os.path.isdir(self._capture_dir):
self._logger.warn("Cannot clean capture directory, it is unset")
return
- for filename in os.listdir(self._captureDir):
+ for filename in os.listdir(self._capture_dir):
if not fnmatch.fnmatch(filename, "*.jpg"):
continue
- os.remove(os.path.join(self._captureDir, filename))
+ os.remove(os.path.join(self._capture_dir, filename))
class ZTimelapse(Timelapse):
- def __init__(self, postRoll=0, fps=25):
- Timelapse.__init__(self, postRoll=postRoll, fps=fps)
+ def __init__(self, post_roll=0, fps=25):
+ Timelapse.__init__(self, post_roll=post_roll, fps=fps)
self._logger.debug("ZTimelapse initialized")
- def eventSubscriptions(self):
+ def event_subscriptions(self):
return [
- (Events.Z_CHANGE, self._onZChange)
+ (Events.Z_CHANGE, self._on_z_change)
]
- def configData(self):
+ def config_data(self):
return {
"type": "zchange"
}
- def processPostRoll(self):
- Timelapse.processPostRoll(self)
+ def process_post_roll(self):
+ with self._capture_mutex:
+ filename = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
+ self._image_number += 1
- filename = os.path.join(self._captureDir, "tmp_%05d.jpg" % self._imageNumber)
- self._imageNumber += 1
- with self._captureMutex:
- self._captureWorker(filename)
+ if self._perform_capture(filename):
+ for _ in range(self._post_roll * self._fps):
+ newFile = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
+ self._image_number += 1
+ shutil.copyfile(filename, newFile)
- for i in range(self._postRoll * self._fps):
- newFile = os.path.join(self._captureDir, "tmp_%05d.jpg" % (self._imageNumber))
- self._imageNumber += 1
- shutil.copyfile(filename, newFile)
+ Timelapse.process_post_roll(self)
- if self._onPostRollDone is not None:
- self._onPostRollDone()
-
- def _onZChange(self, event, payload):
+ def _on_z_change(self, event, payload):
self.captureImage()
class TimedTimelapse(Timelapse):
- def __init__(self, postRoll=0, interval=1, fps=25):
- Timelapse.__init__(self, postRoll=postRoll, fps=fps)
+ def __init__(self, post_roll=0, interval=1, fps=25):
+ Timelapse.__init__(self, post_roll=post_roll, fps=fps)
self._interval = interval
if self._interval < 1:
self._interval = 1 # force minimum interval of 1s
- self._timerThread = None
+ self._postroll_captures = 0
+ self._timer = None
self._logger.debug("TimedTimelapse initialized")
+ @property
def interval(self):
return self._interval
- def configData(self):
+ def config_data(self):
return {
"type": "timed",
"options": {
@@ -399,25 +457,39 @@ class TimedTimelapse(Timelapse):
}
}
- def onPrintStarted(self, event, payload):
- Timelapse.onPrintStarted(self, event, payload)
- if self._timerThread is not None:
+ def on_print_started(self, event, payload):
+ Timelapse.on_print_started(self, event, payload)
+ if self._timer is not None:
return
- self._timerThread = threading.Thread(target=self._timerWorker)
- self._timerThread.daemon = True
- self._timerThread.start()
-
- def onPrintDone(self, event, payload):
- Timelapse.onPrintDone(self, event, payload)
- self._timerThread = None
-
- def _timerWorker(self):
self._logger.debug("Starting timer for interval based timelapse")
- while self._inTimelapse or (self._postRollStart and time.time() - self._postRollStart <= self._postRoll * self._fps):
- self.captureImage()
- time.sleep(self._interval)
+ from octoprint.util import RepeatedTimer
+ self._timer = RepeatedTimer(self._interval, self._timer_task,
+ run_first=True, condition=self._timer_active,
+ on_finish=self._on_timer_finished)
+ self._timer.start()
- if self._postRollStart is not None and self._onPostRollDone is not None:
- self._onPostRollDone()
- self._postRollStart = None
+ def on_print_done(self, event, payload):
+ self._postroll_captures = self.post_roll * self.fps
+ Timelapse.on_print_done(self, event, payload)
+
+ def calculate_post_roll(self):
+ return self.post_roll * self.fps * self.interval
+
+ def process_post_roll(self):
+ pass
+
+ def post_roll_finished(self):
+ Timelapse.post_roll_finished(self)
+ self._timer = None
+
+ def _timer_active(self):
+ return self._in_timelapse or self._postroll_captures > 0
+
+ def _timer_task(self):
+ self.captureImage()
+ if self._postroll_captures > 0:
+ self._postroll_captures -= 1
+
+ def _on_timer_finished(self):
+ self.post_roll_finished()
diff --git a/src/octoprint/translations/de/LC_MESSAGES/messages.mo b/src/octoprint/translations/de/LC_MESSAGES/messages.mo
index 13df51838..9f2ed5e39 100644
Binary files a/src/octoprint/translations/de/LC_MESSAGES/messages.mo and b/src/octoprint/translations/de/LC_MESSAGES/messages.mo differ
diff --git a/src/octoprint/translations/de/LC_MESSAGES/messages.po b/src/octoprint/translations/de/LC_MESSAGES/messages.po
index 96511f22f..f87120120 100644
--- a/src/octoprint/translations/de/LC_MESSAGES/messages.po
+++ b/src/octoprint/translations/de/LC_MESSAGES/messages.po
@@ -11,8 +11,8 @@ msgid ""
msgstr ""
"Project-Id-Version: OctoPrint\n"
"Report-Msgid-Bugs-To: i18n@octoprint.org\n"
-"POT-Creation-Date: 2015-07-07 18:20+0200\n"
-"PO-Revision-Date: 2015-07-07 18:23+0100\n"
+"POT-Creation-Date: 2015-08-31 10:04+0200\n"
+"PO-Revision-Date: 2015-08-31 10:28+0100\n"
"Last-Translator: Gina Häußge \n"
"Language-Team: German (http://www.transifex.com/projects/p/octoprint/language/de/)\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
@@ -46,7 +46,7 @@ msgstr "Profile"
#: src/octoprint/plugins/cura/templates/cura_settings.jinja2:22
#: src/octoprint/templates/dialogs/settings/logs.jinja2:6
-#: src/octoprint/templates/tabs/timelapse.jinja2:45
+#: src/octoprint/templates/tabs/timelapse.jinja2:49
msgid "Sort by"
msgstr "Sortieren"
@@ -61,7 +61,7 @@ msgstr "ID"
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:75
#: src/octoprint/templates/dialogs/settings/logs.jinja2:6
#: src/octoprint/templates/sidebar/files_header.jinja2:6
-#: src/octoprint/templates/tabs/timelapse.jinja2:45
+#: src/octoprint/templates/tabs/timelapse.jinja2:49
msgid "ascending"
msgstr "aufsteigend"
@@ -75,8 +75,8 @@ msgstr "aufsteigend"
#: src/octoprint/templates/dialogs/settings/printerprofiles.jinja2:5
#: src/octoprint/templates/dialogs/settings/printerprofiles.jinja2:44
#: src/octoprint/templates/dialogs/settings/terminalfilters.jinja2:3
-#: src/octoprint/templates/tabs/timelapse.jinja2:45
-#: src/octoprint/templates/tabs/timelapse.jinja2:50
+#: src/octoprint/templates/tabs/timelapse.jinja2:49
+#: src/octoprint/templates/tabs/timelapse.jinja2:54
msgid "Name"
msgstr "Name"
@@ -142,228 +142,228 @@ msgstr "Bestätigen"
msgid "Plugin Manager"
msgstr "Pluginmanager"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:130
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:270
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:132
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:277
msgid "Installing plugin..."
msgstr "Installiere Plugin..."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:130
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:132
msgid "Installing plugin from uploaded archive..."
msgstr "Installiere Plugin von hochgeladenem Archiv..."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:142
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:222
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:295
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:325
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:539
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:569
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:586
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:603
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:147
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:225
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:302
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:332
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:546
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:576
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:593
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:610
msgid "Something went wrong"
msgstr "Etwas ist schief gegangen"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:143
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:223
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:296
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:326
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:148
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:226
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:303
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:333
msgid "Please consult octoprint.log for details"
msgstr "Bitte konsultiere octoprint.log für Details"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:272
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:279
#, python-format
msgid "Installing plugin \"%(name)s\" from %(url)s..."
msgstr "Installiere Plugin \"%(name)s\" von %(url)s..."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:274
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:281
#, python-format
msgid "Installing plugin from %(url)s..."
msgstr "Installiere Plugin von %(url)s..."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:277
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:284
msgid "Reinstalling plugin..."
msgstr "Reinstalliere Plugin..."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:278
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:285
#, python-format
msgid "Reinstalling plugin \"%(name)s\" from %(url)s..."
msgstr "Reinstalliere Plugin \"%(name)s\" von %(url)s..."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:316
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:323
msgid "Uninstalling plugin..."
msgstr "Deinstalliere Plugin..."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:316
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:323
#, python-format
msgid "Uninstalling plugin \"%(name)s\""
msgstr "Deinstalliere Plugin \"%(name)s\""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:351
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:358
msgid "Reinstall"
msgstr "Reinstallieren"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:351
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:358
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:130
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:146
msgid "Install"
msgstr "Installieren"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:351
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:358
msgid "Incompatible"
msgstr "Inkompatibel"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:369
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:376
#: src/octoprint/templates/overlays/reloadui.jinja2:9
msgid "Reload now"
msgstr "Jetzt neu laden"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:438
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:445
msgid "Done!"
msgstr "Fertig!"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:458
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:465
msgid "Enable Plugin"
msgstr "Plugin enablen"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:458
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:465
msgid "Disable Plugin"
msgstr "Plugin disablen"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:523
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:530
msgid "Plugin installed"
msgstr "Plugin installiert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:524
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:531
msgid "A plugin was installed successfully, however it was impossible to detect which one. Please Restart OctoPrint to make sure everything will be registered properly"
msgstr "Ein Plugin wurde erfolgreich installiert, es war aber unmöglich zu detektieren, welches. Bitte starte OctoPrint neu um sicherzustellen, dass alles ordnungsgemäß registriert wird."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:528
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:535
#, python-format
msgid "Plugin \"%(name)s\" reinstalled"
msgstr "Plugin \"%(name)s\" reinstalliert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:529
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:536
msgid "The plugin was reinstalled successfully"
msgstr "Das Plugin wurde erfolgreich reinstalliert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:530
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:537
msgid "The plugin was reinstalled successfully, however a restart of OctoPrint is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich reinstalliert, es ist aber ein Neustart von OctoPrint notwendig bevor es genutzt werden kann."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:531
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:538
msgid "The plugin was reinstalled successfully, however a reload of the page is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich reinstalliert, es ist aber ein Neuladen der Seite notwendig bevor es genutzt werden kann."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:533
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:540
#, python-format
msgid "Plugin \"%(name)s\" installed"
msgstr "Plugin \"%(name)s\" installiert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:534
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:541
msgid "The plugin was installed successfully"
msgstr "Das Plugin wurde erfolgreich installiert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:535
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:542
msgid "The plugin was installed successfully, however a restart of OctoPrint is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich installiert, es ist jedoch ein Neustart von OctoPrint notwendig bevor es genutzt werden kann."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:536
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:543
msgid "The plugin was installed successfully, however a reload of the page is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich installiert, es ist jedoch ein Neuladen der Seite notwendig bevor es genutzt werden kann."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:547
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:554
#, python-format
msgid "Reinstalling the plugin from URL \"%(url)s\" failed: %(reason)s"
msgstr "Reinstallation des Plugins von URL \"%(url)s\" fehlgeschlagen: %(reason)s"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:549
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:556
#, python-format
msgid "Installing the plugin from URL \"%(url)s\" failed: %(reason)s"
msgstr "Installation des Plugins von URL \"%(url)s\" fehlgeschlagen: %(reason)s"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:553
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:560
#, python-format
msgid "Reinstalling the plugin from URL \"%(url)s\" failed, please see the log for details."
msgstr "Reinstallation des Plugins von URL \"%(url)s\" fehlgeschlagen, bitte konsultiere das Log für Details."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:555
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:562
#, python-format
msgid "Installing the plugin from URL \"%(url)s\" failed, please see the log for details."
msgstr "Installation des Plugins von URL \"%(url)s\" fehlgeschlagen, bitte konsultiere das Log für Details"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:564
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:571
#, python-format
msgid "Plugin \"%(name)s\" uninstalled"
msgstr "Plugin \"%(name)s\" deinstalliert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:565
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:572
msgid "The plugin was uninstalled successfully"
msgstr "Das Plugin wurde erfolgreich deinstalliert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:566
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:573
msgid "The plugin was uninstalled successfully, however a restart of OctoPrint is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich deinstalliert, es ist jedoch ein Neustart von OctoPrint notwendig."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:567
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:574
msgid "The plugin was uninstalled successfully, however a reload of the page is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich deinstalliert, es ist jedoch ein Neuladen der Seite notwendig."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:571
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:578
#, python-format
msgid "Uninstalling the plugin failed: %(reason)s"
msgstr "Deinstallation des Plugins fehlgeschlagen: %(reason)s"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:573
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:580
msgid "Uninstalling the plugin failed, please see the log for details."
msgstr "Deinstallation des Plugins fehlgeschlagen, bitte konsultiere das Log für Details."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:581
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:588
#, python-format
msgid "Plugin \"%(name)s\" enabled"
msgstr "Plugin \"%(name)s\" aktiviert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:582
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:589
msgid "The plugin was enabled successfully."
msgstr "Das Plugin wurde erfolgreich aktiviert."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:583
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:590
msgid "The plugin was enabled successfully, however a restart of OctoPrint is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich aktiviert, es ist jedoch ein Neustart von OctoPrint notwendig."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:584
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:591
msgid "The plugin was enabled successfully, however a reload of the page is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich aktiviert, es ist jedoch ein Neuladen der Seite notwendig."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:588
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:605
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:595
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:612
#, python-format
msgid "Toggling the plugin failed: %(reason)s"
msgstr "Togglen des Plugins fehlgeschalgen: %(reason)s"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:590
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:607
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:597
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:614
msgid "Toggling the plugin failed, please see the log for details."
msgstr "Togglen des Plugins fehlgeschlagen, bitte konsultiere das Log für Details."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:598
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:605
#, python-format
msgid "Plugin \"%(name)s\" disabled"
msgstr "Plugin \"%(name)s\" deaktiviert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:599
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:606
msgid "The plugin was disabled successfully."
msgstr "Das Plugin wurde erfolgreich deaktiviert."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:600
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:607
msgid "The plugin was disabled successfully, however a restart of OctoPrint is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich deaktiviert, es ist jedoch ein Neustart von OctoPrint notwendig."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:601
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:608
msgid "The plugin was disabled successfully, however a reload of the page is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich deaktiviert, es ist jedoch ein Neuladen der Seite notwendig."
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:3
msgid "Take note that all plugin management functionality is disabled while your printer is printing."
-msgstr "Bitte beachte das jegliche Pluginmanagementfunktionen während des Druckens deaktiviert sind."
+msgstr "Bitte beachte dass jegliche Pluginmanagementfunktionen während des Druckens deaktiviert sind."
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:9
msgid "Installed Plugins"
@@ -388,8 +388,7 @@ msgid "Get More..."
msgstr "Mehr..."
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:59
-#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:152
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:96
+#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:167
#: src/octoprint/templates/dialogs/settings/appearance.jinja2:96
msgid "Close"
msgstr "Schließen"
@@ -415,7 +414,7 @@ msgstr "Nach Veröffentlichungsdatum sortieren"
#: src/octoprint/templates/dialogs/settings/logs.jinja2:6
#: src/octoprint/templates/sidebar/files_header.jinja2:7
#: src/octoprint/templates/sidebar/files_header.jinja2:8
-#: src/octoprint/templates/tabs/timelapse.jinja2:45
+#: src/octoprint/templates/tabs/timelapse.jinja2:49
msgid "descending"
msgstr "absteigend"
@@ -468,12 +467,23 @@ msgstr "... von einem hochgeladenen Archiv"
msgid "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\""
msgstr "Das sieht nicht aus wie ein valides Pluginarchiv. Valide Pluginarchive sollten entweder ZIP-Dateien oder Tarballs sein und die Dateiextension \".zip\", \".tar.gz\", \".tgz\" oder \".tar\" haben"
-#: src/octoprint/plugins/softwareupdate/__init__.py:331
+#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:152
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:62
+#: src/octoprint/templates/tabs/terminal.jinja2:25
+msgid "Advanced options"
+msgstr "Erweiterte Optionen"
+
+#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:158
+msgid "Use --process-dependency-links with pip install"
+msgstr "--process-dependency-link mit pip install verwenden"
+
+#: src/octoprint/plugins/softwareupdate/__init__.py:378
msgid "Software Update"
msgstr "Software Update"
-#: src/octoprint/plugins/softwareupdate/__init__.py:610
-#: src/octoprint/server/views.py:146
+#: src/octoprint/plugins/softwareupdate/__init__.py:662
+#: src/octoprint/plugins/softwareupdate/__init__.py:693
+#: src/octoprint/server/views.py:149
#: src/octoprint/static/js/app/viewmodels/appearance.js:11
#: src/octoprint/static/js/app/viewmodels/appearance.js:13
#: src/octoprint/static/js/app/viewmodels/appearance.js:18
@@ -481,186 +491,210 @@ msgstr "Software Update"
msgid "OctoPrint"
msgstr "OctoPrint"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:119
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:26
+msgid "Release"
+msgstr "Release"
+
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:27
+msgid "Commit"
+msgstr "Commit"
+
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:145
msgid "There are updates available for the following components:"
msgstr "Es gibt Aktualisierungen für die folgenden Komponenten:"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:133
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:159
msgid "Those components marked with can be updated directly."
msgstr "Die mit markierten Komponenten können direkt aktualisiert werden."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:136
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:162
msgid "Update Available"
msgstr "Aktualisierung verfügbar"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:147
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:174
msgid "Ignore"
msgstr "Ignorieren"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:151
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:178
msgid "You can make this message display again via \"Settings\" > \"Software Update\" > \"Check for update now\""
msgstr "Du kannst diese Nachricht erneut anzeigen lassen mittels \"Einstellungen\" > \"Software Update\" > \"Jetzt nach Aktualisierungen suchen\""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:155
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:182
msgid "Update now"
msgstr "Jetzt aktualisieren"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:172
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:199
msgid "Everything is up-to-date"
msgstr "Alles ist auf dem neusten Stand"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:237
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:268
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:388
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:264
msgid "Updating..."
msgstr "Aktualisiere..."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:238
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:265
msgid "Now updating, please wait."
msgstr "Aktualisiere gerade, bitte warten."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:257
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:284
msgid "Update not started!"
msgstr "Aktualisierung nicht gestartet!"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:258
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:285
msgid "The update could not be started. Is it already active? Please consult the log for details."
msgstr "Die Aktualisierung konnte nicht gestartet werden. Läuft bereits eine? Bitte konsultiere das Log für Details."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:268
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:388
-msgid "Updating, please wait."
-msgstr "Aktualisiere gerade, bitte warten."
-
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:281
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:307
msgid "Can't update while printing"
msgstr "Aktualisierung nicht möglich während gedruckt wird"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:282
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:308
msgid "A print job is currently in progress. Updating will be prevented until it is done."
msgstr "Ein Druckjob ist zur Zeit aktiv. Aktualisierungen werden unterbunden bis er fertig ist."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:286
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:312
msgid "This will update your OctoPrint installation and restart the server."
msgstr "Das wird Deine OctoPrint Installation aktualisieren und den Server neu starten."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:347
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:336
msgid "Restart successful!"
msgstr "Neustart erfolgreich!"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:348
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:337
msgid "The server was restarted successfully. The page will now reload automatically."
msgstr "Der Server wurde erfolgreich neu gestartet. Die Seite wird nun automatisch neu geladen."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:391
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:369
#, python-format
msgid "Now updating %(name)s to %(version)s"
msgstr "Aktualisiere %(name)s auf %(version)s"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:409
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:377
msgid "Update successful, restarting!"
msgstr "Aktualisierung erfolgreich, starte neu!"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:410
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:378
msgid "The update finished successfully and the server will now be restarted."
msgstr "Die Aktualisierung wurde erfolgreich durchgeführt und der Server wird jetzt neu gestartet."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:426
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:475
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:389
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:431
msgid "Restart failed"
msgstr "Neustart fehlgeschlagen"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:427
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:390
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:432
msgid "The server apparently did not restart by itself, you'll have to do it manually. Please consult the log file on what went wrong."
msgstr "Der Server hat anscheinend nicht von selbst neu gstartet, Du wirst das manuell tun müssen. Bitte konsultiere das Logfile."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:449
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:406
msgid "The update finished successfully, please restart OctoPrint now."
msgstr "Die Aktualisierung wurde erfolgreich abgeschlossen, bitte starte OctoPrint jetzt neu."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:451
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:408
msgid "The update finished successfully, please reboot the server now."
msgstr "Die Aktualisierung wurde erfolgreich abgeschlossen, bitte reboote den Server jetzt."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:454
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:412
msgid "Update successful, restart required!"
msgstr "Aktualisierung erfolgreich, Neustart notwendig!"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:470
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:425
msgid "Restarting OctoPrint failed, please restart it manually. You might also want to consult the log file on what went wrong here."
msgstr "Der Neustart von OctoPrint ist fehlgeschlagen, bitte starte es manuell neu. Du solltest das Logfile konsultieren, um herauszufinden, was hier schief gelaufen ist."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:472
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:427
msgid "Rebooting the server failed, please reboot it manually. You might also want to consult the log file on what went wrong here."
msgstr "Reboot des Servers fehlgeschlagen, bitte reboote ihn manuell. Du solltest auch das Logfile konsultieren, um herauszufinden, was hier gerade schief gelaufen ist."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:491
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:445
msgid "Update successful!"
msgstr "Aktualisierung erfolgreich!"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:492
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:446
msgid "The update finished successfully."
msgstr "Die Aktualisierung wurde erfolgreich abgeschlossen."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:507
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:458
msgid "Update failed!"
msgstr "Aktualisierung fehlgeschlagen!"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:508
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:459
msgid "The update did not finish successfully. Please consult the log for details."
msgstr "Die Aktualisierung wurde nicht erfolgreich abgeschlossen. Bitte konsultiere das Log für Details."
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:2
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:54
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:1
+msgid ""
+"\n"
+" Please configure the checkout folder of OctoPrint, otherwise\n"
+" this plugin won't be able to update it. Click on the button\n"
+" to do this. Also refer to the Documentation.\n"
+msgstr " Bitte konfiguriere das Checkoutverzeichnis von OctoPrint, andernfalls wird dieses Plugin Deine Installation nicht updaten können. Klicke dazu auf den Button. Siehe des Weiteren auch die Dokumentation."
+
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:6
+msgid ""
+"\n"
+"
\n"
+" You are running a non-release version of OctoPrint but are tracking OctoPrint\n"
+" releases.\n"
+"
\n"
+" You probably want OctoPrint to track the matching development version instead.\n"
+" If you have a local OctoPrint checkout folder switched to another branch,\n"
+" simply switching over to \"Commit\" tracking will already\n"
+" take care of that. Otherwise please take a look at the\n"
+" Documentation.\n"
+"
\n"
+msgstr "
Du nutzt eine unveröffentlichte Version von OctoPrint, trackst aber OctoPrint Releases.
Du willst vermutlich, dass OctoPrint stattdessen die entsprechende Entwicklungsversion trackt. Falls Du dein lokales OctoPrint-Checkoutverzeichnis auf einen anderen Branch gewechselt hast, dann wechsle das Tracking einfach auf \"Commit\". Ansonsten wirf einen Blick in die Dokumentation.
"
+
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:20
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:72
msgid "Plugin Configuration"
msgstr "Pluginkonfiguration"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:5
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:23
msgid "Current versions"
msgstr "Aktuelle Versionen"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:11
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:29
msgid "Update available"
msgstr "Aktualisierung verfügbar"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:16
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:32
+msgid "Update not possible, configuration ok?"
+msgstr "Update nicht möglich, Konfiguration in Ordnung?"
+
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:34
msgid "Installed:"
msgstr "Installiert:"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:17
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:35
msgid "Available:"
msgstr "Verfügbar:"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:41
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:59
msgid "Check for update now"
msgstr "Jetzt nach Aktualisierungen suchen"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:44
-#: src/octoprint/templates/tabs/terminal.jinja2:25
-msgid "Advanced options"
-msgstr "Erweiterte Optionen"
-
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:46
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:64
msgid "Force check for update (overrides cache used for update checks)"
msgstr "Suche nach Aktualisierungen forcieren (ignoriert den Cache für Aktualisierungsinformationen)"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:47
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:65
msgid "Force update now (even if no new versions are available)"
msgstr "Aktualisierung forcieren (selbst wenn keine neue Versionen verfügbar sind)"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:59
-msgid "Restart Command"
-msgstr "Neustartbefehl"
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:77
+msgid "OctoPrint checkout folder"
+msgstr "Checkoutverzeichnis von OctoPrint "
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:65
-msgid "Reboot Command"
-msgstr "Rebootbefehl"
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:83
+msgid "OctoPrint version tracking"
+msgstr "Versionstracking für OctoPrint"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:71
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:89
msgid "Version cache TTL"
-msgstr "Versionscache TTL"
+msgstr "TTL des Versionscaches"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:82
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:100
#: src/octoprint/templates/dialogs/confirmation.jinja2:11
#: src/octoprint/templates/dialogs/settings.jinja2:51
#: src/octoprint/templates/dialogs/slicing.jinja2:50
@@ -668,113 +702,118 @@ msgstr "Versionscache TTL"
msgid "Cancel"
msgstr "Abbruch"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:83
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:101
#: src/octoprint/templates/dialogs/settings.jinja2:52
msgid "Save"
msgstr "Speichern"
-#: src/octoprint/server/views.py:55
+#: src/octoprint/server/views.py:58
msgid "Plugins"
msgstr "Plugins"
-#: src/octoprint/server/views.py:112
+#: src/octoprint/server/views.py:115
msgid "Connection"
msgstr "Verbindung"
-#: src/octoprint/server/views.py:113
+#: src/octoprint/server/views.py:116
msgid "State"
msgstr "Status"
-#: src/octoprint/server/views.py:114
+#: src/octoprint/server/views.py:117
msgid "Files"
msgstr "Dateien"
-#: src/octoprint/server/views.py:120
+#: src/octoprint/server/views.py:123
msgid "Temperature"
msgstr "Temperatur"
-#: src/octoprint/server/views.py:121
+#: src/octoprint/server/views.py:124
msgid "Control"
msgstr "Steuerung"
-#: src/octoprint/server/views.py:122
+#: src/octoprint/server/views.py:125
msgid "Terminal"
msgstr "Terminal"
-#: src/octoprint/server/views.py:125
+#: src/octoprint/server/views.py:128
msgid "GCode Viewer"
msgstr "GCode Viewer"
-#: src/octoprint/server/views.py:127
+#: src/octoprint/server/views.py:130
#: src/octoprint/templates/sidebar/state.jinja2:3
msgid "Timelapse"
msgstr "Zeitraffer"
-#: src/octoprint/server/views.py:132
+#: src/octoprint/server/views.py:135
msgid "Printer"
msgstr "Drucker"
-#: src/octoprint/server/views.py:134
+#: src/octoprint/server/views.py:137
msgid "Serial Connection"
msgstr "Serielle Verbindung"
-#: src/octoprint/server/views.py:135
+#: src/octoprint/server/views.py:138
#: src/octoprint/templates/dialogs/settings/printerprofiles.jinja2:1
msgid "Printer Profiles"
msgstr "Druckerprofile"
-#: src/octoprint/server/views.py:136
+#: src/octoprint/server/views.py:139
msgid "Temperatures"
msgstr "Temperaturen"
-#: src/octoprint/server/views.py:137
+#: src/octoprint/server/views.py:140
msgid "Terminal Filters"
msgstr "Terminalfilter"
-#: src/octoprint/server/views.py:138
+#: src/octoprint/server/views.py:141
msgid "GCODE Scripts"
msgstr "GCODE Scripts"
-#: src/octoprint/server/views.py:140 src/octoprint/server/views.py:142
+#: src/octoprint/server/views.py:143 src/octoprint/server/views.py:145
msgid "Features"
msgstr "Funktionen"
-#: src/octoprint/server/views.py:143
+#: src/octoprint/server/views.py:146
msgid "Webcam"
msgstr "Webcam"
-#: src/octoprint/server/views.py:144
+#: src/octoprint/server/views.py:147
msgid "API"
msgstr "API"
-#: src/octoprint/server/views.py:148
+#: src/octoprint/server/views.py:151
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:2
msgid "Folders"
msgstr "Verzeichnisse"
-#: src/octoprint/server/views.py:149
+#: src/octoprint/server/views.py:152
msgid "Appearance"
msgstr "Aussehen"
-#: src/octoprint/server/views.py:150
+#: src/octoprint/server/views.py:153
#: src/octoprint/templates/dialogs/settings/logs.jinja2:2
msgid "Logs"
msgstr "Logs"
-#: src/octoprint/server/views.py:153
+#: src/octoprint/server/views.py:154
+msgid "Server"
+msgstr "Server"
+
+#: src/octoprint/server/views.py:157
msgid "Access Control"
msgstr "Zugangsbeschränkung"
-#: src/octoprint/server/views.py:159
+#: src/octoprint/server/views.py:163
msgid "Access"
msgstr "Zugriff"
-#: src/octoprint/server/views.py:160
+#: src/octoprint/server/views.py:164
msgid "Interface"
msgstr "Interface"
#: src/octoprint/static/js/app/dataupdater.js:66
#: src/octoprint/static/js/app/dataupdater.js:100
-#: src/octoprint/static/js/app/helpers.js:436
+#: src/octoprint/static/js/app/helpers.js:464
#: src/octoprint/templates/overlays/offline.jinja2:6
msgid "Server is offline"
msgstr "Der Server ist offline"
@@ -787,85 +826,85 @@ msgstr "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ih
msgid "The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below."
msgstr "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ihm verbinden. Ich konnte mich nicht automatisch neu verbinden, aber Du kannst mittels des folgenden Buttons einen manuellen Verbindungsversuch anstoßen."
-#: src/octoprint/static/js/app/dataupdater.js:168
-#: src/octoprint/static/js/app/dataupdater.js:196
+#: src/octoprint/static/js/app/dataupdater.js:169
+#: src/octoprint/static/js/app/dataupdater.js:197
#, python-format
msgid "Slicing ... (%(percentage)d%%)"
msgstr "Slice ... (%(percentage)d%%)"
-#: src/octoprint/static/js/app/dataupdater.js:185
+#: src/octoprint/static/js/app/dataupdater.js:186
msgid "Rendering timelapse"
msgstr "Zeitrafferaufnahme wird gerendert"
-#: src/octoprint/static/js/app/dataupdater.js:185
+#: src/octoprint/static/js/app/dataupdater.js:186
#, python-format
msgid "Now rendering timelapse %(movie_basename)s"
msgstr "Rendere Zeitrafferaufnahme %(movie_basename)s"
-#: src/octoprint/static/js/app/dataupdater.js:187
+#: src/octoprint/static/js/app/dataupdater.js:188
msgid "Timelapse ready"
msgstr "Zeitrafferaufnahme fertig"
-#: src/octoprint/static/js/app/dataupdater.js:187
+#: src/octoprint/static/js/app/dataupdater.js:188
#, python-format
msgid "New timelapse %(movie_basename)s is done rendering."
msgstr "Neue Zeitrafferaufnahme %(movie_basename)s wurde fertig gerendert"
-#: src/octoprint/static/js/app/dataupdater.js:189
+#: src/octoprint/static/js/app/dataupdater.js:190
#, python-format
msgid "Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s"
msgstr "Rendering der Zeitrafferaufnahme %(movie_basename)s fehlgeschlagen mit Returncode %(returncode)s"
-#: src/octoprint/static/js/app/dataupdater.js:191
+#: src/octoprint/static/js/app/dataupdater.js:192
msgid "Rendering failed"
msgstr "Rendering fehlgeschlagen"
-#: src/octoprint/static/js/app/dataupdater.js:198
+#: src/octoprint/static/js/app/dataupdater.js:199
msgid "Slicing ..."
msgstr "Slice ..."
-#: src/octoprint/static/js/app/dataupdater.js:204
+#: src/octoprint/static/js/app/dataupdater.js:205
msgid "Slicing done"
msgstr "Slicing abgeschlossen"
-#: src/octoprint/static/js/app/dataupdater.js:204
+#: src/octoprint/static/js/app/dataupdater.js:205
#, python-format
msgid "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"
msgstr "%(stl)s nach %(gcode)s geslicet, dauerte %(time).2f Sekunden"
-#: src/octoprint/static/js/app/dataupdater.js:214
+#: src/octoprint/static/js/app/dataupdater.js:215
#, python-format
msgid "Could not slice %(stl)s to %(gcode)s: %(reason)s"
msgstr "Konnte %(stl)s nicht nach %(gcode)s slicen: %(reason)s"
-#: src/octoprint/static/js/app/dataupdater.js:215
+#: src/octoprint/static/js/app/dataupdater.js:216
msgid "Slicing failed"
msgstr "Slicing fehlgeschlagen"
-#: src/octoprint/static/js/app/dataupdater.js:219
+#: src/octoprint/static/js/app/dataupdater.js:220
msgid "Streaming ..."
msgstr "Streaming ..."
-#: src/octoprint/static/js/app/dataupdater.js:225
+#: src/octoprint/static/js/app/dataupdater.js:226
msgid "Streaming done"
msgstr "Streaming abgeschlossen"
-#: src/octoprint/static/js/app/dataupdater.js:226
+#: src/octoprint/static/js/app/dataupdater.js:227
#, python-format
msgid "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"
msgstr "%(local)s nach %(remote)s gestreamt, dauerte %(time).2f Sekunden"
-#: src/octoprint/static/js/app/helpers.js:357
+#: src/octoprint/static/js/app/helpers.js:385
#, python-format
msgid "%(hour)02d:%(minute)02d:%(second)02d"
msgstr "%(hour)02d:%(minute)02d:%(second)02d"
-#: src/octoprint/static/js/app/helpers.js:377
+#: src/octoprint/static/js/app/helpers.js:405
msgid "YYYY-MM-DD HH:mm"
msgstr "DD.MM.YYYY HH:mm"
-#: src/octoprint/static/js/app/helpers.js:395
-#: src/octoprint/static/js/app/helpers.js:400
+#: src/octoprint/static/js/app/helpers.js:423
+#: src/octoprint/static/js/app/helpers.js:428
msgid "off"
msgstr "Aus"
@@ -927,7 +966,7 @@ msgid "Disconnect"
msgstr "Trennen"
#: src/octoprint/static/js/app/viewmodels/control.js:60
-#: src/octoprint/static/js/app/viewmodels/files.js:296
+#: src/octoprint/static/js/app/viewmodels/files.js:330
#: src/octoprint/static/js/app/viewmodels/gcode.js:453
#: src/octoprint/static/js/app/viewmodels/printerstate.js:167
#: src/octoprint/static/js/app/viewmodels/temperature.js:58
@@ -939,32 +978,44 @@ msgstr "Werkzeug"
msgid "Hotend"
msgstr "Hotend"
-#: src/octoprint/static/js/app/viewmodels/files.js:291
-#: src/octoprint/static/js/app/viewmodels/files.js:296
+#: src/octoprint/static/js/app/viewmodels/files.js:47
+msgid "Your available free disk space is critically low."
+msgstr "Dein verfügbarer freier Plattenplatz ist auf einem kritischen Tiefstand."
+
+#: src/octoprint/static/js/app/viewmodels/files.js:49
+msgid "Your available free disk space is starting to run low."
+msgstr "Dein verfügbarer freier Plattenplatz wird langsam knapp."
+
+#: src/octoprint/static/js/app/viewmodels/files.js:51
+msgid "Your current disk usage."
+msgstr "Dein aktuell verfügbarer freier Plattenplatz."
+
+#: src/octoprint/static/js/app/viewmodels/files.js:325
+#: src/octoprint/static/js/app/viewmodels/files.js:330
msgid "Filament"
msgstr "Filament"
-#: src/octoprint/static/js/app/viewmodels/files.js:300
+#: src/octoprint/static/js/app/viewmodels/files.js:334
msgid "Estimated Print Time"
msgstr "Geschätzte Druckdauer"
-#: src/octoprint/static/js/app/viewmodels/files.js:303
+#: src/octoprint/static/js/app/viewmodels/files.js:337
msgid "Last Printed"
msgstr "Zuletzt gedruckt"
-#: src/octoprint/static/js/app/viewmodels/files.js:305
+#: src/octoprint/static/js/app/viewmodels/files.js:339
msgid "Last Print Time"
msgstr "Letzte Druckdauer"
-#: src/octoprint/static/js/app/viewmodels/files.js:386
+#: src/octoprint/static/js/app/viewmodels/files.js:420
msgid "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\"."
msgstr "Konnte die Datei nicht hochladen. Bitte stelle sicher, dass es sich um eine GCODE-Datei mit der Extension \".gcode\" oder \".gco\" oder um eine STL-Datei mit der Extension \".stl\" handelt."
-#: src/octoprint/static/js/app/viewmodels/files.js:402
+#: src/octoprint/static/js/app/viewmodels/files.js:436
msgid "Uploading ..."
msgstr "Uploade ..."
-#: src/octoprint/static/js/app/viewmodels/files.js:405
+#: src/octoprint/static/js/app/viewmodels/files.js:439
msgid "Saving ..."
msgstr "Speichere ..."
@@ -1018,7 +1069,7 @@ msgstr "Schichthöhe"
#: src/octoprint/static/js/app/viewmodels/gcode.js:447
msgid "GCODE commands in layer"
-msgstr "GCODE Kommandos in Schicht"
+msgstr "GCODE Befehle in Schicht"
#: src/octoprint/static/js/app/viewmodels/gcode.js:450
#: src/octoprint/static/js/app/viewmodels/gcode.js:453
@@ -1063,56 +1114,56 @@ msgstr "Du bist jetzt ausgeloggt"
#: src/octoprint/static/js/app/viewmodels/navigation.js:28
#, python-format
msgid "The command \"%(command)s\" executed successfully"
-msgstr "Das Kommando \"%(command)s\" wurde erfolgreich ausgeführt"
+msgstr "Der Befehl \"%(command)s\" wurde erfolgreich ausgeführt"
#: src/octoprint/static/js/app/viewmodels/navigation.js:32
#, python-format
msgid "The command \"%(command)s\" could not be executed."
-msgstr "Das Kommando \"%(command)s\" konnte nicht ausgeführt werden."
+msgstr "Der Befehl \"%(command)s\" konnte nicht ausgeführt werden."
#: src/octoprint/static/js/app/viewmodels/navigation.js:34
msgid "Error"
msgstr "Fehler"
#: src/octoprint/static/js/app/viewmodels/printerprofiles.js:96
-#: src/octoprint/static/js/app/viewmodels/settings.js:53
-#: src/octoprint/static/js/app/viewmodels/settings.js:83
+#: src/octoprint/static/js/app/viewmodels/settings.js:57
+#: src/octoprint/static/js/app/viewmodels/settings.js:87
msgid "default"
msgstr "Standard"
#: src/octoprint/static/js/app/viewmodels/printerprofiles.js:97
-#: src/octoprint/static/js/app/viewmodels/settings.js:54
-#: src/octoprint/static/js/app/viewmodels/settings.js:67
+#: src/octoprint/static/js/app/viewmodels/settings.js:58
+#: src/octoprint/static/js/app/viewmodels/settings.js:71
msgid "red"
msgstr "Rot"
#: src/octoprint/static/js/app/viewmodels/printerprofiles.js:98
-#: src/octoprint/static/js/app/viewmodels/settings.js:55
-#: src/octoprint/static/js/app/viewmodels/settings.js:69
+#: src/octoprint/static/js/app/viewmodels/settings.js:59
+#: src/octoprint/static/js/app/viewmodels/settings.js:73
msgid "orange"
msgstr "Orange"
#: src/octoprint/static/js/app/viewmodels/printerprofiles.js:99
-#: src/octoprint/static/js/app/viewmodels/settings.js:56
-#: src/octoprint/static/js/app/viewmodels/settings.js:71
+#: src/octoprint/static/js/app/viewmodels/settings.js:60
+#: src/octoprint/static/js/app/viewmodels/settings.js:75
msgid "yellow"
msgstr "Gelb"
#: src/octoprint/static/js/app/viewmodels/printerprofiles.js:100
-#: src/octoprint/static/js/app/viewmodels/settings.js:57
-#: src/octoprint/static/js/app/viewmodels/settings.js:73
+#: src/octoprint/static/js/app/viewmodels/settings.js:61
+#: src/octoprint/static/js/app/viewmodels/settings.js:77
msgid "green"
msgstr "Grün"
#: src/octoprint/static/js/app/viewmodels/printerprofiles.js:101
-#: src/octoprint/static/js/app/viewmodels/settings.js:58
-#: src/octoprint/static/js/app/viewmodels/settings.js:75
+#: src/octoprint/static/js/app/viewmodels/settings.js:62
+#: src/octoprint/static/js/app/viewmodels/settings.js:79
msgid "blue"
msgstr "Blau"
#: src/octoprint/static/js/app/viewmodels/printerprofiles.js:102
-#: src/octoprint/static/js/app/viewmodels/settings.js:60
-#: src/octoprint/static/js/app/viewmodels/settings.js:79
+#: src/octoprint/static/js/app/viewmodels/settings.js:64
+#: src/octoprint/static/js/app/viewmodels/settings.js:83
msgid "black"
msgstr "Schwarz"
@@ -1193,18 +1244,18 @@ msgid "Pause"
msgstr "Pause"
#: src/octoprint/static/js/app/viewmodels/printerstate.js:96
-#: src/octoprint/templates/tabs/timelapse.jinja2:7
+#: src/octoprint/templates/tabs/timelapse.jinja2:10
msgid "On Z Change"
msgstr "Bei Ebenenwechsel"
#: src/octoprint/static/js/app/viewmodels/printerstate.js:98
-#: src/octoprint/templates/tabs/timelapse.jinja2:8
+#: src/octoprint/templates/tabs/timelapse.jinja2:11
msgid "Timed"
msgstr "Nach Zeit"
#: src/octoprint/static/js/app/viewmodels/printerstate.js:98
-#: src/octoprint/templates/tabs/timelapse.jinja2:20
-#: src/octoprint/templates/tabs/timelapse.jinja2:27
+#: src/octoprint/templates/tabs/timelapse.jinja2:24
+#: src/octoprint/templates/tabs/timelapse.jinja2:31
msgid "sec"
msgstr "Sek"
@@ -1212,17 +1263,17 @@ msgstr "Sek"
msgid "This will restart the print job from the beginning."
msgstr "Der Druckjob wird zurückgesetzt und von vorne begonnen."
-#: src/octoprint/static/js/app/viewmodels/settings.js:59
-#: src/octoprint/static/js/app/viewmodels/settings.js:77
+#: src/octoprint/static/js/app/viewmodels/settings.js:63
+#: src/octoprint/static/js/app/viewmodels/settings.js:81
msgid "violet"
msgstr "Violett"
-#: src/octoprint/static/js/app/viewmodels/settings.js:61
-#: src/octoprint/static/js/app/viewmodels/settings.js:81
+#: src/octoprint/static/js/app/viewmodels/settings.js:65
+#: src/octoprint/static/js/app/viewmodels/settings.js:85
msgid "white"
msgstr "weiß"
-#: src/octoprint/static/js/app/viewmodels/settings.js:89
+#: src/octoprint/static/js/app/viewmodels/settings.js:93
msgid "Autodetect from browser"
msgstr "Automatisch vom Browser erkennen"
@@ -1470,7 +1521,7 @@ msgstr "Admin"
#: src/octoprint/templates/dialogs/settings/accesscontrol.jinja2:7
#: src/octoprint/templates/dialogs/settings/logs.jinja2:15
#: src/octoprint/templates/dialogs/settings/printerprofiles.jinja2:7
-#: src/octoprint/templates/tabs/timelapse.jinja2:52
+#: src/octoprint/templates/tabs/timelapse.jinja2:56
msgid "Action"
msgstr "Aktion"
@@ -1650,50 +1701,70 @@ msgstr "Immer davon ausgehen, dass eine SD-Karte vorhanden ist"
#: src/octoprint/templates/dialogs/settings/features.jinja2:47
#: src/octoprint/templates/dialogs/settings/features.jinja2:54
#: src/octoprint/templates/dialogs/settings/features.jinja2:61
+#: src/octoprint/templates/dialogs/settings/features.jinja2:68
msgid "Repetier"
msgstr "Repetier"
#: src/octoprint/templates/dialogs/settings/features.jinja2:47
msgid "Send a checksum with every command"
-msgstr "Eine Prüfsumme mit jedem Kommando senden"
+msgstr "Eine Prüfsumme mit jedem Befehl senden"
#: src/octoprint/templates/dialogs/settings/features.jinja2:54
+msgid "Ignore consecutive resend requests for the same line"
+msgstr "Aufeinanderfolgende Resend Requests für die selbe Zeilennummer ignorieren"
+
+#: src/octoprint/templates/dialogs/settings/features.jinja2:61
#, python-format
msgid "Support TargetExtr%%n/TargetBed target temperature format"
msgstr "TargetExtr%%n/TargetBed Zieltemperaturformat unterstützen"
-#: src/octoprint/templates/dialogs/settings/features.jinja2:61
+#: src/octoprint/templates/dialogs/settings/features.jinja2:68
msgid "Disable detection of external heatups"
msgstr "Detektierung externer Aufheizvorgänge deaktivieren"
-#: src/octoprint/templates/dialogs/settings/features.jinja2:68
-msgid "Swallow the first \"ok\" after a resend response"
-msgstr "Erstes \"ok\" nach Resend ignorieren"
-
-#: src/octoprint/templates/dialogs/settings/folders.jinja2:3
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:5
msgid "Upload Folder"
msgstr "Uploadverzeichnis"
-#: src/octoprint/templates/dialogs/settings/folders.jinja2:9
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:11
msgid "Timelapse Folder"
msgstr "Zeitrafferverzeichnis"
-#: src/octoprint/templates/dialogs/settings/folders.jinja2:15
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:17
msgid "Timelapse Temp Folder"
msgstr "Temporäres Zeitrafferverzeichnis"
-#: src/octoprint/templates/dialogs/settings/folders.jinja2:21
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:23
msgid "Logs Folder"
msgstr "Logverzeichnis"
-#: src/octoprint/templates/dialogs/settings/folders.jinja2:27
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:29
msgid "Watched Folder"
msgstr "Beobachtetes Verzeichnis"
-#: src/octoprint/templates/dialogs/settings/folders.jinja2:35
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:37
msgid "Actively poll the watched folder. Check this if files in your watched folder aren't automatically added otherwise."
msgstr "Aktives Pollen des beobachteten Verzeichnisses. Einschalten wenn Dateien in Deinem beobachteten Verzeichnis hinzugefügt werden sonst nicht automatisch hinzugefügt werden."
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:42
+msgid "Disk space thresholds"
+msgstr "Plattenplatzschwellwerte"
+
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:44
+msgid "If the free disk space falls below these thresholds, OctoPrint will warn the user."
+msgstr "Falls der freie Plattenplatz unter diese Schwellwerte fallen sollte wird OctoPrint den Nutzer warnen."
+
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:47
+#: src/octoprint/templates/dialogs/settings/serialconnection.jinja2:69
+#: src/octoprint/templates/tabs/gcodeviewer.jinja2:62
+#: src/octoprint/templates/tabs/timelapse.jinja2:13
+msgid "Warning"
+msgstr "Warnung"
+
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:53
+msgid "Critical"
+msgstr "Kritisch"
+
#: src/octoprint/templates/dialogs/settings/gcodescripts.jinja2:3
msgid "Before print job starts"
msgstr "Vor dem Start eines Druckjobs"
@@ -1726,8 +1797,8 @@ msgstr "Änderungsdatum"
#: src/octoprint/templates/dialogs/settings/logs.jinja2:13
#: src/octoprint/templates/sidebar/files.jinja2:10
#: src/octoprint/templates/sidebar/files.jinja2:24
-#: src/octoprint/templates/tabs/timelapse.jinja2:45
-#: src/octoprint/templates/tabs/timelapse.jinja2:51
+#: src/octoprint/templates/tabs/timelapse.jinja2:49
+#: src/octoprint/templates/tabs/timelapse.jinja2:55
msgid "Size"
msgstr "Größe"
@@ -1891,11 +1962,6 @@ msgstr "Autodetectiontimeout"
msgid "Log communication to serial.log (might negatively impact performance)"
msgstr "Logge die Kommunikation in das serial.log (kann die Performance negativ beeinflussen)"
-#: src/octoprint/templates/dialogs/settings/serialconnection.jinja2:69
-#: src/octoprint/templates/tabs/gcodeviewer.jinja2:62
-msgid "Warning"
-msgstr "Warnung"
-
#: src/octoprint/templates/dialogs/settings/serialconnection.jinja2:74
msgid "Long running commands"
msgstr "Lang laufende Befehle"
@@ -1913,6 +1979,34 @@ msgstr "Zusätzliche serielle Ports"
msgid "Use this to define additional glob patterns matching serial ports to list for connecting against, e.g. /dev/ttyAMA*. One entry per line."
msgstr "Nutze diese Einstellung um zusätzliche glob patterns zu konfigurieren, die auf serielle Ports deines Druckers matchen, z.B. /dev/ttyAMA*. Ein Eintrag pro Zeile."
+#: src/octoprint/templates/dialogs/settings/server.jinja2:2
+msgid "Commands"
+msgstr "Befehle"
+
+#: src/octoprint/templates/dialogs/settings/server.jinja2:4
+msgid "Command to restart the OctoPrint server"
+msgstr "Befehl zum Neustart des OctoPrint-Servers"
+
+#: src/octoprint/templates/dialogs/settings/server.jinja2:5
+msgid "Restart OctoPrint"
+msgstr "OctoPrint neustarten"
+
+#: src/octoprint/templates/dialogs/settings/server.jinja2:10
+msgid "Command to restart the system OctoPrint is running on"
+msgstr "Befehl zum Neustart des Systems, auf dem OctoPrint läuft"
+
+#: src/octoprint/templates/dialogs/settings/server.jinja2:11
+msgid "Restart system"
+msgstr "System neustarten"
+
+#: src/octoprint/templates/dialogs/settings/server.jinja2:16
+msgid "Command to shut down the system OctoPrint is running on"
+msgstr "Befehl zum Herunterfahren des Systems, auf dem OctoPrint läuft"
+
+#: src/octoprint/templates/dialogs/settings/server.jinja2:17
+msgid "Shutdown system"
+msgstr "System herunterfahren"
+
#: src/octoprint/templates/dialogs/settings/temperatures.jinja2:2
msgid "Temperature Graph"
msgstr "Temperaturgraph"
@@ -2059,6 +2153,10 @@ msgstr "Automatisch bei Serverstart verbinden"
msgid "Uploaded"
msgstr "Hochgeladen"
+#: src/octoprint/templates/sidebar/files.jinja2:13
+msgid "Additional data"
+msgstr "Weitere Daten"
+
#: src/octoprint/templates/sidebar/files.jinja2:14
#: src/octoprint/templates/sidebar/files.jinja2:26
msgid "Download"
@@ -2081,6 +2179,10 @@ msgstr "Laden und Drucken"
msgid "Free"
msgstr "Frei"
+#: src/octoprint/templates/sidebar/files.jinja2:37
+msgid "Total"
+msgstr "Gesamt"
+
#: src/octoprint/templates/sidebar/files.jinja2:64
msgid "Hint: You can also drag and drop files on this page to upload them."
msgstr "Hinweis: Du kannst auch Dateien auf diese Seite ziehen um sie hochzuladen."
@@ -2318,7 +2420,7 @@ msgid "Set"
msgstr "Setzen"
#: src/octoprint/templates/tabs/temperature.jinja2:41
-#: src/octoprint/templates/tabs/timelapse.jinja2:6
+#: src/octoprint/templates/tabs/timelapse.jinja2:9
msgid "Off"
msgstr "Aus"
@@ -2340,7 +2442,7 @@ msgstr "Senden"
#: src/octoprint/templates/tabs/terminal.jinja2:20
msgid "Hint: Use the arrow up/down keys to recall commands sent previously"
-msgstr "Hinweis: Nutze die Pfeil hoch/runter Tasten um vorher versandte Kommandos wiederaufzurufen "
+msgstr "Hinweis: Nutze die Pfeil hoch/runter Tasten um vorher versandte Befehle wieder aufzurufen "
#: src/octoprint/templates/tabs/terminal.jinja2:27
msgid "Fake Acknowledgement"
@@ -2350,43 +2452,51 @@ msgstr "Bestätigung faken"
msgid "If acknowledgements (\"ok\"s) sent by the firmware get lost due to issues with the serial communication to your printer, OctoPrint's communication with it can become stuck. If that happens, this can help. Please be advised that such occurences hint at general communication issues with your printer which will probably negatively influence your printing results and which you should therefore try to resolve!"
msgstr "Falls Bestätigungen (\"ok\"s) Deiner Firmware aufgrund von Kommunikationsproblemen mit Deinem Drucker verloren gehen, kann die Kommunikation zwischen OctoPrint und Deinem Drucker zum Stillstand kommen. Falls das passiert, kann das hier helfen. Bitte bedenke, dass solche Vorfälle ein Hinweis auf ein generelles Kommunikationsproblem mit Deinem Drucker hindeuten, das wahrscheinlich Deine Druckergebnisse negativ beeinflusst und dass du daher versuchen solltest, zu beseitigen!"
-#: src/octoprint/templates/tabs/timelapse.jinja2:2
+#: src/octoprint/templates/tabs/timelapse.jinja2:3
+msgid "Take note that timelapse configuration is disabled while your printer is printing."
+msgstr "Bitte beachte dass die Zeitrafferkonfiguration während des Druckens deaktiviert ist."
+
+#: src/octoprint/templates/tabs/timelapse.jinja2:5
msgid "Timelapse Configuration"
msgstr "Zeitrafferkonfiguration"
-#: src/octoprint/templates/tabs/timelapse.jinja2:4
+#: src/octoprint/templates/tabs/timelapse.jinja2:7
msgid "Timelapse Mode"
msgstr "Zeitraffermodus"
-#: src/octoprint/templates/tabs/timelapse.jinja2:11
+#: src/octoprint/templates/tabs/timelapse.jinja2:13
+msgid "Do not use with spiralized (\"Joris\") vases or similar continuous Z models."
+msgstr "Nicht mit spiralisierten Vasen (\"Joris\") oder ähnlichen Modellen mit ständigen Z-Achsen-Änderungen verwenden."
+
+#: src/octoprint/templates/tabs/timelapse.jinja2:15
msgid "Timelapse frame rate (in frames per second)"
msgstr "Zeitrafferbildrate (in Bildern pro Sekunde)"
-#: src/octoprint/templates/tabs/timelapse.jinja2:14
+#: src/octoprint/templates/tabs/timelapse.jinja2:18
msgid "fps"
msgstr "FPS"
-#: src/octoprint/templates/tabs/timelapse.jinja2:17
+#: src/octoprint/templates/tabs/timelapse.jinja2:21
msgid "Timelapse post roll (in rendered seconds)"
msgstr "Zeitraffernachlauf (in gerenderten Sekunden)"
-#: src/octoprint/templates/tabs/timelapse.jinja2:24
+#: src/octoprint/templates/tabs/timelapse.jinja2:28
msgid "Interval"
msgstr "Intervall"
-#: src/octoprint/templates/tabs/timelapse.jinja2:33
+#: src/octoprint/templates/tabs/timelapse.jinja2:37
msgid "Save as default"
msgstr "Als Standard speichern"
-#: src/octoprint/templates/tabs/timelapse.jinja2:38
+#: src/octoprint/templates/tabs/timelapse.jinja2:42
msgid "Save config"
msgstr "Konfiguration speichern"
-#: src/octoprint/templates/tabs/timelapse.jinja2:42
+#: src/octoprint/templates/tabs/timelapse.jinja2:46
msgid "Finished Timelapses"
msgstr "Abgeschlossene Zeitraffer"
-#: src/octoprint/templates/tabs/timelapse.jinja2:45
+#: src/octoprint/templates/tabs/timelapse.jinja2:49
msgid "Creation date"
msgstr "Erstellungsdatum"
@@ -2434,3 +2544,15 @@ msgstr "Erstellungsdatum"
#~ msgid ""
#~ msgstr ""
+
+#~ msgid "Updating, please wait."
+#~ msgstr "Aktualisiere gerade, bitte warten."
+
+#~ msgid "Restart Command"
+#~ msgstr "Neustartbefehl"
+
+#~ msgid "Reboot Command"
+#~ msgstr "Rebootbefehl"
+
+#~ msgid "Swallow the first \"ok\" after a resend response"
+#~ msgstr "Erstes \"ok\" nach Resend ignorieren"
diff --git a/src/octoprint/users.py b/src/octoprint/users.py
index 1aaf20711..45c90e327 100644
--- a/src/octoprint/users.py
+++ b/src/octoprint/users.py
@@ -17,29 +17,37 @@ import logging
from octoprint.settings import settings
+from octoprint.util import atomic_write
+
class UserManager(object):
valid_roles = ["user", "admin"]
def __init__(self):
self._logger = logging.getLogger(__name__)
self._session_users_by_session = dict()
- self._session_users_by_username = dict()
+ self._session_users_by_userid = dict()
def login_user(self, user):
self._cleanup_sessions()
- if user is None \
- or (isinstance(user, LocalProxy) and not isinstance(user._get_current_object(), User)) \
- or (not isinstance(user, LocalProxy) and not isinstance(user, User)):
+ if user is None:
+ return
+
+ if isinstance(user, LocalProxy):
+ user = user._get_current_object()
+
+ if not isinstance(user, User):
return None
if not isinstance(user, SessionUser):
user = SessionUser(user)
+
self._session_users_by_session[user.get_session()] = user
- if not user.get_name() in self._session_users_by_username:
- self._session_users_by_username[user.get_name()] = []
- self._session_users_by_username[user.get_name()].append(user)
+ userid = user.get_id()
+ if not userid in self._session_users_by_userid:
+ self._session_users_by_userid[userid] = []
+ self._session_users_by_userid[userid].append(user)
self._logger.debug("Logged in user: %r" % user)
@@ -49,14 +57,18 @@ class UserManager(object):
if user is None:
return
+ if isinstance(user, LocalProxy):
+ user = user._get_current_object()
+
if not isinstance(user, SessionUser):
return
- if user.get_name() in self._session_users_by_username:
- users_by_username = self._session_users_by_username[user.get_name()]
- for u in users_by_username:
+ userid = user.get_id()
+ if userid in self._session_users_by_userid:
+ users_by_userid = self._session_users_by_userid[userid]
+ for u in users_by_userid:
if u.get_session() == user.get_session():
- users_by_username.remove(u)
+ users_by_userid.remove(u)
break
if user.get_session() in self._session_users_by_session:
@@ -106,7 +118,7 @@ class UserManager(object):
# old hash doesn't match either, wrong password
return False
- def addUser(self, username, password, active, roles):
+ def addUser(self, username, password, active, roles, overwrite=False):
pass
def changeUserActivation(self, username, active):
@@ -137,21 +149,19 @@ class UserManager(object):
pass
def removeUser(self, username):
- if username in self._session_users_by_username:
- users = self._session_users_by_username[username]
+ if username in self._session_users_by_userid:
+ users = self._session_users_by_userid[username]
sessions = [user.get_session() for user in users if isinstance(user, SessionUser)]
for session in sessions:
if session in self._session_users_by_session:
del self._session_users_by_session[session]
- del self._session_users_by_username[username]
+ del self._session_users_by_userid[username]
- def findUser(self, username=None, session=None):
- if session is not None:
- for session in self._session_users_by_session:
- user = self._session_users_by_session[session]
- if username is None or username == user.get_name():
- return user
- break
+ def findUser(self, userid=None, session=None):
+ if session is not None and session in self._session_users_by_session:
+ user = self._session_users_by_session[session]
+ if userid is None or userid == user.get_id():
+ return user
return None
@@ -209,16 +219,16 @@ class FilebasedUserManager(UserManager):
"settings": user._settings
}
- with open(self._userfile, "wb") as f:
+ with atomic_write(self._userfile, "wb") as f:
yaml.safe_dump(data, f, default_flow_style=False, indent=" ", allow_unicode=True)
self._dirty = False
self._load()
- def addUser(self, username, password, active=False, roles=None, apikey=None):
+ def addUser(self, username, password, active=False, roles=None, apikey=None, overwrite=False):
if not roles:
roles = ["user"]
- if username in self._users.keys():
+ if username in self._users.keys() and not overwrite:
raise UserAlreadyExists(username)
self._users[username] = User(username, UserManager.createPasswordHash(password), active, roles, apikey=apikey)
@@ -345,16 +355,16 @@ class FilebasedUserManager(UserManager):
self._dirty = True
self._save()
- def findUser(self, username=None, apikey=None, session=None):
- user = UserManager.findUser(self, username=username, session=session)
+ def findUser(self, userid=None, apikey=None, session=None):
+ user = UserManager.findUser(self, userid=userid, session=session)
if user is not None:
return user
- if username is not None:
- if username not in self._users.keys():
+ if userid is not None:
+ if userid not in self._users.keys():
return None
- return self._users[username]
+ return self._users[userid]
elif apikey is not None:
for user in self._users.values():
@@ -413,7 +423,7 @@ class User(UserMixin):
return self._passwordHash == passwordHash
def get_id(self):
- return self._username
+ return self.get_name()
def get_name(self):
return self._username
@@ -443,7 +453,7 @@ class User(UserMixin):
path = [key]
else:
path = key
- self._set_setting(path, value)
+ return self._set_setting(path, value)
def _get_setting(self, path):
s = self._settings
@@ -474,7 +484,8 @@ class User(UserMixin):
class SessionUser(User):
def __init__(self, user):
- User.__init__(self, user._username, user._passwordHash, user._active, user._roles, user._apikey)
+ self._user = user
+ User.__init__(self, user._username, user._passwordHash, user._active, user._roles, user._apikey, user._settings)
import string
import random
@@ -483,6 +494,18 @@ class SessionUser(User):
self._session = "".join(random.choice(chars) for _ in xrange(10))
self._created = time.time()
+ def __getattribute__(self, item):
+ if item in ("get_session", "_user", "_session", "_created"):
+ return object.__getattribute__(self, item)
+ else:
+ return getattr(object.__getattribute__(self, "_user"), item)
+
+ def __setattr__(self, item, value):
+ if item in ("_user", "_session", "_created"):
+ return object.__setattr__(self, item, value)
+ else:
+ return setattr(self._user, item, value)
+
def get_session(self):
return self._session
diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py
index 3b3d03a45..d5066e48a 100644
--- a/src/octoprint/util/__init__.py
+++ b/src/octoprint/util/__init__.py
@@ -17,7 +17,7 @@ import shutil
import threading
from functools import wraps
import warnings
-
+import contextlib
logger = logging.getLogger(__name__)
@@ -197,29 +197,12 @@ def get_exception_string():
return "%s: '%s' @ %s:%s:%d" % (str(sys.exc_info()[0].__name__), str(sys.exc_info()[1]), os.path.basename(locationInfo[0]), locationInfo[2], locationInfo[1])
+@deprecated("get_free_bytes has been deprecated and will be removed in the future",
+ includedoc="Replaced by `psutil.disk_usage `_.",
+ since="1.2.5")
def get_free_bytes(path):
- """
- Retrieves the number of free bytes on the partition ``path`` is located at and returns it. Works on both Windows and
- Unix/Linux.
-
- Taken from http://stackoverflow.com/a/2372171/2028598
-
- Arguments:
- path (string): The path for which to check the remaining partition space.
-
- Returns:
- int: The amount of bytes still left on the partition.
- """
-
- path = os.path.abspath(path)
- if sys.platform == "win32":
- import ctypes
- freeBytes = ctypes.c_ulonglong(0)
- ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(path), None, None, ctypes.pointer(freeBytes))
- return freeBytes.value
- else:
- st = os.statvfs(path)
- return st.f_bavail * st.f_frsize
+ import psutil
+ return psutil.disk_usage(path).free
def get_dos_filename(origin, existing_filenames=None, extension=None, **kwargs):
@@ -389,12 +372,25 @@ def to_unicode(s_or_u, encoding="utf-8", errors="strict"):
return s_or_u
+def is_running_from_source():
+ root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
+ return os.path.isdir(os.path.join(root, "src")) and os.path.isfile(os.path.join(root, "setup.py"))
+
+
def dict_merge(a, b):
"""
Recursively deep-merges two dictionaries.
Taken from https://www.xormedia.com/recursively-merge-dictionaries-in-python/
+ Example::
+
+ >>> a = dict(foo="foo", bar="bar", fnord=dict(a=1))
+ >>> b = dict(foo="other foo", fnord=dict(b=2, l=["some", "list"]))
+ >>> expected = dict(foo="other foo", bar="bar", fnord=dict(a=1, b=2, l=["some", "list"]))
+ >>> dict_merge(a, b) == expected
+ True
+
Arguments:
a (dict): The dictionary to merge ``b`` into
b (dict): The dictionary to merge into ``a``
@@ -416,14 +412,24 @@ def dict_merge(a, b):
return result
-def dict_clean(a, b):
+def dict_sanitize(a, b):
"""
- Recursively deep-cleans ``b`` from ``a``, removing all keys and corresponding values from ``a`` that appear in
- ``b``.
+ Recursively deep-sanitizes ``a`` based on ``b``, removing all keys (and
+ associated values) from ``a`` that do not appear in ``b``.
+
+ Example::
+
+ >>> a = dict(foo="foo", bar="bar", fnord=dict(a=1, b=2, l=["some", "list"]))
+ >>> b = dict(foo=None, fnord=dict(a=None, b=None))
+ >>> expected = dict(foo="foo", fnord=dict(a=1, b=2))
+ >>> dict_sanitize(a, b) == expected
+ True
+ >>> dict_clean(a, b) == expected
+ True
Arguments:
- a (dict): The dictionary to clean from ``b``.
- b (dict): The dictionary to clean ``b`` from.
+ a (dict): The dictionary to clean against ``b``.
+ b (dict): The dictionary containing the key structure to clean from ``a``.
Results:
dict: A new dict based on ``a`` with all keys (and corresponding values) found in ``b`` removed.
@@ -438,21 +444,87 @@ def dict_clean(a, b):
if not k in b:
del result[k]
elif isinstance(v, dict):
- result[k] = dict_clean(v, b[k])
+ result[k] = dict_sanitize(v, b[k])
else:
result[k] = deepcopy(v)
return result
+dict_clean = deprecated("dict_clean has been renamed to dict_sanitize",
+ includedoc="Replaced by :func:`dict_sanitize`")(dict_sanitize)
-def dict_contains_keys(a, b):
+def dict_minimal_mergediff(source, target):
"""
- Recursively deep-checks if ``a`` contains all keys found in ``b``.
+ Recursively calculates the minimal dict that would be needed to be deep merged with
+ a in order to produce the same result as deep merging a and b.
Example::
- >>> dict_contains_keys(dict(foo="bar", fnord=dict(a=1, b=2, c=3)), dict(foo="some_other_bar", fnord=dict(b=100)))
+ >>> a = dict(foo=dict(a=1, b=2), bar=dict(c=3, d=4))
+ >>> b = dict(bar=dict(c=3, d=5), fnord=None)
+ >>> c = dict_minimal_mergediff(a, b)
+ >>> c == dict(bar=dict(d=5), fnord=None)
True
- >>> dict_contains_keys(dict(foo="bar", fnord=dict(a=1, b=2, c=3)), dict(foo="some_other_bar", fnord=dict(b=100, d=20)))
+ >>> dict_merge(a, c) == dict_merge(a, b)
+ True
+
+ Arguments:
+ source (dict): Source dictionary
+ target (dict): Dictionary to compare to source dictionary and derive diff for
+
+ Returns:
+ dict: The minimal dictionary to deep merge on ``source`` to get the same result
+ as deep merging ``target`` on ``source``.
+ """
+
+ if not isinstance(source, dict) or not isinstance(target, dict):
+ raise ValueError("source and target must be dictionaries")
+
+ if source == target:
+ # shortcut: if both are equal, we return an empty dict as result
+ return dict()
+
+ from copy import deepcopy
+
+ all_keys = set(source.keys() + target.keys())
+ result = dict()
+ for k in all_keys:
+ if k not in target:
+ # key not contained in b => not contained in result
+ continue
+
+ if k in source:
+ # key is present in both dicts, we have to take a look at the value
+ value_source = source[k]
+ value_target = target[k]
+
+ if value_source != value_target:
+ # we only need to look further if the values are not equal
+
+ if isinstance(value_source, dict) and isinstance(value_target, dict):
+ # both are dicts => deeper down it goes into the rabbit hole
+ result[k] = dict_minimal_mergediff(value_source, value_target)
+ else:
+ # new b wins over old a
+ result[k] = deepcopy(value_target)
+
+ else:
+ # key is new, add it
+ result[k] = deepcopy(target[k])
+ return result
+
+
+def dict_contains_keys(keys, dictionary):
+ """
+ Recursively deep-checks if ``dictionary`` contains all keys found in ``keys``.
+
+ Example::
+
+ >>> positive = dict(foo="some_other_bar", fnord=dict(b=100))
+ >>> negative = dict(foo="some_other_bar", fnord=dict(b=100, d=20))
+ >>> dictionary = dict(foo="bar", fnord=dict(a=1, b=2, c=3))
+ >>> dict_contains_keys(positive, dictionary)
+ True
+ >>> dict_contains_keys(negative, dictionary)
False
Arguments:
@@ -463,14 +535,14 @@ def dict_contains_keys(a, b):
boolean: True if all keys found in ``b`` are also present in ``a``, False otherwise.
"""
- if not isinstance(a, dict) or not isinstance(b, dict):
+ if not isinstance(keys, dict) or not isinstance(dictionary, dict):
return False
- for k, v in a.iteritems():
- if not k in b:
+ for k, v in keys.iteritems():
+ if not k in dictionary:
return False
elif isinstance(v, dict):
- if not dict_contains_keys(v, b[k]):
+ if not dict_contains_keys(v, dictionary[k]):
return False
return True
@@ -513,6 +585,38 @@ def address_for_client(host, port):
except:
continue
+
+@contextlib.contextmanager
+def atomic_write(filename, mode="w+b", prefix="tmp", suffix=""):
+ temp_config = tempfile.NamedTemporaryFile(mode=mode, prefix=prefix, suffix=suffix, delete=False)
+ yield temp_config
+ temp_config.close()
+ shutil.move(temp_config.name, filename)
+
+
+def bom_aware_open(filename, encoding="ascii", mode="r", **kwargs):
+ import codecs
+
+ codec = codecs.lookup(encoding)
+ encoding = codec.name
+
+ if kwargs is None:
+ kwargs = dict()
+
+ potential_bom_attribute = "BOM_" + codec.name.replace("utf-", "utf").upper()
+ if "r" in mode and hasattr(codecs, potential_bom_attribute):
+ # these encodings might have a BOM, so let's see if there is one
+ bom = getattr(codecs, potential_bom_attribute)
+
+ with open(filename, "rb") as f:
+ header = f.read(4)
+
+ if header.startswith(bom):
+ encoding += "-sig"
+
+ return codecs.open(filename, encoding=encoding, **kwargs)
+
+
class RepeatedTimer(threading.Thread):
"""
This class represents an action that should be run repeatedly in an interval. It is similar to python's
@@ -570,9 +674,18 @@ class RepeatedTimer(threading.Thread):
run_first (boolean): If set to True, the function will be run for the first time *before* the first wait period.
If set to False (the default), the function will be run for the first time *after* the first wait period.
condition (callable): Condition that needs to be True for loop to continue. Defaults to ``lambda: True``.
+ on_condition_false (callable): Callback to call when the timer finishes due to condition becoming false. Will
+ be called before the ``on_finish`` callback.
+ on_cancelled (callable): Callback to call when the timer finishes due to being cancelled. Will be called
+ before the ``on_finish`` callback.
+ on_finish (callable): Callback to call when the timer finishes, either due to being cancelled or since
+ the condition became false.
+ daemon (bool): daemon flag to set on underlying thread.
"""
- def __init__(self, interval, function, args=None, kwargs=None, run_first=False, condition=None):
+ def __init__(self, interval, function, args=None, kwargs=None,
+ run_first=False, condition=None, on_condition_false=None,
+ on_cancelled=None, on_finish=None, daemon=True):
threading.Thread.__init__(self)
if args is None:
@@ -594,8 +707,14 @@ class RepeatedTimer(threading.Thread):
self.run_first = run_first
self.condition = condition
+ self.on_condition_false = on_condition_false
+ self.on_cancelled = on_cancelled
+ self.on_finish = on_finish
+
+ self.daemon = daemon
+
def cancel(self):
- self.finished.set()
+ self._finish(self.on_cancelled)
def run(self):
while self.condition():
@@ -610,15 +729,26 @@ class RepeatedTimer(threading.Thread):
# wait, but break if we are cancelled
self.finished.wait(self.interval())
if self.finished.is_set():
- break
+ return
if not self.run_first:
# if we are to run the function AFTER waiting for the first time
self.function(*self.args, **self.kwargs)
- # make sure we set our finished event so we can detect that the loop was finished
+ # we'll only get here if the condition was false
+ self._finish(self.on_condition_false)
+
+ def _finish(self, *callbacks):
self.finished.set()
+ for callback in callbacks:
+ if not callable(callback):
+ continue
+ callback()
+
+ if callable(self.on_finish):
+ self.on_finish()
+
class CountedEvent(object):
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index 3e239076a..ebb770789 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -24,13 +24,86 @@ from octoprint.settings import settings, default_settings
from octoprint.events import eventManager, Events
from octoprint.filemanager import valid_file_type
from octoprint.filemanager.destinations import FileDestinations
-from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer
+from octoprint.util import get_exception_string, sanitize_ascii, filter_non_ascii, CountedEvent, RepeatedTimer, to_unicode, bom_aware_open
try:
import _winreg
except:
pass
+_logger = logging.getLogger(__name__)
+
+# a bunch of regexes we'll need for the communication parsing...
+
+regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+"
+regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+"
+regex_int_pattern = "\d+"
+
+regex_command = re.compile("^\s*((?P[GM]\d+)|(?PT)\d+)")
+"""Regex for a GCODE command."""
+
+regex_float = re.compile(regex_float_pattern)
+"""Regex for a float value."""
+
+regexes_parameters = dict(
+ floatP=re.compile("(^|[^A-Za-z])[Pp](?P%s)" % regex_float_pattern),
+ floatS=re.compile("(^|[^A-Za-z])[Ss](?P%s)" % regex_float_pattern),
+ floatZ=re.compile("(^|[^A-Za-z])[Zz](?P%s)" % regex_float_pattern),
+ intN=re.compile("(^|[^A-Za-z])[Nn](?P%s)" % regex_int_pattern),
+ intT=re.compile("(^|[^A-Za-z])[Tt](?P%s)" % regex_int_pattern)
+)
+"""Regexes for parsing various GCODE command parameters."""
+
+regex_minMaxError = re.compile("Error:[0-9]\n")
+"""Regex matching first line of min/max errors from the firmware."""
+
+regex_sdPrintingByte = re.compile("(?P[0-9]*)/(?P[0-9]*)")
+"""Regex matching SD printing status reports.
+
+Groups will be as follows:
+
+ * ``current``: current byte position in file being printed
+ * ``total``: total size of file being printed
+"""
+
+regex_sdFileOpened = re.compile("File opened:\s*(?P.*?)\s+Size:\s*(?P%s)" % regex_int_pattern)
+"""Regex matching "File opened" messages from the firmware.
+
+Groups will be as follows:
+
+ * ``name``: name of the file reported as having been opened (str)
+ * ``size``: size of the file in bytes (int)
+"""
+
+regex_temp = re.compile("(?PB|T(?P\d*)):\s*(?P%s)(\s*\/?\s*(?P%s))?" % (regex_positive_float_pattern, regex_positive_float_pattern))
+"""Regex matching temperature entries in line.
+
+Groups will be as follows:
+
+ * ``tool``: whole tool designator, incl. optional ``toolnum`` (str)
+ * ``toolnum``: tool number, if provided (int)
+ * ``actual``: actual temperature (float)
+ * ``target``: target temperature, if provided (float)
+"""
+
+regex_repetierTempExtr = re.compile("TargetExtr(?P\d+):(?P%s)" % regex_positive_float_pattern)
+"""Regex for matching target temp reporting from Repetier.
+
+Groups will be as follows:
+
+ * ``toolnum``: number of the extruder to which the target temperature
+ report belongs (int)
+ * ``target``: new target temperature (float)
+"""
+
+regex_repetierTempBed = re.compile("TargetBed:(?P%s)" % regex_positive_float_pattern)
+"""Regex for matching target temp reporting from Repetier for beds.
+
+Groups will be as follows:
+
+ * ``target``: new target temperature (float)
+"""
+
def serialList():
baselist=[]
if os.name=="nt":
@@ -64,6 +137,15 @@ def serialList():
def baudrateList():
ret = [250000, 230400, 115200, 57600, 38400, 19200, 9600]
+ additionalBaudrates = settings().get(["serial", "additionalBaudrates"])
+ for additional in additionalBaudrates:
+ try:
+ ret.append(int(additional))
+ except:
+ _logger.warn("{} is not a valid additional baudrate, ignoring it".format(additional))
+
+ ret.sort(reverse=True)
+
prev = settings().getInt(["serial", "baudrate"])
if prev in ret:
ret.remove(prev)
@@ -140,6 +222,7 @@ class MachineCom(object):
self._baudrateDetectRetry = 0
self._temp = {}
self._bedTemp = None
+ self._temperatureTargetSetThreshold = 25
self._tempOffsets = dict()
self._commandQueue = queue.Queue()
self._currentZ = None
@@ -151,19 +234,27 @@ class MachineCom(object):
self._long_running_command = False
self._heating = False
+ self._connection_closing = False
self._timeout = None
+ self._hello_command = settings().get(["serial", "helloCommand"])
+
self._alwaysSendChecksum = settings().getBoolean(["feature", "alwaysSendChecksum"])
+ self._neverSendChecksum = settings().getBoolean(["feature", "neverSendChecksum"])
self._sendChecksumWithUnknownCommands = settings().getBoolean(["feature", "sendChecksumWithUnknownCommands"])
self._unknownCommandsNeedAck = settings().getBoolean(["feature", "unknownCommandsNeedAck"])
self._currentLine = 1
+ self._line_mutex = threading.RLock()
self._resendDelta = None
self._lastLines = deque([], 50)
self._lastCommError = None
self._lastResendNumber = None
self._currentResendCount = 0
self._resendSwallowNextOk = False
+ self._resendSwallowRepetitions = settings().getBoolean(["feature", "ignoreIdenticalResends"])
+ self._resendSwallowRepetitionsCounter = 0
+ self._checksum_requiring_commands = settings().get(["serial", "checksumRequiringCommands"])
self._clear_to_send = CountedEvent(max=10, name="comm.clear_to_send")
self._send_queue = TypedQueue()
@@ -179,6 +270,7 @@ class MachineCom(object):
sending=self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.sending"),
sent=self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.sent")
)
+ self._received_message_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.gcode.received")
self._printer_action_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.action")
self._gcodescript_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.scripts")
@@ -195,28 +287,6 @@ class MachineCom(object):
self._currentFile = None
# regexes
- floatPattern = "[-+]?[0-9]*\.?[0-9]+"
- positiveFloatPattern = "[+]?[0-9]*\.?[0-9]+"
- intPattern = "\d+"
- self._regex_command = re.compile("^\s*([GM]\d+|T)")
- self._regex_float = re.compile(floatPattern)
- self._regex_paramZFloat = re.compile("Z(%s)" % floatPattern)
- self._regex_paramSInt = re.compile("S(%s)" % intPattern)
- self._regex_paramNInt = re.compile("N(%s)" % intPattern)
- self._regex_paramTInt = re.compile("T(%s)" % intPattern)
- self._regex_minMaxError = re.compile("Error:[0-9]\n")
- self._regex_sdPrintingByte = re.compile("([0-9]*)/([0-9]*)")
- self._regex_sdFileOpened = re.compile("File opened:\s*(.*?)\s+Size:\s*(%s)" % intPattern)
-
- # Regex matching temperature entries in line. Groups will be as follows:
- # - 1: whole tool designator incl. optional toolNumber ("T", "Tn", "B")
- # - 2: toolNumber, if given ("", "n", "")
- # - 3: actual temperature
- # - 4: whole target substring, if given (e.g. " / 22.0")
- # - 5: target temperature
- self._regex_temp = re.compile("(B|T(\d*)):\s*(%s)(\s*\/?\s*(%s))?" % (positiveFloatPattern, positiveFloatPattern))
- self._regex_repetierTempExtr = re.compile("TargetExtr([0-9]+):(%s)" % positiveFloatPattern)
- self._regex_repetierTempBed = re.compile("TargetBed:(%s)" % positiveFloatPattern)
self._long_running_commands = settings().get(["serial", "longRunningCommands"])
@@ -271,37 +341,51 @@ class MachineCom(object):
def getState(self):
return self._state
- def getStateString(self):
- if self._state == self.STATE_NONE:
+ def getStateId(self, state=None):
+ if state is None:
+ state = self._state
+
+ possible_states = filter(lambda x: x.startswith("STATE_"), self.__class__.__dict__.keys())
+ for possible_state in possible_states:
+ if getattr(self, possible_state) == state:
+ return possible_state[len("STATE_"):]
+
+ return "UNKNOWN"
+
+ def getStateString(self, state=None):
+ if state is None:
+ state = self._state
+
+ if state == self.STATE_NONE:
return "Offline"
- if self._state == self.STATE_OPEN_SERIAL:
+ if state == self.STATE_OPEN_SERIAL:
return "Opening serial port"
- if self._state == self.STATE_DETECT_SERIAL:
+ if state == self.STATE_DETECT_SERIAL:
return "Detecting serial port"
- if self._state == self.STATE_DETECT_BAUDRATE:
+ if state == self.STATE_DETECT_BAUDRATE:
return "Detecting baudrate"
- if self._state == self.STATE_CONNECTING:
+ if state == self.STATE_CONNECTING:
return "Connecting"
- if self._state == self.STATE_OPERATIONAL:
+ if state == self.STATE_OPERATIONAL:
return "Operational"
- if self._state == self.STATE_PRINTING:
+ if state == self.STATE_PRINTING:
if self.isSdFileSelected():
return "Printing from SD"
elif self.isStreaming():
return "Sending file to SD"
else:
return "Printing"
- if self._state == self.STATE_PAUSED:
+ if state == self.STATE_PAUSED:
return "Paused"
- if self._state == self.STATE_CLOSED:
+ if state == self.STATE_CLOSED:
return "Closed"
- if self._state == self.STATE_ERROR:
+ if state == self.STATE_ERROR:
return "Error: %s" % (self.getErrorString())
- if self._state == self.STATE_CLOSED_WITH_ERROR:
+ if state == self.STATE_CLOSED_WITH_ERROR:
return "Error: %s" % (self.getErrorString())
- if self._state == self.STATE_TRANSFERING_FILE:
+ if state == self.STATE_TRANSFERING_FILE:
return "Transfering file to SD"
- return "?%d?" % (self._state)
+ return "Unknown State (%d)" % (self._state)
def getErrorString(self):
return self._errorValue
@@ -382,7 +466,29 @@ class MachineCom(object):
##~~ external interface
- def close(self, isError = False):
+ def close(self, is_error=False, wait=True, *args, **kwargs):
+ """
+ Closes the connection to the printer.
+
+ If ``is_error`` is False, will attempt to send the ``beforePrinterDisconnected``
+ gcode script. If ``is_error`` is False and ``wait`` is True, will wait
+ until all messages in the send queue (including the ``beforePrinterDisconnected``
+ gcode script) have been sent to the printer.
+
+ Arguments:
+ is_error (bool): Whether the closing takes place due to an error (True)
+ or not (False, default)
+ wait (bool): Whether to wait for all messages in the send
+ queue to be processed before closing (True, default) or not (False)
+ """
+
+ # legacy parameters
+ is_error = kwargs.get("isError", is_error)
+
+ if self._connection_closing:
+ return
+ self._connection_closing = True
+
if self._temperature_timer is not None:
try:
self._temperature_timer.cancel()
@@ -395,16 +501,31 @@ class MachineCom(object):
except:
pass
- self._monitoring_active = False
- self._send_queue_active = False
+ def deactivate_monitoring_and_send_queue():
+ self._monitoring_active = False
+ self._send_queue_active = False
printing = self.isPrinting() or self.isPaused()
if self._serial is not None:
- if isError:
+ if not is_error:
+ self.sendGcodeScript("beforePrinterDisconnected")
+ if wait:
+ self._send_queue.join()
+
+ deactivate_monitoring_and_send_queue()
+
+ try:
+ self._serial.close()
+ except:
+ self._logger.exception("Error while trying to close serial port")
+ is_error = True
+
+ if is_error:
self._changeState(self.STATE_CLOSED_WITH_ERROR)
else:
self._changeState(self.STATE_CLOSED)
- self._serial.close()
+ else:
+ deactivate_monitoring_and_send_queue()
self._serial = None
if settings().getBoolean(["feature", "sdSupport"]):
@@ -419,7 +540,6 @@ class MachineCom(object):
"origin": self._currentFile.getFileLocation()
}
eventManager().fire(Events.PRINT_FAILED, payload)
- eventManager().fire(Events.DISCONNECTED)
def setTemperatureOffset(self, offsets):
self._tempOffsets.update(offsets)
@@ -427,8 +547,8 @@ class MachineCom(object):
def fakeOk(self):
self._clear_to_send.set()
- def sendCommand(self, cmd, cmd_type=None, processed=False):
- cmd = cmd.encode('ascii', 'replace')
+ def sendCommand(self, cmd, cmd_type=None, processed=False, force=False):
+ cmd = to_unicode(cmd, errors="replace")
if not processed:
cmd = process_gcode_line(cmd)
if not cmd:
@@ -436,7 +556,7 @@ class MachineCom(object):
if self.isPrinting() and not self.isSdFileSelected():
self._commandQueue.put((cmd, cmd_type))
- elif self.isOperational():
+ elif self.isOperational() or force:
self._sendCommand(cmd, cmd_type=cmd_type)
def sendGcodeScript(self, scriptName, replacements=None):
@@ -508,7 +628,7 @@ class MachineCom(object):
self._changeState(self.STATE_PRINTING)
- self.sendCommand("M110 N0")
+ self.resetLineNumbers()
payload = {
"file": self._currentFile.getFilename(),
@@ -706,53 +826,21 @@ class MachineCom(object):
self._callback.on_comm_sd_state_change(self._sdAvailable)
self._callback.on_comm_sd_files(self._sdFiles)
+ def sayHello(self):
+ self.sendCommand(self._hello_command, force=True)
+ self._clear_to_send.set()
+
+ def resetLineNumbers(self, number=0):
+ if not self.isOperational():
+ return
+
+ self.sendCommand("M110 N%d" % number)
+
##~~ communication monitoring and handling
- def _parseTemperatures(self, line):
- result = {}
- maxToolNum = 0
- for match in re.finditer(self._regex_temp, line):
- tool = match.group(1)
- toolNumber = int(match.group(2)) if match.group(2) and len(match.group(2)) > 0 else None
- if toolNumber > maxToolNum:
- maxToolNum = toolNumber
-
- try:
- actual = float(match.group(3))
- target = None
- if match.group(4) and match.group(5):
- target = float(match.group(5))
-
- result[tool] = (toolNumber, actual, target)
- except ValueError:
- # catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
- pass
-
- if "T0" in result.keys() and "T" in result.keys():
- del result["T"]
-
- return maxToolNum, result
-
def _processTemperatures(self, line):
- maxToolNum, parsedTemps = self._parseTemperatures(line)
-
- # extruder temperatures
- if not "T0" in parsedTemps.keys() and not "T1" in parsedTemps.keys() and "T" in parsedTemps.keys():
- # no T1 so only single reporting, "T" is our one and only extruder temperature
- toolNum, actual, target = parsedTemps["T"]
-
- if target is not None:
- self._temp[0] = (actual, target)
- elif 0 in self._temp.keys() and self._temp[0] is not None and isinstance(self._temp[0], tuple):
- (oldActual, oldTarget) = self._temp[0]
- self._temp[0] = (actual, oldTarget)
- else:
- self._temp[0] = (actual, None)
- elif not "T0" in parsedTemps.keys() and "T" in parsedTemps.keys():
- # Smoothieware sends multi extruder temperature data this way: "T: T1: ..." and therefore needs some special treatment...
- _, actual, target = parsedTemps["T"]
- del parsedTemps["T"]
- parsedTemps["T0"] = (0, actual, target)
+ current_tool = self._currentTool if self._currentTool is not None else 0
+ maxToolNum, parsedTemps = parse_temperature_line(line, current_tool)
if "T0" in parsedTemps.keys():
for n in range(maxToolNum + 1):
@@ -760,18 +848,18 @@ class MachineCom(object):
if not tool in parsedTemps.keys():
continue
- toolNum, actual, target = parsedTemps[tool]
+ actual, target = parsedTemps[tool]
if target is not None:
- self._temp[toolNum] = (actual, target)
- elif toolNum in self._temp.keys() and self._temp[toolNum] is not None and isinstance(self._temp[toolNum], tuple):
- (oldActual, oldTarget) = self._temp[toolNum]
- self._temp[toolNum] = (actual, oldTarget)
+ self._temp[n] = (actual, target)
+ elif n in self._temp and self._temp[n] is not None and isinstance(self._temp[n], tuple):
+ (oldActual, oldTarget) = self._temp[n]
+ self._temp[n] = (actual, oldTarget)
else:
- self._temp[toolNum] = (actual, None)
+ self._temp[n] = (actual, None)
# bed temperature
if "B" in parsedTemps.keys():
- toolNum, actual, target = parsedTemps["B"]
+ actual, target = parsedTemps["B"]
if target is not None:
self._bedTemp = (actual, target)
elif self._bedTemp is not None and isinstance(self._bedTemp, tuple):
@@ -814,10 +902,9 @@ class MachineCom(object):
connection_timeout = settings().getFloat(["serial", "timeout", "connection"])
detection_timeout = settings().getFloat(["serial", "timeout", "detection"])
- # enqueue an M105 first thing
+ # enqueue the "hello command" first thing
if try_hello:
- self._sendCommand("M110")
- self._clear_to_send.set()
+ self.sayHello()
while self._monitoring_active:
try:
@@ -899,8 +986,8 @@ class MachineCom(object):
self._callback.on_comm_temperature_update(self._temp, self._bedTemp)
elif supportRepetierTargetTemp and ('TargetExtr' in line or 'TargetBed' in line):
- matchExtr = self._regex_repetierTempExtr.match(line)
- matchBed = self._regex_repetierTempBed.match(line)
+ matchExtr = regex_repetierTempExtr.match(line)
+ matchBed = regex_repetierTempBed.match(line)
if matchExtr is not None:
toolNum = int(matchExtr.group(1))
@@ -954,18 +1041,18 @@ class MachineCom(object):
self._callback.on_comm_sd_files(self._sdFiles)
elif 'SD printing byte' in line and self.isSdPrinting():
# answer to M27, at least on Marlin, Repetier and Sprinter: "SD printing byte %d/%d"
- match = self._regex_sdPrintingByte.search(line)
- self._currentFile.setFilepos(int(match.group(1)))
+ match = regex_sdPrintingByte.search(line)
+ self._currentFile.setFilepos(int(match.group("current")))
self._callback.on_comm_progress()
elif 'File opened' in line and not self._ignore_select:
# answer to M23, at least on Marlin, Repetier and Sprinter: "File opened:%s Size:%d"
- match = self._regex_sdFileOpened.search(line)
+ match = regex_sdFileOpened.search(line)
if self._sdFileToSelect:
name = self._sdFileToSelect
self._sdFileToSelect = None
else:
- name = match.group(1)
- self._currentFile = PrintingSdFileInformation(name, int(match.group(2)))
+ name = match.group("name")
+ self._currentFile = PrintingSdFileInformation(name, int(match.group("size")))
elif 'File selected' in line:
if self._ignore_select:
self._ignore_select = False
@@ -1038,8 +1125,7 @@ class MachineCom(object):
self._baudrateDetectRetry -= 1
self._serial.write('\n')
self._log("Baudrate test retry: %d" % (self._baudrateDetectRetry))
- self._sendCommand("M110")
- self._clear_to_send.set()
+ self.sayHello()
elif len(self._baudrateDetectList) > 0:
baudrate = self._baudrateDetectList.pop(0)
try:
@@ -1050,12 +1136,11 @@ class MachineCom(object):
self._baudrateDetectRetry = 5
self._timeout = get_new_timeout("communication")
self._serial.write('\n')
- self._sendCommand("M110")
- self._clear_to_send.set()
+ self.sayHello()
except:
self._log("Unexpected error while setting baudrate: %d %s" % (baudrate, get_exception_string()))
else:
- self.close()
+ self.close(wait=False)
self._errorValue = "No more baudrates to test, and no suitable baudrate found."
self._changeState(self.STATE_ERROR)
eventManager().fire(Events.ERROR, {"error": self.getErrorString()})
@@ -1067,39 +1152,23 @@ class MachineCom(object):
elif self._state == self.STATE_CONNECTING:
if "start" in line and not startSeen:
startSeen = True
- self._sendCommand("M110")
- self._clear_to_send.set()
+ self.sayHello()
elif "ok" in line:
self._onConnected()
elif time.time() > self._timeout:
- self.close()
+ self.close(wait=False)
- ### Operational
- elif self._state == self.STATE_OPERATIONAL or self._state == self.STATE_PAUSED:
- if "ok" in line:
- # if we still have commands to process, process them
- if self._resendSwallowNextOk:
- self._resendSwallowNextOk = False
- elif self._resendDelta is not None:
- self._resendNextCommand()
- elif self._sendFromQueue():
- pass
-
- # resend -> start resend procedure from requested line
- elif line.lower().startswith("resend") or line.lower().startswith("rs"):
- self._handleResendRequest(line)
-
- ### Printing
- elif self._state == self.STATE_PRINTING:
+ ### Operational & Printing
+ if self._state in (self.STATE_OPERATIONAL, self.STATE_PAUSED, self.STATE_PRINTING):
if line == "" and time.time() > self._timeout:
if not self._long_running_command:
- self._log("Communication timeout during printing, forcing a line")
+ self._log("Communication timeout, forcing a line")
self._sendCommand("M105")
self._clear_to_send.set()
else:
self._logger.debug("Ran into a communication timeout, but a command known to be a long runner is currently active")
- if "ok" in line or (supportWait and "wait" in line):
+ elif "ok" in line or (self._state == self.STATE_PRINTING and supportWait and "wait" in line):
# a wait while printing means our printer's buffer ran out, probably due to some ok getting
# swallowed, so we treat it the same as an ok here teo take up communication again
if self._resendSwallowNextOk:
@@ -1111,9 +1180,10 @@ class MachineCom(object):
else:
if self._sendFromQueue():
pass
- elif not self.isSdPrinting():
+ elif self._state == self.STATE_PRINTING and not self.isSdPrinting():
self._sendNext()
+ # resend -> start resend procedure from requested line
elif line.lower().startswith("resend") or line.lower().startswith("rs"):
self._handleResendRequest(line)
except:
@@ -1185,11 +1255,13 @@ class MachineCom(object):
def _onConnected(self):
self._serial.timeout = settings().getFloat(["serial", "timeout", "communication"])
- self._temperature_timer = RepeatedTimer(lambda: get_interval("temperature", default_value=4.0), self._poll_temperature, run_first=True)
+ self._temperature_timer = RepeatedTimer(self._getTemperatureTimerInterval, self._poll_temperature, run_first=True)
self._temperature_timer.start()
self._changeState(self.STATE_OPERATIONAL)
+ self.resetLineNumbers()
+
if self._sdAvailable:
self.refreshSdFiles()
else:
@@ -1199,6 +1271,22 @@ class MachineCom(object):
eventManager().fire(Events.CONNECTED, payload)
self.sendGcodeScript("afterPrinterConnected", replacements=dict(event=payload))
+ def _getTemperatureTimerInterval(self):
+ busy_default = 4.0
+ target_default = 2.0
+
+ if self.isBusy():
+ return get_interval("temperature", default_value=busy_default)
+
+ for temp in [self._temp[k][1] for k in self._temp.keys()]:
+ if temp > self._temperatureTargetSetThreshold:
+ return get_interval("temperatureTargetSet", default_value=target_default)
+
+ if self._bedTemp and len(self._bedTemp) > 0 and self._bedTemp[1] > self._temperatureTargetSetThreshold:
+ return get_interval("temperatureTargetSet", default_value=target_default)
+
+ return get_interval("temperature", default_value=busy_default)
+
def _sendFromQueue(self):
if not self._commandQueue.empty() and not self.isStreaming():
entry = self._commandQueue.get()
@@ -1299,10 +1387,10 @@ class MachineCom(object):
# Marlin reports an MIN/MAX temp error as "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
# But a bed temp error is reported as "Error: Temperature heated bed switched off. MAXTEMP triggered !!"
# So we can have an extra newline in the most common case. Awesome work people.
- if self._regex_minMaxError.match(line):
+ if regex_minMaxError.match(line):
line = line.rstrip() + self._readline()
- if 'line number' in line.lower() or 'checksum' in line.lower() or 'expected line' in line.lower():
+ if 'line number' in line.lower() or 'checksum' in line.lower() or 'format error' in line.lower() or 'expected line' in line.lower():
#Skip the communication errors, as those get corrected.
self._lastCommError = line[6:] if line.startswith("Error:") else line[2:]
pass
@@ -1317,18 +1405,18 @@ class MachineCom(object):
return line
def _readline(self):
- if self._serial == None:
+ if self._serial is None:
return None
+
try:
ret = self._serial.readline()
except:
- self._log("Unexpected error while reading serial port: %s" % (get_exception_string()))
- self._errorValue = get_exception_string()
- self.close(True)
+ if not self._connection_closing:
+ self._logger.exception("Unexpected error while reading from serial port")
+ self._log("Unexpected error while reading serial port, please consult octoprint.log for details: %s" % (get_exception_string()))
+ self._errorValue = get_exception_string()
+ self.close(is_error=True)
return None
- if ret == '':
- #self._log("Recv: TIMEOUT")
- return ''
try:
self._log("Recv: %s" % sanitize_ascii(ret))
@@ -1336,6 +1424,15 @@ class MachineCom(object):
self._log("WARN: While reading last line: %s" % e)
self._log("Recv: %r" % ret)
+ for name, hook in self._received_message_hooks.items():
+ try:
+ ret = hook(self, ret)
+ except:
+ self._logger.exception("Error while processing hook {name}:".format(**locals()))
+ else:
+ if ret is None:
+ return ""
+
return ret
def _getNext(self):
@@ -1401,9 +1498,18 @@ class MachineCom(object):
self._currentResendCount += 1
return
+ # If we ignore resend repetitions (Repetier firmware...), check if we
+ # need to do this now. If the same line number has been requested we
+ # already saw and resent, we'll ignore it up to times.
+ if self._resendSwallowRepetitions and lineToResend == self._lastResendNumber and self._resendSwallowRepetitionsCounter > 0:
+ self._logger.debug("Ignoring resend request for line %d, that is probably a repetition sent by the firmware to ensure it arrives, not a real request" % lineToResend)
+ self._resendSwallowRepetitionsCounter -= 1
+ return
+
self._resendDelta = resendDelta
self._lastResendNumber = lineToResend
self._currentResendCount = 0
+ self._resendSwallowRepetitionsCounter = settings().getInt(["feature", "identicalResendsCountdown"])
if self._resendDelta > len(self._lastLines) or len(self._lastLines) == 0 or self._resendDelta < 0:
self._errorValue = "Printer requested line %d but no sufficient history is available, can't resend" % lineToResend
@@ -1460,25 +1566,6 @@ class MachineCom(object):
# trigger the "queued" phase only if we are not streaming to sd right now
self._process_command_phase("queued", cmd, cmd_type, gcode=gcode)
- def gcode_command_for_cmd(self, cmd):
- """
- Tries to parse the provided ``cmd`` and extract the GCODE command identifier from it (e.g. "G0" for "G0 X10.0").
-
- Arguments:
- cmd (str): The command to try to parse.
-
- Returns:
- str or None: The GCODE command identifier if it could be parsed, or None if not.
- """
- if not cmd:
- return None
-
- gcode = self._regex_command.search(cmd)
- if not gcode:
- return None
-
- return gcode.group(1)
-
##~~ send loop handling
def _enqueue_for_sending(self, command, linenumber=None, command_type=None):
@@ -1509,52 +1596,64 @@ class MachineCom(object):
# wait until we have something in the queue
entry = self._send_queue.get()
- # make sure we are still active
- if not self._send_queue_active:
- break
+ try:
+ # make sure we are still active
+ if not self._send_queue_active:
+ break
- # fetch command and optional linenumber from queue
- command, linenumber, command_type = entry
+ # fetch command and optional linenumber from queue
+ command, linenumber, command_type = entry
- # some firmwares (e.g. Smoothie) might support additional in-band communication that will not
- # stick to the acknowledgement behaviour of GCODE, so we check here if we have a GCODE command
- # at hand here and only clear our clear_to_send flag later if that's the case
- gcode = self.gcode_command_for_cmd(command)
+ # some firmwares (e.g. Smoothie) might support additional in-band communication that will not
+ # stick to the acknowledgement behaviour of GCODE, so we check here if we have a GCODE command
+ # at hand here and only clear our clear_to_send flag later if that's the case
+ gcode = gcode_command_for_cmd(command)
- if linenumber is not None:
- # line number predetermined - this only happens for resends, so we'll use the number and
- # send directly without any processing (since that already took place on the first sending!)
- self._doSendWithChecksum(command, linenumber)
-
- else:
- # trigger "sending" phase
- command, _, gcode = self._process_command_phase("sending", command, command_type, gcode=gcode)
-
- if command is None:
- # so no, we are not going to send this, that was a last-minute bail, let's fetch the next item from the queue
- continue
-
- # now comes the part where we increase line numbers and send stuff - no turning back now
- if (gcode is not None or self._sendChecksumWithUnknownCommands) and (self.isPrinting() or self._alwaysSendChecksum):
- linenumber = self._currentLine
- self._addToLastLines(command)
- self._currentLine += 1
+ if linenumber is not None:
+ # line number predetermined - this only happens for resends, so we'll use the number and
+ # send directly without any processing (since that already took place on the first sending!)
self._doSendWithChecksum(command, linenumber)
+
else:
- self._doSendWithoutChecksum(command)
+ # trigger "sending" phase
+ command, _, gcode = self._process_command_phase("sending", command, command_type, gcode=gcode)
- # trigger "sent" phase and use up one "ok"
- self._process_command_phase("sent", command, command_type, gcode=gcode)
+ if command is None:
+ # so no, we are not going to send this, that was a last-minute bail, let's fetch the next item from the queue
+ continue
- # we only need to use up a clear if the command we just sent was either a gcode command or if we also
- # require ack's for unknown commands
- use_up_clear = self._unknownCommandsNeedAck
- if gcode is not None:
- use_up_clear = True
+ if command.strip() == "":
+ self._logger.info("Refusing to send an empty line to the printer")
+ continue
- # if we need to use up a clear, do that now
- if use_up_clear:
- self._clear_to_send.clear()
+ # now comes the part where we increase line numbers and send stuff - no turning back now
+ command_requiring_checksum = gcode is not None and gcode in self._checksum_requiring_commands
+ command_allowing_checksum = gcode is not None or self._sendChecksumWithUnknownCommands
+ checksum_enabled = self._alwaysSendChecksum or (self.isPrinting() and not self._neverSendChecksum)
+
+ command_to_send = command.encode("ascii", errors="replace")
+ if command_requiring_checksum or (command_allowing_checksum and checksum_enabled):
+ self._doIncrementAndSendWithChecksum(command_to_send)
+ else:
+ self._doSendWithoutChecksum(command_to_send)
+
+ # trigger "sent" phase and use up one "ok"
+ self._process_command_phase("sent", command, command_type, gcode=gcode)
+
+ # we only need to use up a clear if the command we just sent was either a gcode command or if we also
+ # require ack's for unknown commands
+ use_up_clear = self._unknownCommandsNeedAck
+ if gcode is not None:
+ use_up_clear = True
+
+ # if we need to use up a clear, do that now
+ if use_up_clear:
+ self._clear_to_send.clear()
+
+ finally:
+ # no matter _how_ we exit this block, we signal that we
+ # are done processing the last fetched queue entry
+ self._send_queue.task_done()
# now we just wait for the next clear and then start again
self._clear_to_send.wait()
@@ -1567,7 +1666,7 @@ class MachineCom(object):
return command, command_type, gcode
if gcode is None:
- gcode = self.gcode_command_for_cmd(command)
+ gcode = gcode_command_for_cmd(command)
# send it through the phase specific handlers provided by plugins
for name, hook in self._gcode_hooks[phase].items():
@@ -1622,11 +1721,18 @@ class MachineCom(object):
# handler returned a tuple of an unexpected length
return original_tuple
- gcode = self.gcode_command_for_cmd(command)
+ gcode = gcode_command_for_cmd(command)
return command, command_type, gcode
##~~ actual sending via serial
+ def _doIncrementAndSendWithChecksum(self, cmd):
+ with self._line_mutex:
+ linenumber = self._currentLine
+ self._addToLastLines(cmd)
+ self._currentLine += 1
+ self._doSendWithChecksum(cmd, linenumber)
+
def _doSendWithChecksum(self, cmd, lineNumber):
commandToSend = "N%d %s" % (lineNumber, cmd)
checksum = reduce(lambda x,y:x^y, map(ord, commandToSend))
@@ -1634,6 +1740,9 @@ class MachineCom(object):
self._doSendWithoutChecksum(commandToSend)
def _doSendWithoutChecksum(self, cmd):
+ if self._serial is None:
+ return
+
self._log("Send: %s" % cmd)
try:
self._serial.write(cmd + '\n')
@@ -1642,29 +1751,31 @@ class MachineCom(object):
try:
self._serial.write(cmd + '\n')
except:
+ if not self._connection_closing:
+ self._logger.exception("Unexpected error while writing to serial port")
+ self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
+ self._errorValue = get_exception_string()
+ self.close(is_error=True)
+ except:
+ if not self._connection_closing:
self._logger.exception("Unexpected error while writing to serial port")
self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
self._errorValue = get_exception_string()
- self.close(True)
- except:
- self._logger.exception("Unexpected error while writing to serial port")
- self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
- self._errorValue = get_exception_string()
- self.close(True)
+ self.close(is_error=True)
##~~ command handlers
def _gcode_T_sent(self, cmd, cmd_type=None):
- toolMatch = self._regex_paramTInt.search(cmd)
+ toolMatch = regexes_parameters["intT"].search(cmd)
if toolMatch:
- self._currentTool = int(toolMatch.group(1))
+ self._currentTool = int(toolMatch.group("value"))
def _gcode_G0_sent(self, cmd, cmd_type=None):
if 'Z' in cmd:
- match = self._regex_paramZFloat.search(cmd)
+ match = regexes_parameters["floatZ"].search(cmd)
if match:
try:
- z = float(match.group(1))
+ z = float(match.group("value"))
if self._currentZ != z:
self._currentZ = z
self._callback.on_comm_z_change(z)
@@ -1679,13 +1790,13 @@ class MachineCom(object):
def _gcode_M104_sent(self, cmd, cmd_type=None):
toolNum = self._currentTool
- toolMatch = self._regex_paramTInt.search(cmd)
+ toolMatch = regexes_parameters["intT"].search(cmd)
if toolMatch:
- toolNum = int(toolMatch.group(1))
- match = self._regex_paramSInt.search(cmd)
+ toolNum = int(toolMatch.group("value"))
+ match = regexes_parameters["floatS"].search(cmd)
if match:
try:
- target = float(match.group(1))
+ target = float(match.group("value"))
if toolNum in self._temp.keys() and self._temp[toolNum] is not None and isinstance(self._temp[toolNum], tuple):
(actual, oldTarget) = self._temp[toolNum]
self._temp[toolNum] = (actual, target)
@@ -1695,10 +1806,10 @@ class MachineCom(object):
pass
def _gcode_M140_sent(self, cmd, cmd_type=None):
- match = self._regex_paramSInt.search(cmd)
+ match = regexes_parameters["floatS"].search(cmd)
if match:
try:
- target = float(match.group(1))
+ target = float(match.group("value"))
if self._bedTemp is not None and isinstance(self._bedTemp, tuple):
(actual, oldTarget) = self._bedTemp
self._bedTemp = (actual, target)
@@ -1721,37 +1832,61 @@ class MachineCom(object):
def _gcode_M110_sending(self, cmd, cmd_type=None):
newLineNumber = None
- match = self._regex_paramNInt.search(cmd)
+ match = regexes_parameters["intN"].search(cmd)
if match:
try:
- newLineNumber = int(match.group(1))
+ newLineNumber = int(match.group("value"))
except:
pass
else:
newLineNumber = 0
- # send M110 command with new line number
- self._currentLine = newLineNumber
+ with self._line_mutex:
+ # send M110 command with new line number
+ self._currentLine = newLineNumber
- # after a reset of the line number we have no way to determine what line exactly the printer now wants
- self._lastLines.clear()
+ # after a reset of the line number we have no way to determine what line exactly the printer now wants
+ self._lastLines.clear()
self._resendDelta = None
- def _gcode_M112_queuing(self, cmd, cmd_type=None): # It's an emergency what todo? Canceling the print should be the minimum
- self.cancelPrint()
+ def _gcode_M112_queuing(self, cmd, cmd_type=None):
+ # emergency stop, jump the queue with the M112
+ self._doSendWithoutChecksum("M112")
+ self._doIncrementAndSendWithChecksum("M112")
+
+ # No idea if the printer is still listening or if M112 won. Just in case
+ # we'll now try to also manually make sure all heaters are shut off - better
+ # safe than sorry. We do this ignoring the queue since at this point it
+ # is irrelevant whether the printer has sent enough ack's or not, we
+ # are going to shutdown the connection in a second anyhow.
+ for tool in range(self._printerProfileManager.get_current_or_default()["extruder"]["count"]):
+ self._doIncrementAndSendWithChecksum("M104 T{tool} S0".format(tool=tool))
+ self._doIncrementAndSendWithChecksum("M140 S0")
+
+ # close to reset host state
+ self._errorValue = "Closing serial port due to emergency stop M112."
+ self._log(self._errorValue)
+ self.close(is_error=True)
+
+ # fire the M112 event since we sent it and we're going to prevent the caller from seeing it
+ gcode = "M112"
+ if gcode in gcodeToEvent:
+ eventManager().fire(gcodeToEvent[gcode])
+
+ # return None 1-tuple to eat the one that is queuing because we don't want to send it twice
+ # I hope it got it the first time because as far as I can tell, there is no way to know
+ return None,
def _gcode_G4_sent(self, cmd, cmd_type=None):
# we are intending to dwell for a period of time, increase the timeout to match
- cmd = cmd.upper()
- p_idx = cmd.find('P')
- s_idx = cmd.find('S')
+ p_match = regexes_parameters["floatP"].search(cmd)
+ s_match = regexes_parameters["floatS"].search(cmd)
+
_timeout = 0
- if p_idx != -1:
- # dwell time is specified in milliseconds
- _timeout = float(cmd[p_idx+1:]) / 1000.0
- elif s_idx != -1:
- # dwell time is specified in seconds
- _timeout = float(cmd[s_idx+1:])
+ if p_match:
+ _timeout = float(p_match.group("value")) / 1000.0
+ elif s_match:
+ _timeout = float(s_match.group("value"))
self._timeout = get_new_timeout("communication") + _timeout
##~~ command phase handlers
@@ -1905,7 +2040,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
Opens the file for reading and determines the file size.
"""
PrintingFileInformation.start(self)
- self._handle = open(self._filename, "r")
+ self._handle = bom_aware_open(self._filename, encoding="utf-8", errors="replace")
def close(self):
"""
@@ -1935,7 +2070,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
if self._handle is None:
# file got closed just now
return None
- line = self._handle.readline()
+ line = to_unicode(self._handle.readline())
if not line:
self.close()
processed = process_gcode_line(line, offsets=offsets, current_tool=current_tool)
@@ -2141,3 +2276,159 @@ def convert_feedback_controls(configured_controls):
return feedback_controls, feedback_matcher
+def canonicalize_temperatures(parsed, current):
+ """
+ Canonicalizes the temperatures provided in parsed.
+
+ Will make sure that returned result only contains extruder keys
+ like Tn, so always qualified with a tool number.
+
+ The algorithm for cleaning up the parsed keys is the following:
+
+ * If ``T`` is not included with the reported extruders, return
+ * If more than just ``T`` is reported:
+ * If both ``T`` and ``T0`` are reported set ``Tc`` to ``T``, remove
+ ``T`` from the result.
+ * Else set ``T0`` to ``T`` and delete ``T`` (Smoothie extra).
+ * If only ``T`` is reported, set ``Tc`` to ``T`` and delete ``T``
+ * return
+
+ Arguments:
+ parsed (dict): the parsed temperatures (mapping tool => (actual, target))
+ to canonicalize
+ current (int): the current active extruder
+ Returns:
+ dict: the canonicalized version of ``parsed``
+ """
+
+ reported_extruders = filter(lambda x: x.startswith("T"), parsed.keys())
+ if not "T" in reported_extruders:
+ # Our reported_extruders are either empty or consist purely
+ # of Tn keys, no need for any action
+ return parsed
+
+ current_tool_key = "T%d" % current
+ result = dict(parsed)
+
+ if len(reported_extruders) > 1:
+ if "T0" in reported_extruders:
+ # Both T and T0 are present, so T contains the current
+ # extruder's temperature, e.g. for current_tool == 1:
+ #
+ # T: T0: T2: ... B:
+ #
+ # becomes
+ #
+ # T0: T1: T2: ... B:
+ #
+ # Same goes if Tc is already present, it will be overwritten:
+ #
+ # T: T0: T1: T2: ... B:
+ #
+ # becomes
+ #
+ # T0: T1: T2: ... B:
+ result[current_tool_key] = result["T"]
+ del result["T"]
+ else:
+ # So T is there, but T0 isn't. That looks like Smoothieware which
+ # always reports the first extruder T0 as T:
+ #
+ # T: T1: T2: ... B:
+ #
+ # becomes
+ #
+ # T0: T1: T2: ... B:
+ result["T0"] = result["T"]
+ del result["T"]
+
+ else:
+ # We only have T. That can mean two things:
+ #
+ # * we only have one extruder at all, or
+ # * we are currently parsing a response to M109/M190, which on
+ # some firmwares doesn't report the full M105 output while
+ # waiting for the target temperature to be reached but only
+ # reports the current tool and bed
+ #
+ # In both cases it is however safe to just move our T over
+ # to T in the parsed data, current should always stay
+ # 0 for single extruder printers. E.g. for current_tool == 1:
+ #
+ # T:
+ #
+ # becomes
+ #
+ # T1:
+
+ result[current_tool_key] = result["T"]
+ del result["T"]
+
+ return result
+
+def parse_temperature_line(line, current):
+ """
+ Parses the provided temperature line.
+
+ The result will be a dictionary mapping from the extruder or bed key to
+ a tuple with current and target temperature. The result will be canonicalized
+ with :func:`canonicalize_temperatures` before returning.
+
+ Arguments:
+ line (str): the temperature line to parse
+ current (int): the current active extruder
+
+ Returns:
+ tuple: a 2-tuple with the maximum tool number and a dict mapping from
+ key to (actual, target) tuples, with key either matching ``Tn`` for ``n >= 0`` or ``B``
+ """
+
+ result = {}
+ maxToolNum = 0
+ for match in re.finditer(regex_temp, line):
+ values = match.groupdict()
+ tool = values["tool"]
+ toolnum = values.get("toolnum", None)
+ toolNumber = int(toolnum) if toolnum is not None and len(toolnum) else None
+ if toolNumber > maxToolNum:
+ maxToolNum = toolNumber
+
+ try:
+ actual = float(match.group(3))
+ target = None
+ if match.group(4) and match.group(5):
+ target = float(match.group(5))
+
+ result[tool] = (actual, target)
+ except ValueError:
+ # catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
+ pass
+
+ return max(maxToolNum, current), canonicalize_temperatures(result, current)
+
+def gcode_command_for_cmd(cmd):
+ """
+ Tries to parse the provided ``cmd`` and extract the GCODE command identifier from it (e.g. "G0" for "G0 X10.0").
+
+ Arguments:
+ cmd (str): The command to try to parse.
+
+ Returns:
+ str or None: The GCODE command identifier if it could be parsed, or None if not.
+ """
+ if not cmd:
+ return None
+
+ gcode = regex_command.search(cmd)
+ if not gcode:
+ return None
+
+ values = gcode.groupdict()
+ if "commandGM" in values and values["commandGM"]:
+ return values["commandGM"]
+ elif "commandT" in values and values["commandT"]:
+ return values["commandT"]
+ else:
+ # this should never happen
+ return None
+
diff --git a/src/octoprint/util/gcodeInterpreter.py b/src/octoprint/util/gcodeInterpreter.py
index b0b69b665..e32b30626 100644
--- a/src/octoprint/util/gcodeInterpreter.py
+++ b/src/octoprint/util/gcodeInterpreter.py
@@ -35,7 +35,9 @@ class gcode(object):
if os.path.isfile(filename):
self.filename = filename
self._fileSize = os.stat(filename).st_size
- with open(filename, "r") as f:
+
+ import codecs
+ with codecs.open(filename, encoding="utf-8", errors="replace") as f:
self._load(f, printer_profile, throttle=throttle)
def abort(self):
@@ -54,6 +56,9 @@ class gcode(object):
absoluteE = True
scale = 1.0
posAbs = True
+ fwretractTime = 0
+ fwretractDist = 0
+ fwrecoverTime = 0
feedRateXY = min(printer_profile["axes"]["x"]["speed"], printer_profile["axes"]["y"]["speed"])
if feedRateXY == 0:
# some somewhat sane default if axes speeds are insane...
@@ -172,6 +177,10 @@ class gcode(object):
P = getCodeFloat(line, 'P')
if P is not None:
totalMoveTimeMinute += P / 60.0 / 1000.0
+ elif G == 10: #Firmware retract
+ totalMoveTimeMinute += fwretractTime
+ elif G == 11: #Firmware retract recover
+ totalMoveTimeMinute += fwrecoverTime
elif G == 20: #Units are inches
scale = 25.4
elif G == 21: #Units are mm
@@ -214,6 +223,15 @@ class gcode(object):
absoluteE = True
elif M == 83: #Relative E
absoluteE = False
+ elif M == 207 or M == 208: #Firmware retract settings
+ s = getCodeFloat(line, 'S')
+ f = getCodeFloat(line, 'F')
+ if s is not None and f is not None:
+ if M == 207:
+ fwretractTime = s / f
+ fwretractDist = s
+ else:
+ fwrecoverTime = (fwretractDist + s) / f
elif T is not None:
if T > settings().getInt(["gcodeAnalysis", "maxExtruders"]):
diff --git a/src/octoprint/util/pip.py b/src/octoprint/util/pip.py
index 4117546df..4b5b19b93 100644
--- a/src/octoprint/util/pip.py
+++ b/src/octoprint/util/pip.py
@@ -9,26 +9,56 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import sarge
import sys
import logging
+import re
+import site
+
+import pkg_resources
from .commandline import CommandlineCaller
+_cache = dict(version=dict(), setup=dict())
class UnknownPip(Exception):
pass
class PipCaller(CommandlineCaller):
- def __init__(self, configured=None):
+ process_dependency_links = pkg_resources.parse_requirements("pip>=1.5")
+ no_use_wheel = pkg_resources.parse_requirements("pip==1.5.0")
+ broken = pkg_resources.parse_requirements("pip>=6.0.1,<=6.0.3")
+
+ def __init__(self, configured=None, ignore_cache=False, force_sudo=False,
+ force_user=False):
CommandlineCaller.__init__(self)
self._logger = logging.getLogger(__name__)
- self._configured = configured
+ self.configured = configured
+ self.refresh = False
+ self.ignore_cache = ignore_cache
+
+ self.force_sudo = force_sudo
+ self.force_user = force_user
self._command = None
self._version = None
+ self._version_string = None
+ self._use_sudo = False
+ self._use_user = False
+ self._virtual_env = False
+ self._install_dir = None
- self._command, self._version = self._find_pip()
+ self.trigger_refresh()
- self.refresh = False
+ self.on_log_call = lambda *args, **kwargs: None
+ self.on_log_stdout = lambda *args, **kwargs: None
+ self.on_log_stderr = lambda *args, **kwargs: None
+
+ def _reset(self):
+ self._command = None
+ self._version = None
+ self._version_string = None
+ self._use_sudo = False
+ self._use_user = False
+ self._install_dir = None
def __le__(self, other):
return self.version is not None and self.version <= other
@@ -50,83 +80,248 @@ class PipCaller(CommandlineCaller):
def version(self):
return self._version
+ @property
+ def version_string(self):
+ return self._version_string
+
+ @property
+ def install_dir(self):
+ return self._install_dir
+
+ @property
+ def use_sudo(self):
+ return self._use_sudo
+
+ @property
+ def use_user(self):
+ return self._use_user
+
+ @property
+ def virtual_env(self):
+ return self._virtual_env
+
@property
def available(self):
return self._command is not None
+ def trigger_refresh(self):
+ self._reset()
+ try:
+ self._setup_pip()
+ except:
+ self._logger.exception("Error while discovering pip command")
+ self._command = None
+ self._version = None
+ self.refresh = False
+
def execute(self, *args):
if self.refresh:
- self._command, self._version = self._find_pip()
- self.refresh = False
+ self.trigger_refresh()
if self._command is None:
raise UnknownPip()
- command = [self._command] + list(args)
+ arg_list = list(args)
+
+ if "install" in arg_list:
+ # strip --process-dependency-links for versions that don't support it
+ if not self.version in self.__class__.process_dependency_links and "--process-dependency-links" in arg_list:
+ self._logger.debug("Found --process-dependency-links flag, version {} doesn't need that yet though, removing.".format(self.version))
+ arg_list.remove("--process-dependency-links")
+
+ # add --no-use-wheel for versions that otherwise break
+ if self.version in self.__class__.no_use_wheel and not "--no-use-wheel" in arg_list:
+ self._logger.debug("Version {} needs --no-use-wheel to properly work.".format(self.version))
+ arg_list.append("--no-use-wheel")
+
+ # remove --user if it's present and a virtual env is detected
+ if "--user" in arg_list:
+ if self._virtual_env or not site.ENABLE_USER_SITE:
+ self._logger.debug("Virtual environment detected, removing --user flag.")
+ arg_list.remove("--user")
+ # otherwise add it if necessary
+ elif not self._virtual_env and site.ENABLE_USER_SITE and (self.use_user or self.force_user):
+ self._logger.debug("pip needs --user flag for installations.")
+ arg_list.append("--user")
+
+ # add args to command
+ command = [self._command] + list(arg_list)
+
+ # add sudo if necessary
+ if self._use_sudo or self.force_sudo:
+ command = ["sudo"] + command
+
return self.call(command)
- def _find_pip(self):
- pip_command = self._configured
- pip_version = None
+ def _setup_pip(self):
+ pip_command = self.configured
+
+ if pip_command is not None and pip_command.startswith("sudo "):
+ pip_command = pip_command[len("sudo "):]
+ pip_sudo = True
+ else:
+ pip_sudo = False
if pip_command is None:
- import os
- python_command = sys.executable
- binary_dir = os.path.dirname(python_command)
+ pip_command = self._autodetect_pip()
- pip_command = os.path.join(binary_dir, "pip")
- if sys.platform == "win32":
- # Windows is a bit special... first of all the file will be called pip.exe, not just pip, and secondly
- # for a non-virtualenv install (e.g. global install) the pip binary will not be located in the
- # same folder as python.exe, but in a subfolder Scripts, e.g.
- #
- # C:\Python2.7\
- # |- python.exe
- # `- Scripts
- # `- pip.exe
+ if pip_command is None:
+ return
- # virtual env?
- pip_command = os.path.join(binary_dir, "pip.exe")
+ # Determine the pip version
- if not os.path.isfile(pip_command):
- # nope, let's try the Scripts folder then
- scripts_dir = os.path.join(binary_dir, "Scripts")
- if os.path.isdir(scripts_dir):
- pip_command = os.path.join(scripts_dir, "pip.exe")
+ self._logger.debug("Found pip at {}, going to figure out its version".format(pip_command))
- if not os.path.isfile(pip_command) or not os.access(pip_command, os.X_OK):
- pip_command = None
+ pip_version, version_segment = self._get_pip_version(pip_command)
+ if pip_version is None:
+ return
- if pip_command is not None:
- self._logger.debug("Found pip at {}, going to figure out its version".format(pip_command))
- p = sarge.run([pip_command, "--version"], stdout=sarge.Capture(), stderr=sarge.Capture())
+ if pip_version in self.__class__.broken:
+ self._logger.error("This version of pip is known to have errors that make it incompatible with how it needs to be used by OctoPrint. Please upgrade your pip version.")
+ return
- if p.returncode != 0:
- self._logger.warn("Error while trying to run pip --version: {}".format(p.stderr.text))
- pip_command = None
+ self._logger.info("Version of pip at {} is {}".format(pip_command, version_segment))
+
+ # Now figure out if pip belongs to a virtual environment and if the
+ # default installation directory is writable.
+ #
+ # The idea is the following: If OctoPrint is installed globally,
+ # the site-packages folder is probably not writable by our user.
+ # However, the user site-packages folder as usable by providing the
+ # --user parameter during install is. This we may not use though if
+ # the provided pip belongs to a virtual env (since that hiccups hard).
+ #
+ # So we figure out the installation directory, check if it's writable
+ # and if not if pip belongs to a virtual environment. Only if the
+ # installation directory is NOT writable by us but we also don't run
+ # in a virtual environment may we proceed with the --user parameter.
+
+ ok, pip_user, pip_virtual_env, pip_install_dir = self._check_pip_setup(pip_command)
+ if not ok:
+ self._logger.error("Cannot use pip at {}".format(pip_command))
+ return
+
+ self._logger.info("pip at {} installs to {}, --user flag needed => {}, virtual env => {}".format(pip_command, pip_install_dir, "yes" if pip_user else "no", "yes" if pip_virtual_env else "no"))
+
+ self._command = pip_command
+ self._version = pip_version
+ self._version_string = version_segment
+ self._use_sudo = pip_sudo
+ self._use_user = pip_user
+ self._virtual_env = pip_virtual_env
+ self._install_dir = pip_install_dir
+
+ def _autodetect_pip(self):
+ import os
+ python_command = sys.executable
+ binary_dir = os.path.dirname(python_command)
+
+ pip_command = os.path.join(binary_dir, "pip")
+ if sys.platform == "win32":
+ # Windows is a bit special... first of all the file will be called pip.exe, not just pip, and secondly
+ # for a non-virtualenv install (e.g. global install) the pip binary will not be located in the
+ # same folder as python.exe, but in a subfolder Scripts, e.g.
+ #
+ # C:\Python2.7\
+ # |- python.exe
+ # `- Scripts
+ # `- pip.exe
+
+ # virtual env?
+ pip_command = os.path.join(binary_dir, "pip.exe")
+
+ if not os.path.isfile(pip_command):
+ # nope, let's try the Scripts folder then
+ scripts_dir = os.path.join(binary_dir, "Scripts")
+ if os.path.isdir(scripts_dir):
+ pip_command = os.path.join(scripts_dir, "pip.exe")
+
+ if not os.path.isfile(pip_command) or not os.access(pip_command, os.X_OK):
+ pip_command = None
+
+ return pip_command
+
+ def _get_pip_version(self, pip_command):
+ if not self.ignore_cache and pip_command in _cache["version"]:
+ self._logger.debug("Using cached pip version information for {}".format(pip_command))
+ return _cache["version"][pip_command]
+
+ sarge_command = [pip_command, "--version"]
+ p = sarge.run(sarge_command, stdout=sarge.Capture(), stderr=sarge.Capture())
+
+ if p.returncode != 0:
+ self._logger.warn("Error while trying to run pip --version: {}".format(p.stderr.text))
+ return None, None
+
+ output = p.stdout.text
+ # output should look something like this:
+ #
+ # pip from ()
+ #
+ # we'll just split on whitespace and then try to use the second entry
+
+ if not output.startswith("pip"):
+ self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output))
+
+ split_output = map(lambda x: x.strip(), output.split())
+ if len(split_output) < 2:
+ self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output))
+
+ version_segment = split_output[1]
+
+ try:
+ pip_version = pkg_resources.parse_version(version_segment)
+ except:
+ self._logger.exception("Error while trying to parse version string from pip command")
+ return None, None
+
+ result = pip_version, version_segment
+ _cache["version"][pip_command] = result
+ return result
+
+ pip_install_dir_regex = re.compile("^\s*!!! PIP_INSTALL_DIR=(.*)\s*$", re.MULTILINE)
+ pip_virtual_env_regex = re.compile("^\s*!!! PIP_VIRTUAL_ENV=(True|False)\s*$", re.MULTILINE)
+ pip_writable_regex = re.compile("^\s*!!! PIP_WRITABLE=(True|False)\s*$", re.MULTILINE)
+
+ def _check_pip_setup(self, pip_command):
+ if not self.ignore_cache and pip_command in _cache["setup"]:
+ self._logger.debug("Using cached pip setup information for {}".format(pip_command))
+ return _cache["setup"][pip_command]
+
+ import os
+ testballoon = os.path.join(os.path.realpath(os.path.dirname(__file__)), "piptestballoon")
+
+ sarge_command = [pip_command, "install", ".", "--verbose"]
+ try:
+ p = sarge.run(sarge_command,
+ stdout=sarge.Capture(),
+ stderr=sarge.Capture(),
+ cwd=testballoon)
output = p.stdout.text
- # output should look something like this:
- #
- # pip from ()
- #
- # we'll just split on whitespace and then try to use the second entry
+ except:
+ self._logger.exception("Error while trying to install testballoon to figure out pip setup")
+ return False, False, False, None
+ finally:
+ sarge_command = [pip_command, "uninstall", "-y", "OctoPrint-PipTestBalloon"]
+ sarge.run(sarge_command, stdout=sarge.Capture(), stderr=sarge.Capture())
- if not output.startswith("pip"):
- self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output))
+ install_dir_match = self.__class__.pip_install_dir_regex.search(output)
+ virtual_env_match = self.__class__.pip_virtual_env_regex.search(output)
+ writable_match = self.__class__.pip_writable_regex.search(output)
- split_output = map(lambda x: x.strip(), output.split())
- if len(split_output) < 2:
- self._logger.warn("pip command returned unparseable output, can't determine version: {}".format(output))
+ if install_dir_match and virtual_env_match and writable_match:
+ install_dir = install_dir_match.group(1)
+ virtual_env = virtual_env_match.group(1) == "True"
+ writable = writable_match.group(1) == "True"
- version_segment = split_output[1]
-
- from pkg_resources import parse_version
- try:
- pip_version = parse_version(version_segment)
- except:
- self._logger.exception("Error while trying to parse version string from pip command")
- else:
- self._logger.info("Found pip at {}, version is {}".format(pip_command, version_segment))
-
- return pip_command, pip_version
+ # ok, enable user flag, virtual env yes/no, installation dir
+ result = writable or not virtual_env, \
+ not writable and not virtual_env and site.ENABLE_USER_SITE, \
+ virtual_env, \
+ install_dir
+ _cache["setup"][pip_command] = result
+ return result
+ else:
+ self._logger.debug("Could not detect desired output from testballoon install, got this instead: {}".format(" ".join(sarge_command), output))
+ return False, False, False, None
diff --git a/src/octoprint/util/piptestballoon/setup.py b/src/octoprint/util/piptestballoon/setup.py
new file mode 100644
index 000000000..7e0036b78
--- /dev/null
+++ b/src/octoprint/util/piptestballoon/setup.py
@@ -0,0 +1,30 @@
+from setuptools import setup
+
+def run_checks():
+ from distutils.command.install import install as cmd_install
+ from distutils.dist import Distribution
+ import sys
+ import os
+
+ cmd = cmd_install(Distribution())
+ cmd.finalize_options()
+
+ install_dir = cmd.install_lib
+ virtual_env = hasattr(sys, "real_prefix")
+ writable = os.access(install_dir, os.W_OK)
+
+ print("!!! PIP_INSTALL_DIR={}".format(install_dir))
+ print("!!! PIP_VIRTUAL_ENV={}".format(virtual_env))
+ print("!!! PIP_WRITABLE={}".format(writable))
+ sys.stdout.flush()
+
+def parameters():
+ run_checks()
+
+ return dict(
+ name="OctoPrint-PipTestBalloon",
+ version="1.0",
+ description="Just a test balloon to check a couple of pip related settings"
+ )
+
+setup(**parameters())
diff --git a/src/octoprint_setuptools/__init__.py b/src/octoprint_setuptools/__init__.py
index 6ec33e2a4..f683e2e36 100644
--- a/src/octoprint_setuptools/__init__.py
+++ b/src/octoprint_setuptools/__init__.py
@@ -444,7 +444,7 @@ def get_babel_commandclasses(pot_file=None,
def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1", description="TODO", author="TODO",
mail="todo@example.com", url="TODO", license="AGPLv3", source_folder=".", additional_data=None,
additional_packages=None, ignored_packages=None, requires=None, extra_requires=None,
- cmdclass=None, eggs=None, package=None):
+ cmdclass=None, eggs=None, package=None, dependency_links=None):
import pkg_resources
if package is None:
@@ -459,6 +459,9 @@ def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1"
if ignored_packages is None:
ignored_packages = list()
+ if dependency_links is None:
+ dependency_links = list()
+
if requires is None:
requires = ["OctoPrint"]
if not isinstance(requires, list):
@@ -524,6 +527,7 @@ def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1"
install_requires=requires,
extras_require=extra_requires,
+ dependency_links=dependency_links,
# Hook the plugin into the "octoprint.plugin" entry point, mapping the plugin_identifier to the plugin_package.
# That way OctoPrint will be able to find the plugin and load it.
diff --git a/tests/filemanager/__init__.py b/tests/filemanager/__init__.py
index 65f330577..92a8db729 100644
--- a/tests/filemanager/__init__.py
+++ b/tests/filemanager/__init__.py
@@ -8,4 +8,3 @@ from __future__ import absolute_import
__author__ = "Gina Häußge "
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
-
diff --git a/tests/filemanager/test_filemanager.py b/tests/filemanager/test_filemanager.py
index 110df373f..96ac277c7 100644
--- a/tests/filemanager/test_filemanager.py
+++ b/tests/filemanager/test_filemanager.py
@@ -13,6 +13,98 @@ import mock
import octoprint.filemanager
import octoprint.filemanager.util
+class FilemanagerMethodTest(unittest.TestCase):
+
+ def setUp(self):
+ # mock plugin manager
+ self.plugin_manager_patcher = mock.patch("octoprint.plugin.plugin_manager")
+ self.plugin_manager_getter = self.plugin_manager_patcher.start()
+
+ self.plugin_manager = mock.MagicMock()
+
+ hook_extensions = dict(
+ some_plugin=lambda: dict(dict(machinecode=dict(foo=["foo", "f"]))),
+ other_plugin=lambda: dict(dict(model=dict(amf=["amf"]))),
+ mime_map=lambda: dict(
+ mime_map=dict(
+ mime_map_yes=octoprint.filemanager.ContentTypeMapping(["mime_map_yes"], "application/mime_map_yes")
+ )
+ ),
+ mime_detect=lambda: dict(
+ dict(
+ machinecode=dict(
+ mime_detect_yes=octoprint.filemanager.ContentTypeDetector(["mime_detect_yes"], lambda x: "application/mime_detect_yes"),
+ mime_detect_no=octoprint.filemanager.ContentTypeDetector(["mime_detect_no"], lambda x: None)
+ )
+ )
+ )
+ )
+ self.plugin_manager.get_hooks.return_value = hook_extensions
+
+ self.plugin_manager_getter.return_value = self.plugin_manager
+
+ def tearDown(self):
+ self.plugin_manager_patcher.stop()
+
+ def test_full_extension_tree(self):
+ full = octoprint.filemanager.full_extension_tree()
+ self.assertTrue("machinecode" in full)
+ self.assertTrue("gcode" in full["machinecode"])
+ self.assertTrue(isinstance(full["machinecode"]["gcode"], octoprint.filemanager.ContentTypeMapping))
+ self.assertItemsEqual(["gcode", "gco", "g"], full["machinecode"]["gcode"].extensions)
+ self.assertTrue("foo" in full["machinecode"])
+ self.assertTrue(isinstance(full["machinecode"]["foo"], list))
+ self.assertItemsEqual(["f", "foo"], full["machinecode"]["foo"])
+
+ self.assertTrue("model" in full)
+ self.assertTrue("stl" in full["model"])
+ self.assertTrue(isinstance(full["model"]["stl"], octoprint.filemanager.ContentTypeMapping))
+ self.assertItemsEqual(["stl"], full["model"]["stl"].extensions)
+ self.assertTrue("amf" in full["model"])
+ self.assertTrue(isinstance(full["model"]["amf"], list))
+ self.assertItemsEqual(["amf"], full["model"]["amf"])
+
+ def test_get_mimetype(self):
+ self.assertEquals(octoprint.filemanager.get_mime_type("foo.stl"), "application/sla")
+ self.assertEquals(octoprint.filemanager.get_mime_type("foo.gcode"), "text/plain")
+ self.assertEquals(octoprint.filemanager.get_mime_type("foo.unknown"), "application/octet-stream")
+ self.assertEquals(octoprint.filemanager.get_mime_type("foo.mime_map_yes"), "application/mime_map_yes")
+ self.assertEquals(octoprint.filemanager.get_mime_type("foo.mime_map_no"), "application/octet-stream")
+ self.assertEquals(octoprint.filemanager.get_mime_type("foo.mime_detect_yes"), "application/mime_detect_yes")
+ self.assertEquals(octoprint.filemanager.get_mime_type("foo.mime_detect_no"), "application/octet-stream")
+
+ def test_valid_file_type(self):
+ self.assertTrue(octoprint.filemanager.valid_file_type("foo.stl", type="model"))
+ self.assertTrue(octoprint.filemanager.valid_file_type("foo.stl", type="stl"))
+ self.assertFalse(octoprint.filemanager.valid_file_type("foo.stl", type="machinecode"))
+ self.assertTrue(octoprint.filemanager.valid_file_type("foo.foo", type="machinecode"))
+ self.assertTrue(octoprint.filemanager.valid_file_type("foo.foo", type="foo"))
+ self.assertTrue(octoprint.filemanager.valid_file_type("foo.foo"))
+ self.assertTrue(octoprint.filemanager.valid_file_type("foo.mime_map_yes"))
+ self.assertTrue(octoprint.filemanager.valid_file_type("foo.mime_detect_yes"))
+ self.assertFalse(octoprint.filemanager.valid_file_type("foo.unknown"))
+
+ def test_get_file_type(self):
+ self.assertEquals(["machinecode", "gcode"], octoprint.filemanager.get_file_type("foo.gcode"))
+ self.assertEquals(["machinecode", "gcode"], octoprint.filemanager.get_file_type("foo.gco"))
+ self.assertEquals(["machinecode", "foo"], octoprint.filemanager.get_file_type("foo.f"))
+ self.assertEquals(["model", "stl"], octoprint.filemanager.get_file_type("foo.stl"))
+ self.assertEquals(["model", "amf"], octoprint.filemanager.get_file_type("foo.amf"))
+ self.assertIsNone(octoprint.filemanager.get_file_type("foo.unknown"))
+
+ def test_hook_failure(self):
+ def hook():
+ raise RuntimeError("Boo!")
+ self.plugin_manager.get_hooks.return_value = dict(hook=hook)
+
+ with mock.patch("octoprint.filemanager.logging") as patched_logging:
+ logger = mock.MagicMock()
+ patched_logging.getLogger.return_value = logger
+
+ octoprint.filemanager.get_all_extensions()
+
+ self.assertEquals(1, len(logger.mock_calls))
+
class FileManagerTest(unittest.TestCase):
def setUp(self):
@@ -109,13 +201,13 @@ class FileManagerTest(unittest.TestCase):
self.assertEquals(metadata, expected)
self.local_storage.get_metadata.assert_called_once_with("test.file")
- @mock.patch("__builtin__.open", new_callable=mock.mock_open)
+ @mock.patch("octoprint.filemanager.util.atomic_write")
@mock.patch("io.FileIO")
@mock.patch("shutil.copyfileobj")
@mock.patch("os.remove")
@mock.patch("tempfile.NamedTemporaryFile")
@mock.patch("time.time", side_effect=[1411979916.422, 1411979932.116])
- def test_slice(self, mocked_time, mocked_tempfile, mocked_os, mocked_shutil, mocked_fileio, mocked_open):
+ def test_slice(self, mocked_time, mocked_tempfile, mocked_os, mocked_shutil, mocked_fileio, mocked_atomic_write):
callback = mock.MagicMock()
callback_args = ("one", "two", "three")
@@ -187,8 +279,8 @@ class FileManagerTest(unittest.TestCase):
self.local_storage.add_file.assert_called_once_with("dest.file", mock.ANY, printer_profile=expected_printer_profile, allow_overwrite=True, links=expected_links)
# assert that the generated gcode was manipulated as required
- expected_open_calls = [mock.call("prefix/dest.file", "wb")]
- self.assertEquals(mocked_open.call_args_list, expected_open_calls)
+ expected_atomic_write_calls = [mock.call("prefix/dest.file", "wb")]
+ self.assertEquals(mocked_atomic_write.call_args_list, expected_atomic_write_calls)
#mocked_open.return_value.write.assert_called_once_with(";Generated from source.file aabbccddeeff\r")
# assert that shutil was asked to copy the concatenated multistream
@@ -259,4 +351,4 @@ class FileManagerTest(unittest.TestCase):
mocked_os.assert_called_once_with("tmp.file")
# assert that time.time was only called once
- mocked_time.assert_called_once()
+ self.assertEqual(mocked_time.call_count, 1)
diff --git a/tests/filemanager/test_localstorage.py b/tests/filemanager/test_localstorage.py
index 87bc9b9c2..45666a015 100644
--- a/tests/filemanager/test_localstorage.py
+++ b/tests/filemanager/test_localstorage.py
@@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import unittest
import os
import mock
+import os.path
from ddt import ddt, unpack, data
@@ -41,7 +42,7 @@ class LocalStorageTest(unittest.TestCase):
def setUp(self):
import tempfile
- self.basefolder = tempfile.mkdtemp()
+ self.basefolder = os.path.realpath(os.path.abspath(tempfile.mkdtemp()))
self.storage = octoprint.filemanager.storage.LocalFileStorage(self.basefolder)
# mock file manager module
diff --git a/tests/plugin/_plugins/another_ordered_hook_plugin.py b/tests/plugin/_plugins/another_ordered_hook_plugin.py
new file mode 100644
index 000000000..64431c2ba
--- /dev/null
+++ b/tests/plugin/_plugins/another_ordered_hook_plugin.py
@@ -0,0 +1,6 @@
+def callback(*args, **kwargs):
+ pass
+
+__plugin_hooks__ = {
+ "some.ordered.callback": (callback, 100)
+}
diff --git a/tests/plugin/_plugins/hook_plugin.py b/tests/plugin/_plugins/hook_plugin.py
index 03b1057f9..7aeb1b300 100644
--- a/tests/plugin/_plugins/hook_plugin.py
+++ b/tests/plugin/_plugins/hook_plugin.py
@@ -7,4 +7,7 @@ def hook_startup():
__plugin_name__ = "Hook Plugin"
__plugin_description__ = "Test hook plugin"
-__plugin_hooks__ = {'octoprint.core.startup': hook_startup}
\ No newline at end of file
+__plugin_hooks__ = {
+ 'octoprint.core.startup': hook_startup,
+ 'some.ordered.callback': hook_startup
+}
diff --git a/tests/plugin/_plugins/mixed_plugin/__init__.py b/tests/plugin/_plugins/mixed_plugin/__init__.py
index aed5a5edc..ed651173c 100644
--- a/tests/plugin/_plugins/mixed_plugin/__init__.py
+++ b/tests/plugin/_plugins/mixed_plugin/__init__.py
@@ -9,9 +9,13 @@ import octoprint.plugin
class TestMixedPlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.SettingsPlugin):
- pass
+ def get_sorting_key(self, context=None):
+ if context == "sorting_test":
+ return 100
+ else:
+ return None
__plugin_name__ = "Mixed Plugin"
__plugin_description__ = "Test mixed plugin"
-__plugin_implementation__ = TestMixedPlugin()
\ No newline at end of file
+__plugin_implementation__ = TestMixedPlugin()
diff --git a/tests/plugin/_plugins/one_ordered_hook_plugin.py b/tests/plugin/_plugins/one_ordered_hook_plugin.py
new file mode 100644
index 000000000..3d68dcd63
--- /dev/null
+++ b/tests/plugin/_plugins/one_ordered_hook_plugin.py
@@ -0,0 +1,6 @@
+def callback(*args, **kwargs):
+ pass
+
+__plugin_hooks__ = {
+ "some.ordered.callback": (callback, 10)
+}
diff --git a/tests/plugin/_plugins/startup_plugin.py b/tests/plugin/_plugins/startup_plugin.py
index b75ca8518..50e438048 100644
--- a/tests/plugin/_plugins/startup_plugin.py
+++ b/tests/plugin/_plugins/startup_plugin.py
@@ -4,9 +4,13 @@ import octoprint.plugin
class TestStartupPlugin(octoprint.plugin.StartupPlugin):
- pass
+ def get_sorting_key(self, context=None):
+ if context == "sorting_test":
+ return 10
+ else:
+ return None
__plugin_name__ = "Startup Plugin"
__plugin_description__ = "Test startup plugin"
-__plugin_implementation__ = TestStartupPlugin()
\ No newline at end of file
+__plugin_implementation__ = TestStartupPlugin()
diff --git a/tests/plugin/test_core.py b/tests/plugin/test_core.py
index 0667785d1..b76110afb 100644
--- a/tests/plugin/test_core.py
+++ b/tests/plugin/test_core.py
@@ -23,8 +23,8 @@ class PluginTestCase(unittest.TestCase):
self.plugin_manager.initialize_implementations()
def test_plugin_loading(self):
- self.assertEquals(5, len(self.plugin_manager.enabled_plugins))
- self.assertEquals(1, len(self.plugin_manager.plugin_hooks))
+ self.assertEquals(7, len(self.plugin_manager.enabled_plugins))
+ self.assertEquals(2, len(self.plugin_manager.plugin_hooks))
self.assertEquals(4, len(self.plugin_manager.plugin_implementations))
self.assertEquals(3, len(self.plugin_manager.plugin_implementations_by_type))
@@ -32,6 +32,10 @@ class PluginTestCase(unittest.TestCase):
self.assertTrue("octoprint.core.startup" in self.plugin_manager.plugin_hooks)
self.assertEquals(1, len(self.plugin_manager.plugin_hooks["octoprint.core.startup"]))
+ # ordered hook plugins
+ self.assertTrue("some.ordered.callback" in self.plugin_manager.plugin_hooks)
+ self.assertEquals(3, len(self.plugin_manager.plugin_hooks["some.ordered.callback"]))
+
# TestStartupPlugin & TestMixedPlugin
self.assertTrue(octoprint.plugin.StartupPlugin in self.plugin_manager.plugin_implementations_by_type)
self.assertEquals(2, len(self.plugin_manager.plugin_implementations_by_type[octoprint.plugin.StartupPlugin]))
@@ -119,18 +123,31 @@ class PluginTestCase(unittest.TestCase):
hooks = self.plugin_manager.get_hooks("octoprint.printing.print")
self.assertEquals(0, len(hooks))
- def test_get_implementation(self):
+ def test_sorted_hooks(self):
+ hooks = self.plugin_manager.get_hooks("some.ordered.callback")
+ self.assertEquals(3, len(hooks))
+ self.assertListEqual(["one_ordered_hook_plugin", "another_ordered_hook_plugin", "hook_plugin"], hooks.keys())
+
+ def test_get_implementations(self):
implementations = self.plugin_manager.get_implementations(octoprint.plugin.StartupPlugin)
- self.assertEquals(2, len(implementations)) # startup_plugin, mixed_plugin
+ self.assertListEqual(["mixed_plugin", "startup_plugin"], map(lambda x: x._identifier, implementations))
implementations = self.plugin_manager.get_implementations(octoprint.plugin.SettingsPlugin)
- self.assertEquals(2, len(implementations)) # settings_plugin, mixed_plugin
+ self.assertListEqual(["mixed_plugin", "settings_plugin"], map(lambda x: x._identifier, implementations))
implementations = self.plugin_manager.get_implementations(octoprint.plugin.StartupPlugin, octoprint.plugin.SettingsPlugin)
- self.assertEquals(1, len(implementations)) # mixed_plugin
+ self.assertListEqual(["mixed_plugin"], map(lambda x: x._identifier, implementations))
implementations = self.plugin_manager.get_implementations(octoprint.plugin.AssetPlugin)
- self.assertEquals(1, len(implementations)) # deprecated_plugin, but only first implementation!
+ self.assertListEqual(["deprecated_plugin"], map(lambda x: x._identifier, implementations))
+
+ def test_get_filtered_implementations(self):
+ implementations = self.plugin_manager.get_filtered_implementations(lambda x: x._identifier.startswith("startup"), octoprint.plugin.StartupPlugin)
+ self.assertEquals(1, len(implementations))
+
+ def test_get_sorted_implementations(self):
+ implementations = self.plugin_manager.get_implementations(octoprint.plugin.StartupPlugin, sorting_context="sorting_test")
+ self.assertListEqual(["startup_plugin", "mixed_plugin"], map(lambda x: x._identifier, implementations))
def test_client_registration(self):
def test_client(*args, **kwargs):
diff --git a/tests/plugin/test_types_blueprint.py b/tests/plugin/test_types_blueprint.py
new file mode 100644
index 000000000..17df406c3
--- /dev/null
+++ b/tests/plugin/test_types_blueprint.py
@@ -0,0 +1,139 @@
+import unittest
+import mock
+
+import octoprint.plugin
+
+class BlueprintPluginTest(unittest.TestCase):
+
+ def setUp(self):
+ self.basefolder = "/some/funny/basefolder"
+
+ self.plugin = octoprint.plugin.BlueprintPlugin()
+ self.plugin._basefolder = self.basefolder
+
+ class MyAssetPlugin(octoprint.plugin.BlueprintPlugin, octoprint.plugin.AssetPlugin):
+ def get_asset_folder(self):
+ return "/some/asset/folder"
+
+ class MyTemplatePlugin(octoprint.plugin.BlueprintPlugin, octoprint.plugin.TemplatePlugin):
+ def get_template_folder(self):
+ return "/some/template/folder"
+
+ self.assetplugin = MyAssetPlugin()
+ self.assetplugin._basefolder = self.basefolder
+
+ self.templateplugin = MyTemplatePlugin()
+ self.templateplugin._basefolder = self.basefolder
+
+ def test_route(self):
+
+ def test_method():
+ pass
+
+ octoprint.plugin.BlueprintPlugin.route("/test/method", methods=["GET"])(test_method)
+ octoprint.plugin.BlueprintPlugin.route("/test/method/{foo}", methods=["PUT"])(test_method)
+
+ self.assertTrue(hasattr(test_method, "_blueprint_rules"))
+ self.assertTrue("test_method" in test_method._blueprint_rules)
+ self.assertTrue(len(test_method._blueprint_rules["test_method"]) == 2)
+ self.assertListEqual(test_method._blueprint_rules["test_method"], [
+ ("/test/method", dict(methods=["GET"])),
+ ("/test/method/{foo}", dict(methods=["PUT"]))
+ ])
+
+ def test_errorhandler(self):
+
+ def test_method():
+ pass
+
+ octoprint.plugin.BlueprintPlugin.errorhandler(404)(test_method)
+
+ self.assertTrue(hasattr(test_method, "_blueprint_error_handler"))
+ self.assertTrue("test_method" in test_method._blueprint_error_handler)
+ self.assertTrue(len(test_method._blueprint_error_handler["test_method"]) == 1)
+ self.assertListEqual(test_method._blueprint_error_handler["test_method"], [
+ 404
+ ])
+
+ def test_get_blueprint_kwargs(self):
+ import os
+ expected = dict(
+ static_folder=os.path.join(self.basefolder, "static"),
+ template_folder=os.path.join(self.basefolder, "templates")
+ )
+
+ result = self.plugin.get_blueprint_kwargs()
+
+ self.assertEquals(result, expected)
+
+ def test_get_blueprint_kwargs_assetplugin(self):
+ import os
+ expected = dict(
+ static_folder=self.assetplugin.get_asset_folder(),
+ template_folder=os.path.join(self.basefolder, "templates")
+ )
+
+ result = self.assetplugin.get_blueprint_kwargs()
+
+ self.assertEquals(result, expected)
+
+ def test_get_blueprint_kwargs_templateplugin(self):
+ import os
+ expected = dict(
+ static_folder=os.path.join(self.basefolder, "static"),
+ template_folder=self.templateplugin.get_template_folder()
+ )
+
+ result = self.templateplugin.get_blueprint_kwargs()
+
+ self.assertEquals(result, expected)
+
+ def test_get_blueprint(self):
+ import os
+ expected_kwargs = dict(
+ static_folder=os.path.join(self.basefolder, "static"),
+ template_folder=os.path.join(self.basefolder, "templates")
+ )
+
+ class MyPlugin(octoprint.plugin.BlueprintPlugin):
+
+ @octoprint.plugin.BlueprintPlugin.route("/some/path", methods=["GET"])
+ def route_method(self):
+ pass
+
+ @octoprint.plugin.BlueprintPlugin.errorhandler(404)
+ def errorhandler_method(self):
+ pass
+
+ @octoprint.plugin.BlueprintPlugin.route("/hidden/path", methods=["GET"])
+ def _hidden_method(self):
+ pass
+
+ plugin = MyPlugin()
+ plugin._basefolder = self.basefolder
+ plugin._identifier = "myplugin"
+
+ with mock.patch("flask.Blueprint") as MockBlueprint:
+ blueprint = mock.MagicMock()
+ MockBlueprint.return_value = blueprint
+
+ errorhandler = mock.MagicMock()
+ blueprint.errorhandler.return_value = errorhandler
+
+ result = plugin.get_blueprint()
+
+ self.assertEquals(result, blueprint)
+
+ MockBlueprint.assert_called_once_with("plugin.myplugin", "myplugin", **expected_kwargs)
+ blueprint.add_url_rule.assert_called_once_with("/some/path", "route_method", view_func=plugin.route_method, methods=["GET"])
+
+ blueprint.errorhandler.assert_called_once_with(404)
+ errorhandler.assert_called_once_with(plugin.errorhandler_method)
+
+ def test_get_blueprint_cached(self):
+ blueprint = mock.MagicMock()
+ self.plugin._blueprint = blueprint
+
+ result = self.plugin.get_blueprint()
+
+ self.assertEquals(blueprint, result)
diff --git a/tests/plugin/test_types_settings.py b/tests/plugin/test_types_settings.py
new file mode 100644
index 000000000..31a53df7b
--- /dev/null
+++ b/tests/plugin/test_types_settings.py
@@ -0,0 +1,313 @@
+import unittest
+import mock
+
+import octoprint.plugin
+
+class TestSettingsPlugin(unittest.TestCase):
+
+ def setUp(self):
+ self.settings = mock.MagicMock()
+
+ self.plugin = octoprint.plugin.SettingsPlugin()
+ self.plugin._settings = self.settings
+
+ def test_on_settings_cleanup(self):
+ """Tests that after cleanup only minimal config is left in storage."""
+
+ ### setup
+
+ # settings defaults
+ defaults = dict(
+ foo=dict(
+ a=1,
+ b=2,
+ l1=["some", "list"],
+ l2=["another", "list"]
+ ),
+ bar=True,
+ fnord=None
+ )
+ self.plugin.get_settings_defaults = mock.MagicMock()
+ self.plugin.get_settings_defaults.return_value = defaults
+
+ # stored config, containing one redundant entry (bar=True, same as default)
+ in_config = dict(
+ foo=dict(
+ l1=["some", "other", "list"],
+ l2=["another", "list"],
+ l3=["a", "third", "list"]
+ ),
+ bar=True,
+ fnord=dict(
+ c=3,
+ d=4
+ )
+ )
+ self.settings.get_all_data.return_value = in_config
+
+ ### execute
+
+ self.plugin.on_settings_cleanup()
+
+ ### assert
+
+ # minimal config (current without redundant value) should have been set
+ expected = dict(
+ foo=dict(
+ l1=["some", "other", "list"],
+ l3=["a", "third", "list"]
+ ),
+ fnord=dict(
+ c=3,
+ d=4
+ )
+ )
+ self.settings.set.assert_called_once_with([], expected)
+
+ def test_on_settings_cleanup_configversion(self):
+ """Tests that set config version is always left stored."""
+
+ ### setup
+
+ defaults = dict(
+ foo="fnord"
+ )
+ self.plugin.get_settings_defaults = mock.MagicMock()
+ self.plugin.get_settings_defaults.return_value = defaults
+
+ in_config = dict(
+ _config_version=1,
+ foo="fnord"
+ )
+ self.settings.get_all_data.return_value = in_config
+
+ ### execute
+
+ self.plugin.on_settings_cleanup()
+
+ ### assert
+
+ # minimal config incl. config version should have been set
+ self.settings.set.assert_called_once_with([], dict(_config_version=1))
+
+ def test_on_settings_cleanup_noconfigversion(self):
+ """Tests that config versions of None are cleaned from stored data."""
+
+ ### setup
+
+ defaults = dict(
+ foo="bar"
+ )
+ self.plugin.get_settings_defaults = mock.MagicMock()
+ self.plugin.get_settings_defaults.return_value = defaults
+
+ # stored config version is None
+ in_config = dict(
+ _config_version=None,
+ foo="fnord"
+ )
+ self.settings.get_all_data.return_value = in_config
+
+ ### execute
+
+ self.plugin.on_settings_cleanup()
+
+ ### assert
+
+ # minimal config without config version should have been set
+ self.settings.set.assert_called_once_with([], dict(foo="fnord"))
+
+ def test_on_settings_cleanup_emptydiff(self):
+ """Tests that settings are cleaned up if the diff data <-> defaults is empty."""
+
+ ### setup
+
+ defaults = dict(
+ foo="bar"
+ )
+ self.plugin.get_settings_defaults = mock.MagicMock()
+ self.plugin.get_settings_defaults.return_value = defaults
+
+ # current stored config, same as defaults
+ in_config = dict(
+ foo="bar"
+ )
+ self.settings.get_all_data.return_value = in_config
+
+ ### execute
+
+ self.plugin.on_settings_cleanup()
+
+ ### assert
+
+ # should have been cleared
+ self.settings.clean_all_data.assert_called_once_with()
+
+ def test_on_settings_cleanup_nosuchpath(self):
+ """Tests that no processing is done if nothing is stored in settings."""
+
+ from octoprint.settings import NoSuchSettingsPath
+
+ ### setup
+
+ # simulate no settings stored in config.yaml
+ self.settings.get_all_data.side_effect = NoSuchSettingsPath()
+
+ ### execute
+
+ self.plugin.on_settings_cleanup()
+
+ ### assert
+
+ # only get_all_data should have been called
+ self.settings.get_all_data.assert_called_once_with(merged=False, incl_defaults=False, error_on_path=True)
+ self.assertTrue(len(self.settings.method_calls) == 1)
+
+ def test_on_settings_cleanup_none(self):
+ """Tests the None entries in config get cleaned up."""
+
+ ### setup
+
+ # simulate None entry in config.yaml
+ self.settings.get_all_data.return_value = None
+
+ ### execute
+
+ self.plugin.on_settings_cleanup()
+
+ ### assert
+
+ # should have been cleaned
+ self.settings.clean_all_data.assert_called_once_with()
+
+ def test_on_settings_save(self):
+ """Tests that only the diff is saved."""
+
+ ### setup
+
+ current = dict(
+ foo="bar"
+ )
+ self.settings.get_all_data.return_value = current
+
+ defaults = dict(
+ foo="foo",
+ bar=dict(
+ a=1,
+ b=2
+ )
+ )
+ self.plugin.get_settings_defaults = mock.MagicMock()
+ self.plugin.get_settings_defaults.return_value = defaults
+
+ ### execute
+
+ data = dict(
+ foo="fnord",
+ bar=dict(
+ a=1,
+ b=2
+ )
+ )
+ diff = self.plugin.on_settings_save(data)
+
+ ### assert
+
+ # the minimal diff should have been saved
+ expected = dict(
+ foo="fnord"
+ )
+ self.settings.set.assert_called_once_with([], expected)
+
+ self.assertEquals(diff, expected)
+
+ def test_on_settings_save_nodiff(self):
+ """Tests that data is cleaned if there's not difference between data and defaults."""
+
+ ### setup
+
+ self.settings.get_all_data.return_value = None
+
+ defaults = dict(
+ foo="bar",
+ bar=dict(
+ a=1,
+ b=2,
+ l=["some", "list"]
+ )
+ )
+ self.plugin.get_settings_defaults = mock.MagicMock()
+ self.plugin.get_settings_defaults.return_value = defaults
+
+ ### execute
+
+ data = dict(foo="bar")
+ diff = self.plugin.on_settings_save(data)
+
+ ### assert
+
+ self.settings.clean_all_data.assert_called_once_with()
+ self.assertEquals(diff, dict())
+
+ def test_on_settings_save_configversion(self):
+ """Tests that saved data gets stripped config version and set correct one."""
+
+ ### setup
+
+ self.settings.get_all_data.return_value = None
+
+ defaults = dict(
+ foo="bar"
+ )
+ self.plugin.get_settings_defaults = mock.MagicMock()
+ self.plugin.get_settings_defaults.return_value = defaults
+
+ version = 1
+ self.plugin.get_settings_version = mock.MagicMock()
+ self.plugin.get_settings_version.return_value = version
+
+ ### execute
+
+ data = dict(_config_version=None, foo="bar")
+ diff = self.plugin.on_settings_save(data)
+
+ ### assert
+
+ expected_diff = dict()
+ expected_set = dict(_config_version=version)
+
+ # while there was no diff, we should still have saved the new config version
+ self.settings.set.assert_called_once_with([], expected_set)
+
+ self.assertEquals(diff, expected_diff)
+
+ def test_on_settings_load(self):
+ """Tests that on_settings_load returns what's stored in the config, without config version."""
+
+ ### setup
+
+ # current data incl. config version
+ current = dict(
+ _config_version=3,
+ foo="bar",
+ fnord=dict(
+ a=1,
+ b=2,
+ l=["some", "list"]
+ )
+ )
+
+ # expected is current without _config_version - we make the copy now
+ # since our current dict will be modified by the test
+ expected = dict(current)
+ del expected["_config_version"]
+
+ self.settings.get_all_data.return_value = expected
+
+ ### execute
+
+ result = self.plugin.on_settings_load()
+
+ ### assert
+
+ self.assertEquals(result, expected)
diff --git a/tests/slicing/test_slicingmanager.py b/tests/slicing/test_slicingmanager.py
index c91b4dd5c..e0d3ea9f2 100644
--- a/tests/slicing/test_slicingmanager.py
+++ b/tests/slicing/test_slicingmanager.py
@@ -142,11 +142,10 @@ class TestSlicingManager(unittest.TestCase):
# assert that temporary profile was created properly
self.slicer_plugin.save_slicer_profile.assert_called_once_with("tmp.file", default_profile, overrides=overrides)
-
# assert that slicing thread was created properly
mocked_thread.assert_called_once_with(target=mock.ANY, args=(self.slicer_plugin, source_path, dest_path, profile_name, overrides, printer_profile, position, callback, callback_args, callback_kwargs))
self.assertTrue(mock_thread.mock.daemon)
- mock_thread.mock.start.assert_called_once()
+ self.assertEqual(mock_thread.mock.start.call_count, 1)
# assert that slicer was called correctly
self.slicer_plugin.do_slice.assert_called_once_with(source_path, printer_profile, machinecode_path=dest_path, profile_path="tmp.file", position=position, on_progress=None, on_progress_args=None, on_progress_kwargs=None)
diff --git a/tests/static/js/lib/qunit-1.18.0.css b/tests/static/js/lib/qunit-1.18.0.css
new file mode 100644
index 000000000..f1dcd4e1c
--- /dev/null
+++ b/tests/static/js/lib/qunit-1.18.0.css
@@ -0,0 +1,291 @@
+/*!
+ * QUnit 1.18.0
+ * http://qunitjs.com/
+ *
+ * Copyright jQuery Foundation and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2015-04-03T10:23Z
+ */
+
+/** Font Family and Sizes */
+
+#qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult {
+ font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif;
+}
+
+#qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; }
+#qunit-tests { font-size: smaller; }
+
+
+/** Resets */
+
+#qunit-tests, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult, #qunit-modulefilter {
+ margin: 0;
+ padding: 0;
+}
+
+
+/** Header */
+
+#qunit-header {
+ padding: 0.5em 0 0.5em 1em;
+
+ color: #8699A4;
+ background-color: #0D3349;
+
+ font-size: 1.5em;
+ line-height: 1em;
+ font-weight: 400;
+
+ border-radius: 5px 5px 0 0;
+}
+
+#qunit-header a {
+ text-decoration: none;
+ color: #C2CCD1;
+}
+
+#qunit-header a:hover,
+#qunit-header a:focus {
+ color: #FFF;
+}
+
+#qunit-testrunner-toolbar label {
+ display: inline-block;
+ padding: 0 0.5em 0 0.1em;
+}
+
+#qunit-banner {
+ height: 5px;
+}
+
+#qunit-testrunner-toolbar {
+ padding: 0.5em 1em 0.5em 1em;
+ color: #5E740B;
+ background-color: #EEE;
+ overflow: hidden;
+}
+
+#qunit-userAgent {
+ padding: 0.5em 1em 0.5em 1em;
+ background-color: #2B81AF;
+ color: #FFF;
+ text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px;
+}
+
+#qunit-modulefilter-container {
+ float: right;
+ padding: 0.2em;
+}
+
+.qunit-url-config {
+ display: inline-block;
+ padding: 0.1em;
+}
+
+.qunit-filter {
+ display: block;
+ float: right;
+ margin-left: 1em;
+}
+
+/** Tests: Pass/Fail */
+
+#qunit-tests {
+ list-style-position: inside;
+}
+
+#qunit-tests li {
+ padding: 0.4em 1em 0.4em 1em;
+ border-bottom: 1px solid #FFF;
+ list-style-position: inside;
+}
+
+#qunit-tests > li {
+ display: none;
+}
+
+#qunit-tests li.running,
+#qunit-tests li.pass,
+#qunit-tests li.fail,
+#qunit-tests li.skipped {
+ display: list-item;
+}
+
+#qunit-tests.hidepass li.running,
+#qunit-tests.hidepass li.pass {
+ visibility: hidden;
+ position: absolute;
+ width: 0px;
+ height: 0px;
+ padding: 0;
+ border: 0;
+ margin: 0;
+}
+
+#qunit-tests li strong {
+ cursor: pointer;
+}
+
+#qunit-tests li.skipped strong {
+ cursor: default;
+}
+
+#qunit-tests li a {
+ padding: 0.5em;
+ color: #C2CCD1;
+ text-decoration: none;
+}
+
+#qunit-tests li p a {
+ padding: 0.25em;
+ color: #6B6464;
+}
+#qunit-tests li a:hover,
+#qunit-tests li a:focus {
+ color: #000;
+}
+
+#qunit-tests li .runtime {
+ float: right;
+ font-size: smaller;
+}
+
+.qunit-assert-list {
+ margin-top: 0.5em;
+ padding: 0.5em;
+
+ background-color: #FFF;
+
+ border-radius: 5px;
+}
+
+.qunit-collapsed {
+ display: none;
+}
+
+#qunit-tests table {
+ border-collapse: collapse;
+ margin-top: 0.2em;
+}
+
+#qunit-tests th {
+ text-align: right;
+ vertical-align: top;
+ padding: 0 0.5em 0 0;
+}
+
+#qunit-tests td {
+ vertical-align: top;
+}
+
+#qunit-tests pre {
+ margin: 0;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+}
+
+#qunit-tests del {
+ background-color: #E0F2BE;
+ color: #374E0C;
+ text-decoration: none;
+}
+
+#qunit-tests ins {
+ background-color: #FFCACA;
+ color: #500;
+ text-decoration: none;
+}
+
+/*** Test Counts */
+
+#qunit-tests b.counts { color: #000; }
+#qunit-tests b.passed { color: #5E740B; }
+#qunit-tests b.failed { color: #710909; }
+
+#qunit-tests li li {
+ padding: 5px;
+ background-color: #FFF;
+ border-bottom: none;
+ list-style-position: inside;
+}
+
+/*** Passing Styles */
+
+#qunit-tests li li.pass {
+ color: #3C510C;
+ background-color: #FFF;
+ border-left: 10px solid #C6E746;
+}
+
+#qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; }
+#qunit-tests .pass .test-name { color: #366097; }
+
+#qunit-tests .pass .test-actual,
+#qunit-tests .pass .test-expected { color: #999; }
+
+#qunit-banner.qunit-pass { background-color: #C6E746; }
+
+/*** Failing Styles */
+
+#qunit-tests li li.fail {
+ color: #710909;
+ background-color: #FFF;
+ border-left: 10px solid #EE5757;
+ white-space: pre;
+}
+
+#qunit-tests > li:last-child {
+ border-radius: 0 0 5px 5px;
+}
+
+#qunit-tests .fail { color: #000; background-color: #EE5757; }
+#qunit-tests .fail .test-name,
+#qunit-tests .fail .module-name { color: #000; }
+
+#qunit-tests .fail .test-actual { color: #EE5757; }
+#qunit-tests .fail .test-expected { color: #008000; }
+
+#qunit-banner.qunit-fail { background-color: #EE5757; }
+
+/*** Skipped tests */
+
+#qunit-tests .skipped {
+ background-color: #EBECE9;
+}
+
+#qunit-tests .qunit-skipped-label {
+ background-color: #F4FF77;
+ display: inline-block;
+ font-style: normal;
+ color: #366097;
+ line-height: 1.8em;
+ padding: 0 0.5em;
+ margin: -0.4em 0.4em -0.4em 0;
+}
+
+/** Result */
+
+#qunit-testresult {
+ padding: 0.5em 1em 0.5em 1em;
+
+ color: #2B81AF;
+ background-color: #D2E0E6;
+
+ border-bottom: 1px solid #FFF;
+}
+#qunit-testresult .module-name {
+ font-weight: 700;
+}
+
+/** Fixture */
+
+#qunit-fixture {
+ position: absolute;
+ top: -10000px;
+ left: -10000px;
+ width: 1000px;
+ height: 1000px;
+}
diff --git a/tests/static/js/lib/qunit-1.18.0.js b/tests/static/js/lib/qunit-1.18.0.js
new file mode 100644
index 000000000..f3542ca9d
--- /dev/null
+++ b/tests/static/js/lib/qunit-1.18.0.js
@@ -0,0 +1,3828 @@
+/*!
+ * QUnit 1.18.0
+ * http://qunitjs.com/
+ *
+ * Copyright jQuery Foundation and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2015-04-03T10:23Z
+ */
+
+(function( window ) {
+
+var QUnit,
+ config,
+ onErrorFnPrev,
+ loggingCallbacks = {},
+ fileName = ( sourceFromStacktrace( 0 ) || "" ).replace( /(:\d+)+\)?/, "" ).replace( /.+\//, "" ),
+ toString = Object.prototype.toString,
+ hasOwn = Object.prototype.hasOwnProperty,
+ // Keep a local reference to Date (GH-283)
+ Date = window.Date,
+ now = Date.now || function() {
+ return new Date().getTime();
+ },
+ globalStartCalled = false,
+ runStarted = false,
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ defined = {
+ document: window.document !== undefined,
+ setTimeout: window.setTimeout !== undefined,
+ sessionStorage: (function() {
+ var x = "qunit-test-string";
+ try {
+ sessionStorage.setItem( x, x );
+ sessionStorage.removeItem( x );
+ return true;
+ } catch ( e ) {
+ return false;
+ }
+ }())
+ },
+ /**
+ * Provides a normalized error string, correcting an issue
+ * with IE 7 (and prior) where Error.prototype.toString is
+ * not properly implemented
+ *
+ * Based on http://es5.github.com/#x15.11.4.4
+ *
+ * @param {String|Error} error
+ * @return {String} error message
+ */
+ errorString = function( error ) {
+ var name, message,
+ errorString = error.toString();
+ if ( errorString.substring( 0, 7 ) === "[object" ) {
+ name = error.name ? error.name.toString() : "Error";
+ message = error.message ? error.message.toString() : "";
+ if ( name && message ) {
+ return name + ": " + message;
+ } else if ( name ) {
+ return name;
+ } else if ( message ) {
+ return message;
+ } else {
+ return "Error";
+ }
+ } else {
+ return errorString;
+ }
+ },
+ /**
+ * Makes a clone of an object using only Array or Object as base,
+ * and copies over the own enumerable properties.
+ *
+ * @param {Object} obj
+ * @return {Object} New object with only the own properties (recursively).
+ */
+ objectValues = function( obj ) {
+ var key, val,
+ vals = QUnit.is( "array", obj ) ? [] : {};
+ for ( key in obj ) {
+ if ( hasOwn.call( obj, key ) ) {
+ val = obj[ key ];
+ vals[ key ] = val === Object( val ) ? objectValues( val ) : val;
+ }
+ }
+ return vals;
+ };
+
+QUnit = {};
+
+/**
+ * Config object: Maintain internal state
+ * Later exposed as QUnit.config
+ * `config` initialized at top of scope
+ */
+config = {
+ // The queue of tests to run
+ queue: [],
+
+ // block until document ready
+ blocking: true,
+
+ // by default, run previously failed tests first
+ // very useful in combination with "Hide passed tests" checked
+ reorder: true,
+
+ // by default, modify document.title when suite is done
+ altertitle: true,
+
+ // by default, scroll to top of the page when suite is done
+ scrolltop: true,
+
+ // when enabled, all tests must call expect()
+ requireExpects: false,
+
+ // depth up-to which object will be dumped
+ maxDepth: 5,
+
+ // add checkboxes that are persisted in the query-string
+ // when enabled, the id is set to `true` as a `QUnit.config` property
+ urlConfig: [
+ {
+ id: "hidepassed",
+ label: "Hide passed tests",
+ tooltip: "Only show tests and assertions that fail. Stored as query-strings."
+ },
+ {
+ id: "noglobals",
+ label: "Check for Globals",
+ tooltip: "Enabling this will test if any test introduces new properties on the " +
+ "`window` object. Stored as query-strings."
+ },
+ {
+ id: "notrycatch",
+ label: "No try-catch",
+ tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging " +
+ "exceptions in IE reasonable. Stored as query-strings."
+ }
+ ],
+
+ // Set of all modules.
+ modules: [],
+
+ // The first unnamed module
+ currentModule: {
+ name: "",
+ tests: []
+ },
+
+ callbacks: {}
+};
+
+// Push a loose unnamed module to the modules collection
+config.modules.push( config.currentModule );
+
+// Initialize more QUnit.config and QUnit.urlParams
+(function() {
+ var i, current,
+ location = window.location || { search: "", protocol: "file:" },
+ params = location.search.slice( 1 ).split( "&" ),
+ length = params.length,
+ urlParams = {};
+
+ if ( params[ 0 ] ) {
+ for ( i = 0; i < length; i++ ) {
+ current = params[ i ].split( "=" );
+ current[ 0 ] = decodeURIComponent( current[ 0 ] );
+
+ // allow just a key to turn on a flag, e.g., test.html?noglobals
+ current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
+ if ( urlParams[ current[ 0 ] ] ) {
+ urlParams[ current[ 0 ] ] = [].concat( urlParams[ current[ 0 ] ], current[ 1 ] );
+ } else {
+ urlParams[ current[ 0 ] ] = current[ 1 ];
+ }
+ }
+ }
+
+ if ( urlParams.filter === true ) {
+ delete urlParams.filter;
+ }
+
+ QUnit.urlParams = urlParams;
+
+ // String search anywhere in moduleName+testName
+ config.filter = urlParams.filter;
+
+ if ( urlParams.maxDepth ) {
+ config.maxDepth = parseInt( urlParams.maxDepth, 10 ) === -1 ?
+ Number.POSITIVE_INFINITY :
+ urlParams.maxDepth;
+ }
+
+ config.testId = [];
+ if ( urlParams.testId ) {
+
+ // Ensure that urlParams.testId is an array
+ urlParams.testId = decodeURIComponent( urlParams.testId ).split( "," );
+ for ( i = 0; i < urlParams.testId.length; i++ ) {
+ config.testId.push( urlParams.testId[ i ] );
+ }
+ }
+
+ // Figure out if we're running the tests from a server or not
+ QUnit.isLocal = location.protocol === "file:";
+
+ // Expose the current QUnit version
+ QUnit.version = "1.18.0";
+}());
+
+// Root QUnit object.
+// `QUnit` initialized at top of scope
+extend( QUnit, {
+
+ // call on start of module test to prepend name to all tests
+ module: function( name, testEnvironment ) {
+ var currentModule = {
+ name: name,
+ testEnvironment: testEnvironment,
+ tests: []
+ };
+
+ // DEPRECATED: handles setup/teardown functions,
+ // beforeEach and afterEach should be used instead
+ if ( testEnvironment && testEnvironment.setup ) {
+ testEnvironment.beforeEach = testEnvironment.setup;
+ delete testEnvironment.setup;
+ }
+ if ( testEnvironment && testEnvironment.teardown ) {
+ testEnvironment.afterEach = testEnvironment.teardown;
+ delete testEnvironment.teardown;
+ }
+
+ config.modules.push( currentModule );
+ config.currentModule = currentModule;
+ },
+
+ // DEPRECATED: QUnit.asyncTest() will be removed in QUnit 2.0.
+ asyncTest: function( testName, expected, callback ) {
+ if ( arguments.length === 2 ) {
+ callback = expected;
+ expected = null;
+ }
+
+ QUnit.test( testName, expected, callback, true );
+ },
+
+ test: function( testName, expected, callback, async ) {
+ var test;
+
+ if ( arguments.length === 2 ) {
+ callback = expected;
+ expected = null;
+ }
+
+ test = new Test({
+ testName: testName,
+ expected: expected,
+ async: async,
+ callback: callback
+ });
+
+ test.queue();
+ },
+
+ skip: function( testName ) {
+ var test = new Test({
+ testName: testName,
+ skip: true
+ });
+
+ test.queue();
+ },
+
+ // DEPRECATED: The functionality of QUnit.start() will be altered in QUnit 2.0.
+ // In QUnit 2.0, invoking it will ONLY affect the `QUnit.config.autostart` blocking behavior.
+ start: function( count ) {
+ var globalStartAlreadyCalled = globalStartCalled;
+
+ if ( !config.current ) {
+ globalStartCalled = true;
+
+ if ( runStarted ) {
+ throw new Error( "Called start() outside of a test context while already started" );
+ } else if ( globalStartAlreadyCalled || count > 1 ) {
+ throw new Error( "Called start() outside of a test context too many times" );
+ } else if ( config.autostart ) {
+ throw new Error( "Called start() outside of a test context when " +
+ "QUnit.config.autostart was true" );
+ } else if ( !config.pageLoaded ) {
+
+ // The page isn't completely loaded yet, so bail out and let `QUnit.load` handle it
+ config.autostart = true;
+ return;
+ }
+ } else {
+
+ // If a test is running, adjust its semaphore
+ config.current.semaphore -= count || 1;
+
+ // Don't start until equal number of stop-calls
+ if ( config.current.semaphore > 0 ) {
+ return;
+ }
+
+ // throw an Error if start is called more often than stop
+ if ( config.current.semaphore < 0 ) {
+ config.current.semaphore = 0;
+
+ QUnit.pushFailure(
+ "Called start() while already started (test's semaphore was 0 already)",
+ sourceFromStacktrace( 2 )
+ );
+ return;
+ }
+ }
+
+ resumeProcessing();
+ },
+
+ // DEPRECATED: QUnit.stop() will be removed in QUnit 2.0.
+ stop: function( count ) {
+
+ // If there isn't a test running, don't allow QUnit.stop() to be called
+ if ( !config.current ) {
+ throw new Error( "Called stop() outside of a test context" );
+ }
+
+ // If a test is running, adjust its semaphore
+ config.current.semaphore += count || 1;
+
+ pauseProcessing();
+ },
+
+ config: config,
+
+ // Safe object type checking
+ is: function( type, obj ) {
+ return QUnit.objectType( obj ) === type;
+ },
+
+ objectType: function( obj ) {
+ if ( typeof obj === "undefined" ) {
+ return "undefined";
+ }
+
+ // Consider: typeof null === object
+ if ( obj === null ) {
+ return "null";
+ }
+
+ var match = toString.call( obj ).match( /^\[object\s(.*)\]$/ ),
+ type = match && match[ 1 ] || "";
+
+ switch ( type ) {
+ case "Number":
+ if ( isNaN( obj ) ) {
+ return "nan";
+ }
+ return "number";
+ case "String":
+ case "Boolean":
+ case "Array":
+ case "Date":
+ case "RegExp":
+ case "Function":
+ return type.toLowerCase();
+ }
+ if ( typeof obj === "object" ) {
+ return "object";
+ }
+ return undefined;
+ },
+
+ extend: extend,
+
+ load: function() {
+ config.pageLoaded = true;
+
+ // Initialize the configuration options
+ extend( config, {
+ stats: { all: 0, bad: 0 },
+ moduleStats: { all: 0, bad: 0 },
+ started: 0,
+ updateRate: 1000,
+ autostart: true,
+ filter: ""
+ }, true );
+
+ config.blocking = false;
+
+ if ( config.autostart ) {
+ resumeProcessing();
+ }
+ }
+});
+
+// Register logging callbacks
+(function() {
+ var i, l, key,
+ callbacks = [ "begin", "done", "log", "testStart", "testDone",
+ "moduleStart", "moduleDone" ];
+
+ function registerLoggingCallback( key ) {
+ var loggingCallback = function( callback ) {
+ if ( QUnit.objectType( callback ) !== "function" ) {
+ throw new Error(
+ "QUnit logging methods require a callback function as their first parameters."
+ );
+ }
+
+ config.callbacks[ key ].push( callback );
+ };
+
+ // DEPRECATED: This will be removed on QUnit 2.0.0+
+ // Stores the registered functions allowing restoring
+ // at verifyLoggingCallbacks() if modified
+ loggingCallbacks[ key ] = loggingCallback;
+
+ return loggingCallback;
+ }
+
+ for ( i = 0, l = callbacks.length; i < l; i++ ) {
+ key = callbacks[ i ];
+
+ // Initialize key collection of logging callback
+ if ( QUnit.objectType( config.callbacks[ key ] ) === "undefined" ) {
+ config.callbacks[ key ] = [];
+ }
+
+ QUnit[ key ] = registerLoggingCallback( key );
+ }
+})();
+
+// `onErrorFnPrev` initialized at top of scope
+// Preserve other handlers
+onErrorFnPrev = window.onerror;
+
+// Cover uncaught exceptions
+// Returning true will suppress the default browser handler,
+// returning false will let it run.
+window.onerror = function( error, filePath, linerNr ) {
+ var ret = false;
+ if ( onErrorFnPrev ) {
+ ret = onErrorFnPrev( error, filePath, linerNr );
+ }
+
+ // Treat return value as window.onerror itself does,
+ // Only do our handling if not suppressed.
+ if ( ret !== true ) {
+ if ( QUnit.config.current ) {
+ if ( QUnit.config.current.ignoreGlobalErrors ) {
+ return true;
+ }
+ QUnit.pushFailure( error, filePath + ":" + linerNr );
+ } else {
+ QUnit.test( "global failure", extend(function() {
+ QUnit.pushFailure( error, filePath + ":" + linerNr );
+ }, { validTest: true } ) );
+ }
+ return false;
+ }
+
+ return ret;
+};
+
+function done() {
+ var runtime, passed;
+
+ config.autorun = true;
+
+ // Log the last module results
+ if ( config.previousModule ) {
+ runLoggingCallbacks( "moduleDone", {
+ name: config.previousModule.name,
+ tests: config.previousModule.tests,
+ failed: config.moduleStats.bad,
+ passed: config.moduleStats.all - config.moduleStats.bad,
+ total: config.moduleStats.all,
+ runtime: now() - config.moduleStats.started
+ });
+ }
+ delete config.previousModule;
+
+ runtime = now() - config.started;
+ passed = config.stats.all - config.stats.bad;
+
+ runLoggingCallbacks( "done", {
+ failed: config.stats.bad,
+ passed: passed,
+ total: config.stats.all,
+ runtime: runtime
+ });
+}
+
+// Doesn't support IE6 to IE9, it will return undefined on these browsers
+// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
+function extractStacktrace( e, offset ) {
+ offset = offset === undefined ? 4 : offset;
+
+ var stack, include, i;
+
+ if ( e.stack ) {
+ stack = e.stack.split( "\n" );
+ if ( /^error$/i.test( stack[ 0 ] ) ) {
+ stack.shift();
+ }
+ if ( fileName ) {
+ include = [];
+ for ( i = offset; i < stack.length; i++ ) {
+ if ( stack[ i ].indexOf( fileName ) !== -1 ) {
+ break;
+ }
+ include.push( stack[ i ] );
+ }
+ if ( include.length ) {
+ return include.join( "\n" );
+ }
+ }
+ return stack[ offset ];
+
+ // Support: Safari <=6 only
+ } else if ( e.sourceURL ) {
+
+ // exclude useless self-reference for generated Error objects
+ if ( /qunit.js$/.test( e.sourceURL ) ) {
+ return;
+ }
+
+ // for actual exceptions, this is useful
+ return e.sourceURL + ":" + e.line;
+ }
+}
+
+function sourceFromStacktrace( offset ) {
+ var error = new Error();
+
+ // Support: Safari <=7 only, IE <=10 - 11 only
+ // Not all browsers generate the `stack` property for `new Error()`, see also #636
+ if ( !error.stack ) {
+ try {
+ throw error;
+ } catch ( err ) {
+ error = err;
+ }
+ }
+
+ return extractStacktrace( error, offset );
+}
+
+function synchronize( callback, last ) {
+ if ( QUnit.objectType( callback ) === "array" ) {
+ while ( callback.length ) {
+ synchronize( callback.shift() );
+ }
+ return;
+ }
+ config.queue.push( callback );
+
+ if ( config.autorun && !config.blocking ) {
+ process( last );
+ }
+}
+
+function process( last ) {
+ function next() {
+ process( last );
+ }
+ var start = now();
+ config.depth = ( config.depth || 0 ) + 1;
+
+ while ( config.queue.length && !config.blocking ) {
+ if ( !defined.setTimeout || config.updateRate <= 0 ||
+ ( ( now() - start ) < config.updateRate ) ) {
+ if ( config.current ) {
+
+ // Reset async tracking for each phase of the Test lifecycle
+ config.current.usedAsync = false;
+ }
+ config.queue.shift()();
+ } else {
+ setTimeout( next, 13 );
+ break;
+ }
+ }
+ config.depth--;
+ if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
+ done();
+ }
+}
+
+function begin() {
+ var i, l,
+ modulesLog = [];
+
+ // If the test run hasn't officially begun yet
+ if ( !config.started ) {
+
+ // Record the time of the test run's beginning
+ config.started = now();
+
+ verifyLoggingCallbacks();
+
+ // Delete the loose unnamed module if unused.
+ if ( config.modules[ 0 ].name === "" && config.modules[ 0 ].tests.length === 0 ) {
+ config.modules.shift();
+ }
+
+ // Avoid unnecessary information by not logging modules' test environments
+ for ( i = 0, l = config.modules.length; i < l; i++ ) {
+ modulesLog.push({
+ name: config.modules[ i ].name,
+ tests: config.modules[ i ].tests
+ });
+ }
+
+ // The test run is officially beginning now
+ runLoggingCallbacks( "begin", {
+ totalTests: Test.count,
+ modules: modulesLog
+ });
+ }
+
+ config.blocking = false;
+ process( true );
+}
+
+function resumeProcessing() {
+ runStarted = true;
+
+ // A slight delay to allow this iteration of the event loop to finish (more assertions, etc.)
+ if ( defined.setTimeout ) {
+ setTimeout(function() {
+ if ( config.current && config.current.semaphore > 0 ) {
+ return;
+ }
+ if ( config.timeout ) {
+ clearTimeout( config.timeout );
+ }
+
+ begin();
+ }, 13 );
+ } else {
+ begin();
+ }
+}
+
+function pauseProcessing() {
+ config.blocking = true;
+
+ if ( config.testTimeout && defined.setTimeout ) {
+ clearTimeout( config.timeout );
+ config.timeout = setTimeout(function() {
+ if ( config.current ) {
+ config.current.semaphore = 0;
+ QUnit.pushFailure( "Test timed out", sourceFromStacktrace( 2 ) );
+ } else {
+ throw new Error( "Test timed out" );
+ }
+ resumeProcessing();
+ }, config.testTimeout );
+ }
+}
+
+function saveGlobal() {
+ config.pollution = [];
+
+ if ( config.noglobals ) {
+ for ( var key in window ) {
+ if ( hasOwn.call( window, key ) ) {
+ // in Opera sometimes DOM element ids show up here, ignore them
+ if ( /^qunit-test-output/.test( key ) ) {
+ continue;
+ }
+ config.pollution.push( key );
+ }
+ }
+ }
+}
+
+function checkPollution() {
+ var newGlobals,
+ deletedGlobals,
+ old = config.pollution;
+
+ saveGlobal();
+
+ newGlobals = diff( config.pollution, old );
+ if ( newGlobals.length > 0 ) {
+ QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join( ", " ) );
+ }
+
+ deletedGlobals = diff( old, config.pollution );
+ if ( deletedGlobals.length > 0 ) {
+ QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join( ", " ) );
+ }
+}
+
+// returns a new Array with the elements that are in a but not in b
+function diff( a, b ) {
+ var i, j,
+ result = a.slice();
+
+ for ( i = 0; i < result.length; i++ ) {
+ for ( j = 0; j < b.length; j++ ) {
+ if ( result[ i ] === b[ j ] ) {
+ result.splice( i, 1 );
+ i--;
+ break;
+ }
+ }
+ }
+ return result;
+}
+
+function extend( a, b, undefOnly ) {
+ for ( var prop in b ) {
+ if ( hasOwn.call( b, prop ) ) {
+
+ // Avoid "Member not found" error in IE8 caused by messing with window.constructor
+ if ( !( prop === "constructor" && a === window ) ) {
+ if ( b[ prop ] === undefined ) {
+ delete a[ prop ];
+ } else if ( !( undefOnly && typeof a[ prop ] !== "undefined" ) ) {
+ a[ prop ] = b[ prop ];
+ }
+ }
+ }
+ }
+
+ return a;
+}
+
+function runLoggingCallbacks( key, args ) {
+ var i, l, callbacks;
+
+ callbacks = config.callbacks[ key ];
+ for ( i = 0, l = callbacks.length; i < l; i++ ) {
+ callbacks[ i ]( args );
+ }
+}
+
+// DEPRECATED: This will be removed on 2.0.0+
+// This function verifies if the loggingCallbacks were modified by the user
+// If so, it will restore it, assign the given callback and print a console warning
+function verifyLoggingCallbacks() {
+ var loggingCallback, userCallback;
+
+ for ( loggingCallback in loggingCallbacks ) {
+ if ( QUnit[ loggingCallback ] !== loggingCallbacks[ loggingCallback ] ) {
+
+ userCallback = QUnit[ loggingCallback ];
+
+ // Restore the callback function
+ QUnit[ loggingCallback ] = loggingCallbacks[ loggingCallback ];
+
+ // Assign the deprecated given callback
+ QUnit[ loggingCallback ]( userCallback );
+
+ if ( window.console && window.console.warn ) {
+ window.console.warn(
+ "QUnit." + loggingCallback + " was replaced with a new value.\n" +
+ "Please, check out the documentation on how to apply logging callbacks.\n" +
+ "Reference: http://api.qunitjs.com/category/callbacks/"
+ );
+ }
+ }
+ }
+}
+
+// from jquery.js
+function inArray( elem, array ) {
+ if ( array.indexOf ) {
+ return array.indexOf( elem );
+ }
+
+ for ( var i = 0, length = array.length; i < length; i++ ) {
+ if ( array[ i ] === elem ) {
+ return i;
+ }
+ }
+
+ return -1;
+}
+
+function Test( settings ) {
+ var i, l;
+
+ ++Test.count;
+
+ extend( this, settings );
+ this.assertions = [];
+ this.semaphore = 0;
+ this.usedAsync = false;
+ this.module = config.currentModule;
+ this.stack = sourceFromStacktrace( 3 );
+
+ // Register unique strings
+ for ( i = 0, l = this.module.tests; i < l.length; i++ ) {
+ if ( this.module.tests[ i ].name === this.testName ) {
+ this.testName += " ";
+ }
+ }
+
+ this.testId = generateHash( this.module.name, this.testName );
+
+ this.module.tests.push({
+ name: this.testName,
+ testId: this.testId
+ });
+
+ if ( settings.skip ) {
+
+ // Skipped tests will fully ignore any sent callback
+ this.callback = function() {};
+ this.async = false;
+ this.expected = 0;
+ } else {
+ this.assert = new Assert( this );
+ }
+}
+
+Test.count = 0;
+
+Test.prototype = {
+ before: function() {
+ if (
+
+ // Emit moduleStart when we're switching from one module to another
+ this.module !== config.previousModule ||
+
+ // They could be equal (both undefined) but if the previousModule property doesn't
+ // yet exist it means this is the first test in a suite that isn't wrapped in a
+ // module, in which case we'll just emit a moduleStart event for 'undefined'.
+ // Without this, reporters can get testStart before moduleStart which is a problem.
+ !hasOwn.call( config, "previousModule" )
+ ) {
+ if ( hasOwn.call( config, "previousModule" ) ) {
+ runLoggingCallbacks( "moduleDone", {
+ name: config.previousModule.name,
+ tests: config.previousModule.tests,
+ failed: config.moduleStats.bad,
+ passed: config.moduleStats.all - config.moduleStats.bad,
+ total: config.moduleStats.all,
+ runtime: now() - config.moduleStats.started
+ });
+ }
+ config.previousModule = this.module;
+ config.moduleStats = { all: 0, bad: 0, started: now() };
+ runLoggingCallbacks( "moduleStart", {
+ name: this.module.name,
+ tests: this.module.tests
+ });
+ }
+
+ config.current = this;
+
+ this.testEnvironment = extend( {}, this.module.testEnvironment );
+ delete this.testEnvironment.beforeEach;
+ delete this.testEnvironment.afterEach;
+
+ this.started = now();
+ runLoggingCallbacks( "testStart", {
+ name: this.testName,
+ module: this.module.name,
+ testId: this.testId
+ });
+
+ if ( !config.pollution ) {
+ saveGlobal();
+ }
+ },
+
+ run: function() {
+ var promise;
+
+ config.current = this;
+
+ if ( this.async ) {
+ QUnit.stop();
+ }
+
+ this.callbackStarted = now();
+
+ if ( config.notrycatch ) {
+ promise = this.callback.call( this.testEnvironment, this.assert );
+ this.resolvePromise( promise );
+ return;
+ }
+
+ try {
+ promise = this.callback.call( this.testEnvironment, this.assert );
+ this.resolvePromise( promise );
+ } catch ( e ) {
+ this.pushFailure( "Died on test #" + ( this.assertions.length + 1 ) + " " +
+ this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) );
+
+ // else next test will carry the responsibility
+ saveGlobal();
+
+ // Restart the tests if they're blocking
+ if ( config.blocking ) {
+ QUnit.start();
+ }
+ }
+ },
+
+ after: function() {
+ checkPollution();
+ },
+
+ queueHook: function( hook, hookName ) {
+ var promise,
+ test = this;
+ return function runHook() {
+ config.current = test;
+ if ( config.notrycatch ) {
+ promise = hook.call( test.testEnvironment, test.assert );
+ test.resolvePromise( promise, hookName );
+ return;
+ }
+ try {
+ promise = hook.call( test.testEnvironment, test.assert );
+ test.resolvePromise( promise, hookName );
+ } catch ( error ) {
+ test.pushFailure( hookName + " failed on " + test.testName + ": " +
+ ( error.message || error ), extractStacktrace( error, 0 ) );
+ }
+ };
+ },
+
+ // Currently only used for module level hooks, can be used to add global level ones
+ hooks: function( handler ) {
+ var hooks = [];
+
+ // Hooks are ignored on skipped tests
+ if ( this.skip ) {
+ return hooks;
+ }
+
+ if ( this.module.testEnvironment &&
+ QUnit.objectType( this.module.testEnvironment[ handler ] ) === "function" ) {
+ hooks.push( this.queueHook( this.module.testEnvironment[ handler ], handler ) );
+ }
+
+ return hooks;
+ },
+
+ finish: function() {
+ config.current = this;
+ if ( config.requireExpects && this.expected === null ) {
+ this.pushFailure( "Expected number of assertions to be defined, but expect() was " +
+ "not called.", this.stack );
+ } else if ( this.expected !== null && this.expected !== this.assertions.length ) {
+ this.pushFailure( "Expected " + this.expected + " assertions, but " +
+ this.assertions.length + " were run", this.stack );
+ } else if ( this.expected === null && !this.assertions.length ) {
+ this.pushFailure( "Expected at least one assertion, but none were run - call " +
+ "expect(0) to accept zero assertions.", this.stack );
+ }
+
+ var i,
+ bad = 0;
+
+ this.runtime = now() - this.started;
+ config.stats.all += this.assertions.length;
+ config.moduleStats.all += this.assertions.length;
+
+ for ( i = 0; i < this.assertions.length; i++ ) {
+ if ( !this.assertions[ i ].result ) {
+ bad++;
+ config.stats.bad++;
+ config.moduleStats.bad++;
+ }
+ }
+
+ runLoggingCallbacks( "testDone", {
+ name: this.testName,
+ module: this.module.name,
+ skipped: !!this.skip,
+ failed: bad,
+ passed: this.assertions.length - bad,
+ total: this.assertions.length,
+ runtime: this.runtime,
+
+ // HTML Reporter use
+ assertions: this.assertions,
+ testId: this.testId,
+
+ // DEPRECATED: this property will be removed in 2.0.0, use runtime instead
+ duration: this.runtime
+ });
+
+ // QUnit.reset() is deprecated and will be replaced for a new
+ // fixture reset function on QUnit 2.0/2.1.
+ // It's still called here for backwards compatibility handling
+ QUnit.reset();
+
+ config.current = undefined;
+ },
+
+ queue: function() {
+ var bad,
+ test = this;
+
+ if ( !this.valid() ) {
+ return;
+ }
+
+ function run() {
+
+ // each of these can by async
+ synchronize([
+ function() {
+ test.before();
+ },
+
+ test.hooks( "beforeEach" ),
+
+ function() {
+ test.run();
+ },
+
+ test.hooks( "afterEach" ).reverse(),
+
+ function() {
+ test.after();
+ },
+ function() {
+ test.finish();
+ }
+ ]);
+ }
+
+ // `bad` initialized at top of scope
+ // defer when previous test run passed, if storage is available
+ bad = QUnit.config.reorder && defined.sessionStorage &&
+ +sessionStorage.getItem( "qunit-test-" + this.module.name + "-" + this.testName );
+
+ if ( bad ) {
+ run();
+ } else {
+ synchronize( run, true );
+ }
+ },
+
+ push: function( result, actual, expected, message ) {
+ var source,
+ details = {
+ module: this.module.name,
+ name: this.testName,
+ result: result,
+ message: message,
+ actual: actual,
+ expected: expected,
+ testId: this.testId,
+ runtime: now() - this.started
+ };
+
+ if ( !result ) {
+ source = sourceFromStacktrace();
+
+ if ( source ) {
+ details.source = source;
+ }
+ }
+
+ runLoggingCallbacks( "log", details );
+
+ this.assertions.push({
+ result: !!result,
+ message: message
+ });
+ },
+
+ pushFailure: function( message, source, actual ) {
+ if ( !this instanceof Test ) {
+ throw new Error( "pushFailure() assertion outside test context, was " +
+ sourceFromStacktrace( 2 ) );
+ }
+
+ var details = {
+ module: this.module.name,
+ name: this.testName,
+ result: false,
+ message: message || "error",
+ actual: actual || null,
+ testId: this.testId,
+ runtime: now() - this.started
+ };
+
+ if ( source ) {
+ details.source = source;
+ }
+
+ runLoggingCallbacks( "log", details );
+
+ this.assertions.push({
+ result: false,
+ message: message
+ });
+ },
+
+ resolvePromise: function( promise, phase ) {
+ var then, message,
+ test = this;
+ if ( promise != null ) {
+ then = promise.then;
+ if ( QUnit.objectType( then ) === "function" ) {
+ QUnit.stop();
+ then.call(
+ promise,
+ QUnit.start,
+ function( error ) {
+ message = "Promise rejected " +
+ ( !phase ? "during" : phase.replace( /Each$/, "" ) ) +
+ " " + test.testName + ": " + ( error.message || error );
+ test.pushFailure( message, extractStacktrace( error, 0 ) );
+
+ // else next test will carry the responsibility
+ saveGlobal();
+
+ // Unblock
+ QUnit.start();
+ }
+ );
+ }
+ }
+ },
+
+ valid: function() {
+ var include,
+ filter = config.filter && config.filter.toLowerCase(),
+ module = QUnit.urlParams.module && QUnit.urlParams.module.toLowerCase(),
+ fullName = ( this.module.name + ": " + this.testName ).toLowerCase();
+
+ // Internally-generated tests are always valid
+ if ( this.callback && this.callback.validTest ) {
+ return true;
+ }
+
+ if ( config.testId.length > 0 && inArray( this.testId, config.testId ) < 0 ) {
+ return false;
+ }
+
+ if ( module && ( !this.module.name || this.module.name.toLowerCase() !== module ) ) {
+ return false;
+ }
+
+ if ( !filter ) {
+ return true;
+ }
+
+ include = filter.charAt( 0 ) !== "!";
+ if ( !include ) {
+ filter = filter.slice( 1 );
+ }
+
+ // If the filter matches, we need to honour include
+ if ( fullName.indexOf( filter ) !== -1 ) {
+ return include;
+ }
+
+ // Otherwise, do the opposite
+ return !include;
+ }
+
+};
+
+// Resets the test setup. Useful for tests that modify the DOM.
+/*
+DEPRECATED: Use multiple tests instead of resetting inside a test.
+Use testStart or testDone for custom cleanup.
+This method will throw an error in 2.0, and will be removed in 2.1
+*/
+QUnit.reset = function() {
+
+ // Return on non-browser environments
+ // This is necessary to not break on node tests
+ if ( typeof window === "undefined" ) {
+ return;
+ }
+
+ var fixture = defined.document && document.getElementById &&
+ document.getElementById( "qunit-fixture" );
+
+ if ( fixture ) {
+ fixture.innerHTML = config.fixture;
+ }
+};
+
+QUnit.pushFailure = function() {
+ if ( !QUnit.config.current ) {
+ throw new Error( "pushFailure() assertion outside test context, in " +
+ sourceFromStacktrace( 2 ) );
+ }
+
+ // Gets current test obj
+ var currentTest = QUnit.config.current;
+
+ return currentTest.pushFailure.apply( currentTest, arguments );
+};
+
+// Based on Java's String.hashCode, a simple but not
+// rigorously collision resistant hashing function
+function generateHash( module, testName ) {
+ var hex,
+ i = 0,
+ hash = 0,
+ str = module + "\x1C" + testName,
+ len = str.length;
+
+ for ( ; i < len; i++ ) {
+ hash = ( ( hash << 5 ) - hash ) + str.charCodeAt( i );
+ hash |= 0;
+ }
+
+ // Convert the possibly negative integer hash code into an 8 character hex string, which isn't
+ // strictly necessary but increases user understanding that the id is a SHA-like hash
+ hex = ( 0x100000000 + hash ).toString( 16 );
+ if ( hex.length < 8 ) {
+ hex = "0000000" + hex;
+ }
+
+ return hex.slice( -8 );
+}
+
+function Assert( testContext ) {
+ this.test = testContext;
+}
+
+// Assert helpers
+QUnit.assert = Assert.prototype = {
+
+ // Specify the number of expected assertions to guarantee that failed test
+ // (no assertions are run at all) don't slip through.
+ expect: function( asserts ) {
+ if ( arguments.length === 1 ) {
+ this.test.expected = asserts;
+ } else {
+ return this.test.expected;
+ }
+ },
+
+ // Increment this Test's semaphore counter, then return a single-use function that
+ // decrements that counter a maximum of once.
+ async: function() {
+ var test = this.test,
+ popped = false;
+
+ test.semaphore += 1;
+ test.usedAsync = true;
+ pauseProcessing();
+
+ return function done() {
+ if ( !popped ) {
+ test.semaphore -= 1;
+ popped = true;
+ resumeProcessing();
+ } else {
+ test.pushFailure( "Called the callback returned from `assert.async` more than once",
+ sourceFromStacktrace( 2 ) );
+ }
+ };
+ },
+
+ // Exports test.push() to the user API
+ push: function( /* result, actual, expected, message */ ) {
+ var assert = this,
+ currentTest = ( assert instanceof Assert && assert.test ) || QUnit.config.current;
+
+ // Backwards compatibility fix.
+ // Allows the direct use of global exported assertions and QUnit.assert.*
+ // Although, it's use is not recommended as it can leak assertions
+ // to other tests from async tests, because we only get a reference to the current test,
+ // not exactly the test where assertion were intended to be called.
+ if ( !currentTest ) {
+ throw new Error( "assertion outside test context, in " + sourceFromStacktrace( 2 ) );
+ }
+
+ if ( currentTest.usedAsync === true && currentTest.semaphore === 0 ) {
+ currentTest.pushFailure( "Assertion after the final `assert.async` was resolved",
+ sourceFromStacktrace( 2 ) );
+
+ // Allow this assertion to continue running anyway...
+ }
+
+ if ( !( assert instanceof Assert ) ) {
+ assert = currentTest.assert;
+ }
+ return assert.test.push.apply( assert.test, arguments );
+ },
+
+ ok: function( result, message ) {
+ message = message || ( result ? "okay" : "failed, expected argument to be truthy, was: " +
+ QUnit.dump.parse( result ) );
+ this.push( !!result, result, true, message );
+ },
+
+ notOk: function( result, message ) {
+ message = message || ( !result ? "okay" : "failed, expected argument to be falsy, was: " +
+ QUnit.dump.parse( result ) );
+ this.push( !result, result, false, message );
+ },
+
+ equal: function( actual, expected, message ) {
+ /*jshint eqeqeq:false */
+ this.push( expected == actual, actual, expected, message );
+ },
+
+ notEqual: function( actual, expected, message ) {
+ /*jshint eqeqeq:false */
+ this.push( expected != actual, actual, expected, message );
+ },
+
+ propEqual: function( actual, expected, message ) {
+ actual = objectValues( actual );
+ expected = objectValues( expected );
+ this.push( QUnit.equiv( actual, expected ), actual, expected, message );
+ },
+
+ notPropEqual: function( actual, expected, message ) {
+ actual = objectValues( actual );
+ expected = objectValues( expected );
+ this.push( !QUnit.equiv( actual, expected ), actual, expected, message );
+ },
+
+ deepEqual: function( actual, expected, message ) {
+ this.push( QUnit.equiv( actual, expected ), actual, expected, message );
+ },
+
+ notDeepEqual: function( actual, expected, message ) {
+ this.push( !QUnit.equiv( actual, expected ), actual, expected, message );
+ },
+
+ strictEqual: function( actual, expected, message ) {
+ this.push( expected === actual, actual, expected, message );
+ },
+
+ notStrictEqual: function( actual, expected, message ) {
+ this.push( expected !== actual, actual, expected, message );
+ },
+
+ "throws": function( block, expected, message ) {
+ var actual, expectedType,
+ expectedOutput = expected,
+ ok = false,
+ currentTest = ( this instanceof Assert && this.test ) || QUnit.config.current;
+
+ // 'expected' is optional unless doing string comparison
+ if ( message == null && typeof expected === "string" ) {
+ message = expected;
+ expected = null;
+ }
+
+ currentTest.ignoreGlobalErrors = true;
+ try {
+ block.call( currentTest.testEnvironment );
+ } catch (e) {
+ actual = e;
+ }
+ currentTest.ignoreGlobalErrors = false;
+
+ if ( actual ) {
+ expectedType = QUnit.objectType( expected );
+
+ // we don't want to validate thrown error
+ if ( !expected ) {
+ ok = true;
+ expectedOutput = null;
+
+ // expected is a regexp
+ } else if ( expectedType === "regexp" ) {
+ ok = expected.test( errorString( actual ) );
+
+ // expected is a string
+ } else if ( expectedType === "string" ) {
+ ok = expected === errorString( actual );
+
+ // expected is a constructor, maybe an Error constructor
+ } else if ( expectedType === "function" && actual instanceof expected ) {
+ ok = true;
+
+ // expected is an Error object
+ } else if ( expectedType === "object" ) {
+ ok = actual instanceof expected.constructor &&
+ actual.name === expected.name &&
+ actual.message === expected.message;
+
+ // expected is a validation function which returns true if validation passed
+ } else if ( expectedType === "function" && expected.call( {}, actual ) === true ) {
+ expectedOutput = null;
+ ok = true;
+ }
+ }
+
+ currentTest.assert.push( ok, actual, expectedOutput, message );
+ }
+};
+
+// Provide an alternative to assert.throws(), for enviroments that consider throws a reserved word
+// Known to us are: Closure Compiler, Narwhal
+(function() {
+ /*jshint sub:true */
+ Assert.prototype.raises = Assert.prototype[ "throws" ];
+}());
+
+// Test for equality any JavaScript type.
+// Author: Philippe Rathé
+QUnit.equiv = (function() {
+
+ // Call the o related callback with the given arguments.
+ function bindCallbacks( o, callbacks, args ) {
+ var prop = QUnit.objectType( o );
+ if ( prop ) {
+ if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) {
+ return callbacks[ prop ].apply( callbacks, args );
+ } else {
+ return callbacks[ prop ]; // or undefined
+ }
+ }
+ }
+
+ // the real equiv function
+ var innerEquiv,
+
+ // stack to decide between skip/abort functions
+ callers = [],
+
+ // stack to avoiding loops from circular referencing
+ parents = [],
+ parentsB = [],
+
+ getProto = Object.getPrototypeOf || function( obj ) {
+ /* jshint camelcase: false, proto: true */
+ return obj.__proto__;
+ },
+ callbacks = (function() {
+
+ // for string, boolean, number and null
+ function useStrictEquality( b, a ) {
+
+ /*jshint eqeqeq:false */
+ if ( b instanceof a.constructor || a instanceof b.constructor ) {
+
+ // to catch short annotation VS 'new' annotation of a
+ // declaration
+ // e.g. var i = 1;
+ // var j = new Number(1);
+ return a == b;
+ } else {
+ return a === b;
+ }
+ }
+
+ return {
+ "string": useStrictEquality,
+ "boolean": useStrictEquality,
+ "number": useStrictEquality,
+ "null": useStrictEquality,
+ "undefined": useStrictEquality,
+
+ "nan": function( b ) {
+ return isNaN( b );
+ },
+
+ "date": function( b, a ) {
+ return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf();
+ },
+
+ "regexp": function( b, a ) {
+ return QUnit.objectType( b ) === "regexp" &&
+
+ // the regex itself
+ a.source === b.source &&
+
+ // and its modifiers
+ a.global === b.global &&
+
+ // (gmi) ...
+ a.ignoreCase === b.ignoreCase &&
+ a.multiline === b.multiline &&
+ a.sticky === b.sticky;
+ },
+
+ // - skip when the property is a method of an instance (OOP)
+ // - abort otherwise,
+ // initial === would have catch identical references anyway
+ "function": function() {
+ var caller = callers[ callers.length - 1 ];
+ return caller !== Object && typeof caller !== "undefined";
+ },
+
+ "array": function( b, a ) {
+ var i, j, len, loop, aCircular, bCircular;
+
+ // b could be an object literal here
+ if ( QUnit.objectType( b ) !== "array" ) {
+ return false;
+ }
+
+ len = a.length;
+ if ( len !== b.length ) {
+ // safe and faster
+ return false;
+ }
+
+ // track reference to avoid circular references
+ parents.push( a );
+ parentsB.push( b );
+ for ( i = 0; i < len; i++ ) {
+ loop = false;
+ for ( j = 0; j < parents.length; j++ ) {
+ aCircular = parents[ j ] === a[ i ];
+ bCircular = parentsB[ j ] === b[ i ];
+ if ( aCircular || bCircular ) {
+ if ( a[ i ] === b[ i ] || aCircular && bCircular ) {
+ loop = true;
+ } else {
+ parents.pop();
+ parentsB.pop();
+ return false;
+ }
+ }
+ }
+ if ( !loop && !innerEquiv( a[ i ], b[ i ] ) ) {
+ parents.pop();
+ parentsB.pop();
+ return false;
+ }
+ }
+ parents.pop();
+ parentsB.pop();
+ return true;
+ },
+
+ "object": function( b, a ) {
+
+ /*jshint forin:false */
+ var i, j, loop, aCircular, bCircular,
+ // Default to true
+ eq = true,
+ aProperties = [],
+ bProperties = [];
+
+ // comparing constructors is more strict than using
+ // instanceof
+ if ( a.constructor !== b.constructor ) {
+
+ // Allow objects with no prototype to be equivalent to
+ // objects with Object as their constructor.
+ if ( !( ( getProto( a ) === null && getProto( b ) === Object.prototype ) ||
+ ( getProto( b ) === null && getProto( a ) === Object.prototype ) ) ) {
+ return false;
+ }
+ }
+
+ // stack constructor before traversing properties
+ callers.push( a.constructor );
+
+ // track reference to avoid circular references
+ parents.push( a );
+ parentsB.push( b );
+
+ // be strict: don't ensure hasOwnProperty and go deep
+ for ( i in a ) {
+ loop = false;
+ for ( j = 0; j < parents.length; j++ ) {
+ aCircular = parents[ j ] === a[ i ];
+ bCircular = parentsB[ j ] === b[ i ];
+ if ( aCircular || bCircular ) {
+ if ( a[ i ] === b[ i ] || aCircular && bCircular ) {
+ loop = true;
+ } else {
+ eq = false;
+ break;
+ }
+ }
+ }
+ aProperties.push( i );
+ if ( !loop && !innerEquiv( a[ i ], b[ i ] ) ) {
+ eq = false;
+ break;
+ }
+ }
+
+ parents.pop();
+ parentsB.pop();
+ callers.pop(); // unstack, we are done
+
+ for ( i in b ) {
+ bProperties.push( i ); // collect b's properties
+ }
+
+ // Ensures identical properties name
+ return eq && innerEquiv( aProperties.sort(), bProperties.sort() );
+ }
+ };
+ }());
+
+ innerEquiv = function() { // can take multiple arguments
+ var args = [].slice.apply( arguments );
+ if ( args.length < 2 ) {
+ return true; // end transition
+ }
+
+ return ( (function( a, b ) {
+ if ( a === b ) {
+ return true; // catch the most you can
+ } else if ( a === null || b === null || typeof a === "undefined" ||
+ typeof b === "undefined" ||
+ QUnit.objectType( a ) !== QUnit.objectType( b ) ) {
+
+ // don't lose time with error prone cases
+ return false;
+ } else {
+ return bindCallbacks( a, callbacks, [ b, a ] );
+ }
+
+ // apply transition with (1..n) arguments
+ }( args[ 0 ], args[ 1 ] ) ) &&
+ innerEquiv.apply( this, args.splice( 1, args.length - 1 ) ) );
+ };
+
+ return innerEquiv;
+}());
+
+// Based on jsDump by Ariel Flesler
+// http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html
+QUnit.dump = (function() {
+ function quote( str ) {
+ return "\"" + str.toString().replace( /"/g, "\\\"" ) + "\"";
+ }
+ function literal( o ) {
+ return o + "";
+ }
+ function join( pre, arr, post ) {
+ var s = dump.separator(),
+ base = dump.indent(),
+ inner = dump.indent( 1 );
+ if ( arr.join ) {
+ arr = arr.join( "," + s + inner );
+ }
+ if ( !arr ) {
+ return pre + post;
+ }
+ return [ pre, inner + arr, base + post ].join( s );
+ }
+ function array( arr, stack ) {
+ var i = arr.length,
+ ret = new Array( i );
+
+ if ( dump.maxDepth && dump.depth > dump.maxDepth ) {
+ return "[object Array]";
+ }
+
+ this.up();
+ while ( i-- ) {
+ ret[ i ] = this.parse( arr[ i ], undefined, stack );
+ }
+ this.down();
+ return join( "[", ret, "]" );
+ }
+
+ var reName = /^function (\w+)/,
+ dump = {
+
+ // objType is used mostly internally, you can fix a (custom) type in advance
+ parse: function( obj, objType, stack ) {
+ stack = stack || [];
+ var res, parser, parserType,
+ inStack = inArray( obj, stack );
+
+ if ( inStack !== -1 ) {
+ return "recursion(" + ( inStack - stack.length ) + ")";
+ }
+
+ objType = objType || this.typeOf( obj );
+ parser = this.parsers[ objType ];
+ parserType = typeof parser;
+
+ if ( parserType === "function" ) {
+ stack.push( obj );
+ res = parser.call( this, obj, stack );
+ stack.pop();
+ return res;
+ }
+ return ( parserType === "string" ) ? parser : this.parsers.error;
+ },
+ typeOf: function( obj ) {
+ var type;
+ if ( obj === null ) {
+ type = "null";
+ } else if ( typeof obj === "undefined" ) {
+ type = "undefined";
+ } else if ( QUnit.is( "regexp", obj ) ) {
+ type = "regexp";
+ } else if ( QUnit.is( "date", obj ) ) {
+ type = "date";
+ } else if ( QUnit.is( "function", obj ) ) {
+ type = "function";
+ } else if ( obj.setInterval !== undefined &&
+ obj.document !== undefined &&
+ obj.nodeType === undefined ) {
+ type = "window";
+ } else if ( obj.nodeType === 9 ) {
+ type = "document";
+ } else if ( obj.nodeType ) {
+ type = "node";
+ } else if (
+
+ // native arrays
+ toString.call( obj ) === "[object Array]" ||
+
+ // NodeList objects
+ ( typeof obj.length === "number" && obj.item !== undefined &&
+ ( obj.length ? obj.item( 0 ) === obj[ 0 ] : ( obj.item( 0 ) === null &&
+ obj[ 0 ] === undefined ) ) )
+ ) {
+ type = "array";
+ } else if ( obj.constructor === Error.prototype.constructor ) {
+ type = "error";
+ } else {
+ type = typeof obj;
+ }
+ return type;
+ },
+ separator: function() {
+ return this.multiline ? this.HTML ? " " : "\n" : this.HTML ? " " : " ";
+ },
+ // extra can be a number, shortcut for increasing-calling-decreasing
+ indent: function( extra ) {
+ if ( !this.multiline ) {
+ return "";
+ }
+ var chr = this.indentChar;
+ if ( this.HTML ) {
+ chr = chr.replace( /\t/g, " " ).replace( / /g, " " );
+ }
+ return new Array( this.depth + ( extra || 0 ) ).join( chr );
+ },
+ up: function( a ) {
+ this.depth += a || 1;
+ },
+ down: function( a ) {
+ this.depth -= a || 1;
+ },
+ setParser: function( name, parser ) {
+ this.parsers[ name ] = parser;
+ },
+ // The next 3 are exposed so you can use them
+ quote: quote,
+ literal: literal,
+ join: join,
+ //
+ depth: 1,
+ maxDepth: QUnit.config.maxDepth,
+
+ // This is the list of parsers, to modify them, use dump.setParser
+ parsers: {
+ window: "[Window]",
+ document: "[Document]",
+ error: function( error ) {
+ return "Error(\"" + error.message + "\")";
+ },
+ unknown: "[Unknown]",
+ "null": "null",
+ "undefined": "undefined",
+ "function": function( fn ) {
+ var ret = "function",
+
+ // functions never have name in IE
+ name = "name" in fn ? fn.name : ( reName.exec( fn ) || [] )[ 1 ];
+
+ if ( name ) {
+ ret += " " + name;
+ }
+ ret += "( ";
+
+ ret = [ ret, dump.parse( fn, "functionArgs" ), "){" ].join( "" );
+ return join( ret, dump.parse( fn, "functionCode" ), "}" );
+ },
+ array: array,
+ nodelist: array,
+ "arguments": array,
+ object: function( map, stack ) {
+ var keys, key, val, i, nonEnumerableProperties,
+ ret = [];
+
+ if ( dump.maxDepth && dump.depth > dump.maxDepth ) {
+ return "[object Object]";
+ }
+
+ dump.up();
+ keys = [];
+ for ( key in map ) {
+ keys.push( key );
+ }
+
+ // Some properties are not always enumerable on Error objects.
+ nonEnumerableProperties = [ "message", "name" ];
+ for ( i in nonEnumerableProperties ) {
+ key = nonEnumerableProperties[ i ];
+ if ( key in map && inArray( key, keys ) < 0 ) {
+ keys.push( key );
+ }
+ }
+ keys.sort();
+ for ( i = 0; i < keys.length; i++ ) {
+ key = keys[ i ];
+ val = map[ key ];
+ ret.push( dump.parse( key, "key" ) + ": " +
+ dump.parse( val, undefined, stack ) );
+ }
+ dump.down();
+ return join( "{", ret, "}" );
+ },
+ node: function( node ) {
+ var len, i, val,
+ open = dump.HTML ? "<" : "<",
+ close = dump.HTML ? ">" : ">",
+ tag = node.nodeName.toLowerCase(),
+ ret = open + tag,
+ attrs = node.attributes;
+
+ if ( attrs ) {
+ for ( i = 0, len = attrs.length; i < len; i++ ) {
+ val = attrs[ i ].nodeValue;
+
+ // IE6 includes all attributes in .attributes, even ones not explicitly
+ // set. Those have values like undefined, null, 0, false, "" or
+ // "inherit".
+ if ( val && val !== "inherit" ) {
+ ret += " " + attrs[ i ].nodeName + "=" +
+ dump.parse( val, "attribute" );
+ }
+ }
+ }
+ ret += close;
+
+ // Show content of TextNode or CDATASection
+ if ( node.nodeType === 3 || node.nodeType === 4 ) {
+ ret += node.nodeValue;
+ }
+
+ return ret + open + "/" + tag + close;
+ },
+
+ // function calls it internally, it's the arguments part of the function
+ functionArgs: function( fn ) {
+ var args,
+ l = fn.length;
+
+ if ( !l ) {
+ return "";
+ }
+
+ args = new Array( l );
+ while ( l-- ) {
+
+ // 97 is 'a'
+ args[ l ] = String.fromCharCode( 97 + l );
+ }
+ return " " + args.join( ", " ) + " ";
+ },
+ // object calls it internally, the key part of an item in a map
+ key: quote,
+ // function calls it internally, it's the content of the function
+ functionCode: "[code]",
+ // node calls it internally, it's an html attribute value
+ attribute: quote,
+ string: quote,
+ date: quote,
+ regexp: literal,
+ number: literal,
+ "boolean": literal
+ },
+ // if true, entities are escaped ( <, >, \t, space and \n )
+ HTML: false,
+ // indentation unit
+ indentChar: " ",
+ // if true, items in a collection, are separated by a \n, else just a space.
+ multiline: true
+ };
+
+ return dump;
+}());
+
+// back compat
+QUnit.jsDump = QUnit.dump;
+
+// For browser, export only select globals
+if ( typeof window !== "undefined" ) {
+
+ // Deprecated
+ // Extend assert methods to QUnit and Global scope through Backwards compatibility
+ (function() {
+ var i,
+ assertions = Assert.prototype;
+
+ function applyCurrent( current ) {
+ return function() {
+ var assert = new Assert( QUnit.config.current );
+ current.apply( assert, arguments );
+ };
+ }
+
+ for ( i in assertions ) {
+ QUnit[ i ] = applyCurrent( assertions[ i ] );
+ }
+ })();
+
+ (function() {
+ var i, l,
+ keys = [
+ "test",
+ "module",
+ "expect",
+ "asyncTest",
+ "start",
+ "stop",
+ "ok",
+ "notOk",
+ "equal",
+ "notEqual",
+ "propEqual",
+ "notPropEqual",
+ "deepEqual",
+ "notDeepEqual",
+ "strictEqual",
+ "notStrictEqual",
+ "throws"
+ ];
+
+ for ( i = 0, l = keys.length; i < l; i++ ) {
+ window[ keys[ i ] ] = QUnit[ keys[ i ] ];
+ }
+ })();
+
+ window.QUnit = QUnit;
+}
+
+// For nodejs
+if ( typeof module !== "undefined" && module && module.exports ) {
+ module.exports = QUnit;
+
+ // For consistency with CommonJS environments' exports
+ module.exports.QUnit = QUnit;
+}
+
+// For CommonJS with exports, but without module.exports, like Rhino
+if ( typeof exports !== "undefined" && exports ) {
+ exports.QUnit = QUnit;
+}
+
+if ( typeof define === "function" && define.amd ) {
+ define( function() {
+ return QUnit;
+ } );
+ QUnit.config.autostart = false;
+}
+
+// Get a reference to the global object, like window in browsers
+}( (function() {
+ return this;
+})() ));
+
+/*istanbul ignore next */
+// jscs:disable maximumLineLength
+/*
+ * This file is a modified version of google-diff-match-patch's JavaScript implementation
+ * (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js),
+ * modifications are licensed as more fully set forth in LICENSE.txt.
+ *
+ * The original source of google-diff-match-patch is attributable and licensed as follows:
+ *
+ * Copyright 2006 Google Inc.
+ * http://code.google.com/p/google-diff-match-patch/
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * More Info:
+ * https://code.google.com/p/google-diff-match-patch/
+ *
+ * Usage: QUnit.diff(expected, actual)
+ *
+ * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) === "the quick brown fox jumpsed} Array of diff tuples.
+ */
+ DiffMatchPatch.prototype.DiffMain = function( text1, text2, optChecklines, optDeadline ) {
+ var deadline, checklines, commonlength,
+ commonprefix, commonsuffix, diffs;
+ // Set a deadline by which time the diff must be complete.
+ if ( typeof optDeadline === "undefined" ) {
+ if ( this.DiffTimeout <= 0 ) {
+ optDeadline = Number.MAX_VALUE;
+ } else {
+ optDeadline = ( new Date() ).getTime() + this.DiffTimeout * 1000;
+ }
+ }
+ deadline = optDeadline;
+
+ // Check for null inputs.
+ if ( text1 === null || text2 === null ) {
+ throw new Error( "Null input. (DiffMain)" );
+ }
+
+ // Check for equality (speedup).
+ if ( text1 === text2 ) {
+ if ( text1 ) {
+ return [
+ [ DIFF_EQUAL, text1 ]
+ ];
+ }
+ return [];
+ }
+
+ if ( typeof optChecklines === "undefined" ) {
+ optChecklines = true;
+ }
+
+ checklines = optChecklines;
+
+ // Trim off common prefix (speedup).
+ commonlength = this.diffCommonPrefix( text1, text2 );
+ commonprefix = text1.substring( 0, commonlength );
+ text1 = text1.substring( commonlength );
+ text2 = text2.substring( commonlength );
+
+ // Trim off common suffix (speedup).
+ /////////
+ commonlength = this.diffCommonSuffix( text1, text2 );
+ commonsuffix = text1.substring( text1.length - commonlength );
+ text1 = text1.substring( 0, text1.length - commonlength );
+ text2 = text2.substring( 0, text2.length - commonlength );
+
+ // Compute the diff on the middle block.
+ diffs = this.diffCompute( text1, text2, checklines, deadline );
+
+ // Restore the prefix and suffix.
+ if ( commonprefix ) {
+ diffs.unshift( [ DIFF_EQUAL, commonprefix ] );
+ }
+ if ( commonsuffix ) {
+ diffs.push( [ DIFF_EQUAL, commonsuffix ] );
+ }
+ this.diffCleanupMerge( diffs );
+ return diffs;
+ };
+
+ /**
+ * Reduce the number of edits by eliminating operationally trivial equalities.
+ * @param {!Array.} diffs Array of diff tuples.
+ */
+ DiffMatchPatch.prototype.diffCleanupEfficiency = function( diffs ) {
+ var changes, equalities, equalitiesLength, lastequality,
+ pointer, preIns, preDel, postIns, postDel;
+ changes = false;
+ equalities = []; // Stack of indices where equalities are found.
+ equalitiesLength = 0; // Keeping our own length var is faster in JS.
+ /** @type {?string} */
+ lastequality = null;
+ // Always equal to diffs[equalities[equalitiesLength - 1]][1]
+ pointer = 0; // Index of current position.
+ // Is there an insertion operation before the last equality.
+ preIns = false;
+ // Is there a deletion operation before the last equality.
+ preDel = false;
+ // Is there an insertion operation after the last equality.
+ postIns = false;
+ // Is there a deletion operation after the last equality.
+ postDel = false;
+ while ( pointer < diffs.length ) {
+ if ( diffs[ pointer ][ 0 ] === DIFF_EQUAL ) { // Equality found.
+ if ( diffs[ pointer ][ 1 ].length < this.DiffEditCost && ( postIns || postDel ) ) {
+ // Candidate found.
+ equalities[ equalitiesLength++ ] = pointer;
+ preIns = postIns;
+ preDel = postDel;
+ lastequality = diffs[ pointer ][ 1 ];
+ } else {
+ // Not a candidate, and can never become one.
+ equalitiesLength = 0;
+ lastequality = null;
+ }
+ postIns = postDel = false;
+ } else { // An insertion or deletion.
+ if ( diffs[ pointer ][ 0 ] === DIFF_DELETE ) {
+ postDel = true;
+ } else {
+ postIns = true;
+ }
+ /*
+ * Five types to be split:
+ * ABXYCD
+ * AXCD
+ * ABXC
+ * AXCD
+ * ABXC
+ */
+ if ( lastequality && ( ( preIns && preDel && postIns && postDel ) ||
+ ( ( lastequality.length < this.DiffEditCost / 2 ) &&
+ ( preIns + preDel + postIns + postDel ) === 3 ) ) ) {
+ // Duplicate record.
+ diffs.splice( equalities[equalitiesLength - 1], 0, [ DIFF_DELETE, lastequality ] );
+ // Change second copy to insert.
+ diffs[ equalities[ equalitiesLength - 1 ] + 1 ][ 0 ] = DIFF_INSERT;
+ equalitiesLength--; // Throw away the equality we just deleted;
+ lastequality = null;
+ if (preIns && preDel) {
+ // No changes made which could affect previous entry, keep going.
+ postIns = postDel = true;
+ equalitiesLength = 0;
+ } else {
+ equalitiesLength--; // Throw away the previous equality.
+ pointer = equalitiesLength > 0 ? equalities[ equalitiesLength - 1 ] : -1;
+ postIns = postDel = false;
+ }
+ changes = true;
+ }
+ }
+ pointer++;
+ }
+
+ if ( changes ) {
+ this.diffCleanupMerge( diffs );
+ }
+ };
+
+ /**
+ * Convert a diff array into a pretty HTML report.
+ * @param {!Array.} diffs Array of diff tuples.
+ * @param {integer} string to be beautified.
+ * @return {string} HTML representation.
+ */
+ DiffMatchPatch.prototype.diffPrettyHtml = function( diffs ) {
+ var op, data, x, html = [];
+ for ( x = 0; x < diffs.length; x++ ) {
+ op = diffs[x][0]; // Operation (insert, delete, equal)
+ data = diffs[x][1]; // Text of change.
+ switch ( op ) {
+ case DIFF_INSERT:
+ html[x] = "" + data + "";
+ break;
+ case DIFF_DELETE:
+ html[x] = "" + data + "";
+ break;
+ case DIFF_EQUAL:
+ html[x] = "" + data + "";
+ break;
+ }
+ }
+ return html.join("");
+ };
+
+ /**
+ * Determine the common prefix of two strings.
+ * @param {string} text1 First string.
+ * @param {string} text2 Second string.
+ * @return {number} The number of characters common to the start of each
+ * string.
+ */
+ DiffMatchPatch.prototype.diffCommonPrefix = function( text1, text2 ) {
+ var pointermid, pointermax, pointermin, pointerstart;
+ // Quick check for common null cases.
+ if ( !text1 || !text2 || text1.charAt(0) !== text2.charAt(0) ) {
+ return 0;
+ }
+ // Binary search.
+ // Performance analysis: http://neil.fraser.name/news/2007/10/09/
+ pointermin = 0;
+ pointermax = Math.min( text1.length, text2.length );
+ pointermid = pointermax;
+ pointerstart = 0;
+ while ( pointermin < pointermid ) {
+ if ( text1.substring( pointerstart, pointermid ) === text2.substring( pointerstart, pointermid ) ) {
+ pointermin = pointermid;
+ pointerstart = pointermin;
+ } else {
+ pointermax = pointermid;
+ }
+ pointermid = Math.floor( ( pointermax - pointermin ) / 2 + pointermin );
+ }
+ return pointermid;
+ };
+
+ /**
+ * Determine the common suffix of two strings.
+ * @param {string} text1 First string.
+ * @param {string} text2 Second string.
+ * @return {number} The number of characters common to the end of each string.
+ */
+ DiffMatchPatch.prototype.diffCommonSuffix = function( text1, text2 ) {
+ var pointermid, pointermax, pointermin, pointerend;
+ // Quick check for common null cases.
+ if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) {
+ return 0;
+ }
+ // Binary search.
+ // Performance analysis: http://neil.fraser.name/news/2007/10/09/
+ pointermin = 0;
+ pointermax = Math.min(text1.length, text2.length);
+ pointermid = pointermax;
+ pointerend = 0;
+ while ( pointermin < pointermid ) {
+ if (text1.substring( text1.length - pointermid, text1.length - pointerend ) ===
+ text2.substring( text2.length - pointermid, text2.length - pointerend ) ) {
+ pointermin = pointermid;
+ pointerend = pointermin;
+ } else {
+ pointermax = pointermid;
+ }
+ pointermid = Math.floor( ( pointermax - pointermin ) / 2 + pointermin );
+ }
+ return pointermid;
+ };
+
+ /**
+ * Find the differences between two texts. Assumes that the texts do not
+ * have any common prefix or suffix.
+ * @param {string} text1 Old string to be diffed.
+ * @param {string} text2 New string to be diffed.
+ * @param {boolean} checklines Speedup flag. If false, then don't run a
+ * line-level diff first to identify the changed areas.
+ * If true, then run a faster, slightly less optimal diff.
+ * @param {number} deadline Time when the diff should be complete by.
+ * @return {!Array.} Array of diff tuples.
+ * @private
+ */
+ DiffMatchPatch.prototype.diffCompute = function( text1, text2, checklines, deadline ) {
+ var diffs, longtext, shorttext, i, hm,
+ text1A, text2A, text1B, text2B,
+ midCommon, diffsA, diffsB;
+
+ if ( !text1 ) {
+ // Just add some text (speedup).
+ return [
+ [ DIFF_INSERT, text2 ]
+ ];
+ }
+
+ if (!text2) {
+ // Just delete some text (speedup).
+ return [
+ [ DIFF_DELETE, text1 ]
+ ];
+ }
+
+ longtext = text1.length > text2.length ? text1 : text2;
+ shorttext = text1.length > text2.length ? text2 : text1;
+ i = longtext.indexOf( shorttext );
+ if ( i !== -1 ) {
+ // Shorter text is inside the longer text (speedup).
+ diffs = [
+ [ DIFF_INSERT, longtext.substring( 0, i ) ],
+ [ DIFF_EQUAL, shorttext ],
+ [ DIFF_INSERT, longtext.substring( i + shorttext.length ) ]
+ ];
+ // Swap insertions for deletions if diff is reversed.
+ if ( text1.length > text2.length ) {
+ diffs[0][0] = diffs[2][0] = DIFF_DELETE;
+ }
+ return diffs;
+ }
+
+ if ( shorttext.length === 1 ) {
+ // Single character string.
+ // After the previous speedup, the character can't be an equality.
+ return [
+ [ DIFF_DELETE, text1 ],
+ [ DIFF_INSERT, text2 ]
+ ];
+ }
+
+ // Check to see if the problem can be split in two.
+ hm = this.diffHalfMatch(text1, text2);
+ if (hm) {
+ // A half-match was found, sort out the return data.
+ text1A = hm[0];
+ text1B = hm[1];
+ text2A = hm[2];
+ text2B = hm[3];
+ midCommon = hm[4];
+ // Send both pairs off for separate processing.
+ diffsA = this.DiffMain(text1A, text2A, checklines, deadline);
+ diffsB = this.DiffMain(text1B, text2B, checklines, deadline);
+ // Merge the results.
+ return diffsA.concat([
+ [ DIFF_EQUAL, midCommon ]
+ ], diffsB);
+ }
+
+ if (checklines && text1.length > 100 && text2.length > 100) {
+ return this.diffLineMode(text1, text2, deadline);
+ }
+
+ return this.diffBisect(text1, text2, deadline);
+ };
+
+ /**
+ * Do the two texts share a substring which is at least half the length of the
+ * longer text?
+ * This speedup can produce non-minimal diffs.
+ * @param {string} text1 First string.
+ * @param {string} text2 Second string.
+ * @return {Array.} Five element Array, containing the prefix of
+ * text1, the suffix of text1, the prefix of text2, the suffix of
+ * text2 and the common middle. Or null if there was no match.
+ * @private
+ */
+ DiffMatchPatch.prototype.diffHalfMatch = function(text1, text2) {
+ var longtext, shorttext, dmp,
+ text1A, text2B, text2A, text1B, midCommon,
+ hm1, hm2, hm;
+ if (this.DiffTimeout <= 0) {
+ // Don't risk returning a non-optimal diff if we have unlimited time.
+ return null;
+ }
+ longtext = text1.length > text2.length ? text1 : text2;
+ shorttext = text1.length > text2.length ? text2 : text1;
+ if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
+ return null; // Pointless.
+ }
+ dmp = this; // 'this' becomes 'window' in a closure.
+
+ /**
+ * Does a substring of shorttext exist within longtext such that the substring
+ * is at least half the length of longtext?
+ * Closure, but does not reference any external variables.
+ * @param {string} longtext Longer string.
+ * @param {string} shorttext Shorter string.
+ * @param {number} i Start index of quarter length substring within longtext.
+ * @return {Array.} Five element Array, containing the prefix of
+ * longtext, the suffix of longtext, the prefix of shorttext, the suffix
+ * of shorttext and the common middle. Or null if there was no match.
+ * @private
+ */
+ function diffHalfMatchI(longtext, shorttext, i) {
+ var seed, j, bestCommon, prefixLength, suffixLength,
+ bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB;
+ // Start with a 1/4 length substring at position i as a seed.
+ seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
+ j = -1;
+ bestCommon = "";
+ while ((j = shorttext.indexOf(seed, j + 1)) !== -1) {
+ prefixLength = dmp.diffCommonPrefix(longtext.substring(i),
+ shorttext.substring(j));
+ suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i),
+ shorttext.substring(0, j));
+ if (bestCommon.length < suffixLength + prefixLength) {
+ bestCommon = shorttext.substring(j - suffixLength, j) +
+ shorttext.substring(j, j + prefixLength);
+ bestLongtextA = longtext.substring(0, i - suffixLength);
+ bestLongtextB = longtext.substring(i + prefixLength);
+ bestShorttextA = shorttext.substring(0, j - suffixLength);
+ bestShorttextB = shorttext.substring(j + prefixLength);
+ }
+ }
+ if (bestCommon.length * 2 >= longtext.length) {
+ return [ bestLongtextA, bestLongtextB,
+ bestShorttextA, bestShorttextB, bestCommon
+ ];
+ } else {
+ return null;
+ }
+ }
+
+ // First check if the second quarter is the seed for a half-match.
+ hm1 = diffHalfMatchI(longtext, shorttext,
+ Math.ceil(longtext.length / 4));
+ // Check again based on the third quarter.
+ hm2 = diffHalfMatchI(longtext, shorttext,
+ Math.ceil(longtext.length / 2));
+ if (!hm1 && !hm2) {
+ return null;
+ } else if (!hm2) {
+ hm = hm1;
+ } else if (!hm1) {
+ hm = hm2;
+ } else {
+ // Both matched. Select the longest.
+ hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
+ }
+
+ // A half-match was found, sort out the return data.
+ text1A, text1B, text2A, text2B;
+ if (text1.length > text2.length) {
+ text1A = hm[0];
+ text1B = hm[1];
+ text2A = hm[2];
+ text2B = hm[3];
+ } else {
+ text2A = hm[0];
+ text2B = hm[1];
+ text1A = hm[2];
+ text1B = hm[3];
+ }
+ midCommon = hm[4];
+ return [ text1A, text1B, text2A, text2B, midCommon ];
+ };
+
+ /**
+ * Do a quick line-level diff on both strings, then rediff the parts for
+ * greater accuracy.
+ * This speedup can produce non-minimal diffs.
+ * @param {string} text1 Old string to be diffed.
+ * @param {string} text2 New string to be diffed.
+ * @param {number} deadline Time when the diff should be complete by.
+ * @return {!Array.} Array of diff tuples.
+ * @private
+ */
+ DiffMatchPatch.prototype.diffLineMode = function(text1, text2, deadline) {
+ var a, diffs, linearray, pointer, countInsert,
+ countDelete, textInsert, textDelete, j;
+ // Scan the text on a line-by-line basis first.
+ a = this.diffLinesToChars(text1, text2);
+ text1 = a.chars1;
+ text2 = a.chars2;
+ linearray = a.lineArray;
+
+ diffs = this.DiffMain(text1, text2, false, deadline);
+
+ // Convert the diff back to original text.
+ this.diffCharsToLines(diffs, linearray);
+ // Eliminate freak matches (e.g. blank lines)
+ this.diffCleanupSemantic(diffs);
+
+ // Rediff any replacement blocks, this time character-by-character.
+ // Add a dummy entry at the end.
+ diffs.push( [ DIFF_EQUAL, "" ] );
+ pointer = 0;
+ countDelete = 0;
+ countInsert = 0;
+ textDelete = "";
+ textInsert = "";
+ while (pointer < diffs.length) {
+ switch ( diffs[pointer][0] ) {
+ case DIFF_INSERT:
+ countInsert++;
+ textInsert += diffs[pointer][1];
+ break;
+ case DIFF_DELETE:
+ countDelete++;
+ textDelete += diffs[pointer][1];
+ break;
+ case DIFF_EQUAL:
+ // Upon reaching an equality, check for prior redundancies.
+ if (countDelete >= 1 && countInsert >= 1) {
+ // Delete the offending records and add the merged ones.
+ diffs.splice(pointer - countDelete - countInsert,
+ countDelete + countInsert);
+ pointer = pointer - countDelete - countInsert;
+ a = this.DiffMain(textDelete, textInsert, false, deadline);
+ for (j = a.length - 1; j >= 0; j--) {
+ diffs.splice( pointer, 0, a[j] );
+ }
+ pointer = pointer + a.length;
+ }
+ countInsert = 0;
+ countDelete = 0;
+ textDelete = "";
+ textInsert = "";
+ break;
+ }
+ pointer++;
+ }
+ diffs.pop(); // Remove the dummy entry at the end.
+
+ return diffs;
+ };
+
+ /**
+ * Find the 'middle snake' of a diff, split the problem in two
+ * and return the recursively constructed diff.
+ * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
+ * @param {string} text1 Old string to be diffed.
+ * @param {string} text2 New string to be diffed.
+ * @param {number} deadline Time at which to bail if not yet complete.
+ * @return {!Array.} Array of diff tuples.
+ * @private
+ */
+ DiffMatchPatch.prototype.diffBisect = function(text1, text2, deadline) {
+ var text1Length, text2Length, maxD, vOffset, vLength,
+ v1, v2, x, delta, front, k1start, k1end, k2start,
+ k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2;
+ // Cache the text lengths to prevent multiple calls.
+ text1Length = text1.length;
+ text2Length = text2.length;
+ maxD = Math.ceil((text1Length + text2Length) / 2);
+ vOffset = maxD;
+ vLength = 2 * maxD;
+ v1 = new Array(vLength);
+ v2 = new Array(vLength);
+ // Setting all elements to -1 is faster in Chrome & Firefox than mixing
+ // integers and undefined.
+ for (x = 0; x < vLength; x++) {
+ v1[x] = -1;
+ v2[x] = -1;
+ }
+ v1[vOffset + 1] = 0;
+ v2[vOffset + 1] = 0;
+ delta = text1Length - text2Length;
+ // If the total number of characters is odd, then the front path will collide
+ // with the reverse path.
+ front = (delta % 2 !== 0);
+ // Offsets for start and end of k loop.
+ // Prevents mapping of space beyond the grid.
+ k1start = 0;
+ k1end = 0;
+ k2start = 0;
+ k2end = 0;
+ for (d = 0; d < maxD; d++) {
+ // Bail out if deadline is reached.
+ if ((new Date()).getTime() > deadline) {
+ break;
+ }
+
+ // Walk the front path one step.
+ for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
+ k1Offset = vOffset + k1;
+ if ( k1 === -d || ( k1 !== d && v1[ k1Offset - 1 ] < v1[ k1Offset + 1 ] ) ) {
+ x1 = v1[k1Offset + 1];
+ } else {
+ x1 = v1[k1Offset - 1] + 1;
+ }
+ y1 = x1 - k1;
+ while (x1 < text1Length && y1 < text2Length &&
+ text1.charAt(x1) === text2.charAt(y1)) {
+ x1++;
+ y1++;
+ }
+ v1[k1Offset] = x1;
+ if (x1 > text1Length) {
+ // Ran off the right of the graph.
+ k1end += 2;
+ } else if (y1 > text2Length) {
+ // Ran off the bottom of the graph.
+ k1start += 2;
+ } else if (front) {
+ k2Offset = vOffset + delta - k1;
+ if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
+ // Mirror x2 onto top-left coordinate system.
+ x2 = text1Length - v2[k2Offset];
+ if (x1 >= x2) {
+ // Overlap detected.
+ return this.diffBisectSplit(text1, text2, x1, y1, deadline);
+ }
+ }
+ }
+ }
+
+ // Walk the reverse path one step.
+ for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
+ k2Offset = vOffset + k2;
+ if ( k2 === -d || (k2 !== d && v2[ k2Offset - 1 ] < v2[ k2Offset + 1 ] ) ) {
+ x2 = v2[k2Offset + 1];
+ } else {
+ x2 = v2[k2Offset - 1] + 1;
+ }
+ y2 = x2 - k2;
+ while (x2 < text1Length && y2 < text2Length &&
+ text1.charAt(text1Length - x2 - 1) ===
+ text2.charAt(text2Length - y2 - 1)) {
+ x2++;
+ y2++;
+ }
+ v2[k2Offset] = x2;
+ if (x2 > text1Length) {
+ // Ran off the left of the graph.
+ k2end += 2;
+ } else if (y2 > text2Length) {
+ // Ran off the top of the graph.
+ k2start += 2;
+ } else if (!front) {
+ k1Offset = vOffset + delta - k2;
+ if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
+ x1 = v1[k1Offset];
+ y1 = vOffset + x1 - k1Offset;
+ // Mirror x2 onto top-left coordinate system.
+ x2 = text1Length - x2;
+ if (x1 >= x2) {
+ // Overlap detected.
+ return this.diffBisectSplit(text1, text2, x1, y1, deadline);
+ }
+ }
+ }
+ }
+ }
+ // Diff took too long and hit the deadline or
+ // number of diffs equals number of characters, no commonality at all.
+ return [
+ [ DIFF_DELETE, text1 ],
+ [ DIFF_INSERT, text2 ]
+ ];
+ };
+
+ /**
+ * Given the location of the 'middle snake', split the diff in two parts
+ * and recurse.
+ * @param {string} text1 Old string to be diffed.
+ * @param {string} text2 New string to be diffed.
+ * @param {number} x Index of split point in text1.
+ * @param {number} y Index of split point in text2.
+ * @param {number} deadline Time at which to bail if not yet complete.
+ * @return {!Array.} Array of diff tuples.
+ * @private
+ */
+ DiffMatchPatch.prototype.diffBisectSplit = function( text1, text2, x, y, deadline ) {
+ var text1a, text1b, text2a, text2b, diffs, diffsb;
+ text1a = text1.substring(0, x);
+ text2a = text2.substring(0, y);
+ text1b = text1.substring(x);
+ text2b = text2.substring(y);
+
+ // Compute both diffs serially.
+ diffs = this.DiffMain(text1a, text2a, false, deadline);
+ diffsb = this.DiffMain(text1b, text2b, false, deadline);
+
+ return diffs.concat(diffsb);
+ };
+
+ /**
+ * Reduce the number of edits by eliminating semantically trivial equalities.
+ * @param {!Array.} diffs Array of diff tuples.
+ */
+ DiffMatchPatch.prototype.diffCleanupSemantic = function(diffs) {
+ var changes, equalities, equalitiesLength, lastequality,
+ pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1,
+ lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2;
+ changes = false;
+ equalities = []; // Stack of indices where equalities are found.
+ equalitiesLength = 0; // Keeping our own length var is faster in JS.
+ /** @type {?string} */
+ lastequality = null;
+ // Always equal to diffs[equalities[equalitiesLength - 1]][1]
+ pointer = 0; // Index of current position.
+ // Number of characters that changed prior to the equality.
+ lengthInsertions1 = 0;
+ lengthDeletions1 = 0;
+ // Number of characters that changed after the equality.
+ lengthInsertions2 = 0;
+ lengthDeletions2 = 0;
+ while (pointer < diffs.length) {
+ if (diffs[pointer][0] === DIFF_EQUAL) { // Equality found.
+ equalities[equalitiesLength++] = pointer;
+ lengthInsertions1 = lengthInsertions2;
+ lengthDeletions1 = lengthDeletions2;
+ lengthInsertions2 = 0;
+ lengthDeletions2 = 0;
+ lastequality = diffs[pointer][1];
+ } else { // An insertion or deletion.
+ if (diffs[pointer][0] === DIFF_INSERT) {
+ lengthInsertions2 += diffs[pointer][1].length;
+ } else {
+ lengthDeletions2 += diffs[pointer][1].length;
+ }
+ // Eliminate an equality that is smaller or equal to the edits on both
+ // sides of it.
+ if (lastequality && (lastequality.length <=
+ Math.max(lengthInsertions1, lengthDeletions1)) &&
+ (lastequality.length <= Math.max(lengthInsertions2,
+ lengthDeletions2))) {
+ // Duplicate record.
+ diffs.splice( equalities[ equalitiesLength - 1 ], 0, [ DIFF_DELETE, lastequality ] );
+ // Change second copy to insert.
+ diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
+ // Throw away the equality we just deleted.
+ equalitiesLength--;
+ // Throw away the previous equality (it needs to be reevaluated).
+ equalitiesLength--;
+ pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
+ lengthInsertions1 = 0; // Reset the counters.
+ lengthDeletions1 = 0;
+ lengthInsertions2 = 0;
+ lengthDeletions2 = 0;
+ lastequality = null;
+ changes = true;
+ }
+ }
+ pointer++;
+ }
+
+ // Normalize the diff.
+ if (changes) {
+ this.diffCleanupMerge(diffs);
+ }
+
+ // Find any overlaps between deletions and insertions.
+ // e.g: abcxxxxxxdef
+ // -> abcxxxdef
+ // e.g: xxxabcdefxxx
+ // -> defxxxabc
+ // Only extract an overlap if it is as big as the edit ahead or behind it.
+ pointer = 1;
+ while (pointer < diffs.length) {
+ if (diffs[pointer - 1][0] === DIFF_DELETE &&
+ diffs[pointer][0] === DIFF_INSERT) {
+ deletion = diffs[pointer - 1][1];
+ insertion = diffs[pointer][1];
+ overlapLength1 = this.diffCommonOverlap(deletion, insertion);
+ overlapLength2 = this.diffCommonOverlap(insertion, deletion);
+ if (overlapLength1 >= overlapLength2) {
+ if (overlapLength1 >= deletion.length / 2 ||
+ overlapLength1 >= insertion.length / 2) {
+ // Overlap found. Insert an equality and trim the surrounding edits.
+ diffs.splice( pointer, 0, [ DIFF_EQUAL, insertion.substring( 0, overlapLength1 ) ] );
+ diffs[pointer - 1][1] =
+ deletion.substring(0, deletion.length - overlapLength1);
+ diffs[pointer + 1][1] = insertion.substring(overlapLength1);
+ pointer++;
+ }
+ } else {
+ if (overlapLength2 >= deletion.length / 2 ||
+ overlapLength2 >= insertion.length / 2) {
+ // Reverse overlap found.
+ // Insert an equality and swap and trim the surrounding edits.
+ diffs.splice( pointer, 0, [ DIFF_EQUAL, deletion.substring( 0, overlapLength2 ) ] );
+ diffs[pointer - 1][0] = DIFF_INSERT;
+ diffs[pointer - 1][1] =
+ insertion.substring(0, insertion.length - overlapLength2);
+ diffs[pointer + 1][0] = DIFF_DELETE;
+ diffs[pointer + 1][1] =
+ deletion.substring(overlapLength2);
+ pointer++;
+ }
+ }
+ pointer++;
+ }
+ pointer++;
+ }
+ };
+
+ /**
+ * Determine if the suffix of one string is the prefix of another.
+ * @param {string} text1 First string.
+ * @param {string} text2 Second string.
+ * @return {number} The number of characters common to the end of the first
+ * string and the start of the second string.
+ * @private
+ */
+ DiffMatchPatch.prototype.diffCommonOverlap = function(text1, text2) {
+ var text1Length, text2Length, textLength,
+ best, length, pattern, found;
+ // Cache the text lengths to prevent multiple calls.
+ text1Length = text1.length;
+ text2Length = text2.length;
+ // Eliminate the null case.
+ if (text1Length === 0 || text2Length === 0) {
+ return 0;
+ }
+ // Truncate the longer string.
+ if (text1Length > text2Length) {
+ text1 = text1.substring(text1Length - text2Length);
+ } else if (text1Length < text2Length) {
+ text2 = text2.substring(0, text1Length);
+ }
+ textLength = Math.min(text1Length, text2Length);
+ // Quick check for the worst case.
+ if (text1 === text2) {
+ return textLength;
+ }
+
+ // Start by looking for a single character match
+ // and increase length until no match is found.
+ // Performance analysis: http://neil.fraser.name/news/2010/11/04/
+ best = 0;
+ length = 1;
+ while (true) {
+ pattern = text1.substring(textLength - length);
+ found = text2.indexOf(pattern);
+ if (found === -1) {
+ return best;
+ }
+ length += found;
+ if (found === 0 || text1.substring(textLength - length) ===
+ text2.substring(0, length)) {
+ best = length;
+ length++;
+ }
+ }
+ };
+
+ /**
+ * Split two texts into an array of strings. Reduce the texts to a string of
+ * hashes where each Unicode character represents one line.
+ * @param {string} text1 First string.
+ * @param {string} text2 Second string.
+ * @return {{chars1: string, chars2: string, lineArray: !Array.}}
+ * An object containing the encoded text1, the encoded text2 and
+ * the array of unique strings.
+ * The zeroth element of the array of unique strings is intentionally blank.
+ * @private
+ */
+ DiffMatchPatch.prototype.diffLinesToChars = function(text1, text2) {
+ var lineArray, lineHash, chars1, chars2;
+ lineArray = []; // e.g. lineArray[4] === 'Hello\n'
+ lineHash = {}; // e.g. lineHash['Hello\n'] === 4
+
+ // '\x00' is a valid character, but various debuggers don't like it.
+ // So we'll insert a junk entry to avoid generating a null character.
+ lineArray[0] = "";
+
+ /**
+ * Split a text into an array of strings. Reduce the texts to a string of
+ * hashes where each Unicode character represents one line.
+ * Modifies linearray and linehash through being a closure.
+ * @param {string} text String to encode.
+ * @return {string} Encoded string.
+ * @private
+ */
+ function diffLinesToCharsMunge(text) {
+ var chars, lineStart, lineEnd, lineArrayLength, line;
+ chars = "";
+ // Walk the text, pulling out a substring for each line.
+ // text.split('\n') would would temporarily double our memory footprint.
+ // Modifying text would create many large strings to garbage collect.
+ lineStart = 0;
+ lineEnd = -1;
+ // Keeping our own length variable is faster than looking it up.
+ lineArrayLength = lineArray.length;
+ while (lineEnd < text.length - 1) {
+ lineEnd = text.indexOf("\n", lineStart);
+ if (lineEnd === -1) {
+ lineEnd = text.length - 1;
+ }
+ line = text.substring(lineStart, lineEnd + 1);
+ lineStart = lineEnd + 1;
+
+ if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) :
+ (lineHash[line] !== undefined)) {
+ chars += String.fromCharCode( lineHash[ line ] );
+ } else {
+ chars += String.fromCharCode(lineArrayLength);
+ lineHash[line] = lineArrayLength;
+ lineArray[lineArrayLength++] = line;
+ }
+ }
+ return chars;
+ }
+
+ chars1 = diffLinesToCharsMunge(text1);
+ chars2 = diffLinesToCharsMunge(text2);
+ return {
+ chars1: chars1,
+ chars2: chars2,
+ lineArray: lineArray
+ };
+ };
+
+ /**
+ * Rehydrate the text in a diff from a string of line hashes to real lines of
+ * text.
+ * @param {!Array.} diffs Array of diff tuples.
+ * @param {!Array.} lineArray Array of unique strings.
+ * @private
+ */
+ DiffMatchPatch.prototype.diffCharsToLines = function( diffs, lineArray ) {
+ var x, chars, text, y;
+ for ( x = 0; x < diffs.length; x++ ) {
+ chars = diffs[x][1];
+ text = [];
+ for ( y = 0; y < chars.length; y++ ) {
+ text[y] = lineArray[chars.charCodeAt(y)];
+ }
+ diffs[x][1] = text.join("");
+ }
+ };
+
+ /**
+ * Reorder and merge like edit sections. Merge equalities.
+ * Any edit section can move as long as it doesn't cross an equality.
+ * @param {!Array.} diffs Array of diff tuples.
+ */
+ DiffMatchPatch.prototype.diffCleanupMerge = function(diffs) {
+ var pointer, countDelete, countInsert, textInsert, textDelete,
+ commonlength, changes;
+ diffs.push( [ DIFF_EQUAL, "" ] ); // Add a dummy entry at the end.
+ pointer = 0;
+ countDelete = 0;
+ countInsert = 0;
+ textDelete = "";
+ textInsert = "";
+ commonlength;
+ while (pointer < diffs.length) {
+ switch ( diffs[ pointer ][ 0 ] ) {
+ case DIFF_INSERT:
+ countInsert++;
+ textInsert += diffs[pointer][1];
+ pointer++;
+ break;
+ case DIFF_DELETE:
+ countDelete++;
+ textDelete += diffs[pointer][1];
+ pointer++;
+ break;
+ case DIFF_EQUAL:
+ // Upon reaching an equality, check for prior redundancies.
+ if (countDelete + countInsert > 1) {
+ if (countDelete !== 0 && countInsert !== 0) {
+ // Factor out any common prefixies.
+ commonlength = this.diffCommonPrefix(textInsert, textDelete);
+ if (commonlength !== 0) {
+ if ((pointer - countDelete - countInsert) > 0 &&
+ diffs[pointer - countDelete - countInsert - 1][0] ===
+ DIFF_EQUAL) {
+ diffs[pointer - countDelete - countInsert - 1][1] +=
+ textInsert.substring(0, commonlength);
+ } else {
+ diffs.splice( 0, 0, [ DIFF_EQUAL,
+ textInsert.substring( 0, commonlength )
+ ] );
+ pointer++;
+ }
+ textInsert = textInsert.substring(commonlength);
+ textDelete = textDelete.substring(commonlength);
+ }
+ // Factor out any common suffixies.
+ commonlength = this.diffCommonSuffix(textInsert, textDelete);
+ if (commonlength !== 0) {
+ diffs[pointer][1] = textInsert.substring(textInsert.length -
+ commonlength) + diffs[pointer][1];
+ textInsert = textInsert.substring(0, textInsert.length -
+ commonlength);
+ textDelete = textDelete.substring(0, textDelete.length -
+ commonlength);
+ }
+ }
+ // Delete the offending records and add the merged ones.
+ if (countDelete === 0) {
+ diffs.splice( pointer - countInsert,
+ countDelete + countInsert, [ DIFF_INSERT, textInsert ] );
+ } else if (countInsert === 0) {
+ diffs.splice( pointer - countDelete,
+ countDelete + countInsert, [ DIFF_DELETE, textDelete ] );
+ } else {
+ diffs.splice( pointer - countDelete - countInsert,
+ countDelete + countInsert, [ DIFF_DELETE, textDelete ], [ DIFF_INSERT, textInsert ] );
+ }
+ pointer = pointer - countDelete - countInsert +
+ (countDelete ? 1 : 0) + (countInsert ? 1 : 0) + 1;
+ } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {
+ // Merge this equality with the previous one.
+ diffs[pointer - 1][1] += diffs[pointer][1];
+ diffs.splice(pointer, 1);
+ } else {
+ pointer++;
+ }
+ countInsert = 0;
+ countDelete = 0;
+ textDelete = "";
+ textInsert = "";
+ break;
+ }
+ }
+ if (diffs[diffs.length - 1][1] === "") {
+ diffs.pop(); // Remove the dummy entry at the end.
+ }
+
+ // Second pass: look for single edits surrounded on both sides by equalities
+ // which can be shifted sideways to eliminate an equality.
+ // e.g: ABAC -> ABAC
+ changes = false;
+ pointer = 1;
+ // Intentionally ignore the first and last element (don't need checking).
+ while (pointer < diffs.length - 1) {
+ if (diffs[pointer - 1][0] === DIFF_EQUAL &&
+ diffs[pointer + 1][0] === DIFF_EQUAL) {
+ // This is a single edit surrounded by equalities.
+ if ( diffs[ pointer ][ 1 ].substring( diffs[ pointer ][ 1 ].length -
+ diffs[ pointer - 1 ][ 1 ].length ) === diffs[ pointer - 1 ][ 1 ] ) {
+ // Shift the edit over the previous equality.
+ diffs[pointer][1] = diffs[pointer - 1][1] +
+ diffs[pointer][1].substring(0, diffs[pointer][1].length -
+ diffs[pointer - 1][1].length);
+ diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
+ diffs.splice(pointer - 1, 1);
+ changes = true;
+ } else if ( diffs[ pointer ][ 1 ].substring( 0, diffs[ pointer + 1 ][ 1 ].length ) ===
+ diffs[ pointer + 1 ][ 1 ] ) {
+ // Shift the edit over the next equality.
+ diffs[pointer - 1][1] += diffs[pointer + 1][1];
+ diffs[pointer][1] =
+ diffs[pointer][1].substring(diffs[pointer + 1][1].length) +
+ diffs[pointer + 1][1];
+ diffs.splice(pointer + 1, 1);
+ changes = true;
+ }
+ }
+ pointer++;
+ }
+ // If shifts were made, the diff needs reordering and another shift sweep.
+ if (changes) {
+ this.diffCleanupMerge(diffs);
+ }
+ };
+
+ return function(o, n) {
+ var diff, output, text;
+ diff = new DiffMatchPatch();
+ output = diff.DiffMain(o, n);
+ //console.log(output);
+ diff.diffCleanupEfficiency(output);
+ text = diff.diffPrettyHtml(output);
+
+ return text;
+ };
+}());
+// jscs:enable
+
+(function() {
+
+// Deprecated QUnit.init - Ref #530
+// Re-initialize the configuration options
+QUnit.init = function() {
+ var tests, banner, result, qunit,
+ config = QUnit.config;
+
+ config.stats = { all: 0, bad: 0 };
+ config.moduleStats = { all: 0, bad: 0 };
+ config.started = 0;
+ config.updateRate = 1000;
+ config.blocking = false;
+ config.autostart = true;
+ config.autorun = false;
+ config.filter = "";
+ config.queue = [];
+
+ // Return on non-browser environments
+ // This is necessary to not break on node tests
+ if ( typeof window === "undefined" ) {
+ return;
+ }
+
+ qunit = id( "qunit" );
+ if ( qunit ) {
+ qunit.innerHTML =
+ "
" + escapeText( document.title ) + "
" +
+ "" +
+ "" +
+ "" +
+ "";
+ }
+
+ tests = id( "qunit-tests" );
+ banner = id( "qunit-banner" );
+ result = id( "qunit-testresult" );
+
+ if ( tests ) {
+ tests.innerHTML = "";
+ }
+
+ if ( banner ) {
+ banner.className = "";
+ }
+
+ if ( result ) {
+ result.parentNode.removeChild( result );
+ }
+
+ if ( tests ) {
+ result = document.createElement( "p" );
+ result.id = "qunit-testresult";
+ result.className = "result";
+ tests.parentNode.insertBefore( result, tests );
+ result.innerHTML = "Running... ";
+ }
+};
+
+// Don't load the HTML Reporter on non-Browser environments
+if ( typeof window === "undefined" ) {
+ return;
+}
+
+var config = QUnit.config,
+ hasOwn = Object.prototype.hasOwnProperty,
+ defined = {
+ document: window.document !== undefined,
+ sessionStorage: (function() {
+ var x = "qunit-test-string";
+ try {
+ sessionStorage.setItem( x, x );
+ sessionStorage.removeItem( x );
+ return true;
+ } catch ( e ) {
+ return false;
+ }
+ }())
+ },
+ modulesList = [];
+
+/**
+* Escape text for attribute or text content.
+*/
+function escapeText( s ) {
+ if ( !s ) {
+ return "";
+ }
+ s = s + "";
+
+ // Both single quotes and double quotes (for attributes)
+ return s.replace( /['"<>&]/g, function( s ) {
+ switch ( s ) {
+ case "'":
+ return "'";
+ case "\"":
+ return """;
+ case "<":
+ return "<";
+ case ">":
+ return ">";
+ case "&":
+ return "&";
+ }
+ });
+}
+
+/**
+ * @param {HTMLElement} elem
+ * @param {string} type
+ * @param {Function} fn
+ */
+function addEvent( elem, type, fn ) {
+ if ( elem.addEventListener ) {
+
+ // Standards-based browsers
+ elem.addEventListener( type, fn, false );
+ } else if ( elem.attachEvent ) {
+
+ // support: IE <9
+ elem.attachEvent( "on" + type, function() {
+ var event = window.event;
+ if ( !event.target ) {
+ event.target = event.srcElement || document;
+ }
+
+ fn.call( elem, event );
+ });
+ }
+}
+
+/**
+ * @param {Array|NodeList} elems
+ * @param {string} type
+ * @param {Function} fn
+ */
+function addEvents( elems, type, fn ) {
+ var i = elems.length;
+ while ( i-- ) {
+ addEvent( elems[ i ], type, fn );
+ }
+}
+
+function hasClass( elem, name ) {
+ return ( " " + elem.className + " " ).indexOf( " " + name + " " ) >= 0;
+}
+
+function addClass( elem, name ) {
+ if ( !hasClass( elem, name ) ) {
+ elem.className += ( elem.className ? " " : "" ) + name;
+ }
+}
+
+function toggleClass( elem, name ) {
+ if ( hasClass( elem, name ) ) {
+ removeClass( elem, name );
+ } else {
+ addClass( elem, name );
+ }
+}
+
+function removeClass( elem, name ) {
+ var set = " " + elem.className + " ";
+
+ // Class name may appear multiple times
+ while ( set.indexOf( " " + name + " " ) >= 0 ) {
+ set = set.replace( " " + name + " ", " " );
+ }
+
+ // trim for prettiness
+ elem.className = typeof set.trim === "function" ? set.trim() : set.replace( /^\s+|\s+$/g, "" );
+}
+
+function id( name ) {
+ return defined.document && document.getElementById && document.getElementById( name );
+}
+
+function getUrlConfigHtml() {
+ var i, j, val,
+ escaped, escapedTooltip,
+ selection = false,
+ len = config.urlConfig.length,
+ urlConfigHtml = "";
+
+ for ( i = 0; i < len; i++ ) {
+ val = config.urlConfig[ i ];
+ if ( typeof val === "string" ) {
+ val = {
+ id: val,
+ label: val
+ };
+ }
+
+ escaped = escapeText( val.id );
+ escapedTooltip = escapeText( val.tooltip );
+
+ if ( config[ val.id ] === undefined ) {
+ config[ val.id ] = QUnit.urlParams[ val.id ];
+ }
+
+ if ( !val.value || typeof val.value === "string" ) {
+ urlConfigHtml += "";
+ } else {
+ urlConfigHtml += "";
+ }
+ }
+
+ return urlConfigHtml;
+}
+
+// Handle "click" events on toolbar checkboxes and "change" for select menus.
+// Updates the URL with the new state of `config.urlConfig` values.
+function toolbarChanged() {
+ var updatedUrl, value,
+ field = this,
+ params = {};
+
+ // Detect if field is a select menu or a checkbox
+ if ( "selectedIndex" in field ) {
+ value = field.options[ field.selectedIndex ].value || undefined;
+ } else {
+ value = field.checked ? ( field.defaultValue || true ) : undefined;
+ }
+
+ params[ field.name ] = value;
+ updatedUrl = setUrl( params );
+
+ if ( "hidepassed" === field.name && "replaceState" in window.history ) {
+ config[ field.name ] = value || false;
+ if ( value ) {
+ addClass( id( "qunit-tests" ), "hidepass" );
+ } else {
+ removeClass( id( "qunit-tests" ), "hidepass" );
+ }
+
+ // It is not necessary to refresh the whole page
+ window.history.replaceState( null, "", updatedUrl );
+ } else {
+ window.location = updatedUrl;
+ }
+}
+
+function setUrl( params ) {
+ var key,
+ querystring = "?";
+
+ params = QUnit.extend( QUnit.extend( {}, QUnit.urlParams ), params );
+
+ for ( key in params ) {
+ if ( hasOwn.call( params, key ) ) {
+ if ( params[ key ] === undefined ) {
+ continue;
+ }
+ querystring += encodeURIComponent( key );
+ if ( params[ key ] !== true ) {
+ querystring += "=" + encodeURIComponent( params[ key ] );
+ }
+ querystring += "&";
+ }
+ }
+ return location.protocol + "//" + location.host +
+ location.pathname + querystring.slice( 0, -1 );
+}
+
+function applyUrlParams() {
+ var selectedModule,
+ modulesList = id( "qunit-modulefilter" ),
+ filter = id( "qunit-filter-input" ).value;
+
+ selectedModule = modulesList ?
+ decodeURIComponent( modulesList.options[ modulesList.selectedIndex ].value ) :
+ undefined;
+
+ window.location = setUrl({
+ module: ( selectedModule === "" ) ? undefined : selectedModule,
+ filter: ( filter === "" ) ? undefined : filter,
+
+ // Remove testId filter
+ testId: undefined
+ });
+}
+
+function toolbarUrlConfigContainer() {
+ var urlConfigContainer = document.createElement( "span" );
+
+ urlConfigContainer.innerHTML = getUrlConfigHtml();
+ addClass( urlConfigContainer, "qunit-url-config" );
+
+ // For oldIE support:
+ // * Add handlers to the individual elements instead of the container
+ // * Use "click" instead of "change" for checkboxes
+ addEvents( urlConfigContainer.getElementsByTagName( "input" ), "click", toolbarChanged );
+ addEvents( urlConfigContainer.getElementsByTagName( "select" ), "change", toolbarChanged );
+
+ return urlConfigContainer;
+}
+
+function toolbarLooseFilter() {
+ var filter = document.createElement( "form" ),
+ label = document.createElement( "label" ),
+ input = document.createElement( "input" ),
+ button = document.createElement( "button" );
+
+ addClass( filter, "qunit-filter" );
+
+ label.innerHTML = "Filter: ";
+
+ input.type = "text";
+ input.value = config.filter || "";
+ input.name = "filter";
+ input.id = "qunit-filter-input";
+
+ button.innerHTML = "Go";
+
+ label.appendChild( input );
+
+ filter.appendChild( label );
+ filter.appendChild( button );
+ addEvent( filter, "submit", function( ev ) {
+ applyUrlParams();
+
+ if ( ev && ev.preventDefault ) {
+ ev.preventDefault();
+ }
+
+ return false;
+ });
+
+ return filter;
+}
+
+function toolbarModuleFilterHtml() {
+ var i,
+ moduleFilterHtml = "";
+
+ if ( !modulesList.length ) {
+ return false;
+ }
+
+ modulesList.sort(function( a, b ) {
+ return a.localeCompare( b );
+ });
+
+ moduleFilterHtml += "" +
+ "";
+
+ return moduleFilterHtml;
+}
+
+function toolbarModuleFilter() {
+ var toolbar = id( "qunit-testrunner-toolbar" ),
+ moduleFilter = document.createElement( "span" ),
+ moduleFilterHtml = toolbarModuleFilterHtml();
+
+ if ( !toolbar || !moduleFilterHtml ) {
+ return false;
+ }
+
+ moduleFilter.setAttribute( "id", "qunit-modulefilter-container" );
+ moduleFilter.innerHTML = moduleFilterHtml;
+
+ addEvent( moduleFilter.lastChild, "change", applyUrlParams );
+
+ toolbar.appendChild( moduleFilter );
+}
+
+function appendToolbar() {
+ var toolbar = id( "qunit-testrunner-toolbar" );
+
+ if ( toolbar ) {
+ toolbar.appendChild( toolbarUrlConfigContainer() );
+ toolbar.appendChild( toolbarLooseFilter() );
+ }
+}
+
+function appendHeader() {
+ var header = id( "qunit-header" );
+
+ if ( header ) {
+ header.innerHTML = "" + header.innerHTML + " ";
+ }
+}
+
+function appendBanner() {
+ var banner = id( "qunit-banner" );
+
+ if ( banner ) {
+ banner.className = "";
+ }
+}
+
+function appendTestResults() {
+ var tests = id( "qunit-tests" ),
+ result = id( "qunit-testresult" );
+
+ if ( result ) {
+ result.parentNode.removeChild( result );
+ }
+
+ if ( tests ) {
+ tests.innerHTML = "";
+ result = document.createElement( "p" );
+ result.id = "qunit-testresult";
+ result.className = "result";
+ tests.parentNode.insertBefore( result, tests );
+ result.innerHTML = "Running... ";
+ }
+}
+
+function storeFixture() {
+ var fixture = id( "qunit-fixture" );
+ if ( fixture ) {
+ config.fixture = fixture.innerHTML;
+ }
+}
+
+function appendUserAgent() {
+ var userAgent = id( "qunit-userAgent" );
+
+ if ( userAgent ) {
+ userAgent.innerHTML = "";
+ userAgent.appendChild(
+ document.createTextNode(
+ "QUnit " + QUnit.version + "; " + navigator.userAgent
+ )
+ );
+ }
+}
+
+function appendTestsList( modules ) {
+ var i, l, x, z, test, moduleObj;
+
+ for ( i = 0, l = modules.length; i < l; i++ ) {
+ moduleObj = modules[ i ];
+
+ if ( moduleObj.name ) {
+ modulesList.push( moduleObj.name );
+ }
+
+ for ( x = 0, z = moduleObj.tests.length; x < z; x++ ) {
+ test = moduleObj.tests[ x ];
+
+ appendTest( test.name, test.testId, moduleObj.name );
+ }
+ }
+}
+
+function appendTest( name, testId, moduleName ) {
+ var title, rerunTrigger, testBlock, assertList,
+ tests = id( "qunit-tests" );
+
+ if ( !tests ) {
+ return;
+ }
+
+ title = document.createElement( "strong" );
+ title.innerHTML = getNameHtml( name, moduleName );
+
+ rerunTrigger = document.createElement( "a" );
+ rerunTrigger.innerHTML = "Rerun";
+ rerunTrigger.href = setUrl({ testId: testId });
+
+ testBlock = document.createElement( "li" );
+ testBlock.appendChild( title );
+ testBlock.appendChild( rerunTrigger );
+ testBlock.id = "qunit-test-output-" + testId;
+
+ assertList = document.createElement( "ol" );
+ assertList.className = "qunit-assert-list";
+
+ testBlock.appendChild( assertList );
+
+ tests.appendChild( testBlock );
+}
+
+// HTML Reporter initialization and load
+QUnit.begin(function( details ) {
+ var qunit = id( "qunit" );
+
+ // Fixture is the only one necessary to run without the #qunit element
+ storeFixture();
+
+ if ( qunit ) {
+ qunit.innerHTML =
+ "
" + escapeText( document.title ) + "
" +
+ "" +
+ "" +
+ "" +
+ "";
+ }
+
+ appendHeader();
+ appendBanner();
+ appendTestResults();
+ appendUserAgent();
+ appendToolbar();
+ appendTestsList( details.modules );
+ toolbarModuleFilter();
+
+ if ( qunit && config.hidepassed ) {
+ addClass( qunit.lastChild, "hidepass" );
+ }
+});
+
+QUnit.done(function( details ) {
+ var i, key,
+ banner = id( "qunit-banner" ),
+ tests = id( "qunit-tests" ),
+ html = [
+ "Tests completed in ",
+ details.runtime,
+ " milliseconds. ",
+ "",
+ details.passed,
+ " assertions of ",
+ details.total,
+ " passed, ",
+ details.failed,
+ " failed."
+ ].join( "" );
+
+ if ( banner ) {
+ banner.className = details.failed ? "qunit-fail" : "qunit-pass";
+ }
+
+ if ( tests ) {
+ id( "qunit-testresult" ).innerHTML = html;
+ }
+
+ if ( config.altertitle && defined.document && document.title ) {
+
+ // show ✖ for good, ✔ for bad suite result in title
+ // use escape sequences in case file gets loaded with non-utf-8-charset
+ document.title = [
+ ( details.failed ? "\u2716" : "\u2714" ),
+ document.title.replace( /^[\u2714\u2716] /i, "" )
+ ].join( " " );
+ }
+
+ // clear own sessionStorage items if all tests passed
+ if ( config.reorder && defined.sessionStorage && details.failed === 0 ) {
+ for ( i = 0; i < sessionStorage.length; i++ ) {
+ key = sessionStorage.key( i++ );
+ if ( key.indexOf( "qunit-test-" ) === 0 ) {
+ sessionStorage.removeItem( key );
+ }
+ }
+ }
+
+ // scroll back to top to show results
+ if ( config.scrolltop && window.scrollTo ) {
+ window.scrollTo( 0, 0 );
+ }
+});
+
+function getNameHtml( name, module ) {
+ var nameHtml = "";
+
+ if ( module ) {
+ nameHtml = "" + escapeText( module ) + ": ";
+ }
+
+ nameHtml += "" + escapeText( name ) + "";
+
+ return nameHtml;
+}
+
+QUnit.testStart(function( details ) {
+ var running, testBlock, bad;
+
+ testBlock = id( "qunit-test-output-" + details.testId );
+ if ( testBlock ) {
+ testBlock.className = "running";
+ } else {
+
+ // Report later registered tests
+ appendTest( details.name, details.testId, details.module );
+ }
+
+ running = id( "qunit-testresult" );
+ if ( running ) {
+ bad = QUnit.config.reorder && defined.sessionStorage &&
+ +sessionStorage.getItem( "qunit-test-" + details.module + "-" + details.name );
+
+ running.innerHTML = ( bad ?
+ "Rerunning previously failed test: " :
+ "Running: " ) +
+ getNameHtml( details.name, details.module );
+ }
+
+});
+
+QUnit.log(function( details ) {
+ var assertList, assertLi,
+ message, expected, actual,
+ testItem = id( "qunit-test-output-" + details.testId );
+
+ if ( !testItem ) {
+ return;
+ }
+
+ message = escapeText( details.message ) || ( details.result ? "okay" : "failed" );
+ message = "" + message + "";
+ message += "@ " + details.runtime + " ms";
+
+ // pushFailure doesn't provide details.expected
+ // when it calls, it's implicit to also not show expected and diff stuff
+ // Also, we need to check details.expected existence, as it can exist and be undefined
+ if ( !details.result && hasOwn.call( details, "expected" ) ) {
+ expected = escapeText( QUnit.dump.parse( details.expected ) );
+ actual = escapeText( QUnit.dump.parse( details.actual ) );
+ message += "
Expected:
" +
+ expected +
+ "
";
+
+ if ( actual !== expected ) {
+ message += "
";
+
+ // this occours when pushFailure is set and we have an extracted stack trace
+ } else if ( !details.result && details.source ) {
+ message += "
" +
+ "
Source:
" +
+ escapeText( details.source ) + "
" +
+ "
";
+ }
+
+ assertList = testItem.getElementsByTagName( "ol" )[ 0 ];
+
+ assertLi = document.createElement( "li" );
+ assertLi.className = details.result ? "pass" : "fail";
+ assertLi.innerHTML = message;
+ assertList.appendChild( assertLi );
+});
+
+QUnit.testDone(function( details ) {
+ var testTitle, time, testItem, assertList,
+ good, bad, testCounts, skipped,
+ tests = id( "qunit-tests" );
+
+ if ( !tests ) {
+ return;
+ }
+
+ testItem = id( "qunit-test-output-" + details.testId );
+
+ assertList = testItem.getElementsByTagName( "ol" )[ 0 ];
+
+ good = details.passed;
+ bad = details.failed;
+
+ // store result when possible
+ if ( config.reorder && defined.sessionStorage ) {
+ if ( bad ) {
+ sessionStorage.setItem( "qunit-test-" + details.module + "-" + details.name, bad );
+ } else {
+ sessionStorage.removeItem( "qunit-test-" + details.module + "-" + details.name );
+ }
+ }
+
+ if ( bad === 0 ) {
+ addClass( assertList, "qunit-collapsed" );
+ }
+
+ // testItem.firstChild is the test name
+ testTitle = testItem.firstChild;
+
+ testCounts = bad ?
+ "" + bad + ", " + "" + good + ", " :
+ "";
+
+ testTitle.innerHTML += " (" + testCounts +
+ details.assertions.length + ")";
+
+ if ( details.skipped ) {
+ testItem.className = "skipped";
+ skipped = document.createElement( "em" );
+ skipped.className = "qunit-skipped-label";
+ skipped.innerHTML = "skipped";
+ testItem.insertBefore( skipped, testTitle );
+ } else {
+ addEvent( testTitle, "click", function() {
+ toggleClass( assertList, "qunit-collapsed" );
+ });
+
+ testItem.className = bad ? "fail" : "pass";
+
+ time = document.createElement( "span" );
+ time.className = "runtime";
+ time.innerHTML = details.runtime + " ms";
+ testItem.insertBefore( time, assertList );
+ }
+});
+
+if ( defined.document ) {
+ if ( document.readyState === "complete" ) {
+ QUnit.load();
+ } else {
+ addEvent( window, "load", QUnit.load );
+ }
+} else {
+ config.pageLoaded = true;
+ config.autorun = true;
+}
+
+})();
diff --git a/tests/static/js/lib/qunit-parameterize.js b/tests/static/js/lib/qunit-parameterize.js
new file mode 100644
index 000000000..0d0067e52
--- /dev/null
+++ b/tests/static/js/lib/qunit-parameterize.js
@@ -0,0 +1,133 @@
+/*
+ * Parameterize v 0.4
+ * A QUnit Addon For Running Parameterized Tests
+ * https://github.com/AStepaniuk/qunit-parameterize
+ * Released under the MIT license.
+ */
+QUnit.extend(QUnit, {
+ cases : function(testCases) {
+ var currentCases = testCases;
+
+ var createTest = function(methodName, title, expected, callback, parameters) {
+ QUnit[methodName](
+ title,
+ expected,
+ function(assert) { return callback.call(this, parameters, assert); }
+ );
+ };
+
+ var iterateTestCases = function(methodName, title, expected, callback) {
+ if (!currentCases || currentCases.length == 0) {
+ // setup test which will always fail
+ QUnit.test(title, function(assert) {
+ assert.ok(false, "No test cases are provided");
+ });
+ return;
+ }
+
+ if (!callback) {
+ callback = expected;
+ expected = null;
+ }
+
+ for (var i = 0; i < currentCases.length; ++i) {
+ var parameters = currentCases[i];
+
+ var testCaseTitle = title;
+ if (parameters.title) {
+ testCaseTitle += "[" + parameters.title + "]";
+ }
+
+ createTest(methodName, testCaseTitle, expected, callback, parameters);
+ }
+ }
+
+ var getLength = function(arr) {
+ return arr ? arr.length : 0;
+ }
+
+ var getItem = function(arr, idx) {
+ return arr ? arr[idx] : undefined;
+ }
+
+ var mix = function(testCase, mixData) {
+ if (testCase && mixData) {
+ var result = clone(testCase);
+ for(var p in mixData) {
+ if (p !== "title") {
+ if (!(p in result)) result[p] = mixData[p];
+ } else {
+ result[p] = [result[p], mixData[p]].join("");
+ }
+ }
+ return result;
+ } else if (testCase) {
+ return testCase;
+ } else if (mixData) {
+ return mixData;
+ } else {
+ // return null or undefined whatever testCase is
+ return testCase;
+ }
+ }
+
+ var clone = function(testCase) {
+ var result = {};
+ for (var p in testCase) {
+ result[p] = testCase[p];
+ }
+ return result;
+ }
+
+ return {
+ sequential : function(addData) {
+ var casesLength = getLength(currentCases);
+ var addDataLength = getLength(addData);
+ var length = casesLength > addDataLength ? casesLength : addDataLength;
+
+ var newCases = [];
+ for (var i = 0; i < length; ++i) {
+ var currentCaseI = getItem(currentCases, i);
+ var dataI = getItem(addData, i);
+ var newCase = mix(currentCaseI, dataI);
+
+ if (newCase) newCases.push(newCase);
+ }
+ currentCases = newCases;
+
+ return this;
+ },
+
+ combinatorial : function(mixData) {
+ var current = (currentCases && currentCases.length > 0) ? currentCases : [ null ];
+ mixData = (mixData && mixData.length > 0) ? mixData : [ null ];
+ var currentLength = current.length;
+ var mixDataLength = mixData.length;
+
+ var newCases = [];
+ for (var i = 0; i < currentLength; ++i) {
+ for(var j = 0; j < mixDataLength; ++j) {
+ var currentCaseI = current[i];
+ var dataJ = mixData[j];
+ var newCase = mix(currentCaseI, dataJ);
+
+ if (newCase) newCases.push(newCase);
+ }
+ }
+ currentCases = newCases;
+
+ return this;
+ },
+
+ test : function(title, expected, callback) {
+ iterateTestCases("test", title, expected, callback);
+ return this;
+ },
+
+ asyncTest : function(title, expected, callback) {
+ iterateTestCases("asyncTest", title, expected, callback);
+ return this;
+ }
+ }
+ }
+});
diff --git a/tests/static/js/test-helpers.html b/tests/static/js/test-helpers.html
new file mode 100644
index 000000000..98290b80f
--- /dev/null
+++ b/tests/static/js/test-helpers.html
@@ -0,0 +1,18 @@
+
+
+
+
+ src/octoprint/static/js/app/helpers.js Tests
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/static/js/test-helpers.js b/tests/static/js/test-helpers.js
new file mode 100644
index 000000000..4f0ee9fa6
--- /dev/null
+++ b/tests/static/js/test-helpers.js
@@ -0,0 +1,80 @@
+_.mixin({"sprintf": sprintf, "vsprintf": vsprintf});
+
+QUnit.module("bytesFromSize");
+QUnit
+ .cases(function(){
+ var cases = [];
+
+ var params = [
+ // empty inputs
+ { input: undefined, expected: undefined },
+ { input: "", expected: undefined },
+
+ // unknown units
+ { input: "1 PB", expected: undefined },
+ { input: "234.5 unknown", expected: undefined },
+ { input: "234.5unknown", expected: undefined },
+
+ // conversion
+ { input: "1", expected: 1 },
+ { input: "1b", expected: 1 },
+ { input: "1 B", expected: 1 },
+ { input: "1 byte", expected: 1 },
+ { input: "1 bYtES", expected: 1 },
+ { input: "1.1", expected: 1.1 },
+ { input: ".1", expected: 0.1 },
+ { input: "1 KB", expected: 1024 },
+ { input: "2 KB", expected: 2048 },
+ { input: "1 MB", expected: Math.pow(1024, 2)},
+ { input: "500mb", expected: 500 * Math.pow(1024, 2)},
+ { input: "500.2mb", expected: 500.2 * Math.pow(1024, 2)},
+ { input: "1 GB", expected: Math.pow(1024, 3)},
+ { input: "1 TB", expected: Math.pow(1024, 4)}
+ ];
+
+ var param, i;
+ for (i = 0; i < params.length; i++) {
+ param = params[i];
+ param["title"] = param.input != undefined ? '"' + String(param.input) + '"' : "undefined";
+ cases.push(param);
+ }
+
+ return cases;
+ }())
+ .test("bytesFromSize", function(params, assert) {
+ assert.equal(params.expected, bytesFromSize(params.input), "As expected: " + String(params.expected));
+ }
+);
+
+QUnit.module("formatSize");
+QUnit
+ .cases(function(){
+ var cases = [];
+
+ var params = [
+ { input: undefined, expected: "-" },
+ { input: "", expected: "-" },
+ { input: 1, expected: "1.0bytes" },
+ { input: 1.1, expected: "1.1bytes" },
+ { input: 1024, expected: "1.0KB" },
+ { input: 2048, expected: "2.0KB" },
+ { input: 2.2 * 1024, expected: "2.2KB" },
+ { input: 23.5 * Math.pow(1024, 2), expected: "23.5MB" },
+ { input: 23.5 * Math.pow(1024, 3), expected: "23.5GB" },
+ { input: 23.5 * Math.pow(1024, 4), expected: "23.5TB" },
+ { input: 2 * Math.pow(1024, 5), expected: "2048.0TB" }
+ ];
+
+ var param, i;
+ for (i = 0; i < params.length; i++) {
+ param = params[i];
+ param["title"] = String(param.input);
+ cases.push(param);
+ }
+
+ return cases;
+ }())
+ .test("formatSize", function(params, assert) {
+ assert.equal(params.expected, formatSize(params.input), "As expected: " + String(params.expected));
+ }
+);
diff --git a/tests/users/__init__.py b/tests/users/__init__.py
new file mode 100644
index 000000000..f9f102db8
--- /dev/null
+++ b/tests/users/__init__.py
@@ -0,0 +1,112 @@
+# coding=utf-8
+"""
+Unit tests for octoprint.users
+"""
+from __future__ import absolute_import
+
+__author__ = "Gina Häußge "
+__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
+__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
+
+import unittest
+import ddt
+
+import octoprint.users
+from octoprint.util import dict_merge
+
+default_settings = dict(key="value", sub=dict(subkey="subvalue"))
+
+@ddt.ddt
+class UserTestCase(unittest.TestCase):
+ def setUp(self):
+ self.user = octoprint.users.User("user", "passwordHash", True, ("user",), apikey="apikey_user", settings=default_settings)
+ self.admin = octoprint.users.User("admin", "passwordHash", True, ("user","admin"), apikey="apikey_admin", settings=default_settings)
+ self.inactive = octoprint.users.User("inactive", "passwordHash", False, ("user",), apikey="apikey_inactive", settings=default_settings)
+
+ @ddt.data(
+ ("user", dict(name="user",
+ active=True,
+ admin=False,
+ user=True,
+ apikey="apikey_user",
+ settings=default_settings)),
+ ("admin", dict(name="admin",
+ active=True,
+ admin=True,
+ user=True,
+ apikey="apikey_admin",
+ settings=default_settings)),
+ ("inactive", dict(name="inactive",
+ active=False,
+ admin=False,
+ user=True,
+ apikey="apikey_inactive",
+ settings=default_settings))
+ )
+ @ddt.unpack
+ def test_as_dict(self, uservar, expected):
+ user = getattr(self, uservar)
+ self.assertDictEqual(expected, user.asDict())
+
+ @ddt.data(
+ ("key", "value"),
+ (["sub", "subkey"], "subvalue"),
+ ("doesntexist", None)
+ )
+ @ddt.unpack
+ def test_get_setting(self, key, expected):
+ value = self.user.get_setting(key)
+ self.assertEquals(expected, value)
+
+ @ddt.data(
+ ("otherkey", "othervalue", dict(otherkey="othervalue"), True),
+ (["sub", "othersubkey"], "othersubvalue", dict(sub=dict(othersubkey="othersubvalue")), True),
+ ("booleankey", True, dict(booleankey=True), True),
+ (["newsub", "newsubkey"], "newsubvalue", dict(newsub=dict(newsubkey="newsubvalue")), True),
+ (["sub", "subkey", "wontwork"], "wontwork", dict(), False)
+ )
+ @ddt.unpack
+ def test_set_setting_string(self, key, value, update, expected_returnvalue):
+ returnvalue = self.user.set_setting(key, value)
+
+ expected = dict_merge(default_settings, update)
+
+ self.assertDictEqual(expected, self.user.get_all_settings())
+ self.assertEqual(expected_returnvalue, returnvalue)
+
+ def test_check_password(self):
+ self.assertTrue(self.user.check_password("passwordHash"))
+ self.assertFalse(self.user.check_password("notThePasswordHash"))
+
+ @ddt.data(
+ ("user", "User(id=user,name=user,active=True,user=True,admin=False)"),
+ ("admin", "User(id=admin,name=admin,active=True,user=True,admin=True)"),
+ ("inactive", "User(id=inactive,name=inactive,active=False,user=True,admin=False)")
+ )
+ @ddt.unpack
+ def test_repr(self, uservar, output):
+ self.assertEqual(output, repr(getattr(self, uservar)))
+
+class SessionUserTestCase(unittest.TestCase):
+
+ def setUp(self):
+ self.user = octoprint.users.User("username", "passwordHash", True, ("user",), apikey="apikey", settings=dict(key="value"))
+
+ def test_two_sessions(self):
+ session1 = octoprint.users.SessionUser(self.user)
+ session2 = octoprint.users.SessionUser(self.user)
+
+ self.assertNotEqual(session1.get_session(), session2.get_session())
+ self.assertEqual(session1._user, session2._user)
+ self.assertEqual(session1._username, session2._username)
+
+ def test_settings_change_propagates(self):
+ user = octoprint.users.SessionUser(self.user)
+ self.user.set_setting("otherkey", "othervalue")
+
+ self.assertDictEqual(dict(key="value", otherkey="othervalue"), user.get_all_settings())
+
+ def test_repr(self):
+ user = octoprint.users.SessionUser(self.user)
+ expected = "SessionUser(id=username,name=username,active=True,user=True,admin=False,session={},created={})".format(user._session, user._created)
+ self.assertEquals(expected, repr(user))
diff --git a/tests/util/test_comm_helpers.py b/tests/util/test_comm_helpers.py
index 3015e6f65..e7b906f12 100644
--- a/tests/util/test_comm_helpers.py
+++ b/tests/util/test_comm_helpers.py
@@ -156,3 +156,76 @@ class TestCommHelpers(unittest.TestCase):
self.assertEquals(x_template, x["templates"][x_template_key])
self.assertEquals("(?P{temp_regex})|(?P{x_regex})".format(**locals()), matcher.pattern)
+
+ @data(
+ ("G4 P2.0", "floatP", True, "2.0"),
+ ("M109 S220.0", "floatS", True, "220.0"),
+ ("G1 X10.0 Y10.0 Z0.2", "floatZ", True, "0.2"),
+ ("G1X10.0Y10.0Z0.2", "floatZ", True, "0.2"),
+ ("g1x10.0y10.0z0.2", "floatZ", True, "0.2"),
+ ("M110 N0", "intN", True, "0"),
+ ("M104 S220.0 T1", "intT", True, "1"),
+ ("M104 T1 S220.0", "intT", True, "1"),
+ ("N100 M110", "intN", True, "100"),
+ ("NP100", "floatP", False, None),
+ )
+ @unpack
+ def test_parameter_regexes(self, line, parameter, should_match, expected_value):
+ from octoprint.util.comm import regexes_parameters
+
+ regex = regexes_parameters[parameter]
+ match = regex.search(line)
+
+ if should_match:
+ self.assertIsNotNone(match)
+ self.assertEquals(expected_value, match.group("value"))
+ else:
+ self.assertIsNone(match)
+
+ @data(
+ ("G0 X0", "G0"),
+ ("G28 X0 Y0", "G28"),
+ ("M109 S220.0 T1", "M109"),
+ ("M117 Hello World", "M117"),
+ ("T0", "T"),
+ ("T3", "T"),
+ (None, None),
+ ("No match", None)
+ )
+ @unpack
+ def test_gcode_command_for_cmd(self, cmd, expected):
+ from octoprint.util.comm import gcode_command_for_cmd
+ result = gcode_command_for_cmd(cmd)
+ self.assertEquals(expected, result)
+
+ @data(
+ ("T:23.0 B:60.0", 0, dict(T0=(23.0, None), B=(60.0, None)), 0),
+ ("T:23.0 B:60.0", 1, dict(T1=(23.0, None), B=(60.0, None)), 1),
+ ("T:23.0/220.0 B:60.0/70.0", 0, dict(T0=(23.0, 220.0), B=(60.0, 70.0)), 0),
+ ("ok T:23.0/220.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 0, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2),
+ ("ok T:50.2/210.0 T0:23.0/220.0 T1:50.2/210.0 T2:39.4/220.0 B:60.0", 1, dict(T0=(23.0, 220.0), T1=(50.2, 210.0), T2=(39.4, 220.0), B=(60.0, None)), 2)
+ )
+ @unpack
+ def test_process_temperature_line(self, line, current, expected_result, expected_max):
+ from octoprint.util.comm import parse_temperature_line
+ maxtool, result = parse_temperature_line(line, current)
+ self.assertDictEqual(expected_result, result)
+ self.assertEquals(expected_max, maxtool)
+
+ @data(
+ (dict(T=(23.0,None)), 0, dict(T0=(23.0, None))),
+ (dict(T=(23.0,None)), 1, dict(T1=(23.0, None))),
+ (dict(T=(23.0, None), T0=(23.0, None), T1=(42.0, None)), 0, dict(T0=(23.0, None), T1=(42.0, None))),
+ (dict(T=(42.0, None), T0=(23.0, None), T1=(42.0, None)), 1, dict(T0=(23.0, None), T1=(42.0, None))),
+ (dict(T=(21.0, None), T0=(23.0, None), T1=(42.0, None)), 0, dict(T0=(21.0, None), T1=(42.0, None))),
+ (dict(T=(41.0, None), T0=(23.0, None), T1=(42.0, None)), 1, dict(T0=(23.0, None), T1=(41.0, None))),
+ (dict(T=(23.0, None), T1=(42.0, None)), 1, dict(T0=(23.0, None), T1=(42.0, None))),
+ (dict(T0=(23.0, None), T1=(42.0, None)), 1, dict(T0=(23.0, None), T1=(42.0, None)))
+
+ )
+ @unpack
+ def test_canonicalize_temperatures(self, parsed, current, expected):
+ from octoprint.util.comm import canonicalize_temperatures
+ result = canonicalize_temperatures(parsed, current)
+ self.assertDictEqual(expected, result)
+
diff --git a/tests/util/test_counted_event.py b/tests/util/test_counted_event.py
new file mode 100644
index 000000000..ec3a92b4f
--- /dev/null
+++ b/tests/util/test_counted_event.py
@@ -0,0 +1,144 @@
+# coding=utf-8
+from __future__ import absolute_import
+
+__author__ = "Gina Häußge "
+__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
+__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
+
+import unittest
+import time
+import threading
+
+from octoprint.util import CountedEvent
+
+class CountedEventTest(unittest.TestCase):
+
+ def test_set_once(self):
+ """The counter should go from 0 to 1."""
+
+ event = CountedEvent()
+
+ self.assertEquals(0, event._counter)
+ self.assertFalse(event._event.is_set())
+
+ event.set()
+
+ self.assertEquals(1, event._counter)
+ self.assertTrue(event._event.is_set())
+
+ def test_set_more_than_max(self):
+ """The counter should never rise above max."""
+
+ event = CountedEvent(max=1)
+
+ self.assertEquals(0, event._counter)
+ self.assertFalse(event._event.is_set())
+
+ event.set()
+
+ self.assertEquals(1, event._counter)
+ self.assertTrue(event._event.is_set())
+
+ event.set()
+
+ self.assertEquals(1, event._counter)
+ self.assertTrue(event._event.is_set())
+
+ def test_clear_once(self):
+ """The counter should to from 1 to 0."""
+
+ event = CountedEvent(1)
+
+ self.assertEquals(1, event._counter)
+ self.assertTrue(event._event.is_set())
+
+ event.clear()
+
+ self.assertEquals(0, event._counter)
+ self.assertFalse(event._event.is_set())
+
+ def test_clear_all(self):
+ """The counter should go from 10 to 0."""
+
+ event = CountedEvent(10)
+
+ self.assertEquals(10, event._counter)
+ self.assertTrue(event._event.is_set())
+
+ event.clear(completely=True)
+
+ self.assertEquals(0, event._counter)
+ self.assertFalse(event._event.is_set())
+
+ def test_clear_more_than_available(self):
+ """The counter should never sink below 0."""
+
+ event = CountedEvent(1)
+
+ self.assertEquals(1, event._counter)
+ self.assertTrue(event._event.is_set())
+
+ event.clear()
+
+ self.assertEquals(0, event._counter)
+ self.assertFalse(event._event.is_set())
+
+ event.clear()
+
+ self.assertEquals(0, event._counter)
+ self.assertFalse(event._event.is_set())
+
+ def test_blocked(self):
+ """Blocked should only be true if the counter is 0."""
+
+ event = CountedEvent(0)
+
+ self.assertTrue(event.blocked())
+
+ event.set()
+ self.assertFalse(event.blocked())
+
+ event.clear()
+ self.assertTrue(event.blocked())
+
+ def test_wait_immediately(self):
+ """Unblocked wait should immediately return."""
+
+ event = CountedEvent(1)
+
+ start = time.time()
+ event.wait(timeout=2)
+ duration = time.time() - start
+
+ self.assertLess(duration, 1)
+
+ def test_wait_blocking(self):
+ """Set should immediately have blocked wait return."""
+
+ event = CountedEvent(0)
+
+ def set_event():
+ time.sleep(1)
+ event.set()
+
+ thread = threading.Thread(target=set_event)
+ thread.daemon = True
+ thread.start()
+
+ start = time.time()
+ event.wait(timeout=2)
+ duration = time.time() - start
+
+ self.assertLess(duration, 2)
+
+ def test_wait_timeout(self):
+ """Blocked should only wait until timeout."""
+
+ event = CountedEvent(0)
+
+ start = time.time()
+ event.wait(timeout=2)
+ duration = time.time() - start
+
+ self.assertGreaterEqual(duration, 2)
+ self.assertLess(duration, 3)
diff --git a/tests/util/test_repeated_timer.py b/tests/util/test_repeated_timer.py
new file mode 100644
index 000000000..6eed773b9
--- /dev/null
+++ b/tests/util/test_repeated_timer.py
@@ -0,0 +1,180 @@
+# coding=utf-8
+from __future__ import absolute_import
+
+__author__ = "Gina Häußge "
+__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
+__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
+
+import unittest
+import mock
+import time
+
+from octoprint.util import RepeatedTimer
+
+
+class Countdown(object):
+ def __init__(self, start):
+ self._counter = start
+
+ def step(self):
+ self._counter -= 1
+
+ @property
+ def counter(self):
+ return self._counter
+
+
+class IncreasingInterval(Countdown):
+ def __init__(self, start, factor):
+ Countdown.__init__(self, start)
+ self._start = start
+ self._factor = factor
+
+ def interval(self):
+ result = (self._start - self._counter + 1) * self._factor
+ return result
+
+
+class RepeatedTimerTest(unittest.TestCase):
+
+ def setUp(self):
+ pass
+
+ def test_condition(self):
+ countdown = Countdown(5)
+ timer_task = mock.MagicMock()
+ timer_task.side_effect = countdown.step
+
+ timer = RepeatedTimer(0.1, timer_task, condition=lambda: countdown.counter > 0)
+ timer.start()
+
+ # wait for it
+ timer.join()
+
+ self.assertEquals(5, timer_task.call_count)
+
+ def test_finished_callback(self):
+ countdown = Countdown(5)
+ timer_task = mock.MagicMock()
+ timer_task.side_effect = countdown.step
+
+ on_finished = mock.MagicMock()
+
+ timer = RepeatedTimer(0.1, timer_task, condition=lambda: countdown.counter > 0, on_finish=on_finished)
+ timer.start()
+
+ # wait for it
+ timer.join()
+
+ self.assertEquals(1, on_finished.call_count)
+
+ def test_condition_callback(self):
+ countdown = Countdown(5)
+ timer_task = mock.MagicMock()
+ timer_task.side_effect = countdown.step
+
+ on_cancelled = mock.MagicMock()
+ on_condition_false = mock.MagicMock()
+
+ timer = RepeatedTimer(0.1, timer_task,
+ condition=lambda: countdown.counter > 0,
+ on_condition_false=on_condition_false,
+ on_cancelled=on_cancelled)
+ timer.start()
+
+ # wait for it
+ timer.join()
+
+ self.assertEquals(1, on_condition_false.call_count)
+ self.assertEquals(0, on_cancelled.call_count)
+
+ def test_cancelled_callback(self):
+ countdown = Countdown(5)
+ timer_task = mock.MagicMock()
+ timer_task.side_effect = countdown.step
+
+ on_cancelled = mock.MagicMock()
+ on_condition_false = mock.MagicMock()
+
+ timer = RepeatedTimer(10, timer_task,
+ condition=lambda: countdown.counter > 0,
+ on_condition_false=on_condition_false,
+ on_cancelled=on_cancelled)
+ timer.start()
+
+ # give it some time to run
+ time.sleep(1)
+
+ # then cancel it and wait for the thread to really finish
+ timer.cancel()
+ timer.join()
+
+ self.assertEquals(0, on_condition_false.call_count)
+ self.assertEquals(1, on_cancelled.call_count)
+
+ def test_run_first(self):
+ timer_task = mock.MagicMock()
+
+ timer = RepeatedTimer(60, timer_task, run_first=True)
+ timer.start()
+
+ # give it some time to run
+ time.sleep(1)
+
+ # then cancel it and wait for the thread to really finish
+ timer.cancel()
+ timer.join()
+
+ # should have run once
+ self.assertEquals(1, timer_task.call_count)
+
+ def test_not_run_first(self):
+ timer_task = mock.MagicMock()
+
+ timer = RepeatedTimer(60, timer_task)
+ timer.start()
+
+ # give it some time to run - should hang in the sleep phase though
+ time.sleep(1)
+
+ # then cancel it and wait for the thread to really finish
+ timer.cancel()
+ timer.join()
+
+ self.assertEquals(0, timer_task.call_count)
+
+ def test_adjusted_interval(self):
+ increasing_interval = IncreasingInterval(3, 1)
+
+ timer_task = mock.MagicMock()
+ timer_task.side_effect = increasing_interval.step
+
+ timer = RepeatedTimer(increasing_interval.interval,
+ timer_task,
+ condition=lambda: increasing_interval.counter > 0)
+
+ # this should take 1 + 2 + 3 = 6s
+ start_time = time.time()
+ timer.start()
+ timer.join()
+ duration = time.time() - start_time
+
+ self.assertEquals(3, timer_task.call_count)
+ self.assertGreaterEqual(duration, 6)
+ self.assertLess(duration, 7)
+
+ def test_condition_change_during_task(self):
+ def sleep():
+ time.sleep(2)
+
+ timer_task = mock.MagicMock()
+ timer_task.side_effect = sleep
+
+ timer = RepeatedTimer(0.1, timer_task, run_first=True)
+ timer.start()
+
+ time.sleep(1)
+ timer.condition = lambda: False
+ timer.join()
+
+ self.assertEquals(1, timer_task.call_count)
diff --git a/translations/de/LC_MESSAGES/messages.mo b/translations/de/LC_MESSAGES/messages.mo
index 13df51838..9f2ed5e39 100644
Binary files a/translations/de/LC_MESSAGES/messages.mo and b/translations/de/LC_MESSAGES/messages.mo differ
diff --git a/translations/de/LC_MESSAGES/messages.po b/translations/de/LC_MESSAGES/messages.po
index 96511f22f..f87120120 100644
--- a/translations/de/LC_MESSAGES/messages.po
+++ b/translations/de/LC_MESSAGES/messages.po
@@ -11,8 +11,8 @@ msgid ""
msgstr ""
"Project-Id-Version: OctoPrint\n"
"Report-Msgid-Bugs-To: i18n@octoprint.org\n"
-"POT-Creation-Date: 2015-07-07 18:20+0200\n"
-"PO-Revision-Date: 2015-07-07 18:23+0100\n"
+"POT-Creation-Date: 2015-08-31 10:04+0200\n"
+"PO-Revision-Date: 2015-08-31 10:28+0100\n"
"Last-Translator: Gina Häußge \n"
"Language-Team: German (http://www.transifex.com/projects/p/octoprint/language/de/)\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
@@ -46,7 +46,7 @@ msgstr "Profile"
#: src/octoprint/plugins/cura/templates/cura_settings.jinja2:22
#: src/octoprint/templates/dialogs/settings/logs.jinja2:6
-#: src/octoprint/templates/tabs/timelapse.jinja2:45
+#: src/octoprint/templates/tabs/timelapse.jinja2:49
msgid "Sort by"
msgstr "Sortieren"
@@ -61,7 +61,7 @@ msgstr "ID"
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:75
#: src/octoprint/templates/dialogs/settings/logs.jinja2:6
#: src/octoprint/templates/sidebar/files_header.jinja2:6
-#: src/octoprint/templates/tabs/timelapse.jinja2:45
+#: src/octoprint/templates/tabs/timelapse.jinja2:49
msgid "ascending"
msgstr "aufsteigend"
@@ -75,8 +75,8 @@ msgstr "aufsteigend"
#: src/octoprint/templates/dialogs/settings/printerprofiles.jinja2:5
#: src/octoprint/templates/dialogs/settings/printerprofiles.jinja2:44
#: src/octoprint/templates/dialogs/settings/terminalfilters.jinja2:3
-#: src/octoprint/templates/tabs/timelapse.jinja2:45
-#: src/octoprint/templates/tabs/timelapse.jinja2:50
+#: src/octoprint/templates/tabs/timelapse.jinja2:49
+#: src/octoprint/templates/tabs/timelapse.jinja2:54
msgid "Name"
msgstr "Name"
@@ -142,228 +142,228 @@ msgstr "Bestätigen"
msgid "Plugin Manager"
msgstr "Pluginmanager"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:130
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:270
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:132
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:277
msgid "Installing plugin..."
msgstr "Installiere Plugin..."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:130
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:132
msgid "Installing plugin from uploaded archive..."
msgstr "Installiere Plugin von hochgeladenem Archiv..."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:142
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:222
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:295
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:325
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:539
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:569
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:586
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:603
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:147
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:225
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:302
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:332
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:546
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:576
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:593
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:610
msgid "Something went wrong"
msgstr "Etwas ist schief gegangen"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:143
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:223
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:296
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:326
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:148
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:226
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:303
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:333
msgid "Please consult octoprint.log for details"
msgstr "Bitte konsultiere octoprint.log für Details"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:272
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:279
#, python-format
msgid "Installing plugin \"%(name)s\" from %(url)s..."
msgstr "Installiere Plugin \"%(name)s\" von %(url)s..."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:274
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:281
#, python-format
msgid "Installing plugin from %(url)s..."
msgstr "Installiere Plugin von %(url)s..."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:277
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:284
msgid "Reinstalling plugin..."
msgstr "Reinstalliere Plugin..."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:278
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:285
#, python-format
msgid "Reinstalling plugin \"%(name)s\" from %(url)s..."
msgstr "Reinstalliere Plugin \"%(name)s\" von %(url)s..."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:316
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:323
msgid "Uninstalling plugin..."
msgstr "Deinstalliere Plugin..."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:316
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:323
#, python-format
msgid "Uninstalling plugin \"%(name)s\""
msgstr "Deinstalliere Plugin \"%(name)s\""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:351
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:358
msgid "Reinstall"
msgstr "Reinstallieren"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:351
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:358
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:130
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:146
msgid "Install"
msgstr "Installieren"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:351
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:358
msgid "Incompatible"
msgstr "Inkompatibel"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:369
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:376
#: src/octoprint/templates/overlays/reloadui.jinja2:9
msgid "Reload now"
msgstr "Jetzt neu laden"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:438
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:445
msgid "Done!"
msgstr "Fertig!"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:458
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:465
msgid "Enable Plugin"
msgstr "Plugin enablen"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:458
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:465
msgid "Disable Plugin"
msgstr "Plugin disablen"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:523
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:530
msgid "Plugin installed"
msgstr "Plugin installiert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:524
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:531
msgid "A plugin was installed successfully, however it was impossible to detect which one. Please Restart OctoPrint to make sure everything will be registered properly"
msgstr "Ein Plugin wurde erfolgreich installiert, es war aber unmöglich zu detektieren, welches. Bitte starte OctoPrint neu um sicherzustellen, dass alles ordnungsgemäß registriert wird."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:528
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:535
#, python-format
msgid "Plugin \"%(name)s\" reinstalled"
msgstr "Plugin \"%(name)s\" reinstalliert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:529
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:536
msgid "The plugin was reinstalled successfully"
msgstr "Das Plugin wurde erfolgreich reinstalliert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:530
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:537
msgid "The plugin was reinstalled successfully, however a restart of OctoPrint is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich reinstalliert, es ist aber ein Neustart von OctoPrint notwendig bevor es genutzt werden kann."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:531
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:538
msgid "The plugin was reinstalled successfully, however a reload of the page is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich reinstalliert, es ist aber ein Neuladen der Seite notwendig bevor es genutzt werden kann."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:533
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:540
#, python-format
msgid "Plugin \"%(name)s\" installed"
msgstr "Plugin \"%(name)s\" installiert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:534
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:541
msgid "The plugin was installed successfully"
msgstr "Das Plugin wurde erfolgreich installiert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:535
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:542
msgid "The plugin was installed successfully, however a restart of OctoPrint is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich installiert, es ist jedoch ein Neustart von OctoPrint notwendig bevor es genutzt werden kann."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:536
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:543
msgid "The plugin was installed successfully, however a reload of the page is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich installiert, es ist jedoch ein Neuladen der Seite notwendig bevor es genutzt werden kann."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:547
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:554
#, python-format
msgid "Reinstalling the plugin from URL \"%(url)s\" failed: %(reason)s"
msgstr "Reinstallation des Plugins von URL \"%(url)s\" fehlgeschlagen: %(reason)s"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:549
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:556
#, python-format
msgid "Installing the plugin from URL \"%(url)s\" failed: %(reason)s"
msgstr "Installation des Plugins von URL \"%(url)s\" fehlgeschlagen: %(reason)s"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:553
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:560
#, python-format
msgid "Reinstalling the plugin from URL \"%(url)s\" failed, please see the log for details."
msgstr "Reinstallation des Plugins von URL \"%(url)s\" fehlgeschlagen, bitte konsultiere das Log für Details."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:555
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:562
#, python-format
msgid "Installing the plugin from URL \"%(url)s\" failed, please see the log for details."
msgstr "Installation des Plugins von URL \"%(url)s\" fehlgeschlagen, bitte konsultiere das Log für Details"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:564
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:571
#, python-format
msgid "Plugin \"%(name)s\" uninstalled"
msgstr "Plugin \"%(name)s\" deinstalliert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:565
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:572
msgid "The plugin was uninstalled successfully"
msgstr "Das Plugin wurde erfolgreich deinstalliert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:566
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:573
msgid "The plugin was uninstalled successfully, however a restart of OctoPrint is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich deinstalliert, es ist jedoch ein Neustart von OctoPrint notwendig."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:567
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:574
msgid "The plugin was uninstalled successfully, however a reload of the page is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich deinstalliert, es ist jedoch ein Neuladen der Seite notwendig."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:571
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:578
#, python-format
msgid "Uninstalling the plugin failed: %(reason)s"
msgstr "Deinstallation des Plugins fehlgeschlagen: %(reason)s"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:573
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:580
msgid "Uninstalling the plugin failed, please see the log for details."
msgstr "Deinstallation des Plugins fehlgeschlagen, bitte konsultiere das Log für Details."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:581
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:588
#, python-format
msgid "Plugin \"%(name)s\" enabled"
msgstr "Plugin \"%(name)s\" aktiviert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:582
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:589
msgid "The plugin was enabled successfully."
msgstr "Das Plugin wurde erfolgreich aktiviert."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:583
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:590
msgid "The plugin was enabled successfully, however a restart of OctoPrint is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich aktiviert, es ist jedoch ein Neustart von OctoPrint notwendig."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:584
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:591
msgid "The plugin was enabled successfully, however a reload of the page is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich aktiviert, es ist jedoch ein Neuladen der Seite notwendig."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:588
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:605
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:595
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:612
#, python-format
msgid "Toggling the plugin failed: %(reason)s"
msgstr "Togglen des Plugins fehlgeschalgen: %(reason)s"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:590
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:607
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:597
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:614
msgid "Toggling the plugin failed, please see the log for details."
msgstr "Togglen des Plugins fehlgeschlagen, bitte konsultiere das Log für Details."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:598
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:605
#, python-format
msgid "Plugin \"%(name)s\" disabled"
msgstr "Plugin \"%(name)s\" deaktiviert"
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:599
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:606
msgid "The plugin was disabled successfully."
msgstr "Das Plugin wurde erfolgreich deaktiviert."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:600
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:607
msgid "The plugin was disabled successfully, however a restart of OctoPrint is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich deaktiviert, es ist jedoch ein Neustart von OctoPrint notwendig."
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:601
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:608
msgid "The plugin was disabled successfully, however a reload of the page is needed for that to take effect."
msgstr "Das Plugin wurde erfolgreich deaktiviert, es ist jedoch ein Neuladen der Seite notwendig."
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:3
msgid "Take note that all plugin management functionality is disabled while your printer is printing."
-msgstr "Bitte beachte das jegliche Pluginmanagementfunktionen während des Druckens deaktiviert sind."
+msgstr "Bitte beachte dass jegliche Pluginmanagementfunktionen während des Druckens deaktiviert sind."
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:9
msgid "Installed Plugins"
@@ -388,8 +388,7 @@ msgid "Get More..."
msgstr "Mehr..."
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:59
-#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:152
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:96
+#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:167
#: src/octoprint/templates/dialogs/settings/appearance.jinja2:96
msgid "Close"
msgstr "Schließen"
@@ -415,7 +414,7 @@ msgstr "Nach Veröffentlichungsdatum sortieren"
#: src/octoprint/templates/dialogs/settings/logs.jinja2:6
#: src/octoprint/templates/sidebar/files_header.jinja2:7
#: src/octoprint/templates/sidebar/files_header.jinja2:8
-#: src/octoprint/templates/tabs/timelapse.jinja2:45
+#: src/octoprint/templates/tabs/timelapse.jinja2:49
msgid "descending"
msgstr "absteigend"
@@ -468,12 +467,23 @@ msgstr "... von einem hochgeladenen Archiv"
msgid "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\""
msgstr "Das sieht nicht aus wie ein valides Pluginarchiv. Valide Pluginarchive sollten entweder ZIP-Dateien oder Tarballs sein und die Dateiextension \".zip\", \".tar.gz\", \".tgz\" oder \".tar\" haben"
-#: src/octoprint/plugins/softwareupdate/__init__.py:331
+#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:152
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:62
+#: src/octoprint/templates/tabs/terminal.jinja2:25
+msgid "Advanced options"
+msgstr "Erweiterte Optionen"
+
+#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:158
+msgid "Use --process-dependency-links with pip install"
+msgstr "--process-dependency-link mit pip install verwenden"
+
+#: src/octoprint/plugins/softwareupdate/__init__.py:378
msgid "Software Update"
msgstr "Software Update"
-#: src/octoprint/plugins/softwareupdate/__init__.py:610
-#: src/octoprint/server/views.py:146
+#: src/octoprint/plugins/softwareupdate/__init__.py:662
+#: src/octoprint/plugins/softwareupdate/__init__.py:693
+#: src/octoprint/server/views.py:149
#: src/octoprint/static/js/app/viewmodels/appearance.js:11
#: src/octoprint/static/js/app/viewmodels/appearance.js:13
#: src/octoprint/static/js/app/viewmodels/appearance.js:18
@@ -481,186 +491,210 @@ msgstr "Software Update"
msgid "OctoPrint"
msgstr "OctoPrint"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:119
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:26
+msgid "Release"
+msgstr "Release"
+
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:27
+msgid "Commit"
+msgstr "Commit"
+
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:145
msgid "There are updates available for the following components:"
msgstr "Es gibt Aktualisierungen für die folgenden Komponenten:"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:133
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:159
msgid "Those components marked with can be updated directly."
msgstr "Die mit markierten Komponenten können direkt aktualisiert werden."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:136
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:162
msgid "Update Available"
msgstr "Aktualisierung verfügbar"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:147
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:174
msgid "Ignore"
msgstr "Ignorieren"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:151
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:178
msgid "You can make this message display again via \"Settings\" > \"Software Update\" > \"Check for update now\""
msgstr "Du kannst diese Nachricht erneut anzeigen lassen mittels \"Einstellungen\" > \"Software Update\" > \"Jetzt nach Aktualisierungen suchen\""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:155
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:182
msgid "Update now"
msgstr "Jetzt aktualisieren"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:172
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:199
msgid "Everything is up-to-date"
msgstr "Alles ist auf dem neusten Stand"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:237
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:268
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:388
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:264
msgid "Updating..."
msgstr "Aktualisiere..."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:238
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:265
msgid "Now updating, please wait."
msgstr "Aktualisiere gerade, bitte warten."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:257
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:284
msgid "Update not started!"
msgstr "Aktualisierung nicht gestartet!"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:258
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:285
msgid "The update could not be started. Is it already active? Please consult the log for details."
msgstr "Die Aktualisierung konnte nicht gestartet werden. Läuft bereits eine? Bitte konsultiere das Log für Details."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:268
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:388
-msgid "Updating, please wait."
-msgstr "Aktualisiere gerade, bitte warten."
-
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:281
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:307
msgid "Can't update while printing"
msgstr "Aktualisierung nicht möglich während gedruckt wird"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:282
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:308
msgid "A print job is currently in progress. Updating will be prevented until it is done."
msgstr "Ein Druckjob ist zur Zeit aktiv. Aktualisierungen werden unterbunden bis er fertig ist."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:286
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:312
msgid "This will update your OctoPrint installation and restart the server."
msgstr "Das wird Deine OctoPrint Installation aktualisieren und den Server neu starten."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:347
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:336
msgid "Restart successful!"
msgstr "Neustart erfolgreich!"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:348
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:337
msgid "The server was restarted successfully. The page will now reload automatically."
msgstr "Der Server wurde erfolgreich neu gestartet. Die Seite wird nun automatisch neu geladen."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:391
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:369
#, python-format
msgid "Now updating %(name)s to %(version)s"
msgstr "Aktualisiere %(name)s auf %(version)s"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:409
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:377
msgid "Update successful, restarting!"
msgstr "Aktualisierung erfolgreich, starte neu!"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:410
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:378
msgid "The update finished successfully and the server will now be restarted."
msgstr "Die Aktualisierung wurde erfolgreich durchgeführt und der Server wird jetzt neu gestartet."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:426
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:475
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:389
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:431
msgid "Restart failed"
msgstr "Neustart fehlgeschlagen"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:427
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:390
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:432
msgid "The server apparently did not restart by itself, you'll have to do it manually. Please consult the log file on what went wrong."
msgstr "Der Server hat anscheinend nicht von selbst neu gstartet, Du wirst das manuell tun müssen. Bitte konsultiere das Logfile."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:449
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:406
msgid "The update finished successfully, please restart OctoPrint now."
msgstr "Die Aktualisierung wurde erfolgreich abgeschlossen, bitte starte OctoPrint jetzt neu."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:451
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:408
msgid "The update finished successfully, please reboot the server now."
msgstr "Die Aktualisierung wurde erfolgreich abgeschlossen, bitte reboote den Server jetzt."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:454
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:412
msgid "Update successful, restart required!"
msgstr "Aktualisierung erfolgreich, Neustart notwendig!"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:470
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:425
msgid "Restarting OctoPrint failed, please restart it manually. You might also want to consult the log file on what went wrong here."
msgstr "Der Neustart von OctoPrint ist fehlgeschlagen, bitte starte es manuell neu. Du solltest das Logfile konsultieren, um herauszufinden, was hier schief gelaufen ist."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:472
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:427
msgid "Rebooting the server failed, please reboot it manually. You might also want to consult the log file on what went wrong here."
msgstr "Reboot des Servers fehlgeschlagen, bitte reboote ihn manuell. Du solltest auch das Logfile konsultieren, um herauszufinden, was hier gerade schief gelaufen ist."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:491
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:445
msgid "Update successful!"
msgstr "Aktualisierung erfolgreich!"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:492
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:446
msgid "The update finished successfully."
msgstr "Die Aktualisierung wurde erfolgreich abgeschlossen."
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:507
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:458
msgid "Update failed!"
msgstr "Aktualisierung fehlgeschlagen!"
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:508
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:459
msgid "The update did not finish successfully. Please consult the log for details."
msgstr "Die Aktualisierung wurde nicht erfolgreich abgeschlossen. Bitte konsultiere das Log für Details."
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:2
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:54
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:1
+msgid ""
+"\n"
+" Please configure the checkout folder of OctoPrint, otherwise\n"
+" this plugin won't be able to update it. Click on the button\n"
+" to do this. Also refer to the Documentation.\n"
+msgstr " Bitte konfiguriere das Checkoutverzeichnis von OctoPrint, andernfalls wird dieses Plugin Deine Installation nicht updaten können. Klicke dazu auf den Button. Siehe des Weiteren auch die Dokumentation."
+
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:6
+msgid ""
+"\n"
+"
\n"
+" You are running a non-release version of OctoPrint but are tracking OctoPrint\n"
+" releases.\n"
+"
\n"
+" You probably want OctoPrint to track the matching development version instead.\n"
+" If you have a local OctoPrint checkout folder switched to another branch,\n"
+" simply switching over to \"Commit\" tracking will already\n"
+" take care of that. Otherwise please take a look at the\n"
+" Documentation.\n"
+"
\n"
+msgstr "
Du nutzt eine unveröffentlichte Version von OctoPrint, trackst aber OctoPrint Releases.
Du willst vermutlich, dass OctoPrint stattdessen die entsprechende Entwicklungsversion trackt. Falls Du dein lokales OctoPrint-Checkoutverzeichnis auf einen anderen Branch gewechselt hast, dann wechsle das Tracking einfach auf \"Commit\". Ansonsten wirf einen Blick in die Dokumentation.
"
+
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:20
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:72
msgid "Plugin Configuration"
msgstr "Pluginkonfiguration"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:5
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:23
msgid "Current versions"
msgstr "Aktuelle Versionen"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:11
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:29
msgid "Update available"
msgstr "Aktualisierung verfügbar"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:16
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:32
+msgid "Update not possible, configuration ok?"
+msgstr "Update nicht möglich, Konfiguration in Ordnung?"
+
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:34
msgid "Installed:"
msgstr "Installiert:"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:17
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:35
msgid "Available:"
msgstr "Verfügbar:"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:41
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:59
msgid "Check for update now"
msgstr "Jetzt nach Aktualisierungen suchen"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:44
-#: src/octoprint/templates/tabs/terminal.jinja2:25
-msgid "Advanced options"
-msgstr "Erweiterte Optionen"
-
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:46
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:64
msgid "Force check for update (overrides cache used for update checks)"
msgstr "Suche nach Aktualisierungen forcieren (ignoriert den Cache für Aktualisierungsinformationen)"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:47
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:65
msgid "Force update now (even if no new versions are available)"
msgstr "Aktualisierung forcieren (selbst wenn keine neue Versionen verfügbar sind)"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:59
-msgid "Restart Command"
-msgstr "Neustartbefehl"
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:77
+msgid "OctoPrint checkout folder"
+msgstr "Checkoutverzeichnis von OctoPrint "
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:65
-msgid "Reboot Command"
-msgstr "Rebootbefehl"
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:83
+msgid "OctoPrint version tracking"
+msgstr "Versionstracking für OctoPrint"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:71
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:89
msgid "Version cache TTL"
-msgstr "Versionscache TTL"
+msgstr "TTL des Versionscaches"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:82
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:100
#: src/octoprint/templates/dialogs/confirmation.jinja2:11
#: src/octoprint/templates/dialogs/settings.jinja2:51
#: src/octoprint/templates/dialogs/slicing.jinja2:50
@@ -668,113 +702,118 @@ msgstr "Versionscache TTL"
msgid "Cancel"
msgstr "Abbruch"
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:83
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:101
#: src/octoprint/templates/dialogs/settings.jinja2:52
msgid "Save"
msgstr "Speichern"
-#: src/octoprint/server/views.py:55
+#: src/octoprint/server/views.py:58
msgid "Plugins"
msgstr "Plugins"
-#: src/octoprint/server/views.py:112
+#: src/octoprint/server/views.py:115
msgid "Connection"
msgstr "Verbindung"
-#: src/octoprint/server/views.py:113
+#: src/octoprint/server/views.py:116
msgid "State"
msgstr "Status"
-#: src/octoprint/server/views.py:114
+#: src/octoprint/server/views.py:117
msgid "Files"
msgstr "Dateien"
-#: src/octoprint/server/views.py:120
+#: src/octoprint/server/views.py:123
msgid "Temperature"
msgstr "Temperatur"
-#: src/octoprint/server/views.py:121
+#: src/octoprint/server/views.py:124
msgid "Control"
msgstr "Steuerung"
-#: src/octoprint/server/views.py:122
+#: src/octoprint/server/views.py:125
msgid "Terminal"
msgstr "Terminal"
-#: src/octoprint/server/views.py:125
+#: src/octoprint/server/views.py:128
msgid "GCode Viewer"
msgstr "GCode Viewer"
-#: src/octoprint/server/views.py:127
+#: src/octoprint/server/views.py:130
#: src/octoprint/templates/sidebar/state.jinja2:3
msgid "Timelapse"
msgstr "Zeitraffer"
-#: src/octoprint/server/views.py:132
+#: src/octoprint/server/views.py:135
msgid "Printer"
msgstr "Drucker"
-#: src/octoprint/server/views.py:134
+#: src/octoprint/server/views.py:137
msgid "Serial Connection"
msgstr "Serielle Verbindung"
-#: src/octoprint/server/views.py:135
+#: src/octoprint/server/views.py:138
#: src/octoprint/templates/dialogs/settings/printerprofiles.jinja2:1
msgid "Printer Profiles"
msgstr "Druckerprofile"
-#: src/octoprint/server/views.py:136
+#: src/octoprint/server/views.py:139
msgid "Temperatures"
msgstr "Temperaturen"
-#: src/octoprint/server/views.py:137
+#: src/octoprint/server/views.py:140
msgid "Terminal Filters"
msgstr "Terminalfilter"
-#: src/octoprint/server/views.py:138
+#: src/octoprint/server/views.py:141
msgid "GCODE Scripts"
msgstr "GCODE Scripts"
-#: src/octoprint/server/views.py:140 src/octoprint/server/views.py:142
+#: src/octoprint/server/views.py:143 src/octoprint/server/views.py:145
msgid "Features"
msgstr "Funktionen"
-#: src/octoprint/server/views.py:143
+#: src/octoprint/server/views.py:146
msgid "Webcam"
msgstr "Webcam"
-#: src/octoprint/server/views.py:144
+#: src/octoprint/server/views.py:147
msgid "API"
msgstr "API"
-#: src/octoprint/server/views.py:148
+#: src/octoprint/server/views.py:151
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:2
msgid "Folders"
msgstr "Verzeichnisse"
-#: src/octoprint/server/views.py:149
+#: src/octoprint/server/views.py:152
msgid "Appearance"
msgstr "Aussehen"
-#: src/octoprint/server/views.py:150
+#: src/octoprint/server/views.py:153
#: src/octoprint/templates/dialogs/settings/logs.jinja2:2
msgid "Logs"
msgstr "Logs"
-#: src/octoprint/server/views.py:153
+#: src/octoprint/server/views.py:154
+msgid "Server"
+msgstr "Server"
+
+#: src/octoprint/server/views.py:157
msgid "Access Control"
msgstr "Zugangsbeschränkung"
-#: src/octoprint/server/views.py:159
+#: src/octoprint/server/views.py:163
msgid "Access"
msgstr "Zugriff"
-#: src/octoprint/server/views.py:160
+#: src/octoprint/server/views.py:164
msgid "Interface"
msgstr "Interface"
#: src/octoprint/static/js/app/dataupdater.js:66
#: src/octoprint/static/js/app/dataupdater.js:100
-#: src/octoprint/static/js/app/helpers.js:436
+#: src/octoprint/static/js/app/helpers.js:464
#: src/octoprint/templates/overlays/offline.jinja2:6
msgid "Server is offline"
msgstr "Der Server ist offline"
@@ -787,85 +826,85 @@ msgstr "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ih
msgid "The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below."
msgstr "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ihm verbinden. Ich konnte mich nicht automatisch neu verbinden, aber Du kannst mittels des folgenden Buttons einen manuellen Verbindungsversuch anstoßen."
-#: src/octoprint/static/js/app/dataupdater.js:168
-#: src/octoprint/static/js/app/dataupdater.js:196
+#: src/octoprint/static/js/app/dataupdater.js:169
+#: src/octoprint/static/js/app/dataupdater.js:197
#, python-format
msgid "Slicing ... (%(percentage)d%%)"
msgstr "Slice ... (%(percentage)d%%)"
-#: src/octoprint/static/js/app/dataupdater.js:185
+#: src/octoprint/static/js/app/dataupdater.js:186
msgid "Rendering timelapse"
msgstr "Zeitrafferaufnahme wird gerendert"
-#: src/octoprint/static/js/app/dataupdater.js:185
+#: src/octoprint/static/js/app/dataupdater.js:186
#, python-format
msgid "Now rendering timelapse %(movie_basename)s"
msgstr "Rendere Zeitrafferaufnahme %(movie_basename)s"
-#: src/octoprint/static/js/app/dataupdater.js:187
+#: src/octoprint/static/js/app/dataupdater.js:188
msgid "Timelapse ready"
msgstr "Zeitrafferaufnahme fertig"
-#: src/octoprint/static/js/app/dataupdater.js:187
+#: src/octoprint/static/js/app/dataupdater.js:188
#, python-format
msgid "New timelapse %(movie_basename)s is done rendering."
msgstr "Neue Zeitrafferaufnahme %(movie_basename)s wurde fertig gerendert"
-#: src/octoprint/static/js/app/dataupdater.js:189
+#: src/octoprint/static/js/app/dataupdater.js:190
#, python-format
msgid "Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s"
msgstr "Rendering der Zeitrafferaufnahme %(movie_basename)s fehlgeschlagen mit Returncode %(returncode)s"
-#: src/octoprint/static/js/app/dataupdater.js:191
+#: src/octoprint/static/js/app/dataupdater.js:192
msgid "Rendering failed"
msgstr "Rendering fehlgeschlagen"
-#: src/octoprint/static/js/app/dataupdater.js:198
+#: src/octoprint/static/js/app/dataupdater.js:199
msgid "Slicing ..."
msgstr "Slice ..."
-#: src/octoprint/static/js/app/dataupdater.js:204
+#: src/octoprint/static/js/app/dataupdater.js:205
msgid "Slicing done"
msgstr "Slicing abgeschlossen"
-#: src/octoprint/static/js/app/dataupdater.js:204
+#: src/octoprint/static/js/app/dataupdater.js:205
#, python-format
msgid "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"
msgstr "%(stl)s nach %(gcode)s geslicet, dauerte %(time).2f Sekunden"
-#: src/octoprint/static/js/app/dataupdater.js:214
+#: src/octoprint/static/js/app/dataupdater.js:215
#, python-format
msgid "Could not slice %(stl)s to %(gcode)s: %(reason)s"
msgstr "Konnte %(stl)s nicht nach %(gcode)s slicen: %(reason)s"
-#: src/octoprint/static/js/app/dataupdater.js:215
+#: src/octoprint/static/js/app/dataupdater.js:216
msgid "Slicing failed"
msgstr "Slicing fehlgeschlagen"
-#: src/octoprint/static/js/app/dataupdater.js:219
+#: src/octoprint/static/js/app/dataupdater.js:220
msgid "Streaming ..."
msgstr "Streaming ..."
-#: src/octoprint/static/js/app/dataupdater.js:225
+#: src/octoprint/static/js/app/dataupdater.js:226
msgid "Streaming done"
msgstr "Streaming abgeschlossen"
-#: src/octoprint/static/js/app/dataupdater.js:226
+#: src/octoprint/static/js/app/dataupdater.js:227
#, python-format
msgid "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"
msgstr "%(local)s nach %(remote)s gestreamt, dauerte %(time).2f Sekunden"
-#: src/octoprint/static/js/app/helpers.js:357
+#: src/octoprint/static/js/app/helpers.js:385
#, python-format
msgid "%(hour)02d:%(minute)02d:%(second)02d"
msgstr "%(hour)02d:%(minute)02d:%(second)02d"
-#: src/octoprint/static/js/app/helpers.js:377
+#: src/octoprint/static/js/app/helpers.js:405
msgid "YYYY-MM-DD HH:mm"
msgstr "DD.MM.YYYY HH:mm"
-#: src/octoprint/static/js/app/helpers.js:395
-#: src/octoprint/static/js/app/helpers.js:400
+#: src/octoprint/static/js/app/helpers.js:423
+#: src/octoprint/static/js/app/helpers.js:428
msgid "off"
msgstr "Aus"
@@ -927,7 +966,7 @@ msgid "Disconnect"
msgstr "Trennen"
#: src/octoprint/static/js/app/viewmodels/control.js:60
-#: src/octoprint/static/js/app/viewmodels/files.js:296
+#: src/octoprint/static/js/app/viewmodels/files.js:330
#: src/octoprint/static/js/app/viewmodels/gcode.js:453
#: src/octoprint/static/js/app/viewmodels/printerstate.js:167
#: src/octoprint/static/js/app/viewmodels/temperature.js:58
@@ -939,32 +978,44 @@ msgstr "Werkzeug"
msgid "Hotend"
msgstr "Hotend"
-#: src/octoprint/static/js/app/viewmodels/files.js:291
-#: src/octoprint/static/js/app/viewmodels/files.js:296
+#: src/octoprint/static/js/app/viewmodels/files.js:47
+msgid "Your available free disk space is critically low."
+msgstr "Dein verfügbarer freier Plattenplatz ist auf einem kritischen Tiefstand."
+
+#: src/octoprint/static/js/app/viewmodels/files.js:49
+msgid "Your available free disk space is starting to run low."
+msgstr "Dein verfügbarer freier Plattenplatz wird langsam knapp."
+
+#: src/octoprint/static/js/app/viewmodels/files.js:51
+msgid "Your current disk usage."
+msgstr "Dein aktuell verfügbarer freier Plattenplatz."
+
+#: src/octoprint/static/js/app/viewmodels/files.js:325
+#: src/octoprint/static/js/app/viewmodels/files.js:330
msgid "Filament"
msgstr "Filament"
-#: src/octoprint/static/js/app/viewmodels/files.js:300
+#: src/octoprint/static/js/app/viewmodels/files.js:334
msgid "Estimated Print Time"
msgstr "Geschätzte Druckdauer"
-#: src/octoprint/static/js/app/viewmodels/files.js:303
+#: src/octoprint/static/js/app/viewmodels/files.js:337
msgid "Last Printed"
msgstr "Zuletzt gedruckt"
-#: src/octoprint/static/js/app/viewmodels/files.js:305
+#: src/octoprint/static/js/app/viewmodels/files.js:339
msgid "Last Print Time"
msgstr "Letzte Druckdauer"
-#: src/octoprint/static/js/app/viewmodels/files.js:386
+#: src/octoprint/static/js/app/viewmodels/files.js:420
msgid "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\"."
msgstr "Konnte die Datei nicht hochladen. Bitte stelle sicher, dass es sich um eine GCODE-Datei mit der Extension \".gcode\" oder \".gco\" oder um eine STL-Datei mit der Extension \".stl\" handelt."
-#: src/octoprint/static/js/app/viewmodels/files.js:402
+#: src/octoprint/static/js/app/viewmodels/files.js:436
msgid "Uploading ..."
msgstr "Uploade ..."
-#: src/octoprint/static/js/app/viewmodels/files.js:405
+#: src/octoprint/static/js/app/viewmodels/files.js:439
msgid "Saving ..."
msgstr "Speichere ..."
@@ -1018,7 +1069,7 @@ msgstr "Schichthöhe"
#: src/octoprint/static/js/app/viewmodels/gcode.js:447
msgid "GCODE commands in layer"
-msgstr "GCODE Kommandos in Schicht"
+msgstr "GCODE Befehle in Schicht"
#: src/octoprint/static/js/app/viewmodels/gcode.js:450
#: src/octoprint/static/js/app/viewmodels/gcode.js:453
@@ -1063,56 +1114,56 @@ msgstr "Du bist jetzt ausgeloggt"
#: src/octoprint/static/js/app/viewmodels/navigation.js:28
#, python-format
msgid "The command \"%(command)s\" executed successfully"
-msgstr "Das Kommando \"%(command)s\" wurde erfolgreich ausgeführt"
+msgstr "Der Befehl \"%(command)s\" wurde erfolgreich ausgeführt"
#: src/octoprint/static/js/app/viewmodels/navigation.js:32
#, python-format
msgid "The command \"%(command)s\" could not be executed."
-msgstr "Das Kommando \"%(command)s\" konnte nicht ausgeführt werden."
+msgstr "Der Befehl \"%(command)s\" konnte nicht ausgeführt werden."
#: src/octoprint/static/js/app/viewmodels/navigation.js:34
msgid "Error"
msgstr "Fehler"
#: src/octoprint/static/js/app/viewmodels/printerprofiles.js:96
-#: src/octoprint/static/js/app/viewmodels/settings.js:53
-#: src/octoprint/static/js/app/viewmodels/settings.js:83
+#: src/octoprint/static/js/app/viewmodels/settings.js:57
+#: src/octoprint/static/js/app/viewmodels/settings.js:87
msgid "default"
msgstr "Standard"
#: src/octoprint/static/js/app/viewmodels/printerprofiles.js:97
-#: src/octoprint/static/js/app/viewmodels/settings.js:54
-#: src/octoprint/static/js/app/viewmodels/settings.js:67
+#: src/octoprint/static/js/app/viewmodels/settings.js:58
+#: src/octoprint/static/js/app/viewmodels/settings.js:71
msgid "red"
msgstr "Rot"
#: src/octoprint/static/js/app/viewmodels/printerprofiles.js:98
-#: src/octoprint/static/js/app/viewmodels/settings.js:55
-#: src/octoprint/static/js/app/viewmodels/settings.js:69
+#: src/octoprint/static/js/app/viewmodels/settings.js:59
+#: src/octoprint/static/js/app/viewmodels/settings.js:73
msgid "orange"
msgstr "Orange"
#: src/octoprint/static/js/app/viewmodels/printerprofiles.js:99
-#: src/octoprint/static/js/app/viewmodels/settings.js:56
-#: src/octoprint/static/js/app/viewmodels/settings.js:71
+#: src/octoprint/static/js/app/viewmodels/settings.js:60
+#: src/octoprint/static/js/app/viewmodels/settings.js:75
msgid "yellow"
msgstr "Gelb"
#: src/octoprint/static/js/app/viewmodels/printerprofiles.js:100
-#: src/octoprint/static/js/app/viewmodels/settings.js:57
-#: src/octoprint/static/js/app/viewmodels/settings.js:73
+#: src/octoprint/static/js/app/viewmodels/settings.js:61
+#: src/octoprint/static/js/app/viewmodels/settings.js:77
msgid "green"
msgstr "Grün"
#: src/octoprint/static/js/app/viewmodels/printerprofiles.js:101
-#: src/octoprint/static/js/app/viewmodels/settings.js:58
-#: src/octoprint/static/js/app/viewmodels/settings.js:75
+#: src/octoprint/static/js/app/viewmodels/settings.js:62
+#: src/octoprint/static/js/app/viewmodels/settings.js:79
msgid "blue"
msgstr "Blau"
#: src/octoprint/static/js/app/viewmodels/printerprofiles.js:102
-#: src/octoprint/static/js/app/viewmodels/settings.js:60
-#: src/octoprint/static/js/app/viewmodels/settings.js:79
+#: src/octoprint/static/js/app/viewmodels/settings.js:64
+#: src/octoprint/static/js/app/viewmodels/settings.js:83
msgid "black"
msgstr "Schwarz"
@@ -1193,18 +1244,18 @@ msgid "Pause"
msgstr "Pause"
#: src/octoprint/static/js/app/viewmodels/printerstate.js:96
-#: src/octoprint/templates/tabs/timelapse.jinja2:7
+#: src/octoprint/templates/tabs/timelapse.jinja2:10
msgid "On Z Change"
msgstr "Bei Ebenenwechsel"
#: src/octoprint/static/js/app/viewmodels/printerstate.js:98
-#: src/octoprint/templates/tabs/timelapse.jinja2:8
+#: src/octoprint/templates/tabs/timelapse.jinja2:11
msgid "Timed"
msgstr "Nach Zeit"
#: src/octoprint/static/js/app/viewmodels/printerstate.js:98
-#: src/octoprint/templates/tabs/timelapse.jinja2:20
-#: src/octoprint/templates/tabs/timelapse.jinja2:27
+#: src/octoprint/templates/tabs/timelapse.jinja2:24
+#: src/octoprint/templates/tabs/timelapse.jinja2:31
msgid "sec"
msgstr "Sek"
@@ -1212,17 +1263,17 @@ msgstr "Sek"
msgid "This will restart the print job from the beginning."
msgstr "Der Druckjob wird zurückgesetzt und von vorne begonnen."
-#: src/octoprint/static/js/app/viewmodels/settings.js:59
-#: src/octoprint/static/js/app/viewmodels/settings.js:77
+#: src/octoprint/static/js/app/viewmodels/settings.js:63
+#: src/octoprint/static/js/app/viewmodels/settings.js:81
msgid "violet"
msgstr "Violett"
-#: src/octoprint/static/js/app/viewmodels/settings.js:61
-#: src/octoprint/static/js/app/viewmodels/settings.js:81
+#: src/octoprint/static/js/app/viewmodels/settings.js:65
+#: src/octoprint/static/js/app/viewmodels/settings.js:85
msgid "white"
msgstr "weiß"
-#: src/octoprint/static/js/app/viewmodels/settings.js:89
+#: src/octoprint/static/js/app/viewmodels/settings.js:93
msgid "Autodetect from browser"
msgstr "Automatisch vom Browser erkennen"
@@ -1470,7 +1521,7 @@ msgstr "Admin"
#: src/octoprint/templates/dialogs/settings/accesscontrol.jinja2:7
#: src/octoprint/templates/dialogs/settings/logs.jinja2:15
#: src/octoprint/templates/dialogs/settings/printerprofiles.jinja2:7
-#: src/octoprint/templates/tabs/timelapse.jinja2:52
+#: src/octoprint/templates/tabs/timelapse.jinja2:56
msgid "Action"
msgstr "Aktion"
@@ -1650,50 +1701,70 @@ msgstr "Immer davon ausgehen, dass eine SD-Karte vorhanden ist"
#: src/octoprint/templates/dialogs/settings/features.jinja2:47
#: src/octoprint/templates/dialogs/settings/features.jinja2:54
#: src/octoprint/templates/dialogs/settings/features.jinja2:61
+#: src/octoprint/templates/dialogs/settings/features.jinja2:68
msgid "Repetier"
msgstr "Repetier"
#: src/octoprint/templates/dialogs/settings/features.jinja2:47
msgid "Send a checksum with every command"
-msgstr "Eine Prüfsumme mit jedem Kommando senden"
+msgstr "Eine Prüfsumme mit jedem Befehl senden"
#: src/octoprint/templates/dialogs/settings/features.jinja2:54
+msgid "Ignore consecutive resend requests for the same line"
+msgstr "Aufeinanderfolgende Resend Requests für die selbe Zeilennummer ignorieren"
+
+#: src/octoprint/templates/dialogs/settings/features.jinja2:61
#, python-format
msgid "Support TargetExtr%%n/TargetBed target temperature format"
msgstr "TargetExtr%%n/TargetBed Zieltemperaturformat unterstützen"
-#: src/octoprint/templates/dialogs/settings/features.jinja2:61
+#: src/octoprint/templates/dialogs/settings/features.jinja2:68
msgid "Disable detection of external heatups"
msgstr "Detektierung externer Aufheizvorgänge deaktivieren"
-#: src/octoprint/templates/dialogs/settings/features.jinja2:68
-msgid "Swallow the first \"ok\" after a resend response"
-msgstr "Erstes \"ok\" nach Resend ignorieren"
-
-#: src/octoprint/templates/dialogs/settings/folders.jinja2:3
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:5
msgid "Upload Folder"
msgstr "Uploadverzeichnis"
-#: src/octoprint/templates/dialogs/settings/folders.jinja2:9
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:11
msgid "Timelapse Folder"
msgstr "Zeitrafferverzeichnis"
-#: src/octoprint/templates/dialogs/settings/folders.jinja2:15
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:17
msgid "Timelapse Temp Folder"
msgstr "Temporäres Zeitrafferverzeichnis"
-#: src/octoprint/templates/dialogs/settings/folders.jinja2:21
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:23
msgid "Logs Folder"
msgstr "Logverzeichnis"
-#: src/octoprint/templates/dialogs/settings/folders.jinja2:27
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:29
msgid "Watched Folder"
msgstr "Beobachtetes Verzeichnis"
-#: src/octoprint/templates/dialogs/settings/folders.jinja2:35
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:37
msgid "Actively poll the watched folder. Check this if files in your watched folder aren't automatically added otherwise."
msgstr "Aktives Pollen des beobachteten Verzeichnisses. Einschalten wenn Dateien in Deinem beobachteten Verzeichnis hinzugefügt werden sonst nicht automatisch hinzugefügt werden."
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:42
+msgid "Disk space thresholds"
+msgstr "Plattenplatzschwellwerte"
+
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:44
+msgid "If the free disk space falls below these thresholds, OctoPrint will warn the user."
+msgstr "Falls der freie Plattenplatz unter diese Schwellwerte fallen sollte wird OctoPrint den Nutzer warnen."
+
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:47
+#: src/octoprint/templates/dialogs/settings/serialconnection.jinja2:69
+#: src/octoprint/templates/tabs/gcodeviewer.jinja2:62
+#: src/octoprint/templates/tabs/timelapse.jinja2:13
+msgid "Warning"
+msgstr "Warnung"
+
+#: src/octoprint/templates/dialogs/settings/folders.jinja2:53
+msgid "Critical"
+msgstr "Kritisch"
+
#: src/octoprint/templates/dialogs/settings/gcodescripts.jinja2:3
msgid "Before print job starts"
msgstr "Vor dem Start eines Druckjobs"
@@ -1726,8 +1797,8 @@ msgstr "Änderungsdatum"
#: src/octoprint/templates/dialogs/settings/logs.jinja2:13
#: src/octoprint/templates/sidebar/files.jinja2:10
#: src/octoprint/templates/sidebar/files.jinja2:24
-#: src/octoprint/templates/tabs/timelapse.jinja2:45
-#: src/octoprint/templates/tabs/timelapse.jinja2:51
+#: src/octoprint/templates/tabs/timelapse.jinja2:49
+#: src/octoprint/templates/tabs/timelapse.jinja2:55
msgid "Size"
msgstr "Größe"
@@ -1891,11 +1962,6 @@ msgstr "Autodetectiontimeout"
msgid "Log communication to serial.log (might negatively impact performance)"
msgstr "Logge die Kommunikation in das serial.log (kann die Performance negativ beeinflussen)"
-#: src/octoprint/templates/dialogs/settings/serialconnection.jinja2:69
-#: src/octoprint/templates/tabs/gcodeviewer.jinja2:62
-msgid "Warning"
-msgstr "Warnung"
-
#: src/octoprint/templates/dialogs/settings/serialconnection.jinja2:74
msgid "Long running commands"
msgstr "Lang laufende Befehle"
@@ -1913,6 +1979,34 @@ msgstr "Zusätzliche serielle Ports"
msgid "Use this to define additional glob patterns matching serial ports to list for connecting against, e.g. /dev/ttyAMA*. One entry per line."
msgstr "Nutze diese Einstellung um zusätzliche glob patterns zu konfigurieren, die auf serielle Ports deines Druckers matchen, z.B. /dev/ttyAMA*. Ein Eintrag pro Zeile."
+#: src/octoprint/templates/dialogs/settings/server.jinja2:2
+msgid "Commands"
+msgstr "Befehle"
+
+#: src/octoprint/templates/dialogs/settings/server.jinja2:4
+msgid "Command to restart the OctoPrint server"
+msgstr "Befehl zum Neustart des OctoPrint-Servers"
+
+#: src/octoprint/templates/dialogs/settings/server.jinja2:5
+msgid "Restart OctoPrint"
+msgstr "OctoPrint neustarten"
+
+#: src/octoprint/templates/dialogs/settings/server.jinja2:10
+msgid "Command to restart the system OctoPrint is running on"
+msgstr "Befehl zum Neustart des Systems, auf dem OctoPrint läuft"
+
+#: src/octoprint/templates/dialogs/settings/server.jinja2:11
+msgid "Restart system"
+msgstr "System neustarten"
+
+#: src/octoprint/templates/dialogs/settings/server.jinja2:16
+msgid "Command to shut down the system OctoPrint is running on"
+msgstr "Befehl zum Herunterfahren des Systems, auf dem OctoPrint läuft"
+
+#: src/octoprint/templates/dialogs/settings/server.jinja2:17
+msgid "Shutdown system"
+msgstr "System herunterfahren"
+
#: src/octoprint/templates/dialogs/settings/temperatures.jinja2:2
msgid "Temperature Graph"
msgstr "Temperaturgraph"
@@ -2059,6 +2153,10 @@ msgstr "Automatisch bei Serverstart verbinden"
msgid "Uploaded"
msgstr "Hochgeladen"
+#: src/octoprint/templates/sidebar/files.jinja2:13
+msgid "Additional data"
+msgstr "Weitere Daten"
+
#: src/octoprint/templates/sidebar/files.jinja2:14
#: src/octoprint/templates/sidebar/files.jinja2:26
msgid "Download"
@@ -2081,6 +2179,10 @@ msgstr "Laden und Drucken"
msgid "Free"
msgstr "Frei"
+#: src/octoprint/templates/sidebar/files.jinja2:37
+msgid "Total"
+msgstr "Gesamt"
+
#: src/octoprint/templates/sidebar/files.jinja2:64
msgid "Hint: You can also drag and drop files on this page to upload them."
msgstr "Hinweis: Du kannst auch Dateien auf diese Seite ziehen um sie hochzuladen."
@@ -2318,7 +2420,7 @@ msgid "Set"
msgstr "Setzen"
#: src/octoprint/templates/tabs/temperature.jinja2:41
-#: src/octoprint/templates/tabs/timelapse.jinja2:6
+#: src/octoprint/templates/tabs/timelapse.jinja2:9
msgid "Off"
msgstr "Aus"
@@ -2340,7 +2442,7 @@ msgstr "Senden"
#: src/octoprint/templates/tabs/terminal.jinja2:20
msgid "Hint: Use the arrow up/down keys to recall commands sent previously"
-msgstr "Hinweis: Nutze die Pfeil hoch/runter Tasten um vorher versandte Kommandos wiederaufzurufen "
+msgstr "Hinweis: Nutze die Pfeil hoch/runter Tasten um vorher versandte Befehle wieder aufzurufen "
#: src/octoprint/templates/tabs/terminal.jinja2:27
msgid "Fake Acknowledgement"
@@ -2350,43 +2452,51 @@ msgstr "Bestätigung faken"
msgid "If acknowledgements (\"ok\"s) sent by the firmware get lost due to issues with the serial communication to your printer, OctoPrint's communication with it can become stuck. If that happens, this can help. Please be advised that such occurences hint at general communication issues with your printer which will probably negatively influence your printing results and which you should therefore try to resolve!"
msgstr "Falls Bestätigungen (\"ok\"s) Deiner Firmware aufgrund von Kommunikationsproblemen mit Deinem Drucker verloren gehen, kann die Kommunikation zwischen OctoPrint und Deinem Drucker zum Stillstand kommen. Falls das passiert, kann das hier helfen. Bitte bedenke, dass solche Vorfälle ein Hinweis auf ein generelles Kommunikationsproblem mit Deinem Drucker hindeuten, das wahrscheinlich Deine Druckergebnisse negativ beeinflusst und dass du daher versuchen solltest, zu beseitigen!"
-#: src/octoprint/templates/tabs/timelapse.jinja2:2
+#: src/octoprint/templates/tabs/timelapse.jinja2:3
+msgid "Take note that timelapse configuration is disabled while your printer is printing."
+msgstr "Bitte beachte dass die Zeitrafferkonfiguration während des Druckens deaktiviert ist."
+
+#: src/octoprint/templates/tabs/timelapse.jinja2:5
msgid "Timelapse Configuration"
msgstr "Zeitrafferkonfiguration"
-#: src/octoprint/templates/tabs/timelapse.jinja2:4
+#: src/octoprint/templates/tabs/timelapse.jinja2:7
msgid "Timelapse Mode"
msgstr "Zeitraffermodus"
-#: src/octoprint/templates/tabs/timelapse.jinja2:11
+#: src/octoprint/templates/tabs/timelapse.jinja2:13
+msgid "Do not use with spiralized (\"Joris\") vases or similar continuous Z models."
+msgstr "Nicht mit spiralisierten Vasen (\"Joris\") oder ähnlichen Modellen mit ständigen Z-Achsen-Änderungen verwenden."
+
+#: src/octoprint/templates/tabs/timelapse.jinja2:15
msgid "Timelapse frame rate (in frames per second)"
msgstr "Zeitrafferbildrate (in Bildern pro Sekunde)"
-#: src/octoprint/templates/tabs/timelapse.jinja2:14
+#: src/octoprint/templates/tabs/timelapse.jinja2:18
msgid "fps"
msgstr "FPS"
-#: src/octoprint/templates/tabs/timelapse.jinja2:17
+#: src/octoprint/templates/tabs/timelapse.jinja2:21
msgid "Timelapse post roll (in rendered seconds)"
msgstr "Zeitraffernachlauf (in gerenderten Sekunden)"
-#: src/octoprint/templates/tabs/timelapse.jinja2:24
+#: src/octoprint/templates/tabs/timelapse.jinja2:28
msgid "Interval"
msgstr "Intervall"
-#: src/octoprint/templates/tabs/timelapse.jinja2:33
+#: src/octoprint/templates/tabs/timelapse.jinja2:37
msgid "Save as default"
msgstr "Als Standard speichern"
-#: src/octoprint/templates/tabs/timelapse.jinja2:38
+#: src/octoprint/templates/tabs/timelapse.jinja2:42
msgid "Save config"
msgstr "Konfiguration speichern"
-#: src/octoprint/templates/tabs/timelapse.jinja2:42
+#: src/octoprint/templates/tabs/timelapse.jinja2:46
msgid "Finished Timelapses"
msgstr "Abgeschlossene Zeitraffer"
-#: src/octoprint/templates/tabs/timelapse.jinja2:45
+#: src/octoprint/templates/tabs/timelapse.jinja2:49
msgid "Creation date"
msgstr "Erstellungsdatum"
@@ -2434,3 +2544,15 @@ msgstr "Erstellungsdatum"
#~ msgid ""
#~ msgstr ""
+
+#~ msgid "Updating, please wait."
+#~ msgstr "Aktualisiere gerade, bitte warten."
+
+#~ msgid "Restart Command"
+#~ msgstr "Neustartbefehl"
+
+#~ msgid "Reboot Command"
+#~ msgstr "Rebootbefehl"
+
+#~ msgid "Swallow the first \"ok\" after a resend response"
+#~ msgstr "Erstes \"ok\" nach Resend ignorieren"
diff --git a/translations/messages.pot b/translations/messages.pot
index 2397cbf31..e5a10bf43 100644
--- a/translations/messages.pot
+++ b/translations/messages.pot
@@ -6,9 +6,9 @@
#, fuzzy
msgid ""
msgstr ""
-"Project-Id-Version: OctoPrint 1.3.0.dev75+g22d12ac.dirty\n"
+"Project-Id-Version: OctoPrint 1.2.5-dev-57-g8ed0bef-dirty\n"
"Report-Msgid-Bugs-To: i18n@octoprint.org\n"
-"POT-Creation-Date: 2015-07-07 18:20+0200\n"
+"POT-Creation-Date: 2015-08-31 10:04+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME \n"
"Language-Team: LANGUAGE \n"
@@ -40,7 +40,7 @@ msgstr ""
#: src/octoprint/plugins/cura/templates/cura_settings.jinja2:22
#: src/octoprint/templates/dialogs/settings/logs.jinja2:6
-#: src/octoprint/templates/tabs/timelapse.jinja2:45
+#: src/octoprint/templates/tabs/timelapse.jinja2:49
msgid "Sort by"
msgstr ""
@@ -55,7 +55,7 @@ msgstr ""
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:75
#: src/octoprint/templates/dialogs/settings/logs.jinja2:6
#: src/octoprint/templates/sidebar/files_header.jinja2:6
-#: src/octoprint/templates/tabs/timelapse.jinja2:45
+#: src/octoprint/templates/tabs/timelapse.jinja2:49
msgid "ascending"
msgstr ""
@@ -69,8 +69,8 @@ msgstr ""
#: src/octoprint/templates/dialogs/settings/printerprofiles.jinja2:5
#: src/octoprint/templates/dialogs/settings/printerprofiles.jinja2:44
#: src/octoprint/templates/dialogs/settings/terminalfilters.jinja2:3
-#: src/octoprint/templates/tabs/timelapse.jinja2:45
-#: src/octoprint/templates/tabs/timelapse.jinja2:50
+#: src/octoprint/templates/tabs/timelapse.jinja2:49
+#: src/octoprint/templates/tabs/timelapse.jinja2:54
msgid "Name"
msgstr ""
@@ -136,247 +136,247 @@ msgstr ""
msgid "Plugin Manager"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:130
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:270
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:132
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:277
msgid "Installing plugin..."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:130
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:132
msgid "Installing plugin from uploaded archive..."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:142
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:222
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:295
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:325
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:539
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:569
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:586
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:603
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:147
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:225
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:302
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:332
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:546
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:576
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:593
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:610
msgid "Something went wrong"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:143
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:223
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:296
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:326
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:148
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:226
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:303
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:333
msgid "Please consult octoprint.log for details"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:272
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:279
#, python-format
msgid "Installing plugin \"%(name)s\" from %(url)s..."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:274
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:281
#, python-format
msgid "Installing plugin from %(url)s..."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:277
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:284
msgid "Reinstalling plugin..."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:278
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:285
#, python-format
msgid "Reinstalling plugin \"%(name)s\" from %(url)s..."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:316
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:323
msgid "Uninstalling plugin..."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:316
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:323
#, python-format
msgid "Uninstalling plugin \"%(name)s\""
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:351
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:358
msgid "Reinstall"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:351
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:358
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:130
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:146
msgid "Install"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:351
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:358
msgid "Incompatible"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:369
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:376
#: src/octoprint/templates/overlays/reloadui.jinja2:9
msgid "Reload now"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:438
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:445
msgid "Done!"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:458
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:465
msgid "Enable Plugin"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:458
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:465
msgid "Disable Plugin"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:523
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:530
msgid "Plugin installed"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:524
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:531
msgid ""
"A plugin was installed successfully, however it was impossible to detect "
"which one. Please Restart OctoPrint to make sure everything will be "
"registered properly"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:528
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:535
#, python-format
msgid "Plugin \"%(name)s\" reinstalled"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:529
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:536
msgid "The plugin was reinstalled successfully"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:530
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:537
msgid ""
"The plugin was reinstalled successfully, however a restart of OctoPrint "
"is needed for that to take effect."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:531
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:538
msgid ""
"The plugin was reinstalled successfully, however a reload of the page is "
"needed for that to take effect."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:533
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:540
#, python-format
msgid "Plugin \"%(name)s\" installed"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:534
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:541
msgid "The plugin was installed successfully"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:535
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:542
msgid ""
"The plugin was installed successfully, however a restart of OctoPrint is "
"needed for that to take effect."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:536
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:543
msgid ""
"The plugin was installed successfully, however a reload of the page is "
"needed for that to take effect."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:547
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:554
#, python-format
msgid "Reinstalling the plugin from URL \"%(url)s\" failed: %(reason)s"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:549
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:556
#, python-format
msgid "Installing the plugin from URL \"%(url)s\" failed: %(reason)s"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:553
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:560
#, python-format
msgid ""
"Reinstalling the plugin from URL \"%(url)s\" failed, please see the log "
"for details."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:555
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:562
#, python-format
msgid ""
"Installing the plugin from URL \"%(url)s\" failed, please see the log for"
" details."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:564
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:571
#, python-format
msgid "Plugin \"%(name)s\" uninstalled"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:565
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:572
msgid "The plugin was uninstalled successfully"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:566
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:573
msgid ""
"The plugin was uninstalled successfully, however a restart of OctoPrint "
"is needed for that to take effect."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:567
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:574
msgid ""
"The plugin was uninstalled successfully, however a reload of the page is "
"needed for that to take effect."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:571
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:578
#, python-format
msgid "Uninstalling the plugin failed: %(reason)s"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:573
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:580
msgid "Uninstalling the plugin failed, please see the log for details."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:581
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:588
#, python-format
msgid "Plugin \"%(name)s\" enabled"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:582
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:589
msgid "The plugin was enabled successfully."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:583
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:590
msgid ""
"The plugin was enabled successfully, however a restart of OctoPrint is "
"needed for that to take effect."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:584
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:591
msgid ""
"The plugin was enabled successfully, however a reload of the page is "
"needed for that to take effect."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:588
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:605
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:595
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:612
#, python-format
msgid "Toggling the plugin failed: %(reason)s"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:590
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:607
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:597
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:614
msgid "Toggling the plugin failed, please see the log for details."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:598
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:605
#, python-format
msgid "Plugin \"%(name)s\" disabled"
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:599
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:606
msgid "The plugin was disabled successfully."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:600
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:607
msgid ""
"The plugin was disabled successfully, however a restart of OctoPrint is "
"needed for that to take effect."
msgstr ""
-#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:601
+#: src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js:608
msgid ""
"The plugin was disabled successfully, however a reload of the page is "
"needed for that to take effect."
@@ -411,8 +411,7 @@ msgid "Get More..."
msgstr ""
#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:59
-#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:152
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:96
+#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:167
#: src/octoprint/templates/dialogs/settings/appearance.jinja2:96
msgid "Close"
msgstr ""
@@ -438,7 +437,7 @@ msgstr ""
#: src/octoprint/templates/dialogs/settings/logs.jinja2:6
#: src/octoprint/templates/sidebar/files_header.jinja2:7
#: src/octoprint/templates/sidebar/files_header.jinja2:8
-#: src/octoprint/templates/tabs/timelapse.jinja2:45
+#: src/octoprint/templates/tabs/timelapse.jinja2:49
msgid "descending"
msgstr ""
@@ -494,12 +493,23 @@ msgid ""
"\".tar.gz\", \".tgz\" or \".tar\""
msgstr ""
-#: src/octoprint/plugins/softwareupdate/__init__.py:331
+#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:152
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:62
+#: src/octoprint/templates/tabs/terminal.jinja2:25
+msgid "Advanced options"
+msgstr ""
+
+#: src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2:158
+msgid "Use --process-dependency-links with pip install"
+msgstr ""
+
+#: src/octoprint/plugins/softwareupdate/__init__.py:378
msgid "Software Update"
msgstr ""
-#: src/octoprint/plugins/softwareupdate/__init__.py:610
-#: src/octoprint/server/views.py:146
+#: src/octoprint/plugins/softwareupdate/__init__.py:662
+#: src/octoprint/plugins/softwareupdate/__init__.py:693
+#: src/octoprint/server/views.py:149
#: src/octoprint/static/js/app/viewmodels/appearance.js:11
#: src/octoprint/static/js/app/viewmodels/appearance.js:13
#: src/octoprint/static/js/app/viewmodels/appearance.js:18
@@ -507,204 +517,237 @@ msgstr ""
msgid "OctoPrint"
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:119
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:26
+msgid "Release"
+msgstr ""
+
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:27
+msgid "Commit"
+msgstr ""
+
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:145
msgid "There are updates available for the following components:"
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:133
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:159
msgid ""
"Those components marked with can be updated "
"directly."
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:136
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:162
msgid "Update Available"
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:147
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:174
msgid "Ignore"
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:151
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:178
msgid ""
"You can make this message display again via \"Settings\" > \"Software "
"Update\" > \"Check for update now\""
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:155
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:182
msgid "Update now"
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:172
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:199
msgid "Everything is up-to-date"
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:237
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:268
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:388
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:264
msgid "Updating..."
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:238
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:265
msgid "Now updating, please wait."
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:257
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:284
msgid "Update not started!"
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:258
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:285
msgid ""
"The update could not be started. Is it already active? Please consult the"
" log for details."
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:268
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:388
-msgid "Updating, please wait."
-msgstr ""
-
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:281
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:307
msgid "Can't update while printing"
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:282
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:308
msgid ""
"A print job is currently in progress. Updating will be prevented until it"
" is done."
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:286
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:312
msgid "This will update your OctoPrint installation and restart the server."
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:347
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:336
msgid "Restart successful!"
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:348
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:337
msgid ""
"The server was restarted successfully. The page will now reload "
"automatically."
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:391
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:369
#, python-format
msgid "Now updating %(name)s to %(version)s"
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:409
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:377
msgid "Update successful, restarting!"
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:410
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:378
msgid "The update finished successfully and the server will now be restarted."
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:426
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:475
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:389
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:431
msgid "Restart failed"
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:427
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:390
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:432
msgid ""
"The server apparently did not restart by itself, you'll have to do it "
"manually. Please consult the log file on what went wrong."
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:449
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:406
msgid "The update finished successfully, please restart OctoPrint now."
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:451
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:408
msgid "The update finished successfully, please reboot the server now."
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:454
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:412
msgid "Update successful, restart required!"
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:470
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:425
msgid ""
"Restarting OctoPrint failed, please restart it manually. You might also "
"want to consult the log file on what went wrong here."
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:472
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:427
msgid ""
"Rebooting the server failed, please reboot it manually. You might also "
"want to consult the log file on what went wrong here."
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:491
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:445
msgid "Update successful!"
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:492
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:446
msgid "The update finished successfully."
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:507
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:458
msgid "Update failed!"
msgstr ""
-#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:508
+#: src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js:459
msgid ""
"The update did not finish successfully. Please consult the log for "
"details."
msgstr ""
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:2
-#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:54
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:1
+msgid ""
+"\n"
+" Please configure the checkout folder of OctoPrint, "
+"otherwise\n"
+" this plugin won't be able to update it. Click on the button\n"
+" to do this. Also refer to the Documentation.\n"
+msgstr ""
+
+#: src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2:6
+msgid ""
+"\n"
+"
\n"
+" You are running a non-release version of OctoPrint but "
+"are tracking OctoPrint\n"
+" releases.\n"
+"
\n"
+" You probably want OctoPrint to track the matching development "
+"version instead.\n"
+" If you have a local OctoPrint checkout folder switched to another"
+" branch,\n"
+" simply switching over to \"Commit\" tracking "
+"will already\n"
+" take care of that. Otherwise please take a look at the\n"
+" Documentation.\n"
+"