diff --git a/.gitignore b/.gitignore index 87413a783..1c96ad61b 100644 --- a/.gitignore +++ b/.gitignore @@ -4,7 +4,6 @@ *.pyc *.zip *.exe -*.gcode *.swp darwin-Cura-* win32-Cura-* @@ -21,3 +20,5 @@ dist pypy OctoPrint.egg-info *.orig + +*.codekit diff --git a/.travis.yml b/.travis.yml index 15d917c4a..df4eb121f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,8 +2,8 @@ language: python python: - - "2.7" +- "2.7" install: - - pip install -r requirements.txt +- pip install -e .[develop] script: - - nosetests \ No newline at end of file +- nosetests tests/ \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a5474c87..5a491e78c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # OctoPrint Changelog -## 1.2.0 - Unreleased +## 1.2.0 (Unreleased) ### New Features @@ -16,6 +16,28 @@ search * You can now define a folder (default: `~/.octoprint/watched`) to be watched for newly added GCODE (or -- if slicing support is enabled -- STL) files to automatically add. +* OctoPrint now has a [plugin system](http://docs.octoprint.org/en/devel/plugins/index.html) which allows extending its + core functionality. +* New type of API key: [App Session Keys](http://docs.octoprint.org/en/devel/api/apps.html) for trusted applications +* Printer Profiles: Printer properties like print volume, extruder offsets etc are now managed via Printer Profiles. A + connection to a printer will always have a printer profile associated. +* OctoPrint now supports `action:...` commands received via debug messages (`// action:...`) from the printer. Currently supported are + - `action:pause`: Pauses the current job in OctoPrint + - `action:resume`: Resumes the current job in OctoPrint + - `action:disconnect`: Disconnects OctoPrint from the printer + Plugins can add supported commands by [hooking](http://docs.octoprint.org/en/devel/plugins/hooks.html) into the + ``octoprint.comm.protocol.action`` hook +* Mousing over the webcam image in the control tab enables key control mode, allowing you to quickly move the axis of your + printer with your computer's keyboard ([#610](https://github.com/foosel/OctoPrint/pull/610)): + - arrow keys: X and Y axes + - W, S / PageUp, PageDown: Y axes + - Home: Home X and Y axes + - End: Home Z axes + - 1, 2, 3, 4: change step size used (0.1, 1, 10, 100mm) +* Controls for adjusting feed and flow rate factor added to Controls ([#362](https://github.com/foosel/OctoPrint/issues/362)) +* Custom controls now also support slider controls +* Custom controls now support a row layout +* Users can now define custom GCODE scripts to run upon starting/pausing/resuming/success/failure of a print ### Improvements @@ -26,14 +48,181 @@ * Start counting the layers at 1 instead of 0 in the GCODE viewer * Upgraded [Font Awesome](https://fortawesome.github.io/Font-Awesome/) to version 3.2.1 * Better error reporting for timelapse rendering and system commands -* Supports +* Custom control can now be defined so that they show a Confirm dialog with configurable text before executing + ([#532](https://github.com/foosel/OctoPrint/issues/532) and [#590](https://github.com/foosel/OctoPrint/pull/590)) +* Slicing has been greatly improved: + * It now allows for a definition of slicing profiles to use for slicing plus overrides which can be defined per slicing + job (defining overrides is not yet part of the UI but it's on the roadmap). + * A new slicing dialog has been added which allows (re-)slicing uploaded STL files (which are now displayed in the file list + as well). This dialog also allows specifying which action to take after slicing has been completed (none, selecting the + sliced GCODE for printing or starting to print it directly) + * Slicers themselves are integrated into the system via ``SlicingPlugins``. + * The [Cura integration](https://github.com/daid/Cura) has changed in such a way that OctoPrint now calls the + [CuraEngine](https://github.com/Ultimaker/CuraEngine) directly instead of depending on the full Cura installation. See + [the wiki](https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura) for instructions on how to change your setup to + accommodate the new integration. + * The "Slicing done" notification is now colored green ([#558](https://github.com/foosel/OctoPrint/issues/558)). + * The slicing API allows positioning the model to slice on the print bed (Note: this is not yet available in the UI). +* File management now supports STL files as first class citizens (including UI adjustments to allow management of + uploaded STL files including removal and reslicing) and also allows folders (not yet supported by UI). STL files + can be downloaded like GCODE files. +* Also interpret lines starting with "!!" as errors +* Added deletion of pyc files to the `python setup.py clean` command +* Settings now show a QRCode for the API Key ([#637](https://github.com/foosel/OctoPrint/pull/637)) +* Username in UI is no longer enclosed in scare quotes ([#595](https://github.com/foosel/OctoPrint/pull/595)) +* Username in login dialog is not automatically capitalized on mobile devices anymore ([#639](https://github.com/foosel/OctoPrint/pull/639)) +* "Slicing Done" and "Streaming Done" notifications now have a green background ([#558](https://github.com/foosel/OctoPrint/issues/558)) +* Files that are currently in use, be it for slicing, printing or whatever, are now tracked and can not be deleted as + long as they are in use +* Settings in UI get refreshed when opening settings dialog +* New event "SettingsUpdated" +* "Print time left" is now not displayed until it becomes somewhat stable. Display in web interface now also happens + in a fuzzy way instead of the format hh:mm:ss, to not suggest a high accuracy anymore where the can't be one. Additionally + OctoPrint will use data from prior prints to enhance the initial print time estimation. +* Added handler for uncaught exceptions to make sure those get logged, should make the logs even more useful for analysing + bug reports +* The server now tracks the modification date of the configuration file and reloads it prior to saving the config if + it has been changed during runtime by external editing, hence no config settings added manually while the server + was running should be overwritten anymore. +* Automatically hard-reload the UI if upon reconnecting to the server a new version is detected. +* Better handling of errors on the websocket - no more logging of the full stack trace to the log, only a warning + message for now. +* Daemonized OctoPrint now cleans up its pidfile when receiving a TERM signal ([#711](https://github.com/foosel/OctoPrint/issues/711)) +* Added serial types for OpenBSD ([#551](https://github.com/foosel/OctoPrint/pull/551)) +* Improved behaviour of terminal: + * Disabling autoscrolling now also stops cutting of the log while it's enabled, effectively preventing log lines from + being modified at all ([#735](https://github.com/foosel/OctoPrint/issues/735)) + * Applying filters displays ``[...]`` where lines where removed + * Added a link to scroll to the end of the terminal log (useful for when autoscroll is disabled) + * Added a link to select all current contents of the terminal log for easy copy-pasting + * Added a display of how many lines are displayed, how many are filtered and how many are available in total +* Frame rate for timelapses can now be configured per timelapse ([#782](https://github.com/foosel/OctoPrint/pull/782)) +* Added an option to specify the amount of encoding threads for FFMPEG ([#785](https://github.com/foosel/OctoPrint/pull/785)) +* "Disconnected" screen now is not shown directly after a close of the socket, instead the client first tries to + directly reconnect once, and only if that doesn't work displays the dialog. Should reduce short popups of the dialog + due to shaky network connections and/or weird browser behaviour when downloading things from the UI. +* Development dependencies can now be installed with ``pip -e .[develop]`` +* White and transparent colors ;) are supported for the navigation bar ([#789](https://github.com/foosel/OctoPrint/pull/789)) +* Drag-n-drop overlay for file uploads now uses the full available screen space, improving usability on high resolution + displays ([#187](https://github.com/foosel/OctoPrint/issues/187)) +* OctoPrint server should no longer hang when big changes in the system time happen, e.g. after first contact to an + NTP server on a Raspberry Pi image. Achieved through monkey patching Tornado with + [this PR](https://github.com/tornadoweb/tornado/pull/1290). ### Bug Fixes * [#435](https://github.com/foosel/OctoPrint/issues/435) - Always interpret negative duration (e.g. for print time left) as 0 +* [#633](https://github.com/foosel/OctoPrint/issues/633) - Correctly interpret temperature lines from multi extruder + setups under Smoothieware +* [#556](https://github.com/foosel/OctoPrint/issues/556) - Allow login of the same user from multiple browsers without + side effects +* [#680](https://github.com/foosel/OctoPrint/issues/680) - Don't accidentally include a newline from the MIME headers + in the parsed multipart data from file uploads +* [#709](https://github.com/foosel/OctoPrint/issues/709) - Properly initialize time estimation for SD card transfers too +* [#715](https://github.com/foosel/OctoPrint/issues/715) - Fixed an error where Event Triggers of type command caused + and exception to be raised due to a misnamed attribute in the code +* [#717](https://github.com/foosel/OctoPrint/issues/717) - Use ``shutil.move`` instead of ``os.rename`` to avoid cross + device renaming issues +* [#752](https://github.com/foosel/OctoPrint/pull/752) - Fix error in event handlers sending multiple gcode commands. +* [#780](https://github.com/foosel/OctoPrint/issues/780) - Always (re)set file position in SD files to 0 so that reprints + work correctly +* [#784](https://github.com/foosel/OctoPrint/pull/784) - Also include ``requirements.txt`` in files packed up for + ``python setup.py sdist`` +* [#330](https://github.com/foosel/OctoPrint/issues/330) - Ping pong sending to fix potential acknowledgement errors. + Also affects [#166](https://github.com/foosel/OctoPrint/issues/166), [#470](https://github.com/foosel/OctoPrint/issues/470) + and [#490](https://github.com/foosel/OctoPrint/issues/490). +* Various fixes of bugs in newly introduced features and improvements: + * [#625](https://github.com/foosel/OctoPrint/pull/625) - Newly added GCODE files were not being added to the analysis + queue + * [#664](https://github.com/foosel/OctoPrint/issues/664) - Fixed jog controls again + * [#677](https://github.com/foosel/OctoPrint/issues/677) - Fixed extruder offsets not being properly editable in + printer profiles + * [#683](https://github.com/foosel/OctoPrint/issues/683) - Fixed heated bed option not being properly displayed in + printer profiles + * [#685](https://github.com/foosel/OctoPrint/issues/685) - Quoted file name for Timelapse creation to not make + command hiccup on ``~`` in file name + * [#709](https://github.com/foosel/OctoPrint/issues/709) - Fixed file sending to SD card + * [#714](https://github.com/foosel/OctoPrint/issues/714) - Fixed type validation of printer profiles + * Heating up the heated bed (if present) was not properly configured in CuraEngine plugin + * [#720](https://github.com/foosel/OctoPrint/issues/720) - Fixed translation files not being properly copied over + during install + * [#724](https://github.com/foosel/OctoPrint/issues/724) - Fixed timelapse deletion for timelapses with non-ascii + characters in their name + * [#726](https://github.com/foosel/OctoPrint/issues/726) - Fixed ``babel_refresh`` command + * [#759](https://github.com/foosel/OctoPrint/pull/759) - Properly initialize counter for template plugins of type + "generic" + * [#775](https://github.com/foosel/OctoPrint/pull/775) - Error messages in javascript console show the proper name + of the objects + * [#795](https://github.com/foosel/OctoPrint/issues/795) - Allow adding slicing profiles for unconfigured slicers + * [#809](https://github.com/foosel/OctoPrint/issues/809) - Added proper form validation to printer profile editor +* Various fixes without tickets: + * GCODE viewer now doesn't stumble over completely extrusionless GCODE files + * Do not deliver the API key on settings API unless user has admin rights + * Don't hiccup on slic3r filament_diameter comments in GCODE generated for multi extruder setups + * Color code successful or failed print results directly in file list, not just after a reload + * Changing Timelapse post roll activates save button + * Timelapse post roll is loaded properly from config + * Handling of files on the printer's SD card contained in folders now works correctly + * Don't display a "Disconnected" screen when trying to download a timelapse in Firefox + * Fixed handling of SD card files in folders + * Fixed refreshing of timelapse file list upon finished rendering of a new one -## 1.1.0 - 2014-09-03 +([Commits](https://github.com/foosel/OctoPrint/compare/master...devel)) + +## 1.1.2 (Unreleased) + +### Improvements + +* Added deletion of `*.pyc` files to `python setup.py clean` command, should help tremendously when switching branches (backported + from [9e014eb](https://github.com/foosel/OctoPrint/commit/9e014eba1feffde11ed0601d9c911b8cac9f3fb0)) +* Increased default communication and connection timeouts +* [#706](https://github.com/foosel/OctoPrint/issues/706) - Do not truncate error reported from printer + +### Bug Fixes + +* [#634](https://github.com/foosel/OctoPrint/pull/634) - Fixed missing `branch` fields in version dicts generated + by versioneer +* [#679](https://github.com/foosel/OctoPrint/issues/679) - Fix error where API state is requested and printer is offline + (backport of [619fe9a](https://github.com/foosel/OctoPrint/commit/619fe9a0e78826bd1524b235a910156439bcb6d7)). +* [#719](https://github.com/foosel/OctoPrint/issues/719) - Properly center print bed in GCODE viewer +* [#780](https://github.com/foosel/OctoPrint/issues/780) - Always (re)set file position in SD files to 0 so that reprints + work correctly (backported from ``devel``) +* [#801](https://github.com/foosel/OctoPrint/issues/801) - Fixed setting of bed temperature offset +* [IRC] - Don't hiccup on slic3r ``filament_diameter`` comments generated for multi extruder setups +* [ML] - Fixed relative URL to SockJS endpoint, wasn't yet using the proper base url +* [unreported] & [#698](https://github.com/foosel/OctoPrint/issues/698) - Generated URLs now take X-Forwarded-Host header + sent by proxies into account for included host and port, also fixed [#698](https://github.com/foosel/OctoPrint/issues/698) + introduced by this +* Small fixes for timelapse creation: + - [#344](https://github.com/foosel/OctoPrint/issues/344) - Made timelapses capable of coping with missing captures in between by decrementing the image counter again if there + was an error fetching the latest image from the snapshot URL (backport of [1a7a468](https://github.com/foosel/OctoPrint/commit/1a7a468eb65fdf2a13b4c7a7723280e822c9c34b) + and [bf9d5ef](https://github.com/foosel/OctoPrint/commit/bf9d5efe43a1e57aacd8512125082ddca06b4efc)) + - [#693](https://github.com/foosel/OctoPrint/issues/693) - Try not to capture an image if image counter is still unset + - [unreported] Synchronize image counter decrementing as well as incrementing to prevent rare race conditions when generating the + image file names + +([Commits](https://github.com/foosel/OctoPrint/compare/1.1.1...master)) + +## 1.1.1 (2014-10-27) + +### Improvements + +* The API is now enabled by default and the API key -- if not yet set -- will be automatically generated on first + server start and written back into ``config.yaml`` +* Event subscriptions are now enabled by default (it was an accident that they weren't) +* Generate the key used for session hashing individually for each server instance +* Generate the salt used for hashing user passwords individually for each server instance + +### Bug Fixes + +* [#580](https://github.com/foosel/OctoPrint/issues/580) - Properly unset job data when instructed so by callers +* [#604](https://github.com/foosel/OctoPrint/issues/604) - Properly initialize settings basedir on server startup +* [IRC] Also allow downloading .g files via Tornado + +([Commits](https://github.com/foosel/OctoPrint/compare/1.1.0...1.1.1)) + +## 1.1.0 (2014-09-03) ### New Features @@ -103,6 +292,6 @@ ([Commits](https://github.com/foosel/OctoPrint/compare/1.0.0...1.1.0)) -## 1.0.0 +## 1.0.0 (2014-06-22) -First release with new versioning scheme. \ No newline at end of file +First release with new versioning scheme. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b31b719b8..4f4c46cf8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,17 +1,49 @@ Issues, Tickets, however you may call them ------------------------------------------ -- If you want to report a bug, **READ [How to file a bug report](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)!** Tickets will be automatically checked if they comply with the requirements outlined in that wiki node! Other then what's written in there you don't have to do anything special with your ticket. +Read the following short instructions **fully** and **follow them** if you want your ticket to be taken care of and not closed again directly! They are linked on top of every new issue form, so don't say nobody warned you afterwards. + +- **Read the [FAQ](https://github.com/foosel/OctoPrint/wiki/FAQ)** +- Always create **one ticket for one purpose**. So don't mix two or more feature requests, support requests, bugs etc into one ticket. If you do, your ticket will be closed! +- If you want to report a bug, **READ AND FOLLOW [How to file a bug report](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)!** Tickets will be automatically checked if they comply with the requirements outlined in that wiki node! Other then what's written in there (**and really EVERYTHING that is written in there!**) you don't have to do anything special with your ticket. Listen to what GitIssueBot might have to say to you! - If you want to post a **request** of any kind (feature request, documentation request, ...), **add [Request] to your issue's title!** -- If you need **support** with a problem of your installation (e.g. if you have problems getting the webcam to work), **add [Support] to your issue's title!** -- If you have a general **question**, **add [Question] to your issue's title!** -- If you have another reason for creating a ticket that doesn't fit any of the above categories, **add [Misc] to your issue's title!** +- If you need **support** with a problem of your installation (e.g. if you have problems getting the webcam to work) or have a general **question**, the issue tracker is not the right place. Consult the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741) instead! +- If you are a developer that wants to brainstorm a pull request or possible changes to the plugin system, **add [Brainstorming] to your issue's title!** (see below). +- If you have another reason for creating a ticket that doesn't fit any of the above categories, it's something better suited for the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741). + +Following these guidelines (**especially EVERYTHING mentioned in ["How to file a bug report"](https://github.com/foosel/OctoPrint/wiki/How-to-file-a-bug-report)**) is necessary so the tickets stay manageable - you are not the only one with an open issue, so please respect that you have to **play by the rules** so that your problem can be taken care of. Tickets not playing by the rules **will be closed without further investigation!**. Pull Requests ------------- -1. Please create all pull requests against the `devel` branch. -2. Create **one pull request per feature/bug fix**. -3. Create a custom branch for your feature/bug fix and use that as base for your pull request. Pull requests directly against your version of `devel` will be closed. -4. In your pull request's description, state what your pull request is doing, as in, what feature does it implement, what bug does it fix. +1. If you want to add a new feature to OctoPrint, **please always first consider if it wouldn't be better suited for a + plugin.** As a general rule of thumb, any feature that is only of interest to a small sub group should be moved into a + plugin. If the current plugin system doesn't allow you to implement your feature as a plugin, create a "Brainstorming" + ticket to get the discussion going how best to solve *this* in OctoPrint's plugin system - maybe that's the actual PR + you have been waiting for to contribute :) +2. If you plan to make **any large changes to the code or appearance, please open a "Brainstorming" ticket first** so that + we can determine if it's a good time for your specific pull request. It might be that I'm currently in the process of + making heavy changes to the code locations you'd target as well, or your approach doesn't fit the general "project + vision", and that would just cause unnecessary work and frustration for everyone or possibly get the PR rejected. +3. When adding code to OctoPrint, make sure you **follow the current coding style**. That means tabs instead of spaces in the + python files (yes, I know that this goes against PEP-8, I don't care) and space instead of tabs in the Javascript sources, + english language (that means code, variables, comments!), comments where necessary (tell why the code does something like + it does it, structure your code), following the general architecture. If your PR needs to make changes to the Stylesheets, + change the ``.less`` files from which the CSS is compiled. PRs that contain direct changes to the compiled + CSS will be closed. +4. **Test your changes thoroughly**. That also means testing with usage scenarios you don't normally use, e.g. if you only + use access control, test without and vice versa. If you only test with your printer, test with the virtual printer and + vice versa. State in your pull request how your tested your changes. +5. Please create all pull requests **against the `devel` branch**. +6. Create **one pull request per feature/bug fix**. +7. Create a **custom branch** for your feature/bug fix and use that as base for your pull request. Pull requests directly + against your version of `devel` will be closed. +7. In your pull request's description, **state what your pull request is doing**, as in, what feature does it implement, what + bug does it fix. The more thoroughly you explain your intent behind the PR here, the higher the chances it will get merged + fast. +History +------- + + * 2015-01-23: More guidelines for creating pull requests, support/questions redirected to Mailinglist/G+ community + * 2015-01-27: Added another explicit link to the FAQ diff --git a/MANIFEST.in b/MANIFEST.in index 8373cd4d2..82ddf50b3 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,4 +1,8 @@ recursive-include src/octoprint/static * recursive-include src/octoprint/templates * +recursive-include src/octoprint/plugins * +recursive-include src/octoprint/translations * include versioneer.py include src/octoprint/_version.py +include README.md +include requirements.txt diff --git a/README.md b/README.md index f219d1226..ac80de2e2 100644 --- a/README.md +++ b/README.md @@ -29,43 +29,45 @@ OctoPrint via `setup.py`: python setup.py install -You should also do this after pulling from the repository, since the dependencies might have changed. +You should also do this every time after pulling from the repository, since the dependencies might have changed. OctoPrint currently only supports Python 2.7. Usage ----- -From the source directory you can start the server via +Running the `setup.py` script installs the `octoprint` script in your Python installation's scripts folder +(which depending on whether you installed OctoPrint globally or into a virtual env will be on your `PATH` or not). The +following usage examples assume that said `octoprint` script is on your `PATH`. - ./run +You can start the server via + + octoprint By default it binds to all interfaces on port 5000 (so pointing your browser to `http://127.0.0.1:5000` will do the trick). If you want to change that, use the additional command line parameters `host` and `port`, which accept the host ip to bind to and the numeric port number respectively. If for example you want the server to only listen on the local interface on port 8080, the command line would be - ./run --host=127.0.0.1 --port=8080 + octoprint --host=127.0.0.1 --port=8080 Alternatively, the host and port on which to bind can be defined via the configuration. If you want to run OctoPrint as a daemon (only supported on Linux), use - ./run --daemon {start|stop|restart} [--pid PIDFILE] + octoprint --daemon {start|stop|restart} [--pid PIDFILE] If you do not supply a custom pidfile location via `--pid PIDFILE`, it will be created at `/tmp/octoprint.pid`. You can also specify the configfile or the base directory (for basing off the `uploads`, `timelapse` and `logs` folders), e.g.: - ./run --config /path/to/another/config.yaml --basedir /path/to/my/basedir + octoprint --config /path/to/another/config.yaml --basedir /path/to/my/basedir -See `run --help` for further information. - -Running the `setup.py` script also installs the `octoprint` startup script in your Python installation's scripts folder -(which depending on whether you installed OctoPrint globally or into a virtual env will be on your `PATH` or not). The -examples above also work with that startup script as it excepts the same parameters as `run`. +See `octoprint --help` for further information. +OctoPrint also ships with a `run` script in its source directory. You can also invoke that to start up the server, it +takes the same command line arguments as the `octoprint` script. Configuration ------------- @@ -75,4 +77,5 @@ which is located at `~/.octoprint` on Linux, at `%APPDATA%/OctoPrint` on Windows at `~/Library/Application Support/OctoPrint` on MacOS. A comprehensive overview of all available configuration settings can be found -[on the wiki](https://github.com/foosel/OctoPrint/wiki/Configuration). +[on the wiki](https://github.com/foosel/OctoPrint/wiki/Configuration). Please note that the most commonly used +configuration settings can also easily be edited from OctoPrint's settings dialog. diff --git a/babel.cfg b/babel.cfg index cbdd8fa5e..dcdd8e347 100644 --- a/babel.cfg +++ b/babel.cfg @@ -1,6 +1,8 @@ [python: src/octoprint/**.py] [jinja2: src/octoprint/templates/**.jinja2] +[jinja2: src/octoprint/plugins/**.jinja2] extensions=jinja2.ext.autoescape, jinja2.ext.with_ [javascript: src/octoprint/static/js/app/**.js] +[javascript: src/octoprint/plugins/**.js] extract_messages = gettext, ngettext diff --git a/docs/_static/theme_overrides.css b/docs/_static/theme_overrides.css new file mode 100644 index 000000000..36b55506a --- /dev/null +++ b/docs/_static/theme_overrides.css @@ -0,0 +1,38 @@ +/* override table width restrictions */ +.wy-table-responsive table td, .wy-table-responsive table th { + /* !important prevents the common CSS stylesheets from + overriding this as on RTD they are loaded after this stylesheet */ + white-space: normal !important; +} + +.wy-table-responsive { + overflow: visible !important; +} + +/* style headlink for code block captions like other headlinks */ +.code-block-caption .headerlink { + display: none; + visibility: hidden; + font-size: 14px; + font-family: inherit; + font-style: normal; + font-weight: normal; + line-height: 1; + -webkit-font-smoothing: antialiased; +} + +.code-block-caption:hover .headerlink { + display: inline-block; +} + +.code-block-caption .headerlink:after { + visibility: visible; + content: "\f0c1"; + font-family: FontAwesome; + display: inline-block; +} + +/* make whitespace visualization in code listings not appear on same vertical position as dashes */ +.highlight .w { + vertical-align: 10%; +} \ No newline at end of file diff --git a/docs/api/apps.rst b/docs/api/apps.rst new file mode 100644 index 000000000..46ee73c8c --- /dev/null +++ b/docs/api/apps.rst @@ -0,0 +1,170 @@ +.. _sec-api-apps: + +**** +Apps +**** + +.. contents:: + +.. _sec-api-apps-sessionkey: + +Session Keys +============ + +OctoPrint offers a special API key type for apps to use, the so called App Session Key. These keys have a time based +validity and are generated by OctoPrint for requesting apps. + +Obtaining those keys is based on a handshake procedure backed by cryptographic signatures using RSA. OctoPrint needs to +be aware of apps and their associated public keys (this can be achieved either via entries in ``config.yaml`` or by +installing app specific plugins which implement the ``AppPlugin`` type). + +Apps can be registered within OctoPrint via ``config.yaml`` by adding them to the ``api`` > ``apps`` section, using the +application's id concatenated with its version as key, with the public key provided as item ``pubkey`` (stripped of the +``BEGIN RSA PUBLIC KEY`` and ``END RSA PUBLIC KEY`` separators and also newlines) and optionally also whether the app is +enabled or not (defaults to enabled, so can be left out if it's not to be set to disabled explicitly). + +Example: + +.. sourcecode:: yaml + + api: + apps: + "com.example.my_octoprint_app:0.9": + pubkey: MEgCQQDYkr5Fv/YXK5ZL1uwRN4A61IagZaYLGqJ5JJGFo8wDrmpAMRqE9kK4+5hIDblC5DzfEr5oP7OA3tRO48Rf5yInAgMBAAE= + enabled: false + "com.example.my_octoprint_app:1.0": + pubkey: MEgCQQCIWfi7Nc8bcnfZJJtA6a4RyMC+sKBlMOb25OVNNB4L2v0TiGO72jVKR4osvb4oztlbRW5GkdiY0T2LJcfDYvkJAgMBAAE= + +In the example, the app ``com.example.my_octoprint_app`` in version 0.9 has been disabled (e.g. due to the key having +leaked) whereas version 1.0 is fully registered with OctoPrint and may verify app session keys. + + +.. _sec-api-apps-sessionkey-workflow: + +Workflow +-------- + +Apps perform the handshake by first requesting a temporary key with very limited validity, +then sending a message back to OctoPrint containing their id, version, the temporary key and a signature created with their +private key over these three pieces of data. OctoPrint then tries to verify the signature and if successful unlocks the +key to be used as a fully recognized API key. + +For performing the handshake a special API exists within OctoPrint for which no API key is needed which is described below. + +.. _sec-api-apps-sessionkey-get: + +Obtaining a temporary session key +--------------------------------- + +.. http:get:: /apps/auth + + Retrieve a temporary session key with a minimum validity. It can only be used as a proper API key after having been + :ref:`verified `. + + Returns the temporary session key and the timestamp until it's valid. + + **Example**: + + .. sourcecode:: http + + GET /apps/auth HTTP/1.1 + Host: example.com + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "unverifiedKey": "F43A844750F74AD080FE9F438D47B33C", + "validUntil": 1416220357.011 + } + + :statuscode 200: No error + +.. _sec-api-apps-sessionkey-verify: + +Verifying a temporary session key +--------------------------------- + +.. http:post:: /apps/auth + + Verify a formerly :ref:`retrieved ` temporary session key by providing credentials and a + cryptographic signature over these credentials and the temporary key. + + Returns the now verified session key and the new validity. + + **Example**: + + .. sourcecode:: http + + POST /apps/auth HTTP/1.1 + Host: example.com + Content-Type: application/json + + { + "appid": "com.example.my_octoprint_app", + "appversion": "1.0", + "key": "F43A844750F74AD080FE9F438D47B33C", + "_sig": "LGVCiolQWDc4AVn1DOcWljY0cFQxWF4pldVveUjjmL9JhiL0LnCKBbGwZ/CwKBWswFAxPaxQ0kDusVdOmCUa/w==" + } + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "key": "F43A844750F74AD080FE9F438D47B33C", + "validUntil": 1416227497.011 + } + +.. _sec-api-apps-sessionkey-signature: + +Creating the signature +---------------------- + +The signature is created by concatenating the ``appid``, ``appversion`` and ``key`` fields, separated by a ``:`` (colon), +signing the result with the app's private key using SHA-1 and then BASE64-encoding the result, stripping newlines. + +Example for signature generation using Python and the `Python RSA library `_: + +.. sourcecode:: python + + import base64 + import rsa + + appid = "com.example.my_octoprint_app" + version = "1.0" + unverified_key = "F43A844750F74AD080FE9F438D47B33C" + message_to_sign = appid + ":" + version + ":" + unverified_key + // => "com.example.my_octoprint_app:1.0:F43A844750F74AD080FE9F438D47B33C" + + private_key = rsa.PrivateKey.load_pkcs1("...") + signature = base64.encodestring(rsa.sign(message_to_sign, private_key, "SHA-1")).replace("\n", "") + // => "LGVCiolQWDc4AVn1DOcWljY0cFQxWF4pldVveUjjmL9JhiL0LnCKBbGwZ/CwKBWswFAxPaxQ0kDusVdOmCUa/w==" + + +.. _sec-api-apps-sessionkey-testing: + +Testing your implementation +--------------------------- + +If you want to use app session keys, here is the key pair with which the above examples were created, in order for you +to verify your signature implementation:: + + -----BEGIN RSA PRIVATE KEY----- + MIIBPQIBAAJBAIhZ+Ls1zxtyd9kkm0DprhHIwL6woGUw5vbk5U00Hgva/ROIY7va + NUpHiiy9vijO2VtFbkaR2JjRPYslx8Ni+QkCAwEAAQJARK4lFo+FEcs3yR2iQjEy + p+yaAbNQJ4hZXlVvltLAYICzOM3kyKx53/eKU59NjskLz9q6QxfleymYPWAgl4NW + fQIjAJVH8MjwNcaAquTM9z2OiFi3OC8WgaKOi5W/T+r2+B70wG8CHwDp08dqOZ/u + xcBiy4Wzpcme9bckqoVuS3gWMm+YqgcCIwCMFU07kkY0NyumtzxPdIA4F/7OGSWf + IHqWFEfvasAddHlbAh8A5UgkB3Zf7Bt+7aFSBnlvve6FWm/XDPL12xYztYgrAiIa + W3miN6FjIm+8TDowrk+nyYXG2GZefeY7QXOjYr6tlDn0 + -----END RSA PRIVATE KEY----- + + -----BEGIN RSA PUBLIC KEY----- + MEgCQQCIWfi7Nc8bcnfZJJtA6a4RyMC+sKBlMOb25OVNNB4L2v0TiGO72jVKR4os + vb4oztlbRW5GkdiY0T2LJcfDYvkJAgMBAAE= + -----END RSA PUBLIC KEY----- + diff --git a/docs/api/connection.rst b/docs/api/connection.rst index aab57fc44..49904369d 100644 --- a/docs/api/connection.rst +++ b/docs/api/connection.rst @@ -33,13 +33,16 @@ Get connection settings "current": { "state": "Operational", "port": "/dev/ttyACM0", - "baudrate": 250000 + "baudrate": 250000, + "printerProfile": "_default" }, "options": { "ports": ["/dev/ttyACM0", "VIRTUAL"], "baudrates": [250000, 230400, 115200, 57600, 38400, 19200, 9600], + "printerProfiles": [{"name": "Default", id: "_default"}], "portPreference": "/dev/ttyACM0", "baudratePreference": 250000, + "printerProfilePreference": "_default", "autoconnect": true } } @@ -62,6 +65,8 @@ Issue a connection command no preference is available auto detection will be attempted. * ``baudrate``: Optional, specific baudrate to connect with. If not set the current ``baudratePreference`` will be used, or if no preference is available auto detection will be attempted. + * ``printerProfile`` Optional, specific printer profile to use for connection. If not set the current default printer + profile will be used. * ``save``: Optional, whether to save the request's ``port`` and ``baudrate`` settings as new preferences. Defaults to ``false`` if not set. * ``autoconnect``: Optional, whether to automatically connect to the printer on OctoPrint's startup in the future. @@ -83,6 +88,7 @@ Issue a connection command "command": "connect", "port": "/dev/ttyACM0", "baudrate": 115200, + "printerProfile": "my_printer_profile", "save": true, "autoconnect": true } @@ -115,6 +121,8 @@ Issue a connection command :json number baudrate: ``connect`` command: The baudrate to connect with. If left out either the existing ``baudratePreference`` will be used, or if that is not available OctoPrint will attempt autodetection. Must be part of the available baudrates. + :json string printerProfile: ``connect`` command: The id of the printer profile to use for the connection. If left out the current + default printer profile will be used. Must be part of the available printer profiles. :json boolean save: ``connect`` command: Whether to save the supplied connection settings as the new preference. Defaults to ``false`` if not set. :json boolean autoconnect: ``connect`` command: Whether to attempt to automatically connect to the printer on server diff --git a/docs/api/fileops.rst b/docs/api/fileops.rst index baf3440de..4cf2e33e6 100644 --- a/docs/api/fileops.rst +++ b/docs/api/fileops.rst @@ -304,7 +304,34 @@ Issue a file command is not operational when this parameter is present and set to ``true``, the request will fail with a response of ``409 Conflict``. - Upon success, a status code of :http:statuscode:`204` and an empty body is returned. + slice + Slices an STL file into GCODE. Note that this is an asynchronous operation that will take place in the background + after the response has been sent back to the client. Additional parameters are: + + * ``slicer``: The slicing engine to use, defaults to ``cura`` if not set, which is also the only supported slicer right now. + * ``gcode``: Name of the GCODE file to generated, in the same location as the STL file. Defaults to the STL file name + with extension ``.gco`` if not set. + * ``position``: Position of the object-to-slice's center on the print bed. A dictionary containing both ``x`` and ``y`` + coordinate in mm is expected + * ``printerProfile``: Name of the printer profile to use, if not set the default printer profile will be used. + * ``profile``: Name of the slicing profile to use, if not set the default slicing profile of the slicer will be used. + * ``profile.*``: Override parameters, the ``profile.`` prefix will be stripped and the matching profile key will + be overridden with the supplied value. Use this if you want to specify things that change often like a different + temperature, filament diameter or infill percentage. Profile keys are slicer specific. + * ``select``: Optional, if set to ``true`` the file be selected for printing right after the slicing has finished. If the + printer is not operational or already printing when this parameter is present and set to ``true``, the request will + fail with a response of ``409 Conflict`` + * ``print``: Optional, if set to ``true`` the file be selected and start printing right after the slicing has finished. + If the printer is not operational or already printing when this parameter is present and set to ``true``, the request + will fail with a response of ``409 Conflict``. Note that if this parameter is set, the parameter ``select`` does not + need to be set, it is automatically assumed to be ``true`` too, otherwise no printing would be possible. + + If consecutive slicing calls are made targeting the same GCODE filename (that also holds true if the default is used), + the slicing job already running in the background will be cancelled before the new one is started. Note that this will + also mean that if it was supposed to be directly selected and start printing after the slicing finished, this will not + take place anymore and whether this will happen with the new sliced file depends entirely on the new request! + + Upon success, a status code of :http:statuscode:`204` and an empty body is returned, unless specified otherwise. **Example Select Request** @@ -324,16 +351,66 @@ Issue a file command HTTP/1.1 204 No Content - :param target: The target location on which to delete the file, either ``local`` (for OctoPrint's ``uploads`` - folder) or ``sdcard`` for the printer's SD card (if available) - :param filename: The filename of the file for which to issue the command - :json string command: The command to issue for the file, currently only ``select`` is supported - :json boolean print: ``select`` command: Optional, whether to start printing the file directly after selection, - defaults to ``false``. - :statuscode 200: No error - :statuscode 400: If the `command` is unknown or the request is otherwise invalid - :statuscode 404: If `target` is neither ``local`` nor ``sdcard`` or the requested file was not found - :statuscode 409: If a selected file is supposed to start printing directly but the printer is not operational. + **Example Slice Request** + + .. sourcecode:: http + + POST /api/files/local/some_model.stl HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "slice", + "slicer": "cura", + "gcode": "some_model.first_try.gcode", + "printerProfile": "my_custom_reprap", + "profile": "high_quality", + "profile.infill": 75, + "profile.fill_density": 15, + "position": {"x": 100, "y": 100}, + "print": true + } + + .. sourcecode:: http + + HTTP/1.1 202 Accepted + Content-Type: application/json + + { + "origin": "local", + "name": "some_model.first_try.gcode", + "refs": { + "download": "http://example.com/downloads/files/local/some_model.first_try.gcode", + "resource": "http://example.com/api/files/local/some_model.first_try.gcode" + } + } + + + :param target: The target location on which to delete the file, either ``local`` (for OctoPrint's ``uploads`` + folder) or ``sdcard`` for the printer's SD card (if available) + :param filename: The filename of the file for which to issue the command + :json string command: The command to issue for the file, currently only ``select`` is supported + :json boolean print: ``select`` and ``slice`` command: Optional, whether to start printing the file directly after selection + or slicing, defaults to ``false``. + :json string slicer: ``slice`` command: The slicer to use, defaults to the default slicer. + :json string gcode: ``slice`` command: The name of the gcode file to create, defaults to the targeted stl's file name + with its extension changed to ``.gco`` (e.g. "test.stl" will be sliced to "test.gco" if not specified + otherwise) + :json string profile: ``slice`` command: The slicing profile to use, defaults to the selected slicer's default profile. + :json string profile.*: ``slice`` command: Overrides for the selected slicing profile, e.g. to specify a different temperature + or filament diameter. + :json string printerProfile: ``slice`` command: The printer profile to use, defaults to the default printer profile. + :json boolean select: ``slice`` command: Optional, whether to select the file for printing directly after slicing, + defaults to ``false`` + :statuscode 200: No error for a ``select`` command. + :statuscode 202: No error for a ``slice`` command. + :statuscode 400: If the ``command`` is unknown or the request is otherwise invalid + :statuscode 415: If a ``slice`` command was issued against something other than an STL file. + :statuscode 404: If `target` is neither ``local`` nor ``sdcard`` or the requested file was not found + :statuscode 409: If a selected file is supposed to start printing directly but the printer is not operational or + if a file to be sliced is supposed to be selected or start printing directly but the printer + is not operational or already printing. .. _sec-api-fileops-delete: diff --git a/docs/api/general.rst b/docs/api/general.rst index e7c229191..9e6a67fc7 100644 --- a/docs/api/general.rst +++ b/docs/api/general.rst @@ -12,8 +12,8 @@ Authorization ============= OctoPrint's API expects an API key to be supplied with each request. This API key can be either the globally -configured one or a user specific one if "Access Control" is enabled. Users are able to generate and revoke their -custom API key via the "Change password" dialog. +configured one, a user specific one if "Access Control" is enabled or an ref:`App Session Key `. +Users are able to generate and revoke their custom API key via the "Change password" dialog. The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g. diff --git a/docs/api/index.rst b/docs/api/index.rst index 662ce4cb1..f0295e0eb 100644 --- a/docs/api/index.rst +++ b/docs/api/index.rst @@ -1,18 +1,21 @@ .. _sec-api: -################# -API Documentation -################# +######## +REST API +######## .. toctree:: :maxdepth: 2 general.rst version.rst + apps.rst fileops.rst connection.rst printer.rst + printerprofiles.rst job.rst logs.rst + slicing.rst push.rst datamodel.rst diff --git a/docs/api/printer.rst b/docs/api/printer.rst index f80ff6a8a..480722494 100644 --- a/docs/api/printer.rst +++ b/docs/api/printer.rst @@ -199,8 +199,13 @@ Issue a print head command * ``axes``: A list of axes which to home, valid values are one or more of ``x``, ``y``, ``z``. - All of these commands may only be sent if the printer is currently operational and not printing. Otherwise a - :http:statuscode:`409` is returned. + feedrate + Changes the feedrate factor to apply to the movement's of the axes. + + * ``factor``: The new factor, percentage as integer or float (percentage divided by 100) between 50 and 200%. + + All of these commands except ``feedrate`` may only be sent if the printer is currently operational and not printing. + Otherwise a :http:statuscode:`409` is returned. Upon success, a status code of :http:statuscode:`204` and an empty body is returned. @@ -246,13 +251,34 @@ Issue a print head command HTTP/1.1 204 No Content + **Example feed rate request** + + Set the feed rate factor to 105%. + + .. sourcecode:: http + + POST /api/printer/printhead HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "feedrate", + "factor": 105 + } + + .. sourcecode:: http + + HTTP/1.1 204 No Content + :json string command: The command to issue, either ``jog`` or ``home``. :json number x: ``jog`` command: The amount to travel on the X axis in mm. :json number y: ``jog`` command: The amount to travel on the Y axis in mm. :json number z: ``jog`` command: The amount to travel on the Z axis in mm. :json array axes: ``home`` command: The axes which to home, valid values are one or more of ``x``, ``y`` and ``z``. + :json number factor: ``feedrate`` command: The factor to apply to the feed rate, percentage between 50 and 200% as integer or float. :statuscode 204: No error - :statuscode 400: Invalid axis specified, invalid value for travel amount for a jog command or otherwise invalid + :statuscode 400: Invalid axis specified, invalid value for travel amount for a jog command or factor for feed rate or otherwise invalid request. :statuscode 409: If the printer is not operational or currently printing. @@ -288,6 +314,10 @@ Issue a tool command * ``amount``: The amount of filament to extrude in mm. May be negative to retract. + flowrate + Changes the flow rate factor to apply to extrusion of the tool. + + * ``factor``: The new factor, percentage as integer or float (percentage divided by 100) between 75 and 125%. All of these commands may only be sent if the printer is currently operational and -- in case of ``select`` and ``extrude`` -- not printing. Otherwise a :http:statuscode:`409` is returned. @@ -400,14 +430,35 @@ Issue a tool command HTTP/1.1 204 No Content + **Example flow rate request** + + Set the flow rate factor to 95%. + + .. sourcecode:: http + + POST /api/printer/tool HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "flowrate", + "factor": 95 + } + + .. sourcecode:: http + + HTTP/1.1 204 No Content + :json string command: The command to issue, either ``target``, ``offset``, ``select`` or ``extrude``. :json object targets: ``target`` command: The target temperatures to set. Valid properties have to match the format ``tool{n}``. :json object offsets: ``offset`` command: The offset temperature to set. Valid properties have to match the format ``tool{n}``. :json object tool: ``select`` command: The tool to select, value has to match the format ``tool{n}``. :json object amount: ``extrude`` command: The amount of filament to extrude from the currently selected tool. + :json number factor: ``flowrate`` command: The factor to apply to the flow rate, percentage between 75 and 125% as integer or float. :statuscode 204: No error :statuscode 400: If ``targets`` or ``offsets`` contains a property or ``tool`` contains a value not matching the format - ``tool{n}``, the target/offset temperature or extrusion amount is not a valid number or outside of + ``tool{n}``, the target/offset temperature, extrusion amount or flow rate factor is not a valid number or outside of the supported range, or if the request is otherwise invalid. :statuscode 409: If the printer is not operational or -- in case of ``select`` or ``extrude`` -- currently printing. @@ -755,6 +806,61 @@ Retrieve the current SD state :statuscode 200: No error :statuscode 404: If SD support has been disabled in OctoPrint's config. +.. _sec-api-printer-arbcommand: + +Send an arbitrary command to the printer +======================================== + +.. http:post:: /api/printer/command + + Sends any command to the printer via the serial interface. Should be used with some care as some commands can interfere with + or even stop a running print job. + + Expects a :ref:`Arbitrary Command Request ` as the request's body. + + If successful returns a :http:statuscode:`204` and an empty body. + + **Example for sending a single command** + + .. sourcecode:: http + + POST /api/printer/command HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "M106" + } + + .. sourcecode:: http + + HTTP/1.1 204 No Content + + **Example for sending multiple commands** + + .. sourcecode:: http + + POST /api/printer/command HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "commands": [ + "M18", + "M106 S0" + ] + } + + .. sourcecode:: http + + HTTP/1.1 204 No Content + + :json string command: Single command to send to the printer, mutually exclusive with ``commands``. + :json string commands: List of commands to send to the printer, mutually exclusive with ``command``. + :statuscode 204: No error + .. _sec-api-printer-datamodel: Datamodel @@ -783,7 +889,7 @@ Full State Response - The printer's sd state data * - ``state`` - 0..1 - - :ref:`Printer State ` + - :ref:`Printer State ` - The printer's general state .. _sec-api-printer-datamodel-temps: @@ -831,3 +937,36 @@ SD State - Boolean - Whether the SD card has been initialized (``true``) or not (``false``). +.. _sec-api-printer-datamodel-arbcommand: + +Arbitrary Command Request +------------------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``command`` + - 0..1 + - String + - Single command to send to the printer, mutually exclusive with ``commands`` and ``script``. + * - ``commands`` + - 0..* + - Array of String + - Multiple commands to send to the printer (in the given order), mutually exclusive with ``command`` and ``script``. + * - ``script`` + - 0..* + - String + - Name of the GCODE script template to send to the printer, mutually exclusive with ``command`` and ``commands``. + * - ``parameters`` + - 0..1 + - Map of key value pairs + - Key value pairs of parameters to replace in sent commands/provide to the script renderer + * - ``context`` + - 0..1 + - Map of key value pairs + - (only if ``script`` is set) additional template variables to provide to the script renderer diff --git a/docs/api/printerprofiles.rst b/docs/api/printerprofiles.rst new file mode 100644 index 000000000..b529b9d2e --- /dev/null +++ b/docs/api/printerprofiles.rst @@ -0,0 +1,190 @@ +.. _sec-api-printerprofiles: + +************************** +Printer profile operations +************************** + +.. contents:: + +OctoPrint allows the management of Printer profiles that define a printer's physical properties (such as print volume, +whether a heated bed is available, maximum speeds on its axes etc). The data stored within these profiles is used +for both slicing and gcode visualization. + +.. _sec-api-printerprofiles-retrieve: + +Retrieve all printer profiles +============================= + +.. http:get:: /api/printerprofiles + +.. _sec-api-printerprofiles-add: + +Add a new printer profile +========================= + +.. http:post:: /api/printerprofiles + +.. _sec-api-printerporfiles-update: + +Update an existing printer profile +================================== + +.. http:patch:: /api/printerprofiles/(string:profile) + +.. _sec-api-printerprofiles-delete: + +Remove an existing printer profile +================================== + +.. http:delete:: /api/printerprofiles/(string:profile) + +.. _sec-api-printerprofiles-datamodel: + +Datamodel +========= + +.. _sec-api-printerprofiles-datamodel-profilelist: + +Profile list +------------ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``profiles`` + - 1 + - Object + - Collection of all printer profiles available in the system + * - ``profiles.`` + - 0..1 + - :ref:`Profile ` + - Information about a profile stored in the system. + +.. _sec-api-printerprofiles-datamodel-update: + +Add or update request +--------------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``profiles`` + - 1 + - :ref:`Profile ` + - Information about the profile being added/updated. For adding new profiles, all fields must be populated. For updating + and existing profile, only the values to be overwritten need to be supplied. + +.. _sec-api-printerprofiles-datamodel-profile: + +Profile +------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``id`` + - 0..1 + - ``string`` + - Identifier of the profile. Will always be + returned in responses but can be left out of save/update requests. + * - ``name`` + - 0..1 + - ``string`` + - Display name of the profile. Will always be + returned in responses but can be left out of save/update requests. + * - ``color`` + - 0..1 + - ``string`` + - The color to associate with this profile (used in the UI's title bar). Valid values are "default", "red", "orange", + "yellow", "green", "blue", "black". Will always be + returned in responses but can be left out of save/update requests. + * - ``model`` + - 0..1 + - ``string`` + - Printer model of the profile. Will always be + returned in responses but can be left out of save/update requests. + * - ``default`` + - 0..1 + - ``boolean`` + - Whether this is the default profile to be used with new connections (``true``) or not (``false``). Will always be + returned in responses but can be left out of save/update requests. + * - ``current`` + - 0..1 + - ``boolean`` + - Whether this is the profile currently active. Will always be returned in responses but ignored in save/update + requests. + * - ``resource`` + - 0..1 + - ``URL`` + - Resource URL of the profile, will always be returned in responses but can be left out of save/update requests. + * - ``volume`` + - 0..1 + - Object + - The print volume, will always be returned in responses but can be left out of save/update requests. + * - ``volume.formFactor`` + - 0..1 + - ``string`` + - The form factor of the printer's bed, valid values are "rectangular" and "circular" + * - ``volume.width`` + - 0..1 + - ``float`` + - The width of the print volume + * - ``volume.depth`` + - 0..1 + - ``float`` + - The depth of the print volume + * - ``volume.height`` + - 0..1 + - ``float`` + - The height of the print volume + * - ``heatedBed`` + - 0..1 + - ``boolean`` + - Whether the printer has a heated bed (``true``) or not (``false``) + * - ``axes`` + - 0..1 + - Object + - Description of the printer's axes properties, one entry each for ``x``, ``y``, ``z`` and ``e`` holding maxium speed + and whether this axis is inverted or not. + * - ``axes.{axis}.speed`` + - 0..1 + - ``int`` + - Maximum speed of the axis in mm/s. + * - ``axes.{axis}.inverted`` + - 0..1 + - ``boolean`` + - Whether the axis is inverted or not. + * - ``extruder`` + - 0..1 + - Object + - Information about the printer's extruders + * - ``extruder.nozzleDiameter`` + - 0..1 + - ``float`` + - The diameter of the printer's nozzle(s) in mm. + * - ``extruder.count`` + - 0..1 + - ``int`` + - Count of extruders on the printer (defaults to 1) + * - ``extruder.offsets`` + - 0..1 + - Array of ``float`` tuples + - Tuple of (x, y) values describing the offsets of the other extruders relative to the first extruder. E.g. for a + printer with two extruders, if the second extruder is offset by 20mm in the X and 25mm in the Y direction, this + array will read ``[ [0.0, 0.0], [20.0, 25.0] ]`` + diff --git a/docs/api/push.rst b/docs/api/push.rst index fab32b0f1..cf46eb2da 100644 --- a/docs/api/push.rst +++ b/docs/api/push.rst @@ -35,6 +35,9 @@ following message types are currently available for usage by 3rd party clients: payload data model as ``current``, see :ref:`below `. * ``event``: Events triggered within OctoPrint, such as e.g. ``PrintFailed`` or ``MovieRenderDone``. Payload is the event type and payload, see :ref:`below `. Sent when an event is triggered internally. + * ``slicingProgress``: Progress updates from an active slicing background job, payload contains information about the + model being sliced, the target file, the slicer being used and the progress as a percentage. + See :ref:`the payload data model `. Clients must ignore any unknown messages. @@ -112,3 +115,41 @@ Datamodel - 1 - Object - Payload associated with the event + +.. _sec-api-push-datamodel-slicingprogress: + +``slicingProgress`` payload +--------------------------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``slicer`` + - 1 + - String + - Name of the slicer used + * - ``source_location`` + - 1 + - String + - Location of the source file being sliced, at the moment either ``local`` or ``sdcard`` + * - ``source_path`` + - 1 + - String + - Path of the source file being sliced (e.g. an STL file) + * - ``dest_location`` + - 1 + - String + - Location of the destination file being created, at the moment either ``local`` or ``sdcard`` + * - ``dest_path`` + - 1 + - String + - Path of the destination file being sliced (e.g. a GCODE file) + * - ``progress`` + - 1 + - Number (Float) + - Percentage of slicing job already completed diff --git a/docs/api/slicing.rst b/docs/api/slicing.rst new file mode 100644 index 000000000..7edabe8fb --- /dev/null +++ b/docs/api/slicing.rst @@ -0,0 +1,336 @@ +.. _sec-api-slicing: + +******* +Slicing +******* + +.. warning:: + + The interface documented here is the status quo that might be changed while the interfaces are streamlined for + a more general consumption. If you happen to want to develop against it, you should drop me an email to make sure I can give you a heads-up when + something changes. + +.. contents:: + +The Slicing API on one hand offers methods for managing slicing profiles stored within OctoPrint, on the other hand +it will be extended in the future to also allow for multi extruder slicing (which currently is not possible with the +``slice`` command of the :ref:`File operations API ` and other things. + +.. _sec-api-slicing-listall: + +List All Slicers and Slicing Profiles +===================================== + +.. http:get:: /api/slicing + + Returns a list of all available slicing profiles for all registered slicers in the system. + + Returns a :http:statuscode:`200` response with a :ref:`Slicer list ` + as the body upon successful completion. + + **Example** + + .. sourcecode:: http + + GET /api/slicing/profiles HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "cura": { + "key": "cura", + "displayName": "CuraEngine", + "default": true, + "profiles": { + "high_quality": { + "key": "high_quality", + "displayName": "High Quality", + "default": false, + "resource": "http://example.com/api/slicing/cura/profiles/high_quality" + }, + "medium_quality": { + "key": "medium_quality", + "displayName": "Medium Quality", + "default": true, + "resource": "http://example.com/api/slicing/cura/profiles/medium_quality" + }, + ... + } + }, + ... + } + + :statuscode 200: No error + +.. _sec-api-slicing-list: + +List Slicing Profiles of a Specific Slicer +========================================== + +.. http:get:: /api/slicing/(string:slicer)/profiles + + Returns a list of all available slicing profiles for the requested slicer. + + Returns a :http:statuscode:`200` response with a :ref:`Profile list ` + as the body upon successful completion. + + **Example** + + .. sourcecode:: http + + GET /api/slicing/cura/profiles HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "high_quality": { + "key": "high_quality", + "displayName": "High Quality", + "default": false, + "resource": "http://example.com/api/slicing/cura/profiles/high_quality" + }, + "medium_quality": { + "key": "medium_quality", + "displayName": "Medium Quality", + "default": true, + "resource": "http://example.com/api/slicing/cura/profiles/medium_quality" + }, + ... + } + + :param slicer: The identifying key of the slicer for which to list the available profiles. + :statuscode 200: No error + :statuscode 404: If the ``slicer`` was unknown to the system. + +.. _sec-api-slicing-listspecific: + +Retrieve Specific Profile +========================= + +.. http:get:: /api/slicing/(string:slicer)/profiles/(string:key) + + Retrieves the specified profile from the system. + + Returns a :http:statuscode:`200` response with a :ref:`full Profile ` + as the body upon successful completion. + + **Example** + + .. sourcecode:: http + + GET /api/slicing/cura/profiles/quick_test HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + + .. sourcecode:: http + + HTTP/1.1 200 OK + Content-Type: application/json + + { + "displayName": "Just a test", + "description": "This is just a test", + "resource": "http://example.com/api/slicing/cura/profiles/quick_test", + "data": { + "bottom_layer_speed": 20.0, + "bottom_thickness": 0.3, + "brim_line_count": 20, + "cool_head_lift": false, + "cool_min_feedrate": 10.0, + "cool_min_layer_time": 5.0, + ... + } + } + + :param slicer: The identifying key of the slicer for which to list the available profiles. + :param name: The identifying key of the profile to retrieve + :statuscode 200: No error + :statuscode 404: If the ``slicer`` or the profile was unknown to the system. + +.. _sec-api-slicing-add: + +Add Slicing Profile +=================== + +.. http:put:: /api/slicing/(string:slicer)/profiles/(string:key) + + Adds a new slicing profile for the given ``slicer`` to the system. If the profile identified by ``key`` already exists, + it will be overwritten. + + Expects a :ref:`Profile ` as body. + + Returns a :http:statuscode:`201` and an :ref:`abridged Profile ` in the body + upon successful completion. + + **Example** + + .. sourcecode:: http + + PUT /api/slicing/cura/profiles/quick_test HTTP/1.1 + Host: example.com + X-Api-Key: abcdef... + Content-Type: application/json + + { + "displayName": "Just a test", + "description": "This is just a test to show how to create a cura profile with a different layer height and skirt count", + "data": { + "layer_height": 0.2, + "skirt_line_count": 3 + } + } + + + .. sourcecode:: http + + HTTP/1.1 201 Created + Content-Type: application/json + Location: http://example.com/api/slicing/cura/profiles/quick_test + + { + "displayName": "Just a test", + "description": "This is just a test to show how to create a cura profile with a different layer height and skirt count", + "resource": "http://example.com/api/slicing/cura/profiles/quick_test" + } + + :param slicer: The identifying key of the slicer for which to add the profile + :param key: The identifying key of the new profile + :statuscode 201: No error + :statuscode 404: If the ``slicer`` was unknown to the system. + +.. _sec-api-slicing-delete: + +Delete Slicing Profile +====================== + +.. http:delete:: /api/slicing/(string:slicer)/profiles/(string:key) + + Delete the slicing profile identified by ``key`` for the slicer ``slicer``. + + :param slicer: The identifying key of the slicer for which to delete the profile + :param key: The identifying key of the profile to delete + :statuscode 204: No error + :statuscode 404: If the ``slicer`` was unknown to the system. + +.. _sec-api-slicing-datamodel: + +Datamodel +========= + +.. _sec-api-slicing-datamodel-slicerlist: + +Slicer list +----------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ```` + - 0..* + - :ref:`Slicer ` + - Information about a slicer registered in the system, incl. stored profiles without ``data``. + +.. _sec-api-slicing-datamodel-slicer: + +Slicer +------ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``key`` + - 1 + - ``string`` + - Identifier of the slicer + * - ``displayName`` + - 0..1 + - ``string`` + - Display name of the slicer + * - ``default`` + - 1 + - ``boolean`` + - Whether the slicer is the default slicer to use (``true``) or not (``false``). + * - ``profiles`` + - 0..* + - :ref:`Profile list ` + - Slicing profiles available for this slicer, mapped by their ``key`` + +.. _sec-api-slicing-datamodel-profilelist: + +Profile list +------------ + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ```` + - 0..1 + - :ref:`Profile ` + - Information about a profile stored in the system, ``data`` field will be left out. + +.. _sec-api-slicing-datamodel-profile: + +Profile +------- + +.. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Multiplicity + - Type + - Description + * - ``key`` + - 1 + - ``string`` + - Identifier of the profile + * - ``displayName`` + - 0..1 + - ``string`` + - Display name of the profile + * - ``description`` + - 0..1 + - ``string`` + - Description of the profile + * - ``default`` + - 0..1 + - ``boolean`` + - Whether this is the default profile to be used with this slicer (``true``) or not (``false``). Will always be + returned in responses but can be left out of save/update requests. + * - ``resource`` + - 0..1 + - ``URL`` + - Resource URL of the profile, will always be returned in responses but can be left out of save/update requests. + * - ``data`` + - 0..1 + - Object + - The actual profile data, including any default values if the profile was retrieved from the server. May contain + only the keys differing from the defaults when saving/updating a profile. The keys to be found in here a slicer + specific. Will be left out for list responses. + diff --git a/docs/conf.py b/docs/conf.py index 73af7be09..32dd418a5 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -12,25 +12,27 @@ # serve to show the default. import sys, os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath('../src/')) +sys.path.append(os.path.abspath('sphinxext')) + import octoprint._version from datetime import date year_since = 2013 year_current = date.today().year -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -#sys.path.insert(0, os.path.abspath('.')) - # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' +needs_sphinx = '1.3' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.todo', 'sphinxcontrib.httpdomain'] +extensions = ['codeblockext', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain', 'sphinxcontrib.napoleon'] todo_include_todos = True # Add any paths that contain templates here, relative to this directory. @@ -102,9 +104,9 @@ pygments_style = 'sphinx' on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: # only import and set the theme if we're building docs locally - import sphinx_rtd_theme - html_theme = 'sphinx_rtd_theme' - html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] + import sphinx_rtd_theme + html_theme = 'sphinx_rtd_theme' + html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. @@ -139,6 +141,9 @@ if not on_rtd: # only import and set the theme if we're building docs locally # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] +def setup(app): + app.add_stylesheet("theme_overrides.css") + # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst new file mode 100644 index 000000000..141167965 --- /dev/null +++ b/docs/configuration/config_yaml.rst @@ -0,0 +1,388 @@ +.. _sec-configuration-config_yaml: + +config.yaml +=========== + +If not specified via the command line, the main configuration file ``config.yaml`` for OctoPrint is expected in its +settings folder, which unless defined differently via the command line is located at ``~/.octoprint`` on Linux, at +``%APPDATA%/OctoPrint`` on Windows and at ``~/Library/Application Support/OctoPrint`` on MacOS. If the file is not there, +you can just create it - it will only get created by OctoPrint once you save settings that deviate from the default +settings. + +Note that many of these settings are available from the "Settings" menu in OctoPrint itself. + +Serial +------ + +Use the following settings to configure the serial connection to the printer: + +.. code-block:: yaml + + serial: + # Use the following option to define the default serial port, defaults to unset (= AUTO) + port: /dev/ttyACM0 + + # Use the following option to define the default baudrate, defaults to unset (= AUTO) + baudrate: 115200 + + # Whether to automatically connect to the printer on server startup (if available) + autoconnect: false + + # Whether to log whole communication to serial.log (warning: might decrease performance) + log: false + + # Timeouts used for the serial connection to the printer, you might want to adjust these if you are + # experiencing connection problems + timeout: + + # Timeout for waiting for a response from the currently tested port during autodetect, in seconds. + # Defaults to 0.5 sec + detection: 0.5 + + # Timeout for waiting to establish a connection with the selected port, in seconds. + # Defaults to 2 sec + connection: 2 + + # Timeout during serial communication, in seconds. + # Defaults to 5 sec + communication: 5 + + # Use this to define additional patterns to consider for serial port listing. Must be a valid + # "glob" pattern (see http://docs.python.org/2/library/glob.html). Defaults to not set. + additionalPorts: + - /dev/myPrinterSymlink + +Server +------ + +Use the following settings to configure the server: + +.. code-block:: yaml + + server: + # Use this option to define the host to which to bind the server, defaults to "0.0.0.0" (= all interfaces) + host: 0.0.0.0 + + # Use this option to define the port to which to bind the server, defaults to 5000 + port: 5000 + + # Use this option to define an optional baseUrl (with a leading /, so absolute to your + # server's root) under which to run OctoPrint. This should only be needed if you want to run + # OctoPrint behind a reverse proxy under a different root endpoint than `/` and can't configure + # said reverse proxy to send `X-Script-Name` and `X-Scheme` HTTP headers with + # forwarded requests (see below). Defaults to an empty string and therefore the server root. + baseUrl: /octoprint + + # Use this option to define an optional URL scheme under which to run OctoPrint. + # Should only be needed for use with reverse proxies, see above. + scheme: http + + # will be automatically set to false once the first-run-wizard has been completed + firstRun: true + +.. note:: + + If you want to run OctoPrint behind a reverse proxy such as HAProxy or Nginx and use a different base URL than the + server root ``/`` you have two options to achieve this. One approach is using the configuration settings ``baseUrl`` and + ``scheme`` mentioned above in which OctoPrint will only work under the configured base URL. + + The second and better approach is to make your proxy send a couple of custom headers with each forwarded requests: + + * ``X-Script-Name``: should contain your custom baseUrl (absolute server path), e.g. ``/octoprint`` + * ``X-Scheme``: should contain your custom URL scheme to use (if different from ``http``), e.g. ``https`` + + If you use these headers OctoPrint will work both via the reverse proxy as well as when called directly. Take a look + `into OctoPrint's wiki `_ for a couple + of examples on how to configure this. + +Webcam +------ + +Use the following settings to configure webcam support: + +.. code-block:: yaml + + webcam: + # Use this option to enable display of a webcam stream in the UI, e.g. via MJPG-Streamer. + # Webcam support will be disabled if not set + stream: http://:/?action=stream + + # Use this option to enable timelapse support via snapshot, e.g. via MJPG-Streamer. + # Timelapse support will be disabled if not set + snapshot: http://:/?action=snapshot + + # Path to ffmpeg binary to use for creating timelapse recordings. + # Timelapse support will be disabled if not set + ffmpeg: /path/to/ffmpeg + + # The bitrate to use for rendering the timelapse video. This gets directly passed to ffmpeg. + bitrate: 5000k + + # Whether to include a "created with OctoPrint" watermark in the generated timelapse movies + watermark: true + + # The default timelapse settings. + timelapse: + + # The timelapse type. Can be either "off", "zchange" or "timed". Defaults to "off" + type: timed + + # Additional options depending on the timelapse type. Currently only the "timed" timelapse takes + # the interval which to leave between images as option "interval", given in seconds. This example + # therefore configures a "Timed" timelapse with an interval of 2s. Defaults to empty. + options: + interval: 2 + +Feature +------- + +Use the following settings to enable or disable OctoPrint features: + +.. code-block:: yaml + + feature: + # Whether to enable the gcode viewer in the UI or not + gCodeVisualizer: true + + # Whether to enable the temperature graph in the UI or not + temperatureGraph: true + + # Specifies whether OctoPrint should wait for the start response from the printer before trying to send commands + # during connect. + waitForStartOnConnect: false + + # Specifies whether OctoPrint should send linenumber + checksum with every command. Needed for + # successful communication with Repetier firmware + alwaysSendChecksum: false + + # Whether to ignore the first ok after a resend response. Needed for successful communication with + # Repetier firmware + swallowOkAfterResend: false + + # Specifies whether support for SD printing and file management should be enabled + sdSupport: true + +Folder +------ + +Use the following settings to set custom paths for folders used by OctoPrint: + +.. code-block:: yaml + + folder: + # Absolute path where to store gcode uploads. Defaults to the uploads folder in the OctoPrint settings folder + uploads: /path/to/upload/folder + + # Absolute path where to store finished timelapse recordings. Defaults to the timelapse folder in the OctoPrint + # settings dir + timelapse: /path/to/timelapse/folder + + # Absolute path where to store temporary timelapse files. Defaults to the timelapse/tmp folder in the OctoPrint + # settings dir + timelapse_tmp: /path/to/timelapse/tmp/folder + + # Absolute path where to store log files. Defaults to the logs folder in the OctoPrint settings dir + logs: /path/to/logs/folder + + # Absolute path to the virtual printer's simulated SD card. Only useful for development, just ignore + # it otherwise + virtualSd: /path/to/virtualSd/folder + + # Absolute path to a folder being watched for new files which then get automatically + # added to OctoPrint (and deleted from that folder). Can e.g. be used to define a folder which + # can then be mounted from remote machines and used as local folder for quickly adding downloaded + # and/or sliced objects to print in the future. + watched: /path/to/watched/folder + +Temperature +----------- + +Use the following settings to configure temperature profiles which will be displayed in the temperature tab: + +.. code-block:: yaml + + temperature: + profiles: + - name: ABS + extruder: 210 + bed: 100 + - name: PLA + extruder: 180 + bed: 60 + +Appearance +---------- + +Use the following settings to tweak OctoPrint's appearance a bit to better distinguish multiple instances/printers +appearance: + +.. code-block:: yaml + + appearance: + # Use this to give your printer a name. It will be displayed in the title bar (as " [OctoPrint]") and in the + # navigation bar (as "OctoPrint: ") + name: My Printer Model + + # Use this to color the navigation bar. Supported colors are red, orange, yellow, green, blue, violet and default. + color: blue + +Controls +-------- + +Use the ``controls`` section to add :ref:`custom controls ` to the "Controls" tab within +OctoPrint. + +.. code-block:: yaml + + controls: + - name: Fan + layout: horizontal + children: + - name: Enable Fan + type: parametric_command + command: M106 S%(speed)s + input: + - name: Speed (0-255) + parameter: speed + default: 255 + - name: Disable Fan + type: command + command: M107 + +System +------ + +Use the following settings to add custom system commands to the "System" dropdown within OctoPrint's top bar. + +Commands consist of a name, an action identifier, the commandline to execute and an optional confirmation message to +display before actually executing the command (should be set to False if a confirmation dialog is not desired). + +The following example defines a command for shutting down the system under Linux. It assumes that the user under which +OctoPrint is running is allowed to do this without password entry: + +.. code-block:: yaml + + system: + actions: + - name: Shutdown + action: shutdown + command: sudo shutdown -h now + confirm: You are about to shutdown the system. + +Access Control +-------------- + +Use the following settings to enable access control: + +.. code-block:: yaml + + accessControl: + # whether to enable access control or not. Defaults to true + enabled: true + + # The user manager implementation to use for accessing user information. Currently only a filebased + # user manager is implemented which stores configured accounts in a YAML file (Default: users.yaml + # in the default configuration folder, see below) + userManager: octoprint.users.FilebasedUserManager + + # The YAML user file to use. If left out defaults to users.yaml in the default configuration folder. + userFile: /path/to/users.yaml + + # If set to true, will automatically log on clients originating from any of the networks defined in + # "localNetworks" as the user defined in "autologinAs". Defaults to false. + autologinLocal: true + + # The name of the user to automatically log on clients originating from "localNetworks" as. Must + # be the name of one of your configured users. + autologinAs: someUser + + # A list of networks or IPs for which an automatic logon as the user defined in "autologinAs" will + # take place. If available OctoPrint will evaluate the "X-Forwarded-For" HTTP header for determining + # the client's IP address (see https://code.google.com/p/haproxy-docs/wiki/forwardfor on how to + # configure the sending of this header in HAProxy). Defaults to 127.0.0.0/8 (so basically anything + # originating from localhost). + localNetworks: + - 127.0.0.0/8 + - 192.168.1.0/24 + +Events +------ + +Use the following settings to add shell/gcode commands to be executed on certain :ref:`events `: + +.. code-block:: yaml + + events: + subscriptions: + # example event consumer that prints a message to the system log if the printer is disconnected + - event: Disconnected + command: "logger 'Printer got disconnected'" + type: system + + # example event consumer that queries printer information from the firmware, prints a "Connected" + # message to the LCD and homes the print head upon established printer connection, disabled though + - event: Connected + command: M115,M117 printer connected!,G28 + type: gcode + enabled: False + +Terminal Filters +---------------- + +Use the following settings to define a set of terminal filters to display in the terminal tab for filtering certain +lines from the display terminal log. + +Use `Javascript regular expressions `_: + +.. code-block:: yaml + + # A list of filters to display in the terminal tab. Defaults to the filters shown below + terminalFilters: + - name: Suppress M105 requests/responses + regex: '(Send: M105)|(Recv: ok T:)' + - name: Suppress M27 requests/responses + regex: '(Send: M27)|(Recv: SD printing byte)' + +API +--- + +Settings for the REST API: + +.. code-block:: yaml + + api: + # whether to enable the API + enabled: True + + # current API key needed for accessing the API + apikey: ... + +Development settings +-------------------- + +The following settings are only relevant to you if you want to do OctoPrint development: + +.. code-block:: yaml + + # Settings only relevant for development + devel: + + # Settings for the virtual printer + virtualPrinter: + + # Whether to enable the virtual printer and include it in the list of available serial connections. + # Defaults to false. + enabled: true + + # Whether to send an additional "ok" after a resend request (like Repetier) + okAfterResend: false + + # Whether to force checksums and line number in the communication (like Repetier), if set to true + # printer will only accept commands that come with linenumber and checksum and throw an error for + # lines that don't. Defaults to false + forceChecksum: false + + # Whether to send "ok" responses with the line number that gets acknowledged by the "ok". Defaults + # to false. + okWithLinenumber: false + diff --git a/docs/configuration/index.rst b/docs/configuration/index.rst new file mode 100644 index 000000000..8348d8e15 --- /dev/null +++ b/docs/configuration/index.rst @@ -0,0 +1,12 @@ +.. _sec-configuration: + +############# +Configuration +############# + +.. toctree:: + :maxdepth: 2 + + yaml.rst + config_yaml.rst + logging_yaml.rst diff --git a/docs/configuration/logging_yaml.rst b/docs/configuration/logging_yaml.rst new file mode 100644 index 000000000..daf8b462d --- /dev/null +++ b/docs/configuration/logging_yaml.rst @@ -0,0 +1,100 @@ +.. _sec-configuration-logging_yaml: + +logging.yaml +============ + +The logging configuration file ``logging.yaml`` for OctoPrint is expected in its settings folder, which unless defined +differently on the command line is located at ``~/.octoprint`` on Linux, at ``%APPDATA%/OctoPrint`` on Windows and at +``~/Library/Application Support/OctoPrint`` on MacOS. + +You can use it to change the log levels of the individual components within OctoPrint, which might be necessary to help +in debugging issues you are experiencing, or to change the configuration of the logging handlers themselves, e.g. in +order to change size after which to rollover the ``serial.log``. + +Changing log levels +------------------- + +If you need to change the default logging level within OctoPrint, create the file with a text editor of your choice +(it's usually not there). The general format is this:: + + logger: + : + level: + +with ```` being the internal OctoPrint component for which to change the loglevel, and ```` being the +new log level to set. An example for increasing the log level of the events and the file management components to +``DEBUG`` (the highest amount of logging) would be this ``logging.yaml``: + +.. code-block:: yaml + + logger: + octoprint.events: + level: DEBUG + octoprint.filemanager: + level: DEBUG + +A list of important components for which an increase in logging might be interesting follows: + + * ``octoprint.events``: the event sub system + * ``octoprint.filemanager``: the file management layer + * ``octoprint.plugin``: the plugin sub system + * ``octoprint.plugins.``: the plugin ````, e.g. ``octoprint.plugins.discovery`` to change the log level of + the `Discovery plugin `_ or ``octoprint.plugins.cura`` + to change the log level of the `Cura plugin `_. + * ``octoprint.slicing``: the slicing sub system + +This list will be expanded when deemed necessary. + +Changing logging handlers +------------------------- + +You can also change the configuration of the logging handlers themselves, e.g. in order to make the ``serial.log`` larger +for debugging long running communications or to change the behaviour of the ``octoprint.log``. + +You can find the default configurations of the ``file`` handler used for the ``octoprint.log``, the ``serialFile`` handler +used for the ``serial.log`` and the ``console`` handler used for the output to stdout in YAML format below: + +.. code-block:: yaml + + handlers: + # stdout + console: + class: logging.StreamHandler + level: DEBUG + formatter: simple + stream: ext://sys.stdout + + # octoprint.log + file: + class: logging.handlers.TimedRotatingFileHandler + level: DEBUG + formatter: simple + when: D + backupCount: 1 + filename: /path/to/octoprints/logs/octoprint.log + + # serial.log + serialFile: + class: logging.handlers.RotatingFileHandler + level: DEBUG + formatter: simple + maxBytes: 2097152 # 2 * 1024 * 1024 = 2 MB in bytes + filename: /path/to/octoprints/logs/serial.log + +You can find more information on the used logging handlers in the +`Python documentation on logging handlers `_. + +Changing logging formatters +--------------------------- + +The logging formatters can be defined via ``logging.yaml`` as well. The ``simple`` formatter as referenced above is +expressed in YAML as follows: + +.. code-block:: yaml + + formatters: + simple: + format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + +The possible keys for the logging format can be found in the +`Python documentation on LogRecord attributes `_. \ No newline at end of file diff --git a/docs/configuration/yaml.rst b/docs/configuration/yaml.rst new file mode 100644 index 000000000..3c6696561 --- /dev/null +++ b/docs/configuration/yaml.rst @@ -0,0 +1,224 @@ +.. _sec-configuration-yaml: + +A YAML Primer +============= + +Most of OctoPrint's configuration is done under the hood through `YAML `_ files, +which is why it makes sense to shed some light on the basics of this data serialization format. + +YAML is a text based format which excels at representing the most common of data structures in an easy and very human +readable way, which is why it was chosen for OctoPrint's configuration files. A text editor is all you need in order +to write YAML configuration files. + +.. _sec-configuration-yaml-basic: + +Basic Rules +----------- + +First of all some basic things to know about working with YAML files: + + * Never use tabs outside of quoted strings, especially not for indentation. The tab character is illegal within + YAML files. + * Whitespace and indentation matters and plays an important part in structuring the data, so take special care + to stay consistent here. + * YAML's comments start with a ``#`` and go until the end of the line. + +.. _sec-configuration-yaml-types: + +Interesting data types +---------------------- + +You will probably only come across the three most basic types of data within OctoPrint's YAML files: scalars +(such as strings, integers, ...), lists and associated arrays (aka key-value-pairs, aka maps, aka dictionaries). + +.. _sec-configuration-yaml-types-scalar: + +Scalars +....... + +Scalars are the most basic of all data types and are simple string, integer, float or boolean values. + +For most scalars you don't need any quotes at all, but if you need to define some piece of data which contains characters +that could be mistaken with YAML syntax you need to quote it in either double ``"`` or single ``'`` quotes for the +YAML file to stay valid. As simple rule of thumb, if your data contains any of these characters ``:-{}[]!#|>&%@`` better +quote it. Also quote it if you want a string but it could be mistaken for a valid number (integer or float) or if +it consists only of "Yes", "No", "yes", "no", "true" or "false", which would be converted to a boolean without quotes. + +In double quoted strings if you need to include a literal double quote in your string you can escape it by prefixing +it with a backslash ``\`` (which you can in turn escape by itself). In single quoted strings the single quote character +can be escaped by prefixing it with another single quote, basically doubling it. Backslashes in single quoted strings +do not need to be escaped. + +Quoted strings can also span across multiple lines, just indent the following lines. Note that you'll need to add a +completely empty line in order for force a line break, the data will not be actually wrapped across multiple lines +just because you spread its representation across multiple lines. + +.. _sec-configuration-yaml-types-scalar-int: + +int +''' + +.. code-block:: yaml + + 23 + + 42 + +.. _sec-configuration-yaml-types-scalar-float: + +float +''''' + +.. code-block:: yaml + + 23.5 + + 100.0 + +.. _sec-configuration-yaml-types-scalar-boolean: + +boolean +''''''' + +.. code-block:: yaml + + true + + false + + Yes + + No + + yes + + no + +.. _sec-configuration-yaml-types-scalar-string: + +string +'''''' + +.. code-block:: yaml + + a string + + "some quoted string with a : colon and a { bracket and a quote \" and a backslash \\ - phew" + + 'some single quoted string with a single quote '' and a backslash \ - yay' + + "and a multiline string - just because we can we'll make it span + across not two but four YAML lines! + + Including this paragraph. But in fact it will only be two lines :)" + + "23" + + "42.3" + + "Yes" + + "No" + + "true" + + "false" + + yes and no + + true or false + +.. _sec-configuration-yaml-types-lists: + +Lists +..... + +Lists allow to "collect" a number of similar things into one data structure. They are created by prefixing one or more +consecutive lines with a ``-``: + +.. code-block:: yaml + + - item 1 + - 23.42 + - 57 + - true + +Take special care to have all of your list items at the same indentation level! + +.. _sec-configuration-yaml-types-dicts: + +Dictionaries +............ + +Dictionaries (aka associative arrays aka maps) allow organizing the data in key value pairs, with the key and the value +being separated through a colon ``:``: + +.. sourcecode:: yaml + + key: value + anotherkey: another value + +.. _sec-configuration-yaml-examples: + +Examples +-------- + +Based on the three types explained above, quite complex data structures are possible (whitespace made visible to +help track indentation): + +.. code-block-ext:: yaml + :whitespace: + + general: + some_setting: some_value + a_list: + - item 1 + - 23.42 + - 57 + - true + some_flag: true + quoted_string: "This string is quoted because {we have this here} and also > this and : that" + specific: + setting1: value1 + setting2: + subsetting21: value11 + subsetting22: + - subsubsetting221 + - subsubsetting222 + - subsubsetting223 + the_end: yes + +In this example we have a dictionary on the top most "layer" which has three keys, ``general``, ``specific`` and +``the_end``. + +``general`` in turn is a dictionary with the keys ``some_setting`` (a string), ``a_list`` (a list with four items, +a string, a float, an int and a boolean), ``some_flag`` (a boolean) and ``quoted_string`` (a -- you guessed it -- string). + +``specific`` is also a dictionary, with keys ``setting1`` (a string) and ``setting2``, a dictionary with two keys, one +a string and the other again a list. + +Finally, ``the_end`` is just a boolean, since an unquoted ``yes`` evaluates as a boolean value as we saw in the +:ref:`section about boolean scalars above `. + +Don't get confused by the list "dividing" one part of the dictionary under ``general`` from the other -- your mind is +just playing a trick on you due to the list's dashes ``-`` being on the same levels as the dictionary keys. You could +also just add two more spaces to your identation and write that part like this, which makes the structure a bit +clearer (whitespace again made visible to help track indentation): + +.. code-block-ext:: yaml + :whitespace: + + general: + some_setting: some_value + a_list: + - item 1 + - 23.42 + - 57 + - true + some_flag: true + # ... + +Just make sure you follow a consistent way of indenting your files -- YAML is not as strict as Python when it comes to +differing identation variants within the same file (as long as it's still valid), but consistency will help you as +a lot as a human. Ideally you'll use a text editor which highlights white space characters for you (most editors can +be configured this way), this will help tremendously when editing whitespace sensitive syntax such as YAML. \ No newline at end of file diff --git a/docs/development/index.rst b/docs/development/index.rst new file mode 100644 index 000000000..e3381a4e5 --- /dev/null +++ b/docs/development/index.rst @@ -0,0 +1,10 @@ +.. _sec-development: + +########### +Development +########### + +.. todo:: + + This is where notes regarding developing OctoPrint will be placed, such as workflow for setting up the + development environment, code guidelines etc. \ No newline at end of file diff --git a/docs/events/index.rst b/docs/events/index.rst index f264cd9d3..d1973c5e0 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -1,16 +1,19 @@ .. _sec-events: -#################### -Events Documentation -#################### +###### +Events +###### .. contents:: -With release of OctoPrint 1.1.0, the payload data has been harmonized, it is now a key-value-map for all events. -Additionally, the format of the placeholders in both system command and gcode command triggers has been changed to -accommodate for this new format. Last but not least, the way of specifying event hooks has changed, OctoPrint no longer -separates hooks into two sections (gcodeCommandTrigger and systemCommandTrigger) but instead event hooks are now typed -to indicate what to do with the command contained. + +.. note:: + + With release of OctoPrint 1.1.0, the payload data has been harmonized, it is now a key-value-map for all events. + Additionally, the format of the placeholders in both system command and gcode command triggers has been changed to + accommodate for this new format. Last but not least, the way of specifying event hooks has changed, OctoPrint no longer + separates hooks into two sections (gcodeCommandTrigger and systemCommandTrigger) but instead event hooks are now typed + to indicate what to do with the command contained. .. _sec-events-configuration: @@ -56,7 +59,7 @@ Example Placeholders ============ -You can use the following generic placeholders in your events: +You can use the following generic placeholders in your event hooks: * ``{__currentZ}``: the current Z position of the head if known, -1 if not available * ``{__filename}``: filename of the currently selected file, "NO FILE" if not available @@ -96,6 +99,10 @@ ClientOpened ClientClosed A client has disconnected from the webserver + Payload: + + * ``remoteAddress``: the remote address (IP) of the client that disconnected + Printer communication --------------------- @@ -132,7 +139,14 @@ UpdatedFiles Payload: - * ``type``: the type of file list that was modified, currently only ``gcode`` is supported here + * ``type``: the type of file list that was modified. Currently only ``printables`` and ``gcode`` (DEPRECATED) are supported here. + + .. note:: + + The type ``gcode`` has been renamed to ``printables`` with the introduction of a new file management layer that + supports STL files as first class citizens as well. For reasons of backwards compatibility the ``UpdatedFiles`` + event for printable files will be fired twice, once with ``type`` set to ``gcode``, once set to ``printables``. + Support for the ``gcode`` type will be removed in the next release after version 1.2.0. MetadataAnalysisStarted The metadata analysis of a GCODE file has started. @@ -321,6 +335,7 @@ SlicingStarted * ``stl``: the STL's filename * ``gcode``: the sliced GCODE's filename + * ``progressAvailable``: true if progress information via the ``slicingProgress`` push update will be available, false if not SlicingDone The slicing of a file has completed. @@ -331,6 +346,15 @@ SlicingDone * ``gcode``: the sliced GCODE's filename * ``time``: the time needed for slicing, in seconds (float) +SlicingCancelled + The slicing of a file has been cancelled. This will happen if a second slicing job + targeting the same GCODE file has been started by the user. + + Payload: + + * ``stl``: the STL's filename + * ``gcode``: the sliced GCODE's filename + SlicingFailed The slicing of a file has failed. @@ -339,3 +363,9 @@ SlicingFailed * ``stl``: the STL's filename * ``gcode``: the sliced GCODE's filename * ``reason``: the reason for the slicing having failed + +Settings +-------- + +SettingsUpdated + The internal settings were updated. diff --git a/docs/features/custom_controls.rst b/docs/features/custom_controls.rst new file mode 100644 index 000000000..312352339 --- /dev/null +++ b/docs/features/custom_controls.rst @@ -0,0 +1,277 @@ +.. _sec-features-custom_controls: + +Custom Controls +=============== + +.. contents:: + +OctoPrint allows you to add custom controls to the "Control" tab of its interface. Control types reach from simple +buttons which trigger sending of one or more lines of GCODE to the printer over more complex controls allowing +parameterization of these commands with values entered by the user to full blown GCODE script templates backed by +`Jinja2 `_. + +Custom controls are configured within :ref:`config.yaml ` in a ``controls`` section which +basically represents a hierarchical structure of all configured custom controls of various types. + +.. note:: + + To make sure that your ``config.yaml`` stays valid when adding custom controls, don't hesitate to take a look at the + :ref:`YAML Primer `. + +The following example defines a control for enabling the cooling fan with a variable speed defined by the user +(default 255 and selectable through a slider UI element) and a control for disabling the fan, all within a section named +"Fan", two example controls with multiple commands in a section "Example for multiple commands", a command with printer +feedback evaluation for the result of the M114 "Get Position" gcode inside a section named "Reporting" and finally +a GCODE script including user input. + +.. code-block-ext:: yaml + + controls: + - name: Fan + layout: horizontal + children: + - name: Enable Fan + command: M106 S%(speed)s + input: + - name: Speed (0-255) + parameter: speed + default: 255 + slider: + min: 0 + max: 255 + - name: Disable Fan + command: M107 + - name: Example for multiple commands + children: + - name: Move X (static) + confirm: You are about to move the X axis right by 10mm with 3000mm/s. + commands: + - G91 + - G1 X10 F3000 + - G90 + - name: Move X (parametric) + commands: + - G91 + - G1 X%(distance)s F%(speed)s + - G90 + input: + - default: 10 + name: Distance + parameter: distance + - default: 3000 + name: Speed + parameter: speed + - name: Reporting + children: + - name: Get Position + command: M114 + 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: + - name: Dance + script: custom/dance.gco + input: + - name: Go arounds + parameter: repetitions + slider: + max: 10 + min: 1 + step: 1 + +Adding this to ``config.yaml``, restarting the OctoPrint server and switching to the "Control" tab within its +interface yields the following visual representation: + +.. _fig-configuration-custom_controls-example: +.. figure:: ../images/features-custom_controls-example.png + :align: center + :alt: The rendered output created through the example configuration + +As you can see you have two basic types of control definitions here: controls that actually do something (providing a +button that sends one or more commands to the printer when clicked, displaying output received from the printer) and +controls that just serve as *container* for other controls, the latter being identified by having a ``children`` +attribute wrapping more controls. + +.. _sec-features-custom_controls-types: + +Types +----- + +Let's take a closer look at the possible attributes that are available for both basic types. + +.. _sec-features-custom_controls-types-containers: + +Containers +.......... + +.. list-table:: + :widths: 25 75 + + * - **Attribute** + - **Description** + * - ``children`` + - A list of children controls or containers contained within this container + * - ``name`` + - (Optional) A name to display above the container, basically a section header + * - ``layout`` + - (Optional) The layout to use for laying out the contained children, either from top to bottom (``vertical``) or + from left to right (``horizontal``). Defaults to a ``vertical`` layout. + +.. _sec-features-custom_controls-types-controls: + +Controls +........ + +.. list-table:: + :widths: 25 75 + + * - **Attribute** + - **Description** + * - ``name`` + - The name of the control, will be displayed either on the button if it's a control sending a command or as a label + for controls which only display output. + * - ``command`` + - (Optional) A single GCODE command to send to the printer. Will be rendered as a button which sends the command to + the printer upon click. The button text will be the value of the ``name`` attribute. Mutually exclusive with + ``commands`` and ``script``. The rendered button be disabled if the printer is currently offline or printing or + alternatively if the requirements defined via the ``enabled`` attribute are not met. + * - ``commands`` + - (Optional) A list of GCODE commands to send to the printer. Will be rendered as a button which sends the commands + to the printer upon click. The button text will be the value of the ``name`` attribute. Mutually exclusive with + ``command`` and ``script``. The rendered button will be disabled if the printer is currently offline or printing + or alternatively if the requirements defined via the ``enabled`` attribute are not met. + * - ``script`` + - (Optional) The name of a full blown :ref:`GCODE script ` to send to the printer. + Will be rendered as a button which sends the script to the printer upon click. The button text will be the value + of the ``name`` attribute. Mutually exclusive with ``command`` and ``commands``. The rendered button will be + disabled if the printer is currently offline or printing or alternatively if the requirements defined via the + ``enabled`` attribute are not met. + + Values of input parameters will be available in the template context under the ``parameter`` variable (e.g. + an input parameter ``speed`` will be available in the script template as ``parameter.speed``). On top of that all + other variables defined in the :ref:`GCODE template context ` will be available. + + :ref:`See below for an example `. + * - ``javascript`` + - (Optional) A JavaScript snippet to be executed when the button rendered for ``command`` or ``commands`` is + clicked. This allows to override the direct sending of the command or commands to the printer with more + sophisticated behaviour. The JavaScript snippet is ``eval``'d and processed in a context where the control + it is part of is provided as local variable ``data`` and the ``ControlViewModel`` is available as ``self``. + * - ``enabled`` + - (Optional) A JavaScript snippet returning either ``true`` or ``false`` determining whether the control + should be enabled or not. This allow to override the default logic for this (disabled if printer is offline + or currently printing). The JavaScript snippet is ``eval``'d and processed in a context where the control + it is part of is provided as local variable ``data`` and the ``ControlViewModel`` is available as ``self``. + * - ``input`` + - (Optional) A list of definitions of input parameters for a ``command`` or ``commands``, to be rendered as + additional input fields. ``command``/``commands`` may contain placeholders to be replaced by the values obtained + from the user for the defined input fields: + + .. code-block-ext:: yaml + + name: Enable Fan + command: M106 S%(speed)s + input: + - name: Speed (0-255) + parameter: speed + default: 255 + slider: + min: 0 + max: 255 + + In OctoPrint's default UI input fields are always rendered left to right (inline). + * - ``input.name`` + - Name to display for the input field. + * - ``input.parameter`` + - Internal parameter name for the input field, used as a placeholder in ``command``/``commands``. + * - ``input.default`` + - Default value for the input field. + * - ``input.slider`` + - (Optional) If this attribute is included, instead of an input field a slider control will + be rendered. If you don't want to define any of ``min``, ``max`` or ``step``, write ``slider: {}`` to render + a slider based on default values. + * - ``input.slider.min`` + - (Optional) Minimum value of the slider, defaults to 0. + * - ``input.slider.max`` + - (Optional) Maximum value of the slider, defaults to 255. + * - ``input.slider.step`` + - (Optional) Step size per slider "tick", defaults to 1. + * - ``regex`` + - (Optional) A `regular expression `_ to + match against lines received from the printer to retrieve information from it (e.g. specific output). Together + with ``template`` this allows rendition of received data from the printer within the UI. + * - ``template`` + - (Optional) A template to use for rendering the match of ``regex``. May contain placeholders in + `Python Format String Syntax `_ for either named + groups within the regex (e.g. ``Temperature: {temperature}`` for a regex ``T:\s*(?P\d+(\.\d*)``) + or positional groups within the regex (e.g. ``Position: X={0}, Y={1}, Z={2}, E={3}`` for a regex + ``X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)``). + * - ``confirm`` + - (Optional) A text to display to the user to confirm his button press. Can be used with sensitive custom controls + like changing EEPROM values in order to prevent accidental clicks. The text will be displayed in a confirmation + dialog like the following: + + .. _fig-configuration-custom_controls-confirm: + .. figure:: ../images/features-custom_controls-confirm.png + :align: center + :alt: An example confirmation dialog + +.. _sec-features-custom_controls-examples: + +Examples +-------- + +.. _sec-features-custom_controls-examples-gcode_script: + +Parameterized GCODE Script +.......................... + +.. code-block-ext:: yaml + :caption: Control definition in ~/.octoprint/config.yaml + :name: code-features-custom_controls-example-gcode_script-config_yaml + + name: Dance + script: custom/dance.gco + input: + - default: 5 + name: Go arounds + parameter: repetitions + slider: + max: 10 + min: 1 + step: 1 + +.. code-block-ext:: jinja + :caption: ~/.octoprint/scripts/gcode/custom/dance.gco + :name: code-features-custom_controls-example-gcode_script-dance_gco + + {% set center_x = printer_profile.volume.width / 2 %} + {% set center_y = printer_profile.volume.depth / 2 %} + {% set speed_x = printer_profile.axes.x.speed %} + {% set speed_y = printer_profile.axes.y.speed %} + {% set speed_z = printer_profile.axes.z.speed %} + M117 run {{ script.name }} + G4 P500 + G1 Z10 + G1 X{{ center_x }} Y{{ center_y }} F{{ speed_x }} + M117 let's dance! + G91 + G1 X-1 Y-1 F{{ speed_x }} + {% for n in range(parameters.repetitions) %} + M117 and {{ n + 1 }} + {% if n % 2 == 0 %} + G1 Z1 F{{ speed_z }} + G1 Z-2 F{{ speed_z }} + G1 Z1 F{{ speed_z }} + {% endif %} + G1 X2 F{{ speed_x }} + G1 Y2 F{{ speed_y }} + G1 X-2 F{{ speed_x }} + G1 Y-2 F{{ speed_y }} + {% endfor %} + G90 + G1 X{{ center_x }} Y{{ center_y }} F{{ speed_x }} + G28 X0 Y0 + +Note the usage of the ``parameters.repetitions`` template variable in the GCODE script template, which will contain +the value selected by the user for the "Go arounds" slider. \ No newline at end of file diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst new file mode 100644 index 000000000..c37fbe1a7 --- /dev/null +++ b/docs/features/gcode_scripts.rst @@ -0,0 +1,18 @@ +.. _sec-features-gcode_scripts: + +GCODE Scripts +============= + +.. todo:: + + Needs to be written + +.. _sec-features-gcode_scripts-context: + +Context +------- + +.. _sec-features-gcode_scripts-bundled: + +Bundled Scripts +--------------- diff --git a/docs/features/index.rst b/docs/features/index.rst new file mode 100644 index 000000000..83088990f --- /dev/null +++ b/docs/features/index.rst @@ -0,0 +1,11 @@ +.. _section-features: + +******** +Features +******** + +.. toctree:: + :maxdepth: 2 + + custom_controls.rst + gcode_scripts.rst diff --git a/docs/images/features-custom_controls-confirm.png b/docs/images/features-custom_controls-confirm.png new file mode 100644 index 000000000..9bae6fa55 Binary files /dev/null and b/docs/images/features-custom_controls-confirm.png differ diff --git a/docs/images/features-custom_controls-example.png b/docs/images/features-custom_controls-example.png new file mode 100644 index 000000000..ad2b3ea0e Binary files /dev/null and b/docs/images/features-custom_controls-example.png differ diff --git a/docs/images/plugins_gettingstarted_helloworld_navbar.png b/docs/images/plugins_gettingstarted_helloworld_navbar.png new file mode 100644 index 000000000..2f634b0db Binary files /dev/null and b/docs/images/plugins_gettingstarted_helloworld_navbar.png differ diff --git a/docs/images/plugins_gettingstarted_helloworld_settings.png b/docs/images/plugins_gettingstarted_helloworld_settings.png new file mode 100644 index 000000000..255592ea1 Binary files /dev/null and b/docs/images/plugins_gettingstarted_helloworld_settings.png differ diff --git a/docs/images/plugins_gettingstarted_helloworld_tab.png b/docs/images/plugins_gettingstarted_helloworld_tab.png new file mode 100644 index 000000000..d7338a0ba Binary files /dev/null and b/docs/images/plugins_gettingstarted_helloworld_tab.png differ diff --git a/docs/images/template-plugin-type-navbar.png b/docs/images/template-plugin-type-navbar.png new file mode 100644 index 000000000..f00be8635 Binary files /dev/null and b/docs/images/template-plugin-type-navbar.png differ diff --git a/docs/images/template-plugin-type-settings.png b/docs/images/template-plugin-type-settings.png new file mode 100644 index 000000000..ae9c849ea Binary files /dev/null and b/docs/images/template-plugin-type-settings.png differ diff --git a/docs/images/template-plugin-type-sidebar.png b/docs/images/template-plugin-type-sidebar.png new file mode 100644 index 000000000..88db66a8c Binary files /dev/null and b/docs/images/template-plugin-type-sidebar.png differ diff --git a/docs/images/template-plugin-type-tab.png b/docs/images/template-plugin-type-tab.png new file mode 100644 index 000000000..32febed2a Binary files /dev/null and b/docs/images/template-plugin-type-tab.png differ diff --git a/docs/images/template-plugin-types-main.png b/docs/images/template-plugin-types-main.png new file mode 100644 index 000000000..3b4267faf Binary files /dev/null and b/docs/images/template-plugin-types-main.png differ diff --git a/docs/images/template-plugin-types-settings.png b/docs/images/template-plugin-types-settings.png new file mode 100644 index 000000000..2ad2b5dd2 Binary files /dev/null and b/docs/images/template-plugin-types-settings.png differ diff --git a/docs/images/template_plugin_types.ep b/docs/images/template_plugin_types.ep new file mode 100644 index 000000000..d036b24cc --- /dev/null +++ b/docs/images/template_plugin_types.ep @@ -0,0 +1,309 @@ + +sidebar1421408377849_14071531847true#FFFFFFFFtransparent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ]]> + styles_content / styles
classes_content / classes
]]>
+ + + + + + + + + +
data_bind
styles_wrapper / styles
classes_wrapper / classes
]]>
+ + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + +
tab1421409530685_85131531847true#FFFFFFFFtransparent + + + + + + + + + + + + + + + + + + + + + + + + + ]]> + data_bind
styles_link / styles
classes_link / classes
]]>
+ + + + + + + + + +
data_bind
styles_content / styles
classes_content / classes
]]>
+ + + + + + + + + +
settings1421410253180_35791531847true#FFFFFFFFtransparent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ]]> + + data_bind
styles_content / styles
classes_content / classes
]]>
+ + + + + + + + + +
data_bind
styles_link / styles
classes_link / classes
]]>
+ + + + + + + + + +
navbar1421410510071_96931531847true#FFFFFFFFtransparent + + + + + + + + + + + + + + + + + data_bind
styles
classes
]]>
+ + + + + + + + + +
\ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst index 3375a90cb..068959093 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -6,17 +6,16 @@ Welcome to OctoPrint's documentation! :alt: The OctoPrint Logo :align: right -This is a work in progress. The goal is to document OctoPrint's REST API, event system, configuration etc in a way that -allows different documentation per development branch in Git, which so far did not scale well with the Github-Wiki-based -approach. - Contents ======== .. toctree:: :maxdepth: 2 + features/index.rst + configuration/index.rst api/index.rst events/index.rst plugins/index.rst + modules/index.rst diff --git a/docs/modules/filemanager.rst b/docs/modules/filemanager.rst new file mode 100644 index 000000000..aaa7beeb8 --- /dev/null +++ b/docs/modules/filemanager.rst @@ -0,0 +1,32 @@ +.. _sec-modules-filemanager: + +octoprint.filemanager +--------------------- + +.. automodule:: octoprint.filemanager + :members: + +.. _sec-modules-filemanager-analysis: + +octoprint.filemanager.analysis +------------------------------ + +.. automodule:: octoprint.filemanager.analysis + :members: + +.. _sec-modules-filemanager-destinations: + +octoprint.filemanager.destinations +---------------------------------- + +.. automodule:: octoprint.filemanager.destinations + :members: + +.. _sec-modules-filemanager-storage: + +octoprint.filemanager.storage +----------------------------- + +.. automodule:: octoprint.filemanager.storage + :members: StorageInterface, LocalFileStorage + diff --git a/docs/modules/index.rst b/docs/modules/index.rst new file mode 100644 index 000000000..e9ef4825c --- /dev/null +++ b/docs/modules/index.rst @@ -0,0 +1,14 @@ +.. _sec-modules: + +################ +Internal Modules +################ + +.. toctree:: + :maxdepth: 3 + + filemanager.rst + plugin.rst + printer.rst + settings.rst + util.rst diff --git a/docs/modules/plugin.rst b/docs/modules/plugin.rst new file mode 100644 index 000000000..d464b5c34 --- /dev/null +++ b/docs/modules/plugin.rst @@ -0,0 +1,20 @@ +.. _sec-modules-plugin: + +octoprint.plugin +---------------- + +.. automodule:: octoprint.plugin + +.. _sec-modules-plugin-core: + +octoprint.plugin.core +--------------------- + +.. automodule:: octoprint.plugin.core + +.. _sec-modules-plugin-types: + +octoprint.plugin.types +---------------------- + +.. automodule:: octoprint.plugin.types diff --git a/docs/modules/printer.rst b/docs/modules/printer.rst new file mode 100644 index 000000000..ce752f431 --- /dev/null +++ b/docs/modules/printer.rst @@ -0,0 +1,6 @@ +.. _sec-modules-printer: + +octoprint.printer +----------------- + +.. automodule:: octoprint.printer diff --git a/docs/modules/settings.rst b/docs/modules/settings.rst new file mode 100644 index 000000000..80248cbb9 --- /dev/null +++ b/docs/modules/settings.rst @@ -0,0 +1,6 @@ +.. _sec-modules-settings: + +octoprint.settings +------------------ + +.. automodule:: octoprint.settings diff --git a/docs/modules/util.rst b/docs/modules/util.rst new file mode 100644 index 000000000..32a61b728 --- /dev/null +++ b/docs/modules/util.rst @@ -0,0 +1,9 @@ +.. _sec-modules-util: + +octoprint.util +-------------- + +.. automodule:: octoprint.util + :members: + + diff --git a/docs/plugins/distributing.rst b/docs/plugins/distributing.rst new file mode 100644 index 000000000..7a8d6fc0e --- /dev/null +++ b/docs/plugins/distributing.rst @@ -0,0 +1,27 @@ +.. _sec-plugins-distribution: + +Distributing your plugin +======================== + +You can distribute a plugin with OctoPrint via two ways: + + - You can have your users copy it to OctoPrint's plugin folder (normally located at ``~/.octoprint/plugins`` under Linux, + ``%APPDATA%\OctoPrint\plugins`` on Windows and ... on Mac). In this case your plugin will be distributed directly + as a Python module (a single ``.py`` file containing all of your plugin's code directly and named + like your plugin) or a package (a folder named like your plugin + ``__init.py__`` contained within). + - You can have your users install it via ``pip`` and register it for the `entry point `_ ``octoprint.plugin`` via + your plugin's ``setup.py``, this way it will be found automatically by OctoPrint upon initialization of the + plugin subsystem [#f1]_. + + For an example of how the directory structure and related files would look like in this case, please take a + look at the `helloworld example from OctoPrint's example plugins `_. + + This variant is highly recommended for pretty much any plugin besides the most basic ones since it also allows + requirements management and pretty much any thing else that Python's setuptools provide to the developer. + +.. rubric:: Footnotes + +.. [#f1] The automatic registration will only work within the same Python installation (this also includes virtual + environments), so make sure to instruct your users to use the exact same Python installation for installing + the plugin that they also used for installing & running OctoPrint. + diff --git a/docs/plugins/gettingstarted.rst b/docs/plugins/gettingstarted.rst new file mode 100644 index 000000000..61f58e3f2 --- /dev/null +++ b/docs/plugins/gettingstarted.rst @@ -0,0 +1,906 @@ +.. _sec-plugins-gettingstarted: + +Getting Started +=============== + +Over the course of this little tutorial we'll build a full fledged, installable OctoPrint plugin that displays "Hello World!" +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. + +We'll start at the most basic form a plugin can take - just a couple of simple lines of Python code: + +.. code-block:: python + :linenos: + + # coding=utf-8 + from __future__ import absolute_import + + __plugin_name__ = "Hello World" + __plugin_version__ = "1.0" + __plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint" + +Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you something resembling these log entries upon server startup:: + + 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 - Found 3 plugin(s): Hello World (1.0), CuraEngine (0.1), Discovery (0.1) + +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 +``__plugin_description__`` and stored it in an internal data structure, but we'll just ignore this for now. + +.. _sec-plugins-gettingstarted-sayinghello: + +Saying hello: How to make the plugin actually do something +---------------------------------------------------------- + +Apart from being discovered by OctoPrint, our plugin does nothing yet. We want to change that. Let's make it print +"Hello World!" to the log upon server startup. Modify our ``helloworld.py`` like this: + +.. code-block:: python + :emphasize-lines: 4-8,13 + :linenos: + + # coding=utf-8 + from __future__ import absolute_import + + import octoprint.plugin + + class HelloWorldPlugin(octoprint.plugin.StartupPlugin): + def on_after_startup(self): + self._logger.info("Hello World!") + + __plugin_name__ = "Hello World" + __plugin_version__ = "1.0" + __plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint" + __plugin_implementations__ = [HelloWorldPlugin()] + +and restart OctoPrint. You now get this output in the log:: + + 2015-01-27 11:17:10,792 - octoprint.plugins.helloworld - INFO - Hello World! + +Neat, isn't it? We added a custom class that subclasses one of OctoPrint's :ref:`plugin mixins ` +with :class:`~octoprint.plugin.StartupPlugin` and another control property, ``__plugin_implementations__``, that instantiates +our plugin class and tells OctoPrint about it. Taking a look at the documentation of :class:`~octoprint.plugin.StartupPlugin` we see that +this mixin offers two methods that get called by OctoPrint during startup of the server, :func:`~octoprint.plugin.StartupPlugin.on_startup` and +:func:`~octoprint.plugin.StartupPlugin.on_after_startup`. We decided to add our logging output by overriding :func:`~octoprint.plugin.StartupPlugin.on_after_startup`, but we could also have +used :func:`~octoprint.plugin.StartupPlugin.on_startup` instead, in which case our logging statement would be executed before the server was done starting +up and ready to serve requests. + +You'll also note that we are using ``self._logger`` for logging. Where did that one come from? OctoPrint's plugin system +injects :ref:`a couple of useful objects ` into our plugin implementation classes, +one of those being a fully instantiated `python logger `_ ready to be +used by your plugin. As you can see in the log output above, that logger uses the namespace ``octoprint.plugins.helloworld`` +for our little plugin here, or more generally ``octoprint.plugins.``. + +.. _sec-plugins-gettingstarted-growingup: + +Growing up: How to make it distributable +---------------------------------------- + +If you now want to distribute this plugin to other OctoPrint users (since it is so awesome to be greeted upon server +startup), let's take a look at how you'd go about that now before our plugin gets more complicated. + +You basically have two options to distribute your plugin. One would be about the exact same way we are using it now, +as a simple python file following the naming convention ``.py`` that your users add to their +``~/.octoprint/plugins`` folder. You already know how that works. But let's say you have more than just a simple plugin +that can be done in one file. Distributing multiple files and getting your users to install them in the right way +so that OctoPrint will be able to actually find and load them is certainly not impossible (see :ref:`the plugin distribution +documentation ` if you want to take a closer look at that option), but we want to do it in the +best way possible, meaning we want to make our plugin a fully installable python module that your users will be able to +install directly via Python's standard package manager ``pip`` or alternatively via `OctoPrint's own plugin manager `_. + +So let's begin. First checkout the `Plugin Skeleton `_ and rename +the ``octoprint_skeleton`` folder to something better suited to our "Hello World" plugin:: + + $ git clone https://github.com/OctoPrint/OctoPrint-PluginSkeleton.git OctoPrint-HelloWorld + Cloning into 'OctoPrint-HelloWorld'... + [...] + $ cd OctoPrint-HelloWorld + $ mv octoprint_skeleton octoprint_helloworld + +Then edit the configuration in the ``setup.py`` file to mirror our own "Hello World" plugin. The configuration should +look something like this: + +.. code-block:: python + :linenos: + + plugin_identifier = "helloworld" + plugin_name = "OctoPrint-HelloWorld" + plugin_version = "1.0" + plugin_description = "A quick \"Hello World\" example plugin for OctoPrint" + plugin_author = "You" + plugin_author_email = "you@somewhere.net" + plugin_url = "https://github.com/you/OctoPrint-HelloWorld" + +Now all that's left to do is to move our ``helloworld.py`` into the ``octoprint_helloworld`` folder and renaming it to +``__init__.py``. Make sure to delete the copy under ``~/.octoprint/plugins`` in the process, including the `.pyc` file! + +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:: + + $ python setup.py develop + running develop + running egg_info + creating OctoPrint_HelloWorld.egg-info + [...] + Finished processing dependencies for OctoPrint-HelloWorld==1.0 + +Restart OctoPrint. Your plugin should still be properly discovered and the log line should be printed:: + + 2015-01-27 13:43:34,134 - octoprint.server - INFO - Starting OctoPrint 1.2.0-dev-448-gd96e56e (devel branch) + 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 - Found 3 plugin(s): Hello World (1.0), CuraEngine (0.1), Discovery (0.1) + [...] + 2015-01-27 13:43:38,997 - octoprint.plugins.helloworld - INFO - Hello World! + +Looks like it still works! + +Something is still a bit ugly though. Take a look into ``__init__.py`` and ``setup.py``. It seems like we have a bunch +of information now defined twice: + +.. code-block:: python + :linenos: + + # __init__.py: + __plugin_name__ = "Hello World" + __plugin_version__ = "1.0" + __plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint" + + # setup.py + plugin_name = "OctoPrint-HelloWorld" + plugin_version = "1.0" + plugin_description = "A quick \"Hello World\" example plugin for OctoPrint" + +The nice thing about our plugin now being a proper python package is that OctoPrint can and will access the metadata defined +within ``setup.py``! So, we don't really need to define all this data twice. Remove ``__plugin_name__``, ``__plugin_version__`` +and ``__plugin_description__``: + +.. code-block:: python + :linenos: + + # coding=utf-8 + from __future__ import absolute_import + + import octoprint.plugin + + class HelloWorldPlugin(octoprint.plugin.StartupPlugin): + def on_after_startup(self): + self._logger.info("Hello World!") + + __plugin_implementations__ = [HelloWorldPlugin()] + +and restart OctoPrint:: + + 2015-01-27 13:46:33,786 - octoprint.plugin.core - INFO - Found 3 plugin(s): OctoPrint-HelloWorld (1.0), CuraEngine (0.1), Discovery (0.1) + +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: + +.. code-block:: python + :emphasize-lines: 10 + :linenos: + + # coding=utf-8 + from __future__ import absolute_import + + import octoprint.plugin + + class HelloWorldPlugin(octoprint.plugin.StartupPlugin): + def on_after_startup(self): + self._logger.info("Hello World!") + + __plugin_name__ = "Hello World" + __plugin_implementations__ = [HelloWorldPlugin()] + + +Restart OctoPrint again:: + + 2015-01-27 13:48:54,122 - octoprint.plugin.core - INFO - Found 3 plugin(s): Hello World (1.0), CuraEngine (0.1), Discovery (0.1) + +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 +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/you/OctoPrint-HelloWorld/archive/master.zip + +But let's add some more features instead. + +.. _sec-plugins-gettingstarted-templates: + +Frontend fun: How to add functionality to OctoPrint's web interface +------------------------------------------------------------------- + +Outputting a log line upon server startup is all nice and well, but we want to greet not only the administrator of +our OctoPrint instance but actually everyone that opens OctoPrint in their browser. Therefore, we need to modify +OctoPrint's web interface itself. + +We can do this using the :class:`TemplatePlugin` mixin. For now, let's start with a little "Hello World!" in OctoPrint's +navigation bar right at the top that links to the Wikipedia node about "Hello World" programs. For this we'll first +add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class: + +.. code-block:: python + :emphasize-lines: 7 + :linenos: + + # coding=utf-8 + from __future__ import absolute_import + + import octoprint.plugin + + class HelloWorldPlugin(octoprint.plugin.StartupPlugin, + octoprint.plugin.TemplatePlugin): + def on_after_startup(self): + self._logger.info("Hello World!") + + __plugin_name__ = "Hello World" + __plugin_implementations__ = [HelloWorldPlugin()] + +Next, we'll create a sub folder ``templates`` underneath our ``octoprint_helloworld`` folder, and within that a file +``helloworld_navbar.jinja2`` like so: + +.. code-block:: html + :linenos: + + Hello World! + +Our plugin's directory structure should now look like this:: + + octoprint_helloworld/ + templates/ + helloworld_navbar.jinja2 + __init__.py + README.md + requirements.txt + setup.py + +Restart OctoPrint and open the web interface in your browser (make sure to clear your browser's cache!). + +.. _fig-plugins-gettingstarted-helloworld_navbar: +.. figure:: ../images/plugins_gettingstarted_helloworld_navbar.png + :align: center + :alt: Our "Hello World" navigation bar element in action + +Now look at that! + +.. _sec-plugins-gettingstarted-settings: + +Settings Galore: How to make parts of your plugin user adjustable +----------------------------------------------------------------- + +Remember that Wikipedia link we added to our little link in the navigation bar? It links to the english Wikipedia. But +what if we want to allow our users to adjust that according to their wishes, e.g. to link to the german language node +about "Hello World" programs instead? + +To allow your users to customized the behaviour of your plugin you'll need to implement the :class:`~octoprint.plugin.SettingsPlugin` +mixin and override it's :func:`~octoprint.plugin.SettingsPlugin.get_settings_defaults` method. We'll save the URL to +inject into the link under the key ``url`` in our plugin's settings and set it to the old value by default. We'll therefore +return just a single key in our default settings dictionary. To be able to quickly see if we've done that right we'll +extend our little startup message to also log the current setting to the console. We can access that via ``self._settings``, +which is a little settings manager OctoPrint conveniently injects into our Plugin when we include the :class:`~octoprint.plugin.SettingsPlugin` +mixin. + +Let's take a look at how all that would look in our plugin's ``__init__.py``: + +.. code-block:: python + :emphasize-lines: 8, 10, 12-13 + :linenos: + + # coding=utf-8 + from __future__ import absolute_import + + import octoprint.plugin + + class HelloWorldPlugin(octoprint.plugin.StartupPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.SettingsPlugin): + def on_after_startup(self): + self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"])) + + def get_settings_defaults(self): + return dict(url="https://en.wikipedia.org/wiki/Hello_world") + + __plugin_name__ = "Hello World" + __plugin_implementations__ = [HelloWorldPlugin()] + +Restart OctoPrint. You should see something like this:: + + 2015-01-30 11:41:06,058 - octoprint.plugins.helloworld - INFO - Hello World! (more: https://en.wikipedia.org/wiki/Hello_world) + +So far so good. But how do we now get that value into our template? We have two options, the +static one using so called template variables and a dynamic one which retrieves that data from the backend and binds it +into the template using `Knockout data bindings `_. First let's +take a look at the static version using template variables. We already have the :class:`~octoprint.plugin.TemplatePlugin` +mixin included in our plugin, we just need to override its method :func:`~octoprint.plugin.TemplatePlugin.get_template_vars` +to add our URL as a template variable. + +Adjust your plugin's ``__init__.py`` like this: + +.. code-block:: python + :emphasize-lines: 15-16 + :linenos: + + # coding=utf-8 + from __future__ import absolute_import + + import octoprint.plugin + + class HelloWorldPlugin(octoprint.plugin.StartupPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.SettingsPlugin): + def on_after_startup(self): + self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"])) + + def get_settings_defaults(self): + return dict(url="https://en.wikipedia.org/wiki/Hello_world") + + def get_template_vars(self): + return dict(url=self._settings.get(["url"])) + + __plugin_name__ = "Hello World" + __plugin_implementations__ = [HelloWorldPlugin()] + +Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this: + +.. code-block:: html + :linenos: + + Hello World! + +OctoPrint injects the template variables that your plugin defines prefixed with ``plugin__`` into +the template renderer, so your ``url`` got turned into ``plugin_helloworld_url`` which you can now use as a simple +`Jinja2 Variable `_ in your plugin's template. + +Restart OctoPrint and shift-reload the page in your browser (to make sure you really get a fresh copy). The link should +still work and point to the URL we defined as default. + +Let's change the URL! Open up your OctoPrint instance's ``config.yaml`` file and add the following to it (if a ``plugins`` +section doesn't yet exist in the file, create it): + +.. code-block:: yaml + :emphasize-lines: 3-4 + + # [...] + plugins: + helloworld: + url: https://de.wikipedia.org/wiki/Hallo-Welt-Programm + # [...] + +Restart OctoPrint. Not only should the URL displayed in the log file have changed, but also the link should now (after +a proper shift-reload) point to the german Wikipedia node about "Hello World" programs:: + + 2015-01-30 11:47:18,634 - octoprint.plugins.helloworld - INFO - Hello World! (more: https://de.wikipedia.org/wiki/Hallo-Welt-Programm) + +Nice! But not very user friendly. We don't have any way yet to edit the URL from within OctoPrint and have to restart +the server and reload the page every time we want a value change to take effect. Let's try adding a little settings dialog +for our plugin in which we can edit the URL and take any changes take immediate effect. + +First of all, we'll create the settings dialog. You might already have guessed that we'll need another template for that. +So in your plugin's ``templates`` folder create a new file ``helloworld_settings.jinja2`` and put the following content +into it: + +.. code-block:: html + :linenos: + +
+
+ +
+ +
+
+
+ +Note how we access our plugin's property via ``settings.plugins.helloworld.url``. The ``settings`` observable is made +available in the ``SettingsViewModel`` and holds the exact data structure returned from the server for all of +OctoPrint's settings. Accessing plugin settings hence works by following the path under which they are stored in +OctoPrint's internal settings data model (made public via the ``config.yaml``), ``plugins..``. +We'll bind our own settings dialog to the existing ``SettingsViewModel``, so this will be the way we'll access our +property. + +Now adjust your ``templates/helloworld_navbar.jinja2`` file to use a ``data-bind`` attribute to set the value from the +settings view model into the ``href`` attribute of the link tag: + +.. code-block:: html + :linenos: + + Hello World! + +You might have noticed the quite ugly way to access our plugin's ``url`` property here: ``settings.settings.plugins.helloworld.url``. +The reason for this is that we'll make our plugin use the existing ``NavigationViewModel`` which holds the +``SettingsViewModel`` as a property called ``settings``. So to get to the ``settings`` property of the ``SettingsViewModel`` +from the ``NavigationViewModel``, we'll need to first "switch" to the ``SettingsViewModel`` using its property name. Hence +the ugly access string. + +If you were now to restart OctoPrint and reload the web interface, you'll get the settings dialog placed just fine +in OctoPrint's settings, and the link would also still show up in the navigation bar, but both the input field of the +settings dialog as well as the link's ``href`` attribute would not show our link. The reason for this is that OctoPrint +by default assumes that you'll want to bind your own view models to your templates and hence "unbinds" the included +templates from the templates that are in place at the injected location already. In order to tell OctoPrint to please +don't do this here (since we *do* want to use both ``NavigationViewModel`` and ``SettingsViewModel``), we'll need to +override the default template configuration using the :class:`~octoprint.plugin.TemplatePlugin`s +:func:`~octoprint.plugin.TemplatePlugin.get_template_configs` method. We'll tell OctoPrint to use no custom bindings +for both our ``navbar`` and our ``settings`` plugin. We'll also remove the override of :func:`octoprint.plugin.TemplatePlugin.get_template_vars` +again since we don't use that anymore: + +.. code-block:: python + :emphasize-lines: 15-19 + :linenos: + + # coding=utf-8 + from __future__ import absolute_import + + import octoprint.plugin + + class HelloWorldPlugin(octoprint.plugin.StartupPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.SettingsPlugin): + def on_after_startup(self): + self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"])) + + def get_settings_defaults(self): + return dict(url="https://en.wikipedia.org/wiki/Hello_world") + + def get_template_configs(self): + return [ + dict(type="navbar", custom_bindings=False), + dict(type="settings", custom_bindings=False) + ] + + __plugin_name__ = "Hello World" + __plugin_implementations__ = [HelloWorldPlugin()] + +Restart OctoPrint and shift-reload your browser. Your link in the navigation bar should still point to the URL we +defined in ``config.yaml`` earlier. Open the "Settings" and click on the new "Hello World" entry that shows up under +"Plugins". + +.. _fig-plugins-gettingstarted-helloworld_settings: +.. figure:: ../images/plugins_gettingstarted_helloworld_settings.png + :align: center + :alt: Our "Hello World" navigation bar element in action + +Nice! Edit the value, then click "Save". Your link in the navigation bar should now have been updated as well. + +.. note:: + + The way we've done our data binding and how OctoPrint currently works, your link's target will update immediately + when you update the value in the settings dialog. Even if you click Cancel instead of Save, the change will still + be reflected in the UI but will be overwritten again by the stored data upon a reload. This is caused by OctoPrint + not storing a copy of the settings data while it is being edited, which might be changed in the future to + prevent this unexpected behaviour from occurring. + +Congratulations, you've just made your Plugin configurable :) + +More frontend fun: Adding custom javascript to your frontend components +----------------------------------------------------------------------- + +In the previous section we set that ``custom_bindings`` parameter to ``False`` since we wanted OctoPrint to bind the +``SettingsViewModel`` to our settings dialog and the ``NavigationViewModel`` to our entry in the nav bar. + +But what if we want to define our own, with more functionality that is already available? Let's take a look. We'll now +add an additional UI component to our OctoPrint interface, a custom tab. It will act as a little internal web browser, +showing the website behind the URL from the settings in an IFrame but also allowing the user to load a different URL +without having to change the settings. + +First let us create the Jinja2 template for our tab. In your plugin's ``templates`` folder create a new file +``helloworld_tab.jinja2`` like so: + +.. code-block:: html + :linenos: + +
+ + +
+ + + + +Then we create a new folder in your plugin's root called ``static`` and within that folder another folder by the name of +``js``. Finally, within that folder create a file ``helloworld.js``. Our plugin's folder structure should now +look like this:: + + octoprint_helloworld/ + static/ + js/ + helloworld.js + templates/ + helloworld_navbar.jinja2 + helloworld_settings.jinja2 + helloworld_tab.jinja2 + __init__.py + README.md + requirements.txt + setup.py + +We need to tell OctoPrint about this new static asset so that it will properly inject it into the page. For this we +just need to subclass :class:`~octoprint.plugin.AssetPlugin` and override its method :func:`~octoprint.plugin.AssetPlugin.get_assets` +like so: + +.. code-block:: python + :emphasize-lines: 9,22-25 + :linenos: + + # coding=utf-8 + from __future__ import absolute_import + + import octoprint.plugin + + class HelloWorldPlugin(octoprint.plugin.StartupPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.AssetPlugin): + def on_after_startup(self): + self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"])) + + def get_settings_defaults(self): + return dict(url="https://en.wikipedia.org/wiki/Hello_world") + + def get_template_configs(self): + return [ + dict(type="navbar", custom_bindings=False), + dict(type="settings", custom_bindings=False) + ] + + def get_assets(self): + return dict( + js=["js/helloworld.js"] + ) + + __plugin_name__ = "Hello World" + __plugin_implementations__ = [HelloWorldPlugin()] + +Note how we did not add another entry to the return value of :func:`~octoprint.plugin.TemplatePlugin.get_template_configs`. +Remember how we only added those since we wanted OctoPrint to use existing bindings on our navigation bar and settings +menu entries? We don't want this this time, and we named our tab template such that OctoPrint will pick it up automatically +so we don't have to do anything here. + +Then we'll create our custom `Knockout `_ view model in ``helloworld.js`` +like so: + +.. code-block:: javascript + :linenos: + + $(function() { + function HelloWorldViewModel(parameters) { + var self = this; + + self.settings = parameters[0]; + + // this will hold the URL currently displayed by the iframe + self.currentUrl = ko.observable(); + + // this will hold the URL entered in the text field + self.newUrl = ko.observable(); + + // this will be called when the user clicks the "Go" button and set the iframe's URL to + // the entered URL + self.goToUrl = function() { + self.currentUrl(self.newUrl()); + }; + + // This will get called before the HelloWorldViewModel gets bound to the DOM, but after its + // dependencies have already been initialized. It is especially guaranteed that this method + // gets called _after_ the settings have been retrieved from the OctoPrint backend and thus + // the SettingsViewModel been properly populated. + self.onBeforeBinding = function() { + self.newUrl(self.settings.settings.plugins.helloworld.url()); + self.goToUrl(); + } + } + + // This is how our plugin registers itself with the application, by adding some configuration + // information to the global variable OCTOPRINT_VIEWMODELS + OCTOPRINT_VIEWMODELS.push([ + // This is the constructor to call for instantiating the plugin + HelloWorldViewModel, + + // This is a list of dependencies to inject into the plugin, the order which you request + // here is the order in which the dependencies will be injected into your view model upon + // instantiation via the parameters argument + ["settingsViewModel"], + + // Finally, this is the list of selectors for all elements we want this view model to be bound to. + ["#tab_plugin_helloworld"] + ]); + }); + +Take a close look at lines 31 to 42. This is how our plugin tells OctoPrint about our new view model, how to +instantiate it, which dependencies to inject and to which elements in the final page to bind. Since we want to access +the URL from the settings of our plugin, we'll have OctoPrint inject the ``SettingsViewModel`` into our own view model, +which is registered within OctoPrint under the name ``settingsViewModel``. We'll only bind to our custom tab +for now, which OctoPrint will make available in a container with the id ``tab_plugin_helloworld`` (unless otherwise +configured). + +Our view model defines two observables: ``newUrl``, which we bound to the input field in our template, and ``currentUrl`` +which we bound to the ``src`` attribute of the "browser iframe" in our template. There's also a function ``goToUrl`` +which we bound to the click event of the "Go" button in our template. + +Restart OctoPrint and shift-reload the browser. You should see a shiny new "Hello World" tab right at the end of the +tab bar. Click on it! + +.. _fig-plugins-gettingstarted-helloworld_tab: +.. figure:: ../images/plugins_gettingstarted_helloworld_tab.png + :align: center + :alt: Our "Hello World" tab in action + +The desktop version of that article looks a bit squished in there, so let's enter ``https://de.m.wikipedia.org/wiki/Hallo-Welt-Programm`` +into the input field and click the "Go" button. The page inside the iframe should be replaced with the mobile version +of the same article. + +Style matters: Injecting custom CSS into the page +------------------------------------------------- + +So it appears that this stuff is working great already. Only one thing is a bit ugly, let's take another look at +our ``helloworld_tab.jinja2``: + +.. code-block:: html + :linenos: + :emphasize-lines: 6 + +
+ + +
+ + + +We hardcoded some ``style`` on our ``iframe`` in line 6, to make it look a bit better. It would be nicer if that was actually +located inside a stylesheet instead of directly inside our HTML template. Of course that's no problem, we'll just +add a CSS file to our plugin's provided static assets. + +First we'll create a new folder within our plugin's ``static`` folder called ``css`` and within that folders a file +``helloworld.css``. Our plugin's file structure should now look like this:: + + octoprint_helloworld/ + static/ + css/ + helloworld.css + js/ + helloworld.js + templates/ + helloworld_navbar.jinja2 + helloworld_settings.jinja2 + helloworld_tab.jinja2 + __init__.py + README.md + requirements.txt + setup.py + + +Put something like the following into ``helloworld.css``: + +.. code-block:: css + :linenos: + + #tab_plugin_helloworld { + iframe { + width: 100%; + height: 600px; + border: 1px solid #808080; + } + } + +Don't forget to remove the ``style`` attribute from the ``iframe`` tag in ``helloworld_tab.jinja2``: + +.. code-block:: html + :linenos: + :emphasize-lines: 6 + +
+ + +
+ + + +Then adjust our plugin's ``__init__.py`` so that the :func:`~octoprint.plugin.AssetPlugin.get_assets` method returns +a reference to our CSS file: + +.. code-block:: python + :emphasize-lines: 26 + :linenos: + + # coding=utf-8 + from __future__ import absolute_import + + import octoprint.plugin + + class HelloWorldPlugin(octoprint.plugin.StartupPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.AssetPlugin): + + def on_after_startup(self): + self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"])) + + def get_settings_defaults(self): + return dict(url="https://en.wikipedia.org/wiki/Hello_world") + + def get_template_configs(self): + return [ + dict(type="navbar", custom_bindings=False), + dict(type="settings", custom_bindings=False) + ] + + def get_assets(self): + return dict( + js=["js/helloworld.js"], + css=["css/helloworld.css"] + ) + + __plugin_name__ = "Hello World" + __plugin_implementations__ = [HelloWorldPlugin()] + +Restart OctoPrint, shift-reload your browser and take a look. Everything should still look like before, but now +OctoPrint linked to our stylesheet and the style information for the ``iframe`` is taken from that instead of +hardcoded in our template. Way better! + +Now, if you had something more complicated than just the couple of line of CSS we used here, you might want to use +something like LESS for generating your CSS from. If you use `LESS `_, which is what OctoPrint +uses for that purpose, you can even put OctoPrint into a mode where it directly uses your LESS files instead of the +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`` +in the process. The folder structure of our plugin should now look like this:: + + octoprint_helloworld/ + static/ + css/ + helloworld.css + js/ + helloworld.js + less/ + helloworld.less + templates/ + helloworld_navbar.jinja2 + helloworld_settings.jinja2 + helloworld_tab.jinja2 + __init__.py + README.md + requirements.txt + setup.py + + +Then adjust our returned assets to include our LESS file as well: + +.. code-block:: python + :emphasize-lines: 27 + :linenos: + + # coding=utf-8 + from __future__ import absolute_import + + import octoprint.plugin + + class HelloWorldPlugin(octoprint.plugin.StartupPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.AssetPlugin): + + def on_after_startup(self): + self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"])) + + def get_settings_defaults(self): + return dict(url="https://en.wikipedia.org/wiki/Hello_world") + + def get_template_configs(self): + return [ + dict(type="navbar", custom_bindings=False), + dict(type="settings", custom_bindings=False) + ] + + def get_assets(self): + return dict( + js=["js/helloworld.js"], + css=["css/helloworld.css"], + less=["less/helloworld.less"] + ) + + __plugin_name__ = "Hello World" + __plugin_implementations__ = [HelloWorldPlugin()] + + +and enable LESS mode by adjusting one of OctoPrint's ``devel`` flags via the ``config.yaml`` file: + +.. code-block:: yaml + :emphasize-lines: 2-3 + + # [...] + devel: + stylesheet: less + # [...] + +Restart OctoPrint and shift-reload. Your "Hello World" tab should still look like before. Take a look at the site's +source code. In the ``head`` section of the page you'll see that instead of your ``helloworld.css`` OctoPrint now +embedded the ``helloworld.less`` file instead: + +.. code-block:: html + :linenos: + :emphasize-lines: 7 + + + + + + + + + + + + + + + +Switch your config back to CSS mode by either removing the ``stylesheet`` setting we just added to ``config.yaml`` or +setting it to ``css``, e.g. + +.. code-block:: yaml + :emphasize-lines: 3 + + # [...] + devel: + stylesheet: css + # [...] + +Restart and shift-reload and take another look at the ``head``: + +.. code-block:: html + :linenos: + :emphasize-lines: 7 + + + + + + + + + + + + + +Now the CSS file is linked and no trace of the LESS links is left in the source. This should help to speed up your development +tremendously when you have to work with complex stylesheets, just don't forgot to check the generated CSS file in with +the rest of your plugin or people will miss it when trying to run your plugin! + +.. note:: + + If your plugin only provides CSS files, OctoPrint will detect this when switched to LESS mode and include your + CSS files instead of any non-existing LESS files. So you don't really *have* to use LESS if you don't want, but + as soon as you need it just switch over. + + The same thing works the other way around too btw. If your plugin only provides LESS files, OctoPrint will link to + those and add lessjs to the page as well. Please keep in mind though that also providing CSS files is the cleaner + way. + +Where do we go from here? +------------------------- + +You've now seen how easy it is to add functionality to OctoPrint with this little tutorial. You can find the full +source code of the little Hello World plugin we built together here `on Github `_. + +But I want to invite you to dive deeper into OctoPrint's plugin system. To get an idea of all the other various plugin types +you haven't seen yet, :ref:`take a look at the available plugin mixins `. + +For some insight on how to create plugins that react to various events within OctoPrint, +`the Growl Plugin `_ might be a good example to learn from. For how to +add support for a slicer, OctoPrint's own bundled `CuraEngine plugin `_ +might give some hints. For extending OctoPrint's interface, the `NavbarTemp plugin `_ +might show what's possible with a few lines of code already. Finally, just take a look at the +`list of available plugins `_ on the OctoPrint wiki if you are +looking for examples. + +.. rubric:: Footnotes + +.. [#f1] 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 new file mode 100644 index 000000000..1b15dd4a3 --- /dev/null +++ b/docs/plugins/hooks.rst @@ -0,0 +1,8 @@ +.. _sec-plugins-hooks: + +Available plugin hooks +====================== + +.. todo:: + + Needs to be documented \ No newline at end of file diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst index c71261c20..c043aaf68 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -1,61 +1,23 @@ .. _sec-plugins: -##################### -Plugins Documentation -##################### - -.. contents:: +####### +Plugins +####### Starting with OctoPrint 1.2.0, there's now a plugin system in place which allows to individually extend OctoPrint's functionality. -Right now plugins can be used to extend OctoPrint's settings dialog, to execute specific tasks on server startup and -shutdown or to provide custom (API) endpoints with special functionality. More plugin types are planned for the future. +Right now plugins can be used to extend OctoPrint's web interface, to execute specific tasks on server startup and +shutdown, to provide custom (API) endpoints with special functionality, to react on system events or to add support for +additional slicers. More plugin types are planned for the future. -.. _sec-plugins-installation: +.. toctree:: + :maxdepth: 3 -Installing Plugins -================== - -Plugins can be installed either by unpacking them into one of the configured plugin folders (regularly those are -``/plugins`` and ``~/.octoprint/plugins`` or by installing them as regular python modules via ``pip``. -Please refer to the documentation of the plugin for installations instructions. - -The latter is the more common case since all currently published plugins not bundled with OctoPrint can and should be installed -this way. - -For a plugin available on the Python Package Index (PyPi), the process is as simple as issuing a - -.. code-block:: bash - - pip install - -For plugins not available on PyPi, you'll have to give ``pip`` an URL from which to install the package (e.g. the URL to -a ZIP file of the current master branch of a Github repository hosting a plugin, or even a ``git+https`` URL), example: - -.. code-block:: bash - - pip install https://github.com/OctoPrint/OctoPrint-Growl/archive/master.zip - -See `the pip install documentation `_ for what URL -types are possible. - -.. _sec-plugins-available: - -Available Plugins -================= - -Currently there's no such thing as a centralized plugin repository for available plugins. - -Plugins may be found in the lists provided in `the OctoPrint wiki `_ -and on the `OctoPrint organization Github page `_. - -.. _sec-plugins-developing: - -Developing Plugins -================== - -.. todo:: - - A section on how to develop plugins yourself, including a tutorial creating an exemplatory plugin as well as - a documentation of the plugin API, will be added in the near future. + using.rst + gettingstarted.rst + infrastructure.rst + templates.rst + distributing.rst + mixins.rst + hooks.rst diff --git a/docs/plugins/infrastructure.rst b/docs/plugins/infrastructure.rst new file mode 100644 index 000000000..52f058e12 --- /dev/null +++ b/docs/plugins/infrastructure.rst @@ -0,0 +1,70 @@ +.. _sec-plugins-infrastructure: + +Plugin Infrastructure +===================== + +.. _sec-plugins-infrastructure-controlproperties: + +Control Properties +------------------ + +``__plugin_name__`` + Name of your plugin, optional, overrides the name specified in ``setup.py`` if provided. +``__plugin_version__`` + Version of your plugin, optional, overrides the version specified in ``setup.py`` if provided. +``__plugin_description__`` + Description of your plugin, optional, overrides the description specified in ``setup.py`` if provided. +``__plugin_author__`` + Author of your plugin, optional, overrides the author specified in ``setup.py`` if provided. +``__plugin_url__`` + URL of the webpage of your plugin, e.g. the Github repository, optional, overrides the URL specified in ``setup.py`` if + provided. +``__plugin_license__`` + License of your plugin, optional, overrides the license specified in ``setup.py`` if provided. +``__plugin_implementations__`` + Instances of one or more of the various :ref:`plugin mixins ` +``__plugin_hooks__`` + Handlers for one or more of the various :ref:`plugin hooks ` +``__plugin_check__`` + Method called upon discovery of the plugin by the plugin subsystem, should return ``True`` if the + plugin can be instantiated later on, ``False`` if there are reasons why not, e.g. if dependencies + are missing. +``__plugin_init__`` + Method called upon initializing of the plugin by the plugin subsystem, can be used to instantiate + plugin implementations, connecting them to hooks etc. + +.. _sec-plugins-infrastructure-injections: + +Injected Properties +------------------- + +``self._identifier`` + The plugin's identifier. +``self._plugin_name`` + The plugin's name, as taken from either the ``__plugin_name__`` control property or the package info. +``self._plugin_version`` + The plugin's version, as taken from either the ``__plugin_version__`` control property or the package info. +``self._basefolder`` + The plugin's base folder where it's installed. Can be used to refer to files relative to the plugin's installation + location, e.g. included scripts, templates or assets. +``self._logger`` + A `python logger instance `_ logging to the log target + ``octoprint.plugin.``. +``self._settings`` + The plugin's personalized settings manager, injected only into plugins that include the :class:`SettingsPlugin` mixin. +``self._plugin_manager`` + OctoPrint's plugin manager. +``self._printer_profile_manager`` + OctoPrint's printer profile manager. +``self._event_bus`` + OctoPrint's event bus. +``self._analysis_queue`` + OctoPrint's analysis queue for analyzing GCODEs or other files. +``self._slicing_manager`` + OctoPrint's slicing manager. +``self._file_manager`` + OctoPrint's file manager. +``self._printer`` + OctoPrint's printer management object. +``self._app_session_manager`` + OctoPrint's application session manager. diff --git a/docs/plugins/mixins.rst b/docs/plugins/mixins.rst new file mode 100644 index 000000000..c414934de --- /dev/null +++ b/docs/plugins/mixins.rst @@ -0,0 +1,101 @@ +.. _sec-plugins-mixins: + +Available plugin mixins +======================= + +The following plugin mixins are currently available: + +.. contents:: + :local: + +Please note that all plugin mixins inherit from :class:`~octoprint.plugin.core.Plugin` and +:class:`~octoprint.plugin.types.OctoPrintPlugin`, which also provide attributes of interest to plugin developers. + +.. _sec-plugins-mixins-startupplugin: + +StartupPlugin +------------- + +.. autoclass:: octoprint.plugin.StartupPlugin + :members: + +.. _sec-plugins-mixins-shutdownplugin: + +ShutdownPlugin +-------------- + +.. autoclass:: octoprint.plugin.ShutdownPlugin + :members: + +.. _sec-plugins-mixins-settingsplugin: + +SettingsPlugin +-------------- + +.. autoclass:: octoprint.plugin.SettingsPlugin + :members: + +.. _sec-plugins-mixins-assetplugin: + +AssetPlugin +----------- + +.. autoclass:: octoprint.plugin.AssetPlugin + :members: + +.. _sec-plugins-mixins-templateplugin: + +TemplatePlugin +-------------- + +.. autoclass:: octoprint.plugin.TemplatePlugin + :members: + +.. _sec-plugins-mixins-simpleapiplugin: + +SimpleApiPlugin +--------------- + +.. autoclass:: octoprint.plugin.SimpleApiPlugin + :members: + +.. _sec-plugins-mixins-blueprintplugin: + +BlueprintPlugin +--------------- + +.. autoclass:: octoprint.plugin.BlueprintPlugin + :members: + +.. _sec-plugins-mixins-eventhandlerplugin: + +EventHandlerPlugin +------------------ + +.. autoclass:: octoprint.plugin.EventHandlerPlugin + :members: + +.. _sec-plugins-mixins-progressplugin: + +ProgressPlugin +-------------- + +.. autoclass:: octoprint.plugin.ProgressPlugin + :members: + +.. _sec-plugins-mixins-slicerplugin: + +SlicerPlugin +------------ + +.. autoclass:: octoprint.plugin.SlicerPlugin + :members: + +.. _sec-plugins-mixins-appplugin: + +AppPlugin +--------- + +.. autoclass:: octoprint.plugin.AppPlugin + :members: + diff --git a/docs/plugins/templates.rst b/docs/plugins/templates.rst new file mode 100644 index 000000000..c4547dfb1 --- /dev/null +++ b/docs/plugins/templates.rst @@ -0,0 +1,8 @@ +.. _sec-plugins-templates: + +Templates +========= + +.. todo:: + + Needs to be written. \ No newline at end of file diff --git a/docs/plugins/using.rst b/docs/plugins/using.rst new file mode 100644 index 000000000..898996e51 --- /dev/null +++ b/docs/plugins/using.rst @@ -0,0 +1,44 @@ +.. _sec-plugins-using: + +************* +Using Plugins +************* + +.. _sec-plugins-using-available: + +Finding Plugins +=============== + +Currently there's no such thing as a centralized plugin repository for available plugins. + +Plugins may be found in the lists provided in `the OctoPrint wiki `_ +and on the `OctoPrint organization Github page `_. + +.. _sec-plugins-using-installing: + +Installing Plugins +================== + +Plugins can be installed either by unpacking them into one of the configured plugin folders (regularly those are +``/plugins`` and ``~/.octoprint/plugins`` or by installing them as regular python modules via ``pip``. +Please refer to the documentation of the plugin for installations instructions. + +The latter is the more common case since all currently published plugins not bundled with OctoPrint can and should be installed +this way. + +For a plugin available on the Python Package Index (PyPi), the process is as simple as issuing a + +.. code-block:: bash + + pip install + +For plugins not available on PyPi, you'll have to give ``pip`` an URL from which to install the package (e.g. the URL to +a ZIP file of the current master branch of a Github repository hosting a plugin, or even a ``git+https`` URL), example: + +.. code-block:: bash + + pip install https://github.com/OctoPrint/OctoPrint-Growl/archive/master.zip + +See `the pip install documentation `_ for what URL +types are possible. + diff --git a/docs/requirements.txt b/docs/requirements.txt deleted file mode 100644 index 28a38e6dd..000000000 --- a/docs/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -sphinxcontrib-httpdomain -sphinx_rtd_theme diff --git a/docs/sphinxext/codeblockext.py b/docs/sphinxext/codeblockext.py new file mode 100644 index 000000000..d70d883c2 --- /dev/null +++ b/docs/sphinxext/codeblockext.py @@ -0,0 +1,258 @@ +# coding=utf-8 +from __future__ import absolute_import + +__author__ = "Gina Häußge " +__license__ = 'The MIT License ' +__copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the MIT License" + +from sphinx.directives.code import CodeBlock + +import sphinx.highlighting +from sphinx.highlighting import PygmentsBridge +from sphinx.ext import doctest +from sphinx.util.texescape import tex_hl_escape_map_new + +from docutils.nodes import General, FixedTextElement, literal_block, container +from docutils.parsers.rst import directives + +from six import text_type + +from pygments import highlight +from pygments.filters import VisibleWhitespaceFilter, ErrorToken +from pygments.lexers.python import PythonConsoleLexer +from pygments.util import ClassNotFound + +def _merge_dict(a, b): + """ + Little helper to merge two dicts a and b on the fly. + """ + result = dict(a) + result.update(b) + return result + +class literal_block_ext(General, FixedTextElement): + """ + Custom node which is basically the same as a :class:`literal_block`, just with whitespace support and introduced + in order to be able to have a custom visitor. + """ + + @classmethod + def from_literal_block(cls, block): + """ + Factory method constructing an instance exactly copying all attributes over from ``block`` and settings a + custom ``tagname``. + """ + new = literal_block_ext() + for a in ("attributes", "basic_attributes", "child_text_separator", "children", "document", "known_attributes", + "line", "list_attributes", "local_attributes", "parent", "rawsource", "source"): + setattr(new, a, getattr(block, a)) + new.tagname = "literal_block_ext" + return new + +class CodeBlockExt(CodeBlock): + """ + This is basically an extension of a regular :class:`CodeBlock` directive which just supports an additional option + ``whitespace`` which if present will enable (together with everything else in here) to render whitespace in + code blocks. + """ + + option_spec = _merge_dict(CodeBlock.option_spec, dict(whitespace=directives.flag)) + + def run(self): + # get result from parent implementation + code_block = CodeBlock.run(self) + + def find_and_wrap_literal_block(node): + """ + Recursive method to turn all literal blocks located within a node into :class:`literal_block_ext`. + """ + + if isinstance(node, container): + # container node => handle all children + children = [] + for child in node.children: + children.append(find_and_wrap_literal_block(child)) + node.children = children + return node + + elif isinstance(node, literal_block): + # literal block => replace it + return self._wrap_literal_block(node) + + else: + # no idea what that is => leave it alone + return node + + # replace all created literal_blocks with literal_block_ext instances + return map(find_and_wrap_literal_block, code_block) + + def _wrap_literal_block(self, node): + literal = literal_block_ext.from_literal_block(node) + literal["whitespace"] = "whitespace" in self.options + return literal + +class PygmentsBridgeExt(object): + """ + Wrapper for :class:`PygmentsBridge`, delegates everything to the wrapped ``bridge`` but :method:`highlight_block`, + which calls the parent implementation for lexer selection, then + """ + + def __init__(self, bridge, whitespace): + self._bridge = bridge + self._whitespace = whitespace + + def __getattr__(self, item): + return getattr(self._bridge, item) + + def highlight_block(self, source, lang, opts=None, warn=None, force=False, **kwargs): + if not self._whitespace: + return self._bridge.highlight_block(source, lang, opts=opts, warn=warn, force=force, **kwargs) + + # We are still here => we need to basically do everything the parent implementation does (and does so in a very + # unextensible way...), but inject the whitespace filter into the used lexer just before the highlighting run + # and remove it afterwards so the lexer can be safely reused. + # + # For this we define a context manager that will allow us to wrap a lexer and modify its filters on the fly to + # include the whitespace filter. + + class whitespace(object): + def __init__(self, lexer): + self._lexer = lexer + self._orig_filters = lexer.filters + self._orig_tabsize = lexer.tabsize + + def __enter__(self): + new_filters = list(self._orig_filters) + new_filters.append(VisibleWhitespaceFilter(spaces=True, tabs=True, tabsize=self._lexer.tabsize)) + self._lexer.filters = new_filters + self._lexer.tabsize = 0 + return self._lexer + + def __exit__(self, type, value, traceback): + self._lexer.filters = self._orig_filters + self._lexer.tabsize = self._orig_tabsize + + # Then a ton of copy-pasted code follows. Sadly, we need to do this since we have no way to inject ourselves + # into the highlighting call otherwise - lexer selection and actual call are tightly coupled in the original + # "highlight_block" method, with no means for external code to inject different functionality. + # + # Unless otherwise marked ("MODIFIED"), any code in this method after this line is copied verbatim from the + # implementation of sphinx.highlighting.PygmentsBridge, released under the Simplified BSD License, the copyright + # lies with the respective authors. + + if not isinstance(source, text_type): + source = source.decode() + + # find out which lexer to use + if lang in ('py', 'python'): + if source.startswith('>>>'): + # interactive session + lexer = sphinx.highlighting.lexers['pycon'] + elif not force: + # maybe Python -- try parsing it + if self.try_parse(source): + lexer = sphinx.highlighting.lexers['python'] + else: + lexer = sphinx.highlighting.lexers['none'] + else: + lexer = sphinx.highlighting.lexers['python'] + elif lang in ('python3', 'py3') and source.startswith('>>>'): + # for py3, recognize interactive sessions, but do not try parsing... + lexer = sphinx.highlighting.lexers['pycon3'] + elif lang == 'guess': + try: + lexer = sphinx.highlighting.guess_lexer(source) + except Exception: + lexer = sphinx.highlighting.lexers['none'] + else: + if lang in sphinx.highlighting.lexers: + lexer = sphinx.highlighting.lexers[lang] + else: + try: + lexer = sphinx.highlighting.lexers[lang] = sphinx.highlighting.get_lexer_by_name(lang, **opts or {}) + except ClassNotFound: + if warn: + warn('Pygments lexer name %r is not known' % lang) + lexer = sphinx.highlighting.lexers['none'] + else: + raise + else: + lexer.add_filter('raiseonerror') + + if not isinstance(source, text_type): + source = source.decode() + + # trim doctest options if wanted + if isinstance(lexer, PythonConsoleLexer) and self._bridge.trim_doctest_flags: + source = doctest.blankline_re.sub('', source) + source = doctest.doctestopt_re.sub('', source) + + # highlight via Pygments + formatter = self._bridge.get_formatter(**kwargs) + try: + # MODIFIED: replaced by whitespace wrapped call + with whitespace(lexer) as l: + hlsource = highlight(source, l, formatter) + # /MODIFIED + except ErrorToken: + # this is most probably not the selected language, + # so let it pass unhighlighted + + # MODIFIED: replaced by whitespace wrapped call + with whitespace(sphinx.highlighting.lexers["none"]) as l: + hlsource = highlight(source, l, formatter) + # /MODIFIED + if self._bridge.dest == 'html': + return hlsource + else: + if not isinstance(hlsource, text_type): # Py2 / Pygments < 1.6 + hlsource = hlsource.decode() + return hlsource.translate(tex_hl_escape_map_new) + + +class whitespace_highlighter(object): + """ + Context manager for adapting the used highlighter on a translator for a given node's whitespace properties. + """ + def __init__(self, translator, node): + self.translator = translator + self.node = node + + self._orig_highlighter = self.translator.highlighter + + def __enter__(self): + whitespace = self.node["whitespace"] if "whitespace" in self.node else False + if whitespace: + self.translator.highlighter = PygmentsBridgeExt(self._orig_highlighter, whitespace) + return self.translator + + def __exit__(self, exc_type, exc_val, exc_tb): + self.translator.highlighter = self._orig_highlighter + + +def visit_literal_block_ext(translator, node): + """ + When our custom code block is visited, we temporarily exchange the highlighter used in the translator, call the + visitor for regular literal blocks, then switch back again. + """ + with whitespace_highlighter(translator, node): + translator.visit_literal_block(node) + + +def depart_literal_block_ext(translator, node): + """ + Just call the depart function for regular literal blocks. + """ + with whitespace_highlighter(translator, node): + translator.depart_literal_block(node) + + +def setup(app): + # custom directive + app.add_directive("code-block-ext", CodeBlockExt) + + # custom node type + handler = (visit_literal_block_ext, depart_literal_block_ext) + app.add_node(literal_block_ext, html=handler, latex=handler, text=handler) + + return dict(version="0.1") \ No newline at end of file diff --git a/requirements-bbb.txt b/requirements-bbb.txt deleted file mode 100644 index 127383ed9..000000000 --- a/requirements-bbb.txt +++ /dev/null @@ -1,15 +0,0 @@ -flask==0.9 -werkzeug==0.8.3 -tornado==3.0.2 -sockjs-tornado>=1.0.0 -PyYAML==3.10 -Flask-Login==0.2.2 -Flask-Principal==0.3.5 -netaddr>=0.7.10 -mock>=1.0.1 -nose>=1.3.0 -watchdog -sarge - -sphinxcontrib-httpdomain -sphinx_rtd_theme diff --git a/requirements-dev.txt b/requirements-dev.txt deleted file mode 100644 index eac1a3bb0..000000000 --- a/requirements-dev.txt +++ /dev/null @@ -1,5 +0,0 @@ -mock>=1.0.1 -nose>=1.3.0 -sphinxcontrib-httpdomain -sphinx_rtd_theme -po2json diff --git a/requirements.txt b/requirements.txt index 121234d55..3175f72cd 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,13 +1,10 @@ -flask==0.9 -werkzeug==0.8.3 -tornado==4.0.1 -sockjs-tornado>=1.0.0 -PyYAML==3.10 -Flask-Login==0.2.2 -Flask-Principal==0.3.5 -Flask-Babel==0.9 -pyserial -netaddr -watchdog -sarge -netifaces +### +# This file is only here to make sure that something like +# +# pip install -e .[develop] +# +# works as expected. Requirements can be found in setup.py in the +# variables INSTALL_REQUIRES and EXTRA_REQUIRES. +### + +. diff --git a/setup.py b/setup.py index d6b6cb4ba..c15f88502 100644 --- a/setup.py +++ b/setup.py @@ -1,7 +1,64 @@ -# coding=utf-8 #!/usr/bin/env python +# coding=utf-8 +from setuptools import setup, find_packages, Command +import os +import shutil +import glob import versioneer + +#----------------------------------------------------------------------------------------------------------------------- + +# Requirements for out application +INSTALL_REQUIRES = [ + "flask==0.9", + "werkzeug==0.8.3", + "tornado==4.0.1", + "sockjs-tornado>=1.0.0", + "PyYAML==3.10", + "Flask-Login==0.2.2", + "Flask-Principal==0.3.5", + "Flask-Babel==0.9", + "pyserial", + "netaddr", + "watchdog", + "sarge>=0.1.4", + "netifaces", + "pylru", + "rsa", + "pkginfo" +] + +# Requirements for developing etc +EXTRA_REQUIRES = dict( + develop=[ + # Testing dependencies + "mock>=1.0.1", + "nose>=1.3.0", + "ddt", + + # Documentation dependencies + "sphinx>=1.3", + "sphinxcontrib-httpdomain", + "sphinx_rtd_theme", + + # Translation dependencies + "po2json" + ] +) + +# Dependency links for any of the aforementioned dependencies +DEPENDENCY_LINKS = [] + +# I18N setup +I18N_MAPPING_FILE = "babel.cfg" +I18N_DOMAIN = "messages" +I18N_INPUT_DIRS = "." +I18N_OUTPUT_DIR_PY = os.path.join("src", "octoprint", "translations") +I18N_OUTPUT_DIR_JS = os.path.join("src", "octoprint", "static", "js", "i18n") +I18N_POT_FILE = os.path.join(I18N_OUTPUT_DIR_PY, "messages.pot") + +# Versioneer configuration versioneer.VCS = 'git' versioneer.versionfile_source = 'src/octoprint/_version.py' versioneer.versionfile_build = 'octoprint/_version.py' @@ -9,17 +66,8 @@ versioneer.tag_prefix = '' versioneer.parentdir_prefix = '' versioneer.lookupfile = '.versioneer-lookup' -from setuptools import setup, find_packages, Command -import os -import shutil -import glob - -I18N_MAPPING_FILE = "babel.cfg" -I18N_DOMAIN = "messages" -I18N_INPUT_DIRS = "." -I18N_OUTPUT_DIR_PY = os.path.join("src", "octoprint", "translations") -I18N_OUTPUT_DIR_JS = os.path.join("src", "octoprint", "static", "js", "i18n") -I18N_POT_FILE = os.path.join(I18N_OUTPUT_DIR_PY, "messages.pot") +#----------------------------------------------------------------------------------------------------------------------- +# Anything below here is just command setup and general setup configuration def package_data_dirs(source, sub_folders): dirs = [] @@ -33,6 +81,26 @@ def package_data_dirs(source, sub_folders): return dirs +def _recursively_handle_files(directory, file_matcher, folder_handler=None, file_handler=None): + applied_handler = False + + for filename in os.listdir(directory): + path = os.path.join(directory, filename) + + if file_handler is not None and file_matcher(filename): + file_handler(path) + applied_handler = True + + elif os.path.isdir(path): + sub_applied_handler = _recursively_handle_files(path, file_matcher, folder_handler=folder_handler, file_handler=file_handler) + if sub_applied_handler: + applied_handler = True + + if folder_handler is not None: + folder_handler(path, sub_applied_handler) + + return applied_handler + class CleanCommand(Command): description = "clean build artifacts" user_options = [] @@ -45,14 +113,57 @@ class CleanCommand(Command): pass def run(self): + # build folder if os.path.exists('build'): print "Deleting build directory" shutil.rmtree('build') + + # eggs eggs = glob.glob('OctoPrint*.egg-info') for egg in eggs: print "Deleting %s directory" % egg shutil.rmtree(egg) + # pyc files + def delete_folder_if_empty(path, applied_handler): + if not applied_handler: + return + if len(os.listdir(path)) == 0: + shutil.rmtree(path) + print "Deleted %s since it was empty" % path + + def delete_file(path): + os.remove(path) + print "Deleted %s" % path + + import fnmatch + _recursively_handle_files( + os.path.abspath("src"), + lambda name: fnmatch.fnmatch(name.lower(), "*.pyc"), + folder_handler=delete_folder_if_empty, + file_handler=delete_file + ) + + # pyc files + def delete_folder_if_empty(path, applied_handler): + if not applied_handler: + return + if len(os.listdir(path)) == 0: + shutil.rmtree(path) + print "Deleted %s since it was empty" % path + + def delete_file(path): + os.remove(path) + print "Deleted %s" % path + + import fnmatch + _recursively_handle_files( + os.path.abspath("src"), + lambda name: fnmatch.fnmatch(name.lower(), "*.pyc"), + folder_handler=delete_folder_if_empty, + file_handler=delete_file + ) + class NewTranslation(Command): description = "create a new translation" @@ -131,7 +242,7 @@ class RefreshTranslation(Command): self.babel_extract_messages.copyright_holder = "The OctoPrint Project" self.babel_extract_messages.finalize_options() - self.babel_update_messages.input_file = I18N_MAPPING_FILE + self.babel_update_messages.input_file = I18N_POT_FILE self.babel_update_messages.output_dir = I18N_OUTPUT_DIR_PY self.babel_update_messages.locale = self.locale @@ -220,11 +331,23 @@ def params(): packages = find_packages(where="src") package_dir = {"octoprint": "src/octoprint"} - package_data = {"octoprint": package_data_dirs('src/octoprint', ['static', 'templates', 'plugins'])} + package_data = {"octoprint": package_data_dirs('src/octoprint', ['static', 'templates', 'plugins', 'translations'])} include_package_data = True zip_safe = False - install_requires = open("requirements.txt").read().split("\n") + install_requires = INSTALL_REQUIRES + extras_require = EXTRA_REQUIRES + dependency_links = DEPENDENCY_LINKS + + if os.environ.get('READTHEDOCS', None) == 'True': + # we can't tell read the docs to please perform a pip install -e .[develop], so we help + # it a bit here by explicitly adding the development dependencies, which include our + # documentation dependencies + install_requires = install_requires + extras_require['develop'] + + import sys + if sys.platform in ("linux2", "darwin"): + install_requires += ["monotime"] entry_points = { "console_scripts": [ @@ -232,10 +355,6 @@ def params(): ] } - #scripts = { - # "scripts/octoprint.init": "/etc/init.d/octoprint" - #} - return locals() setup(**params()) diff --git a/src/octoprint/_version.py b/src/octoprint/_version.py index 3808a4f84..35090f5b8 100644 --- a/src/octoprint/_version.py +++ b/src/octoprint/_version.py @@ -214,7 +214,7 @@ def versions_from_parentdir(parentdir_prefix, root, verbose=False): print("guessing rootdir is '%s', but '%s' doesn't start with prefix '%s'" % (root, dirname, parentdir_prefix)) return None - return {"version": dirname[len(parentdir_prefix):], "full": ""} + return {"version": dirname[len(parentdir_prefix):], "full": "", "branch": ""} tag_prefix = "" parentdir_prefix = "" @@ -249,7 +249,7 @@ def parse_lookup_file(root, lookup_path=None): break return lookup -def get_versions(default={"version": "unknown", "full": ""}, lookup_path=None, verbose=False): +def get_versions(default={"version": "unknown", "full": "", "branch": "unknown"}, lookup_path=None, verbose=False): # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which diff --git a/src/octoprint/daemon.py b/src/octoprint/daemon.py index f27a91023..4ef56b162 100644 --- a/src/octoprint/daemon.py +++ b/src/octoprint/daemon.py @@ -4,7 +4,7 @@ Generic linux daemon base class for python 3.x Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35 """ -import sys, os, time, atexit, signal +import sys, os, time, signal class Daemon: """A generic daemon class. @@ -53,14 +53,16 @@ class Daemon: os.dup2(se.fileno(), sys.stderr.fileno()) # write pidfile - atexit.register(self.delpid) - pid = str(os.getpid()) with open(self.pidfile,'w+') as f: f.write(pid + '\n') - - def delpid(self): + + # register listener for SIGTERM + signal.signal(signal.SIGTERM, self.term) + + def term(self, _signo, _stack_frame): os.remove(self.pidfile) + sys.exit(0) def start(self): """Start the daemon.""" diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 4a3d2023e..e176b0529 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -20,7 +20,7 @@ _instance = None def all_events(): - return [name for name in Events.__dict__ if not name.startswith("__")] + return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("__")] class Events(object): @@ -42,6 +42,7 @@ class Events(object): UPDATED_FILES = "UpdatedFiles" METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted" METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished" + METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated" # SD Upload TRANSFER_STARTED = "TransferStarted" @@ -62,11 +63,13 @@ class Events(object): HOME = "Home" Z_CHANGE = "ZChange" WAITING = "Waiting" + DWELL = "Dwelling" COOLING = "Cooling" ALERT = "Alert" CONVEYOR = "Conveyor" EJECT = "Eject" E_STOP = "EStop" + REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived" # Timelapse CAPTURE_START = "CaptureStart" @@ -79,6 +82,10 @@ class Events(object): SLICING_STARTED = "SlicingStarted" SLICING_DONE = "SlicingDone" SLICING_FAILED = "SlicingFailed" + SLICING_CANCELLED = "SlicingCancelled" + + # Settings + SETTINGS_UPDATED = "SettingsUpdated" def eventManager(): @@ -103,22 +110,25 @@ class EventManager(object): self._worker.start() def _work(self): - while True: - (event, payload) = self._queue.get(True) + try: + while True: + (event, payload) = self._queue.get(True) - eventListeners = self._registeredListeners[event] - self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload)) + eventListeners = self._registeredListeners[event] + self._logger.debug("Firing event: %s (Payload: %r)" % (event, payload)) - for listener in eventListeners: - self._logger.debug("Sending action to %r" % listener) - try: - listener(event, payload) - except: - self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener)) + for listener in eventListeners: + self._logger.debug("Sending action to %r" % listener) + try: + listener(event, payload) + except: + self._logger.exception("Got an exception while sending event %s (Payload: %r) to %s" % (event, payload, listener)) - octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin, - "on_event", - args=[event, payload]) + octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin, + "on_event", + args=[event, payload]) + except: + self._logger.exception("Ooops, the event bus worker loop crashed") def fire(self, event, payload=None): """ @@ -133,6 +143,15 @@ class EventManager(object): self._queue.put((event, payload), 0) + if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables": + # when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode" + # TODO v1.3.0 Remove again + import copy + legacy_payload = copy.deepcopy(payload) + legacy_payload["type"] = "gcode" + self._queue.put((event, legacy_payload), 0) + + def subscribe(self, event, callback): """ Subscribe a listener to an event -- pass in the event name (as a string) and the callback object @@ -293,7 +312,7 @@ class CommandTrigger(GenericEventListener): def _executeGcodeCommand(self, command): commands = [command] if isinstance(command, (list, tuple, set)): - self.logger.debug("Executing GCode commands: %r" % command) + self._logger.debug("Executing GCode commands: %r" % command) commands = list(command) else: self._logger.debug("Executing GCode command: %s" % command) @@ -322,7 +341,7 @@ class CommandTrigger(GenericEventListener): "__now": datetime.datetime.now().isoformat() } - currentData = self._printer.getCurrentData() + currentData = self._printer.get_current_data() if "currentZ" in currentData.keys() and currentData["currentZ"] is not None: params["__currentZ"] = str(currentData["currentZ"]) diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 7aaa5e369..dfab1da8b 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -1,3 +1,382 @@ # coding=utf-8 -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +from __future__ import absolute_import + +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import logging +import os + +import octoprint.plugin + +from octoprint.events import eventManager, Events + +from .destinations import FileDestinations +from .analysis import QueueEntry, AnalysisQueue +from .storage import LocalFileStorage + +extensions = dict( + # extensions for 3d model files + model=dict( + stl=["stl"] + ), + # extensions for printable machine code + machinecode=dict( + gcode=["gcode", "gco", "g"] + ) +) + +def get_extensions(type, subtree=None): + if not subtree: + subtree = extensions + + for key, value in subtree.items(): + if key == type: + return get_all_extensions(subtree=value) + elif isinstance(value, dict): + sub_extensions = get_extensions(type, subtree=value) + if sub_extensions: + return sub_extensions + + return None + +def get_all_extensions(subtree=None): + if not subtree: + subtree = extensions + + result = [] + if isinstance(subtree, dict): + for key, value in subtree.items(): + if isinstance(value, dict): + result += get_all_extensions(value) + elif isinstance(value, (list, tuple)): + result += value + elif isinstance(subtree, (list, tuple)): + result = subtree + return result + +def get_path_for_extension(extension, subtree=None): + if not subtree: + subtree = extensions + + for key, value in subtree.items(): + if isinstance(value, (list, tuple)) and extension in value: + return [key] + elif isinstance(value, dict): + path = get_path_for_extension(extension, subtree=value) + if path: + return [key] + path + + return None + +all_extensions = get_all_extensions() + +def valid_extension(extension, type=None): + if not type: + return extension in all_extensions + else: + extensions = get_extensions(type) + if extensions: + return extension in extensions + +def valid_file_type(filename, type=None): + _, extension = os.path.splitext(filename) + extension = extension[1:].lower() + return valid_extension(extension, type=type) + +def get_file_type(filename): + _, extension = os.path.splitext(filename) + extension = extension[1:].lower() + return get_path_for_extension(extension) + + +class NoSuchStorage(Exception): + pass + + +class FileManager(object): + def __init__(self, analysis_queue, slicing_manager, printer_profile_manager, initial_storage_managers=None): + self._logger = logging.getLogger(__name__) + self._analysis_queue = analysis_queue + self._analysis_queue.register_finish_callback(self._on_analysis_finished) + + self._storage_managers = dict() + if initial_storage_managers: + self._storage_managers.update(initial_storage_managers) + + self._slicing_manager = slicing_manager + self._printer_profile_manager = printer_profile_manager + + import threading + self._slicing_jobs = dict() + self._slicing_jobs_mutex = threading.Lock() + + self._slicing_progress_callbacks = [] + self._last_slicing_progress = None + + self._progress_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.ProgressPlugin) + + for storage_type, storage_manager in self._storage_managers.items(): + self._determine_analysis_backlog(storage_type, storage_manager) + + def register_slicingprogress_callback(self, callback): + self._slicing_progress_callbacks.append(callback) + + def unregister_slicingprogress_callback(self, callback): + self._slicing_progress_callbacks.remove(callback) + + def _determine_analysis_backlog(self, storage_type, storage_manager): + self._logger.info("Adding backlog items from {storage_type} to analysis queue".format(**locals())) + for entry, path, printer_profile in storage_manager.analysis_backlog: + file_type = get_file_type(path)[-1] + + # we'll use the default printer profile for the backlog since we don't know better + queue_entry = QueueEntry(entry, file_type, storage_type, path, self._printer_profile_manager.get_default()) + self._analysis_queue.enqueue(queue_entry, high_priority=False) + + def add_storage(self, storage_type, storage_manager): + self._storage_managers[storage_type] = storage_manager + self._determine_analysis_backlog(storage_type, storage_manager) + + def remove_storage(self, type): + if not type in self._storage_managers: + return + del self._storage_managers[type] + + @property + def slicing_enabled(self): + return self._slicing_manager.slicing_enabled + + @property + def registered_slicers(self): + return self._slicing_manager.registered_slicers + + @property + def default_slicer(self): + return self._slicing_manager.default_slicer + + def slice(self, slicer_name, source_location, source_path, dest_location, dest_path, + position=None, profile=None, printer_profile_id=None, overrides=None, callback=None, callback_args=None): + absolute_source_path = self.path_on_disk(source_location, source_path) + + def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None): + try: + if _error: + eventManager().fire(Events.SLICING_FAILED, {"stl": source_path, "gcode": dest_path, "reason": _error}) + elif _cancelled: + eventManager().fire(Events.SLICING_CANCELLED, {"stl": source_path, "gcode": dest_path}) + else: + source_meta = self.get_metadata(source_location, source_path) + hash = source_meta["hash"] + + class Wrapper(object): + def __init__(self, stl_name, temp_path, hash): + self.stl_name = stl_name + self.temp_path = temp_path + self.hash = hash + + def save(self, absolute_dest_path): + with open(absolute_dest_path, "w") as d: + d.write(";Generated from {stl_name} {hash}\r".format(**vars(self))) + with open(tmp_path, "r") as s: + import shutil + shutil.copyfileobj(s, d) + + links = [("model", dict(name=source_path))] + _, stl_name = self.split_path(source_location, source_path) + file_obj = Wrapper(stl_name, temp_path, hash) + + printer_profile = self._printer_profile_manager.get(printer_profile_id) + self.add_file(dest_location, dest_path, file_obj, links=links, allow_overwrite=True, printer_profile=printer_profile, analysis=_analysis) + + end_time = time.time() + eventManager().fire(Events.SLICING_DONE, {"stl": source_path, "gcode": dest_path, "time": end_time - start_time}) + + if callback is not None: + if callback_args is None: + callback_args = () + callback(*callback_args) + finally: + os.remove(tmp_path) + + source_job_key = (source_location, source_path) + dest_job_key = (dest_location, dest_path) + + with self._slicing_jobs_mutex: + if source_job_key in self._slicing_jobs: + del self._slicing_jobs[source_job_key] + if dest_job_key in self._slicing_jobs: + del self._slicing_jobs[dest_job_key] + + slicer = self._slicing_manager.get_slicer(slicer_name) + + import time + start_time = time.time() + eventManager().fire(Events.SLICING_STARTED, {"stl": source_path, "gcode": dest_path, "progressAvailable": slicer.get_slicer_properties()["progress_report"] if slicer else False}) + + import tempfile + f = tempfile.NamedTemporaryFile(suffix=".gco", delete=False) + temp_path = f.name + f.close() + + with self._slicing_jobs_mutex: + source_job_key = (source_location, source_path) + dest_job_key = (dest_location, dest_path) + if dest_job_key in self._slicing_jobs: + job_slicer_name, job_absolute_source_path, job_temp_path = self._slicing_jobs[dest_job_key] + + self._slicing_manager.cancel_slicing(job_slicer_name, job_absolute_source_path, job_temp_path) + del self._slicing_jobs[dest_job_key] + + self._slicing_jobs[dest_job_key] = self._slicing_jobs[source_job_key] = (slicer_name, absolute_source_path, temp_path) + + args = (source_location, source_path, temp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args) + return self._slicing_manager.slice( + slicer_name, + absolute_source_path, + temp_path, + profile, + stlProcessed, + position=position, + callback_args=args, + overrides=overrides, + printer_profile_id=printer_profile_id, + on_progress=self.on_slicing_progress, + on_progress_args=(slicer_name, source_location, source_path, dest_location, dest_path)) + + def on_slicing_progress(self, slicer, source_location, source_path, dest_location, dest_path, _progress=None): + if not _progress: + return + + progress_int = int(_progress * 100) + if self._last_slicing_progress != progress_int: + self._last_slicing_progress = progress_int + for callback in self._slicing_progress_callbacks: + try: callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int) + except: self._logger.exception("Exception while pushing slicing progress") + + if progress_int: + def call_plugins(slicer, source_location, source_path, dest_location, dest_path, progress): + for name, plugin in self._progress_plugins.items(): + try: + plugin.on_slicing_progress(slicer, source_location, source_path, dest_location, dest_path, progress) + except: + self._logger.exception("Exception while sending slicing progress to plugin %s" % name) + + import threading + thread = threading.Thread(target=call_plugins, args=(slicer, source_location, source_path, dest_location, dest_path, progress_int)) + thread.daemon = False + thread.start() + + + def get_busy_files(self): + return self._slicing_jobs.keys() + + def file_exists(self, destination, path): + return self._storage(destination).file_exists(path) + + def list_files(self, destinations=None, path=None, filter=None, recursive=None): + if not destinations: + destinations = self._storage_managers.keys() + if isinstance(destinations, (str, unicode, basestring)): + destinations = [destinations] + + result = dict() + for dst in destinations: + result[dst] = self._storage_managers[dst].list_files(path=path, filter=filter, recursive=recursive) + return result + + def add_file(self, destination, path, file_object, links=None, allow_overwrite=False, printer_profile=None, analysis=None): + if printer_profile is None: + printer_profile = self._printer_profile_manager.get_current_or_default() + + file_path = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite) + absolute_path = self._storage(destination).path_on_disk(file_path) + + if analysis is None: + file_type = get_file_type(absolute_path) + if file_type: + queue_entry = QueueEntry(file_path, file_type[-1], destination, absolute_path, printer_profile) + self._analysis_queue.enqueue(queue_entry, high_priority=True) + else: + self._add_analysis_result(destination, path, analysis) + + eventManager().fire(Events.UPDATED_FILES, dict(type="printables")) + return file_path + + def remove_file(self, destination, path): + self._storage(destination).remove_file(path) + 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")) + return folder_path + + def remove_folder(self, destination, path, recursive=True): + self._storage(destination).remove_folder(path, recursive=recursive) + eventManager().fire(Events.UPDATED_FILES, dict(type="printables")) + + def get_metadata(self, destination, path): + return self._storage(destination).get_metadata(path) + + def add_link(self, destination, path, rel, data): + self._storage(destination).add_link(path, rel, data) + + def remove_link(self, destination, path, rel, data): + self._storage(destination).remove_link(path, rel, data) + + def log_print(self, destination, path, timestamp, print_time, success, printer_profile): + try: + if success: + self._storage(destination).add_history(path, dict(timestamp=timestamp, printTime=print_time, success=success, printerProfile=printer_profile)) + else: + self._storage(destination).add_history(path, dict(timestamp=timestamp, success=success, printerProfile=printer_profile)) + eventManager().fire(Events.METADATA_STATISTICS_UPDATED, dict(storage=destination, path=path)) + except NoSuchStorage: + # if there's no storage configured where to log the print, we'll just not log it + pass + + def set_additional_metadata(self, destination, path, key, data, overwrite=False, merge=False): + self._storage(destination).set_additional_metadata(path, key, data, overwrite=overwrite, merge=merge) + + def remove_additional_metadata(self, destination, path, key): + self._storage(destination).remove_additional_metadata(path, key) + + def path_on_disk(self, destination, path): + return self._storage(destination).path_on_disk(path) + + def sanitize(self, destination, path): + return self._storage(destination).sanitize(path) + + def sanitize_name(self, destination, name): + return self._storage(destination).sanitize_name(name) + + def sanitize_path(self, destination, path): + return self._storage(destination).sanitize_path(path) + + def split_path(self, destination, path): + return self._storage(destination).split_path(path) + + def join_path(self, destination, *path): + return self._storage(destination).join_path(*path) + + def path_in_storage(self, destination, path): + return self._storage(destination).path_in_storage(path) + + def _storage(self, destination): + if not destination in self._storage_managers: + raise NoSuchStorage("No storage configured for destination {destination}".format(**locals())) + return self._storage_managers[destination] + + def _add_analysis_result(self, destination, path, result): + if not destination in self._storage_managers: + return + + storage_manager = self._storage_managers[destination] + storage_manager.set_additional_metadata(path, "analysis", result) + + def _on_analysis_finished(self, entry, result): + self._add_analysis_result(entry.location, entry.path, result) diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py new file mode 100644 index 000000000..f746c228d --- /dev/null +++ b/src/octoprint/filemanager/analysis.py @@ -0,0 +1,166 @@ +# 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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import logging +import Queue as queue +import os +import threading +import collections + +from octoprint.events import Events, eventManager + +import octoprint.util.gcodeInterpreter as gcodeInterpreter + + +class QueueEntry(collections.namedtuple("QueueEntry", "path, type, location, absolute_path, printer_profile")): + def __str__(self): + return "{location}:{path}".format(location=self.location, path=self.path) + + +class AnalysisQueue(object): + def __init__(self): + self._logger = logging.getLogger(__name__) + self._callbacks = [] + self._queues = dict( + gcode=GcodeAnalysisQueue(self._analysis_finished) + ) + + def register_finish_callback(self, callback): + self._callbacks.append(callback) + + def unregister_finish_callback(self, callback): + self._callbacks.remove(callback) + + def enqueue(self, entry, high_priority=False): + if not entry.type in self._queues: + return + + self._queues[entry.type].enqueue(entry, high_priority=high_priority) + + def pause(self): + for queue in self._queues.values(): + queue.pause() + + def resume(self): + for queue in self._queues.values(): + queue.resume() + + def _analysis_finished(self, entry, result): + for callback in self._callbacks: + callback(entry, result) + eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"file": entry.path, "result": result}) + +class AbstractAnalysisQueue(object): + def __init__(self, finished_callback): + self._logger = logging.getLogger(__name__) + + self._finished_callback = finished_callback + + self._active = threading.Event() + self._active.set() + + self._currentFile = None + self._currentProgress = None + + self._queue = queue.PriorityQueue() + self._current = None + + self._worker = threading.Thread(target=self._work) + self._worker.daemon = True + self._worker.start() + + def enqueue(self, entry, high_priority=False): + if high_priority: + self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry)) + prio = 0 + else: + self._logger.debug("Adding entry {entry} to analysis queue with low priority".format(entry=entry)) + prio = 100 + + self._queue.put((prio, entry)) + + def pause(self): + self._logger.debug("Pausing analysis") + self._active.clear() + if self._current is not None: + self._logger.debug("Aborting running analysis, will restart when analyzer is resumed") + self._do_abort() + + def resume(self): + self._logger.debug("Resuming analyzer") + self._active.set() + + def _work(self): + aborted = None + while True: + if aborted is not None: + entry = aborted + aborted = None + self._logger.debug("Got an aborted analysis job for entry {entry}, processing this instead of first item in queue".format(**locals())) + else: + (priority, entry) = self._queue.get() + self._logger.debug("Processing entry {entry} from queue (priority {priority})".format(**locals())) + + self._active.wait() + + try: + self._analyze(entry) + self._queue.task_done() + except gcodeInterpreter.AnalysisAborted: + aborted = entry + self._logger.debug("Running analysis of entry {entry} aborted".format(**locals())) + + def _analyze(self, entry): + path = entry.absolute_path + if path is None or not os.path.exists(path): + return + + self._current = entry + self._current_progress = 0 + + try: + self._logger.debug("Starting analysis of {entry}".format(**locals())) + eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"file": entry.path, "type": entry.type}) + result = self._do_analysis() + self._logger.debug("Analysis of entry {entry} finished, notifying callback".format(**locals())) + self._finished_callback(self._current, result) + finally: + self._current = None + self._current_progress = None + + def _do_analysis(self): + return None + + def _do_abort(self): + pass + + +class GcodeAnalysisQueue(AbstractAnalysisQueue): + + def _do_analysis(self): + try: + self._gcode = gcodeInterpreter.gcode() + self._gcode.load(self._current.absolute_path, self._current.printer_profile) + + result = dict() + if self._gcode.totalMoveTimeMinute: + result["estimatedPrintTime"] = self._gcode.totalMoveTimeMinute * 60 + if self._gcode.extrusionAmount: + result["filament"] = dict() + for i in range(len(self._gcode.extrusionAmount)): + result["filament"]["tool%d" % i] = { + "length": self._gcode.extrusionAmount[i], + "volume": self._gcode.extrusionVolume[i] + } + return result + finally: + self._gcode = None + + def _do_abort(self): + if self._gcode: + self._gcode.abort() \ No newline at end of file diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py new file mode 100644 index 000000000..5dc8695fa --- /dev/null +++ b/src/octoprint/filemanager/storage.py @@ -0,0 +1,1010 @@ +# 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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import logging +import os +import pylru +import tempfile + +import octoprint.filemanager + +from octoprint.util import safe_rename + +class StorageInterface(object): + """ + Interface of storage adapters for OctoPrint. + """ + + + @property + def analysis_backlog(self): + """ + Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`. + + The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget + to recurse into folders if your storage adapter supports those. + + :return: an iterator yielding all un-analysed files in the storage + """ + # empty generator pattern, yield is intentionally unreachable + return + yield + + def file_exists(self, path): + """ + Returns whether the file indicated by ``path`` exists or not. + :param string path: the path to check for existence + :return: ``True`` if the file 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 + subfolders. + + An optional filter function can be supplied which will be called with a file name and file data and which has + to return True if the file is to be included in the result or False if not. + + The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes + will contain their metadata here, folder nodes will contain their contained files and folders. Example:: + + { + "some_folder": { + "type": "folder", + "children": { + "some_sub_folder": { + "type": "folder", + "children": { ... } + }, + "some_file.gcode": { + "type": "machinecode", + "hash": "", + "links": [ ... ], + ... + }, + ... + } + "test.gcode": { + "type": "machinecode", + "hash": "", + "links": [...], + ... + }, + "test.stl": { + "type": "model", + "hash": "", + "links": [...], + ... + }, + ... + } + + :param string path: base path from which to recursively list all files, optional, if not supplied listing will start + from root of base folder + :param function filter: a filter that matches the files that are to be returned, may be left out in which case no + filtering will take place + :param bool recursive: will also step into sub folders for building the complete list if set to True + :return: a dictionary mapping entry names to entry data that represents the whole file list + """ + raise NotImplementedError() + + def add_folder(self, path, ignore_existing=True): + """ + Adds a folder as ``path``. The ``path`` will be sanitized. + + :param string path: the path of the new folder + :param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists + :return: the sanitized name of the new folder to be used for future references to the folder + """ + raise NotImplementedError() + + def remove_folder(self, path, recursive=True): + """ + Removes the folder at ``path``. + + :param string path: the path of the folder to remove + :param bool recursive: if set to True, contained folders and files will also be removed, otherwise and error will + be raised if the folder is not empty (apart from ``.metadata.yaml``) when it's to be removed + """ + raise NotImplementedError() + + def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False): + """ + Adds the file ``file_object`` as ``path`` + + :param string path: the file's new path, will be sanitized + :param object file_object: a file object that provides a ``save`` method which will be called with the destination path + where the object should then store its contents + :param object printer_profile: the printer profile associated with this file (if any) + :param list links: any links to add with the file + :param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file + and its metadata will just be silently overwritten + :return: the sanitized name of the file to be used for future references to it + """ + raise NotImplementedError() + + def remove_file(self, path): + """ + Removes the file at ``path``. Will also take care of deleting the corresponding entries + in the metadata and deleting all links pointing to the file. + + :param string path: path of the file to remove + """ + raise NotImplementedError() + + def get_metadata(self, path): + """ + Retrieves the metadata for the file ``path``. + + :param path: virtual path to the file for which to retrieve the metadata + :return: the metadata associated with the file + """ + raise NotImplementedError() + + def add_link(self, path, rel, data): + """ + Adds a link of relation ``rel`` to file ``path`` with the given ``data``. + + The following relation types are currently supported: + + * ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name`` + and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the + current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode`` + refering to ``name`` and its hash will also be added to the linked ``model`` file + * ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected + additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved + against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse + link of type ``model`` refering to ``name`` and its hash will also be added to the linked ``model`` file. + * ``web``: adds a location on the web associated with this file (e.g. a website where to download a model), + expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved`` + attribute describing when the content was retrieved + + Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying + as machine code will be refused. + + :param path: path of the file for which to add a link + :param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported) + :param data: additional data of the link to add + """ + raise NotImplementedError() + + def remove_link(self, path, rel, data): + """ + Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``. + + :param path: path of the file from which to remove the link + :param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported) + :param data: additional data of the link to remove, must match existing link + """ + raise NotImplementedError() + + def set_additional_metadata(self, path, key, data, overwrite=False, merge=False): + """ + Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``. + + If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten. + + If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries, + the two dictionaries will be merged recursively. + + :param path: the virtual path to the file for which to add additional metadata + :param key: key of metadata to add + :param data: metadata to add + :param overwrite: if True and ``key`` already exists, it will be overwritten + :param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they + will be merged + """ + raise NotImplementedError() + + def remove_additional_metadata(self, path, key): + """ + Removes additional metadata under ``key`` for ``name`` on ``path`` + + :param path: the virtual path to the file for which to remove the metadata under ``key`` + :param key: the key to remove + """ + raise NotImplementedError() + + def sanitize(self, path): + """ + Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both + folder and file name, the underlying implementation must separate those if necessary and sanitize individually. + + :param string path: the path to sanitize + :return: a 2-tuple containing the sanitized path and file name + """ + raise NotImplementedError() + + def sanitize_path(self, path): + """ + Sanitizes the given folder-only ``path``, stripping it of all invalid characters. + :param string path: the path to sanitize + :return: the sanitized path + """ + raise NotImplementedError() + + def sanitize_name(self, name): + """ + Sanitizes the given file ``name``, stripping it of all invalid characters. + :param string name: the file name to sanitize + :return: the sanitized name + """ + raise NotImplementedError() + + def split_path(self, path): + """ + Split ``path`` into base directory and file name. + :param path: the path to split + :return: a tuple (base directory, file name) + """ + raise NotImplementedError() + + def join_path(self, *path): + """ + Join path elements together + :param path: path elements to join + :return: joined representation of the path to be usable as fully qualified path for further operations + """ + raise NotImplementedError() + + def path_on_disk(self, path): + """ + Retrieves the path on disk for ``path``. + + Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should + raise an :class:`io.UnsupportedOperation` + + Opposite of :func:`path_in_storage`. + + :param string path: the virtual path for which to retrieve the path on disk + :return: the path on disk to ``path`` + """ + raise NotImplementedError() + + def path_in_storage(self, path): + """ + Retrieves the equivalent in the storage adapter for ``path``. + + Opposite of :func:`path_on_disk`. + + :param string path: the path for which to retrieve the storage path + :return: the path in storage to ``path`` + """ + raise NotImplementedError() + + + +class LocalFileStorage(StorageInterface): + """ + The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk. + + Metadata is managed inside ``.metadata.yaml`` files in the respective folders, indexed by the sanitized filenames + stored within the folder. Metadata access is managed through an LRU cache to minimize access overhead. + + This storage type implements :func:`path_on_disk`. + """ + + def __init__(self, basefolder, create=False): + """ + Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder + if necessary and ``create`` is set to ``True``. + + :param string basefolder: the path to the folder under which to create the storage + :param bool create: ``True`` if the folder should be created if it doesn't exist yet, ``False`` otherwise + """ + self._logger = logging.getLogger(__name__) + + self.basefolder = os.path.realpath(os.path.abspath(basefolder)) + 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())) + + import threading + self._metadata_lock = threading.Lock() + + self._metadata_cache = pylru.lrucache(10) + + @property + def analysis_backlog(self): + for entry in self._analysis_backlog_generator(): + yield entry + + def _analysis_backlog_generator(self, path=None): + if path is None: + path = self.basefolder + + metadata = self._get_metadata(path) + if not metadata: + metadata = dict() + for entry in os.listdir(path): + if entry.startswith(".") or not octoprint.filemanager.valid_file_type(entry): + continue + + absolute_path = os.path.join(path, entry) + if os.path.isfile(absolute_path): + if not entry in metadata or not isinstance(metadata[entry], dict) or not "analysis" in metadata[entry]: + printer_profile_rels = self.get_link(absolute_path, "printerprofile") + if printer_profile_rels: + printer_profile_id = printer_profile_rels[0]["id"] + else: + printer_profile_id = None + + yield entry, absolute_path, printer_profile_id + elif os.path.isdir(absolute_path): + 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_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 list_files(self, path=None, filter=None, recursive=True): + if path: + path = self.sanitize_path(path) + else: + path = self.basefolder + return self._list_folder(path, filter=filter, recursive=recursive) + + def add_folder(self, path, ignore_existing=True): + path, name = self.sanitize(path) + + 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())) + else: + os.mkdir(folder_path) + + return self.path_in_storage((path, name)) + + def remove_folder(self, path, recursive=True): + path, name = self.sanitize(path) + + folder_path = os.path.join(path, name) + if not os.path.exists(folder_path): + return + + contents = os.listdir(folder_path) + 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())) + + import shutil + shutil.rmtree(folder_path) + + 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() + + 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())) + if os.path.exists(file_path) and not allow_overwrite: + raise RuntimeError("{name} does already exist in {path} and overwriting is prohibited".format(**locals())) + + # make sure folders exist + if not os.path.exists(path): + os.makedirs(path) + + # save the file + file_object.save(file_path) + + # 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) + + # process any links that were also provided for adding to the file + if not links: + links = [] + + if printer_profile is not None: + links.append(("printerprofile", dict(id=printer_profile["id"], name=printer_profile["name"]))) + + self._add_links(name, path, links) + + return self.path_in_storage((path, name)) + + 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())) + + try: + os.remove(file_path) + except Exception as e: + raise RuntimeError("Could not delete {name} in {path}".format(**locals()), 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) + + 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 + + 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)]) + + def remove_link(self, path, rel, data): + path, name = self.sanitize(path) + self._remove_links(name, path, [(rel, data)]) + + def add_history(self, path, data): + path, name = self.sanitize(path) + self._add_history(name, path, data) + + def update_history(self, path, index, data): + path, name = self.sanitize(path) + self._update_history(name, path, index, data) + + def remove_history(self, path, index): + path, name = self.sanitize(path) + self._update_history(name, path, index) + + def set_additional_metadata(self, path, key, data, overwrite=False, merge=False): + path, name = self.sanitize(path) + metadata = self._get_metadata(path) + metadata_dirty = False + + if not name in metadata: + return + + if not key in metadata[name] or overwrite: + metadata[name][key] = data + metadata_dirty = True + elif key in metadata[name] and isinstance(metadata[name][key], dict) and isinstance(data, dict) and merge: + current_data = metadata[name][key] + + import octoprint.util + new_data = octoprint.util.dict_merge(current_data, data) + metadata[name][key] = new_data + metadata_dirty = True + elif key in metadata[name] and overwrite: + metadata[name][key] = data + metadata_dirty = True + + if metadata_dirty: + self._save_metadata(path, metadata) + + def remove_additional_metadata(self, path, key): + path, name = self.sanitize(path) + metadata = self._get_metadata(path) + + if not name in metadata: + return + + if not key in metadata[name]: + return + + del metadata[name][key] + self._save_metadata(path, metadata) + + def split_path(self, path): + split = path.split("/") + if len(split) == 1: + return "", split[0] + else: + return self.join_path(*split[:-1]), split[-1] + + def join_path(self, *path): + return "/".join(path) + + def sanitize(self, path): + """ + Returns a ``(path, name)`` tuple derived from the provided ``path``. + + ``path`` may be: + * a storage path + * an absolute file system path + * a tuple or list containing all individual path elements + * a string representation of the path + * with or without a file name + + Note that for a ``path`` without a trailing slash the last part will be considered a file name and + hence be returned at second position. If you only need to convert a folder path, be sure to + include a trailing slash for a string ``path`` or an empty last element for a list ``path``. + + Examples:: + + >>> storage = LocalFileStorage("/some/base/folder") + >>> storage.sanitize("some/folder/and/some file.gco") + ("/some/base/folder/some/folder/and", "some_file.gco") + >>> storage.sanitize(("some", "folder", "and", "some file.gco")) + ("/some/base/folder/some/folder/and", "some_file.gco") + >>> storage.sanitize("some file.gco") + ("/some/base/folder", "some_file.gco") + >>> storage.sanitize(("some file.gco",)) + ("/some/base/folder", "some_file.gco") + >>> storage.sanitize("") + ("/some/base/folder", "") + >>> storage.sanitize("some/folder/with/trailing/slash/") + ("/some/base/folder/some/folder/with/trailing/slash", "") + >>> storage.sanitize("some", "folder", "") + ("/some/base/folder/some/folder", "") + """ + name = None + if isinstance(path, (str, unicode, basestring)): + if path.startswith(self.basefolder): + path = path[len(self.basefolder):] + path = path.replace(os.path.sep, "/") + path = path.split("/") + if isinstance(path, (list, tuple)): + if len(path) == 1: + name = path[0] + path = "/" + else: + name = path[-1] + path = "/" + self.join_path(*path[:-1]) + if not path: + path = "/" + + name = self.sanitize_name(name) + path = self.sanitize_path(path) + return path, name + + def sanitize_name(self, name): + """ + Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise strips any characters from the + given ``name`` that are not any of the ASCII characters, digits, ``-``, ``_``, ``.``, ``(``, ``)`` or space and + replaces and spaces with ``_``. + + Examples:: + + >>> storage = LocalFileStorage("/some/base/folder") + >>> storage.sanitize_name("some_file.gco") + "some_file.gco" + >>> storage.sanitize_name("some_file with (parentheses) and ümläuts and digits 123.gco") + "some_file_with_(parentheses)_and_mluts_and_digits_123.gco" + >>> storage.sanitize_name("pengüino pequeño.stl") + "pengino_pequeo.stl" + >>> storage.sanitize_name("some/folder/still/left.gco") + Traceback (most recent call last): + File "", line 1, in + ValueError: name must not contain / or \ + >>> storage.sanitize_name("also\\no\\backslashes.gco") + Traceback (most recent call last): + File "", line 1, in + ValueError: name must not contain / or \ + """ + if name is None: + return None + + 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 + + def sanitize_path(self, path): + """ + Ensures that the on disk representation of ``path`` is located under the configured basefolder. Resolves all + relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the + absolute path including leading ``basefolder`` path. + + Examples:: + + >>> storage = LocalFileStorage("/some/base/folder") + >>> storage.sanitize_path("folder/with/subfolder") + "/some/base/folder/folder/with/subfolder" + >>> storage.sanitize_path("folder/with/subfolder/../other/folder") + "/some/base/folder/folder/with/other/folder" + >>> storage.sanitize_path("/folder/with/leading/slash") + "/some/base/folder/folder/with/leading/slash" + >>> storage.sanitize_path(".folder/with/leading/dot") + "/some/base/folder/folder/with/leading/dot + >>> storage.sanitize_path("../../folder/out/of/the/basefolder") + Traceback (most recent call last): + File "", line 1, in + ValueError: path not contained in base folder: /some/folder/out/of/the/basefolder + """ + if path[0] == "/" or path[0] == ".": + path = path[1:] + path_elements = path.split("/") + joined_path = self.basefolder + for path_element in path_elements: + joined_path = os.path.join(joined_path, self.sanitize_name(path_element)) + path = os.path.realpath(joined_path) + if not path.startswith(self.basefolder): + raise ValueError("path not contained in base folder: {path}".format(**locals())) + return path + + def path_in_storage(self, path): + if isinstance(path, (tuple, list)): + path = self.join_path(*path) + if isinstance(path, (str, unicode, basestring)): + if path.startswith(self.basefolder): + path = path[len(self.basefolder):] + path = path.replace(os.path.sep, "/") + if path.startswith("/"): + path = path[1:] + + return path + + def path_on_disk(self, path): + path, name = self.sanitize(path) + return os.path.join(path, name) + + ##~~ internals + + def _add_history(self, name, path, data): + metadata = self._get_metadata(path) + + if not name in metadata: + metadata[name] = dict() + + if not "hash" in metadata[name]: + metadata[name]["hash"] = self._create_hash(os.path.join(path, name)) + + if not "history" in metadata[name]: + metadata[name]["history"] = [] + + metadata[name]["history"].append(data) + self._calculate_stats_from_history(name, path, metadata=metadata, save=False) + self._save_metadata(path, metadata) + + def _update_history(self, name, path, index, data): + metadata = self._get_metadata(path) + + if not name in metadata or not "history" in metadata[name]: + return + + try: + metadata[name]["history"][index].update(data) + self._calculate_stats_from_history(name, path, metadata=metadata, save=False) + self._save_metadata(path, metadata) + except IndexError: + pass + + def _delete_history(self, name, path, index): + metadata = self._get_metadata(path) + + if not name in metadata or not "history" in metadata[name]: + return + + try: + del metadata[name]["history"][index] + self._calculate_stats_from_history(name, path, metadata=metadata, save=False) + self._save_metadata(path, metadata) + except IndexError: + pass + + def _calculate_stats_from_history(self, name, path, metadata=None, save=True): + if metadata is None: + metadata = self._get_metadata(path) + + if not name in metadata or not "history" in metadata[name]: + return + + # collect data from history + former_print_times = dict() + last_print = dict() + + + for history_entry in metadata[name]["history"]: + if not "printTime" in history_entry or not "success" in history_entry or not history_entry["success"] or not "printerProfile" in history_entry: + continue + + printer_profile = history_entry["printerProfile"] + print_time = history_entry["printTime"] + + if not printer_profile in former_print_times: + former_print_times[printer_profile] = [] + former_print_times[printer_profile].append(print_time) + + if not printer_profile in last_print or last_print[printer_profile] is None or ("timestamp" in history_entry and history_entry["timestamp"] > last_print[printer_profile]["timestamp"]): + last_print[printer_profile] = history_entry + + # calculate stats + statistics = dict(averagePrintTime=dict(), lastPrintTime=dict()) + + for printer_profile in former_print_times: + if not former_print_times[printer_profile]: + continue + statistics["averagePrintTime"][printer_profile] = sum(former_print_times[printer_profile]) / float(len(former_print_times[printer_profile])) + + for printer_profile in last_print: + if not last_print[printer_profile]: + continue + statistics["lastPrintTime"][printer_profile] = last_print[printer_profile]["printTime"] + + metadata[name]["statistics"] = statistics + + if save: + self._save_metadata(path, metadata) + + def _get_links(self, name, path, searched_rel): + metadata = self._get_metadata(path) + result = [] + + if not name in metadata: + return result + + if not "links" in metadata[name]: + return result + + for data in metadata[name]["links"]: + if not "rel" in data or not data["rel"] == searched_rel: + continue + result.append(data) + return result + + def _add_links(self, name, path, links): + file_type = octoprint.filemanager.get_file_type(name) + if file_type: + file_type = file_type[0] + + metadata = self._get_metadata(path) + metadata_dirty = False + + if not name in metadata: + metadata[name] = dict() + + if not "hash" in metadata[name]: + metadata[name]["hash"] = self._create_hash(os.path.join(path, name)) + + if not "links" in metadata[name]: + metadata[name]["links"] = [] + + for rel, data in links: + if (rel == "model" or rel == "machinecode") and "name" in data: + if file_type == "model" and rel == "model": + # adding a model link to a model doesn't make sense + return + elif file_type == "machinecode" and rel == "machinecode": + # adding a machinecode link to a machinecode doesn't make sense + return + + ref_path = os.path.join(path, data["name"]) + if not os.path.exists(ref_path): + # file doesn't exist, we won't create the link + continue + + # fetch hash of target file + if data["name"] in metadata and "hash" in metadata[data["name"]]: + hash = metadata[data["name"]]["hash"] + else: + hash = self._create_hash(ref_path) + if not data["name"] in metadata: + metadata[data["name"]] = dict( + hash=hash, + links=[] + ) + else: + metadata[data["name"]]["hash"] = hash + + if "hash" in data and not data["hash"] == hash: + # file doesn't have the correct hash, we won't create the link + continue + + if not "links" in metadata[data["name"]]: + metadata[data["name"]]["links"] = [] + + # add reverse link to link target file + metadata[data["name"]]["links"].append( + dict(rel="machinecode" if rel == "model" else "model", name=name, hash=metadata[name]["hash"]) + ) + metadata_dirty = True + + link_dict = dict( + rel=rel, + name=data["name"], + hash=hash + ) + + elif rel == "web" and "href" in data: + link_dict = dict( + rel=rel, + href=data["href"] + ) + if "retrieved" in data: + link_dict["retrieved"] = data["retrieved"] + + else: + continue + + if link_dict: + metadata[name]["links"].append(link_dict) + metadata_dirty = True + + if metadata_dirty: + self._save_metadata(path, metadata) + + def _remove_links(self, name, path, links): + metadata = self._get_metadata(path) + metadata_dirty = False + + if not name in metadata or not "hash" in metadata[name]: + hash = self._create_hash(os.path.join(path, name)) + else: + hash = metadata[name]["hash"] + + for rel, data in links: + if (rel == "model" or rel == "machinecode") and "name" in data: + if data["name"] in metadata and "links" in metadata[data["name"]]: + ref_rel = "model" if rel == "machinecode" else "machinecode" + for link in metadata[data["name"]]["links"]: + if link["rel"] == ref_rel and "name" in link and link["name"] == name and "hash" in link and link["hash"] == hash: + metadata[data["name"]]["links"].remove(link) + metadata_dirty = True + + if "links" in metadata[name]: + for link in metadata[name]["links"]: + if not link["rel"] == rel: + continue + + matches = True + for k, v in data.items(): + if not k in link or not link[k] == v: + matches = False + break + + if not matches: + continue + + metadata[name]["links"].remove(link) + metadata_dirty = True + + if metadata_dirty: + self._save_metadata(path, metadata) + + def _list_folder(self, path, filter=None, recursive=True): + metadata = self._get_metadata(path) + if not metadata: + metadata = dict() + metadata_dirty = False + + result = dict() + for entry in os.listdir(path): + if entry.startswith("."): + # no hidden files and folders + continue + + entry_path = os.path.join(path, entry) + + # file handling + if os.path.isfile(entry_path): + file_type = octoprint.filemanager.get_file_type(entry) + if not file_type: + # only supported extensions + continue + else: + file_type = file_type[0] + + if entry in metadata and isinstance(metadata[entry], dict): + entry_data = metadata[entry] + else: + entry_data = dict( + hash=self._create_hash(entry_path), + links=[], + notes=[] + ) + metadata[entry] = entry_data + metadata_dirty = True + + # TODO extract model hash from source if possible to recreate link + + if not filter or filter(entry, entry_data): + # only add files passing the optional filter + extended_entry_data = dict() + extended_entry_data.update(entry_data) + extended_entry_data["name"] = entry + extended_entry_data["type"] = file_type + stat = os.stat(entry_path) + if stat: + extended_entry_data["size"] = stat.st_size + extended_entry_data["date"] = int(stat.st_mtime) + + result[entry] = extended_entry_data + + # folder recursion + elif os.path.isdir(entry_path) and recursive: + sub_result = self._list_folder(entry_path, filter=filter) + result[entry] = dict( + name=entry, + type="folder", + children=sub_result + ) + + # TODO recreate links if we have metadata less entries + + # save metadata + if metadata_dirty: + self._save_metadata(path, metadata) + + return result + + def _create_hash(self, path): + import hashlib + + blocksize = 65536 + hash = hashlib.sha1() + with open(path, "rb") as f: + buffer = f.read(blocksize) + while len(buffer) > 0: + hash.update(buffer) + buffer = f.read(blocksize) + + return hash.hexdigest() + + def _get_metadata(self, path): + if path in self._metadata_cache: + return self._metadata_cache[path] + + metadata_path = os.path.join(path, ".metadata.yaml") + if os.path.exists(metadata_path): + with self._metadata_lock: + with open(metadata_path) as f: + try: + import yaml + metadata = yaml.safe_load(f) + except: + self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals())) + else: + self._metadata_cache[path] = metadata + return metadata + return dict() + + def _save_metadata(self, path, metadata): + metadata_path = os.path.join(path, ".metadata.yaml") + + fh, metadata_temporary_path = tempfile.mkstemp() + os.close(fh) + + with self._metadata_lock: + try: + with open(metadata_temporary_path, "w") as f: + import yaml + yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True) + safe_rename(metadata_temporary_path, metadata_path, throw_error=True) + except: + self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals())) + else: + self._metadata_cache[path] = metadata diff --git a/src/octoprint/gcodefiles.py b/src/octoprint/gcodefiles.py deleted file mode 100644 index e9f13c659..000000000 --- a/src/octoprint/gcodefiles.py +++ /dev/null @@ -1,615 +0,0 @@ -# coding=utf-8 -import re - -__author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' - -import os -import Queue -import threading -import yaml -import time -import logging -import octoprint.util as util -import octoprint.util.gcodeInterpreter as gcodeInterpreter - -from octoprint.settings import settings -from octoprint.events import eventManager, Events -from octoprint.filemanager.destinations import FileDestinations - -from werkzeug.utils import secure_filename - -GCODE_EXTENSIONS = ["gcode", "gco", "g"] -STL_EXTENSIONS = ["stl"] -SUPPORTED_EXTENSIONS = GCODE_EXTENSIONS + STL_EXTENSIONS - -def isGcodeFileName(filename): - """Simple helper to determine if a filename has the .gcode extension. - - :param filename: :class: `str` - - :returns boolean: - """ - return "." in filename and filename.rsplit(".", 1)[1].lower() in GCODE_EXTENSIONS - - -def isSTLFileName(filename): - """Simple helper to determine if a filename has the .stl extension. - - :param filename: :class: `str` - - :returns boolean: - """ - return "." in filename and filename.rsplit(".", 1)[1].lower() in STL_EXTENSIONS - - -def genGcodeFileName(filename): - if not filename: - return None - - name, ext = filename.rsplit(".", 1) - return name + ".gcode" - - -def genStlFileName(filename): - if not filename: - return None - - name, ext = filename.rsplit(".", 1) - return name + ".stl" - - -class GcodeManager: - def __init__(self): - self._logger = logging.getLogger(__name__) - - self._settings = settings() - - self._uploadFolder = self._settings.getBaseFolder("uploads") - - self._callbacks = [] - - self._metadata = {} - self._metadataDirty = False - self._metadataFile = os.path.join(self._uploadFolder, "metadata.yaml") - self._metadataTempFile = os.path.join(self._uploadFolder, "metadata.yaml.tmp") - self._metadataFileAccessMutex = threading.Lock() - - self._metadataAnalyzer = MetadataAnalyzer(getPathCallback=self.getAbsolutePath, loadedCallback=self._onMetadataAnalysisFinished) - - self._loadMetadata(migrate=True) - self._processAnalysisBacklog() - - def _processAnalysisBacklog(self): - for osFile in os.listdir(self._uploadFolder): - filename = self._getBasicFilename(osFile) - if not isGcodeFileName(filename): - continue - - absolutePath = self.getAbsolutePath(filename) - if absolutePath is None: - continue - - fileData = self.getFileData(filename) - if fileData is not None and "gcodeAnalysis" in fileData.keys(): - continue - - self._metadataAnalyzer.addFileToBacklog(filename) - - def _onMetadataAnalysisFinished(self, filename, gcode): - if filename is None or gcode is None: - return - - basename = os.path.basename(filename) - - absolutePath = self.getAbsolutePath(basename) - if absolutePath is None: - return - - analysisResult = {} - dirty = False - if gcode.totalMoveTimeMinute: - analysisResult["estimatedPrintTime"] = gcode.totalMoveTimeMinute * 60 - dirty = True - if gcode.extrusionAmount: - analysisResult["filament"] = {} - for i in range(len(gcode.extrusionAmount)): - analysisResult["filament"]["tool%d" % i] = { - "length": gcode.extrusionAmount[i], - "volume": gcode.extrusionVolume[i] - } - dirty = True - - if dirty: - metadata = self.getFileMetadata(basename) - metadata["gcodeAnalysis"] = analysisResult - self._metadata[basename] = metadata - self._metadataDirty = True - self._saveMetadata() - eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"file": basename, "result": analysisResult}) - - def _loadMetadata(self, migrate=False): - if os.path.exists(self._metadataFile) and os.path.isfile(self._metadataFile): - with self._metadataFileAccessMutex: - with open(self._metadataFile, "r") as f: - self._metadata = yaml.safe_load(f) - - if self._metadata is None: - self._metadata = {} - - # TODO: Remove in a couple of versions (2013-12-21) - if migrate: - self._migrateMetadata() - - def _migrateMetadata(self): - self._logger.info("Migrating metadata if necessary...") - - printTimeRe = re.compile("(\d+):(\d{2}):(\d{2})") - filamentRe = re.compile("(\d*\.\d+)m(\s/\s(\d*\.\d+)cm.)?") - - hoursToSeconds = 60 * 60 - minutesToSeconds = 60 - - updateCount = 0 - for metadata in self._metadata.values(): - if not "gcodeAnalysis" in metadata: - continue - - updated = False - if "estimatedPrintTime" in metadata["gcodeAnalysis"]: - estimatedPrintTime = metadata["gcodeAnalysis"]["estimatedPrintTime"] - if isinstance(estimatedPrintTime, (str, unicode)): - match = re.match(printTimeRe, estimatedPrintTime) - if match: - metadata["gcodeAnalysis"]["estimatedPrintTime"] = int(match.group(1)) * hoursToSeconds + int(match.group(2)) * minutesToSeconds + int(match.group(3)) - self._metadataDirty = True - updated = True - if "filament" in metadata["gcodeAnalysis"]: - filament = metadata["gcodeAnalysis"]["filament"] - if isinstance(filament, (str, unicode)): - match = re.match(filamentRe, filament) - if match: - metadata["gcodeAnalysis"]["filament"] = { - "tool0": { - "length": int(float(match.group(1)) * 1000) - } - } - if match.group(3) is not None: - metadata["gcodeAnalysis"]["filament"]["tool0"].update({ - "volume": float(match.group(3)) - }) - self._metadataDirty = True - updated = True - elif isinstance(filament, dict) and ("length" in filament.keys() or "volume" in filament.keys()): - metadata["gcodeAnalysis"]["filament"] = { - "tool0": {} - } - if "length" in filament.keys(): - metadata["gcodeAnalysis"]["filament"]["tool0"].update({ - "length": filament["length"] - }) - if "volume" in filament.keys(): - metadata["gcodeAnalysis"]["filament"]["tool0"].update({ - "volume": filament["volume"] - }) - self._metadataDirty = True - updated = True - - if updated: - updateCount += 1 - - self._saveMetadata() - - self._logger.info("Updated %d sets of metadata to new format" % updateCount) - - def _saveMetadata(self, force=False): - if not self._metadataDirty and not force: - return - - with self._metadataFileAccessMutex: - with open(self._metadataTempFile, "wb") as f: - yaml.safe_dump(self._metadata, f, default_flow_style=False, indent=" ", allow_unicode=True) - self._metadataDirty = False - util.safeRename(self._metadataTempFile, self._metadataFile) - - self._loadMetadata() - - def _getBasicFilename(self, filename): - if filename.startswith(self._uploadFolder): - return filename[len(self._uploadFolder + os.path.sep):] - else: - return filename - - #~~ callback handling - - def registerCallback(self, callback): - self._callbacks.append(callback) - - def unregisterCallback(self, callback): - if callback in self._callbacks: - self._callbacks.remove(callback) - - def _sendUpdateTrigger(self, type): - for callback in self._callbacks: - try: callback.sendEvent(type) - except: pass - - #~~ file handling - - def addFile(self, file, destination, uploadCallback=None): - """ - Adds the given file for the given destination to the systems. Takes care of slicing if enabled and - necessary. - - If the file's processing won't be finished directly with the return from this method but happen - asynchronously in the background (e.g. due to slicing), returns a tuple containing the just added file's - filename and False. Otherwise returns a tuple (filename, True). - """ - if not file or not destination: - return None, True - - curaEnabled = self._settings.getBoolean(["cura", "enabled"]) - filename = file.filename - - absolutePath = self.getAbsolutePath(filename, mustExist=False) - gcode = isGcodeFileName(filename) - - if absolutePath is None or (not curaEnabled and not gcode): - return None, True - - file.save(absolutePath) - - if gcode: - return self.processGcode(absolutePath, destination, uploadCallback), True - else: - if curaEnabled and isSTLFileName(filename): - return self.processStl(absolutePath, destination, uploadCallback), False - else: - return filename, False - - def getFutureFileName(self, file): - if not file: - return None - - absolutePath = self.getAbsolutePath(file.filename, mustExist=False) - if absolutePath is None: - return None - - return self._getBasicFilename(absolutePath) - - def processStl(self, absolutePath, destination, uploadCallback=None): - from octoprint.slicers.cura import CuraFactory - - cura = CuraFactory.create_slicer() - gcodePath = genGcodeFileName(absolutePath) - config = self._settings.get(["cura", "config"]) - - slicingStart = time.time() - - def stlProcessed(stlPath, gcodePath, error=None): - if error: - eventManager().fire(Events.SLICING_FAILED, {"stl": self._getBasicFilename(stlPath), "gcode": self._getBasicFilename(gcodePath), "reason": error}) - if os.path.exists(stlPath): - os.remove(stlPath) - else: - slicingStop = time.time() - eventManager().fire(Events.SLICING_DONE, {"stl": self._getBasicFilename(stlPath), "gcode": self._getBasicFilename(gcodePath), "time": slicingStop - slicingStart}) - self.processGcode(gcodePath, destination, uploadCallback) - - eventManager().fire(Events.SLICING_STARTED, {"stl": self._getBasicFilename(absolutePath), "gcode": self._getBasicFilename(gcodePath)}) - cura.process_file(config, gcodePath, absolutePath, stlProcessed, [absolutePath, gcodePath]) - - return self._getBasicFilename(gcodePath) - - def processGcode(self, absolutePath, destination, uploadCallback=None): - if absolutePath is None: - return None - - filename = self._getBasicFilename(absolutePath) - - if filename in self._metadata.keys(): - # delete existing metadata entry, since the file is going to get overwritten - del self._metadata[filename] - self._metadataDirty = True - self._saveMetadata() - - self._metadataAnalyzer.addFileToQueue(os.path.basename(absolutePath)) - - if uploadCallback is not None: - return uploadCallback(filename, absolutePath, destination) - else: - return filename - - def getFutureFilename(self, file): - if not file: - return None - - absolutePath = self.getAbsolutePath(file.filename, mustExist=False) - if absolutePath is None: - return None - - return self._getBasicFilename(absolutePath) - - def removeFile(self, filename): - filename = self._getBasicFilename(filename) - absolutePath = self.getAbsolutePath(filename) - stlPath = genStlFileName(absolutePath) - - if absolutePath is None: - return - - os.remove(absolutePath) - if os.path.exists(stlPath): - os.remove(stlPath) - - self.removeFileFromMetadata(filename) - - def removeFileFromMetadata(self, filename): - if filename in self._metadata.keys(): - del self._metadata[filename] - self._metadataDirty = True - self._saveMetadata() - - def getAbsolutePath(self, filename, mustExist=True): - """ - Returns the absolute path of the given filename in the correct upload folder. - - Ensures that the file -
    -
  • has any of the extensions listed in SUPPORTED_EXTENSIONS
  • -
  • exists and is a file (not a directory) if "mustExist" is set to True
  • -
- - @param filename the name of the file for which to determine the absolute path - @param mustExist if set to true, the method also checks if the file exists and is a file - @return the absolute path of the file or None if the file is not valid - """ - filename = self._getBasicFilename(filename) - - if not util.isAllowedFile(filename.lower(), set(SUPPORTED_EXTENSIONS)): - return None - - # TODO: detect which type of file and add in the extra folder portion - secure = os.path.join(self._uploadFolder, secure_filename(self._getBasicFilename(filename))) - if mustExist and (not os.path.exists(secure) or not os.path.isfile(secure)): - return None - - return secure - - def getAllFilenames(self): - return map(lambda x: x["name"], self.getAllFileData()) - - def getAllFileData(self): - files = [] - for osFile in os.listdir(self._uploadFolder): - fileData = self.getFileData(osFile) - if fileData is not None: - files.append(fileData) - return files - - def getFileData(self, filename): - if not filename: - return - - filename = self._getBasicFilename(filename) - - # TODO: Make this more robust when STLs will be viewable from the client - if isSTLFileName(filename): - return - - absolutePath = self.getAbsolutePath(filename) - if absolutePath is None: - return None - - statResult = os.stat(absolutePath) - fileData = { - "name": filename, - "size": statResult.st_size, - "origin": FileDestinations.LOCAL, - "date": int(statResult.st_ctime) - } - - # enrich with additional metadata from analysis if available - if filename in self._metadata.keys(): - for key in self._metadata[filename].keys(): - if key == "prints": - val = self._metadata[filename][key] - last = None - if "last" in val and val["last"] is not None: - last = { - "date": val["last"]["date"], - "success": val["last"]["success"] - } - if "lastPrintTime" in val["last"] and val["last"]["lastPrintTime"] is not None: - last["lastPrintTime"] = val["last"]["lastPrintTime"] - prints = { - "success": val["success"], - "failure": val["failure"], - "last": last - } - fileData["prints"] = prints - else: - fileData[key] = self._metadata[filename][key] - - return fileData - - def getFileMetadata(self, filename): - filename = self._getBasicFilename(filename) - if filename in self._metadata.keys(): - return self._metadata[filename] - else: - return { - "prints": { - "success": 0, - "failure": 0, - "last": None - } - } - - def setFileMetadata(self, filename, metadata): - filename = self._getBasicFilename(filename) - self._metadata[filename] = metadata - self._metadataDirty = True - - #~~ print job data - - def printSucceeded(self, filename, printTime): - filename = self._getBasicFilename(filename) - absolutePath = self.getAbsolutePath(filename) - if absolutePath is None: - return - - metadata = self.getFileMetadata(filename) - metadata["prints"]["success"] += 1 - metadata["prints"]["last"] = { - "date": time.time(), - "success": True - } - - if printTime is not None: - metadata["prints"]["last"]["lastPrintTime"] = printTime - - self.setFileMetadata(filename, metadata) - self._saveMetadata() - - def printFailed(self, filename, printTime): - filename = self._getBasicFilename(filename) - absolutePath = self.getAbsolutePath(filename) - if absolutePath is None: - return - - metadata = self.getFileMetadata(filename) - metadata["prints"]["failure"] += 1 - metadata["prints"]["last"] = { - "date": time.time(), - "success": False - } - - if printTime is not None: - metadata["prints"]["last"]["lastPrintTime"] = printTime - - self.setFileMetadata(filename, metadata) - self._saveMetadata() - - def changeLastPrintSuccess(self, filename, succeeded): - filename = self._getBasicFilename(filename) - absolutePath = self.getAbsolutePath(filename) - if absolutePath is None: - return - - metadata = self.getFileMetadata(filename) - if metadata is None: - return - - if "prints" in metadata.keys(): - if "last" in metadata.keys() and metadata["prints"]["last"] is not None: - currentSucceeded = metadata["prints"]["last"]["success"] - if currentSucceeded != succeeded: - metadata["prints"]["last"]["success"] = succeeded - if currentSucceeded: - # last print job was counted as success but actually failed - metadata["prints"]["success"] -= 1 - metadata["prints"]["failure"] += 1 - else: - # last print job was counted as a failure but actually succeeded - metadata["prints"]["success"] += 1 - metadata["prints"]["failure"] -= 1 - self.setFileMetadata(filename, metadata) - self._saveMetadata() - - #~~ analysis control - - def pauseAnalysis(self): - self._metadataAnalyzer.pause() - - def resumeAnalysis(self): - self._metadataAnalyzer.resume() - -class MetadataAnalyzer: - def __init__(self, getPathCallback, loadedCallback): - self._logger = logging.getLogger(__name__) - - self._getPathCallback = getPathCallback - self._loadedCallback = loadedCallback - - self._active = threading.Event() - self._active.set() - - self._currentFile = None - self._currentProgress = None - - self._queue = Queue.PriorityQueue() - self._gcode = None - - self._worker = threading.Thread(target=self._work) - self._worker.daemon = True - self._worker.start() - - def addFileToQueue(self, filename): - self._logger.debug("Adding file %s to analysis queue (high priority)" % filename) - self._queue.put((0, filename)) - - def addFileToBacklog(self, filename): - self._logger.debug("Adding file %s to analysis backlog (low priority)" % filename) - self._queue.put((100, filename)) - - def working(self): - return self.isActive() and not (self._queue.empty() and self._currentFile is None) - - def isActive(self): - return self._active.is_set() - - def pause(self): - self._logger.debug("Pausing Gcode analyzer") - self._active.clear() - if self._gcode is not None: - self._logger.debug("Aborting running analysis, will restart when Gcode analyzer is resumed") - self._gcode.abort() - - def resume(self): - self._logger.debug("Resuming Gcode analyzer") - self._active.set() - - def _work(self): - aborted = None - while True: - if aborted is not None: - filename = aborted - aborted = None - self._logger.debug("Got an aborted analysis job for file %s, processing this instead of first item in queue" % filename) - else: - (priority, filename) = self._queue.get() - self._logger.debug("Processing file %s from queue (priority %d)" % (filename, priority)) - - self._active.wait() - - try: - self._analyzeGcode(filename) - self._queue.task_done() - except gcodeInterpreter.AnalysisAborted: - aborted = filename - self._logger.debug("Running analysis of file %s aborted" % filename) - - def _analyzeGcode(self, filename): - path = self._getPathCallback(filename) - if path is None or not os.path.exists(path): - return - - self._currentFile = filename - self._currentProgress = 0 - - try: - self._logger.debug("Starting analysis of file %s" % filename) - eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"file": filename}) - self._gcode = gcodeInterpreter.gcode() - self._gcode.progressCallback = self._onParsingProgress - self._gcode.load(path) - self._logger.debug("Analysis of file %s finished, notifying callback" % filename) - self._loadedCallback(self._currentFile, self._gcode) - finally: - self._gcode = None - self._currentProgress = None - self._currentFile = None - - def _onParsingProgress(self, progress): - self._currentProgress = progress diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index 6278b2a1e..3d4ca5dd1 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -1,4 +1,18 @@ # coding=utf-8 +""" +This module represents OctoPrint's plugin subsystem. This includes management and helper methods as well as the +registered plugin types. + +.. autofunction:: plugin_manager + +.. autofunction:: plugin_settings + +.. autofunction:: call_plugin + +.. autoclass:: PluginSettings + :members: +""" + from __future__ import absolute_import __author__ = "Gina Häußge " @@ -6,17 +20,53 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import os +import logging from octoprint.settings import settings from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin) from octoprint.plugin.types import * +from octoprint.util import deprecated + # singleton _instance = None -def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None): +def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None): + """ + Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager` + singleton. + + Arguments: + init (boolean): A flag indicating whether this is the initial call to construct the singleton (True) or not + (False, default). If this is set to True and the plugin manager has already been initialized, a :class:`ValueError` + will be raised. The same will happen if the plugin manager has not yet been initialized and this is set to + False. + plugin_folders (list): A list of folders (as strings containing the absolute path to them) in which to look for + potential plugin modules. If not provided this defaults to the configured ``plugins`` base folder and + ``src/plugins`` within OctoPrint's code base. + plugin_types (list): A list of recognized plugin types for which to look for provided implementations. If not + provided this defaults to the plugin types found in :mod:`octoprint.plugin.types` without + :class:`~octoprint.plugin.OctoPrintPlugin`. + plugin_entry_points (list): A list of entry points pointing to modules which to load as plugins. If not provided + this defaults to the entry point ``octoprint.plugin``. + plugin_disabled_list (list): A list of plugin identifiers that are currently disabled. If not provided this + defaults to all plugins for which ``enabled`` is set to ``False`` in the settings. + + Returns: + PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin + management tasks. + + Raises: + ValueError: ``init`` was True although the plugin manager was already initialized, or it was False although + the plugin manager was not yet initialized. + """ + global _instance - if _instance is None: + if _instance is not None: + if init: + raise ValueError("Plugin Manager already initialized") + + else: if init: if plugin_folders is None: plugin_folders = (settings().getBaseFolder("plugins"), os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "plugins"))) @@ -28,21 +78,81 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en SimpleApiPlugin, AssetPlugin, BlueprintPlugin, - EventHandlerPlugin] + EventHandlerPlugin, + SlicerPlugin, + AppPlugin, + ProgressPlugin] if plugin_entry_points is None: plugin_entry_points = "octoprint.plugin" + if plugin_disabled_list is None: + all_plugin_settings = settings().get(["plugins"]) + plugin_disabled_list = [] + for key in all_plugin_settings: + if "enabled" in all_plugin_settings[key] and not all_plugin_settings[key]: + plugin_disabled_list.append(key) - _instance = PluginManager(plugin_folders, plugin_types, plugin_entry_points) + _instance = PluginManager(plugin_folders, plugin_types, plugin_entry_points, logging_prefix="octoprint.plugins.", plugin_disabled_list=plugin_disabled_list) else: raise ValueError("Plugin Manager not initialized yet") return _instance -def plugin_settings(plugin_key, defaults=None): - return PluginSettings(settings(), plugin_key, defaults=defaults) +def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None): + """ + Factory method for creating a :class:`PluginSettings` instance. + + Arguments: + plugin_key (string): The plugin identifier for which to create the settings instance. + 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. + + 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) -def call_plugin(types, method, args=None, kwargs=None, callback=None): +def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=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 + and/or failure of each call which can be used to return individual results to the calling code. + + Example: + + .. sourcecode:: python + + def my_success_callback(name, plugin, result): + print("{name} was called successfully and returned {result!r}".format(**locals())) + + def my_error_callback(name, plugin, exc): + print("{name} raised an exception: {exc!s}".format(**locals())) + + octoprint.plugin.call_plugin( + [octoprint.plugin.StartupPlugin], + "on_startup", + args=(my_host, my_port), + callback=my_success_callback, + error_callback=my_error_callback + ) + + Arguments: + types (list): A list of plugin implementation types to match against. + method (string): Name of the method to call on all matching implementations. + args (tuple): A tuple containing the arguments to supply to the called ``method``. Optional. + kwargs (dict): A dictionary containing the keyword arguments to supply to the called ``method``. Optional. + callback (function): A callback to invoke after an implementation has been called successfully. Will be called + with the three arguments ``name``, ``plugin`` and ``result``. ``name`` will be the plugin identifier, + ``plugin`` the plugin implementation instance itself and ``result`` the result returned from the + ``method`` invocation. + error_callback (function): A callback to invoke after the call of an implementation resulted in an exception. + Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin + identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception. + + """ + if not isinstance(types, (list, tuple)): types = [types] if args is None: @@ -53,13 +163,80 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None): plugins = plugin_manager().get_implementations(*types) for name, plugin in plugins.items(): if hasattr(plugin, method): - result = getattr(plugin, method)(*args, **kwargs) - if callback: - callback(name, plugin, result) + try: + result = getattr(plugin, method)(*args, **kwargs) + if callback: + callback(name, plugin, result) + except Exception as exc: + logging.getLogger(__name__).exception("Error while calling plugin %s" % name) + if error_callback: + error_callback(name, plugin, exc) class PluginSettings(object): - def __init__(self, settings, plugin_key, defaults=None): + """ + The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings. + + It provides a couple of convenience methods for directly accessing plugin settings via the regular + :class:`octoprint.settings.Settings` interfaces as well as means to access plugin specific folder locations. + + All getter and setter methods will ensure that plugin settings are stored in their correct location within the + settings structure by modifying the supplied paths accordingly. + + Arguments: + settings (Settings): The :class:`~octoprint.settings.Settings` instance on which to operate. + plugin_key (str): The plugin identifer of the plugin for which to create this instance. + defaults (dict): The plugin's defaults settings, will be used to determine valid paths within the plugin's + settings structure + + .. method:: get(path, merged=False, asdict=False) + + Retrieves a raw value from the settings for ``path``, optionally merging the raw value with the default settings + if ``merged`` is set to True. + + :param path: The path for which to retrieve the value. + :type path: list, tuple + :param boolean merged: Whether to merge the returned result with the default settings (True) or not (False, + default). + :returns: The retrieved settings value. + :rtype: object + + .. method:: get_int(path) + + Like :func:`get` but tries to convert the retrieved value to ``int``. + + .. method:: get_float(path) + + Like :func:`get` but tries to convert the retrieved value to ``float``. + + .. method:: get_boolean(path) + + Like :func:`get` but tries to convert the retrieved value to ``boolean``. + + .. method:: set(path, value, force=False) + + Sets the raw value on the settings for ``path``. + + :param path: The path for which to retrieve the value. + :type path: list, tuple + :param object value: The value to set. + :param boolean force: If set to True, the modified configuration will even be written back to disk if + the value didn't change. + + .. method:: set_int(path, value, force=False) + + Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it. + + .. method:: set_float(path, value, force=False) + + Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it. + + .. method:: set_boolean(path, value, force=False) + + Like :func:`set` but ensures the value is an ``boolean`` through attempted conversion before setting it. + """ + + def __init__(self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None): self.settings = settings self.plugin_key = plugin_key @@ -68,6 +245,16 @@ class PluginSettings(object): self.defaults = dict(plugins=dict()) self.defaults["plugins"][plugin_key] = defaults + if get_preprocessors is None: + get_preprocessors = dict() + self.get_preprocessors = dict(plugins=dict()) + self.get_preprocessors["plugins"][plugin_key] = get_preprocessors + + if set_preprocessors is None: + set_preprocessors = dict() + self.set_preprocessors = dict(plugins=dict()) + self.set_preprocessors["plugins"][plugin_key] = set_preprocessors + def prefix_path(path): return ['plugins', self.plugin_key] + path @@ -84,38 +271,172 @@ class PluginSettings(object): result.extend(args_after) return result - def add_defaults_to_kwargs(kwargs): - kwargs.update(dict(defaults=self.defaults)) + def add_getter_kwargs(kwargs): + kwargs.update(defaults=self.defaults, preprocessors=self.get_preprocessors) return kwargs - self.access_methods = { - 'get': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)), - 'getInt': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)), - 'getFloat': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)), - 'getBoolean': (lambda args,: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)), - 'set': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)), - 'setInt': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)), - 'setFloat': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)), - 'setBoolean': (lambda args: prefix_path_in_args(args), lambda kwargs: add_defaults_to_kwargs(kwargs)) - } + def add_setter_kwargs(kwargs): + kwargs.update(defaults=self.defaults, preprocessors=self.set_preprocessors) + return kwargs - def globalGet(self, path): - return self.settings.get(path) + self.access_methods = dict( + get =("get", prefix_path_in_args, add_getter_kwargs), + get_int =("getInt", prefix_path_in_args, add_getter_kwargs), + get_float =("getFloat", prefix_path_in_args, add_getter_kwargs), + get_boolean=("getBoolean", prefix_path_in_args, add_getter_kwargs), + set =("set", prefix_path_in_args, add_setter_kwargs), + set_int =("setInt", prefix_path_in_args, add_setter_kwargs), + set_float =("setFloat", prefix_path_in_args, add_setter_kwargs), + set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs) + ) + self.deprecated_access_methods = dict( + getInt ="get_int", + getFloat ="get_float", + getBoolean="get_boolean", + setInt ="set_int", + setFloat ="set_float", + setBoolean="set_boolean" + ) - def globalGetInt(self, path): - return self.settings.getInt(path) + def global_get(self, path, **kwargs): + """ + Getter for retrieving settings not managed by the plugin itself from the core settings structure. Use this + to access global settings outside of your plugin. - def globalGetFloat(self, path): - return self.settings.getFloat(path) + Directly forwards to :func:`octoprint.settings.Settings.get`. + """ + return self.settings.get(path, **kwargs) - def globalGetBoolean(self, path): - return self.settings.getBoolean(path) + def global_get_int(self, path, **kwargs): + """ + Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getInt`. + """ + return self.settings.getInt(path, **kwargs) + + def global_get_float(self, path, **kwargs): + """ + Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getFloat`. + """ + return self.settings.getFloat(path, **kwargs) + + def global_get_boolean(self, path, **kwargs): + """ + Like :func:`global_get` but directly orwards to :func:`octoprint.settings.Settings.getBoolean`. + """ + return self.settings.getBoolean(path, **kwargs) + + def global_set(self, path, value, **kwargs): + """ + Setter for modifying settings not managed by the plugin itself on the core settings structure. Use this + to modify global settings outside of your plugin. + + Directly forwards to :func:`octoprint.settings.Settings.set`. + """ + self.settings.set(path, value, **kwargs) + + def global_set_int(self, path, value, **kwargs): + """ + Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setInt`. + """ + self.settings.setInt(path, value, **kwargs) + + def global_set_float(self, path, value, **kwargs): + """ + Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setFloat`. + """ + self.settings.setFloat(path, value, **kwargs) + + def global_set_boolean(self, path, value, **kwargs): + """ + Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setBoolean`. + """ + self.settings.setBoolean(path, value, **kwargs) + + def global_get_basefolder(self, folder_type, **kwargs): + """ + Retrieves a globally defined basefolder of the given ``folder_type``. Directly forwards to + :func:`octoprint.settings.Settings.getBaseFolder`. + """ + return self.settings.getBaseFolder(folder_type, **kwargs) + + def get_plugin_logfile_path(self, postfix=None): + """ + Retrieves the path to a logfile specifically for the plugin. If ``postfix`` is not supplied, the logfile + will be named ``plugin_.log`` and located within the configured ``logs`` folder. If a + postfix is supplied, the name will be ``plugin__.log`` at the same location. + + Plugins may use this for specific logging tasks. For example, a :class:`~octoprint.plugin.SlicingPlugin` might + want to create a log file for logging the output of the slicing engine itself if some debug flag is set. + + Arguments: + postfix (str): Postfix of the logfile for which to create the path. If set, the file name of the log file + will be ``plugin__.log``, if not it will be + ``plugin_.log``. + + Returns: + str: Absolute path to the log file, directly usable by the plugin. + """ + filename = "plugin_" + self.plugin_key + if postfix is not None: + filename += "_" + postfix + filename += ".log" + return os.path.join(self.settings.getBaseFolder("logs"), filename) def __getattr__(self, item): - if item in self.access_methods and hasattr(self.settings, item) and callable(getattr(self.settings, item)): - orig_item = getattr(self.settings, item) - args_mapper, kwargs_mapper = self.access_methods[item] + all_access_methods = self.access_methods.keys() + self.deprecated_access_methods.keys() + if item in all_access_methods: + decorator = None + if item in self.deprecated_access_methods: + new = self.deprecated_access_methods[item] + decorator = deprecated("{old} has been renamed to {new}".format(old=item, new=new), stacklevel=2) + item = new - return lambda *args, **kwargs: orig_item(*args_mapper(args), **kwargs_mapper(kwargs)) - else: - return getattr(self.settings, item) + settings_name, args_mapper, kwargs_mapper = self.access_methods[item] + if hasattr(self.settings, settings_name) and callable(getattr(self.settings, settings_name)): + orig_func = getattr(self.settings, settings_name) + if decorator is not None: + orig_func = decorator(orig_func) + + def _func(*args, **kwargs): + return orig_func(*args_mapper(args), **kwargs_mapper(kwargs)) + _func.__name__ = item + _func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None + + return _func + + return getattr(self.settings, item) + + ##~~ deprecated methods follow + + # TODO: Remove with release of 1.2.0 + + globalGet = deprecated("globalGet has been renamed to global_get", + includedoc="Replaced by :func:`global_get`", + since="1.2.0-dev-546")(global_get) + globalGetInt = deprecated("globalGetInt has been renamed to global_get_int", + includedoc="Replaced by :func:`global_get_int`", + since="1.2.0-dev-546")(global_get_int) + globalGetFloat = deprecated("globalGetFloat has been renamed to global_get_float", + includedoc="Replaced by :func:`global_get_float`", + since="1.2.0-dev-546")(global_get_float) + globalGetBoolean = deprecated("globalGetBoolean has been renamed to global_get_boolean", + includedoc="Replaced by :func:`global_get_boolean`", + since="1.2.0-dev-546")(global_get_boolean) + globalSet = deprecated("globalSet has been renamed to global_set", + includedoc="Replaced by :func:`global_set`", + since="1.2.0-dev-546")(global_set) + globalSetInt = deprecated("globalSetInt has been renamed to global_set_int", + includedoc="Replaced by :func:`global_set_int`", + since="1.2.0-dev-546")(global_set_int) + globalSetFloat = deprecated("globalSetFloat has been renamed to global_set_float", + includedoc="Replaced by :func:`global_set_float`", + since="1.2.0-dev-546")(global_set_float) + globalSetBoolean = deprecated("globalSetBoolean has been renamed to global_set_boolean", + includedoc="Replaced by :func:`global_set_boolean`", + since="1.2.0-dev-546")(global_set_boolean) + globalGetBaseFolder = deprecated("globalGetBaseFolder has been renamed to global_get_basefolder", + includedoc="Replaced by :func:`global_get_basefolder`", + since="1.2.0-dev-546")(global_get_basefolder) + getPluginLogfilePath = deprecated("getPluginLogfilePath has been renamed to get_plugin_logfile_path", + includedoc="Replaced by :func:`get_plugin_logfile_path`", + since="1.2.0-dev-546")(get_plugin_logfile_path) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 627e9eee5..d418483da 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -1,4 +1,16 @@ # coding=utf-8 +""" +In this module resides the core data structures and logic of the plugin system. It is implemented in an OctoPrint-agnostic +way and could be extracted into a separate Python module in the future. + +.. autoclass:: PluginManager + +.. autoclass:: PluginInfo + +.. autoclass:: Plugin + +""" + from __future__ import absolute_import __author__ = "Gina Häußge " @@ -13,6 +25,15 @@ import logging class PluginInfo(object): + """ + The :class:`PluginInfo` class wraps all available information about a registered plugin. + + This includes its meta data (like name, description, version, etc) as well as the actual plugin extensions like + implementations, hooks and helpers. + + It works on Python module objects and extracts the relevant data from those via accessing the + :ref:`control properties `. + """ attr_name = '__plugin_name__' @@ -20,6 +41,12 @@ class PluginInfo(object): attr_version = '__plugin_version__' + attr_author = '__plugin_author__' + + attr_url = '__plugin_url__' + + attr_license = '__plugin_license__' + attr_hooks = '__plugin_hooks__' attr_implementations = '__plugin_implementations__' @@ -30,12 +57,20 @@ class PluginInfo(object): attr_init = '__plugin_init__' - def __init__(self, key, location, instance, version=None): + def __init__(self, key, location, instance, name=None, version=None, description=None, author=None, url=None, license=None): self.key = key self.location = location self.instance = instance + self.origin = None + self.enabled = True + self.bundled = False + self._name = name self._version = version + self._description = description + self._author = author + self._url = url + self._license = license def __str__(self): return "{name} ({version})".format(name=self.name, version=self.version if self.version else "unknown") @@ -58,15 +93,27 @@ class PluginInfo(object): @property def name(self): - return self._get_instance_attribute(self.__class__.attr_name, default=None) + return self._get_instance_attribute(self.__class__.attr_name, defaults=(self._name, self.key)) @property def description(self): - return self._get_instance_attribute(self.__class__.attr_description, default=None) + return self._get_instance_attribute(self.__class__.attr_description, default=self._description) @property def version(self): - return self._version if self._version is not None else self._get_instance_attribute(self.__class__.attr_version, default=None) + return self._version if self._version is not None else self._get_instance_attribute(self.__class__.attr_version, default=self._version) + + @property + def author(self): + return self._get_instance_attribute(self.__class__.attr_author, default=self._author) + + @property + def url(self): + return self._get_instance_attribute(self.__class__.attr_url, default=self._url) + + @property + def license(self): + return self._get_instance_attribute(self.__class__.attr_license, default=self._license) @property def hooks(self): @@ -88,17 +135,29 @@ class PluginInfo(object): def init(self): return self._get_instance_attribute(self.__class__.attr_init, default=lambda: True) - def _get_instance_attribute(self, attr, default=None): + def _get_instance_attribute(self, attr, default=None, defaults=None): if not hasattr(self.instance, attr): + if defaults is not None: + for value in defaults: + if value is not None: + return value return default return getattr(self.instance, attr) class PluginManager(object): + """ + The :class:`PluginManager` is the central component for finding, loading and accessing plugins provided to the + system. - def __init__(self, plugin_folders, plugin_types, plugin_entry_points, plugin_disabled_list=None): + It is able to discover plugins both through possible file system locations as well as customizable entry points. + """ + + def __init__(self, plugin_folders, plugin_types, plugin_entry_points, logging_prefix=None, plugin_disabled_list=None): self.logger = logging.getLogger(__name__) + if logging_prefix is None: + logging_prefix = "" if plugin_disabled_list is None: plugin_disabled_list = [] @@ -106,23 +165,37 @@ class PluginManager(object): self.plugin_types = plugin_types self.plugin_entry_points = plugin_entry_points self.plugin_disabled_list = plugin_disabled_list + self.logging_prefix = logging_prefix self.plugins = dict() self.plugin_hooks = defaultdict(list) - self.plugin_implementations = defaultdict(list) + self.plugin_implementations = defaultdict(set) + self.plugin_implementations_by_type = defaultdict(list) + + self.disabled_plugins = dict() + + self.registered_clients = [] self.reload_plugins() def _find_plugins(self): plugins = dict() + disabled_plugins = dict() if self.plugin_folders: - self._add_plugins_from_folders(self.plugin_folders, plugins) + self._add_plugins_from_folders(self.plugin_folders, plugins, disabled_plugins) if self.plugin_entry_points: - self._add_plugins_from_entry_points(self.plugin_entry_points, plugins) - return plugins + self._add_plugins_from_entry_points(self.plugin_entry_points, plugins, disabled_plugins) + return plugins, disabled_plugins - def _add_plugins_from_folders(self, folders, plugins): + def _add_plugins_from_folders(self, folders, plugins, disabled_plugins): for folder in folders: + readonly = False + if isinstance(folder, (list, tuple)): + if len(folder) == 2: + folder, readonly = folder + else: + continue + if not os.path.exists(folder): self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder)) continue @@ -137,22 +210,27 @@ class PluginManager(object): else: continue - if self._is_plugin_disabled(key): - # plugin is disabled, ignore it - continue - if key in plugins: # plugin is already defined, ignore it continue plugin = self._load_plugin_from_module(key, folder=folder) if plugin: - plugins[key] = plugin + plugin.origin = ("folder", folder) + if readonly: + plugin.bundled = True - return plugins + if self._is_plugin_disabled(key): + plugin.enabled = False + disabled_plugins[key] = plugin + else: + plugins[key] = plugin - def _add_plugins_from_entry_points(self, groups, plugins): + return plugins, disabled_plugins + + def _add_plugins_from_entry_points(self, groups, plugins, disabled_plugins): import pkg_resources + import pkginfo if not isinstance(groups, (list, tuple)): groups = [groups] @@ -163,42 +241,62 @@ class PluginManager(object): module_name = entry_point.module_name version = entry_point.dist.version - if self._is_plugin_disabled(key): - # plugin is disabled, ignore it - continue - if key in plugins: # plugin is already defined, ignore it continue - plugin = self._load_plugin_from_module(key, module_name=module_name, version=version) + kwargs = dict(module_name=module_name, version=version) + try: + module_pkginfo = pkginfo.Installed(module_name) + except: + self.logger.exception("Something went wrong while retrieving package info data for module %s" % module_name) + else: + kwargs.update(dict( + name=module_pkginfo.name, + summary=module_pkginfo.summary, + author=module_pkginfo.author, + url=module_pkginfo.home_page, + license=module_pkginfo.license + )) + + plugin = self._load_plugin_from_module(key, **kwargs) if plugin: - plugins[key] = plugin + plugin.origin = ("entry_point", group, module_name) - return plugins + if self._is_plugin_disabled(key): + plugin.enabled = False + disabled_plugins[key] = plugin + else: + plugins[key] = plugin - def _load_plugin_from_module(self, key, folder=None, module_name=None, version=None): + return plugins, disabled_plugins + + def _load_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None): # TODO error handling - if folder: - module = imp.find_module(key, [folder]) - elif module_name: - module = imp.find_module(module_name) - else: + try: + if folder: + module = imp.find_module(key, [folder]) + elif module_name: + module = imp.find_module(module_name) + else: + return None + except: + self.logger.warn("Could not locate plugin {key}") return None - plugin = self._load_plugin(key, *module, version=version) + plugin = self._load_plugin(key, *module, name=name, version=version, summary=summary, author=author, url=url, license=license) if plugin: if plugin.check(): return plugin else: - self.logger.warn("Plugin \"{plugin}\" did not pass check, disabling it".format(plugin=str(plugin))) + self.logger.warn("Plugin \"{plugin}\" did not pass check".format(plugin=str(plugin))) return None - - def _load_plugin(self, key, f, filename, description, version=None): + + def _load_plugin(self, key, f, filename, description, name=None, version=None, summary=None, author=None, url=None, license=None): try: instance = imp.load_module(key, f, filename, description) - return PluginInfo(key, filename, instance, version=version) + return PluginInfo(key, filename, instance, name=name, version=version, description=summary, author=author, url=url, license=license) except: self.logger.exception("Error loading plugin {key}, disabling it".format(key=key)) return None @@ -208,26 +306,82 @@ class PluginManager(object): def reload_plugins(self): self.logger.info("Loading plugins from {folders} and installed plugin packages...".format(folders=", ".join(self.plugin_folders))) - self.plugins = self._find_plugins() + self.plugins, self.disabled_plugins = self._find_plugins() for name, plugin in self.plugins.items(): - # initialize the plugin - plugin.init() + try: + # initialize the plugin + plugin.init() - # evaluate registered hooks - for hook, callback in plugin.hooks.items(): - self.plugin_hooks[hook].append((name, callback)) + # evaluate registered hooks + for hook, callback in plugin.hooks.items(): + self.plugin_hooks[hook].append((name, callback)) - # evaluate registered implementations - for plugin_type in self.plugin_types: - implementations = plugin.get_implementations(plugin_type) - self.plugin_implementations[plugin_type] += ( (name, implementation) for implementation in implementations ) + # evaluate registered implementations + for plugin_type in self.plugin_types: + implementations = plugin.get_implementations(plugin_type) + self.plugin_implementations_by_type[plugin_type] += ( (name, implementation) for implementation in implementations ) + plugin_implementations = plugin.get_implementations() + if len(plugin_implementations): + self.plugin_implementations[name].update(plugin_implementations) + except: + self.logger.exception("There was an error loading plugin %s" % name) + + self.log_registered_plugins() + + def initialize_implementations(self, additional_injects=None, additional_inject_factories=None): + if additional_injects is None: + additional_injects = dict() + if additional_inject_factories is None: + additional_inject_factories = [] + + for name, implementations in self.plugin_implementations.items(): + plugin = self.plugins[name] + for implementation in implementations: + try: + kwargs = dict(additional_injects) + + kwargs.update(dict( + identifier=name, + plugin_name=plugin.name, + plugin_version=plugin.version, + basefolder=os.path.realpath(plugin.location), + logger=logging.getLogger(self.logging_prefix + name), + )) + + # inject the additional_injects + for arg, value in kwargs.items(): + setattr(implementation, "_" + arg, value) + + # inject any injects produced in the additional_inject_factories + for factory in additional_inject_factories: + try: + return_value = factory(name, implementation) + except: + self.logger.exception("Exception while executing injection factory %r" % factory) + else: + if return_value is not None: + if isinstance(return_value, dict): + for arg, value in return_value.items(): + setattr(implementation, "_" + arg, value) + + implementation.initialize() + except: + self.logger.exception("Exception while initializing plugin") + # TODO disable plugin! + + self.logger.info("Initialized {count} plugin(s)".format(count=len(self.plugin_implementations))) + + def log_registered_plugins(self): if len(self.plugins) <= 0: self.logger.info("No plugins found") else: self.logger.info("Found {count} plugin(s): {plugins}".format(count=len(self.plugins), plugins=", ".join(map(lambda x: str(x), self.plugins.values())))) + if len(self.disabled_plugins) > 0: + self.logger.info("{count} plugin(s) currently disabled: {plugins}".format(count=len(self.disabled_plugins), plugins=", ".join(map(lambda x: str(x), self.disabled_plugins.values())))) + def get_plugin(self, name): if not name in self.plugins: return None @@ -235,21 +389,21 @@ class PluginManager(object): def get_hooks(self, hook): if not hook in self.plugin_hooks: - return [] + return dict() return {hook[0]: hook[1] for hook in self.plugin_hooks[hook]} def get_implementations(self, *types): result = None for t in types: - implementations = self.plugin_implementations[t] + implementations = self.plugin_implementations_by_type[t] if result is None: result = set(implementations) else: result = result.intersection(implementations) if result is None: - return set() + return dict() return {impl[0]: impl[1] for impl in result} def get_helpers(self, name, *helpers): @@ -263,6 +417,49 @@ class PluginManager(object): else: return all_helpers + def register_client(self, client): + if client is None: + return + self.registered_clients.append(client) + + def unregister_client(self, client): + self.registered_clients.remove(client) + + def send_plugin_message(self, plugin, data): + for client in self.registered_clients: + try: client.sendPluginMessage(plugin, data) + except: self.logger.exception("Exception while sending plugin data to client") + class Plugin(object): - pass + """ + The parent class of all plugin implementations. + + .. attribute:: _identifier + + The identifier of the plugin. Injected by the plugin core system upon initialization of the implementation. + + .. attribute:: _plugin_name + + The name of the plugin. Injected by the plugin core system upon initialization of the implementation. + + .. attribute:: _plugin_version + + The version of the plugin. Injected by the plugin core system upon initialization of the implementation. + + .. attribute:: _basefolder + + The base folder of the plugin. Injected by the plugin core system upon initialization of the implementation. + + .. attribute:: _logger + + The logger instance to use, with the logging name set to the :attr:`PluginManager.logging_prefix` of the + :class:`PluginManager` concatenated with :attr:`_identifier`. Injected by the plugin core system upon + initialization of the implementation. + """ + + def initialize(self): + """ + Called by the plugin core after performing all injections. + """ + pass diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index f14039167..836523244 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -1,4 +1,15 @@ # coding=utf-8 +""" +This module bundles all of OctoPrint's supported plugin implementation types as well as their common parent +class, :class:`OctoPrintPlugin`. + +Please note that the plugin implementation types are documented in the section +:ref:`Available plugin mixins `. + +.. autoclass:: OctoPrintPlugin + +""" + from __future__ import absolute_import __author__ = "Gina Häußge " @@ -9,61 +20,1000 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms from .core import Plugin -class StartupPlugin(Plugin): +class OctoPrintPlugin(Plugin): + """ + The parent class of all OctoPrint plugin mixins. + + .. attribute:: _plugin_manager + + The :class:`~octoprint.plugin.core.PluginManager` instance. Injected by the plugin core system upon + initialization of the implementation. + + .. attribute:: _printer_profile_manager + + The :class:`~octoprint.printer.profile.PrinterProfileManager` instance. Injected by the plugin core system upon + initialization of the implementation. + + .. attribute:: _event_bus + + The :class:`~octoprint.events.EventManager` instance. Injected by the plugin core system upon initialization of + the implementation. + + .. attribute:: _analysis_queue + + The :class:`~octoprint.filemanager.analysis.AnalysisQueue` instance. Injected by the plugin core system upon + initialization of the implementation. + + .. attribute:: _slicing_manager + + The :class:`~octoprint.slicing.SlicingManager` instance. Injected by the plugin core system upon initialization + of the implementation. + + .. attribute:: _file_manager + + The :class:`~octoprint.filemanager.FileManager` instance. Injected by the plugin core system upon initialization + of the implementation. + + .. attribute:: _printer + + The :class:`~octoprint.printer.PrinterInterface` instance. Injected by the plugin core system upon initialization + of the implementation. + + .. attribute:: _app_session_manager + + The :class:`~octoprint.users.SessionManager` instance. Injected by the plugin core system upon initialization of + the implementation. + """ + + pass + + +class StartupPlugin(OctoPrintPlugin): + """ + 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. + """ + def on_startup(self, host, port): + """ + Called just before the server is actually launched. Plugins get supplied with the ``host`` and ``port`` the server + will listen on. Note that the ``host`` may be ``0.0.0.0`` if it will listen on all interfaces, so you can't just + blindly use this for constructing publicly reachable URLs. Also note that when this method is called, the server + is not actually up yet and none of your plugin's APIs or blueprints will be reachable yet. If you need to be + externally reachable, use :func:`on_after_startup` instead or additionally. + + :param string host: the host the server will listen on, may be ``0.0.0.0`` + :param int port: the port the server will listen on + """ + pass def on_after_startup(self): + """ + Called just after launch of the server, so when the listen loop is actually running already. + """ + pass -class ShutdownPlugin(Plugin): +class ShutdownPlugin(OctoPrintPlugin): + """ + 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. + """ + def on_shutdown(self): + """ + Called upon the imminent shutdown of OctoPrint. + """ pass -class AssetPlugin(Plugin): +class AssetPlugin(OctoPrintPlugin): + """ + The ``AssetPlugin`` mixin allows plugins to define additional static assets such as Javascript or CSS files to + be automatically embedded into the pages delivered by the server to be used within the client sided part of + the plugin. + + A typical usage of the ``AssetPlugin`` functionality is to embed a custom view model to be used by templates injected + through a :class:`TemplatePlugin`. + """ + def get_asset_folder(self): - return None + """ + Defines the folder where the plugin stores its static assets as defined in :func:`get_assets`. Override this if + your plugin stores its assets at some other place than the ``static`` sub folder in the plugin base directory. + + :return string: the absolute path to the folder where the plugin stores its static assets + """ + import os + return os.path.join(self._basefolder, "static") def get_assets(self): + """ + Defines the static assets the plugin offers. The following asset types are recognized and automatically + imported at the appropriate places to be available: + + js + Javascript files, such as additional view models + css + CSS files with additional styles, will be embedded into delivered pages when not running in LESS mode. + less + LESS files with additional styles, will be embedded into delivered pages when running in LESS mode. + + The expected format to be returned is a dictionary mapping one or more of these keys to a list of files of that + type, the files being represented as relative paths from the asset folder as defined via :func:`get_asset_folder`. + Example: + + .. code-block:: python + + def get_assets(self): + return dict( + js=['js/my_file.js', 'js/my_other_file.js'], + css=['css/my_styles.css'], + less=['less/my_styles.less'] + ) + + The assets will be made available by OctoPrint under the URL ``/plugin_assets//``, with + ``plugin identifier`` being the plugin's identifier and ``path`` being the path as defined in the asset dictionary. + + :return dict: a dictionary describing the static assets to publish for the plugin + """ + return dict() + + +class TemplatePlugin(OctoPrintPlugin): + """ + Using the ``TemplatePlugin`` mixin plugins may inject their own components into the OctoPrint web interface. + + Currently OctoPrint supports the following types of injections: + + Navbar + The right part of the navigation bar located at the top of the UI can be enriched with additional links. Note that + with the current implementation, plugins will always be located *to the left* of the existing links. + + The included template must be called ``_navbar.jinja2`` (e.g. ``myplugin_navbar.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 structure will have all additional classes and styles applied as specified via the configuration supplied + through :func:`get_template_configs`. + + Sidebar + The left side bar containing Connection, State and Files sections can be enriched with additional sections. Note + that with the current implementations, plugins will always be located *beneath* the existing sections. + + The included template must be called ``_sidebar.jinja2`` (e.g. ``myplugin_sidebar.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 divs for both the whole box as well as the content pane will have all additional classes and styles applied + as specified via the configuration supplied through :func:`get_template_configs`. + + Tabs + The available tabs of the main part of the interface may be extended with additional tabs originating from within + plugins. Note that with the current implementation, plugins will always be located *to the right* of the existing + tabs. + + The included template must be called ``_tab.jinja2`` (e.g. ``myplugin_tab.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 navigation will have the additional classes and styles applied as specified via the + configuration supplied through :func:`get_template_configs`. + + Settings + Plugins may inject a dialog into the existing settings view. Note that with the current implementations, plugins + will always be listed beneath the "Plugins" header in the settings link list, ordered alphabetically after + their displayed name. + + The included template must be called ``_settings.jinja2`` (e.g. ``myplugin_settings.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 navigation will have the additional classes and styles applied as defined via the + supplied configuration supplied through :func:`get_template_configs`. + + 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. + + .. figure:: ../images/template-plugin-types-main.png + :align: center + :alt: Template injection types in the main part of the interface + + Template injection types in the main part of the interface + + .. figure:: ../images/template-plugin-types-settings.png + :align: center + :alt: Template injection types in the settings + + Template injection types in the settings + + You can find an example for a simple plugin which injects navbar, sidebar, tab and settings content into the interface in + `the "helloworld" plugin in OctoPrint's collection of plugin examples `_. + """ + + def get_template_configs(self): + """ + Allows configuration of injected navbar, sidebar, tab and settings templates. Should be a list containing one + configuration object per template to inject. Each configuration object is represented by a dictionary with a mandatory key + ``type`` encoding the template type the configuration is targeting. Possible values here are ``navbar``, ``sidebar``, + ``tab``, ``settings`` and ``generic``. + + Further keys to be included in the dictionary depend on the type: + + ``navbar`` type + .. figure:: ../images/template-plugin-type-navbar.png + :align: center + :alt: Structure of navbar plugins + + Configures a navbar component to inject. The following keys are supported: + + .. list-table:: + :widths: 5 95 + + * - template + - Name of the template to inject, defaults to ``_navbar.jinja2``. + * - suffix + - Suffix to attach to the element ID of the injected template, will be ``_`` if not provided and not + the first template of the type, with ``index`` counting from 1 and increasing for each template of the same + type. + * - div + - Id for the div containing the component. If not provided, defaults to ``plugin_`` plus + the suffix if provided or required. + * - replaces + - Id of navbar component this one replaces, might be either one of the core components or a component + provided by another plugin. See :ref:`this section ` for more on replacing template components. + * - custom_bindings + - A boolean value indicating whether the default view model should be bound to the navbar entry (``false``) + or if a custom binding will be used by the plugin (``true``, default). + * - data_bind + - Additional knockout data bindings to apply to the navbar entry, can be used to add further behaviour to + the container based on internal state if necessary. + * - classes + - Additional classes to apply to the navbar entry, as a list of individual classes + (e.g. ``classes=["myclass", "myotherclass"]``) which will be joined into the correct format by the template engine. + * - styles + - Additional CSS styles to apply to the navbar entry, as a list of individual declarations + (e.g. ``styles=["color: red", "display: block"]``) which will be joined into the correct format by the template + engine. + + ``sidebar`` type + .. figure:: ../images/template-plugin-type-sidebar.png + :align: center + :alt: Structure of sidebar plugins + + Configures a sidebar component to inject. The following keys are supported: + + .. list-table:: + :widths: 5 95 + + * - name + - The name of the sidebar entry, if not set the name of the plugin will be used. + * - icon + - Icon to use for the sidebar header, should be the name of a Font Awesome icon without the leading ``icon-`` part. + * - template + - Name of the template to inject, defaults to ``_sidebar.jinja2``. + * - template_header + - Additional template to include in the head section of the sidebar item. For an example of this, see the additional + options included in the "Files" section. + * - suffix + - Suffix to attach to the element ID of the injected template, will be ``_`` if not provided and not + the first template of the type, with ``index`` counting from 1 and increasing for each template of the same + type. + * - div + - Id for the div containing the component. If not provided, defaults to ``plugin_`` plus + the suffix if provided or required. + * - replaces + - Id of sidebar component this one replaces, might be either one of the core components or a component + provided by another plugin. See :ref:`this section ` for more on replacing template components. + * - custom_bindings + - A boolean value indicating whether the default view model should be bound to the sidebar container (``false``) + or if a custom binding will be used by the plugin (``true``, default). + * - data_bind + - Additional knockout data bindings to apply to the template container, can be used to add further behaviour to + the container based on internal state if necessary. + * - classes + - Additional classes to apply to both the wrapper around the sidebar box as well as the content pane itself, as a + list of individual classes (e.g. ``classes=["myclass", "myotherclass"]``) which will be joined into the correct + format by the template engine. + * - classes_wrapper + - Like ``classes`` but only applied to the whole wrapper around the sidebar box. + * - classes_content + - Like ``classes`` but only applied to the content pane itself. + * - styles + - Additional CSS styles to apply to both the wrapper around the sidebar box as well as the content pane itself, + as a list of individual declarations (e.g. ``styles=["color: red", "display: block"]``) which will be joined + into the correct format by the template engine. + * - styles_wrapper + - Like ``styles`` but only applied to the whole wrapper around the sidebar box. + * - styles_content + - Like ``styles`` but only applied to the content pane itself + + ``tab`` type + .. figure:: ../images/template-plugin-type-tab.png + :align: center + :alt: Structure of tab plugins + + Configures a tab component to inject. The value must be a dictionary, supported values are the following: + + .. list-table:: + :widths: 5 95 + + * - name + - The name under which to include the tab, if not set the name of the plugin will be used. + * - template + - Name of the template to inject, defaults to ``_tab.jinja2``. + * - suffix + - Suffix to attach to the element ID of the injected template, will be ``_`` if not provided and not + the first template of the type, with ``index`` counting from 1 and increasing for each template of the same + type. + * - div + - Id for the div containing the component. If not provided, defaults to ``plugin_`` plus + the suffix if provided or required. + * - replaces + - Id of tab component this one replaces, might be either one of the core components or a component + provided by another plugin. See :ref:`this section ` for more on replacing template components. + * - custom_bindings + - A boolean value indicating whether the default view model should be bound to the tab pane and link + in the navigation (``false``) or if a custom binding will be used by the plugin (``true``, default). + * - data_bind + - Additional knockout data bindings to apply to the template container, can be used to add further behaviour to + the container based on internal state if necessary. + * - classes + - Additional classes to apply to both the wrapper around the sidebar box as well as the content pane itself, as a + list of individual classes (e.g. ``classes=["myclass", "myotherclass"]``) which will be joined into the correct + format by the template engine. + * - classes_link + - Like ``classes`` but only applied to the link in the navigation. + * - classes_content + - Like ``classes`` but only applied to the content pane itself. + * - styles + - Additional CSS styles to apply to both the wrapper around the sidebar box as well as the content pane itself, + as a list of individual declarations (e.g. ``styles=["color: red", "display: block"]``) which will be joined + into the correct format by the template engine. + * - styles_link + - Like ``styles`` but only applied to the link in the navigation. + * - styles_content + - Like ``styles`` but only applied to the content pane itself. + + ``settings`` type + .. figure:: ../images/template-plugin-type-settings.png + :align: center + :alt: Structure of settings plugins + + Configures a settings component to inject. The value must be a dictionary, supported values are the following: + + .. list-table:: + :widths: 5 95 + + * - name + - The name under which to include the settings pane, if not set the name of the plugin will be used. + * - template + - Name of the template to inject, defaults to ``_settings.jinja2``. + * - suffix + - Suffix to attach to the element ID of the injected template, will be ``_`` if not provided and not + the first template of the type, with ``index`` counting from 1 and increasing for each template of the same + type. + * - div + - Id for the div containing the component. If not provided, defaults to ``plugin_`` plus + the suffix if provided or required. + * - replaces + - Id of settings component this one replaces, might be either one of the core components or a component + provided by another plugin. See :ref:`this section ` for more on replacing template components. + * - custom_bindings + - A boolean value indicating whether the default settings view model should be bound to the settings pane and link + in the navigation (``false``) or if a custom binding will be used by the plugin (``true``, default). + * - data_bind + - Additional knockout data bindings to apply to the template container, can be used to add further behaviour to + the container based on internal state if necessary. + * - classes + - Additional classes to apply to both the wrapper around the navigation link as well as the content pane itself, as a + list of individual classes (e.g. ``classes=["myclass", "myotherclass"]``) which will be joined into the correct + format by the template engine. + * - classes_link + - Like ``classes`` but only applied to the link in the navigation. + * - classes_content + - Like ``classes`` but only applied to the content pane itself. + * - styles + - Additional CSS styles to apply to both the wrapper around the navigation link as well as the content pane itself, + as a list of individual declarations (e.g. ``styles=["color: red", "display: block"]``) which will be joined + into the correct format by the template engine. + * - styles_link + - Like ``styles`` but only applied to the link in the navigation. + * - styles_content + - Like ``styles`` but only applied to the content pane itself + + ``generic`` type + Configures a generic template to inject. The following keys are supported: + + .. list-table:: + :widths: 5 95 + + * - template + - Name of the template to inject, defaults to ``.jinja2``. + + .. note:: + + As already outlined above, each template type has a default template name (i.e. the default navbar template + of a plugin is called ``_navbar.jinja2``), which may be overridden using the template configuration. + If a plugin needs to include more than one template of a given type, it needs to provide an entry for each of + those, since the implicit default template will only be included automatically if no other templates of that + type are defined. + + :return list: a list containing the configuration options for the plugin's injected templates + """ return [] - -class TemplatePlugin(Plugin): def get_template_vars(self): + """ + Defines additional template variables to include into the template renderer. Variable names will be prefixed + with ``plugin__``. + + :return dict: a dictionary containing any additional template variables to include in the renderer + """ return dict() def get_template_folder(self): - return None + """ + Defines the folder where the plugin stores its templates. Override this if your plugin stores its templates at + some other place than the ``templates`` sub folder in the plugin base directory. + + :return string: the absolute path to the folder where the plugin stores its jinja2 templates + """ + import os + return os.path.join(self._basefolder, "templates") -class SimpleApiPlugin(Plugin): +class SimpleApiPlugin(OctoPrintPlugin): + """ + Utilizing the ``SimpleApiPlugin`` mixin plugins may implement a simple API based around one GET resource and one + resource accepting JSON commands POSTed to it. This is the easy alternative for plugin's which don't need the + full power of a `Flask Blueprint `_ that the :class:`BlueprintPlugin` + mixin offers. + + Use this mixin if all you need to do is return some kind of dynamic data to your plugin from the backend + and/or want to react to simple commands which boil down to a type of command and a couple of flat parameters + supplied with it. + + The simple API constructed by OctoPrint for you will be made available under ``/api/plugin//``. + OctoPrint will do some preliminary request validation for your defined commands, making sure the request body is in + the correct format (content type must be JSON) and contains all obligatory parameters for your command. + + Let's take a look at a small example for such a simple API and how you would go about calling it. + + Take this example of a plugin registered under plugin identifier ``mysimpleapiplugin``: + + .. code-block:: python + :linenos: + + import octoprint.plugin + + import flask + + class MySimpleApiPlugin(octoprint.plugin.SimpleApiPlugin): + def get_api_commands(self): + return dict( + command1=[], + command2=["some_parameter"] + ) + + def on_api_command(self, command, data): + import flask + if command == "command1": + parameter = "unset" + if "parameter" in data: + parameter = "set" + self._logger.info("command1 called, parameter is {parameter}".format(**locals())) + elif command == "command2": + self._logger.info("command2 called, some_parameter is {some_parameter}".format(**data)) + + def on_api_get(self, request): + return flask.jsonify(foo="bar") + + __plugin_implementations__ = [MySimpleApiPlugin()] + + + Our plugin defines two commands, ``command1`` with no mandatory parameters and ``command2`` with one + mandatory parameter ``some_parameter``. + + ``command1`` can also accept an optional parameter ``parameter``, and will log whether + that parameter was set or unset. ``command2`` will log the content of the mandatory ``some_parameter`` parameter. + + A valid POST request for ``command2`` sent to ``/api/plugin/mysimpleapiplugin`` would look like this: + + .. sourcecode:: http + + POST /api/plugin/mysimpleapiplugin HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "command2", + "some_parameter": "some_value", + "some_optional_parameter": 2342 + } + + which would produce a response like this: + + .. sourcecode:: http + + HTTP/1.1 204 No Content + + and print something like this line to ``octoprint.log``:: + + 2015-02-12 17:40:21,140 - octoprint.plugins.mysimpleapiplugin - INFO - command2 called, some_parameter is some_value + + A GET request on our plugin's simple API resource will only return a JSON document like this: + + .. sourcecode:: http + + HTTP/1.1 200 Ok + Content-Type: application/json + + { + "foo": "bar" + } + """ + def get_api_commands(self): + """ + Return a dictionary here with the keys representing the accepted commands and the values being lists of + mandatory parameter names. + """ return None def on_api_command(self, command, data): + """ + Called by OctoPrint upon a POST request to ``/api/plugin/``. ``command`` will contain one of + the commands as specified via :func:`get_api_commands`, ``data`` will contain the full request body parsed + from JSON into a Python dictionary. Note that this will also contain the ``command`` attribute itself. For the + example given above, for the ``command2`` request the ``data`` received by the plugin would be equal to + ``dict(command="command2", some_parameter="some_value")``. + + If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content`` + for you. You may also return regular responses as you would return from any Flask view here though, e.g. + ``return flask.jsonify(result="some json result")`` or ``return flask.make_response("Not found", 404)``. + + :param string command: the command with which the resource was called + :param dict data: the full request body of the POST request parsed from JSON into a Python dictionary + :return: ``None`` in which case OctoPrint will generate a ``204 No content`` response with empty body, or optionally + a proper Flask response. + """ return None def on_api_get(self, request): + """ + Called by OctoPrint upon a GET request to ``/api/plugin/``. ``request`` will contain the + received `Flask request object `_ which you may evaluate + for additional arguments supplied with the request. + + If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content`` + for you. You may also return regular responses as you would return from any Flask view here though, e.g. + ``return flask.jsonify(result="some json result")`` or ``return flask.make_response("Not found", 404)``. + + :param request: the Flask request object + :return: ``None`` in which case OctoPrint will generate a ``204 No content`` response with empty body, or optionally + a proper Flask response. + """ return None -class BlueprintPlugin(Plugin): +class BlueprintPlugin(OctoPrintPlugin): + """ + The ``BlueprintPlugin`` mixin allows plugins to define their own full fledged endpoints for whatever purpose, + be it a more sophisticated API than what is possible via the :class:`SimpleApiPlugin` or a custom web frontend. + + The mechanism at work here is `Flask's `_ own `Blueprint mechanism `_. + + The mixin automatically creates a blueprint for you that will be registered under ``/plugin//``. + All you need to do is decorate all of your view functions with the :func:`route` decorator, + which behaves exactly the same like Flask's regular ``route`` decorators. Example: + + .. code-block:: python + :linenos: + + import octoprint.plugin + import flask + + class MyBlueprintPlugin(octoprint.plugin.BlueprintPlugin): + @octoprint.plugin.BlueprintPlugin.route("/echo", methods=["GET"]) + def myEcho(self): + if not "text" in flask.request.values: + return flask.make_response("Expected a text to echo back.", 400) + return flask.request.values["text"] + + __plugin_implementations__ = [MyBlueprintPlugin()] + + Your blueprint will be published by OctoPrint under the base URL ``/plugin//``, so the above + example of a plugin with the identifier "myblueprintplugin" would be reachable under + ``/plugin/myblueprintplugin/echo``. + + Just like with regular blueprints you'll be able to create URLs via ``url_for``, just use the prefix + ``plugin..``, e.g.: + + .. code-block:: python + + flask.url_for("plugin.myblueprintplugin.myEcho") # will return "/plugin/myblueprintplugin/echo" + + """ + + @staticmethod + def route(rule, **options): + """ + A decorator to mark view methods in your BlueprintPlugin subclass. Works just the same as Flask's + own ``route`` decorator available on blueprints. + + See `the documentation for flask.Blueprint.route `_ + and `the documentation for flask.Flask.route `_ for more + information. + """ + + from collections import defaultdict + def decorator(f): + # We attach the decorator parameters directly to the function object, because that's the only place + # we can access right now. + # This neat little trick was adapter from the Flask-Classy project: https://pythonhosted.org/Flask-Classy/ + if not hasattr(f, "_blueprint_rules") or f._blueprint_rules is None: + f._blueprint_rules = defaultdict(list) + f._blueprint_rules[f.__name__].append((rule, options)) + return f + return decorator + def get_blueprint(self): - return None + """ + Creates and returns the blueprint for your plugin. Override this if you want to define and handle your blueprint yourself. + + This method will only be called once during server initialization. + + :return: the blueprint ready to be registered with Flask + """ + + import flask + kwargs = self.get_blueprint_kwargs() + blueprint = flask.Blueprint("plugin." + self._identifier, self._identifier, **kwargs) + for member in [member for member in dir(self) if not member.startswith("_")]: + f = getattr(self, member) + if hasattr(f, "_blueprint_rules") and member in f._blueprint_rules: + for blueprint_rule in f._blueprint_rules[member]: + rule, options = blueprint_rule + blueprint.add_url_rule(rule, options.pop("endpoint", f.__name__), view_func=f, **options) + return blueprint + + def get_blueprint_kwargs(self): + """ + Override this if you want your blueprint constructed with additional options such as ``static_folder``, + ``template_folder``, etc. + + Defaults to the blueprint's ``static_folder`` and ``template_folder`` to be set to the plugin's basefolder + plus ``/static`` or respectively ``/templates``. + """ + import os + return dict( + static_folder=os.path.join(self._basefolder, "static"), + template_folder=os.path.join(self._basefolder, "templates") + ) + + def is_blueprint_protected(self): + """ + Whether a valid API key is needed to access the blueprint (the default) or not. + """ + + return True -class SettingsPlugin(Plugin): +class SettingsPlugin(OctoPrintPlugin): + """ + Including the ``SettingsPlugin`` mixin allows plugins to store and retrieve their own settings within OctoPrint's + configuration. + + Plugins including the mixing will get injected an additional property ``self._settings`` which is an instance of + :class:`PluginSettingsManager` already properly initialized for use by the plugin. In order for the manager to + know about the available settings structure and default values upon initialization, implementing plugins will need + to provide a dictionary with the plugin's default settings through overriding the method :func:`get_settings_defaults`. + The defined structure will then be available to access through the settings manager available as ``self._settings``. + + If your plugin needs to react to the change of specific configuration values on the fly, e.g. to adjust the log level + of a logger when the user changes a corresponding flag via the settings dialog, you can override the + :func:`on_settings_save` method and wrap the call to the implementation from the parent class with retrieval of the + old and the new value and react accordingly. + + Example: + + .. code-block:: python + + import octoprint.plugin + + class MySettingsPlugin(octoprint.plugin.SettingsPlugin, octoprint.plugin.StartupPlugin): + def get_settings_defaults(self): + return dict( + some_setting="foo", + some_value=23, + sub=dict( + some_flag=True + ) + ) + + def on_settings_save(self, data): + old_flag = self._settings.getBoolean(["sub", "some_flag"]) + + super(MySettingsPlugin, self).on_settings_save(data) + + new_flag = self._settings.getBoolean(["sub", "some_flag"]) + if old_flag != new_flag: + self._logger.info("sub.some_flag changed from {old_flag} to {new_flag}".format(**locals())) + + def on_after_startup(self): + some_setting = self._settings.get(["some_setting"]) + some_value = self._settings.getInt(["some_value"]) + some_flag = self._settings.getBoolean(["sub", "some_flag"]) + self._logger.info("some_setting = {some_setting}, some_value = {some_value}, sub.some_flag = {some_flag}".format(**locals()) + + __plugin_implementations__ = [MySettingsPlugin()] + + Of course, you are always free to completely override both :func:`on_settings_load` and :func:`on_settings_save` if the + default implementations do not fit your requirements. + + .. attribute:: _settings + + The :class:`~octoprint.plugin.PluginSettings` instance to use for accessing the plugin's settings. Injected by + the plugin core system upon initialization of the implementation. + """ + def on_settings_load(self): - return None + """ + Loads the settings for the plugin, called by the Settings API view in order to retrieve all settings from + all plugins. Override this if you want to inject additional settings properties that are not stored within + OctoPrint's configuration. + + .. note:: + + The default implementation will return your plugin's settings as is, so just in the structure and in the types + that are currently stored in OctoPrint's configuration. + + If you need more granular control here, e.g. over the used data types, you'll need to override this method + and iterate yourself over all your settings, using the proper retriever methods on the settings manager + to retrieve the data in the correct format. + + :return: the current settings of the plugin, as a dictionary + """ + return self._settings.get([], asdict=True, merged=True) def on_settings_save(self, data): - pass + """ + Saves the settings for the plugin, called by the Settings API view in order to persist all settings + from all plugins. Override this if you need to directly react to settings changes or want to extract + additional settings properties that are not stored within OctoPrint's configuration. + + .. note:: + + The default implementation will persist your plugin's settings as is, so just in the structure and in the + types that were received by the Settings API view. + + If you need more granular control here, e.g. over the used data types, you'll need to override this method + and iterate yourself over all your settings, retrieving them (if set) from the supplied received ``data`` + and using the proper setter methods on the settings manager to persist the data in the correct format. + + Arguments: + data (dict): The settings dictionary to be saved for the plugin + """ + import octoprint.util + + current = self._settings.get([], asdict=True, merged=True) + data = octoprint.util.dict_merge(current, data) + self._settings.set([], data) + + def get_settings_defaults(self): + """ + Retrieves the plugin's default settings with which the plugin's settings manager will be initialized. + + Override this in your plugin's implementation and return a dictionary defining your settings data structure + with included default values. + """ + return dict() + + def get_settings_preprocessors(self): + """ + Retrieves the plugin's preprocessors to use for preprocessing returned or set values prior to returning/setting + them. + + The preprocessors should be provided as a dictionary mapping the path of the values to preprocess + (hierarchically) to a transform function which will get the value to transform as only input and should return + the transformed value. + + Example: + + .. sourcecode: python + + def get_settings_defaults(self): + return dict(some_key="Some_Value", some_other_key="Some_Value") + + def get_settings_preprocessors(self): + return dict(some_key=lambda x: x.upper()), # getter preprocessors + dict(some_other_key=lambda x: x.lower()) # setter preprocessors + + def some_method(self): + # getting the value for "some_key" should turn it to upper case + assert self._settings.get(["some_key"]) == "SOME_VALUE" + + # the value for "some_other_key" should be left alone + assert self._settings.get(["some_other_key"] = "Some_Value" + + # setting a value for "some_other_key" should cause the value to first be turned to lower case + self._settings.set(["some_other_key"], "SOME_OTHER_VALUE") + assert self._settings.get(["some_other_key"]) == "some_other_value" + + Returns: + (dict, dict): A tuple consisting of two dictionaries, the first being the plugin's preprocessors for + getters, the second the preprocessors for setters + """ + return dict(), dict() -class EventHandlerPlugin(Plugin): +class EventHandlerPlugin(OctoPrintPlugin): + """ + The ``EventHandlerPlugin`` mixin allows OctoPrint plugins to react to any of :ref:`OctoPrint's events `. + OctoPrint will call the :func:`on_event` method for any event fired on its internal event bus, supplying the + event type and the associated payload. Please note that until your plugin returns from that method, further event + processing within OctoPrint will block - the event queue itself is run asynchronously from the rest of OctoPrint, + but the processing of the events within the queue itself happens consecutively. + + This mixin is especially interesting for plugins which want to react on things like print jobs finishing, timelapse + videos rendering etc. + """ + def on_event(self, event, payload): + """ + Called by OctoPrint upon processing of a fired event on the platform. + + :param string event: the type of event that got fired, see :ref:`the list of events ` + for possible values + :param dict payload: the payload as provided with the event + """ pass +class SlicerPlugin(OctoPrintPlugin): + """ + Via the ``SlicerPlugin`` mixin plugins can add support for slicing engines to be used by OctoPrint. + + """ + + def is_slicer_configured(self): + """ + Unless the return value of this method is ``True``, OctoPrint will not register the slicer within the slicing + sub system upon startup. Plugins may use this to do some start up checks to verify that e.g. the path to + a slicing binary as set and the binary is executable, or credentials of a cloud slicing platform are properly + entered etc. + """ + return False + + def get_slicer_properties(self): + """ + Plugins should override this method to return a ``dict`` containing a bunch of meta data about the implemented slicer. + + The expected keys in the returned ``dict`` have the following meaning: + + type + The type identifier to use for the slicer. This should be a short unique lower case string which will be + used to store slicer profiles under or refer to the slicer programmatically or from the API. + name + The human readable name of the slicer. This will be displayed to the user during slicer selection. + same_device + ``True`` if the slicer runs on the same device as OctoPrint, ``False`` otherwise. Slicers running on the same + device will TODO + progress_report + ``True`` if the slicer can report back slicing progress to OctoPrint ``False`` otherwise. + """ + return dict( + type=None, + name=None, + same_device=True, + progress_report=False + ) + + def get_slicer_default_profile(self): + """ + Should return a :class:`SlicingProfile` containing the default slicing profile to use with this slicer if + no other profile has been selected. + """ + return None + + def get_slicer_profile(self, path): + """ + Should return a :class:`SlicingProfile` parsed from the slicing profile stored at the indicated ``path``. + + :param string path: the path from which to read the slicing profile + """ + return None + + def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None): + """ + Should save the provided :class:`SlicingProfile` to the indicated ``path``, after applying any supplied + ``overrides``. If a profile is already saved under the indicated path and ``allow_overwrite`` is set to + ``False`` (defaults to ``True``), an ``IOError`` should be raised. + + :param string path: the path to which to save the profile + :param SlicingProfile profile: the profile to save + :param bool allow_overwrite: whether to allow to overwrite an existing profile at the indicated path (``True``, default) + or not (``False``) - if a profile already exists on the path and this is ``False`` + and :class:`IOError` should be raised + :param dict overrides: profile overrides to apply to the ``profile`` before saving it + """ + pass + + def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None): + """ + Called by OctoPrint to slice ``model_path`` for the indicated ``printer_profile``. If the ``machinecode_path`` is ``None``, + slicer implementations should generate it from the provided model_path. + + If provided, the ``profile_path`` is guaranteed by OctoPrint to be a serialized slicing profile created through the slicing + plugin's own :func:`save_slicer_profile` method. + + If provided, ``position`` will be a ``dict`` containing and ``x`` and a ``y`` key, indicating the position + the center of the model on the print bed should have in the final sliced machine code. If not provided, slicer + implementations should place the model in the center of the print bed. + + ``on_progress`` will be a callback which expects an additional keyword argument ``_progress`` with the current + slicing progress which - if progress reporting is supported - the slicing plugin should call like the following: + + .. code-block:: python + + if on_progress is not None: + if on_progress_args is None: + on_progress_args = () + if on_progress_kwargs is None: + on_progress_kwargs = dict() + + on_progress_kwargs["_progress"] = your_plugins_slicing_progress + on_progress(*on_progress_args, **on_progress_kwargs) + + Please note that both ``on_progress_args`` and ``on_progress_kwargs`` as supplied by OctoPrint might be ``None``, + so always make sure to initialize those values to sane defaults like depicted above before invoking the callback. + """ + pass + + def cancel_slicing(self, machinecode_path): + """ + Cancels the slicing to the indicated file + """ + pass + + +class ProgressPlugin(OctoPrintPlugin): + """ + Via the ``ProgressPlugin`` mixing plugins can let themselves be called upon progress in print jobs or slicing jobs, + limited to minimally 1% steps. + """ + + def on_print_progress(self, storage, path, progress): + """ + Called by OctoPrint on minimally 1% increments during a running print job. + + :param string location: Location of the file + :param string path: Path of the file + :param int progress: Current progress as a value between 0 and 100 + """ + pass + + def on_slicing_progress(self, slicer, source_location, source_path, destination_location, destination_path, progress): + """ + Called by OctoPrint on minimally 1% increments during a running slicing job. + + :param string slicer: Key of the slicer reporting the progress + :param string source_location: Location of the source file + :param string source_path: Path of the source file + :param string destination_location: Location the destination file + :param string destination_path: Path of the destination file + :param int progress: Current progress as a value between 0 and 100 + """ + pass + + +class AppPlugin(OctoPrintPlugin): + def get_additional_apps(self): + return [] + diff --git a/src/octoprint/plugins/cura/__init__.py b/src/octoprint/plugins/cura/__init__.py new file mode 100644 index 000000000..909e4285e --- /dev/null +++ b/src/octoprint/plugins/cura/__init__.py @@ -0,0 +1,421 @@ +# 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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import logging +import logging.handlers +import os +import flask +import math + +import octoprint.plugin +import octoprint.util +import octoprint.slicing +import octoprint.settings + +from .profile import Profile + +class CuraPlugin(octoprint.plugin.SlicerPlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.TemplatePlugin, + octoprint.plugin.AssetPlugin, + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.StartupPlugin): + + def __init__(self): + self._logger = logging.getLogger("octoprint.plugins.cura") + self._cura_logger = logging.getLogger("octoprint.plugins.cura.engine") + + # setup job tracking across threads + import threading + self._slicing_commands = dict() + self._cancelled_jobs = [] + self._job_mutex = threading.Lock() + + ##~~ StartupPlugin API + + def on_startup(self, host, port): + # setup our custom logger + cura_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="engine"), maxBytes=2*1024*1024) + cura_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) + cura_logging_handler.setLevel(logging.DEBUG) + + self._cura_logger.addHandler(cura_logging_handler) + self._cura_logger.setLevel(logging.DEBUG if self._settings.get_boolean(["debug_logging"]) else logging.CRITICAL) + self._cura_logger.propagate = False + + ##~~ BlueprintPlugin API + + @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"]) + input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"]) + + if input_upload_name in flask.request.values and input_upload_path in flask.request.values: + filename = flask.request.values[input_upload_name] + try: + profile_dict = Profile.from_cura_ini(flask.request.values[input_upload_path]) + except Exception as e: + return flask.make_response("Something went wrong while converting imported profile: {message}".format(e.message), 500) + + elif input_name in flask.request.files: + temp_file = tempfile.NamedTemporaryFile("wb", delete=False) + try: + temp_file.close() + upload = flask.request.files[input_name] + upload.save(temp_file.name) + profile_dict = Profile.from_cura_ini(temp_file.name) + except Exception as e: + return flask.make_response("Something went wrong while converting imported profile: {message}".format(e.message), 500) + finally: + os.remove(temp_file) + + filename = upload.filename + + else: + return flask.make_response("No file included", 400) + + if profile_dict is None: + return flask.make_response("Could not convert Cura profile", 400) + + name, _ = os.path.splitext(filename) + + # default values for name, display name and description + profile_name = _sanitize_name(name) + 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 + + # overrides + if "name" in flask.request.values: + profile_name = flask.request.values["name"] + if "displayName" in flask.request.values: + profile_display_name = flask.request.values["displayName"] + 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 + + slicingManager.save_profile("cura", + profile_name, + profile_dict, + allow_overwrite=profile_allow_overwrite, + display_name=profile_display_name, + description=profile_description) + + result = dict( + resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True), + displayName=profile_display_name, + description=profile_description + ) + r = flask.make_response(flask.jsonify(result), 201) + r.headers["Location"] = result["resource"] + return r + + ##~~ AssetPlugin API + + def get_assets(self): + return { + "js": ["js/cura.js"], + "less": ["less/cura.less"], + "css": ["css/cura.css"] + } + + ##~~ SettingsPlugin API + + def on_settings_save(self, data): + old_debug_logging = self._settings.get_boolean(["debug_logging"]) + + super(CuraPlugin, self).on_settings_save(data) + + new_debug_logging = self._settings.get_boolean(["debug_logging"]) + if old_debug_logging != new_debug_logging: + if new_debug_logging: + self._cura_logger.setLevel(logging.DEBUG) + else: + self._cura_logger.setLevel(logging.CRITICAL) + + def get_settings_defaults(self): + return dict( + cura_engine=None, + default_profile=None, + debug_logging=False + ) + + ##~~ 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): + 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) + + def get_slicer_properties(self): + return dict( + type="cura", + name="CuraEngine", + same_device=True, + progress_report=True + ) + + def get_slicer_default_profile(self): + path = self._settings.get(["default_profile"]) + if not path: + path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "profiles", "default.profile.yaml") + return self.get_slicer_profile(path) + + def get_slicer_profile(self, path): + profile_dict = self._load_profile(path) + + display_name = None + description = None + if "_display_name" in profile_dict: + display_name = profile_dict["_display_name"] + del profile_dict["_display_name"] + if "_description" in profile_dict: + description = profile_dict["_description"] + del profile_dict["_description"] + + properties = self.get_slicer_properties() + return octoprint.slicing.SlicingProfile(properties["type"], "unknown", profile_dict, display_name=display_name, description=description) + + def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None): + new_profile = Profile.merge_profile(profile.data, overrides=overrides) + + if profile.display_name is not None: + new_profile["_display_name"] = profile.display_name + if profile.description is not None: + new_profile["_description"] = profile.description + + self._save_profile(path, new_profile, allow_overwrite=allow_overwrite) + + def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None): + try: + with self._job_mutex: + if not profile_path: + profile_path = self._settings.get(["default_profile"]) + if not machinecode_path: + path, _ = os.path.splitext(model_path) + machinecode_path = path + ".gco" + + if position and isinstance(position, dict) and "x" in position and "y" in position: + posX = position["x"] + posY = position["y"] + else: + posX = None + posY = None + + if on_progress: + if not on_progress_args: + on_progress_args = () + if not on_progress_kwargs: + on_progress_kwargs = dict() + + self._cura_logger.info("### 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"]) + if not executable: + return False, "Path to CuraEngine is not configured " + + working_dir, _ = os.path.split(executable) + args = ['"%s"' % executable, '-v', '-p'] + for k, v in engine_settings.items(): + args += ["-s", '"%s=%s"' % (k, str(v))] + args += ['-o', '"%s"' % machinecode_path, '"%s"' % model_path] + + import sarge + command = " ".join(args) + self._logger.info("Running %r in %s" % (command, working_dir)) + + p = sarge.run(command, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture()) + p.wait_events() + self._slicing_commands[machinecode_path] = p.commands[0] + + try: + layer_count = None + step_factor = dict( + inset=0, + skin=1, + export=2 + ) + analysis = None + while p.returncode is None: + line = p.stderr.readline(timeout=0.5) + if not line: + p.commands[0].poll() + continue + + self._cura_logger.debug(line.strip()) + + if on_progress is not None: + # The Cura slicing process has three individual steps, each consisting of substeps: + # + # - inset + # - skin + # - export + # + # So each layer will be processed three times, once for each step, resulting in a total amount of + # substeps of 3 * . + # + # The CuraEngine reports the calculated layer count and the continuous progress on stderr. + # The layer count gets reported right at the beginning in a line of the format: + # + # Layer count: + # + # The individual progress per each of the three steps gets reported on stderr in a line of + # the format: + # + # Progress::: + # + # Thus, for determining the overall progress the following formula applies: + # + # progress = * + / * 3 + # + # with being 0 for "inset", 1 for "skin" and 2 for "export". + + if line.startswith("Layer count:") and layer_count is None: + try: + layer_count = float(line[len("Layer count:"):].strip()) + except: + pass + + elif line.startswith("Progress:"): + split_line = line[len("Progress:"):].strip().split(":") + if len(split_line) == 3: + step, current_layer, _ = split_line + try: + current_layer = float(current_layer) + except: + pass + else: + if not step in step_factor: + continue + on_progress_kwargs["_progress"] = (step_factor[step] * layer_count + current_layer) / (layer_count * 3) + on_progress(*on_progress_args, **on_progress_kwargs) + + elif line.startswith("Print time:"): + try: + print_time = int(line[len("Print time:"):].strip()) + if analysis is None: + analysis = dict() + analysis["estimatedPrintTime"] = print_time + except: + pass + + elif line.startswith("Filament:") or line.startswith("Filament2:"): + if line.startswith("Filament:"): + filament_str = line[len("Filament:"):].strip() + tool_key = "tool0" + else: + filament_str = line[len("Filament2:"):].strip() + tool_key = "tool1" + + 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 + except: + pass + finally: + p.close() + + with self._job_mutex: + if machinecode_path in self._cancelled_jobs: + self._cura_logger.info("### Cancelled") + raise octoprint.slicing.SlicingCancelled() + + self._cura_logger.info("### Finished, returncode %d" % p.returncode) + if p.returncode == 0: + return True, dict(analysis=analysis) + else: + self._logger.warn("Could not slice via Cura, got return code %r" % p.returncode) + return False, "Got returncode %r" % p.returncode + + except octoprint.slicing.SlicingCancelled as e: + raise e + except: + self._logger.exception("Could not slice via Cura, got an unknown error") + return False, "Unknown error, please consult the log file" + + finally: + with self._job_mutex: + if machinecode_path in self._cancelled_jobs: + self._cancelled_jobs.remove(machinecode_path) + if machinecode_path in self._slicing_commands: + del self._slicing_commands[machinecode_path] + + self._cura_logger.info("-" * 40) + + def cancel_slicing(self, machinecode_path): + with self._job_mutex: + if machinecode_path in self._slicing_commands: + self._cancelled_jobs.append(machinecode_path) + command = self._slicing_commands[machinecode_path] + if command is not None: + command.terminate() + self._logger.info("Cancelled slicing of %s" % machinecode_path) + + def _load_profile(self, path): + import yaml + profile_dict = dict() + with open(path, "r") as f: + try: + profile_dict = yaml.safe_load(f) + except: + raise IOError("Couldn't read profile from {path}".format(path=path)) + return profile_dict + + def _save_profile(self, path, profile, allow_overwrite=True): + if not allow_overwrite and os.path.exists(path): + raise IOError("Cannot overwrite {path}".format(path=path)) + + import yaml + with open(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 _sanitize_name(name): + if name is None: + return None + + 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.lower() + +__plugin_name__ = "CuraEngine" +__plugin_version__ = "0.1" +__plugin_author__ = "Gina Häußge" +__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura" +__plugin_description__ = "Adds support for slicing via CuraEngine from within OctoPrint" +__plugin_license__ = "AGPLv3" +__plugin_implementations__ = [CuraPlugin()] \ No newline at end of file diff --git a/src/octoprint/plugins/cura/profile.py b/src/octoprint/plugins/cura/profile.py new file mode 100644 index 000000000..6587c527d --- /dev/null +++ b/src/octoprint/plugins/cura/profile.py @@ -0,0 +1,975 @@ +# 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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import re + +class SupportLocationTypes(object): + NONE = "none" + TOUCHING_BUILDPLATE = "buildplate" + EVERYWHERE = "everywhere" + +class SupportDualTypes(object): + BOTH = "both" + FIRST = "first" + SECOND = "second" + +class SupportTypes(object): + GRID = "grid" + LINES = "lines" + +class PlatformAdhesionTypes(object): + NONE = "none" + BRIM = "brim" + RAFT = "raft" + +class MachineShapeTypes(object): + SQUARE = "square" + CIRCULAR = "circular" + +class GcodeFlavors(object): + REPRAP = "reprap" + REPRAP_VOLUME = "reprap_volume" + ULTIGCODE = "ultigcode" + MAKERBOT = "makerbot" + BFB = "bfb" + MACH3 = "mach3" + + +defaults = dict( + layer_height=0.1, + wall_thickness=0.8, + solid_layer_thickness=0.6, + print_temperature=[220, 0, 0, 0], + print_bed_temperature=70, + platform_adhesion=PlatformAdhesionTypes.NONE, + filament_diameter=[2.85, 0, 0, 0], + filament_flow=100.0, + bottom_thickness=0.3, + first_layer_width_factor=100.0, + object_sink=0.0, + + fill_density=20, + solid_top=True, + solid_bottom=True, + fill_overlap=15, + + # speeds + print_speed=50.0, + travel_speed=150.0, + bottom_layer_speed=20.0, + infill_speed=0.0, + outer_shell_speed=0.0, + inner_shell_speed=0.0, + + # dual extrusion + overlap_dual=0.15, + wipe_tower=False, + wipe_tower_volume=15, + ooze_shield=False, + + # retraction + retraction_enable=True, + retraction_speed=40.0, + retraction_amount=4.5, + retraction_dual_amount=16.5, + retraction_min_travel=1.5, + retraction_combing=True, + retraction_minimal_extrusion=0.02, + retraction_hop=0.0, + + # cooling + cool_min_layer_time=5, + fan_enabled=True, + fan_full_height=0.5, + fan_speed=100, + fan_speed_max=100, + cool_min_feedrate=10, + cool_head_lift=False, + + # support + support=SupportLocationTypes.NONE, + support_type=SupportTypes.GRID, + support_angle=60.0, + support_fill_rate=15, + support_xy_distance=0.7, + support_z_distance=0.15, + support_dual_extrusion=SupportDualTypes.BOTH, + + # platform adhesion + skirt_line_count=1, + skirt_gap=3.0, + skirt_minimal_length=150.0, + brim_line_count=20, + raft_margin=5.0, + raft_line_spacing=3.0, + raft_base_thickness=0.3, + raft_base_linewidth=1.0, + raft_interface_thickness=0.27, + raft_interface_linewidth=0.4, + raft_airgap=0.22, + raft_surface_layers=2, + + # repairing + fix_horrible_union_all_type_a=True, + fix_horrible_union_all_type_b=False, + fix_horrible_use_open_bits=False, + fix_horrible_extensive_stitching=False, + + # extras + spiralize=False, + follow_surface=False, + + machine_width=205, + machine_depth=205, + machine_center_is_zero=False, + has_heated_bed=False, + gcode_flavor=GcodeFlavors.REPRAP, + extruder_amount=1, + steps_per_e=0, + start_gcode=[ + # 1 extruder + """;Sliced at: {day} {date} {time} +;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density} +;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line +;M109 S{print_temperature} ;Uncomment to add your own temperature line +G21 ;metric values +G90 ;absolute positioning +M82 ;set extruder to absolute mode +M107 ;start with the fan off + +G28 X0 Y0 ;move X/Y to min endstops +G28 Z0 ;move Z to min endstops + +G1 Z15.0 F{travel_speed} ;move the platform down 15mm + +G92 E0 ;zero the extruded length +G1 F200 E3 ;extrude 3mm of feed stock +G92 E0 ;zero the extruded length again +G1 F{travel_speed} +;Put printing message on LCD screen +M117 Printing... +""", + # 2 extruders + """;Sliced at: {day} {date} {time} +;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density} +;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line +;M104 S{print_temperature} ;Uncomment to add your own temperature line +;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line +;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line +G21 ;metric values +G90 ;absolute positioning +M107 ;start with the fan off + +G28 X0 Y0 ;move X/Y to min endstops +G28 Z0 ;move Z to min endstops + +G1 Z15.0 F{travel_speed} ;move the platform down 15mm + +T1 ;Switch to the 2nd extruder +G92 E0 ;zero the extruded length +G1 F200 E10 ;extrude 10mm of feed stock +G92 E0 ;zero the extruded length again +G1 F200 E-{retraction_dual_amount} + +T0 ;Switch to the first extruder +G92 E0 ;zero the extruded length +G1 F200 E10 ;extrude 10mm of feed stock +G92 E0 ;zero the extruded length again +G1 F{travel_speed} +;Put printing message on LCD screen +M117 Printing... +""", + # 3 extruders + """;Sliced at: {day} {date} {time} +;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density} +;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line +;M104 S{print_temperature} ;Uncomment to add your own temperature line +;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line +;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line +G21 ;metric values +G90 ;absolute positioning +M107 ;start with the fan off + +G28 X0 Y0 ;move X/Y to min endstops +G28 Z0 ;move Z to min endstops + +G1 Z15.0 F{travel_speed} ;move the platform down 15mm + +T2 ;Switch to the 2nd extruder +G92 E0 ;zero the extruded length +G1 F200 E10 ;extrude 10mm of feed stock +G92 E0 ;zero the extruded length again +G1 F200 E-{retraction_dual_amount} + +T1 ;Switch to the 2nd extruder +G92 E0 ;zero the extruded length +G1 F200 E10 ;extrude 10mm of feed stock +G92 E0 ;zero the extruded length again +G1 F200 E-{retraction_dual_amount} + +T0 ;Switch to the first extruder +G92 E0 ;zero the extruded length +G1 F200 E10 ;extrude 10mm of feed stock +G92 E0 ;zero the extruded length again +G1 F{travel_speed} +;Put printing message on LCD screen +M117 Printing... +""", + # 4 extruders + """;Sliced at: {day} {date} {time} +;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density} +;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line +;M104 S{print_temperature} ;Uncomment to add your own temperature line +;M109 T2 S{print_temperature2} ;Uncomment to add your own temperature line +;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line +;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line +G21 ;metric values +G90 ;absolute positioning +M107 ;start with the fan off + +G28 X0 Y0 ;move X/Y to min endstops +G28 Z0 ;move Z to min endstops + +G1 Z15.0 F{travel_speed} ;move the platform down 15mm + +T3 ;Switch to the 4th extruder +G92 E0 ;zero the extruded length +G1 F200 E10 ;extrude 10mm of feed stock +G92 E0 ;zero the extruded length again +G1 F200 E-{retraction_dual_amount} + +T2 ;Switch to the 3th extruder +G92 E0 ;zero the extruded length +G1 F200 E10 ;extrude 10mm of feed stock +G92 E0 ;zero the extruded length again +G1 F200 E-{retraction_dual_amount} + +T1 ;Switch to the 2nd extruder +G92 E0 ;zero the extruded length +G1 F200 E10 ;extrude 10mm of feed stock +G92 E0 ;zero the extruded length again +G1 F200 E-{retraction_dual_amount} + +T0 ;Switch to the first extruder +G92 E0 ;zero the extruded length +G1 F200 E10 ;extrude 10mm of feed stock +G92 E0 ;zero the extruded length again +G1 F{travel_speed} +;Put printing message on LCD screen +M117 Printing... +""" + ], + end_gcode=[ + # 1 extruder + """;End GCode +M104 S0 ;extruder heater off +M140 S0 ;heated bed heater off (if you have it) + +G91 ;relative positioning +G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure +G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more +G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way + +M84 ;steppers off +G90 ;absolute positioning +;{profile_string} +""", + # 2 extruders + """;End GCode +M104 T0 S0 ;extruder heater off +M104 T1 S0 ;extruder heater off +M140 S0 ;heated bed heater off (if you have it) + +G91 ;relative positioning +G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure +G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more +G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way + +M84 ;steppers off +G90 ;absolute positioning +;{profile_string} +""", + # 3 extruders + """;End GCode +M104 T0 S0 ;extruder heater off +M104 T1 S0 ;extruder heater off +M104 T2 S0 ;extruder heater off +M140 S0 ;heated bed heater off (if you have it) + +G91 ;relative positioning +G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure +G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more +G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way + +M84 ;steppers off +G90 ;absolute positioning +;{profile_string} +""", + # 4 extruders + """;End GCode +M104 T0 S0 ;extruder heater off +M104 T1 S0 ;extruder heater off +M104 T2 S0 ;extruder heater off +M104 T3 S0 ;extruder heater off +M140 S0 ;heated bed heater off (if you have it) + +G91 ;relative positioning +G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure +G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more +G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way + +M84 ;steppers off +G90 ;absolute positioning +;{profile_string} +""" + ], + preSwitchExtruder_gcode=""";Switch between the current extruder and the next extruder, when printing with multiple extruders. +;This code is added before the T(n) +""", + postSwitchExtruder_gcode=""";Switch between the current extruder and the next extruder, when printing with multiple extruders. +;This code is added after the T(n) +""" +) + + +class Profile(object): + + regex_extruder_offset = re.compile("extruder_offset_([xy])(\d)") + regex_filament_diameter = re.compile("filament_diameter(\d?)") + regex_print_temperature = re.compile("print_temperature(\d?)") + regex_strip_comments = re.compile(";.*$", flags=re.MULTILINE) + + @classmethod + def from_cura_ini(cls, path): + import os + if not os.path.exists(path) or not os.path.isfile(path): + return None + + import ConfigParser + config = ConfigParser.ConfigParser() + try: + config.read(path) + except: + return None + + arrayified_options = ["print_temperature", "filament_diameter", "start.gcode", "end.gcode"] + translated_options = dict( + inset0_speed="outer_shell_speed", + insetx_speed="inner_shell_speed", + layer0_width_factor="first_layer_width_factor", + simple_mode="follow_surface", + ) + translated_options["start.gcode"] = "start_gcode" + translated_options["end.gcode"] = "end_gcode" + value_conversions = dict( + platform_adhesion={ + "None": PlatformAdhesionTypes.NONE, + "Brim": PlatformAdhesionTypes.BRIM, + "Raft": PlatformAdhesionTypes.RAFT + }, + support={ + "None": SupportLocationTypes.NONE, + "Touching buildplate": SupportLocationTypes.TOUCHING_BUILDPLATE, + "Everywhere": SupportLocationTypes.EVERYWHERE + }, + support_type={ + "Lines": SupportTypes.LINES, + "Grid": SupportTypes.GRID + }, + support_dual_extrusion={ + "Both": SupportDualTypes.BOTH, + "First extruder": SupportDualTypes.FIRST, + "Second extruder": SupportDualTypes.SECOND + } + ) + + result = dict() + for section in config.sections(): + if not section in ("profile", "alterations"): + continue + + for option in config.options(section): + ignored = False + key = option + + # try to fetch the value in the correct type + try: + value = config.getboolean(section, option) + except: + # no boolean, try int + try: + value = config.getint(section, option) + except: + # no int, try float + try: + value = config.getfloat(section, option) + except: + # no float, use str + value = config.get(section, option) + index = None + + for opt in arrayified_options: + if key.startswith(opt): + if key == opt: + index = 0 + else: + try: + # try to convert the target index, e.g. print_temperature2 => print_temperature[1] + index = int(key[len(opt):]) - 1 + except ValueError: + # ignore entries for which that fails + ignored = True + key = opt + break + if ignored: + continue + + if key in translated_options: + # if the key has to be translated to a new value, do that now + key = translated_options[key] + + if key in value_conversions and value in value_conversions[key]: + value = value_conversions[key][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: + result[key] = [] + if len(result[key]) <= index: + for n in xrange(index - len(result[key]) + 1): + result[key].append(None) + result[key][index] = value + else: + # just set the value if there's no array to fill + result[key] = value + + # merge it with our default settings, the imported profile settings taking precedence + return cls.merge_profile(result) + + + @classmethod + def merge_profile(cls, profile, overrides=None): + result = dict() + for key in defaults.keys(): + r = cls.merge_profile_key(key, profile, overrides=overrides) + if r is not None: + result[key] = r + return result + + @classmethod + def merge_profile_key(cls, key, profile, overrides=None): + profile_value = None + override_value = None + + if not key in defaults: + return None + import copy + result = copy.deepcopy(defaults[key]) + + if key in profile: + profile_value = profile[key] + if overrides and key in overrides: + override_value = overrides[key] + + if profile_value is None and override_value is None: + # neither override nor profile, no need to handle this key further + return None + + if key in ("filament_diameter", "print_temperature", "start_gcode", "end_gcode"): + # the array fields need some special treatment. Basically something like this: + # + # override_value: [None, "b"] + # profile_value : ["a" , None, "c"] + # default_value : ["d" , "e" , "f", "g"] + # + # should merge to something like this: + # + # ["a" , "b" , "c", "g"] + # + # So override > profile > default, if neither override nor profile value are available + # the default value should just be left as is + + for x in xrange(len(result)): + if override_value is not None and x < len(override_value) and override_value[x] is not None: + # we have an override value for this location, so we use it + result[x] = override_value[x] + elif profile_value is not None and x < len(profile_value) and profile_value[x] is not None: + # we have a profile value for this location, so we use it + result[x] = profile_value[x] + + else: + # just change the result value to the override_value if available, otherwise to the profile_value if + # that is given, else just leave as is + if override_value is not None: + result = override_value + elif profile_value is not None: + result = profile_value + + return result + + def __init__(self, profile, printer_profile, posX, posY, overrides=None): + self._profile = self.__class__.merge_profile(profile, overrides=overrides) + self._printer_profile = printer_profile + self._posX = posX + self._posY = posY + + def profile(self): + import copy + return copy.deepcopy(self._profile) + + def get(self, key): + if key in ("machine_width", "machine_depth", "machine_center_is_zero"): + if key == "machine_width": + return self._printer_profile["volume"]["width"] + elif key == "machine_depth": + return self._printer_profile["volume"]["depth"] + elif key == "machine_height": + return self._printer_profile["volume"]["height"] + elif key == "machine_center_is_zero": + return self._printer_profile["volume"]["formFactor"] == "circular" + else: + return None + + elif key == "extruder_amount": + return self._printer_profile["extruder"]["count"] + + elif key.startswith("extruder_offset_"): + extruder_offsets = self._printer_profile["extruder"]["offsets"] + match = Profile.regex_extruder_offset.match(key) + if not match: + return 0.0 + + axis, number = match.groups() + axis = axis.lower() + number = int(number) + + if not axis in ("x", "y"): + return 0.0 + if number >= len(extruder_offsets): + return 0.0 + + if axis == "x": + return extruder_offsets[number][0] + elif axis == "y": + return extruder_offsets[number][1] + else: + return 0.0 + + elif key == "has_heated_bed": + return self._printer_profile["heatedBed"] + + elif key.startswith("filament_diameter"): + match = Profile.regex_filament_diameter.match(key) + if not match: + return 0.0 + + diameters = self._get("filament_diameter") + if not match.group(1): + return diameters[0] + index = int(match.group(1)) + if index >= len(diameters): + return 0.0 + return diameters[index] + + elif key.startswith("print_temperature"): + match = Profile.regex_print_temperature.match(key) + if not match: + return 0.0 + + temperatures = self._get("print_temperature") + if not match.group(1): + return temperatures[0] + index = int(match.group(1)) + if index >= len(temperatures): + return 0.0 + return temperatures[index] + + else: + return self._get(key) + + def _get(self, key): + if key in self._profile: + return self._profile[key] + elif key in defaults: + return defaults[key] + else: + return None + + def get_int(self, key, default=None): + value = self.get(key) + if value is None: + return default + + try: + return int(value) + except ValueError: + return default + + def get_float(self, key, default=None): + value = self.get(key) + if value is None: + return default + + if isinstance(value, (str, unicode, basestring)): + value = value.replace(",", ".").strip() + + try: + return float(value) + except ValueError: + return default + + def get_boolean(self, key, default=None): + value = self.get(key) + if value is None: + return default + + if isinstance(value, bool): + return value + elif isinstance(value, (str, unicode, basestring)): + return value.lower() == "true" or value.lower() == "yes" or value.lower() == "on" or value == "1" + elif isinstance(value, (int, float)): + return value > 0 + else: + return value == True + + def get_microns(self, key, default=None): + value = self.get_float(key, default=None) + if value is None: + return default + return int(value * 1000) + + def get_gcode_template(self, key): + extruder_count = self.get_int("extruder_amount") + + if key in self._profile: + gcode = self._profile[key] + else: + gcode = defaults[key] + + if key in ("start_gcode", "end_gcode"): + return gcode[extruder_count-1] + else: + return gcode + + def get_profile_string(self): + import base64 + import zlib + + import copy + profile = copy.deepcopy(defaults) + profile.update(self._profile) + for key in ("print_temperature", "print_temperature2", "print_temperature3", "print_temperature4", + "filament_diameter", "filament_diameter2", "filament_diameter3", "filament_diameter4"): + profile[key] = self.get(key) + + result = [] + for k, v in profile.items(): + if isinstance(v, (str, unicode)): + result.append("{k}={v}".format(k=k, v=v.encode("utf-8"))) + else: + result.append("{k}={v}".format(k=k, v=v)) + + return base64.b64encode(zlib.compress("\b".join(result), 9)) + + def replaceTagMatch(self, m): + import time + + pre = m.group(1) + tag = m.group(2) + + if tag == 'time': + return pre + time.strftime('%H:%M:%S') + if tag == 'date': + return pre + time.strftime('%d-%m-%Y') + if tag == 'day': + return pre + ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][int(time.strftime('%w'))] + if tag == 'profile_string': + return pre + 'CURA_OCTO_PROFILE_STRING:%s' % (self.get_profile_string()) + + if pre == 'F' and tag == 'max_z_speed': + f = self.get_float("travel_speed") * 60 + elif pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'bottom_layer_speed', 'cool_min_feedrate']: + f = self.get_float(tag) * 60 + elif self.get(tag): + f = self.get(tag) + else: + return '%s?%s?' % (pre, tag) + + if (f % 1) == 0: + return pre + str(int(f)) + + return pre + str(f) + + def get_gcode(self, key): + extruder_count = self.get_int("extruder_amount") + + 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 "" + + 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) + + else: + contents = self.get_gcode_template(key) + + return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n' + + def calculate_edge_width_and_line_count(self): + wall_thickness = self.get_float("wall_thickness") + nozzle_size = self._printer_profile["extruder"]["nozzleDiameter"] + + if self.get_boolean("spiralize") or self.get_boolean("follow_surface"): + return wall_thickness, 1 + if wall_thickness < 0.01: + return nozzle_size, 0 + if wall_thickness < nozzle_size: + return wall_thickness, 1 + + edge_width = None + line_count = int(wall_thickness / (nozzle_size - 0.0001)) + if line_count < 1: + edge_width = nozzle_size + line_count = 1 + line_width = wall_thickness / line_count + line_width_alt = wall_thickness / (line_count + 1) + if line_width > nozzle_size * 1.5: + return line_width_alt, line_count + 1 + if not edge_width: + edge_width = line_width + return edge_width, line_count + + def calculate_solid_layer_count(self): + layer_height = self.get_float("layer_height") + solid_thickness = self.get_float("solid_layer_thickness") + if layer_height == 0.0: + return 1 + import math + return int(math.ceil(solid_thickness / (layer_height - 0.0001))) + + def calculate_minimal_extruder_count(self): + extruder_count = self.get("extruder_amount") + if extruder_count < 2: + return 1 + if self.get("support") == SupportLocationTypes.NONE: + return 1 + if self.get("support_dual_extrusion") == SupportDualTypes.SECOND: + return 2 + return 1 + + def get_pos_x(self): + if self._posX: + try: + return int(float(self._posX) * 1000) + 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 + + def get_pos_y(self): + if self._posY: + try: + return int(float(self._posY) * 1000) + 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 + + def convert_to_engine(self): + + edge_width, line_count = self.calculate_edge_width_and_line_count() + solid_layer_count = self.calculate_solid_layer_count() + + extruder_count = self.get_int("extruder_amount") + minimal_extruder_count = self.calculate_minimal_extruder_count() + + settings = { + "layerThickness": self.get_microns("layer_height"), + "initialLayerThickness": self.get_microns("bottom_thickness") if self.get_float("bottom_thickness") > 0.0 else self.get_microns("layer_height"), + "filamentDiameter": self.get_microns("filament_diameter"), + "filamentFlow": self.get_int("filament_flow"), + "extrusionWidth": edge_width * 1000, + "layer0extrusionWidth": int(edge_width * self.get_float("first_layer_width_factor") / 100 * 1000), + "insetCount": line_count, + "downSkinCount": solid_layer_count if self.get_boolean("solid_bottom") else 0, + "upSkinCount": solid_layer_count if self.get_boolean("solid_top") else 0, + "infillOverlap": self.get_int("fill_overlap"), + "initialSpeedupLayers": int(4), + "initialLayerSpeed": self.get_int("bottom_layer_speed"), + "printSpeed": self.get_int("print_speed"), + "infillSpeed": self.get_int("infill_speed") if self.get_int("infill_speed") > 0 else self.get_int("print_speed"), + "inset0Speed": self.get_int("outer_shell_speed") if self.get_int("outer_shell_speed") > 0 else self.get_int("print_speed"), + "insetXSpeed": self.get_int("inner_shell_speed") if self.get_int("inner_shell_speed") > 0 else self.get_int("print_speed"), + "moveSpeed": self.get_int("travel_speed"), + "fanSpeedMin": self.get_int("fan_speed") if self.get_boolean("fan_enabled") else 0, + "fanSpeedMax": self.get_int("fan_speed_max") if self.get_boolean("fan_enabled") else 0, + "supportAngle": int(-1) if self.get("support") == SupportLocationTypes.NONE else self.get_int("support_angle"), + "supportEverywhere": int(1) if self.get("support") == SupportLocationTypes.EVERYWHERE else int(0), + "supportLineDistance": int(100 * edge_width * 1000 / self.get_float("support_fill_rate")) if self.get_float("support_fill_rate") > 0 else -1, + "supportXYDistance": int(1000 * self.get_float("support_xy_distance")), + "supportZDistance": int(1000 * self.get_float("support_z_distance")), + "supportExtruder": 0 if self.get("support_dual_extrusion") == SupportDualTypes.FIRST else (1 if self.get("support_dual_extrusion") == SupportDualTypes.SECOND and minimal_extruder_count > 1 else -1), + "retractionAmount": self.get_microns("retraction_amount") if self.get_boolean("retraction_enable") else 0, + "retractionSpeed": self.get_int("retraction_speed"), + "retractionMinimalDistance": self.get_microns("retraction_min_travel"), + "retractionAmountExtruderSwitch": self.get_microns("retraction_dual_amount"), + "retractionZHop": self.get_microns("retraction_hop"), + "minimalExtrusionBeforeRetraction": self.get_microns("retraction_minimal_extrusion"), + "enableCombing": 1 if self.get_boolean("retraction_combing") else 0, + "multiVolumeOverlap": self.get_microns("overlap_dual"), + "objectSink": max(0, self.get_microns("object_sink")), + "minimalLayerTime": self.get_int("cool_min_layer_time"), + "minimalFeedrate": self.get_int("cool_min_feedrate"), + "coolHeadLift": 1 if self.get_boolean("cool_head_lift") else 0, + + # model positioning + "posx": self.get_pos_x(), + "posy": self.get_pos_y(), + + # gcodes + "startCode": self.get_gcode("start_gcode"), + "endCode": self.get_gcode("end_gcode"), + "preSwitchExtruderCode": self.get_gcode("preSwitchExtruder_gcode"), + "postSwitchExtruderCode": self.get_gcode("postSwitchExtruder_gcode"), + + # fixing + "fixHorrible": 0, + } + + for extruder in range(1, extruder_count): + for axis in ("x", "y"): + settings["extruderOffset[{extruder}].{axis}".format(extruder=extruder, axis=axis.upper())] = self.get("extruder_offset_{axis}{extruder}".format(extruder=extruder, axis=axis.lower())) + + fanFullHeight = self.get_microns("fan_full_height") + settings["fanFullOnLayerNr"] = (fanFullHeight - settings["initialLayerThickness"] - 1) / settings["layerThickness"] + 1 + if settings["fanFullOnLayerNr"] < 0: + settings["fanFullOnLayerNr"] = 0 + + if self.get("support_type") == SupportTypes.LINES: + settings["supportType"] = 1 + + # infill + if self.get_float("fill_density") == 0: + settings["sparseInfillLineDistance"] = -1 + + elif self.get_float("fill_density") == 100: + settings["sparseInfillLineDistance"] = settings["extrusionWidth"] + settings["downSkinCount"] = 10000 + settings["upSkinCount"] = 10000 + + else: + settings["sparseInfillLineDistance"] = int(100 * edge_width * 1000 / self.get_float("fill_density")) + + # brim/raft/skirt + if self.get("platform_adhesion") == PlatformAdhesionTypes.BRIM: + settings["skirtDistance"] = 0 + settings["skirtLineCount"] = self.get_int("brim_line_count") + + elif self.get("platform_adhesion") == PlatformAdhesionTypes.RAFT: + settings["skirtDistance"] = 0 + settings["skirtLineCount"] = 0 + settings["raftMargin"] = self.get_microns("raft_margin") + settings["raftLineSpacing"] = self.get_microns("raft_line_spacing") + settings["raftBaseThickness"] = self.get_microns("raft_base_thickness") + settings["raftBaseLinewidth"] = self.get_microns("raft_base_linewidth") + settings["raftInterfaceThickness"] = self.get_microns("raft_interface_thickness") + settings["raftInterfaceLinewidth"] = self.get_microns("raft_interface_linewidth") + settings["raftInterfaceLineSpacing"] = self.get_microns("raft_interface_linewidth") * 2 + settings["raftAirGapLayer0"] = self.get_microns("raft_airgap") + settings["raftBaseSpeed"] = self.get_int("bottom_layer_speed") + settings["raftFanSpeed"] = 100 + settings["raftSurfaceThickness"] = settings["raftInterfaceThickness"] + settings["raftSurfaceLinewidth"] = int(edge_width * 1000) + settings["raftSurfaceLineSpacing"] = int(edge_width * 1000 * 0.9) + settings["raftSurfaceLayers"] = self.get_int("raft_surface_layers") + settings["raftSurfaceSpeed"] = self.get_int("bottom_layer_speed") + + else: + settings["skirtDistance"] = self.get_microns("skirt_gap") + settings["skirtLineCount"] = self.get_int("skirt_line_count") + settings["skirtMinLength"] = self.get_microns("skirt_minimal_length") + + # fixing + if self.get_boolean("fix_horrible_union_all_type_a"): + settings["fixHorrible"] |= 0x01 + if self.get_boolean("fix_horrible_union_all_type_b"): + settings["fixHorrible"] |= 0x02 + if self.get_boolean("fix_horrible_use_open_bits"): + settings["fixHorrible"] |= 0x10 + if self.get_boolean("fix_horrible_extensive_stitching"): + settings["fixHorrible"] |= 0x04 + + if settings["layerThickness"] <= 0: + 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 + + # extras + if self.get_boolean("spiralize"): + settings["spiralizeMode"] = 1 + if self.get_boolean("follow_surface"): + settings["simpleMode"] = 1 + + # dual extrusion + if self.get_boolean("wipe_tower") and extruder_count > 1: + import math + settings["wipeTowerSize"] = int(math.sqrt(self.get_float("wipe_tower_volume") * 1000 * 1000 * 1000 / settings["layerThickness"])) + if self.get_boolean("ooze_shield"): + settings["enableOozeShield"] = 1 + + return settings diff --git a/src/octoprint/plugins/cura/profiles/default.profile.yaml b/src/octoprint/plugins/cura/profiles/default.profile.yaml new file mode 100644 index 000000000..d53fabc61 --- /dev/null +++ b/src/octoprint/plugins/cura/profiles/default.profile.yaml @@ -0,0 +1,4 @@ +layer_height: 0.2 +print_temperature: +- 220.0 +- 220.0 \ No newline at end of file diff --git a/src/octoprint/plugins/cura/static/css/cura.css b/src/octoprint/plugins/cura/static/css/cura.css new file mode 100644 index 000000000..f35eab40a --- /dev/null +++ b/src/octoprint/plugins/cura/static/css/cura.css @@ -0,0 +1 @@ +table th.settings_plugin_cura_profiles_key,table td.settings_plugin_cura_profiles_key{text-overflow:ellipsis;text-align:left;width:200px}table th.settings_plugin_cura_profiles_name,table td.settings_plugin_cura_profiles_name{text-overflow:ellipsis;text-align:left}table th.settings_plugin_cura_profiles_actions,table td.settings_plugin_cura_profiles_actions{text-align:center;width:100px}table th.settings_plugin_cura_profiles_actions a,table td.settings_plugin_cura_profiles_actions a{text-decoration:none;color:#000}table th.settings_plugin_cura_profiles_actions a.disabled,table td.settings_plugin_cura_profiles_actions a.disabled{color:#ccc;cursor:default} \ No newline at end of file diff --git a/src/octoprint/plugins/cura/static/js/cura.js b/src/octoprint/plugins/cura/static/js/cura.js new file mode 100644 index 000000000..83a02d79b --- /dev/null +++ b/src/octoprint/plugins/cura/static/js/cura.js @@ -0,0 +1,195 @@ +$(function() { + function CuraViewModel(parameters) { + var self = this; + + self.loginState = parameters[0]; + self.settingsViewModel = parameters[1]; + self.slicingViewModel = parameters[2]; + + self.fileName = ko.observable(); + + self.placeholderName = ko.observable(); + self.placeholderDisplayName = ko.observable(); + self.placeholderDescription = ko.observable(); + + self.profileName = ko.observable(); + self.profileDisplayName = ko.observable(); + self.profileDescription = ko.observable(); + self.profileAllowOverwrite = ko.observable(true); + + self.uploadElement = $("#settings-cura-import"); + self.uploadButton = $("#settings-cura-import-start"); + + self.profiles = new ItemListHelper( + "plugin_cura_profiles", + { + "id": function(a, b) { + if (a["key"].toLocaleLowerCase() < b["key"].toLocaleLowerCase()) return -1; + if (a["key"].toLocaleLowerCase() > b["key"].toLocaleLowerCase()) return 1; + return 0; + }, + "name": function(a, b) { + // sorts ascending + var aName = a.name(); + if (aName === undefined) { + aName = ""; + } + var bName = b.name(); + if (bName === undefined) { + bName = ""; + } + + if (aName.toLocaleLowerCase() < bName.toLocaleLowerCase()) return -1; + if (aName.toLocaleLowerCase() > bName.toLocaleLowerCase()) return 1; + return 0; + } + }, + {}, + "id", + [], + [], + 5 + ); + + self._sanitize = function(name) { + return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_"); + }; + + self.uploadElement.fileupload({ + dataType: "json", + maxNumberOfFiles: 1, + autoUpload: false, + add: function(e, data) { + if (data.files.length == 0) { + return false; + } + + self.fileName(data.files[0].name); + + var name = self.fileName().substr(0, self.fileName().lastIndexOf(".")); + self.placeholderName(self._sanitize(name).toLowerCase()); + self.placeholderDisplayName(name); + self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000)); + + self.uploadButton.on("click", function() { + var form = { + allowOverwrite: self.profileAllowOverwrite() + }; + + if (self.profileName() !== undefined) { + form["name"] = self.profileName(); + } + if (self.profileDisplayName() !== undefined) { + form["displayName"] = self.profileDisplayName(); + } + if (self.profileDescription() !== undefined) { + form["description"] = self.profileDescription(); + } + + data.formData = form; + data.submit(); + }); + }, + done: function(e, data) { + self.fileName(undefined); + self.placeholderName(undefined); + self.placeholderDisplayName(undefined); + self.placeholderDescription(undefined); + self.profileName(undefined); + self.profileDisplayName(undefined); + self.profileDescription(undefined); + self.profileAllowOverwrite(true); + + $("#settings_plugin_cura_import").modal("hide"); + self.requestData(); + self.slicingViewModel.requestData(); + } + }); + + self.removeProfile = function(data) { + if (!data.resource) { + return; + } + + self.profiles.removeItem(function(item) { + return (item.key == data.key); + }); + + $.ajax({ + url: data.resource(), + type: "DELETE", + success: function() { + self.requestData(); + self.slicingViewModel.requestData(); + } + }); + }; + + self.makeProfileDefault = function(data) { + if (!data.resource) { + return; + } + + _.each(self.profiles.items(), function(item) { + item.isdefault(false); + }); + var item = self.profiles.getItem(function(item) { + return item.key == data.key; + }); + if (item !== undefined) { + item.isdefault(true); + } + + $.ajax({ + url: data.resource(), + type: "PATCH", + dataType: "json", + data: JSON.stringify({default: true}), + contentType: "application/json; charset=UTF-8", + success: function() { + self.requestData(); + } + }); + }; + + self.showImportProfileDialog = function() { + $("#settings_plugin_cura_import").modal("show"); + }; + + self.requestData = function() { + $.ajax({ + url: API_BASEURL + "slicing/cura/profiles", + type: "GET", + dataType: "json", + success: self.fromResponse + }); + }; + + self.fromResponse = function(data) { + var profiles = []; + _.each(_.keys(data), function(key) { + profiles.push({ + key: key, + name: ko.observable(data[key].displayName), + description: ko.observable(data[key].description), + isdefault: ko.observable(data[key].default), + resource: ko.observable(data[key].resource) + }); + }); + self.profiles.updateItems(profiles); + }; + + self.onBeforeBinding = function () { + self.settings = self.settingsViewModel.settings; + self.requestData(); + }; + + } + + // view model class, parameters for constructor, container to bind to + OCTOPRINT_VIEWMODELS.push([ + CuraViewModel, + ["loginStateViewModel", "settingsViewModel", "slicingViewModel"], + "#settings_plugin_cura" + ]); +}); \ No newline at end of file diff --git a/src/octoprint/plugins/cura/static/less/cura.less b/src/octoprint/plugins/cura/static/less/cura.less new file mode 100644 index 000000000..0d28da219 --- /dev/null +++ b/src/octoprint/plugins/cura/static/less/cura.less @@ -0,0 +1,29 @@ +table { + th, td { + &.settings_plugin_cura_profiles_key { + text-overflow: ellipsis; + text-align: left; + width: 200px; + } + + &.settings_plugin_cura_profiles_name { + text-overflow: ellipsis; + text-align: left; + } + + &.settings_plugin_cura_profiles_actions { + text-align: center; + width: 100px; + + a { + text-decoration: none; + color: #000; + + &.disabled { + color: #ccc; + cursor: default; + } + } + } + } +} \ No newline at end of file diff --git a/src/octoprint/plugins/cura/templates/cura_settings.jinja2 b/src/octoprint/plugins/cura/templates/cura_settings.jinja2 new file mode 100644 index 000000000..943586ac3 --- /dev/null +++ b/src/octoprint/plugins/cura/templates/cura_settings.jinja2 @@ -0,0 +1,242 @@ +

{{ _('General') }}

+ +
+
+ +
+ +
+
+
+
+ +
+
+
+ +

{{ _('Profiles') }}

+ + + + + + + + + + + + + + + + + +
{{ _('Identifier') }}{{ _('Name') }}{{ _('Actions') }}
+  |  +
+ + + + + + + diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index 1268efe25..7516940d3 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -24,7 +24,10 @@ except: __plugin_name__ = "Discovery" __plugin_version__ = "0.1" +__plugin_author__ = "Gina Häußge" +__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery" __plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP" +__plugin_license__ = "AGPLv3" def __plugin_init__(): if not pybonjour: @@ -47,93 +50,16 @@ def __plugin_init__(): zeroconf_unregister=discovery_plugin.zeroconf_unregister )) - -default_settings = { - "publicHost": None, - "publicPort": None, - "pathPrefix": None, - "httpUsername": None, - "httpPassword": None, - "upnpUuid": None, - "zeroConf": [], - "model": { - "name": None, - "description": None, - "number": None, - "url": None, - "serial": None, - "vendor": None, - "vendorUrl": None - } -} -s = octoprint.plugin.plugin_settings("discovery", defaults=default_settings) - -def get_uuid(): - upnpUuid = s.get(["upnpUuid"]) - if upnpUuid is None: - import uuid - upnpUuid = str(uuid.uuid4()) - s.set(["upnpUuid"], upnpUuid) - s.save() - return upnpUuid -UUID = get_uuid() -del get_uuid - - -def get_instance_name(): - name = s.globalGet(["appearance", "name"]) - if name: - return "OctoPrint instance \"{}\"".format(name) - else: - import socket - return "OctoPrint instance on {}".format(socket.gethostname()) - - -#~~ custom blueprint for providing discovery.xml - -blueprint = flask.Blueprint("plugin.discovery", __name__, template_folder=os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates")) - -@blueprint.route("/discovery.xml") -def discovery(): - logging.getLogger("octoprint.plugins." + __name__).debug("Rendering discovery.xml") - - modelName = s.get(["model", "name"]) - if not modelName: - import octoprint.server - modelName = octoprint.server.DISPLAY_VERSION - - vendor = s.get(["model", "vendor"]) - vendorUrl = s.get(["model", "vendorUrl"]) - if not vendor: - vendor = "The OctoPrint Project" - vendorUrl = "http://www.octoprint.org/" - - response = flask.make_response(flask.render_template("discovery.jinja2", - friendlyName=get_instance_name(), - manufacturer=vendor, - manufacturerUrl=vendorUrl, - modelName=modelName, - modelDescription=s.get(["model", "description"]), - modelNumber=s.get(["model", "number"]), - modelUrl=s.get(["model", "url"]), - serialNumber=s.get(["model", "serial"]), - uuid=UUID, - presentationUrl=flask.url_for("index", _external=True))) - response.headers['Content-Type'] = 'application/xml' - return response - - class DiscoveryPlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.ShutdownPlugin, - octoprint.plugin.BlueprintPlugin): + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.SettingsPlugin): ssdp_multicast_addr = "239.255.255.250" ssdp_multicast_port = 1900 def __init__(self): - self.logger = logging.getLogger("octoprint.plugins." + __name__) - self.host = None self.port = None @@ -147,18 +73,69 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, self._ssdp_notify_timeout = 10 self._ssdp_last_notify = 0 + ##~~ SettingsPlugin API + + def get_settings_defaults(self): + return { + "publicHost": None, + "publicPort": None, + "pathPrefix": None, + "httpUsername": None, + "httpPassword": None, + "upnpUuid": None, + "zeroConf": [], + "model": { + "name": None, + "description": None, + "number": None, + "url": None, + "serial": None, + "vendor": None, + "vendorUrl": None + } + } + ##~~ BlueprintPlugin API -- used for providing the SSDP device descriptor XML - def get_blueprint(self): - return blueprint + @octoprint.plugin.BlueprintPlugin.route("/discovery.xml", methods=["GET"]) + def discovery(self): + self._logger.debug("Rendering discovery.xml") + + modelName = self._settings.get(["model", "name"]) + if not modelName: + import octoprint.server + modelName = octoprint.server.DISPLAY_VERSION + + vendor = self._settings.get(["model", "vendor"]) + vendorUrl = self._settings.get(["model", "vendorUrl"]) + if not vendor: + vendor = "The OctoPrint Project" + vendorUrl = "http://www.octoprint.org/" + + response = flask.make_response(flask.render_template("discovery.xml.jinja2", + friendlyName=self.get_instance_name(), + manufacturer=vendor, + manufacturerUrl=vendorUrl, + modelName=modelName, + modelDescription=self._settings.get(["model", "description"]), + modelNumber=self._settings.get(["model", "number"]), + modelUrl=self._settings.get(["model", "url"]), + serialNumber=self._settings.get(["model", "serial"]), + uuid=self.get_uuid(), + presentationUrl=flask.url_for("index", _external=True))) + response.headers['Content-Type'] = 'application/xml' + return response + + def is_blueprint_protected(self): + return False ##~~ StartupPlugin API -- used for registering OctoPrint's Zeroconf and SSDP services upon application startup def on_startup(self, host, port): - public_host = s.get(["publicHost"]) + public_host = self._settings.get(["publicHost"]) if public_host: host = public_host - public_port = s.get(["publicPort"]) + public_port = self._settings.get(["publicPort"]) if public_port: port = public_port @@ -166,13 +143,13 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, self.port = port # Zeroconf - self.zeroconf_register("_http._tcp", get_instance_name(), txt_record=self._create_http_txt_record_dict()) - self.zeroconf_register("_octoprint._tcp", get_instance_name(), txt_record=self._create_octoprint_txt_record_dict()) - for zeroconf in s.get(["zeroConf"]): + self.zeroconf_register("_http._tcp", self.get_instance_name(), txt_record=self._create_http_txt_record_dict()) + self.zeroconf_register("_octoprint._tcp", self.get_instance_name(), txt_record=self._create_octoprint_txt_record_dict()) + for zeroconf in self._settings.get(["zeroConf"]): if "service" in zeroconf: self.zeroconf_register( zeroconf["service"], - zeroconf["name"] if "name" in zeroconf else get_instance_name(), + zeroconf["name"] if "name" in zeroconf else self.get_instance_name(), port=zeroconf["port"] if "port" in zeroconf else None, txt_record=zeroconf["txtRecord"] if "txtRecord" in zeroconf else None ) @@ -207,7 +184,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, return if not name: - name = get_instance_name() + name = self.get_instance_name() if not port: port = self.port @@ -221,7 +198,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, key = (reg_type, port) self._sd_refs[key] = pybonjour.DNSServiceRegister(**params) - self.logger.info("Registered {name} for {reg_type}".format(**locals())) + self._logger.info(u"Registered {name} for {reg_type}".format(**locals())) def zeroconf_unregister(self, reg_type, port=None): """ @@ -245,9 +222,9 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, sd_ref = self._sd_refs[key] try: sd_ref.close() - self.logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port)) + self._logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port)) except: - self.logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port)) + self._logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port)) def zeroconf_browse(self, service_type, block=True, callback=None, browse_timeout=5, resolve_timeout=5): """ @@ -311,7 +288,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, name = fullname[:fullname.find(service_type) - 1].replace("\\032", " ") host = hosttarget[:-1] - self.logger.debug("Resolved a result for Zeroconf resolution of {service_type}: {name} @ {host}".format(service_type=service_type, name=name, host=host)) + self._logger.debug("Resolved a result for Zeroconf resolution of {service_type}: {name} @ {host}".format(service_type=service_type, name=name, host=host)) result.append(dict( name=name, host=host, @@ -327,7 +304,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, if not (flags & pybonjour.kDNSServiceFlagsAdd): return - self.logger.debug("Got a browsing result for Zeroconf resolution of {service_type}, resolving...".format(service_type=service_type)) + self._logger.debug("Got a browsing result for Zeroconf resolution of {service_type}, resolving...".format(service_type=service_type)) resolve_ref = pybonjour.DNSServiceResolve(0, interface_index, service_name, regtype, reply_domain, resolve_callback) try: @@ -342,7 +319,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, finally: resolve_ref.close() - self.logger.debug("Browsing Zeroconf for {service_type}".format(service_type=service_type)) + self._logger.debug("Browsing Zeroconf for {service_type}".format(service_type=service_type)) def browse(): sd_ref = pybonjour.DNSServiceBrowse(regtype=service_type, callBack=browse_callback) @@ -487,16 +464,16 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, # determine path entry path = "/" - if s.get(["pathPrefix"]): - path = s.get(["pathPrefix"]) + if self._settings.get(["pathPrefix"]): + path = self._settings.get(["pathPrefix"]) else: - prefix = s.globalGet(["server", "reverseProxy", "prefixFallback"]) + prefix = self._settings.global_get(["server", "reverseProxy", "prefixFallback"]) if prefix: path = prefix # fetch username and password (if set) - username = s.get(["httpUsername"]) - password = s.get(["httpPassword"]) + username = self._settings.get(["httpUsername"]) + password = self._settings.get(["httpPassword"]) entries = dict( path=path @@ -534,10 +511,10 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, api=octoprint.server.api.VERSION, )) - modelName = s.get(["model", "name"]) + modelName = self._settings.get(["model", "name"]) if modelName: entries.update(dict(model=modelName)) - vendor = s.get(["model", "vendor"]) + vendor = self._settings.get(["model", "vendor"]) if vendor: entries.update(dict(vendor=vendor)) @@ -595,7 +572,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, location = "http://{addr}:{port}/plugin/discovery/discovery.xml".format(addr=addr, port=self.port) - self.logger.debug("Sending NOTIFY {} via {}".format("alive" if alive else "byebye", addr)) + self._logger.debug("Sending NOTIFY {} via {}".format("alive" if alive else "byebye", addr)) notify_message = "".join([ "NOTIFY * HTTP/1.1\r\n", "Server: Python/2.7\r\n", @@ -606,7 +583,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, "USN: uuid:{uuid}::upnp:rootdevice\r\n", "HOST: {mcast_addr}:{mcast_port}\r\n\r\n" ]) - message = notify_message.format(uuid=UUID, + message = notify_message.format(uuid=self.get_uuid(), location=location, nts="ssdp:alive" if alive else "ssdp:byebye", mcast_addr=self.__class__.ssdp_multicast_addr, @@ -660,7 +637,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(self.__class__.ssdp_multicast_addr) + socket.inet_aton('0.0.0.0')) - self.logger.info("Registered {} for SSDP".format(get_instance_name())) + self._logger.info(u"Registered {} for SSDP".format(self.get_instance_name())) self._ssdp_notify(alive=True) @@ -672,11 +649,11 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, if not request.error_code and request.command == "M-SEARCH" and request.path == "*" and (request.headers["ST"] == "upnp:rootdevice" or request.headers["ST"] == "ssdp:all") and request.headers["MAN"] == '"ssdp:discover"': interface_address = octoprint.util.address_for_client(*address) if not interface_address: - self.logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address)) + self._logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address)) continue - message = location_message.format(uuid=UUID, location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port)) + message = location_message.format(uuid=self.get_uuid(), location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port)) sock.sendto(message, address) - self.logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address)) + self._logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address)) except socket.timeout: pass finally: @@ -687,4 +664,21 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, except: pass + ##~~ helpers + def get_uuid(self): + upnpUuid = self._settings.get(["upnpUuid"]) + if upnpUuid is None: + import uuid + upnpUuid = str(uuid.uuid4()) + self._settings.set(["upnpUuid"], upnpUuid) + self._settings.save() + return upnpUuid + + def get_instance_name(self): + name = self._settings.global_get(["appearance", "name"]) + if name: + return u"OctoPrint instance \"{}\"".format(name) + else: + import socket + return u"OctoPrint instance on {}".format(socket.gethostname()) diff --git a/src/octoprint/plugins/discovery/templates/discovery.jinja2 b/src/octoprint/plugins/discovery/templates/discovery.xml.jinja2 similarity index 100% rename from src/octoprint/plugins/discovery/templates/discovery.jinja2 rename to src/octoprint/plugins/discovery/templates/discovery.xml.jinja2 diff --git a/src/octoprint/printer.py b/src/octoprint/printer.py deleted file mode 100644 index 824a071bb..000000000 --- a/src/octoprint/printer.py +++ /dev/null @@ -1,761 +0,0 @@ -# coding=utf-8 -__author__ = "Gina Häußge " -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' - -import time -import datetime -import threading -import copy -import os -import logging - -import octoprint.util.comm as comm -import octoprint.util as util - -from octoprint.settings import settings -from octoprint.events import eventManager, Events - -from octoprint.filemanager.destinations import FileDestinations - -def getConnectionOptions(): - """ - Retrieves the available ports, baudrates, prefered port and baudrate for connecting to the printer. - """ - return { - "ports": comm.serialList(), - "baudrates": comm.baudrateList(), - "portPreference": settings().get(["serial", "port"]), - "baudratePreference": settings().getInt(["serial", "baudrate"]), - "autoconnect": settings().getBoolean(["serial", "autoconnect"]) - } - -class Printer(): - def __init__(self, gcodeManager): - from collections import deque - - self._gcodeManager = gcodeManager - self._gcodeManager.registerCallback(self) - - # state - # TODO do we really need to hold the temperature here? - self._temp = None - self._bedTemp = None - self._targetTemp = None - self._targetBedTemp = None - self._temps = deque([], 300) - self._tempBacklog = [] - - self._latestMessage = None - self._messages = deque([], 300) - self._messageBacklog = [] - - self._latestLog = None - self._log = deque([], 300) - self._logBacklog = [] - - self._state = None - - self._currentZ = None - - self._progress = None - self._printTime = None - self._printTimeLeft = None - - self._printAfterSelect = False - - # sd handling - self._sdPrinting = False - self._sdStreaming = False - self._sdFilelistAvailable = threading.Event() - self._streamingFinishedCallback = None - - self._selectedFile = None - - # comm - self._comm = None - - # callbacks - self._callbacks = [] - self._lastProgressReport = None - - self._stateMonitor = StateMonitor( - ratelimit=0.5, - updateCallback=self._sendCurrentDataCallbacks, - addTemperatureCallback=self._sendAddTemperatureCallbacks, - addLogCallback=self._sendAddLogCallbacks, - addMessageCallback=self._sendAddMessageCallbacks - ) - self._stateMonitor.reset( - state={"text": self.getStateString(), "flags": self._getStateFlags()}, - jobData={ - "file": { - "name": None, - "size": None, - "origin": None, - "date": None - }, - "estimatedPrintTime": None, - "lastPrintTime": None, - "filament": { - "length": None, - "volume": None - } - }, - progress={"completion": None, "filepos": None, "printTime": None, "printTimeLeft": None}, - currentZ=None - ) - - eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self.onMetadataAnalysisFinished); - - #~~ callback handling - - def registerCallback(self, callback): - self._callbacks.append(callback) - self._sendInitialStateUpdate(callback) - - def unregisterCallback(self, callback): - if callback in self._callbacks: - self._callbacks.remove(callback) - - def _sendAddTemperatureCallbacks(self, data): - for callback in self._callbacks: - try: callback.addTemperature(data) - except: pass - - def _sendAddLogCallbacks(self, data): - for callback in self._callbacks: - try: callback.addLog(data) - except: pass - - def _sendAddMessageCallbacks(self, data): - for callback in self._callbacks: - try: callback.addMessage(data) - except: pass - - def _sendCurrentDataCallbacks(self, data): - for callback in self._callbacks: - try: callback.sendCurrentData(copy.deepcopy(data)) - except: pass - - def _sendTriggerUpdateCallbacks(self, type): - for callback in self._callbacks: - try: callback.sendEvent(type) - except: pass - - def _sendFeedbackCommandOutput(self, name, output): - for callback in self._callbacks: - try: callback.sendFeedbackCommandOutput(name, output) - except: pass - - #~~ callback from gcodemanager - - def sendUpdateTrigger(self, type): - if type == "gcodeFiles" and self._selectedFile: - self._setJobData(self._selectedFile["filename"], - self._selectedFile["filesize"], - self._selectedFile["sd"]) - - #~~ callback from metadata analysis event - - def onMetadataAnalysisFinished(self, event, data): - if self._selectedFile: - self._setJobData(self._selectedFile["filename"], - self._selectedFile["filesize"], - self._selectedFile["sd"]) - - #~~ printer commands - - def connect(self, port=None, baudrate=None): - """ - Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection - will be attempted. - """ - if self._comm is not None: - self._comm.close() - self._comm = comm.MachineCom(port, baudrate, callbackObject=self) - - def disconnect(self): - """ - Closes the connection to the printer. - """ - if self._comm is not None: - self._comm.close() - self._comm = None - eventManager().fire(Events.DISCONNECTED) - - def command(self, command): - """ - Sends a single gcode command to the printer. - """ - self.commands([command]) - - def commands(self, commands): - """ - Sends multiple gcode commands (provided as a list) to the printer. - """ - if self._comm is None: - return - - for command in commands: - self._comm.sendCommand(command) - - def jog(self, axis, amount): - movementSpeed = settings().get(["printerParameters", "movementSpeed", ["x", "y", "z"]], asdict=True) - self.commands(["G91", "G1 %s%.4f F%d" % (axis.upper(), amount, movementSpeed[axis]), "G90"]) - - def home(self, axes): - self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), axes)), "G90"]) - - def extrude(self, amount): - extrusionSpeed = settings().get(["printerParameters", "movementSpeed", "e"]) - self.commands(["G91", "G1 E%s F%d" % (amount, extrusionSpeed), "G90"]) - - def changeTool(self, tool): - try: - toolNum = int(tool[len("tool"):]) - self.command("T%d" % toolNum) - except ValueError: - pass - - def setTemperature(self, type, value): - if type.startswith("tool"): - if settings().getInt(["printerParameters", "numExtruders"]) > 1: - try: - toolNum = int(type[len("tool"):]) - self.command("M104 T%d S%f" % (toolNum, value)) - except ValueError: - pass - else: - self.command("M104 S%f" % value) - elif type == "bed": - self.command("M140 S%f" % value) - - def setTemperatureOffset(self, offsets={}): - if self._comm is None: - return - - tool, bed = self._comm.getOffsets() - - validatedOffsets = {} - - for key in offsets: - value = offsets[key] - if key == "bed": - bed = value - validatedOffsets[key] = value - elif key.startswith("tool"): - try: - toolNum = int(key[len("tool"):]) - tool[toolNum] = value - validatedOffsets[key] = value - except ValueError: - pass - - self._comm.setTemperatureOffset(tool, bed) - self._stateMonitor.setTempOffsets(validatedOffsets) - - def selectFile(self, filename, sd, printAfterSelect=False): - if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()): - logging.info("Cannot load file: printer not connected or currently busy") - return - - self._printAfterSelect = printAfterSelect - self._comm.selectFile(filename, sd) - self._setProgressData(0, None, None, None) - self._setCurrentZ(None) - - def unselectFile(self): - if self._comm is not None and (self._comm.isBusy() or self._comm.isStreaming()): - return - - self._comm.unselectFile() - self._setProgressData(0, None, None, None) - self._setCurrentZ(None) - - def startPrint(self): - """ - Starts the currently loaded print job. - Only starts if the printer is connected and operational, not currently printing and a printjob is loaded - """ - if self._comm is None or not self._comm.isOperational() or self._comm.isPrinting(): - return - if self._selectedFile is None: - return - - self._setCurrentZ(None) - self._comm.startPrint() - - def togglePausePrint(self): - """ - Pause the current printjob. - """ - if self._comm is None: - return - - self._comm.setPause(not self._comm.isPaused()) - - def cancelPrint(self, disableMotorsAndHeater=True): - """ - Cancel the current printjob. - """ - if self._comm is None: - return - - self._comm.cancelPrint() - - if disableMotorsAndHeater: - # disable motors, switch off hotends, bed and fan - commands = ["M84"] - commands.extend(map(lambda x: "M104 T%d S0" % x, range(settings().getInt(["printerParameters", "numExtruders"])))) - commands.extend(["M140 S0", "M106 S0"]) - self.commands(commands) - - # reset progress, height, print time - self._setCurrentZ(None) - self._setProgressData(None, None, None, None) - - # mark print as failure - if self._selectedFile is not None: - self._gcodeManager.printFailed(self._selectedFile["filename"], self._comm.getPrintTime()) - payload = { - "file": self._selectedFile["filename"], - "origin": FileDestinations.LOCAL - } - if self._selectedFile["sd"]: - payload["origin"] = FileDestinations.SDCARD - eventManager().fire(Events.PRINT_FAILED, payload) - - #~~ state monitoring - - def _setCurrentZ(self, currentZ): - self._currentZ = currentZ - self._stateMonitor.setCurrentZ(self._currentZ) - - def _setState(self, state): - self._state = state - self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()}) - - def _addLog(self, log): - self._log.append(log) - self._stateMonitor.addLog(log) - - def _addMessage(self, message): - self._messages.append(message) - self._stateMonitor.addMessage(message) - - def _setProgressData(self, progress, filepos, printTime, printTimeLeft): - self._progress = progress - self._printTime = printTime - self._printTimeLeft = printTimeLeft - - self._stateMonitor.setProgress({ - "completion": self._progress * 100 if self._progress is not None else None, - "filepos": filepos, - "printTime": int(self._printTime) if self._printTime is not None else None, - "printTimeLeft": int(self._printTimeLeft * 60) if self._printTimeLeft is not None else None - }) - - def _addTemperatureData(self, temp, bedTemp): - currentTimeUtc = int(time.time()) - - data = { - "time": currentTimeUtc - } - for tool in temp.keys(): - data["tool%d" % tool] = { - "actual": temp[tool][0], - "target": temp[tool][1] - } - if bedTemp is not None and isinstance(bedTemp, tuple): - data["bed"] = { - "actual": bedTemp[0], - "target": bedTemp[1] - } - - self._temps.append(data) - - self._temp = temp - self._bedTemp = bedTemp - - self._stateMonitor.addTemperature(data) - - def _setJobData(self, filename, filesize, sd): - if filename is not None: - self._selectedFile = { - "filename": filename, - "filesize": filesize, - "sd": sd - } - else: - self._selectedFile = None - - estimatedPrintTime = None - lastPrintTime = None - date = None - filament = None - if filename: - # Use a string for mtime because it could be float and the - # javascript needs to exact match - if not sd: - date = int(os.stat(filename).st_ctime) - - fileData = self._gcodeManager.getFileData(filename) - if fileData is not None: - if "gcodeAnalysis" in fileData: - if estimatedPrintTime is None and "estimatedPrintTime" in fileData["gcodeAnalysis"]: - estimatedPrintTime = fileData["gcodeAnalysis"]["estimatedPrintTime"] - if "filament" in fileData["gcodeAnalysis"].keys(): - filament = fileData["gcodeAnalysis"]["filament"] - if "prints" in fileData and fileData["prints"] and "last" in fileData["prints"] and fileData["prints"]["last"] and "lastPrintTime" in fileData["prints"]["last"]: - lastPrintTime = fileData["prints"]["last"]["lastPrintTime"] - - self._stateMonitor.setJobData({ - "file": { - "name": os.path.basename(filename) if filename is not None else None, - "origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL, - "size": filesize, - "date": date - }, - "estimatedPrintTime": estimatedPrintTime, - "lastPrintTime": lastPrintTime, - "filament": filament, - }) - - def _sendInitialStateUpdate(self, callback): - try: - data = self._stateMonitor.getCurrentData() - data.update({ - "temps": list(self._temps), - "logs": list(self._log), - "messages": list(self._messages) - }) - callback.sendHistoryData(data) - except Exception, err: - import sys - sys.stderr.write("ERROR: %s\n" % str(err)) - pass - - def _getStateFlags(self): - return { - "operational": self.isOperational(), - "printing": self.isPrinting(), - "closedOrError": self.isClosedOrError(), - "error": self.isError(), - "paused": self.isPaused(), - "ready": self.isReady(), - "sdReady": self.isSdReady() - } - - #~~ callbacks triggered from self._comm - - def mcLog(self, message): - """ - Callback method for the comm object, called upon log output. - """ - self._addLog(message) - - def mcTempUpdate(self, temp, bedTemp): - self._addTemperatureData(temp, bedTemp) - - def mcStateChange(self, state): - """ - Callback method for the comm object, called if the connection state changes. - """ - oldState = self._state - - # forward relevant state changes to gcode manager - if self._comm is not None and oldState == self._comm.STATE_PRINTING: - if self._selectedFile is not None: - if state == self._comm.STATE_OPERATIONAL: - self._gcodeManager.printSucceeded(self._selectedFile["filename"], self._comm.getPrintTime()) - elif state == self._comm.STATE_CLOSED or state == self._comm.STATE_ERROR or state == self._comm.STATE_CLOSED_WITH_ERROR: - self._gcodeManager.printFailed(self._selectedFile["filename"], self._comm.getPrintTime()) - self._gcodeManager.resumeAnalysis() # printing done, put those cpu cycles to good use - elif self._comm is not None and state == self._comm.STATE_PRINTING: - self._gcodeManager.pauseAnalysis() # do not analyse gcode while printing - - self._setState(state) - - def mcMessage(self, message): - """ - Callback method for the comm object, called upon message exchanges via serial. - Stores the message in the message buffer, truncates buffer to the last 300 lines. - """ - self._addMessage(message) - - def mcProgress(self): - """ - Callback method for the comm object, called upon any change in progress of the printjob. - Triggers storage of new values for printTime, printTimeLeft and the current progress. - """ - - self._setProgressData(self._comm.getPrintProgress(), self._comm.getPrintFilepos(), self._comm.getPrintTime(), self._comm.getPrintTimeRemainingEstimate()) - - def mcZChange(self, newZ): - """ - Callback method for the comm object, called upon change of the z-layer. - """ - oldZ = self._currentZ - if newZ != oldZ: - # we have to react to all z-changes, even those that might "go backward" due to a slicer's retraction or - # anti-backlash-routines. Event subscribes should individually take care to filter out "wrong" z-changes - eventManager().fire(Events.Z_CHANGE, {"new": newZ, "old": oldZ}) - - self._setCurrentZ(newZ) - - def mcSdStateChange(self, sdReady): - self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()}) - - def mcSdFiles(self, files): - eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"}) - self._sdFilelistAvailable.set() - - def mcFileSelected(self, filename, filesize, sd): - self._setJobData(filename, filesize, sd) - self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()}) - - if self._printAfterSelect: - self.startPrint() - - def mcPrintjobDone(self): - self._setProgressData(1.0, self._selectedFile["filesize"], self._comm.getPrintTime(), 0) - self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()}) - - def mcFileTransferStarted(self, filename, filesize): - self._sdStreaming = True - - self._setJobData(filename, filesize, True) - self._setProgressData(0.0, 0, 0, None) - self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()}) - - def mcFileTransferDone(self, filename): - self._sdStreaming = False - - if self._streamingFinishedCallback is not None: - # in case of SD files, both filename and absolutePath are the same, so we set the (remote) filename for - # both parameters - self._streamingFinishedCallback(filename, filename, FileDestinations.SDCARD) - - self._setCurrentZ(None) - self._setJobData(None, None, None) - self._setProgressData(None, None, None, None) - self._stateMonitor.setState({"text": self.getStateString(), "flags": self._getStateFlags()}) - - def mcReceivedRegisteredMessage(self, command, output): - self._sendFeedbackCommandOutput(command, output) - - #~~ sd file handling - - def getSdFiles(self): - if self._comm is None or not self._comm.isSdReady(): - return [] - return self._comm.getSdFiles() - - def addSdFile(self, filename, absolutePath, streamingFinishedCallback): - if not self._comm or self._comm.isBusy() or not self._comm.isSdReady(): - logging.error("No connection to printer or printer is busy") - return - - self._streamingFinishedCallback = streamingFinishedCallback - - self.refreshSdFiles(blocking=True) - existingSdFiles = map(lambda x: x[0], self._comm.getSdFiles()) - - remoteName = util.getDosFilename(filename, existingSdFiles) - self._comm.startFileTransfer(absolutePath, filename, remoteName) - - return remoteName - - def deleteSdFile(self, filename): - if not self._comm or not self._comm.isSdReady(): - return - self._comm.deleteSdFile(filename) - - def initSdCard(self): - if not self._comm or self._comm.isSdReady(): - return - self._comm.initSdCard() - - def releaseSdCard(self): - if not self._comm or not self._comm.isSdReady(): - return - self._comm.releaseSdCard() - - def refreshSdFiles(self, blocking=False): - """ - Refreshs the list of file stored on the SD card attached to printer (if available and printer communication - available). Optional blocking parameter allows making the method block (max 10s) until the file list has been - received (and can be accessed via self._comm.getSdFiles()). Defaults to a asynchronous operation. - """ - if not self._comm or not self._comm.isSdReady(): - return - self._sdFilelistAvailable.clear() - self._comm.refreshSdFiles() - if blocking: - self._sdFilelistAvailable.wait(10000) - - #~~ state reports - - def getStateString(self): - """ - Returns a human readable string corresponding to the current communication state. - """ - if self._comm is None: - return "Offline" - else: - return self._comm.getStateString() - - def getCurrentData(self): - return self._stateMonitor.getCurrentData() - - def getCurrentJob(self): - currentData = self._stateMonitor.getCurrentData() - return currentData["job"] - - def getCurrentTemperatures(self): - if self._comm is not None: - tempOffset, bedTempOffset = self._comm.getOffsets() - else: - tempOffset = {} - bedTempOffset = None - - result = {} - if self._temp is not None: - for tool in self._temp.keys(): - result["tool%d" % tool] = { - "actual": self._temp[tool][0], - "target": self._temp[tool][1], - "offset": tempOffset[tool] if tool in tempOffset.keys() and tempOffset[tool] is not None else 0 - } - if self._bedTemp is not None: - result["bed"] = { - "actual": self._bedTemp[0], - "target": self._bedTemp[1], - "offset": bedTempOffset - } - - return result - - def getTemperatureHistory(self): - return self._temps - - def getCurrentConnection(self): - if self._comm is None: - return "Closed", None, None - - port, baudrate = self._comm.getConnection() - return self._comm.getStateString(), port, baudrate - - def isClosedOrError(self): - return self._comm is None or self._comm.isClosedOrError() - - def isOperational(self): - return self._comm is not None and self._comm.isOperational() - - def isPrinting(self): - return self._comm is not None and self._comm.isPrinting() - - def isPaused(self): - return self._comm is not None and self._comm.isPaused() - - def isError(self): - return self._comm is not None and self._comm.isError() - - def isReady(self): - return self.isOperational() and not self._comm.isStreaming() - - def isSdReady(self): - if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None: - return False - else: - return self._comm.isSdReady() - -class StateMonitor(object): - def __init__(self, ratelimit, updateCallback, addTemperatureCallback, addLogCallback, addMessageCallback): - self._ratelimit = ratelimit - self._updateCallback = updateCallback - self._addTemperatureCallback = addTemperatureCallback - self._addLogCallback = addLogCallback - self._addMessageCallback = addMessageCallback - - self._state = None - self._jobData = None - self._gcodeData = None - self._sdUploadData = None - self._currentZ = None - self._progress = None - - self._offsets = {} - - self._changeEvent = threading.Event() - self._stateMutex = threading.Lock() - - self._lastUpdate = time.time() - self._worker = threading.Thread(target=self._work) - self._worker.daemon = True - self._worker.start() - - def reset(self, state=None, jobData=None, progress=None, currentZ=None): - self.setState(state) - self.setJobData(jobData) - self.setProgress(progress) - self.setCurrentZ(currentZ) - - def addTemperature(self, temperature): - self._addTemperatureCallback(temperature) - self._changeEvent.set() - - def addLog(self, log): - self._addLogCallback(log) - self._changeEvent.set() - - def addMessage(self, message): - self._addMessageCallback(message) - self._changeEvent.set() - - def setCurrentZ(self, currentZ): - self._currentZ = currentZ - self._changeEvent.set() - - def setState(self, state): - with self._stateMutex: - self._state = state - self._changeEvent.set() - - def setJobData(self, jobData): - self._jobData = jobData - self._changeEvent.set() - - def setProgress(self, progress): - self._progress = progress - self._changeEvent.set() - - def setTempOffsets(self, offsets): - self._offsets = offsets - self._changeEvent.set() - - def _work(self): - while True: - self._changeEvent.wait() - - with self._stateMutex: - now = time.time() - delta = now - self._lastUpdate - additionalWaitTime = self._ratelimit - delta - if additionalWaitTime > 0: - time.sleep(additionalWaitTime) - - data = self.getCurrentData() - self._updateCallback(data) - self._lastUpdate = time.time() - self._changeEvent.clear() - - def getCurrentData(self): - return { - "state": self._state, - "job": self._jobData, - "currentZ": self._currentZ, - "progress": self._progress, - "offsets": self._offsets - } - diff --git a/src/octoprint/printer/__init__.py b/src/octoprint/printer/__init__.py new file mode 100644 index 000000000..3f97dedaf --- /dev/null +++ b/src/octoprint/printer/__init__.py @@ -0,0 +1,464 @@ +# coding=utf-8 +""" +This module defines the interface for communicating with a connected printer. + +The communication is in fact divided in two components, the :class:`PrinterInterface` and a deeper lying +communcation layer. However, plugins should only ever need to use the :class:`PrinterInterface` as the +abstracted version of the actual printer communiciation. + +.. autofunction:: get_connection_options + +.. autoclass:: PrinterInterface + :members: + +.. autoclass:: PrinterCallback + :members: +""" + +from __future__ import absolute_import + +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import re + +import octoprint.util.comm as comm +from octoprint.settings import settings + +def get_connection_options(): + """ + Retrieves the available ports, baudrates, prefered port and baudrate for connecting to the printer. + + Returned ``dict`` has the following structure:: + + ports: + baudrates: + portPreference: + baudratePreference: + autoconnect: + + Returns: + (dict): A dictionary holding the connection options in the structure specified above + """ + return { + "ports": comm.serialList(), + "baudrates": comm.baudrateList(), + "portPreference": settings().get(["serial", "port"]), + "baudratePreference": settings().getInt(["serial", "baudrate"]), + "autoconnect": settings().getBoolean(["serial", "autoconnect"]) + } + + +class PrinterInterface(object): + """ + The :class:`PrinterInterface` represents the developer interface to the :class:`~octoprint.printer.standard.Printer` + instance. + """ + + valid_axes = ("x", "y", "z", "e") + """Valid axes identifiers.""" + + valid_tool_regex = re.compile("^(tool\d+)$") + """Regex for valid tool identifiers.""" + + valid_heater_regex = re.compile("^(tool\d+|bed)$") + """Regex for valid heater identifiers.""" + + def connect(self, port=None, baudrate=None, profile=None): + """ + Connects to the printer, using the specified serial ``port``, ``baudrate`` and printer ``profile``. If a + connection is already established, that connection will be closed prior to connecting anew with the provided + parameters. + + Arguments: + port (str): Name of the serial port to connect to. If not provided, an auto detection will be attempted. + baudrate (int): Baudrate to connect with. If not provided, an auto detection will be attempted. + profile (str): Name of the printer profile to use for this connection. If not provided, the default + will be retrieved from the :class:`PrinterProfileManager`. + """ + pass + + def disconnect(self): + """ + Disconnects from the printer. Does nothing if no connection is currently established. + """ + raise NotImplementedError() + + def get_transport(self): + """ + Returns the communication layer's transport object, if a connection is currently established. + + Note that this doesn't have to necessarily be a :class:`serial.Serial` instance, it might also be something + different, so take care to do instance checks before attempting to access any properties or methods. + + Returns: + object: The communication layer's transport object + """ + raise NotImplementedError() + + def commands(self, commands): + """ + Sends the provided ``commands`` to the printer. + + Arguments: + commands (str, list): The commands to send. Might be a single command provided just as a string or a list + of multiple commands to send in order. + """ + raise NotImplementedError() + + def script(self, name, context=None): + """ + Sends the GCODE script ``name`` to the printer. + + The script will be run through the template engine, the rendering context can be extended by providing a + ``context`` with additional template variables to use. + + If the script is unknown, an :class:`UnknownScriptException` will be raised. + + Arguments: + name (str): The name of the GCODE script to render. + context (dict): An optional context of additional template variables to provide to the renderer. + + Raises: + UnknownScriptException: There is no GCODE script with name ``name`` + """ + raise NotImplementedError() + + def jog(self, axis, amount): + """ + Jogs the specified printer ``axis`` by the specified ``amount`` in mm. + + Arguments: + axis (str): The axis to jog, will be converted to lower case, one of "x", "y", "z" or "e" + amount (int, float): The amount by which to jog in mm + """ + raise NotImplementedError() + + def home(self, axes): + """ + Homes the specified printer ``axes``. + + Arguments: + axes (str, list): The axis or axes to home, each of which must converted to lower case must match one of + "x", "y", "z" and "e" + """ + raise NotImplementedError() + + def extrude(self, amount): + """ + Extrude ``amount`` milimeters of material from the tool. + + Arguments: + amount (int, float): The amount of material to extrude in mm + """ + raise NotImplementedError() + + def change_tool(self, tool): + """ + Switch the currently active ``tool`` (for which extrude commands will apply). + + Arguments: + tool (str): The tool to switch to, matching the regex "tool[0-9]+" (e.g. "tool0", "tool1", ...) + """ + raise NotImplementedError() + + def set_temperature(self, heater, value): + """ + Sets the target temperature on the specified ``heater`` to the given ``value`` in celsius. + + Arguments: + heater (str): The heater for which to set the target temperature. Either "bed" for setting the bed + temperature or something matching the regular expression "tool[0-9]+" (e.g. "tool0", "tool1", ...) for + the hotends of the printer + value (int, float): The temperature in celsius to set the target temperature to. + """ + raise NotImplementedError() + + def set_temperature_offset(self, offsets=None): + """ + Sets the temperature ``offsets`` to apply to target temperatures red from a GCODE file while printing. + + Arguments: + offsets (dict): A dictionary specifying the offsets to apply. Keys must match the format for the ``heater`` + parameter to :func:`set_temperature`, so "bed" for the offset for the bed target temperature and + "tool[0-9]+" for the offsets to the hotend target temperatures. + """ + raise NotImplementedError() + + def feed_rate(self, factor): + """ + Sets the ``factor`` for the printer's feed rate. + + Arguments: + factor (int, float): The factor for the feed rate to send to the firmware. Percentage expressed as either an + int between 0 and 100 or a float between 0 and 1. + """ + raise NotImplementedError() + + def flow_rate(self, factor): + """ + Sets the ``factor`` for the printer's flow rate. + + Arguments: + factor (int, float): The factor for the flow rate to send to the firmware. Percentage expressed as either an + int between 0 and 100 or a float between 0 and 1. + """ + raise NotImplementedError() + + def select_file(self, path, sd, printAfterSelect=False): + """ + Selects the specified ``path`` for printing, specifying if the file is to be found on the ``sd`` or not. + Optionally can also directly start the print after selecting the file. + + Arguments: + path (str): The path to select for printing. Either an absolute path (local file) or a + """ + raise NotImplementedError() + + def unselect_file(self): + """ + Unselects and currently selected file. + """ + raise NotImplementedError() + + def start_print(self): + """ + Starts printing the currently selected file. If no file is currently selected, does nothing. + """ + raise NotImplementedError() + + def toggle_pause_print(self): + """ + Pauses the current print job if it is currently running or resumes it if it is currently paused. + """ + raise NotImplementedError() + + def cancel_print(self): + """ + Cancels the current print job. + """ + raise NotImplementedError() + + def get_state_string(self): + """ + Returns: + (str) A human readable string corresponding to the current communication state. + """ + raise NotImplementedError() + + def get_current_data(self): + """ + Returns: + (dict) The current state data. + """ + raise NotImplementedError() + + def get_current_job(self): + """ + Returns: + (dict) The data of the current job. + """ + raise NotImplementedError() + + def get_current_temperatures(self): + """ + Returns: + (dict) The current temperatures. + """ + raise NotImplementedError() + + def get_temperature_history(self): + """ + Returns: + (list) The temperature history. + """ + raise NotImplementedError() + + def get_current_connection(self): + """ + Returns: + (tuple) The current connection information as a 4-tuple ``(connection_string, port, baudrate, printer_profile)``. + If the printer is currently not connected, the tuple will be ``("Closed", None, None, None)``. + """ + raise NotImplementedError() + + def is_closed_or_error(self): + """ + Returns: + (boolean) Whether the printer is currently disconnected and/or in an error state. + """ + raise NotImplementedError() + + def is_operational(self): + """ + Returns: + (boolean) Whether the printer is currently connected and available. + """ + raise NotImplementedError() + + def is_printing(self): + """ + Returns: + (boolean) Whether the printer is currently printing. + """ + raise NotImplementedError() + + def is_paused(self): + """ + Returns: + (boolean) Whether the printer is currently paused. + """ + raise NotImplementedError() + + def is_error(self): + """ + Returns: + (boolean) Whether the printer is currently in an error state. + """ + raise NotImplementedError() + + def is_ready(self): + """ + Returns: + (boolean) Whether the printer is currently operational and ready for new print jobs (not printing). + """ + raise NotImplementedError() + + def register_callback(self, callback): + """ + Registers a :class:`PrinterCallback` with the instance. + + Arguments: + callback (PrinterCallback): The callback object to register. + """ + raise NotImplementedError() + + def unregister_callback(self, callback): + """ + Unregisters a :class:`PrinterCallback` from the instance. + + Arguments: + callback (PrinterCallback): The callback object to unregister. + """ + raise NotImplementedError() + + +class PrinterCallback(object): + def on_printer_add_log(self, data): + """ + Called when the :class:`PrinterInterface` receives a new communication log entry from the communication layer. + + Arguments: + data (str): The received log line. + """ + pass + + def on_printer_add_message(self, data): + """ + Called when the :class:`PrinterInterface` receives a new message from the communication layer. + + Arguments: + data (str): The received message. + """ + pass + + def on_printer_add_temperature(self, data): + """ + Called when the :class:`PrinterInterface` receives a new temperature data set from the communication layer. + + ``data`` is a ``dict`` of the following structure:: + + tool0: + actual: + target: + ... + bed: + actual: + target: + + Arguments: + data (dict): A dict of all current temperatures in the format as specified above + """ + pass + + def on_printer_received_registered_message(self, name, output): + """ + Called when the :class:`PrinterInterface` received a registered message, e.g. from a feedback command. + + Arguments: + name (str): Name of the registered message (e.g. the feedback command) + output (str): Output for the registered message + """ + pass + + def on_printer_send_initial_data(self, data): + """ + Called when registering as a callback with the :class:`PrinterInterface` to receive the initial data (state, + log and temperature history etc) from the printer. + + ``data`` is a ``dict`` of the following structure:: + + temps: + - time: + tool0: + actual: + target: + ... + bed: + actual: + target: + - ... + logs: + messages: + + Arguments: + data (dict): The initial data in the format as specified above. + """ + pass + + def on_printer_send_current_data(self, data): + """ + Called when the internal state of the :class:`PrinterInterface` changes, due to changes in the printer state, + temperatures, log lines, job progress etc. Updates via this method are guaranteed to be throttled to a maximum + of 2 calles per second. + + ``data`` is a ``dict`` of the following structure:: + + state: + text: + flags: + operational: + printing: + closedOrError: + error: + paused: + ready: + sdReady: + job: + file: + name: , + size: , + origin: , + date: + estimatedPrintTime: + lastPrintTime: + filament: + length: + volume: + progress: + completion: + filepos: + printTime: + printTimeLeft: + currentZ: + offsets: + + Arguments: + data (dict): The current data in the format as specified above. + """ + pass + +class UnknownScript(BaseException): + def __init__(self, name, *args, **kwargs): + self.name = name diff --git a/src/octoprint/printer/estimation.py b/src/octoprint/printer/estimation.py new file mode 100644 index 000000000..30e733fc4 --- /dev/null +++ b/src/octoprint/printer/estimation.py @@ -0,0 +1,74 @@ +# 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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +class TimeEstimationHelper(object): + + STABLE_THRESHOLD = 0.1 + STABLE_COUNTDOWN = 250 + STABLE_ROLLING_WINDOW = 250 + + def __init__(self, rolling_window=None, countdown=None, threshold=None): + if rolling_window is None: + rolling_window = self.__class__.STABLE_ROLLING_WINDOW + if countdown is None: + countdown = self.__class__.STABLE_COUNTDOWN + if threshold is None: + threshold = self.__class__.STABLE_THRESHOLD + + self._rolling_window = rolling_window + self._countdown = countdown + self._threshold = threshold + + import collections + self._distances = collections.deque([], self._rolling_window) + self._totals = collections.deque([], self._rolling_window) + self._sum_total = 0 + self._count = 0 + self._stable_counter = None + + def is_stable(self): + return self._stable_counter is not None and self._stable_counter >= self._countdown + + def update(self, newEstimate): + old_average_total = self.average_total + + self._sum_total += newEstimate + self._totals.append(newEstimate) + self._count += 1 + + if old_average_total: + self._distances.append(abs(self.average_total - old_average_total)) + + if -1.0 * self._threshold < self.average_distance < self._threshold: + if self._stable_counter is None: + self._stable_counter = 0 + else: + self._stable_counter += 1 + else: + self._stable_counter = None + + @property + def average_total(self): + if not self._count: + return None + else: + return self._sum_total / self._count + + @property + def average_total_rolling(self): + if not self._count or self._count < self._rolling_window: + return None + else: + return sum(self._totals) / len(self._totals) + + @property + def average_distance(self): + if not self._count or self._count < self._rolling_window + 1: + return None + else: + return sum(self._distances) / len(self._distances) \ No newline at end of file diff --git a/src/octoprint/printer/profile.py b/src/octoprint/printer/profile.py new file mode 100644 index 000000000..2c9363ef6 --- /dev/null +++ b/src/octoprint/printer/profile.py @@ -0,0 +1,402 @@ +# 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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import os +import copy +import re +import logging + +from octoprint.settings import settings +from octoprint.util import dict_merge, dict_clean, dict_contains_keys + +class SaveError(Exception): + pass + +class CouldNotOverwriteError(SaveError): + pass + +class InvalidProfileError(Exception): + pass + +class BedTypes(object): + RECTANGULAR = "rectangular" + CIRCULAR = "circular" + + @classmethod + def values(cls): + return [getattr(cls, name) for name in cls.__dict__ if not name.startswith("__")] + +class PrinterProfileManager(object): + """ + Manager for printer profiles. Offers methods to select the globally used printer profile and to list, add, remove, + load and save printer profiles. + + A printer profile is a ``dict`` of the following structure: + + .. list-table:: + :widths: 15 5 10 30 + :header-rows: 1 + + * - Name + - Type + - Description + * - ``id`` + - ``string`` + - Internal id of the printer profile + * - ``name`` + - ``string`` + - Human readable name of the printer profile + * - ``model`` + - ``string`` + - Printer model + * - ``color`` + - ``string`` + - Color to associate with the printer profile + * - ``volume`` + - ``dict`` + - Information about the print volume + * - ``volume.width`` + - ``float`` + - Width of the print volume (X axis) + * - ``volume.depth`` + - ``float`` + - Depth of the print volume (Y axis) + * - ``volume.height`` + - ``float`` + - Height of the print volume (Z axis) + * - ``volume.formFactor`` + - ``string`` + - Form factor of the print bed, either ``rectangular`` or ``circular`` + * - ``heatedBed`` + - ``bool`` + - Whether the printer has a heated bed (``True``) or not (``False``) + * - ``extruder`` + - ``dict`` + - Information about the printer's extruders + * - ``extruder.count`` + - ``int`` + - How many extruders the printer has (default 1) + * - ``extruder.offsets`` + - ``list`` of ``tuple``s + - Extruder offsets relative to first extruder, list of (x, y) tuples, first is always (0,0) + * - ``extruder.nozzleDiameter`` + - ``float`` + - Diameter of the printer nozzle + * - ``axes`` + - ``dict`` + - Information about the printer axes + * - ``axes.x`` + - ``dict`` + - Information about the printer's X axis + * - ``axes.x.speed`` + - ``float`` + - Speed of the X axis in mm/s + * - ``axes.x.inverted`` + - ``bool`` + - Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True) + * - ``axes.y`` + - ``dict`` + - Information about the printer's Y axis + * - ``axes.y.speed`` + - ``float`` + - Speed of the Y axis in mm/s + * - ``axes.y.inverted`` + - ``bool`` + - Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True) + * - ``axes.z`` + - ``dict`` + - Information about the printer's Z axis + * - ``axes.z.speed`` + - ``float`` + - Speed of the Z axis in mm/s + * - ``axes.z.inverted`` + - ``bool`` + - Whether a positive value change moves the nozzle away from the print bed (False, default) or towards it (True) + * - ``axes.e`` + - ``dict`` + - Information about the printer's E axis + * - ``axes.e.speed`` + - ``float`` + - Speed of the E axis in mm/s + * - ``axes.e.inverted`` + - ``bool`` + - Whether a positive value change extrudes (False, default) or retracts (True) filament + """ + + default = dict( + id = "_default", + name = "Default", + model = "Generic RepRap Printer", + color = "default", + volume=dict( + width = 200, + depth = 200, + height = 200, + formFactor = BedTypes.RECTANGULAR, + ), + heatedBed = False, + extruder=dict( + count = 1, + offsets = [ + (0, 0) + ], + nozzleDiameter = 0.4 + ), + axes=dict( + x = dict(speed=6000, inverted=False), + y = dict(speed=6000, inverted=False), + z = dict(speed=200, inverted=False), + e = dict(speed=300, inverted=False) + ) + ) + + def __init__(self): + self._current = None + self._folder = settings().getBaseFolder("printerProfiles") + self._logger = logging.getLogger(__name__) + + def select(self, identifier): + if identifier is None or not self.exists(identifier): + self._current = self.get_default() + return False + else: + self._current = self.get(identifier) + return True + + def deselect(self): + self._current = None + + def get_all(self): + return self._load_all() + + def get(self, identifier): + try: + if identifier == "_default": + return self._load_default() + elif self.exists(identifier): + return self._load_from_path(self._get_profile_path(identifier)) + else: + return None + except InvalidProfileError: + return None + + def remove(self, identifier): + if identifier == "_default": + return False + return self._remove_from_path(self._get_profile_path(identifier)) + + def save(self, profile, allow_overwrite=False, make_default=False): + if "id" in profile: + identifier = profile["id"] + elif "name" in profile: + identifier = profile["name"] + else: + raise InvalidProfileError("profile must contain either id or name") + + identifier = self._sanitize(identifier) + profile["id"] = identifier + profile = dict_clean(profile, self.__class__.default) + + if identifier == "_default": + default_profile = dict_merge(self._load_default(), profile) + if not self._ensure_valid_profile(default_profile): + raise InvalidProfileError() + + settings().set(["printerProfiles", "defaultProfile"], default_profile, defaults=dict(printerProfiles=dict(defaultProfile=self.__class__.default))) + settings().save() + else: + self._save_to_path(self._get_profile_path(identifier), profile, allow_overwrite=allow_overwrite) + + if make_default: + settings().set(["printerProfiles", "default"], identifier) + + return self.get(identifier) + + def get_default(self): + default = settings().get(["printerProfiles", "default"]) + if default is not None and self.exists(default): + profile = self.get(default) + if profile is not None: + return profile + + return self._load_default() + + def set_default(self, identifier): + all_identifiers = self._load_all_identifiers().keys() + if identifier is not None and not identifier in all_identifiers: + return + + settings().set(["printerProfile", "default"], identifier) + settings().save() + + def get_current_or_default(self): + if self._current is not None: + return self._current + else: + return self.get_default() + + def get_current(self): + return self._current + + def exists(self, identifier): + if identifier is None: + return False + elif identifier == "_default": + return True + else: + path = self._get_profile_path(identifier) + return os.path.exists(path) and os.path.isfile(path) + + def _load_all(self): + all_identifiers = self._load_all_identifiers() + results = dict() + for identifier, path in all_identifiers.items(): + try: + if identifier == "_default": + profile = self._load_default() + else: + profile = self._load_from_path(path) + except InvalidProfileError: + continue + + if profile is None: + continue + + results[identifier] = dict_merge(self._load_default(), profile) + return results + + def _load_all_identifiers(self): + results = dict(_default=None) + for entry in os.listdir(self._folder): + if entry.startswith(".") or not entry.endswith(".profile") or entry == "_default.profile": + continue + + path = os.path.join(self._folder, entry) + if not os.path.isfile(path): + continue + + identifier = entry[:-len(".profile")] + results[identifier] = path + return results + + def _load_from_path(self, path): + if not os.path.exists(path) or not os.path.isfile(path): + return None + + import yaml + with open(path) as f: + profile = yaml.safe_load(f) + profile = self._ensure_valid_profile(profile) + if not profile: + self._logger.warn("Invalid profile: %s" % path) + raise InvalidProfileError() + return profile + + def _save_to_path(self, path, profile, allow_overwrite=False): + validated_profile = self._ensure_valid_profile(profile) + if not validated_profile: + raise InvalidProfileError() + + if os.path.exists(path) and not allow_overwrite: + raise SaveError("Profile %s already exists and not allowed to overwrite" % profile["id"]) + + import yaml + with open(path, "wb") as f: + try: + yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True) + except Exception as e: + raise SaveError("Cannot save profile %s: %s" % (profile["id"], e.message)) + + def _remove_from_path(self, path): + try: + os.remove(path) + return True + except: + return False + + def _load_default(self): + default_overrides = settings().get(["printerProfiles", "defaultProfile"]) + profile = self._ensure_valid_profile(dict_merge(copy.deepcopy(self.__class__.default), default_overrides)) + if not profile: + self._logger.warn("Invalid default profile after applying overrides") + return copy.deepcopy(self.__class__.default) + return profile + + def _get_profile_path(self, identifier): + return os.path.join(self._folder, "%s.profile" % identifier) + + def _sanitize(self, name): + if name is None: + return None + + 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 + + def _ensure_valid_profile(self, profile): + # ensure all keys are present + if not dict_contains_keys(self.default, profile): + return False + + # conversion helper + def convert_value(profile, path, converter): + value = profile + for part in path[:-1]: + if not isinstance(value, dict) or not part in value: + raise RuntimeError("%s is not contained in profile" % ".".join(path)) + value = value[part] + + if not isinstance(value, dict) or not path[-1] in value: + raise RuntimeError("%s is not contained in profile" % ".".join(path)) + + value[path[-1]] = converter(value[path[-1]]) + + # convert ints + for path in (("extruder", "count"), ("axes", "x", "speed"), ("axes", "y", "speed"), ("axes", "z", "speed")): + try: + convert_value(profile, path, int) + except: + return False + + # convert floats + for path in (("volume", "width"), ("volume", "depth"), ("volume", "height"), ("extruder", "nozzleDiameter")): + try: + convert_value(profile, path, float) + except: + return False + + # convert booleans + for path in (("axes", "x", "inverted"), ("axes", "y", "inverted"), ("axes", "z", "inverted")): + try: + convert_value(profile, path, bool) + except: + return False + + # validate form factor + if not profile["volume"]["formFactor"] in BedTypes.values(): + return False + + # validate offsets + offsets = [] + for offset in profile["extruder"]["offsets"]: + if not len(offset) == 2: + return False + x_offset, y_offset = offset + try: + offsets.append((float(x_offset), float(y_offset))) + except: + return False + profile["extruder"]["offsets"] = offsets + + return profile + diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py new file mode 100644 index 000000000..3127e0278 --- /dev/null +++ b/src/octoprint/printer/standard.py @@ -0,0 +1,927 @@ +# coding=utf-8 +""" +This module holds the standard implementation of the :class:`PrinterInterface` and it helpers. +""" + +from __future__ import absolute_import + +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import copy +import logging +import os +import threading +import time + +from octoprint import util as util +from octoprint.events import eventManager, Events +from octoprint.filemanager import FileDestinations +from octoprint.plugin import plugin_manager, ProgressPlugin +from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript +from octoprint.printer.estimation import TimeEstimationHelper +from octoprint.settings import settings +from octoprint.util import comm as comm + + +class Printer(PrinterInterface, comm.MachineComPrintCallback): + """ + Default implementation of the :class:`PrinterInterface`. Manages the communication layer object and registers + itself with it as a callback to react to changes on the communication layer. + """ + + def __init__(self, fileManager, analysisQueue, printerProfileManager): + from collections import deque + + self._logger = logging.getLogger(__name__) + + self._analysisQueue = analysisQueue + self._fileManager = fileManager + self._printerProfileManager = printerProfileManager + + # state + # TODO do we really need to hold the temperature here? + self._temp = None + self._bedTemp = None + self._targetTemp = None + self._targetBedTemp = None + self._temps = deque([], 300) + self._tempBacklog = [] + + self._latestMessage = None + self._messages = deque([], 300) + self._messageBacklog = [] + + self._latestLog = None + self._log = deque([], 300) + self._logBacklog = [] + + self._state = None + + self._currentZ = None + + self._progress = None + self._printTime = None + self._printTimeLeft = None + + self._printAfterSelect = False + + # sd handling + self._sdPrinting = False + self._sdStreaming = False + self._sdFilelistAvailable = threading.Event() + self._streamingFinishedCallback = None + + self._selectedFile = None + self._timeEstimationData = None + + # comm + self._comm = None + + # callbacks + self._callbacks = [] + + # progress plugins + self._lastProgressReport = None + self._progressPlugins = plugin_manager().get_implementations(ProgressPlugin) + + self._stateMonitor = StateMonitor( + interval=0.5, + on_update=self._sendCurrentDataCallbacks, + on_add_temperature=self._sendAddTemperatureCallbacks, + on_add_log=self._sendAddLogCallbacks, + on_add_message=self._sendAddMessageCallbacks + ) + self._stateMonitor.reset( + state={"text": self.get_state_string(), "flags": self._getStateFlags()}, + job_data={ + "file": { + "name": None, + "size": None, + "origin": None, + "date": None + }, + "estimatedPrintTime": None, + "lastPrintTime": None, + "filament": { + "length": None, + "volume": None + } + }, + progress={"completion": None, "filepos": None, "printTime": None, "printTimeLeft": None}, + current_z=None + ) + + eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self._on_event_MetadataAnalysisFinished) + eventManager().subscribe(Events.METADATA_STATISTICS_UPDATED, self._on_event_MetadataStatisticsUpdated) + + #~~ handling of PrinterCallbacks + + def register_callback(self, callback): + if not isinstance(callback, PrinterCallback): + self._logger.warn("Registering an object as printer callback which doesn't implement the PrinterCallback interface") + + self._callbacks.append(callback) + self._sendInitialStateUpdate(callback) + + def unregister_callback(self, callback): + if callback in self._callbacks: + self._callbacks.remove(callback) + + def _sendAddTemperatureCallbacks(self, data): + for callback in self._callbacks: + try: callback.on_printer_add_temperature(data) + except: self._logger.exception("Exception while adding temperature data point") + + def _sendAddLogCallbacks(self, data): + for callback in self._callbacks: + try: callback.on_printer_add_log(data) + except: self._logger.exception("Exception while adding communication log entry") + + def _sendAddMessageCallbacks(self, data): + for callback in self._callbacks: + try: callback.on_printer_add_message(data) + except: self._logger.exception("Exception while adding printer message") + + def _sendCurrentDataCallbacks(self, data): + for callback in self._callbacks: + try: callback.on_printer_send_current_data(copy.deepcopy(data)) + except: self._logger.exception("Exception while pushing current data") + + #~~ callback from metadata analysis event + + def _on_event_MetadataAnalysisFinished(self, event, data): + if self._selectedFile: + self._setJobData(self._selectedFile["filename"], + self._selectedFile["filesize"], + self._selectedFile["sd"]) + + def _on_event_MetadataStatisticsUpdated(self, event, data): + self._setJobData(self._selectedFile["filename"], + self._selectedFile["filesize"], + self._selectedFile["sd"]) + + #~~ progress plugin reporting + + def _reportPrintProgressToPlugins(self, progress): + if not progress or not self._selectedFile or not "sd" in self._selectedFile or not "filename" in self._selectedFile: + return + + storage = "sdcard" if self._selectedFile["sd"] else "local" + filename = self._selectedFile["filename"] + + def call_plugins(storage, filename, progress): + for name, plugin in self._progressPlugins.items(): + try: + plugin.on_print_progress(storage, filename, progress) + except: + self._logger.exception("Exception while sending print progress to plugin %s" % name) + + thread = threading.Thread(target=call_plugins, args=(storage, filename, progress)) + thread.daemon = False + thread.start() + + #~~ PrinterInterface implementation + + def connect(self, port=None, baudrate=None, profile=None): + """ + Connects to the printer. If port and/or baudrate is provided, uses these settings, otherwise autodetection + will be attempted. + """ + if self._comm is not None: + self._comm.close() + self._printerProfileManager.select(profile) + self._comm = comm.MachineCom(port, baudrate, callbackObject=self, printerProfileManager=self._printerProfileManager) + + def disconnect(self): + """ + Closes the connection to the printer. + """ + if self._comm is not None: + self._comm.close() + self._comm = None + self._printerProfileManager.deselect() + eventManager().fire(Events.DISCONNECTED) + + def get_transport(self): + + if self._comm is None: + return None + + return self._comm.getTransport() + getTransport = util.deprecated("getTransport has been renamed to get_transport", since="1.2.0-dev-590", includedoc="Replaced by :func:`get_transport`") + + def commands(self, commands): + """ + Sends one or more gcode commands to the printer. + """ + if self._comm is None: + return + + if not isinstance(commands, (list, tuple)): + commands = [commands] + + for command in commands: + self._comm.sendCommand(command) + + def script(self, name, context=None): + if self._comm is None: + return + + if name is None or not name: + raise ValueError("name must be set") + + result = self._comm.sendGcodeScript(name, replacements=context) + if not result: + raise UnknownScript(name) + + def jog(self, axis, amount): + if not isinstance(axis, (str, unicode)): + raise ValueError("axis must be a string: {axis}".format(axis=axis)) + + axis = axis.lower() + if not axis in PrinterInterface.valid_axes: + raise ValueError("axis must be any of {axes}: {axis}".format(axes=", ".join(PrinterInterface.valid_axes), axis=axis)) + if not isinstance(amount, (int, long, float)): + raise ValueError("amount must be a valid number: {amount}".format(amount=amount)) + + printer_profile = self._printerProfileManager.get_current_or_default() + movement_speed = printer_profile["axes"][axis]["speed"] + self.commands(["G91", "G1 %s%.4f F%d" % (axis.upper(), amount, movement_speed), "G90"]) + + def home(self, axes): + if not isinstance(axes, (list, tuple)): + if isinstance(axes, (str, unicode)): + axes = [axes] + else: + raise ValueError("axes is neither a list nor a string: {axes}".format(axes=axes)) + + validated_axes = filter(lambda x: x in PrinterInterface.valid_axes, map(lambda x: x.lower(), axes)) + if len(axes) != len(validated_axes): + raise ValueError("axes contains invalid axes: {axes}".format(axes=axes)) + + self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), validated_axes)), "G90"]) + + def extrude(self, amount): + if not isinstance(amount, (int, long, float)): + raise ValueError("amount must be a valid number: {amount}".format(amount=amount)) + + printer_profile = self._printerProfileManager.get_current_or_default() + extrusion_speed = printer_profile["axes"]["e"]["speed"] + self.commands(["G91", "G1 E%s F%d" % (amount, extrusion_speed), "G90"]) + + def change_tool(self, tool): + if not PrinterInterface.valid_tool_regex.match(tool): + raise ValueError("tool must match \"tool[0-9]+\": {tool}".format(tool=tool)) + + tool_num = int(tool[len("tool"):]) + self.commands("T%d" % tool_num) + + def set_temperature(self, heater, value): + if not PrinterInterface.valid_heater_regex.match(heater): + raise ValueError("heater must match \"tool[0-9]+\" or \"bed\": {heater}".format(type=heater)) + + if not isinstance(value, (int, long, float)) or value < 0: + raise ValueError("value must be a valid number >= 0: {value}".format(value=value)) + + if heater.startswith("tool"): + printer_profile = self._printerProfileManager.get_current_or_default() + extruder_count = printer_profile["extruder"]["count"] + if extruder_count > 1: + toolNum = int(heater[len("tool"):]) + self.commands("M104 T%d S%f" % (toolNum, value)) + else: + self.commands("M104 S%f" % value) + + elif heater == "bed": + self.commands("M140 S%f" % value) + + def set_temperature_offset(self, offsets=None): + if offsets is None: + offsets = dict() + + if not isinstance(offsets, dict): + raise ValueError("offsets must be a dict") + + validated_keys = filter(lambda x: PrinterInterface.valid_heater_regex.match(x), offsets.keys()) + validated_values = filter(lambda x: isinstance(x, (int, long, float)), offsets.values()) + + if len(validated_keys) != len(offsets): + raise ValueError("offsets contains invalid keys: {offsets}".format(offsets=offsets)) + if len(validated_values) != len(offsets): + raise ValueError("offsets contains invalid values: {offsets}".format(offsets=offsets)) + + if self._comm is None: + return + + self._comm.setTemperatureOffset(offsets) + self._stateMonitor.set_temp_offsets(offsets) + + def _convert_rate_value(self, factor, min=0, max=200): + if not isinstance(factor, (int, float, long)): + raise ValueError("factor is not a number") + + if isinstance(factor, float): + factor = int(factor * 100.0) + + if factor < min or factor > max: + raise ValueError("factor must be a value between %f and %f" % (min, max)) + + return factor + + def feed_rate(self, factor): + factor = self._convert_rate_value(factor, min=50, max=200) + self.commands("M220 S%d" % factor) + + def flow_rate(self, factor): + factor = self._convert_rate_value(factor, min=75, max=125) + self.commands("M221 S%d" % factor) + + def select_file(self, path, sd, printAfterSelect=False): + if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()): + self._logger.info("Cannot load file: printer not connected or currently busy") + return + + self._printAfterSelect = printAfterSelect + self._comm.selectFile("/" + path if sd else path, sd) + self._setProgressData(0, None, None, None) + self._setCurrentZ(None) + + def unselect_file(self): + if self._comm is not None and (self._comm.isBusy() or self._comm.isStreaming()): + return + + self._comm.unselectFile() + self._setProgressData(0, None, None, None) + self._setCurrentZ(None) + + def start_print(self): + """ + Starts the currently loaded print job. + Only starts if the printer is connected and operational, not currently printing and a printjob is loaded + """ + if self._comm is None or not self._comm.isOperational() or self._comm.isPrinting(): + return + if self._selectedFile is None: + return + + rolling_window = None + threshold = None + countdown = None + if self._selectedFile["sd"]: + # we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived + # by that divided by the sd status polling interval + rolling_window = 15 / settings().get(["serial", "timeout", "sdStatus"]) + + # we are happy if the average of the estimates stays within 60s of the prior one + threshold = 60 + + # we are happy when one rolling window has been stable + countdown = rolling_window + self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window, threshold=threshold, countdown=countdown) + + self._lastProgressReport = None + self._setCurrentZ(None) + self._comm.startPrint() + + def toggle_pause_print(self): + """ + Pause the current printjob. + """ + if self._comm is None: + return + + self._comm.setPause(not self._comm.isPaused()) + + def cancel_print(self): + """ + Cancel the current printjob. + """ + if self._comm is None: + return + + self._comm.cancelPrint() + + # reset progress, height, print time + self._setCurrentZ(None) + self._setProgressData(None, None, None, None) + + # mark print as failure + if self._selectedFile is not None: + self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"]) + payload = { + "file": self._selectedFile["filename"], + "origin": FileDestinations.LOCAL + } + if self._selectedFile["sd"]: + payload["origin"] = FileDestinations.SDCARD + eventManager().fire(Events.PRINT_FAILED, payload) + + def get_state_string(self): + """ + Returns a human readable string corresponding to the current communication state. + """ + if self._comm is None: + return "Offline" + else: + return self._comm.getStateString() + + def get_current_data(self): + return self._stateMonitor.get_current_data() + + def get_current_job(self): + currentData = self._stateMonitor.get_current_data() + return currentData["job"] + + def get_current_temperatures(self): + if self._comm is not None: + tempOffset, bedTempOffset = self._comm.getOffsets() + else: + tempOffset = {} + bedTempOffset = None + + result = {} + if self._temp is not None: + for tool in self._temp.keys(): + result["tool%d" % tool] = { + "actual": self._temp[tool][0], + "target": self._temp[tool][1], + "offset": tempOffset[tool] if tool in tempOffset.keys() and tempOffset[tool] is not None else 0 + } + if self._bedTemp is not None: + result["bed"] = { + "actual": self._bedTemp[0], + "target": self._bedTemp[1], + "offset": bedTempOffset + } + + return result + + def get_temperature_history(self): + return self._temps + + def get_current_connection(self): + if self._comm is None: + return "Closed", None, None, None + + port, baudrate = self._comm.getConnection() + printer_profile = self._printerProfileManager.get_current_or_default() + return self._comm.getStateString(), port, baudrate, printer_profile + + def is_closed_or_error(self): + return self._comm is None or self._comm.isClosedOrError() + + def is_operational(self): + return self._comm is not None and self._comm.isOperational() + + def is_printing(self): + return self._comm is not None and self._comm.isPrinting() + + def is_paused(self): + return self._comm is not None and self._comm.isPaused() + + def is_error(self): + return self._comm is not None and self._comm.isError() + + def is_ready(self): + return self.is_operational() and not self._comm.isStreaming() + + def is_sd_ready(self): + if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None: + return False + else: + return self._comm.isSdReady() + + #~~ sd file handling + + def get_sd_files(self): + if self._comm is None or not self._comm.isSdReady(): + return [] + return map(lambda x: (x[0][1:], x[1]), self._comm.getSdFiles()) + + def add_sd_file(self, filename, absolutePath, streamingFinishedCallback): + if not self._comm or self._comm.isBusy() or not self._comm.isSdReady(): + self._logger.error("No connection to printer or printer is busy") + return + + self._streamingFinishedCallback = streamingFinishedCallback + + self.refresh_sd_files(blocking=True) + existingSdFiles = map(lambda x: x[0], self._comm.getSdFiles()) + + remoteName = util.get_dos_filename(filename, existing_filenames=existingSdFiles, extension="gco") + self._timeEstimationData = TimeEstimationHelper() + self._comm.startFileTransfer(absolutePath, filename, "/" + remoteName) + + return remoteName + + def delete_sd_file(self, filename): + if not self._comm or not self._comm.isSdReady(): + return + self._comm.deleteSdFile("/" + filename) + + def init_sd_card(self): + if not self._comm or self._comm.isSdReady(): + return + self._comm.initSdCard() + + def release_sd_card(self): + if not self._comm or not self._comm.isSdReady(): + return + self._comm.releaseSdCard() + + def refresh_sd_files(self, blocking=False): + """ + Refreshs the list of file stored on the SD card attached to printer (if available and printer communication + available). Optional blocking parameter allows making the method block (max 10s) until the file list has been + received (and can be accessed via self._comm.getSdFiles()). Defaults to an asynchronous operation. + """ + if not self._comm or not self._comm.isSdReady(): + return + self._sdFilelistAvailable.clear() + self._comm.refreshSdFiles() + if blocking: + self._sdFilelistAvailable.wait(10000) + + #~~ state monitoring + + def _setCurrentZ(self, currentZ): + self._currentZ = currentZ + self._stateMonitor.set_current_z(self._currentZ) + + def _setState(self, state): + self._state = state + self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()}) + + def _addLog(self, log): + self._log.append(log) + self._stateMonitor.add_log(log) + + def _addMessage(self, message): + self._messages.append(message) + self._stateMonitor.add_message(message) + + def _estimateTotalPrintTime(self, progress, printTime): + if not progress or not printTime or not self._timeEstimationData: + return None + + else: + newEstimate = printTime / progress + self._timeEstimationData.update(newEstimate) + + result = None + if self._timeEstimationData.is_stable(): + result = self._timeEstimationData.average_total_rolling + + return result + + def _setProgressData(self, progress, filepos, printTime, cleanedPrintTime): + estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime) + totalPrintTime = estimatedTotalPrintTime + + if self._selectedFile and "estimatedPrintTime" in self._selectedFile and self._selectedFile["estimatedPrintTime"]: + statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"] + if progress and cleanedPrintTime: + if estimatedTotalPrintTime is None: + totalPrintTime = statisticalTotalPrintTime + else: + if progress < 0.5: + sub_progress = progress * 2 + else: + sub_progress = 1.0 + totalPrintTime = (1 - sub_progress) * statisticalTotalPrintTime + sub_progress * estimatedTotalPrintTime + + self._progress = progress + self._printTime = printTime + self._printTimeLeft = totalPrintTime - cleanedPrintTime if (totalPrintTime is not None and cleanedPrintTime is not None) else None + + self._stateMonitor.set_progress({ + "completion": self._progress * 100 if self._progress is not None else None, + "filepos": filepos, + "printTime": int(self._printTime) if self._printTime is not None else None, + "printTimeLeft": int(self._printTimeLeft) if self._printTimeLeft is not None else None + }) + + if progress: + progress_int = int(progress * 100) + if self._lastProgressReport != progress_int: + self._lastProgressReport = progress_int + self._reportPrintProgressToPlugins(progress_int) + + + def _addTemperatureData(self, temp, bedTemp): + currentTimeUtc = int(time.time()) + + data = { + "time": currentTimeUtc + } + for tool in temp.keys(): + data["tool%d" % tool] = { + "actual": temp[tool][0], + "target": temp[tool][1] + } + if bedTemp is not None and isinstance(bedTemp, tuple): + data["bed"] = { + "actual": bedTemp[0], + "target": bedTemp[1] + } + + self._temps.append(data) + + self._temp = temp + self._bedTemp = bedTemp + + self._stateMonitor.add_temperature(data) + + def _setJobData(self, filename, filesize, sd): + if filename is not None: + if sd: + path_in_storage = filename + path_on_disk = None + else: + path_in_storage = self._fileManager.path_in_storage(FileDestinations.LOCAL, filename) + path_on_disk = self._fileManager.path_on_disk(FileDestinations.LOCAL, filename) + self._selectedFile = { + "filename": path_in_storage, + "filesize": filesize, + "sd": sd, + "estimatedPrintTime": None + } + else: + self._selectedFile = None + self._stateMonitor.set_job_data({ + "file": { + "name": None, + "origin": None, + "size": None, + "date": None + }, + "estimatedPrintTime": None, + "averagePrintTime": None, + "lastPrintTime": None, + "filament": None, + }) + return + + estimatedPrintTime = None + lastPrintTime = None + averagePrintTime = None + date = None + filament = None + if path_on_disk: + # Use a string for mtime because it could be float and the + # javascript needs to exact match + if not sd: + date = int(os.stat(path_on_disk).st_ctime) + + try: + fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, path_on_disk) + except: + fileData = None + if fileData is not None: + if "analysis" in fileData: + if estimatedPrintTime is None and "estimatedPrintTime" in fileData["analysis"]: + estimatedPrintTime = fileData["analysis"]["estimatedPrintTime"] + if "filament" in fileData["analysis"].keys(): + filament = fileData["analysis"]["filament"] + if "statistics" in fileData: + printer_profile = self._printerProfileManager.get_current_or_default()["id"] + if "averagePrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["averagePrintTime"]: + averagePrintTime = fileData["statistics"]["averagePrintTime"][printer_profile] + if "lastPrintTime" in fileData["statistics"] and printer_profile in fileData["statistics"]["lastPrintTime"]: + lastPrintTime = fileData["statistics"]["lastPrintTime"][printer_profile] + + if averagePrintTime is not None: + self._selectedFile["estimatedPrintTime"] = averagePrintTime + elif estimatedPrintTime is not None: + # TODO apply factor which first needs to be tracked! + self._selectedFile["estimatedPrintTime"] = estimatedPrintTime + + self._stateMonitor.set_job_data({ + "file": { + "name": path_in_storage, + "origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL, + "size": filesize, + "date": date + }, + "estimatedPrintTime": estimatedPrintTime, + "averagePrintTime": averagePrintTime, + "lastPrintTime": lastPrintTime, + "filament": filament, + }) + + def _sendInitialStateUpdate(self, callback): + try: + data = self._stateMonitor.get_current_data() + data.update({ + "temps": list(self._temps), + "logs": list(self._log), + "messages": list(self._messages) + }) + callback.on_printer_send_initial_data(data) + except Exception, err: + import sys + sys.stderr.write("ERROR: %s\n" % str(err)) + pass + + def _getStateFlags(self): + return { + "operational": self.is_operational(), + "printing": self.is_printing(), + "closedOrError": self.is_closed_or_error(), + "error": self.is_error(), + "paused": self.is_paused(), + "ready": self.is_ready(), + "sdReady": self.is_sd_ready() + } + + #~~ comm.MachineComPrintCallback implementation + + def on_comm_log(self, message): + """ + Callback method for the comm object, called upon log output. + """ + self._addLog(message) + + def on_comm_temperature_update(self, temp, bedTemp): + self._addTemperatureData(temp, bedTemp) + + def on_comm_state_change(self, state): + """ + Callback method for the comm object, called if the connection state changes. + """ + oldState = self._state + + # forward relevant state changes to gcode manager + if self._comm is not None and oldState == self._comm.STATE_PRINTING: + if self._selectedFile is not None: + if state == self._comm.STATE_OPERATIONAL: + self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), True, self._printerProfileManager.get_current_or_default()["id"]) + elif state == self._comm.STATE_CLOSED or state == self._comm.STATE_ERROR or state == self._comm.STATE_CLOSED_WITH_ERROR: + self._fileManager.log_print(FileDestinations.SDCARD if self._selectedFile["sd"] else FileDestinations.LOCAL, self._selectedFile["filename"], time.time(), self._comm.getPrintTime(), False, self._printerProfileManager.get_current_or_default()["id"]) + self._analysisQueue.resume() # printing done, put those cpu cycles to good use + elif self._comm is not None and state == self._comm.STATE_PRINTING: + self._analysisQueue.pause() # do not analyse files while printing + + self._setState(state) + + def on_comm_message(self, message): + """ + Callback method for the comm object, called upon message exchanges via serial. + Stores the message in the message buffer, truncates buffer to the last 300 lines. + """ + self._addMessage(message) + + def on_comm_progress(self): + """ + Callback method for the comm object, called upon any change in progress of the printjob. + Triggers storage of new values for printTime, printTimeLeft and the current progress. + """ + + self._setProgressData(self._comm.getPrintProgress(), self._comm.getPrintFilepos(), self._comm.getPrintTime(), self._comm.getCleanedPrintTime()) + + def on_comm_z_change(self, newZ): + """ + Callback method for the comm object, called upon change of the z-layer. + """ + oldZ = self._currentZ + if newZ != oldZ: + # we have to react to all z-changes, even those that might "go backward" due to a slicer's retraction or + # anti-backlash-routines. Event subscribes should individually take care to filter out "wrong" z-changes + eventManager().fire(Events.Z_CHANGE, {"new": newZ, "old": oldZ}) + + self._setCurrentZ(newZ) + + def on_comm_sd_state_change(self, sdReady): + self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()}) + + def on_comm_sd_files(self, files): + eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"}) + self._sdFilelistAvailable.set() + + def on_comm_file_selected(self, filename, filesize, sd): + self._setJobData(filename, filesize, sd) + self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()}) + + if self._printAfterSelect: + self.start_print() + + def on_comm_print_job_done(self): + self._setProgressData(1.0, self._selectedFile["filesize"], self._comm.getPrintTime(), 0) + self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()}) + + def on_comm_file_transfer_started(self, filename, filesize): + self._sdStreaming = True + + self._setJobData(filename, filesize, True) + self._setProgressData(0.0, 0, 0, None) + self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()}) + + def on_comm_file_transfer_done(self, filename): + self._sdStreaming = False + + if self._streamingFinishedCallback is not None: + # in case of SD files, both filename and absolutePath are the same, so we set the (remote) filename for + # both parameters + self._streamingFinishedCallback(filename, filename, FileDestinations.SDCARD) + + self._setCurrentZ(None) + self._setJobData(None, None, None) + self._setProgressData(None, None, None, None) + self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()}) + + def on_comm_force_disconnect(self): + self.disconnect() + + +class StateMonitor(object): + def __init__(self, interval=0.5, on_update=None, on_add_temperature=None, on_add_log=None, on_add_message=None): + self._interval = interval + self._update_callback = on_update + self._on_add_temperature = on_add_temperature + self._on_add_log = on_add_log + self._on_add_message = on_add_message + + self._state = None + self._job_data = None + self._gcode_data = None + self._sd_upload_data = None + self._current_z = None + self._progress = None + + self._offsets = {} + + self._change_event = threading.Event() + self._state_lock = threading.Lock() + + self._last_update = time.time() + self._worker = threading.Thread(target=self._work) + self._worker.daemon = True + self._worker.start() + + def reset(self, state=None, job_data=None, progress=None, current_z=None): + self.set_state(state) + self.set_job_data(job_data) + self.set_progress(progress) + self.set_current_z(current_z) + + def add_temperature(self, temperature): + self._on_add_temperature(temperature) + self._change_event.set() + + def add_log(self, log): + self._on_add_log(log) + self._change_event.set() + + def add_message(self, message): + self._on_add_message(message) + self._change_event.set() + + def set_current_z(self, current_z): + self._current_z = current_z + self._change_event.set() + + def set_state(self, state): + with self._state_lock: + self._state = state + self._change_event.set() + + def set_job_data(self, job_data): + self._job_data = job_data + self._change_event.set() + + def set_progress(self, progress): + self._progress = progress + self._change_event.set() + + def set_temp_offsets(self, offsets): + self._offsets = offsets + self._change_event.set() + + def _work(self): + while True: + self._change_event.wait() + + with self._state_lock: + now = time.time() + delta = now - self._last_update + additional_wait_time = self._interval - delta + if additional_wait_time > 0: + time.sleep(additional_wait_time) + + data = self.get_current_data() + self._update_callback(data) + self._last_update = time.time() + self._change_event.clear() + + def get_current_data(self): + return { + "state": self._state, + "job": self._job_data, + "currentZ": self._current_z, + "progress": self._progress, + "offsets": self._offsets + } + + diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 1f32ba083..c9a6daec8 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -7,12 +7,13 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import uuid from sockjs.tornado import SockJSRouter -from flask import Flask, render_template, send_from_directory, g, request, make_response +from flask import Flask, render_template, send_from_directory, g, request, make_response, session, url_for from flask.ext.login import LoginManager from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed -from flask.ext.babel import Babel +from flask.ext.babel import Babel, gettext, ngettext from babel import Locale from watchdog.observers import Observer +from collections import defaultdict import os import logging @@ -27,28 +28,37 @@ babel = Babel(app) debug = False printer = None -gcodeManager = None +printerProfileManager = None +fileManager = None +slicingManager = None +analysisQueue = None userManager = None eventManager = None loginManager = None pluginManager = None +appSessionManager = None principals = Principal(app) admin_permission = Permission(RoleNeed("admin")) user_permission = Permission(RoleNeed("user")) # only import the octoprint stuff down here, as it might depend on things defined above to be initialized already -from octoprint.printer import Printer, getConnectionOptions +from octoprint.printer import get_connection_options +from octoprint.printer.profile import PrinterProfileManager +from octoprint.printer.standard import Printer from octoprint.settings import settings -import octoprint.gcodefiles as gcodefiles import octoprint.users as users import octoprint.events as events import octoprint.plugin import octoprint.timelapse import octoprint._version import octoprint.util +import octoprint.filemanager.storage +import octoprint.filemanager.analysis +import octoprint.slicing from . import util +util.tornado.fix_ioloop_scheduling() UI_API_KEY = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes) @@ -81,6 +91,14 @@ LANGUAGES = get_available_locale_identifiers(LOCALES) def before_request(): g.locale = get_locale() +@app.after_request +def after_request(response): + # send no-cache headers with all POST responses + if request.method == "POST": + response.cache_control.no_cache = True + response.headers.add("X-Clacks-Overhead", "GNU Terry Pratchett") + return response + @babel.localeselector def get_locale(): @@ -90,39 +108,321 @@ def get_locale(): @app.route("/") +@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values) def index(): - settings_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin, octoprint.plugin.SettingsPlugin) - settings_plugin_template_vars = dict() - for name, implementation in settings_plugins.items(): - settings_plugin_template_vars[name] = implementation.get_template_vars() + + #~~ a bunch of settings + + enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"]) + enable_timelapse = (settings().get(["webcam", "snapshot"]) and settings().get(["webcam", "ffmpeg"])) + enable_systemmenu = settings().get(["system"]) is not None and settings().get(["system", "actions"]) is not None and len(settings().get(["system", "actions"])) > 0 + enable_accesscontrol = userManager is not None + preferred_stylesheet = settings().get(["devel", "stylesheet"]) + + #~~ prepare assets + + supported_stylesheets = ("css", "less") + assets = dict( + js=[], + stylesheets=[] + ) + assets["js"] = [ + url_for('static', filename='js/app/viewmodels/appearance.js'), + url_for('static', filename='js/app/viewmodels/connection.js'), + url_for('static', filename='js/app/viewmodels/control.js'), + url_for('static', filename='js/app/viewmodels/firstrun.js'), + url_for('static', filename='js/app/viewmodels/files.js'), + url_for('static', filename='js/app/viewmodels/loginstate.js'), + url_for('static', filename='js/app/viewmodels/navigation.js'), + url_for('static', filename='js/app/viewmodels/printerstate.js'), + url_for('static', filename='js/app/viewmodels/printerprofiles.js'), + url_for('static', filename='js/app/viewmodels/settings.js'), + url_for('static', filename='js/app/viewmodels/slicing.js'), + url_for('static', filename='js/app/viewmodels/temperature.js'), + url_for('static', filename='js/app/viewmodels/terminal.js'), + url_for('static', filename='js/app/viewmodels/users.js'), + url_for('static', filename='js/app/viewmodels/log.js') + ] + if enable_gcodeviewer: + assets["js"] += [ + url_for('static', filename='js/app/viewmodels/gcode.js'), + url_for('static', filename='gcodeviewer/js/ui.js'), + url_for('static', filename='gcodeviewer/js/gCodeReader.js'), + url_for('static', filename='gcodeviewer/js/renderer.js') + ] + if enable_timelapse: + assets["js"].append(url_for('static', filename='js/app/viewmodels/timelapse.js')) + + if preferred_stylesheet == "less": + assets["stylesheets"].append(("less", url_for('static', filename='less/octoprint.less'))) + elif preferred_stylesheet == "css": + assets["stylesheets"].append(("css", url_for('static', filename='css/octoprint.css'))) asset_plugins = pluginManager.get_implementations(octoprint.plugin.AssetPlugin) - asset_plugin_urls = dict() for name, implementation in asset_plugins.items(): - asset_plugin_urls[name] = implementation.get_assets() + all_assets = implementation.get_assets() - return render_template( - "index.jinja2", + if "js" in all_assets: + for asset in all_assets["js"]: + assets["js"].append(url_for('plugin_assets', name=name, filename=asset)) + + if preferred_stylesheet in all_assets: + for asset in all_assets[preferred_stylesheet]: + assets["stylesheets"].append((preferred_stylesheet, url_for('plugin_assets', name=name, filename=asset))) + else: + for stylesheet in supported_stylesheets: + if not stylesheet in all_assets: + continue + + for asset in all_assets[stylesheet]: + assets["stylesheets"].append((stylesheet, url_for('plugin_assets', name=name, filename=asset))) + break + + ##~~ prepare templates + + templates = dict( + navbar=dict(order=[], entries=dict()), + sidebar=dict(order=[], entries=dict()), + tab=dict(order=[], entries=dict()), + settings=dict(order=[], entries=dict()), + generic=dict(order=[], entries=dict()) + ) + + # navbar + + templates["navbar"]["entries"] = dict( + settings=dict(template="navbar/settings.jinja2", _div="navbar_settings", styles=["display: none"], data_bind="visible: loginState.isAdmin") + ) + if enable_accesscontrol: + templates["navbar"]["entries"]["login"] = dict(template="navbar/login.jinja2", _div="navbar_login", classes=["dropdown"], custom_bindings=False) + if enable_systemmenu: + templates["navbar"]["entries"]["systemmenu"] = dict(template="navbar/systemmenu.jinja2", _div="navbar_systemmenu", styles=["display: none"], classes=["dropdown"], data_bind="visible: loginState.isAdmin", custom_bindings=False) + + # sidebar + + templates["sidebar"]["entries"]= dict( + connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none"], data_bind="visible: loginState.isAdmin")), + state=(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-sign")), + files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], header_addon="sidebar/files_header.jinja2")) + ) + + # tabs + + templates["tab"]["entries"] = dict( + temperature=(gettext("Temperature"), dict(template="tabs/temperature.jinja2", _div="temp")), + control=(gettext("Control"), dict(template="tabs/control.jinja2", _div="control")), + terminal=(gettext("Terminal"), dict(template="tabs/terminal.jinja2", _div="term")), + ) + if enable_gcodeviewer: + templates["tab"]["entries"]["gcodeviewer"] = (gettext("GCode Viewer"), dict(template="tabs/gcodeviewer.jinja2", _div="gcode")) + if enable_timelapse: + templates["tab"]["entries"]["timelapse"] = (gettext("Timelapse"), dict(template="tabs/timelapse.jinja2", _div="timelapse")) + + # settings dialog + + templates["settings"]["entries"] = dict( + section_printer=(gettext("Printer"), None), + + serial=(gettext("Serial Connection"), dict(template="dialogs/settings/serialconnection.jinja2", _div="settings_serialConnection", custom_bindings=False)), + printerprofiles=(gettext("Printer Profiles"), dict(template="dialogs/settings/printerprofiles.jinja2", _div="settings_printerProfiles", custom_bindings=False)), + temperatures=(gettext("Temperatures"), dict(template="dialogs/settings/temperatures.jinja2", _div="settings_temperature", custom_bindings=False)), + terminalfilters=(gettext("Terminal Filters"), dict(template="dialogs/settings/terminalfilters.jinja2", _div="settings_terminalFilters", custom_bindings=False)), + gcodescripts=(gettext("GCODE Scripts"), dict(template="dialogs/settings/gcodescripts.jinja2", _div="settings_gcodeScripts", custom_bindings=False)), + + section_features=(gettext("Features"), None), + + features=(gettext("Features"), dict(template="dialogs/settings/features.jinja2", _div="settings_features", custom_bindings=False)), + webcam=(gettext("Webcam"), dict(template="dialogs/settings/webcam.jinja2", _div="settings_webcam", custom_bindings=False)), + api=(gettext("API"), dict(template="dialogs/settings/api.jinja2", _div="settings_api", custom_bindings=False)), + + section_octoprint=(gettext("OctoPrint"), None), + + folders=(gettext("Folders"), dict(template="dialogs/settings/folders.jinja2", _div="settings_folders", custom_bindings=False)), + appearance=(gettext("Appearance"), dict(template="dialogs/settings/appearance.jinja2", _div="settings_appearance", custom_bindings=False)), + logs=(gettext("Logs"), dict(template="dialogs/settings/logs.jinja2", _div="settings_logs")), + ) + if enable_accesscontrol: + templates["settings"]["entries"]["accesscontrol"] = (gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False)) + + # extract data from template plugins + + template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin) + + # rules for transforming template configs to template entries + rules = dict( + navbar=dict(div=lambda x: "navbar_plugin_" + x, template=lambda x: x + "_navbar.jinja2", to_entry=lambda data: data), + sidebar=dict(div=lambda x: "sidebar_plugin_" + x, template=lambda x: x + "_sidebar.jinja2", to_entry=lambda data: (data["name"], data)), + tab=dict(div=lambda x: "tab_plugin_" + x, template=lambda x: x + "_tab.jinja2", to_entry=lambda data: (data["name"], data)), + settings=dict(div=lambda x: "settings_plugin_" + x, template=lambda x: x + "_settings.jinja2", to_entry=lambda data: (data["name"], data)), + generic=dict(template=lambda x: x + ".jinja2", to_entry=lambda data: data) + ) + + plugin_vars = dict() + plugin_names = template_plugins.keys() + for name, implementation in template_plugins.items(): + vars = implementation.get_template_vars() + if not isinstance(vars, dict): + vars = dict() + + for var_name, var_value in vars.items(): + plugin_vars["plugin_" + name + "_" + var_name] = var_value + + configs = implementation.get_template_configs() + if not isinstance(configs, (list, tuple)): + configs = [] + + includes = _process_template_configs(name, implementation, configs, rules) + + for t in ("navbar", "sidebar", "tab", "settings", "generic"): + for include in includes[t]: + if t == "navbar" or t == "generic": + data = include + else: + data = include[1] + + suffix = data["suffix"] if "suffix" in data else "" + key = "plugin_" + name + suffix + if "replaces" in data: + key = data["replaces"] + templates[t]["entries"][key] = include + + #~~ order internal templates and plugins + + # make sure that + # 1) we only have keys in our ordered list that we have entries for and + # 2) we have all entries located somewhere within the order + + for t in ("navbar", "sidebar", "tab", "settings", "generic"): + configured_order = settings().get(["appearance", "components", "order", t], merged=True) + configured_disabled = settings().get(["appearance", "components", "disabled", t]) + templates[t]["order"] = [x for x in configured_order if x in templates[t]["entries"] and not x in configured_disabled] + + all_ordered = set(templates[t]["order"]) + all_disabled = set(configured_disabled) + + missing_in_order = set(templates[t]["entries"].keys()).difference(all_ordered).difference(all_disabled) + if len(missing_in_order) == 0: + continue + + sorted_missing = list(missing_in_order) + if not t == "navbar" and not t == "generic": + sorted_missing = sorted(missing_in_order, key=lambda x: templates[t]["entries"][x][0]) + if t == "navbar": + templates[t]["order"] = sorted_missing + templates[t]["order"] + elif t == "sidebar" or t == "tab" or t == "generic": + templates[t]["order"] += sorted_missing + elif t == "settings": + templates[t]["entries"]["section_plugins"] = (gettext("Plugins"), None) + templates[t]["order"] += ["section_plugins"] + sorted_missing + + #~~ prepare full set of template vars for rendering + + render_kwargs = dict( webcamStream=settings().get(["webcam", "stream"]), - enableTimelapse=(settings().get(["webcam", "snapshot"]) is not None and settings().get(["webcam", "ffmpeg"]) is not None), - enableGCodeVisualizer=settings().get(["gcodeViewer", "enabled"]), enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]), - enableSystemMenu=settings().get(["system"]) is not None and settings().get(["system", "actions"]) is not None and len(settings().get(["system", "actions"])) > 0, enableAccessControl=userManager is not None, enableSdSupport=settings().get(["feature", "sdSupport"]), firstRun=settings().getBoolean(["server", "firstRun"]) and (userManager is None or not userManager.hasBeenCustomized()), debug=debug, version=VERSION, display_version=DISPLAY_VERSION, - stylesheet=settings().get(["devel", "stylesheet"]), gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]), gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"]), uiApiKey=UI_API_KEY, - settingsPlugins=settings_plugin_template_vars, - assetPlugins=asset_plugin_urls + templates=templates, + assets=assets, + pluginNames=plugin_names + ) + render_kwargs.update(plugin_vars) + + #~~ render! + + return render_template( + "index.jinja2", + **render_kwargs ) +def _process_template_configs(name, implementation, configs, rules): + from jinja2.exceptions import TemplateNotFound + + counters = dict( + navbar=1, + sidebar=1, + tab=1, + settings=1, + generic=1 + ) + includes = defaultdict(list) + + for config in configs: + if not isinstance(config, dict): + continue + if not "type" in config: + continue + + template_type = config["type"] + del config["type"] + + if not template_type in rules: + continue + rule = rules[template_type] + + data = _process_template_config(name, implementation, rule, config=config, counter=counters[template_type]) + if data is None: + continue + + includes[template_type].append(rule["to_entry"](data)) + counters[template_type] += 1 + + for template_type in rules: + if len(includes[template_type]) == 0: + # if no template of that type was added by the config, we'll try to use the default template name + rule = rules[template_type] + data = _process_template_config(name, implementation, rule) + if data is not None: + try: + app.jinja_env.get_or_select_template(data["template"]) + except TemplateNotFound: + pass + else: + includes[template_type].append(rule["to_entry"](data)) + + return includes + +def _process_template_config(name, implementation, rule, config=None, counter=1): + if "mandatory" in rule: + for mandatory in rule["mandatory"]: + if not mandatory in config: + return None + + if config is None: + config = dict() + data = dict(config) + + if "div" in data: + data["_div"] = data["div"] + elif "div" in rule: + data["_div"] = rule["div"](name) + if "suffix" in data: + data["_div"] += "_" + data["suffix"] + elif counter > 1: + data["_div"] += "_%d" % counter + data["suffix"] = "_%d" % counter + else: + data["suffix"] = "" + if not "template" in data: + data["template"] = rule["template"](name) + if not "name" in data: + data["name"] = implementation._plugin_name + if not "custom_bindings" in data or data["custom_bindings"]: + data_bind = "allowBindings: true" + if "data_bind" in data: + data_bind = data_bind + ", " + data["data_bind"] + data["data_bind"] = data_bind + + return data + @app.route("/robots.txt") def robotsTxt(): return send_from_directory(app.static_folder, "robots.txt") @@ -133,11 +433,11 @@ def plugin_assets(name, filename): asset_plugins = pluginManager.get_implementations(octoprint.plugin.AssetPlugin) if not name in asset_plugins: - return make_response(404) + return make_response("Asset not found", 404) asset_plugin = asset_plugins[name] asset_folder = asset_plugin.get_asset_folder() if asset_folder is None: - make_response(404) + return make_response("Asset not found", 404) return send_from_directory(asset_folder, filename) @@ -156,8 +456,19 @@ def on_identity_loaded(sender, identity): def load_user(id): + if id == "_api": + return users.ApiUser() + + if session and "usersession.id" in session: + sessionid = session["usersession.id"] + else: + sessionid = None + if userManager is not None: - return userManager.findUser(id) + if sessionid: + return userManager.findUser(username=id, session=sessionid) + else: + return userManager.findUser(username=id) return users.DummyUser() @@ -180,32 +491,81 @@ class Server(): self._checkForRoot() global printer - global gcodeManager + global printerProfileManager + global fileManager + global slicingManager + global analysisQueue global userManager global eventManager global loginManager global pluginManager + global appSessionManager global debug from tornado.ioloop import IOLoop from tornado.web import Application + import sys + debug = self._debug # first initialize the settings singleton and make sure it uses given configfile and basedir if available - self._initSettings(self._configfile, self._basedir) + settings(init=True, basedir=self._basedir, configfile=self._configfile) # then initialize logging self._initLogging(self._debug, self._logConf) logger = logging.getLogger(__name__) - + def exception_logger(exc_type, exc_value, exc_tb): + logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb)) + sys.excepthook = exception_logger logger.info("Starting OctoPrint %s" % DISPLAY_VERSION) - eventManager = events.eventManager() - gcodeManager = gcodefiles.GcodeManager() - printer = Printer(gcodeManager) + # then initialize the plugin manager pluginManager = octoprint.plugin.plugin_manager(init=True) + printerProfileManager = PrinterProfileManager() + eventManager = events.eventManager() + analysisQueue = octoprint.filemanager.analysis.AnalysisQueue() + slicingManager = octoprint.slicing.SlicingManager(settings().getBaseFolder("slicingProfiles"), printerProfileManager) + storage_managers = dict() + storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(settings().getBaseFolder("uploads")) + fileManager = octoprint.filemanager.FileManager(analysisQueue, slicingManager, printerProfileManager, initial_storage_managers=storage_managers) + printer = Printer(fileManager, analysisQueue, printerProfileManager) + appSessionManager = util.flask.AppSessionManager() + + def octoprint_plugin_inject_factory(name, implementation): + if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin): + return None + return dict( + plugin_manager=pluginManager, + printer_profile_manager=printerProfileManager, + event_bus=eventManager, + analysis_queue=analysisQueue, + slicing_manager=slicingManager, + file_manager=fileManager, + printer=printer, + app_session_manager=appSessionManager + ) + + def settings_plugin_inject_factory(name, implementation): + if not isinstance(implementation, octoprint.plugin.SettingsPlugin): + return None + default_settings = implementation.get_settings_defaults() + get_preprocessors, set_preprocessors = implementation.get_settings_preprocessors() + plugin_settings = octoprint.plugin.plugin_settings(name, + defaults=default_settings, + get_preprocessors=get_preprocessors, + set_preprocessors=set_preprocessors) + return dict(settings=plugin_settings) + + pluginManager.initialize_implementations( + additional_inject_factories=[ + octoprint_plugin_inject_factory, + settings_plugin_inject_factory + ] + ) + slicingManager.initialize() + # configure additional template folders for jinja2 template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin) additional_template_folders = [] @@ -221,6 +581,7 @@ class Server(): ]) app.jinja_loader = jinja_loader del jinja2 + app.jinja_env.add_extension("jinja2.ext.do") # configure timelapse octoprint.timelapse.configureTimelapse() @@ -233,7 +594,7 @@ class Server(): if settings().getBoolean(["accessControl", "enabled"]): userManagerName = settings().get(["accessControl", "userManager"]) try: - clazz = octoprint.util.getClass(userManagerName) + clazz = octoprint.util.get_class(userManagerName) userManager = clazz() except AttributeError, e: logger.exception("Could not instantiate user manager %s, will run with accessControl disabled!" % userManagerName) @@ -242,11 +603,21 @@ class Server(): app.wsgi_app, settings().get(["server", "reverseProxy", "prefixHeader"]), settings().get(["server", "reverseProxy", "schemeHeader"]), + settings().get(["server", "reverseProxy", "hostHeader"]), settings().get(["server", "reverseProxy", "prefixFallback"]), - settings().get(["server", "reverseProxy", "prefixScheme"]) + settings().get(["server", "reverseProxy", "schemeFallback"]), + settings().get(["server", "reverseProxy", "hostFallback"]) ) - app.secret_key = "k3PuVYgtxNm8DXKKTw2nWmFQQun9qceV" + secret_key = settings().get(["server", "secretKey"]) + if not secret_key: + import string + from random import choice + chars = string.ascii_lowercase + string.ascii_uppercase + string.digits + secret_key = "".join(choice(chars) for _ in xrange(32)) + settings().set(["server", "secretKey"], secret_key) + settings().save() + app.secret_key = secret_key loginManager = LoginManager() loginManager.session_protection = "strong" loginManager.user_callback = load_user @@ -263,21 +634,39 @@ class Server(): app.debug = self._debug from octoprint.server.api import api + from octoprint.server.apps import apps # register API blueprint app.register_blueprint(api, url_prefix="/api") + app.register_blueprint(apps, url_prefix="/apps") # also register any blueprints defined in BlueprintPlugins - octoprint.plugin.call_plugin(octoprint.plugin.types.BlueprintPlugin, - "get_blueprint", - callback=lambda name, _, blueprint: app.register_blueprint(blueprint, url_prefix="/plugin/{name}".format(name=name))) + blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.BlueprintPlugin) + for name, plugin in blueprint_plugins.items(): + blueprint = plugin.get_blueprint() + if blueprint is None: + continue + + if plugin.is_blueprint_protected(): + from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler + blueprint.before_request(apiKeyRequestHandler) + blueprint.after_request(corsResponseHandler) + + url_prefix = "/plugin/{name}".format(name=name) + app.register_blueprint(blueprint, url_prefix=url_prefix) + logger.debug("Registered API of plugin {name} under URL prefix {url_prefix}".format(name=name, url_prefix=url_prefix)) + + ## Tornado initialization starts here + + ioloop = IOLoop() + ioloop.install() self._router = SockJSRouter(self._createSocketConnection, "/sockjs") upload_suffixes = dict(name=settings().get(["server", "uploads", "nameSuffix"]), path=settings().get(["server", "uploads", "pathSuffix"])) self._tornado_app = Application(self._router.urls + [ (r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("timelapse"), as_attachment=True)), - (r"/downloads/files/local/([^/]*\.(gco|gcode))", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("uploads"), as_attachment=True)), + (r"/downloads/files/local/([^/]*\.(gco|gcode|g|stl))", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("uploads"), as_attachment=True)), (r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, dict(path=settings().getBaseFolder("logs"), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.admin_validator))), (r"/downloads/camera/current", util.tornado.UrlForwardHandler, dict(url=settings().get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))), (r".*", util.tornado.UploadStorageFallbackHandler, dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app), file_prefix="octoprint-file-upload-", file_suffix=".tmp", suffixes=upload_suffixes)) @@ -291,18 +680,16 @@ class Server(): eventManager.fire(events.Events.STARTUP) if settings().getBoolean(["serial", "autoconnect"]): (port, baudrate) = settings().get(["serial", "port"]), settings().getInt(["serial", "baudrate"]) - connectionOptions = getConnectionOptions() + printer_profile = printerProfileManager.get_default() + connectionOptions = get_connection_options() if port in connectionOptions["ports"]: - printer.connect(port, baudrate) + printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default") # start up watchdogs observer = Observer() - observer.schedule(util.watchdog.GcodeWatchdogHandler(gcodeManager, printer), settings().getBaseFolder("watched")) - observer.schedule(util.watchdog.UploadCleanupWatchdogHandler(gcodeManager), settings().getBaseFolder("uploads")) + observer.schedule(util.watchdog.GcodeWatchdogHandler(fileManager, printer), settings().getBaseFolder("watched")) observer.start() - ioloop = IOLoop.instance() - # run our startup plugins octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin, "on_startup", @@ -342,16 +729,13 @@ class Server(): logger.exception("Stacktrace follows:") def _createSocketConnection(self, session): - global printer, gcodeManager, userManager, eventManager - return util.sockjs.PrinterStateConnection(printer, gcodeManager, userManager, eventManager, session) + global printer, fileManager, analysisQueue, userManager, eventManager + return util.sockjs.PrinterStateConnection(printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session) def _checkForRoot(self): if "geteuid" in dir(os) and os.geteuid() == 0: exit("You should not run OctoPrint as root!") - def _initSettings(self, configfile, basedir): - settings(init=True, basedir=basedir, configfile=configfile) - def _initLogging(self, debug, logConf=None): defaultConfig = { "version": 1, @@ -388,6 +772,9 @@ class Server(): "level": "CRITICAL", "handlers": ["serialFile"], "propagate": False + }, + "tornado.application": { + "level": "ERROR" } }, "root": { @@ -400,7 +787,7 @@ class Server(): defaultConfig["root"]["level"] = "DEBUG" if logConf is None: - logConf = os.path.join(settings().settings_dir, "logging.yaml") + logConf = os.path.join(settings().getBaseFolder("base"), "logging.yaml") configFromFile = {} if os.path.exists(logConf) and os.path.isfile(logConf): @@ -410,6 +797,10 @@ class Server(): config = octoprint.util.dict_merge(defaultConfig, configFromFile) logging.config.dictConfig(config) + logging.captureWarnings(True) + + import warnings + warnings.simplefilter("always") if settings().getBoolean(["serial", "log"]): # enable debug logging to serial.log diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index a8c98cad7..5c4a1fc9f 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -17,10 +17,10 @@ import octoprint.util as util import octoprint.users import octoprint.server import octoprint.plugin -from octoprint.server import admin_permission, NO_CONTENT, UI_API_KEY +from octoprint.server import admin_permission, NO_CONTENT from octoprint.settings import settings as s, valid_boolean_trues -from octoprint.server.util import get_api_key, get_user_for_apikey -from octoprint.server.util.flask import restricted_access +from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler +from octoprint.server.util.flask import restricted_access, get_remote_address, get_json_command_from_request #~~ init api blueprint, including sub modules @@ -35,78 +35,14 @@ from . import settings as api_settings from . import timelapse as api_timelapse from . import users as api_users from . import log as api_logs +from . import slicing as api_slicing +from . import printer_profiles as api_printer_profiles VERSION = "0.1" - -def optionsAllowOrigin(request): - """ Always reply 200 on OPTIONS request """ - - resp = current_app.make_default_options_response() - - # Allow the origin which made the XHR - resp.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] - # Allow the actual method - resp.headers['Access-Control-Allow-Methods'] = request.headers['Access-Control-Request-Method'] - # Allow for 10 seconds - resp.headers['Access-Control-Max-Age'] = "10" - - # 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key) - customRequestHeaders = request.headers.get('Access-Control-Request-Headers', None) - if customRequestHeaders is not None: - # If present => allow them all - resp.headers['Access-Control-Allow-Headers'] = customRequestHeaders - - return resp - -@api.before_request -def beforeApiRequests(): - """ - All requests in this blueprint need to be made supplying an API key. This may be the UI_API_KEY, in which case - the underlying request processing will directly take place, or it may be the global or a user specific case. In any - case it has to be present and must be valid, so anything other than the above three types will result in denying - the request. - """ - - if request.method == 'OPTIONS' and s().getBoolean(["api", "allowCrossOrigin"]): - return optionsAllowOrigin(request) - - apikey = get_api_key(request) - if apikey is None: - # no api key => 401 - return make_response("No API key provided", 401) - - if apikey == UI_API_KEY: - # ui api key => continue regular request processing - return - - if not s().get(["api", "enabled"]): - # api disabled => 401 - return make_response("API disabled", 401) - - if apikey == s().get(["api", "key"]): - # global api key => continue regular request processing - return - - user = get_user_for_apikey(apikey) - if user is not None: - # user specific api key => continue regular request processing - return - - # invalid api key => 401 - return make_response("Invalid API key", 401) - -@api.after_request -def afterApiRequests(resp): - - # Allow crossdomain - allowCrossOrigin = s().getBoolean(["api", "allowCrossOrigin"]) - if request.method != 'OPTIONS' and 'Origin' in request.headers and allowCrossOrigin: - resp.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] - - return resp - +api.before_request(apiKeyRequestHandler) +api.after_request(corsResponseHandler) #~~ data from plugins @@ -137,7 +73,7 @@ def pluginCommand(name): if valid_commands is None: return make_response("Method not allowed", 405) - command, data, response = util.getJsonCommandFromRequest(request, valid_commands) + command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response @@ -181,14 +117,6 @@ def apiPrinterState(): return make_response(("/api/state has been deprecated, use /api/printer instead", 405, [])) -@api.route("/version", methods=["GET"]) -@restricted_access -def apiVersion(): - return jsonify({ - "server": octoprint.server.VERSION, - "api": octoprint.server.api.VERSION - }) - @api.route("/version", methods=["GET"]) @restricted_access def apiVersion(): @@ -243,15 +171,26 @@ def login(): else: remember = False + if "usersession.id" in session: + _logout(current_user) + user = octoprint.server.userManager.findUser(username) if user is not None: - if user.check_password(octoprint.users.UserManager.createPasswordHash(password)): + if octoprint.server.userManager.checkPassword(username, password): + if octoprint.server.userManager is not None: + user = octoprint.server.userManager.login_user(user) + session["usersession.id"] = user.get_session() login_user(user, remember=remember) identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id())) return jsonify(user.asDict()) return make_response(("User unknown or password incorrect", 401, [])) + elif "passive" in request.values.keys(): - user = current_user + if octoprint.server.userManager is not None: + user = octoprint.server.userManager.login_user(current_user) + else: + user = current_user + if user is not None and not user.is_anonymous(): identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id())) return jsonify(user.asDict()) @@ -265,7 +204,7 @@ def login(): localNetworks.add(ip) try: - remoteAddr = util.getRemoteAddress(request) + remoteAddr = get_remote_address(request) if netaddr.IPAddress(remoteAddr) in localNetworks: user = octoprint.server.userManager.findUser(autologinAs) if user is not None: @@ -287,7 +226,12 @@ def logout(): del session[key] identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity()) + _logout(current_user) logout_user() return NO_CONTENT +def _logout(user): + if "usersession.id" in session: + del session["usersession.id"] + octoprint.server.userManager.logout_user(user) diff --git a/src/octoprint/server/api/connection.py b/src/octoprint/server/api/connection.py index f947e8601..7f858c7d1 100644 --- a/src/octoprint/server/api/connection.py +++ b/src/octoprint/server/api/connection.py @@ -8,59 +8,81 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms from flask import request, jsonify, make_response from octoprint.settings import settings -from octoprint.printer import getConnectionOptions -from octoprint.server import printer, NO_CONTENT +from octoprint.printer import get_connection_options +from octoprint.server import printer, printerProfileManager, NO_CONTENT from octoprint.server.api import api -from octoprint.server.util.flask import restricted_access +from octoprint.server.util.flask import restricted_access, get_json_command_from_request import octoprint.util as util @api.route("/connection", methods=["GET"]) def connectionState(): - state, port, baudrate = printer.getCurrentConnection() + state, port, baudrate, printer_profile = printer.get_current_connection() current = { "state": state, "port": port, - "baudrate": baudrate + "baudrate": baudrate, + "printerProfile": printer_profile["id"] if printer_profile is not None and "id" in printer_profile else "_default" } - return jsonify({"current": current, "options": getConnectionOptions()}) + + return jsonify({"current": current, "options": _get_options()}) @api.route("/connection", methods=["POST"]) @restricted_access def connectionCommand(): valid_commands = { - "connect": ["autoconnect"], + "connect": [], "disconnect": [] } - command, data, response = util.getJsonCommandFromRequest(request, valid_commands) + command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response if command == "connect": - options = getConnectionOptions() + connection_options = get_connection_options() port = None baudrate = None + printerProfile = None if "port" in data.keys(): port = data["port"] - if port not in options["ports"]: + if port not in connection_options["ports"]: return make_response("Invalid port: %s" % port, 400) if "baudrate" in data.keys(): baudrate = data["baudrate"] - if baudrate not in options["baudrates"]: + if baudrate not in connection_options["baudrates"]: return make_response("Invalid baudrate: %d" % baudrate, 400) + if "printerProfile" in data.keys(): + printerProfile = data["printerProfile"] + if not printerProfileManager.exists(printerProfile): + return make_response("Invalid printer profile: %s" % printerProfile, 400) if "save" in data.keys() and data["save"]: settings().set(["serial", "port"], port) settings().setInt(["serial", "baudrate"], baudrate) + printerProfileManager.set_default(printerProfile) if "autoconnect" in data.keys(): settings().setBoolean(["serial", "autoconnect"], data["autoconnect"]) settings().save() - printer.connect(port=port, baudrate=baudrate) + printer.connect(port=port, baudrate=baudrate, profile=printerProfile) elif command == "disconnect": printer.disconnect() return NO_CONTENT +def _get_options(): + connection_options = get_connection_options() + profile_options = printerProfileManager.get_all() + default_profile = printerProfileManager.get_default() + options = dict( + ports=connection_options["ports"], + baudrates=connection_options["baudrates"], + printerProfiles=[dict(id=printer_profile["id"], name=printer_profile["name"] if "name" in printer_profile else printer_profile["id"]) for printer_profile in profile_options.values() if "id" in printer_profile], + portPreference=connection_options["portPreference"], + baudratePreference=connection_options["baudratePreference"], + printerProfilePreference=default_profile["id"] if "id" in default_profile else None + ) + + return options \ No newline at end of file diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index 8f0dd0622..0f6d292d3 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -7,14 +7,14 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms from flask import request, jsonify, make_response, url_for -import octoprint.gcodefiles as gcodefiles import octoprint.util as util from octoprint.filemanager.destinations import FileDestinations from octoprint.settings import settings, valid_boolean_trues -from octoprint.server import printer, gcodeManager, eventManager, NO_CONTENT -from octoprint.server.util.flask import restricted_access +from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT +from octoprint.server.util.flask import restricted_access, get_json_command_from_request from octoprint.server.api import api from octoprint.events import Events +import octoprint.filemanager #~~ GCODE file handling @@ -22,9 +22,12 @@ from octoprint.events import Events @api.route("/files", methods=["GET"]) def readGcodeFiles(): - files = _getFileList(FileDestinations.LOCAL) + filter = None + if "filter" in request.values: + filter = request.values["filter"] + files = _getFileList(FileDestinations.LOCAL, filter=filter) files.extend(_getFileList(FileDestinations.SDCARD)) - return jsonify(files=files, free=util.getFreeBytes(settings().getBaseFolder("uploads"))) + return jsonify(files=files, free=util.get_free_bytes(settings().getBaseFolder("uploads"))) @api.route("/files/", methods=["GET"]) @@ -35,7 +38,7 @@ def readGcodeFilesForOrigin(origin): files = _getFileList(origin) if origin == FileDestinations.LOCAL: - return jsonify(files=files, free=util.getFreeBytes(settings().getBaseFolder("uploads"))) + return jsonify(files=files, free=util.get_free_bytes(settings().getBaseFolder("uploads"))) else: return jsonify(files=files) @@ -48,14 +51,15 @@ def _getFileDetails(origin, filename): return None -def _getFileList(origin): +def _getFileList(origin, filter=None): if origin == FileDestinations.SDCARD: - sdFileList = printer.getSdFiles() + sdFileList = printer.get_sd_files() files = [] if sdFileList is not None: for sdFile, sdSize in sdFileList: file = { + "type": "machinecode", "name": sdFile, "origin": FileDestinations.SDCARD, "refs": { @@ -66,8 +70,42 @@ def _getFileList(origin): file.update({"size": sdSize}) files.append(file) else: - files = gcodeManager.getAllFileData() + filter_func = None + if filter: + filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type(entry, type=filter) + files = fileManager.list_files(origin, filter=filter_func, recursive=False)[origin].values() for file in files: + file["origin"] = FileDestinations.LOCAL + + if "analysis" in file and octoprint.filemanager.valid_file_type(file["name"], type="gcode"): + file["gcodeAnalysis"] = file["analysis"] + del file["analysis"] + + if "history" in file and octoprint.filemanager.valid_file_type(file["name"], type="gcode"): + # convert print log + history = file["history"] + del file["history"] + success = 0 + failure = 0 + last = None + for entry in history: + success += 1 if "success" in entry and entry["success"] else 0 + failure += 1 if "success" in entry and not entry["success"] else 0 + if not last or ("timestamp" in entry and "timestamp" in last and entry["timestamp"] > last["timestamp"]): + last = entry + if last: + prints = dict( + success=success, + failure=failure, + last=dict( + success=last["success"], + date=last["timestamp"] + ) + ) + if "printTime" in last: + prints["last"]["printTime"] = last["printTime"] + file["prints"] = prints + file.update({ "refs": { "resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=file["name"], _external=True), @@ -79,11 +117,9 @@ def _getFileList(origin): def _verifyFileExists(origin, filename): if origin == FileDestinations.SDCARD: - availableFiles = map(lambda x: x[0], printer.getSdFiles()) + return filename in map(lambda x: x[0], printer.get_sd_files()) else: - availableFiles = gcodeManager.getAllFilenames() - - return filename in availableFiles + return fileManager.file_exists(origin, filename) @api.route("/files/", methods=["POST"]) @@ -114,15 +150,15 @@ def uploadGcodeFile(target): if sd: # validate that all preconditions for SD upload are met before attempting it - if not (printer.isOperational() and not (printer.isPrinting() or printer.isPaused())): + if not (printer.is_operational() and not (printer.is_printing() or printer.is_paused())): return make_response("Can not upload to SD card, printer is either not operational or already busy", 409) - if not printer.isSdReady(): + if not printer.is_sd_ready(): return make_response("Can not upload to SD card, not yet initialized", 409) # determine current job currentFilename = None currentOrigin = None - currentJob = printer.getCurrentJob() + currentJob = printer.get_current_job() if currentJob is not None and "file" in currentJob.keys(): currentJobFile = currentJob["file"] if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys(): @@ -130,12 +166,15 @@ def uploadGcodeFile(target): currentOrigin = currentJobFile["origin"] # determine future filename of file to be uploaded, abort if it can't be uploaded - futureFilename = gcodeManager.getFutureFilename(upload) - if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not gcodefiles.isGcodeFileName(futureFilename)): + try: + futureFilename = fileManager.sanitize_name(FileDestinations.LOCAL, upload.filename) + except: + futureFilename = None + if futureFilename is None: return make_response("Can not upload file %s, wrong format?" % upload.filename, 415) # prohibit overwriting currently selected file while it's being printed - if futureFilename == currentFilename and target == currentOrigin and printer.isPrinting() or printer.isPaused(): + if futureFilename == currentFilename and target == currentOrigin and printer.is_printing() or printer.is_paused(): return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 409) def fileProcessingFinished(filename, absFilename, destination): @@ -145,8 +184,9 @@ def uploadGcodeFile(target): Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint. """ - if destination == FileDestinations.SDCARD: - return filename, printer.addSdFile(filename, absFilename, selectAndOrPrint) + + if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "gcode"): + return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint) else: selectAndOrPrint(filename, absFilename, destination) return filename @@ -160,12 +200,18 @@ def uploadGcodeFile(target): Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the exact file is already selected, such reloading it. """ - if selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination): - printer.selectFile(absFilename, destination == FileDestinations.SDCARD, printAfterSelect) + if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination)): + printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect) - filename, done = gcodeManager.addFile(upload, target, fileProcessingFinished) - if filename is None: + added_file = fileManager.add_file(FileDestinations.LOCAL, upload.filename, upload, allow_overwrite=True) + if added_file is None: return make_response("Could not upload the file %s" % upload.filename, 500) + if octoprint.filemanager.valid_file_type(added_file, "stl"): + filename = added_file + done = True + else: + filename = fileProcessingFinished(added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target) + done = True sdFilename = None if isinstance(filename, tuple): @@ -226,18 +272,19 @@ def gcodeFileCommand(filename, target): # valid file commands, dict mapping command name to mandatory parameters valid_commands = { - "select": [] + "select": [], + "slice": [] } - command, data, response = util.getJsonCommandFromRequest(request, valid_commands) + command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response if command == "select": # selects/loads a file printAfterLoading = False - if "print" in data.keys() and data["print"]: - if not printer.isOperational(): + if "print" in data.keys() and data["print"] in valid_boolean_trues: + if not printer.is_operational(): return make_response("Printer is not operational, cannot directly start printing", 409) printAfterLoading = True @@ -246,8 +293,112 @@ def gcodeFileCommand(filename, target): filenameToSelect = filename sd = True else: - filenameToSelect = gcodeManager.getAbsolutePath(filename) - printer.selectFile(filenameToSelect, sd, printAfterLoading) + filenameToSelect = fileManager.path_on_disk(target, filename) + printer.select_file(filenameToSelect, sd, printAfterLoading) + + elif command == "slice": + if "slicer" in data.keys(): + slicer = data["slicer"] + del data["slicer"] + if not slicer in slicingManager.registered_slicers: + return make_response("Slicer {slicer} is not available".format(**locals()), 400) + slicer_instance = slicingManager.get_slicer(slicer) + elif "cura" in slicingManager.registered_slicers: + slicer = "cura" + slicer_instance = slicingManager.get_slicer("cura") + else: + return make_response("Cannot slice {filename}, no slicer available".format(**locals()), 415) + + if not octoprint.filemanager.valid_file_type(filename, type="stl"): + return make_response("Cannot slice {filename}, not an STL file".format(**locals()), 415) + + if slicer_instance.get_slicer_properties()["same_device"] and (printer.is_printing() or printer.is_paused()): + # slicer runs on same device as OctoPrint, slicing while printing is hence disabled + return make_response("Cannot slice on {slicer} while printing due to performance reasons".format(**locals()), 409) + + if "gcode" in data.keys() and data["gcode"]: + gcode_name = data["gcode"] + del data["gcode"] + else: + import os + name, _ = os.path.splitext(filename) + gcode_name = name + ".gco" + + # prohibit overwriting the file that is currently being printed + currentOrigin, currentFilename = _getCurrentFile() + if currentFilename == gcode_name and currentOrigin == target and (printer.is_printing() or printer.is_paused()): + make_response("Trying to slice into file that is currently being printed: %s" % gcode_name, 409) + + if "profile" in data.keys() and data["profile"]: + profile = data["profile"] + del data["profile"] + else: + profile = None + + if "printerProfile" in data.keys() and data["printerProfile"]: + printerProfile = data["printerProfile"] + del data["printerProfile"] + else: + printerProfile = None + + if "position" in data.keys() and data["position"] and isinstance(data["position"], dict) and "x" in data["position"] and "y" in data["position"]: + position = data["position"] + del data["position"] + else: + position = None + + select_after_slicing = False + if "select" in data.keys() and data["select"] in valid_boolean_trues: + if not printer.is_operational(): + return make_response("Printer is not operational, cannot directly select for printing", 409) + select_after_slicing = True + + print_after_slicing = False + if "print" in data.keys() and data["print"] in valid_boolean_trues: + if not printer.is_operational(): + return make_response("Printer is not operational, cannot directly start printing", 409) + select_after_slicing = print_after_slicing = True + + override_keys = [k for k in data if k.startswith("profile.") and data[k] is not None] + overrides = dict() + for key in override_keys: + overrides[key[len("profile."):]] = data[key] + + def slicing_done(target, gcode_name, select_after_slicing, print_after_slicing): + if select_after_slicing or print_after_slicing: + sd = False + if target == FileDestinations.SDCARD: + filenameToSelect = gcode_name + sd = True + else: + filenameToSelect = fileManager.path_on_disk(target, gcode_name) + printer.select_file(filenameToSelect, sd, print_after_slicing) + + ok, result = fileManager.slice(slicer, target, filename, target, gcode_name, + profile=profile, + printer_profile_id=printerProfile, + position=position, + overrides=overrides, + callback=slicing_done, + callback_args=(target, gcode_name, select_after_slicing, print_after_slicing)) + + if ok: + files = {} + location = url_for(".readGcodeFile", target=target, filename=gcode_name, _external=True) + result = { + "name": gcode_name, + "origin": FileDestinations.LOCAL, + "refs": { + "resource": location, + "download": url_for("index", _external=True) + "downloads/files/" + target + "/" + gcode_name + } + } + + r = make_response(jsonify(result), 202) + r.headers["Location"] = location + return r + else: + return make_response("Could not slice: {result}".format(result=result), 500) return NO_CONTENT @@ -261,28 +412,30 @@ def deleteGcodeFile(filename, target): if not _verifyFileExists(target, filename): return make_response("File not found on '%s': %s" % (target, filename), 404) - sd = target == FileDestinations.SDCARD - - currentJob = printer.getCurrentJob() - currentFilename = None - currentSd = None - if currentJob is not None and "filename" in currentJob.keys() and "sd" in currentJob.keys(): - currentFilename = currentJob["filename"] - currentSd = currentJob["sd"] - - # prohibit deleting the file that is currently being printed - if currentFilename == filename and currentSd == sd and (printer.isPrinting() or printer.isPaused()): + # prohibit deleting files that are currently in use + currentOrigin, currentFilename = _getCurrentFile() + if currentFilename == filename and currentOrigin == target and (printer.is_printing() or printer.is_paused()): make_response("Trying to delete file that is currently being printed: %s" % filename, 409) + if (target, filename) in fileManager.get_busy_files(): + make_response("Trying to delete a file that is currently in use: %s" % filename, 409) + # deselect the file if it's currently selected if currentFilename is not None and filename == currentFilename: - printer.unselectFile() + printer.unselect_file() # delete it - if sd: - printer.deleteSdFile(filename) + if target == FileDestinations.SDCARD: + printer.delete_sd_file(filename) else: - gcodeManager.removeFile(filename) + fileManager.remove_file(target, filename) return NO_CONTENT +def _getCurrentFile(): + currentJob = printer.get_current_job() + if currentJob is not None and "file" in currentJob.keys() and "name" in currentJob["file"] and "origin" in currentJob["file"]: + return currentJob["file"]["origin"], currentJob["file"]["name"] + else: + return None, None + diff --git a/src/octoprint/server/api/job.py b/src/octoprint/server/api/job.py index 84eacd8a9..b2d9b02e1 100644 --- a/src/octoprint/server/api/job.py +++ b/src/octoprint/server/api/job.py @@ -8,7 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms from flask import request, make_response, jsonify from octoprint.server import printer, NO_CONTENT -from octoprint.server.util.flask import restricted_access +from octoprint.server.util.flask import restricted_access, get_json_command_from_request from octoprint.server.api import api import octoprint.util as util @@ -16,7 +16,7 @@ import octoprint.util as util @api.route("/job", methods=["POST"]) @restricted_access def controlJob(): - if not printer.isOperational(): + if not printer.is_operational(): return make_response("Printer is not operational", 409) valid_commands = { @@ -26,34 +26,34 @@ def controlJob(): "cancel": [] } - command, data, response = util.getJsonCommandFromRequest(request, valid_commands) + command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response - activePrintjob = printer.isPrinting() or printer.isPaused() + activePrintjob = printer.is_printing() or printer.is_paused() if command == "start": if activePrintjob: return make_response("Printer already has an active print job, did you mean 'restart'?", 409) - printer.startPrint() + printer.start_print() elif command == "restart": - if not printer.isPaused(): + if not printer.is_paused(): return make_response("Printer does not have an active print job or is not paused", 409) - printer.startPrint() + printer.start_print() elif command == "pause": if not activePrintjob: return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409) - printer.togglePausePrint() + printer.toggle_pause_print() elif command == "cancel": if not activePrintjob: return make_response("Printer is neither printing nor paused, 'cancel' command cannot be performed", 409) - printer.cancelPrint() + printer.cancel_print() return NO_CONTENT @api.route("/job", methods=["GET"]) def jobState(): - currentData = printer.getCurrentData() + currentData = printer.get_current_data() return jsonify({ "job": currentData["job"], "progress": currentData["progress"], diff --git a/src/octoprint/server/api/log.py b/src/octoprint/server/api/log.py index b1131b320..ccfeb01ac 100644 --- a/src/octoprint/server/api/log.py +++ b/src/octoprint/server/api/log.py @@ -15,7 +15,7 @@ from octoprint.settings import settings from octoprint.server import NO_CONTENT, admin_permission from octoprint.server.util.flask import redirect_to_tornado, restricted_access from octoprint.server.api import api -from octoprint.util import getFreeBytes +from octoprint.util import get_free_bytes @api.route("/logs", methods=["GET"]) @@ -23,7 +23,7 @@ from octoprint.util import getFreeBytes @admin_permission.require(403) def getLogFiles(): files = _getLogFiles() - return jsonify(files=files, free=getFreeBytes(settings().getBaseFolder("logs"))) + return jsonify(files=files, free=get_free_bytes(settings().getBaseFolder("logs"))) @api.route("/logs/", methods=["GET"]) diff --git a/src/octoprint/server/api/printer.py b/src/octoprint/server/api/printer.py index 55ae6d3b1..e260c7621 100644 --- a/src/octoprint/server/api/printer.py +++ b/src/octoprint/server/api/printer.py @@ -6,20 +6,23 @@ __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 flask import request, jsonify, make_response, Response +from flask.exceptions import JSONBadRequest import re from octoprint.settings import settings, valid_boolean_trues from octoprint.server import printer, NO_CONTENT from octoprint.server.api import api -from octoprint.server.util.flask import restricted_access +from octoprint.server.util.flask import restricted_access, get_json_command_from_request import octoprint.util as util +from octoprint.printer import UnknownScript + #~~ Printer @api.route("/printer", methods=["GET"]) def printerState(): - if not printer.isOperational(): + if not printer.is_operational(): return make_response("Printer is not operational", 409) # process excludes @@ -37,11 +40,11 @@ def printerState(): # add sd information if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]): - result.update({"sd": {"ready": printer.isSdReady()}}) + result.update({"sd": {"ready": printer.is_sd_ready()}}) # add state information if not "state" in excludes: - state = printer.getCurrentData()["state"] + state = printer.get_current_data()["state"] result.update({"state": state}) return jsonify(result) @@ -53,16 +56,17 @@ def printerState(): @api.route("/printer/tool", methods=["POST"]) @restricted_access def printerToolCommand(): - if not printer.isOperational(): + if not printer.is_operational(): return make_response("Printer is not operational", 409) valid_commands = { "select": ["tool"], "target": ["targets"], "offset": ["offsets"], - "extrude": ["amount"] + "extrude": ["amount"], + "flowrate": ["factor"] } - command, data, response = util.getJsonCommandFromRequest(request, valid_commands) + command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response @@ -76,7 +80,7 @@ def printerToolCommand(): if not tool.startswith("tool"): return make_response("Invalid tool for selection: %s" % tool, 400) - printer.changeTool(tool) + printer.change_tool(tool) ##~~ temperature elif command == "target": @@ -93,7 +97,7 @@ def printerToolCommand(): # perform the actual temperature commands for tool in validated_values.keys(): - printer.setTemperature(tool, validated_values[tool]) + printer.set_temperature(tool, validated_values[tool]) ##~~ temperature offset elif command == "offset": @@ -111,11 +115,11 @@ def printerToolCommand(): validated_values[tool] = value # set the offsets - printer.setTemperatureOffset(validated_values) + printer.set_temperature_offset(validated_values) ##~~ extrusion elif command == "extrude": - if printer.isPrinting(): + if printer.is_printing(): # do not extrude when a print job is running return make_response("Printer is currently printing", 409) @@ -124,12 +128,21 @@ def printerToolCommand(): return make_response("Not a number for extrusion amount: %r" % amount, 400) printer.extrude(amount) + elif command == "flowrate": + factor = data["factor"] + if not isinstance(factor, (int, long, float)): + return make_response("Not a number for flow rate: %r" % factor, 400) + try: + printer.flow_rate(factor) + except ValueError as e: + return make_response("Invalid value for flow rate: %s" % e.message, 400) + return NO_CONTENT @api.route("/printer/tool", methods=["GET"]) def printerToolState(): - if not printer.isOperational(): + if not printer.is_operational(): return make_response("Printer is not operational", 409) def deleteBed(x): @@ -148,14 +161,14 @@ def printerToolState(): @api.route("/printer/bed", methods=["POST"]) @restricted_access def printerBedCommand(): - if not printer.isOperational(): + if not printer.is_operational(): return make_response("Printer is not operational", 409) valid_commands = { "target": ["target"], "offset": ["offset"] } - command, data, response = util.getJsonCommandFromRequest(request, valid_commands) + command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response @@ -168,7 +181,7 @@ def printerBedCommand(): return make_response("Not a number: %r" % target, 400) # perform the actual temperature command - printer.setTemperature("bed", target) + printer.set_temperature("bed", target) ##~~ temperature offset elif command == "offset": @@ -181,14 +194,14 @@ def printerBedCommand(): return make_response("Offset not in range [-50, 50]: %f" % offset, 400) # set the offsets - printer.setTemperatureOffset({"bed": offset}) + printer.set_temperature_offset({"bed": offset}) return NO_CONTENT @api.route("/printer/bed", methods=["GET"]) def printerBedState(): - if not printer.isOperational(): + if not printer.is_operational(): return make_response("Printer is not operational", 409) def deleteTools(x): @@ -212,18 +225,19 @@ def printerBedState(): @api.route("/printer/printhead", methods=["POST"]) @restricted_access def printerPrintheadCommand(): - if not printer.isOperational() or printer.isPrinting(): - # do not jog when a print job is running or we don't have a connection - return make_response("Printer is not operational or currently printing", 409) - valid_commands = { "jog": [], - "home": ["axes"] + "home": ["axes"], + "feedrate": ["factor"] } - command, data, response = util.getJsonCommandFromRequest(request, valid_commands) + command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response + if not printer.is_operational() or (printer.is_printing() and command != "feedrate"): + # do not jog when a print job is running or we don't have a connection + return make_response("Printer is not operational or currently printing", 409) + valid_axes = ["x", "y", "z"] ##~~ jog command if command == "jog": @@ -252,6 +266,15 @@ def printerPrintheadCommand(): # execute the home command printer.home(validated_values) + elif command == "feedrate": + factor = data["factor"] + if not isinstance(factor, (int, long, float)): + return make_response("Not a number for feed rate: %r" % factor, 400) + try: + printer.feed_rate(factor) + except ValueError as e: + return make_response("Invalid value for feed rate: %s" % e.message, 400) + return NO_CONTENT @@ -264,7 +287,7 @@ def printerSdCommand(): if not settings().getBoolean(["feature", "sdSupport"]): return make_response("SD support is disabled", 404) - if not printer.isOperational() or printer.isPrinting() or printer.isPaused(): + if not printer.is_operational() or printer.is_printing() or printer.is_paused(): return make_response("Printer is not operational or currently busy", 409) valid_commands = { @@ -272,16 +295,16 @@ def printerSdCommand(): "refresh": [], "release": [] } - command, data, response = util.getJsonCommandFromRequest(request, valid_commands) + command, data, response = get_json_command_from_request(request, valid_commands) if response is not None: return response if command == "init": - printer.initSdCard() + printer.init_sd_card() elif command == "refresh": - printer.refreshSdFiles() + printer.refresh_sd_files() elif command == "release": - printer.releaseSdCard() + printer.release_sd_card() return NO_CONTENT @@ -291,7 +314,7 @@ def printerSdState(): if not settings().getBoolean(["feature", "sdSupport"]): return make_response("SD support is disabled", 404) - return jsonify(ready=printer.isSdReady()) + return jsonify(ready=printer.is_sd_ready()) ##~~ Commands @@ -300,37 +323,58 @@ def printerSdState(): @api.route("/printer/command", methods=["POST"]) @restricted_access def printerCommand(): - # TODO: document me - if not printer.isOperational(): + if not printer.is_operational(): return make_response("Printer is not operational", 409) if not "application/json" in request.headers["Content-Type"]: return make_response("Expected content type JSON", 400) - data = request.json + try: + data = request.json + except JSONBadRequest: + return make_response("Malformed JSON body in request", 400) - parameters = {} - if "parameters" in data.keys(): + if "command" in data and "commands" in data: + return make_response("'command' and 'commands' are mutually exclusive", 400) + elif ("command" in data or "commands" in data) and "script" in data: + return make_response("'command'/'commands' and 'script' are mutually exclusive", 400) + elif not ("command" in data or "commands" in data or "script" in data): + return make_response("Need one of 'command', 'commands' or 'script'", 400) + + parameters = dict() + if "parameters" in data: parameters = data["parameters"] - commands = [] - if "command" in data.keys(): - commands = [data["command"]] - elif "commands" in data.keys(): - commands = data["commands"] + if "command" in data or "commands" in data: + if "command" in data: + commands = [data["command"]] + else: + if not isinstance(data["commands"], (list, tuple)): + return make_response("'commands' needs to be a list", 400) + commands = data["commands"] - commandsToSend = [] - for command in commands: - commandToSend = command - if len(parameters) > 0: - commandToSend = command % parameters - commandsToSend.append(commandToSend) + commandsToSend = [] + for command in commands: + commandToSend = command + if len(parameters) > 0: + commandToSend = command % parameters + commandsToSend.append(commandToSend) - printer.commands(commandsToSend) + printer.commands(commandsToSend) + + elif "script" in data: + script_name = data["script"] + context = dict(parameters=parameters) + if "context" in data: + context["context"] = data["context"] + + try: + printer.script(script_name, context=context) + except UnknownScript: + return make_response("Unknown script: {script_name}".format(**locals()), 404) return NO_CONTENT - @api.route("/printer/command/custom", methods=["GET"]) def getCustomControls(): # TODO: document me @@ -339,13 +383,13 @@ def getCustomControls(): def _getTemperatureData(filter): - if not printer.isOperational(): + if not printer.is_operational(): return make_response("Printer is not operational", 409) - tempData = printer.getCurrentTemperatures() + tempData = printer.get_current_temperatures() if "history" in request.values.keys() and request.values["history"] in valid_boolean_trues: - tempHistory = printer.getTemperatureHistory() + tempHistory = printer.get_temperature_history() limit = 300 if "limit" in request.values.keys() and unicode(request.values["limit"]).isnumeric(): diff --git a/src/octoprint/server/api/printer_profiles.py b/src/octoprint/server/api/printer_profiles.py new file mode 100644 index 000000000..e7c1e7c8c --- /dev/null +++ b/src/octoprint/server/api/printer_profiles.py @@ -0,0 +1,139 @@ +# 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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import copy + +from flask import jsonify, make_response, request, url_for +from flask.exceptions import JSONBadRequest + +from octoprint.server.api import api, NO_CONTENT +from octoprint.server.util.flask import restricted_access +from octoprint.util import dict_merge + +from octoprint.server import printerProfileManager +from octoprint.printer.profile import InvalidProfileError, CouldNotOverwriteError, SaveError + + +@api.route("/printerprofiles", methods=["GET"]) +def printerProfilesList(): + all_profiles = printerProfileManager.get_all() + return jsonify(dict(profiles=_convert_profiles(all_profiles))) + +@api.route("/printerprofiles", methods=["POST"]) +@restricted_access +def printerProfilesAdd(): + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) + + try: + json_data = request.json + except JSONBadRequest: + return make_response("Malformed JSON body in request", 400) + + if not "profile" in json_data: + return make_response("No profile included in request", 400) + + base_profile = printerProfileManager.get_default() + if "basedOn" in json_data and isinstance(json_data["basedOn"], basestring): + other_profile = printerProfileManager.get(json_data["basedOn"]) + if other_profile is not None: + base_profile = other_profile + + if "id" in base_profile: + del base_profile["id"] + if "name" in base_profile: + del base_profile["name"] + if "default" in base_profile: + del base_profile["default"] + + new_profile = json_data["profile"] + make_default = False + if "default" in new_profile: + make_default = True + del new_profile["default"] + + profile = dict_merge(base_profile, new_profile) + try: + saved_profile = printerProfileManager.save(profile, allow_overwrite=False, make_default=make_default) + except InvalidProfileError: + return make_response("Profile is invalid", 400) + except CouldNotOverwriteError: + return make_response("Profile already exists and overwriting was not allowed", 400) + except Exception as e: + return make_response("Could not save profile: %s" % e.message, 500) + else: + return jsonify(dict(profile=_convert_profile(saved_profile))) + +@api.route("/printerprofiles/", methods=["GET"]) +def printerProfilesGet(identifier): + profile = printerProfileManager.get(identifier) + if profile is None: + return make_response("Unknown profile: %s" % identifier, 404) + else: + return jsonify(_convert_profile(profile)) + +@api.route("/printerprofiles/", methods=["DELETE"]) +@restricted_access +def printerProfilesDelete(identifier): + printerProfileManager.remove(identifier) + return NO_CONTENT + +@api.route("/printerprofiles/", methods=["PATCH"]) +@restricted_access +def printerProfilesUpdate(identifier): + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) + + try: + json_data = request.json + except JSONBadRequest: + return make_response("Malformed JSON body in request", 400) + + if not "profile" in json_data: + return make_response("No profile included in request", 400) + + profile = printerProfileManager.get(identifier) + if profile is None: + profile = printerProfileManager.get_default() + + new_profile = json_data["profile"] + new_profile = dict_merge(profile, new_profile) + + make_default = False + if "default" in new_profile: + make_default = True + del new_profile["default"] + + new_profile["id"] = identifier + + try: + saved_profile = printerProfileManager.save(new_profile, allow_overwrite=True, make_default=make_default) + except InvalidProfileError: + return make_response("Profile is invalid", 400) + except CouldNotOverwriteError: + return make_response("Profile already exists and overwriting was not allowed", 400) + except Exception as e: + return make_response("Could not save profile: %s" % e.message, 500) + else: + return jsonify(dict(profile=_convert_profile(saved_profile))) + +def _convert_profiles(profiles): + result = dict() + for identifier, profile in profiles.items(): + result[identifier] = _convert_profile(profile) + return result + +def _convert_profile(profile): + default = printerProfileManager.get_default()["id"] + current = printerProfileManager.get_current_or_default()["id"] + + converted = copy.deepcopy(profile) + converted["resource"] = url_for(".printerProfilesGet", identifier=profile["id"], _external=True) + converted["default"] = (profile["id"] == default) + converted["current"] = (profile["id"] == current) + return converted diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 05f6dcecf..6da2cc9a6 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -7,17 +7,19 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import logging -from flask import request, jsonify +from flask import request, jsonify, make_response +from flask.exceptions import JSONBadRequest +from octoprint.events import eventManager, Events from octoprint.settings import settings -from octoprint.printer import getConnectionOptions +from octoprint.printer import get_connection_options from octoprint.server import admin_permission from octoprint.server.api import api from octoprint.server.util.flask import restricted_access import octoprint.plugin - +import octoprint.util #~~ settings @@ -26,30 +28,20 @@ import octoprint.plugin def getSettings(): s = settings() - [movementSpeedX, movementSpeedY, movementSpeedZ, movementSpeedE] \ - = s.get(["printerParameters", "movementSpeed", ["x", "y", "z", "e"]]) - - connectionOptions = getConnectionOptions() + connectionOptions = get_connection_options() data = { "api": { "enabled": s.getBoolean(["api", "enabled"]), - "key": s.get(["api", "key"]), + "key": s.get(["api", "key"]) if admin_permission.can() else "n/a", "allowCrossOrigin": s.get(["api", "allowCrossOrigin"]) }, "appearance": { "name": s.get(["appearance", "name"]), - "color": s.get(["appearance", "color"]) + "color": s.get(["appearance", "color"]), + "colorTransparent": s.getBoolean(["appearance", "colorTransparent"]) }, "printer": { - "movementSpeedX": movementSpeedX, - "movementSpeedY": movementSpeedY, - "movementSpeedZ": movementSpeedZ, - "movementSpeedE": movementSpeedE, - "invertAxes": s.get(["printerParameters", "invertAxes"]), - "numExtruders": s.get(["printerParameters", "numExtruders"]), - "extruderOffsets": s.get(["printerParameters", "extruderOffsets"]), - "bedDimensions": s.get(["printerParameters", "bedDimensions"]), "defaultExtrusionLength": s.getInt(["printerParameters", "defaultExtrusionLength"]) }, "webcam": { @@ -57,6 +49,7 @@ def getSettings(): "snapshotUrl": s.get(["webcam", "snapshot"]), "ffmpegPath": s.get(["webcam", "ffmpeg"]), "bitrate": s.get(["webcam", "bitrate"]), + "ffmpegThreads": s.get(["webcam", "ffmpegThreads"]), "watermark": s.getBoolean(["webcam", "watermark"]), "flipH": s.getBoolean(["webcam", "flipH"]), "flipV": s.getBoolean(["webcam", "flipV"]) @@ -69,7 +62,8 @@ def getSettings(): "sdSupport": s.getBoolean(["feature", "sdSupport"]), "sdAlwaysAvailable": s.getBoolean(["feature", "sdAlwaysAvailable"]), "swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]), - "repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"]) + "repetierTargetTemp": s.getBoolean(["feature", "repetierTargetTemp"]), + "keyboardControl": s.getBoolean(["feature", "keyboardControl"]) }, "serial": { "port": connectionOptions["portPreference"], @@ -99,13 +93,25 @@ def getSettings(): "events": s.get(["system", "events"]) }, "terminalFilters": s.get(["terminalFilters"]), - "cura": { - "enabled": s.getBoolean(["cura", "enabled"]), - "path": s.get(["cura", "path"]), - "config": s.get(["cura", "config"]) + "scripts": { + "gcode": { + "afterPrinterConnected": None, + "beforePrintStarted": None, + "afterPrintCancelled": None, + "afterPrintDone": None, + "beforePrintPaused": None, + "afterPrintResumed": None, + "snippets": dict() + } } } + gcode_scripts = s.listScripts("gcode") + if gcode_scripts: + data["scripts"] = dict(gcode=dict()) + for name in gcode_scripts: + data["scripts"]["gcode"][name] = s.loadScript("gcode", name, source=True) + def process_plugin_result(name, plugin, result): if result: if not "plugins" in data: @@ -125,108 +131,102 @@ def getSettings(): @restricted_access @admin_permission.require(403) def setSettings(): - if "application/json" in request.headers["Content-Type"]: + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) + + try: data = request.json - s = settings() + except JSONBadRequest: + return make_response("Malformed JSON body in request", 400) + s = settings() - if "api" in data.keys(): - if "enabled" in data["api"].keys(): s.setBoolean(["api", "enabled"], data["api"]["enabled"]) - if "key" in data["api"].keys(): s.set(["api", "key"], data["api"]["key"], True) - if "allowCrossOrigin" in data["api"].keys(): s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"]) + if "api" in data.keys(): + if "enabled" in data["api"].keys(): s.setBoolean(["api", "enabled"], data["api"]["enabled"]) + if "key" in data["api"].keys(): s.set(["api", "key"], data["api"]["key"], True) + if "allowCrossOrigin" in data["api"].keys(): s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"]) - if "appearance" in data.keys(): - if "name" in data["appearance"].keys(): s.set(["appearance", "name"], data["appearance"]["name"]) - if "color" in data["appearance"].keys(): s.set(["appearance", "color"], data["appearance"]["color"]) + if "appearance" in data.keys(): + if "name" in data["appearance"].keys(): s.set(["appearance", "name"], data["appearance"]["name"]) + if "color" in data["appearance"].keys(): s.set(["appearance", "color"], data["appearance"]["color"]) + if "colorTransparent" in data["appearance"].keys(): s.setBoolean(["appearance", "colorTransparent"], data["appearance"]["colorTransparent"]) - if "printer" in data.keys(): - if "movementSpeedX" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "x"], data["printer"]["movementSpeedX"]) - if "movementSpeedY" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "y"], data["printer"]["movementSpeedY"]) - if "movementSpeedZ" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "z"], data["printer"]["movementSpeedZ"]) - if "movementSpeedE" in data["printer"].keys(): s.setInt(["printerParameters", "movementSpeed", "e"], data["printer"]["movementSpeedE"]) - if "invertAxes" in data["printer"].keys(): s.set(["printerParameters", "invertAxes"], data["printer"]["invertAxes"]) - if "numExtruders" in data["printer"].keys(): s.setInt(["printerParameters", "numExtruders"], data["printer"]["numExtruders"]) - if "extruderOffsets" in data["printer"].keys(): s.set(["printerParameters", "extruderOffsets"], data["printer"]["extruderOffsets"]) - if "bedDimensions" in data["printer"].keys(): s.set(["printerParameters", "bedDimensions"], data["printer"]["bedDimensions"]) - if "defaultExtrusionLength" in data["printer"]: s.setInt(["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"]) + if "printer" in data.keys(): + if "defaultExtrusionLength" in data["printer"]: s.setInt(["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"]) - if "webcam" in data.keys(): - if "streamUrl" in data["webcam"].keys(): s.set(["webcam", "stream"], data["webcam"]["streamUrl"]) - if "snapshotUrl" in data["webcam"].keys(): s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"]) - if "ffmpegPath" in data["webcam"].keys(): s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"]) - if "bitrate" in data["webcam"].keys(): s.set(["webcam", "bitrate"], data["webcam"]["bitrate"]) - if "watermark" in data["webcam"].keys(): s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"]) - if "flipH" in data["webcam"].keys(): s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"]) - if "flipV" in data["webcam"].keys(): s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"]) + if "webcam" in data.keys(): + if "streamUrl" in data["webcam"].keys(): s.set(["webcam", "stream"], data["webcam"]["streamUrl"]) + if "snapshotUrl" in data["webcam"].keys(): s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"]) + if "ffmpegPath" in data["webcam"].keys(): s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"]) + if "bitrate" in data["webcam"].keys(): s.set(["webcam", "bitrate"], data["webcam"]["bitrate"]) + if "ffmpegThreads" in data["webcam"].keys(): s.setInt(["webcam", "ffmpegThreads"], data["webcam"]["ffmpegThreads"]) + if "watermark" in data["webcam"].keys(): s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"]) + if "flipH" in data["webcam"].keys(): s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"]) + if "flipV" in data["webcam"].keys(): s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"]) - if "feature" in data.keys(): - if "gcodeViewer" in data["feature"].keys(): s.setBoolean(["gcodeViewer", "enabled"], data["feature"]["gcodeViewer"]) - if "temperatureGraph" in data["feature"].keys(): s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"]) - if "waitForStart" in data["feature"].keys(): s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"]) - if "alwaysSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"]) - if "sdSupport" in data["feature"].keys(): s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"]) - if "sdAlwaysAvailable" in data["feature"].keys(): s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"]) - if "swallowOkAfterResend" in data["feature"].keys(): s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"]) - if "repetierTargetTemp" in data["feature"].keys(): s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"]) + if "feature" in data.keys(): + if "gcodeViewer" in data["feature"].keys(): s.setBoolean(["gcodeViewer", "enabled"], data["feature"]["gcodeViewer"]) + if "temperatureGraph" in data["feature"].keys(): s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"]) + if "waitForStart" in data["feature"].keys(): s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"]) + if "alwaysSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"]) + if "sdSupport" in data["feature"].keys(): s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"]) + if "sdAlwaysAvailable" in data["feature"].keys(): s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"]) + if "swallowOkAfterResend" in data["feature"].keys(): s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"]) + if "repetierTargetTemp" in data["feature"].keys(): s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"]) + if "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"]) - if "serial" in data.keys(): - if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"]) - if "port" in data["serial"].keys(): s.set(["serial", "port"], data["serial"]["port"]) - if "baudrate" in data["serial"].keys(): s.setInt(["serial", "baudrate"], data["serial"]["baudrate"]) - if "timeoutConnection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"]) - if "timeoutDetection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"]) - if "timeoutCommunication" in data["serial"].keys(): s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"]) - if "timeoutTemperature" in data["serial"].keys(): s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"]) - if "timeoutSdStatus" in data["serial"].keys(): s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"]) + if "serial" in data.keys(): + if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"]) + if "port" in data["serial"].keys(): s.set(["serial", "port"], data["serial"]["port"]) + if "baudrate" in data["serial"].keys(): s.setInt(["serial", "baudrate"], data["serial"]["baudrate"]) + if "timeoutConnection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"]) + if "timeoutDetection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"]) + if "timeoutCommunication" in data["serial"].keys(): s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"]) + if "timeoutTemperature" in data["serial"].keys(): s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"]) + if "timeoutSdStatus" in data["serial"].keys(): s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"]) - oldLog = s.getBoolean(["serial", "log"]) - if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"]) - if oldLog and not s.getBoolean(["serial", "log"]): - # disable debug logging to serial.log - logging.getLogger("SERIAL").debug("Disabling serial logging") - logging.getLogger("SERIAL").setLevel(logging.CRITICAL) - elif not oldLog and s.getBoolean(["serial", "log"]): - # enable debug logging to serial.log - logging.getLogger("SERIAL").setLevel(logging.DEBUG) - logging.getLogger("SERIAL").debug("Enabling serial logging") + oldLog = s.getBoolean(["serial", "log"]) + if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"]) + if oldLog and not s.getBoolean(["serial", "log"]): + # disable debug logging to serial.log + logging.getLogger("SERIAL").debug("Disabling serial logging") + logging.getLogger("SERIAL").setLevel(logging.CRITICAL) + elif not oldLog and s.getBoolean(["serial", "log"]): + # enable debug logging to serial.log + logging.getLogger("SERIAL").setLevel(logging.DEBUG) + logging.getLogger("SERIAL").debug("Enabling serial logging") - if "folder" in data.keys(): - if "uploads" in data["folder"].keys(): s.setBaseFolder("uploads", data["folder"]["uploads"]) - if "timelapse" in data["folder"].keys(): s.setBaseFolder("timelapse", data["folder"]["timelapse"]) - if "timelapseTmp" in data["folder"].keys(): s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"]) - if "logs" in data["folder"].keys(): s.setBaseFolder("logs", data["folder"]["logs"]) - if "watched" in data["folder"].keys(): s.setBaseFolder("watched", data["folder"]["watched"]) + if "folder" in data.keys(): + if "uploads" in data["folder"].keys(): s.setBaseFolder("uploads", data["folder"]["uploads"]) + if "timelapse" in data["folder"].keys(): s.setBaseFolder("timelapse", data["folder"]["timelapse"]) + if "timelapseTmp" in data["folder"].keys(): s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"]) + if "logs" in data["folder"].keys(): s.setBaseFolder("logs", data["folder"]["logs"]) + if "watched" in data["folder"].keys(): s.setBaseFolder("watched", data["folder"]["watched"]) - if "temperature" in data.keys(): - if "profiles" in data["temperature"].keys(): s.set(["temperature", "profiles"], data["temperature"]["profiles"]) + if "temperature" in data.keys(): + if "profiles" in data["temperature"].keys(): s.set(["temperature", "profiles"], data["temperature"]["profiles"]) - if "terminalFilters" in data.keys(): - s.set(["terminalFilters"], data["terminalFilters"]) + if "terminalFilters" in data.keys(): + s.set(["terminalFilters"], data["terminalFilters"]) - if "system" in data.keys(): - if "actions" in data["system"].keys(): s.set(["system", "actions"], data["system"]["actions"]) - if "events" in data["system"].keys(): s.set(["system", "events"], data["system"]["events"]) + if "system" in data.keys(): + if "actions" in data["system"].keys(): s.set(["system", "actions"], data["system"]["actions"]) + if "events" in data["system"].keys(): s.set(["system", "events"], data["system"]["events"]) - cura = data.get("cura", None) - if cura: - path = cura.get("path") - if path: - s.set(["cura", "path"], path) + if "scripts" in data: + if "gcode" in data["scripts"] and isinstance(data["scripts"]["gcode"], dict): + for name, script in data["scripts"]["gcode"].items(): + if name == "snippets": + continue + s.saveScript("gcode", name, script.replace("\r\n", "\n").replace("\r", "\n")) - config = cura.get("config") - if config: - s.set(["cura", "config"], config) - - # Enabled is a boolean so we cannot check that we have a result - enabled = cura.get("enabled") - s.setBoolean(["cura", "enabled"], enabled) - - if "plugins" in data: - for name, plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin).items(): - if name in data["plugins"]: - plugin.on_settings_save(data["plugins"][name]) + if "plugins" in data: + for name, plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin).items(): + if name in data["plugins"]: + plugin.on_settings_save(data["plugins"][name]) - s.save() + if s.save(): + eventManager().fire(Events.SETTINGS_UPDATED) return getSettings() diff --git a/src/octoprint/server/api/slicing.py b/src/octoprint/server/api/slicing.py new file mode 100644 index 000000000..978103a6d --- /dev/null +++ b/src/octoprint/server/api/slicing.py @@ -0,0 +1,170 @@ +# 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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + +from flask import request, jsonify, make_response, url_for +from flask.exceptions import JSONBadRequest + +from octoprint.server import slicingManager +from octoprint.server.util.flask import restricted_access +from octoprint.server.api import api, NO_CONTENT + +from octoprint.settings import settings as s, valid_boolean_trues + +from octoprint.slicing import SlicerNotConfigured + + +@api.route("/slicing", methods=["GET"]) +def slicingListAll(): + default_slicer = s().get(["slicing", "defaultSlicer"]) + + if "configured" in request.values and request.values["configured"] in valid_boolean_trues: + slicers = slicingManager.configured_slicers + else: + slicers = slicingManager.registered_slicers + + result = dict() + for slicer in slicers: + slicer_impl = slicingManager.get_slicer(slicer, require_configured=False) + result[slicer] = dict( + key=slicer, + displayName=slicer_impl.get_slicer_properties()["name"], + default=default_slicer == slicer, + configured = slicer_impl.is_slicer_configured(), + profiles=_getSlicingProfilesData(slicer) + ) + + return jsonify(result) + +@api.route("/slicing//profiles", methods=["GET"]) +def slicingListSlicerProfiles(slicer): + if not slicer in slicingManager.registered_slicers: + return make_response("Unknown slicer {slicer}".format(**locals()), 404) + + configured = False + if "configured" in request.values and request.values["configured"] in valid_boolean_trues: + if not slicer in slicingManager.configured_slicers: + return make_response("Unknown slicer {slicer}".format(**locals()), 404) + configured = True + + return jsonify(_getSlicingProfilesData(slicer, require_configured=configured)) + +@api.route("/slicing//profiles/", methods=["GET"]) +def slicingGetSlicerProfile(slicer, name): + if not slicer in slicingManager.registered_slicers: + return make_response("Unknown slicer {slicer}".format(**locals()), 404) + + profile = slicingManager.load_profile(slicer, name) + if not profile: + return make_response("Profile not found", 404) + + result = _getSlicingProfileData(slicer, name, profile) + result["data"] = profile.data + return jsonify(result) + +@api.route("/slicing//profiles/", methods=["PUT"]) +@restricted_access +def slicingAddSlicerProfile(slicer, name): + if not slicer in slicingManager.registered_slicers: + return make_response("Unknown slicer {slicer}".format(**locals()), 404) + + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) + + try: + json_data = request.json + except JSONBadRequest: + return make_response("Malformed JSON body in request", 400) + + data = dict() + display_name = None + description = None + if "data" in json_data: + data = json_data["data"] + if "displayName" in json_data: + display_name = json_data["displayName"] + if "description" in json_data: + description = json_data["description"] + + profile = slicingManager.save_profile(slicer, name, data, display_name=display_name, description=description) + + result = _getSlicingProfileData(slicer, name, profile) + r = make_response(jsonify(result), 201) + r.headers["Location"] = result["resource"] + return r + +@api.route("/slicing//profiles/", methods=["PATCH"]) +@restricted_access +def slicingPatchSlicerProfile(slicer, name): + if not slicer in slicingManager.registered_slicers: + return make_response("Unknown slicer {slicer}".format(**locals()), 404) + + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) + + profile = slicingManager.load_profile(slicer, name) + if not profile: + return make_response("Profile not found", 404) + + try: + json_data = request.json + except JSONBadRequest: + return make_response("Malformed JSON body in request", 400) + + data = dict() + display_name = None + description = None + if "data" in json_data: + data = json_data["data"] + if "displayName" in json_data: + display_name = json_data["displayName"] + if "description" in json_data: + description = json_data["description"] + + from octoprint.server.api import valid_boolean_trues + if "default" in json_data and json_data["default"] in valid_boolean_trues: + default_profiles = s().get(["slicing", "defaultProfiles"]) + if not default_profiles: + default_profiles = dict() + default_profiles[slicer] = name + s().set(["slicing", "defaultProfiles"], default_profiles) + s().save(force=True) + + slicingManager.save_profile(slicer, name, profile, overrides=data, display_name=display_name, description=description) + return NO_CONTENT + +@api.route("/slicing//profiles/", methods=["DELETE"]) +@restricted_access +def slicingDelSlicerProfile(slicer, name): + if not slicer in slicingManager.registered_slicers: + return make_response("Unknown slicer {slicer}".format(**locals()), 404) + + slicingManager.delete_profile(slicer, name) + return NO_CONTENT + +def _getSlicingProfilesData(slicer, require_configured=False): + try: + profiles = slicingManager.all_profiles(slicer, require_configured=require_configured) + except SlicerNotConfigured: + return dict() + + result = dict() + for name, profile in profiles.items(): + result[name] = _getSlicingProfileData(slicer, name, profile) + return result + +def _getSlicingProfileData(slicer, name, profile): + defaultProfiles = s().get(["slicing", "defaultProfiles"]) + result = dict( + key=name, + default=defaultProfiles and slicer in defaultProfiles and defaultProfiles[slicer] == name, + resource=url_for(".slicingGetSlicerProfile", slicer=slicer, name=name, _external=True) + ) + if profile.display_name is not None: + result["displayName"] = profile.display_name + if profile.description is not None: + result["description"] = profile.description + return result \ No newline at end of file diff --git a/src/octoprint/server/api/timelapse.py b/src/octoprint/server/api/timelapse.py index 11f27e5b3..bef855365 100644 --- a/src/octoprint/server/api/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -7,7 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import os -from flask import request, jsonify, url_for +from flask import request, jsonify, url_for, make_response from werkzeug.utils import secure_filename import octoprint.timelapse @@ -30,9 +30,11 @@ def getTimelapseData(): if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse): config["type"] = "zchange" config["postRoll"] = timelapse.postRoll() + config["fps"] = timelapse.fps() elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse): config["type"] = "timed" config["postRoll"] = timelapse.postRoll() + config["fps"] = timelapse.fps() config.update({ "interval": timelapse.interval() }) @@ -55,10 +57,11 @@ def downloadTimelapse(filename): @api.route("/timelapse/", methods=["DELETE"]) @restricted_access def deleteTimelapse(filename): - if util.isAllowedFile(filename, {"mpg"}): - secure = os.path.join(settings().getBaseFolder("timelapse"), secure_filename(filename)) - if os.path.exists(secure): - os.remove(secure) + if util.is_allowed_file(filename, {"mpg"}): + timelapse_folder = settings().getBaseFolder("timelapse") + full_path = os.path.realpath(os.path.join(timelapse_folder, filename)) + if full_path.startswith(timelapse_folder) and os.path.exists(full_path): + os.remove(full_path) return getTimelapseData() @@ -69,26 +72,46 @@ def setTimelapseConfig(): config = { "type": request.values["type"], "postRoll": 0, + "fps": 25, "options": {} } - if "postRoll" in request.values: try: - config["postRoll"] = int(request.values["postRoll"]) + postRoll = int(request.values["postRoll"]) except ValueError: - pass + return make_response("Invalid value for postRoll: %r" % request.values["postRoll"], 400) + else: + if postRoll >= 0: + config["postRoll"] = postRoll + else: + return make_response("Invalid value for postRoll: %d" % postRoll, 400) + + if "fps" in request.values: + try: + fps = int(request.values["fps"]) + except ValueError: + return make_response("Invalid value for fps: %r" % request.values["fps"], 400) + else: + if fps > 0: + config["fps"] = fps + else: + return make_response("Invalid value for fps: %d" % fps, 400) if "interval" in request.values: - interval = 10 + config["options"] = { + "interval": 10 + } + try: interval = int(request.values["interval"]) except ValueError: - pass - - config["options"] = { - "interval": interval - } + return make_response("Invalid value for interval: %r" % request.values["interval"]) + else: + if interval > 0: + config["options"]["interval"] = interval + else: + return make_response("Invalid value for interval: %d" % interval) if admin_permission.can() and "save" in request.values and request.values["save"] in valid_boolean_trues: octoprint.timelapse.configureTimelapse(config, True) diff --git a/src/octoprint/server/api/users.py b/src/octoprint/server/api/users.py index 2b6f4022d..cf2e7fd3a 100644 --- a/src/octoprint/server/api/users.py +++ b/src/octoprint/server/api/users.py @@ -6,6 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" from flask import request, jsonify, abort, make_response +from flask.exceptions import JSONBadRequest from flask.ext.login import current_user import octoprint.users as users @@ -35,21 +36,26 @@ def addUser(): if userManager is None: return jsonify(SUCCESS) - if "application/json" in request.headers["Content-Type"]: + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) + + try: data = request.json + except JSONBadRequest: + return make_response("Malformed JSON body in request", 400) - name = data["name"] - password = data["password"] - active = data["active"] + name = data["name"] + password = data["password"] + active = data["active"] - roles = ["user"] - if "admin" in data.keys() and data["admin"]: - roles.append("admin") + roles = ["user"] + if "admin" in data.keys() and data["admin"]: + roles.append("admin") - try: - userManager.addUser(name, password, active, roles) - except users.UserAlreadyExists: - abort(409) + try: + userManager.addUser(name, password, active, roles) + except users.UserAlreadyExists: + abort(409) return getUsers() @@ -78,18 +84,23 @@ def updateUser(username): user = userManager.findUser(username) if user is not None: - if "application/json" in request.headers["Content-Type"]: + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) + + try: data = request.json + except JSONBadRequest: + return make_response("Malformed JSON body in request", 400) - # change roles - roles = ["user"] - if "admin" in data.keys() and data["admin"]: - roles.append("admin") - userManager.changeUserRoles(username, roles) + # change roles + roles = ["user"] + if "admin" in data.keys() and data["admin"]: + roles.append("admin") + userManager.changeUserRoles(username, roles) - # change activation - if "active" in data.keys(): - userManager.changeUserActivation(username, data["active"]) + # change activation + if "active" in data.keys(): + userManager.changeUserActivation(username, data["active"]) return getUsers() else: abort(404) @@ -116,13 +127,22 @@ def changePasswordForUser(username): return jsonify(SUCCESS) if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()): - if "application/json" in request.headers["Content-Type"]: + if not "application/json" in request.headers["Content-Type"]: + return make_response("Expected content-type JSON", 400) + + try: data = request.json - if "password" in data.keys() and data["password"]: - try: - userManager.changeUserPassword(username, data["password"]) - except users.UnknownUser: - return make_response(("Unknown user: %s" % username, 404, [])) + except JSONBadRequest: + return make_response("Malformed JSON body in request", 400) + + if not "password" in data.keys() or not data["password"]: + return make_response("password is missing from request", 400) + + try: + userManager.changeUserPassword(username, data["password"]) + except users.UnknownUser: + return make_response(("Unknown user: %s" % username, 404, [])) + return jsonify(SUCCESS) else: return make_response(("Forbidden", 403, [])) diff --git a/src/octoprint/server/apps/__init__.py b/src/octoprint/server/apps/__init__.py new file mode 100644 index 000000000..47a68cca6 --- /dev/null +++ b/src/octoprint/server/apps/__init__.py @@ -0,0 +1,120 @@ +# 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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import rsa +from flask import Blueprint, request, make_response, jsonify + +import octoprint.server +import octoprint.plugin +from octoprint.settings import settings as s + +apps = Blueprint("apps", __name__) + +@apps.route("/auth", methods=["GET"]) +def getSessionKey(): + unverified_key, valid_until = octoprint.server.appSessionManager.create() + return jsonify(unverifiedKey=unverified_key, validUntil=valid_until) + +@apps.route("/auth", methods=["POST"]) +def verifySessionKey(): + if not "application/json" in request.headers["Content-Type"]: + return None, None, make_response("Expected content-type JSON", 400) + + data = request.json + for key in ("appid", "key", "_sig"): + if not key in data: + return make_response("Missing argument: {key}".format(key=key), 400) + + appid = str(data["appid"]) + if not "appversion" in data: + appversion = "any" + else: + appversion = str(data["appversion"]) + key = str(data["key"]) + + # calculate message that was signed + message = "{appid}:{appversion}:{key}".format(**locals()) + + # decode signature + import base64 + signature = data["_sig"] + signature = base64.decodestring("\n".join([signature[x:x+64] for x in range(0, len(signature), 64)])) + + # fetch and validate app information + lookup_key = appid + ":" + appversion + apps = _get_registered_apps() + if not lookup_key in apps or not apps[lookup_key]["enabled"] or not "pubkey" in apps[lookup_key]: + octoprint.server.appSessionManager.remove(key) + return make_response("Invalid app: {lookup_key}".format(lookup_key=lookup_key), 401) + + pubkey_string = apps[lookup_key]["pubkey"] + pubkey_string = "\n".join([pubkey_string[x:x+64] for x in range(0, len(pubkey_string), 64)]) + try: + pubkey = rsa.PublicKey.load_pkcs1("-----BEGIN RSA PUBLIC KEY-----\n" + pubkey_string + "\n-----END RSA PUBLIC KEY-----\n") + except: + octoprint.server.appSessionManager.remove(key) + return make_response("Invalid pubkey stored in server", 500) + + # verify signature + try: + rsa.verify(message, signature, pubkey) + except rsa.VerificationError: + octoprint.server.appSessionManager.remove(key) + return make_response("Invalid signature", 401) + + # generate new session key and return it + result = octoprint.server.appSessionManager.verify(key) + if not result: + return make_response("Invalid key or already verified", 401) + + verified_key, valid_until = result + return jsonify(key=verified_key, validUntil=valid_until) + +__registered_apps = None +def _get_registered_apps(): + global __registered_apps + + if __registered_apps is not None: + return __registered_apps + + apps = s().get(["api", "apps"], merged=True) + for app, app_data in apps.items(): + if not "enabled" in app_data: + apps[app]["enabled"] = True + + app_plugins = octoprint.server.pluginManager.get_implementations(octoprint.plugin.AppPlugin) + for name, plugin in app_plugins.items(): + additional_apps = plugin.get_additional_apps() + any_version_enabled = dict() + + for app_data in additional_apps: + id, version, pubkey = app_data + key = id + ":" + version + if key in apps: + continue + + if not id in any_version_enabled: + any_version_enabled[id] = False + + if version == "any": + any_version_enabled[id] = True + + apps[key] = dict( + pubkey=pubkey, + enabled=True + ) + + for id, enabled in any_version_enabled.items(): + if enabled: + continue + apps[id + ":any"] = dict( + pubkey=None, + enabled=False + ) + + __registered_apps = apps + return apps \ No newline at end of file diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index 4e964e3f4..b69022698 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -10,22 +10,97 @@ import octoprint.timelapse import octoprint.server from octoprint.users import ApiUser +import flask as _flask + from . import flask from . import sockjs from . import tornado from . import watchdog +def apiKeyRequestHandler(): + """ + All requests in this blueprint need to be made supplying an API key. This may be the UI_API_KEY, in which case + the underlying request processing will directly take place, or it may be the global or a user specific case. In any + case it has to be present and must be valid, so anything other than the above three types will result in denying + the request. + """ + + import octoprint.server + + if _flask.request.method == 'OPTIONS' and settings().getBoolean(["api", "allowCrossOrigin"]): + return optionsAllowOrigin(_flask.request) + + apikey = get_api_key(_flask.request) + if apikey is None: + # no api key => 401 + return _flask.make_response("No API key provided", 401) + + if apikey == octoprint.server.UI_API_KEY: + # ui api key => continue regular request processing + return + + if not settings().get(["api", "enabled"]): + # api disabled => 401 + return _flask.make_response("API disabled", 401) + + if apikey == settings().get(["api", "key"]): + # global api key => continue regular request processing + return + + if octoprint.server.appSessionManager.validate(apikey): + # app session key => continue regular request processing + return + + user = get_user_for_apikey(apikey) + if user is not None: + # user specific api key => continue regular request processing + return + + # invalid api key => 401 + return _flask.make_response("Invalid API key", 401) + + +def corsResponseHandler(resp): + + # Allow crossdomain + allowCrossOrigin = settings().getBoolean(["api", "allowCrossOrigin"]) + if _flask.request.method != 'OPTIONS' and 'Origin' in _flask.request.headers and allowCrossOrigin: + resp.headers['Access-Control-Allow-Origin'] = _flask.request.headers['Origin'] + + return resp + + +def optionsAllowOrigin(request): + """ Always reply 200 on OPTIONS request """ + + resp = _flask.current_app.make_default_options_response() + + # Allow the origin which made the XHR + resp.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] + # Allow the actual method + resp.headers['Access-Control-Allow-Methods'] = request.headers['Access-Control-Request-Method'] + # Allow for 10 seconds + resp.headers['Access-Control-Max-Age'] = "10" + + # 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key) + customRequestHeaders = request.headers.get('Access-Control-Request-Headers', None) + if customRequestHeaders is not None: + # If present => allow them all + resp.headers['Access-Control-Allow-Headers'] = customRequestHeaders + + return resp + + def get_user_for_apikey(apikey): if settings().get(["api", "enabled"]) and apikey is not None: - if apikey == settings().get(["api", "key"]): - # master key was used + if apikey == settings().get(["api", "key"]) or octoprint.server.appSessionManager.validate(apikey): + # master key or an app session key was used return ApiUser() - else: + elif octoprint.server.userManager is not None: # user key might have been used return octoprint.server.userManager.findUser(apikey=apikey) - else: - return None + return None def get_api_key(request): @@ -72,20 +147,25 @@ class ReverseProxied(object): :param app: the WSGI application :param header_script_name: the HTTP header in the wsgi environment from which to determine the prefix :param header_scheme: the HTTP header in the wsgi environment from which to determine the scheme + :param header_host: the HTTP header in the wsgi environment from which to determine the host for which to generate external URLs :param base_url: the prefix to use as fallback if headers are not set + :param scheme: the scheme to use as fallback if headers are not set + :param host: the host to use as fallback if headers are not set """ - def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", base_url="", scheme=""): + def __init__(self, app, header_prefix="x-script-name", header_scheme="x-scheme", header_host="x-forwarded-host", base_url="", scheme="", host=""): self.app = app - # headers for prefix & scheme, converted to conform to WSGI format + # headers for prefix & scheme & host, converted to conform to WSGI format to_wsgi_format = lambda header: "HTTP_" + header.upper().replace("-", "_") self._header_prefix = to_wsgi_format(header_prefix) self._header_scheme = to_wsgi_format(header_scheme) + self._header_host = to_wsgi_format(header_host) - # fallback prefix & scheme from config + # fallback prefix & scheme & host from config self._fallback_prefix = base_url self._fallback_scheme = scheme + self._fallback_host = host def __call__(self, environ, start_response): # determine prefix @@ -109,6 +189,15 @@ class ReverseProxied(object): if scheme: environ["wsgi.url_scheme"] = scheme + # determine host + host = environ.get(self._header_host, "") + if not host: + host = self._fallback_host + + # rewrite host header based on host + if host: + environ["HTTP_HOST"] = host + # call wrapped app with rewritten environment return self.app(environ, start_response) diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 414f5be51..c52f41745 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -1,5 +1,6 @@ # coding=utf-8 from __future__ import absolute_import +from flask import make_response __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' @@ -10,11 +11,57 @@ import flask import flask.ext.login import flask.ext.principal import functools +import time +import uuid +import threading +import logging from octoprint.settings import settings import octoprint.server import octoprint.users +from werkzeug.contrib.cache import SimpleCache + + +#~~ cache decorator for cacheable views + +_cache = SimpleCache() + +def cached(timeout=5 * 60, key="view/%s", unless=None, refreshif=None): + def decorator(f): + @functools.wraps(f) + def decorated_function(*args, **kwargs): + logger = logging.getLogger(__name__) + + # bypass the cache if "unless" condition is true + if callable(unless) and unless(): + logger.debug("Cache bypassed, calling wrapped function") + return f(*args, **kwargs) + + cache_key = key % flask.request.path + + # only take the value from the cache if we are not required to refresh it from the wrapped function + if not callable(refreshif) or not refreshif(): + rv = _cache.get(cache_key) + if rv is not None: + logger.debug("Serving entry from cache") + return rv + + # get value from wrapped function + logger.debug("No cache entry or refreshing cache, calling wrapped function") + rv = f(*args, **kwargs) + + # store it in the cache + _cache.set(cache_key, rv, timeout=timeout) + + return rv + + return decorated_function + + return decorator + +def cache_check_headers(): + return "no-cache" in flask.request.cache_control or "no-cache" in flask.request.pragma #~~ access validators for use with tornado @@ -119,12 +166,7 @@ def restricted_access(func, api_enabled=True): # if API is globally enabled, enabled for this request and an api key is provided that is not the current UI API key, try to use that apikey = octoprint.server.util.get_api_key(flask.request) if settings().get(["api", "enabled"]) and api_enabled and apikey is not None and apikey != octoprint.server.UI_API_KEY: - if apikey == settings().get(["api", "key"]): - # master key was used - user = octoprint.users.ApiUser() - else: - # user key might have been used - user = octoprint.server.userManager.findUser(apikey=apikey) + user = octoprint.server.util.get_user_for_apikey(apikey) if user is None: return flask.make_response("Invalid API key", 401) @@ -137,18 +179,92 @@ def restricted_access(func, api_enabled=True): return decorated_view -def api_access(func): - @functools.wraps(func) - def decorated_view(*args, **kwargs): - if not settings().get(["api", "enabled"]): - flask.make_response("API disabled", 401) - apikey = octoprint.server.util.get_api_key(flask.request) - if apikey is None: - flask.make_response("No API key provided", 401) - if apikey != settings().get(["api", "key"]): - flask.make_response("Invalid API key", 403) - return func(*args, **kwargs) - return decorated_view +class AppSessionManager(object): + + VALIDITY_UNVERIFIED = 1 * 60 # 1 minute + VALIDITY_VERIFIED = 2 * 60 * 60 # 2 hours + + def __init__(self): + self._sessions = dict() + self._oldest = None + self._mutex = threading.RLock() + + self._logger = logging.getLogger(__name__) + + def create(self): + self._clean_sessions() + + key = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes) + created = time.time() + valid_until = created + self.__class__.VALIDITY_UNVERIFIED + + with self._mutex: + self._sessions[key] = (created, False, valid_until) + return key, valid_until + + def remove(self, key): + with self._mutex: + if not key in self._sessions: + return + del self._sessions[key] + + def verify(self, key): + self._clean_sessions() + + if not key in self._sessions: + return False + + with self._mutex: + created, verified, _ = self._sessions[key] + if verified: + return False + + valid_until = created + self.__class__.VALIDITY_VERIFIED + self._sessions[key] = created, True, created + self.__class__.VALIDITY_VERIFIED + + return key, valid_until + + def validate(self, key): + self._clean_sessions() + return key in self._sessions and self._sessions[key][1] + + def _clean_sessions(self): + if self._oldest is not None and self._oldest > time.time(): + return + + with self._mutex: + self._oldest = None + for key, value in self._sessions.items(): + created, verified, valid_until = value + if not verified: + valid_until = created + self.__class__.VALIDITY_UNVERIFIED + + if valid_until < time.time(): + del self._sessions[key] + elif self._oldest is None or valid_until < self._oldest: + self._oldest = valid_until + + self._logger.debug("App sessions after cleanup: %r" % self._sessions) +def get_remote_address(request): + forwardedFor = request.headers.get("X-Forwarded-For", None) + if forwardedFor is not None: + return forwardedFor.split(",")[0] + return request.remote_addr + +def get_json_command_from_request(request, valid_commands): + if not "application/json" in request.headers["Content-Type"]: + return None, None, make_response("Expected content-type JSON", 400) + + data = request.json + if not "command" in data.keys() or not data["command"] in valid_commands.keys(): + return None, None, make_response("Expected valid command", 400) + + command = data["command"] + for parameter in valid_commands[command]: + if not parameter in data: + return None, None, make_response("Mandatory parameter %s missing for command %s" % (parameter, command), 400) + + return command, data, None \ No newline at end of file diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index a39b565f1..deffe1c1c 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -13,9 +13,11 @@ import octoprint.timelapse import octoprint.server from octoprint.events import Events +import octoprint.printer -class PrinterStateConnection(sockjs.tornado.SockJSConnection): - def __init__(self, printer, gcodeManager, userManager, eventManager, session): + +class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback): + def __init__(self, printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session): sockjs.tornado.SockJSConnection.__init__(self, session) self._logger = logging.getLogger(__name__) @@ -28,9 +30,13 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): self._messageBacklogMutex = threading.Lock() self._printer = printer - self._gcodeManager = gcodeManager + self._fileManager = fileManager + self._analysisQueue = analysisQueue self._userManager = userManager self._eventManager = eventManager + self._pluginManager = pluginManager + + self._remoteAddress = None def _getRemoteAddress(self, info): forwardedFor = info.headers.get("X-Forwarded-For") @@ -39,36 +45,38 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): return info.ip def on_open(self, info): - remoteAddress = self._getRemoteAddress(info) - self._logger.info("New connection from client: %s" % remoteAddress) + self._remoteAddress = self._getRemoteAddress(info) + self._logger.info("New connection from client: %s" % self._remoteAddress) # connected => update the API key, might be necessary if the client was left open while the server restarted self._emit("connected", {"apikey": octoprint.server.UI_API_KEY, "version": octoprint.server.VERSION, "display_version": octoprint.server.DISPLAY_VERSION}) - self._printer.registerCallback(self) - self._gcodeManager.registerCallback(self) + self._printer.register_callback(self) + self._fileManager.register_slicingprogress_callback(self) octoprint.timelapse.registerCallback(self) + self._pluginManager.register_client(self) - self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": remoteAddress}) + self._eventManager.fire(Events.CLIENT_OPENED, {"remoteAddress": self._remoteAddress}) for event in octoprint.events.all_events(): self._eventManager.subscribe(event, self._onEvent) octoprint.timelapse.notifyCallbacks(octoprint.timelapse.current) def on_close(self): - self._logger.info("Client connection closed") - self._printer.unregisterCallback(self) - self._gcodeManager.unregisterCallback(self) + self._logger.info("Client connection closed: %s" % self._remoteAddress) + self._printer.unregister_callback(self) + self._fileManager.unregister_slicingprogress_callback(self) octoprint.timelapse.unregisterCallback(self) + self._pluginManager.unregister_client(self) - self._eventManager.fire(Events.CLIENT_CLOSED) + self._eventManager.fire(Events.CLIENT_CLOSED, {"remoteAddress": self._remoteAddress}) for event in octoprint.events.all_events(): self._eventManager.unsubscribe(event, self._onEvent) def on_message(self, message): pass - def sendCurrentData(self, data): + def on_printer_send_current_data(self, data): # add current temperature, log and message backlogs to sent data with self._temperatureBacklogMutex: temperatures = self._temperatureBacklog @@ -82,34 +90,47 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): messages = self._messageBacklog self._messageBacklog = [] + busy_files = [dict(origin=v[0], name=v[1]) for v in self._fileManager.get_busy_files()] + if "job" in data and data["job"] is not None \ + and "file" in data["job"] and "name" in data["job"]["file"] and "origin" in data["job"]["file"] \ + and data["job"]["file"]["name"] is not None and data["job"]["file"]["origin"] is not None \ + and (self._printer.is_printing() or self._printer.is_paused()): + busy_files.append(dict(origin=data["job"]["file"]["origin"], name=data["job"]["file"]["name"])) + data.update({ - "temps": temperatures, - "logs": logs, - "messages": messages + "temps": temperatures, + "logs": logs, + "messages": messages, + "busyFiles": busy_files, }) self._emit("current", data) - def sendHistoryData(self, data): + def on_printer_send_initial_data(self, data): self._emit("history", data) def sendEvent(self, type, payload=None): self._emit("event", {"type": type, "payload": payload}) - def sendFeedbackCommandOutput(self, name, output): - self._emit("feedbackCommandOutput", {"name": name, "output": output}) - def sendTimelapseConfig(self, timelapseConfig): self._emit("timelapse", timelapseConfig) - def addLog(self, data): + def sendSlicingProgress(self, slicer, source_location, source_path, dest_location, dest_path, progress): + self._emit("slicingProgress", + dict(slicer=slicer, source_location=source_location, source_path=source_path, dest_location=dest_location, dest_path=dest_path, progress=progress) + ) + + def sendPluginMessage(self, plugin, data): + self._emit("plugin", dict(plugin=plugin, data=data)) + + def on_printer_add_log(self, data): with self._logBacklogMutex: self._logBacklog.append(data) - def addMessage(self, data): + def on_printer_add_message(self, data): with self._messageBacklogMutex: self._messageBacklog.append(data) - def addTemperature(self, data): + def on_printer_add_temperature(self, data): with self._temperatureBacklogMutex: self._temperatureBacklog.append(data) @@ -117,4 +138,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): self.sendEvent(event, payload) def _emit(self, type, payload): - self.send({type: payload}) + try: + self.send({type: payload}) + except Exception as e: + self._logger.warn("Could not send message to client %s: %s" % (self._remoteAddress, e.message)) diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index b88fe27e8..399dd4d70 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -24,10 +24,41 @@ import tornado.httpclient import tornado.http1connection import tornado.iostream import tornado.tcpserver +import tornado.util import octoprint.util +#~~ Monkey patching + + +def fix_ioloop_scheduling(): + """ + This monkey patches tornado's :meth:`tornado.ioloop.PeriodicCallback._schedule_next` method so it no longer + blocks for long times on slow machines (RPi) when the system time happens to change by a large amount (e.g. due to + the first ever contact to an NTP server). + + Patch by @nosyjoe on Github. See this PR against tornado: https://github.com/tornadoweb/tornado/pull/1290 + """ + + import math + + # patched implementation taken from PR + def _schedule_next(self): + if self._running: + current_time = self.io_loop.time() + + if self._next_timeout <= current_time: + callback_time_sec = self.callback_time / 1000.0 + self._next_timeout += (math.floor((current_time - self._next_timeout) / callback_time_sec) + 1) * callback_time_sec + + self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run) + + # replace original implementation with patched version + import tornado.ioloop + tornado.ioloop.PeriodicCallback._schedule_next = _schedule_next + + #~~ WSGI middleware @@ -193,7 +224,8 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): end_of_header = None if delimiter_loc != -1: # found the delimiter in the currently available data - data, self._buffer = data[0:delimiter_loc], data[delimiter_loc:] + delimiter_data_end = 0 if delimiter_loc == 0 else delimiter_loc - 2 + data, self._buffer = data[0:delimiter_data_end], data[delimiter_loc:] end_of_header = self._buffer.find("\r\n\r\n") else: # make sure any boundary (with single or double ==) contained at the end of chunk does not get @@ -338,7 +370,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): if "content_type" in part and part["content_type"] is not None: self._new_body += b"Content-Type: %s\r\n" % part["content_type"] self._new_body += b"\r\n" - self._new_body += value + self._new_body += value + b"\r\n" self._new_body += b"--%s--\r\n" % self._multipart_boundary def _handle_method(self, *args, **kwargs): @@ -371,7 +403,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler): finally: # make sure the temporary files are removed again for f in self._files: - octoprint.util.silentRemove(f) + octoprint.util.silent_remove(f) # make all http methods trigger _handle_method get = _handle_method @@ -707,8 +739,6 @@ class CustomHTTP1ConnectionParameters(tornado.http1connection.HTTP1ConnectionPar class LargeResponseHandler(tornado.web.StaticFileHandler): - CHUNK_SIZE = 16 * 1024 - def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None): tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename) self._as_attachment = as_attachment @@ -717,70 +747,18 @@ class LargeResponseHandler(tornado.web.StaticFileHandler): def get(self, path, include_body=True): if self._access_validation is not None: self._access_validation(self.request) - - path = self.parse_url_path(path) - abspath = os.path.abspath(os.path.join(self.root, path)) - # os.path.abspath strips a trailing / - # it needs to be temporarily added back for requests to root/ - if not (abspath + os.path.sep).startswith(self.root): - raise tornado.web.HTTPError(403, "%s is not in root static directory", path) - if os.path.isdir(abspath) and self.default_filename is not None: - # need to look at the request.path here for when path is empty - # but there is some prefix to the path that was already - # trimmed by the routing - if not self.request.path.endswith("/"): - self.redirect(self.request.path + "/") - return - abspath = os.path.join(abspath, self.default_filename) - if not os.path.exists(abspath): - raise tornado.web.HTTPError(404) - if not os.path.isfile(abspath): - raise tornado.web.HTTPError(403, "%s is not a file", path) - - stat_result = os.stat(abspath) - modified = datetime.datetime.fromtimestamp(stat_result[stat.ST_MTIME]) - - self.set_header("Last-Modified", modified) - - mime_type, encoding = mimetypes.guess_type(abspath) - if mime_type: - self.set_header("Content-Type", mime_type) - - cache_time = self.get_cache_time(path, modified, mime_type) - - if cache_time > 0: - self.set_header("Expires", datetime.datetime.utcnow() + - datetime.timedelta(seconds=cache_time)) - self.set_header("Cache-Control", "max-age=" + str(cache_time)) - - self.set_extra_headers(path) - - # Check the If-Modified-Since, and don't send the result if the - # content has not been modified - ims_value = self.request.headers.get("If-Modified-Since") - if ims_value is not None: - date_tuple = email.utils.parsedate(ims_value) - if_since = datetime.datetime.fromtimestamp(time.mktime(date_tuple)) - if if_since >= modified: - self.set_status(304) - return - - if not include_body: - assert self.request.method == "HEAD" - self.set_header("Content-Length", stat_result[stat.ST_SIZE]) - else: - with open(abspath, "rb") as file: - while True: - data = file.read(LargeResponseHandler.CHUNK_SIZE) - if not data: - break - self.write(data) - self.flush() + result = tornado.web.StaticFileHandler.get(self, path, include_body=include_body) + return result def set_extra_headers(self, path): if self._as_attachment: self.set_header("Content-Disposition", "attachment") + @classmethod + def get_content_version(cls, abspath): + import os + import stat + return os.stat(abspath)[stat.ST_MTIME] ##~~ URL Forward Handler for forwarding requests to a preconfigured static URL diff --git a/src/octoprint/server/util/watchdog.py b/src/octoprint/server/util/watchdog.py index e6ced528e..2375fbc21 100644 --- a/src/octoprint/server/util/watchdog.py +++ b/src/octoprint/server/util/watchdog.py @@ -6,31 +6,10 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging -import os import watchdog.events -import octoprint.gcodefiles +import octoprint.filemanager import octoprint.util -from octoprint.settings import settings - - -class UploadCleanupWatchdogHandler(watchdog.events.PatternMatchingEventHandler): - """ - Takes care of automatically deleting metadata entries for files that get deleted from the uploads folder - """ - - patterns = map(lambda x: "*.%s" % x, octoprint.gcodefiles.GCODE_EXTENSIONS) - - def __init__(self, gcode_manager): - watchdog.events.PatternMatchingEventHandler.__init__(self) - self._gcode_manager = gcode_manager - - def on_deleted(self, event): - filename = self._gcode_manager._getBasicFilename(event.src_path) - if not filename: - return - - self._gcode_manager.removeFileFromMetadata(filename) class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): @@ -38,32 +17,33 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): Takes care of automatically "uploading" files that get added to the watched folder. """ - patterns = map(lambda x: "*.%s" % x, octoprint.gcodefiles.SUPPORTED_EXTENSIONS) + patterns = map(lambda x: "*.%s" % x, octoprint.filemanager.get_all_extensions()) - def __init__(self, gcodeManager, printer): + def __init__(self, file_manager, printer): watchdog.events.PatternMatchingEventHandler.__init__(self) self._logger = logging.getLogger(__name__) - self._gcodeManager = gcodeManager + self._file_manager = file_manager self._printer = printer def _upload(self, path): class WatchdogFileWrapper(object): def __init__(self, path): + import os self._path = path self.filename = os.path.basename(self._path) def save(self, target): - octoprint.util.safeRename(self._path, target) + octoprint.util.safe_rename(self._path, target) - fileWrapper = WatchdogFileWrapper(path) + file_wrapper = WatchdogFileWrapper(path) # determine current job currentFilename = None currentOrigin = None - currentJob = self._printer.getCurrentJob() + currentJob = self._printer.get_current_job() if currentJob is not None and "file" in currentJob.keys(): currentJobFile = currentJob["file"] if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys(): @@ -71,17 +51,35 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): currentOrigin = currentJobFile["origin"] # determine future filename of file to be uploaded, abort if it can't be uploaded - futureFilename = self._gcodeManager.getFutureFilename(fileWrapper) - if futureFilename is None or (not settings().getBoolean(["cura", "enabled"]) and not octoprint.gcodefiles.isGcodeFileName(futureFilename)): - self._logger.warn("Could not add %s: Invalid file" % fileWrapper.filename) + try: + futureFilename = self._file_manager.sanitize_name(octoprint.filemanager.FileDestinations.LOCAL, file_wrapper.filename) + except: + futureFilename = None + if futureFilename is None or (len(self._file_manager.registered_slicers) == 0 and not octoprint.filemanager.valid_file_type(futureFilename, type="gcode")): return # prohibit overwriting currently selected file while it's being printed - if futureFilename == currentFilename and not currentOrigin == octoprint.gcodefiles.FileDestinations.SDCARD and self._printer.isPrinting() or self._printer.isPaused(): - self._logger.warn("Could not add %s: Trying to overwrite file that is currently being printed" % fileWrapper.filename) + if futureFilename == currentFilename and currentOrigin == octoprint.filemanager.FileDestinations.LOCAL and self._printer.is_printing() or self._printer.is_paused(): return - self._gcodeManager.addFile(fileWrapper, octoprint.gcodefiles.FileDestinations.LOCAL) + added_file = self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL, + file_wrapper.filename, + file_wrapper, + allow_overwrite=True) + if added_file is None: + return + + slicer_name = self._file_manager.default_slicer + if octoprint.filemanager.valid_file_type(added_file, "stl") and slicer_name: + # if it's an STL we now have to slice it before we can continue + import os + name, ext = os.path.splitext(added_file) + gcode_path = name + ".gco" + self._file_manager.slice(slicer_name, + octoprint.filemanager.FileDestinations.LOCAL, + added_file, + octoprint.filemanager.FileDestinations.LOCAL, + gcode_path) def on_created(self, event): self._upload(event.src_path) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 8197dfa54..25f92de4a 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -1,6 +1,27 @@ # coding=utf-8 +""" +This module represents OctoPrint's settings management. Within this module the default settings for the core +application are defined and the instance of the :class:`Settings` is held, which offers getter and setter +methods for the raw configuration values as well as various convenience methods to access the paths to base folders +of various types and the configuration file itself. + +.. autodata:: default_settings + :annotation: = dict(...) + +.. autodata:: valid_boolean_trues + +.. autofunction:: settings + +.. autoclass:: Settings + :members: + :undoc-members: +""" + +from __future__ import absolute_import + __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import sys import os @@ -9,18 +30,44 @@ import logging import re import uuid -APPNAME="OctoPrint" +_APPNAME = "OctoPrint" -instance = None +_instance = None -def settings(init=False, configfile=None, basedir=None): - global instance - if instance is None: +def settings(init=False, basedir=None, configfile=None): + """ + Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.settings.Settings` + singleton. + + Arguments: + init (boolean): A flag indicating whether this is the initial call to construct the singleton (True) or not + (False, default). If this is set to True and the plugin manager has already been initialized, a :class:`ValueError` + will be raised. The same will happen if the plugin manager has not yet been initialized and this is set to + False. + basedir (str): Path of the base directoy for all of OctoPrint's settings, log files, uploads etc. If not set + the default will be used: ``~/.octoprint`` on Linux, ``%APPDATA%/OctoPrint`` on Windows and + ``~/Library/Application Support/OctoPrint`` on MacOS. + configfile (str): Path of the configuration file (``config.yaml``) to work on. If not set the default will + be used: ``/config.yaml`` for ``basedir`` as defined above. + + Returns: + Settings: The fully initialized :class:`Settings` instance. + + Raises: + ValueError: ``init`` is True but settings are already initialized or vice versa. + """ + global _instance + if _instance is not None: if init: - instance = Settings(configfile, basedir) + raise ValueError("Settings Manager already initialized") + + else: + if init: + _instance = Settings(configfile=configfile, basedir=basedir) else: raise ValueError("Settings not initialized yet") - return instance + + return _instance default_settings = { "serial": { @@ -30,8 +77,8 @@ default_settings = { "log": False, "timeout": { "detection": 0.5, - "connection": 2, - "communication": 5, + "connection": 10, + "communication": 30, "temperature": 5, "sdStatus": 1 }, @@ -41,16 +88,19 @@ default_settings = { "host": "0.0.0.0", "port": 5000, "firstRun": True, + "secretKey": None, "reverseProxy": { "prefixHeader": "X-Script-Name", "schemeHeader": "X-Scheme", + "hostHeader": "X-Forwarded-Host", "prefixFallback": "", - "schemeFallback": "" + "schemeFallback": "", + "hostFallback": "" }, "uploads": { "maxSize": 1 * 1024 * 1024 * 1024, # 1GB - "nameSuffix": ".name", - "pathSuffix": ".path" + "nameSuffix": "name", + "pathSuffix": "path" }, "maxSize": 100 * 1024, # 100 KB }, @@ -58,6 +108,7 @@ default_settings = { "stream": None, "snapshot": None, "ffmpeg": None, + "ffmpegThreads": 1, "bitrate": "5000k", "watermark": True, "flipH": False, @@ -65,7 +116,8 @@ default_settings = { "timelapse": { "type": "off", "options": {}, - "postRoll": 0 + "postRoll": 0, + "fps": 25 } }, "gcodeViewer": { @@ -83,7 +135,8 @@ default_settings = { "sdSupport": True, "sdAlwaysAvailable": False, "swallowOkAfterResend": True, - "repetierTargetTemp": False + "repetierTargetTemp": False, + "keyboardControl": True }, "folder": { "uploads": None, @@ -92,36 +145,49 @@ default_settings = { "logs": None, "virtualSd": None, "watched": None, - "plugins": None + "plugins": None, + "slicingProfiles": None, + "printerProfiles": None, + "scripts": None }, "temperature": { - "profiles": - [ - {"name": "ABS", "extruder" : 210, "bed" : 100 }, - {"name": "PLA", "extruder" : 180, "bed" : 60 } - ] + "profiles": [ + {"name": "ABS", "extruder" : 210, "bed" : 100 }, + {"name": "PLA", "extruder" : 180, "bed" : 60 } + ] + }, + "printerProfiles": { + "default": None, + "defaultProfile": {} }, "printerParameters": { - "movementSpeed": { - "x": 6000, - "y": 6000, - "z": 200, - "e": 300 - }, "pauseTriggers": [], - "invertAxes": [], - "numExtruders": 1, - "extruderOffsets": [ - {"x": 0.0, "y": 0.0} - ], - "bedDimensions": { - "x": 200.0, "y": 200.0, "r": 100 - }, "defaultExtrusionLength": 5 }, "appearance": { "name": "", - "color": "default" + "color": "default", + "colorTransparent": False, + "components": { + "order": { + "navbar": ["settings", "systemmenu", "login"], + "sidebar": ["connection", "state", "files"], + "tab": ["temperature", "control", "gcodeviewer", "terminal", "timelapse"], + "settings": [ + "section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts", + "section_features", "features", "webcam", "accesscontrol", "api", + "section_octoprint", "folders", "appearance", "logs" + ], + "generic": [] + }, + "disabled": { + "navbar": [], + "sidebar": [], + "tab": [], + "settings": [], + "generic": [] + } + } }, "controls": [], "system": { @@ -129,31 +195,41 @@ default_settings = { }, "accessControl": { "enabled": True, + "salt": None, "userManager": "octoprint.users.FilebasedUserManager", "userfile": None, "autologinLocal": False, "localNetworks": ["127.0.0.0/8"], "autologinAs": None }, - "cura": { - "enabled": False, - "path": "/default/path/to/cura", - "config": "/default/path/to/your/cura/config.ini" + "slicing": { + "enabled": True, + "defaultSlicer": "cura", + "defaultProfiles": None }, "events": { - "enabled": False, + "enabled": True, "subscriptions": [] }, "api": { - "enabled": False, - "key": ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes), - "allowCrossOrigin": False + "enabled": True, + "key": None, + "allowCrossOrigin": False, + "apps": {} }, "terminalFilters": [ { "name": "Suppress M105 requests/responses", "regex": "(Send: M105)|(Recv: ok T\d*:)" }, { "name": "Suppress M27 requests/responses", "regex": "(Send: M27)|(Recv: SD printing byte)" } ], "plugins": {}, + "scripts": { + "gcode": { + "afterPrintCancelled": "; disable motors\nM84\n\n;disable all heaters\n{% snippet 'disable_hotends' %}\nM140 S0\n\n;disable fan\nM106 S0", + "snippets": { + "disable_hotends": "{% for tool in range(printer_profile.extruder.count) %}M104 T{{ tool }} S0\n{% endfor %}" + } + } + }, "devel": { "stylesheet": "css", "virtualPrinter": { @@ -163,147 +239,387 @@ default_settings = { "okWithLinenumber": False, "numExtruders": 1, "includeCurrentToolInTemps": True, + "movementSpeed": { + "x": 6000, + "y": 6000, + "z": 200, + "e": 300 + }, "hasBed": True, "repetierStyleTargetTemperature": False, - "extendedSdFileList": False + "smoothieTemperatureReporting": False, + "extendedSdFileList": False, + "throttle": 0.01, + "waitOnLongMoves": False, + "rxBuffer": 64, + "txBuffer": 40, + "commandBuffer": 4 } } } +"""The default settings of the core application.""" valid_boolean_trues = [True, "true", "yes", "y", "1"] +""" Values that are considered to be equivalent to the boolean ``True`` value, used for type conversion in various places.""" class Settings(object): + """ + The :class:`Settings` class allows managing all of OctoPrint's settings. It takes care of initializing the settings + directory, loading the configuration from ``config.yaml``, persisting changes to disk etc and provides access + methods for getting and setting specific values from the overall settings structure via paths. + + A general word on the concept of paths, since they play an important role in OctoPrint's settings management. A + path is basically a list or tuple consisting of keys to follow down into the settings (which are basically like + a ``dict``) in order to set or retrieve a specific value (or more than one). For example, for a settings + structure like the following:: + + serial: + port: "/dev/ttyACM0" + baudrate: 250000 + timeouts: + communication: 20.0 + temperature: 5.0 + sdStatus: 1.0 + connection: 10.0 + server: + host: "0.0.0.0" + port: 5000 + + the following paths could be used: + + ========================================== ============================================================================ + Path Value + ========================================== ============================================================================ + ``["serial", "port"]`` :: + + "/dev/ttyACM0" + + ``["serial", "timeouts"]`` :: + + communication: 20.0 + temperature: 5.0 + sdStatus: 1.0 + connection: 10.0 + + ``["serial", "timeouts", "temperature"]`` :: + + 5.0 + + ``["server", "port"]`` :: + + 5000 + + ========================================== ============================================================================ + + However, these would be invalid paths: ``["key"]``, ``["serial", "port", "value"]``, ``["server", "host", 3]``. + """ def __init__(self, configfile=None, basedir=None): self._logger = logging.getLogger(__name__) - self.settings_dir = None + self._basedir = None self._config = None self._dirty = False + self._mtime = None - self._init_settings_dir(basedir) + self._get_preprocessors = dict( + controls=self._process_custom_controls + ) + self._set_preprocessors = dict() + + self._init_basedir(basedir) if configfile is not None: self._configfile = configfile else: - self._configfile = os.path.join(self.settings_dir, "config.yaml") + self._configfile = os.path.join(self._basedir, "config.yaml") self.load(migrate=True) - def _init_settings_dir(self, basedir): - if basedir is not None: - self.settings_dir = basedir - else: - self.settings_dir = _resolveSettingsDir(APPNAME) + if self.get(["api", "key"]) is None: + self.set(["api", "key"], ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)) + self.save(force=True) - def _getDefaultFolder(self, type): + self._script_env = self._init_script_templating() + + def _init_basedir(self, basedir): + if basedir is not None: + self._basedir = basedir + else: + self._basedir = _default_basedir(_APPNAME) + + if not os.path.isdir(self._basedir): + os.makedirs(self._basedir) + + def _get_default_folder(self, type): folder = default_settings["folder"][type] if folder is None: - folder = os.path.join(self.settings_dir, type.replace("_", os.path.sep)) + folder = os.path.join(self._basedir, type.replace("_", os.path.sep)) return folder + def _init_script_templating(self): + from jinja2 import Environment, BaseLoader, FileSystemLoader, ChoiceLoader, TemplateNotFound + from jinja2.nodes import Include, Const + from jinja2.ext import Extension + + class SnippetExtension(Extension): + tags = {"snippet"} + fields = Include.fields + + def parse(self, parser): + node = parser.parse_include() + if not node.template.value.startswith("/"): + node.template.value = "snippets/" + node.template.value + return node + + class SettingsScriptLoader(BaseLoader): + def __init__(self, s): + self._settings = s + + def get_source(self, environment, template): + parts = template.split("/") + if not len(parts): + raise TemplateNotFound(template) + + script = self._settings.get(["scripts"], merged=True) + for part in parts: + if isinstance(script, dict) and part in script: + script = script[part] + else: + raise TemplateNotFound(template) + source = script + if source is None: + raise TemplateNotFound(template) + mtime = self._settings._mtime + return source, None, lambda: mtime == self._settings._last_modified + + def list_templates(self): + scripts = self._settings.get(["scripts"], merged=True) + return self._get_templates(scripts) + + def _get_templates(self, scripts): + templates = [] + for key in scripts: + if isinstance(scripts[key], dict): + templates += map(lambda x: key + "/" + x, self._get_templates(scripts[key])) + elif isinstance(scripts[key], basestring): + templates.append(key) + return templates + + class SelectLoader(BaseLoader): + def __init__(self, default, mapping, sep=":"): + self._default = default + self._mapping = mapping + self._sep = sep + + def get_source(self, environment, template): + if self._sep in template: + prefix, name = template.split(self._sep, 1) + if not prefix in self._mapping: + raise TemplateNotFound(template) + return self._mapping[prefix].get_source(environment, name) + return self._default.get_source(environment, template) + + def list_templates(self): + return self._default.list_templates() + + class RelEnvironment(Environment): + def __init__(self, prefix_sep=":", *args, **kwargs): + Environment.__init__(self, *args, **kwargs) + self._prefix_sep = prefix_sep + + def join_path(self, template, parent): + prefix, name = self._split_prefix(template) + + if name.startswith("/"): + return self._join_prefix(prefix, name[1:]) + else: + _, parent_name = self._split_prefix(parent) + parent_base = parent_name.split("/")[:-1] + return self._join_prefix(prefix, "/".join(parent_base) + "/" + name) + + def _split_prefix(self, template): + if self._prefix_sep in template: + return template.split(self._prefix_sep, 1) + else: + return "", template + + def _join_prefix(self, prefix, template): + if len(prefix): + return prefix + self._prefix_sep + template + else: + return template + + file_system_loader = FileSystemLoader(self.getBaseFolder("scripts")) + settings_loader = SettingsScriptLoader(self) + choice_loader = ChoiceLoader([file_system_loader, settings_loader]) + select_loader = SelectLoader(choice_loader, dict(bundled=settings_loader, file=file_system_loader)) + return RelEnvironment(loader=select_loader, extensions=[SnippetExtension]) + + def _get_script_template(self, script_type, name, source=False): + from jinja2 import TemplateNotFound + + template_name = script_type + "/" + name + try: + if source: + template_name, _, _ = self._script_env.loader.get_source(self._script_env, template_name) + return template_name + else: + return self._script_env.get_template(template_name) + except TemplateNotFound: + return None + except: + self._logger.exception("Exception while trying to resolve template {template_name}".format(**locals())) + return None + + def _get_scripts(self, script_type): + return self._script_env.list_templates(filter_func=lambda x: x.startswith(script_type+"/")) + + def _process_custom_controls(self, controls): + def process_control(c): + # shallow copy + result = dict(c) + + if "regex" in result and "template" in result: + # if it's a template matcher, we need to add a key to associate with the matcher output + import hashlib + key_hash = hashlib.md5() + key_hash.update(result["regex"]) + result["key"] = key_hash.hexdigest() + + template_key_hash = hashlib.md5() + template_key_hash.update(result["template"]) + result["template_key"] = template_key_hash.hexdigest() + + elif "children" in result: + # if it has children we need to process them recursively + result["children"] = map(process_control, result["children"]) + + return result + + return map(process_control, controls) + #~~ load and save def load(self, migrate=False): if os.path.exists(self._configfile) and os.path.isfile(self._configfile): with open(self._configfile, "r") as f: self._config = yaml.safe_load(f) + self._mtime = self._last_modified # changed from else to handle cases where the file exists, but is empty / 0 bytes if not self._config: self._config = {} if migrate: - self._migrateConfig() + self._migrate_config() - def _migrateConfig(self): - if not self._config: - return + def _migrate_config(self): + dirty = False - if "events" in self._config.keys() and ("gcodeCommandTrigger" in self._config["events"] or "systemCommandTrigger" in self._config["events"]): - self._logger.info("Migrating config (event subscriptions)...") + migrators = ( + self._migrate_event_config, + self._migrate_reverse_proxy_config, + self._migrate_printer_parameters, + self._migrate_gcode_scripts + ) - # migrate event hooks to new format - placeholderRe = re.compile("%\((.*?)\)s") - - eventNameReplacements = { - "ClientOpen": "ClientOpened", - "TransferStart": "TransferStarted" - } - payloadDataReplacements = { - "Upload": {"data": "{file}", "filename": "{file}"}, - "Connected": {"data": "{port} at {baudrate} baud"}, - "FileSelected": {"data": "{file}", "filename": "{file}"}, - "TransferStarted": {"data": "{remote}", "filename": "{remote}"}, - "TransferDone": {"data": "{remote}", "filename": "{remote}"}, - "ZChange": {"data": "{new}"}, - "CaptureStart": {"data": "{file}"}, - "CaptureDone": {"data": "{file}"}, - "MovieDone": {"data": "{movie}", "filename": "{gcode}"}, - "Error": {"data": "{error}"}, - "PrintStarted": {"data": "{file}", "filename": "{file}"}, - "PrintDone": {"data": "{file}", "filename": "{file}"}, - } - - def migrateEventHook(event, command): - # migrate placeholders - command = placeholderRe.sub("{__\\1}", command) - - # migrate event names - if event in eventNameReplacements: - event = eventNameReplacements["event"] - - # migrate payloads to more specific placeholders - if event in payloadDataReplacements: - for key in payloadDataReplacements[event]: - command = command.replace("{__%s}" % key, payloadDataReplacements[event][key]) - - # return processed tuple - return event, command - - disableSystemCommands = False - if "systemCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["systemCommandTrigger"]: - disableSystemCommands = not self._config["events"]["systemCommandTrigger"]["enabled"] - - disableGcodeCommands = False - if "gcodeCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["gcodeCommandTrigger"]: - disableGcodeCommands = not self._config["events"]["gcodeCommandTrigger"]["enabled"] - - disableAllCommands = disableSystemCommands and disableGcodeCommands - newEvents = { - "enabled": not disableAllCommands, - "subscriptions": [] - } - - if "systemCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["systemCommandTrigger"]: - for trigger in self._config["events"]["systemCommandTrigger"]["subscriptions"]: - if not ("event" in trigger and "command" in trigger): - continue - - newTrigger = {"type": "system"} - if disableSystemCommands and not disableAllCommands: - newTrigger["enabled"] = False - - newTrigger["event"], newTrigger["command"] = migrateEventHook(trigger["event"], trigger["command"]) - newEvents["subscriptions"].append(newTrigger) - - if "gcodeCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["gcodeCommandTrigger"]: - for trigger in self._config["events"]["gcodeCommandTrigger"]["subscriptions"]: - if not ("event" in trigger and "command" in trigger): - continue - - newTrigger = {"type": "gcode"} - if disableGcodeCommands and not disableAllCommands: - newTrigger["enabled"] = False - - newTrigger["event"], newTrigger["command"] = migrateEventHook(trigger["event"], trigger["command"]) - newTrigger["command"] = newTrigger["command"].split(",") - newEvents["subscriptions"].append(newTrigger) - - self._config["events"] = newEvents + for migrate in migrators: + dirty = migrate() or dirty + if dirty: self.save(force=True) - self._logger.info("Migrated %d event subscriptions to new format and structure" % len(newEvents["subscriptions"])) + + def _migrate_gcode_scripts(self): + """ + Migrates an old development version of gcode scripts to the new template based format. + """ + + dirty = False + if "scripts" in self._config: + if "gcode" in self._config["scripts"]: + if "templates" in self._config["scripts"]["gcode"]: + del self._config["scripts"]["gcode"]["templates"] + + replacements = dict( + disable_steppers="M84", + disable_hotends="{% snippet 'disable_hotends' %}", + disable_bed="M140 S0", + disable_fan="M106 S0" + ) + + for name, script in self._config["scripts"]["gcode"].items(): + self.saveScript("gcode", name, script.format(**replacements)) + del self._config["scripts"] + dirty = True + return dirty + + def _migrate_printer_parameters(self): + """ + Migrates the old "printer > parameters" data structure to the new printer profile mechanism. + """ + default_profile = self._config["printerProfiles"]["defaultProfile"] if "printerProfiles" in self._config and "defaultProfile" in self._config["printerProfiles"] else dict() + dirty = False + + if "printerParameters" in self._config: + printer_parameters = self._config["printerParameters"] + + if "movementSpeed" in printer_parameters or "invertAxes" in printer_parameters: + default_profile["axes"] = dict(x=dict(), y=dict(), z=dict(), e=dict()) + if "movementSpeed" in printer_parameters: + for axis in ("x", "y", "z", "e"): + if axis in printer_parameters["movementSpeed"]: + default_profile["axes"][axis]["speed"] = printer_parameters["movementSpeed"][axis] + del self._config["printerParameters"]["movementSpeed"] + if "invertedAxes" in printer_parameters: + for axis in ("x", "y", "z", "e"): + if axis in printer_parameters["invertedAxes"]: + default_profile["axes"][axis]["inverted"] = True + del self._config["printerParameters"]["invertedAxes"] + + if "numExtruders" in printer_parameters or "extruderOffsets" in printer_parameters: + if not "extruder" in default_profile: + default_profile["extruder"] = dict() + + if "numExtruders" in printer_parameters: + default_profile["extruder"]["count"] = printer_parameters["numExtruders"] + del self._config["printerParameters"]["numExtruders"] + if "extruderOffsets" in printer_parameters: + extruder_offsets = [] + for offset in printer_parameters["extruderOffsets"]: + if "x" in offset and "y" in offset: + extruder_offsets.append((offset["x"], offset["y"])) + default_profile["extruder"]["offsets"] = extruder_offsets + del self._config["printerParameters"]["extruderOffsets"] + + if "bedDimensions" in printer_parameters: + bed_dimensions = printer_parameters["bedDimensions"] + if not "volume" in default_profile: + default_profile["volume"] = dict() + + if "circular" in bed_dimensions and "r" in bed_dimensions and bed_dimensions["circular"]: + default_profile["volume"]["formFactor"] = "circular" + default_profile["volume"]["width"] = 2 * bed_dimensions["r"] + default_profile["volume"]["depth"] = default_profile["volume"]["width"] + elif "x" in bed_dimensions or "y" in bed_dimensions: + default_profile["volume"]["formFactor"] = "rectangular" + if "x" in bed_dimensions: + default_profile["volume"]["width"] = bed_dimensions["x"] + if "y" in bed_dimensions: + default_profile["volume"]["depth"] = bed_dimensions["y"] + del self._config["printerParameters"]["bedDimensions"] + + dirty = True + + if dirty: + if not "printerProfiles" in self._config: + self._config["printerProfiles"] = dict() + self._config["printerProfiles"]["defaultProfile"] = default_profile + return dirty def _migrate_reverse_proxy_config(self): + """ + Migrates the old "server > baseUrl" and "server > scheme" configuration entries to + "server > reverseProxy > prefixFallback" and "server > reverseProxy > schemeFallback". + """ if "server" in self._config.keys() and ("baseUrl" in self._config["server"] or "scheme" in self._config["server"]): prefix = "" if "baseUrl" in self._config["server"]: @@ -327,6 +643,10 @@ class Settings(object): return False def _migrate_event_config(self): + """ + Migrates the old event configuration format of type "events > gcodeCommandTrigger" and + "event > systemCommandTrigger" to the new events format. + """ if "events" in self._config.keys() and ("gcodeCommandTrigger" in self._config["events"] or "systemCommandTrigger" in self._config["events"]): self._logger.info("Migrating config (event subscriptions)...") @@ -415,34 +735,52 @@ class Settings(object): def save(self, force=False): if not self._dirty and not force: - return + return False with open(self._configfile, "wb") as configFile: yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=" ", allow_unicode=True) self._dirty = False self.load() + return True + + @property + def _last_modified(self): + """ + Returns: + int: The last modification time of the configuration file. + """ + stat = os.stat(self._configfile) + return stat.st_mtime #~~ getter - def get(self, path, asdict=False, defaults=None): + def get(self, path, asdict=False, defaults=None, preprocessors=None, merged=False): + import octoprint.util as util + if len(path) == 0: return None config = self._config if defaults is None: defaults = default_settings + if preprocessors is None: + preprocessors = self._get_preprocessors while len(path) > 1: key = path.pop(0) - if key in config.keys() and key in defaults.keys(): + if key in config and key in defaults: config = config[key] defaults = defaults[key] - elif key in defaults.keys(): + elif key in defaults: config = {} defaults = defaults[key] else: return None + if preprocessors and isinstance(preprocessors, dict) and key in preprocessors: + preprocessors = preprocessors[key] + + k = path.pop(0) if not isinstance(k, (list, tuple)): keys = [k] @@ -454,13 +792,18 @@ class Settings(object): else: results = [] for key in keys: - if key in config.keys(): + if key in config: value = config[key] + if merged and key in defaults: + value = util.dict_merge(defaults[key], value) elif key in defaults: value = defaults[key] else: value = None + if preprocessors and isinstance(preprocessors, dict) and key in preprocessors and callable(preprocessors[key]): + value = preprocessors[key](value) + if asdict: results[key] = value else: @@ -474,8 +817,8 @@ class Settings(object): else: return results - def getInt(self, path, defaults=None): - value = self.get(path, defaults=defaults) + def getInt(self, path, defaults=None, preprocessors=None): + value = self.get(path, defaults=defaults, preprocessors=preprocessors) if value is None: return None @@ -485,8 +828,8 @@ class Settings(object): self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path)) return None - def getFloat(self, path, defaults=None): - value = self.get(path, defaults=defaults) + def getFloat(self, path, defaults=None, preprocessors=None): + value = self.get(path, defaults=defaults, preprocessors=preprocessors) if value is None: return None @@ -496,8 +839,8 @@ class Settings(object): self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path)) return None - def getBoolean(self, path, defaults=None): - value = self.get(path, defaults=defaults) + def getBoolean(self, path, defaults=None, preprocessors=None): + value = self.get(path, defaults=defaults, preprocessors=preprocessors) if value is None: return None if isinstance(value, bool): @@ -508,76 +851,62 @@ class Settings(object): return value.lower() in valid_boolean_trues return value is not None - def getBaseFolder(self, type): - if type not in default_settings["folder"].keys(): + def getBaseFolder(self, type, create=True): + if type not in default_settings["folder"].keys() + ["base"]: return None + if type == "base": + return self._basedir + folder = self.get(["folder", type]) if folder is None: - folder = self._getDefaultFolder(type) + folder = self._get_default_folder(type) if not os.path.isdir(folder): - os.makedirs(folder) + if create: + os.makedirs(folder) + else: + raise IOError("No such folder: {folder}".format(folder=folder)) return folder - def getFeedbackControls(self): - feedbackControls = [] - for control in self.get(["controls"]): - feedbackControls.extend(self._getFeedbackControls(control)) - return feedbackControls + def listScripts(self, script_type): + return map(lambda x: x[len(script_type + "/"):], filter(lambda x: x.startswith(script_type + "/"), self._get_scripts(script_type))) - def _getFeedbackControls(self, control=None): - if control["type"] == "feedback_command" or control["type"] == "feedback": - pattern = control["regex"] - try: - matcher = re.compile(pattern) - return [(control["name"], matcher, control["template"])] - except: - # invalid regex or something like this, we'll just skip this entry - pass - elif control["type"] == "section": - result = [] - for c in control["children"]: - result.extend(self._getFeedbackControls(c)) - return result + def loadScript(self, script_type, name, context=None, source=False): + if context is None: + context = dict() + context.update(dict(script=dict(type=script_type, name=name))) + + template = self._get_script_template(script_type, name, source=source) + if template is None: + return None + + if source: + script = template else: - return [] - - def getPauseTriggers(self): - triggers = { - "enable": [], - "disable": [], - "toggle": [] - } - for trigger in self.get(["printerParameters", "pauseTriggers"]): try: - regex = trigger["regex"] - type = trigger["type"] - if type in triggers.keys(): - # make sure regex is valid - re.compile(regex) - # add to type list - triggers[type].append(regex) + script = template.render(**context) except: - # invalid regex or something like this, we'll just skip this entry - pass + self._logger.exception("Exception while trying to render script {script_type}:{name}".format(**locals())) + return None - result = {} - for type in triggers.keys(): - if len(triggers[type]) > 0: - result[type] = re.compile("|".join(map(lambda x: "(%s)" % x, triggers[type]))) - return result + return script #~~ setter - def set(self, path, value, force=False, defaults=None): + def set(self, path, value, force=False, defaults=None, preprocessors=None): if len(path) == 0: return + if self._mtime is not None and self._last_modified != self._mtime: + self.load() + config = self._config if defaults is None: defaults = default_settings + if preprocessors is None: + preprocessors = self._set_preprocessors while len(path) > 1: key = path.pop(0) @@ -591,20 +920,27 @@ class Settings(object): else: return + if preprocessors and isinstance(preprocessors, dict) and key in preprocessors: + preprocessors = preprocessors[key] + key = path.pop(0) - if not force and key in defaults.keys() and key in config.keys() and defaults[key] == value: + + if preprocessors and isinstance(preprocessors, dict) and key in preprocessors and callable(preprocessors[key]): + value = preprocessors[key](value) + + if not force and key in defaults and key in config and defaults[key] == value: del config[key] self._dirty = True - elif force or (not key in config.keys() and defaults[key] != value) or (key in config.keys() and config[key] != value): + elif force or (not key in config and defaults[key] != value) or (key in config and config[key] != value): if value is None: del config[key] else: config[key] = value self._dirty = True - def setInt(self, path, value, force=False, defaults=None): + def setInt(self, path, value, force=False, defaults=None, preprocessors=None): if value is None: - self.set(path, None, force=force, defaults=defaults) + self.set(path, None, force=force, defaults=defaults, preprocessors=preprocessors) return try: @@ -615,9 +951,9 @@ class Settings(object): self.set(path, intValue, force) - def setFloat(self, path, value, force=False, defaults=None): + def setFloat(self, path, value, force=False, defaults=None, preprocessors=None): if value is None: - self.set(path, None, force=force, defaults=defaults) + self.set(path, None, force=force, defaults=defaults, preprocessors=preprocessors) return try: @@ -628,20 +964,20 @@ class Settings(object): self.set(path, floatValue, force) - def setBoolean(self, path, value, force=False, defaults=None): + def setBoolean(self, path, value, force=False, defaults=None, preprocessors=None): if value is None or isinstance(value, bool): - self.set(path, value, force=force, defaults=defaults) + self.set(path, value, force=force, defaults=defaults, preprocessors=preprocessors) elif value.lower() in valid_boolean_trues: - self.set(path, True, force=force, defaults=defaults) + self.set(path, True, force=force, defaults=defaults, preprocessors=preprocessors) else: - self.set(path, False, force=force, defaults=defaults) + self.set(path, False, force=force, defaults=defaults, preprocessors=preprocessors) def setBaseFolder(self, type, path, force=False): if type not in default_settings["folder"].keys(): return None currentPath = self.getBaseFolder(type) - defaultPath = self._getDefaultFolder(type) + defaultPath = self._get_default_folder(type) if (path is None or path == defaultPath) and "folder" in self._config.keys() and type in self._config["folder"].keys(): del self._config["folder"][type] if not self._config["folder"]: @@ -653,7 +989,20 @@ class Settings(object): self._config["folder"][type] = path self._dirty = True -def _resolveSettingsDir(applicationName): + def saveScript(self, script_type, name, script): + script_folder = self.getBaseFolder("scripts") + filename = os.path.realpath(os.path.join(script_folder, script_type, name)) + if not filename.startswith(script_folder): + # oops, jail break, that shouldn't happen + raise ValueError("Invalid script path to save to: {filename} (from {script_type}:{name})".format(**locals())) + + path, _ = os.path.split(filename) + if not os.path.exists(path): + os.makedirs(path) + with open(filename, "w+") as f: + f.write(script) + +def _default_basedir(applicationName): # taken from http://stackoverflow.com/questions/1084697/how-do-i-store-desktop-application-data-in-a-cross-platform-way-for-python if sys.platform == "darwin": from AppKit import NSSearchPathForDirectoriesInDomains diff --git a/src/octoprint/slicers/__init__.py b/src/octoprint/slicers/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/octoprint/slicers/cura/__init__.py b/src/octoprint/slicers/cura/__init__.py deleted file mode 100644 index 083a3f036..000000000 --- a/src/octoprint/slicers/cura/__init__.py +++ /dev/null @@ -1,76 +0,0 @@ -import sarge - -__author__ = "Ross Hendrickson savorywatt" -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' - -import logging -import os - -from octoprint.settings import settings - -class CuraFactory(object): - - @staticmethod - def create_slicer(path=None): - """Utilizes the factory pattern to setup a CuraEngine object - - :param path: :class: `str` - """ - if path: - return Cura(path) - - current_settings = settings(init=True) - path = current_settings.get(["cura", "path"]) - - return Cura(path) - - -class Cura(object): - - def __init__(self, cura_path): - - if not cura_path: - raise Exception("Unable to create CuraEngine - no path specified") - - self.cura_path = cura_path - self._logger = logging.getLogger(__name__) - - - def process_file( - self, config, gcode, file_path, call_back=None, - call_back_args=None): - - """Wraps around the main.cpp processFile method. - - :param config: :class: `string` :path to a cura config file: - :param gcode: :class: `string :path to write out the gcode generated: - :param file_path: :class: `string :path to the STL to be sliced: - :note: This will spawn a thread to handle the subprocess call and allow - us to be able to have a call back - """ - import threading - - def start_thread(call_back, call_back_args, call_args, cwd): - self._logger.info("Running %r in %s" % (call_args, cwd)) - command = " ".join(call_args) - try: - p = sarge.run(command, cwd=cwd) - if p.returncode == 0: - call_back(*call_back_args) - else: - self._logger.warn("Could not slice via Cura, got return code %r" % p.returncode) - call_back_args.append("Got returncode %r" % p.returncode) - call_back(*call_back_args) - except: - self._logger.exception("Could not slice via Cura, got an unknown error") - call_back_args.append("Unknown error, please consult the log file") - call_back(*call_back_args) - - executable = self.cura_path - (workingDir, ignored) = os.path.split(executable) - args = [executable, '-i', config, '-s', file_path, '-o', gcode] - - thread = threading.Thread(target=start_thread, args=(call_back, - call_back_args, args, workingDir)) - - thread.start() diff --git a/src/octoprint/slicers/cura/tests/test_cura.py b/src/octoprint/slicers/cura/tests/test_cura.py deleted file mode 100644 index c9610750a..000000000 --- a/src/octoprint/slicers/cura/tests/test_cura.py +++ /dev/null @@ -1,31 +0,0 @@ - - -import unittest -from mock import patch - -from octoprint.slicers.cura import CuraFactory -from octoprint.slicers.cura import Cura - -class CuraFactoryTestCase(unittest.TestCase): - - - def test_cura_factory(self): - - fake_path = 'my/temp/path' - result = CuraFactory.create_slicer(fake_path) - - self.assertEqual(fake_path, result.cura_path) - - - @patch('threading.Thread') - def test_cura_engine_process_file(self, thread): - path = 'rosshendrickson/workspaces/opensource/CuraEngine/' - - cura = CuraFactory.create_slicer(path) - file_path = './cura/tests/test.stl' - config_path = './cura/tests/config' - gcode_filename = './cura/tests/output.gcode' - - cura.process_file(config_path, gcode_filename, file_path) - self.assertTrue(thread.called) - diff --git a/src/octoprint/slicing/__init__.py b/src/octoprint/slicing/__init__.py new file mode 100644 index 000000000..8d4848e41 --- /dev/null +++ b/src/octoprint/slicing/__init__.py @@ -0,0 +1,295 @@ +# 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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import os +import octoprint.plugin +import octoprint.events +from octoprint.settings import settings + +from .exceptions import * + + +class SlicingProfile(object): + def __init__(self, slicer, name, data, display_name=None, description=None): + self.slicer = slicer + self.name = name + self.data = data + self.display_name = display_name + self.description = description + + +class TemporaryProfile(object): + def __init__(self, save_profile, profile, overrides=None): + self.save_profile = save_profile + self.profile = profile + self.overrides = overrides + + def __enter__(self): + import tempfile + temp_profile = tempfile.NamedTemporaryFile(prefix="slicing-profile-temp-", suffix=".profile", delete=False) + temp_profile.close() + + self.temp_path = temp_profile.name + self.save_profile(self.temp_path, self.profile, overrides=self.overrides) + return self.temp_path + + def __exit__(self, type, value, traceback): + import os + try: + os.remove(self.temp_path) + except: + pass + + +class SlicingManager(object): + def __init__(self, profile_path, printer_profile_manager): + self._profile_path = profile_path + self._printer_profile_manager = printer_profile_manager + + self._slicers = dict() + self._slicer_names = dict() + + self._progress_callbacks = [] + self._last_progress_report = None + + def initialize(self): + self._load_slicers() + + def register_progress_callback(self, callback): + self._progress_callbacks.append(callback) + + def unregister_progress_callback(self, callback): + self._progress_callbacks.remove(callback) + + def _load_slicers(self): + plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin) + for name, plugin in plugins.items(): + self._slicers[plugin.get_slicer_properties()["type"]] = plugin + + @property + def slicing_enabled(self): + return len(self.configured_slicers) > 0 + + @property + def registered_slicers(self): + return self._slicers.keys() + + @property + def configured_slicers(self): + return map(lambda slicer: slicer.get_slicer_properties()["type"], filter(lambda slicer: slicer.is_slicer_configured(), self._slicers.values())) + + @property + def default_slicer(self): + slicer_name = settings().get(["slicing", "defaultSlicer"]) + if slicer_name in self.registered_slicers: + return slicer_name + else: + return None + + def get_slicer(self, slicer, require_configured=True): + if slicer in self._slicers and (not require_configured or self._slicers[slicer].is_slicer_configured()): + return self._slicers[slicer] + raise SlicerNotConfigured(slicer) + + def slice(self, slicer_name, source_path, dest_path, profile_name, callback, callback_args=None, callback_kwargs=None, overrides=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None, printer_profile_id=None, position=None): + if callback_args is None: + callback_args = () + if callback_kwargs is None: + callback_kwargs = dict() + + if not slicer_name in self.configured_slicers: + if not slicer_name in self.registered_slicers: + error = "No such slicer: {slicer_name}".format(**locals()) + exc = UnknownSlicer(slicer_name) + else: + error = "Slicer not configured: {slicer_name}".format(**locals()) + exc = SlicerNotConfigured(slicer_name) + callback_kwargs.update(dict(_error=error, _exc=exc)) + callback(*callback_args, **callback_kwargs) + raise exc + + slicer = self.get_slicer(slicer_name) + + printer_profile = None + if printer_profile_id is not None: + printer_profile = self._printer_profile_manager.get(printer_profile_id) + + if printer_profile is None: + printer_profile = self._printer_profile_manager.get_current_or_default() + + def slicer_worker(slicer, model_path, machinecode_path, profile_name, overrides, printer_profile, position, callback, callback_args, callback_kwargs): + try: + slicer_name = slicer.get_slicer_properties()["type"] + with self.temporary_profile(slicer_name, name=profile_name, overrides=overrides) as profile_path: + ok, result = slicer.do_slice( + model_path, + printer_profile, + machinecode_path=machinecode_path, + profile_path=profile_path, + position=position, + on_progress=on_progress, + on_progress_args=on_progress_args, + on_progress_kwargs=on_progress_kwargs + ) + + if not ok: + callback_kwargs.update(dict(_error=result)) + elif result is not None and isinstance(result, dict) and "analysis" in result: + callback_kwargs.update(dict(_analysis=result["analysis"])) + except SlicingCancelled: + callback_kwargs.update(dict(_cancelled=True)) + finally: + callback(*callback_args, **callback_kwargs) + + import threading + slicer_worker_thread = threading.Thread(target=slicer_worker, + args=(slicer, source_path, dest_path, profile_name, overrides, printer_profile, position, callback, callback_args, callback_kwargs)) + slicer_worker_thread.daemon = True + slicer_worker_thread.start() + return True, None + + def cancel_slicing(self, slicer_name, source_path, dest_path): + if not slicer_name in self.registered_slicers: + raise UnknownSlicer(slicer_name) + + slicer = self.get_slicer(slicer_name) + slicer.cancel_slicing(dest_path) + + def load_profile(self, slicer, name, require_configured=True): + if not slicer in self.registered_slicers: + raise UnknownSlicer(slicer) + + try: + path = self.get_profile_path(slicer, name, must_exist=True) + except IOError: + return None + return self._load_profile_from_path(slicer, path, require_configured=require_configured) + + def save_profile(self, slicer, name, profile, overrides=None, allow_overwrite=True, display_name=None, description=None): + if not slicer in self.registered_slicers: + raise UnknownSlicer(slicer) + + if not isinstance(profile, SlicingProfile): + if isinstance(profile, dict): + profile = SlicingProfile(slicer, name, profile, display_name=display_name, description=description) + else: + raise ValueError("profile must be a SlicingProfile") + else: + profile.slicer = slicer + profile.name = name + if display_name is not None: + profile.display_name = display_name + if description is not None: + profile.description = description + + path = self.get_profile_path(slicer, name) + self._save_profile_to_path(slicer, path, profile, overrides=overrides, allow_overwrite=allow_overwrite) + return profile + + def temporary_profile(self, slicer, name=None, overrides=None): + if not slicer in self.registered_slicers: + raise UnknownSlicer(slicer) + + profile = self._get_default_profile(slicer) + if name: + try: + profile = self.load_profile(slicer, name) + except IOError: + profile = self._get_default_profile(slicer) + else: + if profile is None: + profile = self._get_default_profile(slicer) + + return TemporaryProfile(self.get_slicer(slicer).save_slicer_profile, profile, overrides=overrides) + + def delete_profile(self, slicer, name): + if not slicer in self.registered_slicers: + raise UnknownSlicer(slicer) + + if not name: + raise ValueError("name must be set") + + path = self.get_profile_path(slicer, name) + if not os.path.exists(path) or not os.path.isfile(path): + return + os.remove(path) + + def all_profiles(self, slicer, require_configured=False): + if not slicer in self.registered_slicers: + raise UnknownSlicer(slicer) + if require_configured and not slicer in self.configured_slicers: + raise SlicerNotConfigured(slicer) + + profiles = dict() + slicer_profile_path = self.get_slicer_profile_path(slicer) + for entry in os.listdir(slicer_profile_path): + if not entry.endswith(".profile") or entry.startswith("."): + # we are only interested in profiles and no hidden files + continue + + path = os.path.join(slicer_profile_path, entry) + profile_name = entry[:-len(".profile")] + + profiles[profile_name] = self._load_profile_from_path(slicer, path, require_configured=require_configured) + return profiles + + def get_slicer_profile_path(self, slicer): + if not slicer in self.registered_slicers: + raise UnknownSlicer(slicer) + + path = os.path.join(self._profile_path, slicer) + if not os.path.exists(path): + os.makedirs(path) + return path + + def get_profile_path(self, slicer, name, must_exist=False): + if not slicer in self.registered_slicers: + raise UnknownSlicer(slicer) + + if not name: + raise ValueError("name must be set") + + name = self._sanitize(name) + + path = os.path.join(self.get_slicer_profile_path(slicer), "{name}.profile".format(name=name)) + if not os.path.realpath(path).startswith(self._profile_path): + raise IOError("Path to profile {name} tried to break out of allows sub path".format(**locals())) + if must_exist and not (os.path.exists(path) and os.path.isfile(path)): + raise IOError("Profile {name} doesn't exist".format(**locals())) + return path + + def _sanitize(self, name): + if name is None: + return None + + 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 + + def _load_profile_from_path(self, slicer, path, require_configured=False): + return self.get_slicer(slicer, require_configured=require_configured).get_slicer_profile(path) + + def _save_profile_to_path(self, slicer, path, profile, allow_overwrite=True, overrides=None, require_configured=False): + self.get_slicer(slicer, require_configured=require_configured).save_slicer_profile(path, profile, allow_overwrite=allow_overwrite, overrides=overrides) + + def _get_default_profile(self, slicer): + default_profiles = settings().get(["slicing", "defaultProfiles"]) + if default_profiles and slicer in default_profiles: + try: + return self.load_profile(slicer, default_profiles[slicer]) + except: + pass + + return self.get_slicer(slicer).get_slicer_default_profile() + + diff --git a/src/octoprint/slicing/exceptions.py b/src/octoprint/slicing/exceptions.py new file mode 100644 index 000000000..4eefe4aef --- /dev/null +++ b/src/octoprint/slicing/exceptions.py @@ -0,0 +1,28 @@ +# 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" + + +class SlicingException(BaseException): + pass + +class SlicingCancelled(SlicingException): + pass + +class SlicerException(SlicingException): + def __init__(self, slicer, *args, **kwargs): + super(SlicingException, self).__init__(*args, **kwargs) + self.slicer = slicer + +class SlicerNotConfigured(SlicerException): + def __init__(self, slicer, *args, **kwargs): + super(SlicerException, self).__init__(slicer, *args, **kwargs) + self.message = "Slicer not configured: {slicer}".format(slicer=slicer) + +class UnknownSlicer(SlicerException): + def __init__(self, slicer, *args, **kwargs): + super(SlicerException, self).__init__(slicer, *args, **kwargs) + self.message = "No such slicer: {slicer}".format(slicer=slicer) diff --git a/src/octoprint/static/css/bootstrap-tabdrop.css b/src/octoprint/static/css/bootstrap-tabdrop.css new file mode 100644 index 000000000..4ac468137 --- /dev/null +++ b/src/octoprint/static/css/bootstrap-tabdrop.css @@ -0,0 +1,12 @@ +/*! + * Tab drop for Bootstrap + * + * Copyright 2012 Stefan Petre + * Licensed under the Apache License v2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + */ +.nav-tabs, +.nav-pills { + position: relative; +} diff --git a/src/octoprint/static/css/octoprint.css b/src/octoprint/static/css/octoprint.css index aa71526a2..19f0af919 100644 --- a/src/octoprint/static/css/octoprint.css +++ b/src/octoprint/static/css/octoprint.css @@ -1 +1 @@ -.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning:active,.btn-warning.active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffbd362f',GradientType=0);border-color:#bd362f #bd362f #802420;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#bd362f;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled]{color:#fff;background-color:#bd362f;*background-color:#a9302a}.btn-danger:active,.btn-danger.active{background-color:#942a25 \9}.btn-success{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#5bb75b;background-image:-moz-linear-gradient(top,#62c462,#51a351);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#51a351));background-image:-webkit-linear-gradient(top,#62c462,#51a351);background-image:-o-linear-gradient(top,#62c462,#51a351);background-image:linear-gradient(to bottom,#62c462,#51a351);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff51a351',GradientType=0);border-color:#51a351 #51a351 #387038;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#51a351;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled]{color:#fff;background-color:#51a351;*background-color:#499249}.btn-success:active,.btn-success.active{background-color:#408140 \9}.btn-info{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#49afcd;background-image:-moz-linear-gradient(top,#5bc0de,#2f96b4);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#2f96b4));background-image:-webkit-linear-gradient(top,#5bc0de,#2f96b4);background-image:-o-linear-gradient(top,#5bc0de,#2f96b4);background-image:linear-gradient(to bottom,#5bc0de,#2f96b4);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff2f96b4',GradientType=0);border-color:#2f96b4 #2f96b4 #1f6377;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#2f96b4;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled]{color:#fff;background-color:#2f96b4;*background-color:#2a85a0}.btn-info:active,.btn-info.active{background-color:#24748c \9}.btn-inverse{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#363636;background-image:-moz-linear-gradient(top,#444,#222);background-image:-webkit-gradient(linear,0 0,0 100%,from(#444),to(#222));background-image:-webkit-linear-gradient(top,#444,#222);background-image:-o-linear-gradient(top,#444,#222);background-image:linear-gradient(to bottom,#444,#222);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444',endColorstr='#ff222222',GradientType=0);border-color:#222 #222 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#222;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-inverse:hover,.btn-inverse:focus,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#fff;background-color:#222;*background-color:#151515}.btn-inverse:active,.btn-inverse.active{background-color:#080808 \9}button.btn,input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px}button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner{padding:0;border:0}button.btn.btn-large,input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px}button.btn.btn-small,input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px}button.btn.btn-mini,input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px}.btn-link,.btn-link:active,.btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-link{border-color:transparent;cursor:pointer;color:#08c;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-link:hover,.btn-link:focus{color:#005580;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,.btn-link[disabled]:focus{color:#333;text-decoration:none}.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;content:"";line-height:0}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}#navbar .navbar-inner{background-color:#ebebeb;background-image:-moz-linear-gradient(top,#fff,#ccc);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#ccc));background-image:-webkit-linear-gradient(top,#fff,#ccc);background-image:-o-linear-gradient(top,#fff,#ccc);background-image:linear-gradient(to bottom,#fff,#ccc);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffcccccc',GradientType=0)}#navbar .navbar-inner .brand,#navbar .navbar-inner .nav>li>a{text-shadow:0 1px 0 #fff;color:#333}#navbar .navbar-inner .brand .caret,#navbar .navbar-inner .nav>li>a .caret{border-bottom-color:#939393;border-top-color:#939393}#navbar .navbar-inner .brand:hover .caret,#navbar .navbar-inner .nav>li>a:hover .caret,#navbar .navbar-inner .brand:focus .caret,#navbar .navbar-inner .nav>li>a:focus .caret{border-bottom-color:#636363;border-top-color:#636363}#navbar .navbar-inner .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner .nav li.dropdown.open.active>.dropdown-toggle{background-color:#e0e0e0;background-image:-moz-linear-gradient(top,#ccc,#fff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ccc),to(#fff));background-image:-webkit-linear-gradient(top,#ccc,#fff);background-image:-o-linear-gradient(top,#ccc,#fff);background-image:linear-gradient(to bottom,#ccc,#fff);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffcccccc',endColorstr='#ffffffff',GradientType=0)}#navbar .navbar-inner.red{background-color:#e36565;background-image:-moz-linear-gradient(top,#f9a0a0,#c20c0c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9a0a0),to(#c20c0c));background-image:-webkit-linear-gradient(top,#f9a0a0,#c20c0c);background-image:-o-linear-gradient(top,#f9a0a0,#c20c0c);background-image:linear-gradient(to bottom,#f9a0a0,#c20c0c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9a0a0',endColorstr='#ffc20c0c',GradientType=0)}#navbar .navbar-inner.red .brand,#navbar .navbar-inner.red .nav>li>a{text-shadow:0 1px 0 #c20c0c;color:#f2f2f2}#navbar .navbar-inner.red .brand .caret,#navbar .navbar-inner.red .nav>li>a .caret{border-bottom-color:#f28d8d;border-top-color:#f28d8d}#navbar .navbar-inner.red .brand:hover .caret,#navbar .navbar-inner.red .nav>li>a:hover .caret,#navbar .navbar-inner.red .brand:focus .caret,#navbar .navbar-inner.red .nav>li>a:focus .caret{border-bottom-color:#f2c0c0;border-top-color:#f2c0c0}#navbar .navbar-inner.red .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.red .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.red .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.red .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.red .nav li.dropdown.open.active>.dropdown-toggle{background-color:#d84747;background-image:-moz-linear-gradient(top,#c20c0c,#f9a0a0);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c20c0c),to(#f9a0a0));background-image:-webkit-linear-gradient(top,#c20c0c,#f9a0a0);background-image:-o-linear-gradient(top,#c20c0c,#f9a0a0);background-image:linear-gradient(to bottom,#c20c0c,#f9a0a0);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc20c0c',endColorstr='#fff9a0a0',GradientType=0)}#navbar .navbar-inner.orange{background-color:#e39665;background-image:-moz-linear-gradient(top,#f9c3a0,#c2530c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9c3a0),to(#c2530c));background-image:-webkit-linear-gradient(top,#f9c3a0,#c2530c);background-image:-o-linear-gradient(top,#f9c3a0,#c2530c);background-image:linear-gradient(to bottom,#f9c3a0,#c2530c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9c3a0',endColorstr='#ffc2530c',GradientType=0)}#navbar .navbar-inner.orange .brand,#navbar .navbar-inner.orange .nav>li>a{text-shadow:0 1px 0 #f6a570;color:#333}#navbar .navbar-inner.orange .brand .caret,#navbar .navbar-inner.orange .nav>li>a .caret{border-bottom-color:#93552e;border-top-color:#93552e}#navbar .navbar-inner.orange .brand:hover .caret,#navbar .navbar-inner.orange .nav>li>a:hover .caret,#navbar .navbar-inner.orange .brand:focus .caret,#navbar .navbar-inner.orange .nav>li>a:focus .caret{border-bottom-color:#634430;border-top-color:#634430}#navbar .navbar-inner.orange .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.orange .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.orange .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.orange .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.orange .nav li.dropdown.open.active>.dropdown-toggle{background-color:#d88047;background-image:-moz-linear-gradient(top,#c2530c,#f9c3a0);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c2530c),to(#f9c3a0));background-image:-webkit-linear-gradient(top,#c2530c,#f9c3a0);background-image:-o-linear-gradient(top,#c2530c,#f9c3a0);background-image:linear-gradient(to bottom,#c2530c,#f9c3a0);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc2530c',endColorstr='#fff9c3a0',GradientType=0)}#navbar .navbar-inner.yellow{background-color:#e3d765;background-image:-moz-linear-gradient(top,#f9f0a0,#c2b00c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9f0a0),to(#c2b00c));background-image:-webkit-linear-gradient(top,#f9f0a0,#c2b00c);background-image:-o-linear-gradient(top,#f9f0a0,#c2b00c);background-image:linear-gradient(to bottom,#f9f0a0,#c2b00c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9f0a0',endColorstr='#ffc2b00c',GradientType=0)}#navbar .navbar-inner.yellow .brand,#navbar .navbar-inner.yellow .nav>li>a{text-shadow:0 1px 0 #f6e970;color:#333}#navbar .navbar-inner.yellow .brand .caret,#navbar .navbar-inner.yellow .nav>li>a .caret{border-bottom-color:#93892e;border-top-color:#93892e}#navbar .navbar-inner.yellow .brand:hover .caret,#navbar .navbar-inner.yellow .nav>li>a:hover .caret,#navbar .navbar-inner.yellow .brand:focus .caret,#navbar .navbar-inner.yellow .nav>li>a:focus .caret{border-bottom-color:#635e30;border-top-color:#635e30}#navbar .navbar-inner.yellow .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.yellow .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.yellow .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.yellow .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.yellow .nav li.dropdown.open.active>.dropdown-toggle{background-color:#d8ca47;background-image:-moz-linear-gradient(top,#c2b00c,#f9f0a0);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c2b00c),to(#f9f0a0));background-image:-webkit-linear-gradient(top,#c2b00c,#f9f0a0);background-image:-o-linear-gradient(top,#c2b00c,#f9f0a0);background-image:linear-gradient(to bottom,#c2b00c,#f9f0a0);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc2b00c',endColorstr='#fff9f0a0',GradientType=0)}#navbar .navbar-inner.green{background-color:#98f064;background-image:-moz-linear-gradient(top,#c8ffa7,#50da00);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c8ffa7),to(#50da00));background-image:-webkit-linear-gradient(top,#c8ffa7,#50da00);background-image:-o-linear-gradient(top,#c8ffa7,#50da00);background-image:linear-gradient(to bottom,#c8ffa7,#50da00);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc8ffa7',endColorstr='#ff50da00',GradientType=0)}#navbar .navbar-inner.green .brand,#navbar .navbar-inner.green .nav>li>a{text-shadow:0 1px 0 #a7ff74;color:#333}#navbar .navbar-inner.green .brand .caret,#navbar .navbar-inner.green .nav>li>a .caret{border-bottom-color:#55992e;border-top-color:#55992e}#navbar .navbar-inner.green .brand:hover .caret,#navbar .navbar-inner.green .nav>li>a:hover .caret,#navbar .navbar-inner.green .brand:focus .caret,#navbar .navbar-inner.green .nav>li>a:focus .caret{border-bottom-color:#446630;border-top-color:#446630}#navbar .navbar-inner.green .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.green .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.green .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.green .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.green .nav li.dropdown.open.active>.dropdown-toggle{background-color:#80e943;background-image:-moz-linear-gradient(top,#50da00,#c8ffa7);background-image:-webkit-gradient(linear,0 0,0 100%,from(#50da00),to(#c8ffa7));background-image:-webkit-linear-gradient(top,#50da00,#c8ffa7);background-image:-o-linear-gradient(top,#50da00,#c8ffa7);background-image:linear-gradient(to bottom,#50da00,#c8ffa7);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff50da00',endColorstr='#ffc8ffa7',GradientType=0)}#navbar .navbar-inner.blue{background-color:#6498f0;background-image:-moz-linear-gradient(top,#a7c8ff,#0050da);background-image:-webkit-gradient(linear,0 0,0 100%,from(#a7c8ff),to(#0050da));background-image:-webkit-linear-gradient(top,#a7c8ff,#0050da);background-image:-o-linear-gradient(top,#a7c8ff,#0050da);background-image:linear-gradient(to bottom,#a7c8ff,#0050da);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffa7c8ff',endColorstr='#ff0050da',GradientType=0)}#navbar .navbar-inner.blue .brand,#navbar .navbar-inner.blue .nav>li>a{text-shadow:0 1px 0 #74a7ff;color:#333}#navbar .navbar-inner.blue .brand .caret,#navbar .navbar-inner.blue .nav>li>a .caret{border-bottom-color:#2e5599;border-top-color:#2e5599}#navbar .navbar-inner.blue .brand:hover .caret,#navbar .navbar-inner.blue .nav>li>a:hover .caret,#navbar .navbar-inner.blue .brand:focus .caret,#navbar .navbar-inner.blue .nav>li>a:focus .caret{border-bottom-color:#304466;border-top-color:#304466}#navbar .navbar-inner.blue .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.blue .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.blue .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.blue .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.blue .nav li.dropdown.open.active>.dropdown-toggle{background-color:#4380e9;background-image:-moz-linear-gradient(top,#0050da,#a7c8ff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#0050da),to(#a7c8ff));background-image:-webkit-linear-gradient(top,#0050da,#a7c8ff);background-image:-o-linear-gradient(top,#0050da,#a7c8ff);background-image:linear-gradient(to bottom,#0050da,#a7c8ff);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0050da',endColorstr='#ffa7c8ff',GradientType=0)}#navbar .navbar-inner.violet{background-color:#9864f0;background-image:-moz-linear-gradient(top,#c8a7ff,#5000da);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c8a7ff),to(#5000da));background-image:-webkit-linear-gradient(top,#c8a7ff,#5000da);background-image:-o-linear-gradient(top,#c8a7ff,#5000da);background-image:linear-gradient(to bottom,#c8a7ff,#5000da);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc8a7ff',endColorstr='#ff5000da',GradientType=0)}#navbar .navbar-inner.violet .brand,#navbar .navbar-inner.violet .nav>li>a{text-shadow:0 1px 0 #5000da;color:#f2f2f2}#navbar .navbar-inner.violet .brand .caret,#navbar .navbar-inner.violet .nav>li>a .caret{border-bottom-color:#b58df9;border-top-color:#b58df9}#navbar .navbar-inner.violet .brand:hover .caret,#navbar .navbar-inner.violet .nav>li>a:hover .caret,#navbar .navbar-inner.violet .brand:focus .caret,#navbar .navbar-inner.violet .nav>li>a:focus .caret{border-bottom-color:#d3c0f5;border-top-color:#d3c0f5}#navbar .navbar-inner.violet .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.violet .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.violet .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.violet .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.violet .nav li.dropdown.open.active>.dropdown-toggle{background-color:#8043e9;background-image:-moz-linear-gradient(top,#5000da,#c8a7ff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5000da),to(#c8a7ff));background-image:-webkit-linear-gradient(top,#5000da,#c8a7ff);background-image:-o-linear-gradient(top,#5000da,#c8a7ff);background-image:linear-gradient(to bottom,#5000da,#c8a7ff);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5000da',endColorstr='#ffc8a7ff',GradientType=0)}#navbar .navbar-inner.black{background-color:#4f4f4f;background-image:-moz-linear-gradient(top,#787878,#121212);background-image:-webkit-gradient(linear,0 0,0 100%,from(#787878),to(#121212));background-image:-webkit-linear-gradient(top,#787878,#121212);background-image:-o-linear-gradient(top,#787878,#121212);background-image:linear-gradient(to bottom,#787878,#121212);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff787878',endColorstr='#ff121212',GradientType=0)}#navbar .navbar-inner.black .brand,#navbar .navbar-inner.black .nav>li>a{text-shadow:0 1px 0 #121212;color:#f2f2f2}#navbar .navbar-inner.black .brand .caret,#navbar .navbar-inner.black .nav>li>a .caret{border-bottom-color:#959595;border-top-color:#959595}#navbar .navbar-inner.black .brand:hover .caret,#navbar .navbar-inner.black .nav>li>a:hover .caret,#navbar .navbar-inner.black .brand:focus .caret,#navbar .navbar-inner.black .nav>li>a:focus .caret{border-bottom-color:#c4c4c4;border-top-color:#c4c4c4}#navbar .navbar-inner.black .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.black .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.black .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.black .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.black .nav li.dropdown.open.active>.dropdown-toggle{background-color:#3b3b3b;background-image:-moz-linear-gradient(top,#121212,#787878);background-image:-webkit-gradient(linear,0 0,0 100%,from(#121212),to(#787878));background-image:-webkit-linear-gradient(top,#121212,#787878);background-image:-o-linear-gradient(top,#121212,#787878);background-image:linear-gradient(to bottom,#121212,#787878);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff121212',endColorstr='#ff787878',GradientType=0)}#navbar .navbar-inner .brand span{background-size:20px 20px;background-position:left center;padding-left:24px;background-repeat:no-repeat}.octoprint-container{margin-top:20px}.octoprint-container .tab-content{padding:9px 15px;border-left:1px solid #DDD;border-right:1px solid #DDD;border-bottom:1px solid #DDD;-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px}.octoprint-container .nav{margin-bottom:0}.octoprint-container .tab-content h1{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:40px;color:#333;border:0;border-bottom:1px solid #e5e5e5;font-weight:normal}.octoprint-container .accordion-heading .accordion-heading-button{float:right}.octoprint-container .accordion-heading .accordion-heading-button a{display:inline-block;padding:8px 15px;font-size:14px;line-height:20px;color:#000;text-decoration:none;background:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.octoprint-container .accordion-heading a.accordion-toggle{display:inline-block}.octoprint-container .accordion-heading [class^="icon-"],.octoprint-container .accordion-heading [class*=" icon-"]{color:#000}.print-control .btn{padding-left:4px;padding-right:4px}.upload-buttons .btn{margin-right:0}table{table-layout:fixed}table .popover-title{text-overflow:ellipsis;word-break:break-all}table th,table td{overflow:hidden}table th.gcode_files_name,table td.gcode_files_name{text-overflow:ellipsis;white-space:nowrap;text-align:left}table th.gcode_files_action,table td.gcode_files_action{text-align:center;width:90px}table th.gcode_files_action a,table td.gcode_files_action a{text-decoration:none;color:#000}table th.gcode_files_action a.disabled,table td.gcode_files_action a.disabled{color:#ccc;cursor:default}table th.timelapse_files_name,table td.timelapse_files_name{text-overflow:ellipsis;text-align:left}table th.timelapse_files_size,table td.timelapse_files_size{text-align:right;width:55px}table th.timelapse_files_action,table td.timelapse_files_action{text-align:center;width:45px}table th.timelapse_files_action a,table td.timelapse_files_action a{text-decoration:none;color:#000}table th.timelapse_files_action a.disabled,table td.timelapse_files_action a.disabled{color:#ccc;cursor:default}table th.settings_users_name,table td.settings_users_name{text-overflow:ellipsis;text-align:left}table th.settings_users_active,table td.settings_users_active,table th.settings_users_admin,table td.settings_users_admin{text-align:center;width:55px}table th.settings_users_actions,table td.settings_users_actions{text-align:center;width:60px}table th.settings_users_actions a,table td.settings_users_actions a{text-decoration:none;color:#000}table th.settings_users_actions a.disabled,table td.settings_users_actions a.disabled{color:#ccc;cursor:default}table th.settings_logs_name,table td.settings_logs_name{text-overflow:ellipsis;text-align:left}table th.settings_logs_size,table td.settings_logs_size{text-align:right;width:70px}table th.settings_logs_date,table td.settings_logs_date{text-align:left;width:130px}table th.settings_logs_action,table td.settings_logs_action{text-align:center;width:70px}table th.settings_logs_action a,table td.settings_logs_action a{text-decoration:none;color:#000}table th.settings_logs_action a.disabled,table td.settings_logs_action a.disabled{color:#ccc;cursor:default}#temperature-graph{height:350px;width:100%;background-image:url("../img/graph-background.png");background-position:center;background-repeat:no-repeat}.tab-content,.tab-pane{overflow:visible}.tempInput{width:50px}#temp_newTemp,#temp_newBedTemp,#speed_innerWall,#speed_outerWall,#speed_fill,#speed_support,#webcam_timelapse_interval,#webcam_timelapse_postRoll{text-align:right}ul.dropdown-menu li a{cursor:pointer}#connection_ports,#connection_baudrates{width:100%}#offline_overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#offline_overlay_background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#offline_overlay_wrapper{position:absolute;top:0;bottom:0;left:0;right:0;padding-top:60px}#offline_overlay_wrapper .container{margin:auto}#webcam_container{width:100%}#webcam_container .flipH{-webkit-transform:scaleX(-1);-moz-transform:scaleX(-1)}#webcam_container .flipV{-webkit-transform:scaleY(-1);-moz-transform:scaleY(-1)}#webcam_container .flipH.flipV{-webkit-transform:scaleX(-1) scaleY(-1);-moz-transform:scaleX(-1) scaleY(-1)}#files .gcode_files{padding-right:7px}#files .gcode_files .entry{padding:5px;line-height:20px;border-bottom:1px solid #ddd;position:relative}#files .gcode_files .entry:hover{background-color:#f5f5f5}#files .gcode_files .entry .title{text-overflow:ellipsis;word-break:break-all}#files .gcode_files .entry .uploaded,#files .gcode_files .entry .size,#files .gcode_files .entry .additionalInfo{font-size:85%;color:#999}#files .gcode_files .entry .action-buttons{position:absolute;bottom:5px;right:5px}#files .gcode_files .entry .additionalInfo{padding-bottom:22px}#files .upload-buttons{margin-top:10px}#files .form-search{text-align:center;margin-bottom:5px!important}#control{overflow:hidden}#control .jog-panel{float:left;margin-right:19px}#control h1{text-align:left}#control .jog-panel>div{text-align:center}#control .jog-panel>div.distance{text-align:left}#control .box{width:30px;height:30px;margin-right:10px;margin-bottom:10px;padding-left:8px}#control .control-box{display:block;height:30px;margin-bottom:10px}#control .btn-group{margin-bottom:10px}#control .btn-group.distance>.btn{width:43px;padding:3px 0;height:30px}#gcode .progress{width:582px}#gcode .progress .bar{-webkit-transition:width 0s linear;-moz-transition:width 0s linear;-o-transition:width 0s linear;transition:width 0s linear}#gcode #gcode_layer_slider{height:568px;float:right}#gcode #gcode_layer_slider .slider-handle{width:14px;height:14px;margin-left:-3px;margin-top:-7px}#gcode #gcode_command_slider .slider-handle{width:14px;height:14px;margin-left:-7px;margin-top:-3px}#term #terminal-output{min-height:340px}.footer ul{margin:0}.footer ul li{display:inline;margin-left:1em;font-size:85%}.footer ul li:first-child{margin-left:0}.footer ul li a{color:#555}.ui-pnotify .alert a{color:#c09853}.ui-pnotify .alert-error a,.ui-pnotify .alert-danger a{color:#b94a48}.ui-pnotify .alert-success a{color:#468847}.ui-pnotify .alert-info a{color:#3a87ad}.pnotify_additional_info .pnotify_more{font-size:85%}.text-right{text-align:right}.overflow_visible{overflow:visible!important}#drop_overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#drop_overlay.in{display:block}#drop_overlay #drop_overlay_background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#drop_overlay #drop_overlay_wrapper{position:absolute;top:0;bottom:0;left:0;right:0;padding-top:60px}#drop_overlay #drop_overlay_wrapper #drop,#drop_overlay #drop_overlay_wrapper #drop_background{position:absolute;top:50%;left:50%;margin-left:-200px;margin-top:-200px}#drop_overlay #drop_overlay_wrapper #drop_locally,#drop_overlay #drop_overlay_wrapper #drop_locally_background{position:absolute;top:50%;left:50%;margin-left:-425px;margin-top:-200px}#drop_overlay #drop_overlay_wrapper #drop_sd,#drop_overlay #drop_overlay_wrapper #drop_sd_background{position:absolute;top:50%;left:50%;margin-left:25px;margin-top:-200px}#drop_overlay #drop_overlay_wrapper .dropzone{width:404px;height:404px;z-index:10001;color:#fff;font-size:30px}#drop_overlay #drop_overlay_wrapper .dropzone i{font-size:50px}#drop_overlay #drop_overlay_wrapper .dropzone .centered{display:table-cell;text-align:center;vertical-align:middle;width:400px;height:400px;line-height:40px;filter:alpha(opacity=100);-moz-opacity:1.0;-khtml-opacity:1.0;opacity:1.0}#drop_overlay #drop_overlay_wrapper .dropzone_background{width:400px;height:400px;border:2px dashed #eee;-webkit-border-radius:10px;-moz-border-radius:10px;border-radius:10px;background-color:#000;filter:alpha(opacity=25);-moz-opacity:.25;-khtml-opacity:.25;opacity:.25}#drop_overlay #drop_overlay_wrapper .dropzone_background.hover{background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#drop_overlay #drop_overlay_wrapper .dropzone_background.fade{-webkit-transition:all .3s ease-out;-moz-transition:all .3s ease-out;-ms-transition:all .3s ease-out;-o-transition:all .3s ease-out;transition:all .3s ease-out;opacity:1}.icon-sd-black-14{background:url("../img/icon-sd-black-14.png") 0 3px no-repeat;width:11px;height:17px;display:inline-block!important}.center{float:none;margin-left:auto;margin-right:auto}.slider .slider-selection{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.slider .slider-selection:hover,.slider .slider-selection:focus,.slider .slider-selection:active,.slider .slider-selection.active,.slider .slider-selection.disabled,.slider .slider-selection[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.slider .slider-selection:active,.slider .slider-selection.active{background-color:#039 \9}.slider.slider-disabled .slider-selection{background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.slider .slider-track{background-color:#f5f5f5;border:1px solid #e3e3e3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.slider.slider-disabled .slider-track{background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.slider .slider-handle{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);padding:0;margin-bottom:0;opacity:1;filter:alpha(opacity=100)}.slider .slider-handle:hover,.slider .slider-handle:focus,.slider .slider-handle:active,.slider .slider-handle.active,.slider .slider-handle.disabled,.slider .slider-handle[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.slider .slider-handle:active,.slider .slider-handle.active{background-color:#ccc \9}.slider .slider-handle:first-child{*margin-left:0}.slider .slider-handle:hover,.slider .slider-handle:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.slider .slider-handle:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.slider .slider-handle.active,.slider .slider-handle:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.slider .slider-handle.disabled,.slider .slider-handle[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.slider .slider-handle.hide{display:none}.slider .slider-handle.round{-webkit-border-radius:50%;-moz-border-radius:50%;border-radius:50%} \ No newline at end of file +.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning:active,.btn-warning.active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffbd362f',GradientType=0);border-color:#bd362f #bd362f #802420;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#bd362f;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled]{color:#fff;background-color:#bd362f;*background-color:#a9302a}.btn-danger:active,.btn-danger.active{background-color:#942a25 \9}.btn-success{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#5bb75b;background-image:-moz-linear-gradient(top,#62c462,#51a351);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#51a351));background-image:-webkit-linear-gradient(top,#62c462,#51a351);background-image:-o-linear-gradient(top,#62c462,#51a351);background-image:linear-gradient(to bottom,#62c462,#51a351);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff51a351',GradientType=0);border-color:#51a351 #51a351 #387038;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#51a351;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled]{color:#fff;background-color:#51a351;*background-color:#499249}.btn-success:active,.btn-success.active{background-color:#408140 \9}.btn-info{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#49afcd;background-image:-moz-linear-gradient(top,#5bc0de,#2f96b4);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#2f96b4));background-image:-webkit-linear-gradient(top,#5bc0de,#2f96b4);background-image:-o-linear-gradient(top,#5bc0de,#2f96b4);background-image:linear-gradient(to bottom,#5bc0de,#2f96b4);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff2f96b4',GradientType=0);border-color:#2f96b4 #2f96b4 #1f6377;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#2f96b4;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled]{color:#fff;background-color:#2f96b4;*background-color:#2a85a0}.btn-info:active,.btn-info.active{background-color:#24748c \9}.btn-inverse{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#363636;background-image:-moz-linear-gradient(top,#444,#222);background-image:-webkit-gradient(linear,0 0,0 100%,from(#444),to(#222));background-image:-webkit-linear-gradient(top,#444,#222);background-image:-o-linear-gradient(top,#444,#222);background-image:linear-gradient(to bottom,#444,#222);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444',endColorstr='#ff222222',GradientType=0);border-color:#222 #222 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#222;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-inverse:hover,.btn-inverse:focus,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#fff;background-color:#222;*background-color:#151515}.btn-inverse:active,.btn-inverse.active{background-color:#080808 \9}button.btn,input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px}button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner{padding:0;border:0}button.btn.btn-large,input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px}button.btn.btn-small,input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px}button.btn.btn-mini,input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px}.btn-link,.btn-link:active,.btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-link{border-color:transparent;cursor:pointer;color:#08c;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-link:hover,.btn-link:focus{color:#005580;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,.btn-link[disabled]:focus{color:#333;text-decoration:none}.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;content:"";line-height:0}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.nowrap{white-space:nowrap}.actioncol{text-align:center;white-space:nowrap}.actioncol a{text-decoration:none;color:#000}.actioncol a.disabled{color:#ccc;cursor:default}#navbar .navbar-inner{background-color:#ebebeb;background-image:-moz-linear-gradient(top,#fff,#ccc);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#ccc));background-image:-webkit-linear-gradient(top,#fff,#ccc);background-image:-o-linear-gradient(top,#fff,#ccc);background-image:linear-gradient(to bottom,#fff,#ccc);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffcccccc',GradientType=0)}#navbar .navbar-inner .brand,#navbar .navbar-inner .nav>li>a{text-shadow:0 1px 0 #fff;color:#333}#navbar .navbar-inner .brand .caret,#navbar .navbar-inner .nav>li>a .caret{border-bottom-color:#939393;border-top-color:#939393}#navbar .navbar-inner .brand:hover .caret,#navbar .navbar-inner .nav>li>a:hover .caret,#navbar .navbar-inner .brand:focus .caret,#navbar .navbar-inner .nav>li>a:focus .caret{border-bottom-color:#636363;border-top-color:#636363}#navbar .navbar-inner .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner .nav li.dropdown.open.active>.dropdown-toggle{background-color:#e0e0e0;background-image:-moz-linear-gradient(top,#ccc,#fff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ccc),to(#fff));background-image:-webkit-linear-gradient(top,#ccc,#fff);background-image:-o-linear-gradient(top,#ccc,#fff);background-image:linear-gradient(to bottom,#ccc,#fff);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffcccccc',endColorstr='#ffffffff',GradientType=0)}#navbar .navbar-inner.transparent{background-color:rgba(235,235,235,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(255,255,255,0.6),rgba(204,204,204,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(255,255,255,0.6)),to(rgba(204,204,204,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(255,255,255,0.6),rgba(204,204,204,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(255,255,255,0.6),rgba(204,204,204,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(255,255,255,0.6),rgba(204,204,204,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#99ffffff',endColorstr='#99cccccc',GradientType=0)}#navbar .navbar-inner.transparent .brand,#navbar .navbar-inner.transparent .nav>li>a{text-shadow:0 1px 0 #fff;color:#333}#navbar .navbar-inner.transparent .brand .caret,#navbar .navbar-inner.transparent .nav>li>a .caret{border-bottom-color:#939393;border-top-color:#939393}#navbar .navbar-inner.transparent .brand:hover .caret,#navbar .navbar-inner.transparent .nav>li>a:hover .caret,#navbar .navbar-inner.transparent .brand:focus .caret,#navbar .navbar-inner.transparent .nav>li>a:focus .caret{border-bottom-color:#636363;border-top-color:#636363}#navbar .navbar-inner.transparent .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.transparent .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.transparent .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.transparent .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.transparent .nav li.dropdown.open.active>.dropdown-toggle{background-color:rgba(224,224,224,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(204,204,204,0.6),rgba(255,255,255,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(204,204,204,0.6)),to(rgba(255,255,255,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(204,204,204,0.6),rgba(255,255,255,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(204,204,204,0.6),rgba(255,255,255,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(204,204,204,0.6),rgba(255,255,255,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#99cccccc',endColorstr='#99ffffff',GradientType=0)}#navbar .navbar-inner.red{background-color:#bb645f;background-image:-moz-linear-gradient(top,#e28e8a,#802420);background-image:-webkit-gradient(linear,0 0,0 100%,from(#e28e8a),to(#802420));background-image:-webkit-linear-gradient(top,#e28e8a,#802420);background-image:-o-linear-gradient(top,#e28e8a,#802420);background-image:linear-gradient(to bottom,#e28e8a,#802420);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe28e8a',endColorstr='#ff802420',GradientType=0)}#navbar .navbar-inner.red .brand,#navbar .navbar-inner.red .nav>li>a{text-shadow:0 1px 0 #802420;color:#f2f2f2}#navbar .navbar-inner.red .brand .caret,#navbar .navbar-inner.red .nav>li>a .caret{border-bottom-color:#d89491;border-top-color:#d89491}#navbar .navbar-inner.red .brand:hover .caret,#navbar .navbar-inner.red .nav>li>a:hover .caret,#navbar .navbar-inner.red .brand:focus .caret,#navbar .navbar-inner.red .nav>li>a:focus .caret{border-bottom-color:#e5c3c1;border-top-color:#e5c3c1}#navbar .navbar-inner.red .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.red .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.red .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.red .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.red .nav li.dropdown.open.active>.dropdown-toggle{background-color:#a74f4a;background-image:-moz-linear-gradient(top,#802420,#e28e8a);background-image:-webkit-gradient(linear,0 0,0 100%,from(#802420),to(#e28e8a));background-image:-webkit-linear-gradient(top,#802420,#e28e8a);background-image:-o-linear-gradient(top,#802420,#e28e8a);background-image:linear-gradient(to bottom,#802420,#e28e8a);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff802420',endColorstr='#ffe28e8a',GradientType=0)}#navbar .navbar-inner.red.transparent{background-color:rgba(187,100,95,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(226,142,138,0.6),rgba(128,36,32,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(226,142,138,0.6)),to(rgba(128,36,32,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(226,142,138,0.6),rgba(128,36,32,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(226,142,138,0.6),rgba(128,36,32,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(226,142,138,0.6),rgba(128,36,32,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#99e28e8a',endColorstr='#99802420',GradientType=0)}#navbar .navbar-inner.red.transparent .brand,#navbar .navbar-inner.red.transparent .nav>li>a{text-shadow:0 1px 0 #802420;color:#f2f2f2}#navbar .navbar-inner.red.transparent .brand .caret,#navbar .navbar-inner.red.transparent .nav>li>a .caret{border-bottom-color:#d89491;border-top-color:#d89491}#navbar .navbar-inner.red.transparent .brand:hover .caret,#navbar .navbar-inner.red.transparent .nav>li>a:hover .caret,#navbar .navbar-inner.red.transparent .brand:focus .caret,#navbar .navbar-inner.red.transparent .nav>li>a:focus .caret{border-bottom-color:#e5c3c1;border-top-color:#e5c3c1}#navbar .navbar-inner.red.transparent .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.red.transparent .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.red.transparent .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.red.transparent .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.red.transparent .nav li.dropdown.open.active>.dropdown-toggle{background-color:rgba(167,79,74,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(128,36,32,0.6),rgba(226,142,138,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(128,36,32,0.6)),to(rgba(226,142,138,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(128,36,32,0.6),rgba(226,142,138,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(128,36,32,0.6),rgba(226,142,138,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(128,36,32,0.6),rgba(226,142,138,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#99802420',endColorstr='#99e28e8a',GradientType=0)}#navbar .navbar-inner.orange{background-color:#e39665;background-image:-moz-linear-gradient(top,#f9c3a0,#c2530c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9c3a0),to(#c2530c));background-image:-webkit-linear-gradient(top,#f9c3a0,#c2530c);background-image:-o-linear-gradient(top,#f9c3a0,#c2530c);background-image:linear-gradient(to bottom,#f9c3a0,#c2530c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9c3a0',endColorstr='#ffc2530c',GradientType=0)}#navbar .navbar-inner.orange .brand,#navbar .navbar-inner.orange .nav>li>a{text-shadow:0 1px 0 #f6a570;color:#f2f2f2}#navbar .navbar-inner.orange .brand .caret,#navbar .navbar-inner.orange .nav>li>a .caret{border-bottom-color:#f2b58d;border-top-color:#f2b58d}#navbar .navbar-inner.orange .brand:hover .caret,#navbar .navbar-inner.orange .nav>li>a:hover .caret,#navbar .navbar-inner.orange .brand:focus .caret,#navbar .navbar-inner.orange .nav>li>a:focus .caret{border-bottom-color:#f2d3c0;border-top-color:#f2d3c0}#navbar .navbar-inner.orange .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.orange .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.orange .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.orange .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.orange .nav li.dropdown.open.active>.dropdown-toggle{background-color:#d88047;background-image:-moz-linear-gradient(top,#c2530c,#f9c3a0);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c2530c),to(#f9c3a0));background-image:-webkit-linear-gradient(top,#c2530c,#f9c3a0);background-image:-o-linear-gradient(top,#c2530c,#f9c3a0);background-image:linear-gradient(to bottom,#c2530c,#f9c3a0);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc2530c',endColorstr='#fff9c3a0',GradientType=0)}#navbar .navbar-inner.orange.transparent{background-color:rgba(227,150,101,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(249,195,160,0.6),rgba(194,83,12,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(249,195,160,0.6)),to(rgba(194,83,12,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(249,195,160,0.6),rgba(194,83,12,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(249,195,160,0.6),rgba(194,83,12,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(249,195,160,0.6),rgba(194,83,12,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#99f9c3a0',endColorstr='#99c2530c',GradientType=0)}#navbar .navbar-inner.orange.transparent .brand,#navbar .navbar-inner.orange.transparent .nav>li>a{text-shadow:0 1px 0 #f6a570;color:#f2f2f2}#navbar .navbar-inner.orange.transparent .brand .caret,#navbar .navbar-inner.orange.transparent .nav>li>a .caret{border-bottom-color:#f2b58d;border-top-color:#f2b58d}#navbar .navbar-inner.orange.transparent .brand:hover .caret,#navbar .navbar-inner.orange.transparent .nav>li>a:hover .caret,#navbar .navbar-inner.orange.transparent .brand:focus .caret,#navbar .navbar-inner.orange.transparent .nav>li>a:focus .caret{border-bottom-color:#f2d3c0;border-top-color:#f2d3c0}#navbar .navbar-inner.orange.transparent .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.orange.transparent .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.orange.transparent .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.orange.transparent .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.orange.transparent .nav li.dropdown.open.active>.dropdown-toggle{background-color:rgba(216,128,71,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(194,83,12,0.6),rgba(249,195,160,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(194,83,12,0.6)),to(rgba(249,195,160,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(194,83,12,0.6),rgba(249,195,160,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(194,83,12,0.6),rgba(249,195,160,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(194,83,12,0.6),rgba(249,195,160,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#99c2530c',endColorstr='#99f9c3a0',GradientType=0)}#navbar .navbar-inner.yellow{background-color:#e3d765;background-image:-moz-linear-gradient(top,#f9f0a0,#c2b00c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9f0a0),to(#c2b00c));background-image:-webkit-linear-gradient(top,#f9f0a0,#c2b00c);background-image:-o-linear-gradient(top,#f9f0a0,#c2b00c);background-image:linear-gradient(to bottom,#f9f0a0,#c2b00c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9f0a0',endColorstr='#ffc2b00c',GradientType=0)}#navbar .navbar-inner.yellow .brand,#navbar .navbar-inner.yellow .nav>li>a{text-shadow:0 1px 0 #f6e970;color:#333}#navbar .navbar-inner.yellow .brand .caret,#navbar .navbar-inner.yellow .nav>li>a .caret{border-bottom-color:#93892e;border-top-color:#93892e}#navbar .navbar-inner.yellow .brand:hover .caret,#navbar .navbar-inner.yellow .nav>li>a:hover .caret,#navbar .navbar-inner.yellow .brand:focus .caret,#navbar .navbar-inner.yellow .nav>li>a:focus .caret{border-bottom-color:#635e30;border-top-color:#635e30}#navbar .navbar-inner.yellow .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.yellow .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.yellow .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.yellow .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.yellow .nav li.dropdown.open.active>.dropdown-toggle{background-color:#d8ca47;background-image:-moz-linear-gradient(top,#c2b00c,#f9f0a0);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c2b00c),to(#f9f0a0));background-image:-webkit-linear-gradient(top,#c2b00c,#f9f0a0);background-image:-o-linear-gradient(top,#c2b00c,#f9f0a0);background-image:linear-gradient(to bottom,#c2b00c,#f9f0a0);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc2b00c',endColorstr='#fff9f0a0',GradientType=0)}#navbar .navbar-inner.yellow.transparent{background-color:rgba(227,215,101,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(249,240,160,0.6),rgba(194,176,12,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(249,240,160,0.6)),to(rgba(194,176,12,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(249,240,160,0.6),rgba(194,176,12,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(249,240,160,0.6),rgba(194,176,12,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(249,240,160,0.6),rgba(194,176,12,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#99f9f0a0',endColorstr='#99c2b00c',GradientType=0)}#navbar .navbar-inner.yellow.transparent .brand,#navbar .navbar-inner.yellow.transparent .nav>li>a{text-shadow:0 1px 0 #f6e970;color:#333}#navbar .navbar-inner.yellow.transparent .brand .caret,#navbar .navbar-inner.yellow.transparent .nav>li>a .caret{border-bottom-color:#93892e;border-top-color:#93892e}#navbar .navbar-inner.yellow.transparent .brand:hover .caret,#navbar .navbar-inner.yellow.transparent .nav>li>a:hover .caret,#navbar .navbar-inner.yellow.transparent .brand:focus .caret,#navbar .navbar-inner.yellow.transparent .nav>li>a:focus .caret{border-bottom-color:#635e30;border-top-color:#635e30}#navbar .navbar-inner.yellow.transparent .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.yellow.transparent .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.yellow.transparent .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.yellow.transparent .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.yellow.transparent .nav li.dropdown.open.active>.dropdown-toggle{background-color:rgba(216,202,71,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(194,176,12,0.6),rgba(249,240,160,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(194,176,12,0.6)),to(rgba(249,240,160,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(194,176,12,0.6),rgba(249,240,160,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(194,176,12,0.6),rgba(249,240,160,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(194,176,12,0.6),rgba(249,240,160,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#99c2b00c',endColorstr='#99f9f0a0',GradientType=0)}#navbar .navbar-inner.green{background-color:#98f064;background-image:-moz-linear-gradient(top,#c8ffa7,#50da00);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c8ffa7),to(#50da00));background-image:-webkit-linear-gradient(top,#c8ffa7,#50da00);background-image:-o-linear-gradient(top,#c8ffa7,#50da00);background-image:linear-gradient(to bottom,#c8ffa7,#50da00);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc8ffa7',endColorstr='#ff50da00',GradientType=0)}#navbar .navbar-inner.green .brand,#navbar .navbar-inner.green .nav>li>a{text-shadow:0 1px 0 #a7ff74;color:#333}#navbar .navbar-inner.green .brand .caret,#navbar .navbar-inner.green .nav>li>a .caret{border-bottom-color:#55992e;border-top-color:#55992e}#navbar .navbar-inner.green .brand:hover .caret,#navbar .navbar-inner.green .nav>li>a:hover .caret,#navbar .navbar-inner.green .brand:focus .caret,#navbar .navbar-inner.green .nav>li>a:focus .caret{border-bottom-color:#446630;border-top-color:#446630}#navbar .navbar-inner.green .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.green .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.green .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.green .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.green .nav li.dropdown.open.active>.dropdown-toggle{background-color:#80e943;background-image:-moz-linear-gradient(top,#50da00,#c8ffa7);background-image:-webkit-gradient(linear,0 0,0 100%,from(#50da00),to(#c8ffa7));background-image:-webkit-linear-gradient(top,#50da00,#c8ffa7);background-image:-o-linear-gradient(top,#50da00,#c8ffa7);background-image:linear-gradient(to bottom,#50da00,#c8ffa7);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff50da00',endColorstr='#ffc8ffa7',GradientType=0)}#navbar .navbar-inner.green.transparent{background-color:rgba(152,240,100,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(200,255,167,0.6),rgba(80,218,0,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(200,255,167,0.6)),to(rgba(80,218,0,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(200,255,167,0.6),rgba(80,218,0,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(200,255,167,0.6),rgba(80,218,0,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(200,255,167,0.6),rgba(80,218,0,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#99c8ffa7',endColorstr='#9950da00',GradientType=0)}#navbar .navbar-inner.green.transparent .brand,#navbar .navbar-inner.green.transparent .nav>li>a{text-shadow:0 1px 0 #a7ff74;color:#333}#navbar .navbar-inner.green.transparent .brand .caret,#navbar .navbar-inner.green.transparent .nav>li>a .caret{border-bottom-color:#55992e;border-top-color:#55992e}#navbar .navbar-inner.green.transparent .brand:hover .caret,#navbar .navbar-inner.green.transparent .nav>li>a:hover .caret,#navbar .navbar-inner.green.transparent .brand:focus .caret,#navbar .navbar-inner.green.transparent .nav>li>a:focus .caret{border-bottom-color:#446630;border-top-color:#446630}#navbar .navbar-inner.green.transparent .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.green.transparent .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.green.transparent .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.green.transparent .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.green.transparent .nav li.dropdown.open.active>.dropdown-toggle{background-color:rgba(128,233,67,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(80,218,0,0.6),rgba(200,255,167,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(80,218,0,0.6)),to(rgba(200,255,167,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(80,218,0,0.6),rgba(200,255,167,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(80,218,0,0.6),rgba(200,255,167,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(80,218,0,0.6),rgba(200,255,167,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#9950da00',endColorstr='#99c8ffa7',GradientType=0)}#navbar .navbar-inner.blue{background-color:#2e63cc;background-image:-moz-linear-gradient(top,#4d88ff,#002b80);background-image:-webkit-gradient(linear,0 0,0 100%,from(#4d88ff),to(#002b80));background-image:-webkit-linear-gradient(top,#4d88ff,#002b80);background-image:-o-linear-gradient(top,#4d88ff,#002b80);background-image:linear-gradient(to bottom,#4d88ff,#002b80);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff4d88ff',endColorstr='#ff002b80',GradientType=0)}#navbar .navbar-inner.blue .brand,#navbar .navbar-inner.blue .nav>li>a{text-shadow:0 1px 0 #002b80;color:#f2f2f2}#navbar .navbar-inner.blue .brand .caret,#navbar .navbar-inner.blue .nav>li>a .caret{border-bottom-color:#799bdf;border-top-color:#799bdf}#navbar .navbar-inner.blue .brand:hover .caret,#navbar .navbar-inner.blue .nav>li>a:hover .caret,#navbar .navbar-inner.blue .brand:focus .caret,#navbar .navbar-inner.blue .nav>li>a:focus .caret{border-bottom-color:#b6c7e9;border-top-color:#b6c7e9}#navbar .navbar-inner.blue .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.blue .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.blue .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.blue .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.blue .nav li.dropdown.open.active>.dropdown-toggle{background-color:#1f50b3;background-image:-moz-linear-gradient(top,#002b80,#4d88ff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#002b80),to(#4d88ff));background-image:-webkit-linear-gradient(top,#002b80,#4d88ff);background-image:-o-linear-gradient(top,#002b80,#4d88ff);background-image:linear-gradient(to bottom,#002b80,#4d88ff);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff002b80',endColorstr='#ff4d88ff',GradientType=0)}#navbar .navbar-inner.blue.transparent{background-color:rgba(46,99,204,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(77,136,255,0.6),rgba(0,43,128,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(77,136,255,0.6)),to(rgba(0,43,128,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(77,136,255,0.6),rgba(0,43,128,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(77,136,255,0.6),rgba(0,43,128,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(77,136,255,0.6),rgba(0,43,128,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#994d88ff',endColorstr='#99002b80',GradientType=0)}#navbar .navbar-inner.blue.transparent .brand,#navbar .navbar-inner.blue.transparent .nav>li>a{text-shadow:0 1px 0 #002b80;color:#f2f2f2}#navbar .navbar-inner.blue.transparent .brand .caret,#navbar .navbar-inner.blue.transparent .nav>li>a .caret{border-bottom-color:#799bdf;border-top-color:#799bdf}#navbar .navbar-inner.blue.transparent .brand:hover .caret,#navbar .navbar-inner.blue.transparent .nav>li>a:hover .caret,#navbar .navbar-inner.blue.transparent .brand:focus .caret,#navbar .navbar-inner.blue.transparent .nav>li>a:focus .caret{border-bottom-color:#b6c7e9;border-top-color:#b6c7e9}#navbar .navbar-inner.blue.transparent .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.blue.transparent .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.blue.transparent .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.blue.transparent .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.blue.transparent .nav li.dropdown.open.active>.dropdown-toggle{background-color:rgba(31,80,179,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(0,43,128,0.6),rgba(77,136,255,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(0,43,128,0.6)),to(rgba(77,136,255,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(0,43,128,0.6),rgba(77,136,255,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(0,43,128,0.6),rgba(77,136,255,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(0,43,128,0.6),rgba(77,136,255,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#99002b80',endColorstr='#994d88ff',GradientType=0)}#navbar .navbar-inner.violet{background-color:#9864f0;background-image:-moz-linear-gradient(top,#c8a7ff,#5000da);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c8a7ff),to(#5000da));background-image:-webkit-linear-gradient(top,#c8a7ff,#5000da);background-image:-o-linear-gradient(top,#c8a7ff,#5000da);background-image:linear-gradient(to bottom,#c8a7ff,#5000da);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc8a7ff',endColorstr='#ff5000da',GradientType=0)}#navbar .navbar-inner.violet .brand,#navbar .navbar-inner.violet .nav>li>a{text-shadow:0 1px 0 #5000da;color:#f2f2f2}#navbar .navbar-inner.violet .brand .caret,#navbar .navbar-inner.violet .nav>li>a .caret{border-bottom-color:#b58df9;border-top-color:#b58df9}#navbar .navbar-inner.violet .brand:hover .caret,#navbar .navbar-inner.violet .nav>li>a:hover .caret,#navbar .navbar-inner.violet .brand:focus .caret,#navbar .navbar-inner.violet .nav>li>a:focus .caret{border-bottom-color:#d3c0f5;border-top-color:#d3c0f5}#navbar .navbar-inner.violet .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.violet .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.violet .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.violet .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.violet .nav li.dropdown.open.active>.dropdown-toggle{background-color:#8043e9;background-image:-moz-linear-gradient(top,#5000da,#c8a7ff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5000da),to(#c8a7ff));background-image:-webkit-linear-gradient(top,#5000da,#c8a7ff);background-image:-o-linear-gradient(top,#5000da,#c8a7ff);background-image:linear-gradient(to bottom,#5000da,#c8a7ff);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5000da',endColorstr='#ffc8a7ff',GradientType=0)}#navbar .navbar-inner.violet.transparent{background-color:rgba(152,100,240,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(200,167,255,0.6),rgba(80,0,218,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(200,167,255,0.6)),to(rgba(80,0,218,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(200,167,255,0.6),rgba(80,0,218,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(200,167,255,0.6),rgba(80,0,218,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(200,167,255,0.6),rgba(80,0,218,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#99c8a7ff',endColorstr='#995000da',GradientType=0)}#navbar .navbar-inner.violet.transparent .brand,#navbar .navbar-inner.violet.transparent .nav>li>a{text-shadow:0 1px 0 #5000da;color:#f2f2f2}#navbar .navbar-inner.violet.transparent .brand .caret,#navbar .navbar-inner.violet.transparent .nav>li>a .caret{border-bottom-color:#b58df9;border-top-color:#b58df9}#navbar .navbar-inner.violet.transparent .brand:hover .caret,#navbar .navbar-inner.violet.transparent .nav>li>a:hover .caret,#navbar .navbar-inner.violet.transparent .brand:focus .caret,#navbar .navbar-inner.violet.transparent .nav>li>a:focus .caret{border-bottom-color:#d3c0f5;border-top-color:#d3c0f5}#navbar .navbar-inner.violet.transparent .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.violet.transparent .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.violet.transparent .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.violet.transparent .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.violet.transparent .nav li.dropdown.open.active>.dropdown-toggle{background-color:rgba(128,67,233,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(80,0,218,0.6),rgba(200,167,255,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(80,0,218,0.6)),to(rgba(200,167,255,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(80,0,218,0.6),rgba(200,167,255,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(80,0,218,0.6),rgba(200,167,255,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(80,0,218,0.6),rgba(200,167,255,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#995000da',endColorstr='#99c8a7ff',GradientType=0)}#navbar .navbar-inner.black{background-color:#4f4f4f;background-image:-moz-linear-gradient(top,#787878,#121212);background-image:-webkit-gradient(linear,0 0,0 100%,from(#787878),to(#121212));background-image:-webkit-linear-gradient(top,#787878,#121212);background-image:-o-linear-gradient(top,#787878,#121212);background-image:linear-gradient(to bottom,#787878,#121212);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff787878',endColorstr='#ff121212',GradientType=0)}#navbar .navbar-inner.black .brand,#navbar .navbar-inner.black .nav>li>a{text-shadow:0 1px 0 #121212;color:#f2f2f2}#navbar .navbar-inner.black .brand .caret,#navbar .navbar-inner.black .nav>li>a .caret{border-bottom-color:#959595;border-top-color:#959595}#navbar .navbar-inner.black .brand:hover .caret,#navbar .navbar-inner.black .nav>li>a:hover .caret,#navbar .navbar-inner.black .brand:focus .caret,#navbar .navbar-inner.black .nav>li>a:focus .caret{border-bottom-color:#c4c4c4;border-top-color:#c4c4c4}#navbar .navbar-inner.black .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.black .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.black .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.black .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.black .nav li.dropdown.open.active>.dropdown-toggle{background-color:#3b3b3b;background-image:-moz-linear-gradient(top,#121212,#787878);background-image:-webkit-gradient(linear,0 0,0 100%,from(#121212),to(#787878));background-image:-webkit-linear-gradient(top,#121212,#787878);background-image:-o-linear-gradient(top,#121212,#787878);background-image:linear-gradient(to bottom,#121212,#787878);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff121212',endColorstr='#ff787878',GradientType=0)}#navbar .navbar-inner.black.transparent{background-color:rgba(79,79,79,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(120,120,120,0.6),rgba(18,18,18,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(120,120,120,0.6)),to(rgba(18,18,18,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(120,120,120,0.6),rgba(18,18,18,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(120,120,120,0.6),rgba(18,18,18,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(120,120,120,0.6),rgba(18,18,18,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#99787878',endColorstr='#99121212',GradientType=0)}#navbar .navbar-inner.black.transparent .brand,#navbar .navbar-inner.black.transparent .nav>li>a{text-shadow:0 1px 0 #121212;color:#f2f2f2}#navbar .navbar-inner.black.transparent .brand .caret,#navbar .navbar-inner.black.transparent .nav>li>a .caret{border-bottom-color:#959595;border-top-color:#959595}#navbar .navbar-inner.black.transparent .brand:hover .caret,#navbar .navbar-inner.black.transparent .nav>li>a:hover .caret,#navbar .navbar-inner.black.transparent .brand:focus .caret,#navbar .navbar-inner.black.transparent .nav>li>a:focus .caret{border-bottom-color:#c4c4c4;border-top-color:#c4c4c4}#navbar .navbar-inner.black.transparent .brand span{background-image:url(../img/tentacle-20x20-light.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.black.transparent .brand span{background-image:url(../img/tentacle-20x20-light@2x.png)}}#navbar .navbar-inner.black.transparent .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.black.transparent .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.black.transparent .nav li.dropdown.open.active>.dropdown-toggle{background-color:rgba(59,59,59,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(18,18,18,0.6),rgba(120,120,120,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(18,18,18,0.6)),to(rgba(120,120,120,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(18,18,18,0.6),rgba(120,120,120,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(18,18,18,0.6),rgba(120,120,120,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(18,18,18,0.6),rgba(120,120,120,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#99121212',endColorstr='#99787878',GradientType=0)}#navbar .navbar-inner.white{background-color:#e9e9e9;background-image:-moz-linear-gradient(top,#fff,#c8c8c8);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#c8c8c8));background-image:-webkit-linear-gradient(top,#fff,#c8c8c8);background-image:-o-linear-gradient(top,#fff,#c8c8c8);background-image:linear-gradient(to bottom,#fff,#c8c8c8);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffc8c8c8',GradientType=0)}#navbar .navbar-inner.white .brand,#navbar .navbar-inner.white .nav>li>a{text-shadow:0 1px 0 #fff;color:#333}#navbar .navbar-inner.white .brand .caret,#navbar .navbar-inner.white .nav>li>a .caret{border-bottom-color:#919191;border-top-color:#919191}#navbar .navbar-inner.white .brand:hover .caret,#navbar .navbar-inner.white .nav>li>a:hover .caret,#navbar .navbar-inner.white .brand:focus .caret,#navbar .navbar-inner.white .nav>li>a:focus .caret{border-bottom-color:#626262;border-top-color:#626262}#navbar .navbar-inner.white .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.white .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.white .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.white .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.white .nav li.dropdown.open.active>.dropdown-toggle{background-color:#dedede;background-image:-moz-linear-gradient(top,#c8c8c8,#fff);background-image:-webkit-gradient(linear,0 0,0 100%,from(#c8c8c8),to(#fff));background-image:-webkit-linear-gradient(top,#c8c8c8,#fff);background-image:-o-linear-gradient(top,#c8c8c8,#fff);background-image:linear-gradient(to bottom,#c8c8c8,#fff);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc8c8c8',endColorstr='#ffffffff',GradientType=0)}#navbar .navbar-inner.white.transparent{background-color:rgba(233,233,233,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(255,255,255,0.6),rgba(200,200,200,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(255,255,255,0.6)),to(rgba(200,200,200,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(255,255,255,0.6),rgba(200,200,200,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(255,255,255,0.6),rgba(200,200,200,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(255,255,255,0.6),rgba(200,200,200,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#99ffffff',endColorstr='#99c8c8c8',GradientType=0)}#navbar .navbar-inner.white.transparent .brand,#navbar .navbar-inner.white.transparent .nav>li>a{text-shadow:0 1px 0 #fff;color:#333}#navbar .navbar-inner.white.transparent .brand .caret,#navbar .navbar-inner.white.transparent .nav>li>a .caret{border-bottom-color:#919191;border-top-color:#919191}#navbar .navbar-inner.white.transparent .brand:hover .caret,#navbar .navbar-inner.white.transparent .nav>li>a:hover .caret,#navbar .navbar-inner.white.transparent .brand:focus .caret,#navbar .navbar-inner.white.transparent .nav>li>a:focus .caret{border-bottom-color:#626262;border-top-color:#626262}#navbar .navbar-inner.white.transparent .brand span{background-image:url(../img/tentacle-20x20.png)}@media(-webkit-min-device-pixel-ratio:2),(min-resolution:192dpi){#navbar .navbar-inner.white.transparent .brand span{background-image:url(../img/tentacle-20x20@2x.png)}}#navbar .navbar-inner.white.transparent .nav li.dropdown.open>.dropdown-toggle,#navbar .navbar-inner.white.transparent .nav li.dropdown.active>.dropdown-toggle,#navbar .navbar-inner.white.transparent .nav li.dropdown.open.active>.dropdown-toggle{background-color:rgba(222,222,222,0.6);background-image:"../img/trans-background.png";background-image:-moz-linear-gradient(top,rgba(200,200,200,0.6),rgba(255,255,255,0.6)),url("../img/trans-background.png");background-image:-webkit-gradient(linear,0 0,0 100%,from(rgba(200,200,200,0.6)),to(rgba(255,255,255,0.6))),url("../img/trans-background.png");background-image:-webkit-linear-gradient(top,rgba(200,200,200,0.6),rgba(255,255,255,0.6)),url("../img/trans-background.png");background-image:-o-linear-gradient(top,rgba(200,200,200,0.6),rgba(255,255,255,0.6)),url("../img/trans-background.png");background-image:linear-gradient(to bottom,rgba(200,200,200,0.6),rgba(255,255,255,0.6)),url("../img/trans-background.png");background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#99c8c8c8',endColorstr='#99ffffff',GradientType=0)}#navbar .navbar-inner .brand span{background-size:20px 20px;background-position:left center;padding-left:24px;background-repeat:no-repeat}.octoprint-container{margin-top:20px}.octoprint-container .tab-content{padding:9px 15px;border-left:1px solid #DDD;border-right:1px solid #DDD;border-bottom:1px solid #DDD;-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px}.octoprint-container .nav{margin-bottom:0}.octoprint-container .tab-content h1{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:40px;color:#333;border:0;border-bottom:1px solid #e5e5e5;font-weight:normal}.octoprint-container .accordion-heading .accordion-heading-button{float:right}.octoprint-container .accordion-heading .accordion-heading-button a{display:inline-block;padding:8px 15px;font-size:14px;line-height:20px;color:#000;text-decoration:none;background:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.octoprint-container .accordion-heading a.accordion-toggle{display:inline-block}.octoprint-container .accordion-heading [class^="icon-"],.octoprint-container .accordion-heading [class*=" icon-"]{color:#000}.print-control .btn{padding-left:4px;padding-right:4px}.upload-buttons .btn{margin-right:0}table{table-layout:fixed}table .popover-title{text-overflow:ellipsis;word-break:break-all}table th,table td{overflow:hidden}table th.gcode_files_name,table td.gcode_files_name{text-overflow:ellipsis;text-align:left;white-space:nowrap}table th.gcode_files_action,table td.gcode_files_action{width:90px;text-align:center;white-space:nowrap}table th.gcode_files_action a,table td.gcode_files_action a{text-decoration:none;color:#000}table th.gcode_files_action a.disabled,table td.gcode_files_action a.disabled{color:#ccc;cursor:default}table th.timelapse_files_name,table td.timelapse_files_name{text-overflow:ellipsis;text-align:left}table th.timelapse_files_size,table td.timelapse_files_size{text-align:right;width:55px}table th.timelapse_files_action,table td.timelapse_files_action{width:45px;text-align:center;white-space:nowrap}table th.timelapse_files_action a,table td.timelapse_files_action a{text-decoration:none;color:#000}table th.timelapse_files_action a.disabled,table td.timelapse_files_action a.disabled{color:#ccc;cursor:default}table th.settings_users_name,table td.settings_users_name{text-overflow:ellipsis;text-align:left}table th.settings_users_active,table td.settings_users_active,table th.settings_users_admin,table td.settings_users_admin{text-align:center;width:55px}table th.settings_users_actions,table td.settings_users_actions{width:60px;text-align:center;white-space:nowrap}table th.settings_users_actions a,table td.settings_users_actions a{text-decoration:none;color:#000}table th.settings_users_actions a.disabled,table td.settings_users_actions a.disabled{color:#ccc;cursor:default}table th.settings_logs_name,table td.settings_logs_name{text-overflow:ellipsis;text-align:left}table th.settings_logs_size,table td.settings_logs_size{text-align:right;width:70px}table th.settings_logs_date,table td.settings_logs_date{text-align:left;width:130px}table th.settings_logs_action,table td.settings_logs_action{width:70px;text-align:center;white-space:nowrap}table th.settings_logs_action a,table td.settings_logs_action a{text-decoration:none;color:#000}table th.settings_logs_action a.disabled,table td.settings_logs_action a.disabled{color:#ccc;cursor:default}table th.settings_printerProfiles_profiles_name,table td.settings_printerProfiles_profiles_name{text-overflow:ellipsis;text-align:left}table th.settings_printerProfiles_profiles_model,table td.settings_printerProfiles_profiles_model{text-align:left;width:250px}table th.settings_printerProfiles_profiles_action,table td.settings_printerProfiles_profiles_action{width:80px;text-align:center;white-space:nowrap}table th.settings_printerProfiles_profiles_action a,table td.settings_printerProfiles_profiles_action a{text-decoration:none;color:#000}table th.settings_printerProfiles_profiles_action a.disabled,table td.settings_printerProfiles_profiles_action a.disabled{color:#ccc;cursor:default}#temperature-graph{height:350px;width:100%;background-image:url("../img/graph-background.png");background-position:center;background-repeat:no-repeat}.tab-content,.tab-pane{overflow:visible}.tempInput{width:50px}#temp_newTemp,#temp_newBedTemp,#speed_innerWall,#speed_outerWall,#speed_fill,#speed_support,#webcam_timelapse_interval,#webcam_timelapse_postRoll,#webcam_timelapse_fps{text-align:right}ul.dropdown-menu li a{cursor:pointer}#connection_ports,#connection_baudrates,#connection_printers{width:100%}#offline_overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#offline_overlay_background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#offline_overlay_wrapper{position:absolute;top:0;bottom:0;left:0;right:0;padding-top:60px}#offline_overlay_wrapper .container{margin:auto}#webcam_container{width:100%;position:relative;outline:0}#webcam_container .flipH{-webkit-transform:scaleX(-1);-moz-transform:scaleX(-1)}#webcam_container .flipV{-webkit-transform:scaleY(-1);-moz-transform:scaleY(-1)}#webcam_container .flipH.flipV{-webkit-transform:scaleX(-1) scaleY(-1);-moz-transform:scaleX(-1) scaleY(-1)}#webcam_container .keycontrol_overlay{position:absolute;left:10px;right:10px;bottom:10px;background:rgba(0,0,0,0.5);font-size:85%;color:white;padding:0}#webcam_container .keycontrol_overlay kbd{border:1px solid #eee;border-radius:3px;margin-left:2px;margin-right:2px;font-size:90%;padding:2px;min-width:1em}#webcam_container .keycontrol_overlay .keycontrol_overlay_heading{position:relative;padding:10px;font-weight:bold}#webcam_container .keycontrol_overlay .keycontrol_overlay_column{position:relative;width:45%;padding:10px;float:left}#files .gcode_files{padding-right:7px}#files .gcode_files .entry{padding:5px;line-height:20px;border-bottom:1px solid #ddd;position:relative}#files .gcode_files .entry:hover{background-color:#f5f5f5}#files .gcode_files .entry .title{text-overflow:ellipsis;word-break:break-all}#files .gcode_files .entry .uploaded,#files .gcode_files .entry .size,#files .gcode_files .entry .additionalInfo{font-size:85%;color:#999}#files .gcode_files .entry .action-buttons{position:absolute;bottom:5px;right:5px}#files .gcode_files .entry .additionalInfo{padding-bottom:22px}#files .upload-buttons{margin-top:10px}#files .form-search{text-align:center;margin-bottom:5px!important}#control{overflow:hidden}#control .jog-panel{float:left;margin-right:19px}#control h1{text-align:left}#control .jog-panel>div{text-align:center}#control .jog-panel>div.distance{text-align:left}#control .jog-panel .slider{margin-bottom:10px}#control .box{width:30px;height:30px;margin-right:10px;margin-bottom:10px;padding-left:8px}#control .control-box{display:block;height:30px;margin-bottom:10px}#control .btn-group{margin-bottom:10px}#control .btn-group.distance>.btn{width:43px;padding:3px 0;height:30px}#control .slider-handle{width:14px;height:14px;margin-left:-7px;margin-top:-3px}#control .custom_section_horizontal .custom_control{display:inline-block}#control .custom_control .slider{margin-left:10px;margin-right:10px;margin-bottom:2px}#gcode .progress{width:582px}#gcode .progress .bar{-webkit-transition:width 0s linear;-moz-transition:width 0s linear;-o-transition:width 0s linear;transition:width 0s linear}#gcode #gcode_layer_slider{height:568px;float:right}#gcode #gcode_layer_slider .slider-handle{width:14px;height:14px;margin-left:-3px;margin-top:-7px}#gcode #gcode_command_slider .slider-handle{width:14px;height:14px;margin-left:-7px;margin-top:-3px}#term .terminal{margin-bottom:30px}#term .terminal #terminal-output{min-height:340px;margin-bottom:5px}#term #terminal-sendpanel{text-align:right}.footer ul{margin:0}.footer ul li{display:inline;margin-left:1em;font-size:85%}.footer ul li:first-child{margin-left:0}.footer ul li a{color:#555}.ui-pnotify .alert a{color:#c09853}.ui-pnotify .alert-error a,.ui-pnotify .alert-danger a{color:#b94a48}.ui-pnotify .alert-success a{color:#468847}.ui-pnotify .alert-info a{color:#3a87ad}.pnotify_additional_info .pnotify_more{font-size:85%}.text-right{text-align:right}.overflow_visible{overflow:visible!important}.border_box{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.hidden{display:none}textarea.block{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;width:100%}#drop_overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#drop_overlay.in{display:block}#drop_overlay #drop_overlay_background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#drop_overlay #drop_overlay_wrapper{position:absolute;top:0;bottom:0;left:0;right:0;padding-top:60px}#drop_overlay #drop_overlay_wrapper #drop,#drop_overlay #drop_overlay_wrapper #drop_background{position:absolute;top:0;left:0;margin-left:0;width:100%}#drop_overlay #drop_overlay_wrapper #drop_locally,#drop_overlay #drop_overlay_wrapper #drop_locally_background{position:absolute;top:0;left:50%;margin-left:-50%;width:50%;border-right:2px dashed #ccc}#drop_overlay #drop_overlay_wrapper #drop_sd,#drop_overlay #drop_overlay_wrapper #drop_sd_background{position:absolute;top:0;left:50%;margin-left:0;width:50%;border-left:2px dashed #ccc}#drop_overlay #drop_overlay_wrapper .dropzone{height:100%;z-index:10001;color:#fff;font-size:30px}#drop_overlay #drop_overlay_wrapper .dropzone i{font-size:50px}#drop_overlay #drop_overlay_wrapper .dropzone .text{display:block;text-align:center;line-height:40px;position:absolute;width:100%;bottom:5%;filter:alpha(opacity=100);-moz-opacity:1.0;-khtml-opacity:1.0;opacity:1.0}#drop_overlay #drop_overlay_wrapper .dropzone_background{width:50%;height:100%;background-color:#000;filter:alpha(opacity=25);-moz-opacity:.25;-khtml-opacity:.25;opacity:.25}#drop_overlay #drop_overlay_wrapper .dropzone_background.hover{background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#drop_overlay #drop_overlay_wrapper .dropzone_background.fade{-webkit-transition:all .3s ease-out;-moz-transition:all .3s ease-out;-ms-transition:all .3s ease-out;-o-transition:all .3s ease-out;transition:all .3s ease-out;opacity:1}.icon-sd-black-14{background:url("../img/icon-sd-black-14.png") 0 3px no-repeat;width:11px;height:17px;display:inline-block!important}.center{float:none;margin-left:auto;margin-right:auto}.slider .slider-selection{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.slider .slider-selection:hover,.slider .slider-selection:focus,.slider .slider-selection:active,.slider .slider-selection.active,.slider .slider-selection.disabled,.slider .slider-selection[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.slider .slider-selection:active,.slider .slider-selection.active{background-color:#039 \9}.slider.slider-disabled .slider-selection{background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.slider .slider-track{background-color:#f5f5f5;border:1px solid #e3e3e3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.slider.slider-disabled .slider-track{background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.slider .slider-handle{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);padding:0;margin-bottom:0;opacity:1;filter:alpha(opacity=100)}.slider .slider-handle:hover,.slider .slider-handle:focus,.slider .slider-handle:active,.slider .slider-handle.active,.slider .slider-handle.disabled,.slider .slider-handle[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.slider .slider-handle:active,.slider .slider-handle.active{background-color:#ccc \9}.slider .slider-handle:first-child{*margin-left:0}.slider .slider-handle:hover,.slider .slider-handle:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.slider .slider-handle:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.slider .slider-handle.active,.slider .slider-handle:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.slider .slider-handle.disabled,.slider .slider-handle[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.slider .slider-handle.hide{display:none}.slider .slider-handle.round{-webkit-border-radius:50%;-moz-border-radius:50%;border-radius:50%} \ No newline at end of file diff --git a/src/octoprint/static/img/trans-background.png b/src/octoprint/static/img/trans-background.png new file mode 100644 index 000000000..903bdab2c Binary files /dev/null and b/src/octoprint/static/img/trans-background.png differ diff --git a/src/octoprint/static/js/app/dataupdater.js b/src/octoprint/static/js/app/dataupdater.js index d1a1206c5..d547a16c6 100644 --- a/src/octoprint/static/js/app/dataupdater.js +++ b/src/octoprint/static/js/app/dataupdater.js @@ -6,7 +6,8 @@ function DataUpdater(allViewModels) { self._socket = undefined; self._autoReconnecting = false; self._autoReconnectTrial = 0; - self._autoReconnectTimeouts = [1, 1, 2, 3, 5, 8, 13, 20, 40, 100]; + self._autoReconnectTimeouts = [0, 1, 1, 2, 3, 5, 8, 13, 20, 40, 100]; + self._autoReconnectDialogIndex = 1; self.connect = function() { var options = {}; @@ -31,32 +32,36 @@ function DataUpdater(allViewModels) { }; self._onclose = function() { - var handled = false; - _.each(self.allViewModels, function(viewModel) { - if (handled == true) { + if (self._autoReconnectTrial >= self._autoReconnectDialogIndex) { + // Only consider it a real disconnect if the trial number has exceeded our threshold. + + var handled = false; + _.each(self.allViewModels, function(viewModel) { + if (handled == true) { + return; + } + + if (viewModel.hasOwnProperty("onServerDisconnect")) { + if (!viewModel.onServerDisconnect()) { + handled = true; + } + } + }); + + if (handled) { return; } - if (viewModel.hasOwnProperty("onServerDisconnect")) { - if (!viewModel.onServerDisconnect()) { - handled = true; - } - } - }); - - if (handled) { - return; + showOfflineOverlay( + gettext("Server is offline"), + gettext("The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below."), + self.reconnect + ); } - showOfflineOverlay( - gettext("Server is offline"), - gettext("The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below."), - self.reconnect - ); - if (self._autoReconnectTrial < self._autoReconnectTimeouts.length) { var timeout = self._autoReconnectTimeouts[self._autoReconnectTrial]; - console.log("Reconnect trial #" + self._autoReconnectTrial + ", waiting " + timeout + "s"); + log.info("Reconnect trial #" + self._autoReconnectTrial + ", waiting " + timeout + "s"); setTimeout(self.reconnect, timeout * 1000); self._autoReconnectTrial++; } else { @@ -94,6 +99,9 @@ function DataUpdater(allViewModels) { var data = e.data[prop]; + var gcodeUploadProgress = $("#gcode_upload_progress"); + var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress); + switch (prop) { case "connected": { // update the current UI API key and send it with any request @@ -102,6 +110,7 @@ function DataUpdater(allViewModels) { headers: {"X-Api-Key": UI_API_KEY} }); + var oldVersion = VERSION; VERSION = data["version"]; DISPLAY_VERSION = data["display_version"]; $("span.version").text(DISPLAY_VERSION); @@ -119,6 +128,15 @@ function DataUpdater(allViewModels) { } } + if (oldVersion != VERSION) { + // version change detected, force reloading UI - use randomized delay to reduce server load in + // the case of multiple clients + var delay = 5 + Math.floor(Math.random() * 5) + 1; + setTimeout(function() {location.reload(true);}, delay * 1000); + + // TODO notify about that, or show confirmation + } + break; } case "history": { @@ -137,45 +155,48 @@ function DataUpdater(allViewModels) { }); break; } + case "slicingProgress": { + gcodeUploadProgressBar.text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(data["progress"])})); + + _.each(self.allViewModels, function(viewModel) { + if (viewModel.hasOwnProperty("onSlicingProgress")) { + viewModel.onSlicingProgress(data["slicer"], data["model_path"], data["machinecode_path"], data["progress"]); + } + }); + break; + } case "event": { var type = data["type"]; var payload = data["payload"]; var html = ""; - var gcodeUploadProgress = $("#gcode_upload_progress"); - var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress); + log.debug("Got event " + type + " with payload: " + JSON.stringify(payload)); - if (type == "UpdatedFiles") { - _.each(self.allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onUpdatedFiles")) { - viewModel.onUpdatedFiles(payload); - } - }); - } else if (type == "MetadataAnalysisFinished") { - _.each(self.allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onMetadataAnalysisFinished")) { - viewModel.onMetadataAnalysisFinished(payload); - } - }); - } else if (type == "MovieRendering") { + if (type == "MovieRendering") { new PNotify({title: gettext("Rendering timelapse"), text: _.sprintf(gettext("Now rendering timelapse %(movie_basename)s"), payload)}); } else if (type == "MovieDone") { new PNotify({title: gettext("Timelapse ready"), text: _.sprintf(gettext("New timelapse %(movie_basename)s is done rendering."), payload)}); - timelapseViewModel.requestData(); } else if (type == "MovieFailed") { - html = "

" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failedwith return code %(returncode)s"), payload) + "

"; + html = "

" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s"), payload) + "

"; html += pnotifyAdditionalInfo('
' + payload.error + '
'); new PNotify({title: gettext("Rendering failed"), text: html, type: "error", hide: false}); } else if (type == "SlicingStarted") { gcodeUploadProgress.addClass("progress-striped").addClass("active"); gcodeUploadProgressBar.css("width", "100%"); - gcodeUploadProgressBar.text(gettext("Slicing ...")); + if (payload.progressAvailable) { + gcodeUploadProgressBar.text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: 0})); + } else { + gcodeUploadProgressBar.text(gettext("Slicing ...")); + } } else if (type == "SlicingDone") { gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); gcodeUploadProgressBar.css("width", "0%"); gcodeUploadProgressBar.text(""); - new PNotify({title: gettext("Slicing done"), text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload)}); - gcodeFilesViewModel.requestData(payload.gcode); + new PNotify({title: gettext("Slicing done"), text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload), type: "success"}); + } else if (type == "SlicingCancelled") { + gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); + gcodeUploadProgressBar.css("width", "0%"); + gcodeUploadProgressBar.text(""); } else if (type == "SlicingFailed") { gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); gcodeUploadProgressBar.css("width", "0%"); @@ -191,17 +212,33 @@ function DataUpdater(allViewModels) { gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); gcodeUploadProgressBar.css("width", "0%"); gcodeUploadProgressBar.text(""); - new PNotify({title: gettext("Streaming done"), text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload)}); + new PNotify({ + title: gettext("Streaming done"), + text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload), + type: "success" + }); gcodeFilesViewModel.requestData(payload.remote, "sdcard"); } - break; - } - case "feedbackCommandOutput": { + + var legacyEventHandlers = { + "UpdatedFiles": "onUpdatedFiles", + "MetadataStatisticsUpdated": "onMetadataStatisticsUpdated", + "MetadataAnalysisFinished": "onMetadataAnalysisFinished", + "SlicingDone": "onSlicingDone", + "SlicingCancelled": "onSlicingCancelled", + "SlicingFailed": "onSlicingFailed" + }; _.each(self.allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("fromFeedbackCommandData")) { - viewModel.fromFeedbackCommandData(data); + if (viewModel.hasOwnProperty("onEvent" + type)) { + viewModel["onEvent" + type](payload); + } else if (legacyEventHandlers.hasOwnProperty(type) && viewModel.hasOwnProperty(legacyEventHandlers[type])) { + // there might still be code that uses the old callbacks, make sure those still get called + // but log a warning + log.warn("View model " + viewModel.name + " is using legacy event handler " + legacyEventHandlers[type] + ", new handler is called " + legacyEventHandlers[type]); + viewModel[legacyEventHandlers[type]](payload); } }); + break; } case "timelapse": { @@ -212,6 +249,13 @@ function DataUpdater(allViewModels) { }); break; } + case "plugin": { + _.each(self.allViewModels, function(viewModel) { + if (viewModel.hasOwnProperty("onDataUpdaterPluginMessage")) { + viewModel.onDataUpdaterPluginMessage(data.plugin, data.data); + } + }) + } } } }; diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index a67ad4073..7f97ec462 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -52,6 +52,19 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor return matcher(self.selectedItem()); }; + self.removeItem = function(matcher) { + var item = self.getItem(matcher, true); + if (item === undefined) { + return; + } + + var index = self.allItems.indexOf(item); + if (index > -1) { + self.allItems.splice(index, 1); + self._updateItems(); + } + }; + //~~ pagination self.paginatedItems = ko.dependentObservable(function() { @@ -131,8 +144,13 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor } }; - self.getItem = function(matcher) { - var itemList = self.items(); + self.getItem = function(matcher, all) { + var itemList; + if (all !== undefined && all === true) { + itemList = self.allItems; + } else { + itemList = self.items(); + } for (var i = 0; i < itemList.length; i++) { if (matcher(itemList[i])) { return itemList[i]; @@ -324,6 +342,21 @@ function formatDuration(seconds) { return _.sprintf(gettext(/* L10N: duration format */ "%(hour)02d:%(minute)02d:%(second)02d"), {hour: h, minute: m, second: s}); } +function formatFuzzyEstimation(seconds, base) { + if (!seconds) return "-"; + if (seconds < 0) return "-"; + + var m; + if (base != undefined) { + m = moment(base); + } else { + m = moment(); + } + + m.add(seconds, "s"); + return m.fromNow(true); +} + function formatDate(unixTimestamp) { if (!unixTimestamp) return "-"; return moment.unix(unixTimestamp).format(gettext(/* L10N: Date format */ "YYYY-MM-DD HH:mm")); diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index 21e604461..ed33b1c92 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -1,5 +1,28 @@ $(function() { + //~~ Lodash setup + + _.mixin({"sprintf": sprintf, "vsprintf": vsprintf}); + + //~~ Logging setup + + log.setLevel(CONFIG_DEBUG ? "debug" : "info"); + + //~~ AJAX setup + + // work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at + // http://stackoverflow.com/questions/12506897/is-safari-on-ios-6-caching-ajax-results + $.ajaxSetup({ + type: 'POST', + headers: { "cache-control": "no-cache" } + }); + + // send the current UI API key with any request + $.ajaxSetup({ + headers: {"X-Api-Key": UI_API_KEY} + }); + //~~ Initialize i18n + var catalog = window["BABEL_TO_LOAD_" + LOCALE]; if (catalog === undefined) { catalog = {messages: undefined, plural_expr: undefined, locale: undefined, domain: undefined} @@ -25,317 +48,139 @@ $(function() { gettext("Transfering file to SD") ]; + //~~ Initialize PNotify + PNotify.prototype.options.styling = "bootstrap2"; - // work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at - // http://stackoverflow.com/questions/12506897/is-safari-on-ios-6-caching-ajax-results - $.ajaxSetup({ - type: 'POST', - headers: { "cache-control": "no-cache" } - }); - - // send the current UI API key with any request - $.ajaxSetup({ - headers: {"X-Api-Key": UI_API_KEY} - }); - - //~~ Show settings - to ensure centered - var settingsDialog = $('#settings_dialog'); - settingsDialog.on('show', function() { - _.each(allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onSettingsShown")) { - viewModel.onSettingsShown(); - } - }); - }); - settingsDialog.on('hidden', function() { - _.each(allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onSettingsHidden")) { - viewModel.onSettingsHidden(); - } - }); - }); - $('#navbar_show_settings').click(function() { - settingsDialog.modal() - .css({ - width: 'auto', - 'margin-left': function() { return -($(this).width() /2); } - }); - - return false; - }); - //~~ Initialize view models - var loginStateViewModel = new LoginStateViewModel(); - var usersViewModel = new UsersViewModel(loginStateViewModel); - var settingsViewModel = new SettingsViewModel(loginStateViewModel, usersViewModel); - var connectionViewModel = new ConnectionViewModel(loginStateViewModel, settingsViewModel); - var timelapseViewModel = new TimelapseViewModel(loginStateViewModel); - var printerStateViewModel = new PrinterStateViewModel(loginStateViewModel, timelapseViewModel); - var appearanceViewModel = new AppearanceViewModel(settingsViewModel); - var temperatureViewModel = new TemperatureViewModel(loginStateViewModel, settingsViewModel); - var controlViewModel = new ControlViewModel(loginStateViewModel, settingsViewModel); - var terminalViewModel = new TerminalViewModel(loginStateViewModel, settingsViewModel); - var gcodeFilesViewModel = new GcodeFilesViewModel(printerStateViewModel, loginStateViewModel); - var gcodeViewModel = new GcodeViewModel(loginStateViewModel, settingsViewModel); - var navigationViewModel = new NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsViewModel, usersViewModel); - var logViewModel = new LogViewModel(loginStateViewModel); - var viewModelMap = { - loginStateViewModel: loginStateViewModel, - usersViewModel: usersViewModel, - settingsViewModel: settingsViewModel, - connectionViewModel: connectionViewModel, - timelapseViewModel: timelapseViewModel, - printerStateViewModel: printerStateViewModel, - appearanceViewModel: appearanceViewModel, - temperatureViewModel: temperatureViewModel, - controlViewModel: controlViewModel, - terminalViewModel: terminalViewModel, - gcodeFilesViewModel: gcodeFilesViewModel, - gcodeViewModel: gcodeViewModel, - navigationViewModel: navigationViewModel, - logViewModel: logViewModel - }; + // the view model map is our basic look up table for dependencies that may be injected into other view models + var viewModelMap = {}; - var allViewModels = _.values(viewModelMap); - - var additionalViewModels = []; - _.each(ADDITIONAL_VIEWMODELS, function(viewModel) { + // helper to create a view model instance with injected constructor parameters from the view model map + var _createViewModelInstance = function(viewModel, viewModelMap){ var viewModelClass = viewModel[0]; var viewModelParameters = viewModel[1]; - var viewModelBindTarget = viewModel[2]; - var constructorParameters = []; - _.each(viewModelParameters, function(parameter) { - if (_.has(viewModelMap, parameter)) { - constructorParameters.push(viewModelMap[parameter]); - } else { - constructorParameters.push(undefined); + if (viewModelParameters != undefined) { + if (!_.isArray(viewModelParameters)) { + viewModelParameters = [viewModelParameters]; } - }); - var viewModelInstance = new viewModelClass(constructorParameters); - additionalViewModels.push([viewModelInstance, viewModelBindTarget]); - allViewModels.push(viewModelInstance); + // now we'll try to resolve all of the view model's constructor parameters via our view model map + var constructorParameters = _.map(viewModelParameters, function(parameter){ + return viewModelMap[parameter] + }); + } else { + constructorParameters = []; + } + + if (_.some(constructorParameters, function(parameter) { return parameter === undefined; })) { + var _extractName = function(entry) { return entry[0]; }; + var _onlyUnresolved = function(entry) { return entry[1] === undefined; }; + var missingParameters = _.map(_.filter(_.zip(viewModelParameters, constructorParameters), _onlyUnresolved), _extractName); + log.debug("Postponing", viewModel[0].name, "due to missing parameters:", missingParameters); + return; + } + + // if we came this far then we could resolve all constructor parameters, so let's construct that view model + log.debug("Constructing", viewModel[0].name, "with parameters:", viewModelParameters); + return new viewModelClass(constructorParameters); + }; + + // map any additional view model bindings we might need to make + var additionalBindings = {}; + _.each(OCTOPRINT_ADDITIONAL_BINDINGS, function(bindings) { + var viewModelId = bindings[0]; + var viewModelBindTargets = bindings[1]; + if (!_.isArray(viewModelBindTargets)) { + viewModelBindTargets = [viewModelBindTargets]; + } + + if (!additionalBindings.hasOwnProperty(viewModelId)) { + additionalBindings[viewModelId] = viewModelBindTargets; + } else { + additionalBindings[viewModelId] = additionalBindings[viewModelId].concat(viewModelBindTargets); + } }); + // helper for translating the name of a view model class into an identifier for the view model map + var _getViewModelId = function(viewModel){ + var name = viewModel[0].name; + return name.substr(0, 1).toLowerCase() + name.substr(1); // FooBarViewModel => fooBarViewModel + }; + + // instantiation loop, will make multiple passes over the list of unprocessed view models until all + // view models have been successfully instantiated with all of their dependencies or no changes can be made + // any more which means not all view models can be instantiated due to missing dependencies + var unprocessedViewModels = OCTOPRINT_VIEWMODELS.slice(); + unprocessedViewModels = unprocessedViewModels.concat(ADDITIONAL_VIEWMODELS); + + var allViewModels = []; + var allViewModelData = []; + var pass = 1; + log.info("Starting dependency resolution..."); + while (unprocessedViewModels.length > 0) { + log.debug("Dependency resolution, pass #" + pass); + var startLength = unprocessedViewModels.length; + var postponed = []; + + // now try to instantiate every one of our as of yet unprocessed view model descriptors + while (unprocessedViewModels.length > 0){ + var viewModel = unprocessedViewModels.shift(); + var viewModelId = _getViewModelId(viewModel); + + // make sure that we don't have two view models going by the same name + if (_.has(viewModelMap, viewModelId)) { + log.error("Duplicate name while instantiating " + viewModelId); + continue; + } + + var viewModelInstance = _createViewModelInstance(viewModel, viewModelMap); + + // our view model couldn't yet be instantiated, so postpone it for a bit + if (viewModelInstance === undefined) { + postponed.push(viewModel); + continue; + } + + // we could resolve the depdendencies and the view model is not defined yet => add it, it's now fully processed + var viewModelBindTargets = viewModel[2]; + if (!_.isArray(viewModelBindTargets)) { + viewModelBindTargets = [viewModelBindTargets]; + } + + if (additionalBindings.hasOwnProperty(viewModelId)) { + viewModelBindTargets = viewModelBindTargets.concat(additionalBindings[viewModelId]); + } + + allViewModelData.push([viewModelInstance, viewModelBindTargets]); + allViewModels.push(viewModelInstance); + viewModelMap[viewModelId] = viewModelInstance; + } + + // anything that's now in the postponed list has to be readded to the unprocessedViewModels + unprocessedViewModels = unprocessedViewModels.concat(postponed); + + // if we still have the same amount of items in our list of unprocessed view models it means that we + // couldn't instantiate any more view models over a whole iteration, which in turn mean we can't resolve the + // dependencies of remaining ones, so log that as an error and then quit the loop + if (unprocessedViewModels.length == startLength) { + log.error("Could not instantiate the following view models due to unresolvable dependencies:"); + _.each(unprocessedViewModels, function(entry) { + log.error(entry[0].name + " (missing: " + _.filter(entry[1], function(id) { return !_.has(viewModelMap, id); }).join(", ") + " )"); + }); + break; + } + + log.debug("Dependency resolution pass #" + pass + " finished, " + unprocessedViewModels.length + " view models left to process"); + pass++; + } + log.info("... dependency resolution done"); + var dataUpdater = new DataUpdater(allViewModels); - //~~ Temperature - - $('#tabs a[data-toggle="tab"]').on('shown', function (e) { - temperatureViewModel.updatePlot(); - terminalViewModel.updateOutput(); - }); - - //~~ File list - - $(".gcode_files").slimScroll({ - height: "306px", - size: "5px", - distance: "0", - railVisible: true, - alwaysVisible: true, - scrollBy: "102px" - }); - - //~~ Gcode upload - - function gcode_upload_done(e, data) { - var filename = undefined; - var location = undefined; - if (data.result.files.hasOwnProperty("sdcard")) { - filename = data.result.files.sdcard.name; - location = "sdcard"; - } else if (data.result.files.hasOwnProperty("local")) { - filename = data.result.files.local.name; - location = "local"; - } - gcodeFilesViewModel.requestData(filename, location); - - if (data.result.done) { - $("#gcode_upload_progress .bar").css("width", "0%"); - $("#gcode_upload_progress").removeClass("progress-striped").removeClass("active"); - $("#gcode_upload_progress .bar").text(""); - } - } - - function gcode_upload_fail(e, data) { - var error = "

" + gettext("Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and slicing support is enabled and configured.") + "

"; - error += pnotifyAdditionalInfo("
" + data.jqXHR.responseText + "
"); - new PNotify({ - title: "Upload failed", - text: error, - type: "error", - hide: false - }); - $("#gcode_upload_progress .bar").css("width", "0%"); - $("#gcode_upload_progress").removeClass("progress-striped").removeClass("active"); - $("#gcode_upload_progress .bar").text(""); - } - - function gcode_upload_progress(e, data) { - var progress = parseInt(data.loaded / data.total * 100, 10); - $("#gcode_upload_progress .bar").css("width", progress + "%"); - $("#gcode_upload_progress .bar").text(gettext("Uploading ...")); - if (progress >= 100) { - $("#gcode_upload_progress").addClass("progress-striped").addClass("active"); - $("#gcode_upload_progress .bar").text(gettext("Saving ...")); - } - } - - function enable_local_dropzone() { - $("#gcode_upload").fileupload({ - url: API_BASEURL + "files/local", - dataType: "json", - dropZone: localTarget, - done: gcode_upload_done, - fail: gcode_upload_fail, - progressall: gcode_upload_progress - }); - } - - function disable_local_dropzone() { - $("#gcode_upload").fileupload({ - url: API_BASEURL + "files/local", - dataType: "json", - dropZone: null, - done: gcode_upload_done, - fail: gcode_upload_fail, - progressall: gcode_upload_progress - }); - } - - function enable_sd_dropzone() { - $("#gcode_upload_sd").fileupload({ - url: API_BASEURL + "files/sdcard", - dataType: "json", - dropZone: $("#drop_sd"), - done: gcode_upload_done, - fail: gcode_upload_fail, - progressall: gcode_upload_progress - }); - } - - function disable_sd_dropzone() { - $("#gcode_upload_sd").fileupload({ - url: API_BASEURL + "files/sdcard", - dataType: "json", - dropZone: null, - done: gcode_upload_done, - fail: gcode_upload_fail, - progressall: gcode_upload_progress - }); - } - - var localTarget; - if (CONFIG_SD_SUPPORT) { - localTarget = $("#drop_locally"); - } else { - localTarget = $("#drop"); - } - - loginStateViewModel.isUser.subscribe(function(newValue) { - if (newValue === true) { - enable_local_dropzone(); - } else { - disable_local_dropzone(); - } - }); - - if (loginStateViewModel.isUser()) { - enable_local_dropzone(); - } else { - disable_local_dropzone(); - } - - if (CONFIG_SD_SUPPORT) { - printerStateViewModel.isSdReady.subscribe(function(newValue) { - if (newValue === true && loginStateViewModel.isUser()) { - enable_sd_dropzone(); - } else { - disable_sd_dropzone(); - } - }); - - loginStateViewModel.isUser.subscribe(function(newValue) { - if (newValue === true && printerStateViewModel.isSdReady()) { - enable_sd_dropzone(); - } else { - disable_sd_dropzone(); - } - }); - - if (printerStateViewModel.isSdReady() && loginStateViewModel.isUser()) { - enable_sd_dropzone(); - } else { - disable_sd_dropzone(); - } - } - - $(document).bind("dragover", function (e) { - var dropOverlay = $("#drop_overlay"); - var dropZone = $("#drop"); - var dropZoneLocal = $("#drop_locally"); - var dropZoneSd = $("#drop_sd"); - var dropZoneBackground = $("#drop_background"); - var dropZoneLocalBackground = $("#drop_locally_background"); - var dropZoneSdBackground = $("#drop_sd_background"); - var timeout = window.dropZoneTimeout; - - if (!timeout) { - dropOverlay.addClass('in'); - } else { - clearTimeout(timeout); - } - - var foundLocal = false; - var foundSd = false; - var found = false - var node = e.target; - do { - if (dropZoneLocal && node === dropZoneLocal[0]) { - foundLocal = true; - break; - } else if (dropZoneSd && node === dropZoneSd[0]) { - foundSd = true; - break; - } else if (dropZone && node === dropZone[0]) { - found = true; - break; - } - node = node.parentNode; - } while (node != null); - - if (foundLocal) { - dropZoneLocalBackground.addClass("hover"); - dropZoneSdBackground.removeClass("hover"); - } else if (foundSd && printerStateViewModel.isSdReady()) { - dropZoneSdBackground.addClass("hover"); - dropZoneLocalBackground.removeClass("hover"); - } else if (found) { - dropZoneBackground.addClass("hover"); - } else { - if (dropZoneLocalBackground) dropZoneLocalBackground.removeClass("hover"); - if (dropZoneSdBackground) dropZoneSdBackground.removeClass("hover"); - if (dropZoneBackground) dropZoneBackground.removeClass("hover"); - } - - window.dropZoneTimeout = setTimeout(function () { - window.dropZoneTimeout = null; - dropOverlay.removeClass("in"); - if (dropZoneLocal) dropZoneLocalBackground.removeClass("hover"); - if (dropZoneSd) dropZoneSdBackground.removeClass("hover"); - if (dropZone) dropZoneBackground.removeClass("hover"); - }, 100); - }); - - //~~ Underscore setup - - _.mixin(_.str.exports()); - - //~~ knockout.js bindings + //~~ Custom knockout.js bindings ko.bindingHandlers.popover = { init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { @@ -359,6 +204,7 @@ $(function() { return { controlsDescendantBindings: !valueAccessor() }; } }; + ko.virtualElements.allowedBindings.allowBindings = true; ko.bindingHandlers.slimScrolledForeach = { init: function(element, valueAccessor, allBindings, viewModel, bindingContext) { @@ -372,6 +218,31 @@ $(function() { } }; + ko.bindingHandlers.qrcode = { + update: function(element, valueAccessor, allBindings, viewModel, bindingContext) { + var val = ko.utils.unwrapObservable(valueAccessor()); + + var defaultOptions = { + text: "", + size: 200, + fill: "#000", + background: null, + label: "", + fontname: "sans", + fontcolor: "#000", + radius: 0, + ecLevel: "L" + }; + + var options = {}; + _.each(defaultOptions, function(value, key) { + options[key] = ko.utils.unwrapObservable(val[key]) || value; + }); + + $(element).empty().qrcode(options); + } + }; + ko.bindingHandlers.invisible = { init: function(element, valueAccessor, allBindings, viewModel, bindingContext) { if (!valueAccessor()) return; @@ -381,47 +252,72 @@ $(function() { } }; - settingsViewModel.requestData(function() { - ko.applyBindings(settingsViewModel, document.getElementById("settings_dialog")); + //~~ some additional hooks and initializations - ko.applyBindings(connectionViewModel, document.getElementById("connection_accordion")); - ko.applyBindings(printerStateViewModel, document.getElementById("state_accordion")); - ko.applyBindings(gcodeFilesViewModel, document.getElementById("files_accordion")); - ko.applyBindings(temperatureViewModel, document.getElementById("temp")); - ko.applyBindings(controlViewModel, document.getElementById("control")); - ko.applyBindings(terminalViewModel, document.getElementById("term")); - var gcode = document.getElementById("gcode"); - if (gcode) { - gcodeViewModel.initialize(); - ko.applyBindings(gcodeViewModel, gcode); + // make sure modals max out at the window height + $.fn.modal.defaults.maxHeight = function(){ + // subtract the height of the modal header and footer + return $(window).height() - 165; + }; + + // jquery plugin to select all text in an element + // originally from: http://stackoverflow.com/a/987376 + $.fn.selectText = function() { + var doc = document; + var element = this[0]; + var range, selection; + + if (doc.body.createTextRange) { + range = document.body.createTextRange(); + range.moveToElementText(element); + range.select(); + } else if (window.getSelection) { + selection = window.getSelection(); + range = document.createRange(); + range.selectNodeContents(element); + selection.removeAllRanges(); + selection.addRange(range); } - //ko.applyBindings(settingsViewModel, document.getElementById("settings_dialog")); - ko.applyBindings(navigationViewModel, document.getElementById("navbar")); - ko.applyBindings(appearanceViewModel, document.getElementsByTagName("head")[0]); - ko.applyBindings(printerStateViewModel, document.getElementById("drop_overlay")); - ko.applyBindings(logViewModel, document.getElementById("logs")); + }; - var timelapseElement = document.getElementById("timelapse"); - if (timelapseElement) { - ko.applyBindings(timelapseViewModel, timelapseElement); - } + // Use bootstrap tabdrop for tabs and pills + $('.nav-pills, .nav-tabs').tabdrop(); - // apply bindings and signal startup - _.each(additionalViewModels, function(additionalViewModel) { - if (additionalViewModel[0].hasOwnProperty("onBeforeBinding")) { - additionalViewModel[0].onBeforeBinding(); - } + // Allow components to react to tab change + var tabs = $('#tabs a[data-toggle="tab"]'); + tabs.on('show', function (e) { + var current = e.target.hash; + var previous = e.relatedTarget.hash; - // model instance, target container - ko.applyBindings(additionalViewModel[0], additionalViewModel[1]); - - if (additionalViewModel[0].hasOwnProperty("onAfterBinding")) { - additionalViewModel[0].onAfterBinding(); + _.each(allViewModels, function(viewModel) { + if (viewModel.hasOwnProperty("onTabChange")) { + viewModel.onTabChange(current, previous); } }); }); - //~~ startup commands + tabs.on('shown', function (e) { + var current = e.target.hash; + var previous = e.relatedTarget.hash; + + _.each(allViewModels, function(viewModel) { + if (viewModel.hasOwnProperty("onAfterTabChange")) { + viewModel.onAfterTabChange(current, previous); + } + }); + }); + + // Fix input element click problems on dropdowns + $(".dropdown input, .dropdown label").click(function(e) { + e.stopPropagation(); + }); + + // prevent default action for drag-n-drop + $(document).bind("drop dragover", function (e) { + e.preventDefault(); + }); + + //~~ Starting up the app _.each(allViewModels, function(viewModel) { if (viewModel.hasOwnProperty("onStartup")) { @@ -429,91 +325,84 @@ $(function() { } }); - loginStateViewModel.subscribe(function(change, data) { - if ("login" == change) { - $("#gcode_upload").fileupload("enable"); + //~~ view model binding - if (data.admin) { - usersViewModel.requestData(); + var bindViewModels = function() { + log.info("Going to bind " + allViewModelData.length + " view models..."); + _.each(allViewModelData, function(viewModelData) { + if (!Array.isArray(viewModelData) || viewModelData.length != 2) { + return; } - } else { - $("#gcode_upload").fileupload("disable"); - } - }); - //~~ UI stuff + var viewModel = viewModelData[0]; + var targets = viewModelData[1]; - var webcamDisableTimeout; - $('#tabs a[data-toggle="tab"]').on('show', function (e) { - var current = e.target; - var previous = e.relatedTarget; + if (targets === undefined) { + return; + } - if (current.hash == "#control") { - clearTimeout(webcamDisableTimeout); - var webcamImage = $("#webcam_image"); - var currentSrc = webcamImage.attr("src"); - if (currentSrc === undefined || currentSrc.trim() == "") { - var newSrc = CONFIG_WEBCAM_STREAM; - if (CONFIG_WEBCAM_STREAM.lastIndexOf("?") > -1) { - newSrc += "&"; - } else { - newSrc += "?"; + if (!_.isArray(targets)) { + targets = [targets]; + } + + if (viewModel.hasOwnProperty("onBeforeBinding")) { + viewModel.onBeforeBinding(); + } + + if (targets != undefined) { + if (!_.isArray(targets)) { + targets = [targets]; } - newSrc += new Date().getTime(); - webcamImage.attr("src", newSrc); + _.each(targets, function(target) { + if (target == undefined) { + return; + } + + var object; + if (!(target instanceof jQuery)) { + object = $(target); + } else { + object = target; + } + + if (object == undefined || !object.length) { + log.info("Did not bind view model", viewModel.constructor.name, "to target", target, "since it does not exist"); + return; + } + + var element = object.get(0); + if (element == undefined) { + log.info("Did not bind view model", viewModel.constructor.name, "to target", target, "since it does not exist"); + return; + } + + try { + ko.applyBindings(viewModel, element); + log.debug("View model", viewModel.constructor.name, "bound to", target); + } catch (exc) { + log.error("Could not bind view model", viewModel.constructor.name, "to target", target, ":", exc.stack); + } + }); } - } else if (previous.hash == "#control") { - // only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause - // more load by the constant connection creation than by the actual webcam stream - webcamDisableTimeout = setTimeout(function() { - $("#webcam_image").attr("src", ""); - }, 5000); - } - }); - $(".accordion-toggle[href='#files']").click(function() { - var files = $("#files"); - if (files.hasClass("in")) { - files.removeClass("overflow_visible"); - } else { - setTimeout(function() { - files.addClass("overflow_visible"); - }, 1000); - } - }); + if (viewModel.hasOwnProperty("onAfterBinding")) { + viewModel.onAfterBinding(); + } + }); - $.fn.modal.defaults.maxHeight = function(){ - // subtract the height of the modal header and footer - return $(window).height() - 165; + _.each(allViewModels, function(viewModel) { + if (viewModel.hasOwnProperty("onAllBound")) { + viewModel.onAllBound(allViewModels); + } + }); + log.info("... binding done"); }; - // Fix input element click problem on login dialog - $(".dropdown input, .dropdown label").click(function(e) { - e.stopPropagation(); - }); - - $(document).bind("drop dragover", function (e) { - e.preventDefault(); - }); - - $("#login_user").keyup(function(event) { - if (event.keyCode == 13) { - $("#login_pass").focus(); - } - }); - $("#login_pass").keyup(function(event) { - if (event.keyCode == 13) { - $("#login_button").click(); - } - }); - - if (CONFIG_FIRST_RUN) { - var firstRunViewModel = new FirstRunViewModel(); - ko.applyBindings(firstRunViewModel, document.getElementById("first_run_dialog")); - firstRunViewModel.showDialog(); + if (!_.has(viewModelMap, "settingsViewModel")) { + throw new Error("settingsViewModel is missing, can't run UI") } - + viewModelMap["settingsViewModel"].requestData(bindViewModels); } ); diff --git a/src/octoprint/static/js/app/viewmodels/appearance.js b/src/octoprint/static/js/app/viewmodels/appearance.js index 5ee2b5dc6..304bdb22c 100644 --- a/src/octoprint/static/js/app/viewmodels/appearance.js +++ b/src/octoprint/static/js/app/viewmodels/appearance.js @@ -1,20 +1,29 @@ -function AppearanceViewModel(settingsViewModel) { - var self = this; +$(function() { + function AppearanceViewModel(parameters) { + var self = this; - self.name = settingsViewModel.appearance_name; - self.color = settingsViewModel.appearance_color; + self.name = parameters[0].appearance_name; + self.color = parameters[0].appearance_color; + self.colorTransparent = parameters[0].appearance_colorTransparent; - self.brand = ko.computed(function() { - if (self.name()) - return gettext("OctoPrint") + ": " + self.name(); - else - return gettext("OctoPrint"); - }); + self.brand = ko.computed(function() { + if (self.name()) + return gettext("OctoPrint") + ": " + self.name(); + else + return gettext("OctoPrint"); + }); - self.title = ko.computed(function() { - if (self.name()) - return self.name() + " [" + gettext("OctoPrint") + "]"; - else - return gettext("OctoPrint"); - }); -} + self.title = ko.computed(function() { + if (self.name()) + return self.name() + " [" + gettext("OctoPrint") + "]"; + else + return gettext("OctoPrint"); + }); + } + + OCTOPRINT_VIEWMODELS.push([ + AppearanceViewModel, + ["settingsViewModel"], + "head" + ]); +}); diff --git a/src/octoprint/static/js/app/viewmodels/connection.js b/src/octoprint/static/js/app/viewmodels/connection.js index 424501280..7ccb765dc 100644 --- a/src/octoprint/static/js/app/viewmodels/connection.js +++ b/src/octoprint/static/js/app/viewmodels/connection.js @@ -1,127 +1,158 @@ -function ConnectionViewModel(loginStateViewModel, settingsViewModel) { - var self = this; +$(function() { + function ConnectionViewModel(parameters) { + var self = this; - self.loginState = loginStateViewModel; - self.settings = settingsViewModel; + self.loginState = parameters[0]; + self.settings = parameters[1]; + self.printerProfiles = parameters[2]; - self.portOptions = ko.observableArray(undefined); - self.baudrateOptions = ko.observableArray(undefined); - self.selectedPort = ko.observable(undefined); - self.selectedBaudrate = ko.observable(undefined); - self.saveSettings = ko.observable(undefined); - self.autoconnect = ko.observable(undefined); + self.printerProfiles.profiles.items.subscribe(function() { + var allProfiles = self.printerProfiles.profiles.items(); - self.isErrorOrClosed = ko.observable(undefined); - self.isOperational = ko.observable(undefined); - self.isPrinting = ko.observable(undefined); - self.isPaused = ko.observable(undefined); - self.isError = ko.observable(undefined); - self.isReady = ko.observable(undefined); - self.isLoading = ko.observable(undefined); - - self.buttonText = ko.computed(function() { - if (self.isErrorOrClosed()) - return gettext("Connect"); - else - return gettext("Disconnect"); - }) - - self.previousIsOperational = undefined; - - self.requestData = function() { - $.ajax({ - url: API_BASEURL + "connection", - method: "GET", - dataType: "json", - success: function(response) { - self.fromResponse(response); - } - }) - } - - self.fromResponse = function(response) { - var ports = response.options.ports; - var baudrates = response.options.baudrates; - var portPreference = response.options.portPreference; - var baudratePreference = response.options.baudratePreference; - - self.portOptions(ports); - self.baudrateOptions(baudrates); - - if (!self.selectedPort() && ports && ports.indexOf(portPreference) >= 0) - self.selectedPort(portPreference); - if (!self.selectedBaudrate() && baudrates && baudrates.indexOf(baudratePreference) >= 0) - self.selectedBaudrate(baudratePreference); - - self.saveSettings(false); - } - - self.fromHistoryData = function(data) { - self._processStateData(data.state); - } - - self.fromCurrentData = function(data) { - self._processStateData(data.state); - } - - self._processStateData = function(data) { - self.previousIsOperational = self.isOperational(); - - self.isErrorOrClosed(data.flags.closedOrError); - self.isOperational(data.flags.operational); - self.isPaused(data.flags.paused); - self.isPrinting(data.flags.printing); - self.isError(data.flags.error); - self.isReady(data.flags.ready); - self.isLoading(data.flags.loading); - - var connectionTab = $("#connection"); - if (self.previousIsOperational != self.isOperational()) { - if (self.isOperational() && connectionTab.hasClass("in")) { - // connection just got established, close connection tab for now - connectionTab.collapse("hide"); - } else if (!connectionTab.hasClass("in")) { - // connection just dropped, make sure connection tab is open - connectionTab.collapse("show"); - } - } - } - - self.connect = function() { - if (self.isErrorOrClosed()) { - var data = { - "command": "connect", - "port": self.selectedPort(), - "baudrate": self.selectedBaudrate(), - "autoconnect": self.settings.serial_autoconnect() - }; - - if (self.saveSettings()) - data["save"] = true; - - $.ajax({ - url: API_BASEURL + "connection", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(data), - success: function(response) { - self.settings.requestData() - } + var printerOptions = []; + _.each(allProfiles, function(profile) { + printerOptions.push({id: profile.id, name: profile.name}); }); - } else { - self.requestData(); + self.printerOptions(printerOptions); + }); + + self.printerProfiles.currentProfile.subscribe(function() { + self.selectedPrinter(self.printerProfiles.currentProfile()); + }); + + self.portOptions = ko.observableArray(undefined); + self.baudrateOptions = ko.observableArray(undefined); + self.printerOptions = ko.observableArray(undefined); + self.selectedPort = ko.observable(undefined); + self.selectedBaudrate = ko.observable(undefined); + self.selectedPrinter = ko.observable(undefined); + self.saveSettings = ko.observable(undefined); + self.autoconnect = ko.observable(undefined); + + self.isErrorOrClosed = ko.observable(undefined); + self.isOperational = ko.observable(undefined); + self.isPrinting = ko.observable(undefined); + self.isPaused = ko.observable(undefined); + self.isError = ko.observable(undefined); + self.isReady = ko.observable(undefined); + self.isLoading = ko.observable(undefined); + + self.buttonText = ko.computed(function() { + if (self.isErrorOrClosed()) + return gettext("Connect"); + else + return gettext("Disconnect"); + }); + + self.previousIsOperational = undefined; + + self.requestData = function() { $.ajax({ url: API_BASEURL + "connection", - type: "POST", + method: "GET", dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({"command": "disconnect"}) + success: function(response) { + self.fromResponse(response); + } }) - } + }; + + self.fromResponse = function(response) { + var ports = response.options.ports; + var baudrates = response.options.baudrates; + var portPreference = response.options.portPreference; + var baudratePreference = response.options.baudratePreference; + var printerPreference = response.options.printerProfilePreference; + var printerProfiles = response.options.printerProfiles; + + self.portOptions(ports); + self.baudrateOptions(baudrates); + + if (!self.selectedPort() && ports && ports.indexOf(portPreference) >= 0) + self.selectedPort(portPreference); + if (!self.selectedBaudrate() && baudrates && baudrates.indexOf(baudratePreference) >= 0) + self.selectedBaudrate(baudratePreference); + if (!self.selectedPrinter() && printerProfiles && printerProfiles.indexOf(printerPreference) >= 0) + self.selectedPrinter(printerPreference); + + self.saveSettings(false); + }; + + self.fromHistoryData = function(data) { + self._processStateData(data.state); + }; + + self.fromCurrentData = function(data) { + self._processStateData(data.state); + }; + + self._processStateData = function(data) { + self.previousIsOperational = self.isOperational(); + + self.isErrorOrClosed(data.flags.closedOrError); + self.isOperational(data.flags.operational); + self.isPaused(data.flags.paused); + self.isPrinting(data.flags.printing); + self.isError(data.flags.error); + self.isReady(data.flags.ready); + self.isLoading(data.flags.loading); + + var connectionTab = $("#connection"); + if (self.previousIsOperational != self.isOperational()) { + if (self.isOperational() && connectionTab.hasClass("in")) { + // connection just got established, close connection tab for now + connectionTab.collapse("hide"); + } else if (!connectionTab.hasClass("in")) { + // connection just dropped, make sure connection tab is open + connectionTab.collapse("show"); + } + } + }; + + self.connect = function() { + if (self.isErrorOrClosed()) { + var data = { + "command": "connect", + "port": self.selectedPort(), + "baudrate": self.selectedBaudrate(), + "printerProfile": self.selectedPrinter(), + "autoconnect": self.settings.serial_autoconnect() + }; + + if (self.saveSettings()) + data["save"] = true; + + $.ajax({ + url: API_BASEURL + "connection", + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(data), + success: function(response) { + self.settings.requestData(); + self.settings.printerProfiles.requestData(); + } + }); + } else { + self.requestData(); + $.ajax({ + url: API_BASEURL + "connection", + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify({"command": "disconnect"}) + }) + } + }; + + self.onStartup = function() { + self.requestData(); + }; } - self.onStartup = function() { - self.requestData(); - }; -} + OCTOPRINT_VIEWMODELS.push([ + ConnectionViewModel, + ["loginStateViewModel", "settingsViewModel", "printerProfilesViewModel"], + "#connection_wrapper" + ]); +}); diff --git a/src/octoprint/static/js/app/viewmodels/control.js b/src/octoprint/static/js/app/viewmodels/control.js index 5770d8451..9943a0fb3 100644 --- a/src/octoprint/static/js/app/viewmodels/control.js +++ b/src/octoprint/static/js/app/viewmodels/control.js @@ -1,244 +1,518 @@ -function ControlViewModel(loginStateViewModel, settingsViewModel) { - var self = this; +$(function() { + function ControlViewModel(parameters) { + var self = this; - self.loginState = loginStateViewModel; - self.settings = settingsViewModel; + self.loginState = parameters[0]; + self.settings = parameters[1]; - self._createToolEntry = function() { - return { - name: ko.observable(), - key: ko.observable() - } - }; - - self.isErrorOrClosed = ko.observable(undefined); - self.isOperational = ko.observable(undefined); - self.isPrinting = ko.observable(undefined); - self.isPaused = ko.observable(undefined); - self.isError = ko.observable(undefined); - self.isReady = ko.observable(undefined); - self.isLoading = ko.observable(undefined); - - self.extrusionAmount = ko.observable(undefined); - self.controls = ko.observableArray([]); - - self.tools = ko.observableArray([]); - - self.feedbackControlLookup = {}; - - self.settings.printer_numExtruders.subscribe(function(oldVal, newVal) { - var tools = []; - - var numExtruders = self.settings.printer_numExtruders(); - if (numExtruders > 1) { - // multiple extruders - for (var extruder = 0; extruder < numExtruders; extruder++) { - tools[extruder] = self._createToolEntry(); - tools[extruder]["name"](gettext("Tool") + " " + extruder); - tools[extruder]["key"]("tool" + extruder); + self._createToolEntry = function () { + return { + name: ko.observable(), + key: ko.observable() } - } else { - // only one extruder, no need to add numbers - tools[0] = self._createToolEntry(); - tools[0]["name"](gettext("Hotend")); - tools[0]["key"]("tool0"); - } - - self.tools(tools); - }); - - self.fromCurrentData = function(data) { - self._processStateData(data.state); - }; - - self.fromHistoryData = function(data) { - self._processStateData(data.state); - }; - - self._processStateData = function(data) { - self.isErrorOrClosed(data.flags.closedOrError); - self.isOperational(data.flags.operational); - self.isPaused(data.flags.paused); - self.isPrinting(data.flags.printing); - self.isError(data.flags.error); - self.isReady(data.flags.ready); - self.isLoading(data.flags.loading); - }; - - self.fromFeedbackCommandData = function(data) { - if (data.name in self.feedbackControlLookup) { - self.feedbackControlLookup[data.name](data.output); - } - }; - - self.requestData = function() { - $.ajax({ - url: API_BASEURL + "printer/command/custom", - method: "GET", - dataType: "json", - success: function(response) { - self._fromResponse(response); - } - }); - }; - - self._fromResponse = function(response) { - self.controls(self._processControls(response.controls)); - }; - - self._processControls = function(controls) { - for (var i = 0; i < controls.length; i++) { - controls[i] = self._processControl(controls[i]); - } - return controls; - }; - - self._processControl = function(control) { - if (control.type == "parametric_command" || control.type == "parametric_commands") { - for (var i = 0; i < control.input.length; i++) { - control.input[i].value = control.input[i].default; - } - } else if (control.type == "feedback_command" || control.type == "feedback") { - control.output = ko.observable(""); - self.feedbackControlLookup[control.name] = control.output; - } else if (control.type == "section") { - control.children = self._processControls(control.children); - } - return control; - }; - - self.sendJogCommand = function(axis, multiplier, distance) { - if (typeof distance === "undefined") - distance = $('#jog_distance button.active').data('distance'); - if (self.settings.getPrinterInvertAxis(axis)) { - multiplier *= -1; - } - - var data = { - "command": "jog" - }; - data[axis] = distance * multiplier; - - $.ajax({ - url: API_BASEURL + "printer/printhead", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(data) - }); - }; - - self.sendHomeCommand = function(axis) { - var data = { - "command": "home", - "axes": axis }; - $.ajax({ - url: API_BASEURL + "printer/printhead", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(data) + self.isErrorOrClosed = ko.observable(undefined); + self.isOperational = ko.observable(undefined); + self.isPrinting = ko.observable(undefined); + self.isPaused = ko.observable(undefined); + self.isError = ko.observable(undefined); + self.isReady = ko.observable(undefined); + self.isLoading = ko.observable(undefined); + + self.extrusionAmount = ko.observable(undefined); + self.controls = ko.observableArray([]); + + self.tools = ko.observableArray([]); + + self.feedRate = ko.observable(100); + self.flowRate = ko.observable(100); + + self.feedbackControlLookup = {}; + + self.controlsFromServer = []; + self.additionalControls = []; + + self.webcamDisableTimeout = undefined; + + self.keycontrolActive = ko.observable(false); + self.keycontrolHelpActive = ko.observable(false); + self.keycontrolPossible = ko.computed(function () { + return self.isOperational() && !self.isPrinting() && self.loginState.isUser() && !$.browser.mobile; + }); + self.showKeycontrols = ko.computed(function () { + return self.keycontrolActive() && self.keycontrolPossible(); }); - }; - self.sendExtrudeCommand = function() { - self._sendECommand(1); - }; + self.settings.printerProfiles.currentProfileData.subscribe(function () { + self._updateExtruderCount(); + self.settings.printerProfiles.currentProfileData().extruder.count.subscribe(self._updateExtruderCount); + }); + self._updateExtruderCount = function () { + var tools = []; - self.sendRetractCommand = function() { - self._sendECommand(-1); - }; + var numExtruders = self.settings.printerProfiles.currentProfileData().extruder.count(); + if (numExtruders > 1) { + // multiple extruders + for (var extruder = 0; extruder < numExtruders; extruder++) { + tools[extruder] = self._createToolEntry(); + tools[extruder]["name"](gettext("Tool") + " " + extruder); + tools[extruder]["key"]("tool" + extruder); + } + } else { + // only one extruder, no need to add numbers + tools[0] = self._createToolEntry(); + tools[0]["name"](gettext("Hotend")); + tools[0]["key"]("tool0"); + } - self._sendECommand = function(dir) { - var length = self.extrusionAmount(); - if (!length) length = self.settings.printer_defaultExtrusionLength(); - - var data = { - command: "extrude", - amount: length * dir + self.tools(tools); }; - $.ajax({ - url: API_BASEURL + "printer/tool", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(data) - }); - }; + self.fromCurrentData = function (data) { + self._processStateData(data.state); + }; - self.sendSelectToolCommand = function(data) { - if (!data || !data.key()) return; + self.fromHistoryData = function (data) { + self._processStateData(data.state); + }; - var data = { - command: "select", - tool: data.key() - } + self._processStateData = function (data) { + self.isErrorOrClosed(data.flags.closedOrError); + self.isOperational(data.flags.operational); + self.isPaused(data.flags.paused); + self.isPrinting(data.flags.printing); + self.isError(data.flags.error); + self.isReady(data.flags.ready); + self.isLoading(data.flags.loading); + }; - $.ajax({ - url: API_BASEURL + "printer/tool", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(data) - }); - }; - - self.sendCustomCommand = function(command) { - if (!command) - return; - - var data = undefined; - if (command.type == "command" || command.type == "parametric_command" || command.type == "feedback_command") { - // single command - data = {"command" : command.command}; - } else if (command.type == "commands" || command.type == "parametric_commands") { - // multi command - data = {"commands": command.commands}; - } - - if (command.type == "parametric_command" || command.type == "parametric_commands") { - // parametric command(s) - data["parameters"] = {}; - for (var i = 0; i < command.input.length; i++) { - data["parameters"][command.input[i].parameter] = command.input[i].value; + self.onEventRegisteredMessageReceived = function(payload) { + if (payload.key in self.feedbackControlLookup) { + var outputs = self.feedbackControlLookup[payload.key]; + _.each(payload.outputs, function(value, key) { + if (outputs.hasOwnProperty(key)) { + outputs[key](value); + } + }); } - } + }; - if (data === undefined) - return; + self.rerenderControls = function () { + var allControls = self.controlsFromServer.concat(self.additionalControls); + self.controls(self._processControls(allControls)) + }; - $.ajax({ - url: API_BASEURL + "printer/command", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(data) - }) - }; + self.requestData = function () { + $.ajax({ + url: API_BASEURL + "printer/command/custom", + method: "GET", + dataType: "json", + success: function (response) { + self._fromResponse(response); + } + }); + }; - self.displayMode = function(customControl) { - switch (customControl.type) { - case "section": - return "customControls_sectionTemplate"; - case "command": - case "commands": - return "customControls_commandTemplate"; - case "parametric_command": - case "parametric_commands": - return "customControls_parametricCommandTemplate"; - case "feedback_command": - return "customControls_feedbackCommandTemplate"; - case "feedback": - return "customControls_feedbackTemplate"; - default: - return "customControls_emptyTemplate"; - } - }; + self._fromResponse = function (response) { + self.controlsFromServer = response.controls; + self.rerenderControls(); + }; - self.onStartup = function() { - self.requestData(); - }; -} + self._processControls = function (controls) { + for (var i = 0; i < controls.length; i++) { + controls[i] = self._processControl(controls[i]); + } + return controls; + }; + + self._processControl = function (control) { + if (control.hasOwnProperty("processed") && control.processed) { + return control; + } + + if (control.hasOwnProperty("template") && control.hasOwnProperty("key") && control.hasOwnProperty("template_key") && !control.hasOwnProperty("output")) { + control.output = ko.observable(""); + if (!self.feedbackControlLookup.hasOwnProperty(control.key)) { + self.feedbackControlLookup[control.key] = {}; + } + self.feedbackControlLookup[control.key][control.template_key] = control.output; + } + + if (control.hasOwnProperty("children")) { + control.children = self._processControls(control.children); + if (!control.hasOwnProperty("layout") || !(control.layout == "vertical" || control.layout == "horizontal")) { + control.layout = "vertical"; + } + } + + if (control.hasOwnProperty("input")) { + for (var i = 0; i < control.input.length; i++) { + control.input[i].value = ko.observable(control.input[i].default); + if (!control.input[i].hasOwnProperty("slider")) { + control.input[i].slider = false; + } + } + } + + var js; + if (control.hasOwnProperty("javascript")) { + js = control.javascript; + + // if js is a function everything's fine already, but if it's a string we need to eval that first + if (!_.isFunction(js)) { + control.javascript = function (data) { + eval(js); + }; + } + } + + if (control.hasOwnProperty("enabled")) { + js = control.enabled; + + // if js is a function everything's fine already, but if it's a string we need to eval that first + if (!_.isFunction(js)) { + control.enabled = function (data) { + return eval(js); + } + } + } + + control.processed = true; + return control; + }; + + self.isCustomEnabled = function (data) { + if (data.hasOwnProperty("enabled")) { + return data.enabled(data); + } else { + return self.isOperational() && self.loginState.isUser(); + } + }; + + self.clickCustom = function (data) { + var callback; + if (data.hasOwnProperty("javascript")) { + callback = data.javascript; + } else { + callback = self.sendCustomCommand; + } + + if (data.confirm) { + var confirmationDialog = $("#confirmation_dialog"); + var confirmationDialogAck = $(".confirmation_dialog_acknowledge", confirmationDialog); + + $(".confirmation_dialog_message", confirmationDialog).text(data.confirm); + confirmationDialogAck.unbind("click"); + confirmationDialogAck.bind("click", function (e) { + e.preventDefault(); + $("#confirmation_dialog").modal("hide"); + callback(data); + }); + confirmationDialog.modal("show"); + } else { + callback(data); + } + }; + + self.sendJogCommand = function (axis, multiplier, distance) { + if (typeof distance === "undefined") + distance = $('#jog_distance button.active').data('distance'); + if (self.settings.printerProfiles.currentProfileData() && self.settings.printerProfiles.currentProfileData()["axes"] && self.settings.printerProfiles.currentProfileData()["axes"][axis] && self.settings.printerProfiles.currentProfileData()["axes"][axis]["inverted"]()) { + multiplier *= -1; + } + + var data = { + "command": "jog" + }; + data[axis] = distance * multiplier; + + self.sendPrintHeadCommand(data); + }; + + self.sendHomeCommand = function (axis) { + self.sendPrintHeadCommand({ + "command": "home", + "axes": axis + }); + }; + + self.sendFeedRateCommand = function () { + self.sendPrintHeadCommand({ + "command": "feedrate", + "factor": self.feedRate() + }); + }; + + self.sendExtrudeCommand = function () { + self._sendECommand(1); + }; + + self.sendRetractCommand = function () { + self._sendECommand(-1); + }; + + self.sendFlowRateCommand = function () { + self.sendToolCommand({ + "command": "flowrate", + "factor": self.flowRate() + }); + }; + + self._sendECommand = function (dir) { + var length = self.extrusionAmount(); + if (!length) length = self.settings.printer_defaultExtrusionLength(); + + self.sendToolCommand({ + command: "extrude", + amount: length * dir + }); + }; + + self.sendSelectToolCommand = function (data) { + if (!data || !data.key()) return; + + self.sendToolCommand({ + command: "select", + tool: data.key() + }); + }; + + self.sendPrintHeadCommand = function (data) { + $.ajax({ + url: API_BASEURL + "printer/printhead", + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(data) + }); + }; + + self.sendToolCommand = function (data) { + $.ajax({ + url: API_BASEURL + "printer/tool", + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(data) + }); + }; + + self.sendCustomCommand = function (command) { + if (!command) + return; + + var data = undefined; + if (command.hasOwnProperty("command")) { + // single command + data = {"command": command.command}; + } else if (command.hasOwnProperty("commands")) { + // multi command + data = {"commands": command.commands}; + } else if (command.hasOwnProperty("script")) { + data = {"script": command.script}; + if (command.hasOwnProperty("context")) { + data["context"] = command.context; + } + } else { + return; + } + + if (command.hasOwnProperty("input")) { + // parametric command(s) + data["parameters"] = {}; + _.each(command.input, function(input) { + if (!input.hasOwnProperty("parameter") || !input.hasOwnProperty("value")) { + return; + } + + data["parameters"][input.parameter] = input.value(); + }); + } + + $.ajax({ + url: API_BASEURL + "printer/command", + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(data) + }) + }; + + self.displayMode = function (customControl) { + if (customControl.hasOwnProperty("children")) { + return "customControls_containerTemplate"; + } else { + return "customControls_controlTemplate"; + } + }; + + self.rowCss = function (customControl) { + var span = "span2"; + var offset = ""; + if (customControl.hasOwnProperty("width")) { + span = "span" + customControl.width; + } + if (customControl.hasOwnProperty("offset")) { + offset = "offset" + customControl.offset; + } + return span + " " + offset; + }; + + self.onStartup = function () { + self.requestData(); + }; + + self.onTabChange = function (current, previous) { + if (current == "#control") { + if (self.webcamDisableTimeout != undefined) { + clearTimeout(self.webcamDisableTimeout); + } + var webcamImage = $("#webcam_image"); + var currentSrc = webcamImage.attr("src"); + if (currentSrc === undefined || currentSrc.trim() == "") { + var newSrc = CONFIG_WEBCAM_STREAM; + if (CONFIG_WEBCAM_STREAM.lastIndexOf("?") > -1) { + newSrc += "&"; + } else { + newSrc += "?"; + } + newSrc += new Date().getTime(); + + webcamImage.attr("src", newSrc); + } + } else if (previous == "#control") { + // only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause + // more load by the constant connection creation than by the actual webcam stream + self.webcamDisableTimeout = setTimeout(function () { + $("#webcam_image").attr("src", ""); + }, 5000); + } + }; + + self.onAllBound = function (allViewModels) { + var additionalControls = []; + _.each(allViewModels, function (viewModel) { + if (viewModel.hasOwnProperty("getAdditionalControls")) { + additionalControls = additionalControls.concat(viewModel.getAdditionalControls()); + } + }); + if (additionalControls.length > 0) { + self.additionalControls = additionalControls; + self.rerenderControls(); + } + }; + + self.onFocus = function (data, event) { + if (!self.settings.feature_keyboardControl()) return; + self.keycontrolActive(true); + }; + + self.onMouseOver = function (data, event) { + if (!self.settings.feature_keyboardControl()) return; + $("#webcam_container").focus(); + self.keycontrolActive(true); + }; + + self.onMouseOut = function (data, event) { + if (!self.settings.feature_keyboardControl()) return; + $("#webcam_container").blur(); + self.keycontrolActive(false); + }; + + self.toggleKeycontrolHelp = function () { + self.keycontrolHelpActive(!self.keycontrolHelpActive()); + }; + + self.onKeyDown = function (data, event) { + if (!self.settings.feature_keyboardControl()) return; + + var button = undefined; + var visualizeClick = true; + + switch (event.which) { + case 37: // left arrow key + // X- + button = $("#control-xdec"); + break; + case 38: // up arrow key + // Y+ + button = $("#control-yinc"); + break; + case 39: // right arrow key + // X+ + button = $("#control-xinc"); + break; + case 40: // down arrow key + // Y- + button = $("#control-ydec"); + break; + case 49: // number 1 + case 97: // numpad 1 + // Distance 0.1 + button = $("#control-distance01"); + visualizeClick = false; + break; + case 50: // number 2 + case 98: // numpad 2 + // Distance 1 + button = $("#control-distance1"); + visualizeClick = false; + break; + case 51: // number 3 + case 99: // numpad 3 + // Distance 10 + button = $("#control-distance10"); + visualizeClick = false; + break; + case 52: // number 4 + case 100: // numpad 4 + // Distance 100 + button = $("#control-distance100"); + visualizeClick = false; + break; + case 33: // page up key + case 87: // w key + // z lift up + button = $("#control-zinc"); + break; + case 34: // page down key + case 83: // s key + // z lift down + button = $("#control-zdec"); + break; + case 36: // home key + // xy home + button = $("#control-xyhome"); + break; + case 35: // end key + // z home + button = $("#control-zhome"); + break; + default: + event.preventDefault(); + return false; + } + + if (button === undefined) { + return false; + } else { + event.preventDefault(); + if (visualizeClick) { + button.addClass("active"); + setTimeout(function () { + button.removeClass("active"); + }, 150); + } + button.click(); + } + }; + + } + + OCTOPRINT_VIEWMODELS.push([ + ControlViewModel, + ["loginStateViewModel", "settingsViewModel"], + "#control" + ]); +}); diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index ed28e9c72..cde25948c 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -1,325 +1,578 @@ -function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel) { - var self = this; +$(function() { + function GcodeFilesViewModel(parameters) { + var self = this; - self.printerState = printerStateViewModel; - self.loginState = loginStateViewModel; + self.printerState = parameters[0]; + self.loginState = parameters[1]; + self.slicing = parameters[2]; - self.isErrorOrClosed = ko.observable(undefined); - self.isOperational = ko.observable(undefined); - self.isPrinting = ko.observable(undefined); - self.isPaused = ko.observable(undefined); - self.isError = ko.observable(undefined); - self.isReady = ko.observable(undefined); - self.isLoading = ko.observable(undefined); - self.isSdReady = ko.observable(undefined); + self.isErrorOrClosed = ko.observable(undefined); + self.isOperational = ko.observable(undefined); + self.isPrinting = ko.observable(undefined); + self.isPaused = ko.observable(undefined); + self.isError = ko.observable(undefined); + self.isReady = ko.observable(undefined); + self.isLoading = ko.observable(undefined); + self.isSdReady = ko.observable(undefined); - self.searchQuery = ko.observable(undefined); - self.searchQuery.subscribe(function() { - self.performSearch(); - }); + self.searchQuery = ko.observable(undefined); + self.searchQuery.subscribe(function() { + self.performSearch(); + }); - self.freeSpace = ko.observable(undefined); - self.freeSpaceString = ko.computed(function() { - if (!self.freeSpace()) - return "-"; - return formatSize(self.freeSpace()); - }); + self.freeSpace = ko.observable(undefined); + self.freeSpaceString = ko.computed(function() { + if (!self.freeSpace()) + return "-"; + return formatSize(self.freeSpace()); + }); - // initialize list helper - self.listHelper = new ItemListHelper( - "gcodeFiles", - { - "name": function(a, b) { - // sorts ascending - if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1; - if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1; - return 0; + self.uploadButton = undefined; + + // initialize list helper + self.listHelper = new ItemListHelper( + "gcodeFiles", + { + "name": function(a, b) { + // sorts ascending + if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1; + if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1; + return 0; + }, + "upload": function(a, b) { + // sorts descending + if (b["date"] === undefined || a["date"] > b["date"]) return -1; + if (a["date"] < b["date"]) return 1; + return 0; + }, + "size": function(a, b) { + // sorts descending + if (b["bytes"] === undefined || a["bytes"] > b["bytes"]) return -1; + if (a["bytes"] < b["bytes"]) return 1; + return 0; + } }, - "upload": function(a, b) { - // sorts descending - if (b["date"] === undefined || a["date"] > b["date"]) return -1; - if (a["date"] < b["date"]) return 1; - return 0; + { + "printed": function(file) { + return !(file["prints"] && file["prints"]["success"] && file["prints"]["success"] > 0); + }, + "sd": function(file) { + return file["origin"] && file["origin"] == "sdcard"; + }, + "local": function(file) { + return !(file["origin"] && file["origin"] == "sdcard"); + }, + "machinecode": function(file) { + return file["type"] && file["type"] == "machinecode"; + }, + "model": function(file) { + return file["type"] && file["type"] == "model"; + } }, - "size": function(a, b) { - // sorts descending - if (b["bytes"] === undefined || a["bytes"] > b["bytes"]) return -1; - if (a["bytes"] < b["bytes"]) return 1; - return 0; + "name", + [], + [["sd", "local"], ["machinecode", "model"]], + 0 + ); + + self.isLoadActionPossible = ko.computed(function() { + return self.loginState.isUser() && !self.isPrinting() && !self.isPaused() && !self.isLoading(); + }); + + self.isLoadAndPrintActionPossible = ko.computed(function() { + return self.loginState.isUser() && self.isOperational() && self.isLoadActionPossible(); + }); + + self.printerState.filename.subscribe(function(newValue) { + self.highlightFilename(newValue); + }); + + self.highlightFilename = function(filename) { + if (filename == undefined) { + self.listHelper.selectNone(); + } else { + self.listHelper.selectItem(function(item) { + return item.name == filename; + }); } - }, - { - "printed": function(file) { - return !(file["prints"] && file["prints"]["success"] && file["prints"]["success"] > 0); - }, - "sd": function(file) { - return file["origin"] && file["origin"] == "sdcard"; - }, - "local": function(file) { - return !(file["origin"] && file["origin"] == "sdcard"); - } - }, - "name", - [], - [["sd", "local"]], - 0 - ); + }; - self.isLoadActionPossible = ko.computed(function() { - return self.loginState.isUser() && !self.isPrinting() && !self.isPaused() && !self.isLoading(); - }); + self.fromCurrentData = function(data) { + self._processStateData(data.state); + }; - self.isLoadAndPrintActionPossible = ko.computed(function() { - return self.loginState.isUser() && self.isOperational() && self.isLoadActionPossible(); - }); + self.fromHistoryData = function(data) { + self._processStateData(data.state); + }; - self.printerState.filename.subscribe(function(newValue) { - self.highlightFilename(newValue); - }); + self._processStateData = function(data) { + self.isErrorOrClosed(data.flags.closedOrError); + self.isOperational(data.flags.operational); + self.isPaused(data.flags.paused); + self.isPrinting(data.flags.printing); + self.isError(data.flags.error); + self.isReady(data.flags.ready); + self.isLoading(data.flags.loading); + self.isSdReady(data.flags.sdReady); + }; - self.highlightFilename = function(filename) { - if (filename == undefined) { - self.listHelper.selectNone(); - } else { - self.listHelper.selectItem(function(item) { - return item.name == filename; + self._otherRequestInProgress = false; + self.requestData = function(filenameToFocus, locationToFocus) { + if (self._otherRequestInProgress) return; + + self._otherRequestInProgress = true; + $.ajax({ + url: API_BASEURL + "files", + method: "GET", + dataType: "json", + success: function(response) { + self.fromResponse(response, filenameToFocus, locationToFocus); + self._otherRequestInProgress = false; + }, + error: function() { + self._otherRequestInProgress = false; + } }); - } - }; + }; - self.fromCurrentData = function(data) { - self._processStateData(data.state); - }; + self.fromResponse = function(response, filenameToFocus, locationToFocus) { + var files = response.files; + _.each(files, function(element, index, list) { + if (!element.hasOwnProperty("size")) element.size = undefined; + if (!element.hasOwnProperty("date")) element.date = undefined; + }); + self.listHelper.updateItems(files); - self.fromHistoryData = function(data) { - self._processStateData(data.state); - }; - - self._processStateData = function(data) { - self.isErrorOrClosed(data.flags.closedOrError); - self.isOperational(data.flags.operational); - self.isPaused(data.flags.paused); - self.isPrinting(data.flags.printing); - self.isError(data.flags.error); - self.isReady(data.flags.ready); - self.isLoading(data.flags.loading); - self.isSdReady(data.flags.sdReady); - }; - - self._otherRequestInProgress = false; - self.requestData = function(filenameToFocus, locationToFocus) { - if (self._otherRequestInProgress) return; - - self._otherRequestInProgress = true; - $.ajax({ - url: API_BASEURL + "files", - method: "GET", - dataType: "json", - success: function(response) { - self.fromResponse(response, filenameToFocus, locationToFocus); - self._otherRequestInProgress = false; - }, - error: function() { - self._otherRequestInProgress = false; - } - }); - }; - - self.fromResponse = function(response, filenameToFocus, locationToFocus) { - var files = response.files; - _.each(files, function(element, index, list) { - if (!element.hasOwnProperty("size")) element.size = undefined; - if (!element.hasOwnProperty("date")) element.date = undefined; - }); - self.listHelper.updateItems(files); - - if (filenameToFocus) { - // got a file to scroll to - if (locationToFocus === undefined) { - locationToFocus = "local"; - } - var entryElement = self.getEntryElement({name: filenameToFocus, origin: locationToFocus}); - if (entryElement) { - var entryOffset = entryElement.offsetTop; - $(".gcode_files").slimScroll({ scrollTo: entryOffset + "px" }); - } - } - - if (response.free) { - self.freeSpace(response.free); - } - - self.highlightFilename(self.printerState.filename()); - }; - - self.loadFile = function(filename, printAfterLoad) { - var file = self.listHelper.getItem(function(item) {return item.name == filename}); - if (!file || !file.refs || !file.refs.hasOwnProperty("resource")) return; - - $.ajax({ - url: file.refs.resource, - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({command: "select", print: printAfterLoad}) - }); - }; - - self.removeFile = function(filename) { - var file = self.listHelper.getItem(function(item) {return item.name == filename}); - if (!file || !file.refs || !file.refs.hasOwnProperty("resource")) return; - - var origin; - if (file.origin === undefined) { - origin = "local"; - } else { - origin = file.origin; - } - - $.ajax({ - url: file.refs.resource, - type: "DELETE", - success: function() { - self.requestData(); - } - }); - }; - - self.initSdCard = function() { - self._sendSdCommand("init"); - }; - - self.releaseSdCard = function() { - self._sendSdCommand("release"); - }; - - self.refreshSdFiles = function() { - self._sendSdCommand("refresh"); - }; - - self._sendSdCommand = function(command) { - $.ajax({ - url: API_BASEURL + "printer/sd", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({command: command}) - }); - }; - - self.downloadLink = function(data) { - if (data["refs"] && data["refs"]["download"]) { - return data["refs"]["download"]; - } else { - return false; - } - }; - - self.lastTimePrinted = function(data) { - if (data["prints"] && data["prints"]["last"] && data["prints"]["last"]["date"]) { - return data["prints"]["last"]["date"]; - } else { - return "-"; - } - }; - - self.getSuccessClass = function(data) { - if (!data["prints"] || !data["prints"]["last"]) { - return ""; - } - return data["prints"]["last"]["success"] ? "text-success" : "text-error"; - }; - - self.getEntryId = function(data) { - return "gcode_file_" + md5(data["name"] + ":" + data["origin"]); - }; - - self.getEntryElement = function(data) { - var entryId = self.getEntryId(data); - var entryElements = $("#" + entryId); - if (entryElements && entryElements[0]) { - return entryElements[0]; - } else { - return undefined; - } - }; - - self.enableRemove = function(data) { - return self.loginState.isUser() && !(self.listHelper.isSelected(data) && (self.isPrinting() || self.isPaused())); - }; - - self.enableSelect = function(data, printAfterSelect) { - var isLoadActionPossible = self.loginState.isUser() && self.isOperational() && !(self.isPrinting() || self.isPaused() || self.isLoading()); - return isLoadActionPossible && !self.listHelper.isSelected(data); - }; - - self.enableAdditionalData = function(data) { - return data["gcodeAnalysis"] || data["prints"] && data["prints"]["last"]; - }; - - self.toggleAdditionalData = function(data) { - var entryElement = self.getEntryElement(data); - if (!entryElement) return; - - var additionalInfo = $(".additionalInfo", entryElement); - additionalInfo.slideToggle("fast", function() { - $(".toggleAdditionalData i", entryElement).toggleClass("icon-chevron-down icon-chevron-up"); - }); - }; - - self.getAdditionalData = function(data) { - var output = ""; - if (data["gcodeAnalysis"]) { - if (data["gcodeAnalysis"]["filament"] && typeof(data["gcodeAnalysis"]["filament"]) == "object") { - var filament = data["gcodeAnalysis"]["filament"]; - if (_.keys(filament).length == 1) { - output += gettext("Filament") + ": " + formatFilament(data["gcodeAnalysis"]["filament"]["tool" + 0]) + "
"; - } else if (_.keys(filament).length > 1) { - for (var toolKey in filament) { - if (!_.startsWith(toolKey, "tool") || !filament[toolKey] || !filament[toolKey].hasOwnProperty("length") || filament[toolKey]["length"] <= 0) continue; - - output += gettext("Filament") + " (" + gettext("Tool") + " " + toolKey.substr("tool".length) + "): " + formatFilament(filament[toolKey]) + "
"; - } + if (filenameToFocus) { + // got a file to scroll to + if (locationToFocus === undefined) { + locationToFocus = "local"; + } + var entryElement = self.getEntryElement({name: filenameToFocus, origin: locationToFocus}); + if (entryElement) { + var entryOffset = entryElement.offsetTop; + $(".gcode_files").slimScroll({ scrollTo: entryOffset + "px" }); } } - output += gettext("Estimated Print Time") + ": " + formatDuration(data["gcodeAnalysis"]["estimatedPrintTime"]) + "
"; - } - if (data["prints"] && data["prints"]["last"]) { - output += gettext("Last Printed") + ": " + formatTimeAgo(data["prints"]["last"]["date"]) + "
"; - if (data["prints"]["last"]["lastPrintTime"]) { - output += gettext("Last Print Time") + ": " + formatDuration(data["prints"]["last"]["lastPrintTime"]); + + if (response.free) { + self.freeSpace(response.free); } - } - return output; - }; - self.performSearch = function() { - var query = self.searchQuery(); - if (query !== undefined && query.trim() != "") { - self.listHelper.changeSearchFunction(function(entry) { - return entry && entry["name"].toLocaleLowerCase().indexOf(query) > -1; + self.highlightFilename(self.printerState.filename()); + }; + + self.loadFile = function(file, printAfterLoad) { + if (!file || !file.refs || !file.refs.hasOwnProperty("resource")) return; + + $.ajax({ + url: file.refs.resource, + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify({command: "select", print: printAfterLoad}) }); - } else { - self.listHelper.resetSearch(); - } - }; + }; - self.onDataUpdaterReconnect = function() { - self.requestData(); - }; + self.removeFile = function(file) { + if (!file || !file.refs || !file.refs.hasOwnProperty("resource")) return; - self.onStartup = function() { - self.requestData(); - }; + $.ajax({ + url: file.refs.resource, + type: "DELETE", + success: function() { + self.requestData(); + } + }); + }; - self.onUpdatedFiles = function(payload) { - if (payload.type == "gcode") { + self.sliceFile = function(file) { + if (!file) return; + + self.slicing.show(file.origin, file.name, true); + }; + + self.initSdCard = function() { + self._sendSdCommand("init"); + }; + + self.releaseSdCard = function() { + self._sendSdCommand("release"); + }; + + self.refreshSdFiles = function() { + self._sendSdCommand("refresh"); + }; + + self._sendSdCommand = function(command) { + $.ajax({ + url: API_BASEURL + "printer/sd", + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify({command: command}) + }); + }; + + self.downloadLink = function(data) { + if (data["refs"] && data["refs"]["download"]) { + return data["refs"]["download"]; + } else { + return false; + } + }; + + self.lastTimePrinted = function(data) { + if (data["prints"] && data["prints"]["last"] && data["prints"]["last"]["date"]) { + return data["prints"]["last"]["date"]; + } else { + return "-"; + } + }; + + self.getSuccessClass = function(data) { + if (!data["prints"] || !data["prints"]["last"]) { + return ""; + } + return data["prints"]["last"]["success"] ? "text-success" : "text-error"; + }; + + self.templateFor = function(data) { + return "files_template_" + data.type; + }; + + self.getEntryId = function(data) { + return "gcode_file_" + md5(data["origin"] + ":" + data["name"]); + }; + + self.getEntryElement = function(data) { + var entryId = self.getEntryId(data); + var entryElements = $("#" + entryId); + if (entryElements && entryElements[0]) { + return entryElements[0]; + } else { + return undefined; + } + }; + + self.enableRemove = function(data) { + return self.loginState.isUser() && !_.contains(self.printerState.busyFiles(), data.origin + ":" + data.name); + }; + + self.enableSelect = function(data, printAfterSelect) { + var isLoadActionPossible = self.loginState.isUser() && self.isOperational() && !(self.isPrinting() || self.isPaused() || self.isLoading()); + return isLoadActionPossible && !self.listHelper.isSelected(data); + }; + + self.enableSlicing = function(data) { + return self.loginState.isUser() && self.slicing.enableSlicingDialog(); + }; + + self.enableAdditionalData = function(data) { + return data["gcodeAnalysis"] || data["prints"] && data["prints"]["last"]; + }; + + self.toggleAdditionalData = function(data) { + var entryElement = self.getEntryElement(data); + if (!entryElement) return; + + var additionalInfo = $(".additionalInfo", entryElement); + additionalInfo.slideToggle("fast", function() { + $(".toggleAdditionalData i", entryElement).toggleClass("icon-chevron-down icon-chevron-up"); + }); + }; + + self.getAdditionalData = function(data) { + var output = ""; + if (data["gcodeAnalysis"]) { + if (data["gcodeAnalysis"]["filament"] && typeof(data["gcodeAnalysis"]["filament"]) == "object") { + var filament = data["gcodeAnalysis"]["filament"]; + if (_.keys(filament).length == 1) { + output += gettext("Filament") + ": " + formatFilament(data["gcodeAnalysis"]["filament"]["tool" + 0]) + "
"; + } else if (_.keys(filament).length > 1) { + for (var toolKey in filament) { + if (!_.startsWith(toolKey, "tool") || !filament[toolKey] || !filament[toolKey].hasOwnProperty("length") || filament[toolKey]["length"] <= 0) continue; + + output += gettext("Filament") + " (" + gettext("Tool") + " " + toolKey.substr("tool".length) + "): " + formatFilament(filament[toolKey]) + "
"; + } + } + } + output += gettext("Estimated Print Time") + ": " + formatDuration(data["gcodeAnalysis"]["estimatedPrintTime"]) + "
"; + } + if (data["prints"] && data["prints"]["last"]) { + output += gettext("Last Printed") + ": " + formatTimeAgo(data["prints"]["last"]["date"]) + "
"; + if (data["prints"]["last"]["lastPrintTime"]) { + output += gettext("Last Print Time") + ": " + formatDuration(data["prints"]["last"]["lastPrintTime"]); + } + } + return output; + }; + + self.performSearch = function() { + var query = self.searchQuery(); + if (query !== undefined && query.trim() != "") { + self.listHelper.changeSearchFunction(function(entry) { + return entry && entry["name"].toLocaleLowerCase().indexOf(query) > -1; + }); + } else { + self.listHelper.resetSearch(); + } + }; + + self.onDataUpdaterReconnect = function() { self.requestData(); - } - }; + }; - self.onMetadataAnalysisFinished = function(payload) { - self.requestData(); + self.onStartup = function() { + $(".accordion-toggle[data-target='#files']").click(function() { + var files = $("#files"); + if (files.hasClass("in")) { + files.removeClass("overflow_visible"); + } else { + setTimeout(function() { + files.addClass("overflow_visible"); + }, 100); + } + }); + + $(".gcode_files").slimScroll({ + height: "306px", + size: "5px", + distance: "0", + railVisible: true, + alwaysVisible: true, + scrollBy: "102px" + }); + + //~~ Gcode upload + + self.uploadButton = $("#gcode_upload"); + self.loginState.subscribe(function(change, data) { + if ("login" == change) { + self.uploadButton.fileupload("enable"); + } else { + self.uploadButton.fileupload("disable"); + } + }); + + function gcode_upload_done(e, data) { + var filename = undefined; + var location = undefined; + if (data.result.files.hasOwnProperty("sdcard")) { + filename = data.result.files.sdcard.name; + location = "sdcard"; + } else if (data.result.files.hasOwnProperty("local")) { + filename = data.result.files.local.name; + location = "local"; + } + self.requestData(filename, location); + + if (_.endsWith(filename.toLowerCase(), ".stl")) { + self.slicing.show(location, filename); + } + + if (data.result.done) { + $("#gcode_upload_progress .bar").css("width", "0%"); + $("#gcode_upload_progress").removeClass("progress-striped").removeClass("active"); + $("#gcode_upload_progress .bar").text(""); + } + } + + function gcode_upload_fail(e, data) { + var error = "

" + gettext("Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\".") + "

"; + error += pnotifyAdditionalInfo("
" + data.jqXHR.responseText + "
"); + new PNotify({ + title: "Upload failed", + text: error, + type: "error", + hide: false + }); + $("#gcode_upload_progress .bar").css("width", "0%"); + $("#gcode_upload_progress").removeClass("progress-striped").removeClass("active"); + $("#gcode_upload_progress .bar").text(""); + } + + function gcode_upload_progress(e, data) { + var progress = parseInt(data.loaded / data.total * 100, 10); + $("#gcode_upload_progress .bar").css("width", progress + "%"); + $("#gcode_upload_progress .bar").text(gettext("Uploading ...")); + if (progress >= 100) { + $("#gcode_upload_progress").addClass("progress-striped").addClass("active"); + $("#gcode_upload_progress .bar").text(gettext("Saving ...")); + } + } + + function enable_local_dropzone() { + $("#gcode_upload").fileupload({ + url: API_BASEURL + "files/local", + dataType: "json", + dropZone: localTarget, + done: gcode_upload_done, + fail: gcode_upload_fail, + progressall: gcode_upload_progress + }); + } + + function disable_local_dropzone() { + $("#gcode_upload").fileupload({ + url: API_BASEURL + "files/local", + dataType: "json", + dropZone: null, + done: gcode_upload_done, + fail: gcode_upload_fail, + progressall: gcode_upload_progress + }); + } + + function enable_sd_dropzone() { + $("#gcode_upload_sd").fileupload({ + url: API_BASEURL + "files/sdcard", + dataType: "json", + dropZone: $("#drop_sd"), + done: gcode_upload_done, + fail: gcode_upload_fail, + progressall: gcode_upload_progress + }); + } + + function disable_sd_dropzone() { + $("#gcode_upload_sd").fileupload({ + url: API_BASEURL + "files/sdcard", + dataType: "json", + dropZone: null, + done: gcode_upload_done, + fail: gcode_upload_fail, + progressall: gcode_upload_progress + }); + } + + var localTarget; + if (CONFIG_SD_SUPPORT) { + localTarget = $("#drop_locally"); + } else { + localTarget = $("#drop"); + } + + self.loginState.isUser.subscribe(function(newValue) { + if (newValue === true) { + enable_local_dropzone(); + } else { + disable_local_dropzone(); + } + }); + + if (self.loginState.isUser()) { + enable_local_dropzone(); + } else { + disable_local_dropzone(); + } + + if (CONFIG_SD_SUPPORT) { + self.printerState.isSdReady.subscribe(function(newValue) { + if (newValue === true && self.loginState.isUser()) { + enable_sd_dropzone(); + } else { + disable_sd_dropzone(); + } + }); + + self.loginState.isUser.subscribe(function(newValue) { + if (newValue === true && self.printerState.isSdReady()) { + enable_sd_dropzone(); + } else { + disable_sd_dropzone(); + } + }); + + if (self.printerState.isSdReady() && self.loginState.isUser()) { + enable_sd_dropzone(); + } else { + disable_sd_dropzone(); + } + } + + $(document).bind("dragover", function (e) { + var dropOverlay = $("#drop_overlay"); + var dropZone = $("#drop"); + var dropZoneLocal = $("#drop_locally"); + var dropZoneSd = $("#drop_sd"); + var dropZoneBackground = $("#drop_background"); + var dropZoneLocalBackground = $("#drop_locally_background"); + var dropZoneSdBackground = $("#drop_sd_background"); + var timeout = window.dropZoneTimeout; + + if (!timeout) { + dropOverlay.addClass('in'); + } else { + clearTimeout(timeout); + } + + var foundLocal = false; + var foundSd = false; + var found = false; + var node = e.target; + do { + if (dropZoneLocal && node === dropZoneLocal[0]) { + foundLocal = true; + break; + } else if (dropZoneSd && node === dropZoneSd[0]) { + foundSd = true; + break; + } else if (dropZone && node === dropZone[0]) { + found = true; + break; + } + node = node.parentNode; + } while (node != null); + + if (foundLocal) { + dropZoneLocalBackground.addClass("hover"); + dropZoneSdBackground.removeClass("hover"); + } else if (foundSd && self.printerState.isSdReady()) { + dropZoneSdBackground.addClass("hover"); + dropZoneLocalBackground.removeClass("hover"); + } else if (found) { + dropZoneBackground.addClass("hover"); + } else { + if (dropZoneLocalBackground) dropZoneLocalBackground.removeClass("hover"); + if (dropZoneSdBackground) dropZoneSdBackground.removeClass("hover"); + if (dropZoneBackground) dropZoneBackground.removeClass("hover"); + } + + window.dropZoneTimeout = setTimeout(function () { + window.dropZoneTimeout = null; + dropOverlay.removeClass("in"); + if (dropZoneLocal) dropZoneLocalBackground.removeClass("hover"); + if (dropZoneSd) dropZoneSdBackground.removeClass("hover"); + if (dropZone) dropZoneBackground.removeClass("hover"); + }, 100); + }); + + self.requestData(); + }; + + self.onEventUpdatedFiles = function(payload) { + if (payload.type == "gcode") { + self.requestData(); + } + }; + + self.onEventSlicingDone = function(payload) { + self.requestData(); + }; + + self.onEventMetadataAnalysisFinished = function(payload) { + self.requestData(); + }; + + self.onEventMetadataStatisticsUpdated = function(payload) { + self.requestData(); + }; } -} + OCTOPRINT_VIEWMODELS.push([ + GcodeFilesViewModel, + ["printerStateViewModel", "loginStateViewModel", "slicingViewModel"], + "#files_wrapper" + ]); +}); diff --git a/src/octoprint/static/js/app/viewmodels/firstrun.js b/src/octoprint/static/js/app/viewmodels/firstrun.js index c53e485ee..6b4244070 100644 --- a/src/octoprint/static/js/app/viewmodels/firstrun.js +++ b/src/octoprint/static/js/app/viewmodels/firstrun.js @@ -1,74 +1,88 @@ -function FirstRunViewModel() { - var self = this; +$(function() { + function FirstRunViewModel() { + var self = this; - self.username = ko.observable(undefined); - self.password = ko.observable(undefined); - self.confirmedPassword = ko.observable(undefined); + self.username = ko.observable(undefined); + self.password = ko.observable(undefined); + self.confirmedPassword = ko.observable(undefined); - self.passwordMismatch = ko.computed(function() { - return self.password() != self.confirmedPassword(); - }); + self.passwordMismatch = ko.computed(function() { + return self.password() != self.confirmedPassword(); + }); - self.validUsername = ko.computed(function() { - return self.username() && self.username().trim() != ""; - }); + self.validUsername = ko.computed(function() { + return self.username() && self.username().trim() != ""; + }); - self.validPassword = ko.computed(function() { - return self.password() && self.password().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.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() { - $("#confirmation_dialog .confirmation_dialog_message").html(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!")); - $("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click"); - $("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) { - e.preventDefault(); - $("#confirmation_dialog").modal("hide"); + self.keepAccessControl = function() { + if (!self.validData()) return; var data = { - "ac": false + "ac": true, + "user": self.username(), + "pass1": self.password(), + "pass2": self.confirmedPassword() }; - self._sendData(data, function() { - // if the user indeed disables access control, we'll need to reload the page for this to take effect - location.reload(); + self._sendData(data); + }; + + self.disableAccessControl = function() { + $("#confirmation_dialog .confirmation_dialog_message").html(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!")); + $("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click"); + $("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) { + e.preventDefault(); + $("#confirmation_dialog").modal("hide"); + + var data = { + "ac": false + }; + self._sendData(data, function() { + // if the user indeed disables access control, we'll need to reload the page for this to take effect + location.reload(); + }); }); - }); - $("#confirmation_dialog").modal("show"); - }; + $("#confirmation_dialog").modal("show"); + }; - self._sendData = function(data, callback) { - $.ajax({ - url: API_BASEURL + "setup", - type: "POST", - dataType: "json", - data: data, - success: function() { - self.closeDialog(); - if (callback) callback(); + self._sendData = function(data, callback) { + $.ajax({ + url: API_BASEURL + "setup", + type: "POST", + dataType: "json", + data: data, + success: function() { + self.closeDialog(); + if (callback) callback(); + } + }); + }; + + self.showDialog = function() { + $("#first_run_dialog").modal("show"); + }; + + self.closeDialog = function() { + $("#first_run_dialog").modal("hide"); + }; + + self.onAllBound = function(allViewModels) { + if (CONFIG_FIRST_RUN) { + self.showDialog(); } - }); + } } - self.showDialog = function() { - $("#first_run_dialog").modal("show"); - } - - self.closeDialog = function() { - $("#first_run_dialog").modal("hide"); - } -} + OCTOPRINT_VIEWMODELS.push([ + FirstRunViewModel, + [], + "#first_run_dialog" + ]); +}); diff --git a/src/octoprint/static/js/app/viewmodels/gcode.js b/src/octoprint/static/js/app/viewmodels/gcode.js index b7396d326..e44096c79 100644 --- a/src/octoprint/static/js/app/viewmodels/gcode.js +++ b/src/octoprint/static/js/app/viewmodels/gcode.js @@ -1,412 +1,510 @@ -function GcodeViewModel(loginStateViewModel, settingsViewModel) { - var self = this; +$(function() { + function GcodeViewModel(parameters) { + var self = this; - self.loginState = loginStateViewModel; - self.settings = settingsViewModel; + self.loginState = parameters[0]; + self.settings = parameters[1]; - self.ui_progress_percentage = ko.observable(); - self.ui_progress_type = ko.observable(); - self.ui_progress_text = ko.computed(function() { - var text = ""; - switch (self.ui_progress_type()) { - case "loading": { - text = gettext("Loading...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)"; - break; - } - case "analyzing": { - text = gettext("Analyzing...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)"; - break; - } - case "done": { - text = gettext("Analyzed"); - break; - } - } - - return text; - }); - self.ui_modelInfo = ko.observable(""); - self.ui_layerInfo = ko.observable(""); - - self.enableReload = ko.observable(false); - - self.waitForApproval = ko.observable(false); - self.selectedFile = { - name: ko.observable(undefined), - date: ko.observable(undefined), - size: ko.observable(undefined) - }; - - self.renderer_centerModel = ko.observable(false); - self.renderer_centerViewport = ko.observable(false); - self.renderer_zoomOnModel = ko.observable(false); - self.renderer_showMoves = ko.observable(true); - self.renderer_showRetracts = ko.observable(true); - self.renderer_extrusionWidthEnabled = ko.observable(false); - self.renderer_extrusionWidth = ko.observable(2); - self.renderer_showNext = ko.observable(false); - self.renderer_showPrevious = ko.observable(false); - self.renderer_syncProgress = ko.observable(true); - - self.reader_sortLayers = ko.observable(true); - self.reader_hideEmptyLayers = ko.observable(true); - - self.synchronizeOptions = function(additionalRendererOptions, additionalReaderOptions) { - var renderer = { - moveModel: self.renderer_centerModel(), - centerViewport: self.renderer_centerViewport(), - showMoves: self.renderer_showMoves(), - showRetracts: self.renderer_showRetracts(), - extrusionWidth: self.renderer_extrusionWidthEnabled() ? self.renderer_extrusionWidth() : 1, - showNextLayer: self.renderer_showNext(), - showPreviousLayer: self.renderer_showPrevious(), - zoomInOnModel: self.renderer_zoomOnModel(), - onInternalOptionChange: self._onInternalRendererOptionChange - }; - if (additionalRendererOptions) { - _.extend(renderer, additionalRendererOptions); - } - - var reader = { - sortLayers: self.reader_sortLayers(), - purgeEmptyLayers: self.reader_hideEmptyLayers() - }; - if (additionalReaderOptions) { - _.extend(reader, additionalReaderOptions); - } - - GCODE.ui.updateOptions({ - renderer: renderer, - reader: reader - }); - }; - - // subscribe to update Gcode view on updates... - self.renderer_centerModel.subscribe(self.synchronizeOptions); - self.renderer_centerViewport.subscribe(self.synchronizeOptions); - self.renderer_zoomOnModel.subscribe(self.synchronizeOptions); - self.renderer_showMoves.subscribe(self.synchronizeOptions); - self.renderer_showRetracts.subscribe(self.synchronizeOptions); - self.renderer_extrusionWidthEnabled.subscribe(self.synchronizeOptions); - self.renderer_extrusionWidth.subscribe(self.synchronizeOptions); - self.renderer_showNext.subscribe(self.synchronizeOptions); - self.renderer_showPrevious.subscribe(self.synchronizeOptions); - self.reader_sortLayers.subscribe(self.synchronizeOptions); - self.reader_hideEmptyLayers.subscribe(self.synchronizeOptions); - - // subscribe to relevant printer settings... - self.settings.printer_extruderOffsets.subscribe(function() { - if (!self.enabled) return; - if (!self.settings.printer_extruderOffsets()) return; - - GCODE.ui.updateOptions({ - reader: { - toolOffsets: self.settings.printer_extruderOffsets() - } - }); - }); - self.settings.printer_bedDimensions.subscribe(function() { - if (!self.enabled) return; - - var bedDimensions = self.settings.printer_bedDimensions(); - if (!bedDimensions || (!bedDimensions.hasOwnProperty("x") && !bedDimensions.hasOwnProperty("y") && !bedDimensions.hasOwnProperty("r"))) return; - - GCODE.ui.updateOptions({ - renderer: { - bed: bedDimensions - } - }); - }); - self.settings.printer_invertAxes.subscribe(function() { - if (!self.enabled) return; - if (!self.settings.printer_invertAxes()) return; - - GCODE.ui.updateOptions({ - renderer: { - invertAxes: { - x: self.settings.printer_invertX(), - y: self.settings.printer_invertY() + self.ui_progress_percentage = ko.observable(); + self.ui_progress_type = ko.observable(); + self.ui_progress_text = ko.computed(function() { + var text = ""; + switch (self.ui_progress_type()) { + case "loading": { + text = gettext("Loading...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)"; + break; + } + case "analyzing": { + text = gettext("Analyzing...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)"; + break; + } + case "done": { + text = gettext("Analyzed"); + break; } } + + return text; }); - }); + self.ui_modelInfo = ko.observable(""); + self.ui_layerInfo = ko.observable(""); - self.loadedFilename = undefined; - self.loadedFileDate = undefined; - self.status = 'idle'; - self.enabled = false; + self.enableReload = ko.observable(false); - self.currentlyPrinting = false; + self.waitForApproval = ko.observable(false); + self.selectedFile = { + name: ko.observable(undefined), + date: ko.observable(undefined), + size: ko.observable(undefined) + }; - self.errorCount = 0; + self.renderer_centerModel = ko.observable(false); + self.renderer_centerViewport = ko.observable(false); + self.renderer_zoomOnModel = ko.observable(false); + self.renderer_showMoves = ko.observable(true); + self.renderer_showRetracts = ko.observable(true); + self.renderer_extrusionWidthEnabled = ko.observable(false); + self.renderer_extrusionWidth = ko.observable(2); + self.renderer_showNext = ko.observable(false); + self.renderer_showPrevious = ko.observable(false); + self.renderer_syncProgress = ko.observable(true); - self.layerSlider = undefined; - self.layerCommandSlider = undefined; + self.reader_sortLayers = ko.observable(true); + self.reader_hideEmptyLayers = ko.observable(true); - self.currentLayer = undefined; - self.currentCommand = undefined; + self.synchronizeOptions = function(additionalRendererOptions, additionalReaderOptions) { + var renderer = { + moveModel: self.renderer_centerModel(), + centerViewport: self.renderer_centerViewport(), + showMoves: self.renderer_showMoves(), + showRetracts: self.renderer_showRetracts(), + extrusionWidth: self.renderer_extrusionWidthEnabled() ? self.renderer_extrusionWidth() : 1, + showNextLayer: self.renderer_showNext(), + showPreviousLayer: self.renderer_showPrevious(), + zoomInOnModel: self.renderer_zoomOnModel(), + onInternalOptionChange: self._onInternalRendererOptionChange + }; + if (additionalRendererOptions) { + _.extend(renderer, additionalRendererOptions); + } - self.initialize = function() { - self._configureLayerSlider(); - self._configureLayerCommandSlider(); + var reader = { + sortLayers: self.reader_sortLayers(), + purgeEmptyLayers: self.reader_hideEmptyLayers() + }; + if (additionalReaderOptions) { + _.extend(reader, additionalReaderOptions); + } - self.settings.requestData(function() { - GCODE.ui.init({ - container: "#gcode_canvas", - onProgress: self._onProgress, - onModelLoaded: self._onModelLoaded, - onLayerSelected: self._onLayerSelected, - bed: self.settings.printer_bedDimensions(), - toolOffsets: self.settings.printer_extruderOffsets() + GCODE.ui.updateOptions({ + renderer: renderer, + reader: reader }); - self.synchronizeOptions(); - self.enabled = true; - }); - }; + }; + + // subscribe to update Gcode view on updates... + self.renderer_centerModel.subscribe(self.synchronizeOptions); + self.renderer_centerViewport.subscribe(self.synchronizeOptions); + self.renderer_zoomOnModel.subscribe(self.synchronizeOptions); + self.renderer_showMoves.subscribe(self.synchronizeOptions); + self.renderer_showRetracts.subscribe(self.synchronizeOptions); + self.renderer_extrusionWidthEnabled.subscribe(self.synchronizeOptions); + self.renderer_extrusionWidth.subscribe(self.synchronizeOptions); + self.renderer_showNext.subscribe(self.synchronizeOptions); + self.renderer_showPrevious.subscribe(self.synchronizeOptions); + self.reader_sortLayers.subscribe(self.synchronizeOptions); + self.reader_hideEmptyLayers.subscribe(self.synchronizeOptions); + + // subscribe to relevant printer settings... + self.settings.printerProfiles.currentProfileData.subscribe(function() { + if (!self.enabled) return; + + var currentProfileData = self.settings.printerProfiles.currentProfileData(); + if (!currentProfileData) return; + + var toolOffsets = self._retrieveToolOffsets(currentProfileData); + if (toolOffsets) { + GCODE.ui.updateOptions({ + reader: { + toolOffsets: toolOffsets + } + }); + + } + + var bedDimensions = self._retrieveBedDimensions(currentProfileData); + if (toolOffsets) { + GCODE.ui.updateOptions({ + renderer: { + bed: bedDimensions + } + }); + } + + var axesConfiguration = self._retrieveAxesConfiguration(currentProfileData); + if (axesConfiguration) { + GCODE.ui.updateOptions({ + renderer: { + invertAxes: axesConfiguration + } + }); + } + }); + + self._retrieveBedDimensions = function(currentProfileData) { + if (currentProfileData == undefined) { + currentProfileData = self.settings.printerProfiles.currentProfileData(); + } + + if (currentProfileData && currentProfileData.volume && currentProfileData.volume.formFactor() && currentProfileData.volume.width() && currentProfileData.volume.depth()) { + var x = undefined, y = undefined, r = undefined, circular = false; + + var formFactor = currentProfileData.volume.formFactor(); + if (formFactor == "circular") { + r = currentProfileData.volume.width() / 2; + circular = true; + } else { + x = currentProfileData.volume.width(); + y = currentProfileData.volume.depth(); + } + + return { + x: x, + y: y, + r: r, + circular: circular + }; + } else { + return undefined; + } + }; + + self._retrieveToolOffsets = function(currentProfileData) { + if (currentProfileData == undefined) { + currentProfileData = self.settings.printerProfiles.currentProfileData(); + } + + if (currentProfileData && currentProfileData.extruder && currentProfileData.extruder.offsets()) { + var offsets = []; + _.each(currentProfileData.extruder.offsets(), function(offset) { + offsets.push({x: offset[0], y: offset[1]}) + }); + return offsets; + } else { + return undefined; + } + + }; + + self._retrieveAxesConfiguration = function(currentProfileData) { + if (currentProfileData == undefined) { + currentProfileData = self.settings.printerProfiles.currentProfileData(); + } + + if (currentProfileData && currentProfileData.axes) { + var invertX = false, invertY = false; + if (currentProfileData.axes.x) { + invertX = currentProfileData.axes.x.inverted(); + } + if (currentProfileData.axes.y) { + invertY = currentProfileData.axes.y.inverted(); + } + + return { + x: invertX, + y: invertY + } + } else { + return undefined; + } + }; - self.reset = function() { - self.enableReload(false); self.loadedFilename = undefined; self.loadedFileDate = undefined; - self.clear(); - }; + self.status = 'idle'; + self.enabled = false; - self.clear = function() { - GCODE.ui.clear(); - }; + self.currentlyPrinting = false; - self._configureLayerSlider = function() { - self.layerSlider = $("#gcode_slider_layers").slider({ - id: "gcode_layer_slider", - reversed: true, - selection: "after", - orientation: "vertical", - min: 0, - max: 1, - step: 1, - value: 0, - enabled: false, - formatter: function(value) { return "Layer #" + (value + 1); } - }).on("slide", self.changeLayer); - }; + self.errorCount = 0; - self._configureLayerCommandSlider = function() { - self.layerCommandSlider = $("#gcode_slider_commands").slider({ - id: "gcode_command_slider", - orientation: "horizontal", - min: 0, - max: 1, - step: 1, - value: [0, 1], - enabled: false, - tooltip: "hide" - }).on("slide", self.changeCommandRange); - }; + self.layerSlider = undefined; + self.layerCommandSlider = undefined; - self.loadFile = function(filename, date){ - self.enableReload(false); - if (self.status == "idle" && self.errorCount < 3) { - self.status = "request"; - $.ajax({ - url: BASEURL + "downloads/files/local/" + filename, - data: { "ctime": date }, - type: "GET", - success: function(response, rstatus) { - if(rstatus === 'success'){ - self.showGCodeViewer(response, rstatus); - self.loadedFilename = filename; - self.loadedFileDate = date; - self.status = "idle"; - self.enableReload(true); - } - }, - error: function() { - self.status = "idle"; - self.errorCount++; - } - }); - } - }; + self.currentLayer = undefined; + self.currentCommand = undefined; - self.showGCodeViewer = function(response, rstatus) { - var par = { - target: { - result: response + self.initialize = function() { + var layerSliderElement = $("#gcode_slider_layers"); + var commandSliderElement = $("#gcode_slider_commands"); + var containerElement = $("#gcode_canvas"); + + if (!(layerSliderElement.length && commandSliderElement.length && containerElement.length)) { + return; } + + self._configureLayerSlider(layerSliderElement); + self._configureLayerCommandSlider(commandSliderElement); + + self.settings.requestData(function() { + GCODE.ui.init({ + container: "#gcode_canvas", + onProgress: self._onProgress, + onModelLoaded: self._onModelLoaded, + onLayerSelected: self._onLayerSelected, + bed: self._retrieveBedDimensions(), + toolOffsets: self._retrieveToolOffsets(), + invertAxes: self._retrieveAxesConfiguration() + }); + self.synchronizeOptions(); + self.enabled = true; + }); }; - GCODE.gCodeReader.loadFile(par); - - self.layerSlider.slider("disable"); - self.layerCommandSlider.slider("disable"); - }; - - self.reload = function() { - if (!self.enableReload()) return; - self.loadFile(self.loadedFilename, self.loadedFileDate); - }; - - self.fromHistoryData = function(data) { - self._processData(data); - }; - - self.fromCurrentData = function(data) { - self._processData(data); - }; - - self._processData = function(data) { - if (!data.job.file || !data.job.file.name && (self.loadedFilename || self.loadedFileDate)) { - self.waitForApproval(false); + self.reset = function() { + self.enableReload(false); self.loadedFilename = undefined; self.loadedFileDate = undefined; - self.selectedFile.name(undefined); - self.selectedFile.date(undefined); - self.selectedFile.size(undefined); - self.clear(); - return; - } - if (!self.enabled) return; - self.currentlyPrinting = data.state.flags && (data.state.flags.printing || data.state.flags.paused); + }; - if(self.loadedFilename - && self.loadedFilename == data.job.file.name - && self.loadedFileDate == data.job.file.date) { - if (self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) { - var cmdIndex = GCODE.gCodeReader.getCmdIndexForPercentage(data.progress.completion); - if(cmdIndex){ - GCODE.renderer.render(cmdIndex.layer, 0, cmdIndex.cmd); - GCODE.ui.updateLayerInfo(cmdIndex.layer); + self.clear = function() { + GCODE.ui.clear(); + }; - self.layerSlider.slider("setValue", cmdIndex.layer); - self.layerCommandSlider.slider("setValue", [0, cmdIndex.cmd]); - } + self._configureLayerSlider = function(layerSliderElement) { + self.layerSlider = layerSliderElement.slider({ + id: "gcode_layer_slider", + reversed: true, + selection: "after", + orientation: "vertical", + min: 0, + max: 1, + step: 1, + value: 0, + enabled: false, + formatter: function(value) { return "Layer #" + (value + 1); } + }).on("slide", self.changeLayer); + }; + + self._configureLayerCommandSlider = function(commandSliderElement) { + self.layerCommandSlider = commandSliderElement.slider({ + id: "gcode_command_slider", + orientation: "horizontal", + min: 0, + max: 1, + step: 1, + value: [0, 1], + enabled: false, + tooltip: "hide" + }).on("slide", self.changeCommandRange); + }; + + self.loadFile = function(filename, date){ + self.enableReload(false); + if (self.status == "idle" && self.errorCount < 3) { + self.status = "request"; + $.ajax({ + url: BASEURL + "downloads/files/local/" + filename, + data: { "ctime": date }, + type: "GET", + success: function(response, rstatus) { + if(rstatus === 'success'){ + self.showGCodeViewer(response, rstatus); + self.loadedFilename = filename; + self.loadedFileDate = date; + self.status = "idle"; + self.enableReload(true); + } + }, + error: function() { + self.status = "idle"; + self.errorCount++; + } + }); } - self.errorCount = 0 - } else { - self.clear(); - if (data.job.file.name && data.job.file.origin != "sdcard" - && (!self.waitForApproval() || (self.selectedFile.name() != data.job.file.name || self.selectedFile.date() != data.job.file.date))) { - self.selectedFile.name(data.job.file.name); - self.selectedFile.date(data.job.file.date); - self.selectedFile.size(data.job.file.size); + }; - if (data.job.file.size > CONFIG_GCODE_SIZE_THRESHOLD || ($.browser.mobile && data.job.file.size > CONFIG_GCODE_MOBILE_SIZE_THRESHOLD)) { - self.waitForApproval(true); - self.loadedFilename = undefined; - self.loadedFileDate = undefined; - } else { - self.waitForApproval(false); - self.loadFile(data.job.file.name, data.job.file.date); + self.showGCodeViewer = function(response, rstatus) { + var par = { + target: { + result: response } + }; + GCODE.gCodeReader.loadFile(par); + + if (self.layerSlider != undefined) { + self.layerSlider.slider("disable"); } - } - }; + if (self.layerCommandSlider != undefined) { + self.layerCommandSlider.slider("disable"); + } + }; - self.approveLargeFile = function() { - self.waitForApproval(false); - self.loadFile(self.selectedFile.name(), self.selectedFile.date()); - }; + self.reload = function() { + if (!self.enableReload()) return; + self.loadFile(self.loadedFilename, self.loadedFileDate); + }; - self._onProgress = function(type, percentage) { - self.ui_progress_type(type); - self.ui_progress_percentage(percentage); - }; + self.fromHistoryData = function(data) { + self._processData(data); + }; - self._onModelLoaded = function(model) { - if (!model) { - self.ui_modelInfo(""); - self.layerSlider.slider("disable"); - self.layerSlider.slider("setMax", 1); - self.layerSlider.slider("setValue", 0); - self.currentLayer = 0; - } else { - var output = []; - output.push(gettext("Model size") + ": " + model.width.toFixed(2) + "mm × " + model.depth.toFixed(2) + "mm × " + model.height.toFixed(2) + "mm"); - if (model.filament.length == 0) { - output.push(gettext("Total filament used") + ": " + model.filament.toFixed(2) + gettext("mm")); + self.fromCurrentData = function(data) { + self._processData(data); + }; + + self._processData = function(data) { + if (!data.job.file || !data.job.file.name && (self.loadedFilename || self.loadedFileDate)) { + self.waitForApproval(false); + + self.loadedFilename = undefined; + self.loadedFileDate = undefined; + self.selectedFile.name(undefined); + self.selectedFile.date(undefined); + self.selectedFile.size(undefined); + + self.clear(); + return; + } + if (!self.enabled) return; + self.currentlyPrinting = data.state.flags && (data.state.flags.printing || data.state.flags.paused); + + if(self.loadedFilename + && self.loadedFilename == data.job.file.name + && self.loadedFileDate == data.job.file.date) { + if (self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) { + var cmdIndex = GCODE.gCodeReader.getCmdIndexForPercentage(data.progress.completion); + if(cmdIndex){ + GCODE.renderer.render(cmdIndex.layer, 0, cmdIndex.cmd); + GCODE.ui.updateLayerInfo(cmdIndex.layer); + + if (self.layerSlider != undefined) { + self.layerSlider.slider("setValue", cmdIndex.layer); + } + if (self.layerCommandSlider != undefined) { + self.layerCommandSlider.slider("setValue", [0, cmdIndex.cmd]); + } + } + } + self.errorCount = 0 } else { - for (var i = 0; i < model.filament.length; i++) { - output.push(gettext("Total filament used") + " (" + gettext("Tool") + " " + i + "): " + model.filament[i].toFixed(2) + gettext("mm")); + self.clear(); + if (data.job.file.name && data.job.file.origin != "sdcard" + && (!self.waitForApproval() || (self.selectedFile.name() != data.job.file.name || self.selectedFile.date() != data.job.file.date))) { + self.selectedFile.name(data.job.file.name); + self.selectedFile.date(data.job.file.date); + self.selectedFile.size(data.job.file.size); + + if (data.job.file.size > CONFIG_GCODE_SIZE_THRESHOLD || ($.browser.mobile && data.job.file.size > CONFIG_GCODE_MOBILE_SIZE_THRESHOLD)) { + self.waitForApproval(true); + self.loadedFilename = undefined; + self.loadedFileDate = undefined; + } else { + self.waitForApproval(false); + self.loadFile(data.job.file.name, data.job.file.date); + } } } - output.push(gettext("Estimated print time") + ": " + formatDuration(model.printTime)); - output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm")); - output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext("printed") + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited")); + }; - self.ui_modelInfo(output.join("
")); + self.approveLargeFile = function() { + self.waitForApproval(false); + self.loadFile(self.selectedFile.name(), self.selectedFile.date()); + }; - self.layerSlider.slider("enable"); - self.layerSlider.slider("setMax", model.layersPrinted - 1); - self.layerSlider.slider("setValue", 0); - } - }; + self._onProgress = function(type, percentage) { + self.ui_progress_type(type); + self.ui_progress_percentage(percentage); + }; - self._onLayerSelected = function(layer) { - if (!layer) { - self.ui_layerInfo(""); - self.layerCommandSlider.slider("disable"); - self.layerCommandSlider.slider("setMax", 1); - self.layerCommandSlider.slider("setValue", [0, 1]); - self.currentCommand = [0, 1]; - } else { - var output = []; - output.push(gettext("Layer number") + ": " + (layer.number + 1)); - output.push(gettext("Layer height") + " (mm): " + layer.height); - output.push(gettext("GCODE commands in layer") + ": " + layer.commands); - if (layer.filament.length == 1) { - output.push(gettext("Filament used by layer") + ": " + layer.filament[0].toFixed(2) + "mm"); + self._onModelLoaded = function(model) { + if (!model) { + self.ui_modelInfo(""); + if (self.layerSlider != undefined) { + self.layerSlider.slider("disable"); + self.layerSlider.slider("setMax", 1); + self.layerSlider.slider("setValue", 0); + } + self.currentLayer = 0; } else { - for (var i = 0; i < layer.filament.length; i++) { - output.push(gettext("Filament used by layer") + " (" + gettext("Tool") + " " + i + "): " + layer.filament[i].toFixed(2) + "mm"); + var output = []; + output.push(gettext("Model size") + ": " + model.width.toFixed(2) + "mm × " + model.depth.toFixed(2) + "mm × " + model.height.toFixed(2) + "mm"); + output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm")); + output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext("printed") + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited")); + + self.ui_modelInfo(output.join("
")); + + if (self.layerSlider != undefined) { + self.layerSlider.slider("enable"); + self.layerSlider.slider("setMax", model.layersPrinted - 1); + self.layerSlider.slider("setValue", 0); } } - output.push(gettext("Print time for layer") + ": " + formatDuration(layer.printTime)); + }; - self.ui_layerInfo(output.join("
")); + self._onLayerSelected = function(layer) { + if (!layer) { + self.ui_layerInfo(""); + if (self.layerCommandSlider != undefined) { + self.layerCommandSlider.slider("disable"); + self.layerCommandSlider.slider("setMax", 1); + self.layerCommandSlider.slider("setValue", [0, 1]); + } + self.currentCommand = [0, 1]; + } else { + var output = []; + output.push(gettext("Layer number") + ": " + (layer.number + 1)); + output.push(gettext("Layer height") + " (mm): " + layer.height); + output.push(gettext("GCODE commands in layer") + ": " + layer.commands); + if (layer.filament != undefined) { + if (layer.filament.length == 1) { + output.push(gettext("Filament used by layer") + ": " + layer.filament[0].toFixed(2) + "mm"); + } else { + for (var i = 0; i < layer.filament.length; i++) { + output.push(gettext("Filament used by layer") + " (" + gettext("Tool") + " " + i + "): " + layer.filament[i].toFixed(2) + "mm"); + } + } + } + output.push(gettext("Print time for layer") + ": " + formatDuration(layer.printTime)); - self.layerCommandSlider.slider("enable"); - self.layerCommandSlider.slider("setMax", layer.commands - 1); - self.layerCommandSlider.slider("setValue", [0, layer.commands - 1]); - } - }; + self.ui_layerInfo(output.join("
")); - self._onInternalRendererOptionChange = function(options) { - if (!options) return; - - for (var opt in options) { - if (opt == "zoomInOnModel" && options[opt] != self.renderer_zoomOnModel()) { - self.renderer_zoomOnModel(false); - } else if (opt == "centerViewport" && options[opt] != self.renderer_centerViewport()) { - self.renderer_centerViewport(false); - } else if (opt == "moveModel" && options[opt] != self.renderer_centerModel()) { - self.renderer_centerModel(false); + if (self.layerCommandSlider != undefined) { + self.layerCommandSlider.slider("enable"); + self.layerCommandSlider.slider("setMax", layer.commands - 1); + self.layerCommandSlider.slider("setValue", [0, layer.commands - 1]); + } } + }; + + self._onInternalRendererOptionChange = function(options) { + if (!options) return; + + for (var opt in options) { + if (opt == "zoomInOnModel" && options[opt] != self.renderer_zoomOnModel()) { + self.renderer_zoomOnModel(false); + } else if (opt == "centerViewport" && options[opt] != self.renderer_centerViewport()) { + self.renderer_centerViewport(false); + } else if (opt == "moveModel" && options[opt] != self.renderer_centerModel()) { + self.renderer_centerModel(false); + } + } + }; + + self.changeLayer = function(event) { + if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false); + + var value = event.value; + if (self.currentLayer !== undefined && self.currentLayer == value) return; + self.currentLayer = value; + + GCODE.ui.changeSelectedLayer(value); + }; + + self.changeCommandRange = function(event) { + if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false); + + var tuple = event.value; + if (self.currentCommand !== undefined && self.currentCommand[0] == tuple[0] && self.currentCommand[1] == tuple[1]) return; + self.currentCommand = tuple; + + GCODE.ui.changeSelectedCommands(self.layerSlider.slider("getValue"), tuple[0], tuple[1]); + }; + + self.onDataUpdaterReconnect = function() { + self.reset(); + }; + + self.onBeforeBinding = function() { + self.initialize(); } - }; - self.changeLayer = function(event) { - if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false); - - var value = event.value; - if (self.currentLayer !== undefined && self.currentLayer == value) return; - self.currentLayer = value; - - GCODE.ui.changeSelectedLayer(value); - }; - - self.changeCommandRange = function(event) { - if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false); - - var tuple = event.value; - if (self.currentCommand !== undefined && self.currentCommand[0] == tuple[0] && self.currentCommand[1] == tuple[1]) return; - self.currentCommand = tuple; - - GCODE.ui.changeSelectedCommands(self.layerSlider.slider("getValue"), tuple[0], tuple[1]); - }; - - self.onDataUpdaterReconnect = function() { - self.reset(); } -} + OCTOPRINT_VIEWMODELS.push([ + GcodeViewModel, + ["loginStateViewModel", "settingsViewModel"], + "#gcode" + ]); +}); \ No newline at end of file diff --git a/src/octoprint/static/js/app/viewmodels/log.js b/src/octoprint/static/js/app/viewmodels/log.js index 59d52a5cb..d0ea3f635 100644 --- a/src/octoprint/static/js/app/viewmodels/log.js +++ b/src/octoprint/static/js/app/viewmodels/log.js @@ -1,70 +1,78 @@ -function LogViewModel(loginStateViewModel) { - var self = this; +$(function() { + function LogViewModel(parameters) { + var self = this; - self.loginState = loginStateViewModel; + self.loginState = parameters[0]; - // initialize list helper - self.listHelper = new ItemListHelper( - "logFiles", - { - "name": function(a, b) { - // sorts ascending - if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1; - if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1; - return 0; + // initialize list helper + self.listHelper = new ItemListHelper( + "logFiles", + { + "name": function(a, b) { + // sorts ascending + if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1; + if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1; + return 0; + }, + "modification": function(a, b) { + // sorts descending + if (a["date"] > b["date"]) return -1; + if (a["date"] < b["date"]) return 1; + return 0; + }, + "size": function(a, b) { + // sorts descending + if (a["bytes"] > b["bytes"]) return -1; + if (a["bytes"] < b["bytes"]) return 1; + return 0; + } }, - "modification": function(a, b) { - // sorts descending - if (a["date"] > b["date"]) return -1; - if (a["date"] < b["date"]) return 1; - return 0; + { }, - "size": function(a, b) { - // sorts descending - if (a["bytes"] > b["bytes"]) return -1; - if (a["bytes"] < b["bytes"]) return 1; - return 0; - } - }, - { - }, - "name", - [], - [], - CONFIG_LOGFILESPERPAGE - ); + "name", + [], + [], + CONFIG_LOGFILESPERPAGE + ); - self.requestData = function() { - $.ajax({ - url: API_BASEURL + "logs", - type: "GET", - dataType: "json", - success: self.fromResponse - }); - }; + self.requestData = function() { + $.ajax({ + url: API_BASEURL + "logs", + type: "GET", + dataType: "json", + success: self.fromResponse + }); + }; - self.fromResponse = function(response) { - var files = response.files; - if (files === undefined) - return; + self.fromResponse = function(response) { + var files = response.files; + if (files === undefined) + return; - self.listHelper.updateItems(files); - }; + self.listHelper.updateItems(files); + }; - self.removeFile = function(filename) { - $.ajax({ - url: API_BASEURL + "logs/" + filename, - type: "DELETE", - dataType: "json", - success: self.requestData - }); - }; + self.removeFile = function(filename) { + $.ajax({ + url: API_BASEURL + "logs/" + filename, + type: "DELETE", + dataType: "json", + success: self.requestData + }); + }; - self.onDataUpdaterReconnect = function() { - self.requestData(); - }; + self.onDataUpdaterReconnect = function() { + self.requestData(); + }; - self.onStartup = function() { - self.requestData(); - }; -} + self.onStartup = function() { + self.requestData(); + }; + } + + OCTOPRINT_VIEWMODELS.push([ + LogViewModel, + ["loginStateViewModel"], + "#logs" + ]); +}); \ No newline at end of file diff --git a/src/octoprint/static/js/app/viewmodels/loginstate.js b/src/octoprint/static/js/app/viewmodels/loginstate.js index 2b7c83155..279b34bbb 100644 --- a/src/octoprint/static/js/app/viewmodels/loginstate.js +++ b/src/octoprint/static/js/app/viewmodels/loginstate.js @@ -1,97 +1,121 @@ -function LoginStateViewModel() { - var self = this; +$(function() { + function LoginStateViewModel() { + var self = this; - self.loggedIn = ko.observable(false); - self.username = ko.observable(undefined); - self.isAdmin = ko.observable(false); - self.isUser = ko.observable(false); + self.loginUser = ko.observable(); + self.loginPass = ko.observable(); + self.loginRemember = ko.observable(false); - self.currentUser = ko.observable(undefined); + self.loggedIn = ko.observable(false); + self.username = ko.observable(undefined); + self.isAdmin = ko.observable(false); + self.isUser = ko.observable(false); - self.userMenuText = ko.computed(function() { - if (self.loggedIn()) { - return "\"" + self.username() + "\""; - } else { - return gettext("Login"); - } - }); + self.currentUser = ko.observable(undefined); - self.subscribers = []; - self.subscribe = function(callback) { - if (callback === undefined) return; - self.subscribers.push(callback); - }; - - self.requestData = function() { - $.ajax({ - url: API_BASEURL + "login", - type: "POST", - data: {"passive": true}, - success: self.fromResponse - }) - }; - - self.fromResponse = function(response) { - if (response && response.name) { - self.loggedIn(true); - self.username(response.name); - self.isUser(response.user); - self.isAdmin(response.admin); - - self.currentUser(response); - - _.each(self.subscribers, function(callback) { callback("login", response); }); - } else { - self.loggedIn(false); - self.username(undefined); - self.isUser(false); - self.isAdmin(false); - - self.currentUser(undefined); - - _.each(self.subscribers, function(callback) { callback("logout", {}); }); - } - }; - - self.login = function() { - var username = $("#login_user").val(); - var password = $("#login_pass").val(); - var remember = $("#login_remember").is(":checked"); - - $("#login_user").val(""); - $("#login_pass").val(""); - $("#login_remember").prop("checked", false); - - $.ajax({ - url: API_BASEURL + "login", - type: "POST", - data: {"user": username, "pass": password, "remember": remember}, - success: function(response) { - new PNotify({title: gettext("Login successful"), text: _.sprintf(gettext('You are now logged in as "%(username)s"'), {username: response.name}), type: "success"}); - self.fromResponse(response); - }, - error: function(jqXHR, textStatus, errorThrown) { - new PNotify({title: gettext("Login failed"), text: gettext("User unknown or wrong password"), type: "error"}); + self.userMenuText = ko.computed(function() { + if (self.loggedIn()) { + return self.username(); + } else { + return gettext("Login"); } - }) - }; + }); - self.logout = function() { - $.ajax({ - url: API_BASEURL + "logout", - type: "POST", - success: function(response) { - new PNotify({title: gettext("Logout successful"), text: gettext("You are now logged out"), type: "success"}); - self.fromResponse(response); + self.subscribers = []; + self.subscribe = function(callback) { + if (callback === undefined) return; + self.subscribers.push(callback); + }; + + self.requestData = function() { + $.ajax({ + url: API_BASEURL + "login", + type: "POST", + data: {"passive": true}, + success: self.fromResponse + }) + }; + + self.fromResponse = function(response) { + if (response && response.name) { + self.loggedIn(true); + self.username(response.name); + self.isUser(response.user); + self.isAdmin(response.admin); + + self.currentUser(response); + + _.each(self.subscribers, function(callback) { callback("login", response); }); + } else { + self.loggedIn(false); + self.username(undefined); + self.isUser(false); + self.isAdmin(false); + + self.currentUser(undefined); + + _.each(self.subscribers, function(callback) { callback("logout", {}); }); } - }) - }; + }; - self.onDataUpdaterReconnect = function() { - self.requestData(); - }; + self.login = function() { + var username = self.loginUser(); + var password = self.loginPass(); + var remember = self.loginRemember(); - self.onStartup = function() { - self.requestData(); - }; -} + self.loginUser(""); + self.loginPass(""); + self.loginRemember(false); + + $.ajax({ + url: API_BASEURL + "login", + type: "POST", + data: {"user": username, "pass": password, "remember": remember}, + success: function(response) { + new PNotify({title: gettext("Login successful"), text: _.sprintf(gettext('You are now logged in as "%(username)s"'), {username: response.name}), type: "success"}); + self.fromResponse(response); + }, + error: function(jqXHR, textStatus, errorThrown) { + new PNotify({title: gettext("Login failed"), text: gettext("User unknown or wrong password"), type: "error"}); + } + }) + }; + + self.logout = function() { + $.ajax({ + url: API_BASEURL + "logout", + type: "POST", + success: function(response) { + new PNotify({title: gettext("Logout successful"), text: gettext("You are now logged out"), type: "success"}); + self.fromResponse(response); + } + }) + }; + + self.onLoginUserKeyup = function(data, event) { + if (event.keyCode == 13) { + $("#login_pass").focus(); + } + }; + + self.onLoginPassKeyup = function(data, event) { + if (event.keyCode == 13) { + self.login(); + } + }; + + self.onDataUpdaterReconnect = function() { + self.requestData(); + }; + + self.onStartup = function() { + self.requestData(); + }; + } + + OCTOPRINT_VIEWMODELS.push([ + LoginStateViewModel, + [], + [] + ]); +}); \ No newline at end of file diff --git a/src/octoprint/static/js/app/viewmodels/navigation.js b/src/octoprint/static/js/app/viewmodels/navigation.js index df9a16c3d..6ea94569b 100644 --- a/src/octoprint/static/js/app/viewmodels/navigation.js +++ b/src/octoprint/static/js/app/viewmodels/navigation.js @@ -1,43 +1,62 @@ -function NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsViewModel, usersViewModel) { - var self = this; +$(function() { + function NavigationViewModel(parameters) { + var self = this; - self.loginState = loginStateViewModel; - self.appearance = appearanceViewModel; - self.systemActions = settingsViewModel.system_actions; - self.users = usersViewModel; + self.loginState = parameters[0]; + self.appearance = parameters[1]; + self.settings = parameters[2]; + self.users = parameters[3]; - self.triggerAction = function(action) { - var callback = function() { - $.ajax({ - url: API_BASEURL + "system", - type: "POST", - dataType: "json", - data: "action=" + action.action, - success: function() { - new PNotify({title: "Success", text: _.sprintf(gettext("The command \"%(command)s\" executed successfully"), {command: action.name}), type: "success"}); - }, - error: function(jqXHR, textStatus, errorThrown) { - var error = "

" + _.sprintf(gettext("The command \"%(command)s\" could not be executed."), {command: action.name}) + "

"; - error += pnotifyAdditionalInfo("
" + jqXHR.responseText + "
"); - new PNotify({title: gettext("Error"), text: error, type: "error", hide: false}); - } - }) - }; - if (action.confirm) { - var confirmationDialog = $("#confirmation_dialog"); - var confirmationDialogAck = $(".confirmation_dialog_acknowledge", confirmationDialog); + self.systemActions = self.settings.system_actions; - $(".confirmation_dialog_message", confirmationDialog).text(action.confirm); - confirmationDialogAck.unbind("click"); - confirmationDialogAck.bind("click", function(e) { - e.preventDefault(); - $("#confirmation_dialog").modal("hide"); + self.appearanceClasses = ko.computed(function() { + var classes = self.appearance.color(); + if (self.appearance.colorTransparent()) { + classes += " transparent"; + } + return classes; + }); + + self.triggerAction = function(action) { + var callback = function() { + $.ajax({ + url: API_BASEURL + "system", + type: "POST", + dataType: "json", + data: "action=" + action.action, + success: function() { + new PNotify({title: "Success", text: _.sprintf(gettext("The command \"%(command)s\" executed successfully"), {command: action.name}), type: "success"}); + }, + error: function(jqXHR, textStatus, errorThrown) { + var error = "

" + _.sprintf(gettext("The command \"%(command)s\" could not be executed."), {command: action.name}) + "

"; + error += pnotifyAdditionalInfo("
" + jqXHR.responseText + "
"); + new PNotify({title: gettext("Error"), text: error, type: "error", hide: false}); + } + }) + }; + if (action.confirm) { + var confirmationDialog = $("#confirmation_dialog"); + var confirmationDialogAck = $(".confirmation_dialog_acknowledge", confirmationDialog); + + $(".confirmation_dialog_message", confirmationDialog).text(action.confirm); + confirmationDialogAck.unbind("click"); + confirmationDialogAck.bind("click", function(e) { + e.preventDefault(); + $("#confirmation_dialog").modal("hide"); + callback(); + }); + confirmationDialog.modal("show"); + } else { callback(); - }); - confirmationDialog.modal("show"); - } else { - callback(); + } } } -} + OCTOPRINT_VIEWMODELS.push([ + NavigationViewModel, + ["loginStateViewModel", "appearanceViewModel", "settingsViewModel", "usersViewModel"], + "#navbar" + ]); + + // TODO usersViewModel is needed for what? +}); \ No newline at end of file diff --git a/src/octoprint/static/js/app/viewmodels/printerprofiles.js b/src/octoprint/static/js/app/viewmodels/printerprofiles.js new file mode 100644 index 000000000..955f790e5 --- /dev/null +++ b/src/octoprint/static/js/app/viewmodels/printerprofiles.js @@ -0,0 +1,401 @@ +$(function() { + function PrinterProfilesViewModel() { + var self = this; + + self._cleanProfile = function() { + return { + id: "", + name: "", + model: "", + color: "default", + volume: { + formFactor: "rectangular", + width: 200, + depth: 200, + height: 200 + }, + heatedBed: false, + axes: { + x: {speed: 6000, inverted: false}, + y: {speed: 6000, inverted: false}, + z: {speed: 200, inverted: false}, + e: {speed: 300, inverted: false} + }, + extruder: { + count: 1, + offsets: [ + [0,0] + ], + nozzleDiameter: 0.4 + } + } + }; + + self.requestInProgress = ko.observable(false); + + self.profiles = new ItemListHelper( + "printerProfiles", + { + "name": function(a, b) { + // sorts ascending + if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1; + if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1; + return 0; + } + }, + {}, + "name", + [], + [], + 10 + ); + self.defaultProfile = ko.observable(); + self.currentProfile = ko.observable(); + + self.currentProfileData = ko.observable(ko.mapping.fromJS(self._cleanProfile())); + + self.editorNew = ko.observable(false); + + self.editorName = ko.observable(); + self.editorColor = ko.observable(); + self.editorIdentifier = ko.observable(); + self.editorIdentifierPlaceholder = ko.observable(); + self.editorModel = ko.observable(); + + self.editorVolumeWidth = ko.observable(); + self.editorVolumeDepth = ko.observable(); + self.editorVolumeHeight = ko.observable(); + self.editorVolumeFormFactor = ko.observable(); + + self.editorHeatedBed = ko.observable(); + + self.editorNozzleDiameter = ko.observable(); + self.editorExtruders = ko.observable(); + self.editorExtruderOffsets = ko.observableArray(); + + self.editorAxisXSpeed = ko.observable(); + self.editorAxisYSpeed = ko.observable(); + self.editorAxisZSpeed = ko.observable(); + self.editorAxisESpeed = ko.observable(); + + self.editorAxisXInverted = ko.observable(false); + self.editorAxisYInverted = ko.observable(false); + self.editorAxisZInverted = ko.observable(false); + self.editorAxisEInverted = ko.observable(false); + + self.availableColors = ko.observable([ + {key: "default", name: gettext("default")}, + {key: "red", name: gettext("red")}, + {key: "orange", name: gettext("orange")}, + {key: "yellow", name: gettext("yellow")}, + {key: "green", name: gettext("green")}, + {key: "blue", name: gettext("blue")}, + {key: "black", name: gettext("black")} + ]); + + self.koEditorExtruderOffsets = ko.computed(function() { + var extruderOffsets = self.editorExtruderOffsets(); + var numExtruders = self.editorExtruders(); + if (!numExtruders) { + numExtruders = 1; + } + + if (numExtruders > extruderOffsets.length) { + for (var i = extruderOffsets.length; i < numExtruders; i++) { + extruderOffsets[i] = { + x: ko.observable(0), + y: ko.observable(0) + } + } + self.editorExtruderOffsets(extruderOffsets); + } + + return extruderOffsets.slice(0, numExtruders); + }); + + self.editorNameInvalid = ko.computed(function() { + return !self.editorName(); + }); + + self.editorIdentifierInvalid = ko.computed(function() { + var identifier = self.editorIdentifier(); + var placeholder = self.editorIdentifierPlaceholder(); + var data = identifier; + if (!identifier) { + data = placeholder; + } + + var validCharacters = (data && (data == self._sanitize(data))); + + var existingProfile = self.profiles.getItem(function(item) {return item.id == data}); + return !data || !validCharacters || (self.editorNew() && existingProfile != undefined); + }); + + self.editorIdentifierInvalidText = ko.computed(function() { + if (!self.editorIdentifierInvalid()) { + return ""; + } + + if (!self.editorIdentifier() && !self.editorIdentifierPlaceholder()) { + return gettext("Identifier must be set"); + } else if (self.editorIdentifier() != self._sanitize(self.editorIdentifier())) { + return gettext("Invalid characters, only a-z, A-Z, 0-9, -, ., _, ( and ) are allowed") + } else { + return gettext("A profile with such an identifier already exists"); + } + }); + + self.enableEditorSubmitButton = ko.computed(function() { + return !self.editorNameInvalid() && !self.editorIdentifierInvalid() && !self.requestInProgress(); + }); + + self.editorName.subscribe(function() { + self.editorIdentifierPlaceholder(self._sanitize(self.editorName()).toLowerCase()); + }); + + self.makeDefault = function(data) { + var profile = { + id: data.id, + default: true + }; + + self.updateProfile(profile); + }; + + self.requestData = function() { + $.ajax({ + url: API_BASEURL + "printerprofiles", + type: "GET", + dataType: "json", + success: self.fromResponse + }) + }; + + self.fromResponse = function(data) { + var items = []; + var defaultProfile = undefined; + var currentProfile = undefined; + var currentProfileData = undefined; + _.each(data.profiles, function(entry) { + if (entry.default) { + defaultProfile = entry.id; + } + if (entry.current) { + currentProfile = entry.id; + currentProfileData = ko.mapping.fromJS(entry, self.currentProfileData); + } + entry["isdefault"] = ko.observable(entry.default); + entry["iscurrent"] = ko.observable(entry.current); + items.push(entry); + }); + self.profiles.updateItems(items); + self.defaultProfile(defaultProfile); + self.currentProfile(currentProfile); + self.currentProfileData(currentProfileData); + }; + + self.addProfile = function(callback) { + var profile = self._editorData(); + self.requestInProgress(true); + $.ajax({ + url: API_BASEURL + "printerprofiles", + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify({profile: profile}), + success: function() { + self.requestInProgress(false); + if (callback !== undefined) { + callback(); + } + self.requestData(); + }, + error: function() { + self.requestInProgress(false); + var text = gettext("There was unexpected error while saving the printer profile, please consult the logs."); + new PNotify({title: gettext("Saving failed"), text: text, type: "error", hide: false}); + } + }); + }; + + self.removeProfile = function(data) { + self.requestInProgress(true); + $.ajax({ + url: data.resource, + type: "DELETE", + dataType: "json", + success: function() { + self.requestInProgress(false); + self.requestData(); + }, + error: function() { + self.requestInProgress(false); + var text = gettext("There was unexpected error while removing the printer profile, please consult the logs."); + new PNotify({title: gettext("Saving failed"), text: text, type: "error", hide: false}); + } + }) + }; + + self.updateProfile = function(profile, callback) { + if (profile == undefined) { + profile = self._editorData(); + } + + self.requestInProgress(true); + + $.ajax({ + url: API_BASEURL + "printerprofiles/" + profile.id, + type: "PATCH", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify({profile: profile}), + success: function() { + self.requestInProgress(false); + if (callback !== undefined) { + callback(); + } + self.requestData(); + }, + error: function() { + self.requestInProgress(false); + var text = gettext("There was unexpected error while updating the printer profile, please consult the logs."); + new PNotify({title: gettext("Saving failed"), text: text, type: "error", hide: false}); + } + }); + }; + + self.showEditProfileDialog = function(data) { + var add = false; + if (data == undefined) { + data = self._cleanProfile(); + add = true; + } + + self.editorNew(add); + + self.editorIdentifier(data.id); + self.editorName(data.name); + self.editorColor(data.color); + self.editorModel(data.model); + + self.editorVolumeWidth(data.volume.width); + self.editorVolumeDepth(data.volume.depth); + self.editorVolumeHeight(data.volume.height); + self.editorVolumeFormFactor(data.volume.formFactor); + + self.editorHeatedBed(data.heatedBed); + + self.editorNozzleDiameter(data.extruder.nozzleDiameter); + self.editorExtruders(data.extruder.count); + var offsets = []; + _.each(data.extruder.offsets, function(offset) { + offsets.push({ + x: ko.observable(offset[0]), + y: ko.observable(offset[1]) + }); + }); + self.editorExtruderOffsets(offsets); + + self.editorAxisXSpeed(data.axes.x.speed); + self.editorAxisXInverted(data.axes.x.inverted); + self.editorAxisYSpeed(data.axes.y.speed); + self.editorAxisYInverted(data.axes.y.inverted); + self.editorAxisZSpeed(data.axes.z.speed); + self.editorAxisZInverted(data.axes.z.inverted); + self.editorAxisESpeed(data.axes.e.speed); + self.editorAxisEInverted(data.axes.e.inverted); + + var editDialog = $("#settings_printerProfiles_editDialog"); + var confirmButton = $("button.btn-confirm", editDialog); + var dialogTitle = $("h3.modal-title", editDialog); + + dialogTitle.text(add ? gettext("Add Printer Profile") : _.sprintf(gettext("Edit Printer Profile \"%(name)s\""), {name: data.name})); + confirmButton.unbind("click"); + confirmButton.bind("click", function() { + if (self.enableEditorSubmitButton()) { + self.confirmEditProfile(add); + } + }); + editDialog.modal("show"); + }; + + self.confirmEditProfile = function(add) { + var callback = function() { + $("#settings_printerProfiles_editDialog").modal("hide"); + }; + + if (add) { + self.addProfile(callback); + } else { + self.updateProfile(undefined, callback); + } + }; + + self._editorData = function() { + var identifier = self.editorIdentifier(); + if (!identifier) { + identifier = self.editorIdentifierPlaceholder(); + } + + var profile = { + id: identifier, + name: self.editorName(), + color: self.editorColor(), + model: self.editorModel(), + volume: { + width: parseFloat(self.editorVolumeWidth()), + depth: parseFloat(self.editorVolumeDepth()), + height: parseFloat(self.editorVolumeHeight()), + formFactor: self.editorVolumeFormFactor() + }, + heatedBed: self.editorHeatedBed(), + extruder: { + count: parseInt(self.editorExtruders()), + offsets: [ + [0.0, 0.0] + ], + nozzleDiameter: parseFloat(self.editorNozzleDiameter()) + }, + axes: { + x: { + speed: parseInt(self.editorAxisXSpeed()), + inverted: self.editorAxisXInverted() + }, + y: { + speed: parseInt(self.editorAxisYSpeed()), + inverted: self.editorAxisYInverted() + }, + z: { + speed: parseInt(self.editorAxisZSpeed()), + inverted: self.editorAxisZInverted() + } + } + }; + + if (self.editorExtruders() > 1) { + for (var i = 1; i < self.editorExtruders(); i++) { + var offset = [0.0, 0.0]; + if (i < self.editorExtruderOffsets().length) { + offset = [parseFloat(self.editorExtruderOffsets()[i]["x"]()), parseFloat(self.editorExtruderOffsets()[i]["y"]())]; + } + profile.extruder.offsets.push(offset); + } + } + + return profile; + }; + + self._sanitize = function(name) { + return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_"); + }; + + self.onSettingsShown = self.requestData; + self.onStartup = self.requestData; + } + + OCTOPRINT_VIEWMODELS.push([ + PrinterProfilesViewModel, + [], + [] + ]); +}); \ No newline at end of file diff --git a/src/octoprint/static/js/app/viewmodels/printerstate.js b/src/octoprint/static/js/app/viewmodels/printerstate.js index 5827b13af..00a7b67ee 100644 --- a/src/octoprint/static/js/app/viewmodels/printerstate.js +++ b/src/octoprint/static/js/app/viewmodels/printerstate.js @@ -1,193 +1,245 @@ -function PrinterStateViewModel(loginStateViewModel) { - var self = this; +$(function() { + function PrinterStateViewModel(parameters) { + var self = this; - self.loginState = loginStateViewModel; + self.loginState = parameters[0]; - self.stateString = ko.observable(undefined); - self.isErrorOrClosed = ko.observable(undefined); - self.isOperational = ko.observable(undefined); - self.isPrinting = ko.observable(undefined); - self.isPaused = ko.observable(undefined); - self.isError = ko.observable(undefined); - self.isReady = ko.observable(undefined); - self.isLoading = ko.observable(undefined); - self.isSdReady = ko.observable(undefined); + self.stateString = ko.observable(undefined); + self.isErrorOrClosed = ko.observable(undefined); + self.isOperational = ko.observable(undefined); + self.isPrinting = ko.observable(undefined); + self.isPaused = ko.observable(undefined); + self.isError = ko.observable(undefined); + self.isReady = ko.observable(undefined); + self.isLoading = ko.observable(undefined); + self.isSdReady = ko.observable(undefined); - self.filename = ko.observable(undefined); - self.progress = ko.observable(undefined); - self.filesize = ko.observable(undefined); - self.filepos = ko.observable(undefined); - self.printTime = ko.observable(undefined); - self.printTimeLeft = ko.observable(undefined); - self.sd = ko.observable(undefined); - self.timelapse = ko.observable(undefined); + self.filename = ko.observable(undefined); + self.progress = ko.observable(undefined); + self.filesize = ko.observable(undefined); + self.filepos = ko.observable(undefined); + self.printTime = ko.observable(undefined); + self.printTimeLeft = ko.observable(undefined); + self.sd = ko.observable(undefined); + self.timelapse = ko.observable(undefined); - self.filament = ko.observableArray([]); - self.estimatedPrintTime = ko.observable(undefined); - self.lastPrintTime = ko.observable(undefined); + self.busyFiles = ko.observableArray([]); - self.currentHeight = ko.observable(undefined); + self.filament = ko.observableArray([]); + self.estimatedPrintTime = ko.observable(undefined); + self.lastPrintTime = ko.observable(undefined); - self.estimatedPrintTimeString = ko.computed(function() { - if (self.lastPrintTime()) - return formatDuration(self.lastPrintTime()); - if (self.estimatedPrintTime()) - return formatDuration(self.estimatedPrintTime()); - return "-"; - }); - self.byteString = ko.computed(function() { - if (!self.filesize()) + self.currentHeight = ko.observable(undefined); + + self.TITLE_PRINT_BUTTON_PAUSED = gettext("Restarts the print job from the beginning"); + self.TITLE_PRINT_BUTTON_UNPAUSED = gettext("Starts the print job"); + self.TITLE_PAUSE_BUTTON_PAUSED = gettext("Resumes the print job"); + self.TITLE_PAUSE_BUTTON_UNPAUSED = gettext("Pauses the print job"); + + self.titlePrintButton = ko.observable(self.TITLE_PRINT_BUTTON_UNPAUSED); + self.titlePauseButton = ko.observable(self.TITLE_PAUSE_BUTTON_UNPAUSED); + + self.estimatedPrintTimeString = ko.computed(function() { + if (self.lastPrintTime()) + return formatDuration(self.lastPrintTime()); + if (self.estimatedPrintTime()) + return formatDuration(self.estimatedPrintTime()); return "-"; - var filepos = self.filepos() ? formatSize(self.filepos()) : "-"; - return filepos + " / " + formatSize(self.filesize()); - }); - self.heightString = ko.computed(function() { - if (!self.currentHeight()) - return "-"; - return _.sprintf("%.02fmm", self.currentHeight()); - }); - self.printTimeString = ko.computed(function() { - if (!self.printTime()) - return "-"; - return formatDuration(self.printTime()); - }); - self.printTimeLeftString = ko.computed(function() { - if (!self.printTimeLeft()) - return "-"; - return formatDuration(self.printTimeLeft()); - }); - self.progressString = ko.computed(function() { - if (!self.progress()) - return 0; - return self.progress(); - }); - self.pauseString = ko.computed(function() { - if (self.isPaused()) - return gettext("Continue"); - else - return gettext("Pause"); - }); - - self.timelapseString = ko.computed(function() { - var timelapse = self.timelapse(); - - if (!timelapse || !timelapse.hasOwnProperty("type")) - return "-"; - - var type = timelapse["type"]; - if (type == "zchange") { - return gettext("On Z Change"); - } else if (type == "timed") { - return gettext("Timed") + " (" + timelapse["options"]["interval"] + " " + gettext("sec") + ")"; - } else { - return "-"; - } - }); - - self.fromCurrentData = function(data) { - self._fromData(data); - }; - - self.fromHistoryData = function(data) { - self._fromData(data); - }; - - self.fromTimelapseData = function(data) { - self.timelapse(data); - }; - - self._fromData = function(data) { - self._processStateData(data.state); - self._processJobData(data.job); - self._processProgressData(data.progress); - self._processZData(data.currentZ); - }; - - self._processStateData = function(data) { - self.stateString(gettext(data.text)); - self.isErrorOrClosed(data.flags.closedOrError); - self.isOperational(data.flags.operational); - self.isPaused(data.flags.paused); - self.isPrinting(data.flags.printing); - self.isError(data.flags.error); - self.isReady(data.flags.ready); - self.isSdReady(data.flags.sdReady); - }; - - self._processJobData = function(data) { - if (data.file) { - self.filename(data.file.name); - self.filesize(data.file.size); - self.sd(data.file.origin == "sdcard"); - } else { - self.filename(undefined); - self.filesize(undefined); - self.sd(undefined); - } - - self.estimatedPrintTime(data.estimatedPrintTime); - self.lastPrintTime(data.lastPrintTime); - - var result = []; - if (data.filament && typeof(data.filament) == "object" && _.keys(data.filament).length > 0) { - for (var key in data.filament) { - if (!_.startsWith(key, "tool") || !data.filament[key] || !data.filament[key].hasOwnProperty("length") || data.filament[key].length <= 0) continue; - - result.push({ - name: ko.observable(gettext("Tool") + " " + key.substr("tool".length)), - data: ko.observable(data.filament[key]) - }); + }); + self.byteString = ko.computed(function() { + if (!self.filesize()) + return "-"; + var filepos = self.filepos() ? formatSize(self.filepos()) : "-"; + return filepos + " / " + formatSize(self.filesize()); + }); + self.heightString = ko.computed(function() { + if (!self.currentHeight()) + return "-"; + return _.sprintf("%.02fmm", self.currentHeight()); + }); + self.printTimeString = ko.computed(function() { + if (!self.printTime()) + return "-"; + return formatDuration(self.printTime()); + }); + self.printTimeLeftString = ko.computed(function() { + if (self.printTimeLeft() == undefined) { + if (!self.printTime() || !(self.isPrinting() || self.isPaused())) { + return "-"; + } else { + return gettext("Calculating..."); + } + } else { + return formatFuzzyEstimation(self.printTimeLeft()); } - } - self.filament(result); - }; + }); + self.progressString = ko.computed(function() { + if (!self.progress()) + return 0; + return self.progress(); + }); + self.pauseString = ko.computed(function() { + if (self.isPaused()) + return gettext("Continue"); + else + return gettext("Pause"); + }); - self._processProgressData = function(data) { - if (data.completion) { - self.progress(data.completion); - } else { - self.progress(undefined); - } - self.filepos(data.filepos); - self.printTime(data.printTime); - self.printTimeLeft(data.printTimeLeft); - }; + self.timelapseString = ko.computed(function() { + var timelapse = self.timelapse(); - self._processZData = function(data) { - self.currentHeight(data); - }; + if (!timelapse || !timelapse.hasOwnProperty("type")) + return "-"; - self.print = function() { - var restartCommand = function() { - self._jobCommand("restart"); + var type = timelapse["type"]; + if (type == "zchange") { + return gettext("On Z Change"); + } else if (type == "timed") { + return gettext("Timed") + " (" + timelapse["options"]["interval"] + " " + gettext("sec") + ")"; + } else { + return "-"; + } + }); + + self.fromCurrentData = function(data) { + self._fromData(data); }; - if (self.isPaused()) { - $("#confirmation_dialog .confirmation_dialog_message").text(gettext("This will restart the print job from the beginning.")); - $("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click"); - $("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) {e.preventDefault(); $("#confirmation_dialog").modal("hide"); restartCommand(); }); - $("#confirmation_dialog").modal("show"); - } else { - self._jobCommand("start"); + self.fromHistoryData = function(data) { + self._fromData(data); + }; + + self.fromTimelapseData = function(data) { + self.timelapse(data); + }; + + self._fromData = function(data) { + self._processStateData(data.state); + self._processJobData(data.job); + self._processProgressData(data.progress); + self._processZData(data.currentZ); + self._processBusyFiles(data.busyFiles); + }; + + self._processStateData = function(data) { + var prevPaused = self.isPaused(); + + self.stateString(gettext(data.text)); + self.isErrorOrClosed(data.flags.closedOrError); + self.isOperational(data.flags.operational); + self.isPaused(data.flags.paused); + self.isPrinting(data.flags.printing); + self.isError(data.flags.error); + self.isReady(data.flags.ready); + self.isSdReady(data.flags.sdReady); + + if (self.isPaused() != prevPaused) { + if (self.isPaused()) { + self.titlePrintButton(self.TITLE_PRINT_BUTTON_PAUSED); + self.titlePauseButton(self.TITLE_PAUSE_BUTTON_PAUSED); + } else { + self.titlePrintButton(self.TITLE_PRINT_BUTTON_UNPAUSED); + self.titlePauseButton(self.TITLE_PAUSE_BUTTON_UNPAUSED); + } + } + }; + + self._processJobData = function(data) { + if (data.file) { + self.filename(data.file.name); + self.filesize(data.file.size); + self.sd(data.file.origin == "sdcard"); + } else { + self.filename(undefined); + self.filesize(undefined); + self.sd(undefined); + } + + self.estimatedPrintTime(data.estimatedPrintTime); + self.lastPrintTime(data.lastPrintTime); + + var result = []; + if (data.filament && typeof(data.filament) == "object" && _.keys(data.filament).length > 0) { + for (var key in data.filament) { + if (!_.startsWith(key, "tool") || !data.filament[key] || !data.filament[key].hasOwnProperty("length") || data.filament[key].length <= 0) continue; + + result.push({ + name: ko.observable(gettext("Tool") + " " + key.substr("tool".length)), + data: ko.observable(data.filament[key]) + }); + } + } + self.filament(result); + }; + + self._processProgressData = function(data) { + if (data.completion) { + self.progress(data.completion); + } else { + self.progress(undefined); + } + self.filepos(data.filepos); + self.printTime(data.printTime); + self.printTimeLeft(data.printTimeLeft); + }; + + self._processZData = function(data) { + self.currentHeight(data); + }; + + self._processBusyFiles = function(data) { + var busyFiles = []; + _.each(data, function(entry) { + if (entry.hasOwnProperty("name") && entry.hasOwnProperty("origin")) { + busyFiles.push(entry.origin + ":" + entry.name); + } + }); + self.busyFiles(busyFiles); + }; + + self.print = function() { + var restartCommand = function() { + self._jobCommand("restart"); + }; + + if (self.isPaused()) { + $("#confirmation_dialog .confirmation_dialog_message").text(gettext("This will restart the print job from the beginning.")); + $("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click"); + $("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) {e.preventDefault(); $("#confirmation_dialog").modal("hide"); restartCommand(); }); + $("#confirmation_dialog").modal("show"); + } else { + self._jobCommand("start"); + } + + }; + + self.pause = function() { + self._jobCommand("pause"); + }; + + self.cancel = function() { + self._jobCommand("cancel"); + }; + + self._jobCommand = function(command, callback) { + $.ajax({ + url: API_BASEURL + "job", + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify({command: command}), + success: function(response) { + if (callback != undefined) { + callback(); + } + } + }); } - - }; - - self.pause = function() { - self._jobCommand("pause"); - }; - - self.cancel = function() { - self._jobCommand("cancel"); - }; - - self._jobCommand = function(command) { - $.ajax({ - url: API_BASEURL + "job", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({command: command}) - }); } -} + + OCTOPRINT_VIEWMODELS.push([ + PrinterStateViewModel, + ["loginStateViewModel"], + ["#state_wrapper", "#drop_overlay"] + ]); +}); \ No newline at end of file diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 909be6196..30da456e6 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -1,383 +1,340 @@ -function SettingsViewModel(loginStateViewModel, usersViewModel) { - var self = this; +$(function() { + function SettingsViewModel(parameters) { + var self = this; - self.loginState = loginStateViewModel; - self.users = usersViewModel; + self.loginState = parameters[0]; + self.users = parameters[1]; + self.printerProfiles = parameters[2]; - self.api_enabled = ko.observable(undefined); - self.api_key = ko.observable(undefined); - self.api_allowCrossOrigin = ko.observable(undefined); + self.api_enabled = ko.observable(undefined); + self.api_key = ko.observable(undefined); + self.api_allowCrossOrigin = ko.observable(undefined); - self.appearance_name = ko.observable(undefined); - self.appearance_color = ko.observable(undefined); + self.appearance_name = ko.observable(undefined); + self.appearance_color = ko.observable(undefined); + self.appearance_colorTransparent = ko.observable(); - self.appearance_available_colors = ko.observable([ - {key: "default", name: gettext("default")}, - {key: "red", name: gettext("red")}, - {key: "orange", name: gettext("orange")}, - {key: "yellow", name: gettext("yellow")}, - {key: "green", name: gettext("green")}, - {key: "blue", name: gettext("blue")}, - {key: "violet", name: gettext("violet")}, - {key: "black", name: gettext("black")} - ]); + self.settingsDialog = undefined; - self.appearance_colorName = function(color) { - switch (color) { - case "red": - return gettext("red"); - case "orange": - return gettext("orange"); - case "yellow": - return gettext("yellow"); - case "green": - return gettext("green"); - case "blue": - return gettext("blue"); - case "violet": - return gettext("violet"); - case "black": - return gettext("black"); - case "default": - return gettext("default"); - default: - return color; - } - }; + self.appearance_available_colors = ko.observable([ + {key: "default", name: gettext("default")}, + {key: "red", name: gettext("red")}, + {key: "orange", name: gettext("orange")}, + {key: "yellow", name: gettext("yellow")}, + {key: "green", name: gettext("green")}, + {key: "blue", name: gettext("blue")}, + {key: "violet", name: gettext("violet")}, + {key: "black", name: gettext("black")}, + {key: "white", name: gettext("white")}, + ]); - self.printer_movementSpeedX = ko.observable(undefined); - self.printer_movementSpeedY = ko.observable(undefined); - self.printer_movementSpeedZ = ko.observable(undefined); - self.printer_movementSpeedE = ko.observable(undefined); - self.printer_invertAxes = ko.observable(undefined); - self.printer_numExtruders = ko.observable(undefined); - self.printer_defaultExtrusionLength = ko.observable(undefined); - - self._printer_extruderOffsets = ko.observableArray([]); - self.printer_extruderOffsets = ko.computed({ - read: function() { - var extruderOffsets = self._printer_extruderOffsets(); - var result = []; - for (var i = 0; i < extruderOffsets.length; i++) { - result[i] = { - x: parseFloat(extruderOffsets[i].x()), - y: parseFloat(extruderOffsets[i].y()) - } + self.appearance_colorName = function(color) { + switch (color) { + case "red": + return gettext("red"); + case "orange": + return gettext("orange"); + case "yellow": + return gettext("yellow"); + case "green": + return gettext("green"); + case "blue": + return gettext("blue"); + case "violet": + return gettext("violet"); + case "black": + return gettext("black"); + case "white": + return gettext("white"); + case "default": + return gettext("default"); + default: + return color; } - return result; - }, - write: function(value) { - var result = []; - if (value && Array.isArray(value)) { - for (var i = 0; i < value.length; i++) { - result[i] = { - x: ko.observable(value[i].x), - y: ko.observable(value[i].y) + }; + + self.printer_defaultExtrusionLength = ko.observable(undefined); + + self.webcam_streamUrl = ko.observable(undefined); + self.webcam_snapshotUrl = ko.observable(undefined); + self.webcam_ffmpegPath = ko.observable(undefined); + self.webcam_bitrate = ko.observable(undefined); + self.webcam_ffmpegThreads = ko.observable(undefined); + self.webcam_watermark = ko.observable(undefined); + self.webcam_flipH = ko.observable(undefined); + self.webcam_flipV = ko.observable(undefined); + + self.feature_gcodeViewer = ko.observable(undefined); + self.feature_temperatureGraph = ko.observable(undefined); + self.feature_waitForStart = ko.observable(undefined); + self.feature_alwaysSendChecksum = ko.observable(undefined); + self.feature_sdSupport = ko.observable(undefined); + self.feature_sdAlwaysAvailable = ko.observable(undefined); + self.feature_swallowOkAfterResend = ko.observable(undefined); + self.feature_repetierTargetTemp = ko.observable(undefined); + self.feature_keyboardControl = ko.observable(undefined); + + self.serial_port = ko.observable(); + self.serial_baudrate = ko.observable(); + self.serial_portOptions = ko.observableArray([]); + self.serial_baudrateOptions = ko.observableArray([]); + self.serial_autoconnect = ko.observable(undefined); + self.serial_timeoutConnection = ko.observable(undefined); + self.serial_timeoutDetection = ko.observable(undefined); + self.serial_timeoutCommunication = ko.observable(undefined); + self.serial_timeoutTemperature = ko.observable(undefined); + self.serial_timeoutSdStatus = ko.observable(undefined); + self.serial_log = ko.observable(undefined); + + self.folder_uploads = ko.observable(undefined); + self.folder_timelapse = ko.observable(undefined); + self.folder_timelapseTmp = ko.observable(undefined); + self.folder_logs = ko.observable(undefined); + self.folder_watched = ko.observable(undefined); + + self.scripts_gcode_beforePrintStarted = ko.observable(undefined); + self.scripts_gcode_afterPrintDone = ko.observable(undefined); + self.scripts_gcode_afterPrintCancelled = ko.observable(undefined); + self.scripts_gcode_afterPrintPaused = ko.observable(undefined); + self.scripts_gcode_beforePrintResumed = ko.observable(undefined); + self.scripts_gcode_afterPrinterConnected = ko.observable(undefined); + + self.temperature_profiles = ko.observableArray(undefined); + + self.temperature_profiles = ko.observableArray(undefined); + + self.system_actions = ko.observableArray([]); + + self.terminalFilters = ko.observableArray([]); + + self.settings = undefined; + + self.addTemperatureProfile = function() { + self.temperature_profiles.push({name: "New", extruder:0, bed:0}); + }; + + self.removeTemperatureProfile = function(profile) { + self.temperature_profiles.remove(profile); + }; + + self.addTerminalFilter = function() { + self.terminalFilters.push({name: "New", regex: "(Send: M105)|(Recv: ok T:)"}) + }; + + self.removeTerminalFilter = function(filter) { + self.terminalFilters.remove(filter); + }; + + self.onSettingsShown = function() { + self.requestData(); + }; + + self.onStartup = function() { + self.settingsDialog = $('#settings_dialog'); + }; + + self.onAllBound = function(allViewModels) { + self.settingsDialog.on('show', function() { + _.each(allViewModels, function(viewModel) { + if (viewModel.hasOwnProperty("onSettingsShown")) { + viewModel.onSettingsShown(); + } + }); + }); + self.settingsDialog.on('hidden', function() { + _.each(allViewModels, function(viewModel) { + if (viewModel.hasOwnProperty("onSettingsHidden")) { + viewModel.onSettingsHidden(); + } + }); + }); + }; + + self.show = function() { + // show settings, ensure centered position + self.settingsDialog.modal() + .css({ + width: 'auto', + 'margin-left': function() { return -($(this).width() /2); } + }); + + return false; + }; + + self.requestData = function(callback) { + $.ajax({ + url: API_BASEURL + "settings", + type: "GET", + dataType: "json", + success: function(response) { + self.fromResponse(response); + if (callback) callback(); + } + }); + }; + + self.fromResponse = function(response) { + if (self.settings === undefined) { + self.settings = ko.mapping.fromJS(response); + } else { + ko.mapping.fromJS(response, self.settings); + } + + self.api_enabled(response.api.enabled); + self.api_key(response.api.key); + self.api_allowCrossOrigin(response.api.allowCrossOrigin); + + self.appearance_name(response.appearance.name); + self.appearance_color(response.appearance.color); + self.appearance_colorTransparent(response.appearance.colorTransparent); + + self.printer_defaultExtrusionLength(response.printer.defaultExtrusionLength); + + self.webcam_streamUrl(response.webcam.streamUrl); + self.webcam_snapshotUrl(response.webcam.snapshotUrl); + self.webcam_ffmpegPath(response.webcam.ffmpegPath); + self.webcam_bitrate(response.webcam.bitrate); + self.webcam_ffmpegThreads(response.webcam.ffmpegThreads); + self.webcam_watermark(response.webcam.watermark); + self.webcam_flipH(response.webcam.flipH); + self.webcam_flipV(response.webcam.flipV); + + self.feature_gcodeViewer(response.feature.gcodeViewer); + self.feature_temperatureGraph(response.feature.temperatureGraph); + self.feature_waitForStart(response.feature.waitForStart); + self.feature_alwaysSendChecksum(response.feature.alwaysSendChecksum); + self.feature_sdSupport(response.feature.sdSupport); + self.feature_sdAlwaysAvailable(response.feature.sdAlwaysAvailable); + self.feature_swallowOkAfterResend(response.feature.swallowOkAfterResend); + self.feature_repetierTargetTemp(response.feature.repetierTargetTemp); + self.feature_keyboardControl(response.feature.keyboardControl); + + self.serial_port(response.serial.port); + self.serial_baudrate(response.serial.baudrate); + self.serial_portOptions(response.serial.portOptions); + self.serial_baudrateOptions(response.serial.baudrateOptions); + self.serial_autoconnect(response.serial.autoconnect); + self.serial_timeoutConnection(response.serial.timeoutConnection); + self.serial_timeoutDetection(response.serial.timeoutDetection); + self.serial_timeoutCommunication(response.serial.timeoutCommunication); + self.serial_timeoutTemperature(response.serial.timeoutTemperature); + self.serial_timeoutSdStatus(response.serial.timeoutSdStatus); + self.serial_log(response.serial.log); + + self.folder_uploads(response.folder.uploads); + self.folder_timelapse(response.folder.timelapse); + self.folder_timelapseTmp(response.folder.timelapseTmp); + self.folder_logs(response.folder.logs); + self.folder_watched(response.folder.watched); + + self.temperature_profiles(response.temperature.profiles); + + self.scripts_gcode_beforePrintStarted(response.scripts.gcode.beforePrintStarted); + self.scripts_gcode_afterPrintDone(response.scripts.gcode.afterPrintDone); + self.scripts_gcode_afterPrintCancelled(response.scripts.gcode.afterPrintCancelled); + self.scripts_gcode_afterPrintPaused(response.scripts.gcode.afterPrintPaused); + self.scripts_gcode_beforePrintResumed(response.scripts.gcode.beforePrintResumed); + self.scripts_gcode_afterPrinterConnected(response.scripts.gcode.afterPrinterConnected); + + self.temperature_profiles(response.temperature.profiles); + + self.system_actions(response.system.actions); + + self.terminalFilters(response.terminalFilters); + }; + + self.saveData = function() { + var data = ko.mapping.toJS(self.settings); + + data = _.extend(data, { + "api" : { + "enabled": self.api_enabled(), + "key": self.api_key(), + "allowCrossOrigin": self.api_allowCrossOrigin() + }, + "appearance" : { + "name": self.appearance_name(), + "color": self.appearance_color(), + "colorTransparent": self.appearance_colorTransparent() + }, + "printer": { + "defaultExtrusionLength": self.printer_defaultExtrusionLength() + }, + "webcam": { + "streamUrl": self.webcam_streamUrl(), + "snapshotUrl": self.webcam_snapshotUrl(), + "ffmpegPath": self.webcam_ffmpegPath(), + "bitrate": self.webcam_bitrate(), + "ffmpegThreads": self.webcam_ffmpegThreads(), + "watermark": self.webcam_watermark(), + "flipH": self.webcam_flipH(), + "flipV": self.webcam_flipV() + }, + "feature": { + "gcodeViewer": self.feature_gcodeViewer(), + "temperatureGraph": self.feature_temperatureGraph(), + "waitForStart": self.feature_waitForStart(), + "alwaysSendChecksum": self.feature_alwaysSendChecksum(), + "sdSupport": self.feature_sdSupport(), + "sdAlwaysAvailable": self.feature_sdAlwaysAvailable(), + "swallowOkAfterResend": self.feature_swallowOkAfterResend(), + "repetierTargetTemp": self.feature_repetierTargetTemp(), + "keyboardControl": self.feature_keyboardControl() + }, + "serial": { + "port": self.serial_port(), + "baudrate": self.serial_baudrate(), + "autoconnect": self.serial_autoconnect(), + "timeoutConnection": self.serial_timeoutConnection(), + "timeoutDetection": self.serial_timeoutDetection(), + "timeoutCommunication": self.serial_timeoutCommunication(), + "timeoutTemperature": self.serial_timeoutTemperature(), + "timeoutSdStatus": self.serial_timeoutSdStatus(), + "log": self.serial_log() + }, + "folder": { + "uploads": self.folder_uploads(), + "timelapse": self.folder_timelapse(), + "timelapseTmp": self.folder_timelapseTmp(), + "logs": self.folder_logs(), + "watched": self.folder_watched() + }, + "temperature": { + "profiles": self.temperature_profiles() + }, + "system": { + "actions": self.system_actions() + }, + "terminalFilters": self.terminalFilters(), + "scripts": { + "gcode": { + "beforePrintStarted": self.scripts_gcode_beforePrintStarted(), + "afterPrintDone": self.scripts_gcode_afterPrintDone(), + "afterPrintCancelled": self.scripts_gcode_afterPrintCancelled(), + "afterPrintPaused": self.scripts_gcode_afterPrintPaused(), + "beforePrintResumed": self.scripts_gcode_beforePrintResumed(), + "afterPrinterConnected": self.scripts_gcode_afterPrinterConnected() } } - } - self._printer_extruderOffsets(result); - }, - owner: self - }); - self.ko_printer_extruderOffsets = ko.computed(function() { - var extruderOffsets = self._printer_extruderOffsets(); - var numExtruders = self.printer_numExtruders(); - if (!numExtruders) { - numExtruders = 1; - } + }); - if (numExtruders > extruderOffsets.length) { - for (var i = extruderOffsets.length; i < numExtruders; i++) { - extruderOffsets[i] = { - x: ko.observable(0), - y: ko.observable(0) + $.ajax({ + url: API_BASEURL + "settings", + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(data), + success: function(response) { + self.fromResponse(response); + $("#settings_dialog").modal("hide"); } - } - self._printer_extruderOffsets(extruderOffsets); - } + }); + }; + } - return extruderOffsets.slice(0, numExtruders); - }); - - self.printer_bedDimensionX = ko.observable(undefined); - self.printer_bedDimensionY = ko.observable(undefined); - self.printer_bedDimensionR = ko.observable(undefined); - self.printer_bedCircular = ko.observable(undefined); - self.printer_bedDimensions = ko.computed({ - read: function () { - return { - x: parseFloat(self.printer_bedDimensionX()), - y: parseFloat(self.printer_bedDimensionY()), - r: parseFloat(self.printer_bedDimensionR()), - circular: self.printer_bedCircular() - }; - }, - write: function(value) { - self.printer_bedDimensionX(value.x); - self.printer_bedDimensionY(value.y); - self.printer_bedDimensionR(value.r); - self.printer_bedCircular(value.circular); - }, - owner: self - }); - - self.webcam_streamUrl = ko.observable(undefined); - self.webcam_snapshotUrl = ko.observable(undefined); - self.webcam_ffmpegPath = ko.observable(undefined); - self.webcam_bitrate = ko.observable(undefined); - self.webcam_watermark = ko.observable(undefined); - self.webcam_flipH = ko.observable(undefined); - self.webcam_flipV = ko.observable(undefined); - - self.feature_gcodeViewer = ko.observable(undefined); - self.feature_temperatureGraph = ko.observable(undefined); - self.feature_waitForStart = ko.observable(undefined); - self.feature_alwaysSendChecksum = ko.observable(undefined); - self.feature_sdSupport = ko.observable(undefined); - self.feature_sdAlwaysAvailable = ko.observable(undefined); - self.feature_swallowOkAfterResend = ko.observable(undefined); - self.feature_repetierTargetTemp = ko.observable(undefined); - - self.serial_port = ko.observable(); - self.serial_baudrate = ko.observable(); - self.serial_portOptions = ko.observableArray([]); - self.serial_baudrateOptions = ko.observableArray([]); - self.serial_autoconnect = ko.observable(undefined); - self.serial_timeoutConnection = ko.observable(undefined); - self.serial_timeoutDetection = ko.observable(undefined); - self.serial_timeoutCommunication = ko.observable(undefined); - self.serial_timeoutTemperature = ko.observable(undefined); - self.serial_timeoutSdStatus = ko.observable(undefined); - self.serial_log = ko.observable(undefined); - - self.folder_uploads = ko.observable(undefined); - self.folder_timelapse = ko.observable(undefined); - self.folder_timelapseTmp = ko.observable(undefined); - self.folder_logs = ko.observable(undefined); - self.folder_watched = ko.observable(undefined); - - self.cura_enabled = ko.observable(undefined); - self.cura_path = ko.observable(undefined); - self.cura_config = ko.observable(undefined); - - self.temperature_profiles = ko.observableArray(undefined); - - self.system_actions = ko.observableArray([]); - - self.terminalFilters = ko.observableArray([]); - - self.settings = undefined; - - self.addTemperatureProfile = function() { - self.temperature_profiles.push({name: "New", extruder:0, bed:0}); - }; - - self.removeTemperatureProfile = function(profile) { - self.temperature_profiles.remove(profile); - }; - - self.addTerminalFilter = function() { - self.terminalFilters.push({name: "New", regex: "(Send: M105)|(Recv: ok T:)"}) - }; - - self.removeTerminalFilter = function(filter) { - self.terminalFilters.remove(filter); - }; - - self.getPrinterInvertAxis = function(axis) { - return _.contains((self.printer_invertAxes() || []), axis.toLowerCase()); - }; - - self.setPrinterInvertAxis = function(axis, value) { - var currInvert = self.printer_invertAxes() || []; - var currValue = self.getPrinterInvertAxis(axis); - if (value && !currValue) { - currInvert.push(axis.toLowerCase()); - } else if (!value && currValue) { - currInvert = _.without(currInvert, axis.toLowerCase()); - } - self.printer_invertAxes(currInvert); - }; - - self.koInvertAxis = function (axis) { return ko.computed({ - read: function () { return self.getPrinterInvertAxis(axis); }, - write: function (value) { self.setPrinterInvertAxis(axis, value); }, - owner: self - })}; - - self.printer_invertX = self.koInvertAxis('x'); - self.printer_invertY = self.koInvertAxis('y'); - self.printer_invertZ = self.koInvertAxis('z'); - - self.requestData = function(callback) { - $.ajax({ - url: API_BASEURL + "settings", - type: "GET", - dataType: "json", - success: function(response) { - self.fromResponse(response); - if (callback) callback(); - } - }); - }; - - self.fromResponse = function(response) { - if (self.settings === undefined) { - self.settings = ko.mapping.fromJS(response); - } else { - ko.mapping.fromJS(response, self.settings); - } - - self.api_enabled(response.api.enabled); - self.api_key(response.api.key); - self.api_allowCrossOrigin(response.api.allowCrossOrigin); - - self.appearance_name(response.appearance.name); - self.appearance_color(response.appearance.color); - - self.printer_movementSpeedX(response.printer.movementSpeedX); - self.printer_movementSpeedY(response.printer.movementSpeedY); - self.printer_movementSpeedZ(response.printer.movementSpeedZ); - self.printer_movementSpeedE(response.printer.movementSpeedE); - self.printer_invertAxes(response.printer.invertAxes); - self.printer_numExtruders(response.printer.numExtruders); - self.printer_extruderOffsets(response.printer.extruderOffsets); - self.printer_bedDimensions(response.printer.bedDimensions); - self.printer_defaultExtrusionLength(response.printer.defaultExtrusionLength); - - self.webcam_streamUrl(response.webcam.streamUrl); - self.webcam_snapshotUrl(response.webcam.snapshotUrl); - self.webcam_ffmpegPath(response.webcam.ffmpegPath); - self.webcam_bitrate(response.webcam.bitrate); - self.webcam_watermark(response.webcam.watermark); - self.webcam_flipH(response.webcam.flipH); - self.webcam_flipV(response.webcam.flipV); - - self.feature_gcodeViewer(response.feature.gcodeViewer); - self.feature_temperatureGraph(response.feature.temperatureGraph); - self.feature_waitForStart(response.feature.waitForStart); - self.feature_alwaysSendChecksum(response.feature.alwaysSendChecksum); - self.feature_sdSupport(response.feature.sdSupport); - self.feature_sdAlwaysAvailable(response.feature.sdAlwaysAvailable); - self.feature_swallowOkAfterResend(response.feature.swallowOkAfterResend); - self.feature_repetierTargetTemp(response.feature.repetierTargetTemp); - - self.serial_port(response.serial.port); - self.serial_baudrate(response.serial.baudrate); - self.serial_portOptions(response.serial.portOptions); - self.serial_baudrateOptions(response.serial.baudrateOptions); - self.serial_autoconnect(response.serial.autoconnect); - self.serial_timeoutConnection(response.serial.timeoutConnection); - self.serial_timeoutDetection(response.serial.timeoutDetection); - self.serial_timeoutCommunication(response.serial.timeoutCommunication); - self.serial_timeoutTemperature(response.serial.timeoutTemperature); - self.serial_timeoutSdStatus(response.serial.timeoutSdStatus); - self.serial_log(response.serial.log); - - self.folder_uploads(response.folder.uploads); - self.folder_timelapse(response.folder.timelapse); - self.folder_timelapseTmp(response.folder.timelapseTmp); - self.folder_logs(response.folder.logs); - self.folder_watched(response.folder.watched); - - self.cura_enabled(response.cura.enabled); - self.cura_path(response.cura.path); - self.cura_config(response.cura.config); - - self.temperature_profiles(response.temperature.profiles); - - self.system_actions(response.system.actions); - - self.terminalFilters(response.terminalFilters); - }; - - self.saveData = function() { - var data = ko.mapping.toJS(self.settings); - - data = _.extend(data, { - "api" : { - "enabled": self.api_enabled(), - "key": self.api_key(), - "allowCrossOrigin": self.api_allowCrossOrigin() - }, - "appearance" : { - "name": self.appearance_name(), - "color": self.appearance_color() - }, - "printer": { - "movementSpeedX": self.printer_movementSpeedX(), - "movementSpeedY": self.printer_movementSpeedY(), - "movementSpeedZ": self.printer_movementSpeedZ(), - "movementSpeedE": self.printer_movementSpeedE(), - "invertAxes": self.printer_invertAxes(), - "numExtruders": self.printer_numExtruders(), - "extruderOffsets": self.printer_extruderOffsets(), - "bedDimensions": self.printer_bedDimensions(), - "defaultExtrusionLength": self.printer_defaultExtrusionLength() - }, - "webcam": { - "streamUrl": self.webcam_streamUrl(), - "snapshotUrl": self.webcam_snapshotUrl(), - "ffmpegPath": self.webcam_ffmpegPath(), - "bitrate": self.webcam_bitrate(), - "watermark": self.webcam_watermark(), - "flipH": self.webcam_flipH(), - "flipV": self.webcam_flipV() - }, - "feature": { - "gcodeViewer": self.feature_gcodeViewer(), - "temperatureGraph": self.feature_temperatureGraph(), - "waitForStart": self.feature_waitForStart(), - "alwaysSendChecksum": self.feature_alwaysSendChecksum(), - "sdSupport": self.feature_sdSupport(), - "sdAlwaysAvailable": self.feature_sdAlwaysAvailable(), - "swallowOkAfterResend": self.feature_swallowOkAfterResend(), - "repetierTargetTemp": self.feature_repetierTargetTemp() - }, - "serial": { - "port": self.serial_port(), - "baudrate": self.serial_baudrate(), - "autoconnect": self.serial_autoconnect(), - "timeoutConnection": self.serial_timeoutConnection(), - "timeoutDetection": self.serial_timeoutDetection(), - "timeoutCommunication": self.serial_timeoutCommunication(), - "timeoutTemperature": self.serial_timeoutTemperature(), - "timeoutSdStatus": self.serial_timeoutSdStatus(), - "log": self.serial_log() - }, - "folder": { - "uploads": self.folder_uploads(), - "timelapse": self.folder_timelapse(), - "timelapseTmp": self.folder_timelapseTmp(), - "logs": self.folder_logs(), - "watched": self.folder_watched() - }, - "temperature": { - "profiles": self.temperature_profiles() - }, - "system": { - "actions": self.system_actions() - }, - "cura": { - "enabled": self.cura_enabled(), - "path": self.cura_path(), - "config": self.cura_config() - }, - "terminalFilters": self.terminalFilters() - }); - - $.ajax({ - url: API_BASEURL + "settings", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(data), - success: function(response) { - self.fromResponse(response); - $("#settings_dialog").modal("hide"); - } - }); - }; - -} + OCTOPRINT_VIEWMODELS.push([ + SettingsViewModel, + ["loginStateViewModel", "usersViewModel", "printerProfilesViewModel"], + ["#settings_dialog", "#navbar_settings"] + ]); +}); diff --git a/src/octoprint/static/js/app/viewmodels/slicing.js b/src/octoprint/static/js/app/viewmodels/slicing.js new file mode 100644 index 000000000..eba0581a4 --- /dev/null +++ b/src/octoprint/static/js/app/viewmodels/slicing.js @@ -0,0 +1,199 @@ +$(function() { + function SlicingViewModel(parameters) { + var self = this; + + self.loginState = parameters[0]; + self.printerProfiles = parameters[1]; + + self.target = undefined; + self.file = undefined; + self.data = undefined; + + self.defaultSlicer = undefined; + self.defaultProfile = undefined; + + self.gcodeFilename = ko.observable(); + + self.title = ko.observable(); + self.slicer = ko.observable(); + self.slicers = ko.observableArray(); + self.profile = ko.observable(); + self.profiles = ko.observableArray(); + self.printerProfile = ko.observable(); + + self.configured_slicers = ko.computed(function() { + return _.filter(self.slicers(), function(slicer) { + return slicer.configured; + }); + }); + + self.afterSlicingOptions = [ + {"value": "none", "text": gettext("Do nothing")}, + {"value": "select", "text": gettext("Select for printing")}, + {"value": "print", "text": gettext("Start printing")} + ]; + self.afterSlicing = ko.observable("none"); + + self.show = function(target, file, force) { + if (!self.enableSlicingDialog() && !force) { + return; + } + + self.requestData(); + self.target = target; + self.file = file; + self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: self.file})); + self.gcodeFilename(self.file.substr(0, self.file.lastIndexOf("."))); + self.printerProfile(self.printerProfiles.currentProfile()); + self.afterSlicing("none"); + $("#slicing_configuration_dialog").modal("show"); + }; + + self.slicer.subscribe(function(newValue) { + self.profilesForSlicer(newValue); + }); + + self.enableSlicingDialog = ko.computed(function() { + return self.configured_slicers().length > 0; + }); + + self.enableSliceButton = ko.computed(function() { + return self.gcodeFilename() != undefined + && self.gcodeFilename().trim() != "" + && self.slicer() != undefined + && self.profile() != undefined; + }); + + self.requestData = function(callback) { + $.ajax({ + url: API_BASEURL + "slicing", + type: "GET", + dataType: "json", + success: function(data) { + self.fromResponse(data); + if (callback !== undefined) { + callback(); + } + } + }); + }; + + self.fromResponse = function(data) { + self.data = data; + + var selectedSlicer = undefined; + self.slicers.removeAll(); + _.each(_.values(data), function(slicer) { + var name = slicer.displayName; + if (name == undefined) { + name = slicer.key; + } + + if (slicer.default && slicer.configured) { + selectedSlicer = slicer.key; + } + + self.slicers.push({ + key: slicer.key, + name: name, + configured: slicer.configured + }); + }); + + if (selectedSlicer != undefined) { + self.slicer(selectedSlicer); + } + + self.defaultSlicer = selectedSlicer; + }; + + self.profilesForSlicer = function(key) { + if (key == undefined) { + key = self.slicer(); + } + if (key == undefined || !self.data.hasOwnProperty(key)) { + return; + } + var slicer = self.data[key]; + + var selectedProfile = undefined; + self.profiles.removeAll(); + _.each(_.values(slicer.profiles), function(profile) { + var name = profile.displayName; + if (name == undefined) { + name = profile.key; + } + + if (profile.default) { + selectedProfile = profile.key; + } + + self.profiles.push({ + key: profile.key, + name: name + }) + }); + + if (selectedProfile != undefined) { + self.profile(selectedProfile); + } + + self.defaultProfile = selectedProfile; + }; + + self.slice = function() { + var gcodeFilename = self._sanitize(self.gcodeFilename()); + if (!_.endsWith(gcodeFilename.toLowerCase(), ".gco") + && !_.endsWith(gcodeFilename.toLowerCase(), ".gcode") + && !_.endsWith(gcodeFilename.toLowerCase(), ".g")) { + gcodeFilename = gcodeFilename + ".gco"; + } + + var data = { + command: "slice", + slicer: self.slicer(), + profile: self.profile(), + printerProfile: self.printerProfile(), + gcode: gcodeFilename + }; + + if (self.afterSlicing() == "print") { + data["print"] = true; + } else if (self.afterSlicing() == "select") { + data["select"] = true; + } + + $.ajax({ + url: API_BASEURL + "files/" + self.target + "/" + self.file, + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(data) + }); + + $("#slicing_configuration_dialog").modal("hide"); + + self.gcodeFilename(undefined); + self.slicer(self.defaultSlicer); + self.profile(self.defaultProfile); + }; + + self._sanitize = function(name) { + return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_"); + }; + + self.onStartup = function() { + self.requestData(); + }; + + self.onEventSettingsUpdated = function(payload) { + self.requestData(); + }; + } + + OCTOPRINT_VIEWMODELS.push([ + SlicingViewModel, + ["loginStateViewModel", "printerProfilesViewModel"], + "#slicing_configuration_dialog" + ]); +}); \ No newline at end of file diff --git a/src/octoprint/static/js/app/viewmodels/temperature.js b/src/octoprint/static/js/app/viewmodels/temperature.js index 949001c91..85af5bdb5 100644 --- a/src/octoprint/static/js/app/viewmodels/temperature.js +++ b/src/octoprint/static/js/app/viewmodels/temperature.js @@ -1,353 +1,371 @@ -function TemperatureViewModel(loginStateViewModel, settingsViewModel) { - var self = this; +$(function() { + function TemperatureViewModel(parameters) { + var self = this; - self.loginState = loginStateViewModel; - self.settingsViewModel = settingsViewModel; + self.loginState = parameters[0]; + self.settingsViewModel = parameters[1]; - self._createToolEntry = function() { - return { - name: ko.observable(), - key: ko.observable(), - actual: ko.observable(0), - target: ko.observable(0), - offset: ko.observable(0), - newTarget: ko.observable(), - newOffset: ko.observable() - } - }; + self._createToolEntry = function() { + return { + name: ko.observable(), + key: ko.observable(), + actual: ko.observable(0), + target: ko.observable(0), + offset: ko.observable(0), + newTarget: ko.observable(), + newOffset: ko.observable() + } + }; - self.tools = ko.observableArray([]); - self.hasBed = ko.observable(true); - self.bedTemp = self._createToolEntry(); - self.bedTemp["name"](gettext("Bed")); - self.bedTemp["key"]("bed"); + self.tools = ko.observableArray([]); + self.hasBed = ko.observable(true); + self.bedTemp = self._createToolEntry(); + self.bedTemp["name"](gettext("Bed")); + self.bedTemp["key"]("bed"); - self.isErrorOrClosed = ko.observable(undefined); - self.isOperational = ko.observable(undefined); - self.isPrinting = ko.observable(undefined); - self.isPaused = ko.observable(undefined); - self.isError = ko.observable(undefined); - self.isReady = ko.observable(undefined); - self.isLoading = ko.observable(undefined); + self.isErrorOrClosed = ko.observable(undefined); + self.isOperational = ko.observable(undefined); + self.isPrinting = ko.observable(undefined); + self.isPaused = ko.observable(undefined); + self.isError = ko.observable(undefined); + self.isReady = ko.observable(undefined); + self.isLoading = ko.observable(undefined); - self.temperature_profiles = settingsViewModel.temperature_profiles; + self.temperature_profiles = self.settingsViewModel.temperature_profiles; - self.heaterOptions = ko.observable({}); + self.heaterOptions = ko.observable({}); - self._numExtrudersUpdated = function() { - var graphColors = ["red", "orange", "green", "brown", "purple"]; - var heaterOptions = {}; - var tools = self.tools(); + self._numExtrudersUpdated = function() { + var graphColors = ["red", "orange", "green", "brown", "purple"]; + var heaterOptions = {}; + var tools = self.tools(); - // tools - var numExtruders = self.settingsViewModel.printer_numExtruders(); - if (numExtruders && numExtruders > 1) { - // multiple extruders - for (var extruder = 0; extruder < numExtruders; extruder++) { - var color = graphColors.shift(); - if (!color) color = "black"; - heaterOptions["tool" + extruder] = {name: "T" + extruder, color: color}; + // tools + var numExtruders = self.settingsViewModel.printerProfiles.currentProfileData().extruder.count(); + if (numExtruders && numExtruders > 1) { + // multiple extruders + for (var extruder = 0; extruder < numExtruders; extruder++) { + var color = graphColors.shift(); + if (!color) color = "black"; + heaterOptions["tool" + extruder] = {name: "T" + extruder, color: color}; - if (tools.length <= extruder || !tools[extruder]) { - tools[extruder] = self._createToolEntry(); + if (tools.length <= extruder || !tools[extruder]) { + tools[extruder] = self._createToolEntry(); + } + tools[extruder]["name"](gettext("Tool") + " " + extruder); + tools[extruder]["key"]("tool" + extruder); } - tools[extruder]["name"](gettext("Tool") + " " + extruder); - tools[extruder]["key"]("tool" + extruder); + } else { + // only one extruder, no need to add numbers + var color = graphColors[0]; + heaterOptions["tool0"] = {name: "T", color: color}; + + if (tools.length < 1 || !tools[0]) { + tools[0] = self._createToolEntry(); + } + tools[0]["name"](gettext("Hotend")); + tools[0]["key"]("tool0"); } - } else { - // only one extruder, no need to add numbers - var color = graphColors[0]; - heaterOptions["tool0"] = {name: "T", color: color}; - if (tools.length < 1 || !tools[0]) { - tools[0] = self._createToolEntry(); - } - tools[0]["name"](gettext("Hotend")); - tools[0]["key"]("tool0"); - } + // print bed + heaterOptions["bed"] = {name: gettext("Bed"), color: "blue"}; - // print bed - heaterOptions["bed"] = {name: gettext("Bed"), color: "blue"}; - - // write back - self.heaterOptions(heaterOptions); - self.tools(tools); - }; - self.settingsViewModel.printer_numExtruders.subscribe(self._numExtrudersUpdated); - - self.temperatures = []; - self.plotOptions = { - yaxis: { - min: 0, - max: 310, - ticks: 10 - }, - xaxis: { - mode: "time", - minTickSize: [2, "minute"], - tickFormatter: function(val, axis) { - if (val == undefined || val == 0) - return ""; // we don't want to display the minutes since the epoch if not connected yet ;) - - // current time in milliseconds in UTC - var timestampUtc = Date.now(); - - // calculate difference in milliseconds - var diff = timestampUtc - val; - - // convert to minutes - var diffInMins = Math.round(diff / (60 * 1000)); - if (diffInMins == 0) - return gettext("just now"); - else - return "- " + diffInMins + " " + gettext("min"); - } - }, - legend: { - position: "sw", - noColumns: 2, - backgroundOpacity: 0 - } - }; - - self.fromCurrentData = function(data) { - self._processStateData(data.state); - self._processTemperatureUpdateData(data.temps); - self._processOffsetData(data.offsets); - }; - - self.fromHistoryData = function(data) { - self._processStateData(data.state); - self._processTemperatureHistoryData(data.temps); - self._processOffsetData(data.offsets); - }; - - self._processStateData = function(data) { - self.isErrorOrClosed(data.flags.closedOrError); - self.isOperational(data.flags.operational); - self.isPaused(data.flags.paused); - self.isPrinting(data.flags.printing); - self.isError(data.flags.error); - self.isReady(data.flags.ready); - self.isLoading(data.flags.loading); - }; - - self._processTemperatureUpdateData = function(data) { - if (data.length == 0) - return; - - var lastData = data[data.length - 1]; - - var tools = self.tools(); - for (var i = 0; i < tools.length; i++) { - if (lastData.hasOwnProperty("tool" + i)) { - tools[i]["actual"](lastData["tool" + i].actual); - tools[i]["target"](lastData["tool" + i].target); - } - } - - if (lastData.hasOwnProperty("bed")) { - self.hasBed(true); - self.bedTemp["actual"](lastData.bed.actual); - self.bedTemp["target"](lastData.bed.target); - } else { - self.hasBed(false); - } - - if (!CONFIG_TEMPERATURE_GRAPH) return; - - self.temperatures = self._processTemperatureData(data, self.temperatures); - _.each(_.keys(self.heaterOptions()), function(d) { - self.temperatures[d].actual = self.temperatures[d].actual.slice(-300); - self.temperatures[d].target = self.temperatures[d].target.slice(-300); + // write back + self.heaterOptions(heaterOptions); + self.tools(tools); + }; + self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() { + self._numExtrudersUpdated(); + self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.subscribe(self._numExtrudersUpdated); }); - self.updatePlot(); - }; + self.temperatures = []; + self.plotOptions = { + yaxis: { + min: 0, + max: 310, + ticks: 10 + }, + xaxis: { + mode: "time", + minTickSize: [2, "minute"], + tickFormatter: function(val, axis) { + if (val == undefined || val == 0) + return ""; // we don't want to display the minutes since the epoch if not connected yet ;) - self._processTemperatureHistoryData = function(data) { - self.temperatures = self._processTemperatureData(data); - self.updatePlot(); - }; + // current time in milliseconds in UTC + var timestampUtc = Date.now(); - self._processOffsetData = function(data) { - var tools = self.tools(); - for (var i = 0; i < tools.length; i++) { - if (data.hasOwnProperty("tool" + i)) { - tools[i]["offset"](data["tool" + i]); + // calculate difference in milliseconds + var diff = timestampUtc - val; + + // convert to minutes + var diffInMins = Math.round(diff / (60 * 1000)); + if (diffInMins == 0) + return gettext("just now"); + else + return "- " + diffInMins + " " + gettext("min"); + } + }, + legend: { + position: "sw", + noColumns: 2, + backgroundOpacity: 0 } - } + }; - if (data.hasOwnProperty("bed")) { - self.bedTemp["offset"](data["bed"]); - } - }; + self.fromCurrentData = function(data) { + self._processStateData(data.state); + self._processTemperatureUpdateData(data.temps); + self._processOffsetData(data.offsets); + }; - self._processTemperatureData = function(data, result) { - var types = _.keys(self.heaterOptions()); + self.fromHistoryData = function(data) { + self._processStateData(data.state); + self._processTemperatureHistoryData(data.temps); + self._processOffsetData(data.offsets); + }; - // make sure result is properly initialized - if (!result) { - result = {}; - } + self._processStateData = function(data) { + self.isErrorOrClosed(data.flags.closedOrError); + self.isOperational(data.flags.operational); + self.isPaused(data.flags.paused); + self.isPrinting(data.flags.printing); + self.isError(data.flags.error); + self.isReady(data.flags.ready); + self.isLoading(data.flags.loading); + }; - _.each(types, function(type) { - if (!result.hasOwnProperty(type)) { - result[type] = {actual: [], target: []}; + self._processTemperatureUpdateData = function(data) { + if (data.length == 0) + return; + + var lastData = data[data.length - 1]; + + var tools = self.tools(); + for (var i = 0; i < tools.length; i++) { + if (lastData.hasOwnProperty("tool" + i)) { + tools[i]["actual"](lastData["tool" + i].actual); + tools[i]["target"](lastData["tool" + i].target); + } + } + + if (lastData.hasOwnProperty("bed")) { + self.hasBed(true); + self.bedTemp["actual"](lastData.bed.actual); + self.bedTemp["target"](lastData.bed.target); + } else { + self.hasBed(false); + } + + if (!CONFIG_TEMPERATURE_GRAPH) return; + + self.temperatures = self._processTemperatureData(data, self.temperatures); + _.each(_.keys(self.heaterOptions()), function(d) { + self.temperatures[d].actual = self.temperatures[d].actual.slice(-300); + self.temperatures[d].target = self.temperatures[d].target.slice(-300); + }); + + self.updatePlot(); + }; + + self._processTemperatureHistoryData = function(data) { + self.temperatures = self._processTemperatureData(data); + self.updatePlot(); + }; + + self._processOffsetData = function(data) { + var tools = self.tools(); + for (var i = 0; i < tools.length; i++) { + if (data.hasOwnProperty("tool" + i)) { + tools[i]["offset"](data["tool" + i]); + } + } + + if (data.hasOwnProperty("bed")) { + self.bedTemp["offset"](data["bed"]); + } + }; + + self._processTemperatureData = function(data, result) { + var types = _.keys(self.heaterOptions()); + + // make sure result is properly initialized + if (!result) { + result = {}; } - if (!result[type].hasOwnProperty("actual")) result[type]["actual"] = []; - if (!result[type].hasOwnProperty("target")) result[type]["target"] = []; - }); - // convert data - _.each(data, function(d) { - var time = d.time * 1000; _.each(types, function(type) { - if (!d[type]) return; - result[type].actual.push([time, d[type].actual]); - result[type].target.push([time, d[type].target]); + if (!result.hasOwnProperty(type)) { + result[type] = {actual: [], target: []}; + } + if (!result[type].hasOwnProperty("actual")) result[type]["actual"] = []; + if (!result[type].hasOwnProperty("target")) result[type]["target"] = []; + }); - self.hasBed(self.hasBed() || (type == "bed")); - }) - }); + // convert data + _.each(data, function(d) { + var time = d.time * 1000; + _.each(types, function(type) { + if (!d[type]) return; + result[type].actual.push([time, d[type].actual]); + result[type].target.push([time, d[type].target]); - return result; - }; + self.hasBed(self.hasBed() || (type == "bed")); + }) + }); - self.updatePlot = function() { - var graph = $("#temperature-graph"); - if (graph.length) { - var data = []; - var heaterOptions = self.heaterOptions(); - if (!heaterOptions) return; + return result; + }; - _.each(_.keys(heaterOptions), function(type) { - if (type == "bed" && !self.hasBed()) { + self.updatePlot = function() { + var graph = $("#temperature-graph"); + if (graph.length) { + var data = []; + var heaterOptions = self.heaterOptions(); + if (!heaterOptions) return; + + _.each(_.keys(heaterOptions), function(type) { + if (type == "bed" && !self.hasBed()) { + return; + } + + var actuals = []; + var targets = []; + + if (self.temperatures[type]) { + actuals = self.temperatures[type].actual; + targets = self.temperatures[type].target; + } + + var actualTemp = actuals && actuals.length ? formatTemperature(actuals[actuals.length - 1][1]) : "-"; + var targetTemp = targets && targets.length ? formatTemperature(targets[targets.length - 1][1]) : "-"; + + data.push({ + label: gettext("Actual") + " " + heaterOptions[type].name + ": " + actualTemp, + color: heaterOptions[type].color, + data: actuals + }); + data.push({ + label: gettext("Target") + " " + heaterOptions[type].name + ": " + targetTemp, + color: pusher.color(heaterOptions[type].color).tint(0.5).html(), + data: targets + }); + }); + + $.plot(graph, data, self.plotOptions); + } + }; + + self.setTarget = function(item) { + var value = item.newTarget(); + if (!value) return; + + self._sendToolCommand("target", + item.key(), + item.newTarget(), + function() {item.newTarget("");} + ); + }; + + self.setTargetFromProfile = function(item, profile) { + if (!profile) return; + + var value = undefined; + if (item.key() == "bed") { + value = profile.bed; + } else { + value = profile.extruder; + } + + self._sendToolCommand("target", + item.key(), + value, + function() {item.newTarget("");} + ); + }; + + self.setTargetToZero = function(item) { + self._sendToolCommand("target", + item.key(), + 0, + function() {item.newTarget("");} + ); + }; + + self.setOffset = function(item) { + self._sendToolCommand("offset", + item.key(), + item.newOffset(), + function() {item.newOffset("");} + ); + }; + + self._sendToolCommand = function(command, type, temp, successCb, errorCb) { + var data = { + command: command + }; + + var endpoint; + if (type == "bed") { + if ("target" == command) { + data["target"] = parseInt(temp); + } else if ("offset" == command) { + data["offset"] = parseInt(temp); + } else { return; } - var actuals = []; - var targets = []; - - if (self.temperatures[type]) { - actuals = self.temperatures[type].actual; - targets = self.temperatures[type].target; + endpoint = "bed"; + } else { + var group; + if ("target" == command) { + group = "targets"; + } else if ("offset" == command) { + group = "offsets"; + } else { + return; } + data[group] = {}; + data[group][type] = parseInt(temp); - var actualTemp = actuals && actuals.length ? formatTemperature(actuals[actuals.length - 1][1]) : "-"; - var targetTemp = targets && targets.length ? formatTemperature(targets[targets.length - 1][1]) : "-"; + endpoint = "tool"; + } - data.push({ - label: gettext("Actual") + " " + heaterOptions[type].name + ": " + actualTemp, - color: heaterOptions[type].color, - data: actuals - }); - data.push({ - label: gettext("Target") + " " + heaterOptions[type].name + ": " + targetTemp, - color: pusher.color(heaterOptions[type].color).tint(0.5).html(), - data: targets - }); + $.ajax({ + url: API_BASEURL + "printer/" + endpoint, + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(data), + success: function() { if (successCb !== undefined) successCb(); }, + error: function() { if (errorCb !== undefined) errorCb(); } }); - $.plot(graph, data, self.plotOptions); - } - }; - - self.setTarget = function(item) { - var value = item.newTarget(); - if (!value) return; - - self._sendToolCommand("target", - item.key(), - item.newTarget(), - function() {item.newTarget("");} - ); - }; - - self.setTargetFromProfile = function(item, profile) { - if (!profile) return; - - var value = undefined; - if (item.key() == "bed") { - value = profile.bed; - } else { - value = profile.extruder; - } - - self._sendToolCommand("target", - item.key(), - value, - function() {item.newTarget("");} - ); - }; - - self.setTargetToZero = function(item) { - self._sendToolCommand("target", - item.key(), - 0, - function() {item.newTarget("");} - ); - }; - - self.setOffset = function(item) { - self._sendToolCommand("offset", - item.key(), - item.newOffset(), - function() {item.newOffset("");} - ); - }; - - self._sendToolCommand = function(command, type, temp, successCb, errorCb) { - var data = { - command: command }; - var endpoint; - if (type == "bed") { - if ("target" == command) { - data["target"] = parseInt(temp); - } else if ("offset" == command) { - data["offset"] = parseInt(temp); - } else { + self.handleEnter = function(event, type, item) { + if (event.keyCode == 13) { + if (type == "target") { + self.setTarget(item); + } else if (type == "offset") { + self.setOffset(item); + } + } + }; + + self.onAfterTabChange = function(current, previous) { + if (current != "#temp") { return; } - - endpoint = "bed"; - } else { - var group; - if ("target" == command) { - group = "targets"; - } else if ("offset" == command) { - group = "offsets"; - } else { - return; - } - data[group] = {}; - data[group][type] = parseInt(temp); - - endpoint = "tool"; + self.updatePlot(); } - $.ajax({ - url: API_BASEURL + "printer/" + endpoint, - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(data), - success: function() { if (successCb !== undefined) successCb(); }, - error: function() { if (errorCb !== undefined) errorCb(); } - }); + } - }; - - self.handleEnter = function(event, type, item) { - if (event.keyCode == 13) { - if (type == "target") { - self.setTarget(item); - } else if (type == "offset") { - self.setOffset(item); - } - } - }; - -} + OCTOPRINT_VIEWMODELS.push([ + TemperatureViewModel, + ["loginStateViewModel", "settingsViewModel"], + "#temp" + ]); +}); \ No newline at end of file diff --git a/src/octoprint/static/js/app/viewmodels/terminal.js b/src/octoprint/static/js/app/viewmodels/terminal.js index edf5841c3..235dd0c83 100644 --- a/src/octoprint/static/js/app/viewmodels/terminal.js +++ b/src/octoprint/static/js/app/viewmodels/terminal.js @@ -1,155 +1,225 @@ -function TerminalViewModel(loginStateViewModel, settingsViewModel) { - var self = this; +$(function() { + function TerminalViewModel(parameters) { + var self = this; - self.loginState = loginStateViewModel; - self.settings = settingsViewModel; + self.loginState = parameters[0]; + self.settings = parameters[1]; - self.log = []; + self.log = ko.observableArray([]); + self.buffer = ko.observable(300); - self.command = ko.observable(undefined); + self.command = ko.observable(undefined); - self.isErrorOrClosed = ko.observable(undefined); - self.isOperational = ko.observable(undefined); - self.isPrinting = ko.observable(undefined); - self.isPaused = ko.observable(undefined); - self.isError = ko.observable(undefined); - self.isReady = ko.observable(undefined); - self.isLoading = ko.observable(undefined); + self.isErrorOrClosed = ko.observable(undefined); + self.isOperational = ko.observable(undefined); + self.isPrinting = ko.observable(undefined); + self.isPaused = ko.observable(undefined); + self.isError = ko.observable(undefined); + self.isReady = ko.observable(undefined); + self.isLoading = ko.observable(undefined); - self.autoscrollEnabled = ko.observable(true); + self.autoscrollEnabled = ko.observable(true); - self.filters = self.settings.terminalFilters; - self.filterRegex = undefined; + self.filters = self.settings.terminalFilters; + self.filterRegex = ko.observable(); - self.cmdHistory = []; - self.cmdHistoryIdx = -1; + self.cmdHistory = []; + self.cmdHistoryIdx = -1; - self.activeFilters = ko.observableArray([]); - self.activeFilters.subscribe(function(e) { - self.updateFilterRegex(); - self.updateOutput(); - }); + self.displayedLines = ko.computed(function() { + var regex = self.filterRegex(); + var lineVisible = function(entry) { + return regex == undefined || !entry.line.match(regex); + }; - self.fromCurrentData = function(data) { - self._processStateData(data.state); - self._processCurrentLogData(data.logs); - }; - - self.fromHistoryData = function(data) { - self._processStateData(data.state); - self._processHistoryLogData(data.logs); - }; - - self._processCurrentLogData = function(data) { - if (!self.log) - self.log = []; - self.log = self.log.concat(data); - self.log = self.log.slice(-300); - self.updateOutput(); - }; - - self._processHistoryLogData = function(data) { - self.log = data; - self.updateOutput(); - }; - - self._processStateData = function(data) { - self.isErrorOrClosed(data.flags.closedOrError); - self.isOperational(data.flags.operational); - self.isPaused(data.flags.paused); - self.isPrinting(data.flags.printing); - self.isError(data.flags.error); - self.isReady(data.flags.ready); - self.isLoading(data.flags.loading); - }; - - self.updateFilterRegex = function() { - var filterRegexStr = self.activeFilters().join("|").trim(); - if (filterRegexStr == "") { - self.filterRegex = undefined; - } else { - self.filterRegex = new RegExp(filterRegexStr); - } - console.log("Terminal filter regex: " + filterRegexStr); - }; - - self.updateOutput = function() { - if (!self.log) - return; - - var output = ""; - for (var i = 0; i < self.log.length; i++) { - if (self.filterRegex !== undefined && self.log[i].match(self.filterRegex)) continue; - output += self.log[i] + "\n"; - } - - var container = $("#terminal-output"); - container.text(output); - - if (self.autoscrollEnabled()) { - container.scrollTop(container[0].scrollHeight - container.height()) - } - }; - - self.sendCommand = function() { - var command = self.command(); - if (!command) { - return; - } - - var re = /^([gmt][0-9]+)(\s.*)?/; - var commandMatch = command.match(re); - if (commandMatch != null) { - command = commandMatch[1].toUpperCase() + ((commandMatch[2] !== undefined) ? commandMatch[2] : ""); - } - - if (command) { - $.ajax({ - url: API_BASEURL + "printer/command", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({"command": command}) + var filtered = false; + var result = []; + _.each(self.log(), function(entry) { + if (lineVisible(entry)) { + result.push(entry); + filtered = false; + } else if (!filtered) { + result.push(self._toInternalFormat("[...]", "filtered")); + filtered = true; + } }); - self.cmdHistory.push(command); - self.cmdHistory.slice(-300); // just to set a sane limit to how many manually entered commands will be saved... - self.cmdHistoryIdx = self.cmdHistory.length; - self.command(""); - } - }; + return result; + }); + self.displayedLines.subscribe(function() { + self.updateOutput(); + }); - self.handleKeyDown = function(event) { - var keyCode = event.keyCode; + self.lineCount = ko.computed(function() { + var total = self.log().length; + var displayed = _.filter(self.displayedLines(), function(entry) { return entry.type == "line" }).length; + var filtered = total - displayed; - if (keyCode == 38 || keyCode == 40) { - if (keyCode == 38 && self.cmdHistory.length > 0 && self.cmdHistoryIdx > 0) { - self.cmdHistoryIdx--; - } else if (keyCode == 40 && self.cmdHistoryIdx < self.cmdHistory.length - 1) { - self.cmdHistoryIdx++; + if (total == displayed) { + return _.sprintf(gettext("showing %(displayed)d lines"), {displayed: displayed}); + } else { + return _.sprintf(gettext("showing %(displayed)d lines (%(filtered)d of %(total)d total lines filtered)"), {displayed: displayed, total: total, filtered: filtered}); + } + }); + + self.autoscrollEnabled.subscribe(function(newValue) { + if (newValue) { + self.log(self.log.slice(-self.buffer())); + } + }); + + self.activeFilters = ko.observableArray([]); + self.activeFilters.subscribe(function(e) { + self.updateFilterRegex(); + }); + + self.fromCurrentData = function(data) { + self._processStateData(data.state); + self._processCurrentLogData(data.logs); + }; + + self.fromHistoryData = function(data) { + self._processStateData(data.state); + self._processHistoryLogData(data.logs); + }; + + self._processCurrentLogData = function(data) { + self.log(self.log().concat(_.map(data, function(line) { return self._toInternalFormat(line) }))); + if (self.autoscrollEnabled()) { + self.log(self.log.slice(-300)); + } + }; + + self._processHistoryLogData = function(data) { + self.log(_.map(data, function(line) { return self._toInternalFormat(line) })); + }; + + self._toInternalFormat = function(line, type) { + if (type == undefined) { + type = "line"; + } + return {line: line, type: type} + }; + + self._processStateData = function(data) { + self.isErrorOrClosed(data.flags.closedOrError); + self.isOperational(data.flags.operational); + self.isPaused(data.flags.paused); + self.isPrinting(data.flags.printing); + self.isError(data.flags.error); + self.isReady(data.flags.ready); + self.isLoading(data.flags.loading); + }; + + self.updateFilterRegex = function() { + var filterRegexStr = self.activeFilters().join("|").trim(); + if (filterRegexStr == "") { + self.filterRegex(undefined); + } else { + self.filterRegex(new RegExp(filterRegexStr)); + } + self.updateOutput(); + }; + + self.updateOutput = function() { + if (self.autoscrollEnabled()) { + self.scrollToEnd(); + } + }; + + self.toggleAutoscroll = function() { + self.autoscrollEnabled(!self.autoscrollEnabled()); + }; + + self.selectAll = function() { + var container = $("#terminal-output"); + if (container.length) { + container.selectText(); + } + }; + + self.scrollToEnd = function() { + var container = $("#terminal-output"); + if (container.length) { + container.scrollTop(container[0].scrollHeight - container.height()) + } + }; + + self.sendCommand = function() { + var command = self.command(); + if (!command) { + return; } - if (self.cmdHistoryIdx >= 0 && self.cmdHistoryIdx < self.cmdHistory.length) { - self.command(self.cmdHistory[self.cmdHistoryIdx]); + var re = /^([gmt][0-9]+)(\s.*)?/; + var commandMatch = command.match(re); + if (commandMatch != null) { + command = commandMatch[1].toUpperCase() + ((commandMatch[2] !== undefined) ? commandMatch[2] : ""); } - // prevent the cursor from being moved to the beginning of the input field (this is actually the reason - // why we do the arrow key handling in the keydown event handler, keyup would be too late already to - // prevent this from happening, causing a jumpy cursor) - return false; - } + if (command) { + $.ajax({ + url: API_BASEURL + "printer/command", + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify({"command": command}) + }); - // do not prevent default action - return true; - }; + self.cmdHistory.push(command); + self.cmdHistory.slice(-300); // just to set a sane limit to how many manually entered commands will be saved... + self.cmdHistoryIdx = self.cmdHistory.length; + self.command(""); + } + }; - self.handleKeyUp = function(event) { - if (event.keyCode == 13) { - self.sendCommand(); - } + self.handleKeyDown = function(event) { + var keyCode = event.keyCode; - // do not prevent default action - return true; - }; + if (keyCode == 38 || keyCode == 40) { + if (keyCode == 38 && self.cmdHistory.length > 0 && self.cmdHistoryIdx > 0) { + self.cmdHistoryIdx--; + } else if (keyCode == 40 && self.cmdHistoryIdx < self.cmdHistory.length - 1) { + self.cmdHistoryIdx++; + } -} + if (self.cmdHistoryIdx >= 0 && self.cmdHistoryIdx < self.cmdHistory.length) { + self.command(self.cmdHistory[self.cmdHistoryIdx]); + } + + // prevent the cursor from being moved to the beginning of the input field (this is actually the reason + // why we do the arrow key handling in the keydown event handler, keyup would be too late already to + // prevent this from happening, causing a jumpy cursor) + return false; + } + + // do not prevent default action + return true; + }; + + self.handleKeyUp = function(event) { + if (event.keyCode == 13) { + self.sendCommand(); + } + + // do not prevent default action + return true; + }; + + self.onAfterTabChange = function(current, previous) { + if (current != "#term") { + return; + } + if (self.autoscrollEnabled()) { + self.scrollToEnd(); + } + }; + + } + + OCTOPRINT_VIEWMODELS.push([ + TerminalViewModel, + ["loginStateViewModel", "settingsViewModel"], + "#term" + ]); +}); \ No newline at end of file diff --git a/src/octoprint/static/js/app/viewmodels/timelapse.js b/src/octoprint/static/js/app/viewmodels/timelapse.js index 27b9b9951..ed4188b51 100644 --- a/src/octoprint/static/js/app/viewmodels/timelapse.js +++ b/src/octoprint/static/js/app/viewmodels/timelapse.js @@ -1,153 +1,191 @@ -function TimelapseViewModel(loginStateViewModel) { - var self = this; +$(function() { + function TimelapseViewModel(parameters) { + var self = this; - self.loginState = loginStateViewModel; + self.loginState = parameters[0]; - self.timelapseType = ko.observable(undefined); - self.timelapseTimedInterval = ko.observable(undefined); - self.timelapsePostRoll = ko.observable(undefined); + self.defaultFps = 25; + self.defaultPostRoll = 0; + self.defaultInterval = 10; - self.persist = ko.observable(false); - self.isDirty = ko.observable(false); + self.timelapseType = ko.observable(undefined); + self.timelapseTimedInterval = ko.observable(self.defaultInterval); + self.timelapsePostRoll = ko.observable(self.defaultPostRoll); + self.timelapseFps = ko.observable(self.defaultFps); - self.isErrorOrClosed = ko.observable(undefined); - self.isOperational = ko.observable(undefined); - self.isPrinting = ko.observable(undefined); - self.isPaused = ko.observable(undefined); - self.isError = ko.observable(undefined); - self.isReady = ko.observable(undefined); - self.isLoading = ko.observable(undefined); + self.persist = ko.observable(false); + self.isDirty = ko.observable(false); - self.timelapseTypeSelected = ko.computed(function() { - return ("off" != self.timelapseType()); - }); - self.intervalInputEnabled = ko.computed(function() { - return ("timed" == self.timelapseType()); - }); - self.saveButtonEnabled = ko.computed(function() { - return self.isDirty() && self.isOperational() && !self.isPrinting() && self.loginState.isUser(); - }); + self.isErrorOrClosed = ko.observable(undefined); + self.isOperational = ko.observable(undefined); + self.isPrinting = ko.observable(undefined); + self.isPaused = ko.observable(undefined); + self.isError = ko.observable(undefined); + self.isReady = ko.observable(undefined); + self.isLoading = ko.observable(undefined); - self.isOperational.subscribe(function(newValue) { - self.requestData(); - }); - - self.timelapseType.subscribe(function(newValue) { - self.isDirty(true); - }); - self.timelapseTimedInterval.subscribe(function(newValue) { - self.isDirty(true); - }); - - // initialize list helper - self.listHelper = new ItemListHelper( - "timelapseFiles", - { - "name": function(a, b) { - // sorts ascending - if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1; - if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1; - return 0; - }, - "creation": function(a, b) { - // sorts descending - if (a["date"] > b["date"]) return -1; - if (a["date"] < b["date"]) return 1; - return 0; - }, - "size": function(a, b) { - // sorts descending - if (a["bytes"] > b["bytes"]) return -1; - if (a["bytes"] < b["bytes"]) return 1; - return 0; - } - }, - { - }, - "name", - [], - [], - CONFIG_TIMELAPSEFILESPERPAGE - ); - - self.requestData = function() { - $.ajax({ - url: API_BASEURL + "timelapse", - type: "GET", - dataType: "json", - success: self.fromResponse + self.timelapseTypeSelected = ko.computed(function() { + return ("off" != self.timelapseType()); }); - }; - - self.fromResponse = function(response) { - var config = response.config; - if (config === undefined) return; - - self.timelapseType(config.type); - self.listHelper.updateItems(response.files); - - if (config.type == "timed" && response.config.interval) { - self.timelapseTimedInterval(response.config.interval); - } else { - self.timelapseTimedInterval(undefined); - } - - self.persist(false); - self.isDirty(false); - }; - - self.fromCurrentData = function(data) { - self._processStateData(data.state); - }; - - self.fromHistoryData = function(data) { - self._processStateData(data.state); - }; - - self._processStateData = function(data) { - self.isErrorOrClosed(data.flags.closedOrError); - self.isOperational(data.flags.operational); - self.isPaused(data.flags.paused); - self.isPrinting(data.flags.printing); - self.isError(data.flags.error); - self.isReady(data.flags.ready); - self.isLoading(data.flags.loading); - }; - - self.removeFile = function(filename) { - $.ajax({ - url: API_BASEURL + "timelapse/" + filename, - type: "DELETE", - dataType: "json", - success: self.requestData + self.intervalInputEnabled = ko.computed(function() { + return ("timed" == self.timelapseType()); + }); + self.saveButtonEnabled = ko.computed(function() { + return self.isDirty() && self.isOperational() && !self.isPrinting() && self.loginState.isUser(); }); - }; - self.save = function(data, event) { - var payload = { - "type": self.timelapseType(), - "postRoll": self.timelapsePostRoll(), - "save": self.persist() + self.isOperational.subscribe(function(newValue) { + self.requestData(); + }); + + self.timelapseType.subscribe(function(newValue) { + self.isDirty(true); + }); + self.timelapseTimedInterval.subscribe(function(newValue) { + self.isDirty(true); + }); + self.timelapsePostRoll.subscribe(function(newValue) { + self.isDirty(true); + }); + self.timelapseFps.subscribe(function(newValue) { + self.isDirty(true); + }); + + // initialize list helper + self.listHelper = new ItemListHelper( + "timelapseFiles", + { + "name": function(a, b) { + // sorts ascending + if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1; + if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1; + return 0; + }, + "creation": function(a, b) { + // sorts descending + if (a["date"] > b["date"]) return -1; + if (a["date"] < b["date"]) return 1; + return 0; + }, + "size": function(a, b) { + // sorts descending + if (a["bytes"] > b["bytes"]) return -1; + if (a["bytes"] < b["bytes"]) return 1; + return 0; + } + }, + { + }, + "name", + [], + [], + CONFIG_TIMELAPSEFILESPERPAGE + ); + + self.requestData = function() { + $.ajax({ + url: API_BASEURL + "timelapse", + type: "GET", + dataType: "json", + success: self.fromResponse + }); }; - if (self.timelapseType() == "timed") { - payload["interval"] = self.timelapseTimedInterval(); - } + self.fromResponse = function(response) { + var config = response.config; + if (config === undefined) return; - $.ajax({ - url: API_BASEURL + "timelapse", - type: "POST", - dataType: "json", - data: payload, - success: self.fromResponse - }); - }; + self.timelapseType(config.type); + self.listHelper.updateItems(response.files); - self.onDataUpdaterReconnect = function() { - self.requestData(); - }; + if (config.type == "timed") { + if (config.interval != undefined && config.interval > 0) { + self.timelapseTimedInterval(config.interval); + } + } else { + self.timelapseTimedInterval(self.defaultInterval); + } - self.onStartup = function() { - self.requestData(); - }; -} + if (config.postRoll != undefined && config.postRoll >= 0) { + self.timelapsePostRoll(config.postRoll); + } else { + self.timelapsePostRoll(self.defaultPostRoll); + } + + if (config.fps != undefined && config.fps > 0) { + self.timelapseFps(config.fps); + } else { + self.timelapseFps(self.defaultFps); + } + + self.persist(false); + self.isDirty(false); + }; + + self.fromCurrentData = function(data) { + self._processStateData(data.state); + }; + + self.fromHistoryData = function(data) { + self._processStateData(data.state); + }; + + self._processStateData = function(data) { + self.isErrorOrClosed(data.flags.closedOrError); + self.isOperational(data.flags.operational); + self.isPaused(data.flags.paused); + self.isPrinting(data.flags.printing); + self.isError(data.flags.error); + self.isReady(data.flags.ready); + self.isLoading(data.flags.loading); + }; + + self.removeFile = function(filename) { + $.ajax({ + url: API_BASEURL + "timelapse/" + filename, + type: "DELETE", + dataType: "json", + success: self.requestData + }); + }; + + self.save = function(data, event) { + var payload = { + "type": self.timelapseType(), + "postRoll": self.timelapsePostRoll(), + "fps": self.timelapseFps(), + "save": self.persist() + }; + + if (self.timelapseType() == "timed") { + payload["interval"] = self.timelapseTimedInterval(); + } + + $.ajax({ + url: API_BASEURL + "timelapse", + type: "POST", + dataType: "json", + data: payload, + success: self.fromResponse + }); + }; + + self.onDataUpdaterReconnect = function() { + self.requestData(); + }; + + self.onEventMovieDone = function(payload) { + self.requestData(); + }; + + self.onStartup = function() { + self.requestData(); + }; + } + + OCTOPRINT_VIEWMODELS.push([ + TimelapseViewModel, + ["loginStateViewModel"], + "#timelapse" + ]); +}); diff --git a/src/octoprint/static/js/app/viewmodels/users.js b/src/octoprint/static/js/app/viewmodels/users.js index faaedf5bd..0cb04c36b 100644 --- a/src/octoprint/static/js/app/viewmodels/users.js +++ b/src/octoprint/static/js/app/viewmodels/users.js @@ -1,234 +1,248 @@ -function UsersViewModel(loginStateViewModel) { - var self = this; +$(function() { + function UsersViewModel(parameters) { + var self = this; - self.loginState = loginStateViewModel; + self.loginState = parameters[0]; - // initialize list helper - self.listHelper = new ItemListHelper( - "users", - { - "name": function(a, b) { - // sorts ascending - if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1; - if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1; - return 0; + // initialize list helper + self.listHelper = new ItemListHelper( + "users", + { + "name": function(a, b) { + // sorts ascending + if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1; + if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1; + return 0; + } + }, + {}, + "name", + [], + [], + CONFIG_USERSPERPAGE + ); + + self.emptyUser = {name: "", admin: false, active: false}; + + self.currentUser = ko.observable(self.emptyUser); + + self.editorUsername = ko.observable(undefined); + self.editorPassword = ko.observable(undefined); + self.editorRepeatedPassword = ko.observable(undefined); + self.editorApikey = ko.observable(undefined); + self.editorAdmin = ko.observable(undefined); + self.editorActive = ko.observable(undefined); + + self.currentUser.subscribe(function(newValue) { + if (newValue === undefined) { + self.editorUsername(undefined); + self.editorAdmin(undefined); + self.editorActive(undefined); + self.editorApikey(undefined); + } else { + self.editorUsername(newValue.name); + self.editorAdmin(newValue.admin); + self.editorActive(newValue.active); + self.editorApikey(newValue.apikey); } - }, - {}, - "name", - [], - [], - CONFIG_USERSPERPAGE - ); + self.editorPassword(undefined); + self.editorRepeatedPassword(undefined); + }); - self.emptyUser = {name: "", admin: false, active: false}; + self.editorPasswordMismatch = ko.computed(function() { + return self.editorPassword() != self.editorRepeatedPassword(); + }); - self.currentUser = ko.observable(self.emptyUser); + self.loginState.subscribe(function(change, data) { + if (change == "login" && data.admin) { + self.requestData(); + } + }); - self.editorUsername = ko.observable(undefined); - self.editorPassword = ko.observable(undefined); - self.editorRepeatedPassword = ko.observable(undefined); - self.editorApikey = ko.observable(undefined); - self.editorAdmin = ko.observable(undefined); - self.editorActive = ko.observable(undefined); + self.requestData = function() { + if (!CONFIG_ACCESS_CONTROL) return; - self.currentUser.subscribe(function(newValue) { - if (newValue === undefined) { - self.editorUsername(undefined); - self.editorAdmin(undefined); - self.editorActive(undefined); - self.editorApikey(undefined); - } else { - self.editorUsername(newValue.name); - self.editorAdmin(newValue.admin); - self.editorActive(newValue.active); - self.editorApikey(newValue.apikey); + $.ajax({ + url: API_BASEURL + "users", + type: "GET", + dataType: "json", + success: self.fromResponse + }); + }; + + self.fromResponse = function(response) { + self.listHelper.updateItems(response.users); + }; + + self.showAddUserDialog = function() { + if (!CONFIG_ACCESS_CONTROL) return; + + self.currentUser(undefined); + self.editorActive(true); + $("#settings-usersDialogAddUser").modal("show"); + }; + + self.confirmAddUser = function() { + if (!CONFIG_ACCESS_CONTROL) return; + + var user = {name: self.editorUsername(), password: self.editorPassword(), admin: self.editorAdmin(), active: self.editorActive()}; + self.addUser(user, function() { + // close dialog + self.currentUser(undefined); + $("#settings-usersDialogAddUser").modal("hide"); + }); + }; + + self.showEditUserDialog = function(user) { + if (!CONFIG_ACCESS_CONTROL) return; + + self.currentUser(user); + $("#settings-usersDialogEditUser").modal("show"); + }; + + self.confirmEditUser = function() { + if (!CONFIG_ACCESS_CONTROL) return; + + var user = self.currentUser(); + user.active = self.editorActive(); + user.admin = self.editorAdmin(); + + // make AJAX call + self.updateUser(user, function() { + // close dialog + self.currentUser(undefined); + $("#settings-usersDialogEditUser").modal("hide"); + }); + }; + + self.showChangePasswordDialog = function(user) { + if (!CONFIG_ACCESS_CONTROL) return; + + self.currentUser(user); + $("#settings-usersDialogChangePassword").modal("show"); + }; + + self.confirmChangePassword = function() { + if (!CONFIG_ACCESS_CONTROL) return; + + self.updatePassword(self.currentUser().name, self.editorPassword(), function() { + // close dialog + self.currentUser(undefined); + $("#settings-usersDialogChangePassword").modal("hide"); + }); + }; + + self.confirmGenerateApikey = function() { + if (!CONFIG_ACCESS_CONTROL) return; + + self.generateApikey(self.currentUser().name, function(response) { + self._updateApikey(response.apikey); + }) + }; + + self.confirmDeleteApikey = function() { + if (!CONFIG_ACCESS_CONTROL) return; + + self.deleteApikey(self.currentUser().name, function() { + self._updateApikey(undefined); + }) + }; + + self._updateApikey = function(apikey) { + self.editorApikey(apikey); + self.requestData(); + }; + + //~~ AJAX calls + + self.addUser = function(user, callback) { + if (!CONFIG_ACCESS_CONTROL) return; + if (user === undefined) return; + + $.ajax({ + url: API_BASEURL + "users", + type: "POST", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(user), + success: function(response) { + self.fromResponse(response); + callback(); + } + }); + }; + + self.removeUser = function(user, callback) { + if (!CONFIG_ACCESS_CONTROL) return; + if (user === undefined) return; + + if (user.name == self.loginState.username()) { + // we do not allow to delete ourselves + new PNotify({title: "Not possible", text: "You may not delete your own account.", type: "error"}); + return; + } + + $.ajax({ + url: API_BASEURL + "users/" + user.name, + type: "DELETE", + success: function(response) { + self.fromResponse(response); + callback(); + } + }); + }; + + self.updateUser = function(user, callback) { + if (!CONFIG_ACCESS_CONTROL) return; + if (user === undefined) return; + + $.ajax({ + url: API_BASEURL + "users/" + user.name, + type: "PUT", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify(user), + success: function(response) { + self.fromResponse(response); + callback(); + } + }); + }; + + self.updatePassword = function(username, password, callback) { + if (!CONFIG_ACCESS_CONTROL) return; + + $.ajax({ + url: API_BASEURL + "users/" + username + "/password", + type: "PUT", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify({password: password}), + success: callback + }); + }; + + self.generateApikey = function(username, callback) { + if (!CONFIG_ACCESS_CONTROL) return; + + $.ajax({ + url: API_BASEURL + "users/" + username + "/apikey", + type: "POST", + success: callback + }); + }; + + self.deleteApikey = function(username, callback) { + if (!CONFIG_ACCESS_CONTROL) return; + + $.ajax({ + url: API_BASEURL + "users/" + username + "/apikey", + type: "DELETE", + success: callback + }); } - self.editorPassword(undefined); - self.editorRepeatedPassword(undefined); - }); - - self.editorPasswordMismatch = ko.computed(function() { - return self.editorPassword() != self.editorRepeatedPassword(); - }); - - self.requestData = function() { - if (!CONFIG_ACCESS_CONTROL) return; - - $.ajax({ - url: API_BASEURL + "users", - type: "GET", - dataType: "json", - success: self.fromResponse - }); } - self.fromResponse = function(response) { - self.listHelper.updateItems(response.users); - } - - self.showAddUserDialog = function() { - if (!CONFIG_ACCESS_CONTROL) return; - - self.currentUser(undefined); - self.editorActive(true); - $("#settings-usersDialogAddUser").modal("show"); - } - - self.confirmAddUser = function() { - if (!CONFIG_ACCESS_CONTROL) return; - - var user = {name: self.editorUsername(), password: self.editorPassword(), admin: self.editorAdmin(), active: self.editorActive()}; - self.addUser(user, function() { - // close dialog - self.currentUser(undefined); - $("#settings-usersDialogAddUser").modal("hide"); - }); - } - - self.showEditUserDialog = function(user) { - if (!CONFIG_ACCESS_CONTROL) return; - - self.currentUser(user); - $("#settings-usersDialogEditUser").modal("show"); - } - - self.confirmEditUser = function() { - if (!CONFIG_ACCESS_CONTROL) return; - - var user = self.currentUser(); - user.active = self.editorActive(); - user.admin = self.editorAdmin(); - - // make AJAX call - self.updateUser(user, function() { - // close dialog - self.currentUser(undefined); - $("#settings-usersDialogEditUser").modal("hide"); - }); - } - - self.showChangePasswordDialog = function(user) { - if (!CONFIG_ACCESS_CONTROL) return; - - self.currentUser(user); - $("#settings-usersDialogChangePassword").modal("show"); - } - - self.confirmChangePassword = function() { - if (!CONFIG_ACCESS_CONTROL) return; - - self.updatePassword(self.currentUser().name, self.editorPassword(), function() { - // close dialog - self.currentUser(undefined); - $("#settings-usersDialogChangePassword").modal("hide"); - }); - } - - self.confirmGenerateApikey = function() { - if (!CONFIG_ACCESS_CONTROL) return; - - self.generateApikey(self.currentUser().name, function(response) { - self._updateApikey(response.apikey); - }) - } - - self.confirmDeleteApikey = function() { - if (!CONFIG_ACCESS_CONTROL) return; - - self.deleteApikey(self.currentUser().name, function() { - self._updateApikey(undefined); - }) - } - - self._updateApikey = function(apikey) { - self.editorApikey(apikey); - self.requestData(); - } - - //~~ AJAX calls - - self.addUser = function(user, callback) { - if (!CONFIG_ACCESS_CONTROL) return; - if (user === undefined) return; - - $.ajax({ - url: API_BASEURL + "users", - type: "POST", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(user), - success: function(response) { - self.fromResponse(response); - callback(); - } - }); - } - - self.removeUser = function(user, callback) { - if (!CONFIG_ACCESS_CONTROL) return; - if (user === undefined) return; - - if (user.name == loginStateViewModel.username()) { - // we do not allow to delete ourselves - new PNotify({title: "Not possible", text: "You may not delete your own account.", type: "error"}); - return; - } - - $.ajax({ - url: API_BASEURL + "users/" + user.name, - type: "DELETE", - success: function(response) { - self.fromResponse(response); - callback(); - } - }); - } - - self.updateUser = function(user, callback) { - if (!CONFIG_ACCESS_CONTROL) return; - if (user === undefined) return; - - $.ajax({ - url: API_BASEURL + "users/" + user.name, - type: "PUT", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(user), - success: function(response) { - self.fromResponse(response); - callback(); - } - }); - } - - self.updatePassword = function(username, password, callback) { - if (!CONFIG_ACCESS_CONTROL) return; - - $.ajax({ - url: API_BASEURL + "users/" + username + "/password", - type: "PUT", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({password: password}), - success: callback - }); - } - - self.generateApikey = function(username, callback) { - if (!CONFIG_ACCESS_CONTROL) return; - - $.ajax({ - url: API_BASEURL + "users/" + username + "/apikey", - type: "POST", - success: callback - }); - } - - self.deleteApikey = function(username, callback) { - if (!CONFIG_ACCESS_CONTROL) return; - - $.ajax({ - url: API_BASEURL + "users/" + username + "/apikey", - type: "DELETE", - success: callback - }); - } -} + OCTOPRINT_VIEWMODELS.push([ + UsersViewModel, + ["loginStateViewModel"], + [] + ]); +}); \ No newline at end of file diff --git a/src/octoprint/static/js/i18n/de.js b/src/octoprint/static/js/i18n/de.js index 4dec65711..d83ea8acf 100644 --- a/src/octoprint/static/js/i18n/de.js +++ b/src/octoprint/static/js/i18n/de.js @@ -1 +1 @@ -window.BABEL_TO_LOAD_de = {"locale": "de", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-08-28 15:56+0100\nLast-Translator: Gina H\u00e4u\u00dfge \nLanguage-Team: German (http://www.transifex.com/projects/p/octoprint/language/de/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Verbleibende Druckdauer", "Proceed": "Fortfahren", "Timelapse Temp Folder": "Tempor\u00e4res Zeitrafferverzeichnis", "Title": "Titel", "Only show files stored locally": "Nur lokal abgelegte Dateien anzeigen", "yellow": "Gelb", "Path to Cura": "Pfad zu Cura", "Action": "Aktion", "Passwords do not match": "Passw\u00f6rter nicht identisch", "Sort by name": "Nach Name sortieren", "Save connection settings": "Verbindungseinstellungen speichern", "Rendering timelapse": "Zeitraffer wird gerendert", "Cura": "Cura", "Files": "Dateien", "Bed Size": "Bettdimensionen", "Always assume SD card is present": "Immer davon ausgehen, dass eine SD-Karte vorhanden ist", "Load and Print": "Laden und Drucken", "Sending file to SD": "Sende Datei zu SD", "Number of Extruders": "Anzahl Extruder", "black": "Schwarz", "Last Printed": "Zuletzt gedruckt", "Sourcecode": "Quellcode", "Estimated layer height": "Gesch\u00e4tzte Schichth\u00f6he", "You are now logged out": "Du bist jetzt ausgeloggt", "Uploaded": "Hochgeladen", "Opening serial port": "\u00d6ffnet Serialport", "New timelapse %(movie_basename)s is done rendering.": "Neue Zeitrafferaufnahme %(movie_basename)s wurde fertig gerendert", "Invert control": "Invertieren", "Webcam": "Webcam", "Remember me": "Login merken", "Enable GCode Visualizer": "GCode Viewer aktivieren", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below.": "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ihm verbinden. Ich werde \u00fcber die n\u00e4chsten Minuten versuchen, zu reconnecten, aber Du kannst mittels des folgenden Buttons auch jederzeit einen manuellen Reconnect ansto\u00dfen.", "Rendering failed": "Rendering fehlgeschlagen", "Upload Folder": "Uploadverzeichnis", "descending": "absteigend", "X": "X", "Add user": "Nutzer hinzuf\u00fcgen", "GCODE commands in layer": "GCODE Kommandos in Schicht", "Estimated print time": "Gesch\u00e4tzte Druckzeit", "Serial Connection": "Serielle Verbindung", "Control": "Kontrolle", "Password": "Passwort", "Also show next layer": "Auch n\u00e4chste Schicht anzeigen", "Print Time": "Druckdauer", "Sort by file size": "Nach Gr\u00f6\u00dfe sortieren", "Machine State": "Druckerstatus", "default": "Standard", "API": "API", "Printing from SD": "Drucke von SD", "Terminal filters": "Terminalfilter", "Change password for user \"%(user)s\"": "Passwort\u00e4nderung f\u00fcr Nutzer \"%(user)s\"", "Enable Temperature Graph": "Temperaturgraph aktivieren", "Delete user": "Nutzer l\u00f6schen", "Confirm Password": "Passwort best\u00e4tigen", "Disconnect": "Trennen", "Slicing done": "Slicing abgeschlossen", "Initialize SD card": "SD-Karte initialisieren", "System": "System", "Send": "Senden", "State": "Status", "Version": "Version", "YYYY-MM-DD HH:mm": "DD.MM.YYYY HH:mm", "Attempt to reconnect": "Erneut verbinden", "Streaming done": "Streaming abgeschlossen", "violet": "Violett", "Print": "Drucken", "Layer count": "Schichtanzahl", "OctoPrint Settings": "OctoPrint Einstellungen", "Are you sure?": "Bist Du sicher?", "blue": "Blau", "Printer": "Drucker", "Tool": "Werkzeug", "Settings": "Einstellungen", "Path to FFMPEG": "Pfad zu FFMPEG", "Upload to SD": "Upload (SD)", "The command \"%(command)s\" could not be executed.": "Das Kommando \"%(command)s\" konnte nicht ausgef\u00fchrt werden.", "Printed": "Gedruckt", "Layer number": "Schichtnummer", "Sync with job progress": "Job mit Fortschritt synchronisieren", "Circular": "Rund", "Total filament used": "Gesamtmenge genutzten Filaments", "red": "Rot", "Save as default": "Als Standard speichern", "Slicing ...": "Slice ...", "Last Print Time": "Letzte Druckdauer", "Target": "Soll", "Streaming ...": "Streame ...", "Logout successful": "Logout erfolgreich", "Now rendering timelapse %(movie_basename)s": "Rendere Zeitrafferaufnahme %(movie_basename)s", "Documentation": "Dokumentation", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Upload", "ascending": "aufsteigend", "Model size": "Modelgr\u00f6\u00dfe", "Temperatures": "Temperaturen", "visited": "besucht", "Timed": "Nach Zeit", "Edit user \"%(user)s\"": "Editiere Nutzer \"%(user)s\"", "Snapshot URL": "Snapshot-URL", "Release SD card": "SD-Karte auswerfen", "Server is offline": "Der Server ist offline", "Log communication to serial.log (might negatively impact performance)": "Logge die Kommunikation in das serial.log (kann die Performance negativ beeinflussen)", "Sort by upload date": "Nach Uploaddatum sortieren", "Change Password": "Passwort \u00e4ndern", "Logs": "Logs", "Hotend": "Hotend", "Show retracts": "Retracts zeigen", "Keep Access Control Enabled": "Zugangsbeschr\u00e4nkung aktiviert lassen", "Upload locally": "Upload (lokal)", "Select Tool...": "Werkzeug w\u00e4hlen...", "Paused": "Pausiert", "Continue": "Fortsetzen", "Radius": "Radius", "The command \"%(command)s\" executed successfully": "Das Kommando \"%(command)s\" wurde erfolgreich ausgef\u00fchrt", "Features": "Funktionen", "Download": "Download", "GCode Viewer": "GCode Viewer", "Also show previous layer": "Auch vorherige Schicht anzeigen", "Enable OctoPrint watermark in timelapse movies": "OctoPrint Wasserzeichen in Zeitrafferaufnahmen aktivieren", "Repetier": "Repetier", "Login successful": "Login erfolgreich", "Finished Timelapses": "Abgeschlossene Zeitraffer", "Rendering of timelapse %(movie_basename)s failedwith return code %(returncode)s": "Rendering der Zeitrafferaufnahme %(movie_basename)s fehlgeschlagen mit Returncode %(returncode)s", "Pause": "Pause", "Temperature": "Temperatur", "Enable slicing via Cura": "Slicing mittels Cura aktivieren", "Access Control": "Zugangsbeschr\u00e4nkung", "Analyzing...": "Analysiere...", "just now": "gerade eben", "Operational": "Bereit", "Send a checksum with every command": "Eine Pr\u00fcfsumme mit jedem Kommando senden", "Autodetection timeout": "Autodetectiontimeout", "Connecting": "Verbinde", "Free": "Frei", "Closed": "Geschlossen", "Refresh SD files": "SD-Dateien aktualisieren", "Flip webcam vertically": "Webcam vertikal flippen", "Path to Cura config": "Pfad zur Cura-Konfiguration", "Filament": "Filament", "Could not slice %(stl)s to %(gcode)s: %(reason)s": "Konnte %(stl)s nicht nach %(gcode)s slicen: %(reason)s", "Baudrate": "Baudrate", "Detecting baudrate": "Detektiere Baudrate", "Date": "Datum", "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds": "%(local)s nach %(remote)s gestreamt, dauerte %(time).2f Sekunden", "Show moves": "Bewegungen zeigen", "Motors off": "Motoren aus", "Detecting serial port": "Detektiere Serialport", "New Password": "Neues Passwort", "Logout": "Logout", "Offset": "Offset", "Analyzed": "Analysiert", "Auto-connect on server startup": "Automatisch bei Serverstart verbinden", "Printer Parameters": "Druckerparameter", "E": "E", "Restart": "Neu starten", "Search...": "Suchen...", "Slicing failed": "Slicing fehlgeschlagen", "Actual": "Ist", "Active": "Aktiv", "Creation date": "Erstellungsdatum", "Hint: You can also drag and drop files on this page to upload them.": "Hinweis: Du kannst auch Dateien auf diese Seite ziehen um sie hochzuladen.", "Interval": "Intervall", "N/A": "(nicht vorhanden)", "Bed": "Bett", "Auto-connect to printer on server start": "Automatisch bei Serverstart verbinden", "orange": "Orange", "Connection": "Verbindung", "Error": "Fehler", "On Z Change": "Bei Ebenenwechsel", "Timelapse post roll (in rendered seconds)": "Zeitraffernachlauf (in gerenderten Sekunden)", "Z": "Z", "Are you sure you want to proceed?": "Bist Du sicher, dass du fortfahren willst?", "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!": "Wenn Du die Zugangsbeschr\u00e4nkung deaktivierst und Deine OctoPrint Installation vom Internet aus erreichbar ist, kann jeder auf Deinen Drucker zugreifen - auch die b\u00f6sen Jungs!", "Load": "Laden", "Set": "Setzen", "The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below.": "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ihm verbinden. Ich konnte nicht automatisch reconnected, aber Du kannst mittels des folgenden Buttons einen manuellen Reconnect ansto\u00dfen.", "Zoom in on model": "Auf Model zoomen", "mm": "mm", "Saving ...": "Speichere ...", "RegExp": "RegExp", "Watched Folder": "Beobachtetes Verzeichnis", "General": "Allgemein", "Temperature timeout": "Temperaturtimeout", "Color": "Farbe", "Fans on": "L\u00fcfter an", "Swallow the first \"ok\" after a resend response": "Erstes \"ok\" nach Resend ignorieren", "Enable SD support": "SD-Unterst\u00fctzung aktivieren", "Connect": "Verbinden", "Cancel": "Abbruch", "sec": "Sek", "Warning": "Warnung", "Loading...": "Lade...", "Current API Key": "Aktueller API-Key", "Size": "Gr\u00f6\u00dfe", "Communication timeout": "Kommunikationstimeout", "Modification date": "\u00c4nderungsdatum", "Change password": "Passwort \u00e4ndern", "This will restart the print job from the beginning.": "Der Druckjob wird zur\u00fcckgesetzt und von vorne begonnen.", "Stream URL": "Stream-URL", "Sort by": "Sortieren", "Login failed": "Login fehlgeschlagen", "Abort": "Abbrechen", "Confirm": "Best\u00e4tigen", "Repeat Password": "Passwort wiederholen", "Terminal": "Terminal", "Autoscroll": "Autoscroll", "Print time for layer": "Druckdauer f\u00fcr Schicht", "Disable Access Control": "Zugangsbeschr\u00e4nkung deaktivieren", "Configure Access Control": "Zugangsbeschr\u00e4nkung konfigurieren", "Timelapse Configuration": "Zeitrafferkonfiguration", "Retract": "Retract", "Timelapse bitrate": "Zeitrafferbitrate", "Offline": "Offline", "API Key": "API Key", "Homepage": "Homepage", "Estimated Print Time": "Gesch\u00e4tzte Druckzeit", "Folders": "Verzeichnisse", "Bugs and Requests": "Bugs und Requests", "Save": "Speichern", "Default extrusion length": "Standard Extrusionsl\u00e4nge", "min": "Min", "Support TargetExtr%%n/TargetBed target temperature format": "TargetExtr%%n/TargetBed Zieltemperaturformat unterst\u00fctzen", "Connection timeout": "Verbindungstimeout", "Save config": "Konfiguration speichern", "Center viewport on model": "Ausschnitt auf Modell zentrieren", "User unknown or wrong password": "Nutzer unbekannt oder falsches Passwort", "Allow Cross Origin Resource Sharing (CORS)": "Cross Origin Resource Sharing (CORS) erlauben", "Appearance": "Aussehen", "Enable": "Aktivieren", "Uploading ...": "Uploade ...", "Logs Folder": "Logverzeichnis", "

\n Please read the following, it is very important for your printer's health!\n

\n

\n OctoPrint by default now ships with Access Control enabled, meaning you won't be able to do anything with the\n printer unless you login first as a configured user. This is to prevent strangers - possibly with\n malicious intent - to gain access to your printer via the internet or another untrustworthy network\n and using it in such a way that it is damaged or worse (i.e. causes a fire).\n

\n

\n It looks like you haven't configured access control yet. Please set up an username and password for the\n initial administrator account who will have full access to both the printer and OctoPrint's settings, then click\n on \"Keep Access Control Enabled\":\n

": "

\n Bitte lies die folgenden Zeilen aufmerksam durch, es ist sehr wichtig f\u00fcr die Gesundheit Deines Druckers!\n

\n

\n OctoPrint wird nun standardm\u00e4ssig mit aktivierter Zugangsbeschr\u00e4nkung ausgeliefert, das hei\u00dft, dass Du mit dem Drucker nichts\n anfangen kannst, wenn du nicht als einer der konfigurierten Nutzer eingeloggt bist. Das dient dem Zweck, Fremde mit\n m\u00f6glicherweise b\u00f6swilligen Absichten davon abzuhalten, auf Deinen Drucker \u00fcber das Internet oder ein anderes\n unsicheres Netzwerk zuzugreifen und ihn auf eine Art zu nutzen, die ihn besch\u00e4digt oder schlimmeres (z.B. ein Feuer verursacht).\n

\n

\n Es sieht so aus, als h\u00e4ttest Du die Zugriffsbeschr\u00e4nkung noch nicht konfiguriert. Bitte konfiguriere einen Usernamen\n und ein Passwort f\u00fcr das initiale Administratorkonto, das vollen Zugang zu sowohl dem Drucker als auch OctoPrints\n Einstellungen haben wird, und klicke dann auf \"Zugangsbeschr\u00e4nkung aktiviert lassen\".\n

", "Hide successfully printed files": "Erfolgreich gedruckte Dateien verbergen", "Username": "Username", "Off": "Aus", "Name": "Name", "Extruder Offsets": "Extruderoffsets", "Approx. Total Print Time": "Ungef\u00e4hre Gesamtdruckdauer", "Admin": "Admin", "

\n Note: In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't\n need Access Control for other reasons, you may alternatively disable Access Control. You should only\n do this if you are absolutely certain that only people you know and trust will be able to connect to it.\n

\n

\n Do NOT underestimate the risk of an unsecured access from the internet to your printer!\n

": "

\n Beachte: Falls Deine OctoPrint Installation ausschlie\u00dflich innerhalb eines vertrauensw\u00fcrdigen Netzwerks\n erreicht werden kann und Du die Zugangsbeschr\u00e4nkung nicht f\u00fcr andere Zwecke ben\u00f6tigst, kannst Du sie alternativ auch\n deaktivieren. Du solltest das nur tun, wenn Du Dir absolut sicher bist, dass nur Leute darauf zugreifen k\u00f6nnen, die du kennst\n und denen du vertraust\n

\n

\n UNTERSCH\u00c4TZE NICHT das Risiko eines ungesicherten Zugriffs aus dem Internet auf Deinen Drucker!\n

", "Timelapse": "Zeitraffer", "Remove": "Entfernen", "Reload": "Neu laden", "Printing": "Drucke", "Only show files stored on SD": "Nur auf SD abgelegte Dateien anzeigen", "Y": "Y", "Fans off": "L\u00fcfter aus", "Login": "Login", "Timelapse ready": "Zeitraffer fertig", "Timelapse Mode": "Zeitraffermodus", "Timelapse Folder": "Zeitrafferverzeichnis", "Extruder": "Extruder", "Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and slicing support is enabled and configured.": "Konnte die Datei nicht hochladen. Bitte stelle sicher, dass es sich um eine GCODE-Datei mit der Extension \".gcode\" oder \".gco\" oder um eine STL-Datei mit der Extension \".stl\" handelt und in letzterem Fall auch der Slicingsupport aktiviert ist.", "SD status timeout": "SD-Status-Timeout", "SD not initialized": "SD-Karte ist nicht initialisiert", "Update User": "Nutzer editieren", "off": "Aus", "Serial Port": "Serialport", "Flip webcam horizontally": "Webcam horizontal flippen", "Wait for start on connect": "Bei der Verbindung auf start warten", "Transfering file to SD": "Sende Datei zu SD", "OctoPrint": "OctoPrint", "Layer height": "Schichth\u00f6he", "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds": "%(stl)s nach %(gcode)s geslicet, dauerte %(time).2f Sekunden", "Extrude": "Extrude", "green": "Gr\u00fcn", "File": "Datei", "You are now logged in as \"%(username)s\"": "Du bist jetzt eingeloggt als \"%(username)s\"", "Axis": "Achse", "Filament used by layer": "Genutztes Filament in Schicht"}} ; \ No newline at end of file +window.BABEL_TO_LOAD_de = {"locale": "de", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:11+0000\nLast-Translator: Gina H\u00e4u\u00dfge \nLanguage-Team: German (http://www.transifex.com/projects/p/octoprint/language/de/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Verbleibende Druckdauer", "sec": "Sek", "Proceed": "Fortfahren", "Timelapse Temp Folder": "Tempor\u00e4res Zeitrafferverzeichnis", "Support TargetExtr%%n/TargetBed target temperature format": "TargetExtr%%n/TargetBed Zieltemperaturformat unterst\u00fctzen", "Upload Folder": "Uploadverzeichnis", "Only show files stored locally": "Nur lokal abgelegte Dateien anzeigen", "Add Printer Profile": "Druckerprofil hinzuf\u00fcgen", "yellow": "Gelb", "Save": "Speichern", "Action": "Aktion", "Passwords do not match": "Passw\u00f6rter nicht identisch", "Sort by name": "Nach Name sortieren", "Save connection settings": "Verbindungseinstellungen speichern", "Rendering timelapse": "Zeitraffer wird gerendert", "Color": "Farbe", "Temperature": "Temperatur", "Files": "Dateien", "Resume": "Weiter", "Always assume SD card is present": "Immer davon ausgehen, dass eine SD-Karte vorhanden ist", "Load and Print": "Laden und Drucken", "Sending file to SD": "Sende Datei zu SD", "Number of Extruders": "Anzahl Extruder", "black": "Schwarz", "Last Printed": "Zuletzt gedruckt", "Sourcecode": "Quellcode", "Estimated layer height": "Gesch\u00e4tzte Schichth\u00f6he", "You are now logged out": "Du bist jetzt ausgeloggt", "Uploaded": "Hochgeladen", "Form Factor": "Formfaktor", "Opening serial port": "\u00d6ffnet Serialport", "New timelapse %(movie_basename)s is done rendering.": "Neue Zeitrafferaufnahme %(movie_basename)s wurde fertig gerendert", "Invert control": "Invertieren", "Webcam": "Webcam", "Select for printing": "Zum Drucken ausw\u00e4hlen", "Allow Cross Origin Resource Sharing (CORS)": "Cross Origin Resource Sharing (CORS) erlauben", "Remember me": "Login merken", "Enable GCode Visualizer": "GCode Viewer aktivieren", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below.": "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ihm verbinden. Ich werde \u00fcber die n\u00e4chsten Minuten versuchen, mich erneut zu verbinden, aber Du kannst mittels des folgenden Buttons auch jederzeit einen manuellen Reconnect ansto\u00dfen.", "Rendering failed": "Rendering fehlgeschlagen", "Motors off": "Motoren aus", "descending": "absteigend", "Only show files stored on SD": "Nur auf SD abgelegte Dateien anzeigen", "X": "X", "Add user": "Nutzer hinzuf\u00fcgen", "GCODE commands in layer": "GCODE Kommandos in Schicht", "Estimated print time": "Gesch\u00e4tzte Druckdauer", "Serial Connection": "Serielle Verbindung", "Control": "Kontrolle", "Password": "Passwort", "Also show next layer": "Auch n\u00e4chste Schicht anzeigen", "Print Time": "Druckdauer", "Slicer": "Slicer", "Nozzle Diameter": "D\u00fcsendurchmesser", "Sort by file size": "Nach Gr\u00f6\u00dfe sortieren", "Machine State": "Druckerstatus", "Slicing Profile": "Slicingprofil", "mm": "mm", "API": "API", "Printing from SD": "Drucke von SD", "Stream URL": "Stream-URL", "Terminal filters": "Terminalfilter", "Change password for user \"%(user)s\"": "Passwort\u00e4nderung f\u00fcr Nutzer \"%(user)s\"", "Enable Temperature Graph": "Temperaturgraph aktivieren", "Delete user": "Nutzer l\u00f6schen", "Timelapse bitrate": "Zeitrafferbitrate", "Confirm Password": "Passwort best\u00e4tigen", "Disconnect": "Trennen", "Slicing done": "Slicing abgeschlossen", "Initialize SD card": "SD-Karte initialisieren", "System": "System", "Send": "Senden", "State": "Status", "Version": "Version", "YYYY-MM-DD HH:mm": "DD.MM.YYYY HH:mm", "Attempt to reconnect": "Erneut verbinden", "Streaming done": "Streaming abgeschlossen", "violet": "Violett", "Print": "Drucken", "Layer count": "Schichtanzahl", "OctoPrint Settings": "OctoPrint Einstellungen", "Are you sure?": "Bist Du sicher?", "blue": "Blau", "Printer": "Drucker", "Delete Profile": "Profil entfernen", "Tool": "Werkzeug", "Settings": "Einstellungen", "Circular": "Rund", "Path to FFMPEG": "Pfad zu FFMPEG", "Upload to SD": "Upload (SD)", "The command \"%(command)s\" could not be executed.": "Das Kommando \"%(command)s\" konnte nicht ausgef\u00fchrt werden.", "Select a slicing profile...": "W\u00e4hle ein Slicingprofile...", "Wait for start on connect": "Bei der Verbindung auf start warten", "Sync with job progress": "Job mit Fortschritt synchronisieren", "Calculating...": "Wird ermittelt...", "Total filament used": "Gesamtmenge genutzten Filaments", "red": "Rot", "Save as default": "Als Standard speichern", "Slicing ...": "Slice ...", "Last Print Time": "Letzte Druckdauer", "Target": "Soll", "Add Profile...": "Profil hinzuf\u00fcgen...", "Streaming ...": "Streame ...", "Logout successful": "Logout erfolgreich", "Now rendering timelapse %(movie_basename)s": "Rendere Zeitrafferaufnahme %(movie_basename)s", "Documentation": "Dokumentation", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Upload", "ascending": "aufsteigend", "Model size": "Modelgr\u00f6\u00dfe", "Temperatures": "Temperaturen", "Timed": "Nach Zeit", "Edit user \"%(user)s\"": "Editiere Nutzer \"%(user)s\"", "Identifier": "ID", "Release SD card": "SD-Karte auswerfen", "Server is offline": "Der Server ist offline", "Log communication to serial.log (might negatively impact performance)": "Logge die Kommunikation in das serial.log (kann die Performance negativ beeinflussen)", "Sort by upload date": "Nach Uploaddatum sortieren", "Change Password": "Passwort \u00e4ndern", "Logs": "Logs", "Hotend": "Hotend", "Show retracts": "Retracts zeigen", "Keep Access Control Enabled": "Zugangsbeschr\u00e4nkung aktiviert lassen", "Upload locally": "Upload (lokal)", "Do nothing": "Nichts machen", "Paused": "Pausiert", "Continue": "Fortsetzen", "Edit Printer Profile \"%(name)s\"": "Druckerprofile \"%(name)s\" bearbeiten", "The command \"%(command)s\" executed successfully": "Das Kommando \"%(command)s\" wurde erfolgreich ausgef\u00fchrt", "Features": "Funktionen", "Download": "Download", "GCode Viewer": "GCode Viewer", "Also show previous layer": "Auch vorherige Schicht anzeigen", "Enable OctoPrint watermark in timelapse movies": "OctoPrint Wasserzeichen in Zeitrafferaufnahmen aktivieren", "Repetier": "Repetier", "Login successful": "Login erfolgreich", "Finished Timelapses": "Abgeschlossene Zeitraffer", "Pause": "Pause", "GCode Filename": "GCode Dateiname", "Access Control": "Zugangsbeschr\u00e4nkung", "Start printing": "Drucken", "Swallow the first \"ok\" after a resend response": "Erstes \"ok\" nach Resend ignorieren", "Analyzing...": "Analysiere...", "just now": "gerade eben", "Operational": "Bereit", "Send a checksum with every command": "Eine Pr\u00fcfsumme mit jedem Kommando senden", "Autodetection timeout": "Autodetectiontimeout", "Connecting": "Verbinde", "Free": "Frei", "Closed": "Geschlossen", "Refresh SD files": "SD-Dateien aktualisieren", "Flip webcam vertically": "Webcam vertikal flippen", "Starts the print job": "Startet den Druckjob", "Model": "Modell", "Filament": "Filament", "Could not slice %(stl)s to %(gcode)s: %(reason)s": "Konnte %(stl)s nicht nach %(gcode)s slicen: %(reason)s", "Baudrate": "Baudrate", "Snapshot URL": "Snapshot-URL", "Detecting baudrate": "Detektiere Baudrate", "Date": "Datum", "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds": "%(local)s nach %(remote)s gestreamt, dauerte %(time).2f Sekunden", "Show moves": "Bewegungen zeigen", "Select a printer profile...": "W\u00e4hle ein Druckerprofil...", "Detecting serial port": "Detektiere Serialport", "New Password": "Neues Passwort", "Title": "Titel", "Logout": "Logout", "Offset": "Offset", "Analyzed": "Analysiert", "Auto-connect on server startup": "Automatisch bei Serverstart verbinden", "E": "E", "Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s": "Rendering der Zeitrafferaufnahme %(movie_basename)s fehlgeschlagen mit Returncode %(returncode)s", "Restart": "Restart", "Search...": "Suchen...", "Slicing failed": "Slicing fehlgeschlagen", "Actual": "Ist", "Active": "Aktiv", "SD status timeout": "SD-Status-Timeout", "Creation date": "Erstellungsdatum", "Hint: You can also drag and drop files on this page to upload them.": "Hinweis: Du kannst auch Dateien auf diese Seite ziehen um sie hochzuladen.", "Restarts the print job from the beginning": "Started den Druckjob von vorne", "Interval": "Intervall", "N/A": "(nicht vorhanden)", "Bed": "Bett", "Auto-connect to printer on server start": "Automatisch bei Serverstart verbinden", "orange": "Orange", "Connection": "Verbindung", "Error": "Fehler", "On Z Change": "Bei Ebenenwechsel", "Timelapse post roll (in rendered seconds)": "Zeitraffernachlauf (in gerenderten Sekunden)", "Z": "Z", "Edit Profile": "Profil bearbeiten", "Are you sure you want to proceed?": "Bist Du sicher, dass du fortfahren willst?", "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!": "Wenn Du die Zugangsbeschr\u00e4nkung deaktivierst und Deine OctoPrint Installation vom Internet aus erreichbar ist, kann jeder auf Deinen Drucker zugreifen - auch die b\u00f6sen Jungs!", "Load": "Laden", "Set": "Setzen", "The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below.": "Der Server scheint offline zu sein, zumindest kann ich mich nicht mit ihm verbinden. Ich konnte mich nicht automatisch neu verbinden, aber Du kannst mittels des folgenden Buttons einen manuellen Reconnect ansto\u00dfen.", "Zoom in on model": "Auf Model zoomen", "Pauses the print job": "Pausiert den Druckjob", "After slicing...": "Nach dem Slicing...", "Saving ...": "Speichere ...", "RegExp": "RegExp", "Watched Folder": "Beobachtetes Verzeichnis", "General": "Allgemein", "Temperature timeout": "Temperaturtimeout", "Set as default profile": "Als Standardprofil festlegen", "Fans on": "L\u00fcfter an", "Abort": "Abbrechen", "Enable SD support": "SD-Unterst\u00fctzung aktivieren", "Connect": "Verbinden", "Cancel": "Abbruch", "visited": "besucht", "Warning": "Warnung", "Loading...": "Lade...", "Current API Key": "Aktueller API-Key", "Size": "Gr\u00f6\u00dfe", "Communication timeout": "Kommunikationstimeout", "Modification date": "\u00c4nderungsdatum", "Slice": "Slicen", "Change password": "Passwort \u00e4ndern", "Layer number": "Schichtnummer", "Cancels the print job": "Bricht den Druckjob ab", "This will restart the print job from the beginning.": "Der Druckjob wird zur\u00fcckgesetzt und von vorne begonnen.", "Sort by": "Sortieren", "Login failed": "Login fehlgeschlagen", "Confirm": "Best\u00e4tigen", "Repeat Password": "Passwort wiederholen", "Terminal": "Terminal", "Autoscroll": "Autoscroll", "Print time for layer": "Druckdauer f\u00fcr Schicht", "Disable Access Control": "Zugangsbeschr\u00e4nkung deaktivieren", "Configure Access Control": "Zugangsbeschr\u00e4nkung konfigurieren", "Timelapse Configuration": "Zeitrafferkonfiguration", "Retract": "Retract", "Printer Profile": "Druckerprofil", "Offline": "Offline", "API Key": "API Key", "Homepage": "Homepage", "Estimated Print Time": "Gesch\u00e4tzte Druckdauer", "Folders": "Verzeichnisse", "Select a slicer...": "Slicer w\u00e4hlen...", "Printer Profiles": "Druckerprofile", "Slicing %(filename)s": "Slice %(filename)s", "Extruder Offsets": "Extruderoffsets", "min": "Min", "Only show STL files": "Nur STL Dateien anzeigen", "Slicing ... (%(percentage)d%%)": "Slice ... (%(percentage)d%%)", "Connection timeout": "Verbindungstimeout", "Save config": "Konfiguration speichern", "Center viewport on model": "Ausschnitt auf Modell zentrieren", "User unknown or wrong password": "Nutzer unbekannt oder falsches Passwort", "Volume": "Volumen", "default": "Standard", "Heated Bed": "Heizbett", "Appearance": "Aussehen", "Enable": "Aktivieren", "Uploading ...": "Uploade ...", "Logs Folder": "Logverzeichnis", "

\n Please read the following, it is very important for your printer's health!\n

\n

\n OctoPrint by default now ships with Access Control enabled, meaning you won't be able to do anything with the\n printer unless you login first as a configured user. This is to prevent strangers - possibly with\n malicious intent - to gain access to your printer via the internet or another untrustworthy network\n and using it in such a way that it is damaged or worse (i.e. causes a fire).\n

\n

\n It looks like you haven't configured access control yet. Please set up an username and password for the\n initial administrator account who will have full access to both the printer and OctoPrint's settings, then click\n on \"Keep Access Control Enabled\":\n

": "

\n Bitte lies die folgenden Zeilen aufmerksam durch, es ist sehr wichtig f\u00fcr die Gesundheit Deines Druckers!\n

\n

\n OctoPrint wird nun standardm\u00e4ssig mit aktivierter Zugangsbeschr\u00e4nkung ausgeliefert, das hei\u00dft, dass Du mit dem Drucker nichts\n anfangen kannst, wenn du nicht als einer der konfigurierten Nutzer eingeloggt bist. Das dient dem Zweck, Fremde mit\n m\u00f6glicherweise b\u00f6swilligen Absichten davon abzuhalten, auf Deinen Drucker \u00fcber das Internet oder ein anderes\n unsicheres Netzwerk zuzugreifen und ihn auf eine Art zu nutzen, die ihn besch\u00e4digt oder schlimmeres (z.B. ein Feuer verursacht).\n

\n

\n Es sieht so aus, als h\u00e4ttest Du die Zugriffsbeschr\u00e4nkung noch nicht konfiguriert. Bitte konfiguriere einen Usernamen\n und ein Passwort f\u00fcr das initiale Administratorkonto, das vollen Zugang zu sowohl dem Drucker als auch OctoPrints\n Einstellungen haben wird, und klicke dann auf \"Zugangsbeschr\u00e4nkung aktiviert lassen\".\n

", "Hide successfully printed files": "Erfolgreich gedruckte Dateien verbergen", "Username": "Username", "Select Tool...": "Werkzeug w\u00e4hlen...", "Off": "Aus", "Name": "Name", "Bugs and Requests": "Bugs und Requests", "Approx. Total Print Time": "Ungef\u00e4hre Druckdauer", "Admin": "Admin", "

\n Note: In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't\n need Access Control for other reasons, you may alternatively disable Access Control. You should only\n do this if you are absolutely certain that only people you know and trust will be able to connect to it.\n

\n

\n Do NOT underestimate the risk of an unsecured access from the internet to your printer!\n

": "

\n Beachte: Falls Deine OctoPrint Installation ausschlie\u00dflich innerhalb eines vertrauensw\u00fcrdigen Netzwerks\n erreicht werden kann und Du die Zugangsbeschr\u00e4nkung nicht f\u00fcr andere Zwecke ben\u00f6tigst, kannst Du sie alternativ auch\n deaktivieren. Du solltest das nur tun, wenn Du Dir absolut sicher bist, dass nur Leute darauf zugreifen k\u00f6nnen, die du kennst\n und denen du vertraust\n

\n

\n UNTERSCH\u00c4TZE NICHT das Risiko eines ungesicherten Zugriffs aus dem Internet auf Deinen Drucker!\n

", "Timelapse": "Zeitraffer", "QR Code": "QR Code", "Only show GCode files": "Nur GCode Dateien anzeigen", "Remove": "Entfernen", "Reload": "Neu laden", "Printing": "Drucke", "printed": "gedruckt", "Y": "Y", "Fans off": "L\u00fcfter aus", "Login": "Login", "Rectangular": "Rechteckig", "Timelapse ready": "Zeitraffer fertig", "Timelapse Mode": "Zeitraffermodus", "Timelapse Folder": "Zeitrafferverzeichnis", "Extruder": "Extruder", "Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and slicing support is enabled and configured.": "Konnte die Datei nicht hochladen. Bitte stelle sicher, dass es sich um eine GCODE-Datei mit der Extension \".gcode\" oder \".gco\" oder um eine STL-Datei mit der Extension \".stl\" handelt und in letzterem Fall auch der Slicingsupport aktiviert ist.", "Printed": "Gedruckt", "SD not initialized": "SD-Karte ist nicht initialisiert", "Update User": "Nutzer editieren", "off": "Aus", "Serial Port": "Serialport", "Flip webcam horizontally": "Webcam horizontal flippen", "Resumes the print job": "Setzt den Druckjob fort", "Transfering file to SD": "Sende Datei zu SD", "OctoPrint": "OctoPrint", "Layer height": "Schichth\u00f6he", "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds": "%(stl)s nach %(gcode)s geslicet, dauerte %(time).2f Sekunden", "Extrude": "Extrude", "green": "Gr\u00fcn", "File": "Datei", "You are now logged in as \"%(username)s\"": "Du bist jetzt eingeloggt als \"%(username)s\"", "Axis": "Achse", "Filament used by layer": "Genutztes Filament in Schicht", "Please configure which slicer and which slicing profile to use and name the GCode file to slice to below, or click \"Cancel\" if you do not wish to slice the file now.": "Bitte w\u00e4hle den zu nutzenden Slicer und das zu nutzende Slicerprofile und wie die GCode Datei hei\u00dfen soll, die erzeugt wird. Alternativ kannst du auch auf \"Abbrechen\" klicken, wenn du die Datei jetzt nicht slicen willst."}} ; \ No newline at end of file diff --git a/src/octoprint/static/js/i18n/fr.js b/src/octoprint/static/js/i18n/fr.js index 29ec91de4..b6b3cb068 100644 --- a/src/octoprint/static/js/i18n/fr.js +++ b/src/octoprint/static/js/i18n/fr.js @@ -1 +1 @@ -window.BABEL_TO_LOAD_fr = {"locale": "fr", "domain": "messages", "plural_expr": "(n > 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-08-28 13:54+0000\nLast-Translator: Gina H\u00e4u\u00dfge \nLanguage-Team: French (http://www.transifex.com/projects/p/octoprint/language/fr/)\nPlural-Forms: nplurals=2; plural=(n > 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Temps d'impression restant", "Proceed": "Continuer", "Timelapse Temp Folder": "R\u00e9pertoire temporaire des timelapses", "Title": "Titre", "Only show files stored locally": "Ne montre que les fichiers enregistr\u00e9s localement", "yellow": "jaune", "Path to Cura": "Chemin vers Cura", "Action": "Action", "Passwords do not match": "Les mots de passes ne sont pas semblables", "Sort by name": "Trier par nom", "Save connection settings": "Sauvegarder les param\u00e8tres de connection", "Rendering timelapse": "Rendu du timelapse en cours", "Cura": "Cura", "Files": "Fichiers", "Bed Size": "Taille du lit", "Always assume SD card is present": "Toujours supposer que la carte SD est pr\u00e9sente", "Load and Print": "Charger et imprimer", "Sending file to SD": "Envoi du fichier vers la carte SD en cours", "Number of Extruders": "Nombre d'extrudeurs", "black": "noir", "Last Printed": "Impression pr\u00e9c\u00e9dente", "Sourcecode": "Code source", "Estimated layer height": "Hauteur de couche estim\u00e9e", "You are now logged out": "Vous \u00eates maintenant d\u00e9connect\u00e9", "Uploaded": "Charg\u00e9", "Opening serial port": "Ouverture du port s\u00e9rie en cours", "New timelapse %(movie_basename)s is done rendering.": "Le rendu du nouveau timelapse %(movie_basename)s est termin\u00e9.", "Invert control": "Inverser le contr\u00f4le", "Webcam": "Webcam", "Remember me": "Se souvenir de moi", "Enable GCode Visualizer": "Activer le visualisateur de GCode", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below.": "Le serveur semble \u00eatre hors ligne, du moins je ne re\u00e7ois aucunes r\u00e9ponses de celui-ci. Je vais tenter de me reconnecter automatiquement dans les minutes qui suivent. Quoiqu'il en soit vous pouvez tenter de vous reconnecter manuellement en utilisant le bouton ci-dessous.", "Rendering failed": "Echec du rendu", "Upload Folder": "R\u00e9pertoire des chargements", "descending": "descendant", "X": "X", "Add user": "Ajouter utilisateur", "GCODE commands in layer": "Commandes GCODE dans la couche", "Estimated print time": "Temps d'impression estim\u00e9", "Serial Connection": "Connection s\u00e9rie", "Control": "Contr\u00f4le", "Password": "Mot de passe", "Also show next layer": "Montrer \u00e9galement la couche suivante", "Print Time": "Temps d'impression", "Sort by file size": "Trier par taille des fichiers", "Machine State": "Etat de la machine", "default": "Par d\u00e9faut", "API": "API", "Printing from SD": "Impression depuis la carte SD en cours", "Terminal filters": "Filtres du terminal", "Change password for user \"%(user)s\"": "Changer le mot de passe pour l'utilisateur \"%(user)s\"", "Enable Temperature Graph": "Activer le graphique de temp\u00e9rature", "Delete user": "Supprimer utilisateur", "Confirm Password": "Confirmer le mot de passe", "Disconnect": "D\u00e9connecter", "Slicing done": "Tranchage termin\u00e9", "Initialize SD card": "Initialiser la carte SD", "System": "Syst\u00eame", "Send": "Envoyer", "State": "Etat", "Version": "Version", "YYYY-MM-DD HH:mm": "DD-MM-YYYY HH:mm", "Attempt to reconnect": "Tentative de reconnection", "Streaming done": "Diffusion en direct termin\u00e9", "violet": "violet", "Print": "Imprimer", "Layer count": "Nombre de couches", "OctoPrint Settings": "Param\u00e8tres d'OctoPrint", "Are you sure?": "Etes-vous s\u00fbre?", "blue": "bleu", "Printer": "Imprimante", "Tool": "Outil", "Settings": "Param\u00e8tres", "Path to FFMPEG": "Chemin vers FFMPEG", "Upload to SD": "Chargement vers la carte SD", "The command \"%(command)s\" could not be executed.": "La commande \"%(command)s\" n'a pas pu \u00eatre ex\u00e9cut\u00e9e", "Printed": "Imprim\u00e9", "Layer number": "Couche num\u00e9ro", "Sync with job progress": "Synchroniser avec le progr\u00e8s du job", "Circular": "Circulaire", "Total filament used": "Quantit\u00e9 de filament utilis\u00e9", "red": "rouge", "Save as default": "Sauver en tant que d\u00e9faut", "Slicing ...": "Tranchage en cours...", "Last Print Time": "Temps d'impression pr\u00e9c\u00e9dent", "Target": "Cible", "Streaming ...": "Diffusion en direct en cours...", "Logout successful": "Fermeture de session r\u00e9ussie", "Now rendering timelapse %(movie_basename)s": "Le rendu du timelapse %(movie_basename)s est en cours", "Documentation": "Documentation", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Chargement", "ascending": "ascendant", "Model size": "Taille du mod\u00e8le", "Temperatures": "Temp\u00e9ratures", "visited": "visit\u00e9", "Timed": "Temps", "Edit user \"%(user)s\"": "Editer l'utilisateur \"%(user)s\"", "Snapshot URL": "URL de la photo instantan\u00e9e", "Release SD card": "Lib\u00e9rer la carte SD", "Server is offline": "Le serveur est hors ligne", "Log communication to serial.log (might negatively impact performance)": "Communication vers le log serial.log (peut impacter n\u00e9gativement la performance)", "Sort by upload date": "Trier par date de chargement", "Change Password": "Changer le mot de passe", "Logs": "Logs", "Hotend": "Buse", "Show retracts": "Montrer les r\u00e9traction", "Keep Access Control Enabled": "Garder le contr\u00f4le d'acc\u00e8s activ\u00e9", "Upload locally": "Chargement local", "Select Tool...": "S\u00e9lectionner outil...", "Paused": "En pause", "Continue": "Continuer", "Radius": "Radius", "The command \"%(command)s\" executed successfully": "La commande \"%(command)s\" a \u00e9t\u00e9 ex\u00e9cut\u00e9e avec succ\u00e8s", "Features": "Fonctionnalit\u00e9s", "Download": "T\u00e9l\u00e9charger", "GCode Viewer": "Visualisateur de GCode", "Also show previous layer": "Montrer \u00e9galement la couche pr\u00e9c\u00e9dente", "Enable OctoPrint watermark in timelapse movies": "Activer le watermark Octoprint sur les films timelapses", "Repetier": "Repetier", "Login successful": "Ouverture de session r\u00e9ussie", "Finished Timelapses": "Timelapses termin\u00e9s", "Rendering of timelapse %(movie_basename)s failedwith return code %(returncode)s": "Le rendu du timelapse %(movie_basename)s a \u00e9chou\u00e9 avec le code %(returncode)s", "Pause": "Pause", "Temperature": "Temp\u00e9rature", "Enable slicing via Cura": "Activer le tranchage via Cura", "Access Control": "Contr\u00f4le d'acc\u00e8s", "Analyzing...": "Analyse en cours...", "just now": "a l'instant", "Operational": "Op\u00e9rationnel", "Send a checksum with every command": "Envoyer un checksum avec chaque commande", "Autodetection timeout": "Timeout d'auto-d\u00e9tection", "Connecting": "Connection en cours", "Free": "Lib\u00e9rer", "Closed": "Ferm\u00e9", "Refresh SD files": "Rafraichir les fichiers de la carte SD", "Flip webcam vertically": "Rotation de la webcam verticalement", "Path to Cura config": "Chemin vers la configuration de Cura", "Filament": "Filament", "Could not slice %(stl)s to %(gcode)s: %(reason)s": "Le tranchage de %(stl)s vers %(gcode)s a \u00e9chou\u00e9: %(reason)s", "Baudrate": "Baudrate", "Detecting baudrate": "D\u00e9tection du baudrate en cours", "Date": "Date", "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds": "Diffusion de %(local)s vers %(remote)s sur la carte SD, temps: %(time).2f secondes", "Show moves": "Montrer les mouvements", "Motors off": "Eteindre les moteurs", "Detecting serial port": "D\u00e9tection du port s\u00e9rie en cours", "New Password": "Nouveau mot de passe", "Logout": "Se d\u00e9connecter", "Offset": "Offset", "Analyzed": "Analyse termin\u00e9e", "Auto-connect on server startup": "Connection automatique au red\u00e9marrage du serveur", "Printer Parameters": "Param\u00e8tres de l'imprimante", "E": "E", "Restart": "Red\u00e9marrer", "Search...": "Rechercher...", "Slicing failed": "Le tranchage a \u00e9chou\u00e9", "Actual": "Actuel", "Active": "Actif", "Creation date": "Date de cr\u00e9ation", "Hint: You can also drag and drop files on this page to upload them.": "Astuce: Vous pouvez \u00e9galement vers un glisser/d\u00e9poser des fichiers sur la page pour les charger.", "Interval": "Intervalle", "N/A": "N/A", "Bed": "Lit", "Auto-connect to printer on server start": "Connection automatique a l'imprimante au red\u00e9marrage du serveur", "orange": "orange", "Connection": "", "Error": "Erreur", "On Z Change": "Sur changement de Z", "Timelapse post roll (in rendered seconds)": "Post roll du timelapse (en secondes rendues)", "Z": "Z", "Are you sure you want to proceed?": "Etes-vous s\u00fbre de vouloir continuer?", "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!": "Si vous avez d\u00e9sactiv\u00e9 le contr\u00f4le d'acc\u00e8s et que votre installation OctoPrint est accessible depuis internet, votre imprimante sera accessible a tout le monde - y compris les m\u00e9chants!", "Load": "Charger", "Set": "Fixer", "The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below.": "Le serveur semble \u00eatre hors ligne, du moins je ne re\u00e7ois aucunes r\u00e9ponses de celui-ci. Je n'ai pas pu me reconnecter automatiquement, mais vous pouvez tenter de vous reconnecter manuellement en utilisant le bouton ci-dessous.", "Zoom in on model": "Zoomer sur le mod\u00e8le", "mm": "mm", "Saving ...": "Sauvegarde en cours ... ", "RegExp": "RegExp", "Watched Folder": "R\u00e9pertoire observ\u00e9", "General": "G\u00e9n\u00e9ral", "Temperature timeout": "Timeout de la temp\u00e9rature", "Color": "Couleur", "Fans on": "Allumer la ventilation", "Swallow the first \"ok\" after a resend response": "Avaler le premier \"ok\" apr\u00e8s le r\u00e9-envoi d'une r\u00e9ponse", "Enable SD support": "Activer le support de carte SD", "Connect": "Connecter", "Cancel": "Annuler", "sec": "sec", "Warning": "Avertissement", "Loading...": "Chargement en cours...", "Current API Key": "Cl\u00e9 API courante", "Size": "Taille", "Communication timeout": "Timeout de communication", "Modification date": "Date de modification", "Change password": "Changer le mot de passe", "This will restart the print job from the beginning.": "Ceci va red\u00e9marrer le job d'impression depuis le d\u00e9but", "Stream URL": "URL de diffusion en direct", "Sort by": "Trier par", "Login failed": "Ouverture de session \u00e9chou\u00e9e", "Abort": "Annuler", "Confirm": "Confirmer", "Repeat Password": "R\u00e9p\u00e9ter le mot de passe", "Terminal": "Terminal", "Autoscroll": "Scroll automatique", "Print time for layer": "Temps d'impression pour la couche", "Disable Access Control": "D\u00e9sactiver le contr\u00f4le d'acc\u00e8s", "Configure Access Control": "Configuration du contr\u00f4le d'acc\u00e8s", "Timelapse Configuration": "Configuration du timelapse", "Retract": "Retracter", "Timelapse bitrate": "Bitrate du timelapse", "Offline": "Hors ligne", "API Key": "cl\u00e9 API", "Homepage": "Page d'accueil", "Estimated Print Time": "Temps d'impression estim\u00e9", "Folders": "R\u00e9pertoires", "Bugs and Requests": "Bugs et demandes", "Save": "Sauver", "Default extrusion length": "Longueur d'extrusion par d\u00e9faut", "min": "min", "Support TargetExtr%%n/TargetBed target temperature format": "Support TargetExtr%%n/TargetBed format de temp\u00e9rature de la cible", "Connection timeout": "Timeout de connection", "Save config": "Sauver la configuration", "Center viewport on model": "Centrer le point du vue sur le mod\u00e8le", "User unknown or wrong password": "Utilisateur inconnu ou mauvais mot de passe", "Allow Cross Origin Resource Sharing (CORS)": "Permettre Cross Origin Resource Sharing (CORS)", "Appearance": "Apparence", "Enable": "Activer", "Uploading ...": "Chargement en cours ...", "Logs Folder": "R\u00e9pertoire des logs", "

\n Please read the following, it is very important for your printer's health!\n

\n

\n OctoPrint by default now ships with Access Control enabled, meaning you won't be able to do anything with the\n printer unless you login first as a configured user. This is to prevent strangers - possibly with\n malicious intent - to gain access to your printer via the internet or another untrustworthy network\n and using it in such a way that it is damaged or worse (i.e. causes a fire).\n

\n

\n It looks like you haven't configured access control yet. Please set up an username and password for the\n initial administrator account who will have full access to both the printer and OctoPrint's settings, then click\n on \"Keep Access Control Enabled\":\n

": "

\nLisez ceci, c'est tr\u00e8s important pour la sant\u00e9 de votre imprimante!\n

\n

\nPar d\u00e9faut, OctoPrint est livr\u00e9 avec le contr\u00f4le d'acc\u00e8s activ\u00e9, ce qui signifie que vous ne pourrez rien faire avec\nl'imprimante sauf si vous ouvrez uen session en tant qu'utilisateur configur\u00e9. Ceci est fait pourempecher des personnes ext\u00e9rieures potentiellement avec de mauvaises intentions\n - d'avoir acc\u00e8s a votre imprimante via internet ou tout autre r\u00e9seau non s\u00e9curis\u00e9\net de pouvoir de cette mani\u00e8re utiliser l'imprimante dans le but de l'abimer ou pire (causer un incendie).\n

\n

\nIl semblerait qu vous n'avez pas encore configur\u00e9 le contr\u00f4le d'acc\u00e8s. Veuillez cr\u00e9er un utilisateur et mot de passe pour le\ncompte administrateur initial qui aura un acc\u00e8s comple \u00e0 l'imprimante ainsi qu'aux param\u00e8tres d'OctoPrint, puis cliquez\nsur \"Garder le contr\u00f4le d'acc\u00e8s activ\u00e9\":\n

", "Hide successfully printed files": "Cacher les fichiers imprim\u00e9s avec succ\u00e8s", "Username": "Nom d'utilisateur", "Off": "Eteint", "Name": "Nom", "Extruder Offsets": "Offsets de l'extrudeur", "Approx. Total Print Time": "Temps d'impression total approximatif", "Admin": "Administrateur", "

\n Note: In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't\n need Access Control for other reasons, you may alternatively disable Access Control. You should only\n do this if you are absolutely certain that only people you know and trust will be able to connect to it.\n

\n

\n Do NOT underestimate the risk of an unsecured access from the internet to your printer!\n

": "

\nNote: Dans le cas ou votre installation d'OctoPrint est uniquement accessible d'un r\u00e9seau de confiance et que vous\nn'avez pas besoin du contr\u00f4le d'acc\u00e8s pour d'autres raisons; vous pouvez alternativement d\u00e9sactiver le contr\u00f4le d'acc\u00e8s. Vous ne devriez seulement\nfaire ceci si vous \u00eates certain que seuls des personnes que vous connaissez et en qui vous avez confiance auront la possibilit\u00e9 de se connecter.\n

\n

\nNe sous estim\u00e9 pas le risque d'un acc\u00e8s non s\u00e9curis\u00e9 depuis internet vers votre imprimante!\n

", "Timelapse": "Timelapse", "Remove": "Supprimer", "Reload": "Re-charger", "Printing": "Impression en cours", "Only show files stored on SD": "Ne montrer que les fichier enregistr\u00e9s sur la carte SD", "Y": "Y", "Fans off": "Eteindre la ventilation", "Login": "Ouverture de session", "Timelapse ready": "Le timelapse est pr\u00eat", "Timelapse Mode": "Mode du timelapse", "Timelapse Folder": "R\u00e9pertoire des timelapses", "Extruder": "Extrudeur", "Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and slicing support is enabled and configured.": "Le chargement du fichier a \u00e9chou\u00e9. Verifiez qu'il s'agit bien d'un fichier GCODE avec l'extension \".gcode\" ou \".gco\" ou d'un fichier STL avec l'extension \".stl\" et que le tranchage est configur\u00e9 et activ\u00e9.", "SD status timeout": "Timeout du statut de la carte SD", "SD not initialized": "Carte SD non initialis\u00e9e", "Update User": "Mettre \u00e0 jour l'utilisateur", "off": "eteint", "Serial Port": "Port s\u00e9rie", "Flip webcam horizontally": "Rotation de la webcam horizontalement", "Wait for start on connect": "Attendre start \u00e0 la connection", "Transfering file to SD": "Transfert du fichier vers la carte SD en cours", "OctoPrint": "OctoPrint", "Layer height": "Hauteur de couche", "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds": "Tranchage de %(stl)s vers %(gcode)s, en %(time).2f secondes", "Extrude": "Extruder", "green": "vert", "File": "Fichier", "You are now logged in as \"%(username)s\"": "Vous \u00eates maintenant connecter en tant que \"%(username)s\"", "Axis": "Axe", "Filament used by layer": "Filament utilis\u00e9 par couche"}} ; \ No newline at end of file +window.BABEL_TO_LOAD_fr = {"locale": "fr", "domain": "messages", "plural_expr": "(n > 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:04+0000\nLast-Translator: Gina H\u00e4u\u00dfge \nLanguage-Team: French (http://www.transifex.com/projects/p/octoprint/language/fr/)\nPlural-Forms: nplurals=2; plural=(n > 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Temps d'impression restant", "sec": "sec", "Proceed": "Continuer", "Timelapse Temp Folder": "R\u00e9pertoire temporaire des timelapses", "Support TargetExtr%%n/TargetBed target temperature format": "Support TargetExtr%%n/TargetBed format de temp\u00e9rature de la cible", "Upload Folder": "R\u00e9pertoire des chargements", "Only show files stored locally": "Ne montre que les fichiers enregistr\u00e9s localement", "Add Printer Profile": "", "yellow": "jaune", "Save": "Sauver", "Action": "Action", "Passwords do not match": "Les mots de passes ne sont pas semblables", "Sort by name": "Trier par nom", "Save connection settings": "Sauvegarder les param\u00e8tres de connection", "Rendering timelapse": "Rendu du timelapse en cours", "Color": "Couleur", "Temperature": "Temp\u00e9rature", "Files": "Fichiers", "Resume": "", "Always assume SD card is present": "Toujours supposer que la carte SD est pr\u00e9sente", "Load and Print": "Charger et imprimer", "Sending file to SD": "Envoi du fichier vers la carte SD en cours", "Number of Extruders": "Nombre d'extrudeurs", "black": "noir", "Last Printed": "Impression pr\u00e9c\u00e9dente", "Sourcecode": "Code source", "Estimated layer height": "Hauteur de couche estim\u00e9e", "You are now logged out": "Vous \u00eates maintenant d\u00e9connect\u00e9", "Uploaded": "Charg\u00e9", "Form Factor": "", "Opening serial port": "Ouverture du port s\u00e9rie en cours", "New timelapse %(movie_basename)s is done rendering.": "Le rendu du nouveau timelapse %(movie_basename)s est termin\u00e9.", "Invert control": "Inverser le contr\u00f4le", "Webcam": "Webcam", "Select for printing": "", "Allow Cross Origin Resource Sharing (CORS)": "Permettre Cross Origin Resource Sharing (CORS)", "Remember me": "Se souvenir de moi", "Enable GCode Visualizer": "Activer le visualisateur de GCode", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below.": "Le serveur semble \u00eatre hors ligne, du moins je ne re\u00e7ois aucunes r\u00e9ponses de celui-ci. Je vais tenter de me reconnecter automatiquement dans les minutes qui suivent. Quoiqu'il en soit vous pouvez tenter de vous reconnecter manuellement en utilisant le bouton ci-dessous.", "Rendering failed": "Echec du rendu", "Motors off": "Eteindre les moteurs", "descending": "descendant", "Only show files stored on SD": "Ne montrer que les fichier enregistr\u00e9s sur la carte SD", "X": "X", "Add user": "Ajouter utilisateur", "GCODE commands in layer": "Commandes GCODE dans la couche", "Estimated print time": "Temps d'impression estim\u00e9", "Serial Connection": "Connection s\u00e9rie", "Control": "Contr\u00f4le", "Password": "Mot de passe", "Also show next layer": "Montrer \u00e9galement la couche suivante", "Print Time": "Temps d'impression", "Slicer": "", "Nozzle Diameter": "", "Sort by file size": "Trier par taille des fichiers", "Machine State": "Etat de la machine", "Slicing Profile": "", "mm": "mm", "API": "API", "Printing from SD": "Impression depuis la carte SD en cours", "Stream URL": "URL de diffusion en direct", "Terminal filters": "Filtres du terminal", "Change password for user \"%(user)s\"": "Changer le mot de passe pour l'utilisateur \"%(user)s\"", "Enable Temperature Graph": "Activer le graphique de temp\u00e9rature", "Delete user": "Supprimer utilisateur", "Timelapse bitrate": "Bitrate du timelapse", "Confirm Password": "Confirmer le mot de passe", "Disconnect": "D\u00e9connecter", "Slicing done": "Tranchage termin\u00e9", "Initialize SD card": "Initialiser la carte SD", "System": "Syst\u00eame", "Send": "Envoyer", "State": "Etat", "Version": "Version", "YYYY-MM-DD HH:mm": "DD-MM-YYYY HH:mm", "Attempt to reconnect": "Tentative de reconnection", "Streaming done": "Diffusion en direct termin\u00e9", "violet": "violet", "Print": "Imprimer", "Layer count": "Nombre de couches", "OctoPrint Settings": "Param\u00e8tres d'OctoPrint", "Are you sure?": "Etes-vous s\u00fbre?", "blue": "bleu", "Printer": "Imprimante", "Delete Profile": "", "Tool": "Outil", "Settings": "Param\u00e8tres", "Circular": "Circulaire", "Path to FFMPEG": "Chemin vers FFMPEG", "Upload to SD": "Chargement vers la carte SD", "The command \"%(command)s\" could not be executed.": "La commande \"%(command)s\" n'a pas pu \u00eatre ex\u00e9cut\u00e9e", "Select a slicing profile...": "", "Wait for start on connect": "Attendre start \u00e0 la connection", "Sync with job progress": "Synchroniser avec le progr\u00e8s du job", "Calculating...": "", "Total filament used": "Quantit\u00e9 de filament utilis\u00e9", "red": "rouge", "Save as default": "Sauver en tant que d\u00e9faut", "Slicing ...": "Tranchage en cours...", "Last Print Time": "Temps d'impression pr\u00e9c\u00e9dent", "Target": "Cible", "Add Profile...": "", "Streaming ...": "Diffusion en direct en cours...", "Logout successful": "Fermeture de session r\u00e9ussie", "Now rendering timelapse %(movie_basename)s": "Le rendu du timelapse %(movie_basename)s est en cours", "Documentation": "Documentation", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Chargement", "ascending": "ascendant", "Model size": "Taille du mod\u00e8le", "Temperatures": "Temp\u00e9ratures", "Timed": "Temps", "Edit user \"%(user)s\"": "Editer l'utilisateur \"%(user)s\"", "Identifier": "", "Release SD card": "Lib\u00e9rer la carte SD", "Server is offline": "Le serveur est hors ligne", "Log communication to serial.log (might negatively impact performance)": "Communication vers le log serial.log (peut impacter n\u00e9gativement la performance)", "Sort by upload date": "Trier par date de chargement", "Change Password": "Changer le mot de passe", "Logs": "Logs", "Hotend": "Buse", "Show retracts": "Montrer les r\u00e9traction", "Keep Access Control Enabled": "Garder le contr\u00f4le d'acc\u00e8s activ\u00e9", "Upload locally": "Chargement local", "Do nothing": "", "Paused": "En pause", "Continue": "Continuer", "Edit Printer Profile \"%(name)s\"": "", "The command \"%(command)s\" executed successfully": "La commande \"%(command)s\" a \u00e9t\u00e9 ex\u00e9cut\u00e9e avec succ\u00e8s", "Features": "Fonctionnalit\u00e9s", "Download": "T\u00e9l\u00e9charger", "GCode Viewer": "Visualisateur de GCode", "Also show previous layer": "Montrer \u00e9galement la couche pr\u00e9c\u00e9dente", "Enable OctoPrint watermark in timelapse movies": "Activer le watermark Octoprint sur les films timelapses", "Repetier": "Repetier", "Login successful": "Ouverture de session r\u00e9ussie", "Finished Timelapses": "Timelapses termin\u00e9s", "Pause": "Pause", "GCode Filename": "", "Access Control": "Contr\u00f4le d'acc\u00e8s", "Start printing": "", "Swallow the first \"ok\" after a resend response": "Avaler le premier \"ok\" apr\u00e8s le r\u00e9-envoi d'une r\u00e9ponse", "Analyzing...": "Analyse en cours...", "just now": "a l'instant", "Operational": "Op\u00e9rationnel", "Send a checksum with every command": "Envoyer un checksum avec chaque commande", "Autodetection timeout": "Timeout d'auto-d\u00e9tection", "Connecting": "Connection en cours", "Free": "Lib\u00e9rer", "Closed": "Ferm\u00e9", "Refresh SD files": "Rafraichir les fichiers de la carte SD", "Flip webcam vertically": "Rotation de la webcam verticalement", "Starts the print job": "", "Model": "", "Filament": "Filament", "Could not slice %(stl)s to %(gcode)s: %(reason)s": "Le tranchage de %(stl)s vers %(gcode)s a \u00e9chou\u00e9: %(reason)s", "Baudrate": "Baudrate", "Snapshot URL": "URL de la photo instantan\u00e9e", "Detecting baudrate": "D\u00e9tection du baudrate en cours", "Date": "Date", "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds": "Diffusion de %(local)s vers %(remote)s sur la carte SD, temps: %(time).2f secondes", "Show moves": "Montrer les mouvements", "Select a printer profile...": "", "Detecting serial port": "D\u00e9tection du port s\u00e9rie en cours", "New Password": "Nouveau mot de passe", "Title": "Titre", "Logout": "Se d\u00e9connecter", "Offset": "Offset", "Analyzed": "Analyse termin\u00e9e", "Auto-connect on server startup": "Connection automatique au red\u00e9marrage du serveur", "E": "E", "Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s": "", "Restart": "Red\u00e9marrer", "Search...": "Rechercher...", "Slicing failed": "Le tranchage a \u00e9chou\u00e9", "Actual": "Actuel", "Active": "Actif", "SD status timeout": "Timeout du statut de la carte SD", "Creation date": "Date de cr\u00e9ation", "Hint: You can also drag and drop files on this page to upload them.": "Astuce: Vous pouvez \u00e9galement vers un glisser/d\u00e9poser des fichiers sur la page pour les charger.", "Restarts the print job from the beginning": "", "Interval": "Intervalle", "N/A": "N/A", "Bed": "Lit", "Auto-connect to printer on server start": "Connection automatique a l'imprimante au red\u00e9marrage du serveur", "orange": "orange", "Connection": "Connection", "Error": "Erreur", "On Z Change": "Sur changement de Z", "Timelapse post roll (in rendered seconds)": "Post roll du timelapse (en secondes rendues)", "Z": "Z", "Edit Profile": "", "Are you sure you want to proceed?": "Etes-vous s\u00fbre de vouloir continuer?", "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!": "Si vous avez d\u00e9sactiv\u00e9 le contr\u00f4le d'acc\u00e8s et que votre installation OctoPrint est accessible depuis internet, votre imprimante sera accessible a tout le monde - y compris les m\u00e9chants!", "Load": "Charger", "Set": "Fixer", "The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below.": "Le serveur semble \u00eatre hors ligne, du moins je ne re\u00e7ois aucunes r\u00e9ponses de celui-ci. Je n'ai pas pu me reconnecter automatiquement, mais vous pouvez tenter de vous reconnecter manuellement en utilisant le bouton ci-dessous.", "Zoom in on model": "Zoomer sur le mod\u00e8le", "Pauses the print job": "", "After slicing...": "", "Saving ...": "Sauvegarde en cours ... ", "RegExp": "RegExp", "Watched Folder": "R\u00e9pertoire observ\u00e9", "General": "G\u00e9n\u00e9ral", "Temperature timeout": "Timeout de la temp\u00e9rature", "Set as default profile": "", "Fans on": "Allumer la ventilation", "Abort": "Annuler", "Enable SD support": "Activer le support de carte SD", "Connect": "Connecter", "Cancel": "Annuler", "visited": "visit\u00e9", "Warning": "Avertissement", "Loading...": "Chargement en cours...", "Current API Key": "Cl\u00e9 API courante", "Size": "Taille", "Communication timeout": "Timeout de communication", "Modification date": "Date de modification", "Slice": "", "Change password": "Changer le mot de passe", "Layer number": "Couche num\u00e9ro", "Cancels the print job": "", "This will restart the print job from the beginning.": "Ceci va red\u00e9marrer le job d'impression depuis le d\u00e9but", "Sort by": "Trier par", "Login failed": "Ouverture de session \u00e9chou\u00e9e", "Confirm": "Confirmer", "Repeat Password": "R\u00e9p\u00e9ter le mot de passe", "Terminal": "Terminal", "Autoscroll": "Scroll automatique", "Print time for layer": "Temps d'impression pour la couche", "Disable Access Control": "D\u00e9sactiver le contr\u00f4le d'acc\u00e8s", "Configure Access Control": "Configuration du contr\u00f4le d'acc\u00e8s", "Timelapse Configuration": "Configuration du timelapse", "Retract": "Retracter", "Printer Profile": "", "Offline": "Hors ligne", "API Key": "cl\u00e9 API", "Homepage": "Page d'accueil", "Estimated Print Time": "Temps d'impression estim\u00e9", "Folders": "R\u00e9pertoires", "Select a slicer...": "", "Printer Profiles": "", "Slicing %(filename)s": "", "Extruder Offsets": "Offsets de l'extrudeur", "min": "min", "Only show STL files": "", "Slicing ... (%(percentage)d%%)": "", "Connection timeout": "Timeout de connection", "Save config": "Sauver la configuration", "Center viewport on model": "Centrer le point du vue sur le mod\u00e8le", "User unknown or wrong password": "Utilisateur inconnu ou mauvais mot de passe", "Volume": "", "default": "Par d\u00e9faut", "Heated Bed": "", "Appearance": "Apparence", "Enable": "Activer", "Uploading ...": "Chargement en cours ...", "Logs Folder": "R\u00e9pertoire des logs", "

\n Please read the following, it is very important for your printer's health!\n

\n

\n OctoPrint by default now ships with Access Control enabled, meaning you won't be able to do anything with the\n printer unless you login first as a configured user. This is to prevent strangers - possibly with\n malicious intent - to gain access to your printer via the internet or another untrustworthy network\n and using it in such a way that it is damaged or worse (i.e. causes a fire).\n

\n

\n It looks like you haven't configured access control yet. Please set up an username and password for the\n initial administrator account who will have full access to both the printer and OctoPrint's settings, then click\n on \"Keep Access Control Enabled\":\n

": "

\nLisez ceci, c'est tr\u00e8s important pour la sant\u00e9 de votre imprimante!\n

\n

\nPar d\u00e9faut, OctoPrint est livr\u00e9 avec le contr\u00f4le d'acc\u00e8s activ\u00e9, ce qui signifie que vous ne pourrez rien faire avec\nl'imprimante sauf si vous ouvrez uen session en tant qu'utilisateur configur\u00e9. Ceci est fait pourempecher des personnes ext\u00e9rieures potentiellement avec de mauvaises intentions\n - d'avoir acc\u00e8s a votre imprimante via internet ou tout autre r\u00e9seau non s\u00e9curis\u00e9\net de pouvoir de cette mani\u00e8re utiliser l'imprimante dans le but de l'abimer ou pire (causer un incendie).\n

\n

\nIl semblerait qu vous n'avez pas encore configur\u00e9 le contr\u00f4le d'acc\u00e8s. Veuillez cr\u00e9er un utilisateur et mot de passe pour le\ncompte administrateur initial qui aura un acc\u00e8s comple \u00e0 l'imprimante ainsi qu'aux param\u00e8tres d'OctoPrint, puis cliquez\nsur \"Garder le contr\u00f4le d'acc\u00e8s activ\u00e9\":\n

", "Hide successfully printed files": "Cacher les fichiers imprim\u00e9s avec succ\u00e8s", "Username": "Nom d'utilisateur", "Select Tool...": "S\u00e9lectionner outil...", "Off": "Eteint", "Name": "Nom", "Bugs and Requests": "Bugs et demandes", "Approx. Total Print Time": "Temps d'impression total approximatif", "Admin": "Administrateur", "

\n Note: In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't\n need Access Control for other reasons, you may alternatively disable Access Control. You should only\n do this if you are absolutely certain that only people you know and trust will be able to connect to it.\n

\n

\n Do NOT underestimate the risk of an unsecured access from the internet to your printer!\n

": "

\nNote: Dans le cas ou votre installation d'OctoPrint est uniquement accessible d'un r\u00e9seau de confiance et que vous\nn'avez pas besoin du contr\u00f4le d'acc\u00e8s pour d'autres raisons; vous pouvez alternativement d\u00e9sactiver le contr\u00f4le d'acc\u00e8s. Vous ne devriez seulement\nfaire ceci si vous \u00eates certain que seuls des personnes que vous connaissez et en qui vous avez confiance auront la possibilit\u00e9 de se connecter.\n

\n

\nNe sous estim\u00e9 pas le risque d'un acc\u00e8s non s\u00e9curis\u00e9 depuis internet vers votre imprimante!\n

", "Timelapse": "Timelapse", "QR Code": "", "Only show GCode files": "", "Remove": "Supprimer", "Reload": "Re-charger", "Printing": "Impression en cours", "printed": "", "Y": "Y", "Fans off": "Eteindre la ventilation", "Login": "Ouverture de session", "Rectangular": "", "Timelapse ready": "Le timelapse est pr\u00eat", "Timelapse Mode": "Mode du timelapse", "Timelapse Folder": "R\u00e9pertoire des timelapses", "Extruder": "Extrudeur", "Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and slicing support is enabled and configured.": "Le chargement du fichier a \u00e9chou\u00e9. Verifiez qu'il s'agit bien d'un fichier GCODE avec l'extension \".gcode\" ou \".gco\" ou d'un fichier STL avec l'extension \".stl\" et que le tranchage est configur\u00e9 et activ\u00e9.", "Printed": "Imprim\u00e9", "SD not initialized": "Carte SD non initialis\u00e9e", "Update User": "Mettre \u00e0 jour l'utilisateur", "off": "eteint", "Serial Port": "Port s\u00e9rie", "Flip webcam horizontally": "Rotation de la webcam horizontalement", "Resumes the print job": "", "Transfering file to SD": "Transfert du fichier vers la carte SD en cours", "OctoPrint": "OctoPrint", "Layer height": "Hauteur de couche", "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds": "Tranchage de %(stl)s vers %(gcode)s, en %(time).2f secondes", "Extrude": "Extruder", "green": "vert", "File": "Fichier", "You are now logged in as \"%(username)s\"": "Vous \u00eates maintenant connecter en tant que \"%(username)s\"", "Axis": "Axe", "Filament used by layer": "Filament utilis\u00e9 par couche", "Please configure which slicer and which slicing profile to use and name the GCode file to slice to below, or click \"Cancel\" if you do not wish to slice the file now.": ""}} ; \ No newline at end of file diff --git a/src/octoprint/static/js/i18n/he.js b/src/octoprint/static/js/i18n/he.js index c5eadf9ce..858b250a4 100644 --- a/src/octoprint/static/js/i18n/he.js +++ b/src/octoprint/static/js/i18n/he.js @@ -1 +1 @@ -window.BABEL_TO_LOAD_he = {"locale": "he", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint 1.2.0-dev-131-g854387b\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-31 12:52+0300\nPO-Revision-Date: 2014-08-31 18:44+0200\nLast-Translator: Guy Sheffer \nLanguage-Team: he \nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05e0\u05d5\u05ea\u05e8", "Proceed": "\u05d4\u05de\u05e9\u05da", "Timelapse Temp Folder": "\u05ea\u05e7\u05d9\u05d9\u05d4 \u05d6\u05de\u05e0\u05d9\u05ea \u05dc-timelapse", "Title": "\u05db\u05d5\u05ea\u05e8\u05ea", "Only show files stored locally": "\u05d4\u05e6\u05d2 \u05e8\u05e7 \u05e7\u05d1\u05e6\u05d9\u05dd \u05d4\u05e9\u05de\u05d5\u05e8\u05d9\u05dd \u05de\u05e7\u05d5\u05de\u05d9\u05ea", "yellow": "\u05e6\u05d4\u05d5\u05d1", "Path to Cura": "\u05e0\u05ea\u05d9\u05d1 \u05dc-Cura", "Action": "\u05e4\u05e2\u05d5\u05dc\u05d4", "Passwords do not match": "\u05e1\u05d9\u05e1\u05de\u05d0\u05d5\u05ea \u05dc\u05d0 \u05ea\u05d5\u05d0\u05de\u05d5\u05ea", "Sort by name": "\u05de\u05d9\u05d9\u05df \u05dc\u05e4\u05d9 \u05e9\u05dd", "Save connection settings": "\u05e9\u05de\u05d5\u05e8 \u05d4\u05d2\u05d3\u05e8\u05d5\u05ea \u05d7\u05d9\u05d1\u05d5\u05e8", "Rendering timelapse": "\u05de\u05e8\u05e0\u05d3\u05e8 timelapse", "Cura": "Cura", "Files": "\u05e7\u05d1\u05e6\u05d9\u05dd", "Bed Size": "\u05d2\u05d5\u05d3\u05dc \u05de\u05d9\u05d8\u05d4", "Always assume SD card is present": "\u05ea\u05de\u05d9\u05d3 \u05ea\u05e0\u05d9\u05d7 \u05e9\u05db\u05e8\u05d8\u05d9\u05e1 SD \u05e0\u05de\u05e6\u05d0", "Load and Print": "\u05d8\u05e2\u05df \u05d5\u05d4\u05d3\u05e4\u05e1", "Sending file to SD": "\u05e9\u05d5\u05dc\u05d7 \u05e7\u05d5\u05d1\u05e5 \u05d0\u05dc SD", "Number of Extruders": "\u05de\u05e1\u05e4\u05e8 \u05d0\u05e7\u05e1\u05d8\u05e8\u05d5\u05d3\u05e8\u05d9\u05dd", "black": "\u05e9\u05d7\u05d5\u05e8", "Last Printed": "\u05d4\u05d5\u05d3\u05e4\u05e1 \u05dc\u05d0\u05d7\u05e8\u05d5\u05e0\u05d4", "Sourcecode": "\u05e7\u05d5\u05d3 \u05de\u05e7\u05d5\u05e8", "Estimated layer height": "\u05d2\u05d5\u05d1\u05d4 \u05e9\u05db\u05d1\u05d5\u05ea \u05de\u05e9\u05d5\u05e2\u05e8", "You are now logged out": "\u05d4\u05ea\u05e0\u05ea\u05e7\u05ea \u05de\u05d4\u05de\u05e2\u05e8\u05db\u05ea", "Uploaded": "\u05d4\u05d5\u05e2\u05dc\u05d4", "Opening serial port": "\u05e4\u05d5\u05ea\u05d7 \u05d9\u05e6\u05d9\u05e8\u05d4 \u05d8\u05d5\u05e8\u05d9\u05ea", "New timelapse %(movie_basename)s is done rendering.": "\u05e1\u05d9\u05d9\u05dd \u05dc\u05e8\u05e0\u05d3\u05e8 \u05d0\u05ea \u05d4-timelapse %(movie_basename)s", "Invert control": "\u05d4\u05e4\u05d5\u05da \u05e9\u05dc\u05d9\u05d8\u05d4", "Webcam": "\u05de\u05e6\u05dc\u05de\u05ea \u05e8\u05e9\u05ea", "Remember me": "\u05d6\u05db\u05d5\u05e8 \u05d0\u05d5\u05ea\u05d9", "Enable GCode Visualizer": "\u05d4\u05e4\u05e2\u05dc \u05d5\u05d9\u05d6\u05d5\u05d0\u05dc\u05d9\u05d6\u05e6\u05d9\u05d4 \u05e9\u05dc GCode", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below.": "\u05e0\u05e8\u05d0\u05d4 \u05e9\u05d4\u05e9\u05e8\u05ea \u05dc\u05d0 \u05de\u05d7\u05d5\u05d1\u05e8, \u05d0\u05d5 \u05dc\u05e4\u05d7\u05d5\u05ea \u05d0\u05e0\u05d9 \u05dc\u05d0 \u05de\u05e6\u05dc\u05d9\u05d7 \u05dc\u05e7\u05d1\u05dc \u05db\u05dc \u05ea\u05d2\u05d5\u05d1\u05d4 \u05de\u05de\u05e0\u05d5. \u05d0\u05e0\u05e1\u05d4 \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05de\u05d7\u05d3\u05e9 \u05d0\u05d5\u05d8\u05d5\u05de\u05d8\u05d9\u05ea \u05d1\u05e2\u05d5\u05d3 \u05de\u05e1\u05e4\u05e8 \u05d3\u05e7\u05d5\u05ea, \u05d0\u05d1\u05dc \u05e0\u05d9\u05ea\u05df \u05d2\u05dd \u05dc\u05e0\u05e1\u05d5\u05ea \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05de\u05d7\u05d3\u05e9 \u05e2\u05dd \u05d4\u05db\u05e4\u05ea\u05d5\u05e8 \u05dc\u05d4\u05dc\u05df.", "Rendering failed": "\u05e8\u05d9\u05e0\u05d3\u05d5\u05e8 \u05e0\u05db\u05e9\u05dc", "Upload Folder": "\u05ea\u05e7\u05d9\u05d9\u05ea \u05d4\u05e2\u05dc\u05d0\u05d4", "descending": "\u05e1\u05d3\u05e8 \u05d9\u05d5\u05e8\u05d3", "X": "X", "Add user": "\u05d4\u05d5\u05e1\u05e3 \u05de\u05e9\u05ea\u05de\u05e9", "GCODE commands in layer": "\u05e4\u05e7\u05d5\u05d3\u05d5\u05ea GCODE \u05d1\u05e9\u05db\u05d1\u05d4", "Estimated print time": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05de\u05e9\u05d5\u05e2\u05e8", "Serial Connection": "\u05d7\u05d9\u05d1\u05d5\u05e8 \u05d8\u05d5\u05e8\u05d9", "Control": "\u05e9\u05dc\u05d9\u05d8\u05d4", "Password": "\u05e1\u05d9\u05e1\u05de\u05d4", "Also show next layer": "\u05d0\u05e4\u05e9\u05e8 \u05d4\u05e6\u05d2\u05d4 \u05e9\u05dc \u05e9\u05db\u05d1\u05d4 \u05d4\u05d1\u05d0\u05d4", "Print Time": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4", "Sort by file size": "\u05de\u05d9\u05d9\u05df \u05dc\u05e4\u05d9 \u05d2\u05d5\u05d3\u05dc \u05e7\u05d5\u05d1\u05e5", "Machine State": "\u05de\u05e6\u05d1 \u05de\u05db\u05d5\u05e0\u05d4", "default": "\u05d1\u05e8\u05d9\u05ea \u05de\u05d7\u05d3\u05dc", "API": "API", "Printing from SD": "\u05d4\u05d3\u05e4\u05e1\u05d4 \u05de-SD", "Terminal filters": "\u05e4\u05d9\u05dc\u05d8\u05e8\u05d9 \u05de\u05e1\u05d5\u05e3", "Change password for user \"%(user)s\"": "\u05d4\u05d7\u05dc\u05e3 \u05e1\u05d9\u05e1\u05de\u05d4 \u05e2\u05d1\u05d5\u05e8 \u05de\u05e9\u05ea\u05de\u05e9 \"%(user)s\"", "Enable Temperature Graph": "\u05d4\u05e4\u05e2\u05dc \u05d2\u05e8\u05e3 \u05d8\u05de\u05e4\u05e8\u05d8\u05d5\u05e8\u05d4", "Delete user": "\u05de\u05d7\u05e7 \u05de\u05e9\u05ea\u05de\u05e9", "Confirm Password": "\u05d0\u05d9\u05e9\u05d5\u05e8 \u05e1\u05d9\u05e1\u05de\u05d4", "Disconnect": "\u05d4\u05ea\u05e0\u05ea\u05e7", "Slicing done": "\u05e4\u05e8\u05d9\u05e1\u05d4 \u05d4\u05d5\u05e9\u05dc\u05de\u05d4", "Initialize SD card": "\u05de\u05d0\u05ea\u05db\u05dc \u05db\u05e8\u05d8\u05d9\u05e1 SD", "System": "\u05de\u05e2\u05e8\u05db\u05ea", "Send": "\u05e9\u05dc\u05d7", "State": "\u05de\u05e6\u05d1", "Version": "\u05d2\u05d9\u05e8\u05e1\u05d4", "YYYY-MM-DD HH:mm": "YYYY-MM-DD HH:mm", "Attempt to reconnect": "\u05e0\u05e1\u05d9\u05d5\u05df \u05d7\u05d9\u05d1\u05d5\u05e8 \u05de\u05d7\u05d3\u05e9", "Streaming done": "\u05d4\u05e9\u05d9\u05d3\u05d5\u05e8 \u05d4\u05e1\u05ea\u05d9\u05d9\u05dd", "violet": "\u05e1\u05d2\u05d5\u05dc", "Print": "\u05d4\u05d3\u05e4\u05e1\u05d4", "Layer count": "\u05de\u05e1\u05e4\u05e8 \u05e9\u05db\u05d1\u05d5\u05ea", "OctoPrint Settings": "\u05d4\u05d2\u05d3\u05e8\u05d5\u05ea \u05d0\u05d5\u05e7\u05d8\u05d5\u05e4\u05e8\u05d9\u05e0\u05d8", "Are you sure?": "\u05d4\u05d0\u05dd \u05d0\u05ea/\u05d4 \u05d1\u05d8\u05d5\u05d7?", "blue": "\u05db\u05d7\u05d5\u05dc", "Printer": "\u05de\u05d3\u05e4\u05e1\u05ea", "Tool": "\u05db\u05dc\u05d9", "Settings": "\u05d4\u05d2\u05d3\u05e8\u05d5\u05ea", "Path to FFMPEG": "\u05e0\u05ea\u05d9\u05d1 \u05e2\u05d1\u05d5\u05e8 FFMPEG", "Upload to SD": "\u05d4\u05e2\u05dc\u05d0\u05d4 \u05dc\u05db\u05e8\u05d8\u05d9\u05e1 SD", "The command \"%(command)s\" could not be executed.": "\u05dc\u05d0 \u05e0\u05d9\u05ea\u05df \u05dc\u05d1\u05e6\u05e2 \u05d0\u05ea \u05d4\u05e4\u05e7\u05d5\u05d3\u05d4 \"%(command)s\".", "Printed": "\u05d4\u05d5\u05d3\u05e4\u05e1", "Layer number": "\u05e9\u05db\u05d1\u05d4 \u05de\u05e1\u05e4\u05e8", "Sync with job progress": "\u05e1\u05e0\u05db\u05e8\u05df \u05e2\u05dd \u05d4\u05e2\u05d1\u05d5\u05d3\u05d4", "Circular": "\u05de\u05e2\u05d2\u05dc\u05d9", "Total filament used": "\u05e1\u05da \u05d4\u05db\u05dc \u05e1\u05d9\u05d1 \u05d7\u05d5\u05de\u05e8 \u05e9\u05e0\u05d3\u05e8\u05e9", "red": "\u05d0\u05d3\u05d5\u05dd", "Save as default": "\u05e9\u05de\u05d5\u05e8 \u05db\u05d1\u05e8\u05d9\u05ea \u05de\u05d7\u05d3\u05dc", "Slicing ...": "\u05e4\u05d5\u05e8\u05e1...", "Last Print Time": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05d0\u05d7\u05e8\u05d5\u05df", "Target": "\u05de\u05d8\u05e8\u05d4", "Streaming ...": "\u05de\u05e9\u05d3\u05e8 ...", "Logout successful": "\u05db\u05e0\u05d9\u05e1\u05d4 \u05d4\u05ea\u05d1\u05e6\u05e2\u05d4 \u05d1\u05d4\u05e6\u05dc\u05d7\u05d4", "Now rendering timelapse %(movie_basename)s": "\u05db\u05e2\u05ea \u05de\u05e8\u05e0\u05d3\u05e8 timelapse %(movie_basename)s", "Documentation": "\u05ea\u05d9\u05e2\u05d5\u05d3", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "\u05d4\u05e2\u05dc\u05d0\u05d4", "ascending": "\u05e1\u05d3\u05e8 \u05e2\u05d5\u05dc\u05d4", "Model size": "\u05d2\u05d5\u05d3\u05dc \u05de\u05d5\u05d3\u05dc", "Temperatures": "\u05d8\u05de\u05e4\u05e8\u05d8\u05d5\u05e8\u05d5\u05ea", "visited": "\u05d1\u05bc\u05b4\u05e7\u05bc\u05b5\u05e8", "Timed": "\u05de\u05ea\u05d5\u05d6\u05de\u05df", "Edit user \"%(user)s\"": "\u05e2\u05e8\u05d5\u05da \u05de\u05e9\u05ea\u05de\u05e9 \"%(user)s\"", "Snapshot URL": "\u05db\u05ea\u05d5\u05d1\u05ea \u05e9\u05d9\u05d3\u05d5\u05e8 \u05ea\u05de\u05d5\u05e0\u05d4", "Release SD card": "\u05de\u05e9\u05d7\u05d6\u05e8 \u05db\u05e8\u05d8\u05d9\u05e1 SD", "Server is offline": "\u05e9\u05e8\u05ea \u05dc\u05d0 \u05de\u05d7\u05d5\u05d1\u05e8", "Log communication to serial.log (might negatively impact performance)": "\u05e9\u05de\u05d5\u05e8 \u05d9\u05d5\u05de\u05df \u05ea\u05e7\u05e9\u05d5\u05e8\u05ea \u05e2\u05dc serial.log (\u05e4\u05e2\u05d5\u05dc\u05d4 \u05d6\u05d5 \u05e2\u05dc\u05d5\u05dc\u05d4 \u05dc\u05d4\u05e9\u05e4\u05d9\u05e2 \u05d1\u05e6\u05d5\u05e8\u05d4 \u05e9\u05dc\u05d9\u05dc\u05d9\u05ea \u05e2\u05dc \u05d1\u05d9\u05e6\u05d5\u05e2\u05d9\u05dd)", "Sort by upload date": "\u05de\u05d9\u05d9\u05df \u05dc\u05e4\u05d9 \u05d6\u05de\u05df \u05d4\u05e2\u05dc\u05d0\u05d4", "Change Password": "\u05d4\u05d7\u05dc\u05e3 \u05e1\u05d9\u05e1\u05de\u05d4", "Logs": "\u05dc\u05d5\u05d2\u05d9\u05dd", "Hotend": "\u05e7\u05e6\u05d4 \u05d7\u05dd", "Show retracts": "\u05d4\u05e6\u05d2 \u05e0\u05e1\u05d9\u05d2\u05d5\u05ea", "Keep Access Control Enabled": "\u05e9\u05de\u05d5\u05e8 \u05e2\u05dc \u05dc\u05d5\u05d7 \u05d1\u05e7\u05e8\u05d4 \u05de\u05d5\u05e4\u05e2\u05dc", "Upload locally": "\u05d4\u05e2\u05dc\u05d0\u05d4 \u05de\u05e7\u05d5\u05de\u05d9\u05ea", "Select Tool...": "\u05db\u05dc\u05d9 \u05d1\u05d7\u05d9\u05e8\u05d4", "Paused": "\u05d1\u05d4\u05e4\u05e1\u05e7\u05d4", "Continue": "\u05d4\u05de\u05e9\u05da", "Radius": "\u05e8\u05d3\u05d9\u05d5\u05e1", "The command \"%(command)s\" executed successfully": "\u05d4\u05e4\u05e7\u05d5\u05d3\u05d4 \"%(command)s\" \u05d4\u05ea\u05d1\u05e6\u05e2\u05d4 \u05d1\u05d4\u05e6\u05dc\u05d7\u05d4", "Features": "\u05e4\u05d9\u05e6'\u05e8\u05d9\u05dd", "Download": "\u05d4\u05d5\u05e8\u05d3", "GCode Viewer": "\u05de\u05e6\u05d9\u05d2 Gcode", "Also show previous layer": "\u05d0\u05e4\u05e9\u05e8 \u05d4\u05e6\u05d2\u05d4 \u05e9\u05dc \u05e9\u05db\u05d1\u05d4 \u05e7\u05d5\u05d3\u05de\u05ea", "Enable OctoPrint watermark in timelapse movies": "\u05d4\u05d5\u05e1\u05e3 \u05e1\u05d9\u05de\u05df \u05de\u05d9\u05dd \u05e9\u05dc \u05d0\u05d5\u05e7\u05d8\u05d5\u05e4\u05e8\u05d9\u05e0\u05d8 \u05e2\u05d1\u05d5\u05e8 \u05e1\u05e8\u05d8\u05d5\u05e0\u05d9\u05dd", "Repetier": "Repetier", "Login successful": "\u05db\u05e0\u05d9\u05e1\u05d4 \u05dc\u05de\u05e2\u05e8\u05db\u05ea \u05d4\u05ea\u05d1\u05e6\u05e2\u05d4 \u05d1\u05d4\u05e6\u05dc\u05d7\u05d4", "Finished Timelapses": "Timelapses \u05e9\u05d4\u05e1\u05ea\u05d9\u05d9\u05de\u05d5", "Rendering of timelapse %(movie_basename)s failedwith return code %(returncode)s": "\u05de\u05e8\u05e0\u05d3\u05e8 timelapse %(movie_basename)s \u05d4\u05e1\u05ea\u05d9\u05d9\u05dd \u05d1\u05e9\u05d2\u05d9\u05d0\u05d4 \u05d1\u05e2\u05dc\u05ea \u05e7\u05d5\u05d3 \u05de\u05e1\u05e4\u05e8 %(returncode)s", "Pause": "\u05d4\u05e4\u05e1\u05e7", "Temperature": "\u05d8\u05de\u05e4\u05e8\u05d8\u05d5\u05e8\u05d4", "Enable slicing via Cura": "\u05d4\u05e4\u05e2\u05dc \u05e4\u05e8\u05d9\u05e1\u05d4 \u05d1\u05d0\u05de\u05e6\u05e2\u05d5\u05ea Cura", "Access Control": "\u05d1\u05e7\u05e8\u05ea \u05d2\u05d9\u05e9\u05d4", "Analyzing...": "\u05de\u05e0\u05ea\u05d7 \u05e0\u05ea\u05d5\u05e0\u05d9\u05dd ...", "just now": "\u05d6\u05d4 \u05d4\u05e8\u05d2\u05e2", "Operational": "\u05d0\u05d5\u05e4\u05e6\u05d9\u05d5\u05e0\u05dc\u05d9", "Send a checksum with every command": "\u05d4\u05de\u05ea\u05df \u05e2\u05d1\u05d5\u05e8 \u05e1\u05d9\u05db\u05d5\u05dd \u05d1\u05d9\u05e7\u05d5\u05e8\u05ea (checksum) \u05e2\u05d1\u05d5\u05e8 \u05db\u05dc \u05e4\u05e7\u05d5\u05d3\u05d4", "Autodetection timeout": "\u05d6\u05d4\u05d5\u05d9 timeout \u05d0\u05d5\u05d8\u05de\u05d8\u05d9", "Connecting": "\u05de\u05ea\u05d7\u05d1\u05e8", "Free": "\u05e4\u05e0\u05d5\u05d9", "Closed": "\u05e1\u05d2\u05d5\u05e8", "Refresh SD files": "\u05de\u05e8\u05e2\u05e0\u05df \u05e7\u05d1\u05e6\u05d9 SD", "Flip webcam vertically": "\u05d4\u05e4\u05d5\u05da \u05ea\u05de\u05d5\u05e0\u05ea \u05de\u05e6\u05dc\u05de\u05d4 \u05d0\u05e0\u05db\u05d9\u05ea", "Path to Cura config": "\u05e0\u05ea\u05d9\u05d1 \u05dc\u05d4\u05d2\u05d3\u05e8\u05d5\u05ea \u05e9\u05dc Cura", "Filament": "\u05e1\u05d9\u05d1 \u05d7\u05d5\u05de\u05e8", "Could not slice %(stl)s to %(gcode)s: %(reason)s": "\u05dc\u05d0 \u05d4\u05d9\u05d4 \u05e0\u05d9\u05ea\u05df \u05dc\u05e4\u05e8\u05d5\u05e1 %(stl)s \u05d0\u05dc %(gcode)s: %(reason)s", "Baudrate": "\u05e7\u05e6\u05d1 \u05d1\u05d0\u05d5\u05d3 (Baudrate)", "Detecting baudrate": "\u05de\u05d0\u05ea\u05e8 \u05de\u05d4\u05d9\u05e8\u05d5\u05ea \u05d4\u05e2\u05d1\u05e8\u05d4", "Date": "\u05ea\u05d0\u05e8\u05d9\u05da", "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds": "\u05e9\u05d5\u05d3\u05e8 %(local)s \u05d0\u05dc%(remote)s \u05e2\u05dc SD, \u05dc\u05e7\u05d7 %(time).2f \u05e9\u05e0\u05d9\u05d5\u05ea", "Show moves": "\u05d4\u05e6\u05d2 \u05ea\u05d6\u05d5\u05d6\u05d5\u05ea", "Motors off": "\u05db\u05d1\u05d4 \u05de\u05e0\u05d5\u05e2\u05d9\u05dd", "Detecting serial port": "\u05de\u05d0\u05ea\u05e8 \u05d9\u05e6\u05d9\u05e8\u05d4 \u05d8\u05d5\u05e8\u05d9\u05ea", "New Password": "\u05e1\u05d9\u05e1\u05de\u05d4 \u05d7\u05d3\u05e9\u05d4", "Logout": "\u05d4\u05ea\u05e0\u05ea\u05e7\u05d5\u05ea", "Offset": "\u05d4\u05e1\u05d8", "Analyzed": "\u05e0\u05ea\u05d5\u05e0\u05d9\u05dd \u05e0\u05d5\u05ea\u05d7\u05d5", "Auto-connect on server startup": "\u05d7\u05d9\u05d1\u05d5\u05e8 \u05de\u05d7\u05d3\u05e9 \u05e2\u05dd \u05e2\u05dc\u05d9\u05d9\u05ea \u05d4\u05e9\u05e8\u05ea", "Printer Parameters": "\u05e4\u05e8\u05de\u05d8\u05e8\u05d9\u05dd \u05e9\u05dc \u05d4\u05de\u05d3\u05e4\u05e1\u05ea", "E": "E", "Restart": "\u05d0\u05ea\u05d7\u05d5\u05dc", "Search...": "\u05d7\u05d9\u05e4\u05d5\u05e9...", "Slicing failed": "\u05e4\u05e8\u05d9\u05e1\u05d4 \u05e0\u05db\u05e9\u05dc\u05d4", "Actual": "\u05e0\u05d5\u05db\u05d7\u05d9", "Active": "\u05e4\u05e2\u05d9\u05dc", "Creation date": "\u05ea\u05d0\u05e8\u05d9\u05da \u05d9\u05e6\u05d9\u05e8\u05d4", "Hint: You can also drag and drop files on this page to upload them.": "\u05d8\u05d9\u05e4: \u05e0\u05d9\u05ea\u05df \u05dc\u05d2\u05e8\u05d5\u05e8 \u05e7\u05d1\u05e6\u05d9\u05dd \u05d0\u05dc \u05d3\u05e3 \u05d6\u05d4 \u05db\u05d3\u05d9 \u05dc\u05d4\u05e2\u05dc\u05d5\u05ea \u05d0\u05d5\u05ea\u05dd", "Interval": "\u05d0\u05d9\u05e0\u05d8\u05e8\u05d5\u05d5\u05dc", "N/A": "\u05dc\u05d0 \u05d6\u05de\u05d9\u05df", "Bed": "\u05de\u05d9\u05d8\u05d4", "Auto-connect to printer on server start": "\u05d4\u05ea\u05d7\u05d1\u05e8 \u05de\u05d7\u05d3\u05e9 \u05dc\u05de\u05d3\u05e4\u05e1\u05ea \u05e2\u05dd \u05d4\u05e2\u05dc\u05d9\u05d9\u05d4 \u05e9\u05dc \u05d4\u05e9\u05e8\u05ea", "orange": "\u05db\u05ea\u05d5\u05dd", "Connection": "\u05d7\u05d9\u05d1\u05d5\u05e8", "Error": "\u05e9\u05d2\u05d9\u05d0\u05d4", "On Z Change": "\u05e9\u05d9\u05e0\u05d5\u05d9 \u05e6\u05d9\u05e8 Z", "Timelapse post roll (in rendered seconds)": "\u05e2\u05d9\u05d1\u05d5\u05d3 Timelapse (\u05d1\u05e9\u05e0\u05d9\u05d5\u05ea \u05e9\u05e8\u05d5\u05e0\u05d3\u05e8\u05d5)", "Z": "Z", "Are you sure you want to proceed?": "\u05d4\u05d0\u05dd \u05d1\u05d0\u05de\u05ea \u05dc\u05d4\u05de\u05e9\u05d9\u05da?", "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!": "\u05d0\u05dd \u05d1\u05e8\u05e6\u05d5\u05da \u05dc\u05d1\u05d8\u05dc \u05d0\u05ea \u05d4\u05d4\u05e8\u05e9\u05d0\u05d5\u05ea \u05d2\u05d9\u05e9\u05d4 \u05d5\u05d2\u05dd \u05d4\u05d4\u05ea\u05e7\u05e0\u05d4 \u05e9\u05dc \u05d0\u05d5\u05e7\u05d8\u05d5\u05e4\u05e8\u05d9\u05e0\u05d8 \u05e0\u05d9\u05ea\u05e0\u05ea \u05dc\u05d2\u05d9\u05e9\u05d4 \u05d3\u05e8\u05da \u05d4\u05d0\u05d9\u05e0\u05d8\u05e8\u05e0\u05d8, \u05d0\u05d6 \u05db\u05dc \u05d0\u05d7\u05d3 \u05d9\u05d5\u05db\u05dc \u05dc\u05e9\u05dc\u05d5\u05d8 \u05e2\u05dc \u05d4\u05de\u05d3\u05e4\u05e1\u05ea \u05e9\u05dc\u05da, \u05d6\u05d4 \u05db\u05d5\u05dc\u05dc \u05d0\u05e0\u05e9\u05d9\u05dd \u05e8\u05e2\u05d9\u05dd!", "Load": "\u05d8\u05e2\u05d9\u05e0\u05d4", "Set": "\u05e7\u05d1\u05e2", "The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below.": "\u05e0\u05e8\u05d0\u05d4 \u05e9\u05d4\u05e9\u05e8\u05ea \u05dc\u05d0 \u05de\u05d7\u05d5\u05e8\u05d1, \u05d0\u05d5 \u05dc\u05e4\u05d7\u05d5\u05ea \u05d0\u05e0\u05d9 \u05dc\u05d0 \u05de\u05e6\u05dc\u05d9\u05d7 \u05dc\u05e7\u05d1\u05dc \u05db\u05dc \u05ea\u05d2\u05d5\u05d1\u05d4 \u05de\u05de\u05e0\u05d5. \u05d4\u05d7\u05d9\u05d1\u05d5\u05e8 \u05d4\u05d0\u05d5\u05d8\u05d5\u05de\u05d0\u05d8\u05d9 \u05e0\u05db\u05e9\u05dc, \u05d0\u05d1\u05dc \u05e0\u05d9\u05ea\u05df \u05d2\u05dd \u05dc\u05e0\u05e1\u05d5\u05ea \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05de\u05d7\u05d3\u05e9 \u05e2\u05dd \u05d4\u05db\u05e4\u05ea\u05d5\u05e8 \u05dc\u05d4\u05dc\u05df.", "Zoom in on model": "\u05d6\u05d5\u05dd \u05dc\u05ea\u05d5\u05da \u05de\u05d5\u05d3\u05dc", "mm": "\u05de\"\u05de", "Saving ...": "\u05e9\u05d5\u05de\u05e8 ...", "RegExp": "\u05d1\u05d9\u05d8\u05d5\u05d9 \u05e8\u05d2\u05d5\u05dc\u05e8\u05d9", "Watched Folder": "\u05ea\u05e7\u05d9\u05d9\u05d4 \u05e9\u05e0\u05e6\u05e4\u05ea\u05d4", "General": "\u05db\u05dc\u05dc\u05d9", "Temperature timeout": "\u05d8\u05de\u05e4\u05e8\u05d8\u05d5\u05e8\u05d4 timeout", "Color": "\u05e6\u05d1\u05e2", "Fans on": "\u05de\u05d0\u05d5\u05d5\u05e8\u05e8 \u05d3\u05dc\u05d5\u05e7", "Swallow the first \"ok\" after a resend response": "\u05dc\u05d1\u05dc\u05d5\u05e2 \u05d0\u05ea \u05d4-\"ok\" \u05d4\u05e8\u05d0\u05e9\u05d5\u05df \u05d0\u05d7\u05e8\u05d9 \u05e9\u05e0\u05e9\u05dc\u05d7\u05d4 \u05de\u05d7\u05d3\u05e9\u05d4 \u05ea\u05d2\u05d5\u05d1\u05d4", "Enable SD support": "\u05d4\u05e4\u05e2\u05dc \u05ea\u05de\u05d9\u05db\u05d4 \u05d1-SD", "Connect": "\u05d4\u05ea\u05d7\u05d1\u05e8", "Cancel": "\u05d1\u05d9\u05d8\u05d5\u05dc", "sec": "\u05e9\u05e0'", "Warning": "\u05d0\u05d6\u05d4\u05e8\u05d4", "Loading...": "\u05d8\u05d5\u05e2\u05df", "Current API Key": "\u05de\u05e4\u05ea\u05d7 API \u05e0\u05d5\u05db\u05d7\u05d9", "Size": "\u05d2\u05d5\u05d3\u05dc", "Communication timeout": "\u05d7\u05d9\u05d1\u05d5\u05e8 \u05dc\u05d0 \u05e2\u05d5\u05d1\u05d3 \u05e2\u05e7\u05d1 timeout", "Modification date": "\u05ea\u05d0\u05e8\u05d9\u05da \u05e9\u05d9\u05e0\u05d5\u05d9", "Change password": "\u05e9\u05d9\u05e0\u05d5\u05d9 \u05e1\u05d9\u05e1\u05de\u05d4", "This will restart the print job from the beginning.": "\u05e4\u05e2\u05d5\u05dc\u05d4 \u05d6\u05d5 \u05ea\u05ea\u05d7\u05d9\u05dc \u05de\u05d7\u05d3\u05e9 \u05d0\u05ea \u05d4\u05d4\u05d3\u05e4\u05e1\u05d4 \u05de\u05d4\u05ea\u05d7\u05dc\u05d4", "Stream URL": "\u05db\u05ea\u05d5\u05d1\u05ea \u05e9\u05d9\u05d3\u05d5\u05e8 \u05d5\u05d9\u05d3\u05d0\u05d5", "Sort by": "\u05de\u05d9\u05d9\u05df \u05dc\u05e4\u05d9", "Login failed": "\u05db\u05e0\u05d9\u05e1\u05d4 \u05dc\u05de\u05e2\u05e8\u05db\u05ea \u05e0\u05db\u05e9\u05dc\u05d4", "Abort": "\u05d1\u05d9\u05d8\u05d5\u05dc", "Confirm": "\u05d0\u05d9\u05e9\u05d5\u05e8", "Repeat Password": "\u05d7\u05d6\u05d5\u05e8 \u05e2\u05dc \u05e1\u05d9\u05e1\u05de\u05d4", "Terminal": "\u05de\u05e1\u05d5\u05e3", "Autoscroll": "\u05d2\u05dc\u05d9\u05dc\u05d4 \u05d0\u05d5\u05d8\u05d5\u05de\u05d0\u05d8\u05d9\u05ea", "Print time for layer": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05e2\u05d1\u05d5\u05e8 \u05e9\u05db\u05d1\u05d4", "Disable Access Control": "\u05d1\u05d9\u05d8\u05d5\u05dc \u05dc\u05d5\u05d7 \u05d1\u05e7\u05e8\u05d4", "Configure Access Control": "\u05d4\u05d2\u05d3\u05e8\u05d5\u05ea \u05dc\u05d5\u05d7 \u05d1\u05e7\u05e8\u05d4", "Timelapse Configuration": "\u05d4\u05d2\u05d3\u05e8\u05d5\u05ea timelapse", "Retract": "\u05e0\u05e1\u05d5\u05d2", "Timelapse bitrate": "\u05d0\u05d9\u05db\u05d5\u05ea timelapse", "Offline": "\u05dc\u05d0 \u05de\u05d7\u05d5\u05d1\u05e8", "API Key": "\u05de\u05e4\u05ea\u05d7 API", "Homepage": "\u05d3\u05e3 \u05d1\u05d9\u05ea", "Estimated Print Time": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05de\u05d5\u05e2\u05e8\u05da", "Folders": "\u05ea\u05d9\u05e7\u05d9\u05d5\u05ea", "Bugs and Requests": "\u05d1\u05d0\u05d2\u05d9\u05dd \u05d5\u05d1\u05e7\u05e9\u05d5\u05ea", "Save": "\u05e9\u05de\u05d5\u05e8", "Default extrusion length": "\u05d0\u05d5\u05e8\u05da \u05d1\u05e8\u05d9\u05ea \u05de\u05d7\u05d3\u05dc \u05e9\u05dc \u05d4\u05d5\u05e6\u05d0\u05ea \u05e1\u05d9\u05d1 \u05d7\u05d5\u05de\u05e8", "min": "\u05d3\u05e7\u05d5'", "Support TargetExtr%%n/TargetBed target temperature format": "\u05ea\u05de\u05d5\u05da \u05e2\u05d1\u05d5\u05e8 TargetExtr%%n/TargetBed \u05e4\u05d5\u05e8\u05de\u05d8 \u05d8\u05de\u05e4\u05e8\u05d8\u05d5\u05e8\u05ea \u05d9\u05d9\u05e2\u05d3", "Connection timeout": "\u05d7\u05d9\u05e9\u05d5\u05d1 \u05e4\u05e1\u05e7, timeout", "Save config": "\u05e9\u05de\u05d5\u05e8 \u05d4\u05d2\u05d3\u05e8\u05d5\u05ea", "Center viewport on model": "\u05de\u05e8\u05db\u05d6 \u05ea\u05e6\u05d5\u05d2\u05d4 \u05e2\u05dc \u05de\u05d5\u05d3\u05dc", "User unknown or wrong password": "\u05e9\u05dd \u05de\u05e9\u05ea\u05de\u05e9 \u05dc\u05d0 \u05de\u05d5\u05db\u05e8, \u05d0\u05d5 \u05e9\u05d2\u05d9\u05d0\u05d4 \u05d1\u05e1\u05d9\u05e1\u05de\u05d4", "Allow Cross Origin Resource Sharing (CORS)": "\u05d0\u05e4\u05e9\u05e8 Cross Origin Resource Sharing (CORS)", "Appearance": "\u05de\u05e8\u05d0\u05d4", "Enable": "\u05d0\u05e4\u05e9\u05e8", "Uploading ...": "\u05de\u05e2\u05dc\u05d4 ...", "Logs Folder": "\u05ea\u05e7\u05d9\u05d9\u05ea \u05dc\u05d5\u05d2\u05d9\u05dd", "

\n Please read the following, it is very important for your printer's health!\n

\n

\n OctoPrint by default now ships with Access Control enabled, meaning you won't be able to do anything with the\n printer unless you login first as a configured user. This is to prevent strangers - possibly with\n malicious intent - to gain access to your printer via the internet or another untrustworthy network\n and using it in such a way that it is damaged or worse (i.e. causes a fire).\n

\n

\n It looks like you haven't configured access control yet. Please set up an username and password for the\n initial administrator account who will have full access to both the printer and OctoPrint's settings, then click\n on \"Keep Access Control Enabled\":\n

": "

\n \u05d9\u05e9 \u05dc\u05e7\u05e8\u05d5\u05d0 \u05d0\u05ea \u05d4\u05de\u05d9\u05d3\u05d4 \u05d4\u05d1\u05d0, \u05d4\u05d5\u05d0 \u05d7\u05e9\u05d5\u05d1 \u05dc\u05d1\u05e8\u05d9\u05d0\u05d5\u05ea \u05d4\u05de\u05d3\u05e4\u05e1\u05ea \u05e9\u05dc\u05da!\n

\n

\n \u05d0\u05d5\u05e7\u05d8\u05d5\u05e4\u05e8\u05d9\u05e0\u05d8 \u05d1\u05d1\u05e8\u05d9\u05ea \u05de\u05d7\u05d3\u05dc \u05de\u05d2\u05d9\u05e2 \u05d4\u05dd \u05d1\u05e7\u05e8\u05ea \u05d2\u05d9\u05e9\u05d4 \u05de\u05d5\u05e4\u05e2\u05dc\u05ea, \u05db\u05dc\u05d5\u05de\u05e8 \u05dc\u05d0 \u05d9\u05d4\u05d9\u05d4 \u05e0\u05d9\u05ea\u05df \u05dc\u05d1\u05e6\u05e2 \u05d3\u05d1\u05e8 \u05e2\u05dd \u05d4\u05de\u05d3\u05e4\u05e1\u05ea\n \u05d0\u05dc\u05d4 \u05d0\u05dd \u05d4\u05db\u05e0\u05d9\u05e1\u05d4 \u05d4\u05e8\u05d0\u05e9\u05d5\u05e0\u05d9\u05ea \u05de\u05d5\u05d2\u05d3\u05e8\u05ea \u05e2\u05dd \u05d4\u05de\u05e9\u05ea\u05de\u05e9. \u05d6\u05d0\u05ea \u05db\u05d3\u05d9 \u05dc\u05de\u05e0\u05d5\u05e2 \u05de\u05d0\u05e0\u05e9\u05d9\u05dd \u05d6\u05e8\u05d9\u05dd - \u05db\u05db\u05dc \u05d4\u05e0\u05e8\u05d0\u05d4 \u05e2\u05dd\n \u05de\u05d8\u05e8\u05d5\u05ea \u05d6\u05d3\u05d5\u05df - \u05dc\u05e9\u05d9\u05d2 \u05d2\u05d9\u05e9\u05d4 \u05dc\u05de\u05d3\u05e4\u05e1\u05ea \u05e9\u05dc\u05da \u05d3\u05e8\u05da \u05d4\u05d0\u05d9\u05e0\u05d8\u05e8\u05e0\u05d8 \u05d0\u05d5 \u05e8\u05e9\u05ea \u05dc\u05d0 \u05de\u05d0\u05d5\u05d1\u05d8\u05d7\u05ea\n \u05d5\u05e9\u05d9\u05de\u05d5\u05e9 \u05d1\u05de\u05d3\u05e4\u05e1\u05ea \u05d1\u05d3\u05e8\u05da \u05e9\u05ea\u05d2\u05e8\u05d5\u05dd \u05e0\u05d6\u05e7 \u05dc\u05de\u05d3\u05e4\u05e1\u05ea, \u05d0\u05d5 \u05d2\u05e8\u05d5\u05e2 \u05de\u05db\u05da (\u05dc\u05de\u05e9\u05dc, \u05d2\u05e8\u05de\u05d4 \u05e9\u05dc \u05e9\u05e8\u05d9\u05e4\u05d4)..\n

\n

\n \u05e0\u05e8\u05d0\u05d4 \u05e9\u05e2\u05d3\u05d9\u05df \u05dc\u05d0 \u05d4\u05d5\u05d2\u05d3\u05e8\u05d4 \u05d1\u05e7\u05e8\u05ea \u05d2\u05d9\u05e9\u05d4. \u05d0\u05e0\u05d0 \u05d4\u05d2\u05d3\u05e8 \u05e9\u05dd \u05de\u05e9\u05ea\u05de\u05e9 \u05d5\u05e1\u05d9\u05e1\u05de\u05d4 \u05e2\u05d1\u05d5\u05e8\n \u05de\u05e0\u05d4\u05dc \u05d4\u05de\u05e2\u05e8\u05db\u05ea \u05d4\u05e8\u05d0\u05e9\u05d5\u05df \u05e9\u05d9\u05d4\u05d9\u05d4 \u05d1\u05e2\u05dc \u05d2\u05d9\u05e9\u05d4 \u05dc\u05de\u05d3\u05e4\u05e1\u05ea \u05d5\u05d4\u05d4\u05d2\u05d3\u05e8\u05d5\u05ea \u05e9\u05dc \u05d0\u05d5\u05e7\u05d8\u05d5\u05e4\u05e8\u05d9\u05e0\u05d8,\n \u05dc\u05d0\u05d7\u05e8 \u05de\u05db\u05df \u05d9\u05e9 \u05dc\u05dc\u05d7\u05d5\u05e5 \u05e2\u05dc \"\u05e9\u05de\u05d5\u05e8 \u05e2\u05dc \u05dc\u05d5\u05d7 \u05d1\u05e7\u05e8\u05d4 \u05de\u05d5\u05e4\u05e2\u05dc\":\n

", "Hide successfully printed files": "\u05d4\u05e1\u05ea\u05e8 \u05e7\u05d1\u05e6\u05d9\u05dd \u05e9\u05d4\u05d5\u05d3\u05e4\u05e1\u05d5 \u05d1\u05d4\u05e6\u05dc\u05d7\u05d4", "Username": "\u05e9\u05dd \u05de\u05e9\u05ea\u05de\u05e9", "Off": "\u05db\u05d1\u05d5\u05d9", "Name": "\u05e9\u05dd", "Extruder Offsets": "\u05d4\u05e1\u05d8 \u05d0\u05e7\u05e1\u05d8\u05e8\u05d5\u05d3\u05e8", "Approx. Total Print Time": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05e1\u05d5\u05e4\u05d9 \u05de\u05d5\u05e2\u05e8\u05da", "Admin": "\u05de\u05e0\u05d4\u05dc", "

\n Note: In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't\n need Access Control for other reasons, you may alternatively disable Access Control. You should only\n do this if you are absolutely certain that only people you know and trust will be able to connect to it.\n

\n

\n Do NOT underestimate the risk of an unsecured access from the internet to your printer!\n

": "

\n \u05d4\u05e2\u05e8\u05d4: \u05d1\u05de\u05e7\u05e8\u05d4 \u05e9\u05d4\u05d4\u05ea\u05e7\u05e0\u05d4 \u05e9\u05dc \u05d0\u05d5\u05e7\u05d8\u05d5\u05e4\u05e8\u05d9\u05e0\u05d8 \u05e0\u05d9\u05ea\u05e0\u05ea \u05dc\u05d2\u05d9\u05e9\u05d4 \u05de\u05ea\u05d5\u05da \u05e8\u05e9\u05ea \u05dc\u05d0 \u05de\u05d0\u05d5\u05d1\u05d8\u05d7\u05ea, \u05d5\u05d0\u05d9\u05df \u05e6\u05d5\u05e8\u05da\n \u05d1\u05e0\u05d9\u05d4\u05d5\u05dc \u05d4\u05e8\u05e9\u05d0\u05d5\u05ea \u05d2\u05d9\u05e9\u05d4 \u05de\u05e1\u05d9\u05d1\u05d5\u05ea \u05d0\u05d7\u05e8\u05d5\u05ea, \u05e0\u05d9\u05ea\u05df \u05dc\u05d1\u05d8\u05dc \u05d0\u05ea \u05d4\u05d4\u05e9\u05d0\u05d5\u05ea \u05e0\u05d9\u05d4\u05d5\u05dc \u05d4\u05d2\u05d9\u05e9\u05d4. \u05d0\u05d1\u05dc \u05d9\u05e9 \u05dc\u05e2\u05e9\u05d5\u05ea \u05d6\u05d0\u05ea \u05e8\u05e7\n \u05d0\u05dd \u05d1\u05d8\u05d5\u05d7 \u05dc\u05d7\u05dc\u05d5\u05d8\u05d9\u05df \u05e9\u05e8\u05e7 \u05d0\u05e0\u05e9\u05d9\u05dd \u05e9\u05de\u05db\u05d9\u05e8\u05d9\u05dd \u05d5\u05e1\u05d5\u05de\u05db\u05d9\u05dd \u05e2\u05dc\u05d9\u05d4\u05dd \u05d9\u05d4\u05d9\u05d5 \u05d1\u05e2\u05dc\u05d9 \u05d9\u05db\u05d5\u05dc\u05ea \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05dc\u05de\u05d3\u05e4\u05e1\u05ea.\n

\n

\n \u05e0\u05d0 \u05dc\u05d0 \u05dc\u05d6\u05dc\u05d6\u05dc \u05d1\u05e1\u05d9\u05db\u05d5\u05df \u05e9\u05dc \u05e8\u05e9\u05ea\u05d5\u05ea \u05dc\u05d0 \u05de\u05d0\u05d5\u05d1\u05d8\u05d7\u05d5\u05ea \u05de\u05d4\u05d0\u05d9\u05e0\u05d8\u05e8\u05e0\u05d8 \u05dc\u05de\u05d3\u05e4\u05e1\u05ea \u05e9\u05dc\u05da!!\n

", "Timelapse": "Timelapse", "Remove": "\u05d4\u05e1\u05e8", "Reload": "\u05e8\u05e2\u05e0\u05df", "Printing": "\u05de\u05d3\u05e4\u05d9\u05e1", "Only show files stored on SD": "\u05d4\u05e6\u05d2 \u05e8\u05e7 \u05e7\u05d1\u05e6\u05d9\u05dd \u05d4\u05e9\u05de\u05d5\u05e8\u05d9\u05dd \u05e2\u05dc SD", "Y": "Y", "Fans off": "\u05de\u05d0\u05d5\u05d5\u05e8\u05e8 \u05db\u05d1\u05d5\u05d9", "Login": "\u05db\u05e0\u05d9\u05e1\u05d4", "Timelapse ready": "Timelapse \u05de\u05d5\u05db\u05df", "Timelapse Mode": "\u05de\u05e6\u05d1 timelapse", "Timelapse Folder": "\u05ea\u05e7\u05d9\u05d9\u05ea timelapse", "Extruder": "\u05d0\u05e7\u05e1\u05d8\u05e8\u05d5\u05d3\u05e8", "Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and slicing support is enabled and configured.": "\u05dc\u05d0 \u05d4\u05d9\u05d4 \u05e0\u05d9\u05ea\u05df \u05dc\u05d4\u05e2\u05dc\u05d5\u05ea \u05e7\u05d5\u05d1\u05e5. \u05d9\u05e9 \u05d5\u05d5\u05d3\u05d0 \u05e9\u05d6\u05d4 \u05d4\u05d5\u05d0 \u05e7\u05d5\u05d1\u05e5 GCODE \u05d5\u05e9\u05e1\u05d9\u05d5\u05de\u05ea \u05d4\u05e7\u05d5\u05d1\u05e5 \u05d4\u05d9\u05d0 \".gcode\" \u05d0\u05d5 \".gco\". \u05d0\u05d5 \u05e9\u05d4\u05e7\u05d5\u05d1\u05e5 \u05d4\u05d5\u05d0 STL \u05e2\u05dd \u05d4\u05e1\u05d9\u05d5\u05de\u05ea \".stl\" \u05db\u05d0\u05e9\u05e8 \u05e4\u05e8\u05d9\u05e1\u05d4 \u05de\u05ea\u05de\u05db\u05ea, \u05de\u05d5\u05e4\u05e2\u05dc\u05ea \u05d5\u05de\u05d5\u05d2\u05d3\u05e8\u05ea.", "SD status timeout": "\u05de\u05e6\u05d1 SD \u05d1-timeout", "SD not initialized": "SD \u05dc\u05d0 \u05de\u05d0\u05d5\u05ea\u05d7\u05dc", "Update User": "\u05e2\u05d3\u05db\u05df \u05de\u05e9\u05ea\u05de\u05e9", "off": "\u05db\u05d9\u05d1\u05d5\u05d9", "Serial Port": "\u05d9\u05e6\u05d9\u05d0\u05d4 \u05d8\u05d5\u05e8\u05d9\u05ea", "Flip webcam horizontally": "\u05d4\u05e4\u05d5\u05da \u05ea\u05de\u05d5\u05e0\u05ea \u05de\u05e6\u05dc\u05de\u05d4 \u05d0\u05d5\u05e4\u05e7\u05d9\u05ea", "Wait for start on connect": "\u05d4\u05de\u05ea\u05df \u05e2\u05d1\u05d5\u05e8 start \u05d1\u05d7\u05d9\u05d1\u05d5\u05e8", "Transfering file to SD": "\u05de\u05e2\u05d1\u05d9\u05e8 \u05e7\u05d5\u05d1\u05e5 \u05dc-SD", "OctoPrint": "\u05d0\u05d5\u05e7\u05d8\u05d5\u05e4\u05e8\u05d9\u05e0\u05d8", "Layer height": "\u05d2\u05d5\u05d1\u05d4 \u05e9\u05db\u05d1\u05d4", "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds": "\u05e4\u05e8\u05d9\u05e1\u05d4 \u05e9\u05dc %(stl)s \u05d0\u05dc %(gcode)s, \u05dc\u05e7\u05d7 %(time).2f \u05e9\u05e0\u05d9\u05d5\u05ea", "Extrude": "\u05d4\u05d5\u05e6\u05d0 \u05e1\u05d9\u05d1 \u05d7\u05d5\u05de\u05e8", "green": "\u05d9\u05e8\u05d5\u05e7", "File": "\u05e7\u05d5\u05d1\u05e5", "You are now logged in as \"%(username)s\"": "\u05de\u05d7\u05d5\u05d1\u05e8 \u05db\u05e2\u05ea \u05d1\u05ea\u05d5\u05e8 \"%(username)s\"", "Axis": "\u05e6\u05d9\u05e8\u05d9\u05dd", "Filament used by layer": "\u05e1\u05d9\u05d1 \u05d7\u05d5\u05de\u05e8 \u05e9\u05e0\u05d3\u05e9 \u05d1\u05e9\u05db\u05d1\u05d4"}} ; \ No newline at end of file +window.BABEL_TO_LOAD_he = {"locale": "he", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:04+0000\nLast-Translator: Gina H\u00e4u\u00dfge \nLanguage-Team: Hebrew (http://www.transifex.com/projects/p/octoprint/language/he/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05e0\u05d5\u05ea\u05e8", "sec": "\u05e9\u05e0'", "Proceed": "\u05d4\u05de\u05e9\u05da", "Timelapse Temp Folder": "\u05ea\u05e7\u05d9\u05d9\u05d4 \u05d6\u05de\u05e0\u05d9\u05ea \u05dc-timelapse", "Support TargetExtr%%n/TargetBed target temperature format": "\u05ea\u05de\u05d5\u05da \u05e2\u05d1\u05d5\u05e8 TargetExtr%%n/TargetBed \u05e4\u05d5\u05e8\u05de\u05d8 \u05d8\u05de\u05e4\u05e8\u05d8\u05d5\u05e8\u05ea \u05d9\u05d9\u05e2\u05d3", "Upload Folder": "\u05ea\u05e7\u05d9\u05d9\u05ea \u05d4\u05e2\u05dc\u05d0\u05d4", "Only show files stored locally": "\u05d4\u05e6\u05d2 \u05e8\u05e7 \u05e7\u05d1\u05e6\u05d9\u05dd \u05d4\u05e9\u05de\u05d5\u05e8\u05d9\u05dd \u05de\u05e7\u05d5\u05de\u05d9\u05ea", "Add Printer Profile": "", "yellow": "\u05e6\u05d4\u05d5\u05d1", "Save": "\u05e9\u05de\u05d5\u05e8", "Action": "\u05e4\u05e2\u05d5\u05dc\u05d4", "Passwords do not match": "\u05e1\u05d9\u05e1\u05de\u05d0\u05d5\u05ea \u05dc\u05d0 \u05ea\u05d5\u05d0\u05de\u05d5\u05ea", "Sort by name": "\u05de\u05d9\u05d9\u05df \u05dc\u05e4\u05d9 \u05e9\u05dd", "Save connection settings": "\u05e9\u05de\u05d5\u05e8 \u05d4\u05d2\u05d3\u05e8\u05d5\u05ea \u05d7\u05d9\u05d1\u05d5\u05e8", "Rendering timelapse": "\u05de\u05e8\u05e0\u05d3\u05e8 timelapse", "Color": "\u05e6\u05d1\u05e2", "Temperature": "\u05d8\u05de\u05e4\u05e8\u05d8\u05d5\u05e8\u05d4", "Files": "\u05e7\u05d1\u05e6\u05d9\u05dd", "Resume": "", "Always assume SD card is present": "\u05ea\u05de\u05d9\u05d3 \u05ea\u05e0\u05d9\u05d7 \u05e9\u05db\u05e8\u05d8\u05d9\u05e1 SD \u05e0\u05de\u05e6\u05d0", "Load and Print": "\u05d8\u05e2\u05df \u05d5\u05d4\u05d3\u05e4\u05e1", "Sending file to SD": "\u05e9\u05d5\u05dc\u05d7 \u05e7\u05d5\u05d1\u05e5 \u05d0\u05dc SD", "Number of Extruders": "\u05de\u05e1\u05e4\u05e8 \u05d0\u05e7\u05e1\u05d8\u05e8\u05d5\u05d3\u05e8\u05d9\u05dd", "black": "\u05e9\u05d7\u05d5\u05e8", "Last Printed": "\u05d4\u05d5\u05d3\u05e4\u05e1 \u05dc\u05d0\u05d7\u05e8\u05d5\u05e0\u05d4", "Sourcecode": "\u05e7\u05d5\u05d3 \u05de\u05e7\u05d5\u05e8", "Estimated layer height": "\u05d2\u05d5\u05d1\u05d4 \u05e9\u05db\u05d1\u05d5\u05ea \u05de\u05e9\u05d5\u05e2\u05e8", "You are now logged out": "\u05d4\u05ea\u05e0\u05ea\u05e7\u05ea \u05de\u05d4\u05de\u05e2\u05e8\u05db\u05ea", "Uploaded": "\u05d4\u05d5\u05e2\u05dc\u05d4", "Form Factor": "", "Opening serial port": "\u05e4\u05d5\u05ea\u05d7 \u05d9\u05e6\u05d9\u05e8\u05d4 \u05d8\u05d5\u05e8\u05d9\u05ea", "New timelapse %(movie_basename)s is done rendering.": "\u05e1\u05d9\u05d9\u05dd \u05dc\u05e8\u05e0\u05d3\u05e8 \u05d0\u05ea \u05d4-timelapse %(movie_basename)s", "Invert control": "\u05d4\u05e4\u05d5\u05da \u05e9\u05dc\u05d9\u05d8\u05d4", "Webcam": "\u05de\u05e6\u05dc\u05de\u05ea \u05e8\u05e9\u05ea", "Select for printing": "", "Allow Cross Origin Resource Sharing (CORS)": "\u05d0\u05e4\u05e9\u05e8 Cross Origin Resource Sharing (CORS)", "Remember me": "\u05d6\u05db\u05d5\u05e8 \u05d0\u05d5\u05ea\u05d9", "Enable GCode Visualizer": "\u05d4\u05e4\u05e2\u05dc \u05d5\u05d9\u05d6\u05d5\u05d0\u05dc\u05d9\u05d6\u05e6\u05d9\u05d4 \u05e9\u05dc GCode", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below.": "\u05e0\u05e8\u05d0\u05d4 \u05e9\u05d4\u05e9\u05e8\u05ea \u05dc\u05d0 \u05de\u05d7\u05d5\u05d1\u05e8, \u05d0\u05d5 \u05dc\u05e4\u05d7\u05d5\u05ea \u05d0\u05e0\u05d9 \u05dc\u05d0 \u05de\u05e6\u05dc\u05d9\u05d7 \u05dc\u05e7\u05d1\u05dc \u05db\u05dc \u05ea\u05d2\u05d5\u05d1\u05d4 \u05de\u05de\u05e0\u05d5. \u05d0\u05e0\u05e1\u05d4 \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05de\u05d7\u05d3\u05e9 \u05d0\u05d5\u05d8\u05d5\u05de\u05d8\u05d9\u05ea \u05d1\u05e2\u05d5\u05d3 \u05de\u05e1\u05e4\u05e8 \u05d3\u05e7\u05d5\u05ea, \u05d0\u05d1\u05dc \u05e0\u05d9\u05ea\u05df \u05d2\u05dd \u05dc\u05e0\u05e1\u05d5\u05ea \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05de\u05d7\u05d3\u05e9 \u05e2\u05dd \u05d4\u05db\u05e4\u05ea\u05d5\u05e8 \u05dc\u05d4\u05dc\u05df.", "Rendering failed": "\u05e8\u05d9\u05e0\u05d3\u05d5\u05e8 \u05e0\u05db\u05e9\u05dc", "Motors off": "\u05db\u05d1\u05d4 \u05de\u05e0\u05d5\u05e2\u05d9\u05dd", "descending": "\u05e1\u05d3\u05e8 \u05d9\u05d5\u05e8\u05d3", "Only show files stored on SD": "\u05d4\u05e6\u05d2 \u05e8\u05e7 \u05e7\u05d1\u05e6\u05d9\u05dd \u05d4\u05e9\u05de\u05d5\u05e8\u05d9\u05dd \u05e2\u05dc SD", "X": "X", "Add user": "\u05d4\u05d5\u05e1\u05e3 \u05de\u05e9\u05ea\u05de\u05e9", "GCODE commands in layer": "\u05e4\u05e7\u05d5\u05d3\u05d5\u05ea GCODE \u05d1\u05e9\u05db\u05d1\u05d4", "Estimated print time": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05de\u05e9\u05d5\u05e2\u05e8", "Serial Connection": "\u05d7\u05d9\u05d1\u05d5\u05e8 \u05d8\u05d5\u05e8\u05d9", "Control": "\u05e9\u05dc\u05d9\u05d8\u05d4", "Password": "\u05e1\u05d9\u05e1\u05de\u05d4", "Also show next layer": "\u05d0\u05e4\u05e9\u05e8 \u05d4\u05e6\u05d2\u05d4 \u05e9\u05dc \u05e9\u05db\u05d1\u05d4 \u05d4\u05d1\u05d0\u05d4", "Print Time": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4", "Slicer": "", "Nozzle Diameter": "", "Sort by file size": "\u05de\u05d9\u05d9\u05df \u05dc\u05e4\u05d9 \u05d2\u05d5\u05d3\u05dc \u05e7\u05d5\u05d1\u05e5", "Machine State": "\u05de\u05e6\u05d1 \u05de\u05db\u05d5\u05e0\u05d4", "Slicing Profile": "", "mm": "\u05de\"\u05de", "API": "API", "Printing from SD": "\u05d4\u05d3\u05e4\u05e1\u05d4 \u05de-SD", "Stream URL": "\u05db\u05ea\u05d5\u05d1\u05ea \u05e9\u05d9\u05d3\u05d5\u05e8 \u05d5\u05d9\u05d3\u05d0\u05d5", "Terminal filters": "\u05e4\u05d9\u05dc\u05d8\u05e8\u05d9 \u05de\u05e1\u05d5\u05e3", "Change password for user \"%(user)s\"": "\u05d4\u05d7\u05dc\u05e3 \u05e1\u05d9\u05e1\u05de\u05d4 \u05e2\u05d1\u05d5\u05e8 \u05de\u05e9\u05ea\u05de\u05e9 \"%(user)s\"", "Enable Temperature Graph": "\u05d4\u05e4\u05e2\u05dc \u05d2\u05e8\u05e3 \u05d8\u05de\u05e4\u05e8\u05d8\u05d5\u05e8\u05d4", "Delete user": "\u05de\u05d7\u05e7 \u05de\u05e9\u05ea\u05de\u05e9", "Timelapse bitrate": "\u05d0\u05d9\u05db\u05d5\u05ea timelapse", "Confirm Password": "\u05d0\u05d9\u05e9\u05d5\u05e8 \u05e1\u05d9\u05e1\u05de\u05d4", "Disconnect": "\u05d4\u05ea\u05e0\u05ea\u05e7", "Slicing done": "\u05e4\u05e8\u05d9\u05e1\u05d4 \u05d4\u05d5\u05e9\u05dc\u05de\u05d4", "Initialize SD card": "\u05de\u05d0\u05ea\u05db\u05dc \u05db\u05e8\u05d8\u05d9\u05e1 SD", "System": "\u05de\u05e2\u05e8\u05db\u05ea", "Send": "\u05e9\u05dc\u05d7", "State": "\u05de\u05e6\u05d1", "Version": "\u05d2\u05d9\u05e8\u05e1\u05d4", "YYYY-MM-DD HH:mm": "YYYY-MM-DD HH:mm", "Attempt to reconnect": "\u05e0\u05e1\u05d9\u05d5\u05df \u05d7\u05d9\u05d1\u05d5\u05e8 \u05de\u05d7\u05d3\u05e9", "Streaming done": "\u05d4\u05e9\u05d9\u05d3\u05d5\u05e8 \u05d4\u05e1\u05ea\u05d9\u05d9\u05dd", "violet": "\u05e1\u05d2\u05d5\u05dc", "Print": "\u05d4\u05d3\u05e4\u05e1\u05d4", "Layer count": "\u05de\u05e1\u05e4\u05e8 \u05e9\u05db\u05d1\u05d5\u05ea", "OctoPrint Settings": "\u05d4\u05d2\u05d3\u05e8\u05d5\u05ea \u05d0\u05d5\u05e7\u05d8\u05d5\u05e4\u05e8\u05d9\u05e0\u05d8", "Are you sure?": "\u05d4\u05d0\u05dd \u05d0\u05ea/\u05d4 \u05d1\u05d8\u05d5\u05d7?", "blue": "\u05db\u05d7\u05d5\u05dc", "Printer": "\u05de\u05d3\u05e4\u05e1\u05ea", "Delete Profile": "", "Tool": "\u05db\u05dc\u05d9", "Settings": "\u05d4\u05d2\u05d3\u05e8\u05d5\u05ea", "Circular": "\u05de\u05e2\u05d2\u05dc\u05d9", "Path to FFMPEG": "\u05e0\u05ea\u05d9\u05d1 \u05e2\u05d1\u05d5\u05e8 FFMPEG", "Upload to SD": "\u05d4\u05e2\u05dc\u05d0\u05d4 \u05dc\u05db\u05e8\u05d8\u05d9\u05e1 SD", "The command \"%(command)s\" could not be executed.": "\u05dc\u05d0 \u05e0\u05d9\u05ea\u05df \u05dc\u05d1\u05e6\u05e2 \u05d0\u05ea \u05d4\u05e4\u05e7\u05d5\u05d3\u05d4 \"%(command)s\".", "Select a slicing profile...": "", "Wait for start on connect": "\u05d4\u05de\u05ea\u05df \u05e2\u05d1\u05d5\u05e8 start \u05d1\u05d7\u05d9\u05d1\u05d5\u05e8", "Sync with job progress": "\u05e1\u05e0\u05db\u05e8\u05df \u05e2\u05dd \u05d4\u05e2\u05d1\u05d5\u05d3\u05d4", "Calculating...": "", "Total filament used": "\u05e1\u05da \u05d4\u05db\u05dc \u05e1\u05d9\u05d1 \u05d7\u05d5\u05de\u05e8 \u05e9\u05e0\u05d3\u05e8\u05e9", "red": "\u05d0\u05d3\u05d5\u05dd", "Save as default": "\u05e9\u05de\u05d5\u05e8 \u05db\u05d1\u05e8\u05d9\u05ea \u05de\u05d7\u05d3\u05dc", "Slicing ...": "\u05e4\u05d5\u05e8\u05e1...", "Last Print Time": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05d0\u05d7\u05e8\u05d5\u05df", "Target": "\u05de\u05d8\u05e8\u05d4", "Add Profile...": "", "Streaming ...": "\u05de\u05e9\u05d3\u05e8 ...", "Logout successful": "\u05db\u05e0\u05d9\u05e1\u05d4 \u05d4\u05ea\u05d1\u05e6\u05e2\u05d4 \u05d1\u05d4\u05e6\u05dc\u05d7\u05d4", "Now rendering timelapse %(movie_basename)s": "\u05db\u05e2\u05ea \u05de\u05e8\u05e0\u05d3\u05e8 timelapse %(movie_basename)s", "Documentation": "\u05ea\u05d9\u05e2\u05d5\u05d3", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "\u05d4\u05e2\u05dc\u05d0\u05d4", "ascending": "\u05e1\u05d3\u05e8 \u05e2\u05d5\u05dc\u05d4", "Model size": "\u05d2\u05d5\u05d3\u05dc \u05de\u05d5\u05d3\u05dc", "Temperatures": "\u05d8\u05de\u05e4\u05e8\u05d8\u05d5\u05e8\u05d5\u05ea", "Timed": "\u05de\u05ea\u05d5\u05d6\u05de\u05df", "Edit user \"%(user)s\"": "\u05e2\u05e8\u05d5\u05da \u05de\u05e9\u05ea\u05de\u05e9 \"%(user)s\"", "Identifier": "", "Release SD card": "\u05de\u05e9\u05d7\u05d6\u05e8 \u05db\u05e8\u05d8\u05d9\u05e1 SD", "Server is offline": "\u05e9\u05e8\u05ea \u05dc\u05d0 \u05de\u05d7\u05d5\u05d1\u05e8", "Log communication to serial.log (might negatively impact performance)": "\u05e9\u05de\u05d5\u05e8 \u05d9\u05d5\u05de\u05df \u05ea\u05e7\u05e9\u05d5\u05e8\u05ea \u05e2\u05dc serial.log (\u05e4\u05e2\u05d5\u05dc\u05d4 \u05d6\u05d5 \u05e2\u05dc\u05d5\u05dc\u05d4 \u05dc\u05d4\u05e9\u05e4\u05d9\u05e2 \u05d1\u05e6\u05d5\u05e8\u05d4 \u05e9\u05dc\u05d9\u05dc\u05d9\u05ea \u05e2\u05dc \u05d1\u05d9\u05e6\u05d5\u05e2\u05d9\u05dd)", "Sort by upload date": "\u05de\u05d9\u05d9\u05df \u05dc\u05e4\u05d9 \u05d6\u05de\u05df \u05d4\u05e2\u05dc\u05d0\u05d4", "Change Password": "\u05d4\u05d7\u05dc\u05e3 \u05e1\u05d9\u05e1\u05de\u05d4", "Logs": "\u05dc\u05d5\u05d2\u05d9\u05dd", "Hotend": "\u05e7\u05e6\u05d4 \u05d7\u05dd", "Show retracts": "\u05d4\u05e6\u05d2 \u05e0\u05e1\u05d9\u05d2\u05d5\u05ea", "Keep Access Control Enabled": "\u05e9\u05de\u05d5\u05e8 \u05e2\u05dc \u05dc\u05d5\u05d7 \u05d1\u05e7\u05e8\u05d4 \u05de\u05d5\u05e4\u05e2\u05dc", "Upload locally": "\u05d4\u05e2\u05dc\u05d0\u05d4 \u05de\u05e7\u05d5\u05de\u05d9\u05ea", "Do nothing": "", "Paused": "\u05d1\u05d4\u05e4\u05e1\u05e7\u05d4", "Continue": "\u05d4\u05de\u05e9\u05da", "Edit Printer Profile \"%(name)s\"": "", "The command \"%(command)s\" executed successfully": "\u05d4\u05e4\u05e7\u05d5\u05d3\u05d4 \"%(command)s\" \u05d4\u05ea\u05d1\u05e6\u05e2\u05d4 \u05d1\u05d4\u05e6\u05dc\u05d7\u05d4", "Features": "\u05e4\u05d9\u05e6'\u05e8\u05d9\u05dd", "Download": "\u05d4\u05d5\u05e8\u05d3", "GCode Viewer": "\u05de\u05e6\u05d9\u05d2 Gcode", "Also show previous layer": "\u05d0\u05e4\u05e9\u05e8 \u05d4\u05e6\u05d2\u05d4 \u05e9\u05dc \u05e9\u05db\u05d1\u05d4 \u05e7\u05d5\u05d3\u05de\u05ea", "Enable OctoPrint watermark in timelapse movies": "\u05d4\u05d5\u05e1\u05e3 \u05e1\u05d9\u05de\u05df \u05de\u05d9\u05dd \u05e9\u05dc \u05d0\u05d5\u05e7\u05d8\u05d5\u05e4\u05e8\u05d9\u05e0\u05d8 \u05e2\u05d1\u05d5\u05e8 \u05e1\u05e8\u05d8\u05d5\u05e0\u05d9\u05dd", "Repetier": "Repetier", "Login successful": "\u05db\u05e0\u05d9\u05e1\u05d4 \u05dc\u05de\u05e2\u05e8\u05db\u05ea \u05d4\u05ea\u05d1\u05e6\u05e2\u05d4 \u05d1\u05d4\u05e6\u05dc\u05d7\u05d4", "Finished Timelapses": "Timelapses \u05e9\u05d4\u05e1\u05ea\u05d9\u05d9\u05de\u05d5", "Pause": "\u05d4\u05e4\u05e1\u05e7", "GCode Filename": "", "Access Control": "\u05d1\u05e7\u05e8\u05ea \u05d2\u05d9\u05e9\u05d4", "Start printing": "", "Swallow the first \"ok\" after a resend response": "\u05dc\u05d1\u05dc\u05d5\u05e2 \u05d0\u05ea \u05d4-\"ok\" \u05d4\u05e8\u05d0\u05e9\u05d5\u05df \u05d0\u05d7\u05e8\u05d9 \u05e9\u05e0\u05e9\u05dc\u05d7\u05d4 \u05de\u05d7\u05d3\u05e9\u05d4 \u05ea\u05d2\u05d5\u05d1\u05d4", "Analyzing...": "\u05de\u05e0\u05ea\u05d7 \u05e0\u05ea\u05d5\u05e0\u05d9\u05dd ...", "just now": "\u05d6\u05d4 \u05d4\u05e8\u05d2\u05e2", "Operational": "\u05d0\u05d5\u05e4\u05e6\u05d9\u05d5\u05e0\u05dc\u05d9", "Send a checksum with every command": "\u05d4\u05de\u05ea\u05df \u05e2\u05d1\u05d5\u05e8 \u05e1\u05d9\u05db\u05d5\u05dd \u05d1\u05d9\u05e7\u05d5\u05e8\u05ea (checksum) \u05e2\u05d1\u05d5\u05e8 \u05db\u05dc \u05e4\u05e7\u05d5\u05d3\u05d4", "Autodetection timeout": "\u05d6\u05d4\u05d5\u05d9 timeout \u05d0\u05d5\u05d8\u05de\u05d8\u05d9", "Connecting": "\u05de\u05ea\u05d7\u05d1\u05e8", "Free": "\u05e4\u05e0\u05d5\u05d9", "Closed": "\u05e1\u05d2\u05d5\u05e8", "Refresh SD files": "\u05de\u05e8\u05e2\u05e0\u05df \u05e7\u05d1\u05e6\u05d9 SD", "Flip webcam vertically": "\u05d4\u05e4\u05d5\u05da \u05ea\u05de\u05d5\u05e0\u05ea \u05de\u05e6\u05dc\u05de\u05d4 \u05d0\u05e0\u05db\u05d9\u05ea", "Starts the print job": "", "Model": "", "Filament": "\u05e1\u05d9\u05d1 \u05d7\u05d5\u05de\u05e8", "Could not slice %(stl)s to %(gcode)s: %(reason)s": "\u05dc\u05d0 \u05d4\u05d9\u05d4 \u05e0\u05d9\u05ea\u05df \u05dc\u05e4\u05e8\u05d5\u05e1 %(stl)s \u05d0\u05dc %(gcode)s: %(reason)s", "Baudrate": "\u05e7\u05e6\u05d1 \u05d1\u05d0\u05d5\u05d3 (Baudrate)", "Snapshot URL": "\u05db\u05ea\u05d5\u05d1\u05ea \u05e9\u05d9\u05d3\u05d5\u05e8 \u05ea\u05de\u05d5\u05e0\u05d4", "Detecting baudrate": "\u05de\u05d0\u05ea\u05e8 \u05de\u05d4\u05d9\u05e8\u05d5\u05ea \u05d4\u05e2\u05d1\u05e8\u05d4", "Date": "\u05ea\u05d0\u05e8\u05d9\u05da", "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds": "\u05e9\u05d5\u05d3\u05e8 %(local)s \u05d0\u05dc%(remote)s \u05e2\u05dc SD, \u05dc\u05e7\u05d7 %(time).2f \u05e9\u05e0\u05d9\u05d5\u05ea", "Show moves": "\u05d4\u05e6\u05d2 \u05ea\u05d6\u05d5\u05d6\u05d5\u05ea", "Select a printer profile...": "", "Detecting serial port": "\u05de\u05d0\u05ea\u05e8 \u05d9\u05e6\u05d9\u05e8\u05d4 \u05d8\u05d5\u05e8\u05d9\u05ea", "New Password": "\u05e1\u05d9\u05e1\u05de\u05d4 \u05d7\u05d3\u05e9\u05d4", "Title": "\u05db\u05d5\u05ea\u05e8\u05ea", "Logout": "\u05d4\u05ea\u05e0\u05ea\u05e7\u05d5\u05ea", "Offset": "\u05d4\u05e1\u05d8", "Analyzed": "\u05e0\u05ea\u05d5\u05e0\u05d9\u05dd \u05e0\u05d5\u05ea\u05d7\u05d5", "Auto-connect on server startup": "\u05d7\u05d9\u05d1\u05d5\u05e8 \u05de\u05d7\u05d3\u05e9 \u05e2\u05dd \u05e2\u05dc\u05d9\u05d9\u05ea \u05d4\u05e9\u05e8\u05ea", "E": "E", "Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s": "", "Restart": "\u05d0\u05ea\u05d7\u05d5\u05dc", "Search...": "\u05d7\u05d9\u05e4\u05d5\u05e9...", "Slicing failed": "\u05e4\u05e8\u05d9\u05e1\u05d4 \u05e0\u05db\u05e9\u05dc\u05d4", "Actual": "\u05e0\u05d5\u05db\u05d7\u05d9", "Active": "\u05e4\u05e2\u05d9\u05dc", "SD status timeout": "\u05de\u05e6\u05d1 SD \u05d1-timeout", "Creation date": "\u05ea\u05d0\u05e8\u05d9\u05da \u05d9\u05e6\u05d9\u05e8\u05d4", "Hint: You can also drag and drop files on this page to upload them.": "\u05d8\u05d9\u05e4: \u05e0\u05d9\u05ea\u05df \u05dc\u05d2\u05e8\u05d5\u05e8 \u05e7\u05d1\u05e6\u05d9\u05dd \u05d0\u05dc \u05d3\u05e3 \u05d6\u05d4 \u05db\u05d3\u05d9 \u05dc\u05d4\u05e2\u05dc\u05d5\u05ea \u05d0\u05d5\u05ea\u05dd", "Restarts the print job from the beginning": "", "Interval": "\u05d0\u05d9\u05e0\u05d8\u05e8\u05d5\u05d5\u05dc", "N/A": "\u05dc\u05d0 \u05d6\u05de\u05d9\u05df", "Bed": "\u05de\u05d9\u05d8\u05d4", "Auto-connect to printer on server start": "\u05d4\u05ea\u05d7\u05d1\u05e8 \u05de\u05d7\u05d3\u05e9 \u05dc\u05de\u05d3\u05e4\u05e1\u05ea \u05e2\u05dd \u05d4\u05e2\u05dc\u05d9\u05d9\u05d4 \u05e9\u05dc \u05d4\u05e9\u05e8\u05ea", "orange": "\u05db\u05ea\u05d5\u05dd", "Connection": "\u05d7\u05d9\u05d1\u05d5\u05e8", "Error": "\u05e9\u05d2\u05d9\u05d0\u05d4", "On Z Change": "\u05e9\u05d9\u05e0\u05d5\u05d9 \u05e6\u05d9\u05e8 Z", "Timelapse post roll (in rendered seconds)": "\u05e2\u05d9\u05d1\u05d5\u05d3 Timelapse (\u05d1\u05e9\u05e0\u05d9\u05d5\u05ea \u05e9\u05e8\u05d5\u05e0\u05d3\u05e8\u05d5)", "Z": "Z", "Edit Profile": "", "Are you sure you want to proceed?": "\u05d4\u05d0\u05dd \u05d1\u05d0\u05de\u05ea \u05dc\u05d4\u05de\u05e9\u05d9\u05da?", "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!": "\u05d0\u05dd \u05d1\u05e8\u05e6\u05d5\u05da \u05dc\u05d1\u05d8\u05dc \u05d0\u05ea \u05d4\u05d4\u05e8\u05e9\u05d0\u05d5\u05ea \u05d2\u05d9\u05e9\u05d4 \u05d5\u05d2\u05dd \u05d4\u05d4\u05ea\u05e7\u05e0\u05d4 \u05e9\u05dc \u05d0\u05d5\u05e7\u05d8\u05d5\u05e4\u05e8\u05d9\u05e0\u05d8 \u05e0\u05d9\u05ea\u05e0\u05ea \u05dc\u05d2\u05d9\u05e9\u05d4 \u05d3\u05e8\u05da \u05d4\u05d0\u05d9\u05e0\u05d8\u05e8\u05e0\u05d8, \u05d0\u05d6 \u05db\u05dc \u05d0\u05d7\u05d3 \u05d9\u05d5\u05db\u05dc \u05dc\u05e9\u05dc\u05d5\u05d8 \u05e2\u05dc \u05d4\u05de\u05d3\u05e4\u05e1\u05ea \u05e9\u05dc\u05da, \u05d6\u05d4 \u05db\u05d5\u05dc\u05dc \u05d0\u05e0\u05e9\u05d9\u05dd \u05e8\u05e2\u05d9\u05dd!", "Load": "\u05d8\u05e2\u05d9\u05e0\u05d4", "Set": "\u05e7\u05d1\u05e2", "The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below.": "\u05e0\u05e8\u05d0\u05d4 \u05e9\u05d4\u05e9\u05e8\u05ea \u05dc\u05d0 \u05de\u05d7\u05d5\u05e8\u05d1, \u05d0\u05d5 \u05dc\u05e4\u05d7\u05d5\u05ea \u05d0\u05e0\u05d9 \u05dc\u05d0 \u05de\u05e6\u05dc\u05d9\u05d7 \u05dc\u05e7\u05d1\u05dc \u05db\u05dc \u05ea\u05d2\u05d5\u05d1\u05d4 \u05de\u05de\u05e0\u05d5. \u05d4\u05d7\u05d9\u05d1\u05d5\u05e8 \u05d4\u05d0\u05d5\u05d8\u05d5\u05de\u05d0\u05d8\u05d9 \u05e0\u05db\u05e9\u05dc, \u05d0\u05d1\u05dc \u05e0\u05d9\u05ea\u05df \u05d2\u05dd \u05dc\u05e0\u05e1\u05d5\u05ea \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05de\u05d7\u05d3\u05e9 \u05e2\u05dd \u05d4\u05db\u05e4\u05ea\u05d5\u05e8 \u05dc\u05d4\u05dc\u05df.", "Zoom in on model": "\u05d6\u05d5\u05dd \u05dc\u05ea\u05d5\u05da \u05de\u05d5\u05d3\u05dc", "Pauses the print job": "", "After slicing...": "", "Saving ...": "\u05e9\u05d5\u05de\u05e8 ...", "RegExp": "\u05d1\u05d9\u05d8\u05d5\u05d9 \u05e8\u05d2\u05d5\u05dc\u05e8\u05d9", "Watched Folder": "\u05ea\u05e7\u05d9\u05d9\u05d4 \u05e9\u05e0\u05e6\u05e4\u05ea\u05d4", "General": "\u05db\u05dc\u05dc\u05d9", "Temperature timeout": "\u05d8\u05de\u05e4\u05e8\u05d8\u05d5\u05e8\u05d4 timeout", "Set as default profile": "", "Fans on": "\u05de\u05d0\u05d5\u05d5\u05e8\u05e8 \u05d3\u05dc\u05d5\u05e7", "Abort": "\u05d1\u05d9\u05d8\u05d5\u05dc", "Enable SD support": "\u05d4\u05e4\u05e2\u05dc \u05ea\u05de\u05d9\u05db\u05d4 \u05d1-SD", "Connect": "\u05d4\u05ea\u05d7\u05d1\u05e8", "Cancel": "\u05d1\u05d9\u05d8\u05d5\u05dc", "visited": "\u05d1\u05bc\u05b4\u05e7\u05bc\u05b5\u05e8", "Warning": "\u05d0\u05d6\u05d4\u05e8\u05d4", "Loading...": "\u05d8\u05d5\u05e2\u05df", "Current API Key": "\u05de\u05e4\u05ea\u05d7 API \u05e0\u05d5\u05db\u05d7\u05d9", "Size": "\u05d2\u05d5\u05d3\u05dc", "Communication timeout": "\u05d7\u05d9\u05d1\u05d5\u05e8 \u05dc\u05d0 \u05e2\u05d5\u05d1\u05d3 \u05e2\u05e7\u05d1 timeout", "Modification date": "\u05ea\u05d0\u05e8\u05d9\u05da \u05e9\u05d9\u05e0\u05d5\u05d9", "Slice": "", "Change password": "\u05e9\u05d9\u05e0\u05d5\u05d9 \u05e1\u05d9\u05e1\u05de\u05d4", "Layer number": "\u05e9\u05db\u05d1\u05d4 \u05de\u05e1\u05e4\u05e8", "Cancels the print job": "", "This will restart the print job from the beginning.": "\u05e4\u05e2\u05d5\u05dc\u05d4 \u05d6\u05d5 \u05ea\u05ea\u05d7\u05d9\u05dc \u05de\u05d7\u05d3\u05e9 \u05d0\u05ea \u05d4\u05d4\u05d3\u05e4\u05e1\u05d4 \u05de\u05d4\u05ea\u05d7\u05dc\u05d4", "Sort by": "\u05de\u05d9\u05d9\u05df \u05dc\u05e4\u05d9", "Login failed": "\u05db\u05e0\u05d9\u05e1\u05d4 \u05dc\u05de\u05e2\u05e8\u05db\u05ea \u05e0\u05db\u05e9\u05dc\u05d4", "Confirm": "\u05d0\u05d9\u05e9\u05d5\u05e8", "Repeat Password": "\u05d7\u05d6\u05d5\u05e8 \u05e2\u05dc \u05e1\u05d9\u05e1\u05de\u05d4", "Terminal": "\u05de\u05e1\u05d5\u05e3", "Autoscroll": "\u05d2\u05dc\u05d9\u05dc\u05d4 \u05d0\u05d5\u05d8\u05d5\u05de\u05d0\u05d8\u05d9\u05ea", "Print time for layer": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05e2\u05d1\u05d5\u05e8 \u05e9\u05db\u05d1\u05d4", "Disable Access Control": "\u05d1\u05d9\u05d8\u05d5\u05dc \u05dc\u05d5\u05d7 \u05d1\u05e7\u05e8\u05d4", "Configure Access Control": "\u05d4\u05d2\u05d3\u05e8\u05d5\u05ea \u05dc\u05d5\u05d7 \u05d1\u05e7\u05e8\u05d4", "Timelapse Configuration": "\u05d4\u05d2\u05d3\u05e8\u05d5\u05ea timelapse", "Retract": "\u05e0\u05e1\u05d5\u05d2", "Printer Profile": "", "Offline": "\u05dc\u05d0 \u05de\u05d7\u05d5\u05d1\u05e8", "API Key": "\u05de\u05e4\u05ea\u05d7 API", "Homepage": "\u05d3\u05e3 \u05d1\u05d9\u05ea", "Estimated Print Time": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05de\u05d5\u05e2\u05e8\u05da", "Folders": "\u05ea\u05d9\u05e7\u05d9\u05d5\u05ea", "Select a slicer...": "", "Printer Profiles": "", "Slicing %(filename)s": "", "Extruder Offsets": "\u05d4\u05e1\u05d8 \u05d0\u05e7\u05e1\u05d8\u05e8\u05d5\u05d3\u05e8", "min": "\u05d3\u05e7\u05d5'", "Only show STL files": "", "Slicing ... (%(percentage)d%%)": "", "Connection timeout": "\u05d7\u05d9\u05e9\u05d5\u05d1 \u05e4\u05e1\u05e7, timeout", "Save config": "\u05e9\u05de\u05d5\u05e8 \u05d4\u05d2\u05d3\u05e8\u05d5\u05ea", "Center viewport on model": "\u05de\u05e8\u05db\u05d6 \u05ea\u05e6\u05d5\u05d2\u05d4 \u05e2\u05dc \u05de\u05d5\u05d3\u05dc", "User unknown or wrong password": "\u05e9\u05dd \u05de\u05e9\u05ea\u05de\u05e9 \u05dc\u05d0 \u05de\u05d5\u05db\u05e8, \u05d0\u05d5 \u05e9\u05d2\u05d9\u05d0\u05d4 \u05d1\u05e1\u05d9\u05e1\u05de\u05d4", "Volume": "", "default": "\u05d1\u05e8\u05d9\u05ea \u05de\u05d7\u05d3\u05dc", "Heated Bed": "", "Appearance": "\u05de\u05e8\u05d0\u05d4", "Enable": "\u05d0\u05e4\u05e9\u05e8", "Uploading ...": "\u05de\u05e2\u05dc\u05d4 ...", "Logs Folder": "\u05ea\u05e7\u05d9\u05d9\u05ea \u05dc\u05d5\u05d2\u05d9\u05dd", "

\n Please read the following, it is very important for your printer's health!\n

\n

\n OctoPrint by default now ships with Access Control enabled, meaning you won't be able to do anything with the\n printer unless you login first as a configured user. This is to prevent strangers - possibly with\n malicious intent - to gain access to your printer via the internet or another untrustworthy network\n and using it in such a way that it is damaged or worse (i.e. causes a fire).\n

\n

\n It looks like you haven't configured access control yet. Please set up an username and password for the\n initial administrator account who will have full access to both the printer and OctoPrint's settings, then click\n on \"Keep Access Control Enabled\":\n

": "

\n \u05d9\u05e9 \u05dc\u05e7\u05e8\u05d5\u05d0 \u05d0\u05ea \u05d4\u05de\u05d9\u05d3\u05d4 \u05d4\u05d1\u05d0, \u05d4\u05d5\u05d0 \u05d7\u05e9\u05d5\u05d1 \u05dc\u05d1\u05e8\u05d9\u05d0\u05d5\u05ea \u05d4\u05de\u05d3\u05e4\u05e1\u05ea \u05e9\u05dc\u05da!\n

\n

\n \u05d0\u05d5\u05e7\u05d8\u05d5\u05e4\u05e8\u05d9\u05e0\u05d8 \u05d1\u05d1\u05e8\u05d9\u05ea \u05de\u05d7\u05d3\u05dc \u05de\u05d2\u05d9\u05e2 \u05d4\u05dd \u05d1\u05e7\u05e8\u05ea \u05d2\u05d9\u05e9\u05d4 \u05de\u05d5\u05e4\u05e2\u05dc\u05ea, \u05db\u05dc\u05d5\u05de\u05e8 \u05dc\u05d0 \u05d9\u05d4\u05d9\u05d4 \u05e0\u05d9\u05ea\u05df \u05dc\u05d1\u05e6\u05e2 \u05d3\u05d1\u05e8 \u05e2\u05dd \u05d4\u05de\u05d3\u05e4\u05e1\u05ea\n \u05d0\u05dc\u05d4 \u05d0\u05dd \u05d4\u05db\u05e0\u05d9\u05e1\u05d4 \u05d4\u05e8\u05d0\u05e9\u05d5\u05e0\u05d9\u05ea \u05de\u05d5\u05d2\u05d3\u05e8\u05ea \u05e2\u05dd \u05d4\u05de\u05e9\u05ea\u05de\u05e9. \u05d6\u05d0\u05ea \u05db\u05d3\u05d9 \u05dc\u05de\u05e0\u05d5\u05e2 \u05de\u05d0\u05e0\u05e9\u05d9\u05dd \u05d6\u05e8\u05d9\u05dd - \u05db\u05db\u05dc \u05d4\u05e0\u05e8\u05d0\u05d4 \u05e2\u05dd\n \u05de\u05d8\u05e8\u05d5\u05ea \u05d6\u05d3\u05d5\u05df - \u05dc\u05e9\u05d9\u05d2 \u05d2\u05d9\u05e9\u05d4 \u05dc\u05de\u05d3\u05e4\u05e1\u05ea \u05e9\u05dc\u05da \u05d3\u05e8\u05da \u05d4\u05d0\u05d9\u05e0\u05d8\u05e8\u05e0\u05d8 \u05d0\u05d5 \u05e8\u05e9\u05ea \u05dc\u05d0 \u05de\u05d0\u05d5\u05d1\u05d8\u05d7\u05ea\n \u05d5\u05e9\u05d9\u05de\u05d5\u05e9 \u05d1\u05de\u05d3\u05e4\u05e1\u05ea \u05d1\u05d3\u05e8\u05da \u05e9\u05ea\u05d2\u05e8\u05d5\u05dd \u05e0\u05d6\u05e7 \u05dc\u05de\u05d3\u05e4\u05e1\u05ea, \u05d0\u05d5 \u05d2\u05e8\u05d5\u05e2 \u05de\u05db\u05da (\u05dc\u05de\u05e9\u05dc, \u05d2\u05e8\u05de\u05d4 \u05e9\u05dc \u05e9\u05e8\u05d9\u05e4\u05d4)..\n

\n

\n \u05e0\u05e8\u05d0\u05d4 \u05e9\u05e2\u05d3\u05d9\u05df \u05dc\u05d0 \u05d4\u05d5\u05d2\u05d3\u05e8\u05d4 \u05d1\u05e7\u05e8\u05ea \u05d2\u05d9\u05e9\u05d4. \u05d0\u05e0\u05d0 \u05d4\u05d2\u05d3\u05e8 \u05e9\u05dd \u05de\u05e9\u05ea\u05de\u05e9 \u05d5\u05e1\u05d9\u05e1\u05de\u05d4 \u05e2\u05d1\u05d5\u05e8\n \u05de\u05e0\u05d4\u05dc \u05d4\u05de\u05e2\u05e8\u05db\u05ea \u05d4\u05e8\u05d0\u05e9\u05d5\u05df \u05e9\u05d9\u05d4\u05d9\u05d4 \u05d1\u05e2\u05dc \u05d2\u05d9\u05e9\u05d4 \u05dc\u05de\u05d3\u05e4\u05e1\u05ea \u05d5\u05d4\u05d4\u05d2\u05d3\u05e8\u05d5\u05ea \u05e9\u05dc \u05d0\u05d5\u05e7\u05d8\u05d5\u05e4\u05e8\u05d9\u05e0\u05d8,\n \u05dc\u05d0\u05d7\u05e8 \u05de\u05db\u05df \u05d9\u05e9 \u05dc\u05dc\u05d7\u05d5\u05e5 \u05e2\u05dc \"\u05e9\u05de\u05d5\u05e8 \u05e2\u05dc \u05dc\u05d5\u05d7 \u05d1\u05e7\u05e8\u05d4 \u05de\u05d5\u05e4\u05e2\u05dc\":\n

", "Hide successfully printed files": "\u05d4\u05e1\u05ea\u05e8 \u05e7\u05d1\u05e6\u05d9\u05dd \u05e9\u05d4\u05d5\u05d3\u05e4\u05e1\u05d5 \u05d1\u05d4\u05e6\u05dc\u05d7\u05d4", "Username": "\u05e9\u05dd \u05de\u05e9\u05ea\u05de\u05e9", "Select Tool...": "\u05db\u05dc\u05d9 \u05d1\u05d7\u05d9\u05e8\u05d4", "Off": "\u05db\u05d1\u05d5\u05d9", "Name": "\u05e9\u05dd", "Bugs and Requests": "\u05d1\u05d0\u05d2\u05d9\u05dd \u05d5\u05d1\u05e7\u05e9\u05d5\u05ea", "Approx. Total Print Time": "\u05d6\u05de\u05df \u05d4\u05d3\u05e4\u05e1\u05d4 \u05e1\u05d5\u05e4\u05d9 \u05de\u05d5\u05e2\u05e8\u05da", "Admin": "\u05de\u05e0\u05d4\u05dc", "

\n Note: In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't\n need Access Control for other reasons, you may alternatively disable Access Control. You should only\n do this if you are absolutely certain that only people you know and trust will be able to connect to it.\n

\n

\n Do NOT underestimate the risk of an unsecured access from the internet to your printer!\n

": "

\n \u05d4\u05e2\u05e8\u05d4: \u05d1\u05de\u05e7\u05e8\u05d4 \u05e9\u05d4\u05d4\u05ea\u05e7\u05e0\u05d4 \u05e9\u05dc \u05d0\u05d5\u05e7\u05d8\u05d5\u05e4\u05e8\u05d9\u05e0\u05d8 \u05e0\u05d9\u05ea\u05e0\u05ea \u05dc\u05d2\u05d9\u05e9\u05d4 \u05de\u05ea\u05d5\u05da \u05e8\u05e9\u05ea \u05dc\u05d0 \u05de\u05d0\u05d5\u05d1\u05d8\u05d7\u05ea, \u05d5\u05d0\u05d9\u05df \u05e6\u05d5\u05e8\u05da\n \u05d1\u05e0\u05d9\u05d4\u05d5\u05dc \u05d4\u05e8\u05e9\u05d0\u05d5\u05ea \u05d2\u05d9\u05e9\u05d4 \u05de\u05e1\u05d9\u05d1\u05d5\u05ea \u05d0\u05d7\u05e8\u05d5\u05ea, \u05e0\u05d9\u05ea\u05df \u05dc\u05d1\u05d8\u05dc \u05d0\u05ea \u05d4\u05d4\u05e9\u05d0\u05d5\u05ea \u05e0\u05d9\u05d4\u05d5\u05dc \u05d4\u05d2\u05d9\u05e9\u05d4. \u05d0\u05d1\u05dc \u05d9\u05e9 \u05dc\u05e2\u05e9\u05d5\u05ea \u05d6\u05d0\u05ea \u05e8\u05e7\n \u05d0\u05dd \u05d1\u05d8\u05d5\u05d7 \u05dc\u05d7\u05dc\u05d5\u05d8\u05d9\u05df \u05e9\u05e8\u05e7 \u05d0\u05e0\u05e9\u05d9\u05dd \u05e9\u05de\u05db\u05d9\u05e8\u05d9\u05dd \u05d5\u05e1\u05d5\u05de\u05db\u05d9\u05dd \u05e2\u05dc\u05d9\u05d4\u05dd \u05d9\u05d4\u05d9\u05d5 \u05d1\u05e2\u05dc\u05d9 \u05d9\u05db\u05d5\u05dc\u05ea \u05dc\u05d4\u05ea\u05d7\u05d1\u05e8 \u05dc\u05de\u05d3\u05e4\u05e1\u05ea.\n

\n

\n \u05e0\u05d0 \u05dc\u05d0 \u05dc\u05d6\u05dc\u05d6\u05dc \u05d1\u05e1\u05d9\u05db\u05d5\u05df \u05e9\u05dc \u05e8\u05e9\u05ea\u05d5\u05ea \u05dc\u05d0 \u05de\u05d0\u05d5\u05d1\u05d8\u05d7\u05d5\u05ea \u05de\u05d4\u05d0\u05d9\u05e0\u05d8\u05e8\u05e0\u05d8 \u05dc\u05de\u05d3\u05e4\u05e1\u05ea \u05e9\u05dc\u05da!!\n

", "Timelapse": "Timelapse", "QR Code": "", "Only show GCode files": "", "Remove": "\u05d4\u05e1\u05e8", "Reload": "\u05e8\u05e2\u05e0\u05df", "Printing": "\u05de\u05d3\u05e4\u05d9\u05e1", "printed": "", "Y": "Y", "Fans off": "\u05de\u05d0\u05d5\u05d5\u05e8\u05e8 \u05db\u05d1\u05d5\u05d9", "Login": "\u05db\u05e0\u05d9\u05e1\u05d4", "Rectangular": "", "Timelapse ready": "Timelapse \u05de\u05d5\u05db\u05df", "Timelapse Mode": "\u05de\u05e6\u05d1 timelapse", "Timelapse Folder": "\u05ea\u05e7\u05d9\u05d9\u05ea timelapse", "Extruder": "\u05d0\u05e7\u05e1\u05d8\u05e8\u05d5\u05d3\u05e8", "Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and slicing support is enabled and configured.": "\u05dc\u05d0 \u05d4\u05d9\u05d4 \u05e0\u05d9\u05ea\u05df \u05dc\u05d4\u05e2\u05dc\u05d5\u05ea \u05e7\u05d5\u05d1\u05e5. \u05d9\u05e9 \u05d5\u05d5\u05d3\u05d0 \u05e9\u05d6\u05d4 \u05d4\u05d5\u05d0 \u05e7\u05d5\u05d1\u05e5 GCODE \u05d5\u05e9\u05e1\u05d9\u05d5\u05de\u05ea \u05d4\u05e7\u05d5\u05d1\u05e5 \u05d4\u05d9\u05d0 \".gcode\" \u05d0\u05d5 \".gco\". \u05d0\u05d5 \u05e9\u05d4\u05e7\u05d5\u05d1\u05e5 \u05d4\u05d5\u05d0 STL \u05e2\u05dd \u05d4\u05e1\u05d9\u05d5\u05de\u05ea \".stl\" \u05db\u05d0\u05e9\u05e8 \u05e4\u05e8\u05d9\u05e1\u05d4 \u05de\u05ea\u05de\u05db\u05ea, \u05de\u05d5\u05e4\u05e2\u05dc\u05ea \u05d5\u05de\u05d5\u05d2\u05d3\u05e8\u05ea.", "Printed": "\u05d4\u05d5\u05d3\u05e4\u05e1", "SD not initialized": "SD \u05dc\u05d0 \u05de\u05d0\u05d5\u05ea\u05d7\u05dc", "Update User": "\u05e2\u05d3\u05db\u05df \u05de\u05e9\u05ea\u05de\u05e9", "off": "\u05db\u05d9\u05d1\u05d5\u05d9", "Serial Port": "\u05d9\u05e6\u05d9\u05d0\u05d4 \u05d8\u05d5\u05e8\u05d9\u05ea", "Flip webcam horizontally": "\u05d4\u05e4\u05d5\u05da \u05ea\u05de\u05d5\u05e0\u05ea \u05de\u05e6\u05dc\u05de\u05d4 \u05d0\u05d5\u05e4\u05e7\u05d9\u05ea", "Resumes the print job": "", "Transfering file to SD": "\u05de\u05e2\u05d1\u05d9\u05e8 \u05e7\u05d5\u05d1\u05e5 \u05dc-SD", "OctoPrint": "\u05d0\u05d5\u05e7\u05d8\u05d5\u05e4\u05e8\u05d9\u05e0\u05d8", "Layer height": "\u05d2\u05d5\u05d1\u05d4 \u05e9\u05db\u05d1\u05d4", "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds": "\u05e4\u05e8\u05d9\u05e1\u05d4 \u05e9\u05dc %(stl)s \u05d0\u05dc %(gcode)s, \u05dc\u05e7\u05d7 %(time).2f \u05e9\u05e0\u05d9\u05d5\u05ea", "Extrude": "\u05d4\u05d5\u05e6\u05d0 \u05e1\u05d9\u05d1 \u05d7\u05d5\u05de\u05e8", "green": "\u05d9\u05e8\u05d5\u05e7", "File": "\u05e7\u05d5\u05d1\u05e5", "You are now logged in as \"%(username)s\"": "\u05de\u05d7\u05d5\u05d1\u05e8 \u05db\u05e2\u05ea \u05d1\u05ea\u05d5\u05e8 \"%(username)s\"", "Axis": "\u05e6\u05d9\u05e8\u05d9\u05dd", "Filament used by layer": "\u05e1\u05d9\u05d1 \u05d7\u05d5\u05de\u05e8 \u05e9\u05e0\u05d3\u05e9 \u05d1\u05e9\u05db\u05d1\u05d4", "Please configure which slicer and which slicing profile to use and name the GCode file to slice to below, or click \"Cancel\" if you do not wish to slice the file now.": ""}} ; \ No newline at end of file diff --git a/src/octoprint/static/js/i18n/nl.js b/src/octoprint/static/js/i18n/nl.js index 85dcfaa22..aebcda9ca 100644 --- a/src/octoprint/static/js/i18n/nl.js +++ b/src/octoprint/static/js/i18n/nl.js @@ -1 +1 @@ -window.BABEL_TO_LOAD_nl = {"locale": "nl", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-09-01 20:11+0000\nLast-Translator: leon.bek \nLanguage-Team: Dutch (http://www.transifex.com/projects/p/octoprint/language/nl/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Resterende print tijd", "Proceed": "Verder", "Timelapse Temp Folder": "Tijdelijke timelapse map", "Title": "Titel", "Only show files stored locally": "Laat alleen lokale bestanden zien", "yellow": "geel", "Path to Cura": "Lokatie van Cura", "Action": "Actie", "Passwords do not match": "Wachtwoorden komen niet overeen", "Sort by name": "Sorteer op naam", "Save connection settings": "Verbindings instellingen opslaan", "Rendering timelapse": "Renderen van timelapse", "Cura": "Cura", "Files": "Bestanden", "Bed Size": "Platform grootte", "Always assume SD card is present": "Neem aan dat SD kaart altijd aanwezig is", "Load and Print": "Laad en print", "Sending file to SD": "Verstuur bestand naar SD", "Number of Extruders": "Aantal Extruders", "black": "zwart", "Last Printed": "Laats geprint", "Sourcecode": "Broncode", "Estimated layer height": "Geschatte laag hooge", "You are now logged out": "Je bent nu uitgelogd", "Uploaded": "Geupload", "Opening serial port": "Openen van seri\u00eble poort", "New timelapse %(movie_basename)s is done rendering.": "Nieuwe timelapse %(movie_basename)s is gereed", "Invert control": "Bedieining spiegelen", "Webcam": "Webcam", "Remember me": "Onthoud me", "Enable GCode Visualizer": "Schakel GCode Visualizer in", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below.": "De server lijkt offline te zijn, dat wil zeggen dat ik er geen reactie van krijg. Ik zal proberen om gedurende een paar minuten opnieuw te verbinden. Maar je bent op elk moment vrij om handmatig proberen te verbinden met onderstaande knop.", "Rendering failed": "Renderen mislukt", "Upload Folder": "Lokatie voor Uploads", "descending": "Aflopend", "X": "X", "Add user": "Gebruiker toevoegen", "GCODE commands in layer": "GCODE commando's in laag", "Estimated print time": "Geschatte print tijd", "Serial Connection": "Seri\u00eble verbinding", "Control": "Controle", "Password": "Wachtwoord", "Also show next layer": "Laat ook volgende laag zien", "Print Time": "Print tijd", "Sort by file size": "Sorteer op bestands grootte", "Machine State": "Machine status", "default": "Standaard", "API": "API", "Printing from SD": "Printen vanaf SD", "Terminal filters": "Terminal filters", "Change password for user \"%(user)s\"": "Verander wachtwoord voor gebruiker \"%(user)s\"", "Enable Temperature Graph": "Schakel temperatuur grafiek in", "Delete user": "Gebruiker verwijderen", "Confirm Password": "Bevestig wachtwoord", "Disconnect": "Verbreken", "Slicing done": "Slicing klaar", "Initialize SD card": "Formateer SD kaart", "System": "Systeem", "Send": "Verstuur", "State": "Status", "Version": "Versie", "YYYY-MM-DD HH:mm": "DD-MM-YYYY HH:mm", "Attempt to reconnect": "Probeer opnieuw te verbinden", "Streaming done": "Streaming klaar", "violet": "violet", "Print": "Print", "Layer count": "Aantal lagen", "OctoPrint Settings": "OctoPrint instellingen", "Are you sure?": "Weet je het zeker?", "blue": "blauw", "Printer": "Printer", "Tool": "Gereedschap", "Settings": "Instellingen", "Path to FFMPEG": "Lokatie van FFMPEG", "Upload to SD": "Uploaden naar SD", "The command \"%(command)s\" could not be executed.": "Het commando \"%(command)s\" kon niet uitgevoerd worden.", "Printed": "Geprint", "Layer number": "Laag nummer", "Sync with job progress": "Synchroniseer met taak voortgang", "Circular": "Cirkelvormig", "Total filament used": "Totaal gebruikte filament", "red": "rood", "Save as default": "Stel in als standaard", "Slicing ...": "Slicing ...", "Last Print Time": "Laatste print tijd", "Target": "Doel", "Streaming ...": "Streaming ...", "Logout successful": "Uitloggen succesvol", "Now rendering timelapse %(movie_basename)s": "Aan het renderen van timelapse %(movie_basename)s", "Documentation": "Documentatie", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Upload", "ascending": "Oplopend", "Model size": "Model grootte", "Temperatures": "Temperaturen", "visited": "bezocht", "Timed": "Getimed", "Edit user \"%(user)s\"": "Bewerk gebruiker \"%(user)s\"", "Snapshot URL": "Snapshot URL", "Release SD card": "Geef SD kaart vrij", "Server is offline": "Server is offline", "Log communication to serial.log (might negatively impact performance)": "Log communicatie naar serial.log (kan negetief zijn voor de prestaties)", "Sort by upload date": "Sorteer op upload datum", "Change Password": "Verander wachtwoord", "Logs": "Logs", "Hotend": "Hotend", "Show retracts": "Laat retracts zien", "Keep Access Control Enabled": "Laat toegangscontrole ingeschakeld", "Upload locally": "Lokaal uploaden", "Select Tool...": "Selecteer gereedschap...", "Paused": "Gepauzeerd", "Continue": "Voortzetten", "Radius": "Straal", "The command \"%(command)s\" executed successfully": "Het commando \"%(command)s\" is succesvol uitgevoerd", "Features": "Functies", "Download": "Download", "GCode Viewer": "GCode kijker", "Also show previous layer": "Laat ook de vorige laag zien", "Enable OctoPrint watermark in timelapse movies": "Schakel OctoPrint watermerk in bij timelapse films", "Repetier": "Repetier", "Login successful": "Inloggen succesvol", "Finished Timelapses": "Complete timelapsen", "Rendering of timelapse %(movie_basename)s failedwith return code %(returncode)s": "Renderen van timelapse %(movie_basename)s mislukt met foutcode %(returncode)s", "Pause": "Pauze", "Temperature": "Temperatuur", "Enable slicing via Cura": "Schakel slicen via Cura in", "Access Control": "Toegangs controle", "Analyzing...": "Analyseren...", "just now": "zojuist", "Operational": "Operationeel", "Send a checksum with every command": "Stuur een checksum met elk commando", "Autodetection timeout": "Auto detectie timed-out", "Connecting": "Verbinden", "Free": "Vrij", "Closed": "Gesloten", "Refresh SD files": "Ververs SD bestandslijst", "Flip webcam vertically": "Spiegel webcam verticaal", "Path to Cura config": "Map voor Cura config", "Filament": "Filament", "Could not slice %(stl)s to %(gcode)s: %(reason)s": "Kon %(stl)s niet slicen naar %(gcode)s: %(reason)s", "Baudrate": "Baudrate", "Detecting baudrate": "Baudrate detecteren", "Date": "Datum", "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds": "Streamen van %(local)s naar %(remote)s op SD, duurde %(time).2f seconden", "Show moves": "Laat bewegingen zien", "Motors off": "Motoren uit", "Detecting serial port": "Detecteren van seri\u00eble poort", "New Password": "Nieuw wachtwoord", "Logout": "Uitloggen", "Offset": "Offset", "Analyzed": "Geanalyseerd", "Auto-connect on server startup": "Automatisch herverbinden bij opstarten van server", "Printer Parameters": "Printer Parameters", "E": "E", "Restart": "Herstarten", "Search...": "Zoek...", "Slicing failed": "Slicing mislukt", "Actual": "Huidig", "Active": "Aktief", "Creation date": "Cre\u00eber datum", "Hint: You can also drag and drop files on this page to upload them.": "Hint: Je kunt ook bestanden naar deze pagina slepen en loslaten om ze te uploaden.", "Interval": "Interval", "N/A": "N/B", "Bed": "Bed", "Auto-connect to printer on server start": "Automatisch verbinden met printer bij starten server", "orange": "oranje", "Connection": "Verbinding", "Error": "Fout", "On Z Change": "Bij hoogte verandering", "Timelapse post roll (in rendered seconds)": "Timelapse naloop (in gerenderde seconden)", "Z": "Z", "Are you sure you want to proceed?": "Weet je zeker dat je verder wilt gaan?", "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!": "Als je toegangs-controle uitschakelt en je OctoPrint installatie is toegangkelijk vanaf het internet, dan zal je printer toegankelijk zijn voor iedereen - dat zijn dus ook de slechte jongens!", "Load": "Laden", "Set": "Stel", "The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below.": "De server lijkt offline te zijn, dat wil zeggen dat ik er geen reactie van krijg. Ik kon niet automatisch opnieuw verbinden. Je kunt proberen handmatig proberen te verbinden met onderstaande knop.", "Zoom in on model": "Zoom in op model", "mm": "mm", "Saving ...": "Opslaan ...", "RegExp": "Reguliere Expressie", "Watched Folder": "Bekeken map", "General": "Algemeen", "Temperature timeout": "Temperatuur timed-out", "Color": "Kleur", "Fans on": "Ventilators aan", "Swallow the first \"ok\" after a resend response": "Eerste \"ok\" negeren na opnieuw verzonden reactie", "Enable SD support": "Schakel SD ondersteuning in", "Connect": "Verbindt", "Cancel": "Anuleren", "sec": "sec", "Warning": "Waarschuwing", "Loading...": "Laden...", "Current API Key": "Huidige API sleutel", "Size": "Grootte", "Communication timeout": "Communicatie timed-out", "Modification date": "Datum aangepast", "Change password": "Verander wachtwoord", "This will restart the print job from the beginning.": "Dit zal de print taak herstarten vanaf het begin.", "Stream URL": "Stream URL", "Sort by": "Sorteer op", "Login failed": "Inloggen mislukt", "Abort": "Afbreken", "Confirm": "Bevestig", "Repeat Password": "Wachtwoord herhalen", "Terminal": "Terminal", "Autoscroll": "Automatisch scrollen", "Print time for layer": "Print tijd voor laag", "Disable Access Control": "Toegangscontrole uitschakelen", "Configure Access Control": "Toegangscontrole configureren", "Timelapse Configuration": "Timelapse configuratie", "Retract": "Retract", "Timelapse bitrate": "Timelapse bitrate", "Offline": "Offline", "API Key": "API sleutel", "Homepage": "Thuispagina", "Estimated Print Time": "Geschatte print tijd", "Folders": "Mappen", "Bugs and Requests": "Bugs en Verzoeken", "Save": "Opslaan", "Default extrusion length": "Standaard extrusion lengte", "min": "min", "Support TargetExtr%%n/TargetBed target temperature format": "Support TargetExtr%%n/TargetBed target temperature format", "Connection timeout": "Verbinding timed-out", "Save config": "Bewaar configuratie", "Center viewport on model": "Centreer scherm op model", "User unknown or wrong password": "Gebruiker onbekend of verkeerd wachtwoord", "Allow Cross Origin Resource Sharing (CORS)": "Sta Cross Origin Resource Sharing (CORS) toe", "Appearance": "Uiterlijk", "Enable": "Ingeschakeld", "Uploading ...": "Uploading ...", "Logs Folder": "Logboek map", "

\n Please read the following, it is very important for your printer's health!\n

\n

\n OctoPrint by default now ships with Access Control enabled, meaning you won't be able to do anything with the\n printer unless you login first as a configured user. This is to prevent strangers - possibly with\n malicious intent - to gain access to your printer via the internet or another untrustworthy network\n and using it in such a way that it is damaged or worse (i.e. causes a fire).\n

\n

\n It looks like you haven't configured access control yet. Please set up an username and password for the\n initial administrator account who will have full access to both the printer and OctoPrint's settings, then click\n on \"Keep Access Control Enabled\":\n

": "

\nLees alstublieft dit bericht, het is belangrijk voor de gezondheid van je printer!!\n

\n

\nOctoPrint heeft nu standaard toegangscontrole ingeschakeld. Dit betekent dat je niets kunt doen met de printer,\n tenzij je bent inlogd met een geconfigureerde gebruiker. Dit is om te voorkomen dat vreemdelingen\n - met mogelijk kwade bedoelingen - toegang krijgen tot je printer via het internet of een ander onvertrouwd netwerk.\nEn het zo gebruikt dat het beschadigd of erger (d.w.z. een brand veroorzaakt).\n

\n

\nHet lijkt erop dat je toegangscontrole nog niet ingeschakeld hebt. Stel alsjeblieft\n een gebruikersnaam en wachtwoord in voor het eerste\n administrator account dat volledige toegang zal hebben tot de printer en OctoPrint's instellingen.\nKlik dan op \"Hou toegangscontrole ingeschakeld\":\n

", "Hide successfully printed files": "Verberg succesvolle geprinte bestanden", "Username": "Gebruikersnaam", "Off": "Uit", "Name": "Naam", "Extruder Offsets": "Extruder Offsets", "Approx. Total Print Time": "Geschat. totale print tijd", "Admin": "Admin", "

\n Note: In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't\n need Access Control for other reasons, you may alternatively disable Access Control. You should only\n do this if you are absolutely certain that only people you know and trust will be able to connect to it.\n

\n

\n Do NOT underestimate the risk of an unsecured access from the internet to your printer!\n

": "

\nMemo: In het geval dat je OctoPrint installatie alleen toegankelijk is vanaf een vertrouwd netwerk en je hebt toegangscontrole niet nodig voor andere redenen, kun je eventueel toegangscontrole uitschakelen. Je zou dit alleen moeten doen als je er absoluut zeker van bent dat alleen mensen die je kent en vertrouwd er verbinding mee kunnen maken.\n

\n

\nOnderschat het risico van onbeveiligde toegang vanaf het internet naar je printer niet!!\n

", "Timelapse": "Timelapse", "Remove": "Verwijderen", "Reload": "Herladen", "Printing": "Printen", "Only show files stored on SD": "Laat alleen bestanden op SD zien", "Y": "Y", "Fans off": "Ventilators uit", "Login": "Inloggen", "Timelapse ready": "Timelapse klaar", "Timelapse Mode": "Timelapse modues", "Timelapse Folder": "Lokatie voor timelapse", "Extruder": "Extruder", "Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and slicing support is enabled and configured.": "Kon het bestand niet uploaden. Zorg ervoor dat het bestand een GCODE bestand is en de extensie \".gcode\" of \".gco\" heeft, of dat het een STL bestand is met de extensie \".stl\" en ondersteuning voor slicen is aangezet en geconfigureerd.", "SD status timeout": "SD status timeout", "SD not initialized": "SD niet ge\u00efnitialiseerd", "Update User": "Update gebruiker", "off": "uit", "Serial Port": "Seri\u00eble poort", "Flip webcam horizontally": "Spiegel webcam Horizontaal", "Wait for start on connect": "Wacht voor start bij het verbinden", "Transfering file to SD": "Verstuur bestand naar SD", "OctoPrint": "OctoPrint", "Layer height": "Laag hoogte", "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds": "Slicen van %(stl)s naar %(gcode)s, duurde %(time).2f seconden", "Extrude": "Extrude", "green": "groen", "File": "Bestand", "You are now logged in as \"%(username)s\"": "Je bent nu ingelogd als \"%(username)s\"", "Axis": "Assen", "Filament used by layer": "Filament gebruikt bij laag"}} ; \ No newline at end of file +window.BABEL_TO_LOAD_nl = {"locale": "nl", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:04+0000\nLast-Translator: Gina H\u00e4u\u00dfge \nLanguage-Team: Dutch (http://www.transifex.com/projects/p/octoprint/language/nl/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Resterende print tijd", "sec": "sec", "Proceed": "Doorgaan", "Timelapse Temp Folder": "Tijdelijke timelapse map", "Support TargetExtr%%n/TargetBed target temperature format": "Support TargetExtr%%n/TargetBed target temperature format", "Upload Folder": "Lokatie voor Uploads", "Only show files stored locally": "Laat alleen lokale bestanden zien", "Add Printer Profile": "", "yellow": "geel", "Save": "Opslaan", "Action": "Actie", "Passwords do not match": "De wachtwoorden komen niet overeen", "Sort by name": "Sorteer op naam", "Save connection settings": "Verbindings instellingen opslaan", "Rendering timelapse": "Renderen van timelapse", "Color": "Kleur", "Temperature": "Temperatuur", "Files": "Bestanden", "Resume": "Ga verder", "Always assume SD card is present": "Neem aan dat SD kaart altijd aanwezig is", "Load and Print": "Laad en print", "Sending file to SD": "Verstuur bestand naar SD kaartje", "Number of Extruders": "Aantal Extruders", "black": "zwart", "Last Printed": "Vorige print-job", "Sourcecode": "Broncode", "Estimated layer height": "Geschatte laag hooge", "You are now logged out": "Je bent nu uitgelogd", "Uploaded": "Geupload", "Form Factor": "", "Opening serial port": "Openen van seri\u00eble poort", "New timelapse %(movie_basename)s is done rendering.": "Nieuwe timelapse %(movie_basename)s is gerenderd", "Invert control": "Bedieining spiegelen", "Webcam": "Webcam", "Select for printing": "", "Allow Cross Origin Resource Sharing (CORS)": "Sta Cross Origin Resource Sharing (CORS) toe", "Remember me": "Onthoud me", "Enable GCode Visualizer": "Schakel GCode Visualizer in", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below.": "De server lijkt offline te zijn, althans er komt geen enkele reactie. Ik zal over een paar minuten opnieuw pogen te verbinden. Je kunt op elk moment met onderstaande knop 'handmatig' proberen te verbinden", "Rendering failed": "Renderen mislukt", "Motors off": "Motoren uit", "descending": "Aflopend", "Only show files stored on SD": "Laat alleen bestanden op SD-kaart zien", "X": "X", "Add user": "Gebruiker toevoegen", "GCODE commands in layer": "GCODE commando's in laag", "Estimated print time": "Geschatte print tijd", "Serial Connection": "Seri\u00eble verbinding", "Control": "Controle", "Password": "Wachtwoord", "Also show next layer": "Laat ook volgende laag zien", "Print Time": "Print tijd", "Slicer": "'Slicer' of fileersoftware", "Nozzle Diameter": "", "Sort by file size": "Sorteer op bestands grootte", "Machine State": "Machine status", "Slicing Profile": "Fileer profiel", "mm": "mm", "API": "API", "Printing from SD": "Printen vanaf SD kaartje", "Stream URL": "Stream URL", "Terminal filters": "Terminal filters", "Change password for user \"%(user)s\"": "Verander wachtwoord voor gebruiker \"%(user)s\"", "Enable Temperature Graph": "Schakel temperatuur grafiek in", "Delete user": "Gebruiker verwijderen", "Timelapse bitrate": "Timelapse bitrate", "Confirm Password": "Bevestig wachtwoord", "Disconnect": "Verbreken", "Slicing done": "Fileren is klaar", "Initialize SD card": "Formateer SD kaart", "System": "Systeem", "Send": "Verstuur", "State": "Status", "Version": "Versie", "YYYY-MM-DD HH:mm": "DD-MM-YYYY HH:mm", "Attempt to reconnect": "Probeer opnieuw te verbinden", "Streaming done": "Het Streamen is klaar", "violet": "violet", "Print": "Print", "Layer count": "Aantal lagen", "OctoPrint Settings": "OctoPrint instellingen", "Are you sure?": "Weet je het zeker?", "blue": "blauw", "Printer": "Printer", "Delete Profile": "", "Tool": "Gereedschap", "Settings": "Instellingen", "Circular": "Cirkelvormig", "Path to FFMPEG": "Lokatie van FFMPEG", "Upload to SD": "opslaan op SD-kaart ", "The command \"%(command)s\" could not be executed.": "Het commando \"%(command)s\" kon niet uitgevoerd worden.", "Select a slicing profile...": "", "Wait for start on connect": "Wacht voor start bij het verbinden", "Sync with job progress": "Synchroniseer met taak voortgang", "Calculating...": "", "Total filament used": "Totaal gebruikte filament", "red": "rood", "Save as default": "Stel in als standaard", "Slicing ...": "Slicing ... / Aan het fileren...", "Last Print Time": "Duur vorige print-job ", "Target": "Doel", "Add Profile...": "", "Streaming ...": "Streaming ...", "Logout successful": "Uitloggen succesvol", "Now rendering timelapse %(movie_basename)s": "Nu de timelapse %(movie_basename)s aan het renderen", "Documentation": "Documentatie", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Upload", "ascending": "Oplopend", "Model size": "Model grootte", "Temperatures": "Temperaturen", "Timed": "Getimed", "Edit user \"%(user)s\"": "Bewerk gebruiker \"%(user)s\"", "Identifier": "", "Release SD card": "Geef SD kaart vrij", "Server is offline": "Server is niet bereikbaar", "Log communication to serial.log (might negatively impact performance)": "Log communicatie naar serial.log (kan negetief zijn voor de prestaties)", "Sort by upload date": "Sorteer op upload datum", "Change Password": "Verander het wachtwoord", "Logs": "Logs", "Hotend": "Hotend", "Show retracts": "Laat retracts zien", "Keep Access Control Enabled": "Houd de toegangscontrole ingeschakeld", "Upload locally": "Lokaal uploaden", "Do nothing": "", "Paused": "Gepauzeerd", "Continue": "Voortzetten", "Edit Printer Profile \"%(name)s\"": "", "The command \"%(command)s\" executed successfully": "Het commando \"%(command)s\" is succesvol uitgevoerd", "Features": "Functies", "Download": "Download", "GCode Viewer": "GCode Viewer", "Also show previous layer": "Laat ook de vorige laag zien", "Enable OctoPrint watermark in timelapse movies": "Schakel OctoPrint watermerk in bij timelapse films", "Repetier": "Repetier", "Login successful": "Succesvol ingelogd", "Finished Timelapses": "Complete timelapsen", "Pause": "Pauze", "GCode Filename": "GCode Filename", "Access Control": "Toegangs controle", "Start printing": "", "Swallow the first \"ok\" after a resend response": "Eerste \"ok\" negeren na opnieuw verzonden reactie", "Analyzing...": "Analyseren...", "just now": "zojuist", "Operational": "Operationeel", "Send a checksum with every command": "Stuur een checksum met elk commando", "Autodetection timeout": "Auto detectie timed-out", "Connecting": "Verbinden", "Free": "Vrij", "Closed": "Gesloten", "Refresh SD files": "Ververs de SD-kaart bestandslijst", "Flip webcam vertically": "Spiegel webcam verticaal", "Starts the print job": "Start de print-taak", "Model": "", "Filament": "Filament", "Could not slice %(stl)s to %(gcode)s: %(reason)s": "Kon %(stl)s niet 'slicen/fileren' naar %(gcode)s: %(reason)s", "Baudrate": "Baudrate", "Snapshot URL": "Snapshot URL", "Detecting baudrate": "Baudrate detecteren", "Date": "Datum", "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds": "Streamen van %(local)s naar %(remote)s op SD, duurde %(time).2f seconden", "Show moves": "Laat bewegingen zien", "Select a printer profile...": "", "Detecting serial port": "Detecteren van seri\u00eble poort", "New Password": "Nieuw wachtwoord", "Title": "Titel", "Logout": "Uitloggen", "Offset": "Offset", "Analyzed": "Geanalyseerd", "Auto-connect on server startup": "Automatisch verbinden bij opstarten van server", "E": "E", "Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s": "", "Restart": "Herstarten", "Search...": "Zoek...", "Slicing failed": "Het 'slice/fileren' is mislukt", "Actual": "Werkelijke", "Active": "Aktief", "SD status timeout": "SD status timeout", "Creation date": "Cre\u00eber datum", "Hint: You can also drag and drop files on this page to upload them.": "Hint: Je kunt ook bestanden naar deze pagina slepen en loslaten om ze te uploaden.", "Restarts the print job from the beginning": "Start het print opnieuw vanaf het begin.", "Interval": "Interval", "N/A": "N/B", "Bed": "Bed", "Auto-connect to printer on server start": "Automatisch verbinden met printer bij starten server", "orange": "oranje", "Connection": "Verbinding", "Error": "Fout", "On Z Change": "Bij hoogte verandering op de Z-as", "Timelapse post roll (in rendered seconds)": "Timelapse naloop (in gerenderde seconden)", "Z": "Z", "Edit Profile": "", "Are you sure you want to proceed?": "Weet je zeker dat je verder wilt gaan?", "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!": "Als je de toegangs-controle uitschakelt is je OctoPrint installatie mogelijk toegangkelijk vanaf het internet. Je printer is toegankelijk voor iedereen - ook de kwaaie jongens!", "Load": "Laden", "Set": "Instellen", "The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below.": "De server lijkt offline te zijn, dat wil zeggen dat ik er geen reactie van krijg. Ik kon niet automatisch opnieuw verbinden. Je kunt proberen handmatig proberen te verbinden met onderstaande knop.", "Zoom in on model": "Zoom in op model", "Pauses the print job": "Pauzeert de print-taak", "After slicing...": "", "Saving ...": "Opslaan ...", "RegExp": "Reguliere Expressie", "Watched Folder": "Bekeken map", "General": "Algemeen", "Temperature timeout": "Temperatuur timed-out", "Set as default profile": "", "Fans on": "Ventilatoren aan", "Abort": "Afbreken", "Enable SD support": "Schakel SD ondersteuning in", "Connect": "Verbind", "Cancel": "Annuleren", "visited": "bezocht", "Warning": "Waarschuwing", "Loading...": "Laden...", "Current API Key": "Huidige API sleutel", "Size": "Grootte", "Communication timeout": "Communicatie timed-out", "Modification date": "Datum aangepast", "Slice": "Fileer / 'Slice'", "Change password": "Verander wachtwoord", "Layer number": "Laag aantal", "Cancels the print job": "Stopt met de print taak", "This will restart the print job from the beginning.": "Dit zal de print taak herstarten vanaf het begin.", "Sort by": "Sorteer op", "Login failed": "Inloggen mislukt", "Confirm": "Bevestig", "Repeat Password": "Wachtwoord herhalen", "Terminal": "Terminal", "Autoscroll": "Automatisch scrollen", "Print time for layer": "Print tijd per laag", "Disable Access Control": "Toegangscontrole uitschakelen", "Configure Access Control": "Toegangscontrole configureren", "Timelapse Configuration": "Timelapse configuratie", "Retract": "Terugtrekken", "Printer Profile": "", "Offline": "Offline", "API Key": "API sleutel", "Homepage": "Thuispagina", "Estimated Print Time": "Geschatte print tijd", "Folders": "Mappen", "Select a slicer...": "Selecteer de 'slicer' / fileer-software", "Printer Profiles": "", "Slicing %(filename)s": "%(filename)s aan het fileren", "Extruder Offsets": "Extruder Offsets", "min": "min", "Only show STL files": "Vertoon alleen de STL files", "Slicing ... (%(percentage)d%%)": "", "Connection timeout": "Verbinding timed-out", "Save config": "Bewaar configuratie", "Center viewport on model": "Centreer scherm op model", "User unknown or wrong password": "Gebruiker onbekend of verkeerd wachtwoord", "Volume": "", "default": "Standaard", "Heated Bed": "", "Appearance": "Uiterlijk", "Enable": "Ingeschakeld", "Uploading ...": "Uploaden ...", "Logs Folder": "Logboek map", "

\n Please read the following, it is very important for your printer's health!\n

\n

\n OctoPrint by default now ships with Access Control enabled, meaning you won't be able to do anything with the\n printer unless you login first as a configured user. This is to prevent strangers - possibly with\n malicious intent - to gain access to your printer via the internet or another untrustworthy network\n and using it in such a way that it is damaged or worse (i.e. causes a fire).\n

\n

\n It looks like you haven't configured access control yet. Please set up an username and password for the\n initial administrator account who will have full access to both the printer and OctoPrint's settings, then click\n on \"Keep Access Control Enabled\":\n

": "

\nLees het navolgende bericht, het is belangrijk voor het goed functioneren van je printer!!\n

\n

\nOctoPrint heeft nu de standaard toegangscontrole ingeschakeld. Dit betekent dat je niets kunt doen met de printer,\n tenzij je bent inlogd met een geconfigureerde gebruiker. Dit om te voorkomen dat vreemdelingen\n - met mogelijk kwade bedoelingen - toegang krijgen tot je printer via het internet of een ander onvertrouwd netwerk.\nEn de printer zo kan gebruiken dat beschadiging ontstaat of erger (bijvoorbeeld brand).\n

\n

\nHet lijkt erop dat je toegangscontrole nog niet ingeschakeld hebt. Stel alsjeblieft\n een gebruikersnaam en wachtwoord in voor het eerste\n administrator account dat volledige toegang zal hebben tot de printer en OctoPrint's instellingen.\nKlik dan op \"Hou toegangscontrole ingeschakeld\":\n

", "Hide successfully printed files": "Verberg succesvol geprinte bestanden", "Username": "Gebruikersnaam", "Select Tool...": "Selecteer gereedschap...", "Off": "Uit", "Name": "Naam", "Bugs and Requests": "Bugs en Verzoeken", "Approx. Total Print Time": "Geschatte totale print tijd", "Admin": "Admin", "

\n Note: In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't\n need Access Control for other reasons, you may alternatively disable Access Control. You should only\n do this if you are absolutely certain that only people you know and trust will be able to connect to it.\n

\n

\n Do NOT underestimate the risk of an unsecured access from the internet to your printer!\n

": "

\nMemo: Indien je OctoPrint installatie alleen toegankelijk is vanaf een vertrouwd netwerk en je hebt toegangscontrole niet nodig voor andere redenen, kun je eventueel toegangscontrole uitschakelen. Je zou dit alleen moeten doen als je er absoluut zeker van bent dat alleen mensen die je kent en vertrouwd er verbinding mee kunnen maken.\n

\n

\nOnderschat het risico van onbeveiligde toegang vanaf het internet naar je printer niet!!\n

", "Timelapse": "Timelapse", "QR Code": "", "Only show GCode files": "Vertoon alleen GCode files", "Remove": "Verwijderen", "Reload": "Herladen", "Printing": "Printen", "printed": "geprint", "Y": "Y", "Fans off": "Ventilatoren uit", "Login": "Inloggen", "Rectangular": "", "Timelapse ready": "Timelapse klaar", "Timelapse Mode": "Timelapse modues", "Timelapse Folder": "Lokatie voor timelapse", "Extruder": "Extruder", "Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and slicing support is enabled and configured.": "Kon het bestand niet uploaden. Zorg ervoor dat het bestand een GCODE of STL bestand is en ondersteuning voor fileren is aangezet en geconfigureerd. Een GCODE bestand heeft een extensie \".gcode\" of \".gco\". Een STL bestand heeft de extensie \".stl\".", "Printed": "Geprint", "SD not initialized": "SD-kaart niet ge\u00efnitialiseerd", "Update User": "Update gebruiker", "off": "uit", "Serial Port": "Seri\u00eble poort", "Flip webcam horizontally": "Spiegel webcam Horizontaal", "Resumes the print job": "Gaat verder met de print-taak", "Transfering file to SD": "Verstuur bestand naar SD kaartje", "OctoPrint": "OctoPrint", "Layer height": "Laag hoogte", "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds": "Het 'slicen/fileren' van %(stl)s naar %(gcode)s, duurde %(time).2f seconden", "Extrude": "Extrudeer", "green": "groen", "File": "Bestand", "You are now logged in as \"%(username)s\"": "Je bent nu ingelogd als \"%(username)s\"", "Axis": "Assen", "Filament used by layer": "hoeveelheid Filament gebruikt bij laag", "Please configure which slicer and which slicing profile to use and name the GCode file to slice to below, or click \"Cancel\" if you do not wish to slice the file now.": "Geef aan welke slicer/fileer software gebruikt moet worden en met welk profiel. Geef vervolgens aan de resulterende GCODE file een naam. Of druk op de knop 'Cancel' als je de file nu niet wilt 'slicen'/fileren, "}} ; \ No newline at end of file diff --git a/src/octoprint/static/js/i18n/no.js b/src/octoprint/static/js/i18n/no.js index a5a85f41d..7f6174621 100644 --- a/src/octoprint/static/js/i18n/no.js +++ b/src/octoprint/static/js/i18n/no.js @@ -1 +1 @@ -window.BABEL_TO_LOAD_no = {"locale": "nb_NO", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-09-03 16:07+0000\nLast-Translator: lobster2b \nLanguage-Team: Norwegian (http://www.transifex.com/projects/p/octoprint/language/no/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Gjenst\u00e5ende utskriftstid", "Proceed": "Fortsett", "Timelapse Temp Folder": "Timelapse midlertidig mappe", "Title": "Tittel", "Only show files stored locally": "Bare vis filer lagret lokalt", "yellow": "gul", "Path to Cura": "Sti til Cura", "Action": "Handling", "Passwords do not match": "Passordet er ikke likt", "Sort by name": "Sorter ved navn", "Save connection settings": "Lagre tilkoblingsinnstillinger", "Rendering timelapse": "Sammensetter timelapse", "Cura": "Cura", "Files": "Filer", "Bed Size": "Plattformst\u00f8rrelse", "Always assume SD card is present": "Alltid anta at minnekort er p\u00e5 plass", "Load and Print": "Last og skriv ut", "Sending file to SD": "Sender fil til minnekort", "Number of Extruders": "Antall dyser", "black": "svart", "Last Printed": "Sist utskrevet", "Sourcecode": "Kildekode", "Estimated layer height": "Estimert lagh\u00f8yde", "You are now logged out": "Du er n\u00e5 logget ut", "Uploaded": "Opplastet", "Opening serial port": "\u00c5pner serialport", "New timelapse %(movie_basename)s is done rendering.": "Ny timelapse for %(movie_basename)s er ferdig sammensatt", "Invert control": "Inverter kontroller", "Webcam": "Nettkamera", "Remember me": "Husk meg", "Enable GCode Visualizer": "Aktiver GCode framviser", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below.": "Serveren er tilsynelatende frakoblet, i det minste f\u00e5r jeg ikke noen respons fra den. Jeg pr\u00f8ver \u00e5 koble til automatisk over de neste minuttene, du kan pr\u00f8ve en manuell oppkobling n\u00e5r du \u00f8nsker det ved \u00e5 bruke knappen nedenfor.", "Rendering failed": "Sammensetting feilet", "Upload Folder": "Opplastningsmappe", "descending": "synkende", "X": "X", "Add user": "Legg til bruker", "GCODE commands in layer": "GCODE kommandoer i lag", "Estimated print time": "Beregnet printtid", "Serial Connection": "Seriell kontakt", "Control": "Kontroll", "Password": "Passord", "Also show next layer": "Ogs\u00e5 vis neste lag", "Print Time": "Utskriftstid", "Sort by file size": "Sorter filer etter st\u00f8rrelse", "Machine State": "Maskintilstand", "default": "standard", "API": "API", "Printing from SD": "Utskrift fra minnekort", "Terminal filters": "Terminal filtre", "Change password for user \"%(user)s\"": "Endre passord for bruker \"%(user)s\"", "Enable Temperature Graph": "Aktiver temperaturgraf", "Delete user": "Slett bruker", "Confirm Password": "Bekreft passord", "Disconnect": "Koble fra", "Slicing done": "Slicing ferdig", "Initialize SD card": "Start minnekortet", "System": "System", "Send": "Send", "State": "Tilstand", "Version": "Versjon", "YYYY-MM-DD HH:mm": "YYYY-MM-DD HH:mm", "Attempt to reconnect": "Fors\u00f8k \u00e5 koble til p\u00e5 nytt", "Streaming done": "Streaming ferdig", "violet": "fiolett", "Print": "Utskriv", "Layer count": "Antall lag", "OctoPrint Settings": "OctoPrint innstillinger", "Are you sure?": "Er du sikker?", "blue": "bl\u00e5", "Printer": "Printer", "Tool": "Verkt\u00f8y", "Settings": "Innstillinger", "Path to FFMPEG": "Sti til FFMPEG", "Upload to SD": "Last opp til minnekort", "The command \"%(command)s\" could not be executed.": "Kommando \"%(command)s\" mislykkes", "Printed": "Utskrevet", "Layer number": "Lag nummer", "Sync with job progress": "Synkroniser med jobbprogresjon", "Circular": "Sirkul\u00e6r", "Total filament used": "Totalt tr\u00e5dforbruk", "red": "r\u00f8d", "Save as default": "Lagre som standard", "Slicing ...": "Slicing ...", "Last Print Time": "Siste utskriftstid", "Target": "M\u00e5l", "Streaming ...": "Streaming ...", "Logout successful": "Logg ut vellykket", "Now rendering timelapse %(movie_basename)s": "Sammensetter timelapse %(movie_basename)s", "Documentation": "Dokumentasjon", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Last opp", "ascending": "stigende", "Model size": "Modellst\u00f8rrelse", "Temperatures": "Temperaturer", "visited": "bes\u00f8kt", "Timed": "Tidtakes", "Edit user \"%(user)s\"": "Endre bruker \"%(user)s\"", "Snapshot URL": "Hurtigbilde URL", "Release SD card": "L\u00f8s ut minnekort", "Server is offline": "Server er frakoblet", "Log communication to serial.log (might negatively impact performance)": "Skriv logg til serial.log (kan redusere ytelsen)", "Sort by upload date": "Sorter ved opplastningsdato", "Change Password": "Endre passord", "Logs": "Logger", "Hotend": "Dyse", "Show retracts": "Vis tilbaketrekninger", "Keep Access Control Enabled": "Behold adgangskontroll aktivert", "Upload locally": "Last opp lokalt", "Select Tool...": "Velg verkt\u00f8y", "Paused": "Pause", "Continue": "Fortsett", "Radius": "Radius", "The command \"%(command)s\" executed successfully": "Kommando \"%(command)s\" vellykket", "Features": "Funksjoner", "Download": "Last ned", "GCode Viewer": "GCode framviser", "Also show previous layer": "Ogs\u00e5 vis forrige lag", "Enable OctoPrint watermark in timelapse movies": "Aktiver OctoPrint vannmerke i timelapsefilmer", "Repetier": "Repeter", "Login successful": "Logg inn vellykket", "Finished Timelapses": "Ferdig timelapser", "Rendering of timelapse %(movie_basename)s failedwith return code %(returncode)s": "Sammensetting av timelapse %(movie_basename)s feilet med feilkode %(returncode)s", "Pause": "Pause", "Temperature": "Temperatur", "Enable slicing via Cura": "Aktiver slicing via Cura", "Access Control": "Adgangskontroll", "Analyzing...": "Analyserer...", "just now": "Akkurat no", "Operational": "Operativ", "Send a checksum with every command": "Send en kontrollsum med alle kommandoer", "Autodetection timeout": "Automatisk detekteringstidsavbrudd", "Connecting": "Kobler til", "Free": "Ledig", "Closed": "Lukket", "Refresh SD files": "Oppdater minnekort", "Flip webcam vertically": "Vertikal invertere webcam", "Path to Cura config": "Sti til Curakonfigurasjon", "Filament": "Tr\u00e5d", "Could not slice %(stl)s to %(gcode)s: %(reason)s": "Feilet \u00e5 slice %(stl)s til %(gcode)s: %(reason)s", "Baudrate": "Datemengde", "Detecting baudrate": "Finner seriell hastighet", "Date": "Dato", "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds": "Streamed %(local)s il %(remote)s p\u00e5 minnekort, took %(time).2f sekunder", "Show moves": "Vis forflyttninger", "Motors off": "Motorer av", "Detecting serial port": "Finner serialport", "New Password": "Nytt passord", "Logout": "Logg ut", "Offset": "Avvik", "Analyzed": "Analysert", "Auto-connect on server startup": "Koble til automatisk ved oppstart", "Printer Parameters": "Printer parametere", "E": "E", "Restart": "Omstart", "Search...": "S\u00f8k...", "Slicing failed": "Slicing feilet", "Actual": "Faktisk", "Active": "Aktiv", "Creation date": "Opprettelsesdato", "Hint: You can also drag and drop files on this page to upload them.": "Tips: Du kan ogs\u00e5 dra og slippe filer p\u00e5 denne siden for \u00e5 laste de opp", "Interval": "Interval", "N/A": "N/A", "Bed": "Bord", "Auto-connect to printer on server start": "Koble til printer automatisk ved oppstart", "orange": "orange", "Connection": "Tilkobling", "Error": "Feil", "On Z Change": "P\u00e5 Z endring", "Timelapse post roll (in rendered seconds)": "Timelapse etter opptak (i sekunder)", "Z": "Z", "Are you sure you want to proceed?": "Er du sikker du vil fortsette?", "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!": "Hvis du sl\u00e5r av adgangskontroll og din OctoPrint innstallasjon er tilgjengelig fra internett, din printer vil bli tilgjengelig for alle - inkluderer ogs\u00e5 dei med u\u00e6rlige intensjoner", "Load": "Last", "Set": "Velg", "The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below.": "Serveren er tilsynelatende frakoblet, i det minste f\u00e5r jeg ikke noen respons fra den. Jeg kan ikke koble til den automatisk, du kan pr\u00f8ve en manuell oppkobling n\u00e5r du \u00f8nsker det ved \u00e5 bruke knappen nedenfor.", "Zoom in on model": "Zoom inn p\u00e5 modell", "mm": "mm", "Saving ...": "Lagrer ...", "RegExp": "RegExp", "Watched Folder": "Kontrollert mappe", "General": "Generell", "Temperature timeout": "Temperatur tidsavbrudd", "Color": "Farge", "Fans on": "Vifter p\u00e5", "Swallow the first \"ok\" after a resend response": "Svelg unna f\u00f8rste \"ok\" etter omsendt svar", "Enable SD support": "Aktiver st\u00f8tte for minnekort", "Connect": "Koble til", "Cancel": "Avbryt", "sec": "sek", "Warning": "Advarsel", "Loading...": "Laster...", "Current API Key": "N\u00e5v\u00e6rende API n\u00f8kkel", "Size": "St\u00f8rrelse", "Communication timeout": "Kommunikasjon tidsavbrudd", "Modification date": "Endret dato", "Change password": "Endre passord", "This will restart the print job from the beginning.": "Dette vil starte utskriftsjobbene fra starten", "Stream URL": "Stream URL", "Sort by": "Sorter etter", "Login failed": "Logg inn misslykkes", "Abort": "Avbryt", "Confirm": "Bekreft", "Repeat Password": "Gjenta passord", "Terminal": "Terminal", "Autoscroll": "Autoscroll", "Print time for layer": "Printtid for lag", "Disable Access Control": "Deaktiver adgangskontroll", "Configure Access Control": "Konfigurer adgangskontroll", "Timelapse Configuration": "Timelapse konfigurasjon", "Retract": "Tilbaketrekking", "Timelapse bitrate": "Timelapse bitrate", "Offline": "Frakoblet", "API Key": "API n\u00f8kkel", "Homepage": "Hjemmeside", "Estimated Print Time": "Bergenet utskriftstid", "Folders": "Mapper", "Bugs and Requests": "Feilrapportering og \u00f8nsker", "Save": "Lagre", "Default extrusion length": "Standard extrusion lengde ", "min": "min", "Support TargetExtr%%n/TargetBed target temperature format": "St\u00f8tte TargetExtr%%n/TargetBed m\u00e5l pemperatur format", "Connection timeout": "Oppkoblingstidsavbrudd", "Save config": "Lagre konfigurasjon", "Center viewport on model": "Sentrer bilde p\u00e5 modell", "User unknown or wrong password": "Bruker ukjent eller feil passord", "Allow Cross Origin Resource Sharing (CORS)": "Tillat Cross Origin Resource Sharing (CORS)", "Appearance": "Utseende", "Enable": "Aktiver", "Uploading ...": "Laster opp ...", "Logs Folder": "Loggmappe", "

\n Please read the following, it is very important for your printer's health!\n

\n

\n OctoPrint by default now ships with Access Control enabled, meaning you won't be able to do anything with the\n printer unless you login first as a configured user. This is to prevent strangers - possibly with\n malicious intent - to gain access to your printer via the internet or another untrustworthy network\n and using it in such a way that it is damaged or worse (i.e. causes a fire).\n

\n

\n It looks like you haven't configured access control yet. Please set up an username and password for the\n initial administrator account who will have full access to both the printer and OctoPrint's settings, then click\n on \"Keep Access Control Enabled\":\n

": "

\nVennligst les f\u00f8lgende, det er veldig viktig for din printers helse!!\n

\n

\nOctoPrint kommer originalt med adgangskontroll aktivert, som betyr at du ikke f\u00e5r gjort noe med\nprinteren med mindre du logger inn med en konfigurert bruker. Dette er for \u00e5 forhindre ukjente - med potensielt\nu\u00e6rlige intensjoner - fra \u00e5 f\u00e5 tilgang til din printer via Internett eller et usikret nettverk\nog bruker den i en slik m\u00e5te at skade oppst\u00e5r eller verre (f.eks for\u00e5rsaker en brann).\n

\n

\nDu har ikke konfigurert adgangskontrollen enda. Vennligst sett et brukernavn og passord for den\nf\u00f8rste administratorkontoen som vil ha full adgang til b\u00e5de skriveren og OctoPrint innstillinger, klikk deretter p\u00e5\n\"Behold adgangskontroll aktivert\":\n

", "Hide successfully printed files": "Skjul vellykkede utskriftsfiler", "Username": "Brukernavn", "Off": "Av", "Name": "Navn", "Extruder Offsets": "Extruder avvik", "Approx. Total Print Time": "Beregnet total utskriftstid", "Admin": "Admin", "

\n Note: In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't\n need Access Control for other reasons, you may alternatively disable Access Control. You should only\n do this if you are absolutely certain that only people you know and trust will be able to connect to it.\n

\n

\n Do NOT underestimate the risk of an unsecured access from the internet to your printer!\n

": "

\nNoter: Hvis din OctoPrint installasjon er p\u00e5 et nettverk som du er helt sikker p\u00e5 at det er kun du eller folk du stoler p\u00e5 og du ikke \u00f8nsker adgangskontroll av en eller annen grunn,\nkan du deaktivere adgangskontrollen. Du burde kun\ngj\u00f8re dette vist du er helt sikker p\u00e5 at det er bare folk du kjenner og stoler p\u00e5 som vil koble til printeren.\n

\n

\nIKKE undervurder faren ved en usikret adgang fra Internett til din printer!\n

", "Timelapse": "Timelapse", "Remove": "Fjern", "Reload": "Last p\u00e5 nytt", "Printing": "Skriver ut", "Only show files stored on SD": "Bare vis filer lagret p\u00e5 minnekortet", "Y": "Y", "Fans off": "Vifter av", "Login": "Logg inn", "Timelapse ready": "Timelapse klar", "Timelapse Mode": "Timelapse modus", "Timelapse Folder": "Timelapse mappe", "Extruder": "Extruder", "Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and slicing support is enabled and configured.": "Klarte ikke \u00e5 laste opp filen, S\u00f8rg for at det er en GCODE fil med filtype \".gcode\" eller \".gco\" eller det er en STL fil med filtype \".stl\" og at slicing er aktivert og konfigurert.", "SD status timeout": "Minnekort tidsavbrudd", "SD not initialized": "Minnekort er ikke startet", "Update User": "Oppdater bruker", "off": "Av", "Serial Port": "Seriellport", "Flip webcam horizontally": "Horisontal invertere webcam", "Wait for start on connect": "Vent for start p\u00e5 tilkobling", "Transfering file to SD": "Overf\u00f8rer til minnekort", "OctoPrint": "OctoPrint", "Layer height": "Lag h\u00f8yde", "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds": "Sliced %(stl)s til %(gcode)s, tok %(time).2f sekunder", "Extrude": "Extrude", "green": "gr\u00f8nn", "File": "Fil", "You are now logged in as \"%(username)s\"": "Du er no logget inn som \"%(username)s\"", "Axis": "Akse", "Filament used by layer": "Tr\u00e5d brukt i laget"}} ; \ No newline at end of file +window.BABEL_TO_LOAD_no = {"locale": "nb_NO", "domain": "messages", "plural_expr": "(n != 1)", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:04+0000\nLast-Translator: Gina H\u00e4u\u00dfge \nLanguage-Team: Norwegian (http://www.transifex.com/projects/p/octoprint/language/no/)\nPlural-Forms: nplurals=2; plural=(n != 1)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Gjenst\u00e5ende utskriftstid", "sec": "sek", "Proceed": "Fortsett", "Timelapse Temp Folder": "Timelapse midlertidig mappe", "Support TargetExtr%%n/TargetBed target temperature format": "St\u00f8tte TargetExtr%%n/TargetBed m\u00e5l temperatur format", "Upload Folder": "Opplastningsmappe", "Only show files stored locally": "Bare vis filer lagret lokalt", "Add Printer Profile": "", "yellow": "gul", "Save": "Lagre", "Action": "Handling", "Passwords do not match": "Passordet er ikke likt", "Sort by name": "Sorter ved navn", "Save connection settings": "Lagre tilkoblingsinnstillinger", "Rendering timelapse": "Sammensetter timelapse", "Color": "Farge", "Temperature": "Temperatur", "Files": "Filer", "Resume": "Fortsett", "Always assume SD card is present": "Alltid anta at minnekort er p\u00e5 plass", "Load and Print": "Last og skriv ut", "Sending file to SD": "Sender fil til minnekort", "Number of Extruders": "Antall dyser", "black": "svart", "Last Printed": "Sist utskrevet", "Sourcecode": "Kildekode", "Estimated layer height": "Estimert lagh\u00f8yde", "You are now logged out": "Du er n\u00e5 logget ut", "Uploaded": "Opplastet", "Form Factor": "", "Opening serial port": "\u00c5pner serialport", "New timelapse %(movie_basename)s is done rendering.": "Ny timelapse for %(movie_basename)s er ferdig sammensatt", "Invert control": "Inverter kontroller", "Webcam": "Nettkamera", "Select for printing": "", "Allow Cross Origin Resource Sharing (CORS)": "Tillat Cross Origin Resource Sharing (CORS)", "Remember me": "Husk meg", "Enable GCode Visualizer": "Aktiver GCode framviser", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below.": "Serveren er tilsynelatende frakoblet, i det minste f\u00e5r jeg ikke noen respons fra den. Jeg pr\u00f8ver \u00e5 koble til automatisk over de neste minuttene, du kan pr\u00f8ve en manuell oppkobling n\u00e5r du \u00f8nsker det ved \u00e5 bruke knappen nedenfor.", "Rendering failed": "Sammensetting feilet", "Motors off": "Motorer av", "descending": "synkende", "Only show files stored on SD": "Bare vis filer lagret p\u00e5 minnekortet", "X": "X", "Add user": "Legg til bruker", "GCODE commands in layer": "GCODE kommandoer i lag", "Estimated print time": "Beregnet printtid", "Serial Connection": "Seriell kontakt", "Control": "Kontroll", "Password": "Passord", "Also show next layer": "Ogs\u00e5 vis neste lag", "Print Time": "Utskriftstid", "Slicer": "Slicer", "Nozzle Diameter": "", "Sort by file size": "Sorter filer etter st\u00f8rrelse", "Machine State": "Maskintilstand", "Slicing Profile": "Slicer profil", "mm": "mm", "API": "API", "Printing from SD": "Utskrift fra minnekort", "Stream URL": "Str\u00f8m URL", "Terminal filters": "Terminal filtre", "Change password for user \"%(user)s\"": "Endre passord for bruker \"%(user)s\"", "Enable Temperature Graph": "Aktiver temperaturgraf", "Delete user": "Slett bruker", "Timelapse bitrate": "Timelapse bitrate", "Confirm Password": "Bekreft passord", "Disconnect": "Koble fra", "Slicing done": "Slicing ferdig", "Initialize SD card": "Start minnekortet", "System": "System", "Send": "Send", "State": "Tilstand", "Version": "Versjon", "YYYY-MM-DD HH:mm": "YYYY-MM-DD HH:mm", "Attempt to reconnect": "Fors\u00f8k \u00e5 koble til p\u00e5 nytt", "Streaming done": "Str\u00f8mming ferdig", "violet": "fiolett", "Print": "Utskriv", "Layer count": "Antall lag", "OctoPrint Settings": "OctoPrint innstillinger", "Are you sure?": "Er du sikker?", "blue": "bl\u00e5", "Printer": "Printer", "Delete Profile": "", "Tool": "Verkt\u00f8y", "Settings": "Innstillinger", "Circular": "Sirkul\u00e6r", "Path to FFMPEG": "Sti til FFMPEG", "Upload to SD": "Last opp til minnekort", "The command \"%(command)s\" could not be executed.": "Kommando \"%(command)s\" mislykkes", "Select a slicing profile...": "", "Wait for start on connect": "Vent for start p\u00e5 tilkobling", "Sync with job progress": "Synkroniser med jobbprogresjon", "Calculating...": "", "Total filament used": "Totalt tr\u00e5dforbruk", "red": "r\u00f8d", "Save as default": "Lagre som standard", "Slicing ...": "Slicing ...", "Last Print Time": "Siste utskriftstid", "Target": "M\u00e5l", "Add Profile...": "", "Streaming ...": "Str\u00f8mmer...", "Logout successful": "Logg ut vellykket", "Now rendering timelapse %(movie_basename)s": "Sammensetter timelapse %(movie_basename)s", "Documentation": "Dokumentasjon", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "Last opp", "ascending": "stigende", "Model size": "Modellst\u00f8rrelse", "Temperatures": "Temperaturer", "Timed": "Tidtakes", "Edit user \"%(user)s\"": "Endre bruker \"%(user)s\"", "Identifier": "", "Release SD card": "L\u00f8s ut minnekort", "Server is offline": "Server er frakoblet", "Log communication to serial.log (might negatively impact performance)": "Skriv logg til serial.log (kan redusere ytelsen)", "Sort by upload date": "Sorter etter opplastningsdato", "Change Password": "Endre passord", "Logs": "Logger", "Hotend": "Dyse", "Show retracts": "Vis tilbaketrekninger", "Keep Access Control Enabled": "Behold adgangskontroll aktivert", "Upload locally": "Last opp lokalt", "Do nothing": "", "Paused": "Pause", "Continue": "Fortsett", "Edit Printer Profile \"%(name)s\"": "", "The command \"%(command)s\" executed successfully": "Kommando \"%(command)s\" vellykket", "Features": "Funksjoner", "Download": "Last ned", "GCode Viewer": "GCode framviser", "Also show previous layer": "Ogs\u00e5 vis forrige lag", "Enable OctoPrint watermark in timelapse movies": "Aktiver OctoPrint vannmerke i timelapsefilmer", "Repetier": "Repeter", "Login successful": "Logg inn vellykket", "Finished Timelapses": "Ferdig timelapser", "Pause": "Pause", "GCode Filename": "GCode filnavn", "Access Control": "Adgangskontroll", "Start printing": "", "Swallow the first \"ok\" after a resend response": "Svelg unna f\u00f8rste \"ok\" etter svar", "Analyzing...": "Analyserer...", "just now": "Akkurat no", "Operational": "Operativ", "Send a checksum with every command": "Send en kontrollsum med alle kommandoer", "Autodetection timeout": "Automatisk detekteringstidsavbrudd", "Connecting": "Kobler til", "Free": "Ledig", "Closed": "Lukket", "Refresh SD files": "Oppdater minnekort", "Flip webcam vertically": "Inverter webcam vertikalt", "Starts the print job": "Starter utskriften", "Model": "", "Filament": "Tr\u00e5d", "Could not slice %(stl)s to %(gcode)s: %(reason)s": "Feilet \u00e5 slice %(stl)s til %(gcode)s: %(reason)s", "Baudrate": "Baudrate", "Snapshot URL": "Hurtigbilde URL", "Detecting baudrate": "Finner seriell hastighet", "Date": "Dato", "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds": "Str\u00f8mmet %(local)s til %(remote)s p\u00e5 minnekort, tok %(time).2f sekunder", "Show moves": "Vis forflyttninger", "Select a printer profile...": "", "Detecting serial port": "Finner serialport", "New Password": "Nytt passord", "Title": "Tittel", "Logout": "Logg ut", "Offset": "Avvik", "Analyzed": "Analysert", "Auto-connect on server startup": "Koble til automatisk ved oppstart", "E": "E", "Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s": "", "Restart": "Omstart", "Search...": "S\u00f8k...", "Slicing failed": "Slicing feilet", "Actual": "Faktisk", "Active": "Aktiv", "SD status timeout": "Minnekort tidsavbrudd", "Creation date": "Opprettelsesdato", "Hint: You can also drag and drop files on this page to upload them.": "Tips: Du kan ogs\u00e5 dra og slippe filer p\u00e5 denne siden for \u00e5 laste de opp", "Restarts the print job from the beginning": "Omstarter utskriftsjobben fra begynnelsen", "Interval": "Interval", "N/A": "N/A", "Bed": "Brett", "Auto-connect to printer on server start": "Koble til printer automatisk ved oppstart", "orange": "orange", "Connection": "Tilkobling", "Error": "Feil", "On Z Change": "Ved Z endring", "Timelapse post roll (in rendered seconds)": "Timelapse etter opptak (i sekunder)", "Z": "Z", "Edit Profile": "", "Are you sure you want to proceed?": "Er du sikker du vil fortsette?", "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!": "Hvis du sl\u00e5r av adgangskontroll og din OctoPrint innstallasjon er tilgjengelig fra internett, din printer vil bli tilgjengelig for alle - inkluderer ogs\u00e5 dei med u\u00e6rlige intensjoner", "Load": "Last", "Set": "Velg", "The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below.": "Serveren er tilsynelatende frakoblet, i det minste f\u00e5r jeg ikke noen respons fra den. Jeg kan ikke koble til den automatisk, du kan pr\u00f8ve en manuell oppkobling n\u00e5r du \u00f8nsker det ved \u00e5 bruke knappen nedenfor.", "Zoom in on model": "Zoom inn p\u00e5 modell", "Pauses the print job": "Pause utskriften", "After slicing...": "", "Saving ...": "Lagrer ...", "RegExp": "RegExp", "Watched Folder": "Kontrollert mappe", "General": "Generell", "Temperature timeout": "Temperatur tidsavbrudd", "Set as default profile": "", "Fans on": "Vifter p\u00e5", "Abort": "Avbryt", "Enable SD support": "Aktiver st\u00f8tte for minnekort", "Connect": "Koble til", "Cancel": "Avbryt", "visited": "bes\u00f8kt", "Warning": "Advarsel", "Loading...": "Laster...", "Current API Key": "N\u00e5v\u00e6rende API n\u00f8kkel", "Size": "St\u00f8rrelse", "Communication timeout": "Kommunikasjon tidsavbrudd", "Modification date": "Endret dato", "Slice": "Slice", "Change password": "Endre passord", "Layer number": "Lag nummer", "Cancels the print job": "Avbryter utskriftsjobben", "This will restart the print job from the beginning.": "Dette vil starte utskriftsjobbene fra starten", "Sort by": "Sorter etter", "Login failed": "Logg inn misslykkes", "Confirm": "Bekreft", "Repeat Password": "Gjenta passord", "Terminal": "Terminal", "Autoscroll": "Autoscroll", "Print time for layer": "Printtid for lag", "Disable Access Control": "Deaktiver adgangskontroll", "Configure Access Control": "Konfigurer adgangskontroll", "Timelapse Configuration": "Timelapse konfigurasjon", "Retract": "Tilbaketrekking", "Printer Profile": "", "Offline": "Frakoblet", "API Key": "API n\u00f8kkel", "Homepage": "Hjemmeside", "Estimated Print Time": "Bergenet utskriftstid", "Folders": "Mapper", "Select a slicer...": "Velg en slicer", "Printer Profiles": "", "Slicing %(filename)s": "Slicer %(filename)s", "Extruder Offsets": "Extruder avvik", "min": "min", "Only show STL files": "Vis kun STL filer", "Slicing ... (%(percentage)d%%)": "", "Connection timeout": "Oppkoblingstidsavbrudd", "Save config": "Lagre konfigurasjon", "Center viewport on model": "Sentrer bilde p\u00e5 modell", "User unknown or wrong password": "Bruker ukjent eller feil passord", "Volume": "", "default": "standard", "Heated Bed": "", "Appearance": "Utseende", "Enable": "Aktiver", "Uploading ...": "Laster opp ...", "Logs Folder": "Loggmappe", "

\n Please read the following, it is very important for your printer's health!\n

\n

\n OctoPrint by default now ships with Access Control enabled, meaning you won't be able to do anything with the\n printer unless you login first as a configured user. This is to prevent strangers - possibly with\n malicious intent - to gain access to your printer via the internet or another untrustworthy network\n and using it in such a way that it is damaged or worse (i.e. causes a fire).\n

\n

\n It looks like you haven't configured access control yet. Please set up an username and password for the\n initial administrator account who will have full access to both the printer and OctoPrint's settings, then click\n on \"Keep Access Control Enabled\":\n

": "

\nVennligst les f\u00f8lgende, det er veldig viktig for din printers helse!!\n

\n

\nOctoPrint kommer originalt med adgangskontroll aktivert, som betyr at du ikke f\u00e5r gjort noe med\nprinteren med mindre du logger inn med en konfigurert bruker. Dette er for \u00e5 forhindre ukjente - med potensielt\nu\u00e6rlige intensjoner - fra \u00e5 f\u00e5 tilgang til din printer via Internett eller et usikret nettverk\nog bruker den i en slik m\u00e5te at skade oppst\u00e5r eller verre (f.eks for\u00e5rsaker en brann).\n

\n

\nDu har ikke konfigurert adgangskontrollen enda. Vennligst sett et brukernavn og passord for den\nf\u00f8rste administratorkontoen som vil ha full adgang til b\u00e5de skriveren og OctoPrint innstillinger, klikk deretter p\u00e5\n\"Behold adgangskontroll aktivert\":\n

", "Hide successfully printed files": "Skjul vellykkede utskriftsfiler", "Username": "Brukernavn", "Select Tool...": "Velg verkt\u00f8y", "Off": "Av", "Name": "Navn", "Bugs and Requests": "Feilrapportering og \u00f8nsker", "Approx. Total Print Time": "Beregnet total utskriftstid", "Admin": "Admin", "

\n Note: In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't\n need Access Control for other reasons, you may alternatively disable Access Control. You should only\n do this if you are absolutely certain that only people you know and trust will be able to connect to it.\n

\n

\n Do NOT underestimate the risk of an unsecured access from the internet to your printer!\n

": "

\nNoter: Hvis din OctoPrint installasjon er p\u00e5 et nettverk som du er helt sikker p\u00e5 at det er kun du eller folk du stoler p\u00e5 og du ikke \u00f8nsker adgangskontroll av en eller annen grunn,\nkan du deaktivere adgangskontrollen. Du burde kun\ngj\u00f8re dette vist du er helt sikker p\u00e5 at det er bare folk du kjenner og stoler p\u00e5 som vil koble til printeren.\n

\n

\nIKKE undervurder faren ved en usikret adgang fra Internett til din printer!\n

", "Timelapse": "Timelapse", "QR Code": "", "Only show GCode files": "Bare vis GCode filer", "Remove": "Fjern", "Reload": "Last p\u00e5 nytt", "Printing": "Skriver ut", "printed": "Utskrevet", "Y": "Y", "Fans off": "Vifter av", "Login": "Logg inn", "Rectangular": "", "Timelapse ready": "Timelapse klar", "Timelapse Mode": "Timelapse modus", "Timelapse Folder": "Timelapse mappe", "Extruder": "Extruder", "Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and slicing support is enabled and configured.": "Klarte ikke \u00e5 laste opp filen, S\u00f8rg for at det er en GCODE fil med filtype \".gcode\" eller \".gco\" eller det er en STL fil med filtype \".stl\" og at slicing er aktivert og konfigurert.", "Printed": "Utskrevet", "SD not initialized": "Minnekort er ikke startet", "Update User": "Oppdater bruker", "off": "Av", "Serial Port": "Seriellport", "Flip webcam horizontally": "Inverter webcam horisontalt", "Resumes the print job": "Fortsetter utskriften", "Transfering file to SD": "Overf\u00f8rer til minnekort", "OctoPrint": "OctoPrint", "Layer height": "Lag h\u00f8yde", "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds": "Sliced %(stl)s til %(gcode)s, tok %(time).2f sekunder", "Extrude": "Extrude", "green": "gr\u00f8nn", "File": "Fil", "You are now logged in as \"%(username)s\"": "Du er no logget inn som \"%(username)s\"", "Axis": "Akse", "Filament used by layer": "Tr\u00e5d brukt i laget", "Please configure which slicer and which slicing profile to use and name the GCode file to slice to below, or click \"Cancel\" if you do not wish to slice the file now.": "Vennligst konfigurer hvilken slicer og profil for bruk og velg GCode fil for slicing nedenfor, eller trykk \"Avbryt\" hvis du ikke \u00f8nsker \u00e5 slice filen no."}} ; \ No newline at end of file diff --git a/src/octoprint/static/js/i18n/ro.js b/src/octoprint/static/js/i18n/ro.js index 153482d94..f196ae054 100644 --- a/src/octoprint/static/js/i18n/ro.js +++ b/src/octoprint/static/js/i18n/ro.js @@ -1 +1 @@ -window.BABEL_TO_LOAD_ro = {"locale": "ro", "domain": "messages", "plural_expr": "(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2:1))", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-08-28 15:52+0200\nPO-Revision-Date: 2014-08-31 16:21+0000\nLast-Translator: 3Dmaker4U <3dmaker4u@gmail.com>\nLanguage-Team: Romanian (http://www.transifex.com/projects/p/octoprint/language/ro/)\nPlural-Forms: nplurals=3; plural=(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2:1))\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Timp de imprimare r\u0103mas", "Proceed": "Continuare", "Timelapse Temp Folder": "Director temporar pentru \u00eenregistrarea rapid\u0103", "Title": "Titlu", "Only show files stored locally": "Arat\u0103 doar fi\u0219ierele stocate local", "yellow": "galben", "Path to Cura": "Cale c\u0103tre Cura", "Action": "Ac\u021biune", "Passwords do not match": "Parolele nu se potrivesc", "Sort by name": "Sortare dup\u0103 nume", "Save connection settings": "Salvare configura\u021bie conexiune", "Rendering timelapse": "Redare \u00eenregistrare rapid\u0103", "Cura": "Cura", "Files": "Fi\u0219iere", "Bed Size": "M\u0103rime mas\u0103", "Always assume SD card is present": "Consider\u0103 \u00eentotdeauna cardul SD prezent", "Load and Print": "\u00cenc\u0103rcare \u0219i imprimare", "Sending file to SD": "Se transmite fi\u0219ierul c\u0103tre SD", "Number of Extruders": "Num\u0103r de extrudere", "black": "negru", "Last Printed": "Ultima dat\u0103 imprimat", "Sourcecode": "Cod surs\u0103", "Estimated layer height": "\u00cen\u0103l\u021bimea stratului estimat\u0103", "You are now logged out": "Acum e\u0219ti deconectat", "Uploaded": "\u00cenc\u0103rcat", "Opening serial port": "Se deschide portul serial", "New timelapse %(movie_basename)s is done rendering.": "Redarea noii \u00eenregistr\u0103ri rapide %(movie_basename)s s-a terminat.", "Invert control": "Inversare comand\u0103", "Webcam": "Webcam", "Remember me": "\u021aine-m\u0103 minte", "Enable GCode Visualizer": "Activeaz\u0103 vizualizarea GCode", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below.": "Se pare c\u0103 serverul nu este connectat sau, cel pu\u021bin, mie nu-mi r\u0103spunde. Voi \u00eencerca s\u0103 m\u0103 reconectez automat \u00een urm\u0103toarele dou\u0103 minute, dar po\u021bi \u00eencerca oric\u00e2nd s\u0103 te reconectezi manual utiliz\u00e2nd butonul de mai jos.", "Rendering failed": "Redarea a e\u0219uat", "Upload Folder": "\u00cencarc\u0103 director", "descending": "descresc\u0103tor", "X": "X", "Add user": "Ad\u0103ugare utilizator", "GCODE commands in layer": "comenzi GCODE \u00een strat", "Estimated print time": "Timp de imprimare estimat", "Serial Connection": "Conexiune serial\u0103", "Control": "Control", "Password": "Parol\u0103", "Also show next layer": "Vizualizare strat urm\u0103tor", "Print Time": "Timp de imprimare", "Sort by file size": "Sortare dup\u0103 m\u0103rimea fi\u0219ierului", "Machine State": "Starea ma\u0219inii", "default": "implicit", "API": "API", "Printing from SD": "Se imprim\u0103 de pe SD", "Terminal filters": "Filtre pentru terminal", "Change password for user \"%(user)s\"": "Modificare parol\u0103 pentru utilizatorul \"%(user)s\"", "Enable Temperature Graph": "Activeaz\u0103 graficul temperaturii", "Delete user": "\u0218tergere utilizator", "Confirm Password": "Confirmare parol\u0103", "Disconnect": "Deconectare", "Slicing done": "Feliere terminat\u0103", "Initialize SD card": "Ini\u021bializare card SD", "System": "Sistem", "Send": "Trimitere", "State": "Stare", "Version": "Versiune", "YYYY-MM-DD HH:mm": "DD.MM.YYYY HH.mm", "Attempt to reconnect": "\u00cencercare de reconectare", "Streaming done": "Transmiterea s-a terminat", "violet": "violet", "Print": "Imprimare", "Layer count": "Num\u0103r de straturi", "OctoPrint Settings": "Configurare OctoPrint", "Are you sure?": "E\u0219ti sigur?", "blue": "albastru", "Printer": "Imprimant\u0103", "Tool": "Unealt\u0103", "Settings": "Configura\u021bii", "Path to FFMPEG": "Cale c\u0103tre FFMPEG", "Upload to SD": "\u00cenc\u0103rcare pe SD", "The command \"%(command)s\" could not be executed.": "Comanda \"%(command)s\" nu a putut fi executat\u0103.", "Printed": "Imprimat", "Layer number": "Num\u0103rul stratului", "Sync with job progress": "Sincronizare cu stadiul lucr\u0103rii", "Circular": "Circular", "Total filament used": "Filament utilizat \u00een total", "red": "ro\u0219u", "Save as default": "Salvare ca valori implicite", "Slicing ...": "Se feliaz\u0103...", "Last Print Time": "Ultima imprimare a durat", "Target": "\u021aint\u0103", "Streaming ...": "Se transmite...", "Logout successful": "Deconectare reu\u0219it\u0103", "Now rendering timelapse %(movie_basename)s": "Acum se red\u0103 \u00eenregistrarea rapid\u0103 %(movie_basename)s", "Documentation": "Documenta\u021bie", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "\u00cenc\u0103rcare", "ascending": "cresc\u0103tor", "Model size": "M\u0103rimea modelului", "Temperatures": "Temperaturi", "visited": "vizitat", "Timed": "Temporizat", "Edit user \"%(user)s\"": "Editare utilizator \"%(user)s\"", "Snapshot URL": "URL imagine capturat\u0103", "Release SD card": "Elibereaz\u0103 cardul SD", "Server is offline": "Serverul este deconectat", "Log communication to serial.log (might negatively impact performance)": "\u00cenregistrare comunica\u021bie \u00een serial.log (poate afecta negativ performan\u021ba)", "Sort by upload date": "Sortare dup\u0103 data \u00eenc\u0103rc\u0103rii", "Change Password": "Schimb\u0103 parola", "Logs": "\u00cenregistr\u0103ri activitate", "Hotend": "Hotend", "Show retracts": "Vizualizare retgrageri", "Keep Access Control Enabled": "Men\u021bine controlul accesului activat", "Upload locally": "\u00cenc\u0103rcare local\u0103", "Select Tool...": "Selectare unealt\u0103...", "Paused": "\u00cen pauz\u0103", "Continue": "Continuare", "Radius": "Raz\u0103", "The command \"%(command)s\" executed successfully": "Comanda \"%(command)s\" a fost executat\u0103 cu succes", "Features": "Caracteristici", "Download": "Desc\u0103rcare", "GCode Viewer": "Vizualizare GCode", "Also show previous layer": "Vizualizare strat anterior", "Enable OctoPrint watermark in timelapse movies": "Activeaz\u0103 marcajul OctoPrint \u00een \u00eenregistr\u0103rile rapide", "Repetier": "Repetier", "Login successful": "Conectare reu\u0219it\u0103", "Finished Timelapses": "\u00cenregistr\u0103ri rapide finalizate", "Rendering of timelapse %(movie_basename)s failedwith return code %(returncode)s": "Redarea \u00eenregistr\u0103rii rapide %(movie_basename)s a e\u0219uat, codul de eroare fiind %(returncode)s", "Pause": "Pauz\u0103", "Temperature": "Temperatur\u0103", "Enable slicing via Cura": "Activeaz\u0103 feliere prin Cura", "Access Control": "Control acces", "Analyzing...": "Se analizeaz\u0103...", "just now": "chiar acum", "Operational": "Func\u021bional", "Send a checksum with every command": "Transmite suma de control cu fiecare comand\u0103", "Autodetection timeout": "Expirare temporizare autodetectare", "Connecting": "Se conecteaz\u0103", "Free": "Liber", "Closed": "\u00cenchis", "Refresh SD files": "Re\u00eemprosp\u0103teaz\u0103 fi\u0219ierele SD", "Flip webcam vertically": "Rote\u0219te camera pe vertical\u0103", "Path to Cura config": "Cale c\u0103tre configura\u021bia Cura", "Filament": "Filament", "Could not slice %(stl)s to %(gcode)s: %(reason)s": "Nu s-a putut felia %(stl)s \u00een %(gcode)s: %(reason)s", "Baudrate": "Vitez\u0103 de transfer", "Detecting baudrate": "Se detecteaz\u0103 viteza de transfer", "Date": "Dat\u0103", "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds": "Transmiterea %(local)s c\u0103tre %(remote)s pe SD, a durat %(time).2f secunde", "Show moves": "Vizualizare mi\u0219c\u0103ri", "Motors off": "Oprire motoare", "Detecting serial port": "Se detecteaz\u0103 portul serial", "New Password": "Parol\u0103 nou\u0103", "Logout": "Deconectare", "Offset": "Decalaj", "Analyzed": "Analizat", "Auto-connect on server startup": "Conectare automat\u0103 la pornirea serverului", "Printer Parameters": "Parametrii imprimantei", "E": "E", "Restart": "Reluare", "Search...": "Se caut\u0103...", "Slicing failed": "Felierea a e\u0219uat", "Actual": "Efectiv", "Active": "Activ", "Creation date": "Dat\u0103 creare", "Hint: You can also drag and drop files on this page to upload them.": "Indiciu: Po\u021bi trage \u0219i l\u0103sa fi\u0219ierele pe aceast\u0103 pagin\u0103 pentru a le \u00eenc\u0103rca.", "Interval": "Interval", "N/A": "N/A", "Bed": "Mas\u0103", "Auto-connect to printer on server start": "Conectare automat\u0103 a imprimantei la pornirea serverului", "orange": "portocaliu", "Connection": "Conexiune", "Error": "Eroare", "On Z Change": "La schimbarea Z", "Timelapse post roll (in rendered seconds)": "\u00cent\u00e2rziere oprire \u00eenregistrare automat\u0103 (\u00een secunde vizualizate)", "Z": "Z", "Are you sure you want to proceed?": "E\u0219ti sigur c\u0103 vrei s\u0103 mergi mai departe?", "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!": "Dac\u0103 dezactivezi controlul accesului \u0219i aplica\u021bia ta OctoPrint este accesibil\u0103 din Internet, imprimanta ta va putea fi accesat\u0103 de oricine - asta incluz\u00e2nd \u0219i tipii r\u0103i!", "Load": "\u00cenc\u0103rcare", "Set": "Configurare", "The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below.": "Se pare c\u0103 serverul nu este conectat sau, cel pu\u021bin, mie nu-mi r\u0103spunde. Eu nu pot s\u0103 m\u0103 reconectez automat, dar po\u021bi \u00eencerca s\u0103 te reconectezi manual utiliz\u00e2nd butonul de mai jos.", "Zoom in on model": "M\u0103rire model", "mm": "mm", "Saving ...": "Se salveaz\u0103...", "RegExp": "RegExp", "Watched Folder": "Director pentru \u00eenregistr\u0103ri rapide vizionate", "General": "General", "Temperature timeout": "Expirare temporizare temperatur\u0103", "Color": "Culoare", "Fans on": "Pornire ventilatoare", "Swallow the first \"ok\" after a resend response": "Ascunde primul \"ok\" dup\u0103 un r\u0103spuns retransmis", "Enable SD support": "Activeaz\u0103 suportul pentru SD", "Connect": "Connectare", "Cancel": "Abandonare", "sec": "sec", "Warning": "Avertizare", "Loading...": "Se \u00eencarc\u0103", "Current API Key": "Cheie API curent\u0103", "Size": "M\u0103rime", "Communication timeout": "Expirare temporizare comunica\u021bie", "Modification date": "Data modific\u0103rii", "Change password": "Modificare parol\u0103", "This will restart the print job from the beginning.": "Se va relua imprimarea de la \u00eenceput.", "Stream URL": "URL flux video", "Sort by": "Sortare dup\u0103", "Login failed": "Conectare e\u0219uat\u0103", "Abort": "Abandonare", "Confirm": "Confirmare", "Repeat Password": "Repetare parol\u0103", "Terminal": "Terminal", "Autoscroll": "Defilare automat\u0103", "Print time for layer": "Timp de imprimare pentru strat", "Disable Access Control": "Dezactiveaz\u0103 controlul accesului", "Configure Access Control": "Configurare control acces", "Timelapse Configuration": "Configurare \u00eenregistrare rapid\u0103", "Retract": "Retragere", "Timelapse bitrate": "Vitez\u0103 \u00eenregistrare rapid\u0103", "Offline": "Neconectat", "API Key": "Cheie API", "Homepage": "Pagina de gard\u0103", "Estimated Print Time": "Timp de imprimare estimat", "Folders": "Directoare", "Bugs and Requests": "Probleme \u0219i solicit\u0103ri", "Save": "Salvare", "Default extrusion length": "Lungime implicit\u0103 a extuziunii", "min": "min", "Support TargetExtr%%n/TargetBed target temperature format": "Sus\u021bine formatul TargetExtr%%n/TargetBed pentru temperatura \u021bint\u0103", "Connection timeout": "Expirare temporizare conexiune", "Save config": "Salvare configura\u021bie", "Center viewport on model": "Centrare ecran pe model", "User unknown or wrong password": "Utilizator necunoscut sau parol\u0103 gre\u0219it\u0103", "Allow Cross Origin Resource Sharing (CORS)": "Permite Cross Origin Resource Sharing (CORS)", "Appearance": "Aspect", "Enable": "Activare", "Uploading ...": "Se \u00eencarc\u0103...", "Logs Folder": "Director pentru \u00eenregistrarea activit\u0103\u021bii", "

\n Please read the following, it is very important for your printer's health!\n

\n

\n OctoPrint by default now ships with Access Control enabled, meaning you won't be able to do anything with the\n printer unless you login first as a configured user. This is to prevent strangers - possibly with\n malicious intent - to gain access to your printer via the internet or another untrustworthy network\n and using it in such a way that it is damaged or worse (i.e. causes a fire).\n

\n

\n It looks like you haven't configured access control yet. Please set up an username and password for the\n initial administrator account who will have full access to both the printer and OctoPrint's settings, then click\n on \"Keep Access Control Enabled\":\n

": "

\nTe rog s\u0103 cite\u0219ti \u00een continuare, este foarte important pentru siguran\u021ba imprimantei tale!\n

\n

\nOctoPrint este livrat acum cu controlul accesului activat implicit, ceea ce \u00eenseamn\u0103 c\u0103 nu vei putea face nimic cu\nimprimanta, dac\u0103 nu te vei conecta mai \u00eent\u00e2i ca un utilizator declarat. Asta este pentru a \u00eempiedica persoanele str\u0103ine - av\u00e2nd poate\ninten\u021bii r\u0103uvoitoare - s\u0103 acceseze imprimanta ta din Internet sau prin alte re\u021bele nesigure\n\u0219i s\u0103 o utilizeze \u00eentr-un mod care s\u0103 o poat\u0103 deteriora sau \u0219i mai r\u0103u (de exemplu s\u0103 declan\u0219eze un incendiu).\n

\n

\nSe pare c\u0103 nu ai configurat \u00eenc\u0103 modul de control al accesului. Te rog stabile\u0219te un nume de utilizator \u0219i o parol\u0103 pentru \ncontul ini\u021bial de administrator, care va avea acces deplin la configura\u021biile imprimantei \u0219i OctoPrint, apoi apas\u0103 \n\"Men\u021bine controlul accesului activat\":\n

", "Hide successfully printed files": "Ascunde fi\u0219ierele imprimate cu succes", "Username": "Numele utilizatorului", "Off": "Oprit", "Name": "Nume", "Extruder Offsets": "Decalaje extruder", "Approx. Total Print Time": "Timp de imprimare total estimat", "Admin": "Admin", "

\n Note: In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't\n need Access Control for other reasons, you may alternatively disable Access Control. You should only\n do this if you are absolutely certain that only people you know and trust will be able to connect to it.\n

\n

\n Do NOT underestimate the risk of an unsecured access from the internet to your printer!\n

": "

\nNot\u0103: \u00cen cazul \u00een care aplica\u021bia ta OctoPrint este accesibil\u0103 doar dintr-o re\u021bea sigur\u0103 \u0219i nu\nai nevoie de controlul accesului pentru alte mootive, po\u021bi s\u0103 dezactivezi controlul accesului. \u00ce\u021bi recomand asta\nnumai dac\u0103 e\u0219ti absolut sigur c\u0103 se vor putea conecta doar oameni pe care \u00eei cuno\u0219ti \u0219i \u00een care ai \u00eencredere.\n

\n

\nNU subestima riscul pe care-l prezint\u0103 accesul nesecurizat din Internet la imprimanta ta!\n

", "Timelapse": "\u00cenregistrare rapid\u0103", "Remove": "\u0218tergere", "Reload": "Re\u00eenc\u0103rcare", "Printing": "Se imprim\u0103", "Only show files stored on SD": "Arat\u0103 doar fi\u0219ierele stocate pe SD", "Y": "Y", "Fans off": "Oprire ventilatoare", "Login": "Conectare", "Timelapse ready": "\u00cenregistrarea rapid\u0103 este gata", "Timelapse Mode": "Mod \u00eenregistrare rapid\u0103", "Timelapse Folder": "Director pentru \u00eenregistrarea rapid\u0103", "Extruder": "Extruder", "Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and slicing support is enabled and configured.": "Nu pot \u00eenc\u0103rca fi\u0219ierul. Asigur\u0103-te c\u0103 este un fi\u0219ier GCODE \u0219i c\u0103 are extensia \".gcode\" sau \".gco\" sau c\u0103 este un fi\u0219ier STL cu extensia \".stl\" \u0219i c\u0103 felierea este activat\u0103 \u0219i configurat\u0103.", "SD status timeout": "Expirare temporizare stare SD", "SD not initialized": "SD nu este ini\u021bializat", "Update User": "Actualizare utilizator", "off": "oprit", "Serial Port": "Port serial", "Flip webcam horizontally": "Rote\u0219te camera pe orizontal\u0103", "Wait for start on connect": "A\u0219teapt\u0103 start la conectare", "Transfering file to SD": "Se transfer\u0103 fi\u0219ierul pe SD", "OctoPrint": "OctoPrint", "Layer height": "\u00cen\u0103l\u021bimea stratului", "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds": "S-a feliat %(stl)s ca %(gcode)s \u00een %(time).2f secunde", "Extrude": "Extrudare", "green": "verde", "File": "Fi\u0219ier", "You are now logged in as \"%(username)s\"": "Acum e\u0219ti conectat ca \"%(username)s\"", "Axis": "Ax\u0103", "Filament used by layer": "Filament utilizat \u00een strat"}} ; \ No newline at end of file +window.BABEL_TO_LOAD_ro = {"locale": "ro", "domain": "messages", "plural_expr": "(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2:1))", "messages": {"": "Project-Id-Version: OctoPrint\nReport-Msgid-Bugs-To: i18n@octoprint.org\nPOT-Creation-Date: 2014-12-18 14:45+0100\nPO-Revision-Date: 2014-12-18 14:04+0000\nLast-Translator: Gina H\u00e4u\u00dfge \nLanguage-Team: Romanian (http://www.transifex.com/projects/p/octoprint/language/ro/)\nPlural-Forms: nplurals=3; plural=(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2:1))\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\nGenerated-By: Babel 1.3\n", "Print Time Left": "Timp de imprimare r\u0103mas", "sec": "sec", "Proceed": "Continuare", "Timelapse Temp Folder": "Director temporar pentru \u00eenregistrarea rapid\u0103", "Support TargetExtr%%n/TargetBed target temperature format": "Sus\u021bine formatul TargetExtr%%n/TargetBed pentru temperatura \u021bint\u0103", "Upload Folder": "\u00cencarc\u0103 director", "Only show files stored locally": "Arat\u0103 doar fi\u0219ierele stocate local", "Add Printer Profile": "", "yellow": "galben", "Save": "Salvare", "Action": "Ac\u021biune", "Passwords do not match": "Parolele nu se potrivesc", "Sort by name": "Sortare dup\u0103 nume", "Save connection settings": "Salvare configura\u021bie conexiune", "Rendering timelapse": "Redare \u00eenregistrare rapid\u0103", "Color": "Culoare", "Temperature": "Temperatur\u0103", "Files": "Fi\u0219iere", "Resume": "", "Always assume SD card is present": "Consider\u0103 \u00eentotdeauna cardul SD prezent", "Load and Print": "\u00cenc\u0103rcare \u0219i imprimare", "Sending file to SD": "Se transmite fi\u0219ierul c\u0103tre SD", "Number of Extruders": "Num\u0103r de extrudere", "black": "negru", "Last Printed": "Ultima dat\u0103 imprimat", "Sourcecode": "Cod surs\u0103", "Estimated layer height": "\u00cen\u0103l\u021bimea stratului estimat\u0103", "You are now logged out": "Acum e\u0219ti deconectat", "Uploaded": "\u00cenc\u0103rcat", "Form Factor": "", "Opening serial port": "Se deschide portul serial", "New timelapse %(movie_basename)s is done rendering.": "Redarea noii \u00eenregistr\u0103ri rapide %(movie_basename)s s-a terminat.", "Invert control": "Inversare comand\u0103", "Webcam": "Webcam", "Select for printing": "", "Allow Cross Origin Resource Sharing (CORS)": "Permite Cross Origin Resource Sharing (CORS)", "Remember me": "\u021aine-m\u0103 minte", "Enable GCode Visualizer": "Activeaz\u0103 vizualizarea GCode", "The server appears to be offline, at least I'm not getting any response from it. I'll try to reconnect automatically over the next couple of minutes, however you are welcome to try a manual reconnect anytime using the button below.": "Se pare c\u0103 serverul nu este connectat sau, cel pu\u021bin, mie nu-mi r\u0103spunde. Voi \u00eencerca s\u0103 m\u0103 reconectez automat \u00een urm\u0103toarele dou\u0103 minute, dar po\u021bi \u00eencerca oric\u00e2nd s\u0103 te reconectezi manual utiliz\u00e2nd butonul de mai jos.", "Rendering failed": "Redarea a e\u0219uat", "Motors off": "Oprire motoare", "descending": "descresc\u0103tor", "Only show files stored on SD": "Arat\u0103 doar fi\u0219ierele stocate pe SD", "X": "X", "Add user": "Ad\u0103ugare utilizator", "GCODE commands in layer": "comenzi GCODE \u00een strat", "Estimated print time": "Timp de imprimare estimat", "Serial Connection": "Conexiune serial\u0103", "Control": "Control", "Password": "Parol\u0103", "Also show next layer": "Vizualizare strat urm\u0103tor", "Print Time": "Timp de imprimare", "Slicer": "", "Nozzle Diameter": "", "Sort by file size": "Sortare dup\u0103 m\u0103rimea fi\u0219ierului", "Machine State": "Starea ma\u0219inii", "Slicing Profile": "", "mm": "mm", "API": "API", "Printing from SD": "Se imprim\u0103 de pe SD", "Stream URL": "URL flux video", "Terminal filters": "Filtre pentru terminal", "Change password for user \"%(user)s\"": "Modificare parol\u0103 pentru utilizatorul \"%(user)s\"", "Enable Temperature Graph": "Activeaz\u0103 graficul temperaturii", "Delete user": "\u0218tergere utilizator", "Timelapse bitrate": "Vitez\u0103 \u00eenregistrare rapid\u0103", "Confirm Password": "Confirmare parol\u0103", "Disconnect": "Deconectare", "Slicing done": "Feliere terminat\u0103", "Initialize SD card": "Ini\u021bializare card SD", "System": "Sistem", "Send": "Trimitere", "State": "Stare", "Version": "Versiune", "YYYY-MM-DD HH:mm": "DD.MM.YYYY HH.mm", "Attempt to reconnect": "\u00cencercare de reconectare", "Streaming done": "Transmiterea s-a terminat", "violet": "violet", "Print": "Imprimare", "Layer count": "Num\u0103r de straturi", "OctoPrint Settings": "Configurare OctoPrint", "Are you sure?": "E\u0219ti sigur?", "blue": "albastru", "Printer": "Imprimant\u0103", "Delete Profile": "", "Tool": "Unealt\u0103", "Settings": "Configura\u021bii", "Circular": "Circular", "Path to FFMPEG": "Cale c\u0103tre FFMPEG", "Upload to SD": "\u00cenc\u0103rcare pe SD", "The command \"%(command)s\" could not be executed.": "Comanda \"%(command)s\" nu a putut fi executat\u0103.", "Select a slicing profile...": "", "Wait for start on connect": "A\u0219teapt\u0103 start la conectare", "Sync with job progress": "Sincronizare cu stadiul lucr\u0103rii", "Calculating...": "", "Total filament used": "Filament utilizat \u00een total", "red": "ro\u0219u", "Save as default": "Salvare ca valori implicite", "Slicing ...": "Se feliaz\u0103...", "Last Print Time": "Ultima imprimare a durat", "Target": "\u021aint\u0103", "Add Profile...": "", "Streaming ...": "Se transmite...", "Logout successful": "Deconectare reu\u0219it\u0103", "Now rendering timelapse %(movie_basename)s": "Acum se red\u0103 \u00eenregistrarea rapid\u0103 %(movie_basename)s", "Documentation": "Documenta\u021bie", "%(hour)02d:%(minute)02d:%(second)02d": "%(hour)02d:%(minute)02d:%(second)02d", "Upload": "\u00cenc\u0103rcare", "ascending": "cresc\u0103tor", "Model size": "M\u0103rimea modelului", "Temperatures": "Temperaturi", "Timed": "Temporizat", "Edit user \"%(user)s\"": "Editare utilizator \"%(user)s\"", "Identifier": "", "Release SD card": "Elibereaz\u0103 cardul SD", "Server is offline": "Serverul este deconectat", "Log communication to serial.log (might negatively impact performance)": "\u00cenregistrare comunica\u021bie \u00een serial.log (poate afecta negativ performan\u021ba)", "Sort by upload date": "Sortare dup\u0103 data \u00eenc\u0103rc\u0103rii", "Change Password": "Schimb\u0103 parola", "Logs": "\u00cenregistr\u0103ri activitate", "Hotend": "Hotend", "Show retracts": "Vizualizare retgrageri", "Keep Access Control Enabled": "Men\u021bine controlul accesului activat", "Upload locally": "\u00cenc\u0103rcare local\u0103", "Do nothing": "", "Paused": "\u00cen pauz\u0103", "Continue": "Continuare", "Edit Printer Profile \"%(name)s\"": "", "The command \"%(command)s\" executed successfully": "Comanda \"%(command)s\" a fost executat\u0103 cu succes", "Features": "Caracteristici", "Download": "Desc\u0103rcare", "GCode Viewer": "Vizualizare GCode", "Also show previous layer": "Vizualizare strat anterior", "Enable OctoPrint watermark in timelapse movies": "Activeaz\u0103 marcajul OctoPrint \u00een \u00eenregistr\u0103rile rapide", "Repetier": "Repetier", "Login successful": "Conectare reu\u0219it\u0103", "Finished Timelapses": "\u00cenregistr\u0103ri rapide finalizate", "Pause": "Pauz\u0103", "GCode Filename": "", "Access Control": "Control acces", "Start printing": "", "Swallow the first \"ok\" after a resend response": "Ascunde primul \"ok\" dup\u0103 un r\u0103spuns retransmis", "Analyzing...": "Se analizeaz\u0103...", "just now": "chiar acum", "Operational": "Func\u021bional", "Send a checksum with every command": "Transmite suma de control cu fiecare comand\u0103", "Autodetection timeout": "Expirare temporizare autodetectare", "Connecting": "Se conecteaz\u0103", "Free": "Liber", "Closed": "\u00cenchis", "Refresh SD files": "Re\u00eemprosp\u0103teaz\u0103 fi\u0219ierele SD", "Flip webcam vertically": "Rote\u0219te camera pe vertical\u0103", "Starts the print job": "", "Model": "", "Filament": "Filament", "Could not slice %(stl)s to %(gcode)s: %(reason)s": "Nu s-a putut felia %(stl)s \u00een %(gcode)s: %(reason)s", "Baudrate": "Vitez\u0103 de transfer", "Snapshot URL": "URL imagine capturat\u0103", "Detecting baudrate": "Se detecteaz\u0103 viteza de transfer", "Date": "Dat\u0103", "Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds": "Transmiterea %(local)s c\u0103tre %(remote)s pe SD, a durat %(time).2f secunde", "Show moves": "Vizualizare mi\u0219c\u0103ri", "Select a printer profile...": "", "Detecting serial port": "Se detecteaz\u0103 portul serial", "New Password": "Parol\u0103 nou\u0103", "Title": "Titlu", "Logout": "Deconectare", "Offset": "Decalaj", "Analyzed": "Analizat", "Auto-connect on server startup": "Conectare automat\u0103 la pornirea serverului", "E": "E", "Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s": "", "Restart": "Reluare", "Search...": "Se caut\u0103...", "Slicing failed": "Felierea a e\u0219uat", "Actual": "Efectiv", "Active": "Activ", "SD status timeout": "Expirare temporizare stare SD", "Creation date": "Dat\u0103 creare", "Hint: You can also drag and drop files on this page to upload them.": "Indiciu: Po\u021bi trage \u0219i l\u0103sa fi\u0219ierele pe aceast\u0103 pagin\u0103 pentru a le \u00eenc\u0103rca.", "Restarts the print job from the beginning": "", "Interval": "Interval", "N/A": "N/A", "Bed": "Mas\u0103", "Auto-connect to printer on server start": "Conectare automat\u0103 a imprimantei la pornirea serverului", "orange": "portocaliu", "Connection": "Conexiune", "Error": "Eroare", "On Z Change": "La schimbarea Z", "Timelapse post roll (in rendered seconds)": "\u00cent\u00e2rziere oprire \u00eenregistrare automat\u0103 (\u00een secunde vizualizate)", "Z": "Z", "Edit Profile": "", "Are you sure you want to proceed?": "E\u0219ti sigur c\u0103 vrei s\u0103 mergi mai departe?", "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!": "Dac\u0103 dezactivezi controlul accesului \u0219i aplica\u021bia ta OctoPrint este accesibil\u0103 din Internet, imprimanta ta va putea fi accesat\u0103 de oricine - asta incluz\u00e2nd \u0219i tipii r\u0103i!", "Load": "\u00cenc\u0103rcare", "Set": "Configurare", "The server appears to be offline, at least I'm not getting any response from it. I could not reconnect automatically, but you may try a manual reconnect using the button below.": "Se pare c\u0103 serverul nu este conectat sau, cel pu\u021bin, mie nu-mi r\u0103spunde. Eu nu pot s\u0103 m\u0103 reconectez automat, dar po\u021bi \u00eencerca s\u0103 te reconectezi manual utiliz\u00e2nd butonul de mai jos.", "Zoom in on model": "M\u0103rire model", "Pauses the print job": "", "After slicing...": "", "Saving ...": "Se salveaz\u0103...", "RegExp": "RegExp", "Watched Folder": "Director pentru \u00eenregistr\u0103ri rapide vizionate", "General": "General", "Temperature timeout": "Expirare temporizare temperatur\u0103", "Set as default profile": "", "Fans on": "Pornire ventilatoare", "Abort": "Abandonare", "Enable SD support": "Activeaz\u0103 suportul pentru SD", "Connect": "Connectare", "Cancel": "Abandonare", "visited": "vizitat", "Warning": "Avertizare", "Loading...": "Se \u00eencarc\u0103", "Current API Key": "Cheie API curent\u0103", "Size": "M\u0103rime", "Communication timeout": "Expirare temporizare comunica\u021bie", "Modification date": "Data modific\u0103rii", "Slice": "", "Change password": "Modificare parol\u0103", "Layer number": "Num\u0103rul stratului", "Cancels the print job": "", "This will restart the print job from the beginning.": "Se va relua imprimarea de la \u00eenceput.", "Sort by": "Sortare dup\u0103", "Login failed": "Conectare e\u0219uat\u0103", "Confirm": "Confirmare", "Repeat Password": "Repetare parol\u0103", "Terminal": "Terminal", "Autoscroll": "Defilare automat\u0103", "Print time for layer": "Timp de imprimare pentru strat", "Disable Access Control": "Dezactiveaz\u0103 controlul accesului", "Configure Access Control": "Configurare control acces", "Timelapse Configuration": "Configurare \u00eenregistrare rapid\u0103", "Retract": "Retragere", "Printer Profile": "", "Offline": "Neconectat", "API Key": "Cheie API", "Homepage": "Pagina de gard\u0103", "Estimated Print Time": "Timp de imprimare estimat", "Folders": "Directoare", "Select a slicer...": "", "Printer Profiles": "", "Slicing %(filename)s": "", "Extruder Offsets": "Decalaje extruder", "min": "min", "Only show STL files": "", "Slicing ... (%(percentage)d%%)": "", "Connection timeout": "Expirare temporizare conexiune", "Save config": "Salvare configura\u021bie", "Center viewport on model": "Centrare ecran pe model", "User unknown or wrong password": "Utilizator necunoscut sau parol\u0103 gre\u0219it\u0103", "Volume": "", "default": "implicit", "Heated Bed": "", "Appearance": "Aspect", "Enable": "Activare", "Uploading ...": "Se \u00eencarc\u0103...", "Logs Folder": "Director pentru \u00eenregistrarea activit\u0103\u021bii", "

\n Please read the following, it is very important for your printer's health!\n

\n

\n OctoPrint by default now ships with Access Control enabled, meaning you won't be able to do anything with the\n printer unless you login first as a configured user. This is to prevent strangers - possibly with\n malicious intent - to gain access to your printer via the internet or another untrustworthy network\n and using it in such a way that it is damaged or worse (i.e. causes a fire).\n

\n

\n It looks like you haven't configured access control yet. Please set up an username and password for the\n initial administrator account who will have full access to both the printer and OctoPrint's settings, then click\n on \"Keep Access Control Enabled\":\n

": "

\nTe rog s\u0103 cite\u0219ti \u00een continuare, este foarte important pentru siguran\u021ba imprimantei tale!\n

\n

\nOctoPrint este livrat acum cu controlul accesului activat implicit, ceea ce \u00eenseamn\u0103 c\u0103 nu vei putea face nimic cu\nimprimanta, dac\u0103 nu te vei conecta mai \u00eent\u00e2i ca un utilizator declarat. Asta este pentru a \u00eempiedica persoanele str\u0103ine - av\u00e2nd poate\ninten\u021bii r\u0103uvoitoare - s\u0103 acceseze imprimanta ta din Internet sau prin alte re\u021bele nesigure\n\u0219i s\u0103 o utilizeze \u00eentr-un mod care s\u0103 o poat\u0103 deteriora sau \u0219i mai r\u0103u (de exemplu s\u0103 declan\u0219eze un incendiu).\n

\n

\nSe pare c\u0103 nu ai configurat \u00eenc\u0103 modul de control al accesului. Te rog stabile\u0219te un nume de utilizator \u0219i o parol\u0103 pentru \ncontul ini\u021bial de administrator, care va avea acces deplin la configura\u021biile imprimantei \u0219i OctoPrint, apoi apas\u0103 \n\"Men\u021bine controlul accesului activat\":\n

", "Hide successfully printed files": "Ascunde fi\u0219ierele imprimate cu succes", "Username": "Numele utilizatorului", "Select Tool...": "Selectare unealt\u0103...", "Off": "Oprit", "Name": "Nume", "Bugs and Requests": "Probleme \u0219i solicit\u0103ri", "Approx. Total Print Time": "Timp de imprimare total estimat", "Admin": "Admin", "

\n Note: In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't\n need Access Control for other reasons, you may alternatively disable Access Control. You should only\n do this if you are absolutely certain that only people you know and trust will be able to connect to it.\n

\n

\n Do NOT underestimate the risk of an unsecured access from the internet to your printer!\n

": "

\nNot\u0103: \u00cen cazul \u00een care aplica\u021bia ta OctoPrint este accesibil\u0103 doar dintr-o re\u021bea sigur\u0103 \u0219i nu\nai nevoie de controlul accesului pentru alte mootive, po\u021bi s\u0103 dezactivezi controlul accesului. \u00ce\u021bi recomand asta\nnumai dac\u0103 e\u0219ti absolut sigur c\u0103 se vor putea conecta doar oameni pe care \u00eei cuno\u0219ti \u0219i \u00een care ai \u00eencredere.\n

\n

\nNU subestima riscul pe care-l prezint\u0103 accesul nesecurizat din Internet la imprimanta ta!\n

", "Timelapse": "\u00cenregistrare rapid\u0103", "QR Code": "", "Only show GCode files": "", "Remove": "\u0218tergere", "Reload": "Re\u00eenc\u0103rcare", "Printing": "Se imprim\u0103", "printed": "", "Y": "Y", "Fans off": "Oprire ventilatoare", "Login": "Conectare", "Rectangular": "", "Timelapse ready": "\u00cenregistrarea rapid\u0103 este gata", "Timelapse Mode": "Mod \u00eenregistrare rapid\u0103", "Timelapse Folder": "Director pentru \u00eenregistrarea rapid\u0103", "Extruder": "Extruder", "Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\" and slicing support is enabled and configured.": "Nu pot \u00eenc\u0103rca fi\u0219ierul. Asigur\u0103-te c\u0103 este un fi\u0219ier GCODE \u0219i c\u0103 are extensia \".gcode\" sau \".gco\" sau c\u0103 este un fi\u0219ier STL cu extensia \".stl\" \u0219i c\u0103 felierea este activat\u0103 \u0219i configurat\u0103.", "Printed": "Imprimat", "SD not initialized": "SD nu este ini\u021bializat", "Update User": "Actualizare utilizator", "off": "oprit", "Serial Port": "Port serial", "Flip webcam horizontally": "Rote\u0219te camera pe orizontal\u0103", "Resumes the print job": "", "Transfering file to SD": "Se transfer\u0103 fi\u0219ierul pe SD", "OctoPrint": "OctoPrint", "Layer height": "\u00cen\u0103l\u021bimea stratului", "Sliced %(stl)s to %(gcode)s, took %(time).2f seconds": "S-a feliat %(stl)s ca %(gcode)s \u00een %(time).2f secunde", "Extrude": "Extrudare", "green": "verde", "File": "Fi\u0219ier", "You are now logged in as \"%(username)s\"": "Acum e\u0219ti conectat ca \"%(username)s\"", "Axis": "Ax\u0103", "Filament used by layer": "Filament utilizat \u00een strat", "Please configure which slicer and which slicing profile to use and name the GCode file to slice to below, or click \"Cancel\" if you do not wish to slice the file now.": ""}} ; \ No newline at end of file diff --git a/src/octoprint/static/js/lib/bootstrap-slider-knockout-binding.js b/src/octoprint/static/js/lib/bootstrap-slider-knockout-binding.js new file mode 100644 index 000000000..b4f15f76b --- /dev/null +++ b/src/octoprint/static/js/lib/bootstrap-slider-knockout-binding.js @@ -0,0 +1,44 @@ +/** + * Based on bootstrap-slider-knockout-binding, written by Cosmin Stefan-Dobrin, https://github.com/cosminstefanxp, + * licensed under MIT License + * + * Github: https://github.com/cosminstefanxp/bootstrap-slider-knockout-binding + */ +ko.bindingHandlers.slider = { + init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { + var params = valueAccessor(); + + // Check whether the value observable is either placed directly or in the paramaters object. + if (!(ko.isObservable(params) || params['value'])) + throw "You need to define an observable value for the sliderValue. Either pass the observable directly or as the 'value' field in the parameters."; + + // Identify the value and initialize the slider + var valueObservable; + if (ko.isObservable(params)) { + valueObservable = params; + $(element).slider({value: ko.utils.unwrapObservable(params)}); + } else { + valueObservable = params['value']; + // Replace the 'value' field in the options object with the actual value + params['value'] = ko.utils.unwrapObservable(valueObservable); + $(element).slider(params); + } + + // Make sure we update the observable when changing the slider value + $(element).on('slide', function (ev) { + valueObservable(ev.value); + }); + + }, + update: function (element, valueAccessor, allBindings, viewModel, bindingContext) { + var modelValue = valueAccessor(); + var valueObservable; + if (ko.isObservable(modelValue)) { + valueObservable = modelValue; + } else { + valueObservable = modelValue['value']; + } + + $(element).slider('setValue', parseFloat(ko.isObservable(valueObservable) ? valueObservable() : valueObservable)); + } +}; \ No newline at end of file diff --git a/src/octoprint/static/js/lib/bootstrap/bootstrap-tabdrop.js b/src/octoprint/static/js/lib/bootstrap/bootstrap-tabdrop.js new file mode 100644 index 000000000..3546ba97a --- /dev/null +++ b/src/octoprint/static/js/lib/bootstrap/bootstrap-tabdrop.js @@ -0,0 +1,117 @@ +/* ========================================================= + * bootstrap-tabdrop.js + * http://www.eyecon.ro/bootstrap-tabdrop + * ========================================================= + * Copyright 2012 Stefan Petre + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ========================================================= */ + +!function( $ ) { + + var WinReszier = (function(){ + var registered = []; + var inited = false; + var timer; + var resize = function(ev) { + clearTimeout(timer); + timer = setTimeout(notify, 100); + }; + var notify = function() { + for(var i=0, cnt=registered.length; i'+options.text+' ') + .prependTo(this.element); + if (this.element.parent().is('.tabs-below')) { + this.dropdown.addClass('dropup'); + } + WinReszier.register($.proxy(this.layout, this)); + this.layout(); + }; + + TabDrop.prototype = { + constructor: TabDrop, + + layout: function() { + var collection = []; + this.dropdown.removeClass('hide'); + this.element + .append(this.dropdown.find('li')) + .find('>li') + .not('.tabdrop') + .each(function(){ + if(this.offsetTop > 0) { + collection.push(this); + } + }); + if (collection.length > 0) { + collection = $(collection); + this.dropdown + .find('ul') + .empty() + .append(collection); + if (this.dropdown.find('.active').length == 1) { + this.dropdown.addClass('active'); + } else { + this.dropdown.removeClass('active'); + } + } else { + this.dropdown.addClass('hide'); + } + } + } + + $.fn.tabdrop = function ( option ) { + return this.each(function () { + var $this = $(this), + data = $this.data('tabdrop'), + options = typeof option === 'object' && option; + if (!data) { + $this.data('tabdrop', (data = new TabDrop(this, $.extend({}, $.fn.tabdrop.defaults,options)))); + } + if (typeof option == 'string') { + data[option](); + } + }) + }; + + $.fn.tabdrop.defaults = { + text: '' + }; + + $.fn.tabdrop.Constructor = TabDrop; + +}( window.jQuery ); \ No newline at end of file diff --git a/src/octoprint/static/js/lib/jquery/jquery.min.js b/src/octoprint/static/js/lib/jquery/jquery.min.js index b18e05a95..90b6db293 100644 --- a/src/octoprint/static/js/lib/jquery/jquery.min.js +++ b/src/octoprint/static/js/lib/jquery/jquery.min.js @@ -1,5 +1,4 @@ /*! jQuery v2.0.0 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license -//@ sourceMappingURL=jquery.min.map */ (function(e,undefined){var t,n,r=typeof undefined,i=e.location,o=e.document,s=o.documentElement,a=e.jQuery,u=e.$,l={},c=[],f="2.0.0",p=c.concat,h=c.push,d=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=f.trim,x=function(e,n){return new x.fn.init(e,n,t)},b=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^-ms-/,N=/-([\da-z])/gi,E=function(e,t){return t.toUpperCase()},S=function(){o.removeEventListener("DOMContentLoaded",S,!1),e.removeEventListener("load",S,!1),x.ready()};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,t,n){var r,i;if(!e)return this;if("string"==typeof e){if(r="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:T.exec(e),!r||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof x?t[0]:t,x.merge(this,x.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:o,!0)),C.test(r[1])&&x.isPlainObject(t))for(r in t)x.isFunction(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return i=o.getElementById(r[2]),i&&i.parentNode&&(this.length=1,this[0]=i),this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?n.ready(e):(e.selector!==undefined&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return d.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,t,n,r,i,o,s=arguments[0]||{},a=1,u=arguments.length,l=!1;for("boolean"==typeof s&&(l=s,s=arguments[1]||{},a=2),"object"==typeof s||x.isFunction(s)||(s={}),u===a&&(s=this,--a);u>a;a++)if(null!=(e=arguments[a]))for(t in e)n=s[t],r=e[t],s!==r&&(l&&r&&(x.isPlainObject(r)||(i=x.isArray(r)))?(i?(i=!1,o=n&&x.isArray(n)?n:[]):o=n&&x.isPlainObject(n)?n:{},s[t]=x.extend(l,o,r)):r!==undefined&&(s[t]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=a),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){(e===!0?--x.readyWait:x.isReady)||(x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(o,[x]),x.fn.trigger&&x(o).trigger("ready").off("ready")))},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray,isWindow:function(e){return null!=e&&e===e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if("object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:JSON.parse,parseXML:function(e){var t,n;if(!e||"string"!=typeof e)return null;try{n=new DOMParser,t=n.parseFromString(e,"text/xml")}catch(r){t=undefined}return(!t||t.getElementsByTagName("parsererror").length)&&x.error("Invalid XML: "+e),t},noop:function(){},globalEval:function(e){var t,n=eval;e=x.trim(e),e&&(1===e.indexOf("use strict")?(t=o.createElement("script"),t.text=e,o.head.appendChild(t).parentNode.removeChild(t)):n(e))},camelCase:function(e){return e.replace(k,"ms-").replace(N,E)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,s=j(e);if(n){if(s){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(s){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:function(e){return null==e?"":v.call(e)},makeArray:function(e,t){var n=t||[];return null!=e&&(j(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:g.call(t,e,n)},merge:function(e,t){var n=t.length,r=e.length,i=0;if("number"==typeof n)for(;n>i;i++)e[r++]=t[i];else while(t[i]!==undefined)e[r++]=t[i++];return e.length=r,e},grep:function(e,t,n){var r,i=[],o=0,s=e.length;for(n=!!n;s>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,s=j(e),a=[];if(s)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(a[a.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(a[a.length]=r);return p.apply([],a)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(n=e[t],t=e,e=n),x.isFunction(e)?(r=d.call(arguments,2),i=function(){return e.apply(t||this,r.concat(d.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):undefined},access:function(e,t,n,r,i,o,s){var a=0,u=e.length,l=null==n;if("object"===x.type(n)){i=!0;for(a in n)x.access(e,t,a,n[a],!0,o,s)}else if(r!==undefined&&(i=!0,x.isFunction(r)||(s=!0),l&&(s?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(x(e),n)})),t))for(;u>a;a++)t(e[a],n,s?r:r.call(e[a],a,t(e[a],n)));return i?e:l?t.call(e):u?t(e[0],n):o},now:Date.now,swap:function(e,t,n,r){var i,o,s={};for(o in t)s[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=s[o];return i}}),x.ready.promise=function(t){return n||(n=x.Deferred(),"complete"===o.readyState?setTimeout(x.ready):(o.addEventListener("DOMContentLoaded",S,!1),e.addEventListener("load",S,!1))),n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function j(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}t=x(o),function(e,undefined){var t,n,r,i,o,s,a,u,l,c,f,p,h,d,g,m,y="sizzle"+-new Date,v=e.document,b={},w=0,T=0,C=ot(),k=ot(),N=ot(),E=!1,S=function(){return 0},j=typeof undefined,D=1<<31,A=[],L=A.pop,q=A.push,H=A.push,O=A.slice,F=A.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},P="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",R="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=M.replace("w","w#"),$="\\["+R+"*("+M+")"+R+"*(?:([*^$|!~]?=)"+R+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+R+"*\\]",B=":("+M+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",I=RegExp("^"+R+"+|((?:^|[^\\\\])(?:\\\\.)*)"+R+"+$","g"),z=RegExp("^"+R+"*,"+R+"*"),_=RegExp("^"+R+"*([>+~]|"+R+")"+R+"*"),X=RegExp(R+"*[+~]"),U=RegExp("="+R+"*([^\\]'\"]*)"+R+"*\\]","g"),Y=RegExp(B),V=RegExp("^"+W+"$"),G={ID:RegExp("^#("+M+")"),CLASS:RegExp("^\\.("+M+")"),TAG:RegExp("^("+M.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+B),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+R+"*(even|odd|(([+-]|)(\\d*)n|)"+R+"*(?:([+-]|)"+R+"*(\\d+)|))"+R+"*\\)|)","i"),"boolean":RegExp("^(?:"+P+")$","i"),needsContext:RegExp("^"+R+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+R+"*((?:-\\d)?\\d*)"+R+"*\\)|)(?=[^-]|$)","i")},J=/^[^{]+\{\s*\[native \w/,Q=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,K=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,et=/'|\\/g,tt=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,nt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{H.apply(A=O.call(v.childNodes),v.childNodes),A[v.childNodes.length].nodeType}catch(rt){H={apply:A.length?function(e,t){q.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function it(e){return J.test(e+"")}function ot(){var e,t=[];return e=function(n,i){return t.push(n+=" ")>r.cacheLength&&delete e[t.shift()],e[n]=i}}function st(e){return e[y]=!0,e}function at(e){var t=c.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ut(e,t,n,r){var i,o,s,a,u,f,d,g,x,w;if((t?t.ownerDocument||t:v)!==c&&l(t),t=t||c,n=n||[],!e||"string"!=typeof e)return n;if(1!==(a=t.nodeType)&&9!==a)return[];if(p&&!r){if(i=Q.exec(e))if(s=i[1]){if(9===a){if(o=t.getElementById(s),!o||!o.parentNode)return n;if(o.id===s)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(s))&&m(t,o)&&o.id===s)return n.push(o),n}else{if(i[2])return H.apply(n,t.getElementsByTagName(e)),n;if((s=i[3])&&b.getElementsByClassName&&t.getElementsByClassName)return H.apply(n,t.getElementsByClassName(s)),n}if(b.qsa&&(!h||!h.test(e))){if(g=d=y,x=t,w=9===a&&e,1===a&&"object"!==t.nodeName.toLowerCase()){f=gt(e),(d=t.getAttribute("id"))?g=d.replace(et,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=f.length;while(u--)f[u]=g+mt(f[u]);x=X.test(e)&&t.parentNode||t,w=f.join(",")}if(w)try{return H.apply(n,x.querySelectorAll(w)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(I,"$1"),t,n,r)}o=ut.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},l=ut.setDocument=function(e){var t=e?e.ownerDocument||e:v;return t!==c&&9===t.nodeType&&t.documentElement?(c=t,f=t.documentElement,p=!o(t),b.getElementsByTagName=at(function(e){return e.appendChild(t.createComment("")),!e.getElementsByTagName("*").length}),b.attributes=at(function(e){return e.className="i",!e.getAttribute("className")}),b.getElementsByClassName=at(function(e){return e.innerHTML="
",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),b.sortDetached=at(function(e){return 1&e.compareDocumentPosition(c.createElement("div"))}),b.getById=at(function(e){return f.appendChild(e).id=y,!t.getElementsByName||!t.getElementsByName(y).length}),b.getById?(r.find.ID=function(e,t){if(typeof t.getElementById!==j&&p){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},r.filter.ID=function(e){var t=e.replace(tt,nt);return function(e){return e.getAttribute("id")===t}}):(r.find.ID=function(e,t){if(typeof t.getElementById!==j&&p){var n=t.getElementById(e);return n?n.id===e||typeof n.getAttributeNode!==j&&n.getAttributeNode("id").value===e?[n]:undefined:[]}},r.filter.ID=function(e){var t=e.replace(tt,nt);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),r.find.TAG=b.getElementsByTagName?function(e,t){return typeof t.getElementsByTagName!==j?t.getElementsByTagName(e):undefined}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=b.getElementsByClassName&&function(e,t){return typeof t.getElementsByClassName!==j&&p?t.getElementsByClassName(e):undefined},d=[],h=[],(b.qsa=it(t.querySelectorAll))&&(at(function(e){e.innerHTML="",e.querySelectorAll("[selected]").length||h.push("\\["+R+"*(?:value|"+P+")"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){var t=c.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&h.push("[*^$]="+R+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(b.matchesSelector=it(g=f.webkitMatchesSelector||f.mozMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){b.disconnectedMatch=g.call(e,"div"),g.call(e,"[s!='']:x"),d.push("!=",B)}),h=h.length&&RegExp(h.join("|")),d=d.length&&RegExp(d.join("|")),m=it(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},S=f.compareDocumentPosition?function(e,n){if(e===n)return E=!0,0;var r=n.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(n);return r?1&r||!b.sortDetached&&n.compareDocumentPosition(e)===r?e===t||m(v,e)?-1:n===t||m(v,n)?1:u?F.call(u,e)-F.call(u,n):0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,n){var r,i=0,o=e.parentNode,s=n.parentNode,a=[e],l=[n];if(e===n)return E=!0,0;if(!o||!s)return e===t?-1:n===t?1:o?-1:s?1:u?F.call(u,e)-F.call(u,n):0;if(o===s)return lt(e,n);r=e;while(r=r.parentNode)a.unshift(r);r=n;while(r=r.parentNode)l.unshift(r);while(a[i]===l[i])i++;return i?lt(a[i],l[i]):a[i]===v?-1:l[i]===v?1:0},c):c},ut.matches=function(e,t){return ut(e,null,null,t)},ut.matchesSelector=function(e,t){if((e.ownerDocument||e)!==c&&l(e),t=t.replace(U,"='$1']"),!(!b.matchesSelector||!p||d&&d.test(t)||h&&h.test(t)))try{var n=g.call(e,t);if(n||b.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return ut(t,c,null,[e]).length>0},ut.contains=function(e,t){return(e.ownerDocument||e)!==c&&l(e),m(e,t)},ut.attr=function(e,t){(e.ownerDocument||e)!==c&&l(e);var n=r.attrHandle[t.toLowerCase()],i=n&&n(e,t,!p);return i===undefined?b.attributes||!p?e.getAttribute(t):(i=e.getAttributeNode(t))&&i.specified?i.value:null:i},ut.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},ut.uniqueSort=function(e){var t,n=[],r=0,i=0;if(E=!b.detectDuplicates,u=!b.sortStable&&e.slice(0),e.sort(S),E){while(t=e[i++])t===e[i]&&(r=n.push(i));while(r--)e.splice(n[r],1)}return e};function lt(e,t){var n=t&&e,r=n&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ct(e,t,n){var r;return n?undefined:(r=e.getAttributeNode(t))&&r.specified?r.value:e[t]===!0?t.toLowerCase():null}function ft(e,t,n){var r;return n?undefined:r=e.getAttribute(t,"type"===t.toLowerCase()?1:2)}function pt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ht(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function dt(e){return st(function(t){return t=+t,st(function(n,r){var i,o=e([],n.length,t),s=o.length;while(s--)n[i=o[s]]&&(n[i]=!(r[i]=n[i]))})})}i=ut.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else for(;t=e[r];r++)n+=i(t);return n},r=ut.selectors={cacheLength:50,createPseudo:st,match:G,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(tt,nt),e[3]=(e[4]||e[5]||"").replace(tt,nt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||ut.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&ut.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return G.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&Y.test(n)&&(t=gt(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(tt,nt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=C[e+" "];return t||(t=RegExp("(^|"+R+")"+e+"("+R+"|$)"))&&C(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=ut.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,f,p,h,d,g=o!==s?"nextSibling":"previousSibling",m=t.parentNode,v=a&&t.nodeName.toLowerCase(),x=!u&&!a;if(m){if(o){while(g){f=t;while(f=f[g])if(a?f.nodeName.toLowerCase()===v:1===f.nodeType)return!1;d=g="only"===e&&!d&&"nextSibling"}return!0}if(d=[s?m.firstChild:m.lastChild],s&&x){c=m[y]||(m[y]={}),l=c[e]||[],h=l[0]===w&&l[1],p=l[0]===w&&l[2],f=h&&m.childNodes[h];while(f=++h&&f&&f[g]||(p=h=0)||d.pop())if(1===f.nodeType&&++p&&f===t){c[e]=[w,h,p];break}}else if(x&&(l=(t[y]||(t[y]={}))[e])&&l[0]===w)p=l[1];else while(f=++h&&f&&f[g]||(p=h=0)||d.pop())if((a?f.nodeName.toLowerCase()===v:1===f.nodeType)&&++p&&(x&&((f[y]||(f[y]={}))[e]=[w,p]),f===t))break;return p-=i,p===r||0===p%r&&p/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||ut.error("unsupported pseudo: "+e);return i[y]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?st(function(e,n){var r,o=i(e,t),s=o.length;while(s--)r=F.call(e,o[s]),e[r]=!(n[r]=o[s])}):function(e){return i(e,0,n)}):i}},pseudos:{not:st(function(e){var t=[],n=[],r=s(e.replace(I,"$1"));return r[y]?st(function(e,t,n,i){var o,s=r(e,null,i,[]),a=e.length;while(a--)(o=s[a])&&(e[a]=!(t[a]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:st(function(e){return function(t){return ut(e,t).length>0}}),contains:st(function(e){return function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:st(function(e){return V.test(e||"")||ut.error("unsupported lang: "+e),e=e.replace(tt,nt).toLowerCase(),function(t){var n;do if(n=p?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===c.activeElement&&(!c.hasFocus||c.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Z.test(e.nodeName)},input:function(e){return K.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:dt(function(){return[0]}),last:dt(function(e,t){return[t-1]}),eq:dt(function(e,t,n){return[0>n?n+t:n]}),even:dt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:dt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:dt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:dt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=pt(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=ht(t);function gt(e,t){var n,i,o,s,a,u,l,c=k[e+" "];if(c)return t?0:c.slice(0);a=e,u=[],l=r.preFilter;while(a){(!n||(i=z.exec(a)))&&(i&&(a=a.slice(i[0].length)||a),u.push(o=[])),n=!1,(i=_.exec(a))&&(n=i.shift(),o.push({value:n,type:i[0].replace(I," ")}),a=a.slice(n.length));for(s in r.filter)!(i=G[s].exec(a))||l[s]&&!(i=l[s](i))||(n=i.shift(),o.push({value:n,type:s,matches:i}),a=a.slice(n.length));if(!n)break}return t?a.length:a?ut.error(e):k(e,u).slice(0)}function mt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function yt(e,t,r){var i=t.dir,o=r&&"parentNode"===i,s=T++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,r,a){var u,l,c,f=w+" "+s;if(a){while(t=t[i])if((1===t.nodeType||o)&&e(t,r,a))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[y]||(t[y]={}),(l=c[i])&&l[0]===f){if((u=l[1])===!0||u===n)return u===!0}else if(l=c[i]=[f],l[1]=e(t,r,a)||n,l[1]===!0)return!0}}function vt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,s=[],a=0,u=e.length,l=null!=t;for(;u>a;a++)(o=e[a])&&(!n||n(o,r,i))&&(s.push(o),l&&t.push(a));return s}function bt(e,t,n,r,i,o){return r&&!r[y]&&(r=bt(r)),i&&!i[y]&&(i=bt(i,o)),st(function(o,s,a,u){var l,c,f,p=[],h=[],d=s.length,g=o||Ct(t||"*",a.nodeType?[a]:a,[]),m=!e||!o&&t?g:xt(g,p,e,a,u),y=n?i||(o?e:d||r)?[]:s:m;if(n&&n(m,y,a,u),r){l=xt(y,h),r(l,[],a,u),c=l.length;while(c--)(f=l[c])&&(y[h[c]]=!(m[h[c]]=f))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(f=y[c])&&l.push(m[c]=f);i(null,y=[],l,u)}c=y.length;while(c--)(f=y[c])&&(l=i?F.call(o,f):p[c])>-1&&(o[l]=!(s[l]=f))}}else y=xt(y===s?y.splice(d,y.length):y),i?i(null,s,y,u):H.apply(s,y)})}function wt(e){var t,n,i,o=e.length,s=r.relative[e[0].type],u=s||r.relative[" "],l=s?1:0,c=yt(function(e){return e===t},u,!0),f=yt(function(e){return F.call(t,e)>-1},u,!0),p=[function(e,n,r){return!s&&(r||n!==a)||((t=n).nodeType?c(e,n,r):f(e,n,r))}];for(;o>l;l++)if(n=r.relative[e[l].type])p=[yt(vt(p),n)];else{if(n=r.filter[e[l].type].apply(null,e[l].matches),n[y]){for(i=++l;o>i;i++)if(r.relative[e[i].type])break;return bt(l>1&&vt(p),l>1&&mt(e.slice(0,l-1)).replace(I,"$1"),n,i>l&&wt(e.slice(l,i)),o>i&&wt(e=e.slice(i)),o>i&&mt(e))}p.push(n)}return vt(p)}function Tt(e,t){var i=0,o=t.length>0,s=e.length>0,u=function(u,l,f,p,h){var d,g,m,y=[],v=0,x="0",b=u&&[],T=null!=h,C=a,k=u||s&&r.find.TAG("*",h&&l.parentNode||l),N=w+=null==C?1:Math.random()||.1;for(T&&(a=l!==c&&l,n=i);null!=(d=k[x]);x++){if(s&&d){g=0;while(m=e[g++])if(m(d,l,f)){p.push(d);break}T&&(w=N,n=++i)}o&&((d=!m&&d)&&v--,u&&b.push(d))}if(v+=x,o&&x!==v){g=0;while(m=t[g++])m(b,y,l,f);if(u){if(v>0)while(x--)b[x]||y[x]||(y[x]=L.call(p));y=xt(y)}H.apply(p,y),T&&!u&&y.length>0&&v+t.length>1&&ut.uniqueSort(p)}return T&&(w=N,a=C),b};return o?st(u):u}s=ut.compile=function(e,t){var n,r=[],i=[],o=N[e+" "];if(!o){t||(t=gt(e)),n=t.length;while(n--)o=wt(t[n]),o[y]?r.push(o):i.push(o);o=N(e,Tt(i,r))}return o};function Ct(e,t,n){var r=0,i=t.length;for(;i>r;r++)ut(e,t[r],n);return n}function kt(e,t,n,i){var o,a,u,l,c,f=gt(e);if(!i&&1===f.length){if(a=f[0]=f[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&p&&r.relative[a[1].type]){if(t=(r.find.ID(u.matches[0].replace(tt,nt),t)||[])[0],!t)return n;e=e.slice(a.shift().value.length)}o=G.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],r.relative[l=u.type])break;if((c=r.find[l])&&(i=c(u.matches[0].replace(tt,nt),X.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=i.length&&mt(a),!e)return H.apply(n,i),n;break}}}return s(e,f)(i,t,!p,n,X.test(e)),n}r.pseudos.nth=r.pseudos.eq;function Nt(){}Nt.prototype=r.filters=r.pseudos,r.setFilters=new Nt,b.sortStable=y.split("").sort(S).join("")===y,l(),[0,0].sort(S),b.detectDuplicates=E,at(function(e){if(e.innerHTML="","#"!==e.firstChild.getAttribute("href")){var t="type|href|height|width".split("|"),n=t.length;while(n--)r.attrHandle[t[n]]=ft}}),at(function(e){if(null!=e.getAttribute("disabled")){var t=P.split("|"),n=t.length;while(n--)r.attrHandle[t[n]]=ct}}),x.find=ut,x.expr=ut.selectors,x.expr[":"]=x.expr.pseudos,x.unique=ut.uniqueSort,x.text=ut.getText,x.isXMLDoc=ut.isXML,x.contains=ut.contains}(e);var D={};function A(e){var t=D[e]={};return x.each(e.match(w)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?D[e]||A(e):x.extend({},e);var t,n,r,i,o,s,a=[],u=!e.once&&[],l=function(f){for(t=e.memory&&f,n=!0,s=i||0,i=0,o=a.length,r=!0;a&&o>s;s++)if(a[s].apply(f[0],f[1])===!1&&e.stopOnFalse){t=!1;break}r=!1,a&&(u?u.length&&l(u.shift()):t?a=[]:c.disable())},c={add:function(){if(a){var n=a.length;(function s(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&c.has(n)||a.push(n):n&&n.length&&"string"!==r&&s(n)})})(arguments),r?o=a.length:t&&(i=n,l(t))}return this},remove:function(){return a&&x.each(arguments,function(e,t){var n;while((n=x.inArray(t,a,n))>-1)a.splice(n,1),r&&(o>=n&&o--,s>=n&&s--)}),this},has:function(e){return e?x.inArray(e,a)>-1:!(!a||!a.length)},empty:function(){return a=[],o=0,this},disable:function(){return a=u=t=undefined,this},disabled:function(){return!a},lock:function(){return u=undefined,t||c.disable(),this},locked:function(){return!u},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!a||n&&!u||(r?u.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!n}};return c},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var s=o[0],a=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var s=o[2],a=o[3];r[o[1]]=s.add,a&&s.add(function(){n=a},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=s.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=d.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),s=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?d.call(arguments):r,n===a?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},a,u,l;if(r>1)for(a=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(s(t,l,n)).fail(o.reject).progress(s(t,u,a)):--i;return i||o.resolveWith(l,n),o.promise()}}),x.support=function(t){var n=o.createElement("input"),r=o.createDocumentFragment(),i=o.createElement("div"),s=o.createElement("select"),a=s.appendChild(o.createElement("option"));return n.type?(n.type="checkbox",t.checkOn=""!==n.value,t.optSelected=a.selected,t.reliableMarginRight=!0,t.boxSizingReliable=!0,t.pixelPosition=!1,n.checked=!0,t.noCloneChecked=n.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!a.disabled,n=o.createElement("input"),n.value="t",n.type="radio",t.radioValue="t"===n.value,n.setAttribute("checked","t"),n.setAttribute("name","t"),r.appendChild(n),t.checkClone=r.cloneNode(!0).cloneNode(!0).lastChild.checked,t.focusinBubbles="onfocusin"in e,i.style.backgroundClip="content-box",i.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===i.style.backgroundClip,x(function(){var n,r,s="padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box",a=o.getElementsByTagName("body")[0];a&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",a.appendChild(n).appendChild(i),i.innerHTML="",i.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%",x.swap(a,null!=a.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===i.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(i,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(i,null)||{width:"4px"}).width,r=i.appendChild(o.createElement("div")),r.style.cssText=i.style.cssText=s,r.style.marginRight=r.style.width="0",i.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),a.removeChild(n))}),t):t}({});var L,q,H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,O=/([A-Z])/g;function F(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=x.expando+Math.random()}F.uid=1,F.accepts=function(e){return e.nodeType?1===e.nodeType||9===e.nodeType:!0},F.prototype={key:function(e){if(!F.accepts(e))return 0;var t={},n=e[this.expando];if(!n){n=F.uid++;try{t[this.expando]={value:n},Object.defineProperties(e,t)}catch(r){t[this.expando]=n,x.extend(e,t)}}return this.cache[n]||(this.cache[n]={}),n},set:function(e,t,n){var r,i=this.key(e),o=this.cache[i];if("string"==typeof t)o[t]=n;else if(x.isEmptyObject(o))this.cache[i]=t;else for(r in t)o[r]=t[r]},get:function(e,t){var n=this.cache[this.key(e)];return t===undefined?n:n[t]},access:function(e,t,n){return t===undefined||t&&"string"==typeof t&&n===undefined?this.get(e,t):(this.set(e,t,n),n!==undefined?n:t)},remove:function(e,t){var n,r,i=this.key(e),o=this.cache[i];if(t===undefined)this.cache[i]={};else{x.isArray(t)?r=t.concat(t.map(x.camelCase)):t in o?r=[t]:(r=x.camelCase(t),r=r in o?[r]:r.match(w)||[]),n=r.length;while(n--)delete o[r[n]]}},hasData:function(e){return!x.isEmptyObject(this.cache[e[this.expando]]||{})},discard:function(e){delete this.cache[this.key(e)]}},L=new F,q=new F,x.extend({acceptData:F.accepts,hasData:function(e){return L.hasData(e)||q.hasData(e)},data:function(e,t,n){return L.access(e,t,n)},removeData:function(e,t){L.remove(e,t)},_data:function(e,t,n){return q.access(e,t,n)},_removeData:function(e,t){q.remove(e,t)}}),x.fn.extend({data:function(e,t){var n,r,i=this[0],o=0,s=null;if(e===undefined){if(this.length&&(s=L.get(i),1===i.nodeType&&!q.get(i,"hasDataAttrs"))){for(n=i.attributes;n.length>o;o++)r=n[o].name,0===r.indexOf("data-")&&(r=x.camelCase(r.substring(5)),P(i,r,s[r]));q.set(i,"hasDataAttrs",!0)}return s}return"object"==typeof e?this.each(function(){L.set(this,e)}):x.access(this,function(t){var n,r=x.camelCase(e);if(i&&t===undefined){if(n=L.get(i,e),n!==undefined)return n;if(n=L.get(i,r),n!==undefined)return n;if(n=P(i,r,undefined),n!==undefined)return n}else this.each(function(){var n=L.get(this,r);L.set(this,r,t),-1!==e.indexOf("-")&&n!==undefined&&L.set(this,e,t)})},null,t,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){L.remove(this,e)})}});function P(e,t,n){var r;if(n===undefined&&1===e.nodeType)if(r="data-"+t.replace(O,"-$1").toLowerCase(),n=e.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:H.test(n)?JSON.parse(n):n}catch(i){}L.set(e,t,n)}else n=undefined;return n}x.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=q.get(e,t),n&&(!r||x.isArray(n)?r=q.access(e,t,x.makeArray(n)):r.push(n)),r||[]):undefined},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),s=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,s,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return q.get(e,n)||q.access(e,n,{empty:x.Callbacks("once memory").add(function(){q.remove(e,[t+"queue",n])})})}}),x.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),n>arguments.length?x.queue(this[0],e):t===undefined?this:this.each(function(){var n=x.queue(this,e,t); x._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=x.Deferred(),o=this,s=this.length,a=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=undefined),e=e||"fx";while(s--)n=q.get(o[s],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(a));return a(),i.promise(t)}});var R,M,W=/[\t\r\n]/g,$=/\r/g,B=/^(?:input|select|textarea|button)$/i;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[x.propFix[e]||e]})},addClass:function(e){var t,n,r,i,o,s=0,a=this.length,u="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];a>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(W," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,s=0,a=this.length,u=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];a>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(W," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,i="boolean"==typeof t;return x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,s=0,a=x(this),u=t,l=e.match(w)||[];while(o=l[s++])u=i?u:!a.hasClass(o),a[u?"addClass":"removeClass"](o)}else(n===r||"boolean"===n)&&(this.className&&q.set(this,"__className__",this.className),this.className=this.className||e===!1?"":q.get(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(W," ").indexOf(t)>=0)return!0;return!1},val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=x.isFunction(e),this.each(function(n){var i,o=x(this);1===this.nodeType&&(i=r?e.call(this,n,o.val()):e,null==i?i="":"number"==typeof i?i+="":x.isArray(i)&&(i=x.map(i,function(e){return null==e?"":e+""})),t=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&t.set(this,i,"value")!==undefined||(this.value=i))});if(i)return t=x.valHooks[i.type]||x.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&(n=t.get(i,"value"))!==undefined?n:(n=i.value,"string"==typeof n?n.replace($,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,s=o?null:[],a=o?i+1:r.length,u=0>i?a:o?i:0;for(;a>u;u++)if(n=r[u],!(!n.selected&&u!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),s=i.length;while(s--)r=i[s],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,t,n){var i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===r?x.prop(e,t,n):(1===s&&x.isXMLDoc(e)||(t=t.toLowerCase(),i=x.attrHooks[t]||(x.expr.match.boolean.test(t)?M:R)),n===undefined?i&&"get"in i&&null!==(o=i.get(e,t))?o:(o=x.find.attr(e,t),null==o?undefined:o):null!==n?i&&"set"in i&&(o=i.set(e,n,t))!==undefined?o:(e.setAttribute(t,n+""),n):(x.removeAttr(e,t),undefined))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.boolean.test(n)&&(e[r]=!1),e.removeAttribute(n)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return o=1!==s||!x.isXMLDoc(e),o&&(t=x.propFix[t]||t,i=x.propHooks[t]),n!==undefined?i&&"set"in i&&(r=i.set(e,n,t))!==undefined?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){return e.hasAttribute("tabindex")||B.test(e.nodeName)||e.href?e.tabIndex:-1}}}}),M={set:function(e,t,n){return t===!1?x.removeAttr(e,n):e.setAttribute(n,n),n}},x.each(x.expr.match.boolean.source.match(/\w+/g),function(e,t){var n=x.expr.attrHandle[t]||x.find.attr;x.expr.attrHandle[t]=function(e,t,r){var i=x.expr.attrHandle[t],o=r?undefined:(x.expr.attrHandle[t]=undefined)!=n(e,t,r)?t.toLowerCase():null;return x.expr.attrHandle[t]=i,o}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,t){return x.isArray(t)?e.checked=x.inArray(x(e).val(),t)>=0:undefined}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var I=/^key/,z=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,X=/^([^.]*)(?:\.(.+)|)$/;function U(){return!0}function Y(){return!1}function V(){try{return o.activeElement}catch(e){}}x.event={global:{},add:function(e,t,n,i,o){var s,a,u,l,c,f,p,h,d,g,m,y=q.get(e);if(y){n.handler&&(s=n,n=s.handler,o=s.selector),n.guid||(n.guid=x.guid++),(l=y.events)||(l=y.events={}),(a=y.handle)||(a=y.handle=function(e){return typeof x===r||e&&x.event.triggered===e.type?undefined:x.event.dispatch.apply(a.elem,arguments)},a.elem=e),t=(t||"").match(w)||[""],c=t.length;while(c--)u=X.exec(t[c])||[],d=m=u[1],g=(u[2]||"").split(".").sort(),d&&(p=x.event.special[d]||{},d=(o?p.delegateType:p.bindType)||d,p=x.event.special[d]||{},f=x.extend({type:d,origType:m,data:i,handler:n,guid:n.guid,selector:o,needsContext:o&&x.expr.match.needsContext.test(o),namespace:g.join(".")},s),(h=l[d])||(h=l[d]=[],h.delegateCount=0,p.setup&&p.setup.call(e,i,g,a)!==!1||e.addEventListener&&e.addEventListener(d,a,!1)),p.add&&(p.add.call(e,f),f.handler.guid||(f.handler.guid=n.guid)),o?h.splice(h.delegateCount++,0,f):h.push(f),x.event.global[d]=!0);e=null}},remove:function(e,t,n,r,i){var o,s,a,u,l,c,f,p,h,d,g,m=q.hasData(e)&&q.get(e);if(m&&(u=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(a=X.exec(t[l])||[],h=g=a[1],d=(a[2]||"").split(".").sort(),h){f=x.event.special[h]||{},h=(r?f.delegateType:f.bindType)||h,p=u[h]||[],a=a[2]&&RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"),s=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||a&&!a.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));s&&!p.length&&(f.teardown&&f.teardown.call(e,d,m.handle)!==!1||x.removeEvent(e,h,m.handle),delete u[h])}else for(h in u)x.event.remove(e,h+t[l],n,r,!0);x.isEmptyObject(u)&&(delete m.handle,q.remove(e,"events"))}},trigger:function(t,n,r,i){var s,a,u,l,c,f,p,h=[r||o],d=y.call(t,"type")?t.type:t,g=y.call(t,"namespace")?t.namespace.split("."):[];if(a=u=r=r||o,3!==r.nodeType&&8!==r.nodeType&&!_.test(d+x.event.triggered)&&(d.indexOf(".")>=0&&(g=d.split("."),d=g.shift(),g.sort()),c=0>d.indexOf(":")&&"on"+d,t=t[x.expando]?t:new x.Event(d,"object"==typeof t&&t),t.isTrigger=i?2:3,t.namespace=g.join("."),t.namespace_re=t.namespace?RegExp("(^|\\.)"+g.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=undefined,t.target||(t.target=r),n=null==n?[t]:x.makeArray(n,[t]),p=x.event.special[d]||{},i||!p.trigger||p.trigger.apply(r,n)!==!1)){if(!i&&!p.noBubble&&!x.isWindow(r)){for(l=p.delegateType||d,_.test(l+d)||(a=a.parentNode);a;a=a.parentNode)h.push(a),u=a;u===(r.ownerDocument||o)&&h.push(u.defaultView||u.parentWindow||e)}s=0;while((a=h[s++])&&!t.isPropagationStopped())t.type=s>1?l:p.bindType||d,f=(q.get(a,"events")||{})[t.type]&&q.get(a,"handle"),f&&f.apply(a,n),f=c&&a[c],f&&x.acceptData(a)&&f.apply&&f.apply(a,n)===!1&&t.preventDefault();return t.type=d,i||t.isDefaultPrevented()||p._default&&p._default.apply(h.pop(),n)!==!1||!x.acceptData(r)||c&&x.isFunction(r[d])&&!x.isWindow(r)&&(u=r[c],u&&(r[c]=null),x.event.triggered=d,r[d](),x.event.triggered=undefined,u&&(r[c]=u)),t.result}},dispatch:function(e){e=x.event.fix(e);var t,n,r,i,o,s=[],a=d.call(arguments),u=(q.get(this,"events")||{})[e.type]||[],l=x.event.special[e.type]||{};if(a[0]=e,e.delegateTarget=this,!l.preDispatch||l.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),t=0;while((i=s[t++])&&!e.isPropagationStopped()){e.currentTarget=i.elem,n=0;while((o=i.handlers[n++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(o.namespace))&&(e.handleObj=o,e.data=o.data,r=((x.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,a),r!==undefined&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return l.postDispatch&&l.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,s=[],a=t.delegateCount,u=e.target;if(a&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!==this;u=u.parentNode||this)if(u.disabled!==!0||"click"!==e.type){for(r=[],n=0;a>n;n++)o=t[n],i=o.selector+" ",r[i]===undefined&&(r[i]=o.needsContext?x(i,this).index(u)>=0:x.find(i,this,null,[u]).length),r[i]&&r.push(o);r.length&&s.push({elem:u,handlers:r})}return t.length>a&&s.push({elem:this,handlers:t.slice(a)}),s},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,s=t.button;return null==e.pageX&&null!=t.clientX&&(n=e.target.ownerDocument||o,r=n.documentElement,i=n.body,e.pageX=t.clientX+(r&&r.scrollLeft||i&&i.scrollLeft||0)-(r&&r.clientLeft||i&&i.clientLeft||0),e.pageY=t.clientY+(r&&r.scrollTop||i&&i.scrollTop||0)-(r&&r.clientTop||i&&i.clientTop||0)),e.which||s===undefined||(e.which=1&s?1:2&s?3:4&s?2:0),e}},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=z.test(i)?this.mouseHooks:I.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return 3===e.target.nodeType&&(e.target=e.target.parentNode),s.filter?s.filter(e,o):e},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==V()&&this.focus?(this.focus(),!1):undefined},delegateType:"focusin"},blur:{trigger:function(){return this===V()&&this.blur?(this.blur(),!1):undefined},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&x.nodeName(this,"input")?(this.click(),!1):undefined},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==undefined&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)},x.Event=function(e,t){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.getPreventDefault&&e.getPreventDefault()?U:Y):this.type=e,t&&x.extend(this,t),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,undefined):new x.Event(e,t)},x.Event.prototype={isDefaultPrevented:Y,isPropagationStopped:Y,isImmediatePropagationStopped:Y,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=U,e&&e.preventDefault&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=U,e&&e.stopPropagation&&e.stopPropagation()},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=U,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,t,n,r,i){var o,s;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=undefined);for(s in e)this.on(s,t,n,e[s],i);return this}if(null==n&&null==r?(r=t,n=t=undefined):null==r&&("string"==typeof t?(r=n,n=undefined):(r=n,n=t,t=undefined)),r===!1)r=Y;else if(!r)return this;return 1===i&&(o=r,r=function(e){return x().off(e),o.apply(this,arguments)},r.guid=o.guid||(o.guid=x.guid++)),this.each(function(){x.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,x(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=undefined),n===!1&&(n=Y),this.each(function(){x.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?x.event.trigger(e,t,n,!0):undefined}});var G=/^.[^:#\[\.,]*$/,J=x.expr.match.needsContext,Q={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return t=this,this.pushStack(x(e).filter(function(){for(r=0;i>r;r++)if(x.contains(t[r],this))return!0}));for(n=[],r=0;i>r;r++)x.find(e,this[r],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t=x(e,this),n=t.length;return this.filter(function(){var e=0;for(;n>e;e++)if(x.contains(this,t[e]))return!0})},not:function(e){return this.pushStack(Z(this,e||[],!0))},filter:function(e){return this.pushStack(Z(this,e||[],!1))},is:function(e){return!!e&&("string"==typeof e?J.test(e)?x(e,this.context).index(this[0])>=0:x.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],s=J.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(s?s.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?g.call(x(e),this[0]):g.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function K(e,t){while((e=e[t])&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return K(e,"nextSibling")},prev:function(e){return K(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(Q[e]||x.unique(i),"p"===e[0]&&i.reverse()),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,t,n){var r=[],i=n!==undefined;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&x(e).is(n))break;r.push(e)}return r},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function Z(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(G.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return g.call(t,e)>=0!==n})}var et=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,tt=/<([\w:]+)/,nt=/<|&#?\w+;/,rt=/<(?:script|style|link)/i,it=/^(?:checkbox|radio)$/i,ot=/checked\s*(?:[^=]|=\s*.checked.)/i,st=/^$|\/(?:java|ecma)script/i,at=/^true\/(.*)/,ut=/^\s*\s*$/g,lt={option:[1,""],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};lt.optgroup=lt.option,lt.tbody=lt.tfoot=lt.colgroup=lt.caption=lt.col=lt.thead,lt.th=lt.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===undefined?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=ct(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=ct(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(gt(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&ht(gt(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++)1===e.nodeType&&(x.cleanData(gt(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var t=this[0]||{},n=0,r=this.length;if(e===undefined&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!rt.test(e)&&!lt[(tt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(et,"<$1>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(x.cleanData(gt(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=p.apply([],e);var r,i,o,s,a,u,l=0,c=this.length,f=this,h=c-1,d=e[0],g=x.isFunction(d);if(g||!(1>=c||"string"!=typeof d||x.support.checkClone)&&ot.test(d))return this.each(function(r){var i=f.eq(r);g&&(e[0]=d.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(r=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),i=r.firstChild,1===r.childNodes.length&&(r=i),i)){for(o=x.map(gt(r,"script"),ft),s=o.length;c>l;l++)a=r,l!==h&&(a=x.clone(a,!0,!0),s&&x.merge(o,gt(a,"script"))),t.call(this[l],a,l);if(s)for(u=o[o.length-1].ownerDocument,x.map(o,pt),l=0;s>l;l++)a=o[l],st.test(a.type||"")&&!q.access(a,"globalEval")&&x.contains(u,a)&&(a.src?x._evalUrl(a.src):x.globalEval(a.textContent.replace(ut,"")))}return this}}),x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=[],i=x(e),o=i.length-1,s=0;for(;o>=s;s++)n=s===o?this:this.clone(!0),x(i[s])[t](n),h.apply(r,n.get());return this.pushStack(r)}}),x.extend({clone:function(e,t,n){var r,i,o,s,a=e.cloneNode(!0),u=x.contains(e.ownerDocument,e);if(!(x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(s=gt(a),o=gt(e),r=0,i=o.length;i>r;r++)mt(o[r],s[r]);if(t)if(n)for(o=o||gt(e),s=s||gt(a),r=0,i=o.length;i>r;r++)dt(o[r],s[r]);else dt(e,a);return s=gt(a,"script"),s.length>0&&ht(s,!u&>(e,"script")),a},buildFragment:function(e,t,n,r){var i,o,s,a,u,l,c=0,f=e.length,p=t.createDocumentFragment(),h=[];for(;f>c;c++)if(i=e[c],i||0===i)if("object"===x.type(i))x.merge(h,i.nodeType?[i]:i);else if(nt.test(i)){o=o||p.appendChild(t.createElement("div")),s=(tt.exec(i)||["",""])[1].toLowerCase(),a=lt[s]||lt._default,o.innerHTML=a[1]+i.replace(et,"<$1>")+a[2],l=a[0];while(l--)o=o.firstChild;x.merge(h,o.childNodes),o=p.firstChild,o.textContent=""}else h.push(t.createTextNode(i));p.textContent="",c=0;while(i=h[c++])if((!r||-1===x.inArray(i,r))&&(u=x.contains(i.ownerDocument,i),o=gt(p.appendChild(i),"script"),u&&ht(o),n)){l=0;while(i=o[l++])st.test(i.type||"")&&n.push(i)}return p},cleanData:function(e){var t,n,r,i=e.length,o=0,s=x.event.special;for(;i>o;o++){if(n=e[o],x.acceptData(n)&&(t=q.access(n)))for(r in t.events)s[r]?x.event.remove(n,r):x.removeEvent(n,r,t.handle);L.discard(n),q.discard(n)}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"text",async:!1,global:!1,success:x.globalEval})}});function ct(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function ft(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function pt(e){var t=at.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function ht(e,t){var n=e.length,r=0;for(;n>r;r++)q.set(e[r],"globalEval",!t||q.get(t[r],"globalEval"))}function dt(e,t){var n,r,i,o,s,a,u,l;if(1===t.nodeType){if(q.hasData(e)&&(o=q.access(e),s=x.extend({},o),l=o.events,q.set(t,s),l)){delete s.handle,s.events={};for(i in l)for(n=0,r=l[i].length;r>n;n++)x.event.add(t,i,l[i][n])}L.hasData(e)&&(a=L.access(e),u=x.extend({},a),L.set(t,u))}}function gt(e,t){var n=e.getElementsByTagName?e.getElementsByTagName(t||"*"):e.querySelectorAll?e.querySelectorAll(t||"*"):[];return t===undefined||t&&x.nodeName(e,t)?x.merge([e],n):n}function mt(e,t){var n=t.nodeName.toLowerCase();"input"===n&&it.test(e.type)?t.checked=e.checked:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}x.fn.extend({wrapAll:function(e){var t;return x.isFunction(e)?this.each(function(t){x(this).wrapAll(e.call(this,t))}):(this[0]&&(t=x(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this)},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var yt,vt,xt=/^(none|table(?!-c[ea]).+)/,bt=/^margin/,wt=RegExp("^("+b+")(.*)$","i"),Tt=RegExp("^("+b+")(?!px)[a-z%]+$","i"),Ct=RegExp("^([+-])=("+b+")","i"),kt={BODY:"block"},Nt={position:"absolute",visibility:"hidden",display:"block"},Et={letterSpacing:0,fontWeight:400},St=["Top","Right","Bottom","Left"],jt=["Webkit","O","Moz","ms"];function Dt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=jt.length;while(i--)if(t=jt[i]+n,t in e)return t;return r}function At(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function Lt(t){return e.getComputedStyle(t,null)}function qt(e,t){var n,r,i,o=[],s=0,a=e.length;for(;a>s;s++)r=e[s],r.style&&(o[s]=q.get(r,"olddisplay"),n=r.style.display,t?(o[s]||"none"!==n||(r.style.display=""),""===r.style.display&&At(r)&&(o[s]=q.access(r,"olddisplay",Pt(r.nodeName)))):o[s]||(i=At(r),(n&&"none"!==n||!i)&&q.set(r,"olddisplay",i?n:x.css(r,"display"))));for(s=0;a>s;s++)r=e[s],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[s]||"":"none"));return e}x.fn.extend({css:function(e,t){return x.access(this,function(e,t,n){var r,i,o={},s=0;if(x.isArray(t)){for(r=Lt(e),i=t.length;i>s;s++)o[t[s]]=x.css(e,t[s],!1,r);return o}return n!==undefined?x.style(e,t,n):x.css(e,t)},e,t,arguments.length>1)},show:function(){return qt(this,!0)},hide:function(){return qt(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:At(this))?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=yt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,s,a=x.camelCase(t),u=e.style;return t=x.cssProps[a]||(x.cssProps[a]=Dt(u,a)),s=x.cssHooks[t]||x.cssHooks[a],n===undefined?s&&"get"in s&&(i=s.get(e,!1,r))!==undefined?i:u[t]:(o=typeof n,"string"===o&&(i=Ct.exec(n))&&(n=(i[1]+1)*i[2]+parseFloat(x.css(e,t)),o="number"),null==n||"number"===o&&isNaN(n)||("number"!==o||x.cssNumber[a]||(n+="px"),x.support.clearCloneStyle||""!==n||0!==t.indexOf("background")||(u[t]="inherit"),s&&"set"in s&&(n=s.set(e,n,r))===undefined||(u[t]=n)),undefined)}},css:function(e,t,n,r){var i,o,s,a=x.camelCase(t);return t=x.cssProps[a]||(x.cssProps[a]=Dt(e.style,a)),s=x.cssHooks[t]||x.cssHooks[a],s&&"get"in s&&(i=s.get(e,!0,n)),i===undefined&&(i=yt(e,t,r)),"normal"===i&&t in Et&&(i=Et[t]),""===n||n?(o=parseFloat(i),n===!0||x.isNumeric(o)?o||0:i):i}}),yt=function(e,t,n){var r,i,o,s=n||Lt(e),a=s?s.getPropertyValue(t)||s[t]:undefined,u=e.style;return s&&(""!==a||x.contains(e.ownerDocument,e)||(a=x.style(e,t)),Tt.test(a)&&bt.test(t)&&(r=u.width,i=u.minWidth,o=u.maxWidth,u.minWidth=u.maxWidth=u.width=a,a=s.width,u.width=r,u.minWidth=i,u.maxWidth=o)),a};function Ht(e,t,n){var r=wt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function Ot(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,s=0;for(;4>o;o+=2)"margin"===n&&(s+=x.css(e,n+St[o],!0,i)),r?("content"===n&&(s-=x.css(e,"padding"+St[o],!0,i)),"margin"!==n&&(s-=x.css(e,"border"+St[o]+"Width",!0,i))):(s+=x.css(e,"padding"+St[o],!0,i),"padding"!==n&&(s+=x.css(e,"border"+St[o]+"Width",!0,i)));return s}function Ft(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Lt(e),s=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=yt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Tt.test(i))return i;r=s&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+Ot(e,t,n||(s?"border":"content"),r,o)+"px"}function Pt(e){var t=o,n=kt[e];return n||(n=Rt(e,t),"none"!==n&&n||(vt=(vt||x("