Merge branch 'devel' into dev/tornadoTimeFunc

This commit is contained in:
Gina Häußge committed 2015-03-12 19:20:17 +01:00
commit 1f559049c6
137 files changed
+12479 -6008

No files matched your search

+3 -3
View File
@@ -2,8 +2,8 @@
language: python
python:
- "2.7"
- "2.7"
install:
- pip install -r requirements.txt
- pip install -e .[develop]
script:
- nosetests
- nosetests tests/
+47 -1
View File
@@ -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
+37 -10
View File
@@ -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
+2
View File
@@ -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
+38
View File
@@ -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%;
}
+3 -3
View File
@@ -1,8 +1,8 @@
.. _sec-api:
###
API
###
########
REST API
########
.. toctree::
:maxdepth: 2
+69 -6
View File
@@ -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
+2 -2
View File
@@ -65,7 +65,7 @@ Profile list
- :ref:`Profile <sec-api-slicing-datamodel-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
-------
+9 -5
View File
@@ -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'
+388
View File
@@ -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 <https://github.com/foosel/OctoPrint/wiki/Reverse-proxy-configuration-examples>`_ 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://<stream host>:<stream port>/?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://<stream host>:<stream port>/?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 "<Name> [OctoPrint]") and in the
# navigation bar (as "OctoPrint: <Name>")
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 <sec-features-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 <sec-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 <https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/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
+12
View File
@@ -0,0 +1,12 @@
.. _sec-configuration:
#############
Configuration
#############
.. toctree::
:maxdepth: 2
yaml.rst
config_yaml.rst
logging_yaml.rst
+100
View File
@@ -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:
<component>:
level: <loglevel>
with ``<component>`` being the internal OctoPrint component for which to change the loglevel, and ``<loglevel>`` 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.<plugin>``: the plugin ``<plugin>``, e.g. ``octoprint.plugins.discovery`` to change the log level of
the `Discovery plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery>`_ or ``octoprint.plugins.cura``
to change the log level of the `Cura plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura>`_.
* ``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 <https://docs.python.org/2/library/logging.handlers.html>`_.
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 <https://docs.python.org/2/library/logging.html#logrecord-attributes>`_.
+224
View File
@@ -0,0 +1,224 @@
.. _sec-configuration-yaml:
A YAML Primer
=============
Most of OctoPrint's configuration is done under the hood through `YAML <https://en.wikipedia.org/wiki/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 <sec-configuration-yaml-types-scalar-boolean>`.
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.
+10
View File
@@ -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.
+9 -6
View File
@@ -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
+277
View File
@@ -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 <http://jinja.pocoo.org/>`_.
Custom controls are configured within :ref:`config.yaml <sec-configuration-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 <sec-configuration-yaml>`.
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 <sec-features-gcode_scripts>` 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 <sec-features-gcode_scripts-context>` will be available.
:ref:`See below for an example <sec-features-custom_controls-examples-gcode_script>`.
* - ``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 <https://docs.python.org/2/library/re.html#regular-expression-syntax>`_ 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 <https://docs.python.org/2/library/string.html#format-string-syntax>`_ for either named
groups within the regex (e.g. ``Temperature: {temperature}`` for a regex ``T:\s*(?P<temperature>\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.
+18
View File
@@ -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
---------------
+11
View File
@@ -0,0 +1,11 @@
.. _section-features:
********
Features
********
.. toctree::
:maxdepth: 2
custom_controls.rst
gcode_scripts.rst
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

+3 -4
View File
@@ -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
+32
View File
@@ -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
+14
View File
@@ -0,0 +1,14 @@
.. _sec-modules:
################
Internal Modules
################
.. toctree::
:maxdepth: 3
filemanager.rst
plugin.rst
printer.rst
settings.rst
util.rst
+20
View File
@@ -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
+6
View File
@@ -0,0 +1,6 @@
.. _sec-modules-printer:
octoprint.printer
-----------------
.. automodule:: octoprint.printer
+6
View File
@@ -0,0 +1,6 @@
.. _sec-modules-settings:
octoprint.settings
------------------
.. automodule:: octoprint.settings
+9
View File
@@ -0,0 +1,9 @@
.. _sec-modules-util:
octoprint.util
--------------
.. automodule:: octoprint.util
:members:
+447 -2
View File
@@ -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:
<a href="https://en.wikipedia.org/wiki/Hello_world">Hello World!</a>
@@ -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:
<a href="{{ plugin_helloworld_url|escape }}">Hello World!</a>
@@ -372,6 +384,7 @@ So in your plugin's ``templates`` folder create a new file ``helloworld_settings
into it:
.. code-block:: html
:linenos:
<form class="form-horizontal">
<div class="control-group">
@@ -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:
<a href="#" data-bind="attr: {href: settings.settings.plugins.helloworld.url}">Hello World!</a>
@@ -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 :)
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:
<div class="input-append">
<input type="text" class="input-xxlarge" data-bind="value: newUrl">
<button class="btn btn-primary" data-bind="click: goToUrl">{{ _('Go') }}</button>
</div>
<iframe data-bind="attr: {src: currentUrl}" style="width: 100%; height: 600px; border: 1px solid #808080"></iframe>
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 <http://knockoutjs.com/documentation/introduction.html>`_ 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
<div class="input-append">
<input type="text" class="input-xxlarge" data-bind="value: newUrl">
<button class="btn btn-primary" data-bind="click: goToUrl">{{ _('Go') }}</button>
</div>
<iframe data-bind="attr: {src: currentUrl}" style="width: 100%; height: 600px; border: 1px solid #808080"></iframe>
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
<div class="input-append">
<input type="text" class="input-xxlarge" data-bind="value: newUrl">
<button class="btn btn-primary" data-bind="click: goToUrl">{{ _('Go') }}</button>
</div>
<iframe data-bind="attr: {src: currentUrl}"></iframe>
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 <http://lesscss.org/>`_, 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 <http://lesscss.org/#client-side-usage>`_),
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
<head>
<!-- [...] -->
<link href="/static/less/octoprint.less" rel="stylesheet/less" type="text/css" media="screen">
<!-- Plugin files -->
<!-- [...] -->
<link href="/plugin_assets/helloworld/less/helloworld.less" rel="stylesheet/less" type="text/css" media="screen">
<!-- [...] -->
<!-- /Plugin files -->
<script src="/static/js/lib/less.min.js" type="text/javascript"></script>
<!-- [...] -->
</head>
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
<head>
<!-- [...] -->
<link href="/static/css/octoprint.css" rel="stylesheet" type="text/css" media="screen">
<!-- Plugin files -->
<!-- [...] -->
<link href="/plugin_assets/helloworld/css/helloworld.css" rel="stylesheet" type="text/css" media="screen">
<!-- [...] -->
<!-- /Plugin files -->
<!-- [...] -->
</head>
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 <https://github.com/OctoPrint/Plugin-Examples/tree/master/helloworld>`_.
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 <sec-plugins-mixins>`.
For some insight on how to create plugins that react to various events within OctoPrint,
`the Growl Plugin <https://github.com/OctoPrint/OctoPrint-Growl>`_ might be a good example to learn from. For how to
add support for a slicer, OctoPrint's own bundled `CuraEngine plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura>`_
might give some hints. For extending OctoPrint's interface, the `NavbarTemp plugin <https://github.com/imrahil/OctoPrint-NavbarTemp>`_
might show what's possible with a few lines of code already. Finally, just take a look at the
`list of available plugins <https://github.com/foosel/OctoPrint/wiki#plugins>`_ on the OctoPrint wiki if you are
looking for examples.
.. rubric:: Footnotes
.. [#f1] Refer to the `LESS documentation <http://lesscss.org/#using-less>`_ on how to do that. If you are developing
your plugin under Windows you might also want to give `WinLESS <http://winless.org/>`_ a look which will run
in the background and keep your CSS files up to date with your various project's LESS files automatically.
+1 -2
View File
@@ -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
+95 -3
View File
@@ -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:
+8
View File
@@ -0,0 +1,8 @@
.. _sec-plugins-templates:
Templates
=========
.. todo::
Needs to be written.
-2
View File
@@ -1,2 +0,0 @@
sphinxcontrib-httpdomain
sphinx_rtd_theme
+258
View File
@@ -0,0 +1,258 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'The MIT License <http://opensource.org/licenses/MIT>'
__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")
-15
View File
@@ -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
-6
View File
@@ -1,6 +0,0 @@
mock>=1.0.1
nose>=1.3.0
sphinxcontrib-httpdomain
sphinx_rtd_theme
po2json
ddt
+10 -16
View File
@@ -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.
###
.
+69 -17
View File
@@ -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())
+2 -1
View File
@@ -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"])
+9 -8
View File
@@ -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:
+355 -230
View File
@@ -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": "<sha1 hash>",
"links": [ ... ],
...
},
...
}
"test.gcode": {
"type": "machinecode",
"hash": "<sha1 hash>",
"links": [...],
...
},
"test.stl": {
"type": "model",
"hash": "<sha1 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": "<sha1 hash>",
"links": [ ... ],
...
},
...
}
"test.gcode": {
"type": "machinecode",
"hash": "<sha1 hash>",
"links": [...],
...
},
"test.stl": {
"type": "model",
"hash": "<sha1 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 "<stdin>", line 1, in <module>
ValueError: name must not contain / or \
>>> storage.sanitize_name("also\\no\\backslashes.gco")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
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 "<stdin>", line 1, in <module>
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:
+327 -43
View File
@@ -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 <osd@foosel.net>"
@@ -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_<plugin identifier>.log`` and located within the configured ``logs`` folder. If a
postfix is supplied, the name will be ``plugin_<plugin identifier>_<postfix>.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_<plugin identifier>_<postfix>.log``, if not it will be
``plugin_<plugin identifier>.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)
+60 -1
View File
@@ -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 <osd@foosel.net>"
@@ -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 <sec-plugins-infrastructure-controlproperties>`.
"""
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
+364 -20
View File
@@ -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 <sec-plugins-mixins>`.
.. autoclass:: OctoPrintPlugin
"""
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
@@ -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 ``_<index>`` 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_<pluginname>`` 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 <sec-plugins-templates>` 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 ``_<index>`` 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_<pluginname>`` 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 <sec-plugins-templates>` 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 ``_<index>`` 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_<pluginname>`` 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 <sec-plugins-templates>` 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 ``_<index>`` 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_<pluginname>`` 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 <sec-plugins-templates>` 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 <http://flask.pocoo.org/docs/0.10/blueprints/>`_ 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/<plugin identifier>/``.
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/<plugin identifier>``. ``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/<plugin identifier>``. ``request`` will contain the
received `Flask request object <http://flask.pocoo.org/docs/0.9/api/#flask.Request>`_ 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/<plugin identifier>/``, 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.<plugin identifier>``, e.g.:
``plugin.<plugin identifier>.<method_name>``, 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 <sec-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 <sec-events-available_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 []
+8 -8
View File
@@ -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)
+5 -1
View File
@@ -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"
]);
});
@@ -66,7 +66,7 @@
<div class="input-prepend">
<span class="btn fileinput-button">
<span>{{ _('Browse...') }}</span>
<input id="settings-cura-import" type="file" name="file" data-url="{{ url_for("plugin.cura.importCuraProfile") }}">
<input id="settings-cura-import" type="file" name="file" data-url="{{ url_for("plugin.cura.import_cura_profile") }}">
</span>
<span class="add-on" data-bind="text: fileName"></span>
</div>
+2 -2
View File
@@ -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:
File diff suppressed because it is too large. Load diff
+74
View File
@@ -0,0 +1,74 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__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)
+95
View File
@@ -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",
+927
View File
@@ -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 <osd@foosel.net>"
__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
}
+137 -57
View File
@@ -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
+3 -3
View File
@@ -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:
+6 -6
View File
@@ -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()
+27 -27
View File
@@ -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/<string:origin>", 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:
+10 -10
View File
@@ -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"],
+2 -2
View File
@@ -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/<path:filename>", methods=["GET"])
+89 -50
View File
@@ -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():
+30 -21
View File
@@ -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():
+25 -9
View File
@@ -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/<string:slicer>/profiles/<string:name>", 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()
+33 -11
View File
@@ -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/<filename>", 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)
+23
View File
@@ -1,5 +1,6 @@
# coding=utf-8
from __future__ import absolute_import
from flask import make_response
__author__ = "Gina Häußge <osd@foosel.net>"
__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
+11 -12
View File
@@ -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)
+1 -1
View File
@@ -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
+3 -3
View File
@@ -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,
+434 -94
View File
@@ -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 <osd@foosel.net>"
__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: ``<basedir>/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
+34 -27
View File
@@ -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"])
+28
View File
@@ -0,0 +1,28 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__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)
+12
View File
@@ -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;
}
+1 -1
View File
@@ -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.activeLine truncated
.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:aLine truncated
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

+44 -56
View File
@@ -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 <strong>over the next couple of minutes</strong>, 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 <strong>over the next couple of minutes</strong>, 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 = "<p>" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s"), payload) + "</p>";
html += pnotifyAdditionalInfo('<pre style="overflow: auto">' + payload.error + '</pre>');
@@ -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": {
+202 -427
View File
@@ -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 = "<p>" + 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.") + "</p>";
error += pnotifyAdditionalInfo("<pre>" + data.jqXHR.responseText + "</pre>");
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);
}
);
@@ -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"
]);
});
@@ -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"
]);
});
+488 -348
View File
@@ -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"
]);
});
+551 -314
View File
@@ -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]) + "<br>";
} 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]) + "<br>";
}
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"]) + "<br>";
}
if (data["prints"] && data["prints"]["last"]) {
output += gettext("Last Printed") + ": " + formatTimeAgo(data["prints"]["last"]["date"]) + "<br>";
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]) + "<br>";
} 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]) + "<br>";
}
}
}
output += gettext("Estimated Print Time") + ": " + formatDuration(data["gcodeAnalysis"]["estimatedPrintTime"]) + "<br>";
}
if (data["prints"] && data["prints"]["last"]) {
output += gettext("Last Printed") + ": " + formatTimeAgo(data["prints"]["last"]["date"]) + "<br>";
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 = "<p>" + 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\".") + "</p>";
error += pnotifyAdditionalInfo("<pre>" + data.jqXHR.responseText + "</pre>");
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"
]);
});
@@ -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 <strong>and</strong> your OctoPrint installation is accessible from the internet, your printer <strong>will be accessible by everyone - that also includes the bad guys!</strong>"));
$("#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 <strong>and</strong> your OctoPrint installation is accessible from the internet, your printer <strong>will be accessible by everyone - that also includes the bad guys!</strong>"));
$("#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"
]);
});
+450 -414
View File
@@ -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 &times; " + model.depth.toFixed(2) + "mm &times; " + 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("<br>"));
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("<br>"));
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 &times; " + model.depth.toFixed(2) + "mm &times; " + 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("<br>"));
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("<br>"));
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"
]);
});
+68 -60
View File
@@ -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"
]);
});
@@ -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,
[],
[]
]);
});
@@ -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 = "<p>" + _.sprintf(gettext("The command \"%(command)s\" could not be executed."), {command: action.name}) + "</p>";
error += pnotifyAdditionalInfo("<pre>" + jqXHR.responseText + "</pre>");
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 = "<p>" + _.sprintf(gettext("The command \"%(command)s\" could not be executed."), {command: action.name}) + "</p>";
error += pnotifyAdditionalInfo("<pre>" + jqXHR.responseText + "</pre>");
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?
});
@@ -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;
}
self.onSettingsShown = self.requestData;
self.onStartup = self.requestData;
}
OCTOPRINT_VIEWMODELS.push([
PrinterProfilesViewModel,
[],
[]
]);
});
@@ -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"]
]);
});
+335 -256
View File
@@ -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");
}
});
};
}
});
+180 -153
View File
@@ -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();
};
}
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"
]);
});
@@ -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"
]);
});
+204 -134
View File
@@ -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"
]);
});
@@ -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"
]);
});
+238 -224
View File
@@ -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"],
[]
]);
});
@@ -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));
}
};
@@ -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<cnt; i++) {
registered[i].apply();
}
};
return {
register: function(fn) {
registered.push(fn);
if (inited === false) {
$(window).bind('resize', resize);
inited = true;
}
},
unregister: function(fn) {
for(var i=0, cnt=registered.length; i<cnt; i++) {
if (registered[i] == fn) {
delete registered[i];
break;
}
}
}
}
}());
var TabDrop = function(element, options) {
this.element = $(element);
this.dropdown = $('<li class="dropdown hide pull-right tabdrop"><a class="dropdown-toggle" data-toggle="dropdown" href="#">'+options.text+' <b class="caret"></b></a><ul class="dropdown-menu"></ul></li>')
.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: '<i class="icon-align-justify"></i>'
};
$.fn.tabdrop.Constructor = TabDrop;
}( window.jQuery );
-1
View File
@@ -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]Line truncated
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){varLine truncated
+88
View File
@@ -0,0 +1,88 @@
/**
* @license
* lodash 3.3.0 (Custom Build) lodash.com/license | Underscore.js 1.7.0 underscorejs.org/LICENSE
* Build: `lodash modern -o ./lodash.js`
*/
;(function(){function n(n,t){if(n!==t){var r=n===n,e=t===t;if(n>t||!r||typeof n=="undefined"&&e)return 1;if(n<t||!e||typeof t=="undefined"&&r)return-1}return 0}function t(n,t,r){if(t!==t)return h(n,r);r=(r||0)-1;for(var e=n.length;++r<e;)if(n[r]===t)return r;return-1}function r(n){return typeof n=="function"||false}function e(n,t){var r=n.length;for(n.sort(t);r--;)n[r]=n[r].c;return n}function u(n){return typeof n=="string"?n:null==n?"":n+""}function o(n){return n.charCodeAt(0)}function i(n,t){for(var r=-1,e=n.length;++r<e&&-1<t.indexOf(n.charAt(r)););return r
}function f(n,t){for(var r=n.length;r--&&-1<t.indexOf(n.charAt(r)););return r}function a(t,r){return n(t.a,r.a)||t.b-r.b}function c(t,r){for(var e=-1,u=t.a,o=r.a,i=u.length;++e<i;){var f=n(u[e],o[e]);if(f)return f}return t.b-r.b}function l(n){return Nt[n]}function s(n){return Ut[n]}function p(n){return"\\"+$t[n]}function h(n,t,r){var e=n.length;for(t=r?t||e:(t||0)-1;r?t--:++t<e;){var u=n[t];if(u!==u)return t}return-1}function _(n){return n&&typeof n=="object"||false}function g(n){return 160>=n&&9<=n&&13>=n||32==n||160==n||5760==n||6158==n||8192<=n&&(8202>=n||8232==n||8233==n||8239==n||8287==n||12288==n||65279==n)
}function v(n,t){for(var r=-1,e=n.length,u=-1,o=[];++r<e;)n[r]===t&&(n[r]=z,o[++u]=r);return o}function y(n){for(var t=-1,r=n.length;++t<r&&g(n.charCodeAt(t)););return t}function d(n){for(var t=n.length;t--&&g(n.charCodeAt(t)););return t}function m(n){return Ft[n]}function w(g){function Nt(n){if(_(n)&&!(Wo(n)||n instanceof Lt)){if(n instanceof Ft)return n;if(Fu.call(n,"__chain__")&&Fu.call(n,"__wrapped__"))return ge(n)}return new Ft(n)}function Ut(){}function Ft(n,t,r){this.__wrapped__=n,this.__actions__=r||[],this.__chain__=!!t
}function Lt(n){this.__wrapped__=n,this.__actions__=null,this.__dir__=1,this.__dropCount__=0,this.__filtered__=false,this.__iteratees__=null,this.__takeCount__=po,this.__views__=null}function $t(){this.__data__={}}function zt(n){var t=n?n.length:0;for(this.data={hash:ro(null),set:new Gu};t--;)this.push(n[t])}function Dt(n,t){var r=n.data;return(typeof t=="string"||He(t)?r.set.has(t):r.hash[t])?0:-1}function qt(n,t){var r=-1,e=n.length;for(t||(t=bu(e));++r<e;)t[r]=n[r];return t}function Pt(n,t){for(var r=-1,e=n.length;++r<e&&false!==t(n[r],r,n););return n
}function Kt(n,t){for(var r=-1,e=n.length;++r<e;)if(!t(n[r],r,n))return false;return true}function Vt(n,t){for(var r=-1,e=n.length,u=-1,o=[];++r<e;){var i=n[r];t(i,r,n)&&(o[++u]=i)}return o}function Yt(n,t){for(var r=-1,e=n.length,u=bu(e);++r<e;)u[r]=t(n[r],r,n);return u}function Zt(n){for(var t=-1,r=n.length,e=so;++t<r;){var u=n[t];u>e&&(e=u)}return e}function Gt(n,t,r,e){var u=-1,o=n.length;for(e&&o&&(r=n[++u]);++u<o;)r=t(r,n[u],u,n);return r}function Jt(n,t,r,e){var u=n.length;for(e&&u&&(r=n[--u]);u--;)r=t(r,n[u],u,n);
return r}function Xt(n,t){for(var r=-1,e=n.length;++r<e;)if(t(n[r],r,n))return true;return false}function Ht(n,t){return typeof n=="undefined"?t:n}function Qt(n,t,r,e){return typeof n!="undefined"&&Fu.call(e,r)?n:t}function nr(n,t,r){var e=$o(t);if(!r)return rr(t,n,e);for(var u=-1,o=e.length;++u<o;){var i=e[u],f=n[i],a=r(f,t[i],i,n,t);(a===a?a===f:f!==f)&&(typeof f!="undefined"||i in n)||(n[i]=a)}return n}function tr(n,t){for(var r=-1,e=n.length,u=fe(e),o=t.length,i=bu(o);++r<o;){var f=t[r];u?(f=parseFloat(f),i[r]=oe(f,e)?n[f]:b):i[r]=n[f]
}return i}function rr(n,t,r){r||(r=t,t={});for(var e=-1,u=r.length;++e<u;){var o=r[e];t[o]=n[o]}return t}function er(n,t,r){var e=typeof n;if("function"==e){if(e=typeof t!="undefined"){var e=Nt.support,u=!(e.funcNames?n.name:e.funcDecomp);if(!u){var o=Nu.call(n);e.funcNames||(u=!mt.test(o)),u||(u=Et.test(o)||Qe(n),xo(n,u))}e=u}n=e?Fr(n,t,r):n}else n=null==n?yu:"object"==e?Ar(n):typeof t=="undefined"?Er(n+""):jr(n+"",t);return n}function ur(n,t,r,e,u,o,i){var f;if(r&&(f=u?r(n,e,u):r(n)),typeof f!="undefined")return f;
if(!He(n))return n;if(e=Wo(n)){if(f=re(n),!t)return qt(n,f)}else{var a=$u.call(n),c=a==V;if(a!=Z&&a!=D&&(!c||u))return St[a]?ue(n,a,t):u?n:{};if(f=ee(c?{}:n),!t)return rr(n,f,$o(n))}for(o||(o=[]),i||(i=[]),u=o.length;u--;)if(o[u]==n)return i[u];return o.push(n),i.push(f),(e?Pt:vr)(n,function(e,u){f[u]=ur(e,t,r,u,n,o,i)}),f}function or(n,t,r,e){if(typeof n!="function")throw new Cu(B);return Ju(function(){n.apply(b,Or(r,e))},t)}function ir(n,r){var e=n?n.length:0,u=[];if(!e)return u;var o=-1,i=te(),f=i==t,a=f&&200<=r.length&&Ao(r),c=r.length;
a&&(i=Dt,f=false,r=a);n:for(;++o<e;)if(a=n[o],f&&a===a){for(var l=c;l--;)if(r[l]===a)continue n;u.push(a)}else 0>i(r,a)&&u.push(a);return u}function fr(n,t){var r=n?n.length:0;if(!fe(r))return vr(n,t);for(var e=-1,u=_e(n);++e<r&&false!==t(u[e],e,u););return n}function ar(n,t){var r=n?n.length:0;if(!fe(r))return yr(n,t);for(var e=_e(n);r--&&false!==t(e[r],r,e););return n}function cr(n,t){var r=true;return fr(n,function(n,e,u){return r=!!t(n,e,u)}),r}function lr(n,t){var r=[];return fr(n,function(n,e,u){t(n,e,u)&&r.push(n)
}),r}function sr(n,t,r,e){var u;return r(n,function(n,r,o){return t(n,r,o)?(u=e?r:n,false):void 0}),u}function pr(n,t,r,e){e=(e||0)-1;for(var u=n.length,o=-1,i=[];++e<u;){var f=n[e];if(_(f)&&fe(f.length)&&(Wo(f)||Ge(f))){t&&(f=pr(f,t,r));var a=-1,c=f.length;for(i.length+=c;++a<c;)i[++o]=f[a]}else r||(i[++o]=f)}return i}function hr(n,t,r){var e=-1,u=_e(n);r=r(n);for(var o=r.length;++e<o;){var i=r[e];if(false===t(u[i],i,u))break}return n}function _r(n,t,r){var e=_e(n);r=r(n);for(var u=r.length;u--;){var o=r[u];
if(false===t(e[o],o,e))break}return n}function gr(n,t){hr(n,t,iu)}function vr(n,t){return hr(n,t,$o)}function yr(n,t){return _r(n,t,$o)}function dr(n,t){for(var r=-1,e=t.length,u=-1,o=[];++r<e;){var i=t[r];Uo(n[i])&&(o[++u]=i)}return o}function mr(n,t,r){var e=-1,u=typeof t=="function",o=n?n.length:0,i=fe(o)?bu(o):[];return fr(n,function(n){var o=u?t:null!=n&&n[t];i[++e]=o?o.apply(n,r):b}),i}function wr(n,t,r,e,u,o){if(n===t)return 0!==n||1/n==1/t;var i=typeof n,f=typeof t;if("function"!=i&&"object"!=i&&"function"!=f&&"object"!=f||null==n||null==t)n=n!==n&&t!==t;
else n:{var i=wr,f=Wo(n),a=Wo(t),c=M,l=M;f||(c=$u.call(n),c==D?c=Z:c!=Z&&(f=eu(n))),a||(l=$u.call(t),l==D?l=Z:l!=Z&&eu(t));var s=c==Z,a=l==Z,l=c==l;if(!l||f||s)if(c=s&&Fu.call(n,"__wrapped__"),a=a&&Fu.call(t,"__wrapped__"),c||a)n=i(c?n.value():n,a?t.value():t,r,e,u,o);else if(l){for(u||(u=[]),o||(o=[]),c=u.length;c--;)if(u[c]==n){n=o[c]==t;break n}u.push(n),o.push(t),n=(f?Jr:Hr)(n,t,i,r,e,u,o),u.pop(),o.pop()}else n=false;else n=Xr(n,t,c)}return n}function br(n,t,r,e,u){var o=t.length;if(null==n)return!o;
for(var i=-1,f=!u;++i<o;)if(f&&e[i]?r[i]!==n[t[i]]:!Fu.call(n,t[i]))return false;for(i=-1;++i<o;){var a=t[i];if(f&&e[i])a=Fu.call(n,a);else{var c=n[a],l=r[i],a=u?u(c,l,a):b;typeof a=="undefined"&&(a=wr(l,c,u,true))}if(!a)return false}return true}function xr(n,t){var r=[];return fr(n,function(n,e,u){r.push(t(n,e,u))}),r}function Ar(n){var t=$o(n),r=t.length;if(1==r){var e=t[0],u=n[e];if(ae(u))return function(n){return null!=n&&n[e]===u&&Fu.call(n,e)}}for(var o=bu(r),i=bu(r);r--;)u=n[t[r]],o[r]=u,i[r]=ae(u);return function(n){return br(n,t,o,i)
}}function jr(n,t){return ae(t)?function(r){return null!=r&&r[n]===t}:function(r){return null!=r&&wr(t,r[n],null,true)}}function kr(n,t,r,e,u){if(!He(n))return n;var o=fe(t.length)&&(Wo(t)||eu(t));return(o?Pt:vr)(t,function(t,i,f){if(_(t)){e||(e=[]),u||(u=[]);n:{t=e;for(var a=u,c=t.length,l=f[i];c--;)if(t[c]==l){n[i]=a[c],i=void 0;break n}c=n[i],f=r?r(c,l,i,n,f):b;var s=typeof f=="undefined";s&&(f=l,fe(l.length)&&(Wo(l)||eu(l))?f=Wo(c)?c:c?qt(c):[]:Fo(l)||Ge(l)?f=Ge(c)?uu(c):Fo(c)?c:{}:s=false),t.push(l),a.push(f),s?n[i]=kr(f,l,r,t,a):(f===f?f!==c:c===c)&&(n[i]=f),i=void 0
}return i}a=n[i],f=r?r(a,t,i,n,f):b,(l=typeof f=="undefined")&&(f=t),!o&&typeof f=="undefined"||!l&&(f===f?f===a:a!==a)||(n[i]=f)}),n}function Er(n){return function(t){return null==t?b:t[n]}}function Rr(n,t){return n+Ku(lo()*(t-n+1))}function Ir(n,t,r,e,u){return u(n,function(n,u,o){r=e?(e=false,n):t(r,n,u,o)}),r}function Or(n,t,r){var e=-1,u=n.length;for(t=null==t?0:+t||0,0>t&&(t=-t>u?0:u+t),r=typeof r=="undefined"||r>u?u:+r||0,0>r&&(r+=u),u=t>r?0:r-t>>>0,t>>>=0,r=bu(u);++e<u;)r[e]=n[e+t];return r}function Cr(n,t){var r;
return fr(n,function(n,e,u){return r=t(n,e,u),!r}),!!r}function Tr(n,r){var e=-1,u=te(),o=n.length,i=u==t,f=i&&200<=o,a=f&&Ao(),c=[];a?(u=Dt,i=false):(f=false,a=r?[]:c);n:for(;++e<o;){var l=n[e],s=r?r(l,e,n):l;if(i&&l===l){for(var p=a.length;p--;)if(a[p]===s)continue n;r&&a.push(s),c.push(l)}else 0>u(a,s)&&((r||f)&&a.push(s),c.push(l))}return c}function Sr(n,t){for(var r=-1,e=t.length,u=bu(e);++r<e;)u[r]=n[t[r]];return u}function Wr(n,t){var r=n;r instanceof Lt&&(r=r.value());for(var e=-1,u=t.length;++e<u;){var r=[r],o=t[e];
Yu.apply(r,o.args),r=o.func.apply(o.thisArg,r)}return r}function Nr(n,t,r){var e=0,u=n?n.length:e;if(typeof t=="number"&&t===t&&u<=go){for(;e<u;){var o=e+u>>>1,i=n[o];(r?i<=t:i<t)?e=o+1:u=o}return u}return Ur(n,t,yu,r)}function Ur(n,t,r,e){t=r(t);for(var u=0,o=n?n.length:0,i=t!==t,f=typeof t=="undefined";u<o;){var a=Ku((u+o)/2),c=r(n[a]),l=c===c;(i?l||e:f?l&&(e||typeof c!="undefined"):e?c<=t:c<t)?u=a+1:o=a}return io(o,_o)}function Fr(n,t,r){if(typeof n!="function")return yu;if(typeof t=="undefined")return n;
switch(r){case 1:return function(r){return n.call(t,r)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,o){return n.call(t,r,e,u,o)};case 5:return function(r,e,u,o,i){return n.call(t,r,e,u,o,i)}}return function(){return n.apply(t,arguments)}}function Lr(n){return Mu.call(n,0)}function $r(n,t,r){for(var e=r.length,u=-1,o=oo(n.length-e,0),i=-1,f=t.length,a=bu(o+f);++i<f;)a[i]=t[i];for(;++u<e;)a[r[u]]=n[u];for(;o--;)a[i++]=n[u++];return a}function Br(n,t,r){for(var e=-1,u=r.length,o=-1,i=oo(n.length-u,0),f=-1,a=t.length,c=bu(i+a);++o<i;)c[o]=n[o];
for(i=o;++f<a;)c[i+f]=t[f];for(;++e<u;)c[i+r[e]]=n[o++];return c}function zr(n,t){return function(r,e,u){var o=t?t():{};if(e=ne(e,u,3),Wo(r)){u=-1;for(var i=r.length;++u<i;){var f=r[u];n(o,f,e(f,u,r),r)}}else fr(r,function(t,r,u){n(o,t,e(t,r,u),u)});return o}}function Dr(n){return function(){var t=arguments.length,r=arguments[0];if(2>t||null==r)return r;if(3<t&&ie(arguments[1],arguments[2],arguments[3])&&(t=2),3<t&&"function"==typeof arguments[t-2])var e=Fr(arguments[--t-1],arguments[t--],5);else 2<t&&"function"==typeof arguments[t-1]&&(e=arguments[--t]);
for(var u=0;++u<t;){var o=arguments[u];o&&n(r,o,e)}return r}}function Mr(n,t){function r(){return(this instanceof r?e:n).apply(t,arguments)}var e=Pr(n);return r}function qr(n){return function(t){var r=-1;t=hu(au(t));for(var e=t.length,u="";++r<e;)u=n(u,t[r],r);return u}}function Pr(n){return function(){var t=bo(n.prototype),r=n.apply(t,arguments);return He(r)?r:t}}function Kr(n,t){return function(r,e,u){u&&ie(r,e,u)&&(e=null);var i=ne(),f=null==e;if(i===er&&f||(f=false,e=i(e,u,3)),f){if(e=Wo(r),e||!ru(r))return n(e?r:he(r));
e=o}return Qr(r,e,t)}}function Vr(n,t,r,e,u,o,i,f,a,c){function l(){for(var w=arguments.length,x=w,k=bu(w);x--;)k[x]=arguments[x];if(e&&(k=$r(k,e,u)),o&&(k=Br(k,o,i)),_||y){var x=l.placeholder,E=v(k,x),w=w-E.length;if(w<c){var R=f?qt(f):null,w=oo(c-w,0),C=_?E:null,E=_?null:E,T=_?k:null,k=_?null:k;return t|=_?I:O,t&=~(_?O:I),g||(t&=~(A|j)),k=Vr(n,t,r,T,C,k,E,R,a,w),k.placeholder=x,k}}if(x=p?r:this,h&&(n=x[m]),f)for(R=k.length,w=io(f.length,R),C=qt(k);w--;)E=f[w],k[w]=oe(E,R)?C[E]:b;return s&&a<k.length&&(k.length=a),(this instanceof l?d||Pr(n):n).apply(x,k)
}var s=t&T,p=t&A,h=t&j,_=t&E,g=t&k,y=t&R,d=!h&&Pr(n),m=n;return l}function Yr(n,t,r){return n=n.length,t=+t,n<t&&eo(t)?(t-=n,r=null==r?" ":r+"",su(r,qu(t/r.length)).slice(0,t)):""}function Zr(n,t,r,e){function u(){for(var t=-1,f=arguments.length,a=-1,c=e.length,l=bu(f+c);++a<c;)l[a]=e[a];for(;f--;)l[a++]=arguments[++t];return(this instanceof u?i:n).apply(o?r:this,l)}var o=t&A,i=Pr(n);return u}function Gr(n,t,r,e,u,o,i,f){var a=t&j;if(!a&&typeof n!="function")throw new Cu(B);var c=e?e.length:0;if(c||(t&=~(I|O),e=u=null),c-=u?u.length:0,t&O){var l=e,s=u;
e=u=null}var p=!a&&jo(n);if(r=[n,t,r,e,u,l,s,o,i,f],p&&true!==p){e=r[1],t=p[1],f=e|t,o=T|C,u=A|j,i=o|u|k|R;var l=e&T&&!(t&T),s=e&C&&!(t&C),h=(s?r:p)[7],_=(l?r:p)[8];o=f>=o&&f<=i&&(e<C||(s||l)&&h.length<=_),(!(e>=C&&t>u||e>u&&t>=C)||o)&&(t&A&&(r[2]=p[2],f|=e&A?0:k),(e=p[3])&&(u=r[3],r[3]=u?$r(u,e,p[4]):qt(e),r[4]=u?v(r[3],z):qt(p[4])),(e=p[5])&&(u=r[5],r[5]=u?Br(u,e,p[6]):qt(e),r[6]=u?v(r[5],z):qt(p[6])),(e=p[7])&&(r[7]=qt(e)),t&T&&(r[8]=null==r[8]?p[8]:io(r[8],p[8])),null==r[9]&&(r[9]=p[9]),r[0]=p[0],r[1]=f),t=r[1],f=r[9]
}return r[9]=null==f?a?0:n.length:oo(f-c,0)||0,(p?xo:ko)(t==A?Mr(r[0],r[2]):t!=I&&t!=(A|I)||r[4].length?Vr.apply(b,r):Zr.apply(b,r),r)}function Jr(n,t,r,e,u,o,i){var f=-1,a=n.length,c=t.length,l=true;if(a!=c&&(!u||c<=a))return false;for(;l&&++f<a;){var s=n[f],p=t[f],l=b;if(e&&(l=u?e(p,s,f):e(s,p,f)),typeof l=="undefined")if(u)for(var h=c;h--&&(p=t[h],!(l=s&&s===p||r(s,p,e,u,o,i))););else l=s&&s===p||r(s,p,e,u,o,i)}return!!l}function Xr(n,t,r){switch(r){case q:case P:return+n==+t;case K:return n.name==t.name&&n.message==t.message;
case Y:return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case G:case J:return n==t+""}return false}function Hr(n,t,r,e,u,o,i){var f=$o(n),a=f.length,c=$o(t).length;if(a!=c&&!u)return false;for(var l,c=-1;++c<a;){var s=f[c],p=Fu.call(t,s);if(p){var h=n[s],_=t[s],p=b;e&&(p=u?e(_,h,s):e(h,_,s)),typeof p=="undefined"&&(p=h&&h===_||r(h,_,e,u,o,i))}if(!p)return false;l||(l="constructor"==s)}return l||(r=n.constructor,e=t.constructor,!(r!=e&&"constructor"in n&&"constructor"in t)||typeof r=="function"&&r instanceof r&&typeof e=="function"&&e instanceof e)?true:false
}function Qr(n,t,r){var e=r?po:so,u=e,o=u;return fr(n,function(n,i,f){i=t(n,i,f),((r?i<u:i>u)||i===e&&i===o)&&(u=i,o=n)}),o}function ne(n,t,r){var e=Nt.callback||gu,e=e===gu?er:e;return r?e(n,t,r):e}function te(n,r,e){var u=Nt.indexOf||we,u=u===we?t:u;return n?u(n,r,e):u}function re(n){var t=n.length,r=new n.constructor(t);return t&&"string"==typeof n[0]&&Fu.call(n,"index")&&(r.index=n.index,r.input=n.input),r}function ee(n){return n=n.constructor,typeof n=="function"&&n instanceof n||(n=Ru),new n
}function ue(n,t,r){var e=n.constructor;switch(t){case X:return Lr(n);case q:case P:return new e(+n);case H:case Q:case nt:case tt:case rt:case et:case ut:case ot:case it:return t=n.buffer,new e(r?Lr(t):t,n.byteOffset,n.length);case Y:case J:return new e(n);case G:var u=new e(n.source,dt.exec(n));u.lastIndex=n.lastIndex}return u}function oe(n,t){return n=+n,t=null==t?yo:t,-1<n&&0==n%1&&n<t}function ie(n,t,r){if(!He(r))return false;var e=typeof t;return"number"==e?(e=r.length,e=fe(e)&&oe(t,e)):e="string"==e&&t in r,t=r[t],e&&(n===n?n===t:t!==t)
}function fe(n){return typeof n=="number"&&-1<n&&0==n%1&&n<=yo}function ae(n){return n===n&&(0===n?0<1/n:!He(n))}function ce(n,t){n=_e(n);for(var r=-1,e=t.length,u={};++r<e;){var o=t[r];o in n&&(u[o]=n[o])}return u}function le(n,t){var r={};return gr(n,function(n,e,u){t(n,e,u)&&(r[e]=n)}),r}function se(n){var t;if(!_(n)||$u.call(n)!=Z||!(Fu.call(n,"constructor")||(t=n.constructor,typeof t!="function"||t instanceof t)))return false;var r;return gr(n,function(n,t){r=t}),typeof r=="undefined"||Fu.call(n,r)
}function pe(n){for(var t=iu(n),r=t.length,e=r&&n.length,u=Nt.support,u=e&&fe(e)&&(Wo(n)||u.nonEnumArgs&&Ge(n)),o=-1,i=[];++o<r;){var f=t[o];(u&&oe(f,e)||Fu.call(n,f))&&i.push(f)}return i}function he(n){return null==n?[]:fe(n.length)?He(n)?n:Ru(n):fu(n)}function _e(n){return He(n)?n:Ru(n)}function ge(n){return n instanceof Lt?n.clone():new Ft(n.__wrapped__,n.__chain__,qt(n.__actions__))}function ve(n,t,r){return n&&n.length?((r?ie(n,t,r):null==t)&&(t=1),Or(n,0>t?0:t)):[]}function ye(n,t,r){var e=n?n.length:0;
return e?((r?ie(n,t,r):null==t)&&(t=1),t=e-(+t||0),Or(n,0,0>t?0:t)):[]}function de(n,t,r){var e=-1,u=n?n.length:0;for(t=ne(t,r,3);++e<u;)if(t(n[e],e,n))return e;return-1}function me(n){return n?n[0]:b}function we(n,r,e){var u=n?n.length:0;if(!u)return-1;if(typeof e=="number")e=0>e?oo(u+e,0):e||0;else if(e)return e=Nr(n,r),n=n[e],(r===r?r===n:n!==n)?e:-1;return t(n,r,e)}function be(n){return ve(n,1)}function xe(n,r,e,u){if(!n||!n.length)return[];null!=r&&typeof r!="boolean"&&(u=e,e=ie(n,r,u)?null:r,r=false);
var o=ne();if((o!==er||null!=e)&&(e=o(e,u,3)),r&&te()==t){r=e;var i;e=-1,u=n.length;for(var o=-1,f=[];++e<u;){var a=n[e],c=r?r(a,e,n):a;e&&i===c||(i=c,f[++o]=a)}n=f}else n=Tr(n,e);return n}function Ae(n){for(var t=-1,r=(n&&n.length&&Zt(Yt(n,Uu)))>>>0,e=bu(r);++t<r;)e[t]=Yt(n,Er(t));return e}function je(n,t){var r=-1,e=n?n.length:0,u={};for(!e||t||Wo(n[0])||(t=[]);++r<e;){var o=n[r];t?u[o]=t[r]:o&&(u[o[0]]=o[1])}return u}function ke(n){return n=Nt(n),n.__chain__=true,n}function Ee(n,t,r){return t.call(r,n)
}function Re(n,t,r){var e=Wo(n)?Kt:cr;return(typeof t!="function"||typeof r!="undefined")&&(t=ne(t,r,3)),e(n,t)}function Ie(n,t,r){var e=Wo(n)?Vt:lr;return t=ne(t,r,3),e(n,t)}function Oe(n,t,r){return Wo(n)?(t=de(n,t,r),-1<t?n[t]:b):(t=ne(t,r,3),sr(n,t,fr))}function Ce(n,t,r){return typeof t=="function"&&typeof r=="undefined"&&Wo(n)?Pt(n,t):fr(n,Fr(t,r,3))}function Te(n,t,r){if(typeof t=="function"&&typeof r=="undefined"&&Wo(n))for(r=n.length;r--&&false!==t(n[r],r,n););else n=ar(n,Fr(t,r,3));return n
}function Se(n,t,r){var e=n?n.length:0;return fe(e)||(n=fu(n),e=n.length),e?(r=typeof r=="number"?0>r?oo(e+r,0):r||0:0,typeof n=="string"||!Wo(n)&&ru(n)?r<e&&-1<n.indexOf(t,r):-1<te(n,t,r)):false}function We(n,t,r){var e=Wo(n)?Yt:xr;return t=ne(t,r,3),e(n,t)}function Ne(n,t,r,e){return(Wo(n)?Gt:Ir)(n,ne(t,e,4),r,3>arguments.length,fr)}function Ue(n,t,r,e){return(Wo(n)?Jt:Ir)(n,ne(t,e,4),r,3>arguments.length,ar)}function Fe(n,t,r){return(r?ie(n,t,r):null==t)?(n=he(n),t=n.length,0<t?n[Rr(0,t-1)]:b):(n=Le(n),n.length=io(0>t?0:+t||0,n.length),n)
}function Le(n){n=he(n);for(var t=-1,r=n.length,e=bu(r);++t<r;){var u=Rr(0,t);t!=u&&(e[t]=e[u]),e[u]=n[t]}return e}function $e(n,t,r){var e=Wo(n)?Xt:Cr;return(typeof t!="function"||typeof r!="undefined")&&(t=ne(t,r,3)),e(n,t)}function Be(n,t){var r;if(typeof t!="function"){if(typeof n!="function")throw new Cu(B);var e=n;n=t,t=e}return function(){return 0<--n?r=t.apply(this,arguments):t=null,r}}function ze(n,t){var r=A;if(2<arguments.length)var e=Or(arguments,2),u=v(e,ze.placeholder),r=r|I;return Gr(n,r,t,e,u)
}function De(n,t){var r=A|j;if(2<arguments.length)var e=Or(arguments,2),u=v(e,De.placeholder),r=r|I;return Gr(t,r,n,e,u)}function Me(n,t,r){return r&&ie(n,t,r)&&(t=null),n=Gr(n,E,null,null,null,null,null,t),n.placeholder=Me.placeholder,n}function qe(n,t,r){return r&&ie(n,t,r)&&(t=null),n=Gr(n,R,null,null,null,null,null,t),n.placeholder=qe.placeholder,n}function Pe(n,t,r){function e(){var r=t-(So()-c);0>=r||r>t?(f&&Pu(f),r=p,f=s=p=b,r&&(h=So(),a=n.apply(l,i),s||f||(i=l=null))):s=Ju(e,r)}function u(){s&&Pu(s),f=s=p=b,(g||_!==t)&&(h=So(),a=n.apply(l,i),s||f||(i=l=null))
}function o(){if(i=arguments,c=So(),l=this,p=g&&(s||!v),false===_)var r=v&&!s;else{f||v||(h=c);var o=_-(c-h),y=0>=o||o>_;y?(f&&(f=Pu(f)),h=c,a=n.apply(l,i)):f||(f=Ju(u,o))}return y&&s?s=Pu(s):s||t===_||(s=Ju(e,t)),r&&(y=true,a=n.apply(l,i)),!y||s||f||(i=l=null),a}var i,f,a,c,l,s,p,h=0,_=false,g=true;if(typeof n!="function")throw new Cu(B);if(t=0>t?0:t,true===r)var v=true,g=false;else He(r)&&(v=r.leading,_="maxWait"in r&&oo(+r.maxWait||0,t),g="trailing"in r?r.trailing:g);return o.cancel=function(){s&&Pu(s),f&&Pu(f),f=s=p=b
},o}function Ke(){var n=arguments,t=n.length-1;if(0>t)return function(n){return n};if(!Kt(n,r))throw new Cu(B);return function(){for(var r=t,e=n[r].apply(this,arguments);r--;)e=n[r].call(this,e);return e}}function Ve(n,t){function r(){var e=r.cache,u=t?t.apply(this,arguments):arguments[0];if(e.has(u))return e.get(u);var o=n.apply(this,arguments);return e.set(u,o),o}if(typeof n!="function"||t&&typeof t!="function")throw new Cu(B);return r.cache=new Ve.Cache,r}function Ye(n){var t=Or(arguments,1),r=v(t,Ye.placeholder);
return Gr(n,I,null,t,r)}function Ze(n){var t=Or(arguments,1),r=v(t,Ze.placeholder);return Gr(n,O,null,t,r)}function Ge(n){return fe(_(n)?n.length:b)&&$u.call(n)==D||false}function Je(n){return n&&1===n.nodeType&&_(n)&&-1<$u.call(n).indexOf("Element")||false}function Xe(n){return _(n)&&typeof n.message=="string"&&$u.call(n)==K||false}function He(n){var t=typeof n;return"function"==t||n&&"object"==t||false}function Qe(n){return null==n?false:$u.call(n)==V?zu.test(Nu.call(n)):_(n)&&bt.test(n)||false}function nu(n){return typeof n=="number"||_(n)&&$u.call(n)==Y||false
}function tu(n){return _(n)&&$u.call(n)==G||false}function ru(n){return typeof n=="string"||_(n)&&$u.call(n)==J||false}function eu(n){return _(n)&&fe(n.length)&&Tt[$u.call(n)]||false}function uu(n){return rr(n,iu(n))}function ou(n){return dr(n,iu(n))}function iu(n){if(null==n)return[];He(n)||(n=Ru(n));for(var t=n.length,t=t&&fe(t)&&(Wo(n)||wo.nonEnumArgs&&Ge(n))&&t||0,r=n.constructor,e=-1,r=typeof r=="function"&&r.prototype===n,u=bu(t),o=0<t;++e<t;)u[e]=e+"";for(var i in n)o&&oe(i,t)||"constructor"==i&&(r||!Fu.call(n,i))||u.push(i);
return u}function fu(n){return Sr(n,$o(n))}function au(n){return(n=u(n))&&n.replace(xt,l)}function cu(n){return(n=u(n))&&kt.test(n)?n.replace(jt,"\\$&"):n}function lu(n,t,r){return r&&ie(n,t,r)&&(t=0),co(n,t)}function su(n,t){var r="";if(n=u(n),t=+t,1>t||!n||!eo(t))return r;do t%2&&(r+=n),t=Ku(t/2),n+=n;while(t);return r}function pu(n,t,r){var e=n;return(n=u(n))?(r?ie(e,t,r):null==t)?n.slice(y(n),d(n)+1):(t+="",n.slice(i(n,t),f(n,t)+1)):n}function hu(n,t,r){return r&&ie(n,t,r)&&(t=null),n=u(n),n.match(t||It)||[]
}function _u(){var n=arguments.length,t=arguments[0];try{for(var r=bu(n?n-1:0);0<--n;)r[n-1]=arguments[n];return t.apply(b,r)}catch(e){return Xe(e)?e:new Au(e)}}function gu(n,t,r){return r&&ie(n,t,r)&&(t=null),_(n)?du(n):er(n,t)}function vu(n){return function(){return n}}function yu(n){return n}function du(n){return Ar(ur(n,true))}function mu(n,t,r){if(null==r){var e=He(t),u=e&&$o(t);((u=u&&u.length&&dr(t,u))?u.length:e)||(u=false,r=t,t=n,n=this)}u||(u=dr(t,$o(t)));var o=true,e=-1,i=Uo(n),f=u.length;false===r?o=false:He(r)&&"chain"in r&&(o=r.chain);
for(;++e<f;){r=u[e];var a=t[r];n[r]=a,i&&(n.prototype[r]=function(t){return function(){var r=this.__chain__;if(o||r){var e=n(this.__wrapped__);return(e.__actions__=qt(this.__actions__)).push({func:t,args:arguments,thisArg:n}),e.__chain__=r,e}return r=[this.value()],Yu.apply(r,arguments),t.apply(n,r)}}(a))}return n}function wu(){}g=g?Mt.defaults(Bt.Object(),g,Mt.pick(Bt,Ct)):Bt;var bu=g.Array,xu=g.Date,Au=g.Error,ju=g.Function,ku=g.Math,Eu=g.Number,Ru=g.Object,Iu=g.RegExp,Ou=g.String,Cu=g.TypeError,Tu=bu.prototype,Su=Ru.prototype,Wu=(Wu=g.window)&&Wu.document,Nu=ju.prototype.toString,Uu=Er("length"),Fu=Su.hasOwnProperty,Lu=0,$u=Su.toString,Bu=g._,zu=Iu("^"+cu($u).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Du=Qe(Du=g.ArrayBuffer)&&Du,Mu=Qe(Mu=Du&&new Du(0).slice)&&Mu,qu=ku.ceil,Pu=g.clearTimeout,Ku=ku.floor,Vu=Qe(Vu=Ru.getPrototypeOf)&&Vu,Yu=Tu.push,Zu=Su.propertyIsEnumerable,Gu=Qe(Gu=g.Set)&&Gu,Ju=g.setTimeout,Xu=Tu.splice,Hu=Qe(Hu=g.Uint8Array)&&Hu,Qu=Qe(Qu=g.WeakMap)&&Qu,no=function(){try{var n=Qe(n=g.Float64Array)&&n,t=new n(new Du(10),0,1)&&n
}catch(r){}return t}(),to=Qe(to=bu.isArray)&&to,ro=Qe(ro=Ru.create)&&ro,eo=g.isFinite,uo=Qe(uo=Ru.keys)&&uo,oo=ku.max,io=ku.min,fo=Qe(fo=xu.now)&&fo,ao=Qe(ao=Eu.isFinite)&&ao,co=g.parseInt,lo=ku.random,so=Eu.NEGATIVE_INFINITY,po=Eu.POSITIVE_INFINITY,ho=ku.pow(2,32)-1,_o=ho-1,go=ho>>>1,vo=no?no.BYTES_PER_ELEMENT:0,yo=ku.pow(2,53)-1,mo=Qu&&new Qu,wo=Nt.support={};!function(n){wo.funcDecomp=!Qe(g.WinRTError)&&Et.test(w),wo.funcNames=typeof ju.name=="string";try{wo.dom=11===Wu.createDocumentFragment().nodeType
}catch(t){wo.dom=false}try{wo.nonEnumArgs=!Zu.call(arguments,1)}catch(r){wo.nonEnumArgs=true}}(0,0),Nt.templateSettings={escape:_t,evaluate:gt,interpolate:vt,variable:"",imports:{_:Nt}};var bo=function(){function n(){}return function(t){if(He(t)){n.prototype=t;var r=new n;n.prototype=null}return r||g.Object()}}(),xo=mo?function(n,t){return mo.set(n,t),n}:yu;Mu||(Lr=Du&&Hu?function(n){var t=n.byteLength,r=no?Ku(t/vo):0,e=r*vo,u=new Du(t);if(r){var o=new no(u,0,r);o.set(new no(n,0,r))}return t!=e&&(o=new Hu(u,e),o.set(new Hu(n,e))),u
}:vu(null));var Ao=ro&&Gu?function(n){return new zt(n)}:vu(null),jo=mo?function(n){return mo.get(n)}:wu,ko=function(){var n=0,t=0;return function(r,e){var u=So(),o=U-(u-t);if(t=u,0<o){if(++n>=N)return r}else n=0;return xo(r,e)}}(),Eo=zr(function(n,t,r){Fu.call(n,r)?++n[r]:n[r]=1}),Ro=zr(function(n,t,r){Fu.call(n,r)?n[r].push(t):n[r]=[t]}),Io=zr(function(n,t,r){n[r]=t}),Oo=Kr(Zt),Co=Kr(function(n){for(var t=-1,r=n.length,e=po;++t<r;){var u=n[t];u<e&&(e=u)}return e},true),To=zr(function(n,t,r){n[r?0:1].push(t)
},function(){return[[],[]]}),So=fo||function(){return(new xu).getTime()},Wo=to||function(n){return _(n)&&fe(n.length)&&$u.call(n)==M||false};wo.dom||(Je=function(n){return n&&1===n.nodeType&&_(n)&&!Fo(n)||false});var No=ao||function(n){return typeof n=="number"&&eo(n)},Uo=r(/x/)||Hu&&!r(Hu)?function(n){return $u.call(n)==V}:r,Fo=Vu?function(n){if(!n||$u.call(n)!=Z)return false;var t=n.valueOf,r=Qe(t)&&(r=Vu(t))&&Vu(r);return r?n==r||Vu(n)==r:se(n)}:se,Lo=Dr(nr),$o=uo?function(n){if(n)var t=n.constructor,r=n.length;
return typeof t=="function"&&t.prototype===n||typeof n!="function"&&r&&fe(r)?pe(n):He(n)?uo(n):[]}:pe,Bo=Dr(kr),zo=qr(function(n,t,r){return t=t.toLowerCase(),n+(r?t.charAt(0).toUpperCase()+t.slice(1):t)}),Do=qr(function(n,t,r){return n+(r?"-":"")+t.toLowerCase()});8!=co(Ot+"08")&&(lu=function(n,t,r){return(r?ie(n,t,r):null==t)?t=0:t&&(t=+t),n=pu(n),co(n,t||(wt.test(n)?16:10))});var Mo=qr(function(n,t,r){return n+(r?"_":"")+t.toLowerCase()}),qo=qr(function(n,t,r){return n+(r?" ":"")+(t.charAt(0).toUpperCase()+t.slice(1))
});return Nt.prototype=Ut.prototype,Ft.prototype=bo(Ut.prototype),Ft.prototype.constructor=Ft,Lt.prototype=bo(Ut.prototype),Lt.prototype.constructor=Lt,$t.prototype["delete"]=function(n){return this.has(n)&&delete this.__data__[n]},$t.prototype.get=function(n){return"__proto__"==n?b:this.__data__[n]},$t.prototype.has=function(n){return"__proto__"!=n&&Fu.call(this.__data__,n)},$t.prototype.set=function(n,t){return"__proto__"!=n&&(this.__data__[n]=t),this},zt.prototype.push=function(n){var t=this.data;
typeof n=="string"||He(n)?t.set.add(n):t.hash[n]=true},Ve.Cache=$t,Nt.after=function(n,t){if(typeof t!="function"){if(typeof n!="function")throw new Cu(B);var r=n;n=t,t=r}return n=eo(n=+n)?n:0,function(){return 1>--n?t.apply(this,arguments):void 0}},Nt.ary=function(n,t,r){return r&&ie(n,t,r)&&(t=null),t=n&&null==t?n.length:oo(+t||0,0),Gr(n,T,null,null,null,null,t)},Nt.assign=Lo,Nt.at=function(n){return fe(n?n.length:0)&&(n=he(n)),tr(n,pr(arguments,false,false,1))},Nt.before=Be,Nt.bind=ze,Nt.bindAll=function(n){for(var t=n,r=1<arguments.length?pr(arguments,false,false,1):ou(n),e=-1,u=r.length;++e<u;){var o=r[e];
t[o]=Gr(t[o],A,t)}return t},Nt.bindKey=De,Nt.callback=gu,Nt.chain=ke,Nt.chunk=function(n,t,r){t=(r?ie(n,t,r):null==t)?1:oo(+t||1,1),r=0;for(var e=n?n.length:0,u=-1,o=bu(qu(e/t));r<e;)o[++u]=Or(n,r,r+=t);return o},Nt.compact=function(n){for(var t=-1,r=n?n.length:0,e=-1,u=[];++t<r;){var o=n[t];o&&(u[++e]=o)}return u},Nt.constant=vu,Nt.countBy=Eo,Nt.create=function(n,t,r){var e=bo(n);return r&&ie(n,t,r)&&(t=null),t?rr(t,e,$o(t)):e},Nt.curry=Me,Nt.curryRight=qe,Nt.debounce=Pe,Nt.defaults=function(n){if(null==n)return n;
var t=qt(arguments);return t.push(Ht),Lo.apply(b,t)},Nt.defer=function(n){return or(n,1,arguments,1)},Nt.delay=function(n,t){return or(n,t,arguments,2)},Nt.difference=function(){for(var n=-1,t=arguments.length;++n<t;){var r=arguments[n];if(Wo(r)||Ge(r))break}return ir(r,pr(arguments,false,true,++n))},Nt.drop=ve,Nt.dropRight=ye,Nt.dropRightWhile=function(n,t,r){var e=n?n.length:0;if(!e)return[];for(t=ne(t,r,3);e--&&t(n[e],e,n););return Or(n,0,e+1)},Nt.dropWhile=function(n,t,r){var e=n?n.length:0;if(!e)return[];
var u=-1;for(t=ne(t,r,3);++u<e&&t(n[u],u,n););return Or(n,u)},Nt.fill=function(n,t,r,e){var u=n?n.length:0;if(!u)return[];for(r&&typeof r!="number"&&ie(n,t,r)&&(r=0,e=u),u=n.length,r=null==r?0:+r||0,0>r&&(r=-r>u?0:u+r),e=typeof e=="undefined"||e>u?u:+e||0,0>e&&(e+=u),u=r>e?0:e>>>0,r>>>=0;r<u;)n[r++]=t;return n},Nt.filter=Ie,Nt.flatten=function(n,t,r){var e=n?n.length:0;return r&&ie(n,t,r)&&(t=false),e?pr(n,t):[]},Nt.flattenDeep=function(n){return n&&n.length?pr(n,true):[]},Nt.flow=function(){var n=arguments,t=n.length;
if(!t)return function(n){return n};if(!Kt(n,r))throw new Cu(B);return function(){for(var r=0,e=n[r].apply(this,arguments);++r<t;)e=n[r].call(this,e);return e}},Nt.flowRight=Ke,Nt.forEach=Ce,Nt.forEachRight=Te,Nt.forIn=function(n,t,r){return(typeof t!="function"||typeof r!="undefined")&&(t=Fr(t,r,3)),hr(n,t,iu)},Nt.forInRight=function(n,t,r){return t=Fr(t,r,3),_r(n,t,iu)},Nt.forOwn=function(n,t,r){return(typeof t!="function"||typeof r!="undefined")&&(t=Fr(t,r,3)),vr(n,t)},Nt.forOwnRight=function(n,t,r){return t=Fr(t,r,3),_r(n,t,$o)
},Nt.functions=ou,Nt.groupBy=Ro,Nt.indexBy=Io,Nt.initial=function(n){return ye(n,1)},Nt.intersection=function(){for(var n=[],r=-1,e=arguments.length,u=[],o=te(),i=o==t;++r<e;){var f=arguments[r];(Wo(f)||Ge(f))&&(n.push(f),u.push(i&&120<=f.length&&Ao(r&&f)))}var e=n.length,i=n[0],a=-1,c=i?i.length:0,l=[],s=u[0];n:for(;++a<c;)if(f=i[a],0>(s?Dt(s,f):o(l,f))){for(r=e;--r;){var p=u[r];if(0>(p?Dt(p,f):o(n[r],f)))continue n}s&&s.push(f),l.push(f)}return l},Nt.invert=function(n,t,r){r&&ie(n,t,r)&&(t=null),r=-1;
for(var e=$o(n),u=e.length,o={};++r<u;){var i=e[r],f=n[i];t?Fu.call(o,f)?o[f].push(i):o[f]=[i]:o[f]=i}return o},Nt.invoke=function(n,t){return mr(n,t,Or(arguments,2))},Nt.keys=$o,Nt.keysIn=iu,Nt.map=We,Nt.mapValues=function(n,t,r){var e={};return t=ne(t,r,3),vr(n,function(n,r,u){e[r]=t(n,r,u)}),e},Nt.matches=du,Nt.matchesProperty=function(n,t){return jr(n+"",ur(t,true))},Nt.memoize=Ve,Nt.merge=Bo,Nt.mixin=mu,Nt.negate=function(n){if(typeof n!="function")throw new Cu(B);return function(){return!n.apply(this,arguments)
}},Nt.omit=function(n,t,r){if(null==n)return{};if(typeof t!="function"){var e=Yt(pr(arguments,false,false,1),Ou);return ce(n,ir(iu(n),e))}return t=Fr(t,r,3),le(n,function(n,r,e){return!t(n,r,e)})},Nt.once=function(n){return Be(n,2)},Nt.pairs=function(n){for(var t=-1,r=$o(n),e=r.length,u=bu(e);++t<e;){var o=r[t];u[t]=[o,n[o]]}return u},Nt.partial=Ye,Nt.partialRight=Ze,Nt.partition=To,Nt.pick=function(n,t,r){return null==n?{}:typeof t=="function"?le(n,Fr(t,r,3)):ce(n,pr(arguments,false,false,1))},Nt.pluck=function(n,t){return We(n,Er(t))
},Nt.property=function(n){return Er(n+"")},Nt.propertyOf=function(n){return function(t){return null==n?b:n[t]}},Nt.pull=function(){var n=arguments[0];if(!n||!n.length)return n;for(var t=0,r=te(),e=arguments.length;++t<e;)for(var u=0,o=arguments[t];-1<(u=r(n,o,u));)Xu.call(n,u,1);return n},Nt.pullAt=function(t){var r=t||[],e=pr(arguments,false,false,1),u=e.length,o=tr(r,e);for(e.sort(n);u--;){var i=parseFloat(e[u]);if(i!=f&&oe(i)){var f=i;Xu.call(r,i,1)}}return o},Nt.range=function(n,t,r){r&&ie(n,t,r)&&(t=r=null),n=+n||0,r=null==r?1:+r||0,null==t?(t=n,n=0):t=+t||0;
var e=-1;t=oo(qu((t-n)/(r||1)),0);for(var u=bu(t);++e<t;)u[e]=n,n+=r;return u},Nt.rearg=function(n){var t=pr(arguments,false,false,1);return Gr(n,C,null,null,null,t)},Nt.reject=function(n,t,r){var e=Wo(n)?Vt:lr;return t=ne(t,r,3),e(n,function(n,r,e){return!t(n,r,e)})},Nt.remove=function(n,t,r){var e=-1,u=n?n.length:0,o=[];for(t=ne(t,r,3);++e<u;)r=n[e],t(r,e,n)&&(o.push(r),Xu.call(n,e--,1),u--);return o},Nt.rest=be,Nt.shuffle=Le,Nt.slice=function(n,t,r){var e=n?n.length:0;return e?(r&&typeof r!="number"&&ie(n,t,r)&&(t=0,r=e),Or(n,t,r)):[]
},Nt.sortBy=function(n,t,r){var u=-1,o=n?n.length:0,i=fe(o)?bu(o):[];return r&&ie(n,t,r)&&(t=null),t=ne(t,r,3),fr(n,function(n,r,e){i[++u]={a:t(n,r,e),b:u,c:n}}),e(i,a)},Nt.sortByAll=function(n){var t=arguments;3<t.length&&ie(t[1],t[2],t[3])&&(t=[n,t[1]]);var r=-1,u=n?n.length:0,o=pr(t,false,false,1),i=fe(u)?bu(u):[];return fr(n,function(n){for(var t=o.length,e=bu(t);t--;)e[t]=null==n?b:n[o[t]];i[++r]={a:e,b:r,c:n}}),e(i,c)},Nt.spread=function(n){if(typeof n!="function")throw new Cu(B);return function(t){return n.apply(this,t)
}},Nt.take=function(n,t,r){return n&&n.length?((r?ie(n,t,r):null==t)&&(t=1),Or(n,0,0>t?0:t)):[]},Nt.takeRight=function(n,t,r){var e=n?n.length:0;return e?((r?ie(n,t,r):null==t)&&(t=1),t=e-(+t||0),Or(n,0>t?0:t)):[]},Nt.takeRightWhile=function(n,t,r){var e=n?n.length:0;if(!e)return[];for(t=ne(t,r,3);e--&&t(n[e],e,n););return Or(n,e+1)},Nt.takeWhile=function(n,t,r){var e=n?n.length:0;if(!e)return[];var u=-1;for(t=ne(t,r,3);++u<e&&t(n[u],u,n););return Or(n,0,u)},Nt.tap=function(n,t,r){return t.call(r,n),n
},Nt.throttle=function(n,t,r){var e=true,u=true;if(typeof n!="function")throw new Cu(B);return false===r?e=false:He(r)&&(e="leading"in r?!!r.leading:e,u="trailing"in r?!!r.trailing:u),Wt.leading=e,Wt.maxWait=+t,Wt.trailing=u,Pe(n,t,Wt)},Nt.thru=Ee,Nt.times=function(n,t,r){if(n=+n,1>n||!eo(n))return[];var e=-1,u=bu(io(n,ho));for(t=Fr(t,r,1);++e<n;)e<ho?u[e]=t(e):t(e);return u},Nt.toArray=function(n){var t=n?n.length:0;return fe(t)?t?qt(n):[]:fu(n)},Nt.toPlainObject=uu,Nt.transform=function(n,t,r,e){var u=Wo(n)||eu(n);
return t=ne(t,e,4),null==r&&(u||He(n)?(e=n.constructor,r=u?Wo(n)?new e:[]:bo(Uo(e)&&e.prototype)):r={}),(u?Pt:vr)(n,function(n,e,u){return t(r,n,e,u)}),r},Nt.union=function(){return Tr(pr(arguments,false,true))},Nt.uniq=xe,Nt.unzip=Ae,Nt.values=fu,Nt.valuesIn=function(n){return Sr(n,iu(n))},Nt.where=function(n,t){return Ie(n,Ar(t))},Nt.without=function(n){return ir(n,Or(arguments,1))},Nt.wrap=function(n,t){return t=null==t?yu:t,Gr(t,I,null,[n],[])},Nt.xor=function(){for(var n=-1,t=arguments.length;++n<t;){var r=arguments[n];
if(Wo(r)||Ge(r))var e=e?ir(e,r).concat(ir(r,e)):r}return e?Tr(e):[]},Nt.zip=function(){for(var n=arguments.length,t=bu(n);n--;)t[n]=arguments[n];return Ae(t)},Nt.zipObject=je,Nt.backflow=Ke,Nt.collect=We,Nt.compose=Ke,Nt.each=Ce,Nt.eachRight=Te,Nt.extend=Lo,Nt.iteratee=gu,Nt.methods=ou,Nt.object=je,Nt.select=Ie,Nt.tail=be,Nt.unique=xe,mu(Nt,Nt),Nt.attempt=_u,Nt.camelCase=zo,Nt.capitalize=function(n){return(n=u(n))&&n.charAt(0).toUpperCase()+n.slice(1)},Nt.clone=function(n,t,r,e){return t&&typeof t!="boolean"&&ie(n,t,r)?t=false:typeof t=="function"&&(e=r,r=t,t=false),r=typeof r=="function"&&Fr(r,e,1),ur(n,t,r)
},Nt.cloneDeep=function(n,t,r){return t=typeof t=="function"&&Fr(t,r,1),ur(n,true,t)},Nt.deburr=au,Nt.endsWith=function(n,t,r){n=u(n),t+="";var e=n.length;return r=(typeof r=="undefined"?e:io(0>r?0:+r||0,e))-t.length,0<=r&&n.indexOf(t,r)==r},Nt.escape=function(n){return(n=u(n))&&ht.test(n)?n.replace(st,s):n},Nt.escapeRegExp=cu,Nt.every=Re,Nt.find=Oe,Nt.findIndex=de,Nt.findKey=function(n,t,r){return t=ne(t,r,3),sr(n,t,vr,true)},Nt.findLast=function(n,t,r){return t=ne(t,r,3),sr(n,t,ar)},Nt.findLastIndex=function(n,t,r){var e=n?n.length:0;
for(t=ne(t,r,3);e--;)if(t(n[e],e,n))return e;return-1},Nt.findLastKey=function(n,t,r){return t=ne(t,r,3),sr(n,t,yr,true)},Nt.findWhere=function(n,t){return Oe(n,Ar(t))},Nt.first=me,Nt.has=function(n,t){return n?Fu.call(n,t):false},Nt.identity=yu,Nt.includes=Se,Nt.indexOf=we,Nt.inRange=function(n,t,r){return t=+t||0,"undefined"===typeof r?(r=t,t=0):r=+r||0,n>=t&&n<r},Nt.isArguments=Ge,Nt.isArray=Wo,Nt.isBoolean=function(n){return true===n||false===n||_(n)&&$u.call(n)==q||false},Nt.isDate=function(n){return _(n)&&$u.call(n)==P||false
},Nt.isElement=Je,Nt.isEmpty=function(n){if(null==n)return true;var t=n.length;return fe(t)&&(Wo(n)||ru(n)||Ge(n)||_(n)&&Uo(n.splice))?!t:!$o(n).length},Nt.isEqual=function(n,t,r,e){return r=typeof r=="function"&&Fr(r,e,3),!r&&ae(n)&&ae(t)?n===t:(e=r?r(n,t):b,typeof e=="undefined"?wr(n,t,r):!!e)},Nt.isError=Xe,Nt.isFinite=No,Nt.isFunction=Uo,Nt.isMatch=function(n,t,r,e){var u=$o(t),o=u.length;if(r=typeof r=="function"&&Fr(r,e,3),!r&&1==o){var i=u[0];if(e=t[i],ae(e))return null!=n&&e===n[i]&&Fu.call(n,i)
}for(var i=bu(o),f=bu(o);o--;)e=i[o]=t[u[o]],f[o]=ae(e);return br(n,u,i,f,r)},Nt.isNaN=function(n){return nu(n)&&n!=+n},Nt.isNative=Qe,Nt.isNull=function(n){return null===n},Nt.isNumber=nu,Nt.isObject=He,Nt.isPlainObject=Fo,Nt.isRegExp=tu,Nt.isString=ru,Nt.isTypedArray=eu,Nt.isUndefined=function(n){return typeof n=="undefined"},Nt.kebabCase=Do,Nt.last=function(n){var t=n?n.length:0;return t?n[t-1]:b},Nt.lastIndexOf=function(n,t,r){var e=n?n.length:0;if(!e)return-1;var u=e;if(typeof r=="number")u=(0>r?oo(e+r,0):io(r||0,e-1))+1;
else if(r)return u=Nr(n,t,true)-1,n=n[u],(t===t?t===n:n!==n)?u:-1;if(t!==t)return h(n,u,true);for(;u--;)if(n[u]===t)return u;return-1},Nt.max=Oo,Nt.min=Co,Nt.noConflict=function(){return g._=Bu,this},Nt.noop=wu,Nt.now=So,Nt.pad=function(n,t,r){n=u(n),t=+t;var e=n.length;return e<t&&eo(t)?(e=(t-e)/2,t=Ku(e),e=qu(e),r=Yr("",e,r),r.slice(0,t)+n+r):n},Nt.padLeft=function(n,t,r){return(n=u(n))&&Yr(n,t,r)+n},Nt.padRight=function(n,t,r){return(n=u(n))&&n+Yr(n,t,r)},Nt.parseInt=lu,Nt.random=function(n,t,r){r&&ie(n,t,r)&&(t=r=null);
var e=null==n,u=null==t;return null==r&&(u&&typeof n=="boolean"?(r=n,n=1):typeof t=="boolean"&&(r=t,u=true)),e&&u&&(t=1,u=false),n=+n||0,u?(t=n,n=0):t=+t||0,r||n%1||t%1?(r=lo(),io(n+r*(t-n+parseFloat("1e-"+((r+"").length-1))),t)):Rr(n,t)},Nt.reduce=Ne,Nt.reduceRight=Ue,Nt.repeat=su,Nt.result=function(n,t,r){return t=null==n?b:n[t],typeof t=="undefined"&&(t=r),Uo(t)?t.call(n):t},Nt.runInContext=w,Nt.size=function(n){var t=n?n.length:0;return fe(t)?t:$o(n).length},Nt.snakeCase=Mo,Nt.some=$e,Nt.sortedIndex=function(n,t,r,e){var u=ne(r);
return u===er&&null==r?Nr(n,t):Ur(n,t,u(r,e,1))},Nt.sortedLastIndex=function(n,t,r,e){var u=ne(r);return u===er&&null==r?Nr(n,t,true):Ur(n,t,u(r,e,1),true)},Nt.startCase=qo,Nt.startsWith=function(n,t,r){return n=u(n),r=null==r?0:io(0>r?0:+r||0,n.length),n.lastIndexOf(t,r)==r},Nt.template=function(n,t,r){var e=Nt.templateSettings;r&&ie(n,t,r)&&(t=r=null),n=u(n),t=nr(nr({},r||t),e,Qt),r=nr(nr({},t.imports),e.imports,Qt);var o,i,f=$o(r),a=Sr(r,f),c=0;r=t.interpolate||At;var l="__p+='";r=Iu((t.escape||At).source+"|"+r.source+"|"+(r===vt?yt:At).source+"|"+(t.evaluate||At).source+"|$","g");
var s="sourceURL"in t?"//# sourceURL="+t.sourceURL+"\n":"";if(n.replace(r,function(t,r,e,u,f,a){return e||(e=u),l+=n.slice(c,a).replace(Rt,p),r&&(o=true,l+="'+__e("+r+")+'"),f&&(i=true,l+="';"+f+";\n__p+='"),e&&(l+="'+((__t=("+e+"))==null?'':__t)+'"),c=a+t.length,t}),l+="';",(t=t.variable)||(l="with(obj){"+l+"}"),l=(i?l.replace(ft,""):l).replace(at,"$1").replace(ct,"$1;"),l="function("+(t||"obj")+"){"+(t?"":"obj||(obj={});")+"var __t,__p=''"+(o?",__e=_.escape":"")+(i?",__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}":";")+l+"return __p}",t=_u(function(){return ju(f,s+"return "+l).apply(b,a)
}),t.source=l,Xe(t))throw t;return t},Nt.trim=pu,Nt.trimLeft=function(n,t,r){var e=n;return(n=u(n))?n.slice((r?ie(e,t,r):null==t)?y(n):i(n,t+"")):n},Nt.trimRight=function(n,t,r){var e=n;return(n=u(n))?(r?ie(e,t,r):null==t)?n.slice(0,d(n)+1):n.slice(0,f(n,t+"")+1):n},Nt.trunc=function(n,t,r){r&&ie(n,t,r)&&(t=null);var e=S;if(r=W,null!=t)if(He(t)){var o="separator"in t?t.separator:o,e="length"in t?+t.length||0:e;r="omission"in t?u(t.omission):r}else e=+t||0;if(n=u(n),e>=n.length)return n;if(e-=r.length,1>e)return r;
if(t=n.slice(0,e),null==o)return t+r;if(tu(o)){if(n.slice(e).search(o)){var i,f=n.slice(0,e);for(o.global||(o=Iu(o.source,(dt.exec(o)||"")+"g")),o.lastIndex=0;n=o.exec(f);)i=n.index;t=t.slice(0,null==i?e:i)}}else n.indexOf(o,e)!=e&&(o=t.lastIndexOf(o),-1<o&&(t=t.slice(0,o)));return t+r},Nt.unescape=function(n){return(n=u(n))&&pt.test(n)?n.replace(lt,m):n},Nt.uniqueId=function(n){var t=++Lu;return u(n)+t},Nt.words=hu,Nt.all=Re,Nt.any=$e,Nt.contains=Se,Nt.detect=Oe,Nt.foldl=Ne,Nt.foldr=Ue,Nt.head=me,Nt.include=Se,Nt.inject=Ne,mu(Nt,function(){var n={};
return vr(Nt,function(t,r){Nt.prototype[r]||(n[r]=t)}),n}(),false),Nt.sample=Fe,Nt.prototype.sample=function(n){return this.__chain__||null!=n?this.thru(function(t){return Fe(t,n)}):Fe(this.value())},Nt.VERSION=x,Pt("bind bindKey curry curryRight partial partialRight".split(" "),function(n){Nt[n].placeholder=Nt}),Pt(["filter","map","takeWhile"],function(n,t){var r=t==F,e=t==$;Lt.prototype[n]=function(n,u){var o=this.clone(),i=o.__filtered__,f=o.__iteratees__||(o.__iteratees__=[]);return o.__filtered__=i||r||e&&0>o.__dir__,f.push({iteratee:ne(n,u,3),type:t}),o
}}),Pt(["drop","take"],function(n,t){var r="__"+n+"Count__",e=n+"While";Lt.prototype[n]=function(e){e=null==e?1:oo(Ku(e)||0,0);var u=this.clone();if(u.__filtered__){var o=u[r];u[r]=t?io(o,e):o+e}else(u.__views__||(u.__views__=[])).push({size:e,type:n+(0>u.__dir__?"Right":"")});return u},Lt.prototype[n+"Right"]=function(t){return this.reverse()[n](t).reverse()},Lt.prototype[n+"RightWhile"]=function(n,t){return this.reverse()[e](n,t).reverse()}}),Pt(["first","last"],function(n,t){var r="take"+(t?"Right":"");
Lt.prototype[n]=function(){return this[r](1).value()[0]}}),Pt(["initial","rest"],function(n,t){var r="drop"+(t?"":"Right");Lt.prototype[n]=function(){return this[r](1)}}),Pt(["pluck","where"],function(n,t){var r=t?"filter":"map",e=t?Ar:Er;Lt.prototype[n]=function(n){return this[r](e(n))}}),Lt.prototype.compact=function(){return this.filter(yu)},Lt.prototype.dropWhile=function(n,t){var r;return n=ne(n,t,3),this.filter(function(t,e,u){return r||(r=!n(t,e,u))})},Lt.prototype.reject=function(n,t){return n=ne(n,t,3),this.filter(function(t,r,e){return!n(t,r,e)
})},Lt.prototype.slice=function(n,t){n=null==n?0:+n||0;var r=0>n?this.takeRight(-n):this.drop(n);return typeof t!="undefined"&&(t=+t||0,r=0>t?r.dropRight(-t):r.take(t-n)),r},Lt.prototype.toArray=function(){return this.drop(0)},vr(Lt.prototype,function(n,t){var r=Nt[t],e=/^(?:first|last)$/.test(t);Nt.prototype[t]=function(){function t(n){return n=[n],Yu.apply(n,o),r.apply(Nt,n)}var u=this.__wrapped__,o=arguments,i=this.__chain__,f=!!this.__actions__.length,a=u instanceof Lt,c=a&&!f;return e&&!i?c?n.call(u):r.call(Nt,this.value()):a||Wo(u)?(u=n.apply(c?u:new Lt(this),o),e||!f&&!u.__actions__||(u.__actions__||(u.__actions__=[])).push({func:Ee,args:[t],thisArg:Nt}),new Ft(u,i)):this.thru(t)
}}),Pt("concat join pop push shift sort splice unshift".split(" "),function(n){var t=Tu[n],r=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",e=/^(?:join|pop|shift)$/.test(n);Nt.prototype[n]=function(){var n=arguments;return e&&!this.__chain__?t.apply(this.value(),n):this[r](function(r){return t.apply(r,n)})}}),Lt.prototype.clone=function(){var n=this.__actions__,t=this.__iteratees__,r=this.__views__,e=new Lt(this.__wrapped__);return e.__actions__=n?qt(n):null,e.__dir__=this.__dir__,e.__dropCount__=this.__dropCount__,e.__filtered__=this.__filtered__,e.__iteratees__=t?qt(t):null,e.__takeCount__=this.__takeCount__,e.__views__=r?qt(r):null,e
},Lt.prototype.reverse=function(){if(this.__filtered__){var n=new Lt(this);n.__dir__=-1,n.__filtered__=true}else n=this.clone(),n.__dir__*=-1;return n},Lt.prototype.value=function(){var n=this.__wrapped__.value();if(!Wo(n))return Wr(n,this.__actions__);var t,r=this.__dir__,e=0>r;t=n.length;for(var u=this.__views__,o=0,i=-1,f=u?u.length:0;++i<f;){var a=u[i],c=a.size;switch(a.type){case"drop":o+=c;break;case"dropRight":t-=c;break;case"take":t=io(t,o+c);break;case"takeRight":o=oo(o,t-c)}}t={start:o,end:t},i=t.start,f=t.end,t=f-i,u=this.__dropCount__,o=io(t,this.__takeCount__),e=e?f:i-1,f=(i=this.__iteratees__)?i.length:0,a=0,c=[];
n:for(;t--&&a<o;){for(var e=e+r,l=-1,s=n[e];++l<f;){var p=i[l],h=p.iteratee(s,e,n),p=p.type;if(p==L)s=h;else if(!h){if(p==F)continue n;break n}}u?u--:c[a++]=s}return c},Nt.prototype.chain=function(){return ke(this)},Nt.prototype.commit=function(){return new Ft(this.value(),this.__chain__)},Nt.prototype.plant=function(n){for(var t,r=this;r instanceof Ut;){var e=ge(r);t?u.__wrapped__=e:t=e;var u=e,r=r.__wrapped__}return u.__wrapped__=n,t},Nt.prototype.reverse=function(){var n=this.__wrapped__;return n instanceof Lt?(this.__actions__.length&&(n=new Lt(this)),new Ft(n.reverse(),this.__chain__)):this.thru(function(n){return n.reverse()
})},Nt.prototype.toString=function(){return this.value()+""},Nt.prototype.run=Nt.prototype.toJSON=Nt.prototype.valueOf=Nt.prototype.value=function(){return Wr(this.__wrapped__,this.__actions__)},Nt.prototype.collect=Nt.prototype.map,Nt.prototype.head=Nt.prototype.first,Nt.prototype.select=Nt.prototype.filter,Nt.prototype.tail=Nt.prototype.rest,Nt}var b,x="3.3.0",A=1,j=2,k=4,E=8,R=16,I=32,O=64,C=128,T=256,S=30,W="...",N=150,U=16,F=0,L=1,$=2,B="Expected a function",z="__lodash_placeholder__",D="[object Arguments]",M="[object Array]",q="[object Boolean]",P="[object Date]",K="[object Error]",V="[object Function]",Y="[object Number]",Z="[object Object]",G="[object RegExp]",J="[object String]",X="[object ArrayBuffer]",H="[object Float32Array]",Q="[object Float64Array]",nt="[object Int8Array]",tt="[object Int16Array]",rt="[object Int32Array]",et="[object Uint8Array]",ut="[object Uint8ClampedArray]",ot="[object Uint16Array]",it="[object Uint32Array]",ft=/\b__p\+='';/g,at=/\b(__p\+=)''\+/g,ct=/(__e\(.*?\)|\b__t\))\+'';/g,lt=/&(?:amp|lt|gt|quot|#39|#96);/g,st=/[&<>"'`]/g,pt=RegExp(lt.source),ht=RegExp(st.source),_t=/<%-([\s\S]+?)%>/g,gt=/<%([\s\S]+?)%>/g,vt=/<%=([\s\S]+?)%>/g,yt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,dt=/\w*$/,mt=/^\s*function[ \n\r\t]+\w/,wt=/^0[xX]/,bt=/^\[object .+?Constructor\]$/,xt=/[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g,At=/($^)/,jt=/[.*+?^${}()|[\]\/\\]/g,kt=RegExp(jt.source),Et=/\bthis\b/,Rt=/['\n\r\u2028\u2029\\]/g,It=RegExp("[A-Z\\xc0-\\xd6\\xd8-\\xde]{2,}(?=[A-Z\\xc0-\\xd6\\xd8-\\xde][a-z\\xdf-\\xf6\\xf8-\\xff]+)|[A-Z\\xc0-\\xd6\\xd8-\\xde]?[a-z\\xdf-\\xf6\\xf8-\\xff]+|[A-Z\\xc0-\\xd6\\xd8-\\xde]+|[0-9]+","g"),Ot=" \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000",Ct="Array ArrayBuffer Date Error Float32Array Float64Array Function Int8Array Int16Array Int32Array Math Number Object RegExp Set String _ clearTimeout document isFinite parseInt setTimeout TypeError Uint8Array Uint8ClampedArray Uint16Array Uint32Array WeakMap window WinRTError".split(" "),Tt={};
Tt[H]=Tt[Q]=Tt[nt]=Tt[tt]=Tt[rt]=Tt[et]=Tt[ut]=Tt[ot]=Tt[it]=true,Tt[D]=Tt[M]=Tt[X]=Tt[q]=Tt[P]=Tt[K]=Tt[V]=Tt["[object Map]"]=Tt[Y]=Tt[Z]=Tt[G]=Tt["[object Set]"]=Tt[J]=Tt["[object WeakMap]"]=false;var St={};St[D]=St[M]=St[X]=St[q]=St[P]=St[H]=St[Q]=St[nt]=St[tt]=St[rt]=St[Y]=St[Z]=St[G]=St[J]=St[et]=St[ut]=St[ot]=St[it]=true,St[K]=St[V]=St["[object Map]"]=St["[object Set]"]=St["[object WeakMap]"]=false;var Wt={leading:false,maxWait:0,trailing:false},Nt={"\xc0":"A","\xc1":"A","\xc2":"A","\xc3":"A","\xc4":"A","\xc5":"A","\xe0":"a","\xe1":"a","\xe2":"a","\xe3":"a","\xe4":"a","\xe5":"a","\xc7":"C","\xe7":"c","\xd0":"D","\xf0":"d","\xc8":"E","\xc9":"E","\xca":"E","\xcb":"E","\xe8":"e","\xe9":"e","\xea":"e","\xeb":"e","\xcc":"I","\xcd":"I","\xce":"I","\xcf":"I","\xec":"i","\xed":"i","\xee":"i","\xef":"i","\xd1":"N","\xf1":"n","\xd2":"O","\xd3":"O","\xd4":"O","\xd5":"O","\xd6":"O","\xd8":"O","\xf2":"o","\xf3":"o","\xf4":"o","\xf5":"o","\xf6":"o","\xf8":"o","\xd9":"U","\xda":"U","\xdb":"U","\xdc":"U","\xf9":"u","\xfa":"u","\xfb":"u","\xfc":"u","\xdd":"Y","\xfd":"y","\xff":"y","\xc6":"Ae","\xe6":"ae","\xde":"Th","\xfe":"th","\xdf":"ss"},Ut={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","`":"&#96;"},Ft={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&#96;":"`"},Lt={"function":true,object:true},$t={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Bt=Lt[typeof window]&&window!==(this&&this.window)?window:this,zt=Lt[typeof exports]&&exports&&!exports.nodeType&&exports,Lt=Lt[typeof module]&&module&&!module.nodeType&&module,Dt=zt&&Lt&&typeof global=="object"&&global;
!Dt||Dt.global!==Dt&&Dt.window!==Dt&&Dt.self!==Dt||(Bt=Dt);var Dt=Lt&&Lt.exports===zt&&zt,Mt=w();typeof define=="function"&&typeof define.amd=="object"&&define.amd?(Bt._=Mt, define(function(){return Mt})):zt&&Lt?Dt?(Lt.exports=Mt)._=Mt:zt._=Mt:Bt._=Mt}).call(this);
+2
View File
@@ -0,0 +1,2 @@
/*! loglevel - v1.2.0 - https://github.com/pimterry/loglevel - (c) 2014 Tim Perry - licensed MIT */
!function(a,b){"object"==typeof module&&module.exports&&"function"==typeof require?module.exports=b():"function"==typeof define&&"object"==typeof define.amd?define(b):a.log=b()}(this,function(){function a(a){return typeof console===i?!1:void 0!==console[a]?b(console,a):void 0!==console.log?b(console,"log"):h}function b(a,b){var c=a[b];if("function"==typeof c.bind)return c.bind(a);try{return Function.prototype.bind.call(c,a)}catch(d){return function(){return Function.prototype.apply.apply(c,[a,arguments])}}}function c(a,b){return function(){typeof console!==i&&(d(b),g[a].apply(g,arguments))}}function d(a){for(var b=0;b<j.length;b++){var c=j[b];g[c]=a>b?h:g.methodFactory(c,a)}}function e(a){var b=(j[a]||"silent").toUpperCase();try{return void(window.localStorage.loglevel=b)}catch(c){}try{window.document.cookie="loglevel="+b+";"}catch(c){}}function f(){var a;try{a=window.localStorage.loglevel}catch(b){}if(typeof a===i)try{a=/loglevel=([^;]+)/.exec(window.document.cookie)[1]}catch(b){}void 0===g.levels[a]&&(a="WARN"),g.setLevel(g.levels[a])}var g={},h=function(){},i="undefined",j=["trace","debug","info","warn","error"];g.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},g.methodFactory=function(b,d){return a(b)||c(b,d)},g.setLevel=function(a){if("string"==typeof a&&void 0!==g.levels[a.toUpperCase()]&&(a=g.levels[a.toUpperCase()]),!("number"==typeof a&&a>=0&&a<=g.levels.SILENT))throw"log.setLevel() called with invalid level: "+a;return e(a),d(a),typeof console===i&&a<g.levels.SILENT?"No console available for logging":void 0},g.enableAll=function(){g.setLevel(g.levels.TRACE)},g.disableAll=function(){g.setLevel(g.levels.SILENT)};var k=typeof window!==i?window.log:void 0;return g.noConflict=function(){return typeof window!==i&&window.log===g&&(window.log=k),g},f(),g});
+3
View File
@@ -0,0 +1,3 @@
/*! sprintf-js | Alexandru Marasteanu <hello@alexei.ro> (http://alexei.ro/) | BSD-3-Clause */
!function(a){function b(){var a=arguments[0],c=b.cache;return c[a]&&c.hasOwnProperty(a)||(c[a]=b.parse(a)),b.format.call(null,c[a],arguments)}function c(a){return Object.prototype.toString.call(a).slice(8,-1).toLowerCase()}function d(a,b){return Array(b+1).join(a)}var e={not_string:/[^s]/,number:/[dief]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fiosuxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[\+\-]/};b.format=function(a,f){var g,h,i,j,k,l,m,n=1,o=a.length,p="",q=[],r=!0,s="";for(h=0;o>h;h++)if(p=c(a[h]),"string"===p)q[q.length]=a[h];else if("array"===p){if(j=a[h],j[2])for(g=f[n],i=0;i<j[2].length;i++){if(!g.hasOwnProperty(j[2][i]))throw new Error(b("[sprintf] property '%s' does not exist",j[2][i]));g=g[j[2][i]]}else g=j[1]?f[j[1]]:f[n++];if("function"==c(g)&&(g=g()),e.not_string.test(j[8])&&"number"!=c(g)&&isNaN(g))throw new TypeError(b("[sprintf] expecting number but found %s",c(g)));switch(e.number.test(j[8])&&(r=g>=0),j[8]){case"b":g=g.toString(2);break;case"c":g=String.fromCharCode(g);break;case"d":case"i":g=parseInt(g,10);break;case"e":g=j[7]?g.toExponential(j[7]):g.toExponential();break;case"f":g=j[7]?parseFloat(g).toFixed(j[7]):parseFloat(g);break;case"o":g=g.toString(8);break;case"s":g=(g=String(g))&&j[7]?g.substring(0,j[7]):g;break;case"u":g>>>=0;break;case"x":g=g.toString(16);break;case"X":g=g.toString(16).toUpperCase()}!e.number.test(j[8])||r&&!j[3]?s="":(s=r?"+":"-",g=g.toString().replace(e.sign,"")),l=j[4]?"0"===j[4]?"0":j[4].charAt(1):" ",m=j[6]-(s+g).length,k=j[6]&&m>0?d(l,m):"",q[q.length]=j[5]?s+g+k:"0"===l?s+k+g:k+s+g}return q.join("")},b.cache={},b.parse=function(a){for(var b=a,c=[],d=[],f=0;b;){if(null!==(c=e.text.exec(b)))d[d.length]=c[0];else if(null!==(c=e.modulo.exec(b)))d[d.length]="%";else{if(null===(c=e.placeholder.exec(b)))throw new SyntaxError("[sprintf] unexpected placeholder");if(c[2]){f|=1;var g=[],h=c[2],i=[];if(null===(i=e.key.exec(h)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(g[g.length]=i[1];""!==(h=h.substring(i[0].length));)if(null!==(i=e.key_access.exec(h)))g[g.length]=i[1];else{if(null===(i=e.index_access.exec(h)))throw new SyntaxError("[sprintf] failed to parse named argument key");g[g.length]=i[1]}c[2]=g}else f|=2;if(3===f)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");d[d.length]=c}b=b.substring(c[0].length)}return d};var f=function(a,c,d){return d=(c||[]).slice(0),d.splice(0,0,a),b.apply(null,d)};"undefined"!=typeof exports?(exports.sprintf=b,exports.vsprintf=f):(a.sprintf=b,a.vsprintf=f,"function"==typeof define&&define.amd&&define(function(){return{sprintf:b,vsprintf:f}}))}("undefined"==typeof window?this:window);
-6
View File
@@ -1,6 +0,0 @@
// Underscore.js 1.5.2
// http://underscorejs.org
// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function(){var n=this,t=n._,r={},e=Array.prototype,u=Object.prototype,i=Function.prototype,a=e.push,o=e.slice,c=e.concat,l=u.toString,f=u.hasOwnProperty,s=e.forEach,p=e.map,h=e.reduce,v=e.reduceRight,g=e.filter,d=e.every,m=e.some,y=e.indexOf,b=e.lastIndexOf,x=Array.isArray,w=Object.keys,_=i.bind,j=function(n){return n instanceof j?n:this instanceof j?(this._wrapped=n,void 0):new j(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=j),exports._=j):n._=j,j.VERSION="1.5.2";var A=j.each=j.forEach=function(n,t,e){if(null!=n)if(s&&n.forEach===s)n.forEach(t,e);else if(n.length===+n.length){for(var u=0,i=n.length;i>u;u++)if(t.call(e,n[u],u,n)===r)return}else for(var a=j.keys(n),u=0,i=a.length;i>u;u++)if(t.call(e,n[a[u]],a[u],n)===r)return};j.map=j.collect=function(n,t,r){var e=[];return null==n?e:p&&n.map===p?n.map(t,r):(A(n,function(n,u,i){e.push(t.call(r,n,u,i))}),e)};var E="Reduce of empty array with no initial value";j.reduce=j.foldl=j.inject=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),h&&n.reduce===h)return e&&(t=j.bind(t,e)),u?n.reduce(t,r):n.reduce(t);if(A(n,function(n,i,a){u?r=t.call(e,r,n,i,a):(r=n,u=!0)}),!u)throw new TypeError(E);return r},j.reduceRight=j.foldr=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),v&&n.reduceRight===v)return e&&(t=j.bind(t,e)),u?n.reduceRight(t,r):n.reduceRight(t);var i=n.length;if(i!==+i){var a=j.keys(n);i=a.length}if(A(n,function(o,c,l){c=a?a[--i]:--i,u?r=t.call(e,r,n[c],c,l):(r=n[c],u=!0)}),!u)throw new TypeError(E);return r},j.find=j.detect=function(n,t,r){var e;return O(n,function(n,u,i){return t.call(r,n,u,i)?(e=n,!0):void 0}),e},j.filter=j.select=function(n,t,r){var e=[];return null==n?e:g&&n.filter===g?n.filter(t,r):(A(n,function(n,u,i){t.call(r,n,u,i)&&e.push(n)}),e)},j.reject=function(n,t,r){return j.filter(n,function(n,e,u){return!t.call(r,n,e,u)},r)},j.every=j.all=function(n,t,e){t||(t=j.identity);var u=!0;return null==n?u:d&&n.every===d?n.every(t,e):(A(n,function(n,i,a){return(u=u&&t.call(e,n,i,a))?void 0:r}),!!u)};var O=j.some=j.any=function(n,t,e){t||(t=j.identity);var u=!1;return null==n?u:m&&n.some===m?n.some(t,e):(A(n,function(n,i,a){return u||(u=t.call(e,n,i,a))?r:void 0}),!!u)};j.contains=j.include=function(n,t){return null==n?!1:y&&n.indexOf===y?n.indexOf(t)!=-1:O(n,function(n){return n===t})},j.invoke=function(n,t){var r=o.call(arguments,2),e=j.isFunction(t);return j.map(n,function(n){return(e?t:n[t]).apply(n,r)})},j.pluck=function(n,t){return j.map(n,function(n){return n[t]})},j.where=function(n,t,r){return j.isEmpty(t)?r?void 0:[]:j[r?"find":"filter"](n,function(n){for(var r in t)if(t[r]!==n[r])return!1;return!0})},j.findWhere=function(n,t){return j.where(n,t,!0)},j.max=function(n,t,r){if(!t&&j.isArray(n)&&n[0]===+n[0]&&n.length<65535)return Math.max.apply(Math,n);if(!t&&j.isEmpty(n))return-1/0;var e={computed:-1/0,value:-1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;a>e.computed&&(e={value:n,computed:a})}),e.value},j.min=function(n,t,r){if(!t&&j.isArray(n)&&n[0]===+n[0]&&n.length<65535)return Math.min.apply(Math,n);if(!t&&j.isEmpty(n))return 1/0;var e={computed:1/0,value:1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;a<e.computed&&(e={value:n,computed:a})}),e.value},j.shuffle=function(n){var t,r=0,e=[];return A(n,function(n){t=j.random(r++),e[r-1]=e[t],e[t]=n}),e},j.sample=function(n,t,r){return arguments.length<2||r?n[j.random(n.length-1)]:j.shuffle(n).slice(0,Math.max(0,t))};var k=function(n){return j.isFunction(n)?n:function(t){return t[n]}};j.sortBy=function(n,t,r){var e=k(t);return j.pluck(j.map(n,function(n,t,u){return{value:n,index:t,criteria:e.call(r,n,t,u)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={},i=null==r?j.identity:k(r);return A(t,function(r,a){var o=i.call(e,r,a,t);n(u,o,r)}),u}};j.groupBy=F(function(n,t,r){(j.has(n,t)?n[t]:n[t]=[]).push(r)}),j.indexBy=F(function(n,t,r){n[t]=r}),j.countBy=F(function(n,t){j.has(n,t)?n[t]++:n[t]=1}),j.sortedIndex=function(n,t,r,e){r=null==r?j.identity:k(r);for(var u=r.call(e,t),i=0,a=n.length;a>i;){var o=i+a>>>1;r.call(e,n[o])<u?i=o+1:a=o}return i},j.toArray=function(n){return n?j.isArray(n)?o.call(n):n.length===+n.length?j.map(n,j.identity):j.values(n):[]},j.size=function(n){return null==n?0:n.length===+n.length?n.length:j.keys(n).length},j.first=j.head=j.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:o.call(n,0,t)},j.initial=function(n,t,r){return o.call(n,0,n.length-(null==t||r?1:t))},j.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:o.call(n,Math.max(n.length-t,0))},j.rest=j.tail=j.drop=function(n,t,r){return o.call(n,null==t||r?1:t)},j.compact=function(n){return j.filter(n,j.identity)};var M=function(n,t,r){return t&&j.every(n,j.isArray)?c.apply(r,n):(A(n,function(n){j.isArray(n)||j.isArguments(n)?t?a.apply(rLine truncated
//# sourceMappingURL=underscore-min.map
-1
View File
@@ -1 +0,0 @@
!function(e,t){"use strict";var n=t.prototype.trim,r=t.prototype.trimRight,i=t.prototype.trimLeft,s=function(e){return e*1||0},o=function(e,t){if(t<1)return"";var n="";while(t>0)t&1&&(n+=e),t>>=1,e+=e;return n},u=[].slice,a=function(e){return e==null?"\\s":e.source?e.source:"["+p.escapeRegExp(e)+"]"},f={lt:"<",gt:">",quot:'"',apos:"'",amp:"&"},l={};for(var c in f)l[f[c]]=c;var h=function(){function e(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}var n=o,r=function(){return r.cache.hasOwnProperty(arguments[0])||(r.cache[arguments[0]]=r.parse(arguments[0])),r.format.call(null,r.cache[arguments[0]],arguments)};return r.format=function(r,i){var s=1,o=r.length,u="",a,f=[],l,c,p,d,v,m;for(l=0;l<o;l++){u=e(r[l]);if(u==="string")f.push(r[l]);else if(u==="array"){p=r[l];if(p[2]){a=i[s];for(c=0;c<p[2].length;c++){if(!a.hasOwnProperty(p[2][c]))throw new Error(h('[_.sprintf] property "%s" does not exist',p[2][c]));a=a[p[2][c]]}}else p[1]?a=i[p[1]]:a=i[s++];if(/[^s]/.test(p[8])&&e(a)!="number")throw new Error(h("[_.sprintf] expecting number but found %s",e(a)));switch(p[8]){case"b":a=a.toString(2);break;case"c":a=t.fromCharCode(a);break;case"d":a=parseInt(a,10);break;case"e":a=p[7]?a.toExponential(p[7]):a.toExponential();break;case"f":a=p[7]?parseFloat(a).toFixed(p[7]):parseFloat(a);break;case"o":a=a.toString(8);break;case"s":a=(a=t(a))&&p[7]?a.substring(0,p[7]):a;break;case"u":a=Math.abs(a);break;case"x":a=a.toString(16);break;case"X":a=a.toString(16).toUpperCase()}a=/[def]/.test(p[8])&&p[3]&&a>=0?"+"+a:a,v=p[4]?p[4]=="0"?"0":p[4].charAt(1):" ",m=p[6]-t(a).length,d=p[6]?n(v,m):"",f.push(p[5]?a+d:d+a)}}return f.join("")},r.cache={},r.parse=function(e){var t=e,n=[],r=[],i=0;while(t){if((n=/^[^\x25]+/.exec(t))!==null)r.push(n[0]);else if((n=/^\x25{2}/.exec(t))!==null)r.push("%");else{if((n=/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(t))===null)throw new Error("[_.sprintf] huh?");if(n[2]){i|=1;var s=[],o=n[2],u=[];if((u=/^([a-z_][a-z_\d]*)/i.exec(o))===null)throw new Error("[_.sprintf] huh?");s.push(u[1]);while((o=o.substring(u[0].length))!=="")if((u=/^\.([a-z_][a-z_\d]*)/i.exec(o))!==null)s.push(u[1]);else{if((u=/^\[(\d+)\]/.exec(o))===null)throw new Error("[_.sprintf] huh?");s.push(u[1])}n[2]=s}else i|=2;if(i===3)throw new Error("[_.sprintf] mixing positional and named placeholders is not (yet) supported");r.push(n)}t=t.substring(n[0].length)}return r},r}(),p={VERSION:"2.3.0",isBlank:function(e){return e==null&&(e=""),/^\s*$/.test(e)},stripTags:function(e){return e==null?"":t(e).replace(/<\/?[^>]+>/g,"")},capitalize:function(e){return e=e==null?"":t(e),e.charAt(0).toUpperCase()+e.slice(1)},chop:function(e,n){return e==null?[]:(e=t(e),n=~~n,n>0?e.match(new RegExp(".{1,"+n+"}","g")):[e])},clean:function(e){return p.strip(e).replace(/\s+/g," ")},count:function(e,n){return e==null||n==null?0:t(e).split(n).length-1},chars:function(e){return e==null?[]:t(e).split("")},swapCase:function(e){return e==null?"":t(e).replace(/\S/g,function(e){return e===e.toUpperCase()?e.toLowerCase():e.toUpperCase()})},escapeHTML:function(e){return e==null?"":t(e).replace(/[&<>"']/g,function(e){return"&"+l[e]+";"})},unescapeHTML:function(e){return e==null?"":t(e).replace(/\&([^;]+);/g,function(e,n){var r;return n in f?f[n]:(r=n.match(/^#x([\da-fA-F]+)$/))?t.fromCharCode(parseInt(r[1],16)):(r=n.match(/^#(\d+)$/))?t.fromCharCode(~~r[1]):e})},escapeRegExp:function(e){return e==null?"":t(e).replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")},splice:function(e,t,n,r){var i=p.chars(e);return i.splice(~~t,~~n,r),i.join("")},insert:function(e,t,n){return p.splice(e,t,0,n)},include:function(e,n){return n===""?!0:e==null?!1:t(e).indexOf(n)!==-1},join:function(){var e=u.call(arguments),t=e.shift();return t==null&&(t=""),e.join(t)},lines:function(e){return e==null?[]:t(e).split("\n")},reverse:function(e){return p.chars(e).reverse().join("")},startsWith:function(e,n){return n===""?!0:e==null||n==null?!1:(e=t(e),n=t(n),e.length>=n.length&&e.slice(0,n.length)===n)},endsWith:function(e,n){return n===""?!0:e==null||n==null?!1:(e=t(e),n=t(n),e.length>=n.length&&e.slice(e.length-n.length)===n)},succ:function(e){return e==null?"":(e=t(e),e.slice(0,-1)+t.fromCharCode(e.charCodeAt(e.length-1)+1))},titleize:function(e){return e==null?"":t(e).replace(/(?:^|\s)\S/g,function(e){return e.toUpperCase()})},camelize:function(e){return p.trim(e).replace(/[-_\s]+(.)?/g,function(e,t){return t.toUpperCase()})},underscored:function(e){return p.trim(e).replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()},dasherize:function(e){return p.trim(e).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},classify:function(e){return p.titleize(t(e).replace(/_/g," ")).replace(/\s/g,"")},humanize:function(e){return p.capitalize(p.underscored(e).replace(/_id$/,"").replace(/_/g," "))},trim:function(e,r){return e==null?"":!r&&n?n.call(e):(r=a(r),t(e).replace(new RegExp("^"+r+"+|"+r+"+$","g"),""))},lLine truncated
+14
View File
@@ -0,0 +1,14 @@
// Gradients with background images
#imggradient {
.vertical(@startColor: #555, @endColor: #333, @image) {
background-color: mix(@startColor, @endColor, 60%);
background-image: @image; // fallback
background-image: -moz-linear-gradient(top, @startColor, @endColor), url(@image); // FF 3.6+
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), to(@endColor)), url(@image); // Safari 4+, Chrome 2+
background-image: -webkit-linear-gradient(top, @startColor, @endColor), url(@image); // Safari 5.1+, Chrome 10+
background-image: -o-linear-gradient(top, @startColor, @endColor), url(@image); // Opera 11.10
background-image: linear-gradient(to bottom, @startColor, @endColor), url(@image); // Standard, IE10
background-repeat: repeat-x;
filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=0)",argb(@startColor),argb(@endColor))); // IE9 and down
}
}
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more