diff --git a/.gitignore b/.gitignore
index 1c96ad61b..472e38106 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,7 @@
+src/octoprint/templates/_data/AUTHORS.md
+src/octoprint/templates/_data/CHANGELOG.md
+src/octoprint/templates/_data/THIRDPARTYLICENSES.md
+
*.tar.bz2
*.tar.gz
*.7z
diff --git a/.versioneer-lookup b/.versioneer-lookup
index b0de673da..86ee131b9 100644
--- a/.versioneer-lookup
+++ b/.versioneer-lookup
@@ -14,10 +14,10 @@ master
HEAD
\(detached.*
-# maintenance is currently the branch for preparation of maintenance release 1.2.8
+# maintenance is currently the branch for preparation of maintenance release 1.2.9
# so are any fix/... branches
-maintenance 1.2.8 6c622f7c4332b71c6ece59552ffc87c146155c84 pep440-dev
-fix/.* 1.2.8 6c622f7c4332b71c6ece59552ffc87c146155c84 pep440-dev
+maintenance 1.2.9 dedadbc9ac0305799e94ae279d3bca131629c4c5 pep440-dev
+fix/.* 1.2.9 dedadbc9ac0305799e94ae279d3bca131629c4c5 pep440-dev
# every other branch is a development branch and thus gets resolved to 1.3.0-dev for now
.* 1.3.0 198d3450d94be1a2 pep440-dev
diff --git a/AUTHORS.md b/AUTHORS.md
index 44e77f485..55d2b49fb 100644
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -54,7 +54,9 @@ date of first contribution):
* [Nicanor Romero Venier](https://github.com/nicanor-romero)
* [Thomas Hou](https://github.com/masterhou)
* [Mark Bastiaans](https://github.com/markbastiaans)
+ * [Marcel Hellwig](https://github.com/punkkeks)
* [Kevin Murphy](https://github.com/kevingelion)
+ * [Richard Joyce](https://github.com/richjoyce)
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
[Daid Braam](https://github.com/daid). Parts of its communication layer and
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a07b2b19c..82b15cae8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,74 @@
# OctoPrint Changelog
+## 1.3.0 (unreleased)
+
+### New Features
+
+* A new wizard dialog for system setups that can also be extended by plugins. Replaces the first run dialog
+ for setting up access control and can also be triggered in other cases than only the first run, e.g.
+ if Plugins necessitate user input to function properly.
+* An About dialog including licenses, authors, the changelog and more, extendable by plugins if necessary.
+* New features within the plugin system (TODO):
+ * New plugin mixin `UiPlugin` for plugins that want to provide an alternative web interface delivered by the
+ server.
+* Extracted a Javascript client library for utilizing the server's API, can be reused by `UiPlugin`s. (TODO)
+
+(TODO) = needs to be further described and documented
+
+### Improvements
+
+* Upgraded versioneer, generated version numbers are now PEP440 compatible (relevant
+ for setup)
+* More verbose output for Software Update plugin for logged in administrators.
+ Will now log the update commands and their output similar to the Plugin
+ Manager install and uninstall dialog.
+* Allow hiding plugins from Plugin Manager via ``config.yaml``.
+* Cura Plugin: "Test" button to check if path to cura engine is valid.
+* Cura Plugin: Now also supports 15.06 version of CuraEngine.
+* New central configuration option for commands to restart OctoPrint and to
+ restart and shut down the system OctoPrint is running on. This allows plugins
+ (like the Software Update Plugin or the Plugin Manager) and core functionality
+ to perform these common administrative tasks without the user needing to define
+ everything redundantly.
+* `pip` helper now adjusts `pip install` parameters corresponding to detected
+ `pip` version:
+ * Removes `--process-dependency-links` when it's not needed
+ * Adds `--no-use-wheel` when it's needed
+ * Detects and reports on completely broken versions
+* Better tracking of printer connection state for plugins and scripts:
+ * Introduced three new Events `Connecting`, `Disconnecting` and
+ `PrinterStateChanged`.
+ * Introduced new GCODE script `beforePrinterDisconnected` which will get sent
+ before a (controlled) disconnect from the printer. This can be used to send
+ some final commands to the printer before the connection goes down, e.g.
+ `M117 Bye from OctoPrint`.
+ * The communication layer will now wait for the send queue to be fully processed
+ before disconnecting from the printer for good. This way it is ensured that
+ the `beforePrinterDisconnected` script or any further GCODE injected into it
+ will actually get sent.
+* Additional baud rates to allow for connecting can now be specified along side
+ additional serial ports via the settings dialog and the configuration file.
+* Option to never send checksums (e.g. if the printer firmware doesn't support it),
+ see [#949](https://github.com/foosel/OctoPrint/issues/949).
+* Added secondary temperature polling interval to use when printer is not printing
+ but a target temperature is set - this way the graph should be more responsive
+ while monitoring a manual heatup.
+* Documentation improvements
+* Test buttons for webcam snapshot & stream URL, ffmpeg path and some other settings
+ (see also [#183](https://github.com/foosel/OctoPrint/issues/183)).
+* Temperature graph automatically adjusts its Y axis range if necessary to
+ accomodate the plotted data (see also [#632](https://github.com/foosel/OctoPrint/issues/632)).
+* "Fan on" command now always sends `S255` parameter for better compatibility
+ across firmwares.
+
+### Bug Fixes
+
+* It's not possible anymore to select files that are not machinecode files (e.g.
+ GCODE) for printing on the file API.
+* Changes to a user's personal settings via the UI now propagate across sessions.
+* [#1047](https://github.com/foosel/OctoPrint/issues/1047) - Fixed 90 degree
+ webcam rotation for iOS Safari.
+
## 1.2.8 (2015-12-07)
### Notes for Upgraders
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 68c09bcb4..924bfa25e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -30,8 +30,12 @@ nothing but ticket management.
- If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report)
and *[use the provided template](#what-should-i-include-in-a-ticket)*.
You do not need to do anything else with your ticket.
-- If you want to post a **request** of any kind (feature request, documentation
- request, ...), add `[Request]` to your issue's title (e.g. `[Request] Awesome new feature`).
+- If you want to post a **feature request** or a **documentation request**, add `[Request]`
+ to your issue's title (e.g. `[Request] Awesome new feature`). A question on how to run/change/setup
+ something is **not** what qualifies as a request here, use the
+ [Mailinglist](https://groups.google.com/group/octoprint) or the
+ [Google+ Community](https://plus.google.com/communities/102771308349328485741) for
+ such support issues.
- If you are a **developer** that wants to brainstorm a pull request or possible
changes to the plugin system, add [Brainstorming] to your issue's title (e.g.
`[Brainstorming] New plugin hook for doing some cool stuff`).
diff --git a/MANIFEST.in b/MANIFEST.in
index 82ddf50b3..158333105 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -2,7 +2,11 @@ recursive-include src/octoprint/static *
recursive-include src/octoprint/templates *
recursive-include src/octoprint/plugins *
recursive-include src/octoprint/translations *
+include src/octoprint/util/piptestballoon/setup.py
include versioneer.py
include src/octoprint/_version.py
+include AUTHORS.md
+include CHANGELOG.md
+include LICENSE
include README.md
include requirements.txt
diff --git a/README.md b/README.md
index 4d5a9ba0b..ccb813ce3 100644
--- a/README.md
+++ b/README.md
@@ -47,11 +47,11 @@ which is a custom SD card image that includes OctoPrint plus dependencies.
The generic steps that should basically be done regardless of operating system
and runtime environment are the following (as *regular
user*, please keep your hands *off* of the `sudo` command here!) - this assumes
-you already have Python 2.7, pip and virtualenv set up:
+you already have Python 2.7, pip and virtualenv set up on your system:
1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git`
2. Change into the OctoPrint folder: `cd OctoPrint`
-3. Create a user-owned virtual environment therein: `virtualenv --system-site-packages venv`
+3. Create a user-owned virtual environment therein: `virtualenv venv`
4. Install OctoPrint *into that virtual environment*: `./venv/bin/python setup.py install`
You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage)
diff --git a/THIRDPARTYLICENSES.md b/THIRDPARTYLICENSES.md
new file mode 100644
index 000000000..f181d5879
--- /dev/null
+++ b/THIRDPARTYLICENSES.md
@@ -0,0 +1,56 @@
+# Third Party Licenses
+
+## Web Interface
+
+ * [AVLTree](https://gist.github.com/viking/2424106) (modified): GPL, LGPL (dual licensed)
+ * [Babel JavaScript Support](https://github.com/mitsuhiko/babel/blob/master/contrib/babel.js): BSD
+ * [Bootstrap](http://getbootstrap.com/): Apache License 2.0
+ * [Bootstrap Modal](http://jschr.github.io/bootstrap-modal/): Apache License 2.0
+ * [Bootstrap Slider Knockout Bindings](https://github.com/cosminstefanxp/bootstrap-slider-knockout-binding): MIT
+ * [Bootstrap Slider](http://seiyria.com/bootstrap-slider/): Apache License 2.0
+ * [Bootstrap Tabdrop](http://www.eyecon.ro/bootstrap-tabdrop): Apache License 2.0
+ * [Detect Mobile Browser](http://detectmobilebrowsers.com/): Public Domain
+ * [Flot](http://www.flotcharts.org/): MIT
+ * [JavaScript MD5](https://github.com/blueimp/JavaScript-MD5): MIT
+ * [JQuery](http://jquery.com/): MIT
+ * [JQuery Bootstrap Wizard](http://github.com/VinceG/twitter-bootstrap-wizard): MIT, GPL (dual licensed)
+ * [JQuery File Upload](https://github.com/blueimp/jQuery-File-Upload): MIT
+ * [JQuery iframe transport](https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.iframe-transport.js): MIT
+ * [JQuery QRCode](http://larsjung.de/jquery-qrcode/): MIT
+ * [JQuery Slimscroll](http://rocha.la/jQuery-slimScroll): MIT, GPL (dual licensed)
+ * [JQuery UI Core, Mouse, Slider and Widget](http://jqueryui.com): MIT
+ * [Knockout](http://knockoutjs.com/): MIT
+ * [LESS](http://lesscss.org): Apache License 2.0
+ * [lodash](https://lodash.com): MIT
+ * [Loglevel](https://github.com/pimterry/loglevel): MIT
+ * [Modernizr](http://modernizr.com): MIT
+ * [Moment.js](http://momentjs.com/): MIT
+ * [PNotify](http://sciactive.com/pnotify/): GPL, LGPL, MPL (triple licensed)
+ * [pusher.color.js](http://cache.preserve.io/5g18q0pw/index.html) (original link dead): MIT
+ * [SockJS](https://github.com/sockjs/sockjs-client): MIT
+ * [sprintf-js](http://alexei.ro/): BSD
+
+## Server
+
+ * [Awesome-Slugify](https://pypi.python.org/pypi/awesome-slugify): GPLv3
+ * [Click](http://click.pocoo.org/): BSD
+ * [Flask](http://flask.pocoo.org/): BSD
+ * [Flask-Assets](http://github.com/miracle2k/flask-assets): BSD
+ * [Flask-Babel](http://github.com/mitsuhiko/flask-babel): BSD
+ * [Flask-Login](https://flask-login.readthedocs.org/en/latest/https://github.com/maxcountryman/flask-login): MIT
+ * [Flask-Markdown](http://github.com/dcolish/flask-markdown): BSD
+ * [Flask-Principal](http://packages.python.org/Flask-Principal/): MIT
+ * [netaddr](https://github.com/drkjam/netaddr/): BSD
+ * [netifaces](https://bitbucket.org/al45tair/netifaces): MIT
+ * [pkginfo](http://pypi.python.org/pypi/pkginfo/): Python
+ * [psutil](https://github.com/giampaolo/psutil): BSD
+ * [pylru](https://github.com/jlhutch/pylru): GPLv2
+ * [pyserial](http://pyserial.sourceforge.net/): Python
+ * [PyYAML](http://pyyaml.org/wiki/PyYAML): MIT
+ * [requests](http://python-requests.org/): Apache License 2.0
+ * [rsa](http://stuvel.eu/rsa): Apache License 2.0
+ * [sarge](http://sarge.readthedocs.org/): BSD
+ * [semantic_version](https://github.com/rbarrois/python-semanticversion): BSD
+ * [SockJS-Tornado](http://github.com/mrjoes/sockjs-tornado/): MIT
+ * [Tornado](http://www.tornadoweb.org/): Apache License 2.0
+ * [watchdog](http://github.com/gorakhargosh/watchdog): Apache License 2.0
diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst
index e182e6bb5..27a20352f 100644
--- a/docs/configuration/config_yaml.rst
+++ b/docs/configuration/config_yaml.rst
@@ -611,6 +611,32 @@ Use the following settings to configure the serial connection to the printer:
additionalPorts:
- /dev/myPrinterSymlink
+ # Use this to define additional baud rates to offer for connecting to serial ports. Must be a
+ # valid integer. Defaults to not set
+ additionalBaudrates:
+ - 123456
+
+ # Commands which are known to take a long time to be acknowledged by the firmware. E.g.
+ # homing, dwelling, auto leveling etc. Defaults to the below commands.
+ longRunningCommands:
+ - G4
+ - G28
+ - G29
+ - G30
+ - G32
+ - M400
+ - M226
+
+ # Commands which need to always be send with a checksum. Defaults to only M110
+ checksumRequiringCommands:
+ - M110
+
+ # Command to send in order to initiate a handshake with the printer.
+ # Defaults to "M110 N0" which simply resets the line numbers in the firmware and which
+ # should be acknowledged with a simple "ok".
+ helloCommand:
+ - M110 N0
+
.. _sec-configuration-config_yaml-server:
Server
diff --git a/docs/events/index.rst b/docs/events/index.rst
index 1dfde9007..70aa5d2f9 100644
--- a/docs/events/index.rst
+++ b/docs/events/index.rst
@@ -106,6 +106,9 @@ ClientClosed
Printer communication
---------------------
+Connecting
+ The server is attempting to connect to the printer.
+
Connected
The server has connected to the printer.
@@ -114,6 +117,11 @@ Connected
* ``port``: the connected serial port
* ``baudrate``: the baud rate
+Disconnecting
+ The server is going to disconnect from the printer. Note that this
+ event might not always be sent when the server and printer get disconnected
+ from each other. Do not depend on this for critical life cycle management.
+
Disconnected
The server has disconnected from the printer
@@ -124,6 +132,15 @@ Error
* ``error``: the error string
+PrinterStateChanged
+ The state of the printer changed.
+
+ Payload:
+
+ * ``state_id``: Id of the new state. See
+ :func:`~octoprint.printer.PrinterInterface.get_state_id` for possible values.
+ * ``state_string``: Text representation of the new state.
+
File handling
-------------
diff --git a/docs/features/custom_controls.rst b/docs/features/custom_controls.rst
index 983611fc8..a953617e9 100644
--- a/docs/features/custom_controls.rst
+++ b/docs/features/custom_controls.rst
@@ -65,7 +65,7 @@ a GCODE script including user input.
children:
- name: Get Position
command: M114
- regex: "X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)"
+ regex: "X:([-+]?[0-9.]+) Y:([-+]?[0-9.]+) Z:([-+]?[0-9.]+) E:([-+]?[0-9.]+)"
template: "Position: X={0}, Y={1}, Z={2}, E={3}"
- name: Fun stuff
children:
diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst
index d1b5fde80..86b7d8c22 100644
--- a/docs/features/gcode_scripts.rst
+++ b/docs/features/gcode_scripts.rst
@@ -26,6 +26,10 @@ Predefined Scripts
The following GCODE scripts are sent by OctoPrint automatically:
* ``afterPrinterConnected``: Sent after OctoPrint successfully connected to a printer. Defaults to an empty script.
+ * ``beforePrinterDisconnected``: Sent just before OctoPrint (actively) closes the connection to the printer. Defaults
+ to an empty script. Note that this will *not* be sent for unexpected connection cut offs, e.g. in case of errors
+ on the serial line, only when the user clicks the "Disconnect" button or the printer requests a disconnect via an
+ :ref:`action command
+ Please read the following, it is very important for your printer's health!
+
+ OctoPrint by default ships with Access Control enabled, meaning you won't be able to do anything with the
+ printer unless you login first as a configured user. This is to prevent strangers - possibly with
+ malicious intent - to gain access to your printer via the internet or another untrustworthy network
+ and using it in such a way that it is damaged or worse (i.e. causes a fire).
+
+ It looks like you haven't configured access control yet. Please set up a username and password for the
+ initial administrator account who will have full access to both the printer and OctoPrint's settings, then click
+ on "Keep Access Control Enabled":
+
+ Note: In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't
+ need Access Control for other reasons, you may alternatively disable Access Control. You should only
+ do this if you are absolutely certain that only people you know and trust will be able to connect to it.
+
+ Do NOT underestimate the risk of an unsecured access from the internet to your printer!
+
+ If you have a webcam, you may now configure it here.
+
+ The Stream URL is the URL OctoPrint uses to embed the
+ actual webcam stream (which should be an MJPG stream) into the web
+ interface. This needs to be reachable from your browser.
+
+ It may be
+ {{ _('Access Control') }}
+
+{% trans %}{{ _('Webcam & Timelapse Recordings') }}
+
+{% trans %}{{ _('Webcam') }}
+
+{% trans %}
+
+http://host:port/path),//host:port/path),/absolute/path) orrelative/path)
+ The Snapshot URL is the URL OctoPrint uses to fetch single + images from the webcam for creating timelapse recordings. This needs to be + a fully qualified URL reachable from the OctoPrint server. +
{% endtrans %} + + + ++ To render the snapshots into timelapse recordings, OctoPrint also needs to + know the correct path to FFMPEG. +
{% endtrans %} + + diff --git a/src/octoprint/plugins/cura/__init__.py b/src/octoprint/plugins/cura/__init__.py index 095a274b5..62f6770c5 100644 --- a/src/octoprint/plugins/cura/__init__.py +++ b/src/octoprint/plugins/cura/__init__.py @@ -16,14 +16,19 @@ import octoprint.util import octoprint.slicing import octoprint.settings +from octoprint.util.paths import normalize as normalize_path + from .profile import Profile +from .profile import GcodeFlavors +from .profile import parse_gcode_flavor class CuraPlugin(octoprint.plugin.SlicerPlugin, octoprint.plugin.SettingsPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.AssetPlugin, octoprint.plugin.BlueprintPlugin, - octoprint.plugin.StartupPlugin): + octoprint.plugin.StartupPlugin, + octoprint.plugin.WizardPlugin): def __init__(self): self._logger = logging.getLogger("octoprint.plugins.cura") @@ -35,6 +40,14 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, self._cancelled_jobs = [] self._job_mutex = threading.Lock() + def _is_engine_configured(self, cura_engine=None): + if cura_engine is None: + cura_engine = normalize_path(self._settings.get(["cura_engine"])) + return cura_engine is not None and os.path.isfile(cura_engine) and os.access(cura_engine, os.X_OK) + + def _is_profile_available(self): + return bool(self._slicing_manager.all_profiles("cura", require_configured=False)) + ##~~ TemplatePlugin API def get_template_vars(self): @@ -42,6 +55,17 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, homepage=__plugin_url__ ) + ##~~ WizardPlugin API + + def is_wizard_required(self): + return not self._is_engine_configured() or not self._is_profile_available() + + def get_wizard_details(self): + return dict( + engine=self._is_engine_configured(), + profile=self._is_profile_available() + ) + ##~~ StartupPlugin API def on_startup(self, host, port): @@ -59,9 +83,6 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, @octoprint.plugin.BlueprintPlugin.route("/import", methods=["POST"]) def import_cura_profile(self): import datetime - import tempfile - - from octoprint.server import slicingManager input_name = "file" input_upload_name = input_name + "." + self._settings.global_get(["server", "uploads", "nameSuffix"]) @@ -90,8 +111,10 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, profile_display_name = name profile_description = "Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now())) profile_allow_overwrite = False + profile_make_default = False # overrides + from octoprint.server.api import valid_boolean_trues if "name" in flask.request.values: profile_name = flask.request.values["name"] if "displayName" in flask.request.values: @@ -99,22 +122,31 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, if "description" in flask.request.values: profile_description = flask.request.values["description"] if "allowOverwrite" in flask.request.values: - from octoprint.server.api import valid_boolean_trues profile_allow_overwrite = flask.request.values["allowOverwrite"] in valid_boolean_trues + if "default" in flask.request.values: + profile_make_default = flask.request.values["default"] in valid_boolean_trues try: - slicingManager.save_profile("cura", - profile_name, - profile_dict, - allow_overwrite=profile_allow_overwrite, - display_name=profile_display_name, - description=profile_description) + self._slicing_manager.save_profile("cura", + profile_name, + profile_dict, + allow_overwrite=profile_allow_overwrite, + display_name=profile_display_name, + description=profile_description) except octoprint.slicing.ProfileAlreadyExists: self._logger.warn("Profile {profile_name} already exists, aborting".format(**locals())) return flask.make_response("A profile named {profile_name} already exists for slicer cura".format(**locals()), 409) + if profile_make_default: + try: + self._slicing_manager.set_default_profile("cura", profile_name) + except octoprint.slicing.UnknownProfile: + self._logger.warn("Profile {profile_name} could not be set as default, aborting".format(**locals())) + return flask.make_response("The profile {profile_name} for slicer cura could not be set as default".format(**locals()), 500) + result = dict( resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True), + name=profile_name, displayName=profile_display_name, description=profile_description ) @@ -155,11 +187,12 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, ##~~ SlicerPlugin API def is_slicer_configured(self): - cura_engine = self._settings.get(["cura_engine"]) - if cura_engine is not None and os.path.exists(cura_engine): + cura_engine = normalize_path(self._settings.get(["cura_engine"])) + if self._is_engine_configured(cura_engine=cura_engine): return True else: self._logger.info("Path to CuraEngine has not been configured yet or does not exist (currently set to %r), Cura will not be selectable for slicing" % cura_engine) + return False def get_slicer_properties(self): return dict( @@ -227,15 +260,29 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, self._cura_logger.info(u"### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path)) - engine_settings = self._convert_to_engine(profile_path, printer_profile, posX, posY) - - executable = self._settings.get(["cura_engine"]) + executable = normalize_path(self._settings.get(["cura_engine"])) if not executable: return False, "Path to CuraEngine is not configured " - working_dir, _ = os.path.split(executable) + working_dir = os.path.dirname(executable) + + # Start building the argument list for the CuraEngine command execution args = [executable, '-v', '-p'] - for k, v in engine_settings.items(): + + # Get the CuraEngine version out of the "usage" line that is gotten when calling the CuraEngine with the -h argument + new_engine = self._is_new_engine_version(executable) + + # If the CuraEngine is the new version, add the JSON file path as argument + if new_engine: + args += ['-j', os.path.join(self._basefolder, "profiles", "fdmprinter.json")] + + profile = Profile(self._load_profile(profile_path), printer_profile, posX, posY) + + engine_settings = self._convert_to_engine(profile, new_engine=new_engine) + + # Add the settings (sorted alphabetically) to the command + + for k, v in sorted(engine_settings.items(), key=lambda s: s[0]): args += ["-s", "%s=%s" % (k, str(v))] args += ["-o", machinecode_path, model_path] @@ -318,6 +365,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, except: pass + # Get the filament usage + elif line.startswith(u"Filament:") or line.startswith(u"Filament2:"): if line.startswith(u"Filament:"): filament_str = line[len(u"Filament:"):].strip() @@ -328,17 +377,25 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, try: filament = int(filament_str) + if analysis is None: analysis = dict() if not "filament" in analysis: analysis["filament"] = dict() if not tool_key in analysis["filament"]: analysis["filament"][tool_key] = dict() - analysis["filament"][tool_key]["length"] = filament - if "filamentDiameter" in engine_settings: - radius_in_cm = float(int(engine_settings["filamentDiameter"]) / 10000.0) / 2.0 - filament_in_cm = filament / 10.0 - analysis["filament"][tool_key]["volume"] = filament_in_cm * math.pi * radius_in_cm * radius_in_cm + + if profile.get_float("filament_diameter") != None: + # The new CuraEngine outputs the "Filament" value as volume independently from the Gcode flavor + if new_engine: + analysis["filament"][tool_key] = _get_usage_from_volume(filament, profile.get_float("filament_diameter")) + # The old CuraEngine outputs the "Filament" value as volume only for ULTIGCODE and REPRAP_VOLUME + else: + if profile.get("gcode_flavor") == GcodeFlavors.ULTIGCODE or profile.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME: + analysis["filament"][tool_key] = _get_usage_from_volume(filament, profile.get_float("filament_diameter")) + else: + analysis["filament"][tool_key] = _get_usage_from_length(filament, profile.get_float("filament_diameter")) + except: pass finally: @@ -388,6 +445,11 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, profile_dict = yaml.safe_load(f) except: raise IOError("Couldn't read profile from {path}".format(path=path)) + + if "gcode_flavor" in profile_dict and not isinstance(profile_dict["gcode_flavor"], (list, tuple)): + profile_dict["gcode_flavor"] = parse_gcode_flavor(profile_dict["gcode_flavor"]) + self._save_profile(path, profile_dict) + return profile_dict def _save_profile(self, path, profile, allow_overwrite=True): @@ -395,9 +457,28 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, with octoprint.util.atomic_write(path, "wb") as f: yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True) - def _convert_to_engine(self, profile_path, printer_profile, posX, posY): - profile = Profile(self._load_profile(profile_path), printer_profile, posX, posY) - return profile.convert_to_engine() + def _convert_to_engine(self, profile, new_engine): + if new_engine: + return profile.convert_to_new_engine() + else: + return profile.convert_to_engine() + + def _is_new_engine_version(self, executable): + import sarge + + command = [executable, "-j", os.path.join(self._basefolder, "profiles", "fdmprinter.json")] + p = sarge.run(command, stdout=sarge.Capture(), stderr=sarge.Capture()) + if p.returncode != 0: + self._logger.warn("Could not run {} -j, returned {}".format(executable, p.returncode)) + self._logger.info(u"Assuming pre 15.06 version of CuraEngine.") + return False + + for line in p.stderr.read().split('\n'): + if "unknown option: j" in line.strip().lower(): + self._logger.info(u"Using pre 15.06 version of CuraEngine.") + return False + self._logger.info(u"Using post 15.06 version of CuraEngine.") + return True def _sanitize_name(name): if name is None: @@ -412,9 +493,39 @@ def _sanitize_name(name): sanitized_name = sanitized_name.replace(" ", "_") return sanitized_name.lower() +def _get_usage_from_volume(filament_volume, filament_diameter): + + # filament_volume is expressed in mm^3 + # usage["volume"] is in cm^3 and usage["length"] is in mm + + usage = dict() + usage["volume"] = filament_volume / 1000.0 + + radius_in_mm = filament_diameter / 2.0 + usage["length"] = filament_volume / (math.pi * radius_in_mm * radius_in_mm) + + return usage + +def _get_usage_from_length(filament_length, filament_diameter): + + # filament_length is expressed in mm + # usage["volume"] is in cm^3 and usage["length"] is in mm + + usage = dict() + usage["length"] = filament_length + + radius_in_cm = (filament_diameter / 10.0) / 2.0 + length_in_cm = filament_length / 10.0 + usage["volume"] = length_in_cm * math.pi * radius_in_cm * radius_in_cm + + return usage + __plugin_name__ = "CuraEngine (<= 15.04)" __plugin_author__ = "Gina Häußge" __plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura" __plugin_description__ = "Adds support for slicing via CuraEngine versions up to and including version 15.04 from within OctoPrint" __plugin_license__ = "AGPLv3" __plugin_implementation__ = CuraPlugin() + + + diff --git a/src/octoprint/plugins/cura/profile.py b/src/octoprint/plugins/cura/profile.py index 59a0ee152..6ab7b6b38 100644 --- a/src/octoprint/plugins/cura/profile.py +++ b/src/octoprint/plugins/cura/profile.py @@ -32,12 +32,12 @@ class MachineShapeTypes(object): CIRCULAR = "circular" class GcodeFlavors(object): - REPRAP = "reprap" - REPRAP_VOLUME = "reprap_volume" - ULTIGCODE = "ultigcode" - MAKERBOT = "makerbot" - BFB = "bfb" - MACH3 = "mach3" + REPRAP = (0, "reprap") + ULTIGCODE = (1, "ultigcode") + MAKERBOT = (2, "makerbot") + BFB = (3, "bfb") + MACH3 = (4, "mach3") + REPRAP_VOLUME = (5, "reprap_volume") defaults = dict( @@ -393,15 +393,45 @@ class Profile(object): } ) + # Translation dict for new CuraEngine option names + new_engine_options = dict( + fill_sparse_density="fill_density", + machine_nozzle_size="nozzle_size", + material_print_temperature="print_temperature", + #support_type="support", # In conflict with "support_type" from old CuraEngine + support_pattern="support_type", + adhesion_type="platform_adhesion", + material_diameter="filament_diameter", + material_flow="filament_flow", + speed_travel="travel_speed", + speed_layer_0="bottom_layer_speed", + speed_print="print_speed", + speed_infill="infill_speed", + speed_wall_0="outer_shell_speed", + speed_wall_x="inner_shell_speed", + cool_fan_enabled="fan_enabled", + cool_fan_full_at_height="fan_full_height", + cool_fan_speed="fan_speed", + cool_fan_speed_max="fan_speed_max", + cool_lift_head="cool_head_lift", + cool_min_speed="cool_min_feedrate", + machine_start_gcode="start_gcode", + machine_end_gcode="end_gcode", + machine_gcode_flavor="gcode_flavor") + result = dict() for section in config.sections(): - if not section in ("profile", "alterations"): + + if not section in ("profile", "alterations", "machine"): continue for option in config.options(section): ignored = False key = option + if section == "machine" and key != "gcode_flavor": + continue + # try to fetch the value in the correct type try: value = config.getboolean(section, option) @@ -438,9 +468,16 @@ class Profile(object): # if the key has to be translated to a new value, do that now key = translated_options[key] + if key in new_engine_options: + # if the key has to be translated from the new CuraEngine versions, do that now + key = new_engine_options[key] + if key in value_conversions and value in value_conversions[key]: value = value_conversions[key][value] + if key == "gcode_flavor": + value = parse_gcode_flavor(value) + if index is not None: # if we have an array to fill, make sure the target array exists and has the right size if not key in result: @@ -710,61 +747,70 @@ class Profile(object): return pre + str(f) - def get_gcode(self, key): - extruder_count = self.get_int("extruder_amount") - + def get_gcode(self, key, new_engine=False): prefix = "" postfix = "" if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE: if key == "end_gcode": - return "M25 ;Stop reading from this point on.\n;CURA_PROFILE_STRING:%s\n" % (self.get_profile_string()) + return "M25 ;Stop reading from this point on.\n;CURA_OCTO_PROFILE_STRING:%s\n" % (self.get_profile_string()) return "" if key == "start_gcode": contents = self.get_gcode_template("start_gcode") - e_steps = self.get_float("steps_per_e") - if e_steps > 0: - prefix += "M92 E{e_steps}\n" % (e_steps) - temp = self.get_float("print_temperature") - - bed_temp = 0 - if self.get_boolean("has_heated_bed"): - bed_temp = self.get_float("print_bed_temperature") - include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents) - - if include_bed_temp: - prefix += "M140 S{bed_temp}\n".format(bed_temp=bed_temp) - - if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents): - if extruder_count > 0: - def temp_line(temp, extruder, template): - t = temp - if extruder > 0: - print_temp = self.get_float("print_temperature%d" % (extruder + 1)) - if print_temp > 0: - t = print_temp - return template.format(extruder=extruder, temp=t) - - prefix_preheat = "" - prefix_waitheat = "" - for n in xrange(0, extruder_count): - if n > 0: - prefix_preheat += temp_line(temp, n, "M104 T{extruder} S{temp}\n") - prefix_waitheat += temp_line(temp, n, "M109 T{extruder} S{temp}\n") - prefix += prefix_preheat + prefix_waitheat + "T0\n" - else: - prefix += "M109 S{temp}\n".format(temp=temp) - - if include_bed_temp: - prefix += "M190 S{bed_temp}\n".format(bed_temp=bed_temp) + # If using the new CuraEngine, there is no need to extend the start_gcode + if not new_engine: + prefix += self.get_start_gcode_prefix(contents) else: contents = self.get_gcode_template(key) return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n' + def get_start_gcode_prefix(self, contents): + extruder_count = self.get_int("extruder_amount") + + prefix = "" + + e_steps = self.get_float("steps_per_e") + if e_steps > 0: + prefix += "M92 E{e_steps}\n" % (e_steps) + temp = self.get_float("print_temperature") + + bed_temp = 0 + if self.get_boolean("has_heated_bed"): + bed_temp = self.get_float("print_bed_temperature") + include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents) + + if include_bed_temp: + prefix += "M140 S{bed_temp}\n".format(bed_temp=bed_temp) + + if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents): + if extruder_count > 0: + def temp_line(temp, extruder, template): + t = temp + if extruder > 0: + print_temp = self.get_float("print_temperature%d" % (extruder + 1)) + if print_temp > 0: + t = print_temp + return template.format(extruder=extruder, temp=t) + + prefix_preheat = "" + prefix_waitheat = "" + for n in xrange(0, extruder_count): + if n > 0: + prefix_preheat += temp_line(temp, n, "M104 T{extruder} S{temp}\n") + prefix_waitheat += temp_line(temp, n, "M109 T{extruder} S{temp}\n") + prefix += prefix_preheat + prefix_waitheat + "T0\n" + else: + prefix += "M109 S{temp}\n".format(temp=temp) + + if include_bed_temp: + prefix += "M190 S{bed_temp}\n".format(bed_temp=bed_temp) + + return prefix + def calculate_edge_width_and_line_count(self): wall_thickness = self.get_float("wall_thickness") nozzle_size = self._printer_profile["extruder"]["nozzleDiameter"] @@ -810,20 +856,20 @@ class Profile(object): def get_pos_x(self): if self._posX: try: - return int(float(self._posX) * 1000) + return int(float(self._posX)) except ValueError: pass - return int(self.get_float("machine_width") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0 + return int(self.get_float("machine_width") / 2.0 ) if not self.get_boolean("machine_center_is_zero") else 0.0 def get_pos_y(self): if self._posY: try: - return int(float(self._posY) * 1000) + return int(float(self._posY)) except ValueError: pass - return int(self.get_float("machine_depth") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0 + return int(self.get_float("machine_depth") / 2.0) if not self.get_boolean("machine_center_is_zero") else 0.0 def convert_to_engine(self): @@ -873,8 +919,8 @@ class Profile(object): "coolHeadLift": 1 if self.get_boolean("cool_head_lift") else 0, # model positioning - "posx": self.get_pos_x(), - "posy": self.get_pos_y(), + "posx": self.get_pos_x() * 1000, # in microns + "posy": self.get_pos_y() * 1000, # in microns # gcodes "startCode": self.get_gcode("start_gcode"), @@ -953,16 +999,7 @@ class Profile(object): settings["layerThickness"] = 1000 # gcode flavor - if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE: - settings["gcodeFlavor"] = 1 - elif self.get("gcode_flavor") == GcodeFlavors.MAKERBOT: - settings["gcodeFlavor"] = 2 - elif self.get("gcode_flavor") == GcodeFlavors.BFB: - settings["gcodeFlavor"] = 3 - elif self.get("gcode_flavor") == GcodeFlavors.MACH3: - settings["gcodeFlavor"] = 4 - elif self.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME: - settings["gcodeFlavor"] = 5 + settings["gcodeFlavor"] = self.get("gcode_flavor")[0] # extras if self.get_boolean("spiralize"): @@ -978,3 +1015,132 @@ class Profile(object): settings["enableOozeShield"] = 1 return settings + + def convert_to_new_engine(self): + + settings = { + "layer_height": self.get_float("layer_height"), + "wall_thickness": self.get_float("wall_thickness"), + "retraction_enable": self.get_boolean("retraction_enable"), + "top_bottom_thickness": self.get_float("solid_layer_thickness"), + "fill_sparse_density": self.get_float("fill_density"), + "machine_nozzle_size": self.get_float("nozzle_size"), + "speed_print": self.get_float("print_speed"), + "material_print_temperature": self.get_float("print_temperature"), + "material_diameter": self.get_float("filament_diameter"), + "material_flow": self.get_float("filament_flow"), + "retraction_speed": self.get_float("retraction_speed"), + "retraction_amount": self.get_float("retraction_amount") if self.get_boolean("retraction_enable") else 0, + "retraction_min_travel": self.get_float("retraction_min_travel"), + "retraction_combing": self.get_boolean("retraction_combing"), + "retraction_hop": self.get_float("retraction_hop"), + "bottom_thickness": self.get_float("bottom_thickness"), + "top_layers": self.calculate_solid_layer_count(), + "bottom_layers": self.calculate_solid_layer_count(), + "speed_travel": self.get_float("travel_speed"), + "speed_layer_0": self.get_float("bottom_layer_speed"), + "speed_infill": self.get_float("infill_speed") if self.get_float("infill_speed") > 0 else self.get_float("print_speed"), + "speed_wall_0": self.get_float("outer_shell_speed") if self.get_float("outer_shell_speed") > 0 else self.get_float("print_speed"), # Translated from "inset0_speed" + "speed_wall_x": self.get_float("inner_shell_speed") if self.get_float("inner_shell_speed") > 0 else self.get_float("print_speed"), # Translated from "insetx_speed" + "cool_min_layer_time": self.get_float("cool_min_layer_time"), + "cool_fan_enabled": self.get_boolean("fan_enabled"), + "cool_fan_full_at_height": self.get_int("fan_full_height"), + "cool_fan_speed": self.get_float("fan_speed"), + "cool_fan_speed_max": self.get_float("fan_speed_max") if self.get_boolean("fan_enabled") else 0, + "cool_lift_head": self.get_boolean("cool_head_lift"), + "cool_min_speed": self.get_float("cool_min_feedrate"), + "skirt_line_count": self.get_int("skirt_line_count"), + "fill_overlap": self.get_float("fill_overlap"), + "magic_spiralize": self.get_boolean("spiralize"), + + # machine settings + + "machine_width": self.get_float("machine_width"), + "machine_depth": self.get_float("machine_depth"), + "machine_center_is_zero": self.get_boolean("machine_center_is_zero"), + "machine_heated_bed": self.get_boolean("has_heated_bed"), + + # gcodes + + "machine_start_gcode": self.get_gcode("start_gcode", new_engine=True), + "machine_end_gcode": self.get_gcode("end_gcode", new_engine=True), + } + + # gcode flavor + + settings["machine_gcode_flavor"] = self.get("gcode_flavor")[0] + + # heated bed - The new CuraEngine uses the integer "material_bed_temperature" instead of the boolean "machine_heated_bed" + + if self.get_boolean("has_heated_bed"): + settings["material_bed_temperature"] = self.get_float("print_bed_temperature") + else: + settings["material_bed_temperature"] = 0 + + # support + + if self.get("support") == SupportLocationTypes.NONE: + settings["support_enable"] = False + else: + settings["support_enable"] = True + settings["support_angle"] = self.get_float("support_angle") + settings["support_fill_rate"] = self.get_float("support_fill_rate") + settings["support_xy_distance"] = self.get_float("support_xy_distance") + settings["support_z_distance"] = self.get_float("support_z_distance") + + # support type + + if self.get("support") == SupportLocationTypes.TOUCHING_BUILDPLATE: + settings["support_type"] = "Touching Buildplate" + elif self.get("support") == SupportLocationTypes.EVERYWHERE: + settings["support_type"] = "Everywhere" + + # support pattern + + if self.get("support_type") == SupportTypes.GRID: + settings["support_pattern"] = "Grid" + elif self.get("support_type") == SupportTypes.LINES: + settings["support_pattern"] = "Lines" + + # adhesion type + + if self.get("platform_adhesion") == PlatformAdhesionTypes.NONE: + settings["adhesion_type"] = "None" + elif self.get("platform_adhesion") == PlatformAdhesionTypes.BRIM: + settings["adhesion_type"] = "Brim" + settings["brim_line_count"] = self.get_int("brim_line_count") + elif self.get("platform_adhesion") == PlatformAdhesionTypes.RAFT: + settings["adhesion_type"] = "Raft" + settings["raft_margin"] = self.get_int("raft_margin") + settings["raft_line_spacing"] = self.get_float("raft_line_spacing") + settings["raft_base_thickness"] = self.get_float("raft_base_thickness") + settings["raft_base_linewidth"] = self.get_float("raft_base_linewidth") + settings["raft_interface_thickness"] = self.get_float("raft_interface_thickness") + settings["raft_interface_linewidth"] = self.get_float("raft_interface_linewidth") + settings["raft_airgap"] = self.get_float("raft_airgap") + settings["raft_surface_layers"] = self.get_int("raft_surface_layers") + + # skirt + + if self.get_int("skirt_line_count") != 0: + settings["skirt_gap"] = self.get_float("skirt_gap") + settings["skirt_minimal_length"] = self.get_float("skirt_minimal_length") + + return settings + +def parse_gcode_flavor(value): + + value = value.lower() + + if "reprap" in value and ("volume" in value or "volumatric" in value): + return GcodeFlavors.REPRAP_VOLUME + elif "ultigcode" in value: + return GcodeFlavors.ULTIGCODE + elif "makerbot" in value: + return GcodeFlavors.MAKERBOT + elif "bfb" in value: + return GcodeFlavors.BFB + elif "mach3" in value: + return GcodeFlavors.MACH3 + else: + return GcodeFlavors.REPRAP diff --git a/src/octoprint/plugins/cura/profiles/fdmprinter.json b/src/octoprint/plugins/cura/profiles/fdmprinter.json new file mode 100644 index 000000000..366149b9c --- /dev/null +++ b/src/octoprint/plugins/cura/profiles/fdmprinter.json @@ -0,0 +1,1325 @@ +{ + "visible": false, + "machine_settings": { + "machine_start_gcode": { + "default": "G28 ; Home\nG1 Z15.0 F6000 ;move the platform down 15mm\n;Prime the extruder\nG92 E0\nG1 F200 E3\nG92 E0" + }, + "machine_end_gcode": { + "default": "M104 S0\nM140 S0\n;Retract the filament\nG92 E1\nG1 E-1 F300\nG28 X0 Y0\nM84" + }, + "machine_width": { "default": 230 }, + "machine_depth": { "default": 225 }, + "machine_height": { "default": 205 }, + "machine_heated_bed": { "default": true }, + + "machine_center_is_zero": { "default": false }, + "machine_nozzle_size": { "default": 0.4 }, + "machine_head_shape_min_x": { "default": 40 }, + "machine_head_shape_min_y": { "default": 10 }, + "machine_head_shape_max_x": { "default": 60 }, + "machine_head_shape_max_y": { "default": 30 }, + "machine_nozzle_gantry_distance": { "default": 55 }, + "machine_nozzle_offset_x_1": { "default": 18.0 }, + "machine_nozzle_offset_y_1": { "default": 0.0 }, + "machine_gcode_flavor": { "default": "UltiGCode" }, + "machine_disallowed_areas": { "default": [ + [[-115.0, 112.5], [ -82.0, 112.5], [ -84.0, 104.5], [-115.0, 104.5]], + [[ 115.0, 112.5], [ 115.0, 104.5], [ 110.0, 104.5], [ 108.0, 112.5]], + [[-115.0, -112.5], [-115.0, -104.5], [ -84.0, -104.5], [ -82.0, -112.5]], + [[ 115.0, -112.5], [ 108.0, -112.5], [ 110.0, -104.5], [ 115.0, -104.5]] + ]}, + "machine_platform_offset": { "default": [9.0, 0.0, 0.0] }, + + "machine_nozzle_tip_outer_diameter": { "default": 1.0 }, + "machine_nozzle_head_distance": { "default": 3.0 }, + "machine_nozzle_expansion_angle": { "default": 45 } + }, + "categories": { + "resolution": { + "label": "Quality", + "visible": true, + "icon": "category_quality", + "settings": { + "layer_height": { + "label": "Layer Height", + "description": "The height of each layer, in mm. Normal quality prints are 0.1mm, high quality is 0.06mm. You can go up to 0.25mm with an Ultimaker for very fast prints at low quality. For most purposes, layer heights between 0.1 and 0.2mm give a good tradeoff of speed and surface finish.", + "unit": "mm", + "type": "float", + "default": 0.1, + "min_value": 0.06, + "max_value": 2.0, + "always_visible": true, + "children": { + "layer_height_0": { + "label": "Initial Layer Thickness", + "description": "The layer thickness of the bottom layer. A thicker bottom layer makes sticking to the bed easier.", + "unit": "mm", + "type": "float", + "default": 0.2, + "min_value": 0.06, + "max_value": 2.0, + "visible": false + } + } + }, + "shell_thickness": { + "label": "Shell Thickness", + "description": "The thickness of the outside shell in the horizontal and vertical direction. This is used in combination with the nozzle size to define the number of perimeter lines and the thickness of those perimeter lines. This is also used to define the number of solid top and bottom layers.", + "unit": "mm", + "type": "float", + "default": 0.8, + "min_value": 0.0, + "max_value": 5.0, + "children": { + "wall_thickness": { + "label": "Wall Thickness", + "description": "The thickness of the outside walls in the horizontal direction. This is used in combination with the nozzle size to define the number of perimeter lines and the thickness of those perimeter lines.", + "unit": "mm", + "default": 0.8, + "min_value": 0.0, + "max_value": 5.0, + "min_value_warning": 0.4, + "max_value_warning": 2.0, + "type": "float", + "visible": false, + + "children": { + "wall_line_count": { + "label": "Wall Line Count", + "description": "Number of shell lines. This these lines are called perimeter lines in other tools and impact the strength and structural integrity of your print.", + "default": 2, + "type": "int", + "visible": false, + "inherit_function": "max(1, (int(parent_value / (machine_nozzle_size - 0.0001) + 1) if (parent_value / max(1, int(parent_value / (machine_nozzle_size - 0.0001))) > machine_nozzle_size) * 1.5 else int(parent_value / (machine_nozzle_size - 0.0001))))" + }, + "wall_line_width": { + "label": "Wall Line Width", + "description": "Width of a single shell line. Each line of the shell will be printed with this width in mind.", + "unit": "mm", + "default": 0.4, + "type": "float", + "visible": false, + "inherit_function": "max(machine_nozzle_size, (parent_value / (int(parent_value / (machine_nozzle_size - 0.0001) + 1))) if (parent_value / (int(parent_value / (machine_nozzle_size - 0.0001))) > machine_nozzle_size * 1.5) else (parent_value / int(parent_value / (machine_nozzle_size - 0.0001))))", + + "children": { + "wall_line_width_0": { + "label": "First Wall Line Width", + "description": "Width of the outermost shell line. By printing a thinner outermost wall line you can print higher details with a larger nozzle.", + "unit": "mm", + "default": 0.4, + "type": "float", + "visible": false + }, + "wall_line_width_x": { + "label": "Other Walls Line Width", + "description": "Width of a single shell line for all shell lines except the outermost one.", + "unit": "mm", + "default": 0.4, + "type": "float", + "visible": false + }, + "skirt_line_width": { + "label": "Skirt line width", + "description": "Width of a single skirt line.", + "unit": "mm", + "default": 0.4, + "type": "float", + "visible": false + }, + "skin_line_width": { + "label": "Top/bottom line width", + "description": "Width of a single top/bottom printed line. Which are used to fill up the top/bottom areas of a print.", + "unit": "mm", + "default": 0.4, + "type": "float", + "visible": false + }, + "infill_line_width": { + "label": "Infill line width", + "description": "Width of the inner infill printed lines.", + "unit": "mm", + "default": 0.4, + "type": "float", + "visible": false + }, + "support_line_width": { + "label": "Support line width", + "description": "Width of the printed support structures lines.", + "unit": "mm", + "default": 0.4, + "type": "float", + "visible": false + } + } + } + } + }, + "alternate_extra_perimeter": { + "label": "Alternate Extra Wall", + "description": "Make an extra wall at every second layer, so that infill will be caught between an extra wall above and one below. This results in a better cohesion between infill and walls, but might have an impact on the surface quality.", + "type": "boolean", + "default": false, + "visible": false + }, + "top_bottom_thickness": { + "label": "Bottom/Top Thickness", + "description": "This controls the thickness of the bottom and top layers, the amount of solid layers put down is calculated by the layer thickness and this value. Having this value a multiple of the layer thickness makes sense. And keep it near your wall thickness to make an evenly strong part.", + "unit": "mm", + "default": 0.8, + "min_value": 0.0, + "max_value": 5.0, + "min_value_warning": 0.4, + "max_value_warning": 1.0, + "type": "float", + "visible": false, + + "children": { + "top_thickness": { + "label": "Top Thickness", + "description": "This controls the thickness of the top layers. The number of solid layers printed is calculated from the layer thickness and this value. Having this value be a multiple of the layer thickness makes sense. And keep it nearto your wall thickness to make an evenly strong part.", + "unit": "mm", + "default": 0.8, + "type": "float", + "visible": false, + + "children": { + "top_layers": { + "label": "Top Layers", + "description": "This controls the amount of top layers.", + "default": 8, + "type": "int", + "visible": false, + "inherit_function": "math.ceil(parent_value / layer_height)" + } + } + }, + "bottom_thickness": { + "label": "Bottom Thickness", + "description": "This controls the thickness of the bottom layers. The number of solid layers printed is calculated from the layer thickness and this value. Having this value be a multiple of the layer thickness makes sense. And keep it near to your wall thickness to make an evenly strong part.", + "unit": "mm", + "default": 0.8, + "type": "float", + "visible": false, + + "children": { + "bottom_layers": { + "label": "Bottom Layers", + "description": "This controls the amount of bottom layers.", + "default": 8, + "type": "int", + "visible": false, + "inherit_function": "math.ceil(parent_value / layer_height)" + } + } + } + } + } + } + }, + "wall_overlap_avoid_enabled": { + "label": "Avoid Overlapping Walls", + "description": "Remove parts of a wall which share an overlap which would result in overextrusion in some places. These overlaps occur in thin pieces in a model and sharp corners.", + "type": "boolean", + "default": true, + "visible": false + }, + "fill_perimeter_gaps":{ + "label": "Fill Gaps Between Walls", + "description": "Fill the gaps created by walls where they would otherwise be overlapping. This will also fill thin walls. Optionally only the gaps occurring within the top and bottom skin can be filled.", + "type": "enum", + "options": [ + "Nowhere", + "Everywhere", + "Skin" + ], + "default": "Everywhere", + "visible": false, + "active_if": { + "setting": "wall_overlap_avoid_enabled", + "value": true + } + }, + "top_bottom_pattern": { + "label": "Bottom/Top Pattern", + "description": "Pattern of the top/bottom solid fill. This normally is done with lines to get the best possible finish, but in some cases a concentric fill gives a nicer end result.", + "type": "enum", + "options": [ + "Lines", + "Concentric" + ], + "default": "Lines", + "visible": false + }, + "skin_outline_count": { + "label": "Skin Perimeter Line Count", + "description": "Number of lines around skin regions. Using one or two skin perimeter lines can greatly improve on roofs which would start in the middle of infill cells.", + "default": 0, + "type": "int", + "visible": false, + "active_if": { + "setting": "top_bottom_pattern", + "value": "Lines" + } + }, + "xy_offset": { + "label": "Horizontal expansion", + "description": "Amount of offset applied all polygons in each layer. Positive values can compensate for too big holes; negative values can compensate for too small holes.", + "unit": "mm", + "type": "float", + "default": 0.0, + "visible": false + + } + } + }, + + "material": { + "label": "Material", + "visible": true, + "icon": "category_material", + "settings": { + "material_print_temperature": { + "label": "Printing Temperature", + "description": "The temperature used for printing. Set at 0 to pre-heat yourself. For PLA a value of 210C is usually used.\nFor ABS a value of 230C or higher is required.", + "unit": "°C", + "type": "float", + "default": 220, + "min_value": 10, + "max_value": 340 + }, + "material_bed_temperature": { + "label": "Bed Temperature", + "description": "The temperature used for the heated printer bed. Set at 0 to pre-heat it yourself.", + "unit": "°C", + "type": "float", + "default": 70, + "min_value": 0, + "max_value": 340 + }, + "material_diameter": { + "label": "Diameter", + "description": "The diameter of your filament needs to be measured as accurately as possible.\nIf you cannot measure this value you will have to calibrate it, a higher number means less extrusion, a smaller number generates more extrusion.", + "unit": "mm", + "type": "float", + "default": 2.85, + "min_value": 0.4, + "max_value": 5.0 + }, + "material_flow": { + "label": "Flow", + "description": "Flow compensation: the amount of material extruded is multiplied by this value.", + "unit": "%", + "default": 100.0, + "type": "float", + "min_value": 5.0, + "max_value": 300.0 + }, + "retraction_enable": { + "label": "Enable Retraction", + "description": "Retract the filament when the nozzle is moving over a non-printed area. Details about the retraction can be configured in the advanced tab.", + "type": "boolean", + "default": true, + + "children": { + "retraction_speed": { + "label": "Retraction Speed", + "description": "The speed at which the filament is retracted. A higher retraction speed works better, but a very high retraction speed can lead to filament grinding.", + "unit": "mm/s", + "type": "float", + "default": 25.0, + "visible": false, + "inherit": false, + + "children": { + "retraction_retract_speed": { + "label": "Retraction Retract Speed", + "description": "The speed at which the filament is retracted. A higher retraction speed works better, but a very high retraction speed can lead to filament grinding.", + "unit": "mm/s", + "type": "float", + "default": 25.0, + "visible": false + }, + "retraction_prime_speed": { + "label": "Retraction Prime Speed", + "description": "The speed at which the filament is pushed back after retraction.", + "unit": "mm/s", + "type": "float", + "default": 25.0, + "visible": false + } + } + }, + "retraction_amount": { + "label": "Retraction Distance", + "description": "The amount of retraction: Set at 0 for no retraction at all. A value of 4.5mm seems to generate good results for 3mm filament in Bowden-tube fed printers.", + "unit": "mm", + "type": "float", + "default": 4.5, + "visible": false, + "inherit": false + }, + "retraction_min_travel": { + "label": "Retraction Minimum Travel", + "description": "The minimum distance of travel needed for a retraction to happen at all. This helps ensure you do not get a lot of retractions in a small area.", + "unit": "mm", + "type": "float", + "default": 4.5, + "visible": false, + "inherit": false + }, + "retraction_combing": { + "label": "Enable Combing", + "description": "Combing keeps the head within the interior of the print whenever possible when traveling from one part of the print to another, and does not use retraction. If combing is disabled the printer head moves straight from the start point to the end point and it will always retract.", + "type": "boolean", + "default": true, + "visible": false, + "inherit": false + }, + "retraction_count_max": { + "label": "Maximal Retraction Count", + "description": "This settings limits the number of retractions occuring within the Minimal Extrusion Distance Window. Further retractions within this window will be ignored. This avoids retracting repeatedly on the same piece of filament as that can flatten the filament and cause grinding issues.", + "default": 6, + "type": "int", + "visible": false, + "inherit": false + }, + "retraction_extrusion_window": { + "label": "Minimal Extrusion Distance Window", + "description": "The window in which the Maximal Retraction Count is enforced. This window should be approximately the size of the Retraction distance, so that effectively the number of times a retraction passes the same patch of material is limited.", + "unit": "mm", + "type": "float", + "default": 4.5, + "visible": false, + "inherit_function": "retraction_amount" + }, + "retraction_hop": { + "label": "Z Hop when Retracting", + "description": "Whenever a retraction is done, the head is lifted by this amount to travel over the print. A value of 0.075 works well. This feature has a lot of positive effect on delta towers.", + "unit": "mm", + "type": "float", + "default": 0.0, + "visible": false, + "inherit": false + } + } + } + } + }, + "speed": { + "label": "Speed", + "visible": true, + "icon": "category_speed", + "settings": { + "speed_print": { + "label": "Print Speed", + "description": "The speed at which printing happens. A well-adjusted Ultimaker can reach 150mm/s, but for good quality prints you will want to print slower. Printing speed depends on a lot of factors, so you will need to experiment with optimal settings for this.", + "unit": "mm/s", + "type": "float", + "default": 50.0, + + "children": { + "speed_infill": { + "label": "Infill Speed", + "description": "The speed at which infill parts are printed. Printing the infill faster can greatly reduce printing time, but this can negatively affect print quality.", + "unit": "mm/s", + "type": "float", + "default": 50.0, + "visible": false + }, + "speed_wall": { + "label": "Shell Speed", + "description": "The speed at which shell is printed. Printing the outer shell at a lower speed improves the final skin quality.", + "unit": "mm/s", + "type": "float", + "default": 50.0, + "visible": false, + + "children": { + "speed_wall_0": { + "label": "Outer Shell Speed", + "description": "The speed at which outer shell is printed. Printing the outer shell at a lower speed improves the final skin quality. However, having a large difference between the inner shell speed and the outer shell speed will effect quality in a negative way.", + "unit": "mm/s", + "type": "float", + "default": 50.0, + "visible": false + }, + "speed_wall_x": { + "label": "Inner Shell Speed", + "description": "The speed at which all inner shells are printed. Printing the inner shell fasster than the outer shell will reduce printing time. It is good to set this in between the outer shell speed and the infill speed.", + "unit": "mm/s", + "type": "float", + "default": 50.0, + "visible": false + } + } + }, + "speed_topbottom": { + "label": "Top/Bottom Speed", + "description": "Speed at which top/bottom parts are printed. Printing the top/bottom faster can greatly reduce printing time, but this can negatively affect print quality.", + "unit": "mm/s", + "type": "float", + "default": 50.0, + "visible": false + }, + "speed_support": { + "label": "Support Speed", + "description": "The speed at which exterior support is printed. Printing exterior supports at higher speeds can greatly improve printing time. And the surface quality of exterior support is usually not important, so higher speeds can be used.", + "unit": "mm/s", + "type": "float", + "default": 50.0, + "visible": false, + "inherit_function": "speed_wall_0" + } + } + }, + "speed_travel": { + "label": "Travel Speed", + "description": "The speed at which travel moves are done. A well-built Ultimaker can reach speeds of 250mm/s. But some machines might have misaligned layers then.", + "unit": "mm/s", + "type": "float", + "default": 150.0 + }, + "speed_layer_0": { + "label": "Bottom Layer Speed", + "description": "The print speed for the bottom layer: You want to print the first layer slower so it sticks to the printer bed better.", + "unit": "mm/s", + "type": "float", + "default": 15.0, + "visible": false, + + "children": { + "skirt_speed": { + "label": "Skirt Speed", + "description": "The speed at which the skirt and brim are printed. Normally this is done at the initial layer speed. But sometimes you want to print the skirt at a different speed.", + "unit": "mm/s", + "type": "float", + "default": 15.0, + "visible": false + } + } + }, + "speed_slowdown_layers": { + "label": "Amount of Slower Layers", + "description": "The first few layers are printed slower then the rest of the object, this to get better adhesion to the printer bed and improve the overall success rate of prints. The speed is gradually increased over these layers. 4 layers of speed-up is generally right for most materials and printers.", + "type": "int", + "default": 4, + "visible": false + } + } + }, + "infill": { + "label": "Infill", + "visible": true, + "icon": "category_infill", + "settings": { + "fill_sparse_density": { + "label": "Infill Density", + "description": "This controls how densely filled the insides of your print will be. For a solid part use 100%, for an hollow part use 0%. A value around 20% is usually enough. This won't affect the outside of the print and only adjusts how strong the part becomes.", + "unit": "%", + "type": "float", + "default": 20.0, + + "children": { + "fill_pattern": { + "label": "Infill Pattern", + "description": "Cura defaults to switching between grid and line infill. But with this setting visible you can control this yourself. The line infill swaps direction on alternate layers of infill, while the grid prints the full cross-hatching on each layer of infill.", + "type": "enum", + "visible": false, + "options": [ + "Grid", + "Lines", + "Concentric", + "ZigZag" + ], + "default": "Grid", + "inherit_function": "'Lines' if parent_value > 25 else 'Grid'" + }, + "infill_line_distance": { + "label": "Line distance", + "description": "Distance between the printed infill lines.", + "unit": "mm", + "type": "float", + "default": 2.0, + "visible": false, + "inherit_function": "(infill_line_width * 100) / parent_value" + } + } + }, + "fill_overlap": { + "label": "Infill Overlap", + "description": "The amount of overlap between the infill and the walls. A slight overlap allows the walls to connect firmly to the infill.", + "unit": "%", + "type": "float", + "default": 15.0, + "visible": false + }, + "fill_sparse_thickness": { + "label": "Infill Thickness", + "description": "The thickness of the sparse infill. This is rounded to a multiple of the layerheight and used to print the sparse-infill in fewer, thicker layers to save printing time.", + "unit": "mm", + "type": "float", + "default": 0.1, + "visible": false, + + "children": { + "fill_sparse_combine": { + "label": "Infill Layers", + "description": "Amount of layers that are combined together to form sparse infill.", + "type": "int", + "default": 1, + "visible": false, + "inherit_function": "math.floor((parent_value + 0.001) / layer_height)" + } + } + } + } + }, + "cooling": { + "label": "Cooling", + "visible": true, + "icon": "category_cool", + "settings": { + "cool_fan_enabled": { + "label": "Enable Cooling Fan", + "description": "Enable the cooling fan during the print. The extra cooling from the cooling fan helps parts with small cross sections that print each layer quickly.", + "type": "boolean", + "default": true, + + "children": { + "cool_fan_speed": { + "label": "Fan Speed", + "description": "Fan speed used for the print cooling fan on the printer head.", + "unit": "%", + "type": "float", + "default": 100.0, + "visible": false, + "inherit_function": "100.0 if parent_value else 0.0", + + "children": { + "cool_fan_speed_min": { + "label": "Minimum Fan Speed", + "description": "Normally the fan runs at the minimum fan speed. If the layer is slowed down due to minimum layer time, the fan speed adjusts between minimum and maximum fan speed.", + "unit": "%", + "type": "float", + "default": 100.0, + "visible": false + }, + "cool_fan_speed_max": { + "label": "Maximum Fan Speed", + "description": "Normally the fan runs at the minimum fan speed. If the layer is slowed down due to minimum layer time, the fan speed adjusts between minimum and maximum fan speed.", + "unit": "%", + "type": "float", + "default": 100.0, + "visible": false + } + } + } + } + }, + "cool_fan_full_at_height": { + "label": "Fan Full on at Height", + "description": "The height at which the fan is turned on completely. For the layers below this the fan speed is scaled linearly with the fan off for the first layer.", + "unit": "mm", + "type": "float", + "default": 0.5, + "visible": false, + + "children": { + "cool_fan_full_layer": { + "label": "Fan Full on at Layer", + "description": "The layer number at which the fan is turned on completely. For the layers below this the fan speed is scaled linearly with the fan off for the first layer.", + "type": "int", + "default": 4, + "visible": false, + "inherit_function": "int((parent_value - layer_height_0 + 0.001) / layer_height)" + } + } + }, + "cool_min_layer_time": { + "label": "Minimal Layer Time", + "description": "The minimum time spent in a layer: Gives the layer time to cool down before the next one is put on top. If a layer would print in less time, then the printer will slow down to make sure it has spent at least this many seconds printing the layer.", + "unit": "sec", + "type": "float", + "default": 5.0, + "visible": false + }, + "cool_min_layer_time_fan_speed_max": { + "label": "Minimal Layer Time Full Fan Speed", + "description": "The minimum time spent in a layer which will cause the fan to be at minmum speed. The fan speed increases linearly from maximal fan speed for layers taking minimal layer time to minimal fan speed for layers taking the time specified here.", + "unit": "sec", + "type": "float", + "default": 10.0, + "visible": false + }, + "cool_min_speed": { + "label": "Minimum Speed", + "description": "The minimum layer time can cause the print to slow down so much it starts to droop. The minimum feedrate protects against this. Even if a print gets slowed down it will never be slower than this minimum speed.", + "unit": "mm/s", + "type": "float", + "default": 10.0, + "visible": false + }, + "cool_lift_head": { + "label": "Lift Head", + "description": "Lift the head away from the print if the minimum speed is hit because of cool slowdown, and wait the extra time away from the print surface until the minimum layer time is used up.", + "type": "boolean", + "default": false, + "visible": false + } + } + }, + "support": { + "label": "Support", + "visible": true, + "icon": "category_support", + "settings": { + "support_enable": { + "label": "Enable Support", + "description": "Enable exterior support structures. This will build up supporting structures below the model to prevent the model from sagging or printing in mid air.", + "type": "boolean", + "default": true + }, + "support_type": { + "label": "Placement", + "description": "Where to place support structures. The placement can be restricted such that the support structures won't rest on the model, which could otherwise cause scarring.", + "type": "enum", + "options": [ + "Touching Buildplate", + "Everywhere" + ], + "default": "Touching Buildplate", + "visible": true, + "inherit_function": "'Everywhere' if support_enable else 'None'", + "active_if": { + "setting": "support_enable", + "value": true + } + }, + "support_angle": { + "label": "Overhang Angle", + "description": "The maximum angle of overhangs for which support will be added. With 0 degrees being horizontal, and 90 degrees being vertical.", + "unit": "°", + "type": "float", + "default": 60.0, + "visible": false, + "active_if": { + "setting": "support_enable", + "value": true + } + }, + "support_xy_distance": { + "label": "X/Y Distance", + "description": "Distance of the support structure from the print, in the X/Y directions. 0.7mm typically gives a nice distance from the print so the support does not stick to the surface.", + "unit": "mm", + "type": "float", + "default": 0.7, + "visible": false, + "active_if": { + "setting": "support_enable", + "value": true + } + }, + "support_z_distance": { + "label": "Z Distance", + "description": "Distance from the top/bottom of the support to the print. A small gap here makes it easier to remove the support but makes the print a bit uglier. 0.15mm allows for easier separation of the support structure.", + "unit": "mm", + "type": "float", + "default": 0.15, + "visible": false, + "active_if": { + "setting": "support_enable", + "value": true + }, + + "children": { + "support_top_distance": { + "label": "Top Distance", + "description": "Distance from the top of the support to the print.", + "unit": "mm", + "default": 0.15, + "type": "float", + "visible": false + }, + "support_bottom_distance": { + "label": "Bottom Distance", + "description": "Distance from the print to the bottom of the support.", + "unit": "mm", + "default": 0.15, + "type": "float", + "visible": false + } + } + }, + "support_bottom_stair_step_height": { + "label": "Stair Step Height", + "description": "The height of the steps of the stair-like bottom of support resting on the model. Small steps can cause the support to be hard to remove from the top of the model.", + "unit": "mm", + "type": "float", + "default": 0.5, + "visible": false, + "active_if": { + "setting": "support_type", + "value": "Everywhere" + } + }, + "support_join_distance": { + "label": "Join Distance", + "description": "The maximum distance between support blocks, in the X/Y directions, such that the blocks will merge into a single block.", + "unit": "mm", + "type": "float", + "default": 0.7, + "visible": false + }, + "support_area_smoothing": { + "label": "Area Smoothing", + "description": "Maximal distance in the X/Y directions of a line segment which is to be smoothed out. Ragged lines are introduced by the join distance and support bridge, which cause the machine to resonate. Smoothing the support areas won't cause them to break with the constraints, except it might change the overhang.", + "unit": "mm", + "type": "float", + "default": 0.6, + "visible": false + }, + "support_use_towers": { + "label": "Use towers.", + "description": "Use specialized towers to support tiny overhang areas. These towers have a larger diameter than the region they support. Near the overhang the towers' diameter decreases, forming a roof.", + "type": "boolean", + "default": true, + "visible": true + }, + "support_minimal_diameter": { + "label": "Minimal Diameter", + "description": "Maximal diameter in the X/Y directions of a small area which is to be supported by a specialized support tower. ", + "unit": "mm", + "type": "float", + "default": 1.0, + "visible": false, + "active_if": { + "setting": "support_use_towers", + "value": true + } + }, + "support_tower_diameter": { + "label": "Tower Diameter", + "description": "The diameter of a special tower. ", + "unit": "mm", + "type": "float", + "default": 1.0, + "visible": false, + "active_if": { + "setting": "support_use_towers", + "value": true + } + }, + "support_tower_roof_angle": { + "label": "Tower Roof Angle", + "description": "The angle of the rooftop of a tower. Larger angles mean more pointy towers. ", + "unit": "°", + "type": "int", + "default": 65, + "visible": false, + "active_if": { + "setting": "support_use_towers", + "value": true + } + }, + "support_pattern": { + "label": "Pattern", + "description": "Cura supports 3 distinct types of support structure. First is a grid based support structure which is quite solid and can be removed as 1 piece. The second is a line based support structure which has to be peeled off line by line. The third is a structure in between the other two; it consists of lines which are connected in an accordeon fashion.", + "type": "enum", + "options": [ + "Grid", + "Lines", + "ZigZag" + ], + "default": "ZigZag", + "visible": true, + "active_if": { + "setting": "support_enable", + "value": true + } + }, + "support_connect_zigzags": { + "label": "Connect ZigZags", + "description": "Connect the ZigZags. Makes them harder to remove, but prevents stringing of disconnected zigzags.", + "type": "boolean", + "default": true, + "visible": false, + "active_if": { + "setting": "support_pattern", + "value": "ZigZag" + } + }, + "support_fill_rate": { + "label": "Fill Amount", + "description": "The amount of infill structure in the support, less infill gives weaker support which is easier to remove.", + "unit": "%", + "type": "float", + "default": 15, + "visible": false, + "active_if": { + "setting": "support_enable", + "value": true + }, + + "children": { + "support_line_distance": { + "label": "Line distance", + "description": "Distance between the printed support lines.", + "unit": "mm", + "type": "float", + "default": 2.66, + "visible": false, + "active_if": { + "setting": "support_enable", + "value": true + }, + "inherit_function": "(support_line_width * 100) / parent_value" + } + } + } + } + }, + "platform_adhesion": { + "label": "Platform Adhesion", + "visible": true, + "icon": "category_adhesion", + "settings": { + "adhesion_type": { + "label": "Type", + "description": "Different options that help in preventing corners from lifting due to warping. Brim adds a single-layer-thick flat area around your object which is easy to cut off afterwards, and it is the recommended option. Raft adds a thick grid below the object and a thin interface between this and your object. (Note that enabling the brim or raft disables the skirt.)", + "type": "enum", + "options": [ + "None", + "Brim", + "Raft" + ], + "default": "None" + }, + "skirt_line_count": { + "label": "Skirt Line Count", + "description": "The skirt is a line drawn around the first layer of the. This helps to prime your extruder, and to see if the object fits on your platform. Setting this to 0 will disable the skirt. Multiple skirt lines can help to prime your extruder better for small objects.", + "type": "int", + "default": 1, + "active_if": { + "setting": "adhesion_type", + "value": "None" + } + }, + "skirt_gap": { + "label": "Skirt Distance", + "description": "The horizontal distance between the skirt and the first layer of the print.\nThis is the minimum distance, multiple skirt lines will extend outwards from this distance.", + "unit": "mm", + "type": "float", + "default": 3.0, + "active_if": { + "setting": "adhesion_type", + "value": "None" + } + }, + "skirt_minimal_length": { + "label": "Skirt Minimum Length", + "description": "The minimum length of the skirt. If this minimum length is not reached, more skirt lines will be added to reach this minimum length. Note: If the line count is set to 0 this is ignored.", + "unit": "mm", + "type": "float", + "default": 250, + "active_if": { + "setting": "adhesion_type", + "value": "None" + } + }, + "brim_line_count": { + "label": "Brim Line Count", + "description": "The amount of lines used for a brim: More lines means a larger brim which sticks better, but this also makes your effective print area smaller.", + "type": "int", + "default": 1, + "active_if": { + "setting": "adhesion_type", + "value": "Brim" + } + }, + "raft_margin": { + "label": "Raft Extra Margin", + "description": "If the raft is enabled, this is the extra raft area around the object which is also given a raft. Increasing this margin will create a stronger raft while using more material and leaving less area for your print.", + "unit": "mm", + "type": "float", + "default": 5.0, + "active_if": { + "setting": "adhesion_type", + "value": "Raft" + } + }, + "raft_line_spacing": { + "label": "Raft Line Spacing", + "description": "The distance between the raft lines. The first 2 layers of the raft have this amount of spacing between the raft lines.", + "unit": "mm", + "type": "float", + "default": 5.0, + "active_if": { + "setting": "adhesion_type", + "value": "Raft" + } + }, + "raft_base_thickness": { + "label": "Raft Base Thickness", + "description": "Layer thickness of the first raft layer. This should be a thick layer which sticks firmly to the printer bed.", + "unit": "mm", + "type": "float", + "default": 0.3, + "active_if": { + "setting": "adhesion_type", + "value": "Raft" + } + }, + "raft_base_linewidth": { + "label": "Raft Base Line Width", + "description": "Width of the lines in the first raft layer. These should be thick lines to assist in bed adhesion.", + "unit": "mm", + "type": "float", + "default": 1.0, + "active_if": { + "setting": "adhesion_type", + "value": "Raft" + } + }, + "raft_base_speed": { + "label": "Raft Base Print Speed", + "description": "The speed at which the first raft layer is printed. This should be printed quite slowly, as the amount of material coming out of the nozzle is quite high.", + "unit": "mm/s", + "type": "float", + "default": 15.0, + "active_if": { + "setting": "adhesion_type", + "value": "Raft" + } + }, + "raft_interface_thickness": { + "label": "Raft Interface Thickness", + "description": "Thickness of the 2nd raft layer.", + "unit": "mm", + "type": "float", + "default": 0.27, + "active_if": { + "setting": "adhesion_type", + "value": "Raft" + } + }, + "raft_interface_linewidth": { + "label": "Raft Interface Line Width", + "description": "Width of the 2nd raft layer lines. These lines should be thinner than the first layer, but strong enough to attach the object to.", + "unit": "mm", + "type": "float", + "default": 0.4, + "active_if": { + "setting": "adhesion_type", + "value": "Raft" + } + }, + "raft_airgap": { + "label": "Raft Air-gap", + "description": "The gap between the final raft layer and the first layer of the object. Only the first layer is raised by this amount to lower the bonding between the raft layer and the object. Makes it easier to peel off the raft.", + "unit": "mm", + "type": "float", + "default": 0.22, + "active_if": { + "setting": "adhesion_type", + "value": "Raft" + } + }, + "raft_surface_layers": { + "label": "Raft Surface Layers", + "description": "The number of surface layers on top of the 2nd raft layer. These are fully filled layers that the object sits on. 2 layers usually works fine.", + "type": "int", + "default": 2, + "active_if": { + "setting": "adhesion_type", + "value": "Raft" + } + } + } + }, + "blackmagic": { + "label": "Fixes", + "visible": true, + "icon": "category_fixes", + "settings": { + "magic_spiralize": { + "label": "Spiralize the Outer Contour", + "description": "Spiralize smooths out the Z move of the outer edge. This will create a steady Z increase over the whole print. This feature turns a solid object into a single walled print with a solid bottom. This feature used to be called ‘Joris’ in older versions.", + "type": "boolean", + "default": false, + "visible": false + }, + "wireframe_enabled": { + "label": "Wireframe Printing", + "description": "Print only the outside surface with a sparse webbed structure, printing 'in thin air'. This is realized by horizontally printing the contours of the model at given Z intervals which are connected via upward and diagonally downward lines.", + "type": "boolean", + "default": false, + "visible": false + }, + "wireframe_printspeed": { + "label": "Printing speed", + "description": "Speed at which the nozzle moves when extruding material.", + "unit": "mm/s", + "type": "float", + "default": 5.0, + "visible": false, + "active_if": { + "setting": "wireframe", + "value": true + }, + "children": { + "wireframe_printspeed_bottom": { + "label": "Bottom printing speed", + "description": "Speed of printing the first layer, which is the only layer touching the bluidplatform.", + "unit": "mm/s", + "type": "float", + "default": 5.0, + "visible": false, + "inherit":true + }, + "wireframe_printspeed_up": { + "label": "Upward printing speed", + "description": "Speed of printing a line upward 'in thin air'.", + "unit": "mm/s", + "type": "float", + "default": 5.0, + "visible": false, + "inherit":true + }, + "wireframe_printspeed_down": { + "label": "Downward printing speed", + "description": "Speed of printing a line diagonally downward.", + "unit": "mm/s", + "type": "float", + "default": 5.0, + "visible": false, + "inherit":true + }, + "wireframe_printspeed_flat": { + "label": "Horizontal printing speed", + "description": "Speed of printing the horizontal contours of the object.", + "unit": "mm/s", + "type": "float", + "default": 5.0, + "visible": false, + "inherit":true + } + } + }, + "wireframe_flow": { + "label": "Flow", + "description": "Flow compensation: the amount of material extruded is multiplied by this value.", + "unit": "%", + "default": 100.0, + "type": "float", + "visible": false, + "active_if": { + "setting": "wireframe", + "value": true + }, + "children": { + "wireframe_flow_connection": { + "label": "Connection flow", + "description": "Flow compensation when going up or down.", + "unit": "%", + "default": 100.0, + "type": "float", + "visible": false + }, + "wireframe_flow_flat": { + "label": "Flat flow", + "description": "Flow compensation when printing flat lines.", + "unit": "%", + "default": 100.0, + "type": "float", + "visible": false + } + } + }, + "wireframe_top_delay": { + "label": "Top delay", + "description": "Delay time after an upward move, so that the upward line can harden.", + "unit": "sec", + "type": "float", + "default": 0.0, + "visible": false, + "active_if": { + "setting": "wireframe", + "value": true + } + }, + "wireframe_bottom_delay": { + "label": "Bottom delay", + "description": "Delay time after a downward move.", + "unit": "sec", + "type": "float", + "default": 0.0, + "visible": false, + "active_if": { + "setting": "wireframe", + "value": true + } + }, + "wireframe_flat_delay": { + "label": "Flat delay", + "description": "Delay time between two horizontal segments. Introducing such a delay can cause better adhesion to previous layers at the connection points, while too large delay times cause sagging.", + "unit": "sec", + "type": "float", + "default": 0.1, + "visible": false, + "active_if": { + "setting": "wireframe", + "value": true + } + }, + "wireframe_up_half_speed": { + "label": "Ease upward", + "description": "Distance of an upward move which is extruded with half speed.\nThis can cause better adhesion to previous layers, while not heating the material in those layers too much.", + "type": "float", + "unit": "mm", + "default": 0.3, + "visible": false + }, + "wireframe_top_jump": { + "label": "Knot size", + "description": "Creates a small knot at the top of an upward line, so that the consecutive horizontal layer has a better chance to connect to it.", + "type": "float", + "unit": "mm", + "default": 0.6, + "visible": false, + "active_if": { + "setting": "wireframe", + "value": true + } + }, + "wireframe_fall_down": { + "label": "Fall down", + "description": "Distance with which the material falls down after an upward extrusion. This distance is compensated for.", + "type": "float", + "unit": "mm", + "default": 0.5, + "visible": false, + "active_if": { + "setting": "wireframe", + "value": true + } + }, + "wireframe_drag_along": { + "label": "Drag along", + "description": "Distance with which the material of an upward extrusion is dragged along with the diagonally downward extrusion. This distance is compensated for.", + "type": "float", + "unit": "mm", + "default": 0.6, + "visible": false, + "active_if": { + "setting": "wireframe", + "value": true + } + }, + "wireframe_strategy": { + "label": "Strategy", + "description": "Strategy for making sure two consecutive layers connect at each connection point. Retraction lets the upward lines harden in the right position, but may cause filament grinding. A knot can be made at the end of an upward line to heighten the chance of connecting to it and to let the line cool; however it may require slow printing speeds. Another strategy is to compensate for the sagging of the top of an upward line; however, the lines won't always fall down as predicted.", + "type": "enum", + "options": [ + "Compensate", + "Knot", + "Retract" + ], + "default": "Compensate", + "visible": false, + "active_if": { + "setting": "wireframe", + "value": true + } + }, + "wireframe_straight_before_down": { + "label": "Straighten downward lines", + "description": "Percentage of a diagonally downward line which is covered by a horizontal line piece. This can prevent sagging of the top most point of upward lines.", + "type": "float", + "unit": "%", + "default": 20.0, + "visible": false, + "active_if": { + "setting": "wireframe", + "value": true + } + }, + "wireframe_roof_fall_down": { + "label": "Roof fall down", + "description": "The distance which horizontal roof lines printed 'in thin air' fall down when being printed. This distance is compensated for.", + "type": "float", + "unit": "mm", + "default": 2.0, + "visible": false, + "active_if": { + "setting": "wireframe", + "value": true + } + }, + "wireframe_roof_drag_along": { + "label": "Roof drag along", + "description": "The distance of the end piece of an inward line which gets dragged along when going back to the outer outline of the roof. This distance is compensated for.", + "type": "float", + "unit": "mm", + "default": 0.8, + "visible": false, + "active_if": { + "setting": "wireframe", + "value": true + } + }, + "wireframe_roof_outer_delay": { + "label": "Roof outer delay", + "description": "Time spent at the outer perimeters of hole which is to become a roof. Larger times can ensure a better connection.", + "type": "boolean", + "unit": "sec", + "type": "float", + "default": 0.2, + "visible": false, + "active_if": { + "setting": "wireframe", + "value": true + } + }, + "wireframe_height": { + "label": "Connection height.", + "description": "The height of the upward and diagonally downward lines between two horizontal parts.", + "type": "float", + "unit": "mm", + "default": 3.0, + "visible": false, + "active_if": { + "setting": "wireframe", + "value": true + } + }, + "wireframe_roof_inset": { + "label": "Roof inset distance", + "description": "The distance covered when making a connection from a roof outline inward.", + "type": "float", + "unit": "mm", + "default": 3.0, + "visible": false, + "active_if": { + "setting": "wireframe", + "value": true + }, + "inherit_function": "wireframe_height" + }, + "wireframe_nozzle_clearance": { + "label": "Nozzle clearance", + "description": "Distance between the nozzle and horizontally downward lines. Larger clearance results in diagonally downward lines with a less steep angle, which in turn results in less upward connections with the next layer.", + "type": "float", + "unit": "mm", + "default": 1.0, + "visible": false, + "active_if": { + "setting": "wireframe", + "value": true + } + } + } + } + } +} + + diff --git a/src/octoprint/plugins/cura/static/js/cura.js b/src/octoprint/plugins/cura/static/js/cura.js index 23068292c..0d091ab3b 100644 --- a/src/octoprint/plugins/cura/static/js/cura.js +++ b/src/octoprint/plugins/cura/static/js/cura.js @@ -6,6 +6,13 @@ $(function() { self.settingsViewModel = parameters[1]; self.slicingViewModel = parameters[2]; + self.pathBroken = ko.observable(false); + self.pathOk = ko.observable(false); + self.pathText = ko.observable(); + self.pathHelpVisible = ko.computed(function() { + return self.pathBroken() || self.pathOk(); + }); + self.fileName = ko.observable(); self.placeholderName = ko.observable(); @@ -16,6 +23,10 @@ $(function() { self.profileDisplayName = ko.observable(); self.profileDescription = ko.observable(); self.profileAllowOverwrite = ko.observable(true); + self.profileMakeDefault = ko.observable(false); + + self.unconfiguredCuraEngine = ko.observable(); + self.unconfiguredSlicingProfile = ko.observable(); self.uploadElement = $("#settings-cura-import"); self.uploadButton = $("#settings-cura-import-start"); @@ -59,6 +70,7 @@ $(function() { dataType: "json", maxNumberOfFiles: 1, autoUpload: false, + headers: OctoPrint.getRequestHeaders(), add: function(e, data) { if (data.files.length == 0) { return false; @@ -86,6 +98,9 @@ $(function() { if (self.profileDescription() !== undefined) { form["description"] = self.profileDescription(); } + if (self.profileMakeDefault()) { + form["default"] = true; + } data.formData = form; data.submit(); @@ -100,6 +115,7 @@ $(function() { self.profileDisplayName(undefined); self.profileDescription(undefined); self.profileAllowOverwrite(true); + self.profileMakeDefault(false); $("#settings_plugin_cura_import").modal("hide"); self.requestData(); @@ -116,14 +132,11 @@ $(function() { return (item.key == data.key); }); - $.ajax({ - url: data.resource(), - type: "DELETE", - success: function() { + OctoPrint.slicing.deleteProfileForSlicer("cura", data.key, {url: data.resource()}) + .done(function() { self.requestData(); self.slicingViewModel.requestData(); - } - }); + }); }; self.makeProfileDefault = function(data) { @@ -141,29 +154,42 @@ $(function() { item.isdefault(true); } - $.ajax({ - url: data.resource(), - type: "PATCH", - dataType: "json", - data: JSON.stringify({default: true}), - contentType: "application/json; charset=UTF-8", - success: function() { + OctoPrint.slicing.updateProfileForSlicer("cura", data.key, {default: true}, {url: data.resource()}) + .done(function() { self.requestData(); - } - }); + }); }; - self.showImportProfileDialog = function() { + self.showImportProfileDialog = function(makeDefault) { + if (makeDefault == undefined) { + makeDefault = _.filter(self.profiles.items(), function(profile) { profile.isdefault() }).length == 0; + } + self.profileMakeDefault(makeDefault); $("#settings_plugin_cura_import").modal("show"); }; + self.testEnginePath = function() { + OctoPrint.util.testExecutable(self.settings.plugins.cura.cura_engine()) + .done(function(response) { + if (!response.result) { + if (!response.exists) { + self.pathText(gettext("The path doesn't exist")); + } else if (!response.typeok) { + self.pathText(gettext("The path is not a file")); + } else if (!response.access) { + self.pathText(gettext("The path is not an executable")); + } + } else { + self.pathText(gettext("The path is valid")); + } + self.pathOk(response.result); + self.pathBroken(!response.result); + }); + }; + self.requestData = function() { - $.ajax({ - url: API_BASEURL + "slicing/cura/profiles", - type: "GET", - dataType: "json", - success: self.fromResponse - }); + OctoPrint.slicing.listProfilesForSlicer("cura") + .done(self.fromResponse); }; self.fromResponse = function(data) { @@ -184,12 +210,37 @@ $(function() { self.settings = self.settingsViewModel.settings; self.requestData(); }; + + self.onSettingsHidden = function() { + self.resetPathTest(); + }; + + self.resetPathTest = function() { + self.pathBroken(false); + self.pathOk(false); + self.pathText(""); + }; + + self.onWizardDetails = function(response) { + if (!response.hasOwnProperty("cura") || !response.cura.required) return; + + if (response.cura.details.hasOwnProperty("engine")) { + self.unconfiguredCuraEngine(!response.cura.details.engine); + } + if (response.cura.details.hasOwnProperty("profile")) { + self.unconfiguredSlicingProfile(!response.cura.details.profile); + } + }; + + self.onWizardFinish = function() { + self.resetPathTest(); + }; } // view model class, parameters for constructor, container to bind to OCTOPRINT_VIEWMODELS.push([ CuraViewModel, ["loginStateViewModel", "settingsViewModel", "slicingViewModel"], - "#settings_plugin_cura" + ["#settings_plugin_cura", "#wizard_plugin_cura"] ]); -}); \ No newline at end of file +}); diff --git a/src/octoprint/plugins/cura/templates/_snippets/settings/cura/engineLog.jinja2 b/src/octoprint/plugins/cura/templates/_snippets/settings/cura/engineLog.jinja2 new file mode 100644 index 000000000..690f1490d --- /dev/null +++ b/src/octoprint/plugins/cura/templates/_snippets/settings/cura/engineLog.jinja2 @@ -0,0 +1,7 @@ +| {{ _('Identifier') }} | -{{ _('Name') }} | -{{ _('Actions') }} | -
|---|---|---|
| - | - | - | - | -
{% trans %} + The path to CuraEngine has not yet been set up, in order to be able to use + CuraEngine for slicing it needs to be specified. + {% endtrans %}
+ +{% trans %}You haven't imported a slicing profile to use for slicing with CuraEngine + yet. You should do this now.{% endtrans %}
+ +.ini file this creates via the "Import Profile" button.
+ {% endtrans %}
+ pip command could not be found.
- Please configure it manually. No installation and uninstallation of plugin
+ The pip command could not be found or does not work correctly
+ for this installation of OctoPrint - please consult the log file for details
+ and if necessary configure it manually. No installation and uninstallation of plugin
packages is possible while pip is unavailable.
{% endtrans %}- Using pip at "" (Version , additional arguments: ) -
+" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s"), payload) + "
"; - html += pnotifyAdditionalInfo('' + payload.error + ''); - new PNotify({ - title: gettext("Rendering failed"), - text: html, - type: "error", - hide: false - }); - } else if (type == "PostRollStart") { - var title = gettext("Capturing timelapse postroll"); - - var text; - if (!payload.postroll_duration) { - text = _.sprintf(gettext("Now capturing timelapse post roll, this will take only a moment..."), format); - } else { - if (payload.postroll_duration > 60) { - format = {duration: _.sprintf(gettext("%(minutes)d min"), {minutes: payload.postroll_duration / 60})}; - } else { - format = {duration: _.sprintf(gettext("%(seconds)d sec"), {seconds: payload.postroll_duration})}; - } - text = _.sprintf(gettext("Now capturing timelapse post roll, this will take approximately %(duration)s..."), format); - } - - new PNotify({ - title: title, - text: text - }); - } else if (type == "SlicingStarted") { - gcodeUploadProgress.addClass("progress-striped").addClass("active"); - gcodeUploadProgressBar.css("width", "100%"); - if (payload.progressAvailable) { - gcodeUploadProgressBar.text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: 0})); - } else { - gcodeUploadProgressBar.text(gettext("Slicing ...")); - } - } else if (type == "SlicingDone") { - gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); - gcodeUploadProgressBar.css("width", "0%"); - gcodeUploadProgressBar.text(""); - new PNotify({title: gettext("Slicing done"), text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload), type: "success"}); - } else if (type == "SlicingCancelled") { - gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); - gcodeUploadProgressBar.css("width", "0%"); - gcodeUploadProgressBar.text(""); - } else if (type == "SlicingFailed") { - gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); - gcodeUploadProgressBar.css("width", "0%"); - gcodeUploadProgressBar.text(""); - - html = _.sprintf(gettext("Could not slice %(stl)s to %(gcode)s: %(reason)s"), payload); - new PNotify({title: gettext("Slicing failed"), text: html, type: "error", hide: false}); - } else if (type == "TransferStarted") { - gcodeUploadProgress.addClass("progress-striped").addClass("active"); - gcodeUploadProgressBar.css("width", "100%"); - gcodeUploadProgressBar.text(gettext("Streaming ...")); - } else if (type == "TransferDone") { - gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); - gcodeUploadProgressBar.css("width", "0%"); - gcodeUploadProgressBar.text(""); - new PNotify({ - title: gettext("Streaming done"), - text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload), - type: "success" - }); - } - - 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); - } - }); - - break; - } - case "timelapse": { - _.each(self.allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("fromTimelapseData")) { - viewModel.fromTimelapseData(data); - } - }); - break; - } - case "plugin": { - _.each(self.allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onDataUpdaterPluginMessage")) { - viewModel.onDataUpdaterPluginMessage(data.plugin, data.data); - } - }) - } - } + // 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(); } }; + 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 = ""; + var format = {}; + + log.debug("Got event " + type + " with payload: " + JSON.stringify(payload)); + + if (type == "SettingsUpdated") { + if (payload && payload.hasOwnProperty("config_hash")) { + self._configHash = payload.config_hash; + } + } else if (type == "MovieRendering") { + new PNotify({title: gettext("Rendering timelapse"), text: _.sprintf(gettext("Now rendering timelapse %(movie_basename)s"), payload)}); + } else if (type == "MovieDone") { + new PNotify({title: gettext("Timelapse ready"), text: _.sprintf(gettext("New timelapse %(movie_basename)s is done rendering."), payload)}); + } else if (type == "MovieFailed") { + html = "
" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s"), payload) + "
"; + html += pnotifyAdditionalInfo('' + payload.error + ''); + new PNotify({ + title: gettext("Rendering failed"), + text: html, + type: "error", + hide: false + }); + } else if (type == "PostRollStart") { + var title = gettext("Capturing timelapse postroll"); + + var text; + if (!payload.postroll_duration) { + text = _.sprintf(gettext("Now capturing timelapse post roll, this will take only a moment..."), format); + } else { + if (payload.postroll_duration > 60) { + format = {duration: _.sprintf(gettext("%(minutes)d min"), {minutes: payload.postroll_duration / 60})}; + } else { + format = {duration: _.sprintf(gettext("%(seconds)d sec"), {seconds: payload.postroll_duration})}; + } + text = _.sprintf(gettext("Now capturing timelapse post roll, this will take approximately %(duration)s..."), format); + } + + new PNotify({ + title: title, + text: text + }); + } else if (type == "SlicingStarted") { + gcodeUploadProgress.addClass("progress-striped").addClass("active"); + gcodeUploadProgressBar.css("width", "100%"); + if (payload.progressAvailable) { + gcodeUploadProgressBar.text(_.sprintf(gettext("Slicing ... (%(percentage)d%%)"), {percentage: 0})); + } else { + gcodeUploadProgressBar.text(gettext("Slicing ...")); + } + } else if (type == "SlicingDone") { + gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); + gcodeUploadProgressBar.css("width", "0%"); + gcodeUploadProgressBar.text(""); + new PNotify({title: gettext("Slicing done"), text: _.sprintf(gettext("Sliced %(stl)s to %(gcode)s, took %(time).2f seconds"), payload), type: "success"}); + } else if (type == "SlicingCancelled") { + gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); + gcodeUploadProgressBar.css("width", "0%"); + gcodeUploadProgressBar.text(""); + } else if (type == "SlicingFailed") { + gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); + gcodeUploadProgressBar.css("width", "0%"); + gcodeUploadProgressBar.text(""); + + html = _.sprintf(gettext("Could not slice %(stl)s to %(gcode)s: %(reason)s"), payload); + new PNotify({title: gettext("Slicing failed"), text: html, type: "error", hide: false}); + } else if (type == "TransferStarted") { + gcodeUploadProgress.addClass("progress-striped").addClass("active"); + gcodeUploadProgressBar.css("width", "100%"); + gcodeUploadProgressBar.text(gettext("Streaming ...")); + } else if (type == "TransferDone") { + gcodeUploadProgress.removeClass("progress-striped").removeClass("active"); + gcodeUploadProgressBar.css("width", "0%"); + gcodeUploadProgressBar.text(""); + new PNotify({ + title: gettext("Streaming done"), + text: _.sprintf(gettext("Streamed %(local)s to %(remote)s on SD, took %(time).2f seconds"), payload), + type: "success" + }); + } + + 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._onPluginMessage = function(event) { + callViewModels(self.allViewModels, "onDataUpdaterPluginMessage", [event.data.plugin, event.data.data]); + }; + + OctoPrint.socket.onReconnectAttempt = self._onReconnectAttempt; + OctoPrint.socket.onReconnectFailed = self._onReconnectFailed; + OctoPrint.socket + .onMessage("connected", self._onConnected) + .onMessage("history", self._onHistoryData) + .onMessage("current", self._onCurrentData) + .onMessage("slicingProgress", self._onSlicingProgress) + .onMessage("event", self._onEvent) + .onMessage("timelapse", self._onTimelapse) + .onMessage("plugin", self._onPluginMessage); + self.connect(); } diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index 181229fb8..930eccdd2 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -462,18 +462,99 @@ function hideOfflineOverlay() { $("#offline_overlay").hide(); } -function showConfirmationDialog(message, onacknowledge) { - var confirmationDialog = $("#confirmation_dialog"); - var confirmationDialogAck = $(".confirmation_dialog_acknowledge", confirmationDialog); +function showMessageDialog(msg, options) { + options = options || {}; + if (_.isPlainObject(msg)) { + options = msg; + } else { + options.message = msg; + } - $(".confirmation_dialog_message", confirmationDialog).text(message); - confirmationDialogAck.unbind("click"); - confirmationDialogAck.bind("click", function (e) { - e.preventDefault(); - $("#confirmation_dialog").modal("hide"); - onacknowledge(e); + var title = options.title || ""; + var message = options.message || ""; + var close = options.close || gettext("Close"); + var onclose = options.onclose || undefined; + var onshow = options.onshow || undefined; + var onshown = options.onshown || undefined; + + if (_.isString(message)) { + message = $("
" + message + "
"); + } + + var modalHeader = $('×' + message + '
' + question + '
'); + + var cancelButton = $('' + cancel + '') + .attr("data-dismiss", "modal") + .attr("aria-hidden", "true"); + var proceedButton = $('' + proceed + '') + .addClass("btn-" + proceedClass); + + var modal = $('') + .addClass('modal hide fade') + .append($('').addClass('modal-header').append(modalHeader)) + .append($('').addClass('modal-body').append(modalBody)) + .append($('').addClass('modal-footer').append(cancelButton).append(proceedButton)); + modal.modal("show"); + + proceedButton.click(function(e) { + e.preventDefault(); + modal.modal("hide"); + if (onproceed && _.isFunction(onproceed)) { + onproceed(e); + } + }); + + return modal; +} + +function showReloadOverlay() { + $("#reloadui_overlay").show(); } function commentableLinesToArray(lines) { @@ -490,6 +571,166 @@ function splitTextToArray(text, sep, stripEmpty, filter) { ); } +/** + * Returns true if comparing data and oldData yields changes, false otherwise. + * + * E.g. + * + * hasDataChanged( + * {foo: "bar", fnord: {one: "1", two: "2", three: "three", key: "value"}}, + * {foo: "bar", fnord: {one: "1", two: "2", three: "3", four: "4"}} + * ) + * + * will return + * + * true + * + * and + * + * hasDataChanged( + * {foo: "bar", fnord: {one: "1", two: "2", three: "3"}}, + * {foo: "bar", fnord: {one: "1", two: "2", three: "3"}} + * ) + * + * will return + * + * false + * + * Note that this will assume data and oldData to be structurally identical (same keys) + * and is optimized to check for value changes, not key updates. + */ +function hasDataChanged(data, oldData) { + if (data == undefined) { + return false; + } + + if (oldData == undefined) { + return true; + } + + if (_.isPlainObject(data)) { + return _.any(_.keys(data), function(key) {return hasDataChanged(data[key], oldData[key]);}); + } else { + return !_.isEqual(data, oldData); + } +} + +/** + * Compare provided data and oldData plain objects and only return those + * substructures of data that actually changed. + * + * E.g. + * + * getOnlyChangedData( + * {foo: "bar", fnord: {one: "1", two: "2", three: "three"}}, + * {foo: "bar", fnord: {one: "1", two: "2", three: "3"}} + * ) + * + * will return + * + * {fnord: {three: "three"}} + * + * and + * + * getOnlyChangedData( + * {foo: "bar", fnord: {one: "1", two: "2", three: "3"}}, + * {foo: "bar", fnord: {one: "1", two: "2", three: "3"}} + * ) + * + * will return + * + * {} + * + * Note that this will assume data and oldData to be structurally identical (same keys) + * and is optimized to check for value changes, not key updates. + */ +function getOnlyChangedData(data, oldData) { + if (data == undefined) { + return {}; + } + + if (oldData == undefined) { + return data; + } + + var f = function(root, oldRoot) { + if (!_.isPlainObject(root)) { + return root; + } + + var retval = {}; + _.forOwn(root, function(value, key) { + var oldValue = oldRoot[key]; + if (_.isPlainObject(value)) { + if (hasDataChanged(value, oldValue)) { + retval[key] = f(value, oldValue); + } + } else { + if (!_.isEqual(value, oldValue)) { + retval[key] = value; + } + } + }); + return retval; + }; + + return f(data, oldData); +} + +function callViewModels(allViewModels, method, callback) { + callViewModelsIf(allViewModels, method, undefined, callback); +} + +function callViewModelsIf(allViewModels, method, condition, callback) { + if (condition == undefined || !_.isFunction(condition)) { + condition = function() { return true; }; + } + + var parameters = undefined; + if (!_.isFunction(callback)) { + // if callback is not a function that means we are supposed to directly + // call the view model method instead of providing it to the callback + // - let's figure out how + + if (callback == undefined) { + // directly call view model method with no parameters + parameters = undefined; + log.trace("Calling method", method, "on view models"); + } else if (_.isArray(callback)) { + // directly call view model method with these parameters + parameters = callback; + log.trace("Calling method", method, "on view models with specified parameters", parameters); + } else { + // ok, this doesn't make sense, callback is neither undefined nor + // an array, we'll return without doing anything + return; + } + + // we reset this here so we now further down that we want to call + // the method directly + callback = undefined; + } else { + log.trace("Providing method", method, "on view models to specified callback", callback); + } + + _.each(allViewModels, function(viewModel) { + if (viewModel.hasOwnProperty(method) && condition(viewModel, method)) { + if (callback == undefined) { + if (parameters != undefined) { + // call the method with the provided parameters + viewModel[method].apply(viewModel, parameters); + } else { + // call the method without parameters + viewModel[method](); + } + } else { + // provide the method to the callback + callback(viewModel[method]); + } + } + }); +} + var sizeObservable = function(observable) { return ko.computed({ read: function() { diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index 02930e082..402933a6e 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -1,4 +1,6 @@ $(function() { + OctoPrint = window.OctoPrint; + //~~ Lodash setup _.mixin({"sprintf": sprintf, "vsprintf": vsprintf}); @@ -7,10 +9,26 @@ $(function() { log.setLevel(CONFIG_DEBUG ? "debug" : "info"); - //~~ setup browser and internal tab tracking (in 1.3.0 that will be - // much nicer with the global OctoPrint object...) + //~~ OctoPrint client setup + OctoPrint.options.baseurl = BASEURL; + OctoPrint.options.apikey = UI_API_KEY; - var tabTracking = (function() { + OctoPrint.socket.onMessage("connected", function(data) { + var payload = data.data; + OctoPrint.options.apikey = payload.apikey; + + // update the API key directly in jquery's ajax options too, + // to ensure the fileupload plugin and any plugins still using + // $.ajax directly still work fine too + UI_API_KEY = payload["apikey"]; + $.ajaxSetup({ + headers: {"X-Api-Key": UI_API_KEY} + }); + }); + + //~~ some CoreUI specific stuff we put into OctoPrint.coreui + + OctoPrint.coreui = (function() { var exports = { browserTabVisibility: undefined, selectedTab: undefined @@ -128,23 +146,31 @@ $(function() { PNotify.prototype.options.styling = "bootstrap2"; PNotify.prototype.options.mouse_reset = false; + PNotify.singleButtonNotify = function(options) { + if (!options.confirm || !options.confirm.buttons || !options.confirm.buttons.length) { + return new PNotify(options); + } + + var autoDisplay = options.auto_display != false; + + var params = $.extend(true, {}, options); + params.auto_display = false; + + var notify = new PNotify(params); + notify.options.confirm.buttons = [notify.options.confirm.buttons[0]]; + notify.modules.confirm.makeDialog(notify, notify.options.confirm); + + if (autoDisplay) { + notify.open(); + } + return notify; + }; + //~~ Initialize view models // the view model map is our basic look up table for dependencies that may be injected into other view models var viewModelMap = {}; - // We put our tabTracking into the viewModelMap as a workaround until - // our global OctoPrint object becomes available in 1.3.0. This way - // we'll still be able to access it in our view models. - // - // NOTE TO DEVELOPERS: Do NOT depend on this dependency in your custom - // view models. It is ONLY provided for the core application to be able - // to backport a fix from the 1.3.0 development branch and WILL BE - // REMOVED once 1.3.0 gets released without any fallback! - // - // TODO: Remove with release of 1.3.0 - viewModelMap.tabTracking = tabTracking; - // Fix Function#name on browsers that do not support it (IE): // see: http://stackoverflow.com/questions/6903762/function-name-not-supported-in-ie if (!(function f() {}).name) { @@ -278,91 +304,6 @@ $(function() { var dataUpdater = new DataUpdater(allViewModels); - //~~ Custom knockout.js bindings - - ko.bindingHandlers.popover = { - init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { - var val = ko.utils.unwrapObservable(valueAccessor()); - - var options = { - title: val.title, - animation: val.animation, - placement: val.placement, - trigger: val.trigger, - delay: val.delay, - content: val.content, - html: val.html - }; - $(element).popover(options); - } - }; - - ko.bindingHandlers.allowBindings = { - init: function (elem, valueAccessor) { - return { controlsDescendantBindings: !valueAccessor() }; - } - }; - ko.virtualElements.allowedBindings.allowBindings = true; - - ko.bindingHandlers.slimScrolledForeach = { - init: function(element, valueAccessor, allBindings, viewModel, bindingContext) { - return ko.bindingHandlers.foreach.init(element, valueAccessor(), allBindings, viewModel, bindingContext); - }, - update: function(element, valueAccessor, allBindings, viewModel, bindingContext) { - setTimeout(function() { - $(element).slimScroll({scrollBy: 0}); - }, 10); - return ko.bindingHandlers.foreach.update(element, valueAccessor(), allBindings, viewModel, bindingContext); - } - }; - - ko.bindingHandlers.qrcode = { - update: function(element, valueAccessor, allBindings, viewModel, bindingContext) { - var val = ko.utils.unwrapObservable(valueAccessor()); - - var defaultOptions = { - text: "", - size: 200, - fill: "#000", - background: null, - label: "", - fontname: "sans", - fontcolor: "#000", - radius: 0, - ecLevel: "L" - }; - - var options = {}; - _.each(defaultOptions, function(value, key) { - options[key] = ko.utils.unwrapObservable(val[key]) || value; - }); - - $(element).empty().qrcode(options); - } - }; - - ko.bindingHandlers.invisible = { - init: function(element, valueAccessor, allBindings, viewModel, bindingContext) { - if (!valueAccessor()) return; - ko.bindingHandlers.style.update(element, function() { - return { visibility: 'hidden' }; - }) - } - }; - - ko.bindingHandlers.contextMenu = { - init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { - var val = ko.utils.unwrapObservable(valueAccessor()); - - $(element).contextMenu(val); - }, - update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { - var val = ko.utils.unwrapObservable(valueAccessor()); - - $(element).contextMenu(val); - } - }; - //~~ some additional hooks and initializations // make sure modals max out at the window height @@ -451,13 +392,8 @@ $(function() { // Allow components to react to tab change var onTabChange = function(current, previous) { log.debug("Selected OctoPrint tab changed: previous = " + previous + ", current = " + current); - tabTracking.selectedTab = current; - - _.each(allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onTabChange")) { - viewModel.onTabChange(current, previous); - } - }); + OctoPrint.coreui.selectedTab = current; + callViewModels(allViewModels, "onTabChange", [current, previous]); }; var tabs = $('#tabs a[data-toggle="tab"]'); @@ -470,12 +406,7 @@ $(function() { tabs.on('shown', function (e) { var current = e.target.hash; var previous = e.relatedTarget.hash; - - _.each(allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onAfterTabChange")) { - viewModel.onAfterTabChange(current, previous); - } - }); + callViewModels(allViewModels, "onAfterTabChange", [current, previous]); }); onTabChange(OCTOPRINT_INITIAL_TAB); @@ -490,13 +421,12 @@ $(function() { e.preventDefault(); }); + // reload overlay + $("#reloadui_overlay_reload").click(function() { location.reload(); }); + //~~ Starting up the app - _.each(allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onStartup")) { - viewModel.onStartup(); - } - }); + callViewModels(allViewModels, "onStartup"); //~~ view model binding @@ -527,6 +457,8 @@ $(function() { targets = [targets]; } + viewModel._bindings = []; + _.each(targets, function(target) { if (target == undefined) { return; @@ -552,6 +484,12 @@ $(function() { try { ko.applyBindings(viewModel, element); + viewModel._bindings.push(target); + + if (viewModel.hasOwnProperty("onBoundTo")) { + viewModel.onBoundTo(target, element); + } + log.debug("View model", viewModel.constructor.name, "bound to", target); } catch (exc) { log.error("Could not bind view model", viewModel.constructor.name, "to target", target, ":", (exc.stack || exc)); @@ -559,40 +497,30 @@ $(function() { }); } + viewModel._unbound = viewModel._bindings != undefined && viewModel._bindings.length == 0; + if (viewModel.hasOwnProperty("onAfterBinding")) { viewModel.onAfterBinding(); } }); - _.each(allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onAllBound")) { - viewModel.onAllBound(allViewModels); - } - }); + callViewModels(allViewModels, "onAllBound", [allViewModels]); log.info("... binding done"); // startup complete - _.each(allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onStartupComplete")) { - viewModel.onStartupComplete(); - } - }); + callViewModels(allViewModels, "onStartupComplete"); // make sure we can track the browser tab visibility - tabTracking.onBrowserVisibilityChange(function(status) { + OctoPrint.coreui.onBrowserVisibilityChange(function(status) { log.debug("Browser tab is now " + (status ? "visible" : "hidden")); - _.each(allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onBrowserTabVisibilityChange")) { - viewModel.onBrowserTabVisibilityChange(status); - } - }); + callViewModels(allViewModels, "onBrowserTabVisibilityChange", [status]); }); }; if (!_.has(viewModelMap, "settingsViewModel")) { throw new Error("settingsViewModel is missing, can't run UI") } - viewModelMap["settingsViewModel"].requestData(bindViewModels); + viewModelMap["settingsViewModel"].requestData() + .done(bindViewModels); } ); - diff --git a/src/octoprint/static/js/app/viewmodels/about.js b/src/octoprint/static/js/app/viewmodels/about.js new file mode 100644 index 000000000..8ebf6b9f9 --- /dev/null +++ b/src/octoprint/static/js/app/viewmodels/about.js @@ -0,0 +1,41 @@ +$(function() { + function AboutViewModel(parameters) { + var self = this; + + self.aboutDialog = undefined; + self.aboutContent = undefined; + self.aboutTabs = undefined; + + self.show = function() { + $("a:first", self.aboutTabs).tab("show"); + self.aboutContent.scrollTop(0); + self.aboutDialog.modal({ + minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); } + }).css({ + width: 'auto', + 'margin-left': function() { return -($(this).width() /2); } + }); + return false; + }; + + self.hide = function() { + self.aboutDialog.modal("hide"); + }; + + self.onStartup = function() { + self.aboutDialog = $("#about_dialog"); + self.aboutTabs = $("#about_dialog_tabs"); + self.aboutContent = $("#about_dialog_content"); + + $('a[data-toggle="tab"]', self.aboutTabs).on("show", function() { + self.aboutContent.scrollTop(0); + }); + }; + } + + OCTOPRINT_VIEWMODELS.push([ + AboutViewModel, + [], + ["#about_dialog", "#footer_about"] + ]); +}); diff --git a/src/octoprint/static/js/app/viewmodels/connection.js b/src/octoprint/static/js/app/viewmodels/connection.js index 7f55d6075..d501e7ecc 100644 --- a/src/octoprint/static/js/app/viewmodels/connection.js +++ b/src/octoprint/static/js/app/viewmodels/connection.js @@ -47,14 +47,8 @@ $(function() { self.previousIsOperational = undefined; self.requestData = function() { - $.ajax({ - url: API_BASEURL + "connection", - method: "GET", - dataType: "json", - success: function(response) { - self.fromResponse(response); - } - }) + OctoPrint.connection.getSettings() + .done(self.fromResponse); }; self.fromResponse = function(response) { @@ -93,7 +87,7 @@ $(function() { } else if (!self.isOperational() && !connectionTab.hasClass("in")) { connectionTab.collapse("show"); } - } + }; self._processStateData = function(data) { self.previousIsOperational = self.isOperational(); @@ -116,7 +110,6 @@ $(function() { self.connect = function() { if (self.isErrorOrClosed()) { var data = { - "command": "connect", "port": self.selectedPort() || "AUTO", "baudrate": self.selectedBaudrate() || 0, "printerProfile": self.selectedPrinter(), @@ -126,26 +119,14 @@ $(function() { if (self.saveSettings()) data["save"] = true; - $.ajax({ - url: API_BASEURL + "connection", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(data), - success: function(response) { + OctoPrint.connection.connect(data) + .done(function() { self.settings.requestData(); self.settings.printerProfiles.requestData(); - } - }); + }); } else { self.requestData(); - $.ajax({ - url: API_BASEURL + "connection", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({"command": "disconnect"}) - }) + OctoPrint.connection.disconnect(); } }; diff --git a/src/octoprint/static/js/app/viewmodels/control.js b/src/octoprint/static/js/app/viewmodels/control.js index e1a503442..7a89718ef 100644 --- a/src/octoprint/static/js/app/viewmodels/control.js +++ b/src/octoprint/static/js/app/viewmodels/control.js @@ -5,9 +5,6 @@ $(function() { self.loginState = parameters[0]; self.settings = parameters[1]; - // TODO remove with release of 1.3.0 and switch to OctoPrint.coreui usage - self.tabTracking = parameters[2]; - self._createToolEntry = function () { return { name: ko.observable(), @@ -111,14 +108,10 @@ $(function() { }; self.requestData = function () { - $.ajax({ - url: API_BASEURL + "printer/command/custom", - method: "GET", - dataType: "json", - success: function (response) { + OctoPrint.control.getCustomControls() + .done(function(response) { self._fromResponse(response); - } - }); + }); }; self._fromResponse = function (response) { @@ -239,8 +232,11 @@ $(function() { } if (data.confirm) { - showConfirmationDialog(data.confirm, function (e) { - callback(data); + showConfirmationDialog({ + message: data.confirm, + onproceed: function (e) { + callback(data); + } }); } else { callback(data); @@ -254,26 +250,17 @@ $(function() { multiplier *= -1; } - var data = { - "command": "jog" - }; + var data = {}; data[axis] = distance * multiplier; - - self.sendPrintHeadCommand(data); + OctoPrint.printer.jog(data); }; self.sendHomeCommand = function (axis) { - self.sendPrintHeadCommand({ - "command": "home", - "axes": axis - }); + OctoPrint.printer.home(axis); }; self.sendFeedRateCommand = function () { - self.sendPrintHeadCommand({ - "command": "feedrate", - "factor": self.feedRate() - }); + OctoPrint.printer.setFeedrate(self.feedRate()); }; self.sendExtrudeCommand = function () { @@ -285,90 +272,42 @@ $(function() { }; self.sendFlowRateCommand = function () { - self.sendToolCommand({ - "command": "flowrate", - "factor": self.flowRate() - }); + OctoPrint.printer.setFlowrate(self.flowRate()); }; self._sendECommand = function (dir) { - var length = self.extrusionAmount(); - if (!length) length = self.settings.printer_defaultExtrusionLength(); - - self.sendToolCommand({ - command: "extrude", - amount: length * dir - }); + var length = self.extrusionAmount() || self.settings.printer_defaultExtrusionLength(); + OctoPrint.printer.extrude(length * dir); }; self.sendSelectToolCommand = function (data) { if (!data || !data.key()) return; - self.sendToolCommand({ - command: "select", - tool: data.key() - }); - }; - - self.sendPrintHeadCommand = function (data) { - $.ajax({ - url: API_BASEURL + "printer/printhead", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(data) - }); - }; - - self.sendToolCommand = function (data) { - $.ajax({ - url: API_BASEURL + "printer/tool", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(data) - }); + OctoPrint.printer.selectTool(data.key()); }; self.sendCustomCommand = function (command) { - if (!command) - return; - - var data = undefined; - if (command.hasOwnProperty("command")) { - // single command - data = {"command": command.command}; - } else if (command.hasOwnProperty("commands")) { - // multi command - data = {"commands": command.commands}; - } else if (command.hasOwnProperty("script")) { - data = {"script": command.script}; - if (command.hasOwnProperty("context")) { - data["context"] = command.context; - } - } else { - return; - } + if (!command) return; + var parameters = {}; if (command.hasOwnProperty("input")) { - // parametric command(s) - data["parameters"] = {}; - _.each(command.input, function(input) { + _.each(command.input, function (input) { if (!input.hasOwnProperty("parameter") || !input.hasOwnProperty("value")) { return; } - data["parameters"][input.parameter] = input.value(); + parameters[input.parameter] = input.value(); }); } - $.ajax({ - url: API_BASEURL + "printer/command", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(data) - }) + if (command.hasOwnProperty("command") || command.hasOwnProperty("commands")) { + var commands = command.commands || [command.command]; + OctoPrint.control.sendGcodeWithParameters(commands, parameters); + } else if (command.hasOwnProperty("script")) { + var script = command.script; + var context = command.context || {}; + OctoPrint.control.sendGcodeScriptWithParameters(script, context, parameters); + } }; self.displayMode = function (customControl) { @@ -414,7 +353,7 @@ $(function() { } else { $("#webcam_rotator").css("height", ""); } - } + }; self.onSettingsBeforeSave = self.updateRotatorWidth; @@ -427,7 +366,7 @@ $(function() { }; self._enableWebcam = function() { - if (self.tabTracking.selectedTab != "#control" || !self.tabTracking.browserTabVisible) { + if (OctoPrint.coreui.selectedTab != "#control" || !OctoPrint.coreui.browserTabVisible) { return; } @@ -468,10 +407,8 @@ $(function() { self.onAllBound = function (allViewModels) { var additionalControls = []; - _.each(allViewModels, function (viewModel) { - if (viewModel.hasOwnProperty("getAdditionalControls")) { - additionalControls = additionalControls.concat(viewModel.getAdditionalControls()); - } + callViewModels(allViewModels, "getAdditionalControls", function(method) { + additionalControls = additionalControls.concat(method()); }); if (additionalControls.length > 0) { self.additionalControls = additionalControls; @@ -588,7 +525,7 @@ $(function() { OCTOPRINT_VIEWMODELS.push([ ControlViewModel, - ["loginStateViewModel", "settingsViewModel", "tabTracking"], + ["loginStateViewModel", "settingsViewModel"], "#control" ]); }); diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index 39cede39c..894f96ec0 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -53,6 +53,20 @@ $(function() { }); self.uploadButton = undefined; + self.uploadSdButton = undefined; + self.uploadProgressBar = undefined; + self.localTarget = undefined; + self.sdTarget = undefined; + + self.addFolderDialog = undefined; + self.addFolderName = ko.observable(undefined); + self.enableAddFolder = ko.computed(function() { + return self.loginState.isUser() && self.addFolderName() && self.addFolderName().trim() != ""; + }); + + self.allItems = ko.observable(undefined); + self.listStyle = ko.observable("folders_files"); + self.currentPath = ko.observable(""); // initialize list helper self.listHelper = new ItemListHelper( @@ -78,28 +92,57 @@ $(function() { } }, { - "printed": function(file) { - return !(file["prints"] && file["prints"]["success"] && file["prints"]["success"] > 0); + "printed": function(data) { + return !(data["prints"] && data["prints"]["success"] && data["prints"]["success"] > 0) || (data["type"] && data["type"] == "folder"); }, - "sd": function(file) { - return file["origin"] && file["origin"] == "sdcard"; + "sd": function(data) { + return data["origin"] && data["origin"] == "sdcard"; }, - "local": function(file) { - return !(file["origin"] && file["origin"] == "sdcard"); + "local": function(data) { + return !(data["origin"] && data["origin"] == "sdcard"); }, - "machinecode": function(file) { - return file["type"] && file["type"] == "machinecode"; + "machinecode": function(data) { + return data["type"] && (data["type"] == "machinecode" || data["type"] == "folder"); }, - "model": function(file) { - return file["type"] && file["type"] == "model"; + "model": function(data) { + return data["type"] && (data["type"] == "model" || data["type"] == "folder"); + }, + "emptyFolder": function(data) { + return data["type"] && (data["type"] != "folder" || data["children"].length != 0); } }, "name", - [], + ["emptyFolder"], [["sd", "local"], ["machinecode", "model"]], 0 ); + self.foldersOnlyList = ko.dependentObservable(function() { + var filter = function(data) { return data["type"] && data["type"] == "folder"; }; + return _.filter(self.listHelper.paginatedItems(), filter); + }); + + self.filesOnlyList = ko.dependentObservable(function() { + var filter = function(data) { return data["type"] && data["type"] != "folder"; }; + return _.filter(self.listHelper.paginatedItems(), filter); + }); + + self.filesAndFolders = ko.dependentObservable(function() { + var style = self.listStyle(); + if (style == "folders_files" || style == "files_folders") { + var files = self.filesOnlyList(); + var folders = self.foldersOnlyList(); + + if (style == "folders_files") { + return folders.concat(files); + } else { + return files.concat(folders); + } + } else { + return self.listHelper.paginatedItems(); + } + }); + self.isLoadActionPossible = ko.computed(function() { return self.loginState.isUser() && !self.isPrinting() && !self.isPaused() && !self.isLoading(); }); @@ -112,12 +155,20 @@ $(function() { self.highlightFilename(newValue); }); + self.highlightCurrentFilename = function() { + self.highlightFilename(self.printerState.filename()); + }; + self.highlightFilename = function(filename) { if (filename == undefined) { self.listHelper.selectNone(); } else { self.listHelper.selectItem(function(item) { - return item.name == filename; + if (item.type == "folder") { + return _.startsWith(filename, OctoPrint.files.pathForElement(item) + "/"); + } else { + return OctoPrint.files.pathForElement(item) == filename; + } }); } }; @@ -142,31 +193,30 @@ $(function() { }; self._otherRequestInProgress = false; - self.requestData = function(filenameToFocus, locationToFocus) { + self.requestData = function(filenameToFocus, locationToFocus, switchToPath) { if (self._otherRequestInProgress) return; self._otherRequestInProgress = true; - $.ajax({ - url: API_BASEURL + "files", - method: "GET", - dataType: "json", - success: function(response) { - self.fromResponse(response, filenameToFocus, locationToFocus); + OctoPrint.files.list({ data: { recursive: true} }) + .done(function(response) { + self.fromResponse(response, filenameToFocus, locationToFocus, switchToPath); + }) + .always(function() { self._otherRequestInProgress = false; - }, - error: function() { - self._otherRequestInProgress = false; - } - }); + }); }; - self.fromResponse = function(response, filenameToFocus, locationToFocus) { + self.fromResponse = function(response, filenameToFocus, locationToFocus, switchToPath) { var files = response.files; - _.each(files, function(element, index, list) { - if (!element.hasOwnProperty("size")) element.size = undefined; - if (!element.hasOwnProperty("date")) element.date = undefined; - }); - self.listHelper.updateItems(files); + + self.allItems(files); + self.currentPath(""); + + if (!switchToPath) { + self.listHelper.updateItems(files); + } else { + self.changeFolderByPath(switchToPath); + } if (filenameToFocus) { // got a file to scroll to @@ -188,59 +238,105 @@ $(function() { self.totalSpace(response.total); } - self.highlightFilename(self.printerState.filename()); + self.highlightCurrentFilename(); + }; + + self.changeFolder = function(data) { + self.currentPath(OctoPrint.files.pathForElement(data)); + self.listHelper.updateItems(data.children); + self.highlightCurrentFilename(); + }; + + self.navigateUp = function() { + var path = self.currentPath().split("/"); + path.pop(); + self.changeFolderByPath(path.join("/")); + }; + + self.changeFolderByPath = function(path) { + var element = OctoPrint.files.elementByPath(path, { children: self.allItems() }); + if (element) { + self.currentPath(path); + self.listHelper.updateItems(element.children); + } else{ + self.currentPath(""); + self.listHelper.updateItems(self.allItems()); + } + self.highlightCurrentFilename(); + }; + + self.showAddFolderDialog = function() { + if (self.addFolderDialog) { + self.addFolderDialog.modal("show"); + } + }; + + self.addFolder = function() { + var name = self.addFolderName(); + + // "local" only for now since we only support local and sdcard, + // and sdcard doesn't support creating folders... + OctoPrint.files.createFolder("local", name, self.currentPath()) + .done(function() { + self.addFolderDialog.modal("hide"); + }); }; self.loadFile = function(file, printAfterLoad) { - if (!file || !file.refs || !file.refs.hasOwnProperty("resource")) return; - - $.ajax({ - url: file.refs.resource, - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({command: "select", print: printAfterLoad}) - }); + if (!file) { + return; + } + OctoPrint.files.select(file.origin, OctoPrint.files.pathForElement(file)) + .done(function() { + if (printAfterLoad) { + OctoPrint.job.start(); + } + }); }; self.removeFile = function(file) { - if (!file || !file.refs || !file.refs.hasOwnProperty("resource")) return; + if (!file) { + return; + } - $.ajax({ - url: file.refs.resource, - type: "DELETE", - success: function() { - self.requestData(); - } - }); + var index = self.listHelper.paginatedItems().indexOf(file) + 1; + if (index >= self.listHelper.paginatedItems().length) { + index = index - 2; + } + if (index < 0) { + index = 0; + } + + var filenameToFocus = undefined; + var fileToFocus = self.listHelper.paginatedItems()[index]; + if (fileToFocus) { + filenameToFocus = fileToFocus.name; + } + + OctoPrint.files.delete(file.origin, OctoPrint.files.pathForElement(file)) + .done(function() { + self.requestData(undefined, filenameToFocus, OctoPrint.files.pathForElement(file.parent)); + }) }; self.sliceFile = function(file) { - if (!file) return; + if (!file) { + return; + } - self.slicing.show(file.origin, file.name, true); + self.slicing.show(file.origin, OctoPrint.files.pathForElement(file), true); }; self.initSdCard = function() { - self._sendSdCommand("init"); + OctoPrint.printer.initSd(); }; self.releaseSdCard = function() { - self._sendSdCommand("release"); + OctoPrint.printer.releaseSd(); }; self.refreshSdFiles = function() { - self._sendSdCommand("refresh"); - }; - - self._sendSdCommand = function(command) { - $.ajax({ - url: API_BASEURL + "printer/sd", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({command: command}) - }); + OctoPrint.printer.refreshSd(); }; self.downloadLink = function(data) { @@ -352,9 +448,20 @@ $(function() { var query = self.searchQuery(); if (query !== undefined && query.trim() != "") { query = query.toLocaleLowerCase(); - self.listHelper.changeSearchFunction(function(entry) { - return entry && entry["name"].toLocaleLowerCase().indexOf(query) > -1; - }); + + var recursiveSearch = function(entry) { + if (entry === undefined) { + return false; + } + + if (entry["type"] == "folder" && entry["children"]) { + return _.any(entry["children"], recursiveSearch); + } else { + return entry["name"].toLocaleLowerCase().indexOf(query) > -1; + } + }; + + self.listHelper.changeSearchFunction(recursiveSearch); } else { self.listHelper.resetSearch(); } @@ -362,16 +469,18 @@ $(function() { return false; }; - self.onDataUpdaterReconnect = function() { - self.requestData(); - }; - self.onUserLoggedIn = function(user) { self.uploadButton.fileupload("enable"); + if (self.uploadSdButton) { + self.uploadSdButton.fileupload("enable"); + } }; self.onUserLoggedOut = function() { self.uploadButton.fileupload("disable"); + if (self.uploadSdButton) { + self.uploadSdButton.fileupload("disable"); + } }; self.onStartup = function() { @@ -395,21 +504,17 @@ $(function() { scrollBy: "102px" }); + self.addFolderDialog = $("#add_folder_dialog"); + //~~ Gcode upload self.uploadButton = $("#gcode_upload"); - function gcode_upload_done(e, data) { - var filename = undefined; - var location = undefined; - if (data.result.files.hasOwnProperty("sdcard")) { - filename = data.result.files.sdcard.name; - location = "sdcard"; - } else if (data.result.files.hasOwnProperty("local")) { - filename = data.result.files.local.name; - location = "local"; - } - self.requestData(filename, location); + self.uploadSdButton = $("#gcode_upload_sd"); + if (!self.uploadSdButton.length) { + self.uploadSdButton = undefined; + } +<<<<<<< HEAD if (_.endsWith(filename.toLowerCase(), ".stl")) { self.slicing.show(location, filename); } @@ -426,206 +531,221 @@ $(function() { } } +======= + self.uploadProgress = $("#gcode_upload_progress"); + self.uploadProgressBar = $(".bar", self.uploadProgress); - function gcode_upload_fail(e, data) { - var error = "" + gettext("Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\".") + "
"; - error += pnotifyAdditionalInfo("" + data.jqXHR.responseText + ""); - new PNotify({ - title: "Upload failed", - text: error, - type: "error", - hide: false - }); - $("#gcode_upload_progress .bar").css("width", "0%"); - $("#gcode_upload_progress").removeClass("progress-striped").removeClass("active"); - $("#gcode_upload_progress .bar").text(""); + self.localTarget = CONFIG_SD_SUPPORT ? $("#drop_locally") : $("#drop"); + self.sdTarget = $("#drop_sd"); +>>>>>>> 6945394fc25de4886dea6a77b11b256b62abda72 + + function evaluateDropzones() { + var enableLocal = self.loginState.isUser(); + var enableSd = enableLocal && CONFIG_SD_SUPPORT && self.printerState.isSdReady(); + + self._setDropzone("local", enableLocal); + self._setDropzone("sdcard", enableSd); } - - function gcode_upload_progress(e, data) { - var progress = parseInt(data.loaded / data.total * 100, 10); - $("#gcode_upload_progress .bar").css("width", progress + "%"); - $("#gcode_upload_progress .bar").text(gettext("Uploading ...")); - if (progress >= 100) { - $("#gcode_upload_progress").addClass("progress-striped").addClass("active"); - $("#gcode_upload_progress .bar").text(gettext("Saving ...")); - } - } - - function enable_local_dropzone() { - $("#gcode_upload").fileupload({ - url: API_BASEURL + "files/local", - dataType: "json", - dropZone: localTarget, - done: gcode_upload_done, - fail: gcode_upload_fail, - progressall: gcode_upload_progress - }); - } - - function disable_local_dropzone() { - $("#gcode_upload").fileupload({ - url: API_BASEURL + "files/local", - dataType: "json", - dropZone: null, - done: gcode_upload_done, - fail: gcode_upload_fail, - progressall: gcode_upload_progress - }); - } - - function enable_sd_dropzone() { - $("#gcode_upload_sd").fileupload({ - url: API_BASEURL + "files/sdcard", - dataType: "json", - dropZone: $("#drop_sd"), - done: gcode_upload_done, - fail: gcode_upload_fail, - progressall: gcode_upload_progress - }); - } - - function disable_sd_dropzone() { - $("#gcode_upload_sd").fileupload({ - url: API_BASEURL + "files/sdcard", - dataType: "json", - dropZone: null, - done: gcode_upload_done, - fail: gcode_upload_fail, - progressall: gcode_upload_progress - }); - } - - var localTarget; - if (CONFIG_SD_SUPPORT) { - localTarget = $("#drop_locally"); - } else { - localTarget = $("#drop"); - } - - self.loginState.isUser.subscribe(function(newValue) { - if (newValue === true) { - enable_local_dropzone(); - } else { - disable_local_dropzone(); - } - }); - - if (self.loginState.isUser()) { - enable_local_dropzone(); - } else { - disable_local_dropzone(); - } - - if (CONFIG_SD_SUPPORT) { - self.printerState.isSdReady.subscribe(function(newValue) { - if (newValue === true && self.loginState.isUser()) { - enable_sd_dropzone(); - } else { - disable_sd_dropzone(); - } - }); - - self.loginState.isUser.subscribe(function(newValue) { - if (newValue === true && self.printerState.isSdReady()) { - enable_sd_dropzone(); - } else { - disable_sd_dropzone(); - } - }); - - if (self.printerState.isSdReady() && self.loginState.isUser()) { - enable_sd_dropzone(); - } else { - disable_sd_dropzone(); - } - } - - $(document).bind("dragover", function (e) { - var dropOverlay = $("#drop_overlay"); - var dropZone = $("#drop"); - var dropZoneLocal = $("#drop_locally"); - var dropZoneSd = $("#drop_sd"); - var dropZoneBackground = $("#drop_background"); - var dropZoneLocalBackground = $("#drop_locally_background"); - var dropZoneSdBackground = $("#drop_sd_background"); - var timeout = window.dropZoneTimeout; - - if (!timeout) { - dropOverlay.addClass('in'); - } else { - clearTimeout(timeout); - } - - var foundLocal = false; - var foundSd = false; - var found = false; - var node = e.target; - do { - if (dropZoneLocal && node === dropZoneLocal[0]) { - foundLocal = true; - break; - } else if (dropZoneSd && node === dropZoneSd[0]) { - foundSd = true; - break; - } else if (dropZone && node === dropZone[0]) { - found = true; - break; - } - node = node.parentNode; - } while (node != null); - - if (foundLocal) { - dropZoneLocalBackground.addClass("hover"); - dropZoneSdBackground.removeClass("hover"); - } else if (foundSd && self.printerState.isSdReady()) { - dropZoneSdBackground.addClass("hover"); - dropZoneLocalBackground.removeClass("hover"); - } else if (found) { - dropZoneBackground.addClass("hover"); - } else { - if (dropZoneLocalBackground) dropZoneLocalBackground.removeClass("hover"); - if (dropZoneSdBackground) dropZoneSdBackground.removeClass("hover"); - if (dropZoneBackground) dropZoneBackground.removeClass("hover"); - } - - window.dropZoneTimeout = setTimeout(function () { - window.dropZoneTimeout = null; - dropOverlay.removeClass("in"); - if (dropZoneLocal) dropZoneLocalBackground.removeClass("hover"); - if (dropZoneSd) dropZoneSdBackground.removeClass("hover"); - if (dropZone) dropZoneBackground.removeClass("hover"); - }, 100); - }); + self.loginState.isUser.subscribe(evaluateDropzones); + self.printerState.isSdReady.subscribe(evaluateDropzones); + evaluateDropzones(); self.requestData(); }; self.onEventUpdatedFiles = function(payload) { if (payload.type == "gcode") { - self.requestData(); + self.requestData(undefined, undefined, self.currentPath()); } }; self.onEventSlicingDone = function(payload) { - self.requestData(); + self.requestData(undefined, undefined, self.currentPath()); }; self.onEventMetadataAnalysisFinished = function(payload) { - self.requestData(); + self.requestData(undefined, undefined, self.currentPath()); }; self.onEventMetadataStatisticsUpdated = function(payload) { - self.requestData(); + self.requestData(undefined, undefined, self.currentPath()); }; self.onEventTransferDone = function(payload) { self.requestData(payload.remote, "sdcard"); }; + + self.onServerConnect = function(payload) { + self._enableDragNDrop(true); + self.requestData(undefined, undefined, self.currentPath()); + }; + + self.onServerReconnect = function(payload) { + self._enableDragNDrop(true); + self.requestData(undefined, undefined, self.currentPath()); + }; + + self.onServerDisconnect = function(payload) { + self._enableDragNDrop(false); + }; + + self._setDropzone = function(dropzone, enable) { + var button = (dropzone == "local") ? self.uploadButton : self.uploadSdButton; + var drop = (dropzone == "local") ? self.localTarget : self.sdTarget; + var url = API_BASEURL + "files/" + dropzone; + + if (button === undefined) + return; + + button.fileupload({ + url: url, + dataType: "json", + dropZone: enable ? drop : null, + drop: function(e, data) { + + }, + done: self._handleUploadDone, + fail: self._handleUploadFail, + progressall: self._handleUploadProgress + }).bind('fileuploadsubmit', function(e, data) { + if (self.currentPath() != "") + data.formData = { path: self.currentPath() }; + }); + }; + + self._enableDragNDrop = function(enable) { + if (enable) { + $(document).bind("dragover", self._handleDragNDrop); + log.debug("Enabled drag-n-drop"); + } else { + $(document).unbind("dragover", self._handleDragNDrop); + log.debug("Disabled drag-n-drop"); + } + }; + + self._setProgressBar = function(percentage, text, active) { + self.uploadProgressBar + .css("width", percentage + "%") + .text(text); + + if (active) { + self.uploadProgress + .addClass("progress-striped active"); + } else { + self.uploadProgress + .removeClass("progress-striped active"); + } + } + + + self._handleUploadDone = function(e, data) { + var filename = undefined; + var location = undefined; + if (data.result.files.hasOwnProperty("sdcard")) { + filename = data.result.files.sdcard.name; + location = "sdcard"; + } else if (data.result.files.hasOwnProperty("local")) { + filename = data.result.files.local.name; + location = "local"; + } + self.requestData(filename, location, self.currentPath()); + + if (data.result.done) { + selef._setProgressBar(0, "", false); + } + }; + + self._handleUploadFail = function(e, data) { + var error = "
" + gettext("Could not upload the file. Make sure that it is a GCODE file and has the extension \".gcode\" or \".gco\" or that it is an STL file with the extension \".stl\".") + "
"; + error += pnotifyAdditionalInfo("" + data.jqXHR.responseText + ""); + new PNotify({ + title: "Upload failed", + text: error, + type: "error", + hide: false + }); + self.setProgressBar(0, "", false); + }; + + self._handleUploadProgress = function(e, data) { + var progress = parseInt(data.loaded / data.total * 100, 10); + var uploaded = progress >= 100; + + 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; + + var dataTransfer = undefined; + if (e.dataTransfer) { + dataTransfer = e.dataTransfer; + } else if (e.originalEvent && e.originalEvent.dataTransfer) { + dataTransfer = e.originalEvent.dataTransfer; + } + + if (!dataTransfer || !dataTransfer.items || dataTransfer.items.length > 1 || dataTransfer.items[0].kind != "file") { + return; + } + + if (!timeout) { + dropOverlay.addClass('in'); + } else { + clearTimeout(timeout); + } + + var foundLocal = false; + var foundSd = false; + var found = false; + var node = e.target; + do { + if (dropZoneLocal && node === dropZoneLocal[0]) { + foundLocal = true; + break; + } else if (dropZoneSd && node === dropZoneSd[0]) { + foundSd = true; + break; + } else if (dropZone && node === dropZone[0]) { + found = true; + break; + } + node = node.parentNode; + } while (node != null); + + if (foundLocal) { + dropZoneLocalBackground.addClass("hover"); + dropZoneSdBackground.removeClass("hover"); + } else if (foundSd && self.printerState.isSdReady()) { + dropZoneSdBackground.addClass("hover"); + dropZoneLocalBackground.removeClass("hover"); + } else if (found) { + dropZoneBackground.addClass("hover"); + } else { + if (dropZoneLocalBackground) dropZoneLocalBackground.removeClass("hover"); + if (dropZoneSdBackground) dropZoneSdBackground.removeClass("hover"); + if (dropZoneBackground) dropZoneBackground.removeClass("hover"); + } + + window.dropZoneTimeout = setTimeout(function () { + window.dropZoneTimeout = null; + dropOverlay.removeClass("in"); + if (dropZoneLocal) dropZoneLocalBackground.removeClass("hover"); + if (dropZoneSd) dropZoneSdBackground.removeClass("hover"); + if (dropZone) dropZoneBackground.removeClass("hover"); + }, 100); + } } OCTOPRINT_VIEWMODELS.push([ GcodeFilesViewModel, ["settingsViewModel", "loginStateViewModel", "printerStateViewModel", "slicingViewModel"], - "#files_wrapper" + ["#files_wrapper", "#add_folder_dialog"] ]); }); diff --git a/src/octoprint/static/js/app/viewmodels/firstrun.js b/src/octoprint/static/js/app/viewmodels/firstrun.js deleted file mode 100644 index 9e5552dd1..000000000 --- a/src/octoprint/static/js/app/viewmodels/firstrun.js +++ /dev/null @@ -1,88 +0,0 @@ -$(function() { - function FirstRunViewModel() { - var self = this; - - self.username = ko.observable(undefined); - self.password = ko.observable(undefined); - self.confirmedPassword = ko.observable(undefined); - - self.passwordMismatch = ko.computed(function() { - return self.password() != self.confirmedPassword(); - }); - - self.validUsername = ko.computed(function() { - return self.username() && self.username().trim() != ""; - }); - - self.validPassword = ko.computed(function() { - return self.password() && self.password().trim() != ""; - }); - - self.validData = ko.computed(function() { - return !self.passwordMismatch() && self.validUsername() && self.validPassword(); - }); - - self.keepAccessControl = function() { - if (!self.validData()) return; - - var data = { - "ac": true, - "user": self.username(), - "pass1": self.password(), - "pass2": self.confirmedPassword() - }; - self._sendData(data); - }; - - self.disableAccessControl = function() { - $("#confirmation_dialog .confirmation_dialog_message").html(gettext("If you disable Access Control and your OctoPrint installation is accessible from the internet, your printer will be accessible by everyone - that also includes the bad guys!")); - $("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click"); - $("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) { - e.preventDefault(); - $("#confirmation_dialog").modal("hide"); - - var data = { - "ac": false - }; - self._sendData(data, function() { - // if the user indeed disables access control, we'll need to reload the page for this to take effect - //location.reload(true); // TODO: clear cache doesn't work properly, needs a better way, same issue with reloading plugins - }); - }); - $("#confirmation_dialog").modal("show"); - }; - - self._sendData = function(data, callback) { - $.ajax({ - url: API_BASEURL + "setup", - type: "POST", - dataType: "json", - data: data, - success: function() { - self.closeDialog(); - if (callback) callback(); - } - }); - }; - - self.showDialog = function() { - $("#first_run_dialog").modal("show"); - }; - - self.closeDialog = function() { - $("#first_run_dialog").modal("hide"); - }; - - self.onAllBound = function(allViewModels) { - if (CONFIG_FIRST_RUN) { - self.showDialog(); - } - } - } - - OCTOPRINT_VIEWMODELS.push([ - FirstRunViewModel, - [], - "#first_run_dialog" - ]); -}); diff --git a/src/octoprint/static/js/app/viewmodels/gcode.js b/src/octoprint/static/js/app/viewmodels/gcode.js index 4f82f6f57..63ded17e6 100644 --- a/src/octoprint/static/js/app/viewmodels/gcode.js +++ b/src/octoprint/static/js/app/viewmodels/gcode.js @@ -5,9 +5,6 @@ $(function() { self.loginState = parameters[0]; self.settings = parameters[1]; - // TODO remove with release of 1.3.0 and switch to OctoPrint.coreui usage - self.tabTracking = parameters[2]; - self.ui_progress_percentage = ko.observable(); self.ui_progress_type = ko.observable(); self.ui_progress_text = ko.computed(function() { @@ -32,6 +29,7 @@ $(function() { self.ui_modelInfo = ko.observable(""); self.ui_layerInfo = ko.observable(""); + self.tabActive = false; self.enableReload = ko.observable(false); self.waitForApproval = ko.observable(false); @@ -234,19 +232,20 @@ $(function() { self._configureLayerSlider(layerSliderElement); self._configureLayerCommandSlider(commandSliderElement); - self.settings.requestData(function() { - GCODE.ui.init({ - container: "#gcode_canvas", - onProgress: self._onProgress, - onModelLoaded: self._onModelLoaded, - onLayerSelected: self._onLayerSelected, - bed: self._retrieveBedDimensions(), - toolOffsets: self._retrieveToolOffsets(), - invertAxes: self._retrieveAxesConfiguration() + self.settings.requestData() + .done(function() { + GCODE.ui.init({ + container: "#gcode_canvas", + onProgress: self._onProgress, + onModelLoaded: self._onModelLoaded, + onLayerSelected: self._onLayerSelected, + bed: self._retrieveBedDimensions(), + toolOffsets: self._retrieveToolOffsets(), + invertAxes: self._retrieveAxesConfiguration() + }); + self.synchronizeOptions(); + self.enabled = true; }); - self.synchronizeOptions(); - self.enabled = true; - }); }; self.reset = function() { @@ -292,11 +291,8 @@ $(function() { self.enableReload(false); if (self.status == "idle" && self.errorCount < 3) { self.status = "request"; - $.ajax({ - url: BASEURL + "downloads/files/local/" + filename, - data: { "ctime": date }, - type: "GET", - success: function(response, rstatus) { + OctoPrint.files.download("local", filename) + .done(function(response, rstatus) { if(rstatus === 'success'){ self.showGCodeViewer(response, rstatus); self.loadedFilename = filename; @@ -304,12 +300,11 @@ $(function() { self.status = "idle"; self.enableReload(true); } - }, - error: function() { + }) + .fail(function() { self.status = "idle"; self.errorCount++; - } - }); + }); } }; @@ -376,7 +371,7 @@ $(function() { if(self.loadedFilename && self.loadedFilename == data.job.file.name && self.loadedFileDate == data.job.file.date) { - if (self.tabTracking.browserTabVisible && self.tabActive && self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) { + if (OctoPrint.coreui.browserTabVisible && self.tabActive && self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) { self._renderPercentage(data.progress.completion); } self.errorCount = 0 @@ -526,7 +521,7 @@ $(function() { OCTOPRINT_VIEWMODELS.push([ GcodeViewModel, - ["loginStateViewModel", "settingsViewModel", "tabTracking"], + ["loginStateViewModel", "settingsViewModel"], "#gcode" ]); }); diff --git a/src/octoprint/static/js/app/viewmodels/log.js b/src/octoprint/static/js/app/viewmodels/log.js index fa42aeed6..872eb2888 100644 --- a/src/octoprint/static/js/app/viewmodels/log.js +++ b/src/octoprint/static/js/app/viewmodels/log.js @@ -36,12 +36,8 @@ $(function() { ); self.requestData = function() { - $.ajax({ - url: API_BASEURL + "logs", - type: "GET", - dataType: "json", - success: self.fromResponse - }); + OctoPrint.logs.list() + .done(self.fromResponse); }; self.fromResponse = function(response) { @@ -53,12 +49,8 @@ $(function() { }; self.removeFile = function(filename) { - $.ajax({ - url: API_BASEURL + "logs/" + filename, - type: "DELETE", - dataType: "json", - success: self.requestData - }); + OctoPrint.logs.delete(filename) + .done(self.requestData); }; self.onUserLoggedIn = function(user) { @@ -73,4 +65,4 @@ $(function() { ["loginStateViewModel"], "#logs" ]); -}); \ No newline at end of file +}); diff --git a/src/octoprint/static/js/app/viewmodels/loginstate.js b/src/octoprint/static/js/app/viewmodels/loginstate.js index 25e126c60..44555df82 100644 --- a/src/octoprint/static/js/app/viewmodels/loginstate.js +++ b/src/octoprint/static/js/app/viewmodels/loginstate.js @@ -2,8 +2,8 @@ $(function() { function LoginStateViewModel() { var self = this; - self.loginUser = ko.observable(); - self.loginPass = ko.observable(); + self.loginUser = ko.observable(""); + self.loginPass = ko.observable(""); self.loginRemember = ko.observable(false); self.loggedIn = ko.observable(false); @@ -15,6 +15,10 @@ $(function() { self.currentUser = ko.observable(undefined); + self.elementUsernameInput = undefined; + self.elementPasswordInput = undefined; + self.elementLoginButton = undefined; + self.userMenuText = ko.computed(function() { if (self.loggedIn()) { return self.username(); @@ -28,20 +32,13 @@ $(function() { return; } - $.ajax({ - url: API_BASEURL + "users/" + self.currentUser().name, - type: "GET", - success: self.fromResponse - }) + OctoPrint.users.get(self.currentUser().name) + .done(self.fromResponse); }; self.requestData = function() { - $.ajax({ - url: API_BASEURL + "login", - type: "POST", - data: {"passive": true}, - success: self.fromResponse - }) + OctoPrint.browser.passiveLogin() + .done(self.fromResponse); }; self.fromResponse = function(response) { @@ -53,11 +50,7 @@ $(function() { self.currentUser(response); - _.each(self.allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onUserLoggedIn")) { - viewModel.onUserLoggedIn(response); - } - }); + callViewModels(self.allViewModels, "onUserLoggedIn", [response]); } else { self.loggedIn(false); self.username(undefined); @@ -66,51 +59,40 @@ $(function() { self.currentUser(undefined); - _.each(self.allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onUserLoggedOut")) { - viewModel.onUserLoggedOut(); - } - }); + callViewModels(self.allViewModels, "onUserLoggedOut"); } }; - self.login = function() { - var username = self.loginUser(); - var password = self.loginPass(); - var remember = self.loginRemember(); + self.login = function(u, p, r) { + var username = u || self.loginUser(); + var password = p || self.loginPass(); + var remember = (r != undefined ? r : self.loginRemember()); - self.loginUser(""); - self.loginPass(""); - self.loginRemember(false); - - $.ajax({ - url: API_BASEURL + "login", - type: "POST", - data: {"user": username, "pass": password, "remember": remember}, - success: function(response) { + return OctoPrint.browser.login(username, password, remember) + .done(function(response) { new PNotify({title: gettext("Login successful"), text: _.sprintf(gettext('You are now logged in as "%(username)s"'), {username: response.name}), type: "success"}); self.fromResponse(response); - }, - error: function(jqXHR, textStatus, errorThrown) { + + self.loginUser(""); + self.loginPass(""); + self.loginRemember(false); + }) + .fail(function() { new PNotify({title: gettext("Login failed"), text: gettext("User unknown or wrong password"), type: "error"}); - } - }) + }); }; self.logout = function() { - $.ajax({ - url: API_BASEURL + "logout", - type: "POST", - success: function(response) { + OctoPrint.browser.logout() + .done(function(response) { new PNotify({title: gettext("Logout successful"), text: gettext("You are now logged out"), type: "success"}); self.fromResponse(response); - } - }) + }); }; self.onLoginUserKeyup = function(data, event) { if (event.keyCode == 13) { - $("#login_pass").focus(); + self.elementPasswordInput.focus(); } }; @@ -128,6 +110,18 @@ $(function() { self.requestData(); }; + self.onStartup = function() { + self.elementUsernameInput = $("#login_user"); + self.elementPasswordInput = $("#login_pass"); + self.elementLoginButton = $("#login_button"); + if (self.elementUsernameInput && self.elementUsernameInput.length + && self.elementLoginButton && self.elementLoginButton.length) { + self.elementLoginButton.blur(function() { + self.elementUsernameInput.focus(); + }) + } + }; + self.onStartupComplete = function() { self.requestData(); }; @@ -138,4 +132,4 @@ $(function() { [], [] ]); -}); \ No newline at end of file +}); diff --git a/src/octoprint/static/js/app/viewmodels/navigation.js b/src/octoprint/static/js/app/viewmodels/navigation.js index c9f3b9b17..37bebbe89 100644 --- a/src/octoprint/static/js/app/viewmodels/navigation.js +++ b/src/octoprint/static/js/app/viewmodels/navigation.js @@ -6,8 +6,7 @@ $(function() { self.appearance = parameters[1]; self.settings = parameters[2]; self.usersettings = parameters[3]; - - self.systemActions = self.settings.system_actions; + self.system = parameters[4]; self.appearanceClasses = ko.computed(function() { var classes = self.appearance.color(); @@ -17,38 +16,11 @@ $(function() { return classes; }); - self.triggerAction = function(action) { - var callback = function() { - $.ajax({ - url: API_BASEURL + "system", - type: "POST", - dataType: "json", - data: "action=" + action.action, - success: function() { - new PNotify({title: "Success", text: _.sprintf(gettext("The command \"%(command)s\" executed successfully"), {command: action.name}), type: "success"}); - }, - error: function(jqXHR, textStatus, errorThrown) { - if (!action.hasOwnProperty("ignore") || !action.ignore) { - var error = "
" + _.sprintf(gettext("The command \"%(command)s\" could not be executed."), {command: action.name}) + "
"; - error += pnotifyAdditionalInfo("" + jqXHR.responseText + ""); - new PNotify({title: gettext("Error"), text: error, type: "error", hide: false}); - } - } - }) - }; - if (action.confirm) { - showConfirmationDialog(action.confirm, function (e) { - callback(); - }); - } else { - callback(); - } - } } OCTOPRINT_VIEWMODELS.push([ NavigationViewModel, - ["loginStateViewModel", "appearanceViewModel", "settingsViewModel", "userSettingsViewModel"], + ["loginStateViewModel", "appearanceViewModel", "settingsViewModel", "userSettingsViewModel", "systemViewModel"], "#navbar" ]); }); diff --git a/src/octoprint/static/js/app/viewmodels/printerprofiles.js b/src/octoprint/static/js/app/viewmodels/printerprofiles.js index a3f6aa25b..593598db1 100644 --- a/src/octoprint/static/js/app/viewmodels/printerprofiles.js +++ b/src/octoprint/static/js/app/viewmodels/printerprofiles.js @@ -194,12 +194,8 @@ $(function() { }; self.requestData = function() { - $.ajax({ - url: API_BASEURL + "printerprofiles", - type: "GET", - dataType: "json", - success: self.fromResponse - }) + OctoPrint.printerprofiles.get() + .done(self.fromResponse); }; self.fromResponse = function(data) { @@ -228,43 +224,35 @@ $(function() { self.addProfile = function(callback) { var profile = self._editorData(); self.requestInProgress(true); - $.ajax({ - url: API_BASEURL + "printerprofiles", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({profile: profile}), - success: function() { - self.requestInProgress(false); + OctoPrint.printerprofiles.add(profile) + .done(function() { if (callback !== undefined) { callback(); } self.requestData(); - }, - error: function() { - self.requestInProgress(false); + }) + .fail(function() { var text = gettext("There was unexpected error while saving the printer profile, please consult the logs."); new PNotify({title: gettext("Saving failed"), text: text, type: "error", hide: false}); - } - }); + }) + .always(function() { + self.requestInProgress(false); + }); }; self.removeProfile = function(data) { self.requestInProgress(true); - $.ajax({ - url: data.resource, - type: "DELETE", - dataType: "json", - success: function() { - self.requestInProgress(false); + OctoPrint.printerprofiles.delete(data.id, {url: data.resource}) + .done(function() { self.requestData(); - }, - error: function() { - self.requestInProgress(false); + }) + .fail(function() { var text = gettext("There was unexpected error while removing the printer profile, please consult the logs."); new PNotify({title: gettext("Saving failed"), text: text, type: "error", hide: false}); - } - }) + }) + .always(function() { + self.requestInProgress(false); + }); }; self.updateProfile = function(profile, callback) { @@ -273,26 +261,20 @@ $(function() { } self.requestInProgress(true); - - $.ajax({ - url: API_BASEURL + "printerprofiles/" + profile.id, - type: "PATCH", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({profile: profile}), - success: function() { - self.requestInProgress(false); + OctoPrint.printerprofiles.update(profile.id, profile) + .done(function() { if (callback !== undefined) { callback(); } self.requestData(); - }, - error: 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("Saving failed"), text: text, type: "error", hide: false}); - } - }); + }) + .always(function() { + self.requestInProgress(false); + }); }; self.showEditProfileDialog = function(data) { diff --git a/src/octoprint/static/js/app/viewmodels/printerstate.js b/src/octoprint/static/js/app/viewmodels/printerstate.js index 00a7b67ee..fea76dd7e 100644 --- a/src/octoprint/static/js/app/viewmodels/printerstate.js +++ b/src/octoprint/static/js/app/viewmodels/printerstate.js @@ -14,6 +14,16 @@ $(function() { self.isLoading = ko.observable(undefined); self.isSdReady = ko.observable(undefined); + self.enablePrint = ko.computed(function() { + return self.isOperational() && self.isReady() && !self.isPrinting() && self.loginState.isUser() && self.filename() != undefined; + }); + self.enablePause = ko.computed(function() { + return self.isOperational() && (self.isPrinting() || self.isPaused()) && self.loginState.isUser(); + }); + self.enableCancel = ko.computed(function() { + return self.isOperational() && (self.isPrinting() || self.isPaused()) && self.loginState.isUser(); + }); + self.filename = ko.observable(undefined); self.progress = ko.observable(undefined); self.filesize = ko.observable(undefined); @@ -198,43 +208,25 @@ $(function() { }; self.print = function() { - var restartCommand = function() { - self._jobCommand("restart"); - }; - if (self.isPaused()) { - $("#confirmation_dialog .confirmation_dialog_message").text(gettext("This will restart the print job from the beginning.")); - $("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click"); - $("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) {e.preventDefault(); $("#confirmation_dialog").modal("hide"); restartCommand(); }); - $("#confirmation_dialog").modal("show"); + showConfirmationDialog({ + message: gettext("This will restart the print job from the beginning."), + onproceed: function() { + OctoPrint.job.restart(); + } + }); } else { - self._jobCommand("start"); + OctoPrint.job.start(); } - }; self.pause = function() { - self._jobCommand("pause"); + OctoPrint.job.pause(); }; self.cancel = function() { - self._jobCommand("cancel"); + OctoPrint.job.cancel(); }; - - self._jobCommand = function(command, callback) { - $.ajax({ - url: API_BASEURL + "job", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({command: command}), - success: function(response) { - if (callback != undefined) { - callback(); - } - } - }); - } } OCTOPRINT_VIEWMODELS.push([ @@ -242,4 +234,4 @@ $(function() { ["loginStateViewModel"], ["#state_wrapper", "#drop_overlay"] ]); -}); \ No newline at end of file +}); diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 79c6d526b..ce0aefb86 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -6,20 +6,17 @@ $(function() { self.users = parameters[1]; self.printerProfiles = parameters[2]; + self.allViewModels = []; + self.receiving = ko.observable(false); self.sending = ko.observable(false); - self.callbacks = []; - - self.api_enabled = ko.observable(undefined); - self.api_key = ko.observable(undefined); - self.api_allowCrossOrigin = ko.observable(undefined); - - self.appearance_name = ko.observable(undefined); - self.appearance_color = ko.observable(undefined); - self.appearance_colorTransparent = ko.observable(); - self.appearance_defaultLanguage = ko.observable(); + self.exchanging = ko.computed(function() { + return self.receiving() || self.sending(); + }); + self.outstanding = []; self.settingsDialog = undefined; + self.settings_dialog_update_detected = undefined; self.translationManagerDialog = undefined; self.translationUploadElement = $("#settings_appearance_managelanguagesdialog_upload"); self.translationUploadButton = $("#settings_appearance_managelanguagesdialog_upload_start"); @@ -95,6 +92,15 @@ $(function() { }))); self.locale_languages = _.keys(AVAILABLE_LOCALES); + self.api_enabled = ko.observable(undefined); + self.api_key = ko.observable(undefined); + self.api_allowCrossOrigin = ko.observable(undefined); + + self.appearance_name = ko.observable(undefined); + self.appearance_color = ko.observable(undefined); + self.appearance_colorTransparent = ko.observable(); + self.appearance_defaultLanguage = ko.observable(); + self.printer_defaultExtrusionLength = ko.observable(undefined); self.webcam_streamUrl = ko.observable(undefined); @@ -110,7 +116,7 @@ $(function() { self.feature_gcodeViewer = ko.observable(undefined); self.feature_temperatureGraph = ko.observable(undefined); self.feature_waitForStart = ko.observable(undefined); - self.feature_alwaysSendChecksum = ko.observable(undefined); + self.feature_sendChecksum = ko.observable("print"); self.feature_sdSupport = ko.observable(undefined); self.feature_sdAlwaysAvailable = ko.observable(undefined); self.feature_swallowOkAfterResend = ko.observable(undefined); @@ -129,10 +135,14 @@ $(function() { self.serial_timeoutDetection = ko.observable(undefined); self.serial_timeoutCommunication = ko.observable(undefined); self.serial_timeoutTemperature = ko.observable(undefined); + self.serial_timeoutTemperatureTargetSet = ko.observable(undefined); self.serial_timeoutSdStatus = ko.observable(undefined); self.serial_log = ko.observable(undefined); self.serial_additionalPorts = ko.observable(undefined); + self.serial_additionalBaudrates = ko.observable(undefined); self.serial_longRunningCommands = ko.observable(undefined); + self.serial_checksumRequiringCommands = ko.observable(undefined); + self.serial_helloCommand = ko.observable(undefined); self.folder_uploads = ko.observable(undefined); self.folder_timelapse = ko.observable(undefined); @@ -146,6 +156,7 @@ $(function() { self.scripts_gcode_afterPrintPaused = ko.observable(undefined); self.scripts_gcode_beforePrintResumed = ko.observable(undefined); self.scripts_gcode_afterPrinterConnected = ko.observable(undefined); + self.scripts_gcode_beforePrinterDisconnected = ko.observable(undefined); self.temperature_profiles = ko.observableArray(undefined); self.temperature_cutoff = ko.observable(undefined); @@ -164,6 +175,16 @@ $(function() { self.server_diskspace_critical_str = sizeObservable(self.server_diskspace_critical); self.settings = undefined; + self.lastReceivedSettings = undefined; + + self.webcam_ffmpegPathText = ko.observable(); + self.webcam_ffmpegPathOk = ko.observable(false); + self.webcam_ffmpegPathBroken = ko.observable(false); + self.webcam_ffmpegPathReset = function() { + self.webcam_ffmpegPathText(""); + self.webcam_ffmpegPathOk(false); + self.webcam_ffmpegPathBroken(false); + }; self.addTemperatureProfile = function() { self.temperature_profiles.push({name: "New", extruder:0, bed:0}); @@ -181,12 +202,106 @@ $(function() { self.terminalFilters.remove(filter); }; + self.testWebcamStreamUrl = function() { + if (!self.webcam_streamUrl()) { + return; + } + + var text = gettext("If you see your webcam stream below, the entered stream URL is ok."); + var image = $('
' + text + '
" + _.sprintf(gettext("The command \"%(command)s\" could not be executed."), {command: commandSpec.name}) + "
"; + error += pnotifyAdditionalInfo("" + jqXHR.responseText + ""); + new PNotify({title: gettext("Error"), text: error, type: "error", hide: false}); + deferred.reject(["error", arguments]); + } else { + deferred.resolve(["ignored", arguments]); + } + }); + }; + + if (commandSpec.confirm) { + showConfirmationDialog({ + message: commandSpec.confirm, + onproceed: function() { + callback(); + }, + oncancel: function() { + deferred.reject("cancelled", arguments); + } + }); + } else { + callback(); + } + + return deferred.promise(); + }; + + self.onUserLoggedIn = function(user) { + if (user.admin) { + self.requestData(); + } else { + self.onUserLoggedOut(); + } + }; + + self.onUserLoggedOut = function() { + self.lastCommandResponse = undefined; + self.systemActions([]); + }; + + self.onEventSettingsUpdated = function() { + if (self.loginState.isAdmin()) { + self.requestData(); + } + }; + } + + // view model class, parameters for constructor, container to bind to + ADDITIONAL_VIEWMODELS.push([ + SystemViewModel, + ["loginStateViewModel"], + [] + ]); +}); diff --git a/src/octoprint/static/js/app/viewmodels/temperature.js b/src/octoprint/static/js/app/viewmodels/temperature.js index e05cfd6a9..9a4ea6519 100644 --- a/src/octoprint/static/js/app/viewmodels/temperature.js +++ b/src/octoprint/static/js/app/viewmodels/temperature.js @@ -233,6 +233,8 @@ $(function() { var heaterOptions = self.heaterOptions(); if (!heaterOptions) return; + var maxTemps = [310/1.1]; + _.each(_.keys(heaterOptions), function(type) { if (type == "bed" && !self.hasBed()) { return; @@ -259,97 +261,113 @@ $(function() { color: pusher.color(heaterOptions[type].color).tint(0.5).html(), data: targets }); + + maxTemps.push(self.getMaxTemp(actuals, targets)); }); + self.plotOptions.yaxis.max = Math.max.apply(null, maxTemps) * 1.1; $.plot(graph, data, self.plotOptions); } }; + self.getMaxTemp = function(actuals, targets) { + var pair; + var maxTemp = 0; + actuals.forEach(function(pair) { + if (pair[1] > maxTemp){ + maxTemp = pair[1]; + } + }); + targets.forEach(function(pair) { + if (pair[1] > maxTemp){ + maxTemp = pair[1]; + } + }); + return maxTemp; + } + self.setTarget = function(item) { var value = item.newTarget(); if (!value) return; - self._sendToolCommand("target", - item.key(), - item.newTarget(), - function() {item.newTarget("");} - ); + var onSuccess = function() { + item.newTarget(""); + }; + + if (item.key() == "bed") { + self._setBedTemperature(value) + .done(onSuccess); + } else { + self._setToolTemperature(item.key(), value) + .done(onSuccess); + } }; self.setTargetFromProfile = function(item, profile) { if (!profile) return; - var value = undefined; - if (item.key() == "bed") { - value = profile.bed; - } else { - value = profile.extruder; - } + var onSuccess = function() { + item.newTarget(""); + }; - self._sendToolCommand("target", - item.key(), - value, - function() {item.newTarget("");} - ); + if (item.key() == "bed") { + self._setBedTemperature(profile.bed) + .done(onSuccess); + } else { + self._setToolTemperature(item.key(), profile.extruder) + .done(onSuccess); + } }; self.setTargetToZero = function(item) { - self._sendToolCommand("target", - item.key(), - 0, - function() {item.newTarget("");} - ); + var onSuccess = function() { + item.newTarget(""); + }; + + if (item.key() == "bed") { + self._setBedTemperature(0) + .done(onSuccess); + } else { + self._setToolTemperature(item.key(), 0) + .done(onSuccess); + } }; self.setOffset = function(item) { - self._sendToolCommand("offset", - item.key(), - item.newOffset(), - function() {item.newOffset("");} - ); - }; + var value = item.newOffset(); + if (!value) return; - self._sendToolCommand = function(command, type, temp, successCb, errorCb) { - var data = { - command: command + var onSuccess = function() { + item.newOffset(""); }; - var endpoint; - if (type == "bed") { - if ("target" == command) { - data["target"] = parseInt(temp); - } else if ("offset" == command) { - data["offset"] = parseInt(temp); - } else { - return; - } - - endpoint = "bed"; + if (item.key() == "bed") { + self._setBedOffset(value) + .done(onSuccess); } else { - var group; - if ("target" == command) { - group = "targets"; - } else if ("offset" == command) { - group = "offsets"; - } else { - return; - } - data[group] = {}; - data[group][type] = parseInt(temp); - - endpoint = "tool"; + self._setToolOffset(item.key(), value) + .done(onSuccess); } + }; - $.ajax({ - url: API_BASEURL + "printer/" + endpoint, - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(data), - success: function() { if (successCb !== undefined) successCb(); }, - error: function() { if (errorCb !== undefined) errorCb(); } - }); + self._setToolTemperature = function(tool, temperature) { + var data = {}; + data[tool] = parseInt(temperature); + return OctoPrint.printer.setToolTargetTemperatures(data); + }; + self._setToolOffset = function(tool, offset) { + var data = {}; + data[tool] = parseInt(offset); + return OctoPrint.printer.setToolTemperatureOffsets(data); + }; + + self._setBedTemperature = function(temperature) { + return OctoPrint.printer.setBedTargetTemperature(parseInt(temperature)); + }; + + self._setBedOffset = function(offset) { + return OctoPrint.printer.setBedTemperatureOffset(parseInt(offset)); }; self.handleEnter = function(event, type, item) { diff --git a/src/octoprint/static/js/app/viewmodels/terminal.js b/src/octoprint/static/js/app/viewmodels/terminal.js index ba7b04363..49f09778a 100644 --- a/src/octoprint/static/js/app/viewmodels/terminal.js +++ b/src/octoprint/static/js/app/viewmodels/terminal.js @@ -188,29 +188,18 @@ $(function() { } if (command) { - $.ajax({ - url: API_BASEURL + "printer/command", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({"command": command}) - }); - - self.cmdHistory.push(command); - self.cmdHistory.slice(-300); // just to set a sane limit to how many manually entered commands will be saved... - self.cmdHistoryIdx = self.cmdHistory.length; - self.command(""); + OctoPrint.control.sendGcode(command) + .done(function() { + self.cmdHistory.push(command); + self.cmdHistory.slice(-300); // just to set a sane limit to how many manually entered commands will be saved... + self.cmdHistoryIdx = self.cmdHistory.length; + self.command(""); + }); } }; self.fakeAck = function() { - $.ajax({ - url: API_BASEURL + "connection", - type: "POST", - dataType: "json", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({"command": "fake_ack"}) - }); + OctoPrint.printer.fakeAck(); }; self.handleKeyDown = function(event) { diff --git a/src/octoprint/static/js/app/viewmodels/timelapse.js b/src/octoprint/static/js/app/viewmodels/timelapse.js index ed4188b51..0b3a09503 100644 --- a/src/octoprint/static/js/app/viewmodels/timelapse.js +++ b/src/octoprint/static/js/app/viewmodels/timelapse.js @@ -34,20 +34,20 @@ $(function() { return self.isDirty() && self.isOperational() && !self.isPrinting() && self.loginState.isUser(); }); - self.isOperational.subscribe(function(newValue) { + self.isOperational.subscribe(function() { self.requestData(); }); - self.timelapseType.subscribe(function(newValue) { + self.timelapseType.subscribe(function() { self.isDirty(true); }); - self.timelapseTimedInterval.subscribe(function(newValue) { + self.timelapseTimedInterval.subscribe(function() { self.isDirty(true); }); - self.timelapsePostRoll.subscribe(function(newValue) { + self.timelapsePostRoll.subscribe(function() { self.isDirty(true); }); - self.timelapseFps.subscribe(function(newValue) { + self.timelapseFps.subscribe(function() { self.isDirty(true); }); @@ -83,12 +83,8 @@ $(function() { ); self.requestData = function() { - $.ajax({ - url: API_BASEURL + "timelapse", - type: "GET", - dataType: "json", - success: self.fromResponse - }); + OctoPrint.timelapse.get() + .done(self.fromResponse); }; self.fromResponse = function(response) { @@ -141,15 +137,11 @@ $(function() { }; self.removeFile = function(filename) { - $.ajax({ - url: API_BASEURL + "timelapse/" + filename, - type: "DELETE", - dataType: "json", - success: self.requestData - }); + OctoPrint.timelapse.delete(filename) + .done(self.requestData); }; - self.save = function(data, event) { + self.save = function() { var payload = { "type": self.timelapseType(), "postRoll": self.timelapsePostRoll(), @@ -161,20 +153,15 @@ $(function() { payload["interval"] = self.timelapseTimedInterval(); } - $.ajax({ - url: API_BASEURL + "timelapse", - type: "POST", - dataType: "json", - data: payload, - success: self.fromResponse - }); + OctoPrint.timelapse.saveConfig(payload) + .done(self.fromResponse); }; self.onDataUpdaterReconnect = function() { self.requestData(); }; - self.onEventMovieDone = function(payload) { + self.onEventMovieDone = function() { self.requestData(); }; diff --git a/src/octoprint/static/js/app/viewmodels/users.js b/src/octoprint/static/js/app/viewmodels/users.js index c341a067b..235dd28df 100644 --- a/src/octoprint/static/js/app/viewmodels/users.js +++ b/src/octoprint/static/js/app/viewmodels/users.js @@ -60,12 +60,8 @@ $(function() { self.requestData = function() { if (!CONFIG_ACCESS_CONTROL) return; - $.ajax({ - url: API_BASEURL + "users", - type: "GET", - dataType: "json", - success: self.fromResponse - }); + OctoPrint.users.list() + .done(self.fromResponse); }; self.fromResponse = function(response) { @@ -83,12 +79,19 @@ $(function() { self.confirmAddUser = function() { if (!CONFIG_ACCESS_CONTROL) return; - var user = {name: self.editorUsername(), password: self.editorPassword(), admin: self.editorAdmin(), active: self.editorActive()}; - self.addUser(user, function() { - // close dialog - self.currentUser(undefined); - self.addUserDialog.modal("hide"); - }); + var user = { + name: self.editorUsername(), + password: self.editorPassword(), + admin: self.editorAdmin(), + active: self.editorActive() + }; + + self.addUser(user) + .done(function() { + // close dialog + self.currentUser(undefined); + self.addUserDialog.modal("hide"); + }); }; self.showEditUserDialog = function(user) { @@ -105,12 +108,12 @@ $(function() { user.active = self.editorActive(); user.admin = self.editorAdmin(); - // make AJAX call - self.updateUser(user, function() { - // close dialog - self.currentUser(undefined); - self.editUserDialog.modal("hide"); - }); + self.updateUser(user) + .done(function() { + // close dialog + self.currentUser(undefined); + self.editUserDialog.modal("hide"); + }); }; self.showChangePasswordDialog = function(user) { @@ -123,27 +126,30 @@ $(function() { self.confirmChangePassword = function() { if (!CONFIG_ACCESS_CONTROL) return; - self.updatePassword(self.currentUser().name, self.editorPassword(), function() { - // close dialog - self.currentUser(undefined); - self.changePasswordDialog.modal("hide"); - }); + self.updatePassword(self.currentUser().name, self.editorPassword()) + .done(function() { + // close dialog + self.currentUser(undefined); + self.changePasswordDialog.modal("hide"); + }); }; self.confirmGenerateApikey = function() { if (!CONFIG_ACCESS_CONTROL) return; - self.generateApikey(self.currentUser().name, function(response) { - self._updateApikey(response.apikey); - }) + self.generateApikey(self.currentUser().name) + .done(function(response) { + self._updateApikey(response.apikey); + }); }; self.confirmDeleteApikey = function() { if (!CONFIG_ACCESS_CONTROL) return; - self.deleteApikey(self.currentUser().name, function() { - self._updateApikey(undefined); - }) + self.deleteApikey(self.currentUser().name) + .done(function() { + self._updateApikey(undefined); + }); }; self._updateApikey = function(apikey) { @@ -159,108 +165,55 @@ $(function() { self.changePasswordDialog = $("#settings-usersDialogChangePassword"); }; - //~~ AJAX calls + //~~ API calls - self.addUser = function(user, callback) { - if (!CONFIG_ACCESS_CONTROL) return; - if (user === undefined) return; + self.addUser = function(user) { + if (!user) { + throw OctoPrint.InvalidArgumentError("user must be set"); + } - $.ajax({ - url: API_BASEURL + "users", - type: "POST", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(user), - success: function(response) { - self.fromResponse(response); - if (callback) { - callback(response); - } - } - }); + return OctoPrint.users.add(user) + .done(self.fromResponse); }; - self.removeUser = function(user, callback) { - if (!CONFIG_ACCESS_CONTROL) return; - if (user === undefined) return; + self.removeUser = function(user) { + if (!user) { + throw OctoPrint.InvalidArgumentError("user must be set"); + } if (user.name == self.loginState.username()) { // we do not allow to delete ourselves - new PNotify({title: "Not possible", text: "You may not delete your own account.", type: "error"}); - return; + new PNotify({ + title: gettext("Not possible"), + text: gettext("You may not delete your own account."), + type: "error" + }); + return $.Deferred().reject("You may not delete your own account").promise(); } - $.ajax({ - url: API_BASEURL + "users/" + user.name, - type: "DELETE", - success: function(response) { - self.fromResponse(response); - if (callback) { - callback(response); - } - } - }); + return OctoPrint.users.delete(user.name) + .done(self.fromResponse); }; - self.updateUser = function(user, callback) { - if (!CONFIG_ACCESS_CONTROL) return; - if (user === undefined) return; + self.updateUser = function(user) { + if (!user) { + throw OctoPrint.InvalidArgumentError("user must be set"); + } - $.ajax({ - url: API_BASEURL + "users/" + user.name, - type: "PUT", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(user), - success: function(response) { - self.fromResponse(response); - if (callback) { - callback(response); - } - } - }); + return OctoPrint.users.update(user.name, user.active, user.admin) + .done(self.fromResponse); }; - self.updatePassword = function(username, password, callback) { - if (!CONFIG_ACCESS_CONTROL) return; - - $.ajax({ - url: API_BASEURL + "users/" + username + "/password", - type: "PUT", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify({password: password}), - success: function(response) { - if (callback) { - callback(response); - } - } - }); + self.updatePassword = function(username, password) { + return OctoPrint.users.changePassword(username, password); }; - self.generateApikey = function(username, callback) { - if (!CONFIG_ACCESS_CONTROL) return; - - $.ajax({ - url: API_BASEURL + "users/" + username + "/apikey", - type: "POST", - success: function(response) { - if (callback) { - callback(response); - } - } - }); + self.generateApikey = function(username) { + return OctoPrint.users.generateApiKey(username); }; - self.deleteApikey = function(username, callback) { - if (!CONFIG_ACCESS_CONTROL) return; - - $.ajax({ - url: API_BASEURL + "users/" + username + "/apikey", - type: "DELETE", - success: function(response) { - if (callback) { - callback(response); - } - } - }); + self.deleteApikey = function(username) { + return OctoPrint.users.resetApiKey(username); }; self.onUserLoggedIn = function(user) { @@ -275,4 +228,4 @@ $(function() { ["loginStateViewModel"], [] ]); -}); \ No newline at end of file +}); diff --git a/src/octoprint/static/js/app/viewmodels/usersettings.js b/src/octoprint/static/js/app/viewmodels/usersettings.js index d92a13fc8..99b796315 100644 --- a/src/octoprint/static/js/app/viewmodels/usersettings.js +++ b/src/octoprint/static/js/app/viewmodels/usersettings.js @@ -60,24 +60,17 @@ $(function() { "language": self.interface_language() } }; - self.updateSettings(self.currentUser().name, settings, function() { - // close dialog - self.currentUser(undefined); - self.userSettingsDialog.modal("hide"); - self.loginState.reloadUser(); - }); + self.updateSettings(self.currentUser().name, settings) + .done(function() { + // close dialog + self.currentUser(undefined); + self.userSettingsDialog.modal("hide"); + self.loginState.reloadUser(); + }); }; - self.updateSettings = function(username, settings, callback) { - if (!CONFIG_ACCESS_CONTROL) return; - - $.ajax({ - url: API_BASEURL + "users/" + username + "/settings", - type: "PATCH", - contentType: "application/json; charset=UTF-8", - data: JSON.stringify(settings), - success: callback - }); + self.updateSettings = function(username, settings) { + return OctoPrint.users.saveSettings(username, settings); }; self.saveEnabled = function() { @@ -90,18 +83,10 @@ $(function() { self.onAllBound = function(allViewModels) { self.userSettingsDialog.on('show', function() { - _.each(allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onUserSettingsShown")) { - viewModel.onUserSettingsShown(); - } - }); + callViewModels(allViewModels, "onUserSettingsShown"); }); self.userSettingsDialog.on('hidden', function() { - _.each(allViewModels, function(viewModel) { - if (viewModel.hasOwnProperty("onUserSettingsHidden")) { - viewModel.onUserSettingsHidden(); - } - }); + callViewModels(allViewModels, "onUserSettingsHidden"); }); } @@ -112,4 +97,4 @@ $(function() { ["loginStateViewModel", "usersViewModel"], ["#usersettings_dialog"] ]); -}); \ No newline at end of file +}); diff --git a/src/octoprint/static/js/app/viewmodels/wizard.js b/src/octoprint/static/js/app/viewmodels/wizard.js new file mode 100644 index 000000000..de9db3d0f --- /dev/null +++ b/src/octoprint/static/js/app/viewmodels/wizard.js @@ -0,0 +1,188 @@ +$(function() { + function WizardViewModel(parameters) { + var self = this; + + self.loginState = parameters[0]; + self.settingsViewModel = parameters[1]; + + self.wizardDialog = undefined; + self.reloadOverlay = undefined; + + self.allViewModels = undefined; + + self.finishing = false; + self.wizards = []; + + self.isDialogActive = function() { + return self.wizardDialog.is(":visible"); + }; + + self.showDialog = function() { + if (!CONFIG_WIZARD || !(CONFIG_FIRST_RUN || self.loginState.isAdmin())) return; + + self.getWizardDetails() + .done(function(response) { + callViewModels(self.allViewModels, "onWizardDetails", [response]); + + if (!self.isDialogActive()) { + self.wizardDialog.modal({ + minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); } + }).css({ + width: 'auto', + 'margin-left': function() { return -($(this).width() /2); } + }); + } + }); + }; + + self.closeDialog = function() { + self.wizardDialog.modal("hide"); + }; + + self.onStartup = function() { + self.wizardDialog = $("#wizard_dialog"); + self.reloadOverlay = $("#reloadui_overlay"); + }; + + self.onUserLoggedIn = function() { + self.showDialog(); + }; + + self.onAllBound = function(allViewModels) { + self.allViewModels = allViewModels; + self.wizardDialog.bootstrapWizard({ + tabClass: "nav nav-list", + nextSelector: ".button-next", + previousSelector: ".button-previous", + finishSelector: ".button-finish", + onTabClick: function() { + // we don't allow clicking on the tabs + return false; + }, + onTabShow: function(tab, navigation, index) { + if (index < 0 || tab.length == 0) { + return true; + } + + var total = self.wizardDialog.bootstrapWizard("navigationLength"); + + if (index == total) { + self.wizardDialog.find(".button-next").hide(); + self.wizardDialog.find(".button-finish").show().removeClass("disabled"); + } else { + self.wizardDialog.find(".button-finish").hide(); + self.wizardDialog.find(".button-next").show(); + } + + var active = tab[0].id; + if (active != undefined) { + callViewModels(allViewModels, "onAfterWizardTabChange", [active]); + } + }, + onTabChange: function(tab, navigation, index, nextTabIndex, nextTab) { + var current, next; + + if (index == undefined || index < 0 || + nextTabIndex == undefined || nextTabIndex < 0 || + index == nextTabIndex || + tab.length == 0 || nextTab.length == 0) { + // let's ignore that nonsense + return; + } + + current = tab[0].id; + next = nextTab[0].id; + + if (current != undefined && next != undefined) { + var result = true; + callViewModels(allViewModels, "onWizardTabChange", function(method) { + result = result && (method(current, next) !== false); + }); + return result; + } + }, + onFinish: function(tab, navigation, index) { + var closeDialog = true; + callViewModels(allViewModels, "onBeforeWizardFinish", function(method) { + // we don't need to call all methods here, one method saying that + // the dialog must not be closed yet is enough to stop + // + // we evaluate closeDialog first to make sure we don't call + // the method once it becomes false + closeDialog = closeDialog && (method() !== false); + }); + + if (closeDialog) { + var reload = false; + callViewModels(allViewModels, "onWizardFinish", function(method) { + // if any of our methods returns that it wants to reload + // we'll need to set reload to true + // + // order is important here - the method call needs to happen + // first, or it won't happen after the reload flag has been + // set once due to the || making further evaluation unnecessary + // then + reload = (method() == "reload") || reload; + }); + self.finishWizard() + .done(function() { + self.closeDialog(); + if (reload) { + self.reloadOverlay.show(); + } + }); + } + } + }); + self.showDialog(); + }; + + self.getWizardDetails = function() { + return OctoPrint.wizard.get() + .done(function(response) { + self.wizards = _.filter(_.keys(response), function(key) { return response[key] && response[key]["required"] && !response[key]["ignored"]; }); + }); + }; + + self.finishWizard = function() { + var deferred = $.Deferred(); + self.finishing = true; + + self.settingsViewModel.saveData() + .done(function() { + OctoPrint.wizard.finish(self.wizards) + .done(function() { + deferred.resolve(arguments); + }) + .fail(function() { + deferred.reject(arguments); + }) + .always(function() { + self.finishing = false; + }); + }) + .fail(function() { + deferred.reject(arguments); + }); + + return deferred; + }; + + self.onSettingsPreventRefresh = function() { + if (!self.finishing && self.isDialogActive() + && hasDataChanged(self.settingsViewModel.getLocalData(), self.settingsViewModel.lastReceivedSettings)) { + // we have local changes, show update dialog + self.settingsViewModel.settingsUpdatedDialog.modal("show"); + return true; + } + + return false; + } + } + + OCTOPRINT_VIEWMODELS.push([ + WizardViewModel, + ["loginStateViewModel", "settingsViewModel"], + "#wizard_dialog" + ]); +}); diff --git a/src/octoprint/static/js/lib/bootstrap/bootstrap.js b/src/octoprint/static/js/lib/bootstrap/bootstrap.js index 04c0ae45a..5ca3cc94f 100644 --- a/src/octoprint/static/js/lib/bootstrap/bootstrap.js +++ b/src/octoprint/static/js/lib/bootstrap/bootstrap.js @@ -1,8 +1,8 @@ /* =================================================== - * bootstrap-transition.js v2.2.2 - * http://twitter.github.com/bootstrap/javascript.html#transitions + * bootstrap-transition.js v2.3.2 + * http://getbootstrap.com/2.3.2/javascript.html#transitions * =================================================== - * Copyright 2012 Twitter, Inc. + * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,10 +58,10 @@ }) }(window.jQuery);/* ========================================================== - * bootstrap-alert.js v2.2.2 - * http://twitter.github.com/bootstrap/javascript.html#alerts + * bootstrap-alert.js v2.3.2 + * http://getbootstrap.com/2.3.2/javascript.html#alerts * ========================================================== - * Copyright 2012 Twitter, Inc. + * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -156,10 +156,10 @@ $(document).on('click.alert.data-api', dismiss, Alert.prototype.close) }(window.jQuery);/* ============================================================ - * bootstrap-button.js v2.2.2 - * http://twitter.github.com/bootstrap/javascript.html#buttons + * bootstrap-button.js v2.3.2 + * http://getbootstrap.com/2.3.2/javascript.html#buttons * ============================================================ - * Copyright 2012 Twitter, Inc. + * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -260,10 +260,10 @@ }) }(window.jQuery);/* ========================================================== - * bootstrap-carousel.js v2.2.2 - * http://twitter.github.com/bootstrap/javascript.html#carousel + * bootstrap-carousel.js v2.3.2 + * http://getbootstrap.com/2.3.2/javascript.html#carousel * ========================================================== - * Copyright 2012 Twitter, Inc. + * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -289,6 +289,7 @@ var Carousel = function (element, options) { this.$element = $(element) + this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) @@ -299,19 +300,24 @@ cycle: function (e) { if (!e) this.paused = false + if (this.interval) clearInterval(this.interval); this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } + , getActiveIndex: function () { + this.$active = this.$element.find('.item.active') + this.$items = this.$active.parent().children() + return this.$items.index(this.$active) + } + , to: function (pos) { - var $active = this.$element.find('.item.active') - , children = $active.parent().children() - , activePos = children.index($active) + var activeIndex = this.getActiveIndex() , that = this - if (pos > (children.length - 1) || pos < 0) return + if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) { return this.$element.one('slid', function () { @@ -319,18 +325,18 @@ }) } - if (activePos == pos) { + if (activeIndex == pos) { return this.pause().cycle() } - return this.slide(pos > activePos ? 'next' : 'prev', $(children[pos])) + return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } , pause: function (e) { if (!e) this.paused = true if (this.$element.find('.next, .prev').length && $.support.transition.end) { this.$element.trigger($.support.transition.end) - this.cycle() + this.cycle(true) } clearInterval(this.interval) this.interval = null @@ -364,10 +370,19 @@ e = $.Event('slide', { relatedTarget: $next[0] + , direction: direction }) if ($next.hasClass('active')) return + if (this.$indicators.length) { + this.$indicators.find('.active').removeClass('active') + this.$element.one('slid', function () { + var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) + $nextIndicator && $nextIndicator.addClass('active') + }) + } + if ($.support.transition && this.$element.hasClass('slide')) { this.$element.trigger(e) if (e.isDefaultPrevented()) return @@ -412,7 +427,7 @@ if (!data) $this.data('carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() - else if (options.interval) data.cycle() + else if (options.interval) data.pause().cycle() }) } @@ -435,19 +450,26 @@ /* CAROUSEL DATA-API * ================= */ - $(document).on('click.carousel.data-api', '[data-slide]', function (e) { + $(document).on('click.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var $this = $(this), href , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 , options = $.extend({}, $target.data(), $this.data()) + , slideIndex + $target.carousel(options) + + if (slideIndex = $this.attr('data-slide-to')) { + $target.data('carousel').pause().to(slideIndex).cycle() + } + e.preventDefault() }) }(window.jQuery);/* ============================================================= - * bootstrap-collapse.js v2.2.2 - * http://twitter.github.com/bootstrap/javascript.html#collapse + * bootstrap-collapse.js v2.3.2 + * http://getbootstrap.com/2.3.2/javascript.html#collapse * ============================================================= - * Copyright 2012 Twitter, Inc. + * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -497,7 +519,7 @@ , actives , hasData - if (this.transitioning) return + if (this.transitioning || this.$element.hasClass('in')) return dimension = this.dimension() scroll = $.camelCase(['scroll', dimension].join('-')) @@ -517,7 +539,7 @@ , hide: function () { var dimension - if (this.transitioning) return + if (this.transitioning || !this.$element.hasClass('in')) return dimension = this.dimension() this.reset(this.$element[dimension]()) this.transition('removeClass', $.Event('hide'), 'hidden') @@ -574,7 +596,7 @@ return this.each(function () { var $this = $(this) , data = $this.data('collapse') - , options = typeof option == 'object' && option + , options = $.extend({}, $.fn.collapse.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) @@ -610,10 +632,10 @@ }) }(window.jQuery);/* ============================================================ - * bootstrap-dropdown.js v2.2.2 - * http://twitter.github.com/bootstrap/javascript.html#dropdowns + * bootstrap-dropdown.js v2.3.2 + * http://getbootstrap.com/2.3.2/javascript.html#dropdowns * ============================================================ - * Copyright 2012 Twitter, Inc. + * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -663,6 +685,10 @@ clearMenus() if (!isActive) { + if ('ontouchstart' in document.documentElement) { + // if mobile we we use a backdrop because click events don't delegate + $('').insertBefore($(this)).on('click', clearMenus) + } $parent.toggleClass('open') } @@ -692,7 +718,10 @@ isActive = $parent.hasClass('open') - if (!isActive || (isActive && e.keyCode == 27)) return $this.click() + if (!isActive || (isActive && e.keyCode == 27)) { + if (e.which == 27) $parent.find(toggle).focus() + return $this.click() + } $items = $('[role=menu] li:not(.divider):visible a', $parent) @@ -712,6 +741,7 @@ } function clearMenus() { + $('.dropdown-backdrop').remove() $(toggle).each(function () { getParent($(this)).removeClass('open') }) @@ -764,17 +794,17 @@ * =================================== */ $(document) - .on('click.dropdown.data-api touchstart.dropdown.data-api', clearMenus) - .on('click.dropdown touchstart.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) - .on('touchstart.dropdown.data-api', '.dropdown-menu', function (e) { e.stopPropagation() }) - .on('click.dropdown.data-api touchstart.dropdown.data-api' , toggle, Dropdown.prototype.toggle) - .on('keydown.dropdown.data-api touchstart.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown) + .on('click.dropdown.data-api', clearMenus) + .on('click.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) + .on('click.dropdown.data-api' , toggle, Dropdown.prototype.toggle) + .on('keydown.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown) -}(window.jQuery);/* ========================================================= - * bootstrap-modal.js v2.2.2 - * http://twitter.github.com/bootstrap/javascript.html#modals +}(window.jQuery); +/* ========================================================= + * bootstrap-modal.js v2.3.2 + * http://getbootstrap.com/2.3.2/javascript.html#modals * ========================================================= - * Copyright 2012 Twitter, Inc. + * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -832,8 +862,7 @@ that.$element.appendTo(document.body) //don't move modals dom position } - that.$element - .show() + that.$element.show() if (transition) { that.$element[0].offsetWidth // force reflow @@ -911,16 +940,17 @@ }) } - , hideModal: function (that) { - this.$element - .hide() - .trigger('hidden') - - this.backdrop() + , hideModal: function () { + var that = this + this.$element.hide() + this.backdrop(function () { + that.removeBackdrop() + that.$element.trigger('hidden') + }) } , removeBackdrop: function () { - this.$backdrop.remove() + this.$backdrop && this.$backdrop.remove() this.$backdrop = null } @@ -944,6 +974,8 @@ this.$backdrop.addClass('in') + if (!callback) return + doAnimate ? this.$backdrop.one($.support.transition.end, callback) : callback() @@ -952,8 +984,8 @@ this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? - this.$backdrop.one($.support.transition.end, $.proxy(this.removeBackdrop, this)) : - this.removeBackdrop() + this.$backdrop.one($.support.transition.end, callback) : + callback() } else if (callback) { callback() @@ -1016,11 +1048,11 @@ }(window.jQuery); /* =========================================================== - * bootstrap-tooltip.js v2.2.2 - * http://twitter.github.com/bootstrap/javascript.html#tooltips + * bootstrap-tooltip.js v2.3.2 + * http://getbootstrap.com/2.3.2/javascript.html#tooltips * Inspired by the original jQuery.tipsy by Jason Frame * =========================================================== - * Copyright 2012 Twitter, Inc. + * Copyright 2013 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -1055,19 +1087,27 @@ , init: function (type, element, options) { var eventIn , eventOut + , triggers + , trigger + , i this.type = type this.$element = $(element) this.options = this.getOptions(options) this.enabled = true - if (this.options.trigger == 'click') { - this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) - } else if (this.options.trigger != 'manual') { - eventIn = this.options.trigger == 'hover' ? 'mouseenter' : 'focus' - eventOut = this.options.trigger == 'hover' ? 'mouseleave' : 'blur' - this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) - this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) + triggers = this.options.trigger.split(' ') + + for (i = triggers.length; i--;) { + trigger = triggers[i] + if (trigger == 'click') { + this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) + } else if (trigger != 'manual') { + eventIn = trigger == 'hover' ? 'mouseenter' : 'focus' + eventOut = trigger == 'hover' ? 'mouseleave' : 'blur' + this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) + this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) + } } this.options.selector ? @@ -1076,7 +1116,7 @@ } , getOptions: function (options) { - options = $.extend({}, $.fn[this.type].defaults, options, this.$element.data()) + options = $.extend({}, $.fn[this.type].defaults, this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { @@ -1089,7 +1129,15 @@ } , enter: function (e) { - var self = $(e.currentTarget)[this.type](this._options).data(this.type) + var defaults = $.fn[this.type].defaults + , options = {} + , self + + this._options && $.each(this._options, function (key, value) { + if (defaults[key] != value) options[key] = value + }, this) + + self = $(e.currentTarget)[this.type](options).data(this.type) if (!self.options.delay || !self.options.delay.show) return self.show() @@ -1114,14 +1162,16 @@ , show: function () { var $tip - , inside , pos , actualWidth , actualHeight , placement , tp + , e = $.Event('show') if (this.hasContent() && this.enabled) { + this.$element.trigger(e) + if (e.isDefaultPrevented()) return $tip = this.tip() this.setContent() @@ -1133,19 +1183,18 @@ this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement - inside = /in/.test(placement) - $tip .detach() .css({ top: 0, left: 0, display: 'block' }) - .insertAfter(this.$element) - pos = this.getPosition(inside) + this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) + + pos = this.getPosition() actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight - switch (inside ? placement.split(' ')[1] : placement) { + switch (placement) { case 'bottom': tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2} break @@ -1160,13 +1209,58 @@ break } - $tip - .offset(tp) - .addClass(placement) - .addClass('in') + this.applyPlacement(tp, placement) + this.$element.trigger('shown') } } + , applyPlacement: function(offset, placement){ + var $tip = this.tip() + , width = $tip[0].offsetWidth + , height = $tip[0].offsetHeight + , actualWidth + , actualHeight + , delta + , replace + + $tip + .offset(offset) + .addClass(placement) + .addClass('in') + + actualWidth = $tip[0].offsetWidth + actualHeight = $tip[0].offsetHeight + + if (placement == 'top' && actualHeight != height) { + offset.top = offset.top + height - actualHeight + replace = true + } + + if (placement == 'bottom' || placement == 'top') { + delta = 0 + + if (offset.left < 0){ + delta = offset.left * -2 + offset.left = 0 + $tip.offset(offset) + actualWidth = $tip[0].offsetWidth + actualHeight = $tip[0].offsetHeight + } + + this.replaceArrow(delta - width + actualWidth, actualWidth, 'left') + } else { + this.replaceArrow(actualHeight - height, actualHeight, 'top') + } + + if (replace) $tip.offset(offset) + } + + , replaceArrow: function(delta, dimension, position){ + this + .arrow() + .css(position, delta ? (50 * (1 - delta / dimension) + "%") : '') + } + , setContent: function () { var $tip = this.tip() , title = this.getTitle() @@ -1178,6 +1272,10 @@ , hide: function () { var that = this , $tip = this.tip() + , e = $.Event('hide') + + this.$element.trigger(e) + if (e.isDefaultPrevented()) return $tip.removeClass('in') @@ -1196,13 +1294,15 @@ removeWithAnimation() : $tip.detach() + this.$element.trigger('hidden') + return this } , fixTitle: function () { var $e = this.$element if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') { - $e.attr('data-original-title', $e.attr('title') || '').removeAttr('title') + $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } @@ -1210,11 +1310,12 @@ return this.getTitle() } - , getPosition: function (inside) { - return $.extend({}, (inside ? {top: 0, left: 0} : this.$element.offset()), { - width: this.$element[0].offsetWidth - , height: this.$element[0].offsetHeight - }) + , getPosition: function () { + var el = this.$element[0] + return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : { + width: el.offsetWidth + , height: el.offsetHeight + }, this.$element.offset()) } , getTitle: function () { @@ -1232,6 +1333,10 @@ return this.$tip = this.$tip || $(this.options.template) } + , arrow: function(){ + return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow") + } + , validate: function () { if (!this.$element[0].parentNode) { this.hide() @@ -1253,8 +1358,8 @@ } , toggle: function (e) { - var self = $(e.currentTarget)[this.type](this._options).data(this.type) - self[self.tip().hasClass('in') ? 'hide' : 'show']() + var self = e ? $(e.currentTarget)[this.type](this._options).data(this.type) : this + self.tip().hasClass('in') ? self.hide() : self.show() } , destroy: function () { @@ -1286,10 +1391,11 @@ , placement: 'top' , selector: false , template: '