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 ========= -[![Flattr this git repo](http://api.flattr.com/button/flattr-badge-large.png)](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). + +![Screenshot](http://i.imgur.com/dF3noFp.png) + +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 %} +
+
+ +
+ +
+
+
+ +
+ +
+
+
+ +
+ + {{ _('Passwords do not match') }} +
+
+
+{% 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! +

{% 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 %} + +
+ {% include "_snippets/settings/webcam/webcamStreamUrl.jinja2" %} + {% include "_snippets/settings/webcam/webcamSnapshotUrl.jinja2" %} +
+ +

{{ _('Timelapse Recordings') }}

+ +{% trans %}

+ To render the snapshots into timelapse recordings, OctoPrint also needs to + know the correct path to FFMPEG. +

{% endtrans %} + +
+ {% include "_snippets/settings/webcam/ffmpegPath.jinja2" %} +
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 @@ + diff --git a/src/octoprint/plugins/cura/templates/_snippets/settings/cura/profiles.jinja2 b/src/octoprint/plugins/cura/templates/_snippets/settings/cura/profiles.jinja2 new file mode 100644 index 000000000..454c97065 --- /dev/null +++ b/src/octoprint/plugins/cura/templates/_snippets/settings/cura/profiles.jinja2 @@ -0,0 +1,34 @@ +
+ + + + + + + + + + + + + + + + +
{{ _('Identifier') }}{{ _('Name') }}{{ _('Actions') }}
+  |  +
+ +
diff --git a/src/octoprint/plugins/cura/templates/cura_settings.jinja2 b/src/octoprint/plugins/cura/templates/cura_settings.jinja2 index 1cacf6587..515192852 100644 --- a/src/octoprint/plugins/cura/templates/cura_settings.jinja2 +++ b/src/octoprint/plugins/cura/templates/cura_settings.jinja2 @@ -1,111 +1,14 @@

{{ _('General') }}

-
- -
-
- - -
- -
-
-
-
- -
-
+ {% include "_snippets/settings/cura/enginePath.jinja2" %} + {% include "_snippets/settings/cura/engineLog.jinja2" %}

{{ _('Profiles') }}

- - - - - - - - - - - - - - - - -
{{ _('Identifier') }}{{ _('Name') }}{{ _('Actions') }}
-  |  -
- +{% include "_snippets/settings/cura/profiles.jinja2" %} - - +{% 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 %}

+ +
+
+ {% include "_snippets/settings/cura/enginePath.jinja2" %} +
+
+
+ +
+

{{ _('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 %} +
+
diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 04c2f1fe1..927403fe5 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -52,7 +52,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._repository_cache_path = os.path.join(self.get_plugin_data_folder(), "plugins.json") self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60 - self._pip_caller = PipCaller(configured=self._settings.get(["pip"])) + self._pip_caller = PipCaller(configured=self._settings.get(["pip"]), + force_user=self._settings.get_boolean(["pip_force_user"])) self._pip_caller.on_log_call = self._log_call self._pip_caller.on_log_stdout = self._log_stdout self._pip_caller.on_log_stderr = self._log_stderr @@ -83,13 +84,25 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, repository="http://plugins.octoprint.org/plugins.json", repository_ttl=24*60, pip=None, + pip_args=None, + pip_force_user=False, + dependency_links=False, hidden=[] ) def on_settings_save(self, data): + old_pip = self._settings.get(["pip"]) octoprint.plugin.SettingsPlugin.on_settings_save(self, data) + new_pip = self._settings.get(["pip"]) + self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60 - self._pip_caller.refresh = True + self._pip_caller.force_user = self._settings.get_boolean(["pip_force_user"]) + if old_pip != new_pip: + self._pip_caller.configured = new_pip + try: + self._pip_caller.trigger_refresh() + except: + self._pip_caller ##~~ AssetPlugin @@ -104,7 +117,20 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def get_template_configs(self): return [ - dict(type="settings", name=gettext("Plugin Manager"), template="pluginmanager_settings.jinja2", custom_bindings=True) + dict(type="settings", name=gettext("Plugin Manager"), template="pluginmanager_settings.jinja2", custom_bindings=True), + dict(type="about", name=gettext("Plugin Licenses"), template="pluginmanager_about.jinja2") + ] + + def get_template_vars(self): + plugins = sorted(self._get_plugins(), key=lambda x: x["name"].lower()) + return dict( + all=plugins, + thirdparty=filter(lambda p: not p["bundled"], plugins) + ) + + def get_template_types(self, template_sorting, template_rules, *args, **kwargs): + return [ + ("about_thirdparty", dict(), dict(template=lambda x: x + "_about_thirdparty.jinja2")) ] ##~~ BlueprintPlugin @@ -160,19 +186,26 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if not admin_permission.can(): return make_response("Insufficient rights", 403) - plugins = self._plugin_manager.plugins - - hidden = self._settings.get(["hidden"]) - result = [] - for name, plugin in plugins.items(): - if name in hidden: - continue - result.append(self._to_external_representation(plugin)) - if "refresh_repository" in request.values and request.values["refresh_repository"] in valid_boolean_trues: self._repository_available = self._refresh_repository() - return jsonify(plugins=result, repository=dict(available=self._repository_available, plugins=self._repository_plugins), os=self._get_os(), octoprint=self._get_octoprint_version_string()) + return jsonify(plugins=self._get_plugins(), + repository=dict( + available=self._repository_available, + plugins=self._repository_plugins + ), + os=self._get_os(), + octoprint=self._get_octoprint_version_string(), + pip=dict( + available=self._pip_caller.available, + command=self._pip_caller.command, + version=self._pip_caller.version_string, + install_dir=self._pip_caller.install_dir, + use_sudo=self._pip_caller.use_sudo, + use_user=self._pip_caller.use_user, + virtual_env=self._pip_caller.virtual_env, + additional_args=self._settings.get(["pip_args"]) + )) def on_api_command(self, command, data): if not admin_permission.can(): @@ -187,6 +220,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, plugin_name = data["plugin"] if "plugin" in data else None return self.command_install(url=url, force="force" in data and data["force"] in valid_boolean_trues, + dependency_links="dependency_links" in data and data["dependency_links"] in valid_boolean_trues, reinstall=plugin_name) elif command == "uninstall": @@ -205,7 +239,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, plugin = self._plugin_manager.plugins[plugin_name] return self.command_toggle(plugin, command) - def command_install(self, url=None, path=None, force=False, reinstall=None): + def command_install(self, url=None, path=None, force=False, reinstall=None, dependency_links=False): if url is not None: pip_args = ["install", sarge.shell_quote(url)] elif path is not None: @@ -213,6 +247,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, else: raise ValueError("Either url or path must be provided") + if dependency_links or self._settings.get_boolean(["dependency_links"]): + pip_args.append("--process-dependency-links") + all_plugins_before = self._plugin_manager.find_plugins() success_string = "Successfully installed" @@ -300,12 +337,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._send_result_notification("install", result) return jsonify(result) - self._plugin_manager.mark_plugin(new_plugin_key, uninstalled=False) self._plugin_manager.reload_plugins() - needs_restart = self._plugin_manager.is_restart_needing_plugin(new_plugin) or new_plugin_key in all_plugins_before or reinstall is not None needs_refresh = new_plugin.implementation and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) + is_reinstall = self._plugin_manager.is_plugin_marked(new_plugin_key, "uninstalled") + self._plugin_manager.mark_plugin(new_plugin_key, + uninstalled=False, + installed=not is_reinstall and needs_restart) + self._plugin_manager.log_all_plugins() result = dict(result=True, url=url, needs_restart=needs_restart, needs_refresh=needs_refresh, was_reinstalled=new_plugin_key in all_plugins_before or reinstall is not None, plugin=self._to_external_representation(new_plugin)) @@ -314,10 +354,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def command_uninstall(self, plugin): if plugin.key == "pluginmanager": - return make_response("Can't uninstall Plugin Manager", 400) + return make_response("Can't uninstall Plugin Manager", 403) + + if not plugin.managable: + return make_response("Plugin is not managable and hence cannot be uninstalled", 403) if plugin.bundled: - return make_response("Bundled plugins cannot be uninstalled", 400) + return make_response("Bundled plugins cannot be uninstalled", 403) if plugin.origin is None: self._logger.warn(u"Trying to uninstall plugin {plugin} but origin is unknown".format(**locals())) @@ -361,7 +404,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) - self._plugin_manager.mark_plugin(plugin.key, uninstalled=True) + was_pending_install = self._plugin_manager.is_plugin_marked(plugin.key, "installed") + self._plugin_manager.mark_plugin(plugin.key, + uninstalled=not was_pending_install and needs_restart, + installed=False) if not needs_restart: try: @@ -421,8 +467,19 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def _call_pip(self, args): if self._pip_caller is None or not self._pip_caller.available: raise RuntimeError(u"No pip available, can't operate".format(**locals())) + + if "--process-dependency-links" in args: + self._log_message(u"Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version") + + additional_args = self._settings.get(["pip_args"]) + if additional_args: + args.append(additional_args) + return self._pip_caller.execute(*args) + def _log_message(self, *lines): + self._log(lines, prefix=u"*", stream="message") + def _log_call(self, *lines): self._log(lines, prefix=u" ", stream="call") @@ -500,7 +557,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, try: import json - with open(self._repository_cache_path, "w+b") as f: + with octoprint.util.atomic_write(self._repository_cache_path, "wb") as f: json.dump(repo_data, f) except Exception as e: self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, str(e))) @@ -519,6 +576,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def map_repository_entry(entry): result = dict(entry) + if not "follow_dependency_links" in result: + result["follow_dependency_links"] = False + + if not "follow_dependency_links" in result: + result["follow_dependency_links"] = False + result["is_compatible"] = dict( octoprint=True, os=True @@ -594,6 +657,18 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, octoprint_version = pkg_resources.parse_version(octoprint_version.base_version) return octoprint_version + def _get_plugins(self): + plugins = self._plugin_manager.plugins + + hidden = self._settings.get(["hidden"]) + result = [] + for name, plugin in plugins.items(): + if name in hidden: + continue + result.append(self._to_external_representation(plugin)) + + return result + def _to_external_representation(self, plugin): return dict( key=plugin.key, @@ -604,11 +679,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, url=plugin.url, license=plugin.license, bundled=plugin.bundled, + managable=plugin.managable, enabled=plugin.enabled, pending_enable=(not plugin.enabled and plugin.key in self._pending_enable), pending_disable=(plugin.enabled and plugin.key in self._pending_disable), - pending_install=(plugin.key in self._pending_install), - pending_uninstall=(plugin.key in self._pending_uninstall) + pending_install=(self._plugin_manager.is_plugin_marked(plugin.key, "installed")), + pending_uninstall=(self._plugin_manager.is_plugin_marked(plugin.key, "uninstalled")), + origin=plugin.origin.type ) __plugin_name__ = "Plugin Manager" @@ -623,5 +700,6 @@ def __plugin_load__(): global __plugin_hooks__ __plugin_hooks__ = { - "octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize + "octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize, + "octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types } diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index eba85fade..5e3baf7e1 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -1,3 +1,70 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrint"], factory); + } else { + factory(window.OctoPrint); + } +})(window || this, function(OctoPrint) { + var exports = {}; + + exports.get = function(refresh, opts) { + return OctoPrint.get(OctoPrint.getSimpleApiUrl("pluginmanager") + ((refresh) ? "?refresh_repository=true" : ""), opts); + }; + + exports.getWithRefresh = function(opts) { + return exports.get(true, opts); + }; + + exports.getWithoutRefresh = function(opts) { + return exports.get(false, opts); + }; + + exports.install = function(pluginUrl, dependencyLinks, opts) { + var data = { + url: pluginUrl, + dependency_links: !!dependencyLinks + }; + return OctoPrint.simpleApiCommand("pluginmanager", "install", data, opts); + }; + + exports.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) { + var data = { + url: pluginUrl, + dependency_links: !!dependencyLinks, + reinstall: plugin, + force: true + }; + return OctoPrint.simpleApiCommand("pluginmanager", "install", data, opts); + }; + + exports.uninstall = function(plugin, opts) { + var data = { + plugin: plugin + }; + return OctoPrint.simpleApiCommand("pluginmanager", "uninstall", data, opts); + }; + + exports.enable = function(plugin, opts) { + var data = { + plugin: plugin + }; + return OctoPrint.simpleApiCommand("pluginmanager", "enable", data, opts); + }; + + exports.disable = function(plugin, opts) { + var data = { + plugin: plugin + }; + return OctoPrint.simpleApiCommand("pluginmanager", "disable", data, opts); + }; + + exports.upload = function(file) { + return OctoPrint.upload(OctoPrint.getBlueprintUrl("pluginmanager") + "upload_archive", file); + }; + + OctoPrint.plugins.pluginmanager = exports; +}); + $(function() { function PluginManagerViewModel(parameters) { var self = this; @@ -5,6 +72,15 @@ $(function() { self.loginState = parameters[0]; self.settingsViewModel = parameters[1]; self.printerState = parameters[2]; + self.systemViewModel = parameters[3]; + + self.config_repositoryUrl = ko.observable(); + self.config_repositoryTtl = ko.observable(); + self.config_pipCommand = ko.observable(); + self.config_pipAdditionalArgs = ko.observable(); + self.config_pipForceUser = ko.observable(); + + self.configurationDialog = $("#settings_plugin_pluginmanager_configurationdialog"); self.plugins = new ItemListHelper( "plugin.pluginmanager.installedplugins", @@ -70,11 +146,46 @@ $(function() { self.loglines = ko.observableArray([]); self.installedPlugins = ko.observableArray([]); + self.followDependencyLinks = ko.observable(false); + + self.pipAvailable = ko.observable(false); + self.pipCommand = ko.observable(); + self.pipVersion = ko.observable(); + self.pipInstallDir = ko.observable(); + self.pipUseUser = ko.observable(); + self.pipUseSudo = ko.observable(); + self.pipVirtualEnv = ko.observable(); + self.pipAdditionalArgs = ko.observable(); + + self.pipUseSudoString = ko.computed(function() { + return self.pipUseSudo() ? "yes" : "no"; + }); + self.pipUseUserString = ko.computed(function() { + return self.pipUseUser() ? "yes" : "no"; + }); + self.pipVirtualEnvString = ko.computed(function() { + return self.pipVirtualEnv() ? "yes" : "no"; + }); + self.working = ko.observable(false); self.workingTitle = ko.observable(); self.workingDialog = undefined; self.workingOutput = undefined; + self.restartCommandSpec = undefined; + self.systemViewModel.systemActions.subscribe(function() { + var lastResponse = self.systemViewModel.lastCommandResponse; + if (!lastResponse || !lastResponse.core) { + self.restartCommandSpec = undefined; + return; + } + + var restartSpec = _.filter(lastResponse.core, function(spec) { return spec.action == "restart" }); + self.restartCommandSpec = restartSpec != undefined && restartSpec.length > 0 ? restartSpec[0] : undefined; + }); + + self.notifications = []; + self.enableManagement = ko.computed(function() { return !self.printerState.isPrinting(); }); @@ -84,11 +195,16 @@ $(function() { }; self.enableUninstall = function(data) { - return self.enableManagement() && !data.bundled && data.key != 'pluginmanager' && !data.pending_uninstall; + return self.enableManagement() + && (data.origin != "entry_point" || self.pipAvailable()) + && data.managable + && !data.bundled + && data.key != 'pluginmanager' + && !data.pending_uninstall; }; self.enableRepoInstall = function(data) { - return self.enableManagement() && self.isCompatible(data); + return self.enableManagement() && self.pipAvailable() && self.isCompatible(data); }; self.invalidUrl = ko.computed(function() { @@ -98,7 +214,7 @@ $(function() { self.enableUrlInstall = ko.computed(function() { var url = self.installUrl(); - return self.enableManagement() && url !== undefined && url.trim() != "" && !self.invalidUrl(); + return self.enableManagement() && self.pipAvailable() && url !== undefined && url.trim() != "" && !self.invalidUrl(); }); self.invalidArchive = ko.computed(function() { @@ -108,7 +224,7 @@ $(function() { self.enableArchiveInstall = ko.computed(function() { var name = self.uploadFilename(); - return self.enableManagement() && name !== undefined && name.trim() != "" && !self.invalidArchive(); + return self.enableManagement() && self.pipAvailable() && name !== undefined && name.trim() != "" && !self.invalidArchive(); }); self.uploadElement.fileupload({ @@ -125,6 +241,9 @@ $(function() { self.uploadButton.unbind("click"); self.uploadButton.bind("click", function() { self._markWorking(gettext("Installing plugin..."), gettext("Installing plugin from uploaded archive...")); + data.formData = { + dependency_links: self.followDependencyLinks() + }; data.submit(); return false; }); @@ -162,7 +281,8 @@ $(function() { self.fromResponse = function(data) { self._fromPluginsResponse(data.plugins); - self._fromRepositoryResponse(data.repository) + self._fromRepositoryResponse(data.repository); + self._fromPipResponse(data.pip); }; self._fromPluginsResponse = function(data) { @@ -183,17 +303,34 @@ $(function() { } }; + self._fromPipResponse = function(data) { + self.pipAvailable(data.available); + if (data.available) { + self.pipCommand(data.command); + self.pipVersion(data.version); + self.pipInstallDir(data.install_dir); + self.pipUseUser(data.use_user); + self.pipUseSudo(data.use_sudo); + self.pipVirtualEnv(data.virtual_env); + self.pipAdditionalArgs(data.additional_args); + } else { + self.pipCommand(undefined); + self.pipVersion(undefined); + self.pipInstallDir(undefined); + self.pipUseUser(undefined); + self.pipUseSudo(undefined); + self.pipVirtualEnv(undefined); + self.pipAdditionalArgs(undefined); + } + }; + self.requestData = function(includeRepo) { if (!self.loginState.isAdmin()) { return; } - $.ajax({ - url: API_BASEURL + "plugin/pluginmanager" + ((includeRepo) ? "?refresh_repository=true" : ""), - type: "GET", - dataType: "json", - success: self.fromResponse - }); + OctoPrint.plugins.pluginmanager.get(includeRepo) + .done(self.fromResponse); }; self.togglePlugin = function(data) { @@ -207,19 +344,25 @@ $(function() { if (data.key == "pluginmanager") return; - var command = self._getToggleCommand(data); + var onSuccess = self.requestData, + onError = function() { + new PNotify({ + title: gettext("Something went wrong"), + text: gettext("Please consult octoprint.log for details"), + type: "error", + hide: false + }) + }; - var payload = {plugin: data.key}; - self._postCommand(command, payload, function(response) { - self.requestData(); - }, function() { - new PNotify({ - title: gettext("Something went wrong"), - text: gettext("Please consult octoprint.log for details"), - type: "error", - hide: false - }) - }); + if (self._getToggleCommand(data) == "enable") { + OctoPrint.plugins.pluginmanager.enable(data.key) + .done(onSuccess) + .fail(onError); + } else { + OctoPrint.plugins.pluginmanager.disable(data.key) + .done(onSuccess) + .fail(onError); + } }; self.showRepository = function() { @@ -239,14 +382,10 @@ $(function() { return; } - if (self.installed(data)) { - self.installPlugin(data.archive, data.title, data.id); - } else { - self.installPlugin(data.archive, data.title, undefined); - } + self.installPlugin(data.archive, data.title, (self.installed(data) ? data.id : undefined), data.follow_dependency_links || self.followDependencyLinks()); }; - self.installPlugin = function(url, name, reinstall) { + self.installPlugin = function(url, name, reinstall, followDependencyLinks) { if (!self.loginState.isAdmin()) { return; } @@ -260,6 +399,10 @@ $(function() { } if (!url) return; + if (followDependencyLinks === undefined) { + followDependencyLinks = self.followDependencyLinks(); + } + var workTitle, workText; if (!reinstall) { workTitle = gettext("Installing plugin..."); @@ -274,26 +417,33 @@ $(function() { } self._markWorking(workTitle, workText); - var command = "install"; - var payload = {url: url}; - if (reinstall) { - payload["plugin"] = reinstall; - payload["force"] = true; - } + var onSuccess = function() { + self.requestData(); + self.installUrl(""); + }, + onError = function() { + new PNotify({ + title: gettext("Something went wrong"), + text: gettext("Please consult octoprint.log for details"), + type: "error", + hide: false + }); + }, + onAlways = function() { + self._markDone(); + }; - self._postCommand(command, payload, function(response) { - self.requestData(); - self._markDone(); - self.installUrl(""); - }, function() { - new PNotify({ - title: gettext("Something went wrong"), - text: gettext("Please consult octoprint.log for details"), - type: "error", - hide: false - }); - self._markDone(); - }); + if (reinstall) { + OctoPrint.plugins.pluginmanager.reinstall(reinstall, url, followDependencyLinks) + .done(onSuccess) + .fail(onError) + .always(onAlways); + } else { + OctoPrint.plugins.pluginmanager.install(url, followDependencyLinks) + .done(onSuccess) + .fail(onError) + .always(onAlways); + } }; self.uninstallPlugin = function(data) { @@ -310,20 +460,19 @@ $(function() { self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: data.name})); - var command = "uninstall"; - var payload = {plugin: data.key}; - self._postCommand(command, payload, function(response) { - self.requestData(); - self._markDone(); - }, function() { - new PNotify({ - title: gettext("Something went wrong"), - text: gettext("Please consult octoprint.log for details"), - type: "error", - hide: false + OctoPrint.plugins.pluginmanager.uninstall(data.key) + .done(self.requestData) + .fail(function() { + new PNotify({ + title: gettext("Something went wrong"), + text: gettext("Please consult octoprint.log for details"), + type: "error", + hide: false + }); + }) + .always(function() { + self._markDone(); }); - self._markDone(); - }); }; self.refreshRepository = function() { @@ -334,6 +483,60 @@ $(function() { self.requestData(true); }; + self.showPluginSettings = function() { + self._copyConfig(); + self.configurationDialog.modal(); + }; + + self.savePluginSettings = function() { + var pipCommand = self.config_pipCommand(); + if (pipCommand != undefined && pipCommand.trim() == "") { + pipCommand = null; + } + + var repository = self.config_repositoryUrl(); + if (repository != undefined && repository.trim() == "") { + repository = null; + } + + var repositoryTtl; + try { + repositoryTtl = parseInt(self.config_repositoryTtl()); + } catch (ex) { + repositoryTtl = null; + } + + var pipArgs = self.config_pipAdditionalArgs(); + if (pipArgs != undefined && pipArgs.trim() == "") { + pipArgs = null; + } + + var data = { + plugins: { + pluginmanager: { + repository: repository, + repository_ttl: repositoryTtl, + pip: pipCommand, + pip_args: pipArgs, + pip_force_user: self.config_pipForceUser() + } + } + }; + self.settingsViewModel.saveData(data, function() { + self.configurationDialog.modal("hide"); + self._copyConfig(); + self.refreshRepository(); + }); + }; + + self._copyConfig = function() { + self.config_repositoryUrl(self.settingsViewModel.settings.plugins.pluginmanager.repository()); + self.config_repositoryTtl(self.settingsViewModel.settings.plugins.pluginmanager.repository_ttl()); + self.config_pipCommand(self.settingsViewModel.settings.plugins.pluginmanager.pip()); + self.config_pipAdditionalArgs(self.settingsViewModel.settings.plugins.pluginmanager.pip_args()); + self.config_pipForceUser(self.settingsViewModel.settings.plugins.pluginmanager.pip_force_user()); + }; + self.installed = function(data) { return _.includes(self.installedPlugins(), data.id); }; @@ -347,15 +550,59 @@ $(function() { }; self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, titleError, textError) { + var notification; + + var beforeClose = function(notification) { + self.notifications = _.without(self.notifications, notification); + }; + if (response.result) { if (response.needs_restart) { - new PNotify({ + var options = { title: titleSuccess, text: textRestart, + buttons: { + closer: false, + sticker: false + }, + callbacks: { + before_close: beforeClose + }, hide: false - }); + }; + + if (self.restartCommandSpec) { + options.confirm = { + confirm: true, + buttons: [{ + text: gettext("Restart now"), + click: function () { + showConfirmationDialog({ + message: gettext("This will restart your OctoPrint server."), + onproceed: function() { + OctoPrint.system.executeCommand("core", "restart") + .done(function() { + new PNotify({ + title: gettext("Restart in progress"), + text: gettext("The server is now being restarted in the background") + }) + }) + .fail(function() { + new PNotify({ + title: gettext("Something went wrong"), + text: gettext("Trying to restart the server produced an error, please check octoprint.log for details. You'll have to restart manually.") + }) + }); + } + }); + } + }] + } + } + + notification = PNotify.singleButtonNotify(options); } else if (response.needs_refresh) { - new PNotify({ + notification = PNotify.singleButtonNotify({ title: titleSuccess, text: textReload, confirm: { @@ -371,51 +618,35 @@ $(function() { closer: false, sticker: false }, + callbacks: { + before_close: beforeClose + }, hide: false }) } else { - new PNotify({ + notification = new PNotify({ title: titleSuccess, text: textSuccess, type: "success", + callbacks: { + before_close: beforeClose + }, hide: false }) } } else { - new PNotify({ + notification = new PNotify({ title: titleError, text: textError, type: "error", + callbacks: { + before_close: beforeClose + }, hide: false }); } - }; - self._postCommand = function (command, data, successCallback, failureCallback, alwaysCallback, timeout) { - var payload = _.extend(data, {command: command}); - - var params = { - url: API_BASEURL + "plugin/pluginmanager", - type: "POST", - dataType: "json", - data: JSON.stringify(payload), - contentType: "application/json; charset=UTF-8", - success: function(response) { - if (successCallback) successCallback(response); - }, - error: function() { - if (failureCallback) failureCallback(); - }, - complete: function() { - if (alwaysCallback) alwaysCallback(); - } - }; - - if (timeout != undefined) { - params.timeout = timeout; - } - - $.ajax(params); + self.notifications.push(notification); }; self._markWorking = function(title, line) { @@ -460,6 +691,16 @@ $(function() { self.onUserLoggedIn = function(user) { if (user.admin) { self.requestData(); + } else { + self.onUserLoggedOut(); + } + }; + + self.onUserLoggedOut = function() { + if (self.notifications) { + _.each(self.notifications, function(notification) { + notification.remove(); + }); } }; @@ -613,5 +854,9 @@ $(function() { } // view model class, parameters for constructor, container to bind to - ADDITIONAL_VIEWMODELS.push([PluginManagerViewModel, ["loginStateViewModel", "settingsViewModel", "printerStateViewModel"], "#settings_plugin_pluginmanager"]); + ADDITIONAL_VIEWMODELS.push([ + PluginManagerViewModel, + ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel"], + "#settings_plugin_pluginmanager" + ]); }); diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_about.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_about.jinja2 new file mode 100644 index 000000000..6c3cd1d95 --- /dev/null +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_about.jinja2 @@ -0,0 +1,18 @@ +

Plugin Licenses

+ +
    + {% for plugin in plugin_pluginmanager_thirdparty %} +
  • {{ plugin.name }}: {{ plugin.license }}
  • + {% endfor %} +
+ +{% if templates.plugin_pluginmanager_about_thirdparty.order %} +

Licenses of Plugin Dependencies

+ + {% for key in templates.plugin_pluginmanager_about_thirdparty.order %} + {% set heading, config = templates.plugin_pluginmanager_about_thirdparty.entries[key] %} +

{{ heading }}

+ + {% include config.template ignore missing %} + {% endfor %} +{% endif %} diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index 559817c06..ae1379762 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -4,7 +4,32 @@ {% endmacro %} +{% macro pluginmanager_nopip() %} +
{% 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 %}
+{% endmacro %} + +{% macro pluginmanager_sudopip() %} +
{% 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 %}
+{% endmacro %} + {{ pluginmanager_printing() }} +{{ pluginmanager_nopip() }} +{{ pluginmanager_sudopip() }} + +
+ +

{{ _('Installed Plugins') }}

@@ -18,7 +43,7 @@ -
()
+
()
 
{{ _('Homepage') }} @@ -47,6 +72,23 @@ +
+ +
+ + Installation directory: ("--user" flag: , sudo: )
+ Virtual environment:
+ Additional Arguments: +
+
+
+
+ + + 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. +

+{% endtrans %}
+
@@ -11,7 +29,7 @@ - :
+ :
{{ _('Installed:') }}
{{ _('Available:') }} @@ -44,7 +62,7 @@
- +
@@ -56,15 +74,15 @@