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 d130a26da..7a7afa5eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,8 @@ - `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 @@ -32,6 +34,10 @@ - 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 @@ -58,7 +64,8 @@ * 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) + 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)) @@ -82,6 +89,22 @@ 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)) ### Bug Fixes @@ -98,6 +121,14 @@ 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 @@ -116,10 +147,22 @@ * [#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 * 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 ([Commits](https://github.com/foosel/OctoPrint/compare/master...devel)) @@ -139,6 +182,9 @@ * [#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 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cf41b053e..4f4c46cf8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,22 +1,49 @@ Issues, Tickets, however you may call them ------------------------------------------ -Read the following short instructions **fully** and **follow them** if you want your ticket to be taken care of and not closed again directly! +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. -- 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 treated as if only describing the first purpose, the others will be ignored! -- 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. +- **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!**. Note that for problems like these, the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741) will probably get you help faster! -- If you have a general **question**, **add [Question] to your issue's title!**. Note that for problems like these, the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741) will probably get you help faster! -- If you have another reason for creating a ticket that doesn't fit any of the above categories, think hard if it might not be something better suited for the [Mailinglist](https://groups.google.com/group/octoprint) or the [Google+ Community](https://plus.google.com/communities/102771308349328485741). If you are sure it needs to be reported here, **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 0226858e2..82ddf50b3 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -4,3 +4,5 @@ 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/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/index.rst b/docs/api/index.rst index 4f1d643f6..f0295e0eb 100644 --- a/docs/api/index.rst +++ b/docs/api/index.rst @@ -1,8 +1,8 @@ .. _sec-api: -### -API -### +######## +REST API +######## .. toctree:: :maxdepth: 2 diff --git a/docs/api/printer.rst b/docs/api/printer.rst index 469af8dde..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. @@ -902,8 +953,20 @@ Arbitrary Command Request * - ``command`` - 0..1 - String - - Single command to send to the printer, mutually exclusive with ``commands``. + - 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``. + - 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 index 215d201b4..b529b9d2e 100644 --- a/docs/api/printerprofiles.rst +++ b/docs/api/printerprofiles.rst @@ -65,7 +65,7 @@ Profile list - :ref:`Profile ` - Information about a profile stored in the system. -.. _sec-api-slicing-datamodel-update: +.. _sec-api-printerprofiles-datamodel-update: Add or update request --------------------- @@ -84,7 +84,7 @@ Add or update request - 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-slicing-datamodel-profile: +.. _sec-api-printerprofiles-datamodel-profile: Profile ------- diff --git a/docs/conf.py b/docs/conf.py index 5c5ae80b2..32dd418a5 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -17,6 +17,7 @@ import sys, os # 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 @@ -27,11 +28,11 @@ year_current = date.today().year # -- 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', 'sphinx.ext.autodoc', '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. @@ -103,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. @@ -140,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 58e3dd717..d1973c5e0 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -6,11 +6,14 @@ 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 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_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/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/gettingstarted.rst b/docs/plugins/gettingstarted.rst index 96815e423..61f58e3f2 100644 --- a/docs/plugins/gettingstarted.rst +++ b/docs/plugins/gettingstarted.rst @@ -4,11 +4,13 @@ Getting Started =============== Over the course of this little tutorial we'll build a full fledged, installable OctoPrint plugin that displays "Hello World!" -at various places throughout OctoPrint. +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 @@ -37,6 +39,7 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t .. code-block:: python :emphasize-lines: 4-8,13 + :linenos: # coding=utf-8 from __future__ import absolute_import @@ -100,6 +103,7 @@ Then edit the configuration in the ``setup.py`` file to mirror our own "Hello Wo look something like this: .. code-block:: python + :linenos: plugin_identifier = "helloworld" plugin_name = "OctoPrint-HelloWorld" @@ -137,6 +141,7 @@ Something is still a bit ugly though. Take a look into ``__init__.py`` and ``set of information now defined twice: .. code-block:: python + :linenos: # __init__.py: __plugin_name__ = "Hello World" @@ -153,6 +158,7 @@ within ``setup.py``! So, we don't really need to define all this data twice. Rem and ``__plugin_description__``: .. code-block:: python + :linenos: # coding=utf-8 from __future__ import absolute_import @@ -174,6 +180,7 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the .. code-block:: python :emphasize-lines: 10 + :linenos: # coding=utf-8 from __future__ import absolute_import @@ -218,6 +225,7 @@ add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class: .. code-block:: python :emphasize-lines: 7 + :linenos: # coding=utf-8 from __future__ import absolute_import @@ -236,6 +244,7 @@ Next, we'll create a sub folder ``templates`` underneath our ``octoprint_hellowo ``helloworld_navbar.jinja2`` like so: .. code-block:: html + :linenos: Hello World! @@ -279,6 +288,7 @@ 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 @@ -312,6 +322,7 @@ Adjust your plugin's ``__init__.py`` like this: .. code-block:: python :emphasize-lines: 15-16 + :linenos: # coding=utf-8 from __future__ import absolute_import @@ -336,6 +347,7 @@ Adjust your plugin's ``__init__.py`` like this: Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this: .. code-block:: html + :linenos: Hello World! @@ -372,6 +384,7 @@ So in your plugin's ``templates`` folder create a new file ``helloworld_settings into it: .. code-block:: html + :linenos:
@@ -393,6 +406,7 @@ Now adjust your ``templates/helloworld_navbar.jinja2`` file to use a ``data-bind settings view model into the ``href`` attribute of the link tag: .. code-block:: html + :linenos: Hello World! @@ -415,6 +429,7 @@ again since we don't use that anymore: .. code-block:: python :emphasize-lines: 15-19 + :linenos: # coding=utf-8 from __future__ import absolute_import @@ -458,4 +473,434 @@ Nice! Edit the value, then click "Save". Your link in the navigation bar should 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 :) \ No newline at end of file +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/index.rst b/docs/plugins/index.rst index 76b0621ac..c043aaf68 100644 --- a/docs/plugins/index.rst +++ b/docs/plugins/index.rst @@ -1,5 +1,3 @@ -.. automodule:: octoprint.plugin.types - .. _sec-plugins: ####### @@ -19,6 +17,7 @@ additional slicers. More plugin types are planned for the future. using.rst gettingstarted.rst infrastructure.rst + templates.rst distributing.rst mixins.rst hooks.rst diff --git a/docs/plugins/mixins.rst b/docs/plugins/mixins.rst index 083d8bf00..c414934de 100644 --- a/docs/plugins/mixins.rst +++ b/docs/plugins/mixins.rst @@ -3,7 +3,99 @@ Available plugin mixins ======================= -.. automodule:: octoprint.plugin - :members: AppPlugin, AssetPlugin, BlueprintPlugin, EventHandlerPlugin, ProgressPlugin, SettingsPlugin, ShutdownPlugin, SimpleApiPlugin, SlicerPlugin, StartupPlugin, TemplatePlugin - :undoc-members: +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/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 b3f117e0e..000000000 --- a/requirements-dev.txt +++ /dev/null @@ -1,6 +0,0 @@ -mock>=1.0.1 -nose>=1.3.0 -sphinxcontrib-httpdomain -sphinx_rtd_theme -po2json -ddt diff --git a/requirements.txt b/requirements.txt index 5dbe72185..3175f72cd 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,16 +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>=0.1.4 -netifaces -pylru -rsa -pkginfo +### +# 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 ecb80ffe0..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 = [] @@ -287,7 +335,15 @@ def params(): 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"): @@ -299,10 +355,6 @@ def params(): ] } - #scripts = { - # "scripts/octoprint.init": "/etc/init.d/octoprint" - #} - return locals() setup(**params()) diff --git a/src/octoprint/events.py b/src/octoprint/events.py index f16c23f84..e176b0529 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -69,6 +69,7 @@ class Events(object): CONVEYOR = "Conveyor" EJECT = "Eject" E_STOP = "EStop" + REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived" # Timelapse CAPTURE_START = "CaptureStart" @@ -340,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 9c65a67ae..dfab1da8b 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -8,8 +8,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import logging import os +import octoprint.plugin + from octoprint.events import eventManager, Events -from octoprint.plugin import plugin_manager, ProgressPlugin from .destinations import FileDestinations from .analysis import QueueEntry, AnalysisQueue @@ -114,7 +115,7 @@ class FileManager(object): self._slicing_progress_callbacks = [] self._last_slicing_progress = None - self._progress_plugins = plugin_manager().get_implementations(ProgressPlugin) + 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) @@ -157,7 +158,7 @@ class FileManager(object): 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.get_absolute_path(source_location, source_path) + 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: @@ -291,7 +292,7 @@ class FileManager(object): 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).get_absolute_path(file_path) + absolute_path = self._storage(destination).path_on_disk(file_path) if analysis is None: file_type = get_file_type(absolute_path) @@ -343,8 +344,8 @@ class FileManager(object): def remove_additional_metadata(self, destination, path, key): self._storage(destination).remove_additional_metadata(path, key) - def get_absolute_path(self, destination, path): - return self._storage(destination).get_absolute_path(path) + 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) @@ -361,8 +362,8 @@ class FileManager(object): def join_path(self, destination, *path): return self._storage(destination).join_path(*path) - def rel_path(self, destination, path): - return self._storage(destination).rel_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: diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index b2cf61425..5dc8695fa 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -13,75 +13,291 @@ import tempfile import octoprint.filemanager -from octoprint.util import safeRename - +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 rel_path(self, path): + 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 get_absolute_path(self, path): + 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)) @@ -131,55 +347,6 @@ class LocalFileStorage(StorageInterface): return os.path.exists(file_path) and os.path.isfile(file_path) 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 path: base path from which to recursively list all files, optional, if not supplied listing will start - from root of base folder - :param 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 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 - """ - if path: path = self.sanitize_path(path) else: @@ -187,14 +354,6 @@ class LocalFileStorage(StorageInterface): return self._list_folder(path, filter=filter, recursive=recursive) def add_folder(self, path, ignore_existing=True): - """ - Adds a folder as ``path``. The ``path`` will be sanitized. - - :param path: the path of the new folder - :param 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 - """ - path, name = self.sanitize(path) folder_path = os.path.join(path, name) @@ -204,17 +363,9 @@ class LocalFileStorage(StorageInterface): else: os.mkdir(folder_path) - return self.rel_path((path, name)) + return self.path_in_storage((path, name)) def remove_folder(self, path, recursive=True): - """ - Removes the folder at ``path``. - - :param path: the path of the folder to remove - :param 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 - """ - path, name = self.sanitize(path) folder_path = os.path.join(path, name) @@ -231,19 +382,6 @@ class LocalFileStorage(StorageInterface): shutil.rmtree(folder_path) def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False): - """ - Adds the file ``file_object`` as ``path`` - - :param path: the file's new path, will be sanitized - :param 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 printer_profile: the printer profile associated with this file (if any) - :param links: any links to add with the file - :param 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 - """ - path, name = self.sanitize(path) if not octoprint.filemanager.valid_file_type(name): raise RuntimeError("{name} is an unrecognized file type".format(**locals())) @@ -284,16 +422,9 @@ class LocalFileStorage(StorageInterface): self._add_links(name, path, links) - return self.rel_path((path, name)) + return self.path_in_storage((path, name)) 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 path: path of the file to remove - """ - path, name = self.sanitize(path) metadata = self._get_metadata(path) @@ -322,13 +453,6 @@ class LocalFileStorage(StorageInterface): self._save_metadata(path, metadata) 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 - """ - path, name = self.sanitize(path) metadata = self._get_metadata(path) @@ -343,43 +467,10 @@ class LocalFileStorage(StorageInterface): 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 - """ - path, name = self.sanitize(path) self._add_links(name, path, [(rel, data)]) 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 - """ - path, name = self.sanitize(path) self._remove_links(name, path, [(rel, data)]) @@ -396,22 +487,6 @@ class LocalFileStorage(StorageInterface): self._update_history(name, path, index) 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 - """ - path, name = self.sanitize(path) metadata = self._get_metadata(path) metadata_dirty = False @@ -437,13 +512,6 @@ class LocalFileStorage(StorageInterface): self._save_metadata(path, metadata) 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 - """ - path, name = self.sanitize(path) metadata = self._get_metadata(path) @@ -457,13 +525,6 @@ class LocalFileStorage(StorageInterface): self._save_metadata(path, metadata) 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) - """ - split = path.split("/") if len(split) == 1: return "", split[0] @@ -471,21 +532,143 @@ class LocalFileStorage(StorageInterface): return self.join_path(*split[:-1]), split[-1] 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 - """ - return "/".join(path) - def get_absolute_path(self, path): + def sanitize(self, path): """ - Retrieves the absolute path on disk for ``path`` + Returns a ``(path, name)`` tuple derived from the provided ``path``. - :param path: the virtual path for which to retrieve the absolute path on disk - :return: the absolute path on disk to ``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) @@ -791,64 +974,6 @@ class LocalFileStorage(StorageInterface): return hash.hexdigest() - def sanitize(self, path): - 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): - 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): - 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 rel_path(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 _get_metadata(self, path): if path in self._metadata_cache: return self._metadata_cache[path] @@ -878,7 +1003,7 @@ class LocalFileStorage(StorageInterface): with open(metadata_temporary_path, "w") as f: import yaml yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True) - safeRename(metadata_temporary_path, metadata_path, throw_error=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: diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index 90859e1bf..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 " @@ -12,12 +26,47 @@ 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, 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"))) @@ -48,11 +97,62 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en 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, 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: @@ -67,14 +167,76 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call result = getattr(plugin, method)(*args, **kwargs) if callback: callback(name, plugin, result) - except Exception as e: + except Exception as exc: logging.getLogger(__name__).exception("Error while calling plugin %s" % name) if error_callback: - error_callback(name, plugin, e) + 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 @@ -83,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 @@ -99,49 +271,111 @@ 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 globalSet(self, path, value): - self.settings.set(path, value) + 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 globalSetInt(self, path, value): - self.settings.setInt(path, value) + 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 globalSetFloat(self, path, value): - self.settings.setFloat(path, value) + 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. - def globalSetBoolean(self, path, value): - self.settings.setBoolean(path, value) + Directly forwards to :func:`octoprint.settings.Settings.set`. + """ + self.settings.set(path, value, **kwargs) - def globalGetBaseFolder(self, folder_type): - return self.settings.getBaseFolder(folder_type) + 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 getPluginLogfilePath(self, postfix=None): + 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 @@ -149,10 +383,60 @@ class PluginSettings(object): 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 973cebf39..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__' @@ -125,6 +146,12 @@ class PluginInfo(object): class PluginManager(object): + """ + The :class:`PluginManager` is the central component for finding, loading and accessing plugins provided to the + system. + + 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__) @@ -294,7 +321,10 @@ class PluginManager(object): 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 ) - self.plugin_implementations[name].update(plugin.get_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) @@ -402,5 +432,34 @@ class PluginManager(object): class Plugin(object): + """ + 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 d3cc67439..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,7 +20,55 @@ __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. @@ -37,7 +96,7 @@ class StartupPlugin(Plugin): 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` @@ -51,14 +110,14 @@ class ShutdownPlugin(Plugin): 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 :class:`TemplatePlugin`s. + through a :class:`TemplatePlugin`. """ def get_asset_folder(self): @@ -104,7 +163,7 @@ class AssetPlugin(Plugin): return dict() -class TemplatePlugin(Plugin): +class TemplatePlugin(OctoPrintPlugin): """ Using the ``TemplatePlugin`` mixin plugins may inject their own components into the OctoPrint web interface. @@ -201,6 +260,12 @@ class TemplatePlugin(Plugin): - 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). @@ -238,6 +303,12 @@ class TemplatePlugin(Plugin): - 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). @@ -279,6 +350,12 @@ class TemplatePlugin(Plugin): - 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). @@ -320,6 +397,12 @@ class TemplatePlugin(Plugin): - 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). @@ -384,18 +467,142 @@ class TemplatePlugin(Plugin): 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. @@ -419,18 +626,18 @@ class BlueprintPlugin(Plugin): return flask.make_response("Expected a text to echo back.", 400) return flask.request.values["text"] - __plugin_implementations__ = [MyPlugin()] + __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.: + ``plugin..``, e.g.: .. code-block:: python - flask.url_for("plugin.myblueprintplugin.echo") # will return "/plugin/myblueprintplugin/echo" + flask.url_for("plugin.myblueprintplugin.myEcho") # will return "/plugin/myblueprintplugin/echo" """ @@ -498,7 +705,7 @@ class BlueprintPlugin(Plugin): 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. @@ -549,6 +756,11 @@ class SettingsPlugin(Plugin): 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): @@ -585,7 +797,8 @@ class SettingsPlugin(Plugin): 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. - :param dict data: the settings dictionary to be saved for the plugin + Arguments: + data (dict): The settings dictionary to be saved for the plugin """ import octoprint.util @@ -602,17 +815,99 @@ class SettingsPlugin(Plugin): """ 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(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. + """ -class EventHandlerPlugin(Plugin): 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(Plugin): +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, @@ -620,26 +915,75 @@ class SlicerPlugin(Plugin): progress_report=False ) - def get_slicer_profile_options(self): + 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): - return None + """ + Should return a :class:`SlicingProfile` parsed from the slicing profile stored at the indicated ``path``. - def get_slicer_default_profile(self): + :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, on_progress=None, on_progress_args=None, on_progress_kwargs=None): + 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(Plugin): +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. @@ -669,7 +1013,7 @@ class ProgressPlugin(Plugin): pass -class AppPlugin(Plugin): +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 index b0509df4d..909e4285e 100644 --- a/src/octoprint/plugins/cura/__init__.py +++ b/src/octoprint/plugins/cura/__init__.py @@ -39,26 +39,26 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, def on_startup(self, host, port): # setup our custom logger - cura_logging_handler = logging.handlers.RotatingFileHandler(self._settings.getPluginLogfilePath(postfix="engine"), maxBytes=2*1024*1024) + 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.getBoolean(["debug_logging"]) else logging.CRITICAL) + 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 importCuraProfile(self): + def import_cura_profile(self): import datetime import tempfile from octoprint.server import slicingManager input_name = "file" - input_upload_name = input_name + "." + self._settings.globalGet(["server", "uploads", "nameSuffix"]) - input_upload_path = input_name + "." + self._settings.globalGet(["server", "uploads", "pathSuffix"]) + 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] @@ -92,7 +92,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, # 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.getFormattedDateTime(datetime.datetime.now())) + profile_description = "Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now())) profile_allow_overwrite = False # overrides @@ -134,11 +134,11 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, ##~~ SettingsPlugin API def on_settings_save(self, data): - old_debug_logging = self._settings.getBoolean(["debug_logging"]) + old_debug_logging = self._settings.get_boolean(["debug_logging"]) super(CuraPlugin, self).on_settings_save(data) - new_debug_logging = self._settings.getBoolean(["debug_logging"]) + 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) diff --git a/src/octoprint/plugins/cura/static/js/cura.js b/src/octoprint/plugins/cura/static/js/cura.js index e782a8815..83a02d79b 100644 --- a/src/octoprint/plugins/cura/static/js/cura.js +++ b/src/octoprint/plugins/cura/static/js/cura.js @@ -187,5 +187,9 @@ $(function() { } // view model class, parameters for constructor, container to bind to - ADDITIONAL_VIEWMODELS.push([CuraViewModel, ["loginStateViewModel", "settingsViewModel", "slicingViewModel"], document.getElementById("settings_plugin_cura")]); + OCTOPRINT_VIEWMODELS.push([ + CuraViewModel, + ["loginStateViewModel", "settingsViewModel", "slicingViewModel"], + "#settings_plugin_cura" + ]); }); \ 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 index 35a27d382..943586ac3 100644 --- a/src/octoprint/plugins/cura/templates/cura_settings.jinja2 +++ b/src/octoprint/plugins/cura/templates/cura_settings.jinja2 @@ -66,7 +66,7 @@
{{ _('Browse...') }} - +
diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index 5a7e1dd60..7516940d3 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -467,7 +467,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, if self._settings.get(["pathPrefix"]): path = self._settings.get(["pathPrefix"]) else: - prefix = self._settings.globalGet(["server", "reverseProxy", "prefixFallback"]) + prefix = self._settings.global_get(["server", "reverseProxy", "prefixFallback"]) if prefix: path = prefix @@ -676,7 +676,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, return upnpUuid def get_instance_name(self): - name = self._settings.globalGet(["appearance", "name"]) + name = self._settings.global_get(["appearance", "name"]) if name: return u"OctoPrint instance \"{}\"".format(name) else: diff --git a/src/octoprint/printer/__init__.py b/src/octoprint/printer/__init__.py index e537e2798..3f97dedaf 100644 --- a/src/octoprint/printer/__init__.py +++ b/src/octoprint/printer/__init__.py @@ -1,26 +1,45 @@ # 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 time -import threading -import copy -import os -import logging +import re 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 - -from octoprint.plugin import plugin_manager, ProgressPlugin - -def getConnectionOptions(): +def get_connection_options(): """ - Retrieves the available ports, baudrates, prefered port and baudrate for connecting to the printer. + 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(), @@ -30,908 +49,416 @@ def getConnectionOptions(): "autoconnect": settings().getBoolean(["serial", "autoconnect"]) } -class Printer(): - def __init__(self, fileManager, analysisQueue, printerProfileManager): - from collections import deque - self._logger = logging.getLogger(__name__) - #self._estimationLogger = logging.getLogger("ESTIMATIONS") - #self._printTimeLogger = logging.getLogger("PRINT_TIME") +class PrinterInterface(object): + """ + The :class:`PrinterInterface` represents the developer interface to the :class:`~octoprint.printer.standard.Printer` + instance. + """ - self._analysisQueue = analysisQueue - self._fileManager = fileManager - self._printerProfileManager = printerProfileManager + valid_axes = ("x", "y", "z", "e") + """Valid axes identifiers.""" - # 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 = [] + valid_tool_regex = re.compile("^(tool\d+)$") + """Regex for valid tool identifiers.""" - 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( - 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) - eventManager().subscribe(Events.METADATA_STATISTICS_UPDATED, self.onMetadataStatisticsUpdated) - - #~~ 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: self._logger.exception("Exception while adding temperature data point") - - def _sendAddLogCallbacks(self, data): - for callback in self._callbacks: - try: callback.addLog(data) - except: self._logger.exception("Exception while adding communication log entry") - - def _sendAddMessageCallbacks(self, data): - for callback in self._callbacks: - try: callback.addMessage(data) - except: self._logger.exception("Exception while adding printer message") - - def _sendCurrentDataCallbacks(self, data): - for callback in self._callbacks: - try: callback.sendCurrentData(copy.deepcopy(data)) - except: self._logger.exception("Exception while pushing current data") - - def _sendTriggerUpdateCallbacks(self, type): - for callback in self._callbacks: - try: callback.sendEvent(type) - except: self._logger.exception("Exception while pushing trigger update") - - def _sendFeedbackCommandOutput(self, name, output): - for callback in self._callbacks: - try: callback.sendFeedbackCommandOutput(name, output) - except: self._logger.exception("Exception while pushing feedback command output") - - #~~ callback from metadata analysis event - - def onMetadataAnalysisFinished(self, event, data): - if self._selectedFile: - self._setJobData(self._selectedFile["filename"], - self._selectedFile["filesize"], - self._selectedFile["sd"]) - - def onMetadataStatisticsUpdated(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() - - #~~ printer commands + 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. If port and/or baudrate is provided, uses these settings, otherwise autodetection - will be attempted. + 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`. """ - if self._comm is not None: - self._comm.close() - self._comm = comm.MachineCom(port, baudrate, callbackObject=self) - self._printerProfileManager.select(profile) + pass def disconnect(self): """ - Closes the connection to the printer. + Disconnects from the printer. Does nothing if no connection is currently established. """ - if self._comm is not None: - self._comm.close() - self._comm = None - self._printerProfileManager.deselect() - eventManager().fire(Events.DISCONNECTED) + raise NotImplementedError() - def command(self, command): + def get_transport(self): """ - Sends a single gcode command to the printer. + 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 """ - self.commands([command]) + raise NotImplementedError() def commands(self, commands): """ - Sends multiple gcode commands (provided as a list) to the printer. - """ - if self._comm is None: - return + Sends the provided ``commands`` to the printer. - for command in commands: - self._comm.sendCommand(command) + 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): - 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"]) + """ + 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): - self.commands(["G91", "G28 %s" % " ".join(map(lambda x: "%s0" % x.upper(), axes)), "G90"]) + """ + 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): - 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 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"): - printer_profile = self._printerProfileManager.get_current_or_default() - extruder_count = printer_profile["extruder"]["count"] - if extruder_count > 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()): - self._logger.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 + Extrude ``amount`` milimeters of material from the tool. + + Arguments: + amount (int, float): The amount of material to extrude in mm """ - if self._comm is None or not self._comm.isOperational() or self._comm.isPrinting(): - return - if self._selectedFile is None: - return + raise NotImplementedError() - self._timeEstimationData = TimeEstimationHelper() - self._lastProgressReport = None - self._setCurrentZ(None) - self._comm.startPrint() - - def togglePausePrint(self): + def change_tool(self, tool): """ - Pause the current printjob. + 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", ...) """ - if self._comm is None: - return + raise NotImplementedError() - self._comm.setPause(not self._comm.isPaused()) - - def cancelPrint(self, disableMotorsAndHeater=True): + def set_temperature(self, heater, value): """ - Cancel the current printjob. + 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. """ - if self._comm is None: - return + raise NotImplementedError() - self._comm.cancelPrint() - - if disableMotorsAndHeater: - printer_profile = self._printerProfileManager.get_current_or_default() - extruder_count = printer_profile["extruder"]["count"] - - # disable motors, switch off hotends, bed and fan - commands = ["M84"] - commands.extend(map(lambda x: "M104 T%d S0" % x, range(extruder_count))) - 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._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) - - #~~ 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 _estimateTotalPrintTime(self, progress, printTime): - if not progress or not printTime or not self._timeEstimationData: - #self._estimationLogger.info("{progress};{printTime};;;;".format(**locals())) - return None - - else: - newEstimate = printTime / progress - self._timeEstimationData.update(newEstimate) - - result = None - if self._timeEstimationData.is_stable(): - result = self._timeEstimationData.average_total_rolling - - #averageTotal = self._timeEstimationData.average_total - #averageTotalRolling = self._timeEstimationData.average_total_rolling - #averageDistance = self._timeEstimationData.average_distance - - #self._estimationLogger.info("{progress};{printTime};{newEstimate};{averageTotal};{averageTotalRolling};{averageDistance}".format(**locals())) - - return result - - def _setProgressData(self, progress, filepos, printTime, cleanedPrintTime): - estimatedTotalPrintTime = self._estimateTotalPrintTime(progress, cleanedPrintTime) - statisticalTotalPrintTime = None - 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._printTimeLogger.info("{progress};{cleanedPrintTime};{estimatedTotalPrintTime};{statisticalTotalPrintTime};{totalPrintTime}".format(**locals())) - - self._progress = progress - self._printTime = printTime - self._printTimeLeft = totalPrintTime - cleanedPrintTime if (totalPrintTime is not None and cleanedPrintTime is not None) else None - - 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) 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.addTemperature(data) - - def _setJobData(self, filename, filesize, sd): - if filename is not None: - self._selectedFile = { - "filename": filename, - "filesize": filesize, - "sd": sd, - "estimatedPrintTime": None - } - else: - self._selectedFile = None - self._stateMonitor.setJobData({ - "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 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) - - try: - fileData = self._fileManager.get_metadata(FileDestinations.SDCARD if sd else FileDestinations.LOCAL, filename) - 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.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, - "averagePrintTime": averagePrintTime, - "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): + def set_temperature_offset(self, offsets=None): """ - Callback method for the comm object, called upon log output. + 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. """ - self._addLog(message) + raise NotImplementedError() - def mcTempUpdate(self, temp, bedTemp): - self._addTemperatureData(temp, bedTemp) - - def mcStateChange(self, state): + def feed_rate(self, factor): """ - Callback method for the comm object, called if the connection state changes. + 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. """ - oldState = self._state + raise NotImplementedError() - # 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 mcMessage(self, message): + def flow_rate(self, factor): """ - 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. + 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. """ - self._addMessage(message) + raise NotImplementedError() - def mcProgress(self): + def select_file(self, path, sd, printAfterSelect=False): """ - 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. + 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() - self._setProgressData(self._comm.getPrintProgress(), self._comm.getPrintFilepos(), self._comm.getPrintTime(), self._comm.getCleanedPrintTime()) - - def mcZChange(self, newZ): + def unselect_file(self): """ - Callback method for the comm object, called upon change of the z-layer. + Unselects and currently selected file. """ - 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}) + raise NotImplementedError() - 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) - - def mcForceDisconnect(self): - self.disconnect() - - #~~ 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(): - self._logger.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._timeEstimationData = TimeEstimationHelper() - 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): + def start_print(self): """ - 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. + Starts printing the currently selected file. If no file is currently selected, does nothing. """ - if not self._comm or not self._comm.isSdReady(): - return - self._sdFilelistAvailable.clear() - self._comm.refreshSdFiles() - if blocking: - self._sdFilelistAvailable.wait(10000) + raise NotImplementedError() - #~~ state reports - - def getStateString(self): + def toggle_pause_print(self): """ - Returns a human readable string corresponding to the current communication state. + Pauses the current print job if it is currently running or resumes it if it is currently paused. """ - if self._comm is None: - return "Offline" - else: - return self._comm.getStateString() + raise NotImplementedError() - def getCurrentData(self): - return self._stateMonitor.getCurrentData() + def cancel_print(self): + """ + Cancels the current print job. + """ + raise NotImplementedError() - def getCurrentJob(self): - currentData = self._stateMonitor.getCurrentData() - return currentData["job"] + def get_state_string(self): + """ + Returns: + (str) A human readable string corresponding to the current communication state. + """ + raise NotImplementedError() - def getCurrentTemperatures(self): - if self._comm is not None: - tempOffset, bedTempOffset = self._comm.getOffsets() - else: - tempOffset = {} - bedTempOffset = None + def get_current_data(self): + """ + Returns: + (dict) The current state data. + """ + raise NotImplementedError() - 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 - } + def get_current_job(self): + """ + Returns: + (dict) The data of the current job. + """ + raise NotImplementedError() - return result + def get_current_temperatures(self): + """ + Returns: + (dict) The current temperatures. + """ + raise NotImplementedError() - def getTemperatureHistory(self): - return self._temps + def get_temperature_history(self): + """ + Returns: + (list) The temperature history. + """ + raise NotImplementedError() - def getCurrentConnection(self): - if self._comm is None: - return "Closed", None, None, None + 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() - 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): + """ + Returns: + (boolean) Whether the printer is currently disconnected and/or in an error state. + """ + raise NotImplementedError() - def isClosedOrError(self): - return self._comm is None or self._comm.isClosedOrError() + def is_operational(self): + """ + Returns: + (boolean) Whether the printer is currently connected and available. + """ + raise NotImplementedError() - def isOperational(self): - return self._comm is not None and self._comm.isOperational() + def is_printing(self): + """ + Returns: + (boolean) Whether the printer is currently printing. + """ + raise NotImplementedError() - def isPrinting(self): - return self._comm is not None and self._comm.isPrinting() + def is_paused(self): + """ + Returns: + (boolean) Whether the printer is currently paused. + """ + raise NotImplementedError() - def isPaused(self): - return self._comm is not None and self._comm.isPaused() + def is_error(self): + """ + Returns: + (boolean) Whether the printer is currently in an error state. + """ + raise NotImplementedError() - def isError(self): - return self._comm is not None and self._comm.isError() + def is_ready(self): + """ + Returns: + (boolean) Whether the printer is currently operational and ready for new print jobs (not printing). + """ + raise NotImplementedError() - def isReady(self): - return self.isOperational() and not self._comm.isStreaming() + def register_callback(self, callback): + """ + Registers a :class:`PrinterCallback` with the instance. - def isSdReady(self): - if not settings().getBoolean(["feature", "sdSupport"]) or self._comm is None: - return False - else: - return self._comm.isSdReady() + Arguments: + callback (PrinterCallback): The callback object to register. + """ + raise NotImplementedError() -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 + def unregister_callback(self, callback): + """ + Unregisters a :class:`PrinterCallback` from the instance. - 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 - } + Arguments: + callback (PrinterCallback): The callback object to unregister. + """ + raise NotImplementedError() -class TimeEstimationHelper(object): +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. - STABLE_THRESHOLD = 0.1 - STABLE_COUNTDOWN = 250 - STABLE_ROLLING_WINDOW = 250 + Arguments: + data (str): The received log line. + """ + pass - def __init__(self): - import collections - self._distances = collections.deque([], self.__class__.STABLE_ROLLING_WINDOW) - self._totals = collections.deque([], self.__class__.STABLE_ROLLING_WINDOW) - self._sum_total = 0 - self._count = 0 - self._stable_counter = None + def on_printer_add_message(self, data): + """ + Called when the :class:`PrinterInterface` receives a new message from the communication layer. - def is_stable(self): - return self._stable_counter is not None and self._stable_counter >= self.__class__.STABLE_COUNTDOWN + Arguments: + data (str): The received message. + """ + pass - def update(self, newEstimate): - old_average_total = self.average_total + def on_printer_add_temperature(self, data): + """ + Called when the :class:`PrinterInterface` receives a new temperature data set from the communication layer. - self._sum_total += newEstimate - self._totals.append(newEstimate) - self._count += 1 + ``data`` is a ``dict`` of the following structure:: - if old_average_total: - self._distances.append(abs(self.average_total - old_average_total)) + tool0: + actual: + target: + ... + bed: + actual: + target: - if -1.0 * self.__class__.STABLE_THRESHOLD < self.average_distance < self.__class__.STABLE_THRESHOLD: - if self._stable_counter is None: - self._stable_counter = 0 - else: - self._stable_counter += 1 - else: - self._stable_counter = None + Arguments: + data (dict): A dict of all current temperatures in the format as specified above + """ + pass - @property - def average_total(self): - if not self._count: - return None - else: - return self._sum_total / self._count + def on_printer_received_registered_message(self, name, output): + """ + Called when the :class:`PrinterInterface` received a registered message, e.g. from a feedback command. - @property - def average_total_rolling(self): - if not self._count or self._count < self.__class__.STABLE_ROLLING_WINDOW: - return None - else: - return sum(self._totals) / len(self._totals) + Arguments: + name (str): Name of the registered message (e.g. the feedback command) + output (str): Output for the registered message + """ + pass - @property - def average_distance(self): - if not self._count or self._count < self.__class__.STABLE_ROLLING_WINDOW + 1: - return None - else: - return sum(self._distances) / len(self._distances) + 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 index 2a1333833..2c9363ef6 100644 --- a/src/octoprint/printer/profile.py +++ b/src/octoprint/printer/profile.py @@ -32,6 +32,101 @@ class BedTypes(object): 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", 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 098f95122..28ef95cb3 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -7,7 +7,7 @@ __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, session +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, gettext, ngettext @@ -43,8 +43,9 @@ 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.users as users import octoprint.events as events @@ -108,12 +109,74 @@ def get_locale(): @util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values) def index(): - #~~ extract data from asset plugins + #~~ 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() + + 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()), @@ -123,15 +186,17 @@ def index(): generic=dict(order=[], entries=dict()) ) - #~~ navbar + # navbar templates["navbar"]["entries"] = dict( - settings=dict(template="navbar/settings.jinja2", _div="navbar_settings", styles=["display: none"], data_bind="visible: loginState.isAdmin", custom_bindings=False), - systemmenu=dict(template="navbar/systemmenu.jinja2", _div="navbar_systemmenu", styles=["display: none"], classes=["dropdown"], data_bind="visible: loginState.isAdmin", custom_bindings=False), - login=dict(template="navbar/login.jinja2", _div="navbar_login", classes=["dropdown"], custom_bindings=False) + 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 + # 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")), @@ -139,17 +204,19 @@ def index(): files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], header_addon="sidebar/files_header.jinja2")) ) - #~~ tabs + # 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")), - gcodeviewer=(gettext("GCode Viewer"), dict(template="tabs/gcodeviewer.jinja2", _div="gcode")), terminal=(gettext("Terminal"), dict(template="tabs/terminal.jinja2", _div="term")), - timelapse=(gettext("Timelapse"), dict(template="tabs/timelapse.jinja2", _div="timelapse")) ) + 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 + # settings dialog templates["settings"]["entries"] = dict( section_printer=(gettext("Printer"), None), @@ -158,12 +225,12 @@ def index(): 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)), - accesscontrol=(gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False)), api=(gettext("API"), dict(template="dialogs/settings/api.jinja2", _div="settings_api", custom_bindings=False)), section_octoprint=(gettext("OctoPrint"), None), @@ -172,8 +239,10 @@ def index(): 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 + # extract data from template plugins template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin) @@ -209,31 +278,27 @@ def index(): else: data = include[1] - key = "plugin_" + name + data["suffix"] if "suffix" in data else "" + 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 - templates["navbar"]["order"] = ["settings", "systemmenu", "login"] - templates["sidebar"]["order"] = ["connection", "state", "files"] - templates["tab"]["order"] = ["temperature", "control", "gcodeviewer", "terminal", "timelapse"] - templates["settings"]["order"] = [ - "section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", - "section_features", "features", "webcam", "accesscontrol", "api", - "section_octoprint", "folders", "appearance", "logs" - ] - # 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"): - templates[t]["order"] = [x for x in templates[t]["order"] if x in templates[t]["entries"]] - all_ordered = set(templates[t]["order"]) + 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] - missing_in_order = set(templates[t]["entries"].keys()).difference(all_ordered) + 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 @@ -252,23 +317,19 @@ def index(): 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, templates=templates, - pluginNames=plugin_names, - assetPlugins=asset_plugin_urls, + assets=assets, + pluginNames=plugin_names ) render_kwargs.update(plugin_vars) @@ -287,7 +348,8 @@ def _process_template_configs(name, implementation, configs, rules): navbar=1, sidebar=1, tab=1, - settings=1 + settings=1, + generic=1 ) includes = defaultdict(list) @@ -336,7 +398,9 @@ def _process_template_config(name, implementation, rule, config=None, counter=1) config = dict() data = dict(config) - if "div" in rule: + 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"] @@ -444,7 +508,7 @@ class Server(): 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) @@ -467,23 +531,37 @@ class Server(): printer = Printer(fileManager, analysisQueue, printerProfileManager) appSessionManager = util.flask.AppSessionManager() - def plugin_settings_factory(name, implementation): + 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() - plugin_settings = octoprint.plugin.plugin_settings(name, defaults=default_settings) + 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_injects=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 - ), additional_inject_factories=[plugin_settings_factory]) + pluginManager.initialize_implementations( + additional_inject_factories=[ + octoprint_plugin_inject_factory, + settings_plugin_inject_factory + ] + ) slicingManager.initialize() # configure additional template folders for jinja2 @@ -501,6 +579,7 @@ class Server(): ]) app.jinja_loader = jinja_loader del jinja2 + app.jinja_env.add_extension("jinja2.ext.do") # configure timelapse octoprint.timelapse.configureTimelapse() @@ -513,7 +592,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) @@ -591,7 +670,7 @@ class Server(): 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|g))", 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)) @@ -606,7 +685,7 @@ class Server(): if settings().getBoolean(["serial", "autoconnect"]): (port, baudrate) = settings().get(["serial", "port"]), settings().getInt(["serial", "baudrate"]) printer_profile = printerProfileManager.get_default() - connectionOptions = getConnectionOptions() + connectionOptions = get_connection_options() if port in connectionOptions["ports"]: printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default") @@ -661,9 +740,6 @@ class Server(): 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, @@ -715,7 +791,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): @@ -725,6 +801,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 a4a4ece4f..5c4a1fc9f 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -20,7 +20,7 @@ import octoprint.plugin from octoprint.server import admin_permission, NO_CONTENT from octoprint.settings import settings as s, valid_boolean_trues from octoprint.server.util import apiKeyRequestHandler, corsResponseHandler -from octoprint.server.util.flask import restricted_access +from octoprint.server.util.flask import restricted_access, get_remote_address, get_json_command_from_request #~~ init api blueprint, including sub modules @@ -73,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 @@ -204,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: diff --git a/src/octoprint/server/api/connection.py b/src/octoprint/server/api/connection.py index b562062d7..7f858c7d1 100644 --- a/src/octoprint/server/api/connection.py +++ b/src/octoprint/server/api/connection.py @@ -8,16 +8,16 @@ __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.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_profile = printer.getCurrentConnection() + state, port, baudrate, printer_profile = printer.get_current_connection() current = { "state": state, "port": port, @@ -36,12 +36,12 @@ def connectionCommand(): "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": - connection_options = getConnectionOptions() + connection_options = get_connection_options() port = None baudrate = None @@ -72,7 +72,7 @@ def connectionCommand(): return NO_CONTENT def _get_options(): - connection_options = getConnectionOptions() + connection_options = get_connection_options() profile_options = printerProfileManager.get_all() default_profile = printerProfileManager.get_default() diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index adcbb791d..0f6d292d3 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -11,7 +11,7 @@ import octoprint.util as util from octoprint.filemanager.destinations import FileDestinations from octoprint.settings import settings, valid_boolean_trues from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT -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 from octoprint.events import Events import octoprint.filemanager @@ -27,7 +27,7 @@ def readGcodeFiles(): 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"]) @@ -38,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) @@ -53,7 +53,7 @@ def _getFileDetails(origin, filename): def _getFileList(origin, filter=None): if origin == FileDestinations.SDCARD: - sdFileList = printer.getSdFiles() + sdFileList = printer.get_sd_files() files = [] if sdFileList is not None: @@ -117,7 +117,7 @@ def _getFileList(origin, filter=None): def _verifyFileExists(origin, filename): if origin == FileDestinations.SDCARD: - return filename in map(lambda x: x[0], printer.getSdFiles()) + return filename in map(lambda x: x[0], printer.get_sd_files()) else: return fileManager.file_exists(origin, filename) @@ -150,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(): @@ -170,11 +170,11 @@ def uploadGcodeFile(target): futureFilename = fileManager.sanitize_name(FileDestinations.LOCAL, upload.filename) except: futureFilename = None - if futureFilename is None or not (slicingManager.slicing_enabled or octoprint.filemanager.valid_file_type(futureFilename, type="gcode")): + 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): @@ -186,7 +186,7 @@ def uploadGcodeFile(target): """ if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "gcode"): - return filename, printer.addSdFile(filename, absFilename, selectAndOrPrint) + return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint) else: selectAndOrPrint(filename, absFilename, destination) return filename @@ -201,7 +201,7 @@ def uploadGcodeFile(target): exact file is already selected, such reloading it. """ if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination)): - printer.selectFile(absFilename, destination == FileDestinations.SDCARD, printAfterSelect) + printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect) added_file = fileManager.add_file(FileDestinations.LOCAL, upload.filename, upload, allow_overwrite=True) if added_file is None: @@ -210,7 +210,7 @@ def uploadGcodeFile(target): filename = added_file done = True else: - filename = fileProcessingFinished(added_file, fileManager.get_absolute_path(FileDestinations.LOCAL, added_file), target) + filename = fileProcessingFinished(added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target) done = True sdFilename = None @@ -276,7 +276,7 @@ def gcodeFileCommand(filename, target): "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 @@ -284,7 +284,7 @@ def gcodeFileCommand(filename, target): # selects/loads a file printAfterLoading = False if "print" in data.keys() and data["print"] in valid_boolean_trues: - if not printer.isOperational(): + if not printer.is_operational(): return make_response("Printer is not operational, cannot directly start printing", 409) printAfterLoading = True @@ -293,8 +293,8 @@ def gcodeFileCommand(filename, target): filenameToSelect = filename sd = True else: - filenameToSelect = fileManager.get_absolute_path(target, 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(): @@ -312,7 +312,7 @@ def gcodeFileCommand(filename, target): 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.isPrinting() or printer.isPaused()): + 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) @@ -326,7 +326,7 @@ def gcodeFileCommand(filename, target): # prohibit overwriting the file that is currently being printed currentOrigin, currentFilename = _getCurrentFile() - if currentFilename == gcode_name and currentOrigin == target and (printer.isPrinting() or printer.isPaused()): + 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"]: @@ -349,13 +349,13 @@ def gcodeFileCommand(filename, target): select_after_slicing = False if "select" in data.keys() and data["select"] in valid_boolean_trues: - if not printer.isOperational(): + 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.isOperational(): + if not printer.is_operational(): return make_response("Printer is not operational, cannot directly start printing", 409) select_after_slicing = print_after_slicing = True @@ -371,8 +371,8 @@ def gcodeFileCommand(filename, target): filenameToSelect = gcode_name sd = True else: - filenameToSelect = fileManager.get_absolute_path(target, gcode_name) - printer.selectFile(filenameToSelect, sd, print_after_slicing) + 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, @@ -414,7 +414,7 @@ def deleteGcodeFile(filename, target): # prohibit deleting files that are currently in use currentOrigin, currentFilename = _getCurrentFile() - if currentFilename == filename and currentOrigin == target and (printer.isPrinting() or printer.isPaused()): + 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(): @@ -422,18 +422,18 @@ def deleteGcodeFile(filename, target): # deselect the file if it's currently selected if currentFilename is not None and filename == currentFilename: - printer.unselectFile() + printer.unselect_file() # delete it if target == FileDestinations.SDCARD: - printer.deleteSdFile(filename) + printer.delete_sd_file(filename) else: fileManager.remove_file(target, filename) return NO_CONTENT def _getCurrentFile(): - currentJob = printer.getCurrentJob() + 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: 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 f78beba5f..e260c7621 100644 --- a/src/octoprint/server/api/printer.py +++ b/src/octoprint/server/api/printer.py @@ -12,15 +12,17 @@ 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 @@ -38,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) @@ -54,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 @@ -77,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": @@ -94,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": @@ -112,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) @@ -125,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): @@ -149,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 @@ -169,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": @@ -182,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): @@ -213,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": @@ -253,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 @@ -265,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 = { @@ -273,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 @@ -292,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 @@ -301,7 +323,7 @@ def printerSdState(): @api.route("/printer/command", methods=["POST"]) @restricted_access def printerCommand(): - 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"]: @@ -312,30 +334,47 @@ def printerCommand(): except JSONBadRequest: return make_response("Malformed JSON body in request", 400) - parameters = dict() - if "parameters" in data.keys(): parameters = data["parameters"] - if "command" in data and "commands" in data: return make_response("'command' and 'commands' are mutually exclusive", 400) - elif "command" in data: - commands = [data["command"]] - elif "commands" in data and isinstance(data["commands"], (list, tuple)): - commands = data["commands"] - else: - return make_response("Need either single 'command' or list of 'commands'", 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) - commandsToSend = [] - for command in commands: - commandToSend = command - if len(parameters) > 0: - commandToSend = command % parameters - commandsToSend.append(commandToSend) + parameters = dict() + if "parameters" in data: + parameters = data["parameters"] - printer.commands(commandsToSend) + 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) + + 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 @@ -344,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/settings.py b/src/octoprint/server/api/settings.py index 9cd2d8cbd..6da2cc9a6 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -12,14 +12,14 @@ 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 @@ -28,7 +28,7 @@ import octoprint.plugin def getSettings(): s = settings() - connectionOptions = getConnectionOptions() + connectionOptions = get_connection_options() data = { "api": { @@ -38,7 +38,8 @@ def getSettings(): }, "appearance": { "name": s.get(["appearance", "name"]), - "color": s.get(["appearance", "color"]) + "color": s.get(["appearance", "color"]), + "colorTransparent": s.getBoolean(["appearance", "colorTransparent"]) }, "printer": { "defaultExtrusionLength": s.getInt(["printerParameters", "defaultExtrusionLength"]) @@ -48,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"]) @@ -91,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: @@ -134,6 +148,7 @@ def setSettings(): 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 "defaultExtrusionLength" in data["printer"]: s.setInt(["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"]) @@ -143,6 +158,7 @@ def setSettings(): 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"]) @@ -196,19 +212,12 @@ def setSettings(): 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) - - 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 "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")) if "plugins" in data: for name, plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin).items(): diff --git a/src/octoprint/server/api/slicing.py b/src/octoprint/server/api/slicing.py index 28ab35e96..978103a6d 100644 --- a/src/octoprint/server/api/slicing.py +++ b/src/octoprint/server/api/slicing.py @@ -12,19 +12,28 @@ 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 +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 slicingManager.registered_slicers: + for slicer in slicers: + slicer_impl = slicingManager.get_slicer(slicer, require_configured=False) result[slicer] = dict( key=slicer, - displayName=slicingManager.get_slicer(slicer).get_slicer_properties()["name"], + displayName=slicer_impl.get_slicer_properties()["name"], default=default_slicer == slicer, + configured = slicer_impl.is_slicer_configured(), profiles=_getSlicingProfilesData(slicer) ) @@ -35,7 +44,13 @@ def slicingListSlicerProfiles(slicer): if not slicer in slicingManager.registered_slicers: return make_response("Unknown slicer {slicer}".format(**locals()), 404) - return jsonify(_getSlicingProfilesData(slicer)) + 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): @@ -57,7 +72,7 @@ def slicingAddSlicerProfile(slicer, name): return make_response("Unknown slicer {slicer}".format(**locals()), 404) if not "application/json" in request.headers["Content-Type"]: - return None, None, make_response("Expected content-type JSON", 400) + return make_response("Expected content-type JSON", 400) try: json_data = request.json @@ -88,7 +103,7 @@ def slicingPatchSlicerProfile(slicer, name): return make_response("Unknown slicer {slicer}".format(**locals()), 404) if not "application/json" in request.headers["Content-Type"]: - return None, None, make_response("Expected content-type JSON", 400) + return make_response("Expected content-type JSON", 400) profile = slicingManager.load_profile(slicer, name) if not profile: @@ -130,9 +145,10 @@ def slicingDelSlicerProfile(slicer, name): slicingManager.delete_profile(slicer, name) return NO_CONTENT -def _getSlicingProfilesData(slicer): - profiles = slicingManager.all_profiles(slicer) - if not profiles: +def _getSlicingProfilesData(slicer, require_configured=False): + try: + profiles = slicingManager.all_profiles(slicer, require_configured=require_configured) + except SlicerNotConfigured: return dict() result = dict() diff --git a/src/octoprint/server/api/timelapse.py b/src/octoprint/server/api/timelapse.py index f3c7a2c18..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,7 +57,7 @@ def downloadTimelapse(filename): @api.route("/timelapse/", methods=["DELETE"]) @restricted_access def deleteTimelapse(filename): - if util.isAllowedFile(filename, {"mpg"}): + if util.is_allowed_file(filename, {"mpg"}): timelapse_folder = settings().getBaseFolder("timelapse") full_path = os.path.realpath(os.path.join(timelapse_folder, filename)) if full_path.startswith(timelapse_folder) and os.path.exists(full_path): @@ -70,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/util/flask.py b/src/octoprint/server/util/flask.py index 3f6408ec5..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' @@ -245,3 +246,25 @@ class AppSessionManager(object): 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 3d321b39d..deffe1c1c 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -13,8 +13,10 @@ import octoprint.timelapse import octoprint.server from octoprint.events import Events +import octoprint.printer -class PrinterStateConnection(sockjs.tornado.SockJSConnection): + +class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback): def __init__(self, printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session): sockjs.tornado.SockJSConnection.__init__(self, session) @@ -49,7 +51,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): # 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._printer.register_callback(self) self._fileManager.register_slicingprogress_callback(self) octoprint.timelapse.registerCallback(self) self._pluginManager.register_client(self) @@ -62,7 +64,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): def on_close(self): self._logger.info("Client connection closed: %s" % self._remoteAddress) - self._printer.unregisterCallback(self) + self._printer.unregister_callback(self) self._fileManager.unregister_slicingprogress_callback(self) octoprint.timelapse.unregisterCallback(self) self._pluginManager.unregister_client(self) @@ -74,7 +76,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): 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 @@ -92,7 +94,7 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): 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.isPrinting() or self._printer.isPaused()): + 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({ @@ -103,15 +105,12 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): }) 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) @@ -123,15 +122,15 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection): def sendPluginMessage(self, plugin, data): self._emit("plugin", dict(plugin=plugin, data=data)) - def addLog(self, 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) diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index bc0701219..18e7281ae 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -373,7 +373,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 diff --git a/src/octoprint/server/util/watchdog.py b/src/octoprint/server/util/watchdog.py index 4b40ba303..2375fbc21 100644 --- a/src/octoprint/server/util/watchdog.py +++ b/src/octoprint/server/util/watchdog.py @@ -36,14 +36,14 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): self.filename = os.path.basename(self._path) def save(self, target): - octoprint.util.safeRename(self._path, target) + octoprint.util.safe_rename(self._path, target) 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(): @@ -59,7 +59,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): return # prohibit overwriting currently selected file while it's being printed - if futureFilename == currentFilename and currentOrigin == octoprint.filemanager.FileDestinations.LOCAL and self._printer.isPrinting() or self._printer.isPaused(): + if futureFilename == currentFilename and currentOrigin == octoprint.filemanager.FileDestinations.LOCAL and self._printer.is_printing() or self._printer.is_paused(): return added_file = self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL, diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 40c94a5dd..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": { @@ -61,6 +108,7 @@ default_settings = { "stream": None, "snapshot": None, "ffmpeg": None, + "ffmpegThreads": 1, "bitrate": "5000k", "watermark": True, "flipH": False, @@ -68,7 +116,8 @@ default_settings = { "timelapse": { "type": "off", "options": {}, - "postRoll": 0 + "postRoll": 0, + "fps": 25 } }, "gcodeViewer": { @@ -98,7 +147,8 @@ default_settings = { "watched": None, "plugins": None, "slicingProfiles": None, - "printerProfiles": None + "printerProfiles": None, + "scripts": None }, "temperature": { "profiles": [ @@ -116,7 +166,28 @@ default_settings = { }, "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": { @@ -151,6 +222,14 @@ default_settings = { { "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": { @@ -178,69 +257,305 @@ default_settings = { } } } +"""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) 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 _init_settings_dir(self, basedir): + self._script_env = self._init_script_templating() + + def _init_basedir(self, basedir): if basedir is not None: - self.settings_dir = basedir + self._basedir = basedir else: - self.settings_dir = _resolveSettingsDir(APPNAME) + self._basedir = _default_basedir(_APPNAME) - if not os.path.isdir(self.settings_dir): - os.makedirs(self.settings_dir) + if not os.path.isdir(self._basedir): + os.makedirs(self._basedir) - def _getDefaultFolder(self, type): + 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() + 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): + def _migrate_config(self): dirty = False - for migrate in (self._migrate_event_config, self._migrate_reverse_proxy_config, self._migrate_printer_parameters): + + migrators = ( + self._migrate_event_config, + self._migrate_reverse_proxy_config, + self._migrate_printer_parameters, + self._migrate_gcode_scripts + ) + + for migrate in migrators: dirty = migrate() or dirty if dirty: self.save(force=True) + 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 @@ -301,6 +616,10 @@ class Settings(object): 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"]: @@ -324,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)...") @@ -420,13 +743,18 @@ class Settings(object): 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, merged=False): + def get(self, path, asdict=False, defaults=None, preprocessors=None, merged=False): import octoprint.util as util if len(path) == 0: @@ -435,18 +763,24 @@ class Settings(object): 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] @@ -458,7 +792,7 @@ 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) @@ -467,6 +801,9 @@ class Settings(object): 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: @@ -480,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 @@ -491,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 @@ -502,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): @@ -514,79 +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: + 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) @@ -600,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: @@ -624,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: @@ -637,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"]: @@ -662,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/slicing/__init__.py b/src/octoprint/slicing/__init__.py index 871e4673f..8d4848e41 100644 --- a/src/octoprint/slicing/__init__.py +++ b/src/octoprint/slicing/__init__.py @@ -11,6 +11,8 @@ 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): @@ -44,10 +46,6 @@ class TemporaryProfile(object): pass -class SlicingCancelled(BaseException): - pass - - class SlicingManager(object): def __init__(self, profile_path, printer_profile_manager): self._profile_path = profile_path @@ -71,8 +69,7 @@ class SlicingManager(object): def _load_slicers(self): plugins = octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SlicerPlugin) for name, plugin in plugins.items(): - if plugin.is_slicer_configured(): - self._slicers[plugin.get_slicer_properties()["type"]] = plugin + self._slicers[plugin.get_slicer_properties()["type"]] = plugin @property def slicing_enabled(self): @@ -89,13 +86,15 @@ class SlicingManager(object): @property def default_slicer(self): slicer_name = settings().get(["slicing", "defaultSlicer"]) - if slicer_name in self.configured_slicers: + if slicer_name in self.registered_slicers: return slicer_name else: return None def get_slicer(self, slicer, require_configured=True): - return self._slicers[slicer] if slicer in self._slicers and (not require_configured or self._slicers[slicer].is_slicer_configured()) else None + 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: @@ -106,11 +105,13 @@ class SlicingManager(object): 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()) - callback_kwargs.update(dict(_error=error)) + exc = SlicerNotConfigured(slicer_name) + callback_kwargs.update(dict(_error=error, _exc=exc)) callback(*callback_args, **callback_kwargs) - return False, error + raise exc slicer = self.get_slicer(slicer_name) @@ -154,23 +155,24 @@ class SlicingManager(object): def cancel_slicing(self, slicer_name, source_path, dest_path): if not slicer_name in self.registered_slicers: - return + raise UnknownSlicer(slicer_name) + slicer = self.get_slicer(slicer_name) slicer.cancel_slicing(dest_path) - def load_profile(self, slicer, name): + def load_profile(self, slicer, name, require_configured=True): if not slicer in self.registered_slicers: - return None + 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) + 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: - return + raise UnknownSlicer(slicer) if not isinstance(profile, SlicingProfile): if isinstance(profile, dict): @@ -191,7 +193,7 @@ class SlicingManager(object): def temporary_profile(self, slicer, name=None, overrides=None): if not slicer in self.registered_slicers: - return None + raise UnknownSlicer(slicer) profile = self._get_default_profile(slicer) if name: @@ -207,16 +209,21 @@ class SlicingManager(object): def delete_profile(self, slicer, name): if not slicer in self.registered_slicers: - return None + 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): + def all_profiles(self, slicer, require_configured=False): if not slicer in self.registered_slicers: - return None + 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) @@ -228,12 +235,12 @@ class SlicingManager(object): path = os.path.join(slicer_profile_path, entry) profile_name = entry[:-len(".profile")] - profiles[profile_name] = self._load_profile_from_path(slicer, path) + 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: - return None + raise UnknownSlicer(slicer) path = os.path.join(self._profile_path, slicer) if not os.path.exists(path): @@ -242,10 +249,10 @@ class SlicingManager(object): def get_profile_path(self, slicer, name, must_exist=False): if not slicer in self.registered_slicers: - return None + raise UnknownSlicer(slicer) if not name: - return None + raise ValueError("name must be set") name = self._sanitize(name) @@ -269,11 +276,11 @@ class SlicingManager(object): sanitized_name = sanitized_name.replace(" ", "_") return sanitized_name - def _load_profile_from_path(self, slicer, path): - return self.get_slicer(slicer).get_slicer_profile(path) + 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): - self.get_slicer(slicer).save_slicer_profile(path, profile, allow_overwrite=allow_overwrite, overrides=overrides) + 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"]) 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 6d38b3719..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,.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,.1) rgba(0,0,0,.1) rgba(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,.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary: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,.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,.1) rgba(0,0,0,.1) rgba(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,.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,.1) rgba(0,0,0,.1) rgba(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,.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,.1) rgba(0,0,0,.1) rgba(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,.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,.1) rgba(0,0,0,.1) rgba(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,.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,.1) rgba(0,0,0,.1) rgba(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 #ccc;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 #f67070;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:#f2bfbf;border-top-color:#f2bfbf}#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 #c2530c;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 #c2b00c;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 #50da00;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 #0050da;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 #a774ff;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:#d3bff5;border-top-color:#d3bff5}#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 #5e5e5e;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:400}.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 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{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,.5);font-size:85%;color:#fff;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:700}#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 .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}.hidden{display:none}#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;-khtml-opacity:1;opacity:1}#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,.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,.1) rgba(0,0,0,.1) rgba(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,.05);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(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,.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,.1) rgba(0,0,0,.1) rgba(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 69a5491d5..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 { @@ -165,25 +170,12 @@ function DataUpdater(allViewModels) { var payload = data["payload"]; var html = ""; - console.log("Got event " + type + " with payload: " + JSON.stringify(payload)); + 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 failed with return code %(returncode)s"), payload) + "

"; html += pnotifyAdditionalInfo('
' + payload.error + '
'); @@ -201,21 +193,10 @@ function DataUpdater(allViewModels) { 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), type: "success"}); - - _.each(self.allViewModels, function (viewModel) { - if (viewModel.hasOwnProperty("onSlicingDone")) { - viewModel.onSlicingDone(payload); - } - }); } else if (type == "SlicingCancelled") { gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); gcodeUploadProgressBar.css("width", "0%"); gcodeUploadProgressBar.text(""); - _.each(self.allViewModels, function (viewModel) { - if (viewModel.hasOwnProperty("onSlicingCancelled")) { - viewModel.onSlicingCancelled(payload); - } - }); } else if (type == "SlicingFailed") { gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); gcodeUploadProgressBar.css("width", "0%"); @@ -223,11 +204,6 @@ function DataUpdater(allViewModels) { html = _.sprintf(gettext("Could not slice %(stl)s to %(gcode)s: %(reason)s"), payload); new PNotify({title: gettext("Slicing failed"), text: html, type: "error", hide: false}); - _.each(self.allViewModels, function (viewModel) { - if (viewModel.hasOwnProperty("onSlicingFailed")) { - viewModel.onSlicingFailed(payload); - } - }); } else if (type == "TransferStarted") { gcodeUploadProgress.addClass("progress-striped").addClass("active"); gcodeUploadProgressBar.css("width", "100%"); @@ -243,14 +219,26 @@ function DataUpdater(allViewModels) { }); 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": { diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index 4dc14dbe9..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,106 +48,62 @@ $(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 printerProfilesViewModel = new PrinterProfilesViewModel(); - var usersViewModel = new UsersViewModel(loginStateViewModel); - var timelapseViewModel = new TimelapseViewModel(loginStateViewModel); - var printerStateViewModel = new PrinterStateViewModel(loginStateViewModel, timelapseViewModel); - var settingsViewModel = new SettingsViewModel(loginStateViewModel, usersViewModel, printerProfilesViewModel); - var connectionViewModel = new ConnectionViewModel(loginStateViewModel, settingsViewModel, printerProfilesViewModel); - var appearanceViewModel = new AppearanceViewModel(settingsViewModel, printerStateViewModel); - var temperatureViewModel = new TemperatureViewModel(loginStateViewModel, settingsViewModel); - var controlViewModel = new ControlViewModel(loginStateViewModel, settingsViewModel); - var terminalViewModel = new TerminalViewModel(loginStateViewModel, settingsViewModel); - var slicingViewModel = new SlicingViewModel(loginStateViewModel, printerProfilesViewModel); - var gcodeFilesViewModel = new GcodeFilesViewModel(printerStateViewModel, loginStateViewModel, slicingViewModel); - var gcodeViewModel = new GcodeViewModel(loginStateViewModel, settingsViewModel); - var navigationViewModel = new NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsViewModel, usersViewModel); - var logViewModel = new LogViewModel(loginStateViewModel); // the view model map is our basic look up table for dependencies that may be injected into other view models - var viewModelMap = { - loginStateViewModel: loginStateViewModel, - printerProfilesViewModel: printerProfilesViewModel, - 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, - slicingViewModel: slicingViewModel - }; + var viewModelMap = {}; // 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]; - // 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] - }); + if (viewModelParameters != undefined) { + if (!_.isArray(viewModelParameters)) { + viewModelParameters = [viewModelParameters]; + } + + // 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); - console.log("postponing", viewModel[0].name, "due to missing parameters:", missingParameters.join(", ")); + 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; @@ -134,11 +113,15 @@ $(function() { // 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 = ADDITIONAL_VIEWMODELS.slice(); - var additionalViewModels = []; + 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) { - console.log("View model dependency resolution, pass #" + pass++); + log.debug("Dependency resolution, pass #" + pass); var startLength = unprocessedViewModels.length; var postponed = []; @@ -147,9 +130,9 @@ $(function() { var viewModel = unprocessedViewModels.shift(); var viewModelId = _getViewModelId(viewModel); - // make sure that we don't have to view models going by the same name + // make sure that we don't have two view models going by the same name if (_.has(viewModelMap, viewModelId)) { - console.error("Duplicate class name while instantiating viewModel ", viewModelId); + log.error("Duplicate name while instantiating " + viewModelId); continue; } @@ -162,8 +145,17 @@ $(function() { } // we could resolve the depdendencies and the view model is not defined yet => add it, it's now fully processed - var viewModelBindTarget = viewModel[2]; - additionalViewModels.push([viewModelInstance, viewModelBindTarget]); + 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; } @@ -174,236 +166,21 @@ $(function() { // 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) { - console.error("Could not instantiate the following view models due to unresolvable dependencies:"); + log.error("Could not instantiate the following view models due to unresolvable dependencies:"); _.each(unprocessedViewModels, function(entry) { - console.error(entry[0].name, "(missing:", _.filter(entry[1], function(id) { return !_.has(viewModelMap, id); }).join(", "), ")"); + log.error(entry[0].name + " (missing: " + _.filter(entry[1], function(id) { return !_.has(viewModelMap, id); }).join(", ") + " )"); }); break; } - } - console.log("View model dependency resolution done"); - var allViewModels = _.values(viewModelMap); + 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 (_.endsWith(filename.toLowerCase(), ".stl")) { - slicingViewModel.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\" 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) { @@ -475,7 +252,72 @@ $(function() { } }; - //~~ startup commands + //~~ some additional hooks and initializations + + // 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); + } + }; + + // Use bootstrap tabdrop for tabs and pills + $('.nav-pills, .nav-tabs').tabdrop(); + + // Allow components to react to tab change + var tabs = $('#tabs a[data-toggle="tab"]'); + tabs.on('show', function (e) { + var current = e.target.hash; + var previous = e.relatedTarget.hash; + + _.each(allViewModels, function(viewModel) { + if (viewModel.hasOwnProperty("onTabChange")) { + viewModel.onTabChange(current, previous); + } + }); + }); + + 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")) { @@ -483,57 +325,23 @@ $(function() { } }); - loginStateViewModel.subscribe(function(change, data) { - if ("login" == change) { - $("#gcode_upload").fileupload("enable"); - - if (data.admin) { - usersViewModel.requestData(); - } - } else { - $("#gcode_upload").fileupload("disable"); - } - }); - //~~ view model binding - settingsViewModel.requestData(function() { - ko.applyBindings(settingsViewModel, document.getElementById("settings_dialog")); + var bindViewModels = function() { + log.info("Going to bind " + allViewModelData.length + " view models..."); + _.each(allViewModelData, function(viewModelData) { + if (!Array.isArray(viewModelData) || viewModelData.length != 2) { + return; + } - ko.applyBindings(connectionViewModel, document.getElementById("connection_wrapper")); - ko.applyBindings(printerStateViewModel, document.getElementById("state_wrapper")); - ko.applyBindings(gcodeFilesViewModel, document.getElementById("files_wrapper")); - 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); - } - //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); - } - - ko.applyBindings(slicingViewModel, document.getElementById("slicing_configuration_dialog")); - - // apply bindings and signal startup - _.each(additionalViewModels, function(additionalViewModel) { - var viewModel = additionalViewModel[0]; - var targets = additionalViewModel[1]; + var viewModel = viewModelData[0]; + var targets = viewModelData[1]; if (targets === undefined) { return; } - if (!Array.isArray(targets)) { + if (!_.isArray(targets)) { targets = [targets]; } @@ -541,93 +349,60 @@ $(function() { viewModel.onBeforeBinding(); } - _.each(targets, function(target) { - try { - ko.applyBindings(viewModel, target); - } catch (exc) { - console.log("Could not apply bindings for additional view model " + viewModel + ": " + exc.message); + if (targets != undefined) { + if (!_.isArray(targets)) { + targets = [targets]; } - }); + + _.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); + } + }); + } if (viewModel.hasOwnProperty("onAfterBinding")) { viewModel.onAfterBinding(); } }); - }); - //~~ UI stuff - - var webcamDisableTimeout; - $('#tabs a[data-toggle="tab"]').on('show', function (e) { - var current = e.target; - var previous = e.relatedTarget; - - 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 += "?"; - } - newSrc += new Date().getTime(); - - webcamImage.attr("src", newSrc); + _.each(allViewModels, function(viewModel) { + if (viewModel.hasOwnProperty("onAllBound")) { + viewModel.onAllBound(allViewModels); } - } 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[data-target='#files']").click(function() { - var files = $("#files"); - if (files.hasClass("in")) { - files.removeClass("overflow_visible"); - } else { - setTimeout(function() { - files.addClass("overflow_visible"); - }, 100); - } - }); - - $.fn.modal.defaults.maxHeight = function(){ - // subtract the height of the modal header and footer - return $(window).height() - 165; + }); + 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 0bb256fbd..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, printerStateViewModel) { - 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 504809d65..7ccb765dc 100644 --- a/src/octoprint/static/js/app/viewmodels/connection.js +++ b/src/octoprint/static/js/app/viewmodels/connection.js @@ -1,150 +1,158 @@ -function ConnectionViewModel(loginStateViewModel, settingsViewModel, printerProfilesViewModel) { - var self = this; +$(function() { + function ConnectionViewModel(parameters) { + var self = this; - self.loginState = loginStateViewModel; - self.settings = settingsViewModel; - self.printerProfiles = printerProfilesViewModel; + self.loginState = parameters[0]; + self.settings = parameters[1]; + self.printerProfiles = parameters[2]; - self.printerProfiles.profiles.items.subscribe(function() { - var allProfiles = self.printerProfiles.profiles.items(); + self.printerProfiles.profiles.items.subscribe(function() { + var allProfiles = self.printerProfiles.profiles.items(); - var printerOptions = []; - _.each(allProfiles, function(profile) { - printerOptions.push({id: profile.id, name: profile.name}); - }); - 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", - 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; - 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(); - } + 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.onStartup = function() { - self.requestData(); - }; -} + 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(); + }; + } + + 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 c12767cbe..9943a0fb3 100644 --- a/src/octoprint/static/js/app/viewmodels/control.js +++ b/src/octoprint/static/js/app/viewmodels/control.js @@ -1,209 +1,335 @@ -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.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.settings.printerProfiles.currentProfileData.subscribe(function() { - self._updateExtruderCount(); - self.settings.printerProfiles.currentProfileData().extruder.count.subscribe(self._updateExtruderCount); - }); - self._updateExtruderCount = function() { - var tools = []; - - 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); + 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.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; - - $.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.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); + } + }); + } + }; - self.sendCustomCommand = function(command) { - if (!command) - return; + self.rerenderControls = function () { + var allControls = self.controlsFromServer.concat(self.additionalControls); + self.controls(self._processControls(allControls)) + }; + + 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.controlsFromServer = response.controls; + self.rerenderControls(); + }; + + 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(); + }); + } - var callback = function (){ $.ajax({ url: API_BASEURL + "printer/command", type: "POST", @@ -211,168 +337,182 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) { contentType: "application/json; charset=UTF-8", data: JSON.stringify(data) }) - } - 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.displayMode = function (customControl) { + if (customControl.hasOwnProperty("children")) { + return "customControls_containerTemplate"; + } else { + return "customControls_controlTemplate"; } - } + }; - if (command.confirm) { - var confirmationDialog = $("#confirmation_dialog"); - var confirmationDialogAck = $(".confirmation_dialog_acknowledge", confirmationDialog); + 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; + }; - $(".confirmation_dialog_message", confirmationDialog).text(command.confirm); - confirmationDialogAck.unbind("click"); - confirmationDialogAck.bind("click", function(e) { - e.preventDefault(); - $("#confirmation_dialog").modal("hide"); - callback(); + 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()); + } }); - confirmationDialog.modal("show"); - } else { - callback(); - } - - }; - - 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.onStartup = function() { - self.requestData(); - }; - - 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); + if (additionalControls.length > 0) { + self.additionalControls = additionalControls; + self.rerenderControls(); } - button.click(); - } - }; + }; -} + 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 e187ea709..cde25948c 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -1,341 +1,578 @@ -function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel, slicingViewModel) { - var self = this; +$(function() { + function GcodeFilesViewModel(parameters) { + var self = this; - self.printerState = printerStateViewModel; - self.loginState = loginStateViewModel; - self.slicing = slicingViewModel; + 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"); - }, - "machinecode": function(file) { - return file["type"] && file["type"] == "machinecode"; - }, - "model": function(file) { - return file["type"] && file["type"] == "model"; - } - }, - "name", - ["machinecode"], - [["sd", "local"], ["machinecode", "model"]], - 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(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}) - }); - }; - - self.removeFile = function(file) { - if (!file || !file.refs || !file.refs.hasOwnProperty("resource")) return; - - $.ajax({ - url: file.refs.resource, - type: "DELETE", - success: function() { - self.requestData(); - } - }); - }; - - self.sliceFile = function(file) { - if (!file) return; - - self.slicing.show(file.origin, file.name); - }; - - 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.isPrinting() || self.isPaused()); - }; - - 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.onSlicingDone = 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); + } + }); - self.onMetadataAnalysisFinished = function(payload) { - self.requestData(); - }; -} + $(".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 97d5c8021..e44096c79 100644 --- a/src/octoprint/static/js/app/viewmodels/gcode.js +++ b/src/octoprint/static/js/app/viewmodels/gcode.js @@ -1,474 +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; + 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; + } } - 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 + return text; }); - }; + self.ui_modelInfo = ko.observable(""); + self.ui_layerInfo = ko.observable(""); - // 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); + self.enableReload = ko.observable(false); - // subscribe to relevant printer settings... - self.settings.printerProfiles.currentProfileData.subscribe(function() { - if (!self.enabled) return; + self.waitForApproval = ko.observable(false); + self.selectedFile = { + name: ko.observable(undefined), + date: ko.observable(undefined), + size: ko.observable(undefined) + }; - var currentProfileData = self.settings.printerProfiles.currentProfileData(); - if (!currentProfileData) return; + 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); - var toolOffsets = self._retrieveToolOffsets(currentProfileData); - if (toolOffsets) { - GCODE.ui.updateOptions({ - reader: { - toolOffsets: toolOffsets - } - }); + self.reader_sortLayers = ko.observable(true); + self.reader_hideEmptyLayers = ko.observable(true); - } - - 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 + 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 }; - } else { - return undefined; - } - }; + if (additionalRendererOptions) { + _.extend(renderer, additionalRendererOptions); + } - self._retrieveToolOffsets = function(currentProfileData) { - if (currentProfileData == undefined) { - currentProfileData = self.settings.printerProfiles.currentProfileData(); - } + var reader = { + sortLayers: self.reader_sortLayers(), + purgeEmptyLayers: self.reader_hideEmptyLayers() + }; + if (additionalReaderOptions) { + _.extend(reader, additionalReaderOptions); + } - if (currentProfileData && currentProfileData.extruder && currentProfileData.extruder.offsets()) { - var offsets = []; - _.each(currentProfileData.extruder.offsets(), function(offset) { - offsets.push({x: offset[0], y: offset[1]}) + GCODE.ui.updateOptions({ + renderer: renderer, + reader: reader }); - return offsets; - } else { - return undefined; - } + }; - }; + // 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); - self._retrieveAxesConfiguration = function(currentProfileData) { - if (currentProfileData == undefined) { - currentProfileData = self.settings.printerProfiles.currentProfileData(); - } + // 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 + } + }); - 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 + var bedDimensions = self._retrieveBedDimensions(currentProfileData); + if (toolOffsets) { + GCODE.ui.updateOptions({ + renderer: { + bed: bedDimensions + } + }); } - } else { - return undefined; - } - }; - self.loadedFilename = undefined; - self.loadedFileDate = undefined; - self.status = 'idle'; - self.enabled = false; - - self.currentlyPrinting = false; - - self.errorCount = 0; - - self.layerSlider = undefined; - self.layerCommandSlider = undefined; - - self.currentLayer = undefined; - self.currentCommand = undefined; - - self.initialize = function() { - self._configureLayerSlider(); - self._configureLayerCommandSlider(); - - 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; + var axesConfiguration = self._retrieveAxesConfiguration(currentProfileData); + if (axesConfiguration) { + GCODE.ui.updateOptions({ + renderer: { + invertAxes: axesConfiguration + } + }); + } }); - }; - self.reset = function() { - self.enableReload(false); + 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.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"); - 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.fromCurrentData = function(data) { + self._processData(data); + }; - self.ui_modelInfo(output.join("
")); + self._processData = function(data) { + if (!data.job.file || !data.job.file.name && (self.loadedFilename || self.loadedFileDate)) { + self.waitForApproval(false); - self.layerSlider.slider("enable"); - self.layerSlider.slider("setMax", model.layersPrinted - 1); - self.layerSlider.slider("setValue", 0); - } - }; + self.loadedFilename = undefined; + self.loadedFileDate = undefined; + self.selectedFile.name(undefined); + self.selectedFile.date(undefined); + self.selectedFile.size(undefined); - 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 != 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"); + 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 { + 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("Print time for layer") + ": " + formatDuration(layer.printTime)); + }; - self.ui_layerInfo(output.join("
")); + self.approveLargeFile = function() { + self.waitForApproval(false); + self.loadFile(self.selectedFile.name(), self.selectedFile.date()); + }; - self.layerCommandSlider.slider("enable"); - self.layerCommandSlider.slider("setMax", layer.commands - 1); - self.layerCommandSlider.slider("setValue", [0, layer.commands - 1]); - } - }; + self._onProgress = function(type, percentage) { + self.ui_progress_type(type); + self.ui_progress_percentage(percentage); + }; - self._onInternalRendererOptionChange = function(options) { - if (!options) return; + 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 { + 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")); - 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.ui_modelInfo(output.join("
")); + + if (self.layerSlider != undefined) { + self.layerSlider.slider("enable"); + self.layerSlider.slider("setMax", model.layersPrinted - 1); + self.layerSlider.slider("setValue", 0); + } } + }; + + 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.ui_layerInfo(output.join("
")); + + 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 495b09f50..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 0330eceb8..6ea94569b 100644 --- a/src/octoprint/static/js/app/viewmodels/navigation.js +++ b/src/octoprint/static/js/app/viewmodels/navigation.js @@ -1,44 +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.settings = settingsViewModel; - 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 index dff75348e..5e1986cfd 100644 --- a/src/octoprint/static/js/app/viewmodels/printerprofiles.js +++ b/src/octoprint/static/js/app/viewmodels/printerprofiles.js @@ -1,315 +1,323 @@ -function PrinterProfilesViewModel() { - var self = this; +$(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.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.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._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.editorExtruderOffsets(extruderOffsets); - } - - return extruderOffsets.slice(0, numExtruders); - }); - - 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(); - $.ajax({ - url: API_BASEURL + "printerprofiles", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({profile: profile}), - success: function() { - if (callback !== undefined) { - callback(); + 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; } - self.requestData(); + }, + {}, + "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.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; } - }); - }; - self.removeProfile = function(data) { - $.ajax({ - url: data.resource, - type: "DELETE", - dataType: "json", - success: self.requestData - }) - }; - - self.updateProfile = function(profile, callback) { - if (profile == undefined) { - profile = self._editorData(); - } - - $.ajax({ - url: API_BASEURL + "printerprofiles/" + profile.id, - type: "PATCH", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({profile: profile}), - success: function() { - if (callback !== undefined) { - callback(); + if (numExtruders > extruderOffsets.length) { + for (var i = extruderOffsets.length; i < numExtruders; i++) { + extruderOffsets[i] = { + x: ko.observable(0), + y: ko.observable(0) + } } - self.requestData(); + self.editorExtruderOffsets(extruderOffsets); } + + return extruderOffsets.slice(0, numExtruders); }); - }; - self.showEditProfileDialog = function(data) { - var add = false; - if (data == undefined) { - data = self._cleanProfile(); - add = true; - } + self.makeDefault = function(data) { + var profile = { + id: data.id, + default: true + }; - self.editorNew(add); + self.updateProfile(profile); + }; - self.editorIdentifier(data.id); - self.editorName(data.name); - self.editorColor(data.color); - self.editorModel(data.model); + self.requestData = function() { + $.ajax({ + url: API_BASEURL + "printerprofiles", + type: "GET", + dataType: "json", + success: self.fromResponse + }) + }; - 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.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.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() { - self.confirmEditProfile(add); - }); - editDialog.modal("show"); - }; - - self.confirmEditProfile = function(add) { - var callback = function() { - $("#settings_printerProfiles_editDialog").modal("hide"); + self.profiles.updateItems(items); + self.defaultProfile(defaultProfile); + self.currentProfile(currentProfile); + self.currentProfileData(currentProfileData); }; - if (add) { - self.addProfile(callback); - } else { - self.updateProfile(undefined, callback); - } - }; - - self._editorData = function() { - var profile = { - id: self.editorIdentifier(), - 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() + self.addProfile = function(callback) { + var profile = self._editorData(); + $.ajax({ + url: API_BASEURL + "printerprofiles", + type: "POST", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify({profile: profile}), + success: function() { + if (callback !== undefined) { + callback(); + } + self.requestData(); } + }); + }; + + self.removeProfile = function(data) { + $.ajax({ + url: data.resource, + type: "DELETE", + dataType: "json", + success: self.requestData + }) + }; + + self.updateProfile = function(profile, callback) { + if (profile == undefined) { + profile = self._editorData(); + } + + $.ajax({ + url: API_BASEURL + "printerprofiles/" + profile.id, + type: "PATCH", + dataType: "json", + contentType: "application/json; charset=UTF-8", + data: JSON.stringify({profile: profile}), + success: function() { + if (callback !== undefined) { + callback(); + } + self.requestData(); + } + }); + }; + + 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() { + 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); } }; - 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"]())]; + self._editorData = function() { + var profile = { + id: self.editorIdentifier(), + 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); } - profile.extruder.offsets.push(offset); } - } - return profile; - }; + return profile; + }; - self.onSettingsShown = self.requestData; - self.onStartup = self.requestData; -} \ No newline at end of file + 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 4cc97f346..00a7b67ee 100644 --- a/src/octoprint/static/js/app/viewmodels/printerstate.js +++ b/src/octoprint/static/js/app/viewmodels/printerstate.js @@ -1,237 +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.busyFiles = ko.observableArray([]); + self.busyFiles = ko.observableArray([]); - self.filament = ko.observableArray([]); - self.estimatedPrintTime = ko.observable(undefined); - self.lastPrintTime = ko.observable(undefined); + self.filament = ko.observableArray([]); + self.estimatedPrintTime = ko.observable(undefined); + self.lastPrintTime = ko.observable(undefined); - self.currentHeight = ko.observable(undefined); + 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.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.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 "-"; - }); - self.byteString = ko.computed(function() { - if (!self.filesize()) + 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() == undefined) { - if (!self.printTime() || !(self.isPrinting() || self.isPaused())) { + }); + 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 gettext("Calculating..."); - } - } else { - return formatFuzzyEstimation(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._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); + return formatFuzzyEstimation(self.printTimeLeft()); } }); - self.busyFiles(busyFiles); - }; + 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.print = function() { - var restartCommand = function() { - self._jobCommand("restart"); + 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); }; - 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.pause = function() { - self._jobCommand("pause"); - }; + 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.cancel = function() { - self._jobCommand("cancel"); - }; + self._processStateData = function(data) { + var prevPaused = self.isPaused(); - 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.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(); + } + } + }); + } } -} + + 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 f17fc1804..30da456e6 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -1,261 +1,340 @@ -function SettingsViewModel(loginStateViewModel, usersViewModel, printerProfilesViewModel) { - var self = this; +$(function() { + function SettingsViewModel(parameters) { + var self = this; - self.loginState = loginStateViewModel; - self.users = usersViewModel; - self.printerProfiles = printerProfilesViewModel; + 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_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.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; + } + }; + + 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() + } + } + }); + + $.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"] ]); - - 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.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_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.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.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_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.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.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": { - "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(), - "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() - }); - - $.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"); - } - }); - }; -} +}); diff --git a/src/octoprint/static/js/app/viewmodels/slicing.js b/src/octoprint/static/js/app/viewmodels/slicing.js index 7c60c60e9..eba0581a4 100644 --- a/src/octoprint/static/js/app/viewmodels/slicing.js +++ b/src/octoprint/static/js/app/viewmodels/slicing.js @@ -1,172 +1,199 @@ -function SlicingViewModel(loginStateViewModel, printerProfilesViewModel) { - var self = this; +$(function() { + function SlicingViewModel(parameters) { + var self = this; - self.loginState = loginStateViewModel; - self.printerProfiles = printerProfilesViewModel; + self.loginState = parameters[0]; + self.printerProfiles = parameters[1]; - self.target = undefined; - self.file = undefined; - self.data = undefined; + self.target = undefined; + self.file = undefined; + self.data = undefined; - self.defaultSlicer = undefined; - self.defaultProfile = undefined; + self.defaultSlicer = undefined; + self.defaultProfile = undefined; - self.gcodeFilename = ko.observable(); + 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.title = ko.observable(); + self.slicer = ko.observable(); + self.slicers = ko.observableArray(); + self.profile = ko.observable(); + self.profiles = ko.observableArray(); + self.printerProfile = ko.observable(); - 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) { - 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.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) { - selectedSlicer = slicer.key; - } - - self.slicers.push({ - key: slicer.key, - name: name + self.configured_slicers = ko.computed(function() { + return _.filter(self.slicers(), function(slicer) { + return slicer.configured; }); }); - if (selectedSlicer != undefined) { - self.slicer(selectedSlicer); - } + 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.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; + self.show = function(target, file, force) { + if (!self.enableSlicingDialog() && !force) { + return; } - 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 + 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"); }; - 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) + self.slicer.subscribe(function(newValue) { + self.profilesForSlicer(newValue); }); - $("#slicing_configuration_dialog").modal("hide"); + self.enableSlicingDialog = ko.computed(function() { + return self.configured_slicers().length > 0; + }); - self.gcodeFilename(undefined); - self.slicer(self.defaultSlicer); - self.profile(self.defaultProfile); - }; + self.enableSliceButton = ko.computed(function() { + return self.gcodeFilename() != undefined + && self.gcodeFilename().trim() != "" + && self.slicer() != undefined + && self.profile() != undefined; + }); - self._sanitize = function(name) { - return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_"); - }; + self.requestData = function(callback) { + $.ajax({ + url: API_BASEURL + "slicing", + type: "GET", + dataType: "json", + success: function(data) { + self.fromResponse(data); + if (callback !== undefined) { + callback(); + } + } + }); + }; - self.onStartup = function() { - self.requestData(); - }; -} \ No newline at end of file + 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 aa4e63270..85af5bdb5 100644 --- a/src/octoprint/static/js/app/viewmodels/temperature.js +++ b/src/octoprint/static/js/app/viewmodels/temperature.js @@ -1,356 +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.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}; + // 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.printerProfiles.currentProfileData.subscribe(function() { - self._numExtrudersUpdated(); - self.settingsViewModel.printerProfiles.currentProfileData().extruder.count.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/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("