Merge branch 'devel' of github:foosel/OctoPrint into dev/permission
This commit is contained in:
commit
120406d115
180 files changed
+16327
-4363
No files matched your search
@@ -10,13 +10,14 @@ This is a bug and feature tracker, please only use it to report bugs
|
||||
or request features within OctoPrint (not OctoPi, not any OctoPrint
|
||||
plugins and not unofficial OctoPrint versions).
|
||||
|
||||
Do not seek support here ("I need help with ..."), that belongs on
|
||||
the mailing list or the G+ community (both linked in the "guidelines
|
||||
for contributing" linked above, read it!), NOT here.
|
||||
Do not seek support here ("I need help with ...", "I have a
|
||||
question ..."), that belongs on the mailing list or the G+ community
|
||||
(both linked in the "guidelines for contributing" linked above, read
|
||||
them!), NOT here.
|
||||
|
||||
Mark requests with a "[Request]" prefix in the title please. Fully fill
|
||||
out the bug reporting template for bug reports (if you don't know where
|
||||
to find some information - it's all described in the Contribution
|
||||
Mark requests with a "[Request]" prefix in the title please. For bug
|
||||
reports fully fill out the bug reporting template (if you don't know
|
||||
where to find some information - it's all described in the Contribution
|
||||
Guidelines linked up there in the big yellow box).
|
||||
|
||||
When reporting a bug do NOT delete ANY lines from the template but
|
||||
@@ -91,7 +92,7 @@ reporting communication issues. Never truncate.
|
||||
serial.log is usually not written due to performance reasons and must be
|
||||
enabled explicitly. Provide at the very least the FULL contents of your
|
||||
terminal tab at the time of the bug occurrence, even if you do not have
|
||||
a serial.log.]
|
||||
a serial.log (which the Contribution Guidelines tell you where to find).]
|
||||
|
||||
#### Link to contents of Javascript console in the browser
|
||||
|
||||
|
||||
+7
-4
@@ -16,11 +16,14 @@ prerelease
|
||||
HEAD
|
||||
\(detached.*
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.3
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.3.5
|
||||
# so are any fix/... and improve/... branches
|
||||
maintenance 1.3.3 0a69dbeddb301d5a32827a3f0d561f875df24234 pep440-dev
|
||||
fix/.* 1.3.3 0a69dbeddb301d5a32827a3f0d561f875df24234 pep440-dev
|
||||
improve/.* 1.3.3 0a69dbeddb301d5a32827a3f0d561f875df24234 pep440-dev
|
||||
maintenance 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
|
||||
fix/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
|
||||
improve/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
|
||||
|
||||
# staging/maintenance is currently the branch for preparation of 1.3.5rc1
|
||||
staging/maintenance 1.3.5rc1 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
|
||||
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
|
||||
@@ -81,6 +81,7 @@ date of first contribution):
|
||||
* [Andreas Werner](https://github.com/gallore)
|
||||
* [Shawn Bruce](https://github.com/kantlivelong)
|
||||
* [Claudiu Ceia] (https://github.com/ClaudiuCeia)
|
||||
* [Goswin von Brederlow](https://github.com/mrvn)
|
||||
|
||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||
|
||||
+119
@@ -1,5 +1,124 @@
|
||||
# OctoPrint Changelog
|
||||
|
||||
## 1.3.4 (2017-06-01)
|
||||
|
||||
### Note for owners of Malyan M200/Monoprice Select Mini
|
||||
|
||||
OctoPrint's firmware autodetection is now able to detect this printer. Currently when this printer is detected, the following firmware specific features will be enabled automatically:
|
||||
|
||||
* Always assume SD card is present (`feature.sdAlwaysAvailable`)
|
||||
* Send a checksum with the command: Always (`feature.alwaysSendChecksum`)
|
||||
|
||||
Since the firmware is a very special kind of beast and its sources are so far unavailable, only tests with a real printer will show if those are sufficient settings for communication with this printer to fully function correctly. Thus, if you run into any issues with enabled firmware autodetection on this printer model, please add a comment in [#1762](https://github.com/foosel/OctoPrint/issues/1762) and explain what kind of communication problem you are seeing. Also make sure to include a [`serial.log`](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#where-can-i-find-those-log-files-you-keep-talking-about)!
|
||||
|
||||
### Bug fixes
|
||||
|
||||
* [#1942](https://github.com/foosel/OctoPrint/issues/1942) - Fixed crash on startup in case of an invalid default printer profile combined with "auto-connect on startup" being selected and the printer available to connect to.
|
||||
|
||||
### More information
|
||||
|
||||
* [Commits](https://github.com/foosel/OctoPrint/compare/1.3.1...1.3.2)
|
||||
* Release Candidates:
|
||||
* None since this constitutes a hotfix release to fix an apparently very rare bug introduced with 1.3.3 that seems to be affecting a small number of users.
|
||||
|
||||
## 1.3.3 (2017-05-31)
|
||||
|
||||
### Note for owners of Malyan M200/Monoprice Select Mini
|
||||
|
||||
OctoPrint's firmware autodetection is now able to detect this printer. Currently when this printer is detected, the following firmware specific features will be enabled automatically:
|
||||
|
||||
* Always assume SD card is present (`feature.sdAlwaysAvailable`)
|
||||
* Send a checksum with the command: Always (`feature.alwaysSendChecksum`)
|
||||
|
||||
Since the firmware is a very special kind of beast and its sources are so far unavailable, only tests with a real printer will show if those are sufficient settings for communication with this printer to fully function correctly. Thus, if you run into any issues with enabled firmware autodetection on this printer model, please add a comment in [#1762](https://github.com/foosel/OctoPrint/issues/1762) and explain what kind of communication problem you are seeing. Also make sure to include a [`serial.log`](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#where-can-i-find-those-log-files-you-keep-talking-about)!
|
||||
|
||||
### Improvements
|
||||
|
||||
* [#478](https://github.com/foosel/OctoPrint/issues/478) - Made webcam stream container fixed height (with selectable aspect ratio) to prevent jumps of the controls beneath it on load.
|
||||
* [#748](https://github.com/foosel/OctoPrint/issues/748) - Added delete confirmation and bulk delete for timelapses. See also the discussion in brainstorming ticket [#1807](https://github.com/foosel/OctoPrint/issues/1807).
|
||||
* [#1092](https://github.com/foosel/OctoPrint/issues/1092) - Added new events to the file manager: `FileAdded`, `FileRemoved`, `FolderAdded`, `FolderRemoved`. Contrary to the `Upload` event, `FileAdded` will always fire when a file was added to storage through the file manager, not only when added through the web interface. Extended documentation accordingly.
|
||||
* [#1521](https://github.com/foosel/OctoPrint/issues/1521) - Software update plugin: Display timestamp of last version cache refresh in "Advanced options" area.
|
||||
* [#1734](https://github.com/foosel/OctoPrint/issues/1734) - Treat default/initial printer profile like all other printer profiles, persisting it to disk instead of `config.yaml` and allowing deletion. OctoPrint will migrate the existing default profile to the new location on first start.
|
||||
* [#1734](https://github.com/foosel/OctoPrint/issues/1734) - Better communication of what actions are available for printer profiles.
|
||||
* [#1739](https://github.com/foosel/OctoPrint/issues/1739) - Software update plugin: Added option to hide update notification from users without admin rights, added "ignore" button and note to get in touch with an admit to update notifications for non admin users.
|
||||
* [#1762](https://github.com/foosel/OctoPrint/issues/1762) - Added Malyan M200/Monoprice Select Mini to firmware autodetection.
|
||||
* [#1811](https://github.com/foosel/OctoPrint/issues/1811) - Slight rewording and rearrangement in timelapse configuration, better feedback if settings have been saved.
|
||||
* [#1818](https://github.com/foosel/OctoPrint/issues/1818) - Support both Marlin/Repetier and Smoothieware interpretations of `G90` after an `M83` in GCODE viewer and analysis. Select "G90/G91 overrides relative extruder mode" in Settings > Features for the Smoothieware interpretation.
|
||||
* [#1858](https://github.com/foosel/OctoPrint/issues/1858) - Announcement plugin: Images from registered feeds now are lazy loading.
|
||||
* [#1862](https://github.com/foosel/OctoPrint/issues/1862) - Automatically re-enable fancy terminal functionality when performance recovers.
|
||||
* [#1875](https://github.com/foosel/OctoPrint/issues/1875) - Marked the command input field in the Terminal tab as not supporting autocomplete to work around an issue in Safari. Note that this is probably only a temporary workaround due to browser vendors [working on deprecating `autocomplete="off"` support](https://bugs.chromium.org/p/chromium/issues/detail?id=468153#c164) and a different solution will need to be found in the future.
|
||||
* Added link to [`SerialException` FAQ entry](https://github.com/foosel/OctoPrint/wiki/FAQ#octoprint-randomly-loses-connection-to-the-printer-with-a-serialexception) to terminal output when such an error is encountered, as suggested in [#1876](https://github.com/foosel/OctoPrint/issues/1876).
|
||||
* Force refresh of settings on login/logout.
|
||||
* Made system wide API key management mirror user API key management.
|
||||
* Make sure to always migrate and merge saved printer profiles with default profile to ensure all parameters are set. Should avoid issues with plugins trying to save outdated/incomplete profiles.
|
||||
* Added note on lack of language pack repository & to use the wiki for now.
|
||||
* Earlier validation of file to select for printing.
|
||||
* Limit verbosity of failed system event handlers.
|
||||
* Made bundled python client `octoprint_client` support multiple client instances.
|
||||
* Disable "Reload" button in the "Please reload" overlay once clicked, added spinner.
|
||||
* Updated pnotify to 2.1.0.
|
||||
* Get rid of ridiculous float precision in temperature commands.
|
||||
* Detect invalid settings data to persist (not a dict), send 400 status in such a case.
|
||||
* More logging for preemptive caching, to help narrow down any performance issues that might be related to this.
|
||||
* Further decoupling of some startup tasks from initial server startup thread for better parallelization and improved startup times.
|
||||
* Announcement plugin: Added combined OctoBlog feed, replacing news and spotlight feed, added corresponding config migration.
|
||||
* Announcement plugin: Subscribe to all registered feeds by default to ensure better communication flow (all subscriptions but the "Important" channel can however be unsubscribed easily, added corresponding note to the notifications and also a configuration button to the announcement reader).
|
||||
* Announcement plugin: Auto-hide announcements on logout.
|
||||
* Announcement plugin: Order channels server-side based on new order config setting.
|
||||
* Plugin manager: Show warning when disabling a bundled plugin that is not recommended to be disabled, including a reason why disabling it is not recommended. Applies to the bundled announcement, core wizard, discovery and software update plugins.
|
||||
* Plugin manager: Support for plugin notices for specific plugins from the plugin repository, e.g. to inform users of specific plugins about known issues with the plugin or instruct to update when the software update mechanism of the current plugin version turns out to be misconfigured. Supports matching installed plugin versions and OctoPrint versions to target only affected users.
|
||||
* Plugin manager: Better visualization of plugins disabled on the repository, no longer shown as "incompatible" but "disabled", with link to the plugin repository page that contains more information.
|
||||
* Plugin manager: Detect necessity to reinstall a plugin provided through archive URL or upload and immediately do that instead of reporting an "unknown error" without further information.
|
||||
* Plugin manager: Added `freebsd` for compatibility check.
|
||||
* Plugin manager: More general flexibility for OS compatibility check:
|
||||
* Support for arbitrary values to match against
|
||||
* Allow 1:1 check again `sys.platform` values (with `startswith`).
|
||||
* Support black listing (`!windows`) additionally to white listing. A detected OS must match all provided white list elements (if the white list is empty that is considered to be always the case) and none of the black list elements (if the black list is empty that is also considered to be always the case).
|
||||
* Software update plugin: New check type `bitbucket_commit` (see also [#1898](https://github.com/foosel/OctoPrint/pull/1898))
|
||||
* Docs: Now referring to dedicated Jinja 2.8 documentation as hosted at [jinja.octoprint.org](http://jinja.octoprint.org) for all template needs, to avoid confusion when consulting current Jinja documentation as available on its project page (2.9+, which OctoPrint can't upgrade to due to backwards incompatible changes).
|
||||
* Docs: Better documentation of what kind of input the `FileManager` accepts for `select_file`.
|
||||
* Docs: Specified OctoPrint version required for plugin tutorial.
|
||||
|
||||
### Bug fixes
|
||||
|
||||
* [#202](https://github.com/foosel/OctoPrint/issues/202) - Fixed an issue with the drag-n-drop area flickering if the mouse was moved too slow while dragging (see also [#1867](https://github.com/foosel/OctoPrint/pull/1867)).
|
||||
* [#1671](https://github.com/foosel/OctoPrint/issues/1671) - Removed obsolete entry of no longer available filter for empty folders from file list options.
|
||||
* [#1821](https://github.com/foosel/OctoPrint/issues/1821) - Properly reset "Capture post roll images" setting in timelapse configuration when switching from "off" to "timed" timelapse mode.
|
||||
* [#1822](https://github.com/foosel/OctoPrint/issues/1822) - Properly reset file metadata when a file is overwritten with a new version.
|
||||
* [#1836](https://github.com/foosel/OctoPrint/issues/1836) - Fixed order of `PrintCancelled` and `PrintFailed` events on print cancel.
|
||||
* [#1837](https://github.com/foosel/OctoPrint/issues/1837) - Fixed a race condition causing OctoPrint trying to read data from the current job on job cancel that was no longer there.
|
||||
* [#1838](https://github.com/foosel/OctoPrint/issues/1838) - Fixed a rare race condition causing an error right at the very start of a print.
|
||||
* [#1863](https://github.com/foosel/OctoPrint/issues/1863) - Fixed an issue in the analysis of GCODE files containing coordinate offsets for X, Y or Z via `G92`, leading to a wrong calculation of the model size thanks to accumulating offsets.
|
||||
* [#1882](https://github.com/foosel/OctoPrint/issues/1882) - Fixed a rare race condition occurring at the start of streaming a file to the printer's SD card, leading to endless line number mismatches.
|
||||
* [#1884](https://github.com/foosel/OctoPrint/issues/1884) - CuraEngine plugin: Fixed a potential encoding issue when logging non-ASCII parameters supplied to CuraEngine
|
||||
* [#1891](https://github.com/foosel/OctoPrint/issues/1891) - Fixed error when handling unicode passwords.
|
||||
* [#1893](https://github.com/foosel/OctoPrint/issues/1893) - CuraEngine plugin: Fixed handling of multiple consecutive uploads of slicing profiles (see also [#1894](https://github.com/foosel/OctoPrint/issues/1894))
|
||||
* [#1897](https://github.com/foosel/OctoPrint/issues/1897) - Removed possibility to concurrently try to perform multiple tests of the configured snapshot URL.
|
||||
* [#1906](https://github.com/foosel/OctoPrint/issues/1906) - Fixed interpretation of `G92` in GCODE analysis.
|
||||
* [#1907](https://github.com/foosel/OctoPrint/issues/1907) - Don't send temperature commands with tool parameter when a shared nozzle is defined.
|
||||
* [#1917](https://github.com/foosel/OctoPrint/issues/1917) (regression) - Fix job data resetting on print job completion.
|
||||
* [#1918](https://github.com/foosel/OctoPrint/issues/1918) (regression) - Fix "save as default" checkbox not being disabled when other controls are disabled.
|
||||
* [#1919](https://github.com/foosel/OctoPrint/issues/1919) (regression) - Fix call to no longer existing function in Plugin Manager UI.
|
||||
* [#1934](https://github.com/foosel/OctoPrint/issues/1934) (regression) - Fix consecutive timed timelapse captures without configured post roll.
|
||||
* Fixed API key QR Code being shown (for "n/a" value) when no API key was set.
|
||||
* Fixed timelapse configuration API not returning 400 status code on some bad parameters.
|
||||
* Fixed a typo (see also [#1826](https://github.com/foosel/OctoPrint/pull/1826)).
|
||||
* Fixed `filter` and `force` parameters on `/api/files/<origin>`.
|
||||
* Fixed message catchall `*` not working in the socket client library.
|
||||
* Fixed analysis backlog calculation for sub folders.
|
||||
* Fixed `PrinterInterface.is_ready` to behave as documented.
|
||||
* Use black listing instead of white listing again to detect if the `daemon` sub command is supported or not. Should resolve issues users of FreeBSD and the like where having with `octoprint daemon`.
|
||||
* Use `pip` instead of `python setup.py develop` in `octoprint dev plugin:install` command to avoid issues on Windows.
|
||||
* Docs: Fixed a wrong command in the plugin tutorial (see also [#1860](https://github.com/foosel/OctoPrint/pull/1860)).
|
||||
|
||||
### More information
|
||||
|
||||
- [Commits](https://github.com/foosel/OctoPrint/compare/1.3.2...1.3.3)
|
||||
- Release Candidates:
|
||||
- [1.3.3rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.3rc1)
|
||||
- [1.3.3rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.3rc2)
|
||||
- [1.3.3rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.3rc3)
|
||||
|
||||
## 1.3.2 (2017-03-16)
|
||||
|
||||
### Note for plugin authors
|
||||
|
||||
+7
-1
@@ -365,10 +365,16 @@ There are three main branches in OctoPrint:
|
||||
the `maintenance` branch and are now being pushed on the "Maintenance"
|
||||
pre release channel for further testing. Version number follows the scheme
|
||||
`<x>.<y>.<z>rc<n>` (e.g. `1.2.9rc1`).
|
||||
* `staging/maintenance`: Any preparation for potential follow-up RCs takes place here.
|
||||
Version number follows the scheme `<x>.<y>.<z>rc<n+1>.dev<commits since increase of n>` (e.g.
|
||||
`1.2.9rc1.dev3`) for a current Maintenance RC of `<x>.<y>.<z>rc<n>`.
|
||||
* `rc/devel`: This branch is reserved for future releases that have graduated from
|
||||
the `devel` branch and are now being pushed on the "Devel" pre release channel
|
||||
for further testing. Version number follows the scheme `<x>.<y+1>.0rc<n>` (e.g. `1.3.0rc1`)
|
||||
for a current stable OctoPrint version of `<x>.<y>.<z>`.
|
||||
* `staging/devel`: Any preparation for potential follow-up Devel RCs takes place
|
||||
here. Version number follows the scheme `<x>.<y>.0rc<n+1>.dev<commits since increase of n>` (e.g.
|
||||
`1.3.0rc1.dev12`) for a current Devel RC of `<x>.<y>.0rc<n>`.
|
||||
|
||||
Additionally, from time to time you might see other branches pop up in the repository.
|
||||
Those usually have one of the following prefixes:
|
||||
@@ -380,7 +386,7 @@ Those usually have one of the following prefixes:
|
||||
* `dev/...` or `feature/...`: New functionality under development that is to be merged
|
||||
into the `devel` branch.
|
||||
|
||||
There is also the `gh-pages` branch, which holds OctoPrint's web page, and a couple of
|
||||
There is also the `gh-pages` branch, which holds OctoPrint's web page, and a few
|
||||
older development branches that are slowly being migrated or deleted.
|
||||
|
||||
## How OctoPrint is versioned
|
||||
|
||||
@@ -67,7 +67,7 @@ and at its settings.
|
||||
|
||||
## Dependencies
|
||||
|
||||
OctoPrint depends on a couple of python modules to do its job. Those are automatically installed when installing
|
||||
OctoPrint depends on a few python modules to do its job. Those are automatically installed when installing
|
||||
OctoPrint via `setup.py`:
|
||||
|
||||
python setup.py install
|
||||
|
||||
+7
-6
@@ -1,4 +1,4 @@
|
||||
# Supporters
|
||||
# Supporters
|
||||
|
||||
Development of this version of OctoPrint wouldn't have been possible without
|
||||
[financial support by the community](http://octoprint.org/support-octoprint/) -
|
||||
@@ -10,11 +10,11 @@ thanks to everyone who contributed!
|
||||
* Aleph Objects, Inc.
|
||||
* Andrew Moorby
|
||||
* Arnljot Arntsen
|
||||
* BEEVERYCREATIVE
|
||||
* Boris Hussein
|
||||
* Brad Jackson
|
||||
* Brent Fiegle
|
||||
* Brian E. Tyler
|
||||
* Christopher Day
|
||||
* Chris Day
|
||||
* Christian Petropolis
|
||||
* CreativeTools
|
||||
* D Brian Kimmel
|
||||
@@ -23,13 +23,15 @@ thanks to everyone who contributed!
|
||||
* E3D BigBox
|
||||
* Ernesto Martinez
|
||||
* Exovite
|
||||
* F. Kunsmann
|
||||
* Frank Sander
|
||||
* Gary Deen
|
||||
* Gary N McKinney
|
||||
* George Robles
|
||||
* günter weber
|
||||
* Ivan Krasin
|
||||
* James Seigel
|
||||
* Jamie R McGuigan
|
||||
* Jamie van Dyke
|
||||
* Jeff Moe
|
||||
* Josh Daniels
|
||||
* Kaile Riser
|
||||
@@ -59,9 +61,8 @@ thanks to everyone who contributed!
|
||||
* Stefan Krister
|
||||
* Stephane Schittly
|
||||
* Sven Mueller
|
||||
* Terrance Shaw
|
||||
* Thomas Hatley
|
||||
* Timeshell.ca
|
||||
* Trent Shumay
|
||||
|
||||
and 1041 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
and 1098 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
|
||||
@@ -31,7 +31,7 @@ Printer State
|
||||
* - ``flags``
|
||||
- 1
|
||||
- Printer state flags
|
||||
- A couple of boolean printer state flags
|
||||
- A few boolean printer state flags
|
||||
* - ``flags.operational``
|
||||
- 1
|
||||
- Boolean
|
||||
|
||||
@@ -54,6 +54,12 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``:
|
||||
# Time to live for the repository cache
|
||||
repository_ttl: 1440
|
||||
|
||||
# The URL of the plugin notices feed to use
|
||||
notices: http://plugins.octoprint.org/notices.json
|
||||
|
||||
# Time to live for the notices feed cache
|
||||
notices_ttl: 360
|
||||
|
||||
# Additional arguments to use with pip. Defaults to unset,
|
||||
# you normally shouldn't need to modify this
|
||||
pip_args: --some --additional --pip --arguments
|
||||
@@ -76,6 +82,36 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``:
|
||||
- hidden
|
||||
- plugins
|
||||
|
||||
.. _sec-bundledplugins-pluginmanager-hooks:
|
||||
|
||||
Hooks
|
||||
-----
|
||||
|
||||
.. _sec-bundledplugins-pluginmanager-hooks-reconnect_hooks:
|
||||
|
||||
octoprint.plugin.pluginmanager.reconnect_hooks
|
||||
++++++++++++++++++++++++++++++++++++++++++++++
|
||||
|
||||
.. py:function:: reconnect_hooks_hook(*args, **kwargs)
|
||||
|
||||
Returns additional hooks defined by the plugin for which the plugin manager
|
||||
should display the "You should reconnect to your printer" message on plugin
|
||||
install/uninstall/enabling/disabling.
|
||||
|
||||
Handlers should return a Python list containing the affected hook names.
|
||||
|
||||
**Example**
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def reconnect_hooks_hook(*args, **kwargs):
|
||||
return ["octoprint.plugin.exampleplugin.some_custom_hook",
|
||||
"octoprint.plugin.exampleplugin.some_other_custom_hook"]
|
||||
|
||||
__plugin_hooks__ = {
|
||||
"octoprint.plugin.pluginmanager.reconnect_hooks": reconnect_hooks_hook
|
||||
}
|
||||
|
||||
.. _sec-bundledplugins-pluginmanager-sourcecode:
|
||||
|
||||
Source Code
|
||||
|
||||
@@ -188,6 +188,16 @@ Version checks
|
||||
* ``repo``: (mandatory) Github repository to check
|
||||
* ``branch``: Branch of the Github repository to check, defaults to
|
||||
``master`` if not set.
|
||||
* ``current``: Current commit hash. Will be updated automatically.
|
||||
|
||||
* ``bitbucket_commit``: Checks against commits pushed to Bitbucket. Additional
|
||||
config parameters:
|
||||
|
||||
* ``user``: (mandatory) Bitbucket user the repository to check belongs to
|
||||
* ``repo``: (mandatory) Bitbucket repository to check
|
||||
* ``branch``: Branch of the Bitbucket repository to check, defaults to
|
||||
``master`` if not set.
|
||||
* ``current``: Current commit hash. Will be updated automatically.
|
||||
|
||||
* ``git_commit``: Checks a local git repository for new commits on its
|
||||
configured remote. Additional config parameters:
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ 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 = ['codeblockext', 'onlineinclude', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain',
|
||||
'sphinx.ext.napoleon']
|
||||
'sphinx.ext.napoleon', 'sphinxcontrib.mermaid']
|
||||
todo_include_todos = True
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
|
||||
@@ -943,8 +943,8 @@ Use the following settings to configure the server:
|
||||
* ``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.
|
||||
`into OctoPrint's wiki <https://github.com/foosel/OctoPrint/wiki/Reverse-proxy-configuration-examples>`_ for some
|
||||
examples on how to configure this.
|
||||
|
||||
.. _sec-configuration-config_yaml-slicing:
|
||||
|
||||
|
||||
@@ -477,6 +477,15 @@ PositionUpdate
|
||||
* ``t``: last tool selected *through OctoPrint*
|
||||
* ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint*
|
||||
|
||||
ToolChange
|
||||
A tool change command was sent to the printer. The payload contains the former current tool index and the
|
||||
new current tool index.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``old``: old tool index
|
||||
* ``new``: new tool index
|
||||
|
||||
Timelapses
|
||||
----------
|
||||
|
||||
|
||||
@@ -13,11 +13,19 @@ Unless :ref:`configured otherwise <sec-configuration-config_yaml-folder>`, OctoP
|
||||
the ``scripts/gcode`` folder in OctoPrint configuration directory (per default ``~/.octoprint`` on Linux, ``%APPDATA%\OctoPrint``
|
||||
on Windows and ``~/Library/Application Support/OctoPrint`` on MacOS).
|
||||
|
||||
These GCODE scripts are backed by the templating engine `Jinja2 <http://jinja.pocoo.org/>`_, allowing more than just
|
||||
These GCODE scripts are backed by the templating engine Jinja2, allowing more than just
|
||||
simple "send-as-is" scripts but making use of a full blown templating language in order to create your scripts. To
|
||||
this end, OctoPrint injects a couple of variables into the :ref:`template rendering context <sec-features-gcode_scripts-context>`
|
||||
this end, OctoPrint injects some variables into the :ref:`template rendering context <sec-features-gcode_scripts-context>`
|
||||
as described below.
|
||||
|
||||
You can find the docs on the Jinja templating engine as used in OctoPrint at `jinja.octoprint.org <http://jinja.octoprint.org/templates.html>`_.
|
||||
|
||||
.. note::
|
||||
|
||||
Due to backwards compatibility issues with Jinja versions 2.9+, OctoPrint currently only supports Jinja 2.8. For this
|
||||
reason use the template documentation at `jinja.octoprint.org <http://jinja.octoprint.org/templates.html>`_ instead of the
|
||||
documentation of current stable Jinja versions.
|
||||
|
||||
.. _sec-features-gcode_scripts-predefined:
|
||||
|
||||
Predefined Scripts
|
||||
@@ -60,23 +68,35 @@ All GCODE scripts have access to the following template variables through the te
|
||||
|
||||
* ``printer_profile``: The currently selected Printer Profile, including
|
||||
information such as the extruder count, the build volume size, the filament diameter etc.
|
||||
* ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!)
|
||||
* ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!).
|
||||
Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
|
||||
current tool ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no
|
||||
position could be retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)!
|
||||
* ``last_temperature``: Last actual and target temperature reported for all available tools and if available the
|
||||
heated bed. This is a dictionary of key-value pairs. The keys are the indices of the available tools (``0``, ``1``,
|
||||
...) and ``b`` for the heated bed. The values are a dictionary consisting of ``actual`` and ``target`` keys mapped
|
||||
to the corresponding temperature in degrees celsius. Note that not all tools your printer has must necessarily be
|
||||
present here, neither must the heated bed - it depends on whether OctoPrint has values for a tool or the bed. Also
|
||||
note that ``actual`` and ``target`` might be ``None``.
|
||||
* ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type``
|
||||
and ``script.name`` respectively.
|
||||
|
||||
There are a couple of additional template variables available for the following specific scripts:
|
||||
There are a few additional template variables available for the following specific scripts:
|
||||
|
||||
* ``afterPrintPaused`` and ``beforePrintResumed``
|
||||
|
||||
* ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. Consists
|
||||
of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and current tool
|
||||
``t`` taken from commands sent through OctoPrint.
|
||||
* ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. See
|
||||
``last_position`` above for the structure to expect here.
|
||||
* ``pause_temperature``: Last known temperature values when the print was paused. See ``last_temperature`` above
|
||||
for the structure to expect here.
|
||||
|
||||
* ``afterPrintCancelled``
|
||||
|
||||
* ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled.
|
||||
Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and
|
||||
current tool ``t`` taken from commands sent through OctoPrint.
|
||||
See ``last_position`` above for the structure to expect here.
|
||||
* ``cancel_temperature``: Last known temperature values when the print was cancelled. See ``last_temperature`` above
|
||||
for the structure to expect here.
|
||||
|
||||
|
||||
.. warning::
|
||||
|
||||
@@ -150,6 +170,7 @@ to 0 if a heated bed is configured.
|
||||
|
||||
.. seealso::
|
||||
|
||||
`Jinja Template Designer Documentation <http://jinja.pocoo.org/docs/dev/templates/>`_
|
||||
`Jinja Template Designer Documentation <http://jinja.octoprint.org/templates.html>`_
|
||||
Jinja's Template Designer Documentation describes the syntax and semantics of the template language used
|
||||
also by OctoPrint's GCODE scripts.
|
||||
also by OctoPrint's GCODE scripts. Linked here are the docs for Jinja 2.8.1, which OctoPrint still
|
||||
relies on for backwards compatibility reasons.
|
||||
@@ -20,7 +20,7 @@ development environment::
|
||||
$ virtualenv venv
|
||||
[...]
|
||||
$ source venv/bin/activate
|
||||
(venv) $ pip install -e[develop]
|
||||
(venv) $ pip install -e .[develop]
|
||||
[...]
|
||||
(venv) $ octoprint --help
|
||||
Usage: octoprint [OPTIONS] COMMAND [ARGS]...
|
||||
@@ -41,7 +41,15 @@ development environment::
|
||||
|
||||
[...]
|
||||
|
||||
We'll start at the most basic form a plugin can take - just a couple of simple lines of Python code:
|
||||
.. important::
|
||||
|
||||
This tutorial assumes you are running OctoPrint 1.3.0 and up. Please make sure your version of
|
||||
OctoPrint is up to date before proceeding. If you did a fresh checkout, that should already
|
||||
be the case but if not you might have to update first. You can check your version of OctoPrint
|
||||
by running ``octoprint --version`` or by taking a look into the lower left corner in OctoPrint's
|
||||
web interface.
|
||||
|
||||
We'll start at the most basic form a plugin can take - just a few simple lines of Python code:
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
@@ -108,7 +116,7 @@ used :func:`~octoprint.plugin.StartupPlugin.on_startup` instead, in which case o
|
||||
up and ready to serve requests.
|
||||
|
||||
You'll also note that we are using ``self._logger`` for logging. Where did that one come from? OctoPrint's plugin system
|
||||
injects :ref:`a couple of useful objects <sec-plugins-mixins-injectedproperties>` into our plugin implementation classes,
|
||||
injects :ref:`a some useful objects <sec-plugins-mixins-injectedproperties>` into our plugin implementation classes,
|
||||
one of those being a fully instantiated `python logger <https://docs.python.org/2/library/logging.html>`_ ready to be
|
||||
used by your plugin. As you can see in the log output above, that logger uses the namespace ``octoprint.plugins.helloworld``
|
||||
for our little plugin here, or more generally ``octoprint.plugins.<plugin identifier>``.
|
||||
@@ -482,7 +490,7 @@ Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this:
|
||||
|
||||
OctoPrint injects the template variables that your plugin defines prefixed with ``plugin_<plugin identifier>_`` into
|
||||
the template renderer, so your ``url`` got turned into ``plugin_helloworld_url`` which you can now use as a simple
|
||||
`Jinja2 Variable <http://jinja.pocoo.org/docs/dev/templates/#variables>`_ in your plugin's template.
|
||||
`Jinja2 Variable <http://jinja.octoprint.org/templates.html#variables>`_ in your plugin's template.
|
||||
|
||||
Restart OctoPrint and shift-reload the page in your browser (to make sure you really get a fresh copy). The link should
|
||||
still work and point to the URL we defined as default.
|
||||
@@ -1070,8 +1078,14 @@ For some insight on how to create plugins that react to various events within Oc
|
||||
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.
|
||||
`official Plugin Repository <http://plugins.octoprint.org>`_ if you are looking for examples.
|
||||
|
||||
.. seealso::
|
||||
|
||||
`Jinja Template Designer Documentation <http://jinja.octoprint.org/templates.html>`_
|
||||
Jinja's Template Designer Documentation describes the syntax and semantics of the template language used
|
||||
by OctoPrint's frontend. Linked here are the docs for Jinja 2.8.1, which OctoPrint still
|
||||
relies on for backwards compatibility reasons [#f3]_.
|
||||
|
||||
.. rubric:: Footnotes
|
||||
|
||||
@@ -1084,3 +1098,7 @@ looking for examples.
|
||||
.. [#f2] 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.
|
||||
.. [#f3] Please always consult the Jinja documentation at `jinja.octoprint.org <http://jinja.octoprint.org>`_ instead of
|
||||
the current stable documentation available at Jinja's project page. The reason for that is that for backwards
|
||||
compatibility reasons OctoPrint currently sadly has to rely on an older version of Jinja. The documentation
|
||||
available at `jinja.octoprint.org <http://jinja.octoprint.org>`_ matches that older version.
|
||||
@@ -6,7 +6,7 @@ Helpers
|
||||
Helpers are methods that plugin can exposed to other plugins in order to make common functionality available on the
|
||||
system. They are registered with the OctoPrint plugin system through the use of the control property ``__plugin_helpers__``.
|
||||
|
||||
An example for providing a couple of helper functions to the system can be found in the
|
||||
An example for providing some helper functions to the system can be found in the
|
||||
`Discovery Plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery>`_,
|
||||
which provides it's SSDP browsing and Zeroconf browsing and publishing functions as helper methods.
|
||||
|
||||
|
||||
+20
-1
@@ -396,7 +396,8 @@ This describes actually four hooks:
|
||||
|
||||
* ``queuing``: This phase is triggered just before the command is added to the send queue of the communication layer. This
|
||||
corresponds to the moment a command is being read from a file that is currently being printed. Handlers
|
||||
may suppress or change commands or their command type here.
|
||||
may suppress or change commands or their command type here. This is the only phase that supports multi command
|
||||
expansion by having the handler return a list, see below for details.
|
||||
* ``queued``: This phase is triggered just after the command was added to the send queue of the communication layer.
|
||||
No manipulation is possible here anymore (returned values will be ignored).
|
||||
* ``sending``: This phase is triggered just before the command is actually being sent to the printer. Right afterwards
|
||||
@@ -450,6 +451,24 @@ This describes actually four hooks:
|
||||
should use this option.
|
||||
* A 2-tuple consisting of a rewritten version of the ``cmd`` and the ``cmd_type``, e.g. ``return "M105", "temperature_poll"``.
|
||||
Handlers which wish to rewrite both the command and the command type should use this option.
|
||||
* A list of any of the above to allow for expanding one command into
|
||||
many. The following example shows how any queued command could be turned into a sequence of a temperature query,
|
||||
line number reset, display of the ``gcode`` on the printer's display and finally the actual command (this example
|
||||
does not make a lot of sense to be quite honest):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
|
||||
if gcode or not cmd.startswith("@foo"):
|
||||
return
|
||||
|
||||
return [("M105", "temperature_poll"),
|
||||
("M110",),
|
||||
"M117 echo foo: {}".format(cmd)]
|
||||
|
||||
|
||||
Note: Only one command of a given ``cmd_type`` (other than None) may be queued at a time. Trying to rewrite the ``cmd_type``
|
||||
to one already in the queue will give an error.
|
||||
|
||||
**Example**
|
||||
|
||||
|
||||
@@ -299,6 +299,130 @@ on your view model, taking a list of all bound view models:
|
||||
});
|
||||
})
|
||||
|
||||
.. _sec-plugins-viewmodels-livecycle:
|
||||
|
||||
Lifecycle diagrams
|
||||
------------------
|
||||
|
||||
.. _sec-plugins-viewmodels-startup:
|
||||
|
||||
Web interface startup
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. mermaid::
|
||||
|
||||
sequenceDiagram
|
||||
participant Main
|
||||
participant onServerConnect
|
||||
participant fetchSettings
|
||||
participant bindViewModels
|
||||
participant DataUpdater
|
||||
participant LoginStateViewModel
|
||||
|
||||
Note right of DataUpdater: connectCallback = undefined
|
||||
|
||||
activate Main
|
||||
|
||||
Main->>+DataUpdater: connect
|
||||
Note right of DataUpdater: initialized = false
|
||||
DataUpdater-->>Main: ok
|
||||
deactivate Main
|
||||
DataUpdater->>DataUpdater: asynchronous connect to server...
|
||||
activate DataUpdater
|
||||
Note right of DataUpdater: store any callbacks instead of triggering (e.g. onServerConnect, fromHistoryData, fromCurrentData, ...)
|
||||
DataUpdater-X+Main: done
|
||||
deactivate DataUpdater
|
||||
deactivate DataUpdater
|
||||
|
||||
Main->>+DataUpdater: connectCallback = onServerConnect
|
||||
Note right of DataUpdater: connectCallback = onServerConnect
|
||||
DataUpdater-->>-Main: ok
|
||||
Main->>+onServerConnect: call
|
||||
onServerConnect->>+LoginStateViewModel: passiveLogin
|
||||
LoginStateViewModel-->>onServerConnect: ok
|
||||
onServerConnect-->>Main: ok
|
||||
deactivate onServerConnect
|
||||
deactivate Main
|
||||
|
||||
LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login
|
||||
Note over Main,LoginStateViewModel: Session available!
|
||||
LoginStateViewModel-X+onServerConnect: done
|
||||
deactivate LoginStateViewModel
|
||||
deactivate LoginStateViewModel
|
||||
|
||||
onServerConnect->>+DataUpdater: initialized
|
||||
Note right of DataUpdater: initialized = true
|
||||
DataUpdater->DataUpdater: trigger stored callbacks
|
||||
DataUpdater-->>-onServerConnect: ok
|
||||
onServerConnect-X+Main: done
|
||||
deactivate onServerConnect
|
||||
|
||||
Main->>+fetchSettings: call
|
||||
Note right of fetchSettings: trigger onStartup
|
||||
|
||||
fetchSettings-->>Main: ok
|
||||
deactivate Main
|
||||
|
||||
fetchSettings->>+fetchSettings: asynchronous settings fetch
|
||||
fetchSettings->>+bindViewModels: call
|
||||
|
||||
loop for each view model
|
||||
bindViewModels->bindViewModels: trigger onBeforeBinding
|
||||
bindViewModels->bindViewModels: trigger onBoundTo
|
||||
bindViewModels->bindViewModels: trigger onAfterBinding
|
||||
end
|
||||
|
||||
bindViewModels->bindViewModels: trigger onAllBound
|
||||
opt User is logged in
|
||||
bindViewModels->>+LoginStateViewModel: onAllBound
|
||||
LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn
|
||||
LoginStateViewModel-->>-bindViewModels: ok
|
||||
end
|
||||
bindViewModels->bindViewModels: trigger onStartupComplete
|
||||
bindViewModels-->>-fetchSettings: ok
|
||||
|
||||
deactivate fetchSettings
|
||||
deactivate fetchSettings
|
||||
|
||||
|
||||
.. _sec-plugins-viewmodels-reconnect:
|
||||
|
||||
Web interface reconnect
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. mermaid::
|
||||
|
||||
sequenceDiagram
|
||||
participant onServerConnect
|
||||
participant DataUpdater
|
||||
participant LoginStateViewModel
|
||||
|
||||
activate DataUpdater
|
||||
DataUpdater->>DataUpdater: call connectCallback
|
||||
DataUpdater->>+onServerConnect: call
|
||||
onServerConnect-->>DataUpdater: ok
|
||||
deactivate DataUpdater
|
||||
|
||||
onServerConnect->>+LoginStateViewModel: passiveLogin
|
||||
LoginStateViewModel-->>onServerConnect: ok
|
||||
deactivate onServerConnect
|
||||
LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login
|
||||
Note over onServerConnect,LoginStateViewModel: Session available!
|
||||
opt User is logged in
|
||||
LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn
|
||||
end
|
||||
|
||||
activate onServerConnect
|
||||
LoginStateViewModel-XonServerConnect: done
|
||||
deactivate LoginStateViewModel
|
||||
deactivate LoginStateViewModel
|
||||
|
||||
onServerConnect->>+DataUpdater: initialized
|
||||
DataUpdater->DataUpdater: trigger stored callbacks
|
||||
DataUpdater-->>onServerConnect: ok
|
||||
deactivate DataUpdater
|
||||
deactivate onServerConnect
|
||||
|
||||
.. seealso::
|
||||
|
||||
`OctoPrint's core viewmodels <https://github.com/foosel/OctoPrint/tree/devel/src/octoprint/static/js/app/viewmodels>`_
|
||||
|
||||
@@ -7,41 +7,99 @@ __copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the
|
||||
|
||||
|
||||
import codecs
|
||||
import urllib2
|
||||
import requests
|
||||
from contextlib import closing
|
||||
|
||||
from sphinx.directives import LiteralInclude, dedent_lines
|
||||
from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \
|
||||
nodes, set_source_info, parselinenos, logger, container_wrapper
|
||||
|
||||
if False:
|
||||
# For type annotation
|
||||
from typing import Any, List # NOQA
|
||||
|
||||
cache = dict()
|
||||
|
||||
class OnlineIncludeReader(LiteralIncludeReader):
|
||||
|
||||
def read_file(self, filename, location=None):
|
||||
# type: (unicode, Any) -> List[unicode]
|
||||
|
||||
global cache
|
||||
try:
|
||||
if filename in cache:
|
||||
lines = cache[filename]
|
||||
else:
|
||||
with closing(requests.get(filename, stream=True)) as r:
|
||||
r.encoding = self.encoding
|
||||
lines = r.text.splitlines(True)
|
||||
cache[filename] = lines
|
||||
|
||||
if 'tab-width' in self.options:
|
||||
lines = [line.expandtabs(self.options['tab-width']) for line in lines]
|
||||
|
||||
return lines
|
||||
except (IOError, OSError):
|
||||
raise IOError(_('Include file %r not found or reading it failed') % filename)
|
||||
except UnicodeError:
|
||||
raise UnicodeError(_('Encoding %r used for reading included file %r seems to '
|
||||
'be wrong, try giving an :encoding: option') %
|
||||
(self.encoding, filename))
|
||||
|
||||
|
||||
class OnlineIncludeDirective(LiteralInclude):
|
||||
|
||||
def read_with_encoding(self, filename, document, codec_info, encoding):
|
||||
global cache
|
||||
def run(self):
|
||||
# type: () -> List[nodes.Node]
|
||||
document = self.state.document
|
||||
if not document.settings.file_insertion_enabled:
|
||||
return [document.reporter.warning('File insertion disabled',
|
||||
line=self.lineno)]
|
||||
env = document.settings.env
|
||||
|
||||
# convert options['diff'] to absolute path
|
||||
if 'diff' in self.options:
|
||||
_, path = env.relfn2path(self.options['diff'])
|
||||
self.options['diff'] = path
|
||||
|
||||
f = None
|
||||
try:
|
||||
if not self.arguments[0] in cache:
|
||||
f = codecs.StreamReaderWriter(urllib2.urlopen(self.arguments[0]), codec_info[2],
|
||||
codec_info[3], 'strict')
|
||||
lines = f.readlines()
|
||||
cache[self.arguments[0]] = lines
|
||||
else:
|
||||
lines = cache[self.arguments[0]]
|
||||
location = self.state_machine.get_source_and_line(self.lineno)
|
||||
url = self.arguments[0]
|
||||
|
||||
reader = OnlineIncludeReader(url, self.options, env.config)
|
||||
text, lines = reader.read(location=location)
|
||||
|
||||
retnode = nodes.literal_block(text, text, source=url)
|
||||
set_source_info(self, retnode)
|
||||
if self.options.get('diff'): # if diff is set, set udiff
|
||||
retnode['language'] = 'udiff'
|
||||
elif 'language' in self.options:
|
||||
retnode['language'] = self.options['language']
|
||||
retnode['linenos'] = ('linenos' in self.options or
|
||||
'lineno-start' in self.options or
|
||||
'lineno-match' in self.options)
|
||||
retnode['classes'] += self.options.get('class', [])
|
||||
extra_args = retnode['highlight_args'] = {}
|
||||
if 'emphasize-lines' in self.options:
|
||||
hl_lines = parselinenos(self.options['emphasize-lines'], lines)
|
||||
if any(i >= lines for i in hl_lines):
|
||||
logger.warning('line number spec is out of range(1-%d): %r' %
|
||||
(lines, self.options['emphasize-lines']),
|
||||
location=location)
|
||||
extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines]
|
||||
extra_args['linenostart'] = reader.lineno_start
|
||||
|
||||
if 'caption' in self.options:
|
||||
caption = self.options['caption'] or self.arguments[0]
|
||||
retnode = container_wrapper(self, retnode, caption)
|
||||
|
||||
# retnode will be note_implicit_target that is linked from caption and numref.
|
||||
# when options['name'] is provided, it should be primary ID.
|
||||
self.add_name(retnode)
|
||||
|
||||
return [retnode]
|
||||
except Exception as exc:
|
||||
return [document.reporter.warning(str(exc), line=self.lineno)]
|
||||
|
||||
lines = dedent_lines(lines, self.options.get('dedent'))
|
||||
return lines
|
||||
except (IOError, OSError, urllib2.URLError):
|
||||
return [document.reporter.warning(
|
||||
'Include file %r not found or reading it failed' % self.arguments[0],
|
||||
line=self.lineno)]
|
||||
except UnicodeError:
|
||||
return [document.reporter.warning(
|
||||
'Encoding %r used for reading included file %r seems to '
|
||||
'be wrong, try giving an :encoding: option' %
|
||||
(encoding, self.arguments[0]))]
|
||||
finally:
|
||||
if f is not None:
|
||||
f.close()
|
||||
|
||||
def visit_onlineinclude(translator, node):
|
||||
translator.visit_literal_block(node)
|
||||
@@ -53,4 +111,4 @@ def setup(app):
|
||||
app.add_directive("onlineinclude", OnlineIncludeDirective)
|
||||
|
||||
handler = (visit_onlineinclude, depart_onlineinclude)
|
||||
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
|
||||
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
|
||||
@@ -3,7 +3,7 @@ description-file = README.md
|
||||
|
||||
[versioneer]
|
||||
VCS = git
|
||||
style = pep440-post
|
||||
style = pep440-tag
|
||||
versionfile_source = src/octoprint/_version.py
|
||||
versionfile_build = octoprint/_version.py
|
||||
tag_prefix =
|
||||
|
||||
@@ -45,7 +45,8 @@ INSTALL_REQUIRES = [
|
||||
"future>=0.15,<0.16",
|
||||
"scandir>=1.3,<1.4",
|
||||
"websocket-client>=0.40,<0.41",
|
||||
"python-dateutil>=2.6,<2.7"
|
||||
"python-dateutil>=2.6,<2.7",
|
||||
"wrapt>=1.10.10,<1.11"
|
||||
]
|
||||
|
||||
if sys.platform == "darwin":
|
||||
@@ -61,9 +62,10 @@ EXTRA_REQUIRES = dict(
|
||||
"ddt",
|
||||
|
||||
# Documentation dependencies
|
||||
"sphinx>=1.3,<1.4",
|
||||
"sphinx>=1.6,<1.7",
|
||||
"sphinxcontrib-httpdomain",
|
||||
"sphinx_rtd_theme",
|
||||
"sphinxcontrib-mermaid",
|
||||
"sphinx_bootstrap_theme",
|
||||
|
||||
# PyPi upload related
|
||||
"pypandoc"
|
||||
|
||||
@@ -12,12 +12,13 @@ import hashlib
|
||||
import os
|
||||
import yaml
|
||||
import uuid
|
||||
import wrapt
|
||||
|
||||
import logging
|
||||
from builtins import range, bytes
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import atomic_write, deprecated
|
||||
from octoprint.util import atomic_write, to_str, deprecated
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
|
||||
@@ -57,13 +58,13 @@ class UserManager(object):
|
||||
if not isinstance(user, SessionUser):
|
||||
user = SessionUser(user)
|
||||
|
||||
self._session_users_by_session[user.get_session()] = user
|
||||
self._session_users_by_session[user.session] = user
|
||||
|
||||
userid = user.get_id()
|
||||
if not userid in self._sessionids_by_userid:
|
||||
self._sessionids_by_userid[userid] = set()
|
||||
|
||||
self._sessionids_by_userid[userid].add(user.get_session())
|
||||
self._sessionids_by_userid[userid].add(user.session)
|
||||
|
||||
self._logger.debug("Logged in user: %r" % user)
|
||||
|
||||
@@ -80,7 +81,7 @@ class UserManager(object):
|
||||
return
|
||||
|
||||
userid = user.get_id()
|
||||
sessionid = user.get_session()
|
||||
sessionid = user.session
|
||||
|
||||
if userid in self._sessionids_by_userid:
|
||||
try:
|
||||
@@ -98,7 +99,7 @@ class UserManager(object):
|
||||
for session, user in self._session_users_by_session.items():
|
||||
if not isinstance(user, SessionUser):
|
||||
continue
|
||||
if user._created + (24 * 60 * 60) < time.time():
|
||||
if user.created + (24 * 60 * 60) < time.time():
|
||||
self.logout_user(user)
|
||||
|
||||
@staticmethod
|
||||
@@ -113,7 +114,7 @@ class UserManager(object):
|
||||
settings().set(["accessControl", "salt"], salt)
|
||||
settings().save()
|
||||
|
||||
return hashlib.sha512(password + salt).hexdigest()
|
||||
return hashlib.sha512(to_str(password, encoding="utf-8", errors="replace") + to_str(salt)).hexdigest()
|
||||
|
||||
def checkPassword(self, username, password):
|
||||
user = self.findUser(username)
|
||||
@@ -501,7 +502,7 @@ class FilebasedUserManager(UserManager):
|
||||
return None
|
||||
|
||||
def getAllUsers(self):
|
||||
return self._users.values()
|
||||
return map(lambda x: x.asDict(), self._users.values())
|
||||
|
||||
def hasBeenCustomized(self):
|
||||
return self._customized
|
||||
@@ -650,7 +651,7 @@ class User(UserMixin):
|
||||
@property
|
||||
@deprecated("is_user is deprecated, please use has_permissions", since="now")
|
||||
def is_user(self):
|
||||
return True
|
||||
return OctoPrintUserMethodReplacedByBooleanProperty("is_user", lambda: "user" in self._roles)
|
||||
|
||||
@property
|
||||
@deprecated("is_admin is deprecated, please use has_permissions", since="now")
|
||||
@@ -821,10 +822,7 @@ class User(UserMixin):
|
||||
return "User(id=%s,name=%s,active=%r,user=True,admin=%r,permissions=%s,groups=%s)" % (self.get_id(), self.get_name(), bool(self.is_active), self.has_permission(Permissions.ADMIN), self._permissions, self._groups)
|
||||
|
||||
|
||||
class AnonymousUser(User, AnonymousUserMixin):
|
||||
def __init__(self):
|
||||
from octoprint.server import groupManager
|
||||
User.__init__(self, "Guest", "", True, [], [groupManager.guests_group])
|
||||
class AnonymousUser(AnonymousUserMixin):
|
||||
|
||||
@property
|
||||
def is_anonymous(self):
|
||||
@@ -841,39 +839,34 @@ class AnonymousUser(User, AnonymousUserMixin):
|
||||
def check_password(self, passwordHash):
|
||||
return True
|
||||
|
||||
|
||||
class SessionUser(User):
|
||||
class SessionUser(wrapt.ObjectProxy):
|
||||
def __init__(self, user):
|
||||
self._user = user
|
||||
wrapt.ObjectProxy.__init__(self, user)
|
||||
|
||||
import string
|
||||
import random
|
||||
import time
|
||||
chars = string.ascii_uppercase + string.ascii_lowercase + string.digits
|
||||
self._session = "".join(random.choice(chars) for _ in range(10))
|
||||
self._created = time.time()
|
||||
self._self_session = "".join(random.choice(chars) for _ in range(10))
|
||||
self._self_created = time.time()
|
||||
|
||||
def __getattribute__(self, item):
|
||||
if item in ("get_session", "update_user", "_user", "_session", "_created"):
|
||||
return object.__getattribute__(self, item)
|
||||
else:
|
||||
return getattr(object.__getattribute__(self, "_user"), item)
|
||||
@property
|
||||
def session(self):
|
||||
return self._self_session
|
||||
|
||||
def __setattr__(self, item, value):
|
||||
if item in ("_user", "_session", "_created"):
|
||||
return object.__setattr__(self, item, value)
|
||||
else:
|
||||
return setattr(self._user, item, value)
|
||||
@property
|
||||
def created(self):
|
||||
return self._self_created
|
||||
|
||||
@deprecated("SessionUser.get_session() has been deprecated, use SessionUser.session instead", since="1.3.5")
|
||||
def get_session(self):
|
||||
return self._session
|
||||
return self.session
|
||||
|
||||
def update_user(self, user):
|
||||
self._user = user
|
||||
self.__wrapped__ = user
|
||||
|
||||
def __repr__(self):
|
||||
return "SessionUser(id=%s,name=%s,active=%r,user=True,admin=%r,session=%s,created=%s)" % (self.get_id(), self.get_name(), bool(self.is_active), self.has_permission(Permissions.ADMIN), self._session, self._created)
|
||||
|
||||
return "SessionUser({!r},session={},created={})".format(self.__wrapped__, self.session, self.created)
|
||||
|
||||
##~~ DummyUser object to use when accessControl is disabled
|
||||
|
||||
|
||||
@@ -160,11 +160,11 @@ def octo(ctx, **kwargs):
|
||||
"start|stop|restart\" is deprecated, please use "
|
||||
"\"octoprint daemon start|stop|restart\" from now on")
|
||||
|
||||
if sys.platform.startswith("linux") or sys.platform.startswith("freebsd"):
|
||||
if sys.platform == "win32" or sys.platform == "darwin":
|
||||
click.echo("Sorry, daemon mode is not supported under your operating system right now")
|
||||
else:
|
||||
from octoprint.cli.server import daemon_command
|
||||
ctx.invoke(daemon_command, command=daemon, **kwargs)
|
||||
else:
|
||||
click.echo("Sorry, daemon mode is not supported under your operating system right now")
|
||||
else:
|
||||
click.echo("Starting the server via \"octoprint\" is deprecated, "
|
||||
"please use \"octoprint serve\" from now on.")
|
||||
|
||||
+24
-16
@@ -79,30 +79,33 @@ def log_response(response, status_code=True, body=True, headers=False):
|
||||
|
||||
@client.command("get")
|
||||
@click.argument("path")
|
||||
@click.option("--timeout", type=float, default=None)
|
||||
@click.pass_context
|
||||
def get(ctx, path):
|
||||
def get(ctx, path, timeout):
|
||||
"""Performs a GET request against the specified server path."""
|
||||
r = ctx.obj.client.get(path)
|
||||
r = ctx.obj.client.get(path, timeout=timeout)
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("post_json")
|
||||
@click.argument("path")
|
||||
@click.argument("data", type=JsonStringParamType())
|
||||
@click.option("--timeout", type=float, default=None)
|
||||
@click.pass_context
|
||||
def post_json(ctx, path, data):
|
||||
def post_json(ctx, path, data, timeout):
|
||||
"""POSTs JSON data to the specified server path."""
|
||||
r = ctx.obj.client.post_json(path, data)
|
||||
r = ctx.obj.client.post_json(path, data, timeout=timeout)
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("patch_json")
|
||||
@click.argument("path")
|
||||
@click.argument("data", type=JsonStringParamType())
|
||||
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||
@click.pass_context
|
||||
def patch_json(ctx, path, data):
|
||||
def patch_json(ctx, path, data, timeout):
|
||||
"""PATCHes JSON data to the specified server path."""
|
||||
r = ctx.obj.client.patch(path, data, encoding="json")
|
||||
r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout)
|
||||
log_response(r)
|
||||
|
||||
|
||||
@@ -111,9 +114,10 @@ def patch_json(ctx, path, data):
|
||||
@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True))
|
||||
@click.option("--json", is_flag=True)
|
||||
@click.option("--yaml", is_flag=True)
|
||||
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||
@click.pass_context
|
||||
def post_from_file(ctx, path, file_path, json_flag, yaml_flag):
|
||||
"""POSTs JSON data to the specified server path."""
|
||||
def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
|
||||
"""POSTs JSON data to the specified server path, taking the data from the specified file."""
|
||||
if json_flag or yaml_flag:
|
||||
if json_flag:
|
||||
with open(file_path, "rb") as fp:
|
||||
@@ -123,12 +127,12 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag):
|
||||
with open(file_path, "rb") as fp:
|
||||
data = yaml.safe_load(fp)
|
||||
|
||||
r = ctx.obj.client.post_json(path, data)
|
||||
r = ctx.obj.client.post_json(path, data, timeout=timeout)
|
||||
else:
|
||||
with open(file_path, "rb") as fp:
|
||||
data = fp.read()
|
||||
|
||||
r = ctx.obj.client.post(path, data)
|
||||
r = ctx.obj.client.post(path, data, timeout=timeout)
|
||||
|
||||
log_response(r)
|
||||
|
||||
@@ -140,14 +144,15 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag):
|
||||
@click.option("--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int]))
|
||||
@click.option("--float", "-f", "float_params", multiple=True, nargs=2, type=click.Tuple([unicode, float]))
|
||||
@click.option("--bool", "-b", "bool_params", multiple=True, nargs=2, type=click.Tuple([unicode, bool]))
|
||||
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||
@click.pass_context
|
||||
def command(ctx, path, command, str_params, int_params, float_params, bool_params):
|
||||
def command(ctx, path, command, str_params, int_params, float_params, bool_params, timeout):
|
||||
"""Sends a JSON command to the specified server path."""
|
||||
data = dict()
|
||||
params = str_params + int_params + float_params + bool_params
|
||||
for param in params:
|
||||
data[param[0]] = param[1]
|
||||
r = ctx.obj.client.post_command(path, command, additional=data)
|
||||
r = ctx.obj.client.post_command(path, command, additional=data, timeout=timeout)
|
||||
log_response(r, body=False)
|
||||
|
||||
|
||||
@@ -157,23 +162,26 @@ def command(ctx, path, command, str_params, int_params, float_params, bool_param
|
||||
@click.option("--parameter", "-P", "params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode]))
|
||||
@click.option("--file-name", type=click.STRING)
|
||||
@click.option("--content-type", type=click.STRING)
|
||||
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||
@click.pass_context
|
||||
def upload(ctx, path, file_path, params, file_name, content_type):
|
||||
def upload(ctx, path, file_path, params, file_name, content_type, timeout):
|
||||
"""Uploads the specified file to the specified server path."""
|
||||
data = dict()
|
||||
for param in params:
|
||||
data[param[0]] = param[1]
|
||||
|
||||
r = ctx.obj.client.upload(path, file_path, additional=data, file_name=file_name, content_type=content_type)
|
||||
r = ctx.obj.client.upload(path, file_path,
|
||||
additional=data, file_name=file_name, content_type=content_type, timeout=timeout)
|
||||
log_response(r)
|
||||
|
||||
|
||||
@client.command("delete")
|
||||
@click.argument("path")
|
||||
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
|
||||
@click.pass_context
|
||||
def delete(ctx, path):
|
||||
def delete(ctx, path, timeout):
|
||||
"""Sends a DELETE request to the specified server path."""
|
||||
r = ctx.obj.client.delete(path)
|
||||
r = ctx.obj.client.delete(path, timeout=timeout)
|
||||
log_response(r)
|
||||
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
|
||||
|
||||
import click
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
class OctoPrintDevelCommands(click.MultiCommand):
|
||||
"""
|
||||
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
|
||||
@@ -204,7 +206,7 @@ class OctoPrintDevelCommands(click.MultiCommand):
|
||||
click.echo("This doesn't look like an OctoPrint plugin folder")
|
||||
sys.exit(1)
|
||||
|
||||
self.command_caller.call([sys.executable, "setup.py", "develop"], cwd=path)
|
||||
self.command_caller.call([sys.executable, "-m", "pip", "install", "-e", "."], cwd=path)
|
||||
|
||||
return command
|
||||
|
||||
|
||||
@@ -150,8 +150,8 @@ def serve_command(ctx, **kwargs):
|
||||
allow_root, logging, verbosity, safe_mode)
|
||||
|
||||
|
||||
if sys.platform.startswith("linux") or sys.platform.startswith("freebsd"):
|
||||
# we only support daemon mode under Linux and FreeBSD for now
|
||||
if sys.platform != "win32" and sys.platform != "darwin":
|
||||
# we do not support daemon mode under windows or macosx
|
||||
|
||||
@server_commands.command(name="daemon")
|
||||
@server_options
|
||||
|
||||
@@ -84,6 +84,7 @@ class Events(object):
|
||||
EJECT = "Eject"
|
||||
E_STOP = "EStop"
|
||||
POSITION_UPDATE = "PositionUpdate"
|
||||
TOOL_CHANGE = "ToolChange"
|
||||
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
|
||||
|
||||
# Timelapse
|
||||
@@ -376,7 +377,7 @@ class CommandTrigger(GenericEventListener):
|
||||
|
||||
def _processCommand(self, command, payload):
|
||||
"""
|
||||
Performs string substitutions in the command string based on a couple of current parameters.
|
||||
Performs string substitutions in the command string based on a few current parameters.
|
||||
|
||||
The following substitutions are currently supported:
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
|
||||
ContentTypeDetector = namedtuple("ContentTypeDetector", "extensions, detector")
|
||||
|
||||
|
||||
@@ -19,8 +19,6 @@ import time
|
||||
from octoprint.events import Events, eventManager
|
||||
from octoprint.settings import settings
|
||||
|
||||
import octoprint.util.gcodeInterpreter as gcodeInterpreter
|
||||
|
||||
|
||||
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")):
|
||||
"""
|
||||
@@ -305,39 +303,95 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
* The extruded volume in cm³
|
||||
"""
|
||||
|
||||
def _do_analysis(self, high_priority=False):
|
||||
try:
|
||||
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
|
||||
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
|
||||
if throttle > 0:
|
||||
def throttle_callback(filePos, readBytes):
|
||||
if filePos % throttle_lines == 0:
|
||||
# only apply throttle every 100 lines
|
||||
time.sleep(throttle)
|
||||
else:
|
||||
throttle_callback = None
|
||||
def __init__(self, finished_callback):
|
||||
AbstractAnalysisQueue.__init__(self, finished_callback)
|
||||
|
||||
self._gcode = gcodeInterpreter.gcode()
|
||||
self._gcode.load(self._current.absolute_path, self._current.printer_profile, throttle=throttle_callback)
|
||||
self._aborted = False
|
||||
self._reenqueue = False
|
||||
|
||||
def _do_analysis(self, high_priority=False):
|
||||
import sarge
|
||||
import sys
|
||||
import yaml
|
||||
|
||||
try:
|
||||
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \
|
||||
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
|
||||
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
|
||||
max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"])
|
||||
g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"])
|
||||
speedx = self._current.printer_profile["axes"]["x"]["speed"]
|
||||
speedy = self._current.printer_profile["axes"]["y"]["speed"]
|
||||
offsets = self._current.printer_profile["extruder"]["offsets"]
|
||||
|
||||
interpreter = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "util", "gcodeInterpreter.py"))
|
||||
command = [sys.executable, interpreter, "--speed-x={}".format(speedx), "--speed-y={}".format(speedy),
|
||||
"--max-t={}".format(max_extruders), "--throttle={}".format(throttle),
|
||||
"--throttle-lines={}".format(throttle_lines)]
|
||||
for offset in offsets[1:]:
|
||||
command += ["--offset", str(offset[0]), str(offset[1])]
|
||||
if g90_extruder:
|
||||
command += ["--g90-extruder"]
|
||||
command.append(self._current.absolute_path)
|
||||
|
||||
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
|
||||
|
||||
self._aborted = False
|
||||
p = sarge.run(command, async=True, stdout=sarge.Capture())
|
||||
|
||||
while len(p.commands) == 0:
|
||||
# somewhat ugly... we can't use wait_events because
|
||||
# the events might not be all set if an exception
|
||||
# by sarge is triggered within the async process
|
||||
# thread
|
||||
time.sleep(0.01)
|
||||
|
||||
# by now we should have a command, let's wait for its
|
||||
# process to have been prepared
|
||||
p.commands[0].process_ready.wait()
|
||||
|
||||
if not p.commands[0].process:
|
||||
# the process might have been set to None in case of any exception
|
||||
raise RuntimeError(u"Error while trying to run command {}".format(" ".join(command)))
|
||||
|
||||
try:
|
||||
# let's wait for stuff to finish
|
||||
while p.returncode is None:
|
||||
if self._aborted:
|
||||
# oh, we shall abort, let's do so!
|
||||
p.commands[0].terminate()
|
||||
raise AnalysisAborted(reenqueue=self._reenqueue)
|
||||
|
||||
# else continue
|
||||
p.commands[0].poll()
|
||||
finally:
|
||||
p.close()
|
||||
|
||||
output = p.stdout.text
|
||||
self._logger.debug("Got output: {!r}".format(output))
|
||||
|
||||
if not "RESULTS:" in output:
|
||||
raise RuntimeError("No analysis result found")
|
||||
|
||||
_, output = output.split("RESULTS:")
|
||||
analysis = yaml.safe_load(output)
|
||||
|
||||
result = dict()
|
||||
result["printingArea"] = self._gcode.printing_area
|
||||
result["dimensions"] = self._gcode.dimensions
|
||||
if self._gcode.totalMoveTimeMinute:
|
||||
result["estimatedPrintTime"] = self._gcode.totalMoveTimeMinute * 60
|
||||
if self._gcode.extrusionAmount:
|
||||
result["printingArea"] = analysis["printing_area"]
|
||||
result["dimensions"] = analysis["dimensions"]
|
||||
if analysis["total_time"]:
|
||||
result["estimatedPrintTime"] = analysis["total_time"] * 60
|
||||
if analysis["extrusion_length"]:
|
||||
result["filament"] = dict()
|
||||
for i in range(len(self._gcode.extrusionAmount)):
|
||||
for i in range(len(analysis["extrusion_length"])):
|
||||
result["filament"]["tool%d" % i] = {
|
||||
"length": self._gcode.extrusionAmount[i],
|
||||
"volume": self._gcode.extrusionVolume[i]
|
||||
"length": analysis["extrusion_length"][i],
|
||||
"volume": analysis["extrusion_volume"][i]
|
||||
}
|
||||
return result
|
||||
except gcodeInterpreter.AnalysisAborted as ex:
|
||||
raise AnalysisAborted(reenqueue=ex.reenqueue)
|
||||
finally:
|
||||
self._gcode = None
|
||||
|
||||
def _do_abort(self, reenqueue=True):
|
||||
if self._gcode:
|
||||
self._gcode.abort(reenqueue=reenqueue)
|
||||
self._aborted = True
|
||||
self._reenqueue = reenqueue
|
||||
@@ -20,6 +20,8 @@ from octoprint.util import atomic_write
|
||||
from contextlib import contextmanager
|
||||
from copy import deepcopy
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
import octoprint.filemanager
|
||||
|
||||
from octoprint.util import is_hidden_path
|
||||
@@ -669,16 +671,9 @@ class LocalFileStorage(StorageInterface):
|
||||
# save the file's hash to the metadata of the folder
|
||||
file_hash = self._create_hash(file_path)
|
||||
metadata = self._get_metadata_entry(path, name, default=dict())
|
||||
metadata_dirty = False
|
||||
if not "hash" in metadata or metadata["hash"] != file_hash:
|
||||
metadata["hash"] = file_hash
|
||||
metadata_dirty = True
|
||||
if "analysis" in metadata:
|
||||
del metadata["analysis"]
|
||||
metadata_dirty = True
|
||||
|
||||
if metadata_dirty:
|
||||
self._update_metadata_entry(path, name, metadata)
|
||||
# hash changed -> throw away old metadata
|
||||
self._update_metadata_entry(path, name, dict(hash=file_hash))
|
||||
|
||||
# process any links that were also provided for adding to the file
|
||||
if not links:
|
||||
|
||||
@@ -104,7 +104,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
|
||||
UiPlugin]
|
||||
|
||||
if plugin_restart_needing_hooks is None:
|
||||
plugin_restart_needing_hooks = ["octoprint.server.http"]
|
||||
plugin_restart_needing_hooks = ["octoprint.server.http.*",
|
||||
"octoprint.printer.factory"]
|
||||
|
||||
if plugin_obsolete_hooks is None:
|
||||
plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"]
|
||||
@@ -239,7 +240,7 @@ class PluginSettings(object):
|
||||
"""
|
||||
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
|
||||
It provides some 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
|
||||
@@ -263,13 +264,17 @@ class PluginSettings(object):
|
||||
:returns: The retrieved settings value.
|
||||
:rtype: object
|
||||
|
||||
.. method:: get_int(path)
|
||||
.. method:: get_int(path, min=None, max=None)
|
||||
|
||||
Like :func:`get` but tries to convert the retrieved value to ``int``.
|
||||
Like :func:`get` but tries to convert the retrieved value to ``int``. If ``min`` is provided and the retrieved
|
||||
value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if
|
||||
the value is greater than it.
|
||||
|
||||
.. method:: get_float(path)
|
||||
.. method:: get_float(path, min=None, max=None)
|
||||
|
||||
Like :func:`get` but tries to convert the retrieved value to ``float``.
|
||||
Like :func:`get` but tries to convert the retrieved value to ``float``. If ``min`` is provided and the retrieved
|
||||
value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if
|
||||
the value is greater than it.
|
||||
|
||||
.. method:: get_boolean(path)
|
||||
|
||||
@@ -285,13 +290,19 @@ class PluginSettings(object):
|
||||
: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)
|
||||
.. method:: set_int(path, value, force=False, min=None, max=None)
|
||||
|
||||
Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it.
|
||||
If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal
|
||||
to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than
|
||||
that, ``max`` if greater than that) will be set instead.
|
||||
|
||||
.. method:: set_float(path, value, force=False)
|
||||
.. method:: set_float(path, value, force=False, min=None, max=None)
|
||||
|
||||
Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it.
|
||||
If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal
|
||||
to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than
|
||||
that, ``max`` if greater than that) will be set instead.
|
||||
|
||||
.. method:: set_boolean(path, value, force=False)
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ import os
|
||||
import imp
|
||||
from collections import defaultdict, namedtuple, OrderedDict
|
||||
import logging
|
||||
import fnmatch
|
||||
|
||||
import pkg_resources
|
||||
import pkginfo
|
||||
@@ -571,6 +572,10 @@ class PluginManager(object):
|
||||
key = entry.name
|
||||
elif entry.is_file() and entry.name.endswith(".py"):
|
||||
key = entry.name[:-3] # strip off the .py extension
|
||||
if key.startswith("__"):
|
||||
# might be an __init__.py in our plugins folder, or something else we don't want
|
||||
# to handle
|
||||
continue
|
||||
else:
|
||||
continue
|
||||
|
||||
@@ -942,45 +947,107 @@ class PluginManager(object):
|
||||
return plugin.needs_restart or self.has_restart_needing_implementation(plugin) or self.has_restart_needing_hooks(plugin)
|
||||
|
||||
def has_restart_needing_implementation(self, plugin):
|
||||
if not plugin.implementation:
|
||||
return False
|
||||
|
||||
return isinstance(plugin.implementation, RestartNeedingPlugin)
|
||||
return self.has_any_of_mixins(plugin, RestartNeedingPlugin)
|
||||
|
||||
def has_restart_needing_hooks(self, plugin):
|
||||
if not plugin.hooks:
|
||||
return False
|
||||
|
||||
hooks = plugin.hooks.keys()
|
||||
for hook in hooks:
|
||||
if self.is_restart_needing_hook(hook):
|
||||
return True
|
||||
return False
|
||||
return self.has_any_of_hooks(plugin, self.plugin_restart_needing_hooks)
|
||||
|
||||
def has_obsolete_hooks(self, plugin):
|
||||
if not plugin.hooks:
|
||||
return False
|
||||
|
||||
hooks = plugin.hooks.keys()
|
||||
for hook in hooks:
|
||||
if self.is_obsolete_hook(hook):
|
||||
return True
|
||||
return False
|
||||
return self.has_any_of_hooks(plugin, self.plugin_obsolete_hooks)
|
||||
|
||||
def is_restart_needing_hook(self, hook):
|
||||
if self.plugin_restart_needing_hooks is None:
|
||||
return False
|
||||
|
||||
for h in self.plugin_restart_needing_hooks:
|
||||
if hook.startswith(h):
|
||||
return True
|
||||
|
||||
return False
|
||||
return self.hook_matches_hooks(hook, self.plugin_restart_needing_hooks)
|
||||
|
||||
def is_obsolete_hook(self, hook):
|
||||
if self.plugin_obsolete_hooks is None:
|
||||
return self.hook_matches_hooks(hook, self.plugin_obsolete_hooks)
|
||||
|
||||
@staticmethod
|
||||
def has_any_of_hooks(plugin, *hooks):
|
||||
"""
|
||||
Tests if the ``plugin`` contains any of the provided ``hooks``.
|
||||
|
||||
Uses :func:`octoprint.plugin.core.PluginManager.hook_matches_hooks`.
|
||||
|
||||
Args:
|
||||
plugin: plugin to test hooks for
|
||||
*hooks: hooks to test against
|
||||
|
||||
Returns:
|
||||
(bool): True if any of the plugin's hooks match the provided hooks,
|
||||
False otherwise.
|
||||
"""
|
||||
|
||||
if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)):
|
||||
hooks = hooks[0]
|
||||
|
||||
hooks = filter(lambda hook: hook is not None, hooks)
|
||||
if not hooks:
|
||||
return False
|
||||
return hook in self.plugin_obsolete_hooks
|
||||
if not plugin or not plugin.hooks:
|
||||
return False
|
||||
|
||||
plugin_hooks = plugin.hooks.keys()
|
||||
|
||||
return any(map(lambda hook: PluginManager.hook_matches_hooks(hook, *hooks),
|
||||
plugin_hooks))
|
||||
|
||||
@staticmethod
|
||||
def hook_matches_hooks(hook, *hooks):
|
||||
"""
|
||||
Tests if ``hook`` matches any of the provided ``hooks`` to test for.
|
||||
|
||||
``hook`` is expected to be an exact hook name.
|
||||
|
||||
``hooks`` is expected to be a list containing one or more hook names or
|
||||
patterns. That can be either an exact hook name or an
|
||||
:func:`fnmatch.fnmatch` pattern.
|
||||
|
||||
Args:
|
||||
hook: the hook to test
|
||||
hooks: the hook name patterns to test against
|
||||
|
||||
Returns:
|
||||
(bool): True if the ``hook`` matches any of the ``hooks``, False otherwise.
|
||||
|
||||
"""
|
||||
|
||||
if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)):
|
||||
hooks = hooks[0]
|
||||
|
||||
hooks = filter(lambda hook: hook is not None, hooks)
|
||||
if not hooks:
|
||||
return False
|
||||
if not hook:
|
||||
return False
|
||||
|
||||
return any(map(lambda h: fnmatch.fnmatch(hook, h),
|
||||
hooks))
|
||||
|
||||
@staticmethod
|
||||
def has_any_of_mixins(plugin, *mixins):
|
||||
"""
|
||||
Tests if the ``plugin`` has an implementation implementing any
|
||||
of the provided ``mixins``.
|
||||
|
||||
Args:
|
||||
plugin: plugin for which to check the implementation
|
||||
*mixins: mixins to test against
|
||||
|
||||
Returns:
|
||||
(bool): True if the plugin's implementation implements any of the
|
||||
provided mixins, False otherwise.
|
||||
"""
|
||||
|
||||
if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)):
|
||||
mixins = mixins[0]
|
||||
|
||||
mixins = filter(lambda mixin: mixin is not None, mixins)
|
||||
if not mixins:
|
||||
return False
|
||||
if not plugin or not plugin.implementation:
|
||||
return False
|
||||
|
||||
return isinstance(plugin.implementation, tuple(mixins))
|
||||
|
||||
def initialize_implementations(self, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None):
|
||||
for name, plugin in self.enabled_plugins.items():
|
||||
|
||||
@@ -23,6 +23,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
from .core import (Plugin, RestartNeedingPlugin, SortablePlugin)
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
class OctoPrintPlugin(Plugin):
|
||||
"""
|
||||
@@ -531,7 +532,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
provided request by calling :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` with the Flask
|
||||
`Request <http://flask.pocoo.org/docs/0.10/api/#flask.Request>`_ object as
|
||||
parameter. If you plugin returns `True` here, OctoPrint will next call
|
||||
:meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a couple of parameters like
|
||||
:meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a few parameters like
|
||||
- again - the Flask Request object and the render keyword arguments as
|
||||
used by the default OctoPrint web interface. For more information see below.
|
||||
|
||||
@@ -582,7 +583,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
it only gets re-rendered if the request demands that (by having no-cache headers set) or if
|
||||
the cache gets invalidated otherwise.
|
||||
|
||||
In order to be able to do that, the ``UiPlugin`` offers overriding a couple of cache specific
|
||||
In order to be able to do that, the ``UiPlugin`` offers overriding some cache specific
|
||||
methods used for figuring out the source files whose modification time to use for cache invalidation
|
||||
as well as override possibilities for ETag and LastModified calculation. Additionally there are
|
||||
methods to allow persisting call parameters to allow for preemptively caching your UI during
|
||||
@@ -742,7 +743,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin):
|
||||
OctoPrint's version, current ``UI_API_KEY``, tracked file paths and ``LastModified`` value).
|
||||
|
||||
Returns:
|
||||
basestring: An alternatively calculated ETag value. Ignored if ``None`` is returned (default).
|
||||
str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default).
|
||||
"""
|
||||
return None
|
||||
|
||||
@@ -1038,7 +1039,7 @@ class SimpleApiPlugin(OctoPrintPlugin):
|
||||
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
|
||||
and/or want to react to simple commands which boil down to a type of command and a few flat parameters
|
||||
supplied with it.
|
||||
|
||||
The simple API constructed by OctoPrint for you will be made available under ``/api/plugin/<plugin identifier>/``.
|
||||
@@ -1377,6 +1378,14 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
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.
|
||||
|
||||
|
||||
.. warning::
|
||||
|
||||
Make sure to protect sensitive information stored by your plugin that only logged in administrators (or users)
|
||||
should have access to via :meth:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths`. OctoPrint will
|
||||
return its settings on the REST API even to anonymous clients, but will filter out fields it know are restricted,
|
||||
therefore you **must** make sure that you specify sensitive information accordingly to limit access as required!
|
||||
|
||||
.. attribute:: _settings
|
||||
|
||||
The :class:`~octoprint.plugin.PluginSettings` instance to use for accessing the plugin's settings. Injected by
|
||||
@@ -1548,8 +1557,8 @@ class SettingsPlugin(OctoPrintPlugin):
|
||||
field="field"),
|
||||
path=dict(to=dict(never=dict(return="return"))))
|
||||
|
||||
def get_settings_restricted_path(self):
|
||||
return dict(admin=[["some", "admin_only", "path"], ["another", "admin_only", "path"],
|
||||
def get_settings_restricted_paths(self):
|
||||
return dict(admin=[["some", "admin_only", "path"], ["another", "admin_only", "path"],],
|
||||
user=[["some", "user_only", "path"],],
|
||||
never=[["path", "to", "never", "return"],])
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
# make our plugins testable
|
||||
@@ -41,7 +41,13 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
# StartupPlugin
|
||||
|
||||
def on_after_startup(self):
|
||||
self._fetch_all_channels()
|
||||
# decouple channel fetching from server startup
|
||||
def fetch_data():
|
||||
self._fetch_all_channels()
|
||||
|
||||
thread = threading.Thread(target=fetch_data)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
# SettingsPlugin
|
||||
|
||||
@@ -324,7 +330,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
url = config["url"]
|
||||
try:
|
||||
start = time.time()
|
||||
r = requests.get(url)
|
||||
r = requests.get(url, timeout=30)
|
||||
r.raise_for_status()
|
||||
self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start))
|
||||
except Exception as e:
|
||||
self._logger.exception(
|
||||
@@ -359,7 +366,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
return dict(title=entry["title"],
|
||||
title_without_tags=_strip_tags(entry["title"]),
|
||||
summary=entry["summary"],
|
||||
summary=_lazy_images(entry["summary"]),
|
||||
summary_without_images=_strip_images(entry["summary"]),
|
||||
published=published,
|
||||
link=entry["link"],
|
||||
@@ -374,8 +381,57 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
|
||||
|
||||
_image_tag_re = re.compile(r'<img.*?/?>')
|
||||
def _strip_images(text):
|
||||
"""
|
||||
>>> _strip_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>")
|
||||
u"<a href='test.html'>I'm a link</a> and this is an image: "
|
||||
>>> _strip_images(u"One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">")
|
||||
u'One and two and three and four '
|
||||
>>> _strip_images(u"No images here")
|
||||
u'No images here'
|
||||
"""
|
||||
return _image_tag_re.sub('', text)
|
||||
|
||||
def _replace_images(text, callback):
|
||||
"""
|
||||
>>> callback = lambda img: "foobar"
|
||||
>>> _replace_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", callback)
|
||||
u"<a href='test.html'>I'm a link</a> and this is an image: foobar"
|
||||
>>> _replace_images(u"One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", callback)
|
||||
u'One foobar and two foobar and three foobar and four foobar'
|
||||
"""
|
||||
result = text
|
||||
for match in _image_tag_re.finditer(text):
|
||||
tag = match.group(0)
|
||||
replaced = callback(tag)
|
||||
result = result.replace(tag, replaced)
|
||||
return result
|
||||
|
||||
_image_src_re = re.compile(r'src=(?P<quote>[\'"]*)(?P<src>.*?)(?P=quote)(?=\s+|>)')
|
||||
def _lazy_images(text, placeholder=None):
|
||||
"""
|
||||
>>> _lazy_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>")
|
||||
u'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
|
||||
>>> _lazy_images(u"<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", placeholder="ph.png")
|
||||
u'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="ph.png" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
|
||||
>>> _lazy_images(u"One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", placeholder="ph.png")
|
||||
u'One <img src="ph.png" data-src="one.jpg"> and two <img src="ph.png" data-src=\\'two.jpg\\' > and three <img src="ph.png" data-src=three.jpg> and four <img src="ph.png" data-src="four.png" alt="four">'
|
||||
>>> _lazy_images(u"No images here")
|
||||
u'No images here'
|
||||
"""
|
||||
if placeholder is None:
|
||||
# 1px transparent gif
|
||||
placeholder = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
|
||||
|
||||
def callback(img_tag):
|
||||
match = _image_src_re.search(img_tag)
|
||||
if match is not None:
|
||||
src = match.group("src")
|
||||
quote = match.group("quote")
|
||||
quoted_src = quote + src + quote
|
||||
img_tag = img_tag.replace(match.group(0), 'src="{}" data-src={}'.format(placeholder, quoted_src))
|
||||
return img_tag
|
||||
|
||||
return _replace_images(text, callback)
|
||||
|
||||
def _strip_tags(text):
|
||||
"""
|
||||
|
||||
@@ -40,7 +40,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.toggleButtonCss = function(data) {
|
||||
var icon = data.enabled ? "icon-circle" : "icon-circle-blank";
|
||||
var icon = data.enabled ? "fa fa-circle" : "fa fa-circle-o";
|
||||
var disabled = (self.enableToggle(data)) ? "" : " disabled";
|
||||
|
||||
return icon + disabled;
|
||||
@@ -143,6 +143,9 @@ $(function() {
|
||||
self.showAnnouncementDialog = function(channel) {
|
||||
if (!self.loginState.isAdmin()) return;
|
||||
|
||||
// lazy load images that still need lazy-loading
|
||||
$("#plugin_announcements_dialog_content article img").lazyload();
|
||||
|
||||
self.announcementDialogContent.scrollTop(0);
|
||||
|
||||
if (!self.announcementDialog.hasClass("in")) {
|
||||
@@ -255,22 +258,22 @@ $(function() {
|
||||
buttons: [{
|
||||
text: gettext("Later"),
|
||||
click: function(notice) {
|
||||
self.hiddenChannels.push(key);
|
||||
notice.remove();
|
||||
self.hiddenChannels.push(key);
|
||||
}
|
||||
}, {
|
||||
text: gettext("Mark read"),
|
||||
click: function(notice) {
|
||||
self.markRead(key, value.last);
|
||||
notice.remove();
|
||||
self.markRead(key, value.last);
|
||||
}
|
||||
}, {
|
||||
text: gettext("Read..."),
|
||||
addClass: "btn-primary",
|
||||
click: function(notice) {
|
||||
notice.remove();
|
||||
self.showAnnouncementDialog(key);
|
||||
self.markRead(key, value.last);
|
||||
notice.remove();
|
||||
}
|
||||
}]
|
||||
},
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
<div class="content" data-bind="html: $data.summary"></div>
|
||||
<div class="actions">
|
||||
<span class="articlelink"><small><a data-bind="text: $data.link, attr: {href: $data.link}" target="_blank" rel="noreferrer noopener"></a></small></span>
|
||||
<span class="markread"><small><a href="javascript:void(0)" data-bind="click: function() { $root.markRead($parent.key, $data.published) }"><i class="icon-eye-open"></i> {{ _('Mark as last read') }}</a></small></span>
|
||||
<span class="markread"><small><a href="javascript:void(0)" data-bind="click: function() { $root.markRead($parent.key, $data.published) }"><i class="fa fa-eye"></i> {{ _('Mark as last read') }}</a></small></span>
|
||||
</div>
|
||||
</article>
|
||||
<!-- /ko -->
|
||||
@@ -40,7 +40,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn configurelink" data-bind="click: configureAnnouncements"><i class="icon-wrench"></i></button>
|
||||
<button class="btn configurelink" data-bind="click: configureAnnouncements"><i class="fa fa-wrench"></i></button>
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,3 +1,3 @@
|
||||
<a id="navbar_show_announcements" class="pull-right" href="javascript:void(0)" data-bind="click: function() { showAnnouncementDialog(); }" title="{{ _('Announcements') }}">
|
||||
<i data-bind="css: {'icon-bell': !unread(), 'icon-bell-alt': unread()}"></i>
|
||||
<i class="fa" data-bind="css: {'fa-bell-o': !unread(), 'fa-bell': unread()}"></i>
|
||||
</a>
|
||||
@@ -32,4 +32,4 @@
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button class="btn btn-block" data-bind="click: $root.refreshAnnouncements"><i class="icon-refresh"></i> {{ _('Refresh Announcements') }}</button>
|
||||
<button class="btn btn-block" data-bind="click: $root.refreshAnnouncements"><i class="fa fa-refresh"></i> {{ _('Refresh Announcements') }}</button>
|
||||
@@ -49,9 +49,12 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
#~~ AssetPlugin API
|
||||
|
||||
def get_assets(self):
|
||||
return dict(
|
||||
js=["js/corewizard.js"]
|
||||
)
|
||||
if self.is_wizard_required():
|
||||
return dict(
|
||||
js=["js/corewizard.js"]
|
||||
)
|
||||
else:
|
||||
return dict()
|
||||
|
||||
#~~ WizardPlugin API
|
||||
|
||||
@@ -74,7 +77,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
return self._user_manager.enabled and not self._user_manager.hasBeenCustomized()
|
||||
|
||||
def _get_acl_wizard_details(self):
|
||||
return dict()
|
||||
return dict(required=self._is_acl_wizard_required())
|
||||
|
||||
def _get_acl_wizard_name(self):
|
||||
return gettext("Access Control")
|
||||
@@ -120,7 +123,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path)
|
||||
|
||||
def _get_webcam_wizard_details(self):
|
||||
return dict()
|
||||
return dict(required=self._is_webcam_wizard_required())
|
||||
|
||||
def _get_webcam_wizard_name(self):
|
||||
return gettext("Webcam & Timelapse")
|
||||
@@ -135,7 +138,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
return not (system_shutdown_command and system_restart_command and server_restart_command)
|
||||
|
||||
def _get_servercommands_wizard_details(self):
|
||||
return dict()
|
||||
return dict(required=self._is_servercommands_wizard_required())
|
||||
|
||||
def _get_servercommands_wizard_name(self):
|
||||
return gettext("Server Commands")
|
||||
@@ -146,7 +149,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
|
||||
return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1
|
||||
|
||||
def _get_printerprofile_wizard_details(self):
|
||||
return dict()
|
||||
return dict(required=self._is_printerprofile_wizard_required())
|
||||
|
||||
def _get_printerprofile_wizard_name(self):
|
||||
return gettext("Default Printer Profile")
|
||||
|
||||
@@ -11,6 +11,8 @@ $(function() {
|
||||
self.setup = ko.observable(false);
|
||||
self.decision = ko.observable();
|
||||
|
||||
self.required = false;
|
||||
|
||||
self.passwordMismatch = ko.pureComputed(function() {
|
||||
return self.password() != self.confirmedPassword();
|
||||
});
|
||||
@@ -72,6 +74,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onBeforeWizardTabChange = function(next, current) {
|
||||
if (!self.required) return true;
|
||||
|
||||
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_acl_") || self.setup()) {
|
||||
return true;
|
||||
}
|
||||
@@ -82,7 +86,13 @@ $(function() {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.acl && response.corewizard.details.acl.required;
|
||||
};
|
||||
|
||||
self.onWizardFinish = function() {
|
||||
if (!self.required) return;
|
||||
|
||||
if (!self.decision()) {
|
||||
return "reload";
|
||||
}
|
||||
@@ -94,7 +104,14 @@ $(function() {
|
||||
|
||||
self.settingsViewModel = parameters[0];
|
||||
|
||||
self.required = false;
|
||||
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.webcam && response.corewizard.details.webcam.required;
|
||||
};
|
||||
|
||||
self.onWizardFinish = function() {
|
||||
if (!self.required) return;
|
||||
if (self.settingsViewModel.webcam_streamUrl()
|
||||
|| (self.settingsViewModel.webcam_snapshotUrl() && self.settingsViewModel.webcam_ffmpegPath())) {
|
||||
return "reload";
|
||||
@@ -113,18 +130,29 @@ $(function() {
|
||||
|
||||
self.printerProfiles = parameters[0];
|
||||
|
||||
self.required = false;
|
||||
|
||||
self.editor = self.printerProfiles.createProfileEditor();
|
||||
self.editorLoaded = ko.observable(false);
|
||||
|
||||
self.onStartup = function() {
|
||||
self.onWizardDetails = function(response) {
|
||||
self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.printerprofile && response.corewizard.details.printerprofile.required;
|
||||
if (!self.required) return;
|
||||
|
||||
OctoPrint.printerprofiles.get("_default")
|
||||
.done(function(data) {
|
||||
self.editor.fromProfileData(data);
|
||||
self.editorLoaded(true);
|
||||
})
|
||||
.fail(function() {
|
||||
self.editor.fromProfileData();
|
||||
self.editorLoaded(true);
|
||||
});
|
||||
};
|
||||
|
||||
self.onWizardFinish = function() {
|
||||
if (!self.required) return;
|
||||
|
||||
OctoPrint.printerprofiles.update("_default", self.editor.toProfileData())
|
||||
.done(function() {
|
||||
self.printerProfiles.requestData();
|
||||
|
||||
@@ -17,6 +17,7 @@ import octoprint.slicing
|
||||
import octoprint.settings
|
||||
|
||||
from octoprint.util.paths import normalize as normalize_path
|
||||
from octoprint.util import to_unicode
|
||||
|
||||
from .profile import Profile
|
||||
from .profile import GcodeFlavors
|
||||
@@ -236,7 +237,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
self._save_profile(path, new_profile, allow_overwrite=allow_overwrite)
|
||||
|
||||
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None):
|
||||
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None,
|
||||
on_progress=None, on_progress_args=None, on_progress_kwargs=None):
|
||||
try:
|
||||
with self._job_mutex:
|
||||
if not profile_path:
|
||||
@@ -258,7 +260,10 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
if not on_progress_kwargs:
|
||||
on_progress_kwargs = dict()
|
||||
|
||||
self._cura_logger.info(u"### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path))
|
||||
self._cura_logger.info(u"### Slicing {} to {} using profile stored at {}"
|
||||
.format(to_unicode(model_path, errors="replace"),
|
||||
to_unicode(machinecode_path, errors="replace"),
|
||||
to_unicode(profile_path, errors="replace")))
|
||||
|
||||
executable = normalize_path(self._settings.get(["cura_engine"]))
|
||||
if not executable:
|
||||
@@ -293,7 +298,9 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
args += ["-s", "%s=%s" % (k, str(v))]
|
||||
args += ["-o", machinecode_path, model_path]
|
||||
|
||||
self._logger.info(u"Running %r in %s" % (" ".join(args), working_dir))
|
||||
self._logger.info(u"Running {!r} in {}".format(u" ".join(map(lambda x: to_unicode(x, errors="replace"),
|
||||
args)),
|
||||
working_dir))
|
||||
|
||||
import sarge
|
||||
p = sarge.run(args, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
@@ -314,7 +321,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
p.commands[0].poll()
|
||||
continue
|
||||
|
||||
line = octoprint.util.to_unicode(line, errors="replace")
|
||||
line = to_unicode(line, errors="replace")
|
||||
self._cura_logger.debug(line.strip())
|
||||
|
||||
if on_progress is not None:
|
||||
@@ -437,7 +444,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
command = self._slicing_commands[machinecode_path]
|
||||
if command is not None:
|
||||
command.terminate()
|
||||
self._logger.info(u"Cancelled slicing of %s" % machinecode_path)
|
||||
self._logger.info(u"Cancelled slicing of {}"
|
||||
.format(to_unicode(machinecode_path, errors="replace")))
|
||||
|
||||
def _load_profile(self, path):
|
||||
import yaml
|
||||
|
||||
@@ -7,7 +7,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
|
||||
import re
|
||||
|
||||
from builtins import range
|
||||
from past.builtins import basestring
|
||||
|
||||
class SupportLocationTypes(object):
|
||||
NONE = "none"
|
||||
|
||||
@@ -25,11 +25,35 @@ $(function() {
|
||||
self.profileAllowOverwrite = ko.observable(true);
|
||||
self.profileMakeDefault = ko.observable(false);
|
||||
|
||||
// make sure to update form data if any of the metadata changes
|
||||
self.profileName.subscribe(function() { self.copyProfileMetadata(); });
|
||||
self.profileDisplayName.subscribe(function() {
|
||||
if (self.profileDisplayName()) {
|
||||
self.placeholderName(self._sanitize(self.profileDisplayName()).toLowerCase());
|
||||
}
|
||||
self.copyProfileMetadata();
|
||||
});
|
||||
self.profileDescription.subscribe(function() { self.copyProfileMetadata(); });
|
||||
self.profileAllowOverwrite.subscribe(function() { self.copyProfileMetadata(); });
|
||||
self.profileMakeDefault.subscribe(function() { self.copyProfileMetadata(); });
|
||||
|
||||
self.unconfiguredCuraEngine = ko.observable();
|
||||
self.unconfiguredSlicingProfile = ko.observable();
|
||||
|
||||
self.uploadDialog = $("#settings_plugin_cura_import");
|
||||
self.uploadElement = $("#settings-cura-import");
|
||||
self.uploadButton = $("#settings-cura-import-start");
|
||||
self.uploadData = ko.observable(undefined);
|
||||
self.uploadBusy = ko.observable(false);
|
||||
|
||||
self.uploadEnabled = ko.pureComputed(function() {
|
||||
return self.fieldsEnabled();
|
||||
});
|
||||
self.fieldsEnabled = ko.pureComputed(function() {
|
||||
return self.uploadData() && !self.uploadBusy()
|
||||
&& (self.profileName() || self.placeholderName())
|
||||
&& (self.profileDisplayName() || self.placeholderDisplayName())
|
||||
&& (self.profileDescription() || self.placeholderDescription());
|
||||
});
|
||||
|
||||
self.profiles = new ItemListHelper(
|
||||
"plugin_cura_profiles",
|
||||
@@ -66,6 +90,53 @@ $(function() {
|
||||
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
|
||||
};
|
||||
|
||||
self.performUpload = function() {
|
||||
if (self.uploadData()) {
|
||||
self.uploadData().submit();
|
||||
}
|
||||
};
|
||||
|
||||
self.copyProfileMetadata = function(form) {
|
||||
form = form || (self.uploadData() ? self.uploadData().formData : {});
|
||||
|
||||
if (self.profileName() !== undefined) {
|
||||
form["name"] = self.profileName();
|
||||
} else if (self.placeholderName() !== undefined) {
|
||||
form["name"] = self.placeholderName();
|
||||
}
|
||||
|
||||
if (self.profileDisplayName() !== undefined) {
|
||||
form["displayName"] = self.profileDisplayName();
|
||||
} else if (self.placeholderDisplayName() !== undefined) {
|
||||
form["displayName"] = self.placeholderDisplayName();
|
||||
}
|
||||
|
||||
if (self.profileDescription() !== undefined) {
|
||||
form["description"] = self.profileDescription();
|
||||
} else if (self.placeholderDescription() !== undefined) {
|
||||
form["description"] = self.placeholderDescription();
|
||||
}
|
||||
|
||||
if (self.profileMakeDefault()) {
|
||||
form["default"] = true;
|
||||
}
|
||||
|
||||
return form;
|
||||
};
|
||||
|
||||
self.clearUpload = function() {
|
||||
self.uploadData(undefined);
|
||||
self.fileName(undefined);
|
||||
self.placeholderName(undefined);
|
||||
self.placeholderDisplayName(undefined);
|
||||
self.placeholderDescription(undefined);
|
||||
self.profileName(undefined);
|
||||
self.profileDisplayName(undefined);
|
||||
self.profileDescription(undefined);
|
||||
self.profileAllowOverwrite(true);
|
||||
self.profileMakeDefault(false);
|
||||
};
|
||||
|
||||
self.uploadElement.fileupload({
|
||||
dataType: "json",
|
||||
maxNumberOfFiles: 1,
|
||||
@@ -73,6 +144,11 @@ $(function() {
|
||||
headers: OctoPrint.getRequestHeaders(),
|
||||
add: function(e, data) {
|
||||
if (data.files.length == 0) {
|
||||
// no files? ignore
|
||||
return false;
|
||||
}
|
||||
if (self.uploadData()) {
|
||||
// data already defined? ignore (should never happen)
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -83,41 +159,22 @@ $(function() {
|
||||
self.placeholderDisplayName(name);
|
||||
self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000));
|
||||
|
||||
self.uploadButton.unbind("click");
|
||||
self.uploadButton.on("click", function() {
|
||||
var form = {
|
||||
allowOverwrite: self.profileAllowOverwrite()
|
||||
};
|
||||
var form = {
|
||||
allowOverwrite: self.profileAllowOverwrite()
|
||||
};
|
||||
data.formData = self.copyProfileMetadata(form);
|
||||
|
||||
if (self.profileName() !== undefined) {
|
||||
form["name"] = self.profileName();
|
||||
}
|
||||
if (self.profileDisplayName() !== undefined) {
|
||||
form["displayName"] = self.profileDisplayName();
|
||||
}
|
||||
if (self.profileDescription() !== undefined) {
|
||||
form["description"] = self.profileDescription();
|
||||
}
|
||||
if (self.profileMakeDefault()) {
|
||||
form["default"] = true;
|
||||
}
|
||||
|
||||
data.formData = form;
|
||||
data.submit();
|
||||
});
|
||||
self.uploadData(data);
|
||||
},
|
||||
submit: function(e, data) {
|
||||
self.copyProfileMetadata();
|
||||
self.uploadBusy(true);
|
||||
},
|
||||
done: function(e, data) {
|
||||
self.fileName(undefined);
|
||||
self.placeholderName(undefined);
|
||||
self.placeholderDisplayName(undefined);
|
||||
self.placeholderDescription(undefined);
|
||||
self.profileName(undefined);
|
||||
self.profileDisplayName(undefined);
|
||||
self.profileDescription(undefined);
|
||||
self.profileAllowOverwrite(true);
|
||||
self.profileMakeDefault(false);
|
||||
self.uploadBusy(false);
|
||||
self.clearUpload();
|
||||
|
||||
$("#settings_plugin_cura_import").modal("hide");
|
||||
self.uploadDialog.modal("hide");
|
||||
self.requestData();
|
||||
self.slicingViewModel.requestData();
|
||||
}
|
||||
@@ -160,12 +217,9 @@ $(function() {
|
||||
});
|
||||
};
|
||||
|
||||
self.showImportProfileDialog = function(makeDefault) {
|
||||
if (makeDefault == undefined) {
|
||||
makeDefault = _.filter(self.profiles.items(), function(profile) { profile.isdefault() }).length == 0;
|
||||
}
|
||||
self.profileMakeDefault(makeDefault);
|
||||
$("#settings_plugin_cura_import").modal("show");
|
||||
self.showImportProfileDialog = function() {
|
||||
self.clearUpload();
|
||||
self.uploadDialog.modal("show");
|
||||
};
|
||||
|
||||
self.testEnginePath = function() {
|
||||
@@ -207,7 +261,18 @@ $(function() {
|
||||
|
||||
self.onBeforeBinding = function () {
|
||||
self.settings = self.settingsViewModel.settings;
|
||||
//self.requestData();
|
||||
};
|
||||
|
||||
self.onAllBound = function() {
|
||||
self.uploadDialog.on("hidden", function(event) {
|
||||
if (event.target.id == "settings_plugin_cura_import") {
|
||||
self.clearUpload();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.onSettingsShown = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onSettingsHidden = function() {
|
||||
|
||||
@@ -20,31 +20,31 @@
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Identifier') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}, enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Name') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, attr: {placeholder: placeholderDisplayName}">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, valueUpdate: 'afterkeydown', attr: {placeholder: placeholderDisplayName}, enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Description') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}">
|
||||
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}, enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<label class="checkbox" data-bind="enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
|
||||
<input type="checkbox" data-bind="checked: profileMakeDefault"> {{ _('Make default profile') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<label class="checkbox" data-bind="enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
|
||||
<input type="checkbox" data-bind="checked: profileAllowOverwrite"> {{ _('Overwrite existing file') }}
|
||||
</label>
|
||||
</div>
|
||||
@@ -59,6 +59,6 @@
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
|
||||
<button class="btn btn-primary" id="settings-cura-import-start">{{ _('Confirm') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: performUpload, enable: uploadEnabled, css: {disabled: !uploadEnabled()}" id="settings-cura-import-start"><i class="fa fa-spinner fa-spin" data-bind="visible: uploadBusy"></i> {{ _('Confirm') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -12,10 +12,10 @@
|
||||
</thead>
|
||||
<tbody data-bind="foreach: profiles.paginatedItems">
|
||||
<tr data-bind="attr: {title: description}">
|
||||
<td class="settings_plugin_cura_profiles_key"><span class="icon-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
|
||||
<td class="settings_plugin_cura_profiles_key"><span class="fa fa-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
|
||||
<td class="settings_plugin_cura_profiles_name" data-bind="text: name"></td>
|
||||
<td class="settings_plugin_cura_profiles_actions">
|
||||
<a href="#" class="icon-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a> | <a href="#" class="icon-trash" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
|
||||
<a href="#" class="fa fa-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a> | <a href="#" class="fa fa-trash-o" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
|
||||
@@ -5,6 +5,7 @@ __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"
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
import octoprint.plugin
|
||||
import octoprint.plugin.core
|
||||
@@ -29,6 +30,7 @@ import pkg_resources
|
||||
import copy
|
||||
import dateutil.parser
|
||||
import time
|
||||
import threading
|
||||
|
||||
class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
@@ -40,10 +42,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar")
|
||||
|
||||
OPERATING_SYSTEMS = dict(windows=["win32"],
|
||||
linux=["linux2"],
|
||||
macos=["darwin"])
|
||||
linux=lambda x: x.startswith("linux"),
|
||||
macos=["darwin"],
|
||||
freebsd=lambda x: x.startswith("freebsd"))
|
||||
|
||||
pip_inapplicable_arguments = dict(uninstall=["--user"])
|
||||
PIP_INAPPLICABLE_ARGUMENTS = dict(uninstall=["--user"])
|
||||
|
||||
RECONNECT_HOOKS = ["octoprint.comm.protocol.*",]
|
||||
|
||||
def __init__(self):
|
||||
self._pending_enable = set()
|
||||
@@ -85,7 +90,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
##~~ StartupPlugin
|
||||
|
||||
def on_startup(self, host, port):
|
||||
def on_after_startup(self):
|
||||
from octoprint.logging.handlers import CleaningTimedRotatingFileHandler
|
||||
console_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), when="D", backupCount=3)
|
||||
console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
|
||||
@@ -95,8 +100,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
self._console_logger.setLevel(logging.DEBUG)
|
||||
self._console_logger.propagate = False
|
||||
|
||||
self._repository_available = self._fetch_repository_from_disk()
|
||||
self._notices_available = self._fetch_notices_from_disk()
|
||||
# decouple repository fetching from server startup
|
||||
def fetch_data():
|
||||
self._repository_available = self._fetch_repository_from_disk()
|
||||
self._notices_available = self._fetch_notices_from_disk()
|
||||
|
||||
thread = threading.Thread(target=fetch_data)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
##~~ SettingsPlugin
|
||||
|
||||
@@ -408,6 +419,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
source_type=source_type,
|
||||
needs_restart=True,
|
||||
needs_refresh=True,
|
||||
needs_reconnect=True,
|
||||
was_reinstalled=False,
|
||||
plugin="unknown")
|
||||
self._send_result_notification("install", result)
|
||||
@@ -419,6 +431,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
or reinstall is not None
|
||||
needs_refresh = new_plugin.implementation \
|
||||
and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
|
||||
needs_reconnect = self._plugin_manager.has_any_of_hooks(new_plugin, self._reconnect_hooks) and self._printer.is_operational()
|
||||
|
||||
is_reinstall = self._plugin_manager.is_plugin_marked(new_plugin.key, "uninstalled")
|
||||
self._plugin_manager.mark_plugin(new_plugin.key,
|
||||
@@ -433,6 +446,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
source_type=source_type,
|
||||
needs_restart=needs_restart,
|
||||
needs_refresh=needs_refresh,
|
||||
needs_reconnect=needs_reconnect,
|
||||
was_reinstalled=new_plugin.key in all_plugins_before or reinstall is not None,
|
||||
plugin=self._to_external_plugin(new_plugin))
|
||||
self._send_result_notification("install", result)
|
||||
@@ -489,6 +503,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
|
||||
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
|
||||
needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational()
|
||||
|
||||
was_pending_install = self._plugin_manager.is_plugin_marked(plugin.key, "installed")
|
||||
self._plugin_manager.mark_plugin(plugin.key,
|
||||
@@ -514,7 +529,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
self._plugin_manager.reload_plugins()
|
||||
|
||||
result = dict(result=True, needs_restart=needs_restart, needs_refresh=needs_refresh, plugin=self._to_external_plugin(plugin))
|
||||
result = dict(result=True,
|
||||
needs_restart=needs_restart,
|
||||
needs_refresh=needs_refresh,
|
||||
needs_reconnect=needs_reconnect,
|
||||
plugin=self._to_external_plugin(plugin))
|
||||
self._send_result_notification("uninstall", result)
|
||||
return jsonify(result)
|
||||
|
||||
@@ -524,11 +543,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
|
||||
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
|
||||
needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational()
|
||||
|
||||
pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable))
|
||||
safe_mode_victim = getattr(plugin, "safe_mode_victim", False)
|
||||
needs_restart_api = (needs_restart or safe_mode_victim) and not pending
|
||||
needs_refresh_api = needs_refresh and not pending
|
||||
needs_reconnect_api = needs_reconnect and not pending
|
||||
|
||||
try:
|
||||
if command == "disable":
|
||||
@@ -542,11 +563,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
result = dict(result=True,
|
||||
needs_restart=True,
|
||||
needs_refresh=True,
|
||||
needs_reconnect=True,
|
||||
plugin=self._to_external_plugin(plugin))
|
||||
else:
|
||||
result = dict(result=True,
|
||||
needs_restart=needs_restart_api,
|
||||
needs_refresh=needs_refresh_api,
|
||||
needs_reconnect=needs_reconnect_api,
|
||||
plugin=self._to_external_plugin(plugin))
|
||||
|
||||
self._send_result_notification(command, result)
|
||||
@@ -598,7 +621,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
if additional_args is not None:
|
||||
|
||||
inapplicable_arguments = self.__class__.pip_inapplicable_arguments.get(args[0], list())
|
||||
inapplicable_arguments = self.__class__.PIP_INAPPLICABLE_ARGUMENTS.get(args[0], list())
|
||||
for inapplicable_argument in inapplicable_arguments:
|
||||
additional_args = re.sub("(^|\s)" + re.escape(inapplicable_argument) + "\\b", "", additional_args)
|
||||
|
||||
@@ -676,7 +699,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
def _fetch_repository_from_url(self):
|
||||
repository_url = self._settings.get(["repository"])
|
||||
try:
|
||||
r = requests.get(repository_url)
|
||||
r = requests.get(repository_url, timeout=30)
|
||||
r.raise_for_status()
|
||||
self._logger.info("Loaded plugin repository data from {}".format(repository_url))
|
||||
except Exception as e:
|
||||
self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=str(e)))
|
||||
@@ -744,7 +768,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
def _fetch_notices_from_url(self):
|
||||
notices_url = self._settings.get(["notices"])
|
||||
try:
|
||||
r = requests.get(notices_url)
|
||||
r = requests.get(notices_url, timeout=30)
|
||||
r.raise_for_status()
|
||||
self._logger.info("Loaded plugin notices data from {}".format(notices_url))
|
||||
except Exception as e:
|
||||
self._logger.exception("Could not fetch notices from {notices_url}: {message}".format(notices_url=notices_url, message=str(e)))
|
||||
@@ -808,18 +833,37 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
return True
|
||||
|
||||
def _is_os_compatible(self, current_os, compatibility_entries):
|
||||
@staticmethod
|
||||
def _is_os_compatible(current_os, compatibility_entries):
|
||||
"""
|
||||
Tests if the ``current_os`` matches any of the provided ``compatibility_entries``.
|
||||
Tests if the ``current_os`` or ``sys.platform`` are blacklisted or whitelisted in ``compatibility_entries``
|
||||
"""
|
||||
return current_os in filter(lambda x: x in self.__class__.OPERATING_SYSTEMS.keys(), compatibility_entries)
|
||||
if len(compatibility_entries) == 0:
|
||||
# shortcut - no compatibility info means we are compatible
|
||||
return True
|
||||
|
||||
def _get_os(self):
|
||||
for identifier, platforms in self.__class__.OPERATING_SYSTEMS.items():
|
||||
if sys.platform in platforms:
|
||||
negative_entries = map(lambda x: x[1:], filter(lambda x: x.startswith("!"), compatibility_entries))
|
||||
positive_entries = filter(lambda x: not x.startswith("!"), compatibility_entries)
|
||||
|
||||
negative_match = False
|
||||
if negative_entries:
|
||||
# check if we are blacklisted
|
||||
negative_match = current_os in negative_entries or any(map(lambda x: sys.platform.startswith(x), negative_entries))
|
||||
|
||||
positive_match = True
|
||||
if positive_entries:
|
||||
# check if we are whitelisted
|
||||
positive_match = current_os in positive_entries or any(map(lambda x: sys.platform.startswith(x), positive_entries))
|
||||
|
||||
return positive_match and not negative_match
|
||||
|
||||
@classmethod
|
||||
def _get_os(cls):
|
||||
for identifier, platforms in cls.OPERATING_SYSTEMS.items():
|
||||
if (callable(platforms) and platforms(sys.platform)) or (isinstance(platforms, list) and sys.platform in platforms):
|
||||
return identifier
|
||||
else:
|
||||
return "unknown"
|
||||
return "unmapped"
|
||||
|
||||
def _get_octoprint_version_string(self):
|
||||
return VERSION
|
||||
@@ -853,6 +897,22 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
octoprint_version = pkg_resources.parse_version(octoprint_version.base_version)
|
||||
return octoprint_version
|
||||
|
||||
@property
|
||||
def _reconnect_hooks(self):
|
||||
reconnect_hooks = self.__class__.RECONNECT_HOOKS
|
||||
|
||||
reconnect_hook_provider_hooks = self._plugin_manager.get_hooks("octoprint.plugin.pluginmanager.reconnect_hooks")
|
||||
for name, hook in reconnect_hook_provider_hooks.items():
|
||||
try:
|
||||
result = hook()
|
||||
if isinstance(result, (list, tuple)):
|
||||
reconnect_hooks.extend(filter(lambda x: isinstance(x, basestring), result))
|
||||
except:
|
||||
self._logger.exception("Error while retrieving additional hooks for which a "
|
||||
"reconnect is required from plugin {name}".format(**locals()))
|
||||
|
||||
return reconnect_hooks
|
||||
|
||||
def _get_plugins(self):
|
||||
plugins = self._plugin_manager.plugins
|
||||
|
||||
|
||||
@@ -527,13 +527,11 @@ $(function() {
|
||||
if (reinstall) {
|
||||
OctoPrint.plugins.pluginmanager.reinstall(reinstall, url, followDependencyLinks)
|
||||
.done(onSuccess)
|
||||
.fail(onError)
|
||||
.always(onAlways);
|
||||
.fail(onError);
|
||||
} else {
|
||||
OctoPrint.plugins.pluginmanager.install(url, followDependencyLinks)
|
||||
.done(onSuccess)
|
||||
.fail(onError)
|
||||
.always(onAlways);
|
||||
.fail(onError);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -666,7 +664,7 @@ $(function() {
|
||||
return self.isCompatible(data) ? (self.installed(data) ? gettext("Reinstall") : gettext("Install")) : (data.disabled ? gettext("Disabled") : gettext("Incompatible"));
|
||||
};
|
||||
|
||||
self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, titleError, textError) {
|
||||
self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError) {
|
||||
var notification;
|
||||
|
||||
var beforeClose = function(notification) {
|
||||
@@ -688,17 +686,21 @@ $(function() {
|
||||
hide: false
|
||||
};
|
||||
|
||||
var restartClicked = false;
|
||||
if (self.restartCommandSpec) {
|
||||
options.confirm = {
|
||||
confirm: true,
|
||||
buttons: [{
|
||||
text: gettext("Restart now"),
|
||||
click: function () {
|
||||
click: function (notice) {
|
||||
if (restartClicked) return;
|
||||
restartClicked = true;
|
||||
showConfirmationDialog({
|
||||
message: gettext("This will restart your OctoPrint server."),
|
||||
onproceed: function() {
|
||||
OctoPrint.system.executeCommand("core", "restart")
|
||||
.done(function() {
|
||||
notice.remove();
|
||||
new PNotify({
|
||||
title: gettext("Restart in progress"),
|
||||
text: gettext("The server is now being restarted in the background")
|
||||
@@ -710,6 +712,9 @@ $(function() {
|
||||
text: gettext("Trying to restart the server produced an error, please check octoprint.log for details. You'll have to restart manually.")
|
||||
})
|
||||
});
|
||||
},
|
||||
onclose: function() {
|
||||
restartClicked = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -719,6 +724,7 @@ $(function() {
|
||||
|
||||
notification = PNotify.singleButtonNotify(options);
|
||||
} else if (response.needs_refresh) {
|
||||
var refreshClicked = false;
|
||||
notification = PNotify.singleButtonNotify({
|
||||
title: titleSuccess,
|
||||
text: textReload,
|
||||
@@ -727,6 +733,8 @@ $(function() {
|
||||
buttons: [{
|
||||
text: gettext("Reload now"),
|
||||
click: function () {
|
||||
if (refreshClicked) return;
|
||||
refreshClicked = true;
|
||||
location.reload(true);
|
||||
}
|
||||
}]
|
||||
@@ -740,6 +748,15 @@ $(function() {
|
||||
},
|
||||
hide: false
|
||||
})
|
||||
} else if (response.needs_reconnect) {
|
||||
notification = new PNotify({
|
||||
title: titleSuccess,
|
||||
text: textReconnect,
|
||||
callbacks: {
|
||||
before_close: beforeClose
|
||||
},
|
||||
hide: false
|
||||
})
|
||||
} else {
|
||||
notification = new PNotify({
|
||||
title: titleSuccess,
|
||||
@@ -798,7 +815,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.toggleButtonCss = function(data) {
|
||||
var icon = self._getToggleCommand(data) == "enable" ? "icon-circle-blank" : "icon-circle";
|
||||
var icon = self._getToggleCommand(data) == "enable" ? "fa fa-circle-o" : "fa fa-circle";
|
||||
var disabled = (self.enableToggle(data)) ? "" : " disabled";
|
||||
|
||||
return icon + disabled;
|
||||
@@ -1053,7 +1070,7 @@ $(function() {
|
||||
});
|
||||
self._scrollWorkingOutputToEnd();
|
||||
} else if (messageType == "result") {
|
||||
var titleSuccess, textSuccess, textRestart, textReload, titleError, textError;
|
||||
var titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError;
|
||||
var action = data.action;
|
||||
|
||||
var name = "Unknown";
|
||||
@@ -1073,16 +1090,19 @@ $(function() {
|
||||
textSuccess = gettext("A plugin was installed successfully, however it was impossible to detect which one. Please Restart OctoPrint to make sure everything will be registered properly");
|
||||
textRestart = textSuccess;
|
||||
textReload = textSuccess;
|
||||
textReconnect = textSuccess;
|
||||
} else if (data.was_reinstalled) {
|
||||
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" reinstalled"), {name: name});
|
||||
textSuccess = gettext("The plugin was reinstalled successfully");
|
||||
textRestart = gettext("The plugin was reinstalled successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was reinstalled successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was reinstalled successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
} else {
|
||||
titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" installed"), {name: name});
|
||||
textSuccess = gettext("The plugin was installed successfully");
|
||||
textRestart = gettext("The plugin was installed successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was installed successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was installed successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
}
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
@@ -1134,6 +1154,7 @@ $(function() {
|
||||
textSuccess = gettext("The plugin was uninstalled successfully");
|
||||
textRestart = gettext("The plugin was uninstalled successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was uninstalled successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was uninstalled successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
if (data.hasOwnProperty("reason")) {
|
||||
@@ -1151,6 +1172,7 @@ $(function() {
|
||||
textSuccess = gettext("The plugin was enabled successfully.");
|
||||
textRestart = gettext("The plugin was enabled successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was enabled successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was enabled successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
if (data.hasOwnProperty("reason")) {
|
||||
@@ -1168,6 +1190,7 @@ $(function() {
|
||||
textSuccess = gettext("The plugin was disabled successfully.");
|
||||
textRestart = gettext("The plugin was disabled successfully, however a restart of OctoPrint is needed for that to take effect.");
|
||||
textReload = gettext("The plugin was disabled successfully, however a reload of the page is needed for that to take effect.");
|
||||
textReconnect = gettext("The plugin was disabled successfully, however a reconnect to the printer is needed for that to take effect.");
|
||||
|
||||
titleError = gettext("Something went wrong");
|
||||
if (data.hasOwnProperty("reason")) {
|
||||
@@ -1180,7 +1203,7 @@ $(function() {
|
||||
return;
|
||||
}
|
||||
|
||||
self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, titleError, textError);
|
||||
self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError);
|
||||
self.requestData();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
{{ pluginmanager_safemode() }}
|
||||
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="fa fa-wrench"></i></button>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Installed Plugins') }}</h3>
|
||||
@@ -40,18 +40,18 @@
|
||||
<tbody data-bind="foreach: plugins.paginatedItems">
|
||||
<tr>
|
||||
<td class="settings_plugin_plugin_manager_plugins_name">
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="icon-th-large" data-bind="visible: bundled"></i> <i class="icon-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="icon-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="icon-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="icon-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="icon-medkit" data-bind="visible: safe_mode_victim"></i> <i class="icon-exclamation-sign" title="{{ _('There are notices available regarding this plugin') }}" data-bind="visible: notifications && notifications.length"></i></div>
|
||||
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="fa fa-th-large" data-bind="visible: bundled"></i> <i class="fa fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="fa fa-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="fa fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="fa fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="fa fa-medkit" data-bind="visible: safe_mode_victim"></i> <i class="fa fa-exclamation-triangle" title="{{ _('There are notices available regarding this plugin') }}" data-bind="visible: notifications && notifications.length"></i></div>
|
||||
<div data-bind="visible: notifications && notifications.length"><a href="javascript:void(0)" class="text-error" style="text-decoration: underline" data-bind="click: function() { $root.showPluginNotifications($data) }, text: $root.showPluginNotificationsLinkText($data)"></a></div>
|
||||
<div><small class="muted" data-bind="text: description"> </small></div>
|
||||
<div data-bind="css: {muted: !enabled}">
|
||||
<small data-bind="visible: url"><i class="icon-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
|
||||
<small data-bind="visible: license"><i class="icon-legal"></i> <span data-bind="text: license"></span></small>
|
||||
<small data-bind="visible: author"><i class="icon-user"></i> <span data-bind="text: author"></span></small>
|
||||
<small data-bind="visible: url"><i class="fa fa-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
|
||||
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
|
||||
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
|
||||
<small> </small>
|
||||
</div>
|
||||
</td>
|
||||
<td class="settings_plugin_plugin_manager_plugins_actions">
|
||||
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.togglePlugin($data) }"></a> | <a href="#" class="icon-trash" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
|
||||
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.togglePlugin($data) }"></a> | <a href="#" class="fa fa-trash-o" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
@@ -73,8 +73,8 @@
|
||||
<div class="muted" data-bind="visible: pipAvailable()">
|
||||
<div>
|
||||
<small>
|
||||
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="toggle-arrow icon-caret-right"></i> Using pip of "<span data-bind="text: pipPython"></span>", Version <span data-bind="text: pipVersion"></span>
|
||||
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="fa toggle-arrow fa-caret-right"></i> Using pip of "<span data-bind="text: pipPython"></span>", Version <span data-bind="text: pipVersion"></span>
|
||||
</a>
|
||||
</small>
|
||||
</div>
|
||||
@@ -90,8 +90,8 @@
|
||||
<div class="muted">
|
||||
<div>
|
||||
<small>
|
||||
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="toggle-arrow icon-caret-right"></i> <span data-bind="text: noticeCountText"></span>
|
||||
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
|
||||
<i class="toggle-arrow fa fa-caret-right"></i> <span data-bind="text: noticeCountText"></span>
|
||||
</a>
|
||||
</small>
|
||||
</div>
|
||||
@@ -108,7 +108,7 @@
|
||||
<h3 data-bind="text: workingTitle"></h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<pre id="settings_plugin_pluginmanager_workingdialog_output" class="terminal pre-scrollable" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span><br></pre>
|
||||
<pre id="settings_plugin_pluginmanager_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span></pre>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
|
||||
@@ -128,16 +128,16 @@
|
||||
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
|
||||
<div class="dropdown pull-right">
|
||||
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
|
||||
<span class="icon-wrench"></span>
|
||||
<span class="fa fa-wrench"></span>
|
||||
</a>
|
||||
<ul class="dropdown-menu pull-right">
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('title'); }"><i class="icon-ok" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'title' ? 'visible' : 'hidden'}"></i> {{ _('Sort by title') }} ({{ _('ascending') }})</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('published'); }"><i class="icon-ok" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'published' ? 'visible' : 'hidden'}"></i> {{ _('Sort by publication date') }} ({{ _('descending') }})</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('title'); }"><i class="fa fa-check" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'title' ? 'visible' : 'hidden'}"></i> {{ _('Sort by title') }} ({{ _('ascending') }})</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('published'); }"><i class="fa fa-check" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'published' ? 'visible' : 'hidden'}"></i> {{ _('Sort by publication date') }} ({{ _('descending') }})</a></li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_installed'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_installed') ? 'visible' : 'hidden'}"></i> {{ _('Only show uninstalled plugins') }}</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_incompatible'); }"><i class="icon-ok" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_incompatible') ? 'visible' : 'hidden'}"></i> {{ _('Only show compatible plugins') }}</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_installed'); }"><i class="fa fa-check" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_installed') ? 'visible' : 'hidden'}"></i> {{ _('Only show uninstalled plugins') }}</a></li>
|
||||
<li><a href="#" data-bind="click: function() { repositoryplugins.toggleFilter('filter_incompatible'); }"><i class="fa fa-check" data-bind="style: {visibility: _.contains(repositoryplugins.currentFilters(), 'filter_incompatible') ? 'visible' : 'hidden'}"></i> {{ _('Only show compatible plugins') }}</a></li>
|
||||
<li class="divider"></li>
|
||||
<li><a href="#" data-bind="click: function() { refreshRepository(); }"><i class="icon-refresh"></i> {{ _('Refresh list from repository') }}</a></li>
|
||||
<li><a href="#" data-bind="click: function() { refreshRepository(); }"><i class="fa fa-refresh"></i> {{ _('Refresh list from repository') }}</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</h4>
|
||||
@@ -154,15 +154,15 @@
|
||||
<div><span data-bind="text: title"></span></div>
|
||||
<div><small class="muted" data-bind="text: description"> </small></div>
|
||||
<div>
|
||||
<small data-bind="visible: page"><i class="icon-info"></i> <a data-bind="attr: {href: page}" target="_blank">{{ _('Details') }}</a></small>
|
||||
<small data-bind="visible: homepage"><i class="icon-home"></i> <a data-bind="attr: {href: homepage}" target="_blank">{{ _('Homepage') }}</a></small>
|
||||
<small data-bind="visible: license"><i class="icon-legal"></i> <span data-bind="text: license"></span></small>
|
||||
<small data-bind="visible: author"><i class="icon-user"></i> <span data-bind="text: author"></span></small>
|
||||
<small data-bind="visible: page"><i class="fa fa-info"></i> <a data-bind="attr: {href: page}" target="_blank">{{ _('Details') }}</a></small>
|
||||
<small data-bind="visible: homepage"><i class="fa fa-home"></i> <a data-bind="attr: {href: homepage}" target="_blank">{{ _('Homepage') }}</a></small>
|
||||
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
|
||||
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
|
||||
<small> </small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="span3">
|
||||
<button class="btn btn-primary btn-block" data-bind="enable: $root.enableRepoInstall($data), css: {disabled: !$root.enableRepoInstall($data)}, click: function() { if ($root.enableRepoInstall($data)) { $root.installFromRepository($data); } else { return false; } }"><i class="icon-add"></i> <span data-bind="text: $root.installButtonText($data)"></span></button>
|
||||
<button class="btn btn-primary btn-block" data-bind="enable: $root.enableRepoInstall($data), css: {disabled: !$root.enableRepoInstall($data)}, click: function() { if ($root.enableRepoInstall($data)) { $root.installFromRepository($data); } else { return false; } }"><i class="fa fa-add"></i> <span data-bind="text: $root.installButtonText($data)"></span></button>
|
||||
<div data-bind="visible: $data.disabled !== undefined" style="text-align: center"><small><a data-bind="attr: {href: page}" target="_blank">{{ _('"Why?"') }}</a></small></div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -209,7 +209,7 @@
|
||||
</form>
|
||||
|
||||
<div>
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
|
||||
@@ -36,6 +36,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
octoprint.plugin.TemplatePlugin,
|
||||
octoprint.plugin.StartupPlugin,
|
||||
octoprint.plugin.WizardPlugin):
|
||||
|
||||
COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit")
|
||||
|
||||
def __init__(self):
|
||||
self._update_in_progress = False
|
||||
self._configured_checks_mutex = threading.Lock()
|
||||
@@ -48,6 +51,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._version_cache_ttl = 0
|
||||
self._version_cache_path = None
|
||||
self._version_cache_dirty = False
|
||||
self._version_cache_timestamp = None
|
||||
|
||||
self._console_logger = None
|
||||
|
||||
@@ -75,8 +79,14 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._console_logger.propagate = False
|
||||
|
||||
def on_after_startup(self):
|
||||
# refresh cache now if necessary so it's faster once the user connects to the instance
|
||||
self.get_current_versions()
|
||||
# refresh cache now if necessary so it's faster once the user connects to the instance - but decouple it from
|
||||
# the server startup
|
||||
def fetch_data():
|
||||
self.get_current_versions()
|
||||
|
||||
thread = threading.Thread(target=fetch_data)
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
def _get_configured_checks(self):
|
||||
with self._configured_checks_mutex:
|
||||
@@ -115,7 +125,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
# This used to be part of the settings migration (version 2) due to a bug - it can't
|
||||
# stay there though since it interferes with manual entries to the checks not
|
||||
# originating from within a plugin. Hence we do that step now here.
|
||||
if "type" not in effective_config or effective_config["type"] != "github_commit":
|
||||
if "type" not in effective_config or effective_config["type"] not in self.COMMIT_TRACKING_TYPES:
|
||||
deletables = ["current", "displayVersion"]
|
||||
else:
|
||||
deletables = []
|
||||
@@ -154,6 +164,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
try:
|
||||
with open(self._version_cache_path) as f:
|
||||
data = yaml.safe_load(f)
|
||||
timestamp = os.stat(self._version_cache_path).st_mtime
|
||||
except:
|
||||
self._logger.exception("Error while loading version cache from disk")
|
||||
else:
|
||||
@@ -176,6 +187,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
self._version_cache = data
|
||||
self._version_cache_dirty = False
|
||||
self._version_cache_timestamp = timestamp
|
||||
self._logger.info("Loaded version cache from disk")
|
||||
except:
|
||||
self._logger.exception("Error parsing in version cache data")
|
||||
@@ -192,6 +204,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
yaml.safe_dump(self._version_cache, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
|
||||
self._version_cache_dirty = False
|
||||
self._version_cache_timestamp = time.time()
|
||||
self._logger.info("Saved version cache to disk")
|
||||
|
||||
#~~ SettingsPlugin API
|
||||
@@ -206,9 +219,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
"repo": "OctoPrint",
|
||||
"update_script": "{{python}} \"{update_script}\" --branch={{branch}} --force={{force}} \"{{folder}}\" {{target}}".format(update_script=update_script),
|
||||
"restart": "octoprint",
|
||||
"stable_branch": dict(branch="master", name="Stable"),
|
||||
"prerelease_branches": [dict(branch="rc/maintenance", name="Maintenance RCs"),
|
||||
dict(branch="rc/devel", name="Devel RCs")]
|
||||
"stable_branch": dict(branch="master", commitish=["master"], name="Stable"),
|
||||
"prerelease_branches": [dict(branch="rc/maintenance",
|
||||
commitish=["rc/maintenance"], # maintenance RCs
|
||||
name="Maintenance RCs"),
|
||||
dict(branch="rc/devel",
|
||||
commitish=["rc/maintenance", "rc/devel"], # devel & maintenance RCs
|
||||
name="Devel RCs")]
|
||||
},
|
||||
},
|
||||
"pip_command": None,
|
||||
@@ -385,7 +402,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
||||
if configured_checks is not None and "octoprint" in configured_checks:
|
||||
octoprint_check = dict(configured_checks["octoprint"])
|
||||
if "type" not in octoprint_check or octoprint_check["type"] != "github_commit":
|
||||
if "type" not in octoprint_check or octoprint_check["type"] not in self.COMMIT_TRACKING_TYPES:
|
||||
deletables=["current", "displayName", "displayVersion"]
|
||||
else:
|
||||
deletables=[]
|
||||
@@ -461,7 +478,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
data["check"]["python_updater"] = True
|
||||
|
||||
return flask.jsonify(dict(status="updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current",
|
||||
information=information))
|
||||
information=information,
|
||||
timestamp=self._version_cache_timestamp))
|
||||
except exceptions.ConfigurationInvalid as e:
|
||||
return flask.make_response("Update not properly configured, can't proceed: %s" % e.message, 500)
|
||||
|
||||
@@ -487,6 +505,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
hash.update(str(data["possible"]))
|
||||
|
||||
hash.update(",".join(targets))
|
||||
hash.update(str(self._version_cache_timestamp))
|
||||
return hash.hexdigest()
|
||||
|
||||
def condition():
|
||||
@@ -834,7 +853,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._settings.load()
|
||||
|
||||
# persist the new version if necessary for check type
|
||||
if check["type"] == "github_commit":
|
||||
if check["type"] in self.COMMIT_TRACKING_TYPES:
|
||||
dummy_default = dict(plugins=dict())
|
||||
dummy_default["plugins"][self._identifier] = dict(checks=dict())
|
||||
dummy_default["plugins"][self._identifier]["checks"][target] = dict(current=None)
|
||||
@@ -856,7 +875,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
|
||||
self._logger.info("Restarting...")
|
||||
try:
|
||||
util.execute(restart_command)
|
||||
util.execute(restart_command, evaluate_returncode=False, async=True)
|
||||
except exceptions.ScriptError as e:
|
||||
self._logger.exception("Error while restarting via command {}".format(restart_command))
|
||||
self._logger.warn("Restart stdout:\n{}".format(e.stdout))
|
||||
@@ -891,7 +910,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
release_branches += [x["branch"] for x in check["prerelease_branches"]]
|
||||
result["released_version"] = not release_branches or BRANCH in release_branches
|
||||
|
||||
if check["type"] == "github_commit":
|
||||
if check["type"] in self.COMMIT_TRACKING_TYPES:
|
||||
result["current"] = REVISION if REVISION else "unknown"
|
||||
else:
|
||||
result["current"] = VERSION
|
||||
@@ -905,8 +924,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
result["force_base"] = False
|
||||
|
||||
if check.get("update_script", None):
|
||||
# if we are using the update_script, we need to set our update_branch and force
|
||||
# to install the exact version we requested
|
||||
# if we are using the update_script, we need to set our update_branch
|
||||
|
||||
if check.get("prerelease", None):
|
||||
# we are tracking prereleases => we want to be on the correct prerelease channel/branch
|
||||
@@ -916,14 +934,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
# in case it's not already set
|
||||
result["update_branch"] = check.get("update_branch", channel)
|
||||
|
||||
# we also force our target version in the update
|
||||
result["force_exact_version"] = True
|
||||
|
||||
else:
|
||||
# we are not tracking prereleases, but aren't on the stable branch either => switch back
|
||||
# to stable branch on update
|
||||
result["update_branch"] = check.get("update_branch", stable_branch)
|
||||
|
||||
# we also force an exact version
|
||||
result["force_exact_version"] = True
|
||||
|
||||
if BRANCH != result.get("prerelease_channel"):
|
||||
# we force python unequality check here because that will also allow us to
|
||||
@@ -945,7 +962,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
# displayVersion AND current missing or None
|
||||
result["displayVersion"] = u"unknown"
|
||||
|
||||
if check["type"] in ("github_commit",):
|
||||
if check["type"] in self.COMMIT_TRACKING_TYPES:
|
||||
result["current"] = check.get("current", None)
|
||||
else:
|
||||
result["current"] = check.get("current", check.get("displayVersion", None))
|
||||
@@ -977,18 +994,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
raise exceptions.ConfigurationInvalid("no check type defined")
|
||||
|
||||
check_type = check["type"]
|
||||
if check_type == "github_release":
|
||||
return version_checks.github_release
|
||||
elif check_type == "github_commit":
|
||||
return version_checks.github_commit
|
||||
elif check_type == "git_commit":
|
||||
return version_checks.git_commit
|
||||
elif check_type == "commandline":
|
||||
return version_checks.commandline
|
||||
elif check_type == "python_checker":
|
||||
return version_checks.python_checker
|
||||
else:
|
||||
method = getattr(version_checks, check_type)
|
||||
if method is None:
|
||||
raise exceptions.UnknownCheckType()
|
||||
else:
|
||||
return method
|
||||
|
||||
def _get_update_method(self, target, check, valid_methods=None):
|
||||
"""
|
||||
|
||||
@@ -1 +1 @@
|
||||
td.settings_plugin_softwareupdate_column_update{width:16px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:bold}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:bold;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:bold;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
|
||||
td.settings_plugin_softwareupdate_column_update{width:16px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
|
||||
@@ -112,6 +112,11 @@ $(function() {
|
||||
self.octoprintUnconfigured = ko.observable();
|
||||
self.octoprintUnreleased = ko.observable();
|
||||
|
||||
self.cacheTimestamp = ko.observable();
|
||||
self.cacheTimestampText = ko.pureComputed(function() {
|
||||
return formatDate(self.cacheTimestamp());
|
||||
});
|
||||
|
||||
self.config_cacheTtl = ko.observable();
|
||||
self.config_notifyUsers = ko.observable();
|
||||
self.config_checkoutFolder = ko.observable();
|
||||
@@ -119,8 +124,9 @@ $(function() {
|
||||
self.config_updateMethod = ko.observable();
|
||||
self.config_releaseChannel = ko.observable();
|
||||
|
||||
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
|
||||
self.confirmationDialog = $("#softwareupdate_confirmation_dialog");
|
||||
self.configurationDialog = undefined;
|
||||
self.confirmationDialog = undefined;
|
||||
self._updateClicked = false;
|
||||
|
||||
self.config_availableCheckTypes = ko.observableArray([]);
|
||||
self.config_availableReleaseChannels = ko.observableArray([]);
|
||||
@@ -199,7 +205,7 @@ $(function() {
|
||||
|
||||
self.savePluginSettings = function(viewModel, event) {
|
||||
var target = $(event.target);
|
||||
target.prepend('<i class="icon-spinner icon-spin"></i> ');
|
||||
target.prepend('<i class="fa fa-spinner fa-spin"></i> ');
|
||||
|
||||
var data = {
|
||||
plugins: {
|
||||
@@ -219,7 +225,7 @@ $(function() {
|
||||
self.performCheck();
|
||||
},
|
||||
complete: function() {
|
||||
$("i.icon-spinner", target).remove();
|
||||
$("i.fa-spinner", target).remove();
|
||||
},
|
||||
sending: true
|
||||
});
|
||||
@@ -257,6 +263,8 @@ $(function() {
|
||||
};
|
||||
|
||||
self.fromCheckResponse = function(data, ignoreSeen, showIfNothingNew) {
|
||||
self.cacheTimestamp(data.timestamp);
|
||||
|
||||
var versions = [];
|
||||
_.each(data.information, function(value, key) {
|
||||
value["key"] = key;
|
||||
@@ -308,11 +316,11 @@ $(function() {
|
||||
if (data.status == "updateAvailable" || data.status == "updatePossible") {
|
||||
var text = "<div class='softwareupdate_notification'>" + gettext("There are updates available for the following components:");
|
||||
|
||||
text += "<ul class='icons-ul'>";
|
||||
text += "<ul class='fa-ul'>";
|
||||
_.each(self.versions.items(), function(update_info) {
|
||||
if (update_info.updateAvailable) {
|
||||
text += "<li>"
|
||||
+ "<i class='icon-li " + (update_info.updatePossible ? "icon-ok" : "icon-remove")+ "'></i>"
|
||||
+ "<i class='fa fa-li " + (update_info.updatePossible ? "fa-check" : "fa-remove")+ "'></i>"
|
||||
+ "<span class='name' title='" + update_info.fullNameRemote + "'>" + update_info.fullNameRemote + "</span>"
|
||||
+ (update_info.releaseNotes ? "<a href=\"" + update_info.releaseNotes + "\" target=\"_blank\">" + gettext("Release Notes") + "</a>" : "")
|
||||
+ "</li>";
|
||||
@@ -320,7 +328,7 @@ $(function() {
|
||||
});
|
||||
text += "</ul>";
|
||||
|
||||
text += "<p><small>" + gettext("Those components marked with <i class=\"icon-ok\"></i> can be updated directly.") + "</small></p>";
|
||||
text += "<p><small>" + gettext("Those components marked with <i class=\"fa fa-check\"></i> can be updated directly.") + "</small></p>";
|
||||
|
||||
if (!self.loginState.isAdmin()) {
|
||||
text += "<p><small>" + gettext("To have updates applied, get in touch with an administrator of this OctoPrint instance.") + "</small></p>";
|
||||
@@ -351,7 +359,11 @@ $(function() {
|
||||
}, {
|
||||
text: gettext("Update now"),
|
||||
addClass: "btn-primary",
|
||||
click: self.update
|
||||
click: function() {
|
||||
if (self._updateClicked) return;
|
||||
self._updateClicked = true;
|
||||
self.update();
|
||||
}
|
||||
}]
|
||||
};
|
||||
options["buttons"] = {
|
||||
@@ -462,7 +474,7 @@ $(function() {
|
||||
var options = {
|
||||
title: gettext("Updating..."),
|
||||
text: gettext("Now updating, please wait."),
|
||||
icon: "icon-cog icon-spin",
|
||||
icon: "fa fa-cog fa-spin",
|
||||
hide: false,
|
||||
buttons: {
|
||||
closer: false,
|
||||
@@ -491,8 +503,19 @@ $(function() {
|
||||
};
|
||||
|
||||
self.update = function(force) {
|
||||
<<<<<<< HEAD
|
||||
if (self.updateInProgress) return;
|
||||
if (!self.loginState.hasPermission(self.access.permissions.SETTINGS)) return;
|
||||
=======
|
||||
if (self.updateInProgress) {
|
||||
self._updateClicked = false;
|
||||
return;
|
||||
}
|
||||
if (!self.loginState.isAdmin()) {
|
||||
self._updateClicked = false;
|
||||
return;
|
||||
}
|
||||
>>>>>>> 2e6d65378f21ffa3f2ea00880188f632bac5e102
|
||||
|
||||
if (self.printerState.isPrinting()) {
|
||||
self._showPopup({
|
||||
@@ -500,6 +523,7 @@ $(function() {
|
||||
text: gettext("A print job is currently in progress. Updating will be prevented until it is done."),
|
||||
type: "error"
|
||||
});
|
||||
self._updateClicked = false;
|
||||
} else {
|
||||
self.forceUpdate = (force == true);
|
||||
self.confirmationDialog.modal("show");
|
||||
@@ -508,9 +532,13 @@ $(function() {
|
||||
};
|
||||
|
||||
self.confirmUpdate = function() {
|
||||
self.confirmationDialog.modal("hide");
|
||||
self.performUpdate(self.forceUpdate,
|
||||
_.map(self.availableAndPossible(), function(info) { return info.key }));
|
||||
self.confirmationDialog.modal("hide");
|
||||
};
|
||||
|
||||
self.confirmationHidden = function() {
|
||||
self._updateClicked = false;
|
||||
};
|
||||
|
||||
self._showWorkingDialog = function(title) {
|
||||
@@ -568,6 +596,10 @@ $(function() {
|
||||
self.onStartup = function() {
|
||||
self.workingDialog = $("#settings_plugin_softwareupdate_workingdialog");
|
||||
self.workingOutput = $("#settings_plugin_softwareupdate_workingdialog_output");
|
||||
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
|
||||
self.confirmationDialog = $("#softwareupdate_confirmation_dialog");
|
||||
|
||||
self.confirmationDialog.on("hidden", self.confirmationHidden);
|
||||
};
|
||||
|
||||
self.onServerDisconnect = function() {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<div class="alert" data-bind="visible: octoprintUnconfigured()">{% trans %}
|
||||
Please configure the <strong>checkout folder</strong> of OctoPrint, otherwise
|
||||
this plugin won't be able to update it. Click on the <i class="icon-wrench"></i> button
|
||||
this plugin won't be able to update it. Click on the <i class="fa fa-wrench"></i> button
|
||||
to do this. Also refer to the <a href="https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update" target="_blank">Documentation</a>.
|
||||
{% endtrans %}</div>
|
||||
<div class="alert" data-bind="visible: !octoprintUnconfigured() && octoprintUnreleased()">{% trans %}
|
||||
@@ -17,7 +17,7 @@
|
||||
{% endtrans %}</div>
|
||||
|
||||
<div class="pull-right">
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="icon-wrench"></i></button>
|
||||
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="fa fa-wrench"></i></button>
|
||||
</div>
|
||||
|
||||
<h3>{{ _('Current versions') }}</h3>
|
||||
@@ -26,10 +26,10 @@
|
||||
<tbody data-bind="foreach: versions.paginatedItems">
|
||||
<tr data-bind="attr: {title: displayName}">
|
||||
<td class="settings_plugin_softwareupdate_column_update">
|
||||
<span data-bind="invisible: !updateAvailable"><i class="icon-bell" title="{{ _('Update available') }}"></i></span>
|
||||
<span data-bind="invisible: !updateAvailable"><i class="fa fa-bell-o" title="{{ _('Update available') }}"></i></span>
|
||||
</td>
|
||||
<td class="settings_plugin_softwareupdate_column_information">
|
||||
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="icon-exclamation-sign" title="{{ _('Update not possible, configuration ok?') }}"></i></span><br>
|
||||
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fa fa-exclamation-triangle" title="{{ _('Update not possible, configuration ok?') }}"></i></span><br>
|
||||
<small class="muted">
|
||||
{{ _('Installed:') }} <span data-bind="text: information.local.name"></span><br>
|
||||
{{ _('Available:') }} <span data-bind="text: information.remote.name"></span><br>
|
||||
@@ -57,13 +57,14 @@
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="icon-spinner icon-spin" data-bind="visible: checking"></i> {{ _('Check for update now') }}</button>
|
||||
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fa fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Check for update now') }}</button>
|
||||
|
||||
<div>
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }, enable: !checking(), css: {disabled: checking()}"><i class="icon-spinner icon-spin" data-bind="visible: checking"></i> {{ _('Force check for update (overrides cache used for update checks)') }}</button>
|
||||
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.update(true); }">{{ _('Force update now (even if no new versions are available)') }}</button>
|
||||
<small class="muted" style="display: block">{{ _('Last cache refresh:') }} <span data-bind="text: cacheTimestampText"></span></small>
|
||||
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, true, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fa fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force check for update (overrides cache used for update checks)') }}</button>
|
||||
<button class="btn btn-block btn-danger" data-bind="visible: CONFIG_DEBUG, click: function() { $root.update(true); }, enable: !checking(), css: {disabled: checking()}"><i class="fa fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Force update now (even if no new versions are available)') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -107,7 +108,7 @@
|
||||
<h3 data-bind="text: workingTitle"></h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="terminal pre-scrollable" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span><br></pre>
|
||||
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span></pre>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
|
||||
|
||||
@@ -9,12 +9,12 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
from .exceptions import ScriptError
|
||||
|
||||
|
||||
def execute(command, cwd=None, evaluate_returncode=True):
|
||||
def execute(command, cwd=None, evaluate_returncode=True, async=False):
|
||||
import sarge
|
||||
p = None
|
||||
|
||||
try:
|
||||
p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
p = sarge.run(command, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture(), async=async)
|
||||
except:
|
||||
returncode = p.returncode if p is not None else None
|
||||
stdout = p.stdout.text if p is not None and p.stdout is not None else ""
|
||||
|
||||
@@ -5,7 +5,7 @@ __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"
|
||||
|
||||
from . import commandline, git_commit, github_commit, github_release, python_checker
|
||||
from . import commandline, git_commit, github_commit, github_release, bitbucket_commit, python_checker
|
||||
|
||||
def log_github_ratelimit(logger, r):
|
||||
ratelimit = r.headers["X-RateLimit-Limit"] if "X-RateLimit-Limit" in r.headers else "?"
|
||||
@@ -17,4 +17,4 @@ def log_github_ratelimit(logger, r):
|
||||
except:
|
||||
reset = "?"
|
||||
|
||||
logger.debug("Github rate limit: %s/%s, reset at %s" % (remaining, ratelimit, reset))
|
||||
logger.debug("Github rate limit: %s/%s, reset at %s" % (remaining, ratelimit, reset))
|
||||
@@ -0,0 +1,52 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import requests
|
||||
import logging
|
||||
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
|
||||
BRANCH_HEAD_URL = "https://api.bitbucket.org/2.0/repositories/{user}/{repo}/commit/{branch}"
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.bitbucket_commit")
|
||||
|
||||
def _get_latest_commit(user, repo, branch):
|
||||
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch))
|
||||
|
||||
if not r.status_code == requests.codes.ok:
|
||||
return None
|
||||
|
||||
reference = r.json()
|
||||
if not "hash" in reference:
|
||||
return None
|
||||
|
||||
return reference["hash"]
|
||||
|
||||
|
||||
def get_latest(target, check):
|
||||
if "user" not in check or "repo" not in check:
|
||||
raise ConfigurationInvalid("Update configuration for %s of type bitbucket_commit needs all of user and repo" % target)
|
||||
|
||||
branch = "master"
|
||||
if "branch" in check:
|
||||
branch = check["branch"]
|
||||
|
||||
current = None
|
||||
if "current" in check:
|
||||
current = check["current"]
|
||||
|
||||
remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
|
||||
|
||||
information = dict(
|
||||
local=dict(name="Commit {commit}".format(commit=current if current is not None else "unknown"), value=current),
|
||||
remote=dict(name="Commit {commit}".format(commit=remote_commit if remote_commit is not None else "unknown"), value=remote_commit)
|
||||
)
|
||||
is_current = (current is not None and current == remote_commit) or remote_commit is None
|
||||
|
||||
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
|
||||
|
||||
return information, is_current
|
||||
|
||||
@@ -15,7 +15,7 @@ BRANCH_HEAD_URL = "https://api.github.com/repos/{user}/{repo}/git/refs/heads/{br
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_commit")
|
||||
|
||||
def _get_latest_commit(user, repo, branch):
|
||||
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch))
|
||||
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch), timeout=30)
|
||||
|
||||
from . import log_github_ratelimit
|
||||
log_github_ratelimit(logger, r)
|
||||
|
||||
@@ -15,7 +15,7 @@ logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.gith
|
||||
def _filter_out_latest(releases,
|
||||
sort_key=None,
|
||||
include_prerelease=False,
|
||||
prerelease_channel=None):
|
||||
commitish=None):
|
||||
"""
|
||||
Filters out the newest of all matching releases.
|
||||
|
||||
@@ -26,31 +26,43 @@ def _filter_out_latest(releases,
|
||||
>>> release_1_2_16rc2 = dict(name="1.2.16rc2", tag_name="1.2.16rc2", html_url="some_url", published_at="2016-08-30T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
|
||||
>>> release_1_2_17rc1 = dict(name="1.2.17rc1", tag_name="1.2.17rc1", html_url="some_url", published_at="2016-08-31T12:00:00Z", prerelease=True, draft=True, target_commitish="rc/maintenance")
|
||||
>>> release_1_3_0rc1 = dict(name="1.3.0rc1", tag_name="1.3.0rc1", html_url="some_url", published_at="2016-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
|
||||
>>> release_1_3_5rc1 = dict(name="1.3.5rc1", tag_name="1.3.5rc1", html_url="some_url", published_at="2017-06-14T10:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
|
||||
>>> release_1_2_18 = dict(name="1.2.18", tag_name="1.2.18", html_url="some_url", published_at="2016-12-13T12:00:00Z", prerelease=False, draft=False, target_commitish="master")
|
||||
>>> release_1_4_0rc1 = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/future")
|
||||
>>> release_1_4_0rc1_devel = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
|
||||
>>> releases = [release_1_2_15, release_1_2_16rc1, release_1_2_16rc2, release_1_2_17rc1, release_1_3_0rc1, release_1_4_0rc1]
|
||||
>>> _filter_out_latest(releases, include_prerelease=False, prerelease_channel=None)
|
||||
>>> _filter_out_latest(releases, include_prerelease=False, commitish=None)
|
||||
('1.2.15', '1.2.15', 'some_url')
|
||||
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/maintenance")
|
||||
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/maintenance"])
|
||||
('1.2.16rc2', '1.2.16rc2', 'some_url')
|
||||
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/devel")
|
||||
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/devel"])
|
||||
('1.3.0rc1', '1.3.0rc1', 'some_url')
|
||||
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel=None)
|
||||
>>> _filter_out_latest(releases, include_prerelease=True, commitish=None)
|
||||
('1.4.0rc1', '1.4.0rc1', 'some_url')
|
||||
>>> _filter_out_latest(releases, include_prerelease=True, prerelease_channel="rc/doesntexist")
|
||||
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/doesntexist"])
|
||||
('1.2.15', '1.2.15', 'some_url')
|
||||
>>> _filter_out_latest([release_1_2_17rc1])
|
||||
(None, None, None)
|
||||
>>> _filter_out_latest([release_1_2_16rc1, release_1_2_16rc2])
|
||||
(None, None, None)
|
||||
|
||||
>>> comparable_factory = _get_comparable_factory("python", force_base=True)
|
||||
>>> sort_key = lambda release: comparable_factory(_get_sanitized_version(release["tag_name"]))
|
||||
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=False, prerelease_channel=None, sort_key=sort_key)
|
||||
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=False, commitish=None, sort_key=sort_key)
|
||||
('1.2.18', '1.2.18', 'some_url')
|
||||
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, prerelease_channel="rc/maintenance", sort_key=sort_key)
|
||||
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/maintenance"], sort_key=sort_key)
|
||||
('1.2.18', '1.2.18', 'some_url')
|
||||
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, prerelease_channel="rc/devel", sort_key=sort_key)
|
||||
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/devel"], sort_key=sort_key)
|
||||
('1.3.0rc1', '1.3.0rc1', 'some_url')
|
||||
|
||||
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance"])
|
||||
('1.3.5rc1', '1.3.5rc1', 'some_url')
|
||||
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"])
|
||||
('1.3.5rc1', '1.3.5rc1', 'some_url')
|
||||
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance"])
|
||||
('1.3.5rc1', '1.3.5rc1', 'some_url')
|
||||
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"])
|
||||
('1.4.0rc1', '1.4.0rc1', 'some_url')
|
||||
"""
|
||||
|
||||
nothing = None, None, None
|
||||
@@ -61,9 +73,9 @@ def _filter_out_latest(releases,
|
||||
# filter out prereleases and drafts
|
||||
filter_function = lambda rel: not rel["prerelease"] and not rel["draft"]
|
||||
if include_prerelease:
|
||||
if prerelease_channel:
|
||||
filter_function = lambda rel: not rel["draft"] and (
|
||||
not rel["prerelease"] or rel["target_commitish"] == prerelease_channel)
|
||||
if commitish:
|
||||
filter_function = lambda rel: not rel["draft"] and \
|
||||
(not rel["prerelease"] or rel["target_commitish"] in commitish)
|
||||
else:
|
||||
filter_function = lambda rel: not rel["draft"]
|
||||
|
||||
@@ -82,10 +94,10 @@ def _filter_out_latest(releases,
|
||||
|
||||
def _get_latest_release(user, repo, compare_type,
|
||||
include_prerelease=False,
|
||||
prerelease_channel=None,
|
||||
commitish=None,
|
||||
force_base=True):
|
||||
nothing = None, None, None
|
||||
r = requests.get(RELEASE_URL.format(user=user, repo=repo))
|
||||
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=30)
|
||||
|
||||
from . import log_github_ratelimit
|
||||
log_github_ratelimit(logger, r)
|
||||
@@ -107,7 +119,7 @@ def _get_latest_release(user, repo, compare_type,
|
||||
return _filter_out_latest(releases,
|
||||
sort_key=sort_key,
|
||||
include_prerelease=include_prerelease,
|
||||
prerelease_channel=prerelease_channel)
|
||||
commitish=commitish)
|
||||
|
||||
|
||||
def _get_sanitized_version(version_string):
|
||||
@@ -257,6 +269,16 @@ def get_latest(target, check, custom_compare=None):
|
||||
|
||||
include_prerelease = check.get("prerelease", False)
|
||||
prerelease_channel = check.get("prerelease_channel", None)
|
||||
|
||||
# determine valid "commitish" values in case we track prereleases
|
||||
commitish = None
|
||||
if prerelease_channel:
|
||||
prerelease_branches = check.get("prerelease_branches", None)
|
||||
if prerelease_branches:
|
||||
# fetch valid commitish list from configured prerelease_branches for selected channel
|
||||
commitishes = dict((x["branch"], x.get("commitish", [x["branch"]])) for x in prerelease_branches)
|
||||
commitish = commitishes.get(prerelease_channel, [prerelease_channel])
|
||||
|
||||
force_base = check.get("force_base", True)
|
||||
compare_type = _get_sanitized_compare_type(check.get("release_compare", "python"),
|
||||
custom=custom_compare)
|
||||
@@ -265,7 +287,7 @@ def get_latest(target, check, custom_compare=None):
|
||||
check["repo"],
|
||||
compare_type,
|
||||
include_prerelease=include_prerelease,
|
||||
prerelease_channel=prerelease_channel,
|
||||
commitish=commitish,
|
||||
force_base=force_base)
|
||||
|
||||
information =dict(
|
||||
|
||||
@@ -18,6 +18,7 @@ from serial import SerialTimeoutException
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.plugin import plugin_manager
|
||||
from octoprint.util import RepeatedTimer
|
||||
|
||||
class VirtualPrinter(object):
|
||||
command_regex = re.compile("^([GMTF])(\d+)")
|
||||
@@ -113,6 +114,10 @@ class VirtualPrinter(object):
|
||||
|
||||
self._okFormatString = settings().get(["devel", "virtualPrinter", "okFormatString"])
|
||||
|
||||
self._capabilities = settings().get(["devel", "virtualPrinter", "capabilities"])
|
||||
|
||||
self._temperature_reporter = None
|
||||
|
||||
self.currentLine = 0
|
||||
self.lastN = 0
|
||||
|
||||
@@ -405,11 +410,26 @@ class VirtualPrinter(object):
|
||||
output = self._m115FormatString.format(firmware_name=self._firmwareName)
|
||||
self._send(output)
|
||||
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "m115ReportCapabilities"]):
|
||||
for cap, enabled in self._capabilities.items():
|
||||
self._send("Cap:{}:{}".format(cap.upper(), "1" if enabled else "0"))
|
||||
|
||||
def _gcode_M117(self, data):
|
||||
# we'll just use this to echo a message, to allow playing around with pause triggers
|
||||
if self._echoOnM117:
|
||||
self._send("echo:%s" % re.search("M117\s+(.*)", data).group(1))
|
||||
|
||||
def _gcode_M155(self, data):
|
||||
interval = int(re.search("S([0-9]+)", data).group(1))
|
||||
if self._temperature_reporter is not None:
|
||||
self._temperature_reporter.cancel()
|
||||
|
||||
if interval > 0:
|
||||
self._temperature_reporter = RepeatedTimer(interval, lambda: self._send(self._generateTemperatureOutput()))
|
||||
self._temperature_reporter.start()
|
||||
else:
|
||||
self._temperature_reporter = None
|
||||
|
||||
def _gcode_M220(self, data):
|
||||
self._feedrate_multiplier = float(re.search('S([0-9]+)', data).group(1))
|
||||
|
||||
@@ -675,9 +695,8 @@ class VirtualPrinter(object):
|
||||
else:
|
||||
self._send("Not SD printing")
|
||||
|
||||
def _processTemperatureQuery(self):
|
||||
def _generateTemperatureOutput(self):
|
||||
includeTarget = not settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"])
|
||||
includeOk = not self._okBeforeCommandOutput
|
||||
|
||||
# send simulated temperature data
|
||||
if self.temperatureCount > 1:
|
||||
@@ -709,6 +728,11 @@ class VirtualPrinter(object):
|
||||
output = "T:%.2f B:%.2f" % (self.temp[0], self.bedTemp)
|
||||
|
||||
output += " @:64\n"
|
||||
return output
|
||||
|
||||
def _processTemperatureQuery(self):
|
||||
includeOk = not self._okBeforeCommandOutput
|
||||
output = self._generateTemperatureOutput()
|
||||
|
||||
if includeOk:
|
||||
output = "{} {}".format(self._ok(), output)
|
||||
|
||||
@@ -199,7 +199,7 @@ class PrinterInterface(object):
|
||||
|
||||
def set_temperature_offset(self, offsets=None):
|
||||
"""
|
||||
Sets the temperature ``offsets`` to apply to target temperatures red from a GCODE file while printing.
|
||||
Sets the temperature ``offsets`` to apply to target temperatures read from a GCODE file while printing.
|
||||
|
||||
Arguments:
|
||||
offsets (dict): A dictionary specifying the offsets to apply. Keys must match the format for the ``heater``
|
||||
@@ -299,6 +299,7 @@ class PrinterInterface(object):
|
||||
after the file is selected.
|
||||
|
||||
Raises:
|
||||
InvalidFileType: if the file is not a machinecode file and hence cannot be printed
|
||||
InvalidFileLocation: if an absolute path was provided and not contained within local storage or
|
||||
doesn't exist
|
||||
"""
|
||||
@@ -366,7 +367,7 @@ class PrinterInterface(object):
|
||||
* CLOSED
|
||||
* ERROR
|
||||
* CLOSED_WITH_ERROR
|
||||
* TRANFERING_FILE
|
||||
* TRANSFERING_FILE
|
||||
* OFFLINE
|
||||
* UNKNOWN
|
||||
* NONE
|
||||
@@ -593,3 +594,6 @@ class UnknownScript(Exception):
|
||||
|
||||
class InvalidFileLocation(Exception):
|
||||
pass
|
||||
|
||||
class InvalidFileType(Exception):
|
||||
pass
|
||||
@@ -215,25 +215,42 @@ class PrinterProfileManager(object):
|
||||
if self.exists("_default"):
|
||||
return
|
||||
|
||||
if not isinstance(default_overrides, dict):
|
||||
self._logger.warn("Existing default profile from settings is not a valid profile, refusing to migrate: {!r}".format(default_overrides))
|
||||
return
|
||||
|
||||
default_overrides["id"] = "_default"
|
||||
self.save(default_overrides)
|
||||
|
||||
settings().set(["printerProfiles", "defaultProfile"], None)
|
||||
settings().save()
|
||||
|
||||
self._logger.info("Migrated default printer profile from settings to _default.profile: {!r}".format(default_overrides))
|
||||
|
||||
def _verify_default_available(self):
|
||||
default_id = settings().get(["printerProfile", "default"])
|
||||
default_id = settings().get(["printerProfiles", "default"])
|
||||
if default_id is None:
|
||||
default_id = "_default"
|
||||
|
||||
if not self.exists(default_id):
|
||||
if not self.exists("_default"):
|
||||
self._logger.error("Selected default profile {} and _default do not exist, creating _default again and setting it as default".format(default_id))
|
||||
if default_id == "_default":
|
||||
self._logger.error("Profile _default does not exist, creating _default again and setting it as default")
|
||||
else:
|
||||
self._logger.error("Selected default profile {} and _default do not exist, creating _default again and setting it as default".format(default_id))
|
||||
self.save(self.__class__.default, allow_overwrite=True, make_default=True)
|
||||
else:
|
||||
self._logger.error("Selected default profile {} does not exists, resetting to _default".format(default_id))
|
||||
settings().set(["printerProfiles", "default"], "_default")
|
||||
settings().save()
|
||||
default_id = "_default"
|
||||
|
||||
profile = self.get(default_id)
|
||||
if profile is None:
|
||||
self._logger.error("Selected default profile {} is invalid, resetting to default values".format(default_id))
|
||||
profile = copy.deepcopy(self.__class__.default)
|
||||
profile["id"] = default_id
|
||||
self.save(self.__class__.default, allow_overwrite=True, make_default=True)
|
||||
|
||||
def select(self, identifier):
|
||||
if identifier is None or not self.exists(identifier):
|
||||
@@ -241,7 +258,12 @@ class PrinterProfileManager(object):
|
||||
return False
|
||||
else:
|
||||
self._current = self.get(identifier)
|
||||
return True
|
||||
if self._current is None:
|
||||
self._logger.error("Profile {} is invalid, cannot select, falling back to default".format(identifier))
|
||||
self._current = self.get_default()
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
def deselect(self):
|
||||
self._current = None
|
||||
@@ -310,6 +332,8 @@ class PrinterProfileManager(object):
|
||||
profile = self.get(default)
|
||||
if profile is not None:
|
||||
return profile
|
||||
else:
|
||||
self._logger.warn("Default profile {} is invalid, falling back to built-in defaults".format(default))
|
||||
|
||||
return copy.deepcopy(self.__class__.default)
|
||||
|
||||
@@ -318,7 +342,7 @@ class PrinterProfileManager(object):
|
||||
if identifier is not None and not identifier in all_identifiers:
|
||||
return
|
||||
|
||||
settings().set(["printerProfile", "default"], identifier)
|
||||
settings().set(["printerProfiles", "default"], identifier)
|
||||
settings().save()
|
||||
|
||||
def get_current_or_default(self):
|
||||
@@ -344,6 +368,7 @@ class PrinterProfileManager(object):
|
||||
try:
|
||||
profile = self._load_from_path(path)
|
||||
except InvalidProfileError:
|
||||
self._logger.warn("Profile {} is invalid, skipping".format(identifier))
|
||||
continue
|
||||
|
||||
if profile is None:
|
||||
@@ -373,6 +398,9 @@ class PrinterProfileManager(object):
|
||||
with open(path) as f:
|
||||
profile = yaml.safe_load(f)
|
||||
|
||||
if profile is None or not isinstance(profile, dict):
|
||||
raise InvalidProfileError("Profile is None or not a dictionary")
|
||||
|
||||
if self._migrate_profile(profile):
|
||||
try:
|
||||
self._save_to_path(path, profile, allow_overwrite=True)
|
||||
|
||||
@@ -15,11 +15,13 @@ import os
|
||||
import threading
|
||||
import time
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
from octoprint import util as util
|
||||
from octoprint.events import eventManager, Events
|
||||
from octoprint.filemanager import FileDestinations, NoSuchStorage
|
||||
from octoprint.filemanager import FileDestinations, NoSuchStorage, valid_file_type
|
||||
from octoprint.plugin import plugin_manager, ProgressPlugin
|
||||
from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript, InvalidFileLocation
|
||||
from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript, InvalidFileLocation, InvalidFileType
|
||||
from octoprint.printer.estimation import TimeEstimationHelper
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import comm as comm
|
||||
@@ -331,14 +333,15 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
if heater.startswith("tool"):
|
||||
printer_profile = self._printerProfileManager.get_current_or_default()
|
||||
extruder_count = printer_profile["extruder"]["count"]
|
||||
if extruder_count > 1:
|
||||
shared_nozzle = printer_profile["extruder"]["sharedNozzle"]
|
||||
if extruder_count > 1 and not shared_nozzle:
|
||||
toolNum = int(heater[len("tool"):])
|
||||
self.commands("M104 T%d S%f" % (toolNum, value))
|
||||
self.commands("M104 T{} S{}".format(toolNum, value))
|
||||
else:
|
||||
self.commands("M104 S%f" % value)
|
||||
self.commands("M104 S{}".format(value))
|
||||
|
||||
elif heater == "bed":
|
||||
self.commands("M140 S%f" % value)
|
||||
self.commands("M140 S{}".format(value))
|
||||
|
||||
def set_temperature_offset(self, offsets=None):
|
||||
if offsets is None:
|
||||
@@ -369,7 +372,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
factor = int(factor * 100.0)
|
||||
|
||||
if factor < min or factor > max:
|
||||
raise ValueError("factor must be a value between %f and %f" % (min, max))
|
||||
raise ValueError("factor must be a value between {} and {}".format(min, max))
|
||||
|
||||
return factor
|
||||
|
||||
@@ -845,6 +848,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._stateMonitor.add_temperature(data)
|
||||
|
||||
def _validateJob(self, filename, sd):
|
||||
if not valid_file_type(filename, type="machinecode"):
|
||||
raise InvalidFileType("{} is not a machinecode file, cannot print".format(filename))
|
||||
|
||||
if sd:
|
||||
return
|
||||
|
||||
@@ -1069,13 +1075,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
must_be_set=False)
|
||||
|
||||
def on_comm_print_job_done(self):
|
||||
self._updateProgressData()
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
self._fileManager.delete_recovery_data()
|
||||
|
||||
payload = self._payload_for_print_job_event()
|
||||
if payload:
|
||||
payload["time"] = self._comm.getPrintTime()
|
||||
self._updateProgressData(completion=1.0,
|
||||
filepos=payload["size"],
|
||||
printTime=payload["time"],
|
||||
printTimeLeft=0)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
eventManager().fire(Events.PRINT_DONE, payload)
|
||||
self.script("afterPrintDone",
|
||||
context=dict(event=payload),
|
||||
@@ -1087,6 +1097,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
payload["time"],
|
||||
True,
|
||||
self._printerProfileManager.get_current_or_default()["id"])
|
||||
else:
|
||||
self._updateProgressData()
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
|
||||
def on_comm_print_job_failed(self):
|
||||
payload = self._payload_for_print_job_event()
|
||||
@@ -1133,7 +1147,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._sdStreaming = True
|
||||
|
||||
self._setJobData(filename, filesize, True)
|
||||
self._updateProgressData()
|
||||
self._updateProgressData(completion=0.0, filepos=0, printTime=0)
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
def on_comm_file_transfer_done(self, filename):
|
||||
@@ -1160,7 +1174,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
except:
|
||||
self._logger.exception("Error while trying to persist print recovery data")
|
||||
|
||||
def _payload_for_print_job_event(self, location=None, print_job_file=None, position=None):
|
||||
def _payload_for_print_job_event(self, location=None, print_job_file=None, print_job_size=None, position=None):
|
||||
if print_job_file is None:
|
||||
with self._selectedFileMutex:
|
||||
selected_file = self._selectedFile
|
||||
@@ -1168,6 +1182,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
return dict()
|
||||
|
||||
print_job_file = selected_file.get("filename", None)
|
||||
print_job_size = selected_file.get("filesize", None)
|
||||
location = FileDestinations.SDCARD if selected_file.get("sd", False) else FileDestinations.LOCAL
|
||||
|
||||
if not print_job_file or not location:
|
||||
@@ -1189,6 +1204,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
result= dict(name=name,
|
||||
path=path,
|
||||
origin=origin,
|
||||
size=print_job_size,
|
||||
|
||||
# TODO deprecated, remove in 1.4.0
|
||||
file=full_path,
|
||||
@@ -1211,15 +1227,12 @@ class StateMonitor(object):
|
||||
|
||||
self._state = None
|
||||
self._job_data = None
|
||||
self._gcode_data = None
|
||||
self._sd_upload_data = None
|
||||
self._current_z = None
|
||||
self._offsets = {}
|
||||
self._progress = None
|
||||
|
||||
self._progress_dirty = False
|
||||
|
||||
self._offsets = {}
|
||||
|
||||
self._change_event = threading.Event()
|
||||
self._state_lock = threading.Lock()
|
||||
self._progress_lock = threading.Lock()
|
||||
|
||||
@@ -16,7 +16,9 @@ from babel import Locale
|
||||
from watchdog.observers import Observer
|
||||
from watchdog.observers.polling import PollingObserver
|
||||
from collections import defaultdict
|
||||
|
||||
from builtins import bytes, range
|
||||
from past.builtins import basestring
|
||||
|
||||
from octoprint import util
|
||||
|
||||
@@ -268,7 +270,7 @@ class Server(object):
|
||||
try:
|
||||
clazz = octoprint.util.get_class(userManagerName)
|
||||
userManager = clazz()
|
||||
except AttributeError as e:
|
||||
except:
|
||||
self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName))
|
||||
userManager = octoprint.access.users.FilebasedUserManager()
|
||||
finally:
|
||||
@@ -391,7 +393,7 @@ class Server(object):
|
||||
if not userManager.enabled:
|
||||
loginManager.anonymous_user = users.DummyUser
|
||||
principals.identity_loaders.appendleft(users.dummy_identity_loader)
|
||||
loginManager.init_app(app)
|
||||
loginManager.init_app(app, add_context_processor=False)
|
||||
|
||||
# register API blueprint
|
||||
self._setup_blueprints()
|
||||
@@ -406,7 +408,8 @@ class Server(object):
|
||||
ioloop = IOLoop()
|
||||
ioloop.install()
|
||||
|
||||
self._router = SockJSRouter(self._create_socket_connection, "/sockjs")
|
||||
self._router = SockJSRouter(self._create_socket_connection, "/sockjs",
|
||||
session_kls=util.sockjs.ThreadSafeSession)
|
||||
|
||||
upload_suffixes = dict(name=self._settings.get(["server", "uploads", "nameSuffix"]), path=self._settings.get(["server", "uploads", "pathSuffix"]))
|
||||
|
||||
@@ -490,9 +493,22 @@ class Server(object):
|
||||
self._logger.debug("Adding additional route {route} handled by handler {handler} and with additional arguments {kwargs!r}".format(**locals()))
|
||||
server_routes.append((route, handler, kwargs))
|
||||
|
||||
server_routes.append((r".*", util.tornado.UploadStorageFallbackHandler, dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app), file_prefix="octoprint-file-upload-", file_suffix=".tmp", suffixes=upload_suffixes)))
|
||||
headers = {"X-Robots-Tag": "noindex, nofollow, noimageindex"}
|
||||
removed_headers = ["Server"]
|
||||
|
||||
self._tornado_app = Application(server_routes)
|
||||
server_routes.append((r".*", util.tornado.UploadStorageFallbackHandler, dict(fallback=util.tornado.WsgiInputContainer(app.wsgi_app,
|
||||
headers=headers,
|
||||
removed_headers=removed_headers),
|
||||
file_prefix="octoprint-file-upload-",
|
||||
file_suffix=".tmp",
|
||||
suffixes=upload_suffixes)))
|
||||
|
||||
transforms = [util.tornado.GlobalHeaderTransform.for_headers("OctoPrintGlobalHeaderTransform",
|
||||
headers=headers,
|
||||
removed_headers=removed_headers)]
|
||||
|
||||
self._tornado_app = Application(handlers=server_routes,
|
||||
transforms=transforms)
|
||||
max_body_sizes = [
|
||||
("POST", r"/api/files/([^/]*)", self._settings.getInt(["server", "uploads", "maxSize"])),
|
||||
("POST", r"/api/languages", 5 * 1024 * 1024)
|
||||
@@ -530,11 +546,14 @@ class Server(object):
|
||||
|
||||
# auto connect
|
||||
if self._settings.getBoolean(["serial", "autoconnect"]):
|
||||
(port, baudrate) = self._settings.get(["serial", "port"]), self._settings.getInt(["serial", "baudrate"])
|
||||
printer_profile = printerProfileManager.get_default()
|
||||
connectionOptions = printer.__class__.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")
|
||||
try:
|
||||
(port, baudrate) = self._settings.get(["serial", "port"]), self._settings.getInt(["serial", "baudrate"])
|
||||
printer_profile = printerProfileManager.get_default()
|
||||
connectionOptions = printer.__class__.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")
|
||||
except:
|
||||
self._logger.exception("Something went wrong while attempting to automatically connect to the printer")
|
||||
|
||||
# start up watchdogs
|
||||
if self._settings.getBoolean(["feature", "pollWatched"]):
|
||||
@@ -605,7 +624,7 @@ class Server(object):
|
||||
"on_shutdown",
|
||||
sorting_context="ShutdownPlugin.on_shutdown")
|
||||
|
||||
# wait for shutdown even to be processed, but maximally for 15s
|
||||
# wait for shutdown event to be processed, but maximally for 15s
|
||||
event_timeout = 15.0
|
||||
if eventManager.join(timeout=event_timeout):
|
||||
self._logger.warn("Event loop was still busy processing after {}s, shutting down anyhow".format(event_timeout))
|
||||
@@ -620,13 +639,16 @@ class Server(object):
|
||||
def sigterm_handler(*args, **kwargs):
|
||||
# will stop tornado on SIGTERM, making the program exit cleanly
|
||||
def shutdown_tornado():
|
||||
self._logger.debug("Shutting down tornado's IOLoop...")
|
||||
ioloop.stop()
|
||||
self._logger.debug("SIGTERM received...")
|
||||
ioloop.add_callback_from_signal(shutdown_tornado)
|
||||
signal.signal(signal.SIGTERM, sigterm_handler)
|
||||
|
||||
try:
|
||||
# this is the main loop - as long as tornado is running, OctoPrint is running
|
||||
ioloop.start()
|
||||
self._logger.debug("Tornado's IOLoop stopped")
|
||||
except (KeyboardInterrupt, SystemExit):
|
||||
pass
|
||||
except:
|
||||
@@ -852,6 +874,8 @@ class Server(object):
|
||||
return
|
||||
|
||||
def execute_caching():
|
||||
logger = logging.getLogger(__name__ + ".preemptive_cache")
|
||||
|
||||
for route in sorted(cache_data.keys(), key=lambda x: (x.count("/"), x)):
|
||||
entries = reversed(sorted(cache_data[route], key=lambda x: x.get("_count", 0)))
|
||||
for kwargs in entries:
|
||||
@@ -860,18 +884,18 @@ class Server(object):
|
||||
try:
|
||||
plugin_info = pluginManager.get_plugin_info(plugin, require_enabled=True)
|
||||
if plugin_info is None:
|
||||
self._logger.info("About to preemptively cache plugin {} but it is not installed or enabled, preemptive caching makes no sense".format(plugin))
|
||||
logger.info("About to preemptively cache plugin {} but it is not installed or enabled, preemptive caching makes no sense".format(plugin))
|
||||
continue
|
||||
|
||||
implementation = plugin_info.implementation
|
||||
if implementation is None or not isinstance(implementation, octoprint.plugin.UiPlugin):
|
||||
self._logger.info("About to preemptively cache plugin {} but it is not a UiPlugin, preemptive caching makes no sense".format(plugin))
|
||||
logger.info("About to preemptively cache plugin {} but it is not a UiPlugin, preemptive caching makes no sense".format(plugin))
|
||||
continue
|
||||
if not implementation.get_ui_preemptive_caching_enabled():
|
||||
self._logger.info("About to preemptively cache plugin {} but it has disabled preemptive caching".format(plugin))
|
||||
logger.info("About to preemptively cache plugin {} but it has disabled preemptive caching".format(plugin))
|
||||
continue
|
||||
except:
|
||||
self._logger.exception("Error while trying to check if plugin {} has preemptive caching enabled, skipping entry")
|
||||
logger.exception("Error while trying to check if plugin {} has preemptive caching enabled, skipping entry")
|
||||
continue
|
||||
|
||||
additional_request_data = kwargs.get("_additional_request_data", dict())
|
||||
@@ -879,10 +903,11 @@ class Server(object):
|
||||
kwargs.update(additional_request_data)
|
||||
|
||||
try:
|
||||
start = time.time()
|
||||
if plugin:
|
||||
self._logger.info("Preemptively caching {} (ui {}) for {!r}".format(route, plugin, kwargs))
|
||||
logger.info("Preemptively caching {} (ui {}) for {!r}".format(route, plugin, kwargs))
|
||||
else:
|
||||
self._logger.info("Preemptively caching {} (ui _default) for {!r}".format(route, kwargs))
|
||||
logger.info("Preemptively caching {} (ui _default) for {!r}".format(route, kwargs))
|
||||
|
||||
headers = kwargs.get("headers", dict())
|
||||
headers["X-Force-View"] = plugin if plugin else "_default"
|
||||
@@ -891,8 +916,10 @@ class Server(object):
|
||||
|
||||
builder = EnvironBuilder(**kwargs)
|
||||
app(builder.get_environ(), lambda *a, **kw: None)
|
||||
|
||||
logger.info("... done in {:.2f}s".format(time.time() - start))
|
||||
except:
|
||||
self._logger.exception("Error while trying to preemptively cache {} for {!r}".format(route, kwargs))
|
||||
logger.exception("Error while trying to preemptively cache {} for {!r}".format(route, kwargs))
|
||||
|
||||
# asynchronous caching
|
||||
import threading
|
||||
@@ -1073,7 +1100,6 @@ class Server(object):
|
||||
|
||||
enable_gcodeviewer = self._settings.getBoolean(["gcodeViewer", "enabled"])
|
||||
preferred_stylesheet = self._settings.get(["devel", "stylesheet"])
|
||||
minify = self._settings.getBoolean(["devel", "webassets", "minify"])
|
||||
|
||||
dynamic_core_assets = util.flask.collect_core_assets(enable_gcodeviewer=enable_gcodeviewer)
|
||||
dynamic_plugin_assets = util.flask.collect_plugin_assets(
|
||||
@@ -1082,7 +1108,7 @@ class Server(object):
|
||||
)
|
||||
|
||||
js_libs = [
|
||||
"js/lib/jquery/jquery.min.js" if minify else "js/lib/jquery/jquery.js",
|
||||
"js/lib/jquery/jquery.js",
|
||||
"js/lib/modernizr.custom.js",
|
||||
"js/lib/lodash.min.js",
|
||||
"js/lib/sprintf.min.js",
|
||||
@@ -1099,6 +1125,9 @@ class Server(object):
|
||||
"js/lib/jquery/jquery.ui.widget.js",
|
||||
"js/lib/jquery/jquery.ui.mouse.js",
|
||||
"js/lib/jquery/jquery.flot.js",
|
||||
"js/lib/jquery/jquery.flot.time.js",
|
||||
"js/lib/jquery/jquery.flot.crosshair.js",
|
||||
"js/lib/jquery/jquery.flot.resize.js",
|
||||
"js/lib/jquery/jquery.iframe-transport.js",
|
||||
"js/lib/jquery/jquery.fileupload.js",
|
||||
"js/lib/jquery/jquery.slimscroll.min.js",
|
||||
@@ -1120,7 +1149,7 @@ class Server(object):
|
||||
"js/lib/md5.min.js",
|
||||
"js/lib/bootstrap-slider-knockout-binding.js",
|
||||
"js/lib/loglevel.min.js",
|
||||
"js/lib/sockjs.min.js" if minify else "js/lib/sockjs.js"
|
||||
"js/lib/sockjs.js"
|
||||
]
|
||||
js_client = [
|
||||
"js/app/client/base.js",
|
||||
@@ -1149,14 +1178,14 @@ class Server(object):
|
||||
"js/app/helpers.js",
|
||||
"js/app/main.js"]
|
||||
js_plugins = dynamic_plugin_assets["external"]["js"]
|
||||
js_app = js_plugins + js_core
|
||||
|
||||
css_libs = [
|
||||
"css/bootstrap.min.css",
|
||||
"css/bootstrap-modal.css",
|
||||
"css/bootstrap-slider.css",
|
||||
"css/bootstrap-tabdrop.css",
|
||||
"css/font-awesome.min.css",
|
||||
"vendor/font-awesome-3.2.1/css/font-awesome.min.css",
|
||||
"vendor/font-awesome-4.7.0/css/font-awesome.min.css",
|
||||
"css/jquery.fileupload-ui.css",
|
||||
"css/pnotify.core.min.css",
|
||||
"css/pnotify.buttons.min.css",
|
||||
@@ -1164,93 +1193,65 @@ class Server(object):
|
||||
]
|
||||
css_core = list(dynamic_core_assets["css"]) + list(dynamic_plugin_assets["bundled"]["css"])
|
||||
css_plugins = list(dynamic_plugin_assets["external"]["css"])
|
||||
css_app = css_core + css_plugins
|
||||
|
||||
less_core = list(dynamic_core_assets["less"]) + list(dynamic_plugin_assets["bundled"]["less"])
|
||||
less_plugins = list(dynamic_plugin_assets["external"]["less"])
|
||||
less_app = less_core + less_plugins
|
||||
|
||||
from webassets.filter import register_filter, Filter
|
||||
from webassets.filter.cssrewrite.base import PatternRewriter
|
||||
import re
|
||||
class LessImportRewrite(PatternRewriter):
|
||||
name = "less_importrewrite"
|
||||
|
||||
patterns = {
|
||||
"import_rewrite": re.compile("(@import(\s+\(.*\))?\s+)\"(.*)\";")
|
||||
}
|
||||
|
||||
def import_rewrite(self, m):
|
||||
import_with_options = m.group(1)
|
||||
import_url = m.group(3)
|
||||
|
||||
if not import_url.startswith("http:") and not import_url.startswith("https:") and not import_url.startswith("/"):
|
||||
import_url = "../less/" + import_url
|
||||
|
||||
return "{import_with_options}\"{import_url}\";".format(**locals())
|
||||
|
||||
class JsDelimiterBundler(Filter):
|
||||
name = "js_delimiter_bundler"
|
||||
options = {}
|
||||
def input(self, _in, out, **kwargs):
|
||||
out.write(_in.read())
|
||||
out.write("\n;\n")
|
||||
# a couple of custom filters
|
||||
from octoprint.server.util.webassets import LessImportRewrite, JsDelimiterBundler, SourceMapRewrite, SourceMapRemove
|
||||
from webassets.filter import register_filter
|
||||
|
||||
register_filter(LessImportRewrite)
|
||||
register_filter(SourceMapRewrite)
|
||||
register_filter(SourceMapRemove)
|
||||
register_filter(JsDelimiterBundler)
|
||||
|
||||
# JS
|
||||
js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters="js_delimiter_bundler")
|
||||
if minify:
|
||||
js_client_bundle = Bundle(*js_client, output="webassets/packed_client.js", filters="rjsmin, js_delimiter_bundler")
|
||||
js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters="rjsmin, js_delimiter_bundler")
|
||||
if len(js_plugins) == 0:
|
||||
js_plugins_bundle = Bundle(*[])
|
||||
else:
|
||||
js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters="rjsmin, js_delimiter_bundler")
|
||||
js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="rjsmin, js_delimiter_bundler")
|
||||
js_filters = ["sourcemap_remove", "js_delimiter_bundler"]
|
||||
|
||||
js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters=",".join(js_filters))
|
||||
|
||||
js_client_bundle = Bundle(*js_client, output="webassets/packed_client.js", filters=",".join(js_filters))
|
||||
js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters=",".join(js_filters))
|
||||
|
||||
if len(js_plugins) == 0:
|
||||
js_plugins_bundle = Bundle(*[])
|
||||
else:
|
||||
js_client_bundle = Bundle(*js_client, output="webassets/packed_client.js", filters="js_delimiter_bundler")
|
||||
js_core_bundle = Bundle(*js_core, output="webassets/packed_core.js", filters="js_delimiter_bundler")
|
||||
if len(js_plugins) == 0:
|
||||
js_plugins_bundle = Bundle(*[])
|
||||
else:
|
||||
js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters="js_delimiter_bundler")
|
||||
js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="js_delimiter_bundler")
|
||||
js_plugins_bundle = Bundle(*js_plugins, output="webassets/packed_plugins.js", filters=",".join(js_filters))
|
||||
|
||||
js_app_bundle = Bundle(js_plugins_bundle, js_core_bundle, output="webassets/packed_app.js", filters=",".join(js_filters))
|
||||
|
||||
# CSS
|
||||
css_libs_bundle = Bundle(*css_libs, output="webassets/packed_libs.css")
|
||||
css_filters = ["cssrewrite"]
|
||||
|
||||
css_libs_bundle = Bundle(*css_libs, output="webassets/packed_libs.css", filters=",".join(css_filters))
|
||||
|
||||
if len(css_core) == 0:
|
||||
css_core_bundle = Bundle(*[])
|
||||
else:
|
||||
css_core_bundle = Bundle(*css_core, output="webassets/packed_core.css", filters="cssrewrite")
|
||||
css_core_bundle = Bundle(*css_core, output="webassets/packed_core.css", filters=",".join(css_filters))
|
||||
|
||||
if len(css_plugins) == 0:
|
||||
css_plugins_bundle = Bundle(*[])
|
||||
else:
|
||||
css_plugins_bundle = Bundle(*css_plugins, output="webassets/packed_plugins.css", filters="cssrewrite")
|
||||
css_plugins_bundle = Bundle(*css_plugins, output="webassets/packed_plugins.css", filters=",".join(css_filters))
|
||||
|
||||
if len(css_app) == 0:
|
||||
css_app_bundle = Bundle(*[])
|
||||
else:
|
||||
css_app_bundle = Bundle(*css_app, output="webassets/packed_app.css", filters="cssrewrite")
|
||||
css_app_bundle = Bundle(css_core, css_plugins, output="webassets/packed_app.css", filters=",".join(css_filters))
|
||||
|
||||
# LESS
|
||||
less_filters = ["cssrewrite", "less_importrewrite"]
|
||||
|
||||
if len(less_core) == 0:
|
||||
less_core_bundle = Bundle(*[])
|
||||
else:
|
||||
less_core_bundle = Bundle(*less_core, output="webassets/packed_core.less", filters="cssrewrite, less_importrewrite")
|
||||
less_core_bundle = Bundle(*less_core, output="webassets/packed_core.less", filters=",".join(less_filters))
|
||||
|
||||
if len(less_plugins) == 0:
|
||||
less_plugins_bundle = Bundle(*[])
|
||||
else:
|
||||
less_plugins_bundle = Bundle(*less_plugins, output="webassets/packed_plugins.less", filters="cssrewrite, less_importrewrite")
|
||||
less_plugins_bundle = Bundle(*less_plugins, output="webassets/packed_plugins.less", filters=",".join(less_filters))
|
||||
|
||||
if len(less_app) == 0:
|
||||
less_app_bundle = Bundle(*[])
|
||||
else:
|
||||
less_app_bundle = Bundle(*less_app, output="webassets/packed_app.less", filters="cssrewrite, less_importrewrite")
|
||||
less_app_bundle = Bundle(less_core, less_plugins, output="webassets/packed_app.less", filters=",".join(less_filters))
|
||||
|
||||
# asset registration
|
||||
assets.register("js_libs", js_libs_bundle)
|
||||
|
||||
@@ -209,7 +209,7 @@ def login():
|
||||
if octoprint.server.userManager.checkPassword(username, password):
|
||||
if octoprint.server.userManager.enabled:
|
||||
user = octoprint.server.userManager.login_user(user)
|
||||
session["usersession.id"] = user.get_session()
|
||||
session["usersession.id"] = user.session
|
||||
g.user = user
|
||||
login_user(user, remember=remember)
|
||||
identity_changed.send(current_app._get_current_object(), identity=Identity(user.get_id()))
|
||||
|
||||
@@ -80,8 +80,8 @@ def _get_options():
|
||||
default_profile = printerProfileManager.get_default()
|
||||
|
||||
options = dict(
|
||||
ports=connection_options["ports"],
|
||||
baudrates=connection_options["baudrates"],
|
||||
ports=sorted(connection_options["ports"]),
|
||||
baudrates=sorted(connection_options["baudrates"], reverse=True),
|
||||
printerProfiles=[dict(id=printer_profile["id"], name=printer_profile["name"] if "name" in printer_profile else printer_profile["id"]) for printer_profile in profile_options.values() if "id" in printer_profile],
|
||||
portPreference=connection_options["portPreference"],
|
||||
baudratePreference=connection_options["baudratePreference"],
|
||||
|
||||
@@ -11,6 +11,8 @@ import copy
|
||||
from flask import jsonify, make_response, request, url_for
|
||||
from werkzeug.exceptions import BadRequest
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
from octoprint.server.api import api, NO_CONTENT, valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access, with_revalidation_checking
|
||||
from octoprint.util import dict_merge
|
||||
@@ -19,7 +21,6 @@ from octoprint.server import printerProfileManager
|
||||
from octoprint.printer.profile import InvalidProfileError, CouldNotOverwriteError
|
||||
from octoprint.access.permissions import Permissions
|
||||
|
||||
|
||||
def _lastmodified():
|
||||
return printerProfileManager.last_modified
|
||||
|
||||
|
||||
@@ -99,6 +99,8 @@ def getSettings():
|
||||
},
|
||||
"webcam": {
|
||||
"streamUrl": s.get(["webcam", "stream"]),
|
||||
"streamRatio": s.get(["webcam", "streamRatio"]),
|
||||
"streamTimeout": s.getInt(["webcam", "streamTimeout"]),
|
||||
"snapshotUrl": s.get(["webcam", "snapshot"]),
|
||||
"ffmpegPath": s.get(["webcam", "ffmpeg"]),
|
||||
"bitrate": s.get(["webcam", "bitrate"]),
|
||||
@@ -128,7 +130,8 @@ def getSettings():
|
||||
"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]),
|
||||
"firmwareDetection": s.getBoolean(["feature", "firmwareDetection"]),
|
||||
"printCancelConfirmation": s.getBoolean(["feature", "printCancelConfirmation"]),
|
||||
"blockWhileDwelling": s.getBoolean(["feature", "blockWhileDwelling"])
|
||||
"blockWhileDwelling": s.getBoolean(["feature", "blockWhileDwelling"]),
|
||||
"g90InfluencesExtruder": s.getBoolean(["feature", "g90InfluencesExtruder"])
|
||||
},
|
||||
"serial": {
|
||||
"port": connectionOptions["portPreference"],
|
||||
@@ -141,6 +144,7 @@ def getSettings():
|
||||
"timeoutCommunication": s.getFloat(["serial", "timeout", "communication"]),
|
||||
"timeoutTemperature": s.getFloat(["serial", "timeout", "temperature"]),
|
||||
"timeoutTemperatureTargetSet": s.getFloat(["serial", "timeout", "temperatureTargetSet"]),
|
||||
"timeoutTemperatureAutoreport": s.getFloat(["serial", "timeout", "temperatureAutoreport"]),
|
||||
"timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]),
|
||||
"log": s.getBoolean(["serial", "log"]),
|
||||
"additionalPorts": s.get(["serial", "additionalPorts"]),
|
||||
@@ -165,7 +169,9 @@ def getSettings():
|
||||
},
|
||||
"temperature": {
|
||||
"profiles": s.get(["temperature", "profiles"]),
|
||||
"cutoff": s.getInt(["temperature", "cutoff"])
|
||||
"cutoff": s.getInt(["temperature", "cutoff"]),
|
||||
"sendAutomatically": s.getBoolean(["temperature", "sendAutomatically"]),
|
||||
"sendAutomaticallyAfter": s.getInt(["temperature", "sendAutomaticallyAfter"], min=0, max=30),
|
||||
},
|
||||
"system": {
|
||||
"actions": s.get(["system", "actions"]),
|
||||
@@ -181,6 +187,8 @@ def getSettings():
|
||||
"afterPrintDone": None,
|
||||
"beforePrintPaused": None,
|
||||
"afterPrintResumed": None,
|
||||
"beforeToolChange": None,
|
||||
"afterToolChange": None,
|
||||
"snippets": dict()
|
||||
}
|
||||
},
|
||||
@@ -259,6 +267,10 @@ def setSettings():
|
||||
if data is None:
|
||||
return make_response("Malformed JSON body in request", 400)
|
||||
|
||||
if not isinstance(data, dict):
|
||||
return make_response("Malformed request, need settings dictionary, "
|
||||
"got a {} instead: {!r}".format(type(data).__name__, data), 400)
|
||||
|
||||
_saveSettings(data)
|
||||
return getSettings()
|
||||
|
||||
@@ -303,6 +315,8 @@ def _saveSettings(data):
|
||||
|
||||
if "webcam" in data.keys():
|
||||
if "streamUrl" in data["webcam"]: s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
|
||||
if "streamRatio" in data["webcam"] and data["webcam"]["streamRatio"] in ("16:9", "4:3"): s.set(["webcam", "streamRatio"], data["webcam"]["streamRatio"])
|
||||
if "streamTimeout" in data["webcam"]: s.setInt(["webcam", "streamTimeout"], data["webcam"]["streamTimeout"])
|
||||
if "snapshotUrl" in data["webcam"]: s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
|
||||
if "ffmpegPath" in data["webcam"]: s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"])
|
||||
if "bitrate" in data["webcam"]: s.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
|
||||
@@ -333,6 +347,7 @@ def _saveSettings(data):
|
||||
if "firmwareDetection" in data["feature"]: s.setBoolean(["feature", "firmwareDetection"], data["feature"]["firmwareDetection"])
|
||||
if "printCancelConfirmation" in data["feature"]: s.setBoolean(["feature", "printCancelConfirmation"], data["feature"]["printCancelConfirmation"])
|
||||
if "blockWhileDwelling" in data["feature"]: s.setBoolean(["feature", "blockWhileDwelling"], data["feature"]["blockWhileDwelling"])
|
||||
if "g90InfluencesExtruder" in data["feature"]: s.setBoolean(["feature", "g90InfluencesExtruder"], data["feature"]["g90InfluencesExtruder"])
|
||||
|
||||
if "serial" in data.keys():
|
||||
if "autoconnect" in data["serial"]: s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
|
||||
@@ -343,6 +358,7 @@ def _saveSettings(data):
|
||||
if "timeoutCommunication" in data["serial"]: s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"])
|
||||
if "timeoutTemperature" in data["serial"]: s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"])
|
||||
if "timeoutTemperatureTargetSet" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"])
|
||||
if "timeoutTemperatureAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureAutoreport"], data["serial"]["timeoutTemperatureAutoreport"])
|
||||
if "timeoutSdStatus" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
|
||||
if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"])
|
||||
if "additionalBaudrates" in data["serial"] and isinstance(data["serial"]["additionalBaudrates"], (list, tuple)): s.set(["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"])
|
||||
@@ -378,6 +394,8 @@ def _saveSettings(data):
|
||||
if "temperature" in data.keys():
|
||||
if "profiles" in data["temperature"]: s.set(["temperature", "profiles"], data["temperature"]["profiles"])
|
||||
if "cutoff" in data["temperature"]: s.setInt(["temperature", "cutoff"], data["temperature"]["cutoff"])
|
||||
if "sendAutomatically" in data["temperature"]: s.setBoolean(["temperature", "sendAutomatically"], data["temperature"]["sendAutomatically"])
|
||||
if "sendAutomaticallyAfter" in data["temperature"]: s.setInt(["temperature", "sendAutomaticallyAfter"], data["temperature"]["sendAutomaticallyAfter"], min=0, max=30)
|
||||
|
||||
if "terminalFilters" in data.keys():
|
||||
s.set(["terminalFilters"], data["terminalFilters"])
|
||||
|
||||
@@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import os
|
||||
import threading
|
||||
import logging
|
||||
|
||||
from flask import request, jsonify, url_for, make_response
|
||||
|
||||
@@ -131,7 +132,12 @@ def deleteTimelapse(filename):
|
||||
timelapse_folder = settings().getBaseFolder("timelapse")
|
||||
full_path = os.path.realpath(os.path.join(timelapse_folder, filename))
|
||||
if full_path.startswith(timelapse_folder) and os.path.exists(full_path):
|
||||
os.remove(full_path)
|
||||
try:
|
||||
os.remove(full_path)
|
||||
except Exception as ex:
|
||||
logging.getLogger(__file__).exception("Error deleting timelapse file {}".format(full_path))
|
||||
return make_response("Unexpected error: {}".format(ex), 500)
|
||||
|
||||
return getTimelapseData()
|
||||
|
||||
|
||||
|
||||
@@ -30,6 +30,8 @@ import octoprint.plugin
|
||||
|
||||
from werkzeug.contrib.cache import BaseCache
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
try:
|
||||
from os import scandir, walk
|
||||
except ImportError:
|
||||
@@ -507,8 +509,8 @@ def passive_login():
|
||||
|
||||
if user is not None and not user.is_anonymous:
|
||||
flask_principal.identity_changed.send(flask.current_app._get_current_object(), identity=flask_principal.Identity(user.get_id()))
|
||||
if hasattr(user, "get_session"):
|
||||
flask.session["usersession.id"] = user.get_session()
|
||||
if hasattr(user, "session"):
|
||||
flask.session["usersession.id"] = user.session
|
||||
flask.g.user = user
|
||||
return flask.jsonify(user)
|
||||
elif settings().getBoolean(["accessControl", "autologinLocal"]) \
|
||||
@@ -526,7 +528,7 @@ def passive_login():
|
||||
user = octoprint.server.userManager.findUser(autologinAs)
|
||||
if user is not None:
|
||||
user = octoprint.server.userManager.login_user(user)
|
||||
flask.session["usersession.id"] = user.get_session()
|
||||
flask.session["usersession.id"] = user.session
|
||||
flask.g.user = user
|
||||
|
||||
flask_login.login_user(user)
|
||||
|
||||
@@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import logging
|
||||
import threading
|
||||
import sockjs.tornado
|
||||
import sockjs.tornado.session
|
||||
import time
|
||||
|
||||
import octoprint.timelapse
|
||||
@@ -21,6 +22,34 @@ from octoprint.settings import settings
|
||||
import octoprint.printer
|
||||
|
||||
|
||||
class ThreadSafeSession(sockjs.tornado.session.Session):
|
||||
def __init__(self, conn, server, session_id, expiry=None):
|
||||
sockjs.tornado.session.Session.__init__(self, conn, server, session_id, expiry=expiry)
|
||||
|
||||
def set_handler(self, handler, start_heartbeat=True):
|
||||
if getattr(handler, "__orig_send_pack", None) is None:
|
||||
orig_send_pack = handler.send_pack
|
||||
mutex = threading.RLock()
|
||||
|
||||
def send_pack(*args, **kwargs):
|
||||
with mutex:
|
||||
return orig_send_pack(*args, **kwargs)
|
||||
|
||||
handler.send_pack = send_pack
|
||||
setattr(handler, "__orig_send_pack", orig_send_pack)
|
||||
|
||||
return sockjs.tornado.session.Session.set_handler(self, handler, start_heartbeat=start_heartbeat)
|
||||
|
||||
def remove_handler(self, handler):
|
||||
result = sockjs.tornado.session.Session.remove_handler(self, handler)
|
||||
|
||||
if getattr(handler, "__orig_send_pack", None) is not None:
|
||||
handler.send_pack = getattr(handler, "__orig_send_pack")
|
||||
delattr(handler, "__orig_send_pack")
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback):
|
||||
def __init__(self, printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session):
|
||||
sockjs.tornado.SockJSConnection.__init__(self, session)
|
||||
@@ -47,8 +76,6 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
|
||||
self._lastCurrent = 0
|
||||
self._baseRateLimit = 0.5
|
||||
|
||||
self._emit_mutex = threading.RLock()
|
||||
|
||||
def _getRemoteAddress(self, info):
|
||||
forwardedFor = info.headers.get("X-Forwarded-For")
|
||||
if forwardedFor is not None:
|
||||
@@ -205,11 +232,10 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
|
||||
self.sendEvent(event, payload)
|
||||
|
||||
def _emit(self, type, payload):
|
||||
with self._emit_mutex:
|
||||
try:
|
||||
self.send({type: payload})
|
||||
except Exception as e:
|
||||
if self._logger.isEnabledFor(logging.DEBUG):
|
||||
self._logger.exception("Could not send message to client {}".format(self._remoteAddress))
|
||||
else:
|
||||
self._logger.warn("Could not send message to client {}: {}".format(self._remoteAddress, e))
|
||||
try:
|
||||
self.send({type: payload})
|
||||
except Exception as e:
|
||||
if self._logger.isEnabledFor(logging.DEBUG):
|
||||
self._logger.exception("Could not send message to client {}".format(self._remoteAddress))
|
||||
else:
|
||||
self._logger.warn("Could not send message to client {}: {}".format(self._remoteAddress, e))
|
||||
@@ -497,9 +497,20 @@ class WsgiInputContainer(object):
|
||||
methods have been adjusted to allow for an optionally supplied ``body`` argument which is then used for ``wsgi.input``.
|
||||
"""
|
||||
|
||||
def __init__(self, wsgi_application):
|
||||
def __init__(self, wsgi_application, headers=None, forced_headers=None, removed_headers=None):
|
||||
self.wsgi_application = wsgi_application
|
||||
|
||||
if headers is None:
|
||||
headers = dict()
|
||||
if forced_headers is None:
|
||||
forced_headers = dict()
|
||||
if removed_headers is None:
|
||||
removed_headers = []
|
||||
|
||||
self.headers = headers
|
||||
self.forced_headers = forced_headers
|
||||
self.removed_headers = removed_headers
|
||||
|
||||
def __call__(self, request, body=None):
|
||||
"""
|
||||
Wraps the call against the WSGI app, deriving the WSGI environment from the supplied Tornado ``HTTPServerRequest``.
|
||||
@@ -536,8 +547,14 @@ class WsgiInputContainer(object):
|
||||
headers.append(("Content-Length", str(len(body))))
|
||||
if "content-type" not in header_set:
|
||||
headers.append(("Content-Type", "text/html; charset=UTF-8"))
|
||||
if "server" not in header_set:
|
||||
headers.append(("Server", "TornadoServer/%s" % tornado.version))
|
||||
|
||||
header_set = set(k.lower() for (k, v) in headers)
|
||||
for header, value in self.headers.items():
|
||||
if header.lower() not in header_set:
|
||||
headers.append((header, value))
|
||||
for header, value in self.forced_headers.items():
|
||||
headers.append((header, value))
|
||||
headers = [(header, value) for header, value in headers if not header.lower() in self.removed_headers]
|
||||
|
||||
start_line = tornado.httputil.ResponseStartLine("HTTP/1.1", status_code, reason)
|
||||
header_obj = tornado.httputil.HTTPHeaders()
|
||||
@@ -1000,6 +1017,39 @@ class StaticDataHandler(tornado.web.RequestHandler):
|
||||
self.finish()
|
||||
|
||||
|
||||
class GlobalHeaderTransform(tornado.web.OutputTransform):
|
||||
|
||||
HEADERS = dict()
|
||||
FORCED_HEADERS = dict()
|
||||
REMOVED_HEADERS = []
|
||||
|
||||
@classmethod
|
||||
def for_headers(cls, name, headers=None, forced_headers=None, removed_headers=None):
|
||||
if headers is None:
|
||||
headers = dict()
|
||||
if forced_headers is None:
|
||||
forced_headers = dict()
|
||||
if removed_headers is None:
|
||||
removed_headers = []
|
||||
|
||||
return type(name, (GlobalHeaderTransform,), dict(HEADERS=headers,
|
||||
FORCED_HEADERS=forced_headers,
|
||||
REMOVED_HEADERS=removed_headers))
|
||||
|
||||
def __init__(self, request):
|
||||
tornado.web.OutputTransform.__init__(self, request)
|
||||
|
||||
def transform_first_chunk(self, status_code, headers, chunk, finishing):
|
||||
for header, value in self.HEADERS.items():
|
||||
if not header in headers:
|
||||
headers[header] = value
|
||||
for header, value in self.FORCED_HEADERS.items():
|
||||
headers[header] = value
|
||||
for header in self.REMOVED_HEADERS:
|
||||
del headers[header]
|
||||
return status_code, headers, chunk
|
||||
|
||||
|
||||
#~~ Factory method for creating Flask access validation wrappers from the Tornado request context
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__author__ = "Gina Häußge <gina@octoprint.org>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import re
|
||||
|
||||
try:
|
||||
from urllib import parse as urlparse
|
||||
except:
|
||||
import urlparse
|
||||
|
||||
from webassets.filter import Filter
|
||||
from webassets.filter.cssrewrite.base import PatternRewriter
|
||||
import webassets.filter.cssrewrite.urlpath as urlpath
|
||||
|
||||
|
||||
def replace_url(source_url, output_url, url):
|
||||
# If path is an absolute one, keep it
|
||||
parsed = urlparse.urlparse(url)
|
||||
|
||||
if not parsed.scheme and not parsed.path.startswith('/'):
|
||||
abs_source_url = urlparse.urljoin(source_url, url)
|
||||
|
||||
# relpath() will not detect this case
|
||||
if urlparse.urlparse(abs_source_url).scheme:
|
||||
return abs_source_url
|
||||
|
||||
# rewritten url: relative path from new location (output)
|
||||
# to location of referenced file (source + current url)
|
||||
url = urlpath.relpath(output_url, abs_source_url)
|
||||
|
||||
return url
|
||||
|
||||
|
||||
class UrlRewriter(PatternRewriter):
|
||||
|
||||
def input(self, _in, out, **kw):
|
||||
source, source_path, output, output_path = \
|
||||
kw['source'], kw['source_path'], kw['output'], kw['output_path']
|
||||
|
||||
self.source_path = source_path
|
||||
self.output_path = output_path
|
||||
self.source_url = self.ctx.resolver.resolve_source_to_url(
|
||||
self.ctx, source_path, source)
|
||||
self.output_url = self.ctx.resolver.resolve_output_to_url(
|
||||
self.ctx, output)
|
||||
|
||||
return super(UrlRewriter, self).input(_in, out, **kw)
|
||||
|
||||
def replace_url(self, url):
|
||||
return replace_url(self.source_url, self.output_url, url)
|
||||
|
||||
|
||||
class LessImportRewrite(UrlRewriter):
|
||||
name = "less_importrewrite"
|
||||
|
||||
patterns = {
|
||||
"import_rewrite": re.compile("(@import(\s+\(.*\))?\s+)\"(.*)\";")
|
||||
}
|
||||
|
||||
def import_rewrite(self, m):
|
||||
import_with_options = m.group(1)
|
||||
import_url = self.replace_url(m.group(3))
|
||||
return "{import_with_options}\"{import_url}\";".format(**locals())
|
||||
|
||||
|
||||
class SourceMapRewrite(UrlRewriter):
|
||||
name = "sourcemap_urlrewrite"
|
||||
|
||||
patterns = {
|
||||
"url_rewrite": re.compile("(//#\s+sourceMappingURL=)(.*)")
|
||||
}
|
||||
|
||||
def url_rewrite(self, m):
|
||||
mapping = m.group(1)
|
||||
source_url = self.replace_url(m.group(2))
|
||||
return "{mapping}{source_url}".format(**locals())
|
||||
|
||||
|
||||
class SourceMapRemove(PatternRewriter):
|
||||
name = "sourcemap_remove"
|
||||
|
||||
patterns = {
|
||||
"sourcemap_remove": re.compile("(//#\s+sourceMappingURL=)(.*)")
|
||||
}
|
||||
|
||||
def sourcemap_remove(self, m):
|
||||
return ""
|
||||
|
||||
|
||||
class JsDelimiterBundler(Filter):
|
||||
name = "js_delimiter_bundler"
|
||||
options = {}
|
||||
|
||||
def input(self, _in, out, **kwargs):
|
||||
out.write(_in.read())
|
||||
out.write("\n;\n")
|
||||
@@ -9,6 +9,8 @@ import os
|
||||
import datetime
|
||||
import codecs
|
||||
|
||||
from past.builtins import basestring
|
||||
|
||||
from collections import defaultdict
|
||||
from flask import request, g, url_for, make_response, render_template, send_from_directory, redirect, abort
|
||||
|
||||
@@ -518,14 +520,10 @@ def _process_templates():
|
||||
# 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.hasPermission(access.permissions.CONNECTION)")),
|
||||
state=(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-sign", data_bind="visible: loginState.hasPermission(access.permissions.STATUS)")),
|
||||
files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], template_header="sidebar/files_header.jinja2", data_bind="visible: loginState.hasPermission(access.permissions.DOWNLOAD)() || \
|
||||
loginState.hasPermission(access.permissions.UPLOAD)() || \
|
||||
loginState.hasPermission(access.permissions.DELETE)() || \
|
||||
loginState.hasPermission(access.permissions.SELECT)() || \
|
||||
loginState.hasPermission(access.permissions.PRINT)() || \
|
||||
loginState.hasPermission(access.permissions.SLICE)()"))
|
||||
connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none"], permission_test="access.permissions.CONNECTION")),
|
||||
state=(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-circle", permission_test="access.permissions.STATUS")),
|
||||
files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], template_header="sidebar/files_header.jinja2",
|
||||
permission_test="access.permissions.DOWNLOAD, access.permissions.UPLOAD, access.permissions.DELETE, access.permissions.SELECT, access.permissions.PRINT, access.permissions.SLICE]"))
|
||||
)
|
||||
|
||||
# tabs
|
||||
|
||||
@@ -34,6 +34,7 @@ import copy
|
||||
import time
|
||||
|
||||
from builtins import bytes
|
||||
from past.builtins import basestring
|
||||
|
||||
try:
|
||||
from collections import ChainMap
|
||||
@@ -93,6 +94,7 @@ default_settings = {
|
||||
"communication": 30,
|
||||
"temperature": 5,
|
||||
"temperatureTargetSet": 2,
|
||||
"temperatureAutoreport": 2,
|
||||
"sdStatus": 1
|
||||
},
|
||||
"maxCommunicationTimeouts": {
|
||||
@@ -155,6 +157,8 @@ default_settings = {
|
||||
},
|
||||
"webcam": {
|
||||
"stream": None,
|
||||
"streamRatio": "16:9",
|
||||
"streamTimeout": 5,
|
||||
"snapshot": None,
|
||||
"ffmpeg": None,
|
||||
"ffmpegThreads": 1,
|
||||
@@ -204,7 +208,8 @@ default_settings = {
|
||||
"modelSizeDetection": True,
|
||||
"firmwareDetection": True,
|
||||
"printCancelConfirmation": True,
|
||||
"blockWhileDwelling": False
|
||||
"blockWhileDwelling": False,
|
||||
"g90InfluencesExtruder": False
|
||||
},
|
||||
"folder": {
|
||||
"uploads": None,
|
||||
@@ -226,7 +231,9 @@ default_settings = {
|
||||
{"name": "ABS", "extruder" : 210, "bed" : 100 },
|
||||
{"name": "PLA", "extruder" : 180, "bed" : 60 }
|
||||
],
|
||||
"cutoff": 30
|
||||
"cutoff": 30,
|
||||
"sendAutomatically": False,
|
||||
"sendAutomaticallyAfter": 1,
|
||||
},
|
||||
"printerProfiles": {
|
||||
"default": None
|
||||
@@ -298,7 +305,7 @@ default_settings = {
|
||||
"apps": {}
|
||||
},
|
||||
"terminalFilters": [
|
||||
{ "name": "Suppress temperature messages", "regex": "(Send: (N\d+\s+)?M105)|(Recv: ok (B|T\d*):)" },
|
||||
{ "name": "Suppress temperature messages", "regex": "(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?(B|T\d*):)" },
|
||||
{ "name": "Suppress SD status messages", "regex": "(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)" },
|
||||
{ "name": "Suppress wait responses", "regex": "Recv: wait"}
|
||||
],
|
||||
@@ -330,7 +337,6 @@ default_settings = {
|
||||
"preemptive": True
|
||||
},
|
||||
"webassets": {
|
||||
"minify": False,
|
||||
"bundle": True,
|
||||
"clean_on_startup": True
|
||||
},
|
||||
@@ -364,7 +370,11 @@ default_settings = {
|
||||
"simulateReset": True,
|
||||
"preparedOks": [],
|
||||
"okFormatString": "ok",
|
||||
"m115FormatString": "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0"
|
||||
"m115FormatString": "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0",
|
||||
"m115ReportCapabilities": False,
|
||||
"capabilities": {
|
||||
"AUTOREPORT_TEMP": True
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1270,23 +1280,43 @@ class Settings(object):
|
||||
return None
|
||||
|
||||
def getInt(self, path, **kwargs):
|
||||
minimum = kwargs.pop("min", None)
|
||||
maximum = kwargs.pop("max", None)
|
||||
|
||||
value = self.get(path, **kwargs)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
return int(value)
|
||||
intValue = int(value)
|
||||
|
||||
if minimum is not None and intValue < minimum:
|
||||
return minimum
|
||||
elif maximum is not None and intValue > maximum:
|
||||
return maximum
|
||||
else:
|
||||
return intValue
|
||||
except ValueError:
|
||||
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
|
||||
return None
|
||||
|
||||
def getFloat(self, path, **kwargs):
|
||||
minimum = kwargs.pop("min", None)
|
||||
maximum = kwargs.pop("max", None)
|
||||
|
||||
value = self.get(path, **kwargs)
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
return float(value)
|
||||
floatValue = float(value)
|
||||
|
||||
if minimum is not None and floatValue < minimum:
|
||||
return minimum
|
||||
elif maximum is not None and floatValue > maximum:
|
||||
return maximum
|
||||
else:
|
||||
return floatValue
|
||||
except ValueError:
|
||||
self._logger.warn("Could not convert %r to a valid integer when getting option %r" % (value, path))
|
||||
return None
|
||||
@@ -1314,11 +1344,14 @@ class Settings(object):
|
||||
if folder is None:
|
||||
folder = self._get_default_folder(type)
|
||||
|
||||
if not os.path.isdir(folder):
|
||||
if not os.path.exists(folder):
|
||||
if create:
|
||||
os.makedirs(folder)
|
||||
else:
|
||||
raise IOError("No such folder: {folder}".format(folder=folder))
|
||||
raise IOError("No such folder: {}".format(folder))
|
||||
elif os.path.isfile(folder):
|
||||
# hardening against misconfiguration, see #1953
|
||||
raise IOError("Expected a folder at {} but found a file instead".format(folder))
|
||||
|
||||
return folder
|
||||
|
||||
@@ -1439,8 +1472,16 @@ class Settings(object):
|
||||
self.set(path, None, **kwargs)
|
||||
return
|
||||
|
||||
minimum = kwargs.pop("min", None)
|
||||
maximum = kwargs.pop("max", None)
|
||||
|
||||
try:
|
||||
intValue = int(value)
|
||||
|
||||
if minimum is not None and intValue < minimum:
|
||||
intValue = minimum
|
||||
if maximum is not None and intValue > maximum:
|
||||
intValue = maximum
|
||||
except ValueError:
|
||||
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
|
||||
return
|
||||
@@ -1452,8 +1493,16 @@ class Settings(object):
|
||||
self.set(path, None, **kwargs)
|
||||
return
|
||||
|
||||
minimum = kwargs.pop("min", None)
|
||||
maximum = kwargs.pop("max", None)
|
||||
|
||||
try:
|
||||
floatValue = float(value)
|
||||
|
||||
if minimum is not None and floatValue < minimum:
|
||||
floatValue = minimum
|
||||
if maximum is not None and floatValue > maximum:
|
||||
floatValue = maximum
|
||||
except ValueError:
|
||||
self._logger.warn("Could not convert %r to a valid integer when setting option %r" % (value, path))
|
||||
return
|
||||
|
||||
-403
@@ -1,403 +0,0 @@
|
||||
@font-face{font-family:'FontAwesome';src:url('../font/fontawesome-webfont.eot?v=3.2.1');src:url('../font/fontawesome-webfont.eot?#iefix&v=3.2.1') format('embedded-opentype'),url('../font/fontawesome-webfont.woff?v=3.2.1') format('woff'),url('../font/fontawesome-webfont.ttf?v=3.2.1') format('truetype'),url('../font/fontawesome-webfont.svg#fontawesomeregular?v=3.2.1') format('svg');font-weight:normal;font-style:normal;}[class^="icon-"],[class*=" icon-"]{font-family:FontAwesome;font-weight:normal;font-style:normal;text-decoration:inherit;-webkit-font-smoothing:antialiased;*margin-right:.3em;}
|
||||
[class^="icon-"]:before,[class*=" icon-"]:before{text-decoration:inherit;display:inline-block;speak:none;}
|
||||
.icon-large:before{vertical-align:-10%;font-size:1.3333333333333333em;}
|
||||
a [class^="icon-"],a [class*=" icon-"]{display:inline;}
|
||||
[class^="icon-"].icon-fixed-width,[class*=" icon-"].icon-fixed-width{display:inline-block;width:1.1428571428571428em;text-align:right;padding-right:0.2857142857142857em;}[class^="icon-"].icon-fixed-width.icon-large,[class*=" icon-"].icon-fixed-width.icon-large{width:1.4285714285714286em;}
|
||||
.icons-ul{margin-left:2.142857142857143em;list-style-type:none;}.icons-ul>li{position:relative;}
|
||||
.icons-ul .icon-li{position:absolute;left:-2.142857142857143em;width:2.142857142857143em;text-align:center;line-height:inherit;}
|
||||
[class^="icon-"].hide,[class*=" icon-"].hide{display:none;}
|
||||
.icon-muted{color:#eeeeee;}
|
||||
.icon-light{color:#ffffff;}
|
||||
.icon-dark{color:#333333;}
|
||||
.icon-border{border:solid 1px #eeeeee;padding:.2em .25em .15em;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;}
|
||||
.icon-2x{font-size:2em;}.icon-2x.icon-border{border-width:2px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}
|
||||
.icon-3x{font-size:3em;}.icon-3x.icon-border{border-width:3px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;}
|
||||
.icon-4x{font-size:4em;}.icon-4x.icon-border{border-width:4px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;}
|
||||
.icon-5x{font-size:5em;}.icon-5x.icon-border{border-width:5px;-webkit-border-radius:7px;-moz-border-radius:7px;border-radius:7px;}
|
||||
.pull-right{float:right;}
|
||||
.pull-left{float:left;}
|
||||
[class^="icon-"].pull-left,[class*=" icon-"].pull-left{margin-right:.3em;}
|
||||
[class^="icon-"].pull-right,[class*=" icon-"].pull-right{margin-left:.3em;}
|
||||
[class^="icon-"],[class*=" icon-"]{display:inline;width:auto;height:auto;line-height:normal;vertical-align:baseline;background-image:none;background-position:0% 0%;background-repeat:repeat;margin-top:0;}
|
||||
.icon-white,.nav-pills>.active>a>[class^="icon-"],.nav-pills>.active>a>[class*=" icon-"],.nav-list>.active>a>[class^="icon-"],.nav-list>.active>a>[class*=" icon-"],.navbar-inverse .nav>.active>a>[class^="icon-"],.navbar-inverse .nav>.active>a>[class*=" icon-"],.dropdown-menu>li>a:hover>[class^="icon-"],.dropdown-menu>li>a:hover>[class*=" icon-"],.dropdown-menu>.active>a>[class^="icon-"],.dropdown-menu>.active>a>[class*=" icon-"],.dropdown-submenu:hover>a>[class^="icon-"],.dropdown-submenu:hover>a>[class*=" icon-"]{background-image:none;}
|
||||
.btn [class^="icon-"].icon-large,.nav [class^="icon-"].icon-large,.btn [class*=" icon-"].icon-large,.nav [class*=" icon-"].icon-large{line-height:.9em;}
|
||||
.btn [class^="icon-"].icon-spin,.nav [class^="icon-"].icon-spin,.btn [class*=" icon-"].icon-spin,.nav [class*=" icon-"].icon-spin{display:inline-block;}
|
||||
.nav-tabs [class^="icon-"],.nav-pills [class^="icon-"],.nav-tabs [class*=" icon-"],.nav-pills [class*=" icon-"],.nav-tabs [class^="icon-"].icon-large,.nav-pills [class^="icon-"].icon-large,.nav-tabs [class*=" icon-"].icon-large,.nav-pills [class*=" icon-"].icon-large{line-height:.9em;}
|
||||
.btn [class^="icon-"].pull-left.icon-2x,.btn [class*=" icon-"].pull-left.icon-2x,.btn [class^="icon-"].pull-right.icon-2x,.btn [class*=" icon-"].pull-right.icon-2x{margin-top:.18em;}
|
||||
.btn [class^="icon-"].icon-spin.icon-large,.btn [class*=" icon-"].icon-spin.icon-large{line-height:.8em;}
|
||||
.btn.btn-small [class^="icon-"].pull-left.icon-2x,.btn.btn-small [class*=" icon-"].pull-left.icon-2x,.btn.btn-small [class^="icon-"].pull-right.icon-2x,.btn.btn-small [class*=" icon-"].pull-right.icon-2x{margin-top:.25em;}
|
||||
.btn.btn-large [class^="icon-"],.btn.btn-large [class*=" icon-"]{margin-top:0;}.btn.btn-large [class^="icon-"].pull-left.icon-2x,.btn.btn-large [class*=" icon-"].pull-left.icon-2x,.btn.btn-large [class^="icon-"].pull-right.icon-2x,.btn.btn-large [class*=" icon-"].pull-right.icon-2x{margin-top:.05em;}
|
||||
.btn.btn-large [class^="icon-"].pull-left.icon-2x,.btn.btn-large [class*=" icon-"].pull-left.icon-2x{margin-right:.2em;}
|
||||
.btn.btn-large [class^="icon-"].pull-right.icon-2x,.btn.btn-large [class*=" icon-"].pull-right.icon-2x{margin-left:.2em;}
|
||||
.nav-list [class^="icon-"],.nav-list [class*=" icon-"]{line-height:inherit;}
|
||||
.icon-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:-35%;}.icon-stack [class^="icon-"],.icon-stack [class*=" icon-"]{display:block;text-align:center;position:absolute;width:100%;height:100%;font-size:1em;line-height:inherit;*line-height:2em;}
|
||||
.icon-stack .icon-stack-base{font-size:2em;*line-height:1em;}
|
||||
.icon-spin{display:inline-block;-moz-animation:spin 2s infinite linear;-o-animation:spin 2s infinite linear;-webkit-animation:spin 2s infinite linear;animation:spin 2s infinite linear;}
|
||||
a .icon-stack,a .icon-spin{display:inline-block;text-decoration:none;}
|
||||
@-moz-keyframes spin{0%{-moz-transform:rotate(0deg);} 100%{-moz-transform:rotate(359deg);}}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0deg);} 100%{-webkit-transform:rotate(359deg);}}@-o-keyframes spin{0%{-o-transform:rotate(0deg);} 100%{-o-transform:rotate(359deg);}}@-ms-keyframes spin{0%{-ms-transform:rotate(0deg);} 100%{-ms-transform:rotate(359deg);}}@keyframes spin{0%{transform:rotate(0deg);} 100%{transform:rotate(359deg);}}.icon-rotate-90:before{-webkit-transform:rotate(90deg);-moz-transform:rotate(90deg);-ms-transform:rotate(90deg);-o-transform:rotate(90deg);transform:rotate(90deg);filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=1);}
|
||||
.icon-rotate-180:before{-webkit-transform:rotate(180deg);-moz-transform:rotate(180deg);-ms-transform:rotate(180deg);-o-transform:rotate(180deg);transform:rotate(180deg);filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);}
|
||||
.icon-rotate-270:before{-webkit-transform:rotate(270deg);-moz-transform:rotate(270deg);-ms-transform:rotate(270deg);-o-transform:rotate(270deg);transform:rotate(270deg);filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);}
|
||||
.icon-flip-horizontal:before{-webkit-transform:scale(-1, 1);-moz-transform:scale(-1, 1);-ms-transform:scale(-1, 1);-o-transform:scale(-1, 1);transform:scale(-1, 1);}
|
||||
.icon-flip-vertical:before{-webkit-transform:scale(1, -1);-moz-transform:scale(1, -1);-ms-transform:scale(1, -1);-o-transform:scale(1, -1);transform:scale(1, -1);}
|
||||
a .icon-rotate-90:before,a .icon-rotate-180:before,a .icon-rotate-270:before,a .icon-flip-horizontal:before,a .icon-flip-vertical:before{display:inline-block;}
|
||||
.icon-glass:before{content:"\f000";}
|
||||
.icon-music:before{content:"\f001";}
|
||||
.icon-search:before{content:"\f002";}
|
||||
.icon-envelope-alt:before{content:"\f003";}
|
||||
.icon-heart:before{content:"\f004";}
|
||||
.icon-star:before{content:"\f005";}
|
||||
.icon-star-empty:before{content:"\f006";}
|
||||
.icon-user:before{content:"\f007";}
|
||||
.icon-film:before{content:"\f008";}
|
||||
.icon-th-large:before{content:"\f009";}
|
||||
.icon-th:before{content:"\f00a";}
|
||||
.icon-th-list:before{content:"\f00b";}
|
||||
.icon-ok:before{content:"\f00c";}
|
||||
.icon-remove:before{content:"\f00d";}
|
||||
.icon-zoom-in:before{content:"\f00e";}
|
||||
.icon-zoom-out:before{content:"\f010";}
|
||||
.icon-power-off:before,.icon-off:before{content:"\f011";}
|
||||
.icon-signal:before{content:"\f012";}
|
||||
.icon-gear:before,.icon-cog:before{content:"\f013";}
|
||||
.icon-trash:before{content:"\f014";}
|
||||
.icon-home:before{content:"\f015";}
|
||||
.icon-file-alt:before{content:"\f016";}
|
||||
.icon-time:before{content:"\f017";}
|
||||
.icon-road:before{content:"\f018";}
|
||||
.icon-download-alt:before{content:"\f019";}
|
||||
.icon-download:before{content:"\f01a";}
|
||||
.icon-upload:before{content:"\f01b";}
|
||||
.icon-inbox:before{content:"\f01c";}
|
||||
.icon-play-circle:before{content:"\f01d";}
|
||||
.icon-rotate-right:before,.icon-repeat:before{content:"\f01e";}
|
||||
.icon-refresh:before{content:"\f021";}
|
||||
.icon-list-alt:before{content:"\f022";}
|
||||
.icon-lock:before{content:"\f023";}
|
||||
.icon-flag:before{content:"\f024";}
|
||||
.icon-headphones:before{content:"\f025";}
|
||||
.icon-volume-off:before{content:"\f026";}
|
||||
.icon-volume-down:before{content:"\f027";}
|
||||
.icon-volume-up:before{content:"\f028";}
|
||||
.icon-qrcode:before{content:"\f029";}
|
||||
.icon-barcode:before{content:"\f02a";}
|
||||
.icon-tag:before{content:"\f02b";}
|
||||
.icon-tags:before{content:"\f02c";}
|
||||
.icon-book:before{content:"\f02d";}
|
||||
.icon-bookmark:before{content:"\f02e";}
|
||||
.icon-print:before{content:"\f02f";}
|
||||
.icon-camera:before{content:"\f030";}
|
||||
.icon-font:before{content:"\f031";}
|
||||
.icon-bold:before{content:"\f032";}
|
||||
.icon-italic:before{content:"\f033";}
|
||||
.icon-text-height:before{content:"\f034";}
|
||||
.icon-text-width:before{content:"\f035";}
|
||||
.icon-align-left:before{content:"\f036";}
|
||||
.icon-align-center:before{content:"\f037";}
|
||||
.icon-align-right:before{content:"\f038";}
|
||||
.icon-align-justify:before{content:"\f039";}
|
||||
.icon-list:before{content:"\f03a";}
|
||||
.icon-indent-left:before{content:"\f03b";}
|
||||
.icon-indent-right:before{content:"\f03c";}
|
||||
.icon-facetime-video:before{content:"\f03d";}
|
||||
.icon-picture:before{content:"\f03e";}
|
||||
.icon-pencil:before{content:"\f040";}
|
||||
.icon-map-marker:before{content:"\f041";}
|
||||
.icon-adjust:before{content:"\f042";}
|
||||
.icon-tint:before{content:"\f043";}
|
||||
.icon-edit:before{content:"\f044";}
|
||||
.icon-share:before{content:"\f045";}
|
||||
.icon-check:before{content:"\f046";}
|
||||
.icon-move:before{content:"\f047";}
|
||||
.icon-step-backward:before{content:"\f048";}
|
||||
.icon-fast-backward:before{content:"\f049";}
|
||||
.icon-backward:before{content:"\f04a";}
|
||||
.icon-play:before{content:"\f04b";}
|
||||
.icon-pause:before{content:"\f04c";}
|
||||
.icon-stop:before{content:"\f04d";}
|
||||
.icon-forward:before{content:"\f04e";}
|
||||
.icon-fast-forward:before{content:"\f050";}
|
||||
.icon-step-forward:before{content:"\f051";}
|
||||
.icon-eject:before{content:"\f052";}
|
||||
.icon-chevron-left:before{content:"\f053";}
|
||||
.icon-chevron-right:before{content:"\f054";}
|
||||
.icon-plus-sign:before{content:"\f055";}
|
||||
.icon-minus-sign:before{content:"\f056";}
|
||||
.icon-remove-sign:before{content:"\f057";}
|
||||
.icon-ok-sign:before{content:"\f058";}
|
||||
.icon-question-sign:before{content:"\f059";}
|
||||
.icon-info-sign:before{content:"\f05a";}
|
||||
.icon-screenshot:before{content:"\f05b";}
|
||||
.icon-remove-circle:before{content:"\f05c";}
|
||||
.icon-ok-circle:before{content:"\f05d";}
|
||||
.icon-ban-circle:before{content:"\f05e";}
|
||||
.icon-arrow-left:before{content:"\f060";}
|
||||
.icon-arrow-right:before{content:"\f061";}
|
||||
.icon-arrow-up:before{content:"\f062";}
|
||||
.icon-arrow-down:before{content:"\f063";}
|
||||
.icon-mail-forward:before,.icon-share-alt:before{content:"\f064";}
|
||||
.icon-resize-full:before{content:"\f065";}
|
||||
.icon-resize-small:before{content:"\f066";}
|
||||
.icon-plus:before{content:"\f067";}
|
||||
.icon-minus:before{content:"\f068";}
|
||||
.icon-asterisk:before{content:"\f069";}
|
||||
.icon-exclamation-sign:before{content:"\f06a";}
|
||||
.icon-gift:before{content:"\f06b";}
|
||||
.icon-leaf:before{content:"\f06c";}
|
||||
.icon-fire:before{content:"\f06d";}
|
||||
.icon-eye-open:before{content:"\f06e";}
|
||||
.icon-eye-close:before{content:"\f070";}
|
||||
.icon-warning-sign:before{content:"\f071";}
|
||||
.icon-plane:before{content:"\f072";}
|
||||
.icon-calendar:before{content:"\f073";}
|
||||
.icon-random:before{content:"\f074";}
|
||||
.icon-comment:before{content:"\f075";}
|
||||
.icon-magnet:before{content:"\f076";}
|
||||
.icon-chevron-up:before{content:"\f077";}
|
||||
.icon-chevron-down:before{content:"\f078";}
|
||||
.icon-retweet:before{content:"\f079";}
|
||||
.icon-shopping-cart:before{content:"\f07a";}
|
||||
.icon-folder-close:before{content:"\f07b";}
|
||||
.icon-folder-open:before{content:"\f07c";}
|
||||
.icon-resize-vertical:before{content:"\f07d";}
|
||||
.icon-resize-horizontal:before{content:"\f07e";}
|
||||
.icon-bar-chart:before{content:"\f080";}
|
||||
.icon-twitter-sign:before{content:"\f081";}
|
||||
.icon-facebook-sign:before{content:"\f082";}
|
||||
.icon-camera-retro:before{content:"\f083";}
|
||||
.icon-key:before{content:"\f084";}
|
||||
.icon-gears:before,.icon-cogs:before{content:"\f085";}
|
||||
.icon-comments:before{content:"\f086";}
|
||||
.icon-thumbs-up-alt:before{content:"\f087";}
|
||||
.icon-thumbs-down-alt:before{content:"\f088";}
|
||||
.icon-star-half:before{content:"\f089";}
|
||||
.icon-heart-empty:before{content:"\f08a";}
|
||||
.icon-signout:before{content:"\f08b";}
|
||||
.icon-linkedin-sign:before{content:"\f08c";}
|
||||
.icon-pushpin:before{content:"\f08d";}
|
||||
.icon-external-link:before{content:"\f08e";}
|
||||
.icon-signin:before{content:"\f090";}
|
||||
.icon-trophy:before{content:"\f091";}
|
||||
.icon-github-sign:before{content:"\f092";}
|
||||
.icon-upload-alt:before{content:"\f093";}
|
||||
.icon-lemon:before{content:"\f094";}
|
||||
.icon-phone:before{content:"\f095";}
|
||||
.icon-unchecked:before,.icon-check-empty:before{content:"\f096";}
|
||||
.icon-bookmark-empty:before{content:"\f097";}
|
||||
.icon-phone-sign:before{content:"\f098";}
|
||||
.icon-twitter:before{content:"\f099";}
|
||||
.icon-facebook:before{content:"\f09a";}
|
||||
.icon-github:before{content:"\f09b";}
|
||||
.icon-unlock:before{content:"\f09c";}
|
||||
.icon-credit-card:before{content:"\f09d";}
|
||||
.icon-rss:before{content:"\f09e";}
|
||||
.icon-hdd:before{content:"\f0a0";}
|
||||
.icon-bullhorn:before{content:"\f0a1";}
|
||||
.icon-bell:before{content:"\f0a2";}
|
||||
.icon-certificate:before{content:"\f0a3";}
|
||||
.icon-hand-right:before{content:"\f0a4";}
|
||||
.icon-hand-left:before{content:"\f0a5";}
|
||||
.icon-hand-up:before{content:"\f0a6";}
|
||||
.icon-hand-down:before{content:"\f0a7";}
|
||||
.icon-circle-arrow-left:before{content:"\f0a8";}
|
||||
.icon-circle-arrow-right:before{content:"\f0a9";}
|
||||
.icon-circle-arrow-up:before{content:"\f0aa";}
|
||||
.icon-circle-arrow-down:before{content:"\f0ab";}
|
||||
.icon-globe:before{content:"\f0ac";}
|
||||
.icon-wrench:before{content:"\f0ad";}
|
||||
.icon-tasks:before{content:"\f0ae";}
|
||||
.icon-filter:before{content:"\f0b0";}
|
||||
.icon-briefcase:before{content:"\f0b1";}
|
||||
.icon-fullscreen:before{content:"\f0b2";}
|
||||
.icon-group:before{content:"\f0c0";}
|
||||
.icon-link:before{content:"\f0c1";}
|
||||
.icon-cloud:before{content:"\f0c2";}
|
||||
.icon-beaker:before{content:"\f0c3";}
|
||||
.icon-cut:before{content:"\f0c4";}
|
||||
.icon-copy:before{content:"\f0c5";}
|
||||
.icon-paperclip:before,.icon-paper-clip:before{content:"\f0c6";}
|
||||
.icon-save:before{content:"\f0c7";}
|
||||
.icon-sign-blank:before{content:"\f0c8";}
|
||||
.icon-reorder:before{content:"\f0c9";}
|
||||
.icon-list-ul:before{content:"\f0ca";}
|
||||
.icon-list-ol:before{content:"\f0cb";}
|
||||
.icon-strikethrough:before{content:"\f0cc";}
|
||||
.icon-underline:before{content:"\f0cd";}
|
||||
.icon-table:before{content:"\f0ce";}
|
||||
.icon-magic:before{content:"\f0d0";}
|
||||
.icon-truck:before{content:"\f0d1";}
|
||||
.icon-pinterest:before{content:"\f0d2";}
|
||||
.icon-pinterest-sign:before{content:"\f0d3";}
|
||||
.icon-google-plus-sign:before{content:"\f0d4";}
|
||||
.icon-google-plus:before{content:"\f0d5";}
|
||||
.icon-money:before{content:"\f0d6";}
|
||||
.icon-caret-down:before{content:"\f0d7";}
|
||||
.icon-caret-up:before{content:"\f0d8";}
|
||||
.icon-caret-left:before{content:"\f0d9";}
|
||||
.icon-caret-right:before{content:"\f0da";}
|
||||
.icon-columns:before{content:"\f0db";}
|
||||
.icon-sort:before{content:"\f0dc";}
|
||||
.icon-sort-down:before{content:"\f0dd";}
|
||||
.icon-sort-up:before{content:"\f0de";}
|
||||
.icon-envelope:before{content:"\f0e0";}
|
||||
.icon-linkedin:before{content:"\f0e1";}
|
||||
.icon-rotate-left:before,.icon-undo:before{content:"\f0e2";}
|
||||
.icon-legal:before{content:"\f0e3";}
|
||||
.icon-dashboard:before{content:"\f0e4";}
|
||||
.icon-comment-alt:before{content:"\f0e5";}
|
||||
.icon-comments-alt:before{content:"\f0e6";}
|
||||
.icon-bolt:before{content:"\f0e7";}
|
||||
.icon-sitemap:before{content:"\f0e8";}
|
||||
.icon-umbrella:before{content:"\f0e9";}
|
||||
.icon-paste:before{content:"\f0ea";}
|
||||
.icon-lightbulb:before{content:"\f0eb";}
|
||||
.icon-exchange:before{content:"\f0ec";}
|
||||
.icon-cloud-download:before{content:"\f0ed";}
|
||||
.icon-cloud-upload:before{content:"\f0ee";}
|
||||
.icon-user-md:before{content:"\f0f0";}
|
||||
.icon-stethoscope:before{content:"\f0f1";}
|
||||
.icon-suitcase:before{content:"\f0f2";}
|
||||
.icon-bell-alt:before{content:"\f0f3";}
|
||||
.icon-coffee:before{content:"\f0f4";}
|
||||
.icon-food:before{content:"\f0f5";}
|
||||
.icon-file-text-alt:before{content:"\f0f6";}
|
||||
.icon-building:before{content:"\f0f7";}
|
||||
.icon-hospital:before{content:"\f0f8";}
|
||||
.icon-ambulance:before{content:"\f0f9";}
|
||||
.icon-medkit:before{content:"\f0fa";}
|
||||
.icon-fighter-jet:before{content:"\f0fb";}
|
||||
.icon-beer:before{content:"\f0fc";}
|
||||
.icon-h-sign:before{content:"\f0fd";}
|
||||
.icon-plus-sign-alt:before{content:"\f0fe";}
|
||||
.icon-double-angle-left:before{content:"\f100";}
|
||||
.icon-double-angle-right:before{content:"\f101";}
|
||||
.icon-double-angle-up:before{content:"\f102";}
|
||||
.icon-double-angle-down:before{content:"\f103";}
|
||||
.icon-angle-left:before{content:"\f104";}
|
||||
.icon-angle-right:before{content:"\f105";}
|
||||
.icon-angle-up:before{content:"\f106";}
|
||||
.icon-angle-down:before{content:"\f107";}
|
||||
.icon-desktop:before{content:"\f108";}
|
||||
.icon-laptop:before{content:"\f109";}
|
||||
.icon-tablet:before{content:"\f10a";}
|
||||
.icon-mobile-phone:before{content:"\f10b";}
|
||||
.icon-circle-blank:before{content:"\f10c";}
|
||||
.icon-quote-left:before{content:"\f10d";}
|
||||
.icon-quote-right:before{content:"\f10e";}
|
||||
.icon-spinner:before{content:"\f110";}
|
||||
.icon-circle:before{content:"\f111";}
|
||||
.icon-mail-reply:before,.icon-reply:before{content:"\f112";}
|
||||
.icon-github-alt:before{content:"\f113";}
|
||||
.icon-folder-close-alt:before{content:"\f114";}
|
||||
.icon-folder-open-alt:before{content:"\f115";}
|
||||
.icon-expand-alt:before{content:"\f116";}
|
||||
.icon-collapse-alt:before{content:"\f117";}
|
||||
.icon-smile:before{content:"\f118";}
|
||||
.icon-frown:before{content:"\f119";}
|
||||
.icon-meh:before{content:"\f11a";}
|
||||
.icon-gamepad:before{content:"\f11b";}
|
||||
.icon-keyboard:before{content:"\f11c";}
|
||||
.icon-flag-alt:before{content:"\f11d";}
|
||||
.icon-flag-checkered:before{content:"\f11e";}
|
||||
.icon-terminal:before{content:"\f120";}
|
||||
.icon-code:before{content:"\f121";}
|
||||
.icon-reply-all:before{content:"\f122";}
|
||||
.icon-mail-reply-all:before{content:"\f122";}
|
||||
.icon-star-half-full:before,.icon-star-half-empty:before{content:"\f123";}
|
||||
.icon-location-arrow:before{content:"\f124";}
|
||||
.icon-crop:before{content:"\f125";}
|
||||
.icon-code-fork:before{content:"\f126";}
|
||||
.icon-unlink:before{content:"\f127";}
|
||||
.icon-question:before{content:"\f128";}
|
||||
.icon-info:before{content:"\f129";}
|
||||
.icon-exclamation:before{content:"\f12a";}
|
||||
.icon-superscript:before{content:"\f12b";}
|
||||
.icon-subscript:before{content:"\f12c";}
|
||||
.icon-eraser:before{content:"\f12d";}
|
||||
.icon-puzzle-piece:before{content:"\f12e";}
|
||||
.icon-microphone:before{content:"\f130";}
|
||||
.icon-microphone-off:before{content:"\f131";}
|
||||
.icon-shield:before{content:"\f132";}
|
||||
.icon-calendar-empty:before{content:"\f133";}
|
||||
.icon-fire-extinguisher:before{content:"\f134";}
|
||||
.icon-rocket:before{content:"\f135";}
|
||||
.icon-maxcdn:before{content:"\f136";}
|
||||
.icon-chevron-sign-left:before{content:"\f137";}
|
||||
.icon-chevron-sign-right:before{content:"\f138";}
|
||||
.icon-chevron-sign-up:before{content:"\f139";}
|
||||
.icon-chevron-sign-down:before{content:"\f13a";}
|
||||
.icon-html5:before{content:"\f13b";}
|
||||
.icon-css3:before{content:"\f13c";}
|
||||
.icon-anchor:before{content:"\f13d";}
|
||||
.icon-unlock-alt:before{content:"\f13e";}
|
||||
.icon-bullseye:before{content:"\f140";}
|
||||
.icon-ellipsis-horizontal:before{content:"\f141";}
|
||||
.icon-ellipsis-vertical:before{content:"\f142";}
|
||||
.icon-rss-sign:before{content:"\f143";}
|
||||
.icon-play-sign:before{content:"\f144";}
|
||||
.icon-ticket:before{content:"\f145";}
|
||||
.icon-minus-sign-alt:before{content:"\f146";}
|
||||
.icon-check-minus:before{content:"\f147";}
|
||||
.icon-level-up:before{content:"\f148";}
|
||||
.icon-level-down:before{content:"\f149";}
|
||||
.icon-check-sign:before{content:"\f14a";}
|
||||
.icon-edit-sign:before{content:"\f14b";}
|
||||
.icon-external-link-sign:before{content:"\f14c";}
|
||||
.icon-share-sign:before{content:"\f14d";}
|
||||
.icon-compass:before{content:"\f14e";}
|
||||
.icon-collapse:before{content:"\f150";}
|
||||
.icon-collapse-top:before{content:"\f151";}
|
||||
.icon-expand:before{content:"\f152";}
|
||||
.icon-euro:before,.icon-eur:before{content:"\f153";}
|
||||
.icon-gbp:before{content:"\f154";}
|
||||
.icon-dollar:before,.icon-usd:before{content:"\f155";}
|
||||
.icon-rupee:before,.icon-inr:before{content:"\f156";}
|
||||
.icon-yen:before,.icon-jpy:before{content:"\f157";}
|
||||
.icon-renminbi:before,.icon-cny:before{content:"\f158";}
|
||||
.icon-won:before,.icon-krw:before{content:"\f159";}
|
||||
.icon-bitcoin:before,.icon-btc:before{content:"\f15a";}
|
||||
.icon-file:before{content:"\f15b";}
|
||||
.icon-file-text:before{content:"\f15c";}
|
||||
.icon-sort-by-alphabet:before{content:"\f15d";}
|
||||
.icon-sort-by-alphabet-alt:before{content:"\f15e";}
|
||||
.icon-sort-by-attributes:before{content:"\f160";}
|
||||
.icon-sort-by-attributes-alt:before{content:"\f161";}
|
||||
.icon-sort-by-order:before{content:"\f162";}
|
||||
.icon-sort-by-order-alt:before{content:"\f163";}
|
||||
.icon-thumbs-up:before{content:"\f164";}
|
||||
.icon-thumbs-down:before{content:"\f165";}
|
||||
.icon-youtube-sign:before{content:"\f166";}
|
||||
.icon-youtube:before{content:"\f167";}
|
||||
.icon-xing:before{content:"\f168";}
|
||||
.icon-xing-sign:before{content:"\f169";}
|
||||
.icon-youtube-play:before{content:"\f16a";}
|
||||
.icon-dropbox:before{content:"\f16b";}
|
||||
.icon-stackexchange:before{content:"\f16c";}
|
||||
.icon-instagram:before{content:"\f16d";}
|
||||
.icon-flickr:before{content:"\f16e";}
|
||||
.icon-adn:before{content:"\f170";}
|
||||
.icon-bitbucket:before{content:"\f171";}
|
||||
.icon-bitbucket-sign:before{content:"\f172";}
|
||||
.icon-tumblr:before{content:"\f173";}
|
||||
.icon-tumblr-sign:before{content:"\f174";}
|
||||
.icon-long-arrow-down:before{content:"\f175";}
|
||||
.icon-long-arrow-up:before{content:"\f176";}
|
||||
.icon-long-arrow-left:before{content:"\f177";}
|
||||
.icon-long-arrow-right:before{content:"\f178";}
|
||||
.icon-apple:before{content:"\f179";}
|
||||
.icon-windows:before{content:"\f17a";}
|
||||
.icon-android:before{content:"\f17b";}
|
||||
.icon-linux:before{content:"\f17c";}
|
||||
.icon-dribbble:before{content:"\f17d";}
|
||||
.icon-skype:before{content:"\f17e";}
|
||||
.icon-foursquare:before{content:"\f180";}
|
||||
.icon-trello:before{content:"\f181";}
|
||||
.icon-female:before{content:"\f182";}
|
||||
.icon-male:before{content:"\f183";}
|
||||
.icon-gittip:before{content:"\f184";}
|
||||
.icon-sun:before{content:"\f185";}
|
||||
.icon-moon:before{content:"\f186";}
|
||||
.icon-archive:before{content:"\f187";}
|
||||
.icon-bug:before{content:"\f188";}
|
||||
.icon-vk:before{content:"\f189";}
|
||||
.icon-weibo:before{content:"\f18a";}
|
||||
.icon-renren:before{content:"\f18b";}
|
||||
@@ -1 +1 @@
|
||||
.btn{display:inline-block;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);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-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.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6}.btn.active,.btn:active{background-color:#ccc\9}.btn:focus,.btn:hover{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-danger.active,.btn-info.active,.btn-inverse.active,.btn-primary.active,.btn-success.active,.btn-warning.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);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c}.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);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406}.btn-warning.active,.btn-warning:active{background-color:#c67605\9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);backLine truncated
|
||||
.btn{display:inline-block;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);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-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.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6}.btn.active,.btn:active{background-color:#ccc\9}.btn:focus,.btn:hover{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-danger.active,.btn-info.active,.btn-inverse.active,.btn-primary.active,.btn-success.active,.btn-warning.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);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c}.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);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406}.btn-warning.active,.btn-warning:active{background-color:#c67605\9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);backLine truncated
|
||||
@@ -9,11 +9,15 @@ var firstReport;
|
||||
var toolOffsets = [
|
||||
{x: 0, y: 0}
|
||||
];
|
||||
var g90InfluencesExtruder = false;
|
||||
var z_heights = {};
|
||||
var model = [];
|
||||
var max = {x: undefined, y: undefined, z: undefined};
|
||||
var min = {x: undefined, y: undefined, z: undefined};
|
||||
var boundingBox = {minX: undefined, maxX: undefined, minY: undefined, maxY: undefined, minZ: undefined, maxZ: undefined};
|
||||
var modelSize = {x: undefined, y: undefined, z: undefined};
|
||||
var bed = {x: undefined, y: undefined, r: undefined, circular: false, centeredOrigin: false};
|
||||
var ignoreOutsideBed = false;
|
||||
var filamentByLayer = {};
|
||||
var totalFilament = [0];
|
||||
var printTime = 0;
|
||||
@@ -75,6 +79,7 @@ var sendAnalyzeDone = function () {
|
||||
max: max,
|
||||
min: min,
|
||||
modelSize: modelSize,
|
||||
boundingBox: boundingBox,
|
||||
totalFilament: totalFilament,
|
||||
filamentByLayer: filamentByLayer,
|
||||
printTime: printTime,
|
||||
@@ -105,6 +110,36 @@ var purgeLayers = function () {
|
||||
}
|
||||
};
|
||||
|
||||
var bedBounds = function() {
|
||||
if (!bed) {
|
||||
return {xMin: 0, xMax: 0, yMin: 0, yMax: 0};
|
||||
}
|
||||
|
||||
var result;
|
||||
if (bed.circular) {
|
||||
result = {xMin: -bed.r, xMax: bed.r, yMin: -bed.r, yMax: bed.r};
|
||||
} else if (bed.centeredOrigin) {
|
||||
result = {xMin: -bed.x/2.0, xMax: bed.x/2.0, yMin: -bed.y/2.0, yMax: bed.y/2.0};
|
||||
} else {
|
||||
result = {xMin: 0, xMax: bed.x, yMin: 0, yMax: bed.y};
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
var withinBedBounds = function(x, y, bedBounds) {
|
||||
if (!ignoreOutsideBed) return true;
|
||||
|
||||
var result = true;
|
||||
|
||||
if (x !== undefined && !isNaN(x)) {
|
||||
result = result && (x >= bedBounds.xMin && x <= bedBounds.xMax);
|
||||
}
|
||||
if (y !== undefined && !isNaN(y)) {
|
||||
result = result && (y >= bedBounds.yMin && y <= bedBounds.yMax);
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
var analyzeModel = function () {
|
||||
var tmp1 = 0, tmp2 = 0;
|
||||
@@ -112,6 +147,8 @@ var analyzeModel = function () {
|
||||
var type;
|
||||
var printTimeAdd = 0;
|
||||
|
||||
var bounds = bedBounds();
|
||||
|
||||
for (var i = 0; i < model.length; i++) {
|
||||
var cmds = model[i];
|
||||
if (!cmds) continue;
|
||||
@@ -119,41 +156,56 @@ var analyzeModel = function () {
|
||||
for (var j = 0; j < cmds.length; j++) {
|
||||
var tool = cmds[j].tool;
|
||||
|
||||
var x_ok = false;
|
||||
var y_ok = false;
|
||||
var retract = cmds[j].retract && cmds[j].retract > 0;
|
||||
var extrude = cmds[j].extrude && cmds[j].extrude > 0 && !retract;
|
||||
var move = cmds[j].x !== undefined || cmds[j].y !== undefined || cmds[j].z !== undefined;
|
||||
|
||||
var prevInBounds = withinBedBounds(cmds[j].prevX, cmds[j].prevY, bounds);
|
||||
var inBounds = withinBedBounds(cmds[j].x === undefined ? cmds[j].prevX : cmds[j].x,
|
||||
cmds[j].y === undefined ? cmds[j].prevY : cmds[j].y,
|
||||
bounds);
|
||||
|
||||
var recordX = function(x, inBounds) {
|
||||
if (x === undefined || isNaN(x)) return;
|
||||
|
||||
if (typeof(cmds[j].x) !== 'undefined'
|
||||
&& typeof(cmds[j].prevX) !== 'undefined'
|
||||
&& typeof(cmds[j].extrude) !== 'undefined'
|
||||
&& cmds[j].extrude
|
||||
&& !isNaN(cmds[j].x)) {
|
||||
var x = cmds[j].x;
|
||||
max.x = max.x !== undefined ? Math.max(max.x, x) : x;
|
||||
min.x = min.x !== undefined ? Math.min(min.x, x) : x;
|
||||
|
||||
x_ok = true;
|
||||
}
|
||||
if (inBounds) {
|
||||
boundingBox.minX = boundingBox.minX !== undefined ? Math.min(boundingBox.minX, x): x;
|
||||
boundingBox.maxX = boundingBox.maxX !== undefined ? Math.max(boundingBox.maxX, x): x;
|
||||
}
|
||||
};
|
||||
|
||||
if (typeof(cmds[j].y) !== 'undefined'
|
||||
&& typeof(cmds[j].prevY) !== 'undefined'
|
||||
&& typeof(cmds[j].extrude) !== 'undefined'
|
||||
&& cmds[j].extrude
|
||||
&& !isNaN(cmds[j].y)) {
|
||||
var y = cmds[j].y;
|
||||
var recordY = function(y, inBounds) {
|
||||
if (y === undefined || isNaN(y)) return;
|
||||
|
||||
max.y = max.y !== undefined ? Math.max(max.y, y) : y;
|
||||
min.y = min.y !== undefined ? Math.min(min.y, y) : y;
|
||||
|
||||
y_ok = true;
|
||||
}
|
||||
if (inBounds) {
|
||||
boundingBox.minY = boundingBox.minY !== undefined ? Math.min(boundingBox.minY, y): y;
|
||||
boundingBox.maxY = boundingBox.maxY !== undefined ? Math.max(boundingBox.maxY, y): y;
|
||||
}
|
||||
};
|
||||
|
||||
var recordZ = function(z) {
|
||||
if (z === undefined || isNaN(z)) return;
|
||||
|
||||
if (typeof(cmds[j].prevZ) !== 'undefined'
|
||||
&& typeof(cmds[j].extrude) !== 'undefined'
|
||||
&& cmds[j].extrude
|
||||
&& !isNaN(cmds[j].prevZ)) {
|
||||
var z = cmds[j].prevZ;
|
||||
max.z = max.z !== undefined ? Math.max(max.z, z) : z;
|
||||
min.z = min.z !== undefined ? Math.min(min.z, z) : z;
|
||||
|
||||
boundingBox.minZ = min.z;
|
||||
boundingBox.maxZ = max.z;
|
||||
};
|
||||
|
||||
if (move && extrude) {
|
||||
recordX(cmds[j].prevX, prevInBounds);
|
||||
recordX(cmds[j].x, inBounds);
|
||||
recordY(cmds[j].prevY, prevInBounds);
|
||||
recordY(cmds[j].y, inBounds);
|
||||
recordZ(cmds[j].prevZ);
|
||||
recordZ(cmds[j].z);
|
||||
}
|
||||
|
||||
if (!totalFilament[tool]) totalFilament[tool] = 0;
|
||||
@@ -164,20 +216,25 @@ var analyzeModel = function () {
|
||||
filamentByLayer[cmds[j].prevZ][tool] += cmds[j].extrusion;
|
||||
}
|
||||
|
||||
var diffX = cmds[j].x - cmds[j].prevX;
|
||||
var diffY = cmds[j].y - cmds[j].prevY;
|
||||
if (x_ok && y_ok) {
|
||||
printTimeAdd = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
|
||||
} else if (cmds[j].retract === 0 && cmds[j].extrusion !== 0) {
|
||||
tmp1 = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
|
||||
tmp2 = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60));
|
||||
printTimeAdd = Math.max(tmp1, tmp2);
|
||||
} else if (cmds[j].retract !== 0) {
|
||||
printTimeAdd = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60));
|
||||
if (cmds[j].x !== undefined && !isNaN(cmds[j].x)
|
||||
&& cmds[j].y !== undefined && !isNaN(cmds[j].y)) {
|
||||
var diffX = cmds[j].x - cmds[j].prevX;
|
||||
var diffY = cmds[j].y - cmds[j].prevY;
|
||||
if (move) {
|
||||
printTimeAdd = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
|
||||
} else if (extrude) {
|
||||
tmp1 = Math.sqrt(diffX * diffX + diffY * diffY) / (cmds[j].speed / 60);
|
||||
tmp2 = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60));
|
||||
printTimeAdd = Math.max(tmp1, tmp2);
|
||||
} else if (retract) {
|
||||
printTimeAdd = Math.abs(cmds[j].extrusion / (cmds[j].speed / 60));
|
||||
}
|
||||
} else {
|
||||
printTimeAdd = 0;
|
||||
}
|
||||
|
||||
printTime += printTimeAdd;
|
||||
if (typeof(printTimeByLayer[cmds[j].prevZ]) === 'undefined') {
|
||||
if (printTimeByLayer[cmds[j].prevZ] === undefined) {
|
||||
printTimeByLayer[cmds[j].prevZ] = 0;
|
||||
}
|
||||
printTimeByLayer[cmds[j].prevZ] += printTimeAdd;
|
||||
@@ -232,8 +289,8 @@ var doParse = function () {
|
||||
var center_i, center_j, direction;
|
||||
var prevX = 0, prevY = 0, prevZ = 0;
|
||||
var f, lastF = 4000;
|
||||
var extrude = false, extrudeRelative = false, retract = 0;
|
||||
var positionRelative = false;
|
||||
var extrude = false, relativeE = false, retract = 0;
|
||||
var relativeMode = false;
|
||||
var zLift = false;
|
||||
var zLiftZ = undefined;
|
||||
var zLiftMoves = [];
|
||||
@@ -244,10 +301,16 @@ var doParse = function () {
|
||||
var tool = 0;
|
||||
var prev_extrude = [{a: 0, b: 0, c: 0, e: 0, abs: 0}];
|
||||
var prev_retract = [0];
|
||||
var offset = toolOffsets[0];
|
||||
|
||||
// we keep track of our active toolOffset here so that our visualization lines up - if we didn't
|
||||
// offset the coordinates from the GCODE file with the tool offset, stuff would look wonky since our
|
||||
// visualizer doesn't actually have a physical offset ;)
|
||||
var activeToolOffset = toolOffsets[0];
|
||||
|
||||
var i, j, args;
|
||||
|
||||
model = [];
|
||||
for (var i = 0; i < gcode.length; i++) {
|
||||
for (i = 0; i < gcode.length; i++) {
|
||||
x = undefined;
|
||||
y = undefined;
|
||||
z = undefined;
|
||||
@@ -268,30 +331,30 @@ var doParse = function () {
|
||||
var log = false;
|
||||
|
||||
if (/^(?:G0|G1|G2|G3)\s/i.test(line)) {
|
||||
var args = line.split(/\s/);
|
||||
args = line.split(/\s/);
|
||||
|
||||
for (var j = 0; j < args.length; j++) {
|
||||
for (j = 0; j < args.length; j++) {
|
||||
switch (argChar = args[j].charAt(0).toLowerCase()) {
|
||||
case 'x':
|
||||
if (positionRelative) {
|
||||
x = prevX + Number(args[j].slice(1)) + offset.x;
|
||||
if (relativeMode) {
|
||||
x = prevX + Number(args[j].slice(1)) + activeToolOffset.x;
|
||||
} else {
|
||||
x = Number(args[j].slice(1)) + offset.x;
|
||||
x = Number(args[j].slice(1)) + activeToolOffset.x;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 'y':
|
||||
if (positionRelative) {
|
||||
y = prevY + Number(args[j].slice(1)) + offset.y;
|
||||
if (relativeMode) {
|
||||
y = prevY + Number(args[j].slice(1)) + activeToolOffset.y;
|
||||
} else {
|
||||
y = Number(args[j].slice(1)) + offset.y;
|
||||
y = Number(args[j].slice(1)) + activeToolOffset.y;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 'z':
|
||||
if (positionRelative) {
|
||||
if (relativeMode) {
|
||||
z = prevZ + Number(args[j].slice(1));
|
||||
} else {
|
||||
z = Number(args[j].slice(1));
|
||||
@@ -306,20 +369,20 @@ var doParse = function () {
|
||||
assumeNonDC = true;
|
||||
numSlice = Number(args[j].slice(1));
|
||||
|
||||
if (!extrudeRelative) {
|
||||
if (relativeMode || relativeE) {
|
||||
prev_extrude[tool]["abs"] = numSlice;
|
||||
prev_extrude[tool][argChar] += numSlice;
|
||||
} else {
|
||||
// absolute extrusion positioning
|
||||
prev_extrude[tool]["abs"] = numSlice - prev_extrude[tool][argChar];
|
||||
prev_extrude[tool][argChar] = numSlice;
|
||||
} else {
|
||||
prev_extrude[tool]["abs"] = numSlice;
|
||||
prev_extrude[tool][argChar] += numSlice;
|
||||
}
|
||||
|
||||
extrude = prev_extrude[tool]["abs"] > 0;
|
||||
if (prev_extrude[tool]["abs"] < 0) {
|
||||
prev_retract[tool] = -1;
|
||||
retract = -1;
|
||||
} else if (prev_extrude[tool]["abs"] == 0) {
|
||||
} else if (prev_extrude[tool]["abs"] === 0) {
|
||||
retract = 0;
|
||||
} else if (prev_extrude[tool]["abs"] > 0 && prev_retract[tool] < 0) {
|
||||
prev_retract[tool] = 0;
|
||||
@@ -341,9 +404,9 @@ var doParse = function () {
|
||||
center_j = Number(args[j].slice(1));
|
||||
break;
|
||||
case 'g':
|
||||
if(args[j].charAt(1).toLowerCase()=='2')
|
||||
if(args[j].charAt(1).toLowerCase() === '2')
|
||||
direction=1;
|
||||
if(args[j].charAt(1).toLowerCase()=='3')
|
||||
if(args[j].charAt(1).toLowerCase() === '3')
|
||||
direction=-1;
|
||||
break;
|
||||
}
|
||||
@@ -354,31 +417,35 @@ var doParse = function () {
|
||||
prev_extrude[tool]["abs"] = Math.sqrt((prevX - x) * (prevX - x) + (prevY - y) * (prevY - y));
|
||||
}
|
||||
|
||||
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract != 0) {
|
||||
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract !== 0) {
|
||||
addToModel = true;
|
||||
move = true;
|
||||
}
|
||||
} else if (/^(?:M82)/i.test(line)) {
|
||||
extrudeRelative = false;
|
||||
relativeE = false;
|
||||
} else if (/^(?:G91)/i.test(line)) {
|
||||
positionRelative = true;
|
||||
extrudeRelative = true;
|
||||
relativeMode = true;
|
||||
if (g90InfluencesExtruder) {
|
||||
relativeE = true;
|
||||
}
|
||||
} else if (/^(?:G90)/i.test(line)) {
|
||||
positionRelative = false;
|
||||
extrudeRelative = false;
|
||||
relativeMode = false;
|
||||
if (g90InfluencesExtruder) {
|
||||
relativeE = false;
|
||||
}
|
||||
} else if (/^(?:M83)/i.test(line)) {
|
||||
extrudeRelative = true;
|
||||
relativeE = true;
|
||||
} else if (/^(?:M101)/i.test(line)) {
|
||||
dcExtrude = true;
|
||||
} else if (/^(?:M103)/i.test(line)) {
|
||||
dcExtrude = false;
|
||||
} else if (/^(?:G92)/i.test(line)) {
|
||||
var args = line.split(/\s/);
|
||||
args = line.split(/\s/);
|
||||
|
||||
for (var j = 0; j < args.length; j++) {
|
||||
for (j = 0; j < args.length; j++) {
|
||||
if (!args[j]) continue;
|
||||
|
||||
if (args.length == 1) {
|
||||
if (args.length === 1) {
|
||||
// G92 without coordinates => reset all axes to 0
|
||||
x = 0;
|
||||
y = 0;
|
||||
@@ -390,11 +457,11 @@ var doParse = function () {
|
||||
} else {
|
||||
switch (argChar = args[j].charAt(0).toLowerCase()) {
|
||||
case 'x':
|
||||
x = Number(args[j].slice(1)) + offset.x;
|
||||
x = Number(args[j].slice(1)) + activeToolOffset.x;
|
||||
break;
|
||||
|
||||
case 'y':
|
||||
y = Number(args[j].slice(1)) + offset.y;
|
||||
y = Number(args[j].slice(1)) + activeToolOffset.y;
|
||||
break;
|
||||
|
||||
case 'z':
|
||||
@@ -407,10 +474,10 @@ var doParse = function () {
|
||||
case 'b':
|
||||
case 'c':
|
||||
numSlice = Number(args[j].slice(1));
|
||||
if (!extrudeRelative)
|
||||
prev_extrude[tool][argChar] = 0;
|
||||
else {
|
||||
if (relativeMode || relativeE) {
|
||||
prev_extrude[tool][argChar] = numSlice;
|
||||
} else {
|
||||
prev_extrude[tool][argChar] = 0;
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -423,9 +490,9 @@ var doParse = function () {
|
||||
}
|
||||
|
||||
} else if (/^(?:G28)/i.test(line)) {
|
||||
var args = line.split(/\s/);
|
||||
args = line.split(/\s/);
|
||||
|
||||
if (args.length == 1) {
|
||||
if (args.length === 1) {
|
||||
// G28 with no arguments => home all axis
|
||||
x = 0;
|
||||
y = 0;
|
||||
@@ -449,11 +516,11 @@ var doParse = function () {
|
||||
}
|
||||
|
||||
// if it's the first layer and G28 was without z
|
||||
if (layer == 0 && typeof(z) === 'undefined') {
|
||||
if (layer === 0 && typeof(z) === 'undefined') {
|
||||
z = 0;
|
||||
}
|
||||
|
||||
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract != 0) {
|
||||
if (typeof(x) !== 'undefined' || typeof(y) !== 'undefined' || typeof(z) !== 'undefined' || retract !== 0) {
|
||||
addToModel = true;
|
||||
move = true;
|
||||
}
|
||||
@@ -462,13 +529,13 @@ var doParse = function () {
|
||||
if (!prev_extrude[tool]) prev_extrude[tool] = {a: 0, b: 0, c: 0, e: 0, abs: 0};
|
||||
if (!prev_retract[tool]) prev_retract[tool] = 0;
|
||||
|
||||
offset = toolOffsets[tool];
|
||||
if (!offset) offset = {x: 0, y: 0};
|
||||
activeToolOffset = toolOffsets[tool];
|
||||
if (!activeToolOffset) activeToolOffset = {x: 0, y: 0};
|
||||
}
|
||||
|
||||
// If move is on a new height and it's not extruding and
|
||||
// it's not currently already in a Z-lift, assume it's possibly a Z-lift
|
||||
if (typeof(z) !== 'undefined' && z != prevZ && !extrude && !zLift) {
|
||||
if (typeof(z) !== 'undefined' && z !== prevZ && !extrude && !zLift) {
|
||||
zLift = true;
|
||||
zLiftZ = prevZ;
|
||||
}
|
||||
@@ -477,7 +544,7 @@ var doParse = function () {
|
||||
zLift = false;
|
||||
}
|
||||
|
||||
if (typeof(z) !== 'undefined' && z != prevZ) {
|
||||
if (typeof(z) !== 'undefined' && z !== prevZ) {
|
||||
if (z_heights[z]) {
|
||||
layer = z_heights[z];
|
||||
} else {
|
||||
@@ -488,7 +555,7 @@ var doParse = function () {
|
||||
sendLayer = layer;
|
||||
sendLayerZ = z;
|
||||
prevZ = z;
|
||||
} else if (typeof(z) == 'undefined' && typeof(prevZ) != 'undefined') {
|
||||
} else if (typeof(z) === 'undefined' && typeof(prevZ) !== 'undefined') {
|
||||
if (z_heights.hasOwnProperty(prevZ)) {
|
||||
layer = z_heights[prevZ];
|
||||
} else {
|
||||
@@ -548,7 +615,7 @@ var doParse = function () {
|
||||
}
|
||||
|
||||
if (typeof(sendLayer) !== "undefined") {
|
||||
if (i - lastSend > gcode.length * 0.02 && sendMultiLayer.length != 0) {
|
||||
if (i - lastSend > gcode.length * 0.02 && sendMultiLayer.length !== 0) {
|
||||
lastSend = i;
|
||||
sendMultiLayerToParent(sendMultiLayer, sendMultiLayerZ, i / gcode.length * 100);
|
||||
sendMultiLayer = [];
|
||||
@@ -568,7 +635,10 @@ var parseGCode = function (message) {
|
||||
gcode = message.gcode;
|
||||
firstReport = message.options.firstReport;
|
||||
toolOffsets = message.options.toolOffsets;
|
||||
if (!toolOffsets || toolOffsets.length == 0) toolOffsets = [{x: 0, y: 0}]
|
||||
if (!toolOffsets || toolOffsets.length === 0) toolOffsets = [{x: 0, y: 0}];
|
||||
bed = message.options.bed;
|
||||
ignoreOutsideBed = message.options.ignoreOutsideBed;
|
||||
g90InfluencesExtruder = message.options.g90InfluencesExtruder;
|
||||
|
||||
doParse();
|
||||
gcode = [];
|
||||
@@ -589,6 +659,7 @@ var runAnalyze = function (message) {
|
||||
max = {x: undefined, y: undefined, z: undefined};
|
||||
min = {x: undefined, y: undefined, z: undefined};
|
||||
modelSize = {x: undefined, y: undefined, z: undefined};
|
||||
boundingBox = {minX: undefined, maxX: undefined, minY: undefined, maxY: undefined, minZ: undefined, maxZ: undefined};
|
||||
filamentByLayer = {};
|
||||
totalFilament = 0;
|
||||
printTime = 0;
|
||||
@@ -601,6 +672,7 @@ var runAnalyze = function (message) {
|
||||
|
||||
var setOption = function (options) {
|
||||
for (var opt in options) {
|
||||
if (!options.hasOwnProperty(opt)) continue;
|
||||
gCodeOptions[opt] = options[opt];
|
||||
}
|
||||
};
|
||||
|
||||
@@ -12,6 +12,9 @@ GCODE.gCodeReader = (function(){
|
||||
var max = {x: undefined, y: undefined, z: undefined};
|
||||
var min = {x: undefined, y: undefined, z: undefined};
|
||||
var modelSize = {x: undefined, y: undefined, z: undefined};
|
||||
var boundingBox = {minX: undefined, maxX: undefined,
|
||||
minY: undefined, maxY: undefined,
|
||||
minZ: undefined, maxZ: undefined};
|
||||
var filamentByLayer = {};
|
||||
var printTimeByLayer;
|
||||
var totalFilament=0;
|
||||
@@ -24,7 +27,16 @@ GCODE.gCodeReader = (function(){
|
||||
analyzeModel: false,
|
||||
toolOffsets: [
|
||||
{x: 0, y: 0}
|
||||
]
|
||||
],
|
||||
bed: {
|
||||
x: undefined,
|
||||
y: undefined,
|
||||
r: undefined,
|
||||
circular: undefined,
|
||||
centeredOrigin: undefined
|
||||
},
|
||||
ignoreOutsideBed: false,
|
||||
g90InfluencesExtruder: false
|
||||
};
|
||||
|
||||
var percentageTree = undefined;
|
||||
@@ -122,6 +134,12 @@ GCODE.gCodeReader = (function(){
|
||||
clear: function() {
|
||||
model = [];
|
||||
z_heights = [];
|
||||
max = {x: undefined, y: undefined, z: undefined};
|
||||
min = {x: undefined, y: undefined, z: undefined};
|
||||
modelSize = {x: undefined, y: undefined, z: undefined};
|
||||
boundingBox = {minX: undefined, maxX: undefined,
|
||||
minY: undefined, maxY: undefined,
|
||||
minZ: undefined, maxZ: undefined};
|
||||
},
|
||||
|
||||
loadFile: function(reader){
|
||||
@@ -138,7 +156,10 @@ GCODE.gCodeReader = (function(){
|
||||
gcode: gcode,
|
||||
options: {
|
||||
firstReport: 5,
|
||||
toolOffsets: gCodeOptions["toolOffsets"]
|
||||
toolOffsets: gCodeOptions["toolOffsets"],
|
||||
bed: gCodeOptions["bed"],
|
||||
ignoreOutsideBed: gCodeOptions["ignoreOutsideBed"],
|
||||
g90InfluencesExtruder: gCodeOptions["g90InfluencesExtruder"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -180,6 +201,7 @@ GCODE.gCodeReader = (function(){
|
||||
min = msg.min;
|
||||
max = msg.max;
|
||||
modelSize = msg.modelSize;
|
||||
boundingBox = msg.boundingBox;
|
||||
totalFilament = msg.totalFilament;
|
||||
filamentByLayer = msg.filamentByLayer;
|
||||
speeds = msg.speeds;
|
||||
@@ -201,6 +223,7 @@ GCODE.gCodeReader = (function(){
|
||||
min: min,
|
||||
max: max,
|
||||
modelSize: modelSize,
|
||||
boundingBox: boundingBox,
|
||||
totalFilament: totalFilament,
|
||||
speeds: speeds,
|
||||
speedsByLayer: speedsByLayer,
|
||||
|
||||
@@ -20,7 +20,8 @@ GCODE.renderer = (function(){
|
||||
var lastX, lastY;
|
||||
var dragStart, dragged;
|
||||
var scaleFactor = 1.1;
|
||||
var model;
|
||||
var model = undefined;
|
||||
var modelInfo = undefined;
|
||||
var initialized = false;
|
||||
var renderOptions = {
|
||||
colorGrid: "#bbbbbb",
|
||||
@@ -40,6 +41,8 @@ GCODE.renderer = (function(){
|
||||
differentiateColors: true,
|
||||
showNextLayer: false,
|
||||
showPreviousLayer: false,
|
||||
showBoundingBox: false,
|
||||
showFullSize: false,
|
||||
|
||||
moveModel: true,
|
||||
zoomInOnModel: false,
|
||||
@@ -65,6 +68,7 @@ GCODE.renderer = (function(){
|
||||
var p2 = ctx.transformedPoint(canvas.width,canvas.height);
|
||||
ctx.clearRect(p1.x,p1.y,p2.x-p1.x,p2.y-p1.y);
|
||||
drawGrid();
|
||||
drawBoundingBox();
|
||||
if(renderOptions['showNextLayer'] && layerNumStore < model.length - 1) {
|
||||
drawLayer(layerNumStore + 1, 0, GCODE.renderer.getLayerNumSegments(layerNumStore + 1), true);
|
||||
}
|
||||
@@ -378,6 +382,44 @@ GCODE.renderer = (function(){
|
||||
ctx.stroke();
|
||||
};
|
||||
|
||||
var drawBoundingBox = function() {
|
||||
if (!modelInfo) return;
|
||||
|
||||
var minX, minY, width, height;
|
||||
|
||||
if (renderOptions["showFullSize"]) {
|
||||
minX = modelInfo.min.x * zoomFactor;
|
||||
minY = modelInfo.min.y * zoomFactor;
|
||||
width = modelInfo.modelSize.x * zoomFactor;
|
||||
height = modelInfo.modelSize.y * zoomFactor;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.strokeStyle = "#0000ff";
|
||||
ctx.setLineDash([2, 5]);
|
||||
|
||||
ctx.rect(minX, minY * -1, width, height * -1);
|
||||
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
if (renderOptions["showBoundingBox"]) {
|
||||
minX = modelInfo.boundingBox.minX * zoomFactor;
|
||||
minY = modelInfo.boundingBox.minY * zoomFactor;
|
||||
width = modelInfo.boundingBox.maxX * zoomFactor - minX;
|
||||
height = modelInfo.boundingBox.maxY * zoomFactor - minY;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.strokeStyle = "#ff0000";
|
||||
ctx.setLineDash([2, 5]);
|
||||
|
||||
ctx.rect(minX, minY * -1, width, height * -1);
|
||||
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
ctx.setLineDash([1, 0]);
|
||||
};
|
||||
|
||||
var drawLayer = function(layerNum, fromProgress, toProgress, isNotCurrentLayer){
|
||||
log.trace("Drawing layer " + layerNum + " from " + fromProgress + " to " + toProgress + " (current: " + !isNotCurrentLayer + ")");
|
||||
|
||||
@@ -524,27 +566,27 @@ GCODE.renderer = (function(){
|
||||
ctx.stroke();
|
||||
};
|
||||
|
||||
var applyOffsets = function(mdlInfo) {
|
||||
var applyOffsets = function() {
|
||||
var canvasCenter;
|
||||
|
||||
// determine bed and model offsets
|
||||
if (ctx) ctx.translate(-offsetModelX, -offsetModelY);
|
||||
if (renderOptions["centerViewport"] || renderOptions["zoomInOnModel"]) {
|
||||
canvasCenter = ctx.transformedPoint(canvas.width / 2, canvas.height / 2);
|
||||
if (mdlInfo) {
|
||||
offsetModelX = canvasCenter.x - (mdlInfo.min.x + mdlInfo.modelSize.x / 2) * zoomFactor;
|
||||
offsetModelY = canvasCenter.y + (mdlInfo.min.y + mdlInfo.modelSize.y / 2) * zoomFactor;
|
||||
if (modelInfo) {
|
||||
offsetModelX = canvasCenter.x - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) * zoomFactor / 2;
|
||||
offsetModelY = canvasCenter.y + (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) * zoomFactor / 2;
|
||||
} else {
|
||||
offsetModelX = 0;
|
||||
offsetModelY = 0;
|
||||
}
|
||||
offsetBedX = 0;
|
||||
offsetBedY = 0;
|
||||
} else if (mdlInfo && renderOptions["moveModel"]) {
|
||||
offsetModelX = (renderOptions["bed"]["x"] / 2 - (mdlInfo.min.x + mdlInfo.modelSize.x / 2)) * zoomFactor;
|
||||
offsetModelY = -1 * (renderOptions["bed"]["y"] / 2 - (mdlInfo.min.y + mdlInfo.modelSize.y / 2)) * zoomFactor;
|
||||
offsetBedX = -1 * (renderOptions["bed"]["x"] / 2 - (mdlInfo.min.x + mdlInfo.modelSize.x / 2)) * zoomFactor;
|
||||
offsetBedY = (renderOptions["bed"]["y"] / 2 - (mdlInfo.min.y + mdlInfo.modelSize.y / 2)) * zoomFactor;
|
||||
} else if (modelInfo && renderOptions["moveModel"]) {
|
||||
offsetModelX = (renderOptions["bed"]["x"] / 2 - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2) * zoomFactor;
|
||||
offsetModelY = -1 * (renderOptions["bed"]["y"] / 2 - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2) * zoomFactor;
|
||||
offsetBedX = -1 * (renderOptions["bed"]["x"] / 2 - (modelInfo.boundingBox.minX + modelInfo.boundingBox.maxX) / 2) * zoomFactor;
|
||||
offsetBedY = (renderOptions["bed"]["y"] / 2 - (modelInfo.boundingBox.minY + modelInfo.boundingBox.maxY) / 2) * zoomFactor;
|
||||
} else if (renderOptions["bed"]["circular"] || renderOptions["bed"]["centeredOrigin"]) {
|
||||
canvasCenter = ctx.transformedPoint(canvas.width / 2, canvas.height / 2);
|
||||
offsetModelX = canvasCenter.x;
|
||||
@@ -560,7 +602,7 @@ GCODE.renderer = (function(){
|
||||
if (ctx) ctx.translate(offsetModelX, offsetModelY);
|
||||
};
|
||||
|
||||
var applyZoom = function(mdlInfo) {
|
||||
var applyZoom = function() {
|
||||
// get middle of canvas
|
||||
var pt = ctx.transformedPoint(canvas.width/2,canvas.height/2);
|
||||
|
||||
@@ -575,9 +617,12 @@ GCODE.renderer = (function(){
|
||||
transform = ctx.getTransform();
|
||||
}
|
||||
|
||||
if (mdlInfo && renderOptions["zoomInOnModel"]) {
|
||||
if (modelInfo && renderOptions["zoomInOnModel"]) {
|
||||
// if we need to zoom in on model, scale factor is calculated by longer side of object in relation to that axis of canvas
|
||||
var scaleF = mdlInfo.modelSize.x > mdlInfo.modelSize.y ? (canvas.width - 10) / mdlInfo.modelSize.x : (canvas.height - 10) / mdlInfo.modelSize.y;
|
||||
var width = modelInfo.boundingBox.maxX - modelInfo.boundingBox.minX;
|
||||
var length = modelInfo.boundingBox.maxY - modelInfo.boundingBox.minY;
|
||||
|
||||
var scaleF = width > length ? (canvas.width - 10) / width : (canvas.height - 10) / length;
|
||||
scaleF /= zoomFactor;
|
||||
if (transform.a && transform.d) {
|
||||
scaleX = scaleF / transform.a * (renderOptions["invertAxes"]["x"] ? -1 : 1);
|
||||
@@ -682,6 +727,7 @@ GCODE.renderer = (function(){
|
||||
var p2 = ctx.transformedPoint(canvas.width, canvas.height);
|
||||
ctx.clearRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
|
||||
drawGrid();
|
||||
drawBoundingBox();
|
||||
if (model && model.length) {
|
||||
if (layerNum < model.length) {
|
||||
if (renderOptions['showNextLayer'] && layerNum < model.length - 1) {
|
||||
@@ -715,30 +761,31 @@ GCODE.renderer = (function(){
|
||||
scaleY = 1;
|
||||
speeds = [];
|
||||
speedsByLayer = {};
|
||||
modelInfo = undefined;
|
||||
|
||||
this.doRender([], 0);
|
||||
},
|
||||
doRender: function(mdl, layerNum){
|
||||
model = mdl;
|
||||
modelInfo = undefined;
|
||||
|
||||
var mdlInfo = undefined;
|
||||
prevX = 0;
|
||||
prevY = 0;
|
||||
if (!initialized) this.init();
|
||||
|
||||
var toProgress = 1;
|
||||
if (model) {
|
||||
mdlInfo = GCODE.gCodeReader.getModelInfo();
|
||||
speeds = mdlInfo.speeds;
|
||||
speedsByLayer = mdlInfo.speedsByLayer;
|
||||
if (model && model.length) {
|
||||
modelInfo = GCODE.gCodeReader.getModelInfo();
|
||||
speeds = modelInfo.speeds;
|
||||
speedsByLayer = modelInfo.speedsByLayer;
|
||||
if (model[layerNum]) {
|
||||
toProgress = model[layerNum].length;
|
||||
}
|
||||
}
|
||||
|
||||
applyInversion();
|
||||
applyOffsets(mdlInfo);
|
||||
applyZoom(mdlInfo);
|
||||
applyOffsets();
|
||||
applyZoom();
|
||||
|
||||
this.render(layerNum, 0, toProgress);
|
||||
},
|
||||
|
||||
@@ -161,7 +161,8 @@ GCODE.ui = (function(){
|
||||
bed: options.bed
|
||||
});
|
||||
GCODE.gCodeReader.setOption({
|
||||
toolOffsets: options.toolOffsets
|
||||
toolOffsets: options.toolOffsets,
|
||||
bed: options.bed
|
||||
});
|
||||
GCODE.renderer.render(0, 0);
|
||||
|
||||
|
||||
@@ -11,6 +11,13 @@
|
||||
background-color: #ffffff;
|
||||
}
|
||||
|
||||
a,
|
||||
a:hover,
|
||||
a:active,
|
||||
a:visited {
|
||||
color: #333333;
|
||||
}
|
||||
|
||||
#startup-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
@@ -53,6 +60,10 @@
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.normal {
|
||||
color: #333333;
|
||||
}
|
||||
|
||||
.green {
|
||||
color: #169300;
|
||||
}
|
||||
@@ -166,9 +177,22 @@
|
||||
var cachedTimeout;
|
||||
|
||||
var message = window.document.getElementById("message");
|
||||
var reloadnow = window.document.getElementById("reloadnow");
|
||||
var reloadnowlink = window.document.getElementById("reloadnowlink");
|
||||
|
||||
var reload = function() {
|
||||
var reloadUrl = baseUrl + currentQuery + currentFragment;
|
||||
if (reloadUrl == window.location.href) {
|
||||
window.location.reload(false);
|
||||
} else {
|
||||
window.location.href = reloadUrl;
|
||||
}
|
||||
};
|
||||
|
||||
var indexCached = false;
|
||||
var indexCachedCallback = function(result) {
|
||||
if (indexCached) return;
|
||||
|
||||
if (result == "load") {
|
||||
if (indexCached) {
|
||||
return;
|
||||
@@ -178,13 +202,9 @@
|
||||
indexCached = true;
|
||||
message.className = "pulsate1 green";
|
||||
message.innerText = "OctoPrint server ready, reloading page...";
|
||||
reloadnow.style.display = "none";
|
||||
|
||||
var reloadUrl = baseUrl + currentQuery + currentFragment;
|
||||
if (reloadUrl == window.location.href) {
|
||||
window.location.reload(false);
|
||||
} else {
|
||||
window.location.href = reloadUrl;
|
||||
}
|
||||
reload();
|
||||
} else {
|
||||
// cached.gif still not available, let's look at it again in a second
|
||||
cachedTimeout = setTimeout(function() {
|
||||
@@ -198,6 +218,19 @@
|
||||
if (result == "load") {
|
||||
// our online.gif loaded, so the server is up, let's wait for it to become ready
|
||||
serverIsOnline = true;
|
||||
|
||||
message.innerText = "OctoPrint server started, waiting for it to get ready...";
|
||||
reloadnowlink.onclick = function() {
|
||||
indexCached = true; // not really, but we fake it
|
||||
|
||||
message.className = "pulsate1";
|
||||
message.innerText = "Reloading page...";
|
||||
reloadnow.style.display = "none";
|
||||
|
||||
reload();
|
||||
};
|
||||
reloadnow.style.display = "block";
|
||||
|
||||
ping(indexCachedUrl, timeout, indexCachedCallback);
|
||||
} else {
|
||||
// online.gif still not available, let's look at it again later
|
||||
@@ -255,6 +288,7 @@
|
||||
<div class="inner">
|
||||
<div class="content">
|
||||
<h1 id="message" class="pulsate3">OctoPrint is still starting up, please wait...</h1>
|
||||
<small id="reloadnow" style="display: none"><a id="reloadnowlink" class="normal" href="javascript:void(0)">Don't wait, reload now!</a></small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -14,6 +14,7 @@ ko.bindingHandlers.toggleContent = {
|
||||
e.preventDefault();
|
||||
if(options.class) {
|
||||
$elm.children('[class^="icon-"]').toggleClass(options.class);
|
||||
$elm.children('[class^="fa"]').toggleClass(options.class);
|
||||
}
|
||||
if(options.container) {
|
||||
if(options.parent) {
|
||||
|
||||
@@ -106,6 +106,7 @@
|
||||
var onOpen = function() {
|
||||
self.reconnecting = false;
|
||||
self.reconnectTrial = 0;
|
||||
self.onConnected();
|
||||
};
|
||||
|
||||
var onClose = function(e) {
|
||||
@@ -117,6 +118,8 @@
|
||||
return;
|
||||
}
|
||||
|
||||
self.onDisconnected(e.code);
|
||||
|
||||
if (self.reconnectTrial < self.options.timeouts.length) {
|
||||
var timeout = self.options.timeouts[self.reconnectTrial];
|
||||
setTimeout(function() { self.reconnect() }, timeout * 1000);
|
||||
@@ -160,6 +163,8 @@
|
||||
|
||||
OctoPrintSocketClient.prototype.onReconnectAttempt = function(trial) {};
|
||||
OctoPrintSocketClient.prototype.onReconnectFailed = function() {};
|
||||
OctoPrintSocketClient.prototype.onConnected = function() {};
|
||||
OctoPrintSocketClient.prototype.onDisconnected = function(code) {};
|
||||
|
||||
OctoPrintSocketClient.prototype.onRateTooLow = function(measured, minimum) {
|
||||
this.increaseRate();
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
function DataUpdater(allViewModels) {
|
||||
function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
|
||||
var self = this;
|
||||
|
||||
self.allViewModels = allViewModels;
|
||||
self.connectCallback = connectCallback;
|
||||
self.disconnectCallback = disconnectCallback;
|
||||
|
||||
self._pluginHash = undefined;
|
||||
self._configHash = undefined;
|
||||
|
||||
self._connectedDeferred = undefined;
|
||||
|
||||
self._initializedDeferred = undefined;
|
||||
|
||||
self._throttleFactor = 1;
|
||||
self._baseProcessingLimit = 500.0;
|
||||
self._lastProcessingTimes = [];
|
||||
@@ -57,6 +61,13 @@ function DataUpdater(allViewModels) {
|
||||
return self._connectedDeferred.promise();
|
||||
};
|
||||
|
||||
self.initialized = function() {
|
||||
if (self._initializedDeferred) {
|
||||
self._initializedDeferred.resolve();
|
||||
self._initializedDeferred = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
self._onReconnectAttempt = function(trial) {
|
||||
if (trial <= 0) {
|
||||
// Only consider it a real disconnect if the trial number has exceeded our threshold.
|
||||
@@ -99,7 +110,27 @@ function DataUpdater(allViewModels) {
|
||||
$("#offline_overlay_message").html(gettext("The server appears to be offline, at least I'm not getting any response from it. I <strong>could not reconnect automatically</strong>, but you may try a manual reconnect using the button below."));
|
||||
};
|
||||
|
||||
self._onConnected = function(event) {
|
||||
self._onDisconnected = function(code) {
|
||||
if (self._initializedDeferred) {
|
||||
self._initializedDeferred.reject();
|
||||
}
|
||||
self._initializedDeferred = undefined;
|
||||
|
||||
if (self.disconnectCallback) {
|
||||
self.disconnectCallback();
|
||||
}
|
||||
};
|
||||
|
||||
self._onConnectMessage = function(event) {
|
||||
if (self._initializedDeferred) {
|
||||
self._initializedDeferred.reject();
|
||||
}
|
||||
self._initializedDeferred = $.Deferred();
|
||||
|
||||
if (self.connectCallback) {
|
||||
self.connectCallback();
|
||||
}
|
||||
|
||||
var data = event.data;
|
||||
|
||||
// update version information
|
||||
@@ -117,37 +148,40 @@ function DataUpdater(allViewModels) {
|
||||
var oldConfigHash = self._configHash;
|
||||
self._configHash = data["config_hash"];
|
||||
|
||||
// process safe mode
|
||||
if (self._safeModePopup) self._safeModePopup.remove();
|
||||
if (data["safe_mode"]) {
|
||||
// safe mode is active, let's inform the user
|
||||
log.info("Safe mode is active. Third party plugins are disabled and cannot be enabled.");
|
||||
self._ifInitialized(function() {
|
||||
// process safe mode
|
||||
if (self._safeModePopup) self._safeModePopup.remove();
|
||||
if (data["safe_mode"]) {
|
||||
// safe mode is active, let's inform the user
|
||||
log.info("Safe mode is active. Third party plugins are disabled and cannot be enabled.");
|
||||
|
||||
self._safeModePopup = new PNotify({
|
||||
title: gettext("Safe mode is active"),
|
||||
text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."),
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
self._safeModePopup = new PNotify({
|
||||
title: gettext("Safe mode is active"),
|
||||
text: gettext("The server is currently running in safe mode. Third party plugins are disabled and cannot be enabled."),
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
|
||||
// if the offline overlay is still showing, now's a good time to
|
||||
// hide it, plus reload the camera feed if it's currently displayed
|
||||
if ($("#offline_overlay").is(":visible")) {
|
||||
hideOfflineOverlay();
|
||||
callViewModels(self.allViewModels, "onServerReconnect");
|
||||
callViewModels(self.allViewModels, "onDataUpdaterReconnect");
|
||||
} else {
|
||||
callViewModels(self.allViewModels, "onServerConnect");
|
||||
}
|
||||
// if the offline overlay is still showing, now's a good time to
|
||||
// hide it, plus reload the camera feed if it's currently displayed
|
||||
if ($("#offline_overlay").is(":visible")) {
|
||||
hideOfflineOverlay();
|
||||
callViewModels(self.allViewModels, "onServerReconnect");
|
||||
callViewModels(self.allViewModels, "onDataUpdaterReconnect");
|
||||
} else {
|
||||
callViewModels(self.allViewModels, "onServerConnect");
|
||||
}
|
||||
|
||||
// if the version, the plugin hash or the config hash changed, we
|
||||
// want the user to reload the UI since it might be stale now
|
||||
var versionChanged = oldVersion != VERSION;
|
||||
var pluginsChanged = oldPluginHash != undefined && oldPluginHash != self._pluginHash;
|
||||
var configChanged = oldConfigHash != undefined && oldConfigHash != self._configHash;
|
||||
if (versionChanged || pluginsChanged || configChanged) {
|
||||
showReloadOverlay();
|
||||
}
|
||||
// if the version, the plugin hash or the config hash changed, we
|
||||
// want the user to reload the UI since it might be stale now
|
||||
var versionChanged = oldVersion !== VERSION;
|
||||
var pluginsChanged = oldPluginHash !== undefined && oldPluginHash !== self._pluginHash;
|
||||
var configChanged = oldConfigHash !== undefined && oldConfigHash !== self._configHash;
|
||||
if (versionChanged || pluginsChanged || configChanged) {
|
||||
showReloadOverlay();
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
log.info("Connected to the server");
|
||||
|
||||
@@ -159,79 +193,89 @@ function DataUpdater(allViewModels) {
|
||||
};
|
||||
|
||||
self._onHistoryData = function(event) {
|
||||
callViewModels(self.allViewModels, "fromHistoryData", [event.data]);
|
||||
};
|
||||
|
||||
self._onCurrentData = function(event) {
|
||||
callViewModels(self.allViewModels, "fromCurrentData", [event.data]);
|
||||
};
|
||||
|
||||
self._onSlicingProgress = function(event) {
|
||||
$("#gcode_upload_progress").find(".bar").text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(event.data["progress"])}));
|
||||
|
||||
var data = event.data;
|
||||
callViewModels(self.allViewModels, "onSlicingProgress", [
|
||||
data["slicer"],
|
||||
data["model_path"],
|
||||
data["machinecode_path"],
|
||||
data["progress"]
|
||||
]);
|
||||
};
|
||||
|
||||
self._onEvent = function(event) {
|
||||
var gcodeUploadProgress = $("#gcode_upload_progress");
|
||||
var gcodeUploadProgressBar = $(".bar", gcodeUploadProgress);
|
||||
|
||||
var type = event.data["type"];
|
||||
var payload = event.data["payload"];
|
||||
var html = "";
|
||||
|
||||
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
|
||||
|
||||
if (type == "PrintCancelled") {
|
||||
if (payload.firmwareError) {
|
||||
new PNotify({
|
||||
title: gettext("Unhandled communication error"),
|
||||
text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
} else if (type == "Error") {
|
||||
new PNotify({
|
||||
title: gettext("Unhandled communication error"),
|
||||
text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
|
||||
var legacyEventHandlers = {
|
||||
"UpdatedFiles": "onUpdatedFiles",
|
||||
"MetadataStatisticsUpdated": "onMetadataStatisticsUpdated",
|
||||
"MetadataAnalysisFinished": "onMetadataAnalysisFinished",
|
||||
"SlicingDone": "onSlicingDone",
|
||||
"SlicingCancelled": "onSlicingCancelled",
|
||||
"SlicingFailed": "onSlicingFailed"
|
||||
};
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
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);
|
||||
}
|
||||
self._ifInitialized(function() {
|
||||
callViewModels(self.allViewModels, "fromHistoryData", [event.data]);
|
||||
});
|
||||
};
|
||||
|
||||
self._onCurrentData = function(event) {
|
||||
self._ifInitialized(function() {
|
||||
callViewModels(self.allViewModels, "fromCurrentData", [event.data]);
|
||||
});
|
||||
};
|
||||
|
||||
self._onSlicingProgress = function(event) {
|
||||
self._ifInitialized(function() {
|
||||
$("#gcode_upload_progress").find(".bar").text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: Math.round(event.data["progress"])}));
|
||||
|
||||
var data = event.data;
|
||||
callViewModels(self.allViewModels, "onSlicingProgress", [
|
||||
data["slicer"],
|
||||
data["model_path"],
|
||||
data["machinecode_path"],
|
||||
data["progress"]
|
||||
]);
|
||||
});
|
||||
};
|
||||
|
||||
self._onEvent = function(event) {
|
||||
self._ifInitialized(function() {
|
||||
var type = event.data["type"];
|
||||
var payload = event.data["payload"];
|
||||
|
||||
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
|
||||
|
||||
if (type == "PrintCancelled") {
|
||||
if (payload.firmwareError) {
|
||||
new PNotify({
|
||||
title: gettext("Unhandled communication error"),
|
||||
text: _.sprintf(gettext("There was an unhandled error while talking to the printer. Due to that the ongoing print job was cancelled. Error: %(firmwareError)s"), payload),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
} else if (type == "Error") {
|
||||
if (payload.error && payload.error.indexOf("autodetect") == -1) { // ignore "failed to autodetect"
|
||||
new PNotify({
|
||||
title: gettext("Unhandled communication error"),
|
||||
text: _.sprintf(gettext("The was an unhandled error while talking to the printer. Due to that OctoPrint disconnected. Error: %(error)s"), payload),
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
var legacyEventHandlers = {
|
||||
"UpdatedFiles": "onUpdatedFiles",
|
||||
"MetadataStatisticsUpdated": "onMetadataStatisticsUpdated",
|
||||
"MetadataAnalysisFinished": "onMetadataAnalysisFinished",
|
||||
"SlicingDone": "onSlicingDone",
|
||||
"SlicingCancelled": "onSlicingCancelled",
|
||||
"SlicingFailed": "onSlicingFailed"
|
||||
};
|
||||
_.each(self.allViewModels, function(viewModel) {
|
||||
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);
|
||||
}
|
||||
});
|
||||
})
|
||||
};
|
||||
|
||||
self._onTimelapse = function(event) {
|
||||
callViewModels(self.allViewModels, "fromTimelapseData", [event.data]);
|
||||
self._ifInitialized(function() {
|
||||
callViewModels(self.allViewModels, "fromTimelapseData", [event.data]);
|
||||
})
|
||||
};
|
||||
|
||||
self._onPluginMessage = function(event) {
|
||||
callViewModels(self.allViewModels, "onDataUpdaterPluginMessage", [event.data.plugin, event.data.data]);
|
||||
self._ifInitialized(function() {
|
||||
callViewModels(self.allViewModels, "onDataUpdaterPluginMessage", [event.data.plugin, event.data.data]);
|
||||
})
|
||||
};
|
||||
|
||||
self._onIncreaseRate = function(measurement, minimum) {
|
||||
@@ -244,12 +288,21 @@ function DataUpdater(allViewModels) {
|
||||
OctoPrint.socket.decreaseRate();
|
||||
};
|
||||
|
||||
self._ifInitialized = function(callback) {
|
||||
if (self._initializedDeferred) {
|
||||
self._initializedDeferred.done(callback);
|
||||
} else {
|
||||
callback();
|
||||
}
|
||||
};
|
||||
|
||||
OctoPrint.socket.onDisconnected = self._onDisconnected;
|
||||
OctoPrint.socket.onReconnectAttempt = self._onReconnectAttempt;
|
||||
OctoPrint.socket.onReconnectFailed = self._onReconnectFailed;
|
||||
OctoPrint.socket.onRateTooHigh = self._onDecreaseRate;
|
||||
OctoPrint.socket.onRateTooLow = self._onIncreaseRate;
|
||||
OctoPrint.socket
|
||||
.onMessage("connected", self._onConnected)
|
||||
.onMessage("connected", self._onConnectMessage)
|
||||
.onMessage("history", self._onHistoryData)
|
||||
.onMessage("current", self._onCurrentData)
|
||||
.onMessage("slicingProgress", self._onSlicingProgress)
|
||||
|
||||
@@ -398,7 +398,7 @@ function formatFuzzyPrintTime(totalSeconds) {
|
||||
*
|
||||
* Accuracy decreases the higher the estimation is:
|
||||
*
|
||||
* * less than 30s: "a couple of seconds"
|
||||
* * less than 30s: "a few seconds"
|
||||
* * 30s to a minute: "less than a minute"
|
||||
* * 1 to 30min: rounded to full minutes, above 30s is minute + 1 ("27 minutes", "2 minutes")
|
||||
* * 30min to 40min: "40 minutes"
|
||||
@@ -495,7 +495,7 @@ function formatFuzzyPrintTime(totalSeconds) {
|
||||
} else {
|
||||
// only seconds
|
||||
if (seconds < 30) {
|
||||
text = gettext("a couple of seconds");
|
||||
text = gettext("a few seconds");
|
||||
} else {
|
||||
text = gettext("less than a minute");
|
||||
}
|
||||
@@ -524,12 +524,14 @@ function formatFilament(filament) {
|
||||
}
|
||||
|
||||
function cleanTemperature(temp) {
|
||||
if (!temp || temp < 10) return gettext("off");
|
||||
if (temp === undefined || !_.isNumber(temp)) return "-";
|
||||
if (temp < 10) return gettext("off");
|
||||
return temp;
|
||||
}
|
||||
|
||||
function formatTemperature(temp, showF) {
|
||||
if (!temp || temp < 10) return gettext("off");
|
||||
if (temp === undefined || !_.isNumber(temp)) return "-";
|
||||
if (temp < 10) return gettext("off");
|
||||
if (showF) {
|
||||
return _.sprintf("%.1f°C (%.1f°F)", temp, temp * 9 / 5 + 32);
|
||||
} else {
|
||||
@@ -646,6 +648,7 @@ function showConfirmationDialog(msg, onacknowledge, options) {
|
||||
var proceed = options.proceed || gettext("Proceed");
|
||||
var proceedClass = options.proceedClass || "danger";
|
||||
var onproceed = options.onproceed || undefined;
|
||||
var onclose = options.onclose || undefined;
|
||||
var dialogClass = options.dialogClass || "";
|
||||
|
||||
var modalHeader = $('<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">×</a><h3>' + title + '</h3>');
|
||||
@@ -663,14 +666,19 @@ function showConfirmationDialog(msg, onacknowledge, options) {
|
||||
.append($('<div></div>').addClass('modal-header').append(modalHeader))
|
||||
.append($('<div></div>').addClass('modal-body').append(modalBody))
|
||||
.append($('<div></div>').addClass('modal-footer').append(cancelButton).append(proceedButton));
|
||||
modal.on('hidden', function(event) {
|
||||
if (onclose && _.isFunction(onclose)) {
|
||||
onclose(event);
|
||||
}
|
||||
});
|
||||
modal.modal("show");
|
||||
|
||||
proceedButton.click(function(e) {
|
||||
e.preventDefault();
|
||||
modal.modal("hide");
|
||||
if (onproceed && _.isFunction(onproceed)) {
|
||||
onproceed(e);
|
||||
}
|
||||
modal.modal("hide");
|
||||
});
|
||||
|
||||
return modal;
|
||||
@@ -682,9 +690,14 @@ function showConfirmationDialog(msg, onacknowledge, options) {
|
||||
* Will listen to the supplied promise, update the progress on .progress events and
|
||||
* enabling the close button and (optionally) closing the dialog on promise resolve.
|
||||
*
|
||||
* The calling code should call "notify" on the deferred backing the promise and supply
|
||||
* two parameters: the text to display on the progress bar and the optional output field and
|
||||
* a boolean value indicating whether the operation behind that update was successful or not.
|
||||
* The calling code should call "notify" on the deferred backing the promise and supply:
|
||||
*
|
||||
* * the text to display on the progress bar and the optional output field and
|
||||
* a boolean value indicating whether the operation behind that update was successful or not
|
||||
* * a short text to display on the progress bar, a long text to display on the optional output
|
||||
* field and a boolean value indicating whether the operation behind that update was
|
||||
* successful or not
|
||||
*
|
||||
* Non-successful progress updates will remove the barClassSuccess class from the progress bar and
|
||||
* apply the barClassFailure class and also apply the outputClassFailure to the produced line
|
||||
* in the output.
|
||||
@@ -764,7 +777,7 @@ function showProgressModal(options, promise) {
|
||||
|
||||
var pre;
|
||||
if (output) {
|
||||
pre = $("<pre class='terminal pre-scrollable' style='height: 70px; font-size: 0.8em'></pre>");
|
||||
pre = $("<pre class='pre-scrollable pre-output' style='height: 70px; font-size: 0.8em'></pre>");
|
||||
modalBody.append(pre);
|
||||
}
|
||||
|
||||
@@ -778,7 +791,19 @@ function showProgressModal(options, promise) {
|
||||
|
||||
var counter = 0;
|
||||
promise
|
||||
.progress(function(text, success) {
|
||||
.progress(function() {
|
||||
var short, long, success;
|
||||
if (arguments.length === 2) {
|
||||
short = long = arguments[0];
|
||||
success = arguments[1];
|
||||
} else if (arguments.length === 3) {
|
||||
short = arguments[0];
|
||||
long = arguments[1];
|
||||
success = arguments[2];
|
||||
} else {
|
||||
throw Error("Invalid parameters for showProgressModal, expected either (text, success) or (short, long, success)");
|
||||
}
|
||||
|
||||
var value;
|
||||
|
||||
if (max === undefined || max <= 0) {
|
||||
@@ -790,8 +815,8 @@ function showProgressModal(options, promise) {
|
||||
|
||||
// update progress bar
|
||||
progressBar.width(String(value) + "%");
|
||||
progressTextFront.text(text);
|
||||
progressTextBack.text(text);
|
||||
progressTextFront.text(short);
|
||||
progressTextBack.text(short);
|
||||
progressTextFront.width(progress.width());
|
||||
|
||||
// if not successful, apply failure class
|
||||
@@ -803,9 +828,9 @@ function showProgressModal(options, promise) {
|
||||
|
||||
if (output && pre) {
|
||||
if (success) {
|
||||
pre.append($("<span class='" + outputClassSuccess + "'>" + text + "</span><br>"));
|
||||
pre.append($("<span class='" + outputClassSuccess + "'>" + long + "</span>"));
|
||||
} else {
|
||||
pre.append($("<span class='" + outputClassFailure + "'>" + text + "</span><br>"));
|
||||
pre.append($("<span class='" + outputClassFailure + "'>" + long + "</span>"));
|
||||
}
|
||||
pre.scrollTop(pre[0].scrollHeight - pre.height());
|
||||
}
|
||||
@@ -958,6 +983,22 @@ function getOnlyChangedData(data, oldData) {
|
||||
return f(data, oldData);
|
||||
}
|
||||
|
||||
function setOnViewModels(allViewModels, key, value) {
|
||||
setOnViewModelsIf(allViewModels, key, value, undefined);
|
||||
}
|
||||
|
||||
function setOnViewModelsIf(allViewModels, key, value, condition) {
|
||||
if (condition === undefined || !_.isFunction(condition)) {
|
||||
condition = function() { return true; };
|
||||
}
|
||||
|
||||
_.each(allViewModels, function(viewModel) {
|
||||
if (condition(viewModel)) {
|
||||
viewModel[key] = value;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function callViewModels(allViewModels, method, callback) {
|
||||
callViewModelsIf(allViewModels, method, undefined, callback);
|
||||
}
|
||||
@@ -1048,8 +1089,9 @@ var getQueryParameterByName = function(name, url) {
|
||||
*
|
||||
* E.g. turns a null byte in the string into "\x00".
|
||||
*
|
||||
* Only characters 0 to 31, 127 and 255 will be escaped, that
|
||||
* should leave printable characters and unicode alone.
|
||||
* Characters 0 to 31 excluding 9, 10 and 13 will be escaped, as will
|
||||
* 127 and 255. That should leave printable characters and unicode
|
||||
* alone.
|
||||
*
|
||||
* Originally based on
|
||||
* https://gist.github.com/mathiasbynens/1243213#gistcomment-53590
|
||||
@@ -1063,7 +1105,7 @@ var escapeUnprintableCharacters = function(str) {
|
||||
var charCode;
|
||||
|
||||
while (!isNaN(charCode = str.charCodeAt(index))) {
|
||||
if (charCode < 32 || charCode == 127 || charCode == 255) {
|
||||
if ((charCode < 32 && charCode != 9 && charCode != 10 && charCode != 13) || charCode == 127 || charCode == 255) {
|
||||
// special hex chars
|
||||
result += "\\x" + (charCode > 15 ? "" : "0") + charCode.toString(16)
|
||||
} else {
|
||||
|
||||
@@ -7,7 +7,7 @@ $(function() {
|
||||
|
||||
//~~ Logging setup
|
||||
|
||||
log.setLevel(CONFIG_DEBUG ? "debug" : "info");
|
||||
log.setLevel(CONFIG_DEBUG ? log.levels.DEBUG : log.levels.INFO);
|
||||
|
||||
//~~ OctoPrint client setup
|
||||
OctoPrint.options.baseurl = BASEURL;
|
||||
@@ -38,7 +38,18 @@ $(function() {
|
||||
browserTabVisibility: undefined,
|
||||
selectedTab: undefined,
|
||||
settingsOpen: false,
|
||||
wizardOpen: false
|
||||
wizardOpen: false,
|
||||
browser: {
|
||||
chrome: false,
|
||||
firefox: false,
|
||||
safari: false,
|
||||
ie: false,
|
||||
edge: false,
|
||||
opera: false,
|
||||
|
||||
mobile: false,
|
||||
desktop: false
|
||||
}
|
||||
};
|
||||
|
||||
var browserVisibilityCallbacks = [];
|
||||
@@ -88,6 +99,22 @@ $(function() {
|
||||
updateBrowserVisibility();
|
||||
}
|
||||
|
||||
// determine browser - loosely based on is.js
|
||||
|
||||
var navigator = window.navigator;
|
||||
var userAgent = (navigator && navigator.userAgent || "").toLowerCase();
|
||||
var vendor = (navigator && navigator.vendor || "").toLowerCase();
|
||||
|
||||
exports.browser.opera = userAgent.match(/opera|opr/) != null;
|
||||
exports.browser.chrome = !exports.browser.opera && /google inc/.test(vendor) && userAgent.match(/chrome|crios/) != null;
|
||||
exports.browser.firefox = userAgent.match(/firefox|fxios/) != null;
|
||||
exports.browser.ie = userAgent.match(/msie|trident/) != null;
|
||||
exports.browser.edge = userAgent.match(/edge/) != null;
|
||||
exports.browser.safari = !exports.browser.chrome && !exports.browser.edge && !exports.browser.opera && userAgent.match(/safari/) != null;
|
||||
|
||||
exports.browser.mobile = $.browser.mobile;
|
||||
exports.browser.desktop = !exports.browser.mobile;
|
||||
|
||||
// exports
|
||||
|
||||
exports.isVisible = function() { return !isHidden() };
|
||||
@@ -98,6 +125,8 @@ $(function() {
|
||||
return exports;
|
||||
})();
|
||||
|
||||
log.debug("Browser enviroment:", OctoPrint.coreui.browser);
|
||||
|
||||
//~~ AJAX setup
|
||||
|
||||
// work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at
|
||||
@@ -444,6 +473,18 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
$.fn.lazyload = function() {
|
||||
return this.each(function() {
|
||||
if (this.tagName.toLowerCase() != "img") return;
|
||||
|
||||
var src = this.getAttribute("data-src");
|
||||
if (src) {
|
||||
this.setAttribute("src", src);
|
||||
this.removeAttribute("data-src");
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Use bootstrap tabdrop for tabs and pills
|
||||
$('.nav-pills, .nav-tabs').tabdrop();
|
||||
|
||||
@@ -493,7 +534,15 @@ $(function() {
|
||||
}
|
||||
}
|
||||
|
||||
//~~ view model binding
|
||||
//~~ final initialization - passive login, settings fetch, view model binding
|
||||
|
||||
if (!_.has(viewModelMap, "settingsViewModel")) {
|
||||
throw new Error("settingsViewModel is missing, can't run UI");
|
||||
}
|
||||
|
||||
if (!_.has(viewModelMap, "loginStateViewModel")) {
|
||||
throw new Error("loginStateViewModel is missing, can't run UI");
|
||||
}
|
||||
|
||||
var bindViewModels = function() {
|
||||
log.info("Going to bind " + allViewModelData.length + " view models...");
|
||||
@@ -562,7 +611,8 @@ $(function() {
|
||||
});
|
||||
}
|
||||
|
||||
viewModel._unbound = viewModel._bindings != undefined && viewModel._bindings.length == 0;
|
||||
viewModel._unbound = viewModel._bindings !== undefined && viewModel._bindings.length === 0;
|
||||
viewModel._bound = viewModel._bindings.length > 0;
|
||||
|
||||
if (viewModel.hasOwnProperty("onAfterBinding")) {
|
||||
viewModel.onAfterBinding();
|
||||
@@ -574,6 +624,7 @@ $(function() {
|
||||
|
||||
// startup complete
|
||||
callViewModels(allViewModels, "onStartupComplete");
|
||||
setOnViewModels(allViewModels, "_startupComplete", true);
|
||||
|
||||
// make sure we can track the browser tab visibility
|
||||
OctoPrint.coreui.onBrowserVisibilityChange(function(status) {
|
||||
@@ -593,34 +644,84 @@ $(function() {
|
||||
log.info("Application startup complete");
|
||||
};
|
||||
|
||||
if (!_.has(viewModelMap, "settingsViewModel")) {
|
||||
throw new Error("settingsViewModel is missing, can't run UI")
|
||||
}
|
||||
var fetchSettings = function() {
|
||||
log.info("Finalizing application startup");
|
||||
|
||||
//~~ Starting up the app
|
||||
callViewModels(allViewModels, "onStartup");
|
||||
|
||||
viewModelMap["settingsViewModel"].requestData()
|
||||
.done(function() {
|
||||
// There appears to be an odd race condition either in JQuery's AJAX implementation or
|
||||
// the browser's implementation of XHR, causing a second GET request from inside the
|
||||
// completion handler of the very same request to never get its completion handler called
|
||||
// if ETag headers are present on the response (the status code of the request does NOT
|
||||
// seem to matter here, only that the ETag header is present).
|
||||
//
|
||||
// Minimal example with which I was able to reproduce this behaviour can be found
|
||||
// at https://gist.github.com/foosel/b2ddb9ebd71b0b63a749444651bfce3f
|
||||
//
|
||||
// Decoupling all consecutive calls from this done event handler hence is an easy way
|
||||
// to avoid this problem. A zero timeout should do the trick nicely.
|
||||
window.setTimeout(bindViewModels, 0);
|
||||
});
|
||||
};
|
||||
|
||||
log.info("Initial application setup done, connecting to server...");
|
||||
|
||||
/**
|
||||
* The following looks a bit complicated, so let me explain...
|
||||
*
|
||||
* Once we connect to the server (and that also includes consecutive reconnects), the
|
||||
* first thing we need to do is perform a passive login to a) establish a proper request
|
||||
* session with the server and b) figure out the login status of our client. That passive
|
||||
* login will be responded to with our session cookie and we must make absolutely sure that
|
||||
* this cannot be overridden by any concurrent requests. E.g. if we would send the passive
|
||||
* login request and also something like a settings fetch, the settings would not have the
|
||||
* cookie yet, hence the server would generate a new session for that request, and if the
|
||||
* response for the settings now arrives later than the passive login we'll get our
|
||||
* session cookie from that login directly overwritten again. That will not only lead to
|
||||
* us losing our login session with the server but also the client _thinking_ it is logged
|
||||
* in when in fact it isn't. See also #1881.
|
||||
*
|
||||
* So what we do here is ensure that we send the passive login request _and nothing else_
|
||||
* until that has been responded to and hence our session been properly established. Only
|
||||
* then we may trigger stuff like the various view model callbacks that might cause
|
||||
* additional requests.
|
||||
*
|
||||
* onServerConnect below takes care of the passive login. Only once that's completed it tells
|
||||
* our DataUpdater that it's ok to trigger any callbacks in view models. On the initial
|
||||
* server connect (during first initialization) we also trigger the settings fetch and
|
||||
* binding proceedure once that's done, but only then.
|
||||
*
|
||||
* Or, as a fancy diagram: https://gist.githubusercontent.com/foosel/0cdc3a03cf5311804271f12e87293c0c/raw/abc84fdc3b13030d70961539d9c132ae39c32085/octoprint_web_startup.txt
|
||||
*/
|
||||
|
||||
var onServerConnect = function() {
|
||||
// Always perform a passive login on server (re)connect. No need for
|
||||
// onServerConnect/onServerReconnect on the LoginStateViewModel with this in place.
|
||||
return viewModelMap["loginStateViewModel"].requestData()
|
||||
.done(function() {
|
||||
// Only mark our data updater as initialized once we've done our initial
|
||||
// passive login request.
|
||||
//
|
||||
// This is to ensure that we have no concurrent requests triggered by socket events
|
||||
// overriding each other's session during app intialization
|
||||
dataUpdater.initialized();
|
||||
});
|
||||
};
|
||||
|
||||
var dataUpdater = new DataUpdater(allViewModels);
|
||||
dataUpdater.connect()
|
||||
.done(function() {
|
||||
log.info("Finalizing application startup");
|
||||
// make sure we trigger onServerConnect should we dis- and reconnect to the server
|
||||
dataUpdater.connectCallback = onServerConnect;
|
||||
|
||||
//~~ Starting up the app
|
||||
callViewModels(allViewModels, "onStartup");
|
||||
|
||||
viewModelMap["settingsViewModel"].requestData()
|
||||
.done(function() {
|
||||
// There appears to be an odd race condition either in JQuery's AJAX implementation or
|
||||
// the browser's implementation of XHR, causing a second GET request from inside the
|
||||
// completion handler of the very same request to never get its completion handler called
|
||||
// if ETag headers are present on the response (the status code of the request does NOT
|
||||
// seem to matter here, only that the ETag header is present).
|
||||
//
|
||||
// Minimal example with which I was able to reproduce this behaviour can be found
|
||||
// at https://gist.github.com/foosel/b2ddb9ebd71b0b63a749444651bfce3f
|
||||
//
|
||||
// Decoupling all consecutive calls from this done event handler hence is an easy way
|
||||
// to avoid this problem. A zero timeout should do the trick nicely.
|
||||
window.setTimeout(bindViewModels, 0);
|
||||
});
|
||||
// perform passive login first
|
||||
onServerConnect().done(function() {
|
||||
// then trigger a settings fetch
|
||||
window.setTimeout(fetchSettings, 0);
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
||||
@@ -101,7 +101,7 @@ $(function() {
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
|
||||
if (self.loginState.hasPermission(self.access.permissions.CONNECTION)() && self.previousIsOperational != self.isOperational()) {
|
||||
if (self.loginState.hasPermission(self.access.permissions.CONNECTION)() && self.previousIsOperational !== self.isOperational()) {
|
||||
// only open or close if the panel is visible (for admins) and
|
||||
// the state just changed to avoid thwarting manual open/close
|
||||
self.openOrCloseOnStateChange();
|
||||
@@ -133,16 +133,14 @@ $(function() {
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
// when isAdmin becomes true the first time, set the panel open or
|
||||
// closed based on the connection state
|
||||
var subscription = self.loginState.isAdmin.subscribe(function(newValue) {
|
||||
if (newValue) {
|
||||
// wait until after the isAdmin state has run through all subscriptions
|
||||
setTimeout(self.openOrCloseOnStateChange, 0);
|
||||
subscription.dispose();
|
||||
}
|
||||
});
|
||||
self.onUserLoggedIn = function() {
|
||||
self.openOrCloseOnStateChange();
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
self.openOrCloseOnStateChange();
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,8 @@ $(function() {
|
||||
self.additionalControls = [];
|
||||
|
||||
self.webcamDisableTimeout = undefined;
|
||||
self.webcamLoaded = ko.observable(false);
|
||||
self.webcamError = ko.observable(false);
|
||||
|
||||
self.keycontrolActive = ko.observable(false);
|
||||
self.keycontrolHelpActive = ko.observable(false);
|
||||
@@ -48,6 +50,14 @@ $(function() {
|
||||
return self.keycontrolActive() && self.keycontrolPossible();
|
||||
});
|
||||
|
||||
self.webcamRatioClass = ko.pureComputed(function() {
|
||||
if (self.settings.webcam_streamRatio() == "4:3") {
|
||||
return "ratio43";
|
||||
} else {
|
||||
return "ratio169";
|
||||
}
|
||||
});
|
||||
|
||||
self.settings.printerProfiles.currentProfileData.subscribe(function () {
|
||||
self._updateExtruderCount();
|
||||
self.settings.printerProfiles.currentProfileData().extruder.count.subscribe(self._updateExtruderCount);
|
||||
@@ -344,43 +354,21 @@ $(function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.updateRotatorWidth = function() {
|
||||
var webcamImage = $("#webcam_image");
|
||||
if (self.settings.webcam_rotate90()) {
|
||||
if (webcamImage.width() > 0) {
|
||||
$("#webcam_rotator").css("height", webcamImage.width());
|
||||
} else {
|
||||
webcamImage.off("load.rotator");
|
||||
webcamImage.on("load.rotator", function() {
|
||||
$("#webcam_rotator").css("height", webcamImage.width());
|
||||
webcamImage.off("load.rotator");
|
||||
});
|
||||
}
|
||||
} else {
|
||||
$("#webcam_rotator").css("height", "");
|
||||
}
|
||||
};
|
||||
|
||||
self.onSettingsBeforeSave = self.updateRotatorWidth;
|
||||
|
||||
self._isSafari = function() {
|
||||
var is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
|
||||
var is_safari = navigator.userAgent.indexOf("Safari") > -1;
|
||||
return is_safari && !is_chrome;
|
||||
}
|
||||
|
||||
self._disableWebcam = function() {
|
||||
// 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
|
||||
|
||||
// safari bug doesn't release the mjpeg stream, so we just disable this for safari.
|
||||
if (self._isSafari()) {
|
||||
if (OctoPrint.coreui.browser.safari) {
|
||||
return;
|
||||
}
|
||||
|
||||
var timeout = self.settings.webcam_streamTimeout() || 5;
|
||||
self.webcamDisableTimeout = setTimeout(function () {
|
||||
log.debug("Unloading webcam stream");
|
||||
$("#webcam_image").attr("src", "");
|
||||
}, 5000);
|
||||
self.webcamLoaded(false);
|
||||
}, timeout * 1000);
|
||||
};
|
||||
|
||||
self._enableWebcam = function() {
|
||||
@@ -395,7 +383,7 @@ $(function() {
|
||||
var currentSrc = webcamImage.attr("src");
|
||||
|
||||
// safari bug doesn't release the mjpeg stream, so we just set it up the once
|
||||
if (self._isSafari() && currentSrc != undefined) {
|
||||
if (OctoPrint.coreui.browser.safari && currentSrc != undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -408,11 +396,24 @@ $(function() {
|
||||
}
|
||||
newSrc += new Date().getTime();
|
||||
|
||||
self.updateRotatorWidth();
|
||||
self.webcamLoaded(false);
|
||||
self.webcamError(false);
|
||||
webcamImage.attr("src", newSrc);
|
||||
}
|
||||
};
|
||||
|
||||
self.onWebcamLoaded = function() {
|
||||
log.debug("Webcam stream loaded");
|
||||
self.webcamLoaded(true);
|
||||
self.webcamError(false);
|
||||
};
|
||||
|
||||
self.onWebcamErrored = function() {
|
||||
log.debug("Webcam stream failed to load/disabled");
|
||||
self.webcamLoaded(false);
|
||||
self.webcamError(true);
|
||||
};
|
||||
|
||||
self.onTabChange = function (current, previous) {
|
||||
if (current == "#control") {
|
||||
self._enableWebcam();
|
||||
@@ -438,6 +439,7 @@ $(function() {
|
||||
self.additionalControls = additionalControls;
|
||||
self.rerenderControls();
|
||||
}
|
||||
self._enableWebcam();
|
||||
};
|
||||
|
||||
self.onFocus = function (data, event) {
|
||||
|
||||
@@ -60,6 +60,14 @@ $(function() {
|
||||
self.localTarget = undefined;
|
||||
self.sdTarget = undefined;
|
||||
|
||||
self.dropOverlay = undefined;
|
||||
self.dropZone = undefined;
|
||||
self.dropZoneLocal = undefined;
|
||||
self.dropZoneSd = undefined;
|
||||
self.dropZoneBackground = undefined;
|
||||
self.dropZoneLocalBackground = undefined;
|
||||
self.dropZoneSdBackground = undefined;
|
||||
|
||||
self.ignoreUpdatedFilesEvent = false;
|
||||
|
||||
self.addingFolder = ko.observable(false);
|
||||
@@ -400,14 +408,21 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.loadFile = function(file, printAfterLoad) {
|
||||
if (!file) {
|
||||
self.loadFile = function(data, printAfterLoad) {
|
||||
if (!data) {
|
||||
return;
|
||||
}
|
||||
var withinPrintDimensions = self.evaluatePrintDimensions(file, true);
|
||||
var print = printAfterLoad && withinPrintDimensions;
|
||||
|
||||
OctoPrint.files.select(file.origin, file.path, print);
|
||||
if (printAfterLoad && self.listHelper.isSelected(data) && self.enablePrint(data)) {
|
||||
// file was already selected, just start the print job
|
||||
OctoPrint.job.start();
|
||||
} else {
|
||||
// select file, start print job (if requested and within dimensions)
|
||||
var withinPrintDimensions = self.evaluatePrintDimensions(data, true);
|
||||
var print = printAfterLoad && withinPrintDimensions;
|
||||
|
||||
OctoPrint.files.select(data.origin, data.path, print);
|
||||
}
|
||||
};
|
||||
|
||||
self.removeFile = function(file, event) {
|
||||
@@ -456,13 +471,13 @@ $(function() {
|
||||
if (event) {
|
||||
var element = $(event.currentTarget);
|
||||
if (element.length) {
|
||||
var icon = $("i.icon-trash", element);
|
||||
var icon = $("i.fa-trash-o", element);
|
||||
if (icon.length) {
|
||||
activateSpinner = function() {
|
||||
icon.removeClass("icon-trash").addClass("icon-spinner icon-spin");
|
||||
icon.removeClass("fa-trash-o").addClass("fa-spinner fa-spin");
|
||||
};
|
||||
finishSpinner = function() {
|
||||
icon.removeClass("icon-spinner icon-spin").addClass("icon-trash");
|
||||
icon.removeClass("fa-spinner fa-spin").addClass("fa-trash-o");
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -550,9 +565,13 @@ $(function() {
|
||||
};
|
||||
|
||||
self.enableSelect = function(data) {
|
||||
var isLoadActionPossible = self.isLoadActionPossible();
|
||||
return isLoadActionPossible && !self.listHelper.isSelected(data);
|
||||
return self.isLoadAndPrintActionPossible() && !self.listHelper.isSelected(data);
|
||||
}
|
||||
|
||||
self.enablePrint = function(data) {
|
||||
return self.loginState.hasPermission(self.access.permissions.PRINT)() && self.isOperational() && !(self.isPrinting() || self.isPaused() || self.isLoading());
|
||||
};
|
||||
|
||||
self.enableSelectAndPrint = function(data, printAfterSelect) {
|
||||
var isLoadAndPrintActionPossible = self.isLoadAndPrintActionPossible();
|
||||
return isLoadAndPrintActionPossible && !self.listHelper.isSelected(data);
|
||||
@@ -829,15 +848,26 @@ $(function() {
|
||||
}
|
||||
self.sdTarget = $("#drop_sd");
|
||||
|
||||
self.dropOverlay = $("#drop_overlay");
|
||||
self.dropZone = $("#drop");
|
||||
self.dropZoneLocal = $("#drop_locally");
|
||||
self.dropZoneSd = $("#drop_sd");
|
||||
self.dropZoneBackground = $("#drop_background");
|
||||
self.dropZoneLocalBackground = $("#drop_locally_background");
|
||||
self.dropZoneSdBackground = $("#drop_sd_background");
|
||||
|
||||
self.dropOverlay.on('drop', self._forceEndDragNDrop);
|
||||
|
||||
function evaluateDropzones() {
|
||||
var enableLocal = self.loginState.hasPermission(self.access.permissions.UPLOAD)();
|
||||
var enableSd = enableLocal && CONFIG_SD_SUPPORT && self.printerState.isSdReady();
|
||||
var enableSd = enableLocal && CONFIG_SD_SUPPORT && self.printerState.isSdReady() && !self.isPrinting();
|
||||
|
||||
self._setDropzone("local", enableLocal);
|
||||
self._setDropzone("sdcard", enableSd);
|
||||
}
|
||||
self.loginState.currentUser.subscribe(evaluateDropzones);
|
||||
self.printerState.isSdReady.subscribe(evaluateDropzones);
|
||||
self.isPrinting.subscribe(evaluateDropzones);
|
||||
evaluateDropzones();
|
||||
|
||||
self.requestData();
|
||||
@@ -980,10 +1010,12 @@ $(function() {
|
||||
|
||||
self._enableDragNDrop = function(enable) {
|
||||
if (enable) {
|
||||
$(document).bind("dragover", self._handleDragNDrop);
|
||||
$(document).bind("dragenter", self._handleDragNDrop);
|
||||
$(document).bind("dragleave", self._endDragNDrop);
|
||||
log.debug("Enabled drag-n-drop");
|
||||
} else {
|
||||
$(document).unbind("dragover", self._handleDragNDrop);
|
||||
$(document).unbind("dragenter", self._handleDragNDrop);
|
||||
$(document).unbind("dragleave", self._endDragNDrop);
|
||||
log.debug("Disabled drag-n-drop");
|
||||
}
|
||||
};
|
||||
@@ -1056,34 +1088,35 @@ $(function() {
|
||||
self._setProgressBar(progress, uploaded ? gettext("Saving ...") : gettext("Uploading ..."), uploaded);
|
||||
};
|
||||
|
||||
self._handleDragNDrop = 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;
|
||||
self._dragNDropTarget = null;
|
||||
self._forceEndDragNDrop = function () {
|
||||
self.dropOverlay.removeClass("in");
|
||||
if (self.dropZoneLocal) self.dropZoneLocalBackground.removeClass("hover");
|
||||
if (self.dropZoneSd) self.dropZoneSdBackground.removeClass("hover");
|
||||
if (self.dropZone) self.dropZoneBackground.removeClass("hover");
|
||||
self._dragNDropTarget = null;
|
||||
};
|
||||
|
||||
if (!timeout) {
|
||||
dropOverlay.addClass('in');
|
||||
} else {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
self._endDragNDrop = function (e) {
|
||||
if (e.target != self._dragNDropTarget) return;
|
||||
self._forceEndDragNDrop();
|
||||
};
|
||||
|
||||
self._handleDragNDrop = function (e) {
|
||||
self.dropOverlay.addClass('in');
|
||||
|
||||
var foundLocal = false;
|
||||
var foundSd = false;
|
||||
var found = false;
|
||||
var node = e.target;
|
||||
do {
|
||||
if (dropZoneLocal && node === dropZoneLocal[0]) {
|
||||
if (self.dropZoneLocal && node === self.dropZoneLocal[0]) {
|
||||
foundLocal = true;
|
||||
break;
|
||||
} else if (dropZoneSd && node === dropZoneSd[0]) {
|
||||
} else if (self.dropZoneSd && node === self.dropZoneSd[0]) {
|
||||
foundSd = true;
|
||||
break;
|
||||
} else if (dropZone && node === dropZone[0]) {
|
||||
} else if (self.dropZone && node === self.dropZone[0]) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
@@ -1091,26 +1124,19 @@ $(function() {
|
||||
} while (node != null);
|
||||
|
||||
if (foundLocal) {
|
||||
dropZoneLocalBackground.addClass("hover");
|
||||
dropZoneSdBackground.removeClass("hover");
|
||||
} else if (foundSd && self.printerState.isSdReady()) {
|
||||
dropZoneSdBackground.addClass("hover");
|
||||
dropZoneLocalBackground.removeClass("hover");
|
||||
self.dropZoneLocalBackground.addClass("hover");
|
||||
self.dropZoneSdBackground.removeClass("hover");
|
||||
} else if (foundSd && self.printerState.isSdReady() && !self.isPrinting()) {
|
||||
self.dropZoneSdBackground.addClass("hover");
|
||||
self.dropZoneLocalBackground.removeClass("hover");
|
||||
} else if (found) {
|
||||
dropZoneBackground.addClass("hover");
|
||||
self.dropZoneBackground.addClass("hover");
|
||||
} else {
|
||||
if (dropZoneLocalBackground) dropZoneLocalBackground.removeClass("hover");
|
||||
if (dropZoneSdBackground) dropZoneSdBackground.removeClass("hover");
|
||||
if (dropZoneBackground) dropZoneBackground.removeClass("hover");
|
||||
if (self.dropZoneLocalBackground) self.dropZoneLocalBackground.removeClass("hover");
|
||||
if (self.dropZoneSdBackground) self.dropZoneSdBackground.removeClass("hover");
|
||||
if (self.dropZoneBackground) self.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._dragNDropTarget = e.target;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -47,6 +47,8 @@ $(function() {
|
||||
self.renderer_zoomOnModel = ko.observable(false);
|
||||
self.renderer_showMoves = ko.observable(true);
|
||||
self.renderer_showRetracts = ko.observable(true);
|
||||
self.renderer_showBoundingBox = ko.observable(false);
|
||||
self.renderer_showFullSize = ko.observable(false);
|
||||
self.renderer_extrusionWidthEnabled = ko.observable(false);
|
||||
self.renderer_extrusionWidth = ko.observable(2);
|
||||
self.renderer_showNext = ko.observable(false);
|
||||
@@ -66,6 +68,8 @@ $(function() {
|
||||
centerViewport: self.renderer_centerViewport(),
|
||||
showMoves: self.renderer_showMoves(),
|
||||
showRetracts: self.renderer_showRetracts(),
|
||||
showBoundingBox: self.renderer_showBoundingBox(),
|
||||
showFullSize: self.renderer_showFullSize(),
|
||||
extrusionWidth: self.renderer_extrusionWidthEnabled() ? self.renderer_extrusionWidth() : 1,
|
||||
showNextLayer: self.renderer_showNext(),
|
||||
showPreviousLayer: self.renderer_showPrevious(),
|
||||
@@ -78,7 +82,8 @@ $(function() {
|
||||
|
||||
var reader = {
|
||||
sortLayers: self.reader_sortLayers(),
|
||||
purgeEmptyLayers: self.reader_hideEmptyLayers()
|
||||
purgeEmptyLayers: self.reader_hideEmptyLayers(),
|
||||
ignoreOutsideBed: true
|
||||
};
|
||||
if (additionalReaderOptions) {
|
||||
_.extend(reader, additionalReaderOptions);
|
||||
@@ -96,6 +101,8 @@ $(function() {
|
||||
self.renderer_zoomOnModel.subscribe(self.synchronizeOptions);
|
||||
self.renderer_showMoves.subscribe(self.synchronizeOptions);
|
||||
self.renderer_showRetracts.subscribe(self.synchronizeOptions);
|
||||
self.renderer_showBoundingBox.subscribe(self.synchronizeOptions);
|
||||
self.renderer_showFullSize.subscribe(self.synchronizeOptions);
|
||||
self.renderer_extrusionWidthEnabled.subscribe(self.synchronizeOptions);
|
||||
self.renderer_extrusionWidth.subscribe(self.synchronizeOptions);
|
||||
self.renderer_showNext.subscribe(self.synchronizeOptions);
|
||||
@@ -121,10 +128,13 @@ $(function() {
|
||||
}
|
||||
|
||||
var bedDimensions = self._retrieveBedDimensions(currentProfileData);
|
||||
if (toolOffsets) {
|
||||
if (bedDimensions) {
|
||||
GCODE.ui.updateOptions({
|
||||
renderer: {
|
||||
bed: bedDimensions
|
||||
},
|
||||
reader: {
|
||||
bed: bedDimensions
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -139,6 +149,14 @@ $(function() {
|
||||
}
|
||||
});
|
||||
|
||||
self.settings.feature_g90InfluencesExtruder.subscribe(function() {
|
||||
GCODE.ui.updateOptions({
|
||||
reader: {
|
||||
g90InfluencesExtruder: self.settings.feature_g90InfluencesExtruder()
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
self._retrieveBedDimensions = function(currentProfileData) {
|
||||
if (currentProfileData == undefined) {
|
||||
currentProfileData = self.settings.printerProfiles.currentProfileData();
|
||||
@@ -240,7 +258,7 @@ $(function() {
|
||||
self._configureLayerSlider(layerSliderElement);
|
||||
self._configureLayerCommandSlider(commandSliderElement);
|
||||
|
||||
self.settings.requestData()
|
||||
self.settings.firstRequest
|
||||
.done(function() {
|
||||
var initResult = GCODE.ui.init({
|
||||
container: "#gcode_canvas",
|
||||
@@ -329,6 +347,7 @@ $(function() {
|
||||
result: response
|
||||
}
|
||||
};
|
||||
GCODE.renderer.clear();
|
||||
GCODE.gCodeReader.loadFile(par);
|
||||
|
||||
if (self.layerSlider != undefined) {
|
||||
@@ -399,7 +418,7 @@ $(function() {
|
||||
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)) {
|
||||
if (data.job.file.size > CONFIG_GCODE_SIZE_THRESHOLD || (OctoPrint.coreui.browser.mobile && data.job.file.size > CONFIG_GCODE_MOBILE_SIZE_THRESHOLD)) {
|
||||
self.waitForApproval(true);
|
||||
self.loadedFilepath = undefined;
|
||||
self.loadedFileDate = undefined;
|
||||
|
||||
@@ -13,6 +13,7 @@ $(function() {
|
||||
self.isUser = ko.observable(false);
|
||||
|
||||
self.allViewModels = undefined;
|
||||
self.startupDeferred = $.Deferred();
|
||||
|
||||
self.currentUser = ko.observable(undefined);
|
||||
|
||||
@@ -37,28 +38,45 @@ $(function() {
|
||||
});
|
||||
|
||||
self.reloadUser = function() {
|
||||
if (self.currentUser() == undefined) {
|
||||
if (self.currentUser() === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
OctoPrint.access.users.get(self.currentUser().name)
|
||||
return OctoPrint.access.users.get(self.currentUser().name)
|
||||
.done(self.updateCurrentUserData);
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.browser.passiveLogin()
|
||||
return OctoPrint.browser.passiveLogin()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
self.fromResponse = function(response) {
|
||||
if (response && response.name) {
|
||||
self.loggedIn(true);
|
||||
self.updateCurrentUserData(response);
|
||||
callViewModels(self.allViewModels, "onUserLoggedIn", [response]);
|
||||
var process = function() {
|
||||
var currentLoggedIn = self.loggedIn();
|
||||
if (response && response.name) {
|
||||
self.loggedIn(true);
|
||||
self.updateCurrentUserData(response);
|
||||
if (!currentLoggedIn) {
|
||||
callViewModels(self.allViewModels, "onUserLoggedIn", [response]);
|
||||
log.info("User " + response.name + " logged in")
|
||||
}
|
||||
} else {
|
||||
self.loggedIn(false);
|
||||
self.resetCurrentUserData();
|
||||
if (currentLoggedIn) {
|
||||
callViewModels(self.allViewModels, "onUserLoggedOut");
|
||||
log.info("User logged out");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (self.startupDeferred !== undefined) {
|
||||
// Make sure we only fire our "onUserLogged(In|Out)" message after the application
|
||||
// has started up.
|
||||
self.startupDeferred.done(process);
|
||||
} else {
|
||||
self.loggedIn(false);
|
||||
self.resetCurrentUserData();
|
||||
callViewModels(self.allViewModels, "onUserLoggedOut");
|
||||
process();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -108,7 +126,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.logout = function() {
|
||||
OctoPrint.browser.logout()
|
||||
return OctoPrint.browser.logout()
|
||||
.done(function(response) {
|
||||
new PNotify({title: gettext("Logout successful"), text: gettext("You are now logged out"), type: "success"});
|
||||
self.fromResponse(response);
|
||||
@@ -129,11 +147,8 @@ $(function() {
|
||||
|
||||
self.onAllBound = function(allViewModels) {
|
||||
self.allViewModels = allViewModels;
|
||||
};
|
||||
|
||||
self.onStartupComplete = self.onServerConnect = self.onServerReconnect = function() {
|
||||
if (self.allViewModels == undefined) return;
|
||||
self.requestData();
|
||||
self.startupDeferred.resolve();
|
||||
self.startupDeferred = undefined;
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
|
||||
@@ -453,7 +453,7 @@ $(function() {
|
||||
};
|
||||
|
||||
self.requestData = function() {
|
||||
OctoPrint.printerprofiles.list()
|
||||
return OctoPrint.printerprofiles.list()
|
||||
.done(self.fromResponse);
|
||||
};
|
||||
|
||||
@@ -476,8 +476,16 @@ $(function() {
|
||||
});
|
||||
self.profiles.updateItems(items);
|
||||
self.defaultProfile(defaultProfile);
|
||||
self.currentProfile(currentProfile);
|
||||
self.currentProfileData(currentProfileData);
|
||||
|
||||
if (currentProfile && currentProfileData) {
|
||||
self.currentProfile(currentProfile);
|
||||
self.currentProfileData(currentProfileData);
|
||||
} else {
|
||||
// shouldn't normally happen, but just to not have anything else crash...
|
||||
log.warn("Current printer profile could not be detected, using default values");
|
||||
self.currentProfile("");
|
||||
self.currentProfileData(ko.mapping.fromJS(cleanProfile(), self.currentProfileData));
|
||||
}
|
||||
};
|
||||
|
||||
self.addProfile = function(callback) {
|
||||
@@ -504,7 +512,10 @@ $(function() {
|
||||
self.requestInProgress(true);
|
||||
OctoPrint.printerprofiles.delete(data.id, {url: data.resource})
|
||||
.done(function() {
|
||||
self.requestData();
|
||||
self.requestData()
|
||||
.always(function() {
|
||||
self.requestInProgress(false);
|
||||
});
|
||||
})
|
||||
.fail(function(xhr) {
|
||||
var text;
|
||||
@@ -514,8 +525,6 @@ $(function() {
|
||||
text = gettext("There was unexpected error while removing the printer profile, please consult the logs.");
|
||||
}
|
||||
new PNotify({title: gettext("Could not delete profile"), text: text, type: "error", hide: false});
|
||||
})
|
||||
.always(function() {
|
||||
self.requestInProgress(false);
|
||||
});
|
||||
};
|
||||
@@ -535,13 +544,14 @@ $(function() {
|
||||
if (callback !== undefined) {
|
||||
callback();
|
||||
}
|
||||
self.requestData();
|
||||
self.requestData()
|
||||
.always(function() {
|
||||
self.requestInProgress(false);
|
||||
});
|
||||
})
|
||||
.fail(function() {
|
||||
var text = gettext("There was unexpected error while updating the printer profile, please consult the logs.");
|
||||
new PNotify({title: gettext("Could not update profile"), text: text, type: "error", hide: false});
|
||||
})
|
||||
.always(function() {
|
||||
self.requestInProgress(false);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -7,6 +7,11 @@ $(function() {
|
||||
self.printerProfiles = parameters[2];
|
||||
self.about = parameters[3];
|
||||
|
||||
// use this promise to do certain things once the SettingsViewModel has processed
|
||||
// its first request
|
||||
var firstRequest = $.Deferred();
|
||||
self.firstRequest = firstRequest.promise();
|
||||
|
||||
self.allViewModels = [];
|
||||
|
||||
self.receiving = ko.observable(false);
|
||||
@@ -91,6 +96,8 @@ $(function() {
|
||||
}
|
||||
};
|
||||
|
||||
self.webcam_available_ratios = ["16:9", "4:3"];
|
||||
|
||||
var auto_locale = {language: "_default", display: gettext("Autodetect from browser"), english: undefined};
|
||||
self.locales = ko.observableArray([auto_locale].concat(_.sortBy(_.values(AVAILABLE_LOCALES), function(n) {
|
||||
return n.display;
|
||||
@@ -110,6 +117,8 @@ $(function() {
|
||||
self.printer_defaultExtrusionLength = ko.observable(undefined);
|
||||
|
||||
self.webcam_streamUrl = ko.observable(undefined);
|
||||
self.webcam_streamRatio = ko.observable(undefined);
|
||||
self.webcam_streamTimeout = ko.observable(undefined);
|
||||
self.webcam_snapshotUrl = ko.observable(undefined);
|
||||
self.webcam_ffmpegPath = ko.observable(undefined);
|
||||
self.webcam_bitrate = ko.observable(undefined);
|
||||
@@ -140,6 +149,7 @@ $(function() {
|
||||
self.feature_firmwareDetection = ko.observable(undefined);
|
||||
self.feature_printCancelConfirmation = ko.observable(undefined);
|
||||
self.feature_blockWhileDwelling = ko.observable(undefined);
|
||||
self.feature_g90InfluencesExtruder = ko.observable(undefined);
|
||||
|
||||
self.serial_port = ko.observable();
|
||||
self.serial_baudrate = ko.observable();
|
||||
@@ -151,6 +161,7 @@ $(function() {
|
||||
self.serial_timeoutCommunication = ko.observable(undefined);
|
||||
self.serial_timeoutTemperature = ko.observable(undefined);
|
||||
self.serial_timeoutTemperatureTargetSet = ko.observable(undefined);
|
||||
self.serial_timeoutTemperatureAutoreport = ko.observable(undefined);
|
||||
self.serial_timeoutSdStatus = ko.observable(undefined);
|
||||
self.serial_log = ko.observable(undefined);
|
||||
self.serial_additionalPorts = ko.observable(undefined);
|
||||
@@ -179,9 +190,13 @@ $(function() {
|
||||
self.scripts_gcode_beforePrintResumed = ko.observable(undefined);
|
||||
self.scripts_gcode_afterPrinterConnected = ko.observable(undefined);
|
||||
self.scripts_gcode_beforePrinterDisconnected = ko.observable(undefined);
|
||||
self.scripts_gcode_afterToolChange = ko.observable(undefined);
|
||||
self.scripts_gcode_beforeToolChange = ko.observable(undefined);
|
||||
|
||||
self.temperature_profiles = ko.observableArray(undefined);
|
||||
self.temperature_cutoff = ko.observable(undefined);
|
||||
self.temperature_sendAutomatically = ko.observable(undefined);
|
||||
self.temperature_sendAutomaticallyAfter = ko.observable(undefined);
|
||||
|
||||
self.system_actions = ko.observableArray([]);
|
||||
|
||||
@@ -224,37 +239,48 @@ $(function() {
|
||||
self.terminalFilters.remove(filter);
|
||||
};
|
||||
|
||||
self.testWebcamStreamUrlBusy = ko.observable(false);
|
||||
self.testWebcamStreamUrl = function() {
|
||||
if (!self.webcam_streamUrl()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.testWebcamStreamUrlBusy()) {
|
||||
return;
|
||||
}
|
||||
|
||||
var text = gettext("If you see your webcam stream below, the entered stream URL is ok.");
|
||||
var image = $('<img src="' + self.webcam_streamUrl() + '">');
|
||||
var message = $("<p></p>")
|
||||
.append(text)
|
||||
.append(image);
|
||||
|
||||
self.testWebcamStreamUrlBusy(true);
|
||||
showMessageDialog({
|
||||
title: gettext("Stream test"),
|
||||
message: message
|
||||
message: message,
|
||||
onclose: function() {
|
||||
self.testWebcamStreamUrlBusy(false);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.testWebcamSnapshotUrlBusy = ko.observable(false);
|
||||
self.testWebcamSnapshotUrl = function(viewModel, event) {
|
||||
if (!self.webcam_snapshotUrl()) {
|
||||
return;
|
||||
}
|
||||
|
||||
var target = $(event.target);
|
||||
target.prepend('<i class="icon-spinner icon-spin"></i> ');
|
||||
if (self.testWebcamSnapshotUrlBusy()) {
|
||||
return;
|
||||
}
|
||||
|
||||
var errorText = gettext("Could not retrieve snapshot URL, please double check the URL");
|
||||
var errorTitle = gettext("Snapshot test failed");
|
||||
|
||||
self.testWebcamSnapshotUrlBusy(true);
|
||||
OctoPrint.util.testUrl(self.webcam_snapshotUrl(), {method: "GET", response: "bytes"})
|
||||
.done(function(response) {
|
||||
$("i.icon-spinner", target).remove();
|
||||
|
||||
if (!response.result) {
|
||||
showMessageDialog({
|
||||
title: errorTitle,
|
||||
@@ -274,23 +300,34 @@ $(function() {
|
||||
var text = gettext("If you see your webcam snapshot picture below, the entered snapshot URL is ok.");
|
||||
showMessageDialog({
|
||||
title: gettext("Snapshot test"),
|
||||
message: $('<p>' + text + '</p><p><img src="data:' + mimeType + ';base64,' + content + '" /></p>')
|
||||
message: $('<p>' + text + '</p><p><img src="data:' + mimeType + ';base64,' + content + '" /></p>'),
|
||||
onclose: function() {
|
||||
self.testWebcamSnapshotUrlBusy(false);
|
||||
}
|
||||
});
|
||||
})
|
||||
.fail(function() {
|
||||
$("i.icon-spinner", target).remove();
|
||||
showMessageDialog({
|
||||
title: errorTitle,
|
||||
message: errorText
|
||||
message: errorText,
|
||||
onclose: function() {
|
||||
self.testWebcamSnapshotUrlBusy(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
self.testWebcamFfmpegPathBusy = ko.observable(false);
|
||||
self.testWebcamFfmpegPath = function() {
|
||||
if (!self.webcam_ffmpegPath()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.testWebcamFfmpegPathBusy()) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.testWebcamFfmpegPathBusy(true);
|
||||
OctoPrint.util.testExecutable(self.webcam_ffmpegPath())
|
||||
.done(function(response) {
|
||||
if (!response.result) {
|
||||
@@ -306,6 +343,9 @@ $(function() {
|
||||
}
|
||||
self.webcam_ffmpegPathOk(response.result);
|
||||
self.webcam_ffmpegPathBroken(!response.result);
|
||||
})
|
||||
.always(function() {
|
||||
self.testWebcamFfmpegPathBusy(false);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -730,6 +770,8 @@ $(function() {
|
||||
};
|
||||
|
||||
mapToObservables(serverChangedData, specialMappings, clientChangedData);
|
||||
|
||||
firstRequest.resolve();
|
||||
};
|
||||
|
||||
self.saveData = function (data, successCallback, setAsSending) {
|
||||
@@ -844,12 +886,14 @@ $(function() {
|
||||
};
|
||||
|
||||
self.onUserLoggedIn = function() {
|
||||
// we might have other user rights now, refresh
|
||||
// we might have other user rights now, refresh (but only if startup has fully completed)
|
||||
if (!self._startupComplete) return;
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.onUserLoggedOut = function() {
|
||||
// we might have other user rights now, refresh
|
||||
// we might have other user rights now, refresh (but only if startup has fully completed)
|
||||
if (!self._startupComplete) return;
|
||||
self.requestData();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ $(function() {
|
||||
self.access = parameters[2];
|
||||
|
||||
self._createToolEntry = function() {
|
||||
return {
|
||||
var entry = {
|
||||
name: ko.observable(),
|
||||
key: ko.observable(),
|
||||
actual: ko.observable(0),
|
||||
@@ -15,14 +15,66 @@ $(function() {
|
||||
offset: ko.observable(0),
|
||||
newTarget: ko.observable(),
|
||||
newOffset: ko.observable()
|
||||
}
|
||||
};
|
||||
|
||||
entry.newTargetValid = ko.pureComputed(function() {
|
||||
var value = entry.newTarget();
|
||||
|
||||
try {
|
||||
value = parseInt(value);
|
||||
} catch (exc) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (value >= 0 && value <= 999);
|
||||
});
|
||||
|
||||
entry.newOffsetValid = ko.pureComputed(function() {
|
||||
var value = entry.newOffset();
|
||||
|
||||
try {
|
||||
value = parseInt(value);
|
||||
} catch (exc) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (-50 <= value <= 50);
|
||||
});
|
||||
|
||||
entry.offset.subscribe(function(newValue) {
|
||||
if (self.changingOffset.item !== undefined && self.changingOffset.item.key() == entry.key()) {
|
||||
// if our we currently have the offset dialog open for this entry and the offset changed
|
||||
// meanwhile, update the displayed value in the dialog
|
||||
self.changingOffset.offset(newValue);
|
||||
}
|
||||
});
|
||||
|
||||
return entry;
|
||||
};
|
||||
|
||||
self.changingOffset = {
|
||||
offset: ko.observable(0),
|
||||
newOffset: ko.observable(0),
|
||||
name: ko.observable(""),
|
||||
item: undefined,
|
||||
|
||||
title: ko.pureComputed(function() {
|
||||
return _.sprintf(gettext("Changing Offset of %(name)s"), {name: self.changingOffset.name()});
|
||||
}),
|
||||
description: ko.pureComputed(function() {
|
||||
return _.sprintf(gettext("Use the form below to specify a new offset to apply to all temperature commands sent from printed files for \"%(name)s\""),
|
||||
{name: self.changingOffset.name()});
|
||||
})
|
||||
};
|
||||
self.changeOffsetDialog = undefined;
|
||||
|
||||
// TODO: find some nicer way to update plot AFTER graph becomes visible
|
||||
self.loginStateSubscription = undefined;
|
||||
|
||||
self.tools = ko.observableArray([]);
|
||||
|
||||
self.hasBed = ko.observable(true);
|
||||
|
||||
self.bedTemp = self._createToolEntry();
|
||||
self.bedTemp["name"](gettext("Bed"));
|
||||
self.bedTemp["key"]("bed");
|
||||
@@ -94,7 +146,7 @@ $(function() {
|
||||
if (!self._printerProfileInitialized) {
|
||||
self._triggerBacklog();
|
||||
}
|
||||
self.updatePlot();
|
||||
self.updatePlot(false);
|
||||
};
|
||||
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
|
||||
self._printerProfileUpdated();
|
||||
@@ -124,39 +176,10 @@ $(function() {
|
||||
});
|
||||
|
||||
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.plot = undefined;
|
||||
self.plotHoverPos = undefined;
|
||||
self.plotLegendTimeout = undefined;
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
@@ -222,12 +245,12 @@ $(function() {
|
||||
if (!CONFIG_TEMPERATURE_GRAPH) return;
|
||||
|
||||
self.temperatures = self._processTemperatureData(serverTime, data, self.temperatures);
|
||||
self.updatePlot();
|
||||
self.updatePlot(false);
|
||||
};
|
||||
|
||||
self._processTemperatureHistoryData = function(serverTime, data) {
|
||||
self.temperatures = self._processTemperatureData(serverTime, data);
|
||||
self.updatePlot();
|
||||
self.updatePlot(false);
|
||||
};
|
||||
|
||||
self._processOffsetData = function(data) {
|
||||
@@ -286,7 +309,9 @@ $(function() {
|
||||
return result;
|
||||
};
|
||||
|
||||
self.updatePlot = function() {
|
||||
self.updatePlot = function(force) {
|
||||
force = force == undefined ? true : force;
|
||||
|
||||
var graph = $("#temperature-graph");
|
||||
if (graph.length) {
|
||||
var data = [];
|
||||
@@ -295,6 +320,8 @@ $(function() {
|
||||
|
||||
var maxTemps = [310/1.1];
|
||||
|
||||
var showFahrenheit = self._shallShowFahrenheit();
|
||||
|
||||
_.each(_.keys(heaterOptions), function(type) {
|
||||
if (type == "bed" && !self.hasBed()) {
|
||||
return;
|
||||
@@ -308,9 +335,6 @@ $(function() {
|
||||
targets = self.temperatures[type].target;
|
||||
}
|
||||
|
||||
var showFahrenheit = (self.settingsViewModel.settings !== undefined )
|
||||
? self.settingsViewModel.settings.appearance.showFahrenheitAlso()
|
||||
: false;
|
||||
var actualTemp = actuals && actuals.length ? formatTemperature(actuals[actuals.length - 1][1], showFahrenheit) : "-";
|
||||
var targetTemp = targets && targets.length ? formatTemperature(targets[targets.length - 1][1], showFahrenheit) : "-";
|
||||
|
||||
@@ -328,11 +352,115 @@ $(function() {
|
||||
maxTemps.push(self.getMaxTemp(actuals, targets));
|
||||
});
|
||||
|
||||
self.plotOptions.yaxis.max = Math.max.apply(null, maxTemps) * 1.1;
|
||||
$.plot(graph, data, self.plotOptions);
|
||||
if (!self.plot || force) {
|
||||
// we don't have a plot yet, we need to set stuff up
|
||||
var options = {
|
||||
yaxis: {
|
||||
min: 0,
|
||||
max: Math.max(Math.max.apply(null, maxTemps) * 1.1, 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
|
||||
}
|
||||
};
|
||||
|
||||
if (!OctoPrint.coreui.browser.mobile) {
|
||||
options["crosshair"] = { mode: "x" };
|
||||
options["grid"] = { hoverable: true, autoHighlight: false };
|
||||
}
|
||||
|
||||
self.plot = $.plot(graph, data, options);
|
||||
|
||||
} else {
|
||||
// graph already active, let's just update the data
|
||||
self.plot.setData(data);
|
||||
self.plot.getAxes().yaxis.max = Math.max(Math.max.apply(null, maxTemps) * 1.1, 310);
|
||||
self.updateLegend(self._replaceLegendLabel);
|
||||
self.plot.draw();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.updateLegend = function(replaceLegendLabel) {
|
||||
self.plotLegendTimeout = undefined;
|
||||
|
||||
var resetLegend = function() {
|
||||
_.each(dataset, function(series, index) {
|
||||
var value = series.data && series.data.length ? series.data[series.data.length - 1][1] : undefined;
|
||||
replaceLegendLabel(index, series, value);
|
||||
});
|
||||
};
|
||||
|
||||
var pos = self.plotHoverPos;
|
||||
if (pos && !OctoPrint.coreui.browser.mobile) {
|
||||
// we got a hover position, let's see what we need to do with that
|
||||
|
||||
var i;
|
||||
var axes = self.plot.getAxes();
|
||||
var dataset = self.plot.getData();
|
||||
|
||||
if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max ||
|
||||
pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) {
|
||||
// position outside of the graph, show latest temperature in legend
|
||||
resetLegend();
|
||||
} else {
|
||||
// position inside the graph, determine temperature at point and display that in the legend
|
||||
_.each(dataset, function(series, index) {
|
||||
for (i = 0; i < series.data.length; i++) {
|
||||
if (series.data[i][0] > pos.x) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var y;
|
||||
var p1 = series.data[i - 1];
|
||||
var p2 = series.data[i];
|
||||
|
||||
if (p1 === undefined && p2 === undefined) {
|
||||
y = undefined;
|
||||
} else if (p1 === undefined) {
|
||||
y = p2[1];
|
||||
} else if (p2 === undefined) {
|
||||
y = p1[1];
|
||||
} else {
|
||||
y = p1[1] + (p2[1] - p1[1]) * (pos.x - p1[0]) / (p2[0] - p1[0]);
|
||||
}
|
||||
|
||||
replaceLegendLabel(index, series, y, true);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
resetLegend();
|
||||
}
|
||||
|
||||
// update the grid
|
||||
self.plot.setupGrid();
|
||||
};
|
||||
|
||||
self.getMaxTemp = function(actuals, targets) {
|
||||
var pair;
|
||||
var maxTemp = 0;
|
||||
@@ -349,66 +477,191 @@ $(function() {
|
||||
return maxTemp;
|
||||
};
|
||||
|
||||
self.setTarget = function(item) {
|
||||
self.incrementTarget = function(item) {
|
||||
var value = item.newTarget();
|
||||
if (!value) return;
|
||||
|
||||
var onSuccess = function() {
|
||||
item.newTarget("");
|
||||
};
|
||||
|
||||
if (item.key() == "bed") {
|
||||
self._setBedTemperature(value)
|
||||
.done(onSuccess);
|
||||
} else {
|
||||
self._setToolTemperature(item.key(), value)
|
||||
.done(onSuccess);
|
||||
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) {
|
||||
value = item.target();
|
||||
}
|
||||
try {
|
||||
value = parseInt(value);
|
||||
if (value > 999) return;
|
||||
item.newTarget(value + 1);
|
||||
self.autosendTarget(item);
|
||||
} catch (ex) {
|
||||
// do nothing
|
||||
}
|
||||
};
|
||||
|
||||
self.decrementTarget = function(item) {
|
||||
var value = item.newTarget();
|
||||
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) {
|
||||
value = item.target();
|
||||
}
|
||||
try {
|
||||
value = parseInt(value);
|
||||
if (value <= 0) return;
|
||||
item.newTarget(value - 1);
|
||||
self.autosendTarget(item);
|
||||
} catch (ex) {
|
||||
// do nothing
|
||||
}
|
||||
};
|
||||
|
||||
var _sendTimeout = {};
|
||||
|
||||
self.autosendTarget = function(item) {
|
||||
if (!self.settingsViewModel.temperature_sendAutomatically()) return;
|
||||
var delay = self.settingsViewModel.temperature_sendAutomaticallyAfter() * 1000;
|
||||
|
||||
var name = item.name();
|
||||
if (_sendTimeout[name]) {
|
||||
window.clearTimeout(_sendTimeout[name]);
|
||||
}
|
||||
_sendTimeout[name] = window.setTimeout(function() {
|
||||
self.setTarget(item);
|
||||
delete _sendTimeout[name];
|
||||
}, delay);
|
||||
};
|
||||
|
||||
self.clearAutosendTarget = function(item) {
|
||||
var name = item.name();
|
||||
if (_sendTimeout[name]) {
|
||||
window.clearTimeout(_sendTimeout[name]);
|
||||
delete _sendTimeout[name];
|
||||
}
|
||||
};
|
||||
|
||||
self.setTarget = function(item, form) {
|
||||
var value = item.newTarget();
|
||||
if (form !== undefined) {
|
||||
$(form).find("input").blur();
|
||||
}
|
||||
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) return OctoPrintClient.createRejectedDeferred();
|
||||
|
||||
self.clearAutosendTarget(item);
|
||||
return self.setTargetToValue(item, value);
|
||||
};
|
||||
|
||||
self.setTargetFromProfile = function(item, profile) {
|
||||
if (!profile) return;
|
||||
if (!profile) return OctoPrintClient.createRejectedDeferred();
|
||||
|
||||
self.clearAutosendTarget(item);
|
||||
return self.setTargetToValue(item, (item.key() == "bed" ? profile.bed : profile.extruder));
|
||||
};
|
||||
|
||||
self.setTargetToZero = function(item) {
|
||||
self.clearAutosendTarget(item);
|
||||
return self.setTargetToValue(item, 0);
|
||||
};
|
||||
|
||||
self.setTargetToValue = function(item, value) {
|
||||
self.clearAutosendTarget(item);
|
||||
|
||||
try {
|
||||
value = parseInt(value);
|
||||
} catch (ex) {
|
||||
return OctoPrintClient.createRejectedDeferred();
|
||||
}
|
||||
|
||||
if (value < 0 || value > 999) return OctoPrintClient.createRejectedDeferred();
|
||||
|
||||
var onSuccess = function() {
|
||||
item.target(value);
|
||||
item.newTarget("");
|
||||
};
|
||||
|
||||
if (item.key() == "bed") {
|
||||
self._setBedTemperature(profile.bed)
|
||||
return self._setBedTemperature(value)
|
||||
.done(onSuccess);
|
||||
} else {
|
||||
self._setToolTemperature(item.key(), profile.extruder)
|
||||
return self._setToolTemperature(item.key(), value)
|
||||
.done(onSuccess);
|
||||
}
|
||||
};
|
||||
|
||||
self.setTargetToZero = function(item) {
|
||||
var onSuccess = function() {
|
||||
item.newTarget("");
|
||||
};
|
||||
self.changeOffset = function(item) {
|
||||
// copy values
|
||||
self.changingOffset.item = item;
|
||||
self.changingOffset.name(item.name());
|
||||
self.changingOffset.offset(item.offset());
|
||||
self.changingOffset.newOffset(item.offset());
|
||||
|
||||
if (item.key() == "bed") {
|
||||
self._setBedTemperature(0)
|
||||
.done(onSuccess);
|
||||
} else {
|
||||
self._setToolTemperature(item.key(), 0)
|
||||
.done(onSuccess);
|
||||
self.changeOffsetDialog.modal("show");
|
||||
};
|
||||
|
||||
self.incrementChangeOffset = function() {
|
||||
var value = self.changingOffset.newOffset();
|
||||
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) value = self.changingOffset.offset();
|
||||
try {
|
||||
value = parseInt(value);
|
||||
if (value >= 50) return;
|
||||
self.changingOffset.newOffset(value + 1);
|
||||
} catch (ex) {
|
||||
// do nothing
|
||||
}
|
||||
};
|
||||
|
||||
self.decrementChangeOffset = function() {
|
||||
var value = self.changingOffset.newOffset();
|
||||
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) value = self.changingOffset.offset();
|
||||
try {
|
||||
value = parseInt(value);
|
||||
if (value <= -50) return;
|
||||
self.changingOffset.newOffset(value - 1);
|
||||
} catch (ex) {
|
||||
// do nothing
|
||||
}
|
||||
};
|
||||
|
||||
self.deleteChangeOffset = function() {
|
||||
self.changingOffset.newOffset(0);
|
||||
};
|
||||
|
||||
self.confirmChangeOffset = function() {
|
||||
var item = self.changingOffset.item;
|
||||
item.newOffset(self.changingOffset.newOffset());
|
||||
|
||||
self.setOffset(item)
|
||||
.done(function() {
|
||||
self.changeOffsetDialog.modal("hide");
|
||||
|
||||
// reset
|
||||
self.changingOffset.offset(0);
|
||||
self.changingOffset.newOffset(0);
|
||||
self.changingOffset.name("");
|
||||
self.changingOffset.item = undefined;
|
||||
})
|
||||
};
|
||||
|
||||
self.setOffset = function(item) {
|
||||
var value = item.newOffset();
|
||||
if (!value) return;
|
||||
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) return OctoPrintClient.createRejectedDeferred();
|
||||
return self.setOffsetToValue(item, value);
|
||||
};
|
||||
|
||||
self.setOffsetToZero = function(item) {
|
||||
return self.setOffsetToValue(item, 0);
|
||||
};
|
||||
|
||||
self.setOffsetToValue = function(item, value) {
|
||||
try {
|
||||
value = parseInt(value);
|
||||
} catch (ex) {
|
||||
return OctoPrintClient.createRejectedDeferred();
|
||||
}
|
||||
|
||||
if (value < -50 || value > 50) return OctoPrintClient.createRejectedDeferred();
|
||||
|
||||
var onSuccess = function() {
|
||||
item.offset(value);
|
||||
item.newOffset("");
|
||||
};
|
||||
|
||||
if (item.key() == "bed") {
|
||||
self._setBedOffset(value)
|
||||
return self._setBedOffset(value)
|
||||
.done(onSuccess);
|
||||
} else {
|
||||
self._setToolOffset(item.key(), value)
|
||||
return self._setToolOffset(item.key(), value)
|
||||
.done(onSuccess);
|
||||
}
|
||||
};
|
||||
@@ -433,21 +686,70 @@ $(function() {
|
||||
return OctoPrint.printer.setBedTemperatureOffset(parseInt(offset));
|
||||
};
|
||||
|
||||
self._replaceLegendLabel = function(index, series, value, emph) {
|
||||
var showFahrenheit = self._shallShowFahrenheit();
|
||||
|
||||
var temp = formatTemperature(value, showFahrenheit);
|
||||
if (emph) {
|
||||
temp = "<em>" + temp + "</em>";
|
||||
}
|
||||
series.label = series.label.replace(/:.*/, ": " + temp);
|
||||
};
|
||||
|
||||
self._shallShowFahrenheit = function() {
|
||||
return (self.settingsViewModel.settings !== undefined )
|
||||
? self.settingsViewModel.settings.appearance.showFahrenheitAlso()
|
||||
: false;
|
||||
};
|
||||
|
||||
self.handleEnter = function(event, type, item) {
|
||||
if (event.keyCode == 13) {
|
||||
if (type == "target") {
|
||||
self.setTarget(item);
|
||||
self.setTarget(item)
|
||||
.done(function() {
|
||||
event.target.blur();
|
||||
});
|
||||
} else if (type == "offset") {
|
||||
self.setOffset(item);
|
||||
self.confirmChangeOffset();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
self.handleFocus = function(event, type, item) {
|
||||
if (type == "target") {
|
||||
var value = item.newTarget();
|
||||
if (value === undefined || (typeof(value) == "string" && value.trim() == "")) {
|
||||
item.newTarget(item.target());
|
||||
}
|
||||
event.target.select();
|
||||
} else if (type == "offset") {
|
||||
event.target.select();
|
||||
}
|
||||
};
|
||||
|
||||
self.onAfterTabChange = function(current, previous) {
|
||||
if (current != "#temp") {
|
||||
return;
|
||||
}
|
||||
self.updatePlot();
|
||||
self.updatePlot(false);
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
var graph = $("#temperature-graph");
|
||||
if (graph.length && !OctoPrint.coreui.browser.mobile) {
|
||||
graph.bind("plothover", function (event, pos, item) {
|
||||
self.plotHoverPos = pos;
|
||||
if (!self.plotLegendTimeout) {
|
||||
self.plotLegendTimeout = window.setTimeout(function() {
|
||||
self.updateLegend(self._replaceLegendLabel)
|
||||
}, 50);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
self.onStartup = function() {
|
||||
self.changeOffsetDialog = $("#change_offset_dialog");
|
||||
};
|
||||
|
||||
self.onStartupComplete = function() {
|
||||
@@ -459,6 +761,6 @@ $(function() {
|
||||
OCTOPRINT_VIEWMODELS.push([
|
||||
TemperatureViewModel,
|
||||
["loginStateViewModel", "settingsViewModel", "accessViewModel"],
|
||||
["#temp", "#temp_link"]
|
||||
["#temp", "#change_offset_dialog"]
|
||||
]);
|
||||
});
|
||||
@@ -36,8 +36,10 @@ $(function() {
|
||||
|
||||
self.enableFancyFunctionality = ko.observable(true);
|
||||
self.disableTerminalLogDuringPrinting = ko.observable(false);
|
||||
self.acceptableTime = 500;
|
||||
|
||||
self.acceptableFancyTime = 500;
|
||||
self.acceptableUnfancyTime = 300;
|
||||
self.reenableTimeout = 5000;
|
||||
|
||||
self.forceFancyFunctionality = ko.observable(false);
|
||||
self.forceTerminalLogDuringPrinting = ko.observable(false);
|
||||
@@ -123,23 +125,63 @@ $(function() {
|
||||
self.updateFilterRegex();
|
||||
});
|
||||
|
||||
self._reenableFancyTimer = undefined;
|
||||
self._reenableUnfancyTimer = undefined;
|
||||
self._disableFancy = function(difference) {
|
||||
log.warn("Terminal: Detected slow client (needed " + difference + "ms for processing new log data), disabling fancy terminal functionality");
|
||||
if (self._reenableFancyTimer) {
|
||||
window.clearTimeout(self._reenableFancyTimer);
|
||||
self._reenableFancyTimer = undefined;
|
||||
}
|
||||
self.enableFancyFunctionality(false);
|
||||
};
|
||||
self._reenableFancy = function(difference) {
|
||||
if (self._reenableFancyTimer) return;
|
||||
self._reenableFancyTimer = window.setTimeout(function() {
|
||||
log.info("Terminal: Client speed recovered, enabling fancy terminal functionality");
|
||||
self.enableFancyFunctionality(true);
|
||||
}, self.reenableTimeout);
|
||||
};
|
||||
self._disableUnfancy = function(difference) {
|
||||
log.warn("Terminal: Detected very slow client (needed " + difference + "ms for processing new log data), completely disabling terminal output during printing");
|
||||
if (self._reenableUnfancyTimer) {
|
||||
window.clearTimeout(self._reenableUnfancyTimer);
|
||||
self._reenableUnfancyTimer = undefined;
|
||||
}
|
||||
self.disableTerminalLogDuringPrinting(true);
|
||||
};
|
||||
self._reenableUnfancy = function() {
|
||||
if (self._reenableUnfancyTimer) return;
|
||||
self._reenableUnfancyTimer = window.setTimeout(function() {
|
||||
log.info("Terminal: Client speed recovered, enabling terminal output during printing");
|
||||
self.disableTerminalLogDuringPrinting(false);
|
||||
}, self.reenableTimeout);
|
||||
};
|
||||
|
||||
self.fromCurrentData = function(data) {
|
||||
self._processStateData(data.state);
|
||||
|
||||
var start = new Date().getTime();
|
||||
self._processCurrentLogData(data.logs);
|
||||
var end = new Date().getTime();
|
||||
|
||||
var difference = end - start;
|
||||
|
||||
if (self.enableFancyFunctionality()) {
|
||||
if (difference > self.acceptableTime) {
|
||||
self.enableFancyFunctionality(false);
|
||||
log.warn("Terminal: Detected slow client (needed " + difference + "ms for processing new log data), disabling fancy terminal functionality");
|
||||
// fancy enabled -> check if we need to disable fancy
|
||||
if (difference >= self.acceptableFancyTime) {
|
||||
self._disableFancy(difference);
|
||||
}
|
||||
} else if (!self.disableTerminalLogDuringPrinting()) {
|
||||
// fancy disabled, unfancy not -> check if we need to disable unfancy or re-enable fancy
|
||||
if (difference >= self.acceptableUnfancyTime) {
|
||||
self._disableUnfancy(difference);
|
||||
} else if (difference < self.acceptableFancyTime / 2.0) {
|
||||
self._reenableFancy(difference);
|
||||
}
|
||||
} else {
|
||||
if (!self.disableTerminalLogDuringPrinting() && difference > self.acceptableUnfancyTime) {
|
||||
self.disableTerminalLogDuringPrinting(true);
|
||||
log.warn("Terminal: Detected very slow client (needed " + difference + "ms for processing new log data), completely disabling terminal output during printing");
|
||||
// fancy & unfancy disabled -> check if we need to re-enable unfancy
|
||||
if (difference < self.acceptableUnfancyTime / 2.0) {
|
||||
self._reenableUnfancy(difference);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -11,7 +11,7 @@ $(function() {
|
||||
self.defaultPostRoll = 0;
|
||||
self.defaultInterval = 10;
|
||||
self.defaultRetractionZHop = 0;
|
||||
self.defaultCapturePostroll = true;
|
||||
self.defaultCapturePostRoll = true;
|
||||
|
||||
self.timelapseType = ko.observable(undefined);
|
||||
self.timelapseTimedInterval = ko.observable(self.defaultInterval);
|
||||
@@ -52,10 +52,6 @@ $(function() {
|
||||
return self.loginState.hasPermission(self.access.permissions.TIMELAPSE_ADMIN)() && self.isDirty() && self.isOperational() && !self.isPrinting();
|
||||
});
|
||||
|
||||
self.isOperational.subscribe(function() {
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
self.timelapseType.subscribe(function() {
|
||||
self.isDirty(true);
|
||||
});
|
||||
@@ -163,18 +159,20 @@ $(function() {
|
||||
// timelapse config
|
||||
self.timelapseType(config.type);
|
||||
|
||||
if (config.type == "timed") {
|
||||
if (config.interval != undefined && config.interval > 0) {
|
||||
self.timelapseTimedInterval(config.interval);
|
||||
}
|
||||
if (config.type == "timed" && config.interval != undefined && config.interval > 0) {
|
||||
self.timelapseTimedInterval(config.interval);
|
||||
} else {
|
||||
self.timelapseTimedInterval(self.defaultInterval);
|
||||
}
|
||||
|
||||
if (config.type == "zchange") {
|
||||
if (config.retractionZHop != undefined && config.retractionZHop > 0) {
|
||||
self.timelapseRetractionZHop(config.retractionZHop);
|
||||
}
|
||||
if (config.type == "timed" && config.capturePostRoll != undefined){
|
||||
self.timelapseCapturePostRoll(config.capturePostRoll);
|
||||
} else {
|
||||
self.timelapseCapturePostRoll(self.defaultCapturePostRoll);
|
||||
}
|
||||
|
||||
if (config.type == "zchange" && config.retractionZHop != undefined && config.retractionZHop > 0) {
|
||||
self.timelapseRetractionZHop(config.retractionZHop);
|
||||
} else {
|
||||
self.timelapseRetractionZHop(self.defaultRetractionZHop);
|
||||
}
|
||||
@@ -191,12 +189,6 @@ $(function() {
|
||||
self.timelapseFps(self.defaultFps);
|
||||
}
|
||||
|
||||
if (config.capturePostRoll != undefined){
|
||||
self.timelapseCapturePostRoll(config.capturePostRoll);
|
||||
} else {
|
||||
self.timelapseCapturePostRoll(self.defaultCapturePostRoll);
|
||||
}
|
||||
|
||||
self.persist(false);
|
||||
self.isDirty(false);
|
||||
};
|
||||
@@ -240,6 +232,16 @@ $(function() {
|
||||
.done(function() {
|
||||
self.markedForFileDeletion.remove(filename);
|
||||
self.requestData()
|
||||
})
|
||||
.fail(function(jqXHR) {
|
||||
var html = "<p>" + _.sprintf(gettext("Failed to remove timelapse %(name)s.</p><p>Please consult octoprint.log for details.</p>"), {name: filename});
|
||||
html += pnotifyAdditionalInfo('<pre style="overflow: auto">' + jqXHR.responseText + '</pre>');
|
||||
new PNotify({
|
||||
title: gettext("Could not remove timelapse"),
|
||||
text: html,
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
@@ -308,7 +310,7 @@ $(function() {
|
||||
self._bulkRemove = function(files, type) {
|
||||
var title, message, handler;
|
||||
|
||||
if (type == "files") {
|
||||
if (type === "files") {
|
||||
title = gettext("Deleting timelapse files");
|
||||
message = _.sprintf(gettext("Deleting %(count)d timelapse files..."), {count: files.length});
|
||||
handler = function(filename) {
|
||||
@@ -316,11 +318,13 @@ $(function() {
|
||||
.done(function() {
|
||||
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
|
||||
})
|
||||
.fail(function() {
|
||||
deferred.notify(_.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename}), false);
|
||||
.fail(function(jqXHR) {
|
||||
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename});
|
||||
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText});
|
||||
deferred.notify(short, long, false);
|
||||
});
|
||||
}
|
||||
} else if (type == "unrendered") {
|
||||
} else if (type === "unrendered") {
|
||||
title = gettext("Deleting unrendered timelapses");
|
||||
message = _.sprintf(gettext("Deleting %(count)d unrendered timelapses..."), {count: files.length});
|
||||
handler = function(filename) {
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
/* Flot plugin for showing crosshairs when the mouse hovers over the plot.
|
||||
|
||||
Copyright (c) 2007-2014 IOLA and Ole Laursen.
|
||||
Licensed under the MIT license.
|
||||
|
||||
The plugin supports these options:
|
||||
|
||||
crosshair: {
|
||||
mode: null or "x" or "y" or "xy"
|
||||
color: color
|
||||
lineWidth: number
|
||||
}
|
||||
|
||||
Set the mode to one of "x", "y" or "xy". The "x" mode enables a vertical
|
||||
crosshair that lets you trace the values on the x axis, "y" enables a
|
||||
horizontal crosshair and "xy" enables them both. "color" is the color of the
|
||||
crosshair (default is "rgba(170, 0, 0, 0.80)"), "lineWidth" is the width of
|
||||
the drawn lines (default is 1).
|
||||
|
||||
The plugin also adds four public methods:
|
||||
|
||||
- setCrosshair( pos )
|
||||
|
||||
Set the position of the crosshair. Note that this is cleared if the user
|
||||
moves the mouse. "pos" is in coordinates of the plot and should be on the
|
||||
form { x: xpos, y: ypos } (you can use x2/x3/... if you're using multiple
|
||||
axes), which is coincidentally the same format as what you get from a
|
||||
"plothover" event. If "pos" is null, the crosshair is cleared.
|
||||
|
||||
- clearCrosshair()
|
||||
|
||||
Clear the crosshair.
|
||||
|
||||
- lockCrosshair(pos)
|
||||
|
||||
Cause the crosshair to lock to the current location, no longer updating if
|
||||
the user moves the mouse. Optionally supply a position (passed on to
|
||||
setCrosshair()) to move it to.
|
||||
|
||||
Example usage:
|
||||
|
||||
var myFlot = $.plot( $("#graph"), ..., { crosshair: { mode: "x" } } };
|
||||
$("#graph").bind( "plothover", function ( evt, position, item ) {
|
||||
if ( item ) {
|
||||
// Lock the crosshair to the data point being hovered
|
||||
myFlot.lockCrosshair({
|
||||
x: item.datapoint[ 0 ],
|
||||
y: item.datapoint[ 1 ]
|
||||
});
|
||||
} else {
|
||||
// Return normal crosshair operation
|
||||
myFlot.unlockCrosshair();
|
||||
}
|
||||
});
|
||||
|
||||
- unlockCrosshair()
|
||||
|
||||
Free the crosshair to move again after locking it.
|
||||
*/
|
||||
|
||||
(function ($) {
|
||||
var options = {
|
||||
crosshair: {
|
||||
mode: null, // one of null, "x", "y" or "xy",
|
||||
color: "rgba(170, 0, 0, 0.80)",
|
||||
lineWidth: 1
|
||||
}
|
||||
};
|
||||
|
||||
function init(plot) {
|
||||
// position of crosshair in pixels
|
||||
var crosshair = { x: -1, y: -1, locked: false };
|
||||
|
||||
plot.setCrosshair = function setCrosshair(pos) {
|
||||
if (!pos)
|
||||
crosshair.x = -1;
|
||||
else {
|
||||
var o = plot.p2c(pos);
|
||||
crosshair.x = Math.max(0, Math.min(o.left, plot.width()));
|
||||
crosshair.y = Math.max(0, Math.min(o.top, plot.height()));
|
||||
}
|
||||
|
||||
plot.triggerRedrawOverlay();
|
||||
};
|
||||
|
||||
plot.clearCrosshair = plot.setCrosshair; // passes null for pos
|
||||
|
||||
plot.lockCrosshair = function lockCrosshair(pos) {
|
||||
if (pos)
|
||||
plot.setCrosshair(pos);
|
||||
crosshair.locked = true;
|
||||
};
|
||||
|
||||
plot.unlockCrosshair = function unlockCrosshair() {
|
||||
crosshair.locked = false;
|
||||
};
|
||||
|
||||
function onMouseOut(e) {
|
||||
if (crosshair.locked)
|
||||
return;
|
||||
|
||||
if (crosshair.x != -1) {
|
||||
crosshair.x = -1;
|
||||
plot.triggerRedrawOverlay();
|
||||
}
|
||||
}
|
||||
|
||||
function onMouseMove(e) {
|
||||
if (crosshair.locked)
|
||||
return;
|
||||
|
||||
if (plot.getSelection && plot.getSelection()) {
|
||||
crosshair.x = -1; // hide the crosshair while selecting
|
||||
return;
|
||||
}
|
||||
|
||||
var offset = plot.offset();
|
||||
crosshair.x = Math.max(0, Math.min(e.pageX - offset.left, plot.width()));
|
||||
crosshair.y = Math.max(0, Math.min(e.pageY - offset.top, plot.height()));
|
||||
plot.triggerRedrawOverlay();
|
||||
}
|
||||
|
||||
plot.hooks.bindEvents.push(function (plot, eventHolder) {
|
||||
if (!plot.getOptions().crosshair.mode)
|
||||
return;
|
||||
|
||||
eventHolder.mouseout(onMouseOut);
|
||||
eventHolder.mousemove(onMouseMove);
|
||||
});
|
||||
|
||||
plot.hooks.drawOverlay.push(function (plot, ctx) {
|
||||
var c = plot.getOptions().crosshair;
|
||||
if (!c.mode)
|
||||
return;
|
||||
|
||||
var plotOffset = plot.getPlotOffset();
|
||||
|
||||
ctx.save();
|
||||
ctx.translate(plotOffset.left, plotOffset.top);
|
||||
|
||||
if (crosshair.x != -1) {
|
||||
var adj = plot.getOptions().crosshair.lineWidth % 2 ? 0.5 : 0;
|
||||
|
||||
ctx.strokeStyle = c.color;
|
||||
ctx.lineWidth = c.lineWidth;
|
||||
ctx.lineJoin = "round";
|
||||
|
||||
ctx.beginPath();
|
||||
if (c.mode.indexOf("x") != -1) {
|
||||
var drawX = Math.floor(crosshair.x) + adj;
|
||||
ctx.moveTo(drawX, 0);
|
||||
ctx.lineTo(drawX, plot.height());
|
||||
}
|
||||
if (c.mode.indexOf("y") != -1) {
|
||||
var drawY = Math.floor(crosshair.y) + adj;
|
||||
ctx.moveTo(0, drawY);
|
||||
ctx.lineTo(plot.width(), drawY);
|
||||
}
|
||||
ctx.stroke();
|
||||
}
|
||||
ctx.restore();
|
||||
});
|
||||
|
||||
plot.hooks.shutdown.push(function (plot, eventHolder) {
|
||||
eventHolder.unbind("mouseout", onMouseOut);
|
||||
eventHolder.unbind("mousemove", onMouseMove);
|
||||
});
|
||||
}
|
||||
|
||||
$.plot.plugins.push({
|
||||
init: init,
|
||||
options: options,
|
||||
name: 'crosshair',
|
||||
version: '1.0'
|
||||
});
|
||||
})(jQuery);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,59 @@
|
||||
/* Flot plugin for automatically redrawing plots as the placeholder resizes.
|
||||
|
||||
Copyright (c) 2007-2014 IOLA and Ole Laursen.
|
||||
Licensed under the MIT license.
|
||||
|
||||
It works by listening for changes on the placeholder div (through the jQuery
|
||||
resize event plugin) - if the size changes, it will redraw the plot.
|
||||
|
||||
There are no options. If you need to disable the plugin for some plots, you
|
||||
can just fix the size of their placeholders.
|
||||
|
||||
*/
|
||||
|
||||
/* Inline dependency:
|
||||
* jQuery resize event - v1.1 - 3/14/2010
|
||||
* http://benalman.com/projects/jquery-resize-plugin/
|
||||
*
|
||||
* Copyright (c) 2010 "Cowboy" Ben Alman
|
||||
* Dual licensed under the MIT and GPL licenses.
|
||||
* http://benalman.com/about/license/
|
||||
*/
|
||||
(function($,e,t){"$:nomunge";var i=[],n=$.resize=$.extend($.resize,{}),a,r=false,s="setTimeout",u="resize",m=u+"-special-event",o="pendingDelay",l="activeDelay",f="throttleWindow";n[o]=200;n[l]=20;n[f]=true;$.event.special[u]={setup:function(){if(!n[f]&&this[s]){return false}var e=$(this);i.push(this);e.data(m,{w:e.width(),h:e.height()});if(i.length===1){a=t;h()}},teardown:function(){if(!n[f]&&this[s]){return false}var e=$(this);for(var t=i.length-1;t>=0;t--){if(i[t]==this){i.splice(t,1);break}}e.removeData(m);if(!i.length){if(r){cancelAnimationFrame(a)}else{clearTimeout(a)}a=null}},add:function(e){if(!n[f]&&this[s]){return false}var i;function a(e,n,a){var r=$(this),s=r.data(m)||{};s.w=n!==t?n:r.width();s.h=a!==t?a:r.height();i.apply(this,arguments)}if($.isFunction(e)){i=e;return a}else{i=e.handler;e.handler=a}}};function h(t){if(r===true){r=t||1}for(var s=i.length-1;s>=0;s--){var l=$(i[s]);if(l[0]==e||l.is(":visible")){var f=l.width(),c=l.height(),d=l.data(m);if(d&&(f!==d.w||c!==d.h)){l.trigger(u,[d.w=f,d.h=c]);r=t||true}}else{d=l.data(m);d.w=0;d.h=0}}if(a!==null){if(r&&(t==null||t-r<1e3)){a=e.requestAnimationFrame(h)}else{a=setTimeout(h,n[o]);r=false}}}if(!e.requestAnimationFrame){e.requestAnimationFrame=function(){return e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(t,i){return e.setTimeout(function(){t((new Date).getTime())},n[l])}}()}if(!e.cancelAnimationFrame){e.cancelAnimationFrame=function(){return e.webkitCancelRequestAnimationFrame||e.mozCancelRequestAnimationFrame||e.oCancelRequestAnimationFrame||e.msCancelRequestAnimationFrame||clearTimeout}()}})(jQuery,this);
|
||||
|
||||
(function ($) {
|
||||
var options = { }; // no options
|
||||
|
||||
function init(plot) {
|
||||
function onResize() {
|
||||
var placeholder = plot.getPlaceholder();
|
||||
|
||||
// somebody might have hidden us and we can't plot
|
||||
// when we don't have the dimensions
|
||||
if (placeholder.width() == 0 || placeholder.height() == 0)
|
||||
return;
|
||||
|
||||
plot.resize();
|
||||
plot.setupGrid();
|
||||
plot.draw();
|
||||
}
|
||||
|
||||
function bindEvents(plot, eventHolder) {
|
||||
plot.getPlaceholder().resize(onResize);
|
||||
}
|
||||
|
||||
function shutdown(plot, eventHolder) {
|
||||
plot.getPlaceholder().unbind("resize", onResize);
|
||||
}
|
||||
|
||||
plot.hooks.bindEvents.push(bindEvents);
|
||||
plot.hooks.shutdown.push(shutdown);
|
||||
}
|
||||
|
||||
$.plot.plugins.push({
|
||||
init: init,
|
||||
options: options,
|
||||
name: 'resize',
|
||||
version: '1.0'
|
||||
});
|
||||
})(jQuery);
|
||||
@@ -0,0 +1,432 @@
|
||||
/* Pretty handling of time axes.
|
||||
|
||||
Copyright (c) 2007-2014 IOLA and Ole Laursen.
|
||||
Licensed under the MIT license.
|
||||
|
||||
Set axis.mode to "time" to enable. See the section "Time series data" in
|
||||
API.txt for details.
|
||||
|
||||
*/
|
||||
|
||||
(function($) {
|
||||
|
||||
var options = {
|
||||
xaxis: {
|
||||
timezone: null, // "browser" for local to the client or timezone for timezone-js
|
||||
timeformat: null, // format string to use
|
||||
twelveHourClock: false, // 12 or 24 time in time mode
|
||||
monthNames: null // list of names of months
|
||||
}
|
||||
};
|
||||
|
||||
// round to nearby lower multiple of base
|
||||
|
||||
function floorInBase(n, base) {
|
||||
return base * Math.floor(n / base);
|
||||
}
|
||||
|
||||
// Returns a string with the date d formatted according to fmt.
|
||||
// A subset of the Open Group's strftime format is supported.
|
||||
|
||||
function formatDate(d, fmt, monthNames, dayNames) {
|
||||
|
||||
if (typeof d.strftime == "function") {
|
||||
return d.strftime(fmt);
|
||||
}
|
||||
|
||||
var leftPad = function(n, pad) {
|
||||
n = "" + n;
|
||||
pad = "" + (pad == null ? "0" : pad);
|
||||
return n.length == 1 ? pad + n : n;
|
||||
};
|
||||
|
||||
var r = [];
|
||||
var escape = false;
|
||||
var hours = d.getHours();
|
||||
var isAM = hours < 12;
|
||||
|
||||
if (monthNames == null) {
|
||||
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
||||
}
|
||||
|
||||
if (dayNames == null) {
|
||||
dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
||||
}
|
||||
|
||||
var hours12;
|
||||
|
||||
if (hours > 12) {
|
||||
hours12 = hours - 12;
|
||||
} else if (hours == 0) {
|
||||
hours12 = 12;
|
||||
} else {
|
||||
hours12 = hours;
|
||||
}
|
||||
|
||||
for (var i = 0; i < fmt.length; ++i) {
|
||||
|
||||
var c = fmt.charAt(i);
|
||||
|
||||
if (escape) {
|
||||
switch (c) {
|
||||
case 'a': c = "" + dayNames[d.getDay()]; break;
|
||||
case 'b': c = "" + monthNames[d.getMonth()]; break;
|
||||
case 'd': c = leftPad(d.getDate()); break;
|
||||
case 'e': c = leftPad(d.getDate(), " "); break;
|
||||
case 'h': // For back-compat with 0.7; remove in 1.0
|
||||
case 'H': c = leftPad(hours); break;
|
||||
case 'I': c = leftPad(hours12); break;
|
||||
case 'l': c = leftPad(hours12, " "); break;
|
||||
case 'm': c = leftPad(d.getMonth() + 1); break;
|
||||
case 'M': c = leftPad(d.getMinutes()); break;
|
||||
// quarters not in Open Group's strftime specification
|
||||
case 'q':
|
||||
c = "" + (Math.floor(d.getMonth() / 3) + 1); break;
|
||||
case 'S': c = leftPad(d.getSeconds()); break;
|
||||
case 'y': c = leftPad(d.getFullYear() % 100); break;
|
||||
case 'Y': c = "" + d.getFullYear(); break;
|
||||
case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break;
|
||||
case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break;
|
||||
case 'w': c = "" + d.getDay(); break;
|
||||
}
|
||||
r.push(c);
|
||||
escape = false;
|
||||
} else {
|
||||
if (c == "%") {
|
||||
escape = true;
|
||||
} else {
|
||||
r.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return r.join("");
|
||||
}
|
||||
|
||||
// To have a consistent view of time-based data independent of which time
|
||||
// zone the client happens to be in we need a date-like object independent
|
||||
// of time zones. This is done through a wrapper that only calls the UTC
|
||||
// versions of the accessor methods.
|
||||
|
||||
function makeUtcWrapper(d) {
|
||||
|
||||
function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) {
|
||||
sourceObj[sourceMethod] = function() {
|
||||
return targetObj[targetMethod].apply(targetObj, arguments);
|
||||
};
|
||||
};
|
||||
|
||||
var utc = {
|
||||
date: d
|
||||
};
|
||||
|
||||
// support strftime, if found
|
||||
|
||||
if (d.strftime != undefined) {
|
||||
addProxyMethod(utc, "strftime", d, "strftime");
|
||||
}
|
||||
|
||||
addProxyMethod(utc, "getTime", d, "getTime");
|
||||
addProxyMethod(utc, "setTime", d, "setTime");
|
||||
|
||||
var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"];
|
||||
|
||||
for (var p = 0; p < props.length; p++) {
|
||||
addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]);
|
||||
addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]);
|
||||
}
|
||||
|
||||
return utc;
|
||||
};
|
||||
|
||||
// select time zone strategy. This returns a date-like object tied to the
|
||||
// desired timezone
|
||||
|
||||
function dateGenerator(ts, opts) {
|
||||
if (opts.timezone == "browser") {
|
||||
return new Date(ts);
|
||||
} else if (!opts.timezone || opts.timezone == "utc") {
|
||||
return makeUtcWrapper(new Date(ts));
|
||||
} else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") {
|
||||
var d = new timezoneJS.Date();
|
||||
// timezone-js is fickle, so be sure to set the time zone before
|
||||
// setting the time.
|
||||
d.setTimezone(opts.timezone);
|
||||
d.setTime(ts);
|
||||
return d;
|
||||
} else {
|
||||
return makeUtcWrapper(new Date(ts));
|
||||
}
|
||||
}
|
||||
|
||||
// map of app. size of time units in milliseconds
|
||||
|
||||
var timeUnitSize = {
|
||||
"second": 1000,
|
||||
"minute": 60 * 1000,
|
||||
"hour": 60 * 60 * 1000,
|
||||
"day": 24 * 60 * 60 * 1000,
|
||||
"month": 30 * 24 * 60 * 60 * 1000,
|
||||
"quarter": 3 * 30 * 24 * 60 * 60 * 1000,
|
||||
"year": 365.2425 * 24 * 60 * 60 * 1000
|
||||
};
|
||||
|
||||
// the allowed tick sizes, after 1 year we use
|
||||
// an integer algorithm
|
||||
|
||||
var baseSpec = [
|
||||
[1, "second"], [2, "second"], [5, "second"], [10, "second"],
|
||||
[30, "second"],
|
||||
[1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
|
||||
[30, "minute"],
|
||||
[1, "hour"], [2, "hour"], [4, "hour"],
|
||||
[8, "hour"], [12, "hour"],
|
||||
[1, "day"], [2, "day"], [3, "day"],
|
||||
[0.25, "month"], [0.5, "month"], [1, "month"],
|
||||
[2, "month"]
|
||||
];
|
||||
|
||||
// we don't know which variant(s) we'll need yet, but generating both is
|
||||
// cheap
|
||||
|
||||
var specMonths = baseSpec.concat([[3, "month"], [6, "month"],
|
||||
[1, "year"]]);
|
||||
var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"],
|
||||
[1, "year"]]);
|
||||
|
||||
function init(plot) {
|
||||
plot.hooks.processOptions.push(function (plot, options) {
|
||||
$.each(plot.getAxes(), function(axisName, axis) {
|
||||
|
||||
var opts = axis.options;
|
||||
|
||||
if (opts.mode == "time") {
|
||||
axis.tickGenerator = function(axis) {
|
||||
|
||||
var ticks = [];
|
||||
var d = dateGenerator(axis.min, opts);
|
||||
var minSize = 0;
|
||||
|
||||
// make quarter use a possibility if quarters are
|
||||
// mentioned in either of these options
|
||||
|
||||
var spec = (opts.tickSize && opts.tickSize[1] ===
|
||||
"quarter") ||
|
||||
(opts.minTickSize && opts.minTickSize[1] ===
|
||||
"quarter") ? specQuarters : specMonths;
|
||||
|
||||
if (opts.minTickSize != null) {
|
||||
if (typeof opts.tickSize == "number") {
|
||||
minSize = opts.tickSize;
|
||||
} else {
|
||||
minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < spec.length - 1; ++i) {
|
||||
if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]]
|
||||
+ spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
|
||||
&& spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var size = spec[i][0];
|
||||
var unit = spec[i][1];
|
||||
|
||||
// special-case the possibility of several years
|
||||
|
||||
if (unit == "year") {
|
||||
|
||||
// if given a minTickSize in years, just use it,
|
||||
// ensuring that it's an integer
|
||||
|
||||
if (opts.minTickSize != null && opts.minTickSize[1] == "year") {
|
||||
size = Math.floor(opts.minTickSize[0]);
|
||||
} else {
|
||||
|
||||
var magn = Math.pow(10, Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10));
|
||||
var norm = (axis.delta / timeUnitSize.year) / magn;
|
||||
|
||||
if (norm < 1.5) {
|
||||
size = 1;
|
||||
} else if (norm < 3) {
|
||||
size = 2;
|
||||
} else if (norm < 7.5) {
|
||||
size = 5;
|
||||
} else {
|
||||
size = 10;
|
||||
}
|
||||
|
||||
size *= magn;
|
||||
}
|
||||
|
||||
// minimum size for years is 1
|
||||
|
||||
if (size < 1) {
|
||||
size = 1;
|
||||
}
|
||||
}
|
||||
|
||||
axis.tickSize = opts.tickSize || [size, unit];
|
||||
var tickSize = axis.tickSize[0];
|
||||
unit = axis.tickSize[1];
|
||||
|
||||
var step = tickSize * timeUnitSize[unit];
|
||||
|
||||
if (unit == "second") {
|
||||
d.setSeconds(floorInBase(d.getSeconds(), tickSize));
|
||||
} else if (unit == "minute") {
|
||||
d.setMinutes(floorInBase(d.getMinutes(), tickSize));
|
||||
} else if (unit == "hour") {
|
||||
d.setHours(floorInBase(d.getHours(), tickSize));
|
||||
} else if (unit == "month") {
|
||||
d.setMonth(floorInBase(d.getMonth(), tickSize));
|
||||
} else if (unit == "quarter") {
|
||||
d.setMonth(3 * floorInBase(d.getMonth() / 3,
|
||||
tickSize));
|
||||
} else if (unit == "year") {
|
||||
d.setFullYear(floorInBase(d.getFullYear(), tickSize));
|
||||
}
|
||||
|
||||
// reset smaller components
|
||||
|
||||
d.setMilliseconds(0);
|
||||
|
||||
if (step >= timeUnitSize.minute) {
|
||||
d.setSeconds(0);
|
||||
}
|
||||
if (step >= timeUnitSize.hour) {
|
||||
d.setMinutes(0);
|
||||
}
|
||||
if (step >= timeUnitSize.day) {
|
||||
d.setHours(0);
|
||||
}
|
||||
if (step >= timeUnitSize.day * 4) {
|
||||
d.setDate(1);
|
||||
}
|
||||
if (step >= timeUnitSize.month * 2) {
|
||||
d.setMonth(floorInBase(d.getMonth(), 3));
|
||||
}
|
||||
if (step >= timeUnitSize.quarter * 2) {
|
||||
d.setMonth(floorInBase(d.getMonth(), 6));
|
||||
}
|
||||
if (step >= timeUnitSize.year) {
|
||||
d.setMonth(0);
|
||||
}
|
||||
|
||||
var carry = 0;
|
||||
var v = Number.NaN;
|
||||
var prev;
|
||||
|
||||
do {
|
||||
|
||||
prev = v;
|
||||
v = d.getTime();
|
||||
ticks.push(v);
|
||||
|
||||
if (unit == "month" || unit == "quarter") {
|
||||
if (tickSize < 1) {
|
||||
|
||||
// a bit complicated - we'll divide the
|
||||
// month/quarter up but we need to take
|
||||
// care of fractions so we don't end up in
|
||||
// the middle of a day
|
||||
|
||||
d.setDate(1);
|
||||
var start = d.getTime();
|
||||
d.setMonth(d.getMonth() +
|
||||
(unit == "quarter" ? 3 : 1));
|
||||
var end = d.getTime();
|
||||
d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
|
||||
carry = d.getHours();
|
||||
d.setHours(0);
|
||||
} else {
|
||||
d.setMonth(d.getMonth() +
|
||||
tickSize * (unit == "quarter" ? 3 : 1));
|
||||
}
|
||||
} else if (unit == "year") {
|
||||
d.setFullYear(d.getFullYear() + tickSize);
|
||||
} else {
|
||||
d.setTime(v + step);
|
||||
}
|
||||
} while (v < axis.max && v != prev);
|
||||
|
||||
return ticks;
|
||||
};
|
||||
|
||||
axis.tickFormatter = function (v, axis) {
|
||||
|
||||
var d = dateGenerator(v, axis.options);
|
||||
|
||||
// first check global format
|
||||
|
||||
if (opts.timeformat != null) {
|
||||
return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames);
|
||||
}
|
||||
|
||||
// possibly use quarters if quarters are mentioned in
|
||||
// any of these places
|
||||
|
||||
var useQuarters = (axis.options.tickSize &&
|
||||
axis.options.tickSize[1] == "quarter") ||
|
||||
(axis.options.minTickSize &&
|
||||
axis.options.minTickSize[1] == "quarter");
|
||||
|
||||
var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
|
||||
var span = axis.max - axis.min;
|
||||
var suffix = (opts.twelveHourClock) ? " %p" : "";
|
||||
var hourCode = (opts.twelveHourClock) ? "%I" : "%H";
|
||||
var fmt;
|
||||
|
||||
if (t < timeUnitSize.minute) {
|
||||
fmt = hourCode + ":%M:%S" + suffix;
|
||||
} else if (t < timeUnitSize.day) {
|
||||
if (span < 2 * timeUnitSize.day) {
|
||||
fmt = hourCode + ":%M" + suffix;
|
||||
} else {
|
||||
fmt = "%b %d " + hourCode + ":%M" + suffix;
|
||||
}
|
||||
} else if (t < timeUnitSize.month) {
|
||||
fmt = "%b %d";
|
||||
} else if ((useQuarters && t < timeUnitSize.quarter) ||
|
||||
(!useQuarters && t < timeUnitSize.year)) {
|
||||
if (span < timeUnitSize.year) {
|
||||
fmt = "%b";
|
||||
} else {
|
||||
fmt = "%b %Y";
|
||||
}
|
||||
} else if (useQuarters && t < timeUnitSize.year) {
|
||||
if (span < timeUnitSize.year) {
|
||||
fmt = "Q%q";
|
||||
} else {
|
||||
fmt = "Q%q %Y";
|
||||
}
|
||||
} else {
|
||||
fmt = "%Y";
|
||||
}
|
||||
|
||||
var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames);
|
||||
|
||||
return rt;
|
||||
};
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
$.plot.plugins.push({
|
||||
init: init,
|
||||
options: options,
|
||||
name: 'time',
|
||||
version: '1.0'
|
||||
});
|
||||
|
||||
// Time-axis support used to be in Flot core, which exposed the
|
||||
// formatDate function on the plot object. Various plugins depend
|
||||
// on the function, so we need to re-expose it here.
|
||||
|
||||
$.plot.formatDate = formatDate;
|
||||
$.plot.dateGenerator = dateGenerator;
|
||||
|
||||
})(jQuery);
|
||||
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user