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/.versioneer-lookup b/.versioneer-lookup index b0de673da..86ee131b9 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -14,10 +14,10 @@ master HEAD \(detached.* -# maintenance is currently the branch for preparation of maintenance release 1.2.8 +# maintenance is currently the branch for preparation of maintenance release 1.2.9 # so are any fix/... branches -maintenance 1.2.8 6c622f7c4332b71c6ece59552ffc87c146155c84 pep440-dev -fix/.* 1.2.8 6c622f7c4332b71c6ece59552ffc87c146155c84 pep440-dev +maintenance 1.2.9 dedadbc9ac0305799e94ae279d3bca131629c4c5 pep440-dev +fix/.* 1.2.9 dedadbc9ac0305799e94ae279d3bca131629c4c5 pep440-dev # every other branch is a development branch and thus gets resolved to 1.3.0-dev for now .* 1.3.0 198d3450d94be1a2 pep440-dev diff --git a/AUTHORS.md b/AUTHORS.md index 44e77f485..55d2b49fb 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -54,7 +54,9 @@ date of first contribution): * [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) * [Kevin Murphy](https://github.com/kevingelion) + * [Richard Joyce](https://github.com/richjoyce) 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 a07b2b19c..82b15cae8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,74 @@ # OctoPrint Changelog +## 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 + for setup) +* More verbose output for Software Update plugin for logged in administrators. + Will now log the update commands and their output similar to the Plugin + 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.8 (2015-12-07) ### Notes for Upgraders diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 68c09bcb4..924bfa25e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -30,8 +30,12 @@ nothing but ticket management. - If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report) and *[use the provided template](#what-should-i-include-in-a-ticket)*. You do not need to do anything else with your ticket. -- If you want to post a **request** of any kind (feature request, documentation - request, ...), add `[Request]` to your issue's title (e.g. `[Request] Awesome new feature`). +- If you want to post a **feature request** or a **documentation request**, add `[Request]` + to your issue's title (e.g. `[Request] Awesome new feature`). A question on how to run/change/setup + something is **not** what qualifies as a request here, use the + [Mailinglist](https://groups.google.com/group/octoprint) or the + [Google+ Community](https://plus.google.com/communities/102771308349328485741) for + such support issues. - If you are a **developer** that wants to brainstorm a pull request or possible changes to the plugin system, add [Brainstorming] to your issue's title (e.g. `[Brainstorming] New plugin hook for doing some cool stuff`). 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 4d5a9ba0b..ccb813ce3 100644 --- a/README.md +++ b/README.md @@ -47,11 +47,11 @@ 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: +you already have Python 2.7, pip and virtualenv set up on your system: 1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git` 2. Change into the OctoPrint folder: `cd OctoPrint` -3. Create a user-owned virtual environment therein: `virtualenv --system-site-packages venv` +3. Create a user-owned virtual environment therein: `virtualenv venv` 4. Install OctoPrint *into that virtual environment*: `./venv/bin/python setup.py install` You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage) diff --git a/THIRDPARTYLICENSES.md b/THIRDPARTYLICENSES.md new file mode 100644 index 000000000..f181d5879 --- /dev/null +++ b/THIRDPARTYLICENSES.md @@ -0,0 +1,56 @@ +# 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 + + * [Awesome-Slugify](https://pypi.python.org/pypi/awesome-slugify): GPLv3 + * [Click](http://click.pocoo.org/): BSD + * [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/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index e182e6bb5..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 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/custom_controls.rst b/docs/features/custom_controls.rst index 983611fc8..a953617e9 100644 --- a/docs/features/custom_controls.rst +++ b/docs/features/custom_controls.rst @@ -65,7 +65,7 @@ a GCODE script including user input. children: - name: Get Position command: M114 - regex: "X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)" + regex: "X:([-+]?[0-9.]+) Y:([-+]?[0-9.]+) Z:([-+]?[0-9.]+) E:([-+]?[0-9.]+)" template: "Position: X={0}, Y={1}, Z={2}, E={3}" - name: Fun stuff children: diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst index d1b5fde80..86b7d8c22 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/modules/cli.rst b/docs/modules/cli.rst new file mode 100644 index 000000000..74f7458bb --- /dev/null +++ b/docs/modules/cli.rst @@ -0,0 +1,31 @@ +.. _sec-modules-cli: + +octoprint.cli +------------- + +.. automodule:: octoprint.cli + :members: + +.. _sec-modules-cli-dev: + +octoprint.cli.dev +----------------- + +.. automodule:: octoprint.cli.dev + :members: + +.. _sec-modules-cli-plugins: + +octoprint.cli.plugins +--------------------- + +.. automodule:: octoprint.cli.plugins + :members: + +.. _sec-modules-cli-server: + +octoprint.cli.server +-------------------- + +.. automodule:: octoprint.cli.server + :members: diff --git a/docs/modules/index.rst b/docs/modules/index.rst index db82bdde2..1cdb36a0a 100644 --- a/docs/modules/index.rst +++ b/docs/modules/index.rst @@ -7,6 +7,7 @@ Internal Modules .. toctree:: :maxdepth: 3 + cli.rst filemanager.rst plugin.rst printer.rst 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/gettingstarted.rst b/docs/plugins/gettingstarted.rst index 3c6c60d27..63c7ece70 100644 --- a/docs/plugins/gettingstarted.rst +++ b/docs/plugins/gettingstarted.rst @@ -10,6 +10,37 @@ Over the course of this little tutorial we'll build a full fledged, installable at some locations throughout OctoPrint and also offers some other basic functionality to give you an idea of what you can achieve with OctoPrint's plugin system. +First of all let use make sure that you have OctoPrint checked out and set up for development on your local +development environment:: + + $ cd ~/devel + $ git clone https://github.com/foosel/OctoPrint + [...] + $ cd OctoPrint + $ virtualenv venv + [...] + $ source venv/bin/activate + (venv) $ pip install -e[develop] + [...] + (venv) $ octoprint --help + Usage: octoprint [OPTIONS] COMMAND [ARGS]... + + [...] + +.. note:: + + You can also develop your plugin directly on your Raspberry Pi running OctoPi of course. In that + case please ignore the above instructions, you'll only need to activate the ``oprint`` + virtual environment: + + .. code-block:: none + + $ source ~/oprint/bin/activate + (oprint) $ octoprint --help + Usage: octoprint [OPTIONS] COMMAND [ARGS]... + + [...] + We'll start at the most basic form a plugin can take - just a couple of simple lines of Python code: .. code-block:: python @@ -24,14 +55,15 @@ We'll start at the most basic form a plugin can take - just a couple of simple l Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you something resembling these log entries upon server startup:: + (venv) $ octoprint serve 2015-01-27 11:14:35,124 - octoprint.server - INFO - Starting OctoPrint 1.2.0-dev-448-gd96e56e (devel branch) [...] 2015-01-27 11:14:35,124 - octoprint.plugin.core - INFO - Loading plugins from /home/pi/.octoprint/plugins, /home/pi/OctoPrint/src/octoprint/plugins and installed plugin packages... [...] 2015-01-27 11:14:36,135 - octoprint.plugin.core - INFO - 3 plugin(s) registered with the system: - | CuraEngine (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/cura - | Discovery (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/discovery + [...] | Hello World (1.0.0) = /home/pi/.octoprint/plugins/helloworld.py + [...] OctoPrint found that plugin in the folder and took a look into it. The name and the version it displays in that log entry it got from the ``__plugin_name__`` and ``__plugin_version__`` lines. It also read the description from @@ -101,31 +133,35 @@ or alternatively manually utilizing Python's standard package manager ``pip`` di So let's begin. We'll use the `cookiecutter `_ template for OctoPrint plugins here, so we'll first need to install that:: - $ pip install cookiecutter + (venv) $ pip install cookiecutter -Then we can use the ``cookiecutter`` command to generate a new OctoPrint plugin skeleton for us:: +Then we can use the ``octoprint dev plugin:new`` command [#f1]_ to generate a new OctoPrint plugin skeleton for us:: - $ cookiecutter gh:OctoPrint/cookiecutter-octoprint-plugin + (venv) $ cd ~/devel + (venv) $ octoprint dev plugin:new helloworld Cloning into 'cookiecutter-octoprint-plugin'... - remote: Counting objects: 70, done. - remote: Compressing objects: 100% (17/17), done. - emote: Total 70 (delta 0), reused 0 (delta 0), pack-reused 51 - Unpacking objects: 100% (70/70), done. - Checking connectivity... done. - plugin_identifier (default is "skeleton")? helloworld - plugin_package (default is "octoprint_helloworld")? - plugin_name (default is "OctoPrint-Helloworld")? - repo_name (default is "OctoPrint-Helloworld")? - full_name (default is "You")? Your Name - email (default is "you@example.com")? you@somewhere.net - github_username (default is "you")? yourGithubName - plugin_version (default is "0.1.0")? 1.0.0 - plugin_description (default is "TODO")? A quick "Hello World" example plugin for OctoPrint - plugin_license (default is "AGPLv3")? - plugin_homepage (default is "https://github.com/yourGithubName/OctoPrint-Helloworld")? - plugin_source (default is "https://github.com/yourGithubName/OctoPrint-Helloworld")? - plugin_installurl (default is "https://github.com/yourGithubName/OctoPrint-Helloworld/archive/master.zip")? - $ cd OctoPrint-HelloWorld + remote: Counting objects: 101, done. + remote: Total 101 (delta 0), reused 0 (delta 0), pack-reused 101 + Receiving objects: 100% (101/101), 53.69 KiB, done. + Resolving deltas: 100% (35/35), done. + plugin_package [octoprint_helloworld]: + plugin_name [OctoPrint-Helloworld]: + repo_name [OctoPrint-Helloworld]: + full_name [You]: Your Name + email [you@example.com]: you@somewhere.net + github_username [you]: yourGithubName + plugin_version [0.1.0]: 1.0.0 + plugin_description [TODO]: A quick "Hello World" example plugin for OCtoPrint + plugin_license [AGPLv3]: + plugin_homepage [https://github.com/yourGithubName/OctoPrint-Helloworld]: + plugin_source [https://github.com/yourGithubName/OctoPrint-Helloworld]: + plugin_installurl [https://github.com/yourGithubName/OctoPrint-Helloworld/archive/master.zip]: + (venv) $ cd OctoPrint-HelloWorld + +.. note:: + + If ``octoprint dev plugin:new`` isn't recognized as a command (and also doesn't show up in the output of + ``octoprint --help``, make sure you installed cookiecutter into the same python environment as OctoPrint. This will create a project structure in the ``OctoPrint-HelloWorld`` folder we just changed to that looks like this:: @@ -193,9 +229,11 @@ Now all that's left to do is to move our ``helloworld.py`` into the ``octoprint_ The plugin is now ready to be installed via ``python setup.py install``. However, since we are still working on our plugin, it makes more sense to use ``python setup.py develop`` for now -- this way the plugin becomes -discoverable by OctoPrint, however we don't have to reinstall it after any changes we will still do:: +discoverable by OctoPrint, however we don't have to reinstall it after any changes we will still do. We can have the +``octoprint dev plugin:install`` command do everything for us here, it will ensure to use the python binary belonging +to your OctoPrint installation:: - $ python setup.py develop + (venv) $ octoprint dev plugin:install running develop running egg_info creating OctoPrint_HelloWorld.egg-info @@ -209,9 +247,8 @@ Restart OctoPrint. Your plugin should still be properly discovered and the log l 2015-01-27 13:43:34,134 - octoprint.plugin.core - INFO - Loading plugins from /home/pi/.octoprint/plugins, /home/pi/OctoPrint/src/octoprint/plugins and installed plugin packages... [...] 2015-01-27 13:43:34,818 - octoprint.plugin.core - INFO - 3 plugin(s) registered with the system: - | CuraEngine (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/cura - | Discovery (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/discovery - | Hello World (1.0.0) = /home/pi/OctoPrint-HelloWorld/octoprint_helloworld + [...] + | Hello World (1.0.0) = /home/pi/devel/OctoPrint-HelloWorld/octoprint_helloworld [...] 2015-01-27 13:43:38,997 - octoprint.plugins.helloworld - INFO - Hello World! @@ -257,9 +294,9 @@ and ``__plugin_description__`` from ``__init__.py``: and restart OctoPrint:: 2015-01-27 13:46:33,786 - octoprint.plugin.core - INFO - 3 plugin(s) registered with the system: - | CuraEngine (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/cura - | Discovery (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/discovery - | OctoPrint-HelloWorld (1.0.0) = /home/pi/OctoPrint-HelloWorld/octoprint_helloworld + [...] + | OctoPrint-HelloWorld (1.0.0) = /home/pi/devel/OctoPrint-HelloWorld/octoprint_helloworld + [...] Our "Hello World" Plugin still gets detected fine, but it's now listed under the same name it's installed under, "OctoPrint-HelloWorld". That's a bit redundant and squashed, so we'll override that bit via ``__plugin_name__`` again: @@ -284,9 +321,9 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the Restart OctoPrint again:: 2015-01-27 13:48:54,122 - octoprint.plugin.core - INFO - 3 plugin(s) registered with the system: - | CuraEngine (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/cura - | Discovery (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/discovery + [...] | Hello World (1.0.0) = /home/pi/OctoPrint-HelloWorld/octoprint_helloworld + [...] Much better! You can override pretty much all of the metadata defined within ``setup.py`` from within your Plugin itself -- take a look at :ref:`the available control properties ` for all available @@ -295,7 +332,7 @@ overrides. Following the README of the `Plugin Skeleton `_ you could now already publish your plugin on Github and it would be directly installable by others using pip:: - pip install https://github.com/yourGithubName/OctoPrint-HelloWorld/archive/master.zip + (venv) $ pip install https://github.com/yourGithubName/OctoPrint-HelloWorld/archive/master.zip But let's add some more features instead. @@ -857,7 +894,7 @@ generated CSS files (and compiles them on the fly in your browser using `lessjs which makes development so much easier. Let's try that, so you know how it works for future bigger projects. Add another folder to our ``static`` folder called ``less`` and within that create a file ``helloworld.less``. Put -into that the same content as into our CSS file. Compile that LESS file to CSS [#f1]_, overwriting our old ``helloworld.css`` +into that the same content as into our CSS file. Compile that LESS file to CSS [#f2]_, overwriting our old ``helloworld.css`` in the process. The folder structure of our plugin should now look like this:: octoprint_helloworld/ @@ -1038,6 +1075,12 @@ looking for examples. .. rubric:: Footnotes -.. [#f1] Refer to the `LESS documentation `_ on how to do that. If you are developing +.. [#f1] Instead of the ``octoprint dev plugin:new`` you could also have manually called cookiecutter with the + template's repository URL shortcut: ``cookiecutter gh:OctoPrint/cookiecutter-octoprint-plugin``. The + ``devel:newplugin`` command already does this for you, makes sure cookiecutter always uses a fresh + checkout without prompting you for it and also allows to pre-specify a bunch of settings (like the + plugin's identifier) directly from the command line. Take a look at ``octoprint dev plugin:new --help`` + for the usage details. +.. [#f2] Refer to the `LESS documentation `_ on how to do that. If you are developing your plugin under Windows you might also want to give `WinLESS `_ a look which will run in the background and keep your CSS files up to date with your various project's LESS files automatically. diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 36a6e2c36..8cd32abfe 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -37,6 +37,143 @@ octoprint.accesscontrol.appkey :return: A list of 3-tuples as described above :rtype: list +.. _sec-plugins-hook-cli-commands: + +octoprint.cli.commands +---------------------- + +.. py:function:: hook(cli_group, pass_octoprint_ctx, *args, **kwargs) + + By providing a handler for this hook plugins may register commands on OctoPrint's command line interface (CLI). + + Handlers are expected to return a list of callables annotated as `Click commands `_ to register with the + CLI. + + The custom ``MultiCommand`` instance :class:`~octoprint.cli.plugins.OctoPrintPluginCommands` is provided + as parameter. Via that object handlers may access the *global* :class:`~octoprint.settings.Settings` + and the :class:`~octoprint.plugin.core.PluginManager` instance as ``cli_group.settings`` and ``cli_group.plugin_manager``. + + **Example:** + + Registers two new commands, ``custom_cli_command:greet`` and ``custom_cli_command:random`` with + OctoPrint: + + .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_cli_command.py + :linenos: + :tab-width: 4 + :caption: `custom_cli_command.py `_ + + Calling ``octoprint --help`` shows the two new commands: + + .. code-block:: none + + $ octoprint --help + Usage: octoprint [OPTIONS] COMMAND [ARGS]... + + Options: + -b, --basedir PATH Specify the basedir to use for uploads, timelapses etc. + -c, --config PATH Specify the config file to use. + -v, --verbose Increase logging verbosity + --version Show the version and exit. + --help Show this message and exit. + + Commands: + daemon Starts, stops or restarts in daemon mode. + dev:plugin Helpers for plugin developers + plugin:custom_cli_command custom_cli_command commands + serve Starts the OctoPrint server. + + $ octoprint plugin:custom_cli_command --help + Usage: octoprint plugin:custom_cli_command [OPTIONS] COMMAND [ARGS]... + + custom_cli_command commands + + Options: + --help Show this message and exit. + + Commands: + greet Greet someone by name, the greeting can be... + random Greet someone by name with a random greeting. + + Each also has an individual help output: + + .. code-block:: none + + $ octoprint plugin:custom_cli_command greet --help + Usage: octoprint plugin:custom_cli_command greet [OPTIONS] [NAME] + + Greet someone by name, the greeting can be customized. + + Options: + -g, --greeting TEXT The greeting to use + --help Show this message and exit. + + $ octoprint plugin:custom_cli_command random --help + Usage: octoprint plugin:custom_cli_command random [OPTIONS] [NAME] + + Greet someone by name with a random greeting. + + Options: + --help Show this message and exit. + + And of course they work too: + + .. code-block:: none + + $ octoprint plugin:custom_cli_command greet + Hello World! + + $ octoprint plugin:custom_cli_command greet --greeting "Good morning" + Good morning World! + + $ octoprint plugin:custom_cli_command random stranger + Hola stranger! + + .. note:: + + If your hook handler is an instance method of a plugin mixin implementation, be aware that the hook will be + called without OctoPrint initializing your implementation instance. That means that **none** of the + :ref:`injected properties ` will be available and also the + :method:`~octoprint.plugin.Plugin.initialize` method will not be called. + + Your hook handler will have access to the plugin manager as ``cli_group.plugin_manager`` and to the + *global* settings as ``cli_group.settings``. You can have your handler turn the latter into a + :class:`~octoprint.plugin.PluginSettings` instance by using :func:`octoprint.plugin.plugin_settings_from_settings_plugin` + if your plugin's implementation implements the :class:`~octoprint.plugin.SettingsPlugin` mixin and inject + that and the plugin manager instance yourself: + + .. code-block:: python + + import octoprint.plugin + + class MyPlugin(octoprint.plugin.SettingsPlugin): + + def get_cli_commands(self, cli_group, pass_octoprint_ctx, *args, **kwargs): + import logging + + settings = cli_group._settings + plugin_settings = octoprint.plugin.plugin_settings_for_settings_plugin("myplugin", self) + if plugin_settings is None: + # this can happen if anything goes wrong with preparing the PluginSettings instance + return dict() + + self._settings = plugin_settings + self._plugin_manager = cli_group._plugin_manager + self._logger = logging.getLogger(__name__) + + ### command definition starts here + + # ... + + + No other platform components will be available - the CLI runs outside of a running, fully initialized + OctoPrint server context, so there is absolutely no way to access a printer connection, the event bus or + anything else like that. The only things available are the settings and the plugin manager. + + :return: A list of `Click commands or groups `_ to provide on + OctoPrint's CLI. + :rtype: list + .. _sec-plugins-hook-comm-protocol-action: octoprint.comm.protocol.action @@ -159,6 +296,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.default b/scripts/octoprint.default index 2d9a46d7f..1f58092a6 100644 --- a/scripts/octoprint.default +++ b/scripts/octoprint.default @@ -3,11 +3,17 @@ # The init.d script will only run if this variable non-empty. OCTOPRINT_USER=pi +# base directory to use +#BASEDIR=/home/pi/.octoprint + +# configuration file to use +#CONFIGFILE=/home/pi/.octoprint/config.yaml + # On what port to run daemon, default is 5000 PORT=5000 -# Path to the OctoPrint executable, use this to override the default setting "/usr/bin/octoprint" -#DAEMON=/path/to/octoprint/executable +# Path to the OctoPrint executable, you need to set this to match your installation! +#DAEMON=/home/pi/OctoPrint/venv/bin/octoprint # What arguments to pass to octoprint, usually no need to touch this DAEMON_ARGS="--port=$PORT" diff --git a/scripts/octoprint.init b/scripts/octoprint.init index b0916fae9..97601ebb4 100644 --- a/scripts/octoprint.init +++ b/scripts/octoprint.init @@ -16,17 +16,23 @@ # Author: Sami Olmari PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin -DESC="Octoprint Daemon" -NAME="Octoprint" -DAEMON=/usr/local/bin/octoprint -PIDFILE=/var/run/$NAME.pid +DESC="OctoPrint Daemon" +NAME="OctoPrint" PKGNAME=octoprint +PIDFILE=/var/run/$PKGNAME.pid SCRIPTNAME=/etc/init.d/$PKGNAME # Read configuration variable file if it is present [ -r /etc/default/$PKGNAME ] && . /etc/default/$PKGNAME -# Exit if the octoprint is not installed +# Exit if the DAEMON is not set +if [ -z "$DAEMON" ] +then + log_warning_msg "Not starting $PKGNAME, DAEMON not set in /etc/default/$PKGNAME." + exit 0 +fi + +# Exit if the DAEMON is not installed [ -x "$DAEMON" ] || exit 0 # Load the VERBOSE setting and other rcS variables @@ -48,6 +54,17 @@ then exit 0 fi +COMMAND_ARGS= +if [ -z "$BASEDIR" ] +then + COMMAND_ARGS="--basedir $BASEDIR $COMMAND_ARGS" +fi + +if [ -z "$CONFIGFILE" ] +then + COMMAND_ARGS="--config $CONFIGFILE $COMMAND_ARGS" +fi + # # Function to verify if a pid is alive # @@ -74,7 +91,7 @@ do_start() if [ $RETVAL != 0 ]; then start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile \ --exec $DAEMON --chuid $OCTOPRINT_USER --user $OCTOPRINT_USER --umask $UMASK --nicelevel=$NICELEVEL \ - -- $DAEMON_ARGS + -- $COMMAND_ARGS serve $DAEMON_ARGS RETVAL="$?" fi } @@ -116,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 @@ -135,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.py b/setup.py index 86b7837f9..837df8743 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 @@ -14,25 +15,28 @@ import octoprint_setuptools # Requirements for our application INSTALL_REQUIRES = [ "flask>=0.9,<0.11", - "werkzeug==0.8.3", - "tornado==4.0.1", - "sockjs-tornado==1.0.1", - "PyYAML==3.10", - "Flask-Login==0.2.2", - "Flask-Principal==0.3.5", - "Flask-Babel==0.9", - "Flask-Assets==0.10", - "pyserial==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" + "werkzeug>=0.8.3,<0.9", + "tornado>=4.0.2,<4.1", + "sockjs-tornado>=1.0.2,<1.1", + "PyYAML>=3.10,<3.11", + "Flask-Login>=0.2.2,<0.3", + "Flask-Principal>=0.3.5,<0.4", + "Flask-Babel>=0.9,<0.10", + "Flask-Assets>=0.10,<0.11", + "Flask-Markdown>=0.3,<0.4", + "pyserial>=2.7,<2.8", + "netaddr>=0.7.17,<0.8", + "watchdog>=0.8.3,<0.9", + "sarge>=0.1.4,<0.2", + "netifaces>=0.10,<0.11", + "pylru>=1.0.9,<1.1", + "rsa>=3.2,<3.3", + "pkginfo>=1.2.1,<1.3", + "requests>=2.7,<2.8", + "semantic_version>=2.4.2,<2.5", + "psutil>=3.2.1,<3.3", + "Click>=5.1,<5.2", + "awesome-slugify>=1.6.5,<1.7" ] # Additional requirements for optional install options @@ -40,12 +44,12 @@ EXTRA_REQUIRES = dict( # Dependencies for developing OctoPrint develop=[ # Testing dependencies - "mock>=1.0.1", - "nose>=1.3.0", + "mock>=1.0.1,<1.1", + "nose>=1.3.0,<1.4", "ddt", # Documentation dependencies - "sphinx>=1.3", + "sphinx>=1.3,<1.4", "sphinxcontrib-httpdomain", "sphinx_rtd_theme", @@ -68,6 +72,32 @@ 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() @@ -80,6 +110,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 @@ -130,10 +168,12 @@ 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 diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 67baa4f74..eb4776de1 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -1,84 +1,215 @@ -#!/usr/bin/env python +#!/usr/bin/env python2 +# coding=utf-8 +from __future__ import absolute_import, print_function + import sys -from octoprint.daemon import Daemon -from octoprint.server import Server +import logging #~~ version from ._version import get_versions -__version__ = get_versions()['version'] +versions = get_versions() + +__version__ = versions['version'] +__branch__ = versions.get('branch', None) +__display_version__ = "{} ({} branch)".format(__version__, __branch__) if __branch__ else __version__ +__revision__ = versions.get('full-revisionid', versions.get('full', None)) + +del versions del get_versions -#~~ main class +#~~ sane logging defaults -class Main(Daemon): - def __init__(self, pidfile, configfile, basedir, host, port, debug, allowRoot, logConf): - Daemon.__init__(self, pidfile) +logging.basicConfig() - self._configfile = configfile - self._basedir = basedir - self._host = host - self._port = port - self._debug = debug - self._allowRoot = allowRoot - self._logConf = logConf +#~~ try to ensure a sound SSL environment - def run(self): - octoprint = Server(self._configfile, self._basedir, self._host, self._port, self._debug, self._allowRoot) - octoprint.run() +urllib3_ssl = True +"""Whether requests/urllib3 and urllib3 (if installed) should be able to establish + a sound SSL environment or not.""" + +version_info = sys.version_info +if version_info.major == 2 and version_info.minor <= 7 and version_info.micro < 9: + try: + # make sure our requests version of urllib3 is properly patched (if possible) + import requests.packages.urllib3.contrib.pyopenssl + requests.packages.urllib3.contrib.pyopenssl.inject_into_urllib3() + except ImportError: + urllib3_ssl = False + + try: + import urllib3 + + # only proceed if urllib3 is even installed on its own + try: + # urllib3 is there, let's patch that too + import urllib3.contrib.pyopenssl + urllib3.contrib.pyopenssl.inject_into_urllib3() + except ImportError: + urllib3_ssl = False + except ImportError: + pass + +del version_info + +#~~ init methods to bring up platform + +def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, + logging_config=None, debug=False, verbosity=0, uncaught_logger=None, + uncaught_handler=None, after_settings=None, after_logging=None): + settings = init_settings(basedir, configfile) + if callable(after_settings): + after_settings(settings) + + logger = init_logging(settings, + use_logging_file=use_logging_file, + logging_file=logging_file, + default_config=logging_config, + debug=debug, + verbosity=verbosity, + uncaught_logger=uncaught_logger, + uncaught_handler=uncaught_handler) + if callable(after_logging): + after_logging(logger) + + plugin_manager = init_pluginsystem(settings) + return settings, logger, plugin_manager + + +def init_settings(basedir, configfile): + """Inits the settings instance based on basedir and configfile to use.""" + + from octoprint.settings import settings + return settings(init=True, basedir=basedir, configfile=configfile) + + +def init_logging(settings, use_logging_file=True, logging_file=None, default_config=None, debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None): + """Sets up logging.""" + + import os + + from octoprint.util import dict_merge + + # default logging configuration + if default_config is None: + default_config = { + "version": 1, + "formatters": { + "simple": { + "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + } + }, + "handlers": { + "console": { + "class": "logging.StreamHandler", + "level": "DEBUG", + "formatter": "simple", + "stream": "ext://sys.stdout" + }, + "file": { + "class": "logging.handlers.TimedRotatingFileHandler", + "level": "DEBUG", + "formatter": "simple", + "when": "D", + "backupCount": "1", + "filename": os.path.join(settings.getBaseFolder("logs"), "octoprint.log") + }, + "serialFile": { + "class": "logging.handlers.RotatingFileHandler", + "level": "DEBUG", + "formatter": "simple", + "maxBytes": 2 * 1024 * 1024, # let's limit the serial log to 2MB in size + "filename": os.path.join(settings.getBaseFolder("logs"), "serial.log") + } + }, + "loggers": { + "SERIAL": { + "level": "CRITICAL", + "handlers": ["serialFile"], + "propagate": False + }, + "octoprint": { + "level": "INFO" + }, + "octoprint.util": { + "level": "INFO" + }, + "octoprint.plugins": { + "level": "INFO" + } + }, + "root": { + "level": "WARN", + "handlers": ["console", "file"] + } + } + + if debug or verbosity > 0: + default_config["loggers"]["octoprint"]["level"] = "DEBUG" + default_config["root"]["level"] = "INFO" + if verbosity > 1: + default_config["loggers"]["octoprint.plugins"]["level"] = "DEBUG" + if verbosity > 2: + default_config["root"]["level"] = "DEBUG" + + if use_logging_file: + # further logging configuration from file... + if logging_file is None: + logging_file = os.path.join(settings.getBaseFolder("base"), "logging.yaml") + + config_from_file = {} + if os.path.exists(logging_file) and os.path.isfile(logging_file): + import yaml + with open(logging_file, "r") as f: + config_from_file = yaml.safe_load(f) + + # we merge that with the default config + config = dict_merge(default_config, config_from_file) + else: + config = default_config + + # configure logging globally + import logging.config + logging.config.dictConfig(config) + + # make sure we log any warnings + logging.captureWarnings(True) + + import warnings + + categories = (DeprecationWarning, PendingDeprecationWarning) + if verbosity > 2: + warnings.simplefilter("always") + elif debug or verbosity > 0: + for category in categories: + warnings.simplefilter("always", category=category) + + # make sure we also log any uncaught exceptions + if uncaught_logger is None: + logger = logging.getLogger(__name__) + else: + logger = logging.getLogger(uncaught_logger) + + if uncaught_handler is None: + def exception_logger(exc_type, exc_value, exc_tb): + logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb)) + uncaught_handler = exception_logger + sys.excepthook = uncaught_handler + + return logger + + +def init_pluginsystem(settings): + """Initializes the plugin manager based on the settings.""" + from octoprint.plugin import plugin_manager + return plugin_manager(init=True, settings=settings) + +#~~ server main method def main(): - import argparse + from octoprint.cli import octo + octo(prog_name="octoprint", auto_envvar_prefix="OCTOPRINT") - parser = argparse.ArgumentParser(prog="run") - - parser.add_argument("-v", "--version", action="store_true", dest="version", - help="Output OctoPrint's version and exit") - - parser.add_argument("-d", "--debug", action="store_true", dest="debug", - help="Enable debug mode") - - parser.add_argument("--host", action="store", type=str, dest="host", - help="Specify the host on which to bind the server") - parser.add_argument("--port", action="store", type=int, dest="port", - help="Specify the port on which to bind the server") - - parser.add_argument("-c", "--config", action="store", dest="config", - help="Specify the config file to use. OctoPrint needs to have write access for the settings dialog to work. Defaults to ~/.octoprint/config.yaml") - parser.add_argument("-b", "--basedir", action="store", dest="basedir", - help="Specify the basedir to use for uploads, timelapses etc. OctoPrint needs to have write access. Defaults to ~/.octoprint") - parser.add_argument("--logging", action="store", dest="logConf", - help="Specify the config file to use for configuring logging. Defaults to ~/.octoprint/logging.yaml") - - parser.add_argument("--daemon", action="store", type=str, choices=["start", "stop", "restart"], - help="Daemonize/control daemonized OctoPrint instance (only supported under Linux right now)") - parser.add_argument("--pid", action="store", type=str, dest="pidfile", default="/tmp/octoprint.pid", - help="Pidfile to use for daemonizing, defaults to /tmp/octoprint.pid") - - parser.add_argument("--iknowwhatimdoing", action="store_true", dest="allowRoot", - help="Allow OctoPrint to run as user root") - - args = parser.parse_args() - - if args.version: - print "OctoPrint version %s" % __version__ - sys.exit(0) - - if args.daemon: - if sys.platform == "darwin" or sys.platform == "win32": - print >> sys.stderr, "Sorry, daemon mode is only supported under Linux right now" - sys.exit(2) - - daemon = Main(args.pidfile, args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot, args.logConf) - if "start" == args.daemon: - daemon.start() - elif "stop" == args.daemon: - daemon.stop() - elif "restart" == args.daemon: - daemon.restart() - else: - octoprint = Server(args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot, args.logConf) - octoprint.run() if __name__ == "__main__": main() diff --git a/src/octoprint/_version.py b/src/octoprint/_version.py index 60161f3c8..f40ef1bc0 100644 --- a/src/octoprint/_version.py +++ b/src/octoprint/_version.py @@ -40,11 +40,11 @@ def get_config(): # _version.py cfg = VersioneerConfig() cfg.VCS = "git" - cfg.style = "pep440" + cfg.style = "pep440-post" cfg.tag_prefix = "" cfg.parentdir_prefix = "" cfg.versionfile_source = "src/octoprint/_version.py" - cfg.lookupfile = None + cfg.lookupfile = ".versioneer-lookup" cfg.verbose = False return cfg diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py new file mode 100644 index 000000000..113f737b7 --- /dev/null +++ b/src/octoprint/cli/__init__.py @@ -0,0 +1,151 @@ +# coding=utf-8 +from __future__ import absolute_import + +__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 click +import octoprint + +#~~ click context + +class OctoPrintContext(object): + """Custom context wrapping the standard options.""" + + def __init__(self, configfile=None, basedir=None, verbosity=0): + self.configfile = configfile + self.basedir = basedir + self.verbosity = verbosity + +pass_octoprint_ctx = click.make_pass_decorator(OctoPrintContext, ensure=True) +"""Decorator to pass in the :class:`OctoPrintContext` instance.""" + +#~~ Custom click option to hide from help + +class HiddenOption(click.Option): + """Custom option sub class with empty help.""" + def get_help_record(self, ctx): + pass + +def hidden_option(*param_decls, **attrs): + """Attaches a hidden option to the command. All positional arguments are + passed as parameter declarations to :class:`Option`; all keyword + arguments are forwarded unchanged. This is equivalent to creating an + :class:`Option` instance manually and attaching it to the + :attr:`Command.params` list. + """ + + import inspect + from click.decorators import _param_memo + + def decorator(f): + if 'help' in attrs: + attrs['help'] = inspect.cleandoc(attrs['help']) + _param_memo(f, HiddenOption(param_decls, **attrs)) + return f + return decorator + +#~~ helper for settings context options + +def set_ctx_obj_option(ctx, param, value): + """Helper for setting eager options on the context.""" + if ctx.obj is None: + ctx.obj = OctoPrintContext() + + if hasattr(ctx.obj, param.name): + setattr(ctx.obj, param.name, value) + +#~~ helper for setting a lot of bulk options + +def bulk_options(options): + """ + Utility decorator to decorate a function with a list of click decorators. + + The provided list of ``options`` will be reversed to ensure correct + processing order (inverse from what would be intuitive). + """ + + def decorator(f): + options.reverse() + for option in options: + option(f) + return f + return decorator + +#~~ helper for setting --basedir, --config and --verbose options + +def standard_options(hidden=False): + """ + Decorator to add the standard options shared among all "octoprint" commands. + + Adds the options ``--basedir``, ``--config`` and ``--verbose``. If ``hidden`` + is set to ``True``, the options will be available on the command but not + listed in its help page. + """ + + factory = click.option + if hidden: + factory = hidden_option + + options = [ + factory("--basedir", "-b", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False, + help="Specify the basedir to use for uploads, timelapses etc."), + factory("--config", "-c", "configfile", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False, + help="Specify the config file to use."), + factory("--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False, + help="Increase logging verbosity"), + ] + + return bulk_options(options) + +#~~ helper for settings legacy options we still have to support on "octoprint" + +legacy_options = bulk_options([ + hidden_option("--host", type=click.STRING), + hidden_option("--port", type=click.INT), + hidden_option("--logging", type=click.Path()), + hidden_option("--debug", "-d", is_flag=True), + hidden_option("--daemon", type=click.Choice(["start", "stop", "restart"])), + hidden_option("--pid", type=click.Path(), default="/tmp/octoprint.pid"), + hidden_option("--iknowwhatimdoing", "allow_root", is_flag=True), +]) +"""Legacy options available directly on the "octoprint" command in earlier versions. + Kept available for reasons of backwards compatibility, but hidden from the + generated help pages.""" + +#~~ "octoprint" command, merges server_commands and plugin_commands groups + +from .server import server_commands +from .plugins import plugin_commands +from .dev import dev_commands +from .client import client_commands + +@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection, + sources=[server_commands, plugin_commands, dev_commands, client_commands]) +@standard_options() +@legacy_options +@click.version_option(version=octoprint.__version__) +@click.pass_context +def octo(ctx, debug, host, port, logging, daemon, pid, allow_root): + + if ctx.invoked_subcommand is None: + # We have to support calling the octoprint command without any + # sub commands to remain backwards compatible. + # + # But better print a message to inform people that they should + # use the sub commands instead. + + if daemon: + click.echo("Daemon operation via \"octoprint --daemon " + "start|stop|restart\" is deprecated, please use " + "\"octoprint daemon start|stop|restart\" from now on") + + from octoprint.cli.server import daemon_command + ctx.invoke(daemon_command, debug=debug, pid=pid, daemon=daemon, allow_root=allow_root) + else: + click.echo("Starting the server via \"octoprint\" is deprecated, " + "please use \"octoprint serve\" from now on.") + + from octoprint.cli.server import serve_command + ctx.invoke(serve_command, debug=debug, host=host, port=port, logging=logging, allow_root=allow_root) diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py new file mode 100644 index 000000000..9615ddee9 --- /dev/null +++ b/src/octoprint/cli/client.py @@ -0,0 +1,176 @@ +# coding=utf-8 +from __future__ import absolute_import + +__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 click +import json + +import octoprint_client + +from octoprint.cli import pass_octoprint_ctx, bulk_options, standard_options +from octoprint import init_settings + + +class JsonStringParamType(click.ParamType): + name = "json" + + def convert(self, value, param, ctx): + try: + return json.loads(value) + except: + self.fail("%s is not a valid json string" % value, param, ctx) + + +@click.group() +def client_commands(): + pass + + +@client_commands.group("client", context_settings=dict(ignore_unknown_options=True)) +@click.option("--host", "-h", type=click.STRING) +@click.option("--port", "-p", type=click.INT) +@click.option("--httpuser", type=click.STRING) +@click.option("--httppass", type=click.STRING) +@click.option("--https", is_flag=True) +@click.option("--prefix", type=click.STRING) +@pass_octoprint_ctx +def client(obj, host, port, httpuser, httppass, https, prefix): + """Basic API client.""" + obj.settings = init_settings(obj.basedir, obj.configfile) + octoprint_client.init_client(obj.settings, https=https, httpuser=httpuser, httppass=httppass, host=host, port=port, prefix=prefix) + + +def log_response(response, status_code=True, body=True, headers=False): + if status_code: + click.echo("Status Code: {}".format(response.status_code)) + if headers: + for header, value in response.headers.items(): + click.echo("{}: {}".format(header, value)) + click.echo() + if body: + click.echo(response.text) + + +@client.command("get") +@click.argument("path") +def get(path): + """Performs a GET request against the specified server path.""" + r = octoprint_client.get(path) + log_response(r) + + +@client.command("post_json") +@click.argument("path") +@click.argument("data", type=JsonStringParamType()) +def post_json(path, data): + """POSTs JSON data to the specified server path.""" + r = octoprint_client.post_json(path, data) + log_response(r) + + +@client.command("patch_json") +@click.argument("path") +@click.argument("data", type=JsonStringParamType()) +def patch_json(path, data): + """PATCHes JSON data to the specified server path.""" + r = octoprint_client.patch(path, data, encoding="json") + log_response(r) + + +@client.command("post_from_file") +@click.argument("path") +@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True)) +@click.option("--json", is_flag=True) +@click.option("--yaml", is_flag=True) +def post_from_file(path, file_path, json_flag, yaml_flag): + """POSTs JSON data to the specified server path.""" + if json_flag or yaml_flag: + if json_flag: + with open(file_path, "rb") as fp: + data = json.load(fp) + else: + import yaml + with open(file_path, "rb") as fp: + data = yaml.safe_load(fp) + + r = octoprint_client.post_json(path, data) + else: + with open(file_path, "rb") as fp: + data = fp.read() + + r = octoprint_client.post(path, data) + + log_response(r) + + +@client.command("command") +@click.argument("path") +@click.argument("command") +@click.option("--str", "-s", "str_params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode])) +@click.option("--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int])) +@click.option("--float", "-f", "float_params", multiple=True, nargs=2, type=click.Tuple([unicode, float])) +@click.option("--bool", "-b", "bool_params", multiple=True, nargs=2, type=click.Tuple([unicode, bool])) +def command(path, command, str_params, int_params, float_params, bool_params): + """Sends a JSON command to the specified server path.""" + data = dict() + params = str_params + int_params + float_params + bool_params + for param in params: + data[param[0]] = param[1] + r = octoprint_client.post_command(path, command, additional=data) + log_response(r, body=False) + + +@client.command("upload") +@click.argument("path") +@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True)) +@click.option("--parameter", "-P", "params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode])) +@click.option("--file-name", type=click.STRING) +@click.option("--content-type", type=click.STRING) +def upload(path, file_path, params, file_name, content_type): + """Uploads the specified file to the specified server path.""" + data = dict() + for param in params: + data[param[0]] = param[1] + + r = octoprint_client.upload(path, file_path, additional=data, file_name=file_name, content_type=content_type) + log_response(r) + + +@client.command("delete") +@click.argument("path") +def delete(path): + """Sends a DELETE request to the specified server path.""" + r = octoprint_client.delete(path) + log_response(r) + + +@client.command("listen") +def listen(): + def on_connect(ws): + click.echo(">>> Connected!") + + def on_close(ws): + click.echo(">>> Connection closed!") + + def on_error(ws, error): + click.echo("!!! Error: {}".format(error)) + + def on_heartbeat(ws): + click.echo("<3") + + def on_message(ws, message_type, message_payload): + click.echo("Message: {}, Payload: {}".format(message_type, json.dumps(message_payload))) + + socket = octoprint_client.connect_socket(on_connect=on_connect, + on_close=on_close, + on_error=on_error, + on_heartbeat=on_heartbeat, + on_message=on_message) + + click.echo(">>> Waiting for client to exit") + try: + socket.wait() + finally: + click.echo(">>> Goodbye...") diff --git a/src/octoprint/cli/dev.py b/src/octoprint/cli/dev.py new file mode 100644 index 000000000..3f7269fcf --- /dev/null +++ b/src/octoprint/cli/dev.py @@ -0,0 +1,235 @@ +# 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 click + +class OctoPrintDevelCommands(click.MultiCommand): + """ + Custom `click.MultiCommand `_ + implementation that provides commands relevant for (plugin) development + based on availability of development dependencies. + """ + + sep = ":" + groups = ("plugin",) + + def __init__(self, *args, **kwargs): + click.MultiCommand.__init__(self, *args, **kwargs) + + from octoprint.util.commandline import CommandlineCaller + from functools import partial + + def log_util(f): + def log(*lines): + for line in lines: + f(line) + return log + + self.command_caller = CommandlineCaller() + self.command_caller.on_log_call = log_util(lambda x: click.echo(">> {}".format(x))) + self.command_caller.on_log_stdout = log_util(click.echo) + self.command_caller.on_log_stderr = log_util(partial(click.echo, err=True)) + + def _get_prefix_methods(self, method_prefix): + for name in [x for x in dir(self) if x.startswith(method_prefix)]: + method = getattr(self, name) + yield method + + def _get_commands_from_prefix_methods(self, method_prefix): + for method in self._get_prefix_methods(method_prefix): + result = method() + if result is not None and isinstance(result, click.Command): + yield result + + def _get_commands(self): + result = dict() + for group in self.groups: + for command in self._get_commands_from_prefix_methods("{}_".format(group)): + result[group + self.sep + command.name] = command + return result + + def list_commands(self, ctx): + result = [name for name in self._get_commands()] + result.sort() + return result + + def get_command(self, ctx, cmd_name): + commands = self._get_commands() + return commands.get(cmd_name, None) + + def plugin_new(self): + try: + import cookiecutter.main + except ImportError: + return None + + import contextlib + + @contextlib.contextmanager + def custom_cookiecutter_config(config): + """ + Allows overriding cookiecutter's user config with a custom dict + with fallback to the original data. + """ + from octoprint.util import fallback_dict + + original_get_user_config = cookiecutter.main.get_user_config + try: + def f(*args, **kwargs): + original_config = original_get_user_config(*args, **kwargs) + return fallback_dict(config, original_config) + cookiecutter.main.get_user_config = f + yield + finally: + cookiecutter.main.get_user_config = original_get_user_config + + @contextlib.contextmanager + def custom_cookiecutter_prompt(options): + """ + Custom cookiecutter prompter for the template config. + + If a setting is available in the provided options (read from the CLI) + that will be used, otherwise the user will be prompted for a value + via click. + """ + original_prompt_for_config = cookiecutter.main.prompt_for_config + + def custom_prompt_for_config(context, no_input=False): + import cookiecutter.prompt + + cookiecutter_dict = {} + env = cookiecutter.prompt.Environment() + + for key, raw in context['cookiecutter'].items(): + if key in options: + val = options[key] + else: + raw = raw if isinstance(raw, basestring) else str(raw) + val = env.from_string(raw).render(cookiecutter=cookiecutter_dict) + + if not no_input: + val = click.prompt(key, default=val) + + cookiecutter_dict[key] = val + return cookiecutter_dict + + try: + cookiecutter.main.prompt_for_config = custom_prompt_for_config + yield + finally: + cookiecutter.main.prompt_for_config = original_prompt_for_config + + @click.command("new") + @click.option("--name", "-n", help="The name of the plugin") + @click.option("--package", "-p", help="The plugin package") + @click.option("--author", "-a", help="The plugin author's name") + @click.option("--email", "-e", help="The plugin author's mail address") + @click.option("--license", "-l", help="The plugin's license") + @click.option("--description", "-d", help="The plugin's description") + @click.option("--homepage", help="The plugin's homepage URL") + @click.option("--source", "-s", help="The URL to the plugin's source") + @click.option("--installurl", "-i", help="The plugin's install URL") + @click.argument("identifier", required=False) + def command(name, package, author, email, description, license, homepage, source, installurl, identifier): + """Creates a new plugin based on the OctoPrint Plugin cookiecutter template.""" + from octoprint.util import tempdir + + # deleting a git checkout folder might run into access errors due + # to write-protected sub folders, so we use a custom onerror handler + # that tries to fix such permissions + def onerror(func, path, exc_info): + """Originally from http://stackoverflow.com/a/2656405/2028598""" + import stat + import os + + if not os.access(path, os.W_OK): + os.chmod(path, stat.S_IWUSR) + func(path) + else: + raise + + with tempdir(onerror=onerror) as path: + custom = dict(cookiecutters_dir=path) + with custom_cookiecutter_config(custom): + raw_options = dict( + plugin_identifier=identifier, + plugin_package=package, + plugin_name=name, + full_name=author, + email=email, + plugin_description=description, + plugin_license=license, + plugin_homepage=homepage, + plugin_source=source, + plugin_installurl=installurl + ) + options = dict((k, v) for k, v in raw_options.items() if v is not None) + + with custom_cookiecutter_prompt(options): + cookiecutter.main.cookiecutter("gh:OctoPrint/cookiecutter-octoprint-plugin") + + return command + + def plugin_install(self): + @click.command("install") + @click.option("--path", help="Path of the local plugin development folder to install") + def command(path): + """ + Installs the local plugin in development mode. + + Note: This can NOT be used to install plugins from remote locations + such as the plugin repository! It is strictly for local development + of plugins, to ensure the plugin is installed (editable) into the + same python environment that OctoPrint is installed under. + """ + + import os + import sys + + if not path: + path = os.getcwd() + + # check if this really looks like a plugin + if not os.path.isfile(os.path.join(path, "setup.py")): + click.echo("This doesn't look like an OctoPrint plugin folder") + sys.exit(1) + + self.command_caller.call([sys.executable, "setup.py", "develop"], cwd=path) + + return command + + def plugin_uninstall(self): + from octoprint.util.pip import PipCaller + pip_command = PipCaller.autodetect_pip() + if pip_command is None: + return + + @click.command("uninstall") + @click.argument("name") + def command(name): + """Uninstalls the plugin with the given name.""" + import sys + + lower_name = name.lower() + if not lower_name.startswith("octoprint_") and not lower_name.startswith("octoprint-"): + click.echo("This doesn't look like an OctoPrint plugin name") + sys.exit(1) + + call = [pip_command, "uninstall", "--yes", name] + self.command_caller.call(call) + + return command + +@click.group() +def dev_commands(): + pass + +@dev_commands.group(name="dev", cls=OctoPrintDevelCommands) +def dev(): + """Additional commands for development tasks.""" + pass diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py new file mode 100644 index 000000000..47bf887a6 --- /dev/null +++ b/src/octoprint/cli/plugins.py @@ -0,0 +1,99 @@ +# coding=utf-8 +from __future__ import absolute_import + +__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 click +import logging + +from octoprint.cli import pass_octoprint_ctx, OctoPrintContext + +#~~ "octoprint plugin:command" commands + +class OctoPrintPluginCommands(click.MultiCommand): + """ + Custom `click.MultiCommand `_ + implementation that collects commands from the plugin hook + :ref:`octoprint.cli.commands `. + + .. attribute:: settings + + The global :class:`~octoprint.settings.Settings` instance. + + .. attribute:: plugin_manager + + The :class:`~octoprint.plugin.core.PluginManager` instance. + """ + + sep = ":" + + def __init__(self, *args, **kwargs): + click.MultiCommand.__init__(self, *args, **kwargs) + + self.settings = None + self.plugin_manager = None + self.hooks = dict() + + self._logger = logging.getLogger(__name__) + self._initialized = False + + def _initialize(self, ctx): + if self._initialized: + return + + if ctx.obj is None: + ctx.obj = OctoPrintContext() + + # initialize settings and plugin manager based on provided + # context (basedir and configfile) + from octoprint import init_settings, init_pluginsystem + self.settings = init_settings(ctx.obj.basedir, ctx.obj.configfile) + self.plugin_manager = init_pluginsystem(self.settings) + + # fetch registered hooks + self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands") + + self._initialized = True + + def list_commands(self, ctx): + self._initialize(ctx) + result = [name for name in self._get_commands()] + result.sort() + return result + + def get_command(self, ctx, cmd_name): + self._initialize(ctx) + commands = self._get_commands() + return commands.get(cmd_name, None) + + def _get_commands(self): + """Fetch all commands from plugins providing any.""" + + import collections + result = collections.OrderedDict() + + for name, hook in self.hooks.items(): + try: + commands = hook(self, pass_octoprint_ctx) + for command in commands: + if not isinstance(command, click.Command): + self._logger.warn("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command)) + continue + result[name + self.sep + command.name] = command + except: + self._logger.exception("Error while retrieving cli commants for plugin {}".format(name)) + + return result + +@click.group() +@pass_octoprint_ctx +def plugin_commands(obj): + logging.basicConfig(level=logging.DEBUG if obj.verbosity > 0 else logging.WARN) + +@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands) +def plugins(): + """Additional commands provided by plugins.""" + pass + diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py new file mode 100644 index 000000000..e5737ffc0 --- /dev/null +++ b/src/octoprint/cli/server.py @@ -0,0 +1,131 @@ +# coding=utf-8 +from __future__ import absolute_import + +__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 click +import logging +import sys + +from octoprint.cli import pass_octoprint_ctx, bulk_options, standard_options + +def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity): + """Initializes the environment and starts up the server.""" + + from octoprint import init_platform, __display_version__ + + def log_startup(_): + logging.getLogger("octoprint.server").info("Starting OctoPrint {}".format(__display_version__)) + + from octoprint import urllib3_ssl + if not urllib3_ssl: + logging.getLogger("octoprint.server")\ + .warn("requests/urllib3 will run in an insecure SSL environment. " + "You might see corresponding warnings logged later " + "(\"InsecurePlatformWarning\"). It is recommended to either " + "update to a Python version >= 2.7.9 or alternatively " + "install PyOpenSSL plus its dependencies. For details see " + "https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl") + + settings, _, plugin_manager = init_platform(basedir, + configfile, + logging_file=logging_config, + debug=debug, + verbosity=verbosity, + uncaught_logger=__name__, + after_logging=log_startup) + + from octoprint.server import Server + octoprint_server = Server(settings=settings, plugin_manager=plugin_manager, host=host, port=port, debug=debug, allow_root=allow_root) + octoprint_server.run() + +#~~ server options + +server_options = bulk_options([ + click.option("--host", type=click.STRING, + help="Specify the host on which to bind the server."), + click.option("--port", type=click.INT, + help="Specify the port on which to bind the server."), + click.option("--logging", type=click.Path(), + help="Specify the config file to use for configuring logging."), + click.option("--iknowwhatimdoing", "allow_root", is_flag=True, + help="Allow OctoPrint to run as user root."), + click.option("--debug", is_flag=True, help="Enable debug mode"), +]) +"""Decorator to add the options shared among the server commands: ``--host``, ``--port``, + ``--logging``, ``--iknowwhatimdoing`` and ``--debug``.""" + +#~~ "octoprint serve" and "octoprint daemon" commands + +@click.group() +@pass_octoprint_ctx +def server_commands(obj): + pass + + +@server_commands.command(name="serve") +@server_options +@standard_options(hidden=True) +@pass_octoprint_ctx +def serve_command(obj, host, port, logging, allow_root, debug): + """Starts the OctoPrint server.""" + run_server(obj.basedir, obj.configfile, host, port, debug, + allow_root, logging, obj.verbosity) + + +@server_commands.command(name="daemon") +@click.option("--pid", type=click.Path(), default="/tmp/octoprint.pid", + help="Pidfile to use for daemonizing.") +@server_options +@standard_options(hidden=True) +@click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]), + metavar="start|stop|restart|status") +@pass_octoprint_ctx +def daemon_command(octoprint_ctx, pid, host, port, logging, allow_root, debug, command): + """ + Starts, stops or restarts in daemon mode. + + Please note that daemon mode is only supported under Linux right now. + """ + if sys.platform == "darwin" or sys.platform == "win32": + click.echo("Sorry, daemon mode is only supported under Linux right now", + file=sys.stderr) + sys.exit(2) + + if pid is None: + click.echo("No path to a pidfile set", + file=sys.stderr) + sys.exit(1) + + from octoprint.daemon import Daemon + class OctoPrintDaemon(Daemon): + def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity): + Daemon.__init__(self, pidfile) + + self._basedir = basedir + self._configfile = configfile + self._host = host + self._port = port + self._debug = debug + self._allow_root = allow_root + self._logging_config = logging_config + self._verbosity = verbosity + + def run(self): + run_server(self._basedir, self._configfile, self._host, self._port, self._debug, self._allow_root, self._logging_config, self._verbosity) + + octoprint_daemon = OctoPrintDaemon(pid, octoprint_ctx.basedir, octoprint_ctx.configfile, + host, port, debug, allow_root, logging, octoprint_ctx.verbosity) + + if command == "start": + octoprint_daemon.start() + elif command == "stop": + octoprint_daemon.stop() + elif command == "restart": + octoprint_daemon.restart() + elif command == "status": + octoprint_daemon.status() + + diff --git a/src/octoprint/daemon.py b/src/octoprint/daemon.py index 4ef56b162..4d00252f7 100644 --- a/src/octoprint/daemon.py +++ b/src/octoprint/daemon.py @@ -1,46 +1,65 @@ +# coding=utf-8 """ -Generic linux daemon base class for python 3.x +Generic linux daemon base class Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35 """ +from __future__ import (print_function, absolute_import) import sys, os, time, signal class Daemon: - """A generic daemon class. + """ + A generic daemon class. - Usage: subclass the daemon class and override the run() method.""" + Usage: subclass the daemon class and override the run() method. - def __init__(self, pidfile): self.pidfile = pidfile - - def daemonize(self): - """Deamonize class. UNIX double fork mechanism.""" + If you want to log the output to someplace different that stdout and stderr, + also override the echo() and error() methods. + """ - try: - pid = os.fork() + def __init__(self, pidfile): + self.pidfile = pidfile + + def _daemonize(self): + """Daemonize class. UNIX double fork mechanism.""" + + self._double_fork() + self._redirect_io() + + # write pidfile + pid = str(os.getpid()) + self.set_pid(pid) + + # register listener for SIGTERM + signal.signal(signal.SIGTERM, self._on_sigterm) + + def _double_fork(self): + try: + pid = os.fork() if pid > 0: # exit first parent - sys.exit(0) - except OSError as err: - sys.stderr.write('fork #1 failed: {0}\n'.format(err)) + sys.exit(0) + except OSError as err: + self.error("First fork failed: {}".format(str(err))) sys.exit(1) - - # decouple from parent environment - os.chdir('/') - os.setsid() - os.umask(002) - - # do second fork - try: - pid = os.fork() - if pid > 0: + # decouple from parent environment + os.chdir('/') + os.setsid() + os.umask(002) + + # do second fork + try: + pid = os.fork() + if pid > 0: # exit from second parent - sys.exit(0) - except OSError as err: - sys.stderr.write('fork #2 failed: {0}\n'.format(err)) - sys.exit(1) - + sys.exit(0) + except OSError as err: + self.error("Second fork failed: {}".format(str(err))) + sys.exit(1) + + def _redirect_io(self): # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() @@ -51,57 +70,39 @@ class Daemon: os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) - - # write pidfile - pid = str(os.getpid()) - with open(self.pidfile,'w+') as f: - f.write(pid + '\n') - # register listener for SIGTERM - signal.signal(signal.SIGTERM, self.term) - - def term(self, _signo, _stack_frame): - os.remove(self.pidfile) + def _on_sigterm(self, _signo, _stack_frame): + """Signal handler for SIGTERM, deletes the pidfile.""" + self.remove_pidfile() sys.exit(0) def start(self): """Start the daemon.""" # Check for a pidfile to see if the daemon already runs - try: - with open(self.pidfile,'r') as pf: - - pid = int(pf.read().strip()) - except IOError: - pid = None - + pid = self.get_pid() if pid: - message = "pidfile {0} already exist. " + \ - "Daemon already running?\n" - sys.stderr.write(message.format(self.pidfile)) + self.error("pidfile {} already exist. Is the daemon already running?".format(self.pidfile)) sys.exit(1) - + + self.echo("Starting daemon...") + # Start the daemon - self.daemonize() + self._daemonize() self.run() - def stop(self): + def stop(self, check_running=True): """Stop the daemon.""" - - # Get the pid from the pidfile - try: - with open(self.pidfile,'r') as pf: - pid = int(pf.read().strip()) - except IOError: - pid = None - + pid = self.get_pid() if not pid: - message = "pidfile {0} does not exist. " + \ - "Daemon not running?\n" - sys.stderr.write(message.format(self.pidfile)) - return # not an error in a restart + if not check_running: + return + self.error("pidfile {} does not exist. Is the daemon really running?".format(self.pidfile)) + sys.exit(1) - # Try killing the daemon process + self.echo("Stopping daemon...") + + # Try killing the daemon process try: while 1: os.kill(pid, signal.SIGTERM) @@ -109,20 +110,71 @@ class Daemon: except OSError as err: e = str(err.args) if e.find("No such process") > 0: - if os.path.exists(self.pidfile): - os.remove(self.pidfile) + self.remove_pidfile() else: - print (str(err.args)) + self.error(e) sys.exit(1) def restart(self): """Restart the daemon.""" - self.stop() + self.stop(check_running=False) self.start() + def status(self): + """Prints the daemon status.""" + if self.is_running(): + self.echo("Daemon is running") + else: + self.echo("Daemon is not running") + + def is_running(self): + """Check if a process is running under the specified pid.""" + pid = self.get_pid() + if pid is None: + return False + + try: + os.kill(pid, 0) + except OSError: + try: + self.remove_pidfile() + except: + self.error("Daemon found not running, but could not remove stale pidfile") + return False + else: + return True + + def get_pid(self): + """Get the pid from the pidfile.""" + try: + with open(self.pidfile,'r') as pf: + pid = int(pf.read().strip()) + except (IOError, ValueError): + pid = None + return pid + + def set_pid(self, pid): + """Write the pid to the pidfile.""" + with open(self.pidfile,'w+') as f: + f.write(str(pid) + '\n') + + def remove_pidfile(self): + """Removes the pidfile.""" + if os.path.isfile(self.pidfile): + os.remove(self.pidfile) + def run(self): """You should override this method when you subclass Daemon. - - It will be called after the process has been daemonized by + + It will be called after the process has been daemonized by start() or restart().""" + raise NotImplementedError() + + @classmethod + def echo(cls, line): + print(line) + + @classmethod + def error(cls, line): + print(line, stream=sys.stderr) diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 2cc765d9b..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" diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 34f31680c..795cb2c00 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -340,9 +340,15 @@ class FileManager(object): def get_busy_files(self): return self._slicing_jobs.keys() + def file_in_path(self, destination, path, file): + return self._storage(destination).file_in_path(path, file) + def file_exists(self, destination, path): return self._storage(destination).file_exists(path) + def folder_exists(self, destination, path): + return self._storage(destination).folder_exists(path) + def list_files(self, destinations=None, path=None, filter=None, recursive=None): if not destinations: destinations = self._storage_managers.keys() @@ -385,6 +391,14 @@ class FileManager(object): self._storage(destination).remove_file(path) eventManager().fire(Events.UPDATED_FILES, dict(type="printables")) + def copy_file(self, destination, source, dst): + self._storage(destination).copy_file(source, dst) + eventManager().fire(Events.UPDATED_FILES, dict(type="printables")) + + def move_file(self, destination, source, dst): + self._storage(destination).move_file(source, dst) + eventManager().fire(Events.UPDATED_FILES, dict(type="printables")) + def add_folder(self, destination, path, ignore_existing=True): folder_path = self._storage(destination).add_folder(path, ignore_existing=ignore_existing) eventManager().fire(Events.UPDATED_FILES, dict(type="printables")) @@ -394,6 +408,14 @@ class FileManager(object): self._storage(destination).remove_folder(path, recursive=recursive) eventManager().fire(Events.UPDATED_FILES, dict(type="printables")) + def copy_folder(self, destination, source, dst): + self._storage(destination).copy_folder(source, dst) + eventManager().fire(Events.UPDATED_FILES, dict(type="printables")) + + def move_folder(self, destination, source, dst): + self._storage(destination).move_folder(source, dst) + eventManager().fire(Events.UPDATED_FILES, dict(type="printables")) + def get_metadata(self, destination, path): return self._storage(destination).get_metadata(path) diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 6a2378dd6..1d1617058 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -9,7 +9,11 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import logging import os import pylru -import tempfile +import shutil + +from octoprint.util import atomic_write +from contextlib import contextmanager +from copy import deepcopy import octoprint.filemanager @@ -35,6 +39,15 @@ class StorageInterface(object): return yield + def file_in_path(self, path, filepath): + """ + Returns whether the file indicated by ``file`` is inside ``path`` or not. + :param string path: the path to check + :param string filepath: path to the file + :return: ``True`` if the file is inside the path, ``False`` otherwise + """ + return NotImplementedError() + def file_exists(self, path): """ Returns whether the file indicated by ``path`` exists or not. @@ -43,6 +56,14 @@ class StorageInterface(object): """ raise NotImplementedError() + def folder_exists(self, path): + """ + Returns whether the folder indicated by ``path`` exists or not. + :param string path: the path to check for existence + :return: ``True`` if the folder exists, ``False`` otherwise + """ + raise NotImplementedError() + def list_files(self, path=None, filter=None, recursive=True): """ List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into @@ -114,6 +135,24 @@ class StorageInterface(object): """ raise NotImplementedError() + def copy_folder(self, source, destination): + """ + Copys the folder ``source`` to ``destination`` + + :param string source: path to the source folder + :param string destination: path to destination + """ + raise NotImplementedError() + + def move_folder(self, source, destination): + """ + Moves the folder ``source`` to ``destination`` + + :param string source: path to the source folder + :param string destination: path to destination + """ + raise NotImplementedError() + def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False): """ Adds the file ``file_object`` as ``path`` @@ -138,6 +177,24 @@ class StorageInterface(object): """ raise NotImplementedError() + def copy_file(self, source, destination): + """ + Copys the file ``source`` to ``destination`` + + :param string source: path to the source file + :param string destination: path to destination + """ + raise NotImplementedError() + + def move_file(self, source, destination): + """ + Moves the file ``source`` to ``destination`` + + :param string source: path to the source file + :param string destination: path to destination + """ + raise NotImplementedError() + def get_metadata(self, path): """ Retrieves the metadata for the file ``path``. @@ -279,6 +336,25 @@ class StorageInterface(object): raise NotImplementedError() +class StorageError(Exception): + UNKNOWN = "unknown" + INVALID_DIRECTORY = "invalid_directory" + INVALID_FILE = "invalid_file" + INVALID_SOURCE = "invalid_source" + INVALID_DESTINATION = "invalid_destination" + DOES_NOT_EXIST = "does_not_exist" + ALREADY_EXISTS = "already_exists" + NOT_EMPTY = "not_empty" + + def __init__(self, message, code=None, cause=None): + BaseException.__init__(self) + self.message = message + self.cause = cause + + if code is None: + code = StorageError.UNKNOWN + self.code = code + class LocalFileStorage(StorageInterface): """ @@ -304,13 +380,18 @@ class LocalFileStorage(StorageInterface): if not os.path.exists(self.basefolder) and create: os.makedirs(self.basefolder) if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder): - raise RuntimeError("{basefolder} is not a valid directory".format(**locals())) + raise StorageError("{basefolder} is not a valid directory".format(**locals()), code=StorageError.INVALID_DIRECTORY) import threading - self._metadata_lock = threading.Lock() + self._metadata_lock_mutex = threading.RLock() + self._metadata_locks = dict() self._metadata_cache = pylru.lrucache(10) + from slugify import Slugify + self._slugify = Slugify() + self._slugify.safe_chars = "-_.() " + self._old_metadata = None self._initialize_metadata() @@ -376,11 +457,22 @@ class LocalFileStorage(StorageInterface): for sub_entry in self._analysis_backlog_generator(absolute_path): yield self.join_path(entry, sub_entry[0]), sub_entry[1], sub_entry[2] + def file_in_path(self, path, filepath): + filepath = self.sanitize_path(filepath) + path = self.sanitize_path(path) + + return filepath.startswith(path) + def file_exists(self, path): path, name = self.sanitize(path) file_path = os.path.join(path, name) return os.path.exists(file_path) and os.path.isfile(file_path) + def folder_exists(self, path): + path, name = self.sanitize(path) + folder_path = os.path.join(path, name) + return os.path.exists(folder_path) and os.path.isdir(folder_path) + def list_files(self, path=None, filter=None, recursive=True): if path: path = self.sanitize_path(path) @@ -394,7 +486,7 @@ class LocalFileStorage(StorageInterface): folder_path = os.path.join(path, name) if os.path.exists(folder_path): if not ignore_existing: - raise RuntimeError("{sanitized_foldername} does already exist in {virtual_path}".format(**locals())) + raise StorageError("{sanitized_foldername} does already exist in {virtual_path}".format(**locals()), code=StorageError.ALREADY_EXISTS) else: os.mkdir(folder_path) @@ -411,25 +503,69 @@ class LocalFileStorage(StorageInterface): if ".metadata.yaml" in contents: contents.remove(".metadata.yaml") if contents and not recursive: - raise RuntimeError("{sanitized_foldername} in {virtual_path} is not empty".format(**locals())) + raise StorageError("{sanitized_foldername} in {virtual_path} is not empty".format(**locals()), code=StorageError.NOT_EMPTY) import shutil shutil.rmtree(folder_path) + self._delete_metadata(folder_path) + + def _get_source_destination_data(self, source, destination): + """Prepares data dicts about source and destination for copy/move.""" + source_path, source_name = self.sanitize(source) + destination_path, destination_name = self.sanitize(destination) + + source_fullpath = os.path.join(source_path, source_name) + destination_fullpath = os.path.join(destination_path, destination_name) + + if not os.path.exists(source_fullpath): + raise StorageError("{} in {} does not exist".format(source_name, source_path), code=StorageError.INVALID_SOURCE) + + if not os.path.isdir(destination_path): + raise StorageError("Destination path {} does not exist or is not a folder".format(destination_path), code=StorageError.INVALID_DESTINATION) + if os.path.exists(destination_fullpath): + raise StorageError("{} does already exist in {}".format(destination_name, destination_path), code=StorageError.INVALID_DESTINATION) + + source_data = dict( + path=source_path, + name=source_name, + fullpath=source_fullpath, + ) + destination_data = dict( + path=destination_path, + name=destination_name, + fullpath=destination_fullpath, + ) + return source_data, destination_data + + def copy_folder(self, source, destination): + source_data, destination_data = self._get_source_destination_data(source, destination) + + try: + shutil.copytree(source_data["fullpath"], destination_data["fullpath"]) + except Exception as e: + raise StorageError("Could not copy %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e) + + def move_folder(self, source, destination): + source_data, destination_data = self._get_source_destination_data(source, destination) + + try: + shutil.move(source_data["fullpath"], destination_data["fullpath"]) + except Exception as e: + raise StorageError("Could not move %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e) + + self._delete_metadata(source_data["fullpath"]) + def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False): path, name = self.sanitize(path) if not octoprint.filemanager.valid_file_type(name): - raise RuntimeError("{name} is an unrecognized file type".format(**locals())) - - metadata = self._get_metadata(path) - if not metadata: - metadata = dict() + raise StorageError("{name} is an unrecognized file type".format(**locals()), code=StorageError.INVALID_FILE) file_path = os.path.join(path, name) if os.path.exists(file_path) and not os.path.isfile(file_path): - raise RuntimeError("{name} does already exist in {path} and is not a file".format(**locals())) + raise StorageError("{name} does already exist in {path} and is not a file".format(**locals()), code=StorageError.ALREADY_EXISTS) if os.path.exists(file_path) and not allow_overwrite: - raise RuntimeError("{name} does already exist in {path} and overwriting is prohibited".format(**locals())) + raise StorageError("{name} does already exist in {path} and overwriting is prohibited".format(**locals()), code=StorageError.ALREADY_EXISTS) # make sure folders exist if not os.path.exists(path): @@ -440,13 +576,10 @@ class LocalFileStorage(StorageInterface): # save the file's hash to the metadata of the folder file_hash = self._create_hash(file_path) - if not name in metadata or not "hash" in metadata[name] or metadata[name]["hash"] != file_hash: - # make sure to create a new metadata entry if we've never seen that file with that content before - file_metadata = dict( - hash=file_hash - ) - metadata[name] = file_metadata - self._save_metadata(path, metadata) + metadata = self._get_metadata_entry(path, name, default=dict()) + if not "hash" in metadata or metadata["hash"] != file_hash: + metadata["hash"] = file_hash + self._update_metadata_entry(path, name, metadata) # process any links that were also provided for adding to the file if not links: @@ -465,45 +598,50 @@ class LocalFileStorage(StorageInterface): def remove_file(self, path): path, name = self.sanitize(path) - metadata = self._get_metadata(path) - file_path = os.path.join(path, name) if not os.path.exists(file_path): return if not os.path.isfile(file_path): - raise RuntimeError("{name} in {path} is not a file".format(**locals())) + raise StorageError("{name} in {path} is not a file".format(**locals()), code=StorageError.INVALID_FILE) try: os.remove(file_path) except Exception as e: - raise RuntimeError("Could not delete {name} in {path}".format(**locals()), e) + raise StorageError("Could not delete {name} in {path}".format(**locals()), cause=e) - if name in metadata: - if "hash" in metadata[name]: - hash = metadata[name]["hash"] - for m in metadata.values(): - if not "links" in m: - continue - for link in m["links"]: - if "rel" in link and "hash" in link and (link["rel"] == "model" or link["rel"] == "machinecode") and link["hash"] == hash: - m["links"].remove(link) - del metadata[name] - self._save_metadata(path, metadata) + self._remove_metadata_entry(path, name) + + def copy_file(self, source, destination): + source_data, destination_data = self._get_source_destination_data(source, destination) + + try: + shutil.copy2(source_data["fullpath"], destination_data["fullpath"]) + except Exception as e: + raise StorageError("Could not copy %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e) + + self._copy_metadata_entry(source_data["path"], source_data["name"], + destination_data["path"], destination_data["name"]) + + def move_file(self, source, destination, allow_overwrite=False): + source_data, destination_data = self._get_source_destination_data(source, destination) + + try: + shutil.move(source_data["fullpath"], destination_data["fullpath"]) + except Exception as e: + raise StorageError("Could not move %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e) + + self._copy_metadata_entry(source_data["path"], source_data["name"], + destination_data["path"], destination_data["name"], + delete_source=True) def get_metadata(self, path): path, name = self.sanitize(path) - - metadata = self._get_metadata(path) - if name in metadata: - return metadata[name] - else: - return None + return self._get_metadata_entry(path, name) def get_link(self, path, rel): path, name = self.sanitize(path) return self._get_links(name, path, rel) - def add_link(self, path, rel, data): path, name = self.sanitize(path) self._add_links(name, path, [(rel, data)]) @@ -609,9 +747,9 @@ class LocalFileStorage(StorageInterface): def sanitize_name(self, name): """ - Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise strips any characters from the - given ``name`` that are not any of the ASCII characters, digits, ``-``, ``_``, ``.``, ``(``, ``)`` or space and - replaces and spaces with ``_``. + Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise + slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``, + ``(``, and ``)`` as is. """ if name is None: return None @@ -619,11 +757,7 @@ class LocalFileStorage(StorageInterface): if "/" in name or "\\" in name: raise ValueError("name must not contain / or \\") - import string - valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits) - sanitized_name = ''.join(c for c in name if c in valid_chars) - sanitized_name = sanitized_name.replace(" ", "_") - return sanitized_name + return self._slugify(name).replace(" ", "_") def sanitize_path(self, path): """ @@ -927,13 +1061,29 @@ class LocalFileStorage(StorageInterface): # folder recursion elif os.path.isdir(entry_path) and recursive: - sub_result = self._list_folder(entry_path, filter=filter) - result[entry] = dict( + sub_result = self._list_folder(entry_path, filter=filter, recursive=recursive) + entry_data = dict( name=entry, type="folder", children=sub_result ) + if not filter or filter(entry, entry_data): + def get_size(): + total_size = 0 + for element in entry_data["children"].itervalues(): + if "size" in element: + total_size += element["size"] + + return total_size + + # only add folders passing the optional filter + extended_entry_data = dict() + extended_entry_data.update(entry_data) + extended_entry_data["size"] = get_size() + + result[entry] = extended_entry_data + # TODO recreate links if we have metadata less entries # save metadata @@ -980,13 +1130,53 @@ class LocalFileStorage(StorageInterface): return hash.hexdigest() - def _get_metadata(self, path): - if path in self._metadata_cache: - return self._metadata_cache[path] + def _get_metadata_entry(self, path, name, default=None): + with self._get_metadata_lock(path): + metadata = self._get_metadata(path) + return metadata.get(name, default) - metadata_path = os.path.join(path, ".metadata.yaml") - if os.path.exists(metadata_path): - with self._metadata_lock: + def _remove_metadata_entry(self, path, name): + with self._get_metadata_lock(path): + metadata = self._get_metadata(path) + if not name in metadata: + return + + if "hash" in metadata[name]: + hash = metadata[name]["hash"] + for m in metadata.values(): + if not "links" in m: + continue + links_hash = lambda link: "hash" in link and link["hash"] == hash and "rel" in link and (link["rel"] == "model" or link["rel"] == "machinecode") + m["links"] = [link for link in m["links"] if not links_hash(link)] + + del metadata[name] + self._save_metadata(path, metadata) + + def _update_metadata_entry(self, path, name, data): + with self._get_metadata_lock(path): + metadata = self._get_metadata(path) + metadata[name] = data + self._save_metadata(path, metadata) + + def _copy_metadata_entry(self, source_path, source_name, destination_path, destination_name, delete_source=False): + with self._get_metadata_lock(source_path): + source_data = self._get_metadata_entry(source_path, source_name, default=dict()) + if not source_data: + return + + if delete_source: + self._remove_metadata_entry(source_path, source_name) + + with self._get_metadata_lock(destination_path): + self._update_metadata_entry(destination_path, destination_name, source_data) + + def _get_metadata(self, path): + with self._get_metadata_lock(path): + if path in self._metadata_cache: + return deepcopy(self._metadata_cache[path]) + + metadata_path = os.path.join(path, ".metadata.yaml") + if os.path.exists(metadata_path): with open(metadata_path) as f: try: import yaml @@ -994,30 +1184,49 @@ class LocalFileStorage(StorageInterface): except: self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals())) else: - self._metadata_cache[path] = metadata + self._metadata_cache[path] = deepcopy(metadata) return metadata - return dict() + return dict() def _save_metadata(self, path, metadata): - metadata_path = os.path.join(path, ".metadata.yaml") - - with self._metadata_lock: + with self._get_metadata_lock(path): + metadata_path = os.path.join(path, ".metadata.yaml") try: import yaml - import shutil - - file_obj = tempfile.NamedTemporaryFile(delete=False) - try: - yaml.safe_dump(metadata, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True) - file_obj.close() - shutil.move(file_obj.name, metadata_path) - 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))) + with atomic_write(metadata_path) as f: + yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True) except: self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals())) else: - self._metadata_cache[path] = metadata + self._metadata_cache[path] = deepcopy(metadata) + + def _delete_metadata(self, path): + with self._get_metadata_lock(path): + metadata_path = os.path.join(path, ".metadata.yaml") + if os.path.exists(metadata_path): + try: + os.remove(metadata_path) + except: + self._logger.exception("Error while deleting .metadata.yaml from {path}".format(**locals())) + if path in self._metadata_cache: + del self._metadata_cache[path] + + @contextmanager + def _get_metadata_lock(self, path): + with self._metadata_lock_mutex: + if path not in self._metadata_locks: + import threading + self._metadata_locks[path] = (0, threading.RLock()) + + counter, lock = self._metadata_locks[path] + counter += 1 + self._metadata_locks[path] = (counter, lock) + + yield lock + + counter = self._metadata_locks[path][0] + counter -= 1 + if counter <= 0: + del self._metadata_locks[path] + else: + self._metadata_locks[path] = (counter, lock) diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index 0cc587150..fa6810e2d 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -22,7 +22,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import os import logging -from octoprint.settings import settings +from octoprint.settings import settings as s from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin) from octoprint.plugin.types import * @@ -44,7 +44,7 @@ def _validate_plugin(phase, plugin_info): setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks) def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None, - plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None): + plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None, settings=None): """ Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager` singleton. @@ -87,9 +87,12 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en else: if init: + if settings is None: + settings = s() + if plugin_folders is None: plugin_folders = ( - settings().getBaseFolder("plugins"), + settings.getBaseFolder("plugins"), (os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "plugins")), True) ) if plugin_types is None: @@ -103,11 +106,13 @@ 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: - plugin_disabled_list = settings().get(["plugins", "_disabled"]) + plugin_disabled_list = settings.get(["plugins", "_disabled"]) if plugin_restart_needing_hooks is None: plugin_restart_needing_hooks = [ "octoprint.server.http" @@ -134,7 +139,7 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en return _instance -def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None): +def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None, settings=None): """ Factory method for creating a :class:`PluginSettings` instance. @@ -143,15 +148,48 @@ def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_prepr defaults (dict): The default settings for the plugin. get_preprocessors (dict): The getter preprocessors for the plugin. set_preprocessors (dict): The setter preprocessors for the plugin. + settings (octoprint.settings.Settings): The settings instance to use. Returns: PluginSettings: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's settings """ - return PluginSettings(settings(), plugin_key, defaults=defaults, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors) + if settings is None: + settings = s() + return PluginSettings(settings, plugin_key, defaults=defaults, + get_preprocessors=get_preprocessors, + set_preprocessors=set_preprocessors) -def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None): +def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None): + """ + Factory method for creating a :class:`PluginSettings` instance for a given :class:`SettingsPlugin` instance. + + Will return `None` if the provided `instance` is not a :class:`SettingsPlugin` instance. + + Arguments: + plugin_key (string): The plugin identifier for which to create the settings instance. + implementation (octoprint.plugin.SettingsPlugin): The :class:`SettingsPlugin` instance. + settings (octoprint.settings.Settings): The settings instance to use. Defaults to the global OctoPrint settings. + + Returns: + PluginSettings or None: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's + settings, or `None` if the provided `instance` was not a class:`SettingsPlugin` + """ + if not isinstance(instance, SettingsPlugin): + return None + + try: + defaults = instance.get_settings_defaults() + get_preprocessors, set_preprocessors = instance.get_settings_preprocessors() + except: + logging.getLogger(__name__).exception("Error while retrieving defaults or preprocessors for plugin {}".format(plugin_key)) + return None + + return plugin_settings(plugin_key, defaults=defaults, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings) + + +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 @@ -197,7 +235,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: @@ -330,7 +368,7 @@ class PluginSettings(object): 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), - remove =("remove", prefix_path_in_args) + remove =("remove", prefix_path_in_args, lambda x: x) ) self.deprecated_access_methods = dict( getInt ="get_int", diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index bcb28ce01..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,14 +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) @@ -492,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)) @@ -520,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 @@ -532,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] @@ -567,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 @@ -637,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: @@ -779,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: @@ -791,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 @@ -1017,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``. @@ -1030,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: @@ -1040,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`. @@ -1056,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): @@ -1116,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): @@ -1209,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 d1987ea6e..0223772ca 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,377 @@ 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 + + def get_ui_additional_key_data_for_cache(self): + return None + + def get_ui_additional_tracked_files(self): + return None + + def get_ui_custom_tracked_files(self): + return None + + def get_ui_custom_etag(self): + return None + + def get_ui_custom_lastmodified(self): + return None + + def get_ui_data_for_preemptive_caching(self): + return None + + def get_ui_additional_request_data_for_preemptive_caching(self): + 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 +1049,8 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): flask.url_for("plugin.myblueprintplugin.myEcho") # will return "/plugin/myblueprintplugin/echo" + + ``BlueprintPlugin`` implements :class:`~octoprint.plugins.core.RestartNeedingPlugin`. """ @staticmethod diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py new file mode 100644 index 000000000..37d734a91 --- /dev/null +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -0,0 +1,147 @@ +# 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.enabled 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) + self._user_manager.enable() + self._user_manager.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._user_manager.disable() + 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 095a274b5..62f6770c5 100644 --- a/src/octoprint/plugins/cura/__init__.py +++ b/src/octoprint/plugins/cura/__init__.py @@ -16,14 +16,19 @@ import octoprint.util import octoprint.slicing 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") @@ -35,6 +40,14 @@ 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_vars(self): @@ -42,6 +55,17 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, homepage=__plugin_url__ ) + ##~~ 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): @@ -59,9 +83,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"]) @@ -90,8 +111,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: @@ -99,22 +122,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 ) @@ -155,11 +187,12 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, ##~~ SlicerPlugin API def is_slicer_configured(self): - cura_engine = self._settings.get(["cura_engine"]) - if cura_engine is not None and os.path.exists(cura_engine): + cura_engine = normalize_path(self._settings.get(["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( @@ -227,15 +260,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 = self._settings.get(["cura_engine"]) + 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] @@ -318,6 +365,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() @@ -328,17 +377,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: @@ -388,6 +445,11 @@ 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): @@ -395,9 +457,28 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, 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: @@ -412,9 +493,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 (<= 15.04)" __plugin_author__ = "Gina Häußge" __plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura" __plugin_description__ = "Adds support for slicing via CuraEngine versions up to and including version 15.04 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 23068292c..0d091ab3b 100644 --- a/src/octoprint/plugins/cura/static/js/cura.js +++ b/src/octoprint/plugins/cura/static/js/cura.js @@ -6,6 +6,13 @@ $(function() { self.settingsViewModel = parameters[1]; self.slicingViewModel = parameters[2]; + self.pathBroken = ko.observable(false); + self.pathOk = ko.observable(false); + self.pathText = ko.observable(); + self.pathHelpVisible = ko.computed(function() { + return self.pathBroken() || self.pathOk(); + }); + self.fileName = ko.observable(); self.placeholderName = ko.observable(); @@ -16,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"); @@ -59,6 +70,7 @@ $(function() { dataType: "json", maxNumberOfFiles: 1, autoUpload: false, + headers: OctoPrint.getRequestHeaders(), add: function(e, data) { if (data.files.length == 0) { return false; @@ -86,6 +98,9 @@ $(function() { if (self.profileDescription() !== undefined) { form["description"] = self.profileDescription(); } + if (self.profileMakeDefault()) { + form["default"] = true; + } data.formData = form; data.submit(); @@ -100,6 +115,7 @@ $(function() { self.profileDisplayName(undefined); self.profileDescription(undefined); self.profileAllowOverwrite(true); + self.profileMakeDefault(false); $("#settings_plugin_cura_import").modal("hide"); self.requestData(); @@ -116,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) { @@ -141,29 +154,42 @@ $(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() { + 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")); + } else if (!response.typeok) { + self.pathText(gettext("The path is not a file")); + } else if (!response.access) { + self.pathText(gettext("The path is not an executable")); + } + } else { + self.pathText(gettext("The path is valid")); + } + 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) { @@ -184,12 +210,37 @@ $(function() { self.settings = self.settingsViewModel.settings; self.requestData(); }; + + 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"] ]); -}); \ No newline at end of file +}); 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..1db74c084 --- /dev/null +++ b/src/octoprint/plugins/cura/templates/_snippets/settings/cura/profileImporter.jinja2 @@ -0,0 +1,64 @@ + 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 92cfe0ae0..2bba70fdc 100644 --- a/src/octoprint/plugins/cura/templates/cura_settings.jinja2 +++ b/src/octoprint/plugins/cura/templates/cura_settings.jinja2 @@ -8,55 +8,13 @@ {% endtrans %}

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

{{ _('Profiles') }}

- - - - - - - - - - - - - - - - -
{{ _('Identifier') }}{{ _('Name') }}{{ _('Actions') }}
-  |  -
- +{% include "_snippets/settings/cura/profiles.jinja2" %} @@ -64,62 +22,4 @@ {% trans %}For more information on configuration and usage please see the Plugin's homepage.{% endtrans %} - - +{% 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..2ca68070e --- /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 up to and including version 15.04, + 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 0c40562a1..6841f3d5c 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -11,7 +11,7 @@ import octoprint.plugin.core from octoprint.settings import valid_boolean_trues from octoprint.server.util.flask import restricted_access -from octoprint.server import admin_permission +from octoprint.server import admin_permission, VERSION from octoprint.util.pip import PipCaller, UnknownPip from flask import jsonify, make_response @@ -39,19 +39,21 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._pending_uninstall = set() self._pip_caller = None - self._pip_version_dependency_links = pkg_resources.parse_version("1.5") self._repository_available = False self._repository_plugins = [] self._repository_cache_path = None self._repository_cache_ttl = 0 + self._console_logger = None + def initialize(self): self._console_logger = logging.getLogger("octoprint.plugins.pluginmanager.console") 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,6 +85,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, repository_ttl=24*60, pip=None, pip_args=None, + pip_force_user=False, dependency_links=False, hidden=[] ) @@ -93,6 +96,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, new_pip = self._settings.get(["pip"]) self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60 + self._pip_caller.force_user = self._settings.get_boolean(["pip_force_user"]) if old_pip != new_pip: self._pip_caller.configured = new_pip try: @@ -113,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 @@ -169,27 +186,24 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if not admin_permission.can(): return make_response("Insufficient rights", 403) - plugins = self._plugin_manager.plugins - - result = [] - for name, plugin in plugins.items(): - 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, + 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(), + 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"]) )) @@ -323,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)) @@ -337,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())) @@ -384,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: @@ -447,8 +470,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if "--process-dependency-links" in args: self._log_message(u"Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version") - if self._pip_caller < self._pip_version_dependency_links: - args.remove("--process-dependency-links") additional_args = self._settings.get(["pip_args"]) if additional_args: @@ -550,9 +571,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return False current_os = self._get_os() - octoprint_version = self._get_octoprint_version() - if "-" in octoprint_version: - octoprint_version = octoprint_version[:octoprint_version.find("-")] + octoprint_version = self._get_octoprint_version(base=True) def map_repository_entry(entry): result = dict(entry) @@ -577,12 +596,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._repository_plugins = map(map_repository_entry, repo_data) return True - def _is_octoprint_compatible(self, octoprint_version_string, compatibility_entries): + def _is_octoprint_compatible(self, octoprint_version, compatibility_entries): """ Tests if the current ``octoprint_version`` is compatible to any of the provided ``compatibility_entries``. """ - octoprint_version = pkg_resources.parse_version(octoprint_version_string) for octo_compat in compatibility_entries: if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")): octo_compat = ">={}".format(octo_compat) @@ -611,9 +629,42 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, else: return "unknown" - def _get_octoprint_version(self): - from octoprint._version import get_versions - return get_versions()["version"] + def _get_octoprint_version_string(self): + return VERSION + + def _get_octoprint_version(self, base=False): + octoprint_version_string = self._get_octoprint_version_string() + + if "-" in octoprint_version_string: + octoprint_version_string = octoprint_version_string[:octoprint_version_string.find("-")] + + octoprint_version = pkg_resources.parse_version(octoprint_version_string) + if base: + if isinstance(octoprint_version, tuple): + # old setuptools + base_version = [] + for part in octoprint_version: + if part.startswith("*"): + break + base_version.append(part) + base_version.append("*final") + octoprint_version = tuple(base_version) + else: + # new setuptools + octoprint_version = pkg_resources.parse_version(octoprint_version.base_version) + return octoprint_version + + def _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( @@ -625,11 +676,12 @@ 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 ) @@ -645,5 +697,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 75c8e2f39..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,11 +72,13 @@ $(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"); @@ -82,14 +151,41 @@ $(function() { 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(); }); @@ -101,6 +197,7 @@ $(function() { self.enableUninstall = function(data) { return self.enableManagement() && (data.origin != "entry_point" || self.pipAvailable()) + && data.managable && !data.bundled && data.key != 'pluginmanager' && !data.pending_uninstall; @@ -211,12 +308,18 @@ $(function() { 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); } }; @@ -226,12 +329,8 @@ $(function() { 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) { @@ -245,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() { @@ -277,11 +382,7 @@ $(function() { return; } - if (self.installed(data)) { - self.installPlugin(data.archive, data.title, data.id, data.follow_dependency_links || self.followDependencyLinks()); - } else { - self.installPlugin(data.archive, data.title, undefined, data.follow_dependency_links || self.followDependencyLinks()); - } + self.installPlugin(data.archive, data.title, (self.installed(data) ? data.id : undefined), data.follow_dependency_links || self.followDependencyLinks()); }; self.installPlugin = function(url, name, reinstall, followDependencyLinks) { @@ -316,26 +417,33 @@ $(function() { } self._markWorking(workTitle, workText); - var command = "install"; - var payload = {url: url, dependency_links: followDependencyLinks}; - 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) { @@ -352,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() { @@ -410,7 +517,8 @@ $(function() { repository: repository, repository_ttl: repositoryTtl, pip: pipCommand, - pip_args: pipArgs + pip_args: pipArgs, + pip_force_user: self.config_pipForceUser() } } }; @@ -426,6 +534,7 @@ $(function() { 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) { @@ -441,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: { @@ -465,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) { @@ -554,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(); + }); } }; @@ -707,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 d399b593c..6804c6849 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -6,8 +6,9 @@ {% macro pluginmanager_nopip() %}
{% trans %} - The pip command could not be found. - Please configure it manually. No installation and uninstallation of plugin + 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 %} @@ -42,7 +43,7 @@ -
()
+
()
 
{{ _('Homepage') }} @@ -71,9 +72,22 @@ -

- Using pip at "" (Version , additional arguments: ) -

+
+ +
+ + Installation directory: ("--user" flag: , sudo: )
+ Virtual environment:
+ Additional Arguments: +
+
+