Merge branch 'maintenance' into devel

# Conflicts:
#	setup.py
#	src/octoprint/server/util/__init__.py
This commit is contained in:
Gina Häußge committed 2017-10-25 09:32:38 +02:00
commit e9fb3a3ebb
43 files changed
+814 -234

No files matched your search

+6
View File
@@ -37,6 +37,11 @@
vertical-align: 10%;
}
.rst-content .highlight>pre,
.rst-content .linenodiv>pre {
line-height: 1.5;
}
/* make code tags non-red again */
code,
.rst-content tt {
@@ -52,3 +57,4 @@ a:visited code,
.rst-content a:visited tt {
color: #9B59B6 !important;
}
+3 -3
View File
@@ -39,7 +39,7 @@ List all registered system commands
"action": "shutdown",
"name": "Shutdown",
"command": "sudo shutdown -h now",
"confirm": "<b>You are about to shutdown the system.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"confirm": "<strong>You are about to shutdown the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"async": true,
"ignore": true,
"source": "core",
@@ -49,7 +49,7 @@ List all registered system commands
"action": "reboot",
"name": "Reboot",
"command": "sudo reboot",
"confirm": "<b>You are about to reboot the system.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"confirm": "<strong>You are about to reboot the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"async": true,
"ignore": true,
"source": "core",
@@ -59,7 +59,7 @@ List all registered system commands
"action": "restart",
"name": "Restart OctoPrint",
"command": "sudo service octoprint restart",
"confirm": "<b>You are about to restart the OctoPrint server.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"confirm": "<strong>You are about to restart the OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).",
"async": true,
"ignore": true,
"source": "core",
+84 -1
View File
@@ -68,6 +68,21 @@ Test paths or URLs
when the test could be performed. The status code of the response does NOT reflect the
test result!
.. _sec-api-util-test-server:
server
Tests whether a provided server identified by host and port can be reached. Protocol can optionally be specified
as well. Supported parameters are:
* ``host``: The host to test. IP or host name. Mandatory.
* ``port``: The port to test. Integer. Mandatory.
* ``protocol``: The protocol to test with. ``tcp`` or ``udp``. Optional, defaults to ``tcp``.
* ``timeout``: A timeout for the test, in seconds. If no successful connection to the server could be established
within this time frame, the check will be considered a failure. Optional, defaults to 3.05 seconds.
The ``server`` command returns :http:statuscode:`200` with a :ref:`Server test result <sec-api-util-datamodel-servertestresult>`
when the test could be performed. The status code of the response does NOT reflect the test result!
Requires admin rights.
**Example 1**
@@ -226,6 +241,35 @@ Test paths or URLs
}
}
**Example 6**
Test whether a server is reachable on a given port via TCP.
.. sourcecode:: http
POST /api/util/test HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
Content-Type: application/json
{
"command": "server",
"host": "8.8.8.8",
"port": 53
}
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"host": "8.8.8.8",
"port": 53,
"protocol": "tcp",
"result": true
}
:json command: The command to execute, currently either ``path`` or ``url``
:json path: ``path`` command only: the path to test
:json check_type: ``path`` command only: the type of path to test for, either ``file`` or ``dir``
@@ -233,8 +277,11 @@ Test paths or URLs
:json url: ``url`` command only: the URL to test
:json status: ``url`` command only: one or more expected status codes
:json method: ``url`` command only: the HTTP method to use for the check
:json timeout: ``url`` command only: the timeout for the HTTP request
:json timeout: ``url`` and ``server`` commands only: the timeout for the test request
:json response: ``url`` command only: whether to include response data and if so in what form
:json host: ``server`` command only: the server to test
:json port: ``server`` command only: the port to test
:json protocol: ``server`` command only: the protocol to test
:statuscode 200: No error occurred
.. _sec-api-util-datamodel:
@@ -244,6 +291,9 @@ Data model
.. _sec-api-util-datamodel-pathtestresult:
Path test result
----------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
@@ -275,6 +325,9 @@ Data model
.. _sec-api-util-datamodel-urltestresult:
URL test result
---------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
@@ -306,3 +359,33 @@ Data model
- object
- A dictionary with all headers of the checked URL's response. Only present if ``response`` in the
request was set.
.. _sec-api-util-datamodel-servertestresult:
Server test result
------------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``host``
- 1
- string
- The host that was tested.
* - ``port``
- 1
- int
- The port that was tested
* - ``protocol``
- 1
- string
- The protocol that was tested, ``tcp`` or ``udp``
* - ``result``
- 1
- bool
- ``true`` if the check passed.
+30 -5
View File
@@ -16,6 +16,9 @@ Additionally, OctoPrint allows uninstalling plugins in this mode, allowing recov
a third party plugin causes the server to not start up or the web interface to not render or function
correctly anymore.
Whenever reporting an issue with OctoPrint, please always attempt to reproduce it in safe mode as well to
ensure it really is an issue in OctoPrint itself and now caused by one of your installed third party plugins.
.. _sec-features-safemode-how:
How to start OctoPrint in safe mode
@@ -23,15 +26,37 @@ How to start OctoPrint in safe mode
There exist three ways to start OctoPrint in safe mode:
* since OctoPrint 1.3.2: by selecting "Restart OctoPrint in safe mode" from the "System" menu,
if the "Restart OctoPrint" server command has been correctly configured (see :numref:`fig-features-safemode-systemmenu`).
* by starting OctoPrint with the command line parameter ``--safe``, e.g. ``octoprint serve --safe``
* by setting the option ``server.startOnceInSafeMode`` in :ref:`config.yaml <sec-configuration-config_yaml>`
to ``true`` and restarting
* by selecting "Restart OctoPrint in safe mode" from the "System" menu,
if the "Restart OctoPrint" server command has been correctly configured (since OctoPrint 1.3.2,
see :numref:`fig-features-safemode-systemmenu`)
* by setting the flag ``server.startOnceInSafeMode`` in :ref:`config.yaml <sec-configuration-config_yaml>`
to ``true`` and restarting. To set this flag you have the following options:
* from command line run ``octoprint safemode`` (since OctoPrint 1.3.6)
* from command line run ``octoprint config set --bool server.startOnceInSafeMode true`` (fixed in OctoPrint 1.3.6)
* use the `Yamlpatcher Plugin <http://plugins.octoprint.org/plugins/yamlpatcher/>`_ and enter & apply the patch
``[["set", "server.startOnceInSafeMode", true]]``
* edit ``config.yaml`` manually with a text editor, locate the ``server`` block if it already exists or create it
if it doesn't and add ``startOnceInSafeMode: true`` to it:
.. code-block:: yaml
# ...
server:
startOnceInSafeMode: true
# ...
Please also refer to the :ref:`YAML primer <sec-configuration-yaml>`.
* by starting OctoPrint with the command line parameter ``--safe``, e.g. ``octoprint serve --safe`` (don't forget to
shutdown OctoPrint first before doing this)
The last two options will have OctoPrint enable safe mode only for the next server start - once you
restart OctoPrint again, safe mode will be disabled again.
.. note::
**OctoPi users**: For you that's ``~/oprint/bin/octoprint`` wherever it says just ``octoprint``.
.. _fig-features-safemode-systemmenu:
.. figure:: ../images/features-safemode-systemmenu.png
:align: center
+51 -1
View File
@@ -126,8 +126,16 @@
.done(function(response) {
if (response.result) {
// check passed
var content = response.response.content;
var mimeType = "image/jpeg";
var headers = response.response.headers;
if (headers && headers["content-type"]) {
mimeType = headers["content-type"].split(";")[0];
}
var image = $("#someimage");
image.
image.src = "data:" + mimeType + ";base64," + content;
} else {
// check failed
}
@@ -153,6 +161,48 @@
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.util.testServer(host, port, additional, opts)
Test if a server is reachable. More options supported by the :ref:`server test command <sec-api-util-test-server>`
can be provided via the ``additional`` object.
**Example 1**
Test if ``8.8.8.8`` is reachable on port 53 within the default timeout.
.. code-block:: javascript
OctoPrint.util.testServer("8.8.8.8", 53)
.done(function(response) {
if (response.result) {
// check passed
} else {
// check failed
}
});
**Example 2**
Test if ``127.0.0.1`` is reachable on port 1234 and UDP.
.. code-block:: javascript
OctoPrint.util.testUrl("127.0.0.1", 1234, {"protocol": "udp"})
.done(function(response) {
if (response.result) {
// check passed
} else {
// check failed
}
});
:param string url: Host to test
:param int port: Port to test
:param object additional: Additional parameters for the test command
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. seealso::
:ref:`Util API <sec-api-util>`
+6 -7
View File
@@ -20,7 +20,7 @@ development environment::
$ virtualenv venv
[...]
$ source venv/bin/activate
(venv) $ pip install -e .[develop]
(venv) $ pip install -e .[develop,plugins]
[...]
(venv) $ octoprint --help
Usage: octoprint [OPTIONS] COMMAND [ARGS]...
@@ -138,10 +138,11 @@ best way possible, meaning we want to make our plugin a fully installable python
install directly via `OctoPrint's built-in Plugin Manager <https://github.com/foosel/OctoPrint/wiki/Plugin:-Plugin-Manager>`_
or alternatively manually utilizing Python's standard package manager ``pip`` directly.
So let's begin. We'll use the `cookiecutter <https://github.com/audreyr/cookiecutter>`_ template for OctoPrint plugins here,
so we'll first need to install that::
So let's begin. We'll use the `cookiecutter <https://github.com/audreyr/cookiecutter>`_ template for OctoPrint plugins
here. This should already be installed if you used the ``plugins`` extra while installing OctoPrint. However,
you may install it with::
(venv) $ pip install cookiecutter
(venv) $ pip install "cookiecutter>=1.4,<1.7"
Then we can use the ``octoprint dev plugin:new`` command [#f1]_ to generate a new OctoPrint plugin skeleton for us::
@@ -819,12 +820,10 @@ Put something like the following into ``helloworld.css``:
.. code-block:: css
:linenos:
#tab_plugin_helloworld {
iframe {
#tab_plugin_helloworld iframe {
width: 100%;
height: 600px;
border: 1px solid #808080;
}
}
Don't forget to remove the ``style`` attribute from the ``iframe`` tag in ``helloworld_tab.jinja2``:
+31
View File
@@ -226,6 +226,37 @@ octoprint.accesscontrol.appkey
:return: A list of 3-tuples as described above
:rtype: list
.. _sec-plugins-hook-accesscontrol-keyvalidator:
octoprint.accesscontrol.keyvalidator
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: acl_keyvalidator_hook(apikey, *args, **kwargs)
Via this hook plugins may validate their own customized API keys to be used to access OctoPrint's API.
``apikey`` will be the API key as read from the request headers.
Hook handlers are expected to return a :class:`~octoprint.users.User` instance here that will then be considered that
user making the request. By returning ``None`` or nothing at all, hook handlers signal that they do not handle the
provided key.
**Example:**
Allows using a user's id as their API key (for obvious reasons this is NOT recommended in production environments
and merely provided for educational purposes):
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_keyvalidator.py
:linenos:
:tab-width: 4
:caption: `custom_keyvalidator.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_keyvalidator.py>`_
.. versionadded:: 1.3.6
:param str apikey: The API key to validate
:return: The user in whose name the request will be processed further
:rtype: :class:`~octoprint.users.User`
.. _sec-plugins-hook-cli-commands:
octoprint.cli.commands
+3 -3
View File
@@ -35,7 +35,7 @@ INSTALL_REQUIRES = [
"pylru>=1.0.9,<1.1",
"rsa>=3.4,<3.5",
"pkginfo>=1.4.1,<1.5",
"requests>=2.13.0,<2.14",
"requests>=2.18.4,<3",
"semantic_version>=2.6.0,<2.7",
"psutil>=5.1.3,<5.2",
"Click>=6.7,<6.8",
@@ -67,7 +67,7 @@ EXTRA_REQUIRES = dict(
"sphinx>=1.6,<1.7",
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid",
"sphinx_bootstrap_theme",
"sphinx_rtd_theme",
# PyPi upload related
"pypandoc"
@@ -75,7 +75,7 @@ EXTRA_REQUIRES = dict(
# Dependencies for developing OctoPrint plugins
plugins=[
"cookiecutter>=1.5,<1.6"
"cookiecutter>=1.5,<1.7"
]
)
+1 -1
View File
@@ -102,7 +102,7 @@ def standard_options(hidden=False):
options = [
factory("--basedir", "-b", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Specify the basedir to use for uploads, timelapses etc."),
help="Specify the basedir to use for configs, uploads, timelapses etc."),
factory("--config", "-c", "configfile", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Specify the config file to use."),
factory("--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
+2 -4
View File
@@ -9,7 +9,7 @@ import click
import logging
from octoprint import init_settings, FatalStartupError
from octoprint.cli import pass_octoprint_ctx, standard_options, bulk_options, get_ctx_obj_option
from octoprint.cli import standard_options, bulk_options, get_ctx_obj_option
import yaml
import json
@@ -54,7 +54,7 @@ def config(ctx):
ctx.obj.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the client.", err=True)
click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
@@ -70,7 +70,6 @@ def config(ctx):
help="Interpret value as int")
@click.option("--json", "as_json", is_flag=True,
help="Parse value from json")
@pass_octoprint_ctx
@click.pass_context
def set_command(ctx, path, value, as_bool, as_float, as_int, as_json):
"""Sets a config path to the provided value."""
@@ -163,7 +162,6 @@ def insert_value_command(ctx, path, index, value, as_json=False):
@click.argument("path", type=click.STRING)
@click.argument("value", type=click.STRING)
@click.option("--json", "as_json", is_flag=True)
@pass_octoprint_ctx
@click.pass_context
def remove_value_command(ctx, path, value, as_json=False):
"""Removes value from list at config path."""
+21
View File
@@ -125,6 +125,27 @@ def server_commands():
pass
@server_commands.command(name="safemode")
@standard_options(hidden=True)
@click.pass_context
def enable_safemode(ctx, **kwargs):
"""Sets the safe mode flag for the next start."""
from octoprint import init_settings, FatalStartupError
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
try:
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
settings.setBoolean(["server", "startOnceInSafeMode"], True)
settings.save()
click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.")
@server_commands.command(name="serve")
@server_options
@standard_options(hidden=True)
@@ -24,6 +24,7 @@
<form class="form-horizontal" data-bind="with: settingsViewModel, enable: !setup(), css {disabled: setup()}">
{% include "snippets/settings/server/serverOnlineCheckHost.jinja2" %}
{% include "snippets/settings/server/serverOnlineCheckPort.jinja2" %}
{% include "snippets/settings/server/serverOnlineCheckTest.jinja2" %}
</form>
<p>{% trans %}
+13 -5
View File
@@ -79,6 +79,11 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
self._cura_logger.addHandler(cura_logging_handler)
self._cura_logger.setLevel(logging.DEBUG if self._settings.get_boolean(["debug_logging"]) else logging.CRITICAL)
self._cura_logger.propagate = False
engine = self._settings.get(["cura_engine"])
if not self._is_engine_configured(cura_engine=engine):
self._logger.info("Path to CuraEngine has not been configured or does not exist (currently set to %r), "
"Cura will not be selectable for slicing" % engine)
##~~ BlueprintPlugin API
@@ -168,11 +173,18 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
##~~ SettingsPlugin API
def on_settings_save(self, data):
old_engine = self._settings.get(["cura_engine"])
old_debug_logging = self._settings.get_boolean(["debug_logging"])
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
new_engine = self._settings.get(["cura_engine"])
new_debug_logging = self._settings.get_boolean(["debug_logging"])
if old_engine != new_engine and not self._is_engine_configured(new_engine):
self._logger.info("Path to CuraEngine has not been configured or does not exist (currently set to %r), "
"Cura will not be selectable for slicing" % new_engine)
if old_debug_logging != new_debug_logging:
if new_debug_logging:
self._cura_logger.setLevel(logging.DEBUG)
@@ -190,11 +202,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
def is_slicer_configured(self):
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
return self._is_engine_configured(cura_engine=cura_engine)
def get_slicer_properties(self):
return dict(
+5 -1
View File
@@ -24,6 +24,7 @@ $(function() {
self.profileDescription = ko.observable();
self.profileAllowOverwrite = ko.observable(true);
self.profileMakeDefault = ko.observable(false);
self.profileFirst = ko.observable(false);
// make sure to update form data if any of the metadata changes
self.profileName.subscribe(function() { self.copyProfileMetadata(); });
@@ -134,7 +135,10 @@ $(function() {
self.profileDisplayName(undefined);
self.profileDescription(undefined);
self.profileAllowOverwrite(true);
self.profileMakeDefault(false);
var firstProfile = self.profiles.items().length === 0;
self.profileMakeDefault(firstProfile);
self.profileFirst(firstProfile);
};
self.uploadElement.fileupload({
@@ -37,15 +37,15 @@
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox" data-bind="enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
<input type="checkbox" data-bind="checked: profileMakeDefault"> {{ _('Make default profile') }}
<label class="checkbox">
<input type="checkbox" data-bind="checked: profileMakeDefault, enable: fieldsEnabled() && !profileFirst(), css: {disabled: !fieldsEnabled() || profileFirst()}"> {{ _('Make default profile') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox" data-bind="enable: fieldsEnabled, css: {disabled: !fieldsEnabled()}">
<input type="checkbox" data-bind="checked: profileAllowOverwrite"> {{ _('Overwrite existing file') }}
<label class="checkbox">
<input type="checkbox" data-bind="checked: profileAllowOverwrite, enable: fieldsEnabled() && !profileFirst(), css: {disabled: !fieldsEnabled() || profileFirst()}"> {{ _('Overwrite existing file') }}
</label>
</div>
</div>
@@ -731,7 +731,7 @@ $(function() {
if (restartClicked) return;
restartClicked = true;
showConfirmationDialog({
message: gettext("<b>This will restart your OctoPrint server.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."),
message: gettext("<strong>This will restart your OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."),
onproceed: function() {
OctoPrint.system.executeCommand("core", "restart")
.done(function() {
@@ -19,7 +19,7 @@
{{ _('Be sure to read through any linked release notes, especially those for OctoPrint since they might contain important information you need to know <strong>before</strong> upgrading.') }}
</p>
<p>
<h5>{{ _('This action may disrupt any ongoing print jobs.') }}</h5>
<strong>{{ _('This action may disrupt any ongoing print jobs.') }}</strong>
</p>
<p>
{{ _('Depending on your printer\'s controller and general setup, restarting OctoPrint may cause your printer to be reset.') }}
+32 -3
View File
@@ -246,7 +246,8 @@ def _logout(user):
def utilTestPath():
valid_commands = dict(
path=["path"],
url=["url"]
url=["url"],
server=["host", "port"]
)
command, data, response = get_json_command_from_request(request, valid_commands)
@@ -339,7 +340,7 @@ def utilTestPath():
try:
timeout = float(data["timeout"])
except:
return make_response("{!r} is not a valid value for timeout (must be int or float)".format(data["timeout"]))
return make_response("{!r} is not a valid value for timeout (must be int or float)".format(data["timeout"]), 400)
if "status" in data:
request_status = data["status"]
@@ -386,5 +387,33 @@ def utilTestPath():
headers=dict(response.headers),
content=content
)
return jsonify(**result)
elif command == "server":
host = data["host"]
try:
port = int(data["port"])
except:
return make_response("{!r} is not a valid value for port (must be int)".format(data["port"]), 400)
timeout = 3.05
if "timeout" in data:
try:
timeout = float(data["timeout"])
except:
return make_response("{!r} is not a valid value for timeout (must be int or float)".format(data["timeout"]), 400)
protocol = data.get("protocol", "tcp")
if protocol not in ("tcp", "udp"):
return make_response("{!r} is not a valid value for protocol, must be tcp or udp".format(protocol), 400)
from octoprint.util import server_reachable
reachable = server_reachable(host, port, timeout=timeout, proto=protocol)
result = dict(host=host,
port=port,
protocol=protocol,
result=reachable)
return jsonify(**result)
+3 -2
View File
@@ -29,7 +29,7 @@ import threading
_file_cache = dict()
_file_cache_mutex = threading.RLock()
_FILES_DATA_VERSION = 1
_DATA_FORMAT_VERSION = "v2"
def _clear_file_cache():
with _file_cache_mutex:
@@ -73,7 +73,6 @@ def _create_etag(path, filter, recursive, lm=None):
return None
hash = hashlib.sha1()
hash.update(str(_FILES_DATA_VERSION))
hash.update(str(lm))
hash.update(str(filter))
hash.update(str(recursive))
@@ -82,6 +81,8 @@ def _create_etag(path, filter, recursive, lm=None):
# include sd data in etag
hash.update(repr(sorted(printer.get_sd_files(), key=lambda x: x[0])))
hash.update(_DATA_FORMAT_VERSION) # increment version if we change the API format
return hash.hexdigest()
+14 -3
View File
@@ -17,6 +17,9 @@ from octoprint.settings import settings as s, valid_boolean_trues
from octoprint.slicing import UnknownSlicer, SlicerNotConfigured, ProfileAlreadyExists, UnknownProfile, CouldNotDeleteProfile
_DATA_FORMAT_VERSION = "v2"
def _lastmodified(configured):
if configured:
slicers = slicingManager.configured_slicers
@@ -39,11 +42,19 @@ def _etag(configured, lm=None):
hash.update(str(lm))
if configured:
hash.update(repr(sorted(slicingManager.configured_slicers)))
slicers = slicingManager.configured_slicers
else:
hash.update(repr(sorted(slicingManager.registered_slicers)))
slicers = slicingManager.registered_slicers
hash.update("v2") # increment version if we change the API format
default_slicer = s().get(["slicing", "defaultSlicer"])
for slicer in sorted(slicers):
slicer_impl = slicingManager.get_slicer(slicer, require_configured=False)
hash.update(slicer)
hash.update(str(slicer_impl.is_slicer_configured()))
hash.update(str(slicer == default_slicer))
hash.update(_DATA_FORMAT_VERSION) # increment version if we change the API format
return hash.hexdigest()
+4 -4
View File
@@ -167,19 +167,19 @@ def _get_core_command_specs():
shutdown=dict(
command=s().get(["server", "commands", "systemShutdownCommand"]),
name=gettext("Shutdown system"),
confirm=gettext("<b>You are about to shutdown the system.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")),
confirm=gettext("<strong>You are about to shutdown the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")),
reboot=dict(
command=s().get(["server", "commands", "systemRestartCommand"]),
name=gettext("Reboot system"),
confirm=gettext("<b>You are about to reboot the system.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")),
confirm=gettext("<strong>You are about to reboot the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")),
restart=dict(
command=s().get(["server", "commands", "serverRestartCommand"]),
name=gettext("Restart OctoPrint"),
confirm=gettext("<b>You are about to restart the OctoPrint server.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")),
confirm=gettext("<strong>You are about to restart the OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")),
restart_safe=dict(
command=s().get(["server", "commands", "serverRestartCommand"]),
name=gettext("Restart OctoPrint in safe mode"),
confirm=gettext("<b>You are about to restart the OctoPrint server in safe mode.</b></p><p> This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."),
confirm=gettext("<strong>You are about to restart the OctoPrint server in safe mode.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."),
before=enable_safe_mode)
)
+33 -13
View File
@@ -11,10 +11,10 @@ import octoprint.server
from octoprint.users import ApiUser
from octoprint.util import deprecated
from octoprint.plugin import plugin_manager
import flask as _flask
import flask_login
import flask_principal
import logging
from . import flask
from . import sockjs
@@ -57,14 +57,22 @@ def loginFromApiKeyRequestHandler():
"""
apikey = get_api_key(_flask.request)
if apikey and apikey != octoprint.server.UI_API_KEY and not octoprint.server.appSessionManager.validate(apikey):
user = get_user_for_apikey(apikey)
if user is not None and not user.is_anonymous and flask_login.login_user(user, remember=False):
flask_principal.identity_changed.send(_flask.current_app._get_current_object(),
identity=flask_principal.Identity(user.get_id()))
else:
return _flask.make_response("Invalid API key", 401)
if not apikey:
return
if apikey == octoprint.server.UI_API_KEY:
return
if octoprint.server.appSessionManager.validate(apikey):
return
user = get_user_for_apikey(apikey)
if user is not None and _flask.ext.login.login_user(user, remember=False):
_flask.ext.principal.identity_changed.send(_flask.current_app._get_current_object(),
identity=_flask.ext.principal.Identity(user.get_id()))
else:
return _flask.make_response("Invalid API key", 401)
def corsRequestHandler():
@@ -145,9 +153,21 @@ def get_user_for_apikey(apikey):
if apikey == settings().get(["api", "key"]) or octoprint.server.appSessionManager.validate(apikey):
# master key or an app session key was used
return ApiUser()
elif octoprint.server.userManager.enabled:
# user key might have been used
return octoprint.server.userManager.findUser(apikey=apikey)
if octoprint.server.userManager.enabled:
user = octoprint.server.userManager.findUser(apikey=apikey)
if user is not None:
# user key was used
return user
apikey_hooks = plugin_manager().get_hooks("octoprint.accesscontrol.keyvalidator")
for name, hook in apikey_hooks.items():
try:
user = hook(apikey)
if user is not None:
return user
except:
logging.getLogger(__name__).exception("Error running api key validator for plugin {} and key {}".format(name, apikey))
return None
+10
View File
@@ -377,6 +377,10 @@ class SlicingManager(object):
If it's a :class:`dict`, a new :class:`SlicingProfile` instance will be created with the supplied meta data and
the profile data as the :attr:`~SlicingProfile.data` attribute.
.. note::
If the profile is the first profile to be saved for the slicer, it will automatically be marked as default.
Arguments:
slicer (str): Identifier of the slicer for which to save the ``profile``.
@@ -414,6 +418,8 @@ class SlicingManager(object):
if description is not None:
profile.description = description
first_profile = len(self.all_profiles(slicer, require_configured=False)) == 0
path = self.get_profile_path(slicer, name)
is_overwrite = os.path.exists(path)
@@ -426,6 +432,10 @@ class SlicingManager(object):
profile=name)
event = octoprint.events.Events.SLICING_PROFILE_MODIFIED if is_overwrite else octoprint.events.Events.SLICING_PROFILE_ADDED
octoprint.events.eventManager().fire(event, payload)
if first_profile:
# enforce the first profile we add for this slicer is set as default
self.set_default_profile(slicer, name)
return profile
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn.active,.btn:active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:#333 dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary.active,.btn-primary:active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning.active,.btn-warning:active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#da4f49;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeaLine truncated
@@ -78,6 +78,7 @@ GCODE.gCodeReader = (function(){
percentageTree = undefined;
for (var l = 0; l < model.length; l++) {
if (model[l] === undefined) continue;
for (var i = 0; i < model[l].length; i++) {
var percentage = model[l][i].percentage;
var value = {layer: l, cmd: i};
@@ -45,6 +45,16 @@
return this.test("url", data, opts);
};
OctoPrintUtilClient.prototype.testServer = function(host, port, additional, opts) {
additional = additional || {};
var data = $.extend({}, additional);
data.host = host;
data.port = port;
return this.test("server", data, opts);
};
OctoPrintClient.registerComponent("util", OctoPrintUtilClient);
return OctoPrintUtilClient;
});
+60 -28
View File
@@ -988,43 +988,75 @@ function setOnViewModels(allViewModels, key, value) {
}
function setOnViewModelsIf(allViewModels, key, value, condition) {
if (!allViewModels) return;
_.each(allViewModels, function(viewModel) {
setOnViewModelIf(viewModel, key, value, condition);
})
}
function setOnViewModel(viewModel, key, value) {
setOnViewModelIf(viewModel, key, value, undefined);
}
function setOnViewModelIf(viewModel, key, value, condition) {
if (condition === undefined || !_.isFunction(condition)) {
condition = function() { return true; };
}
_.each(allViewModels, function(viewModel) {
if (condition(viewModel)) {
viewModel[key] = value;
try {
if (!condition(viewModel)) {
return;
}
})
viewModel[key] = value;
} catch (exc) {
log.error("Error while setting", key, "to", value, "on view model", viewModel.constructor.name, ":", (exc.stack || exc));
}
}
function callViewModels(allViewModels, method, callback) {
if (!allViewModels) return;
callViewModelsIf(allViewModels, method, undefined, callback);
}
function callViewModelsIf(allViewModels, method, condition, callback) {
if (!allViewModels) return;
if (condition == undefined || !_.isFunction(condition)) {
_.each(allViewModels, function(viewModel) {
try {
callViewModelIf(viewModel, method, condition, callback);
} catch (exc) {
log.error("Error calling", method, "on view model", viewModel.constructor.name, ":", (exc.stack || exc));
}
});
}
function callViewModel(viewModel, method, callback, raiseErrors) {
callViewModelIf(viewModel, method, undefined, callback, raiseErrors);
}
function callViewModelIf(viewModel, method, condition, callback, raiseErrors) {
raiseErrors = raiseErrors === true || false;
if (condition === undefined || !_.isFunction(condition)) {
condition = function() { return true; };
}
if (!viewModel.hasOwnProperty(method) || !condition(viewModel, method)) return;
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) {
if (callback === undefined) {
// directly call view model method with no parameters
parameters = undefined;
log.trace("Calling method", method, "on view models");
log.trace("Calling method", method, "on view model");
} 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);
log.trace("Calling method", method, "on view model with specified parameters", parameters);
} else {
// ok, this doesn't make sense, callback is neither undefined nor
// an array, we'll return without doing anything
@@ -1035,29 +1067,29 @@ function callViewModelsIf(allViewModels, method, condition, callback) {
// the method directly
callback = undefined;
} else {
log.trace("Providing method", method, "on view models to specified callback", callback);
log.trace("Providing method", method, "on view model to specified callback", callback);
}
_.each(allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty(method) && condition(viewModel, method)) {
try {
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], viewModel);
}
} catch (exc) {
log.error("Error calling", method, "on view model", viewModel.constructor.name, ":", (exc.stack || exc));
try {
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], viewModel);
}
});
} catch (exc) {
if (raiseErrors) {
throw exc;
} else {
log.error("Error calling", method, "on view model", viewModel.constructor.name, ":", (exc.stack || exc));
}
}
}
var sizeObservable = function(observable) {
+84 -56
View File
@@ -334,7 +334,13 @@ $(function() {
continue;
}
var viewModelInstance = _createViewModelInstance(viewModel, viewModelMap, optionalDependencyPass);
var viewModelInstance;
try {
viewModelInstance = _createViewModelInstance(viewModel, viewModelMap, optionalDependencyPass);
} catch (exc) {
log.error("Error instantiating", viewModel.name, ":", (exc.stack || exc));
continue;
}
// our view model couldn't yet be instantiated, so postpone it for a bit
if (viewModelInstance === undefined) {
@@ -497,6 +503,10 @@ $(function() {
callViewModels(allViewModels, "onTabChange", [current, previous]);
};
var onAfterTabChange = function(current, previous) {
callViewModels(allViewModels, "onAfterTabChange", [current, previous]);
};
var tabs = $('#tabs a[data-toggle="tab"]');
tabs.on('show', function (e) {
var current = e.target.hash;
@@ -507,10 +517,11 @@ $(function() {
tabs.on('shown', function (e) {
var current = e.target.hash;
var previous = e.relatedTarget.hash;
callViewModels(allViewModels, "onAfterTabChange", [current, previous]);
onAfterTabChange(current, previous);
});
onTabChange(OCTOPRINT_INITIAL_TAB);
onAfterTabChange(OCTOPRINT_INITIAL_TAB, undefined);
// Fix input element click problems on dropdowns
$(".dropdown input, .dropdown label").click(function(e) {
@@ -549,75 +560,92 @@ $(function() {
var bindViewModels = function() {
log.info("Going to bind " + allViewModelData.length + " view models...");
_.each(allViewModelData, function(viewModelData) {
if (!Array.isArray(viewModelData) || viewModelData.length != 2) {
return;
}
try {
if (!Array.isArray(viewModelData) || viewModelData.length !== 2) {
log.error("View model data for", viewModel.constructor.name, "has wrong format, expected 2-tuple (viewModel, targets), got:", viewModelData);
return;
}
var viewModel = viewModelData[0];
var targets = viewModelData[1];
var viewModel = viewModelData[0];
var targets = viewModelData[1];
if (targets === undefined) {
return;
}
if (targets === undefined) {
log.error("No binding targets defined for view model", viewMode.constructor.name);
return;
}
if (!_.isArray(targets)) {
targets = [targets];
}
if (viewModel.hasOwnProperty("onBeforeBinding")) {
viewModel.onBeforeBinding();
}
if (targets != undefined) {
if (!_.isArray(targets)) {
targets = [targets];
}
viewModel._bindings = [];
try {
callViewModel(viewModel, "onBeforeBinding", undefined, true);
} catch (exc) {
log.error("Error calling onBeforeBinding on view model", viewModel.constructor.name, ":", (exc.stack || exc));
return;
}
_.each(targets, function(target) {
if (target == undefined) {
return;
if (targets !== undefined) {
if (!_.isArray(targets)) {
targets = [targets];
}
var object;
if (!(target instanceof jQuery)) {
object = $(target);
} else {
object = target;
}
viewModel._bindings = [];
if (object == undefined || !object.length) {
log.info("Did not bind view model", viewModel.constructor.name, "to target", target, "since it does not exist");
return;
}
var element = object.get(0);
if (element == undefined) {
log.info("Did not bind view model", viewModel.constructor.name, "to target", target, "since it does not exist");
return;
}
try {
ko.applyBindings(viewModel, element);
viewModel._bindings.push(target);
if (viewModel.hasOwnProperty("onBoundTo")) {
viewModel.onBoundTo(target, element);
_.each(targets, function (target) {
if (target === undefined) {
log.error("Undefined target for view model", viewModel.constructor.name);
return;
}
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));
}
});
}
var object;
if (!(target instanceof jQuery)) {
try {
object = $(target);
} catch (exc) {
log.error("Error while attempting to jquery-fy target", target, "of view model", viewModel.constructor.name, ":", (exc.stack || exc));
return;
}
} else {
object = target;
}
viewModel._unbound = viewModel._bindings !== undefined && viewModel._bindings.length === 0;
viewModel._bound = viewModel._bindings.length > 0;
if (object === undefined || !object.length) {
log.info("Did not bind view model", viewModel.constructor.name, "to target", target, "since it does not exist");
return;
}
if (viewModel.hasOwnProperty("onAfterBinding")) {
viewModel.onAfterBinding();
var element = object.get(0);
if (element === undefined) {
log.info("Did not bind view model", viewModel.constructor.name, "to target", target, "since it does not exist");
return;
}
try {
ko.applyBindings(viewModel, element);
viewModel._bindings.push(target);
callViewModel(viewModel, "onBoundTo", [target, element], true);
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));
}
});
}
viewModel._unbound = viewModel._bindings === undefined || viewModel._bindings.length === 0;
viewModel._bound = viewModel._bindings && viewModel._bindings.length > 0;
callViewModel(viewModel, "onAfterBinding");
} catch (exc) {
var name;
try {
name = viewModel.constructor.name;
} catch (exc) {
name = "n/a";
}
log.error("Error while processing view model", name, "for binding:", (exc.stack || exc));
}
});
@@ -402,6 +402,8 @@ $(function() {
};
self.onWebcamLoaded = function() {
if (self.webcamLoaded()) return;
log.debug("Webcam stream loaded");
self.webcamLoaded(true);
self.webcamError(false);
+87 -53
View File
@@ -36,11 +36,11 @@ $(function() {
});
self.diskusageWarning = ko.pureComputed(function() {
return self.freeSpace() != undefined
return self.freeSpace() !== undefined
&& self.freeSpace() < self.settingsViewModel.server_diskspace_warning();
});
self.diskusageCritical = ko.pureComputed(function() {
return self.freeSpace() != undefined
return self.freeSpace() !== undefined
&& self.freeSpace() < self.settingsViewModel.server_diskspace_critical();
});
self.diskusageString = ko.pureComputed(function() {
@@ -76,7 +76,8 @@ $(function() {
self.addFolderDialog = undefined;
self.addFolderName = ko.observable(undefined);
self.enableAddFolder = ko.pureComputed(function() {
return self.loginState.isUser() && self.addFolderName() && self.addFolderName().trim() != "" && !self.addingFolder();
return self.loginState.isUser() && self.addFolderName() && self.addFolderName().trim() !== ""
&& !self.addingFolder();
});
self.allItems = ko.observable(undefined);
@@ -109,19 +110,20 @@ $(function() {
},
{
"printed": function(data) {
return !(data["prints"] && data["prints"]["success"] && data["prints"]["success"] > 0) || (data["type"] && data["type"] == "folder");
return !(data["prints"] && data["prints"]["success"] && data["prints"]["success"] > 0)
|| (data["type"] && data["type"] === "folder");
},
"sd": function(data) {
return data["origin"] && data["origin"] == "sdcard";
return data["origin"] && data["origin"] === "sdcard";
},
"local": function(data) {
return !(data["origin"] && data["origin"] == "sdcard");
return !(data["origin"] && data["origin"] === "sdcard");
},
"machinecode": function(data) {
return data["type"] && (data["type"] == "machinecode" || data["type"] == "folder");
return data["type"] && (data["type"] === "machinecode" || data["type"] === "folder");
},
"model": function(data) {
return data["type"] && (data["type"] == "model" || data["type"] == "folder");
return data["type"] && (data["type"] === "model" || data["type"] === "folder");
}
},
"name",
@@ -131,22 +133,22 @@ $(function() {
);
self.foldersOnlyList = ko.dependentObservable(function() {
var filter = function(data) { return data["type"] && data["type"] == "folder"; };
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"; };
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") {
if (style === "folders_files" || style === "files_folders") {
var files = self.filesOnlyList();
var folders = self.foldersOnlyList();
if (style == "folders_files") {
if (style === "folders_files") {
return folders.concat(files);
} else {
return files.concat(folders);
@@ -173,14 +175,14 @@ $(function() {
};
self.highlightFilename = function(filename) {
if (filename == undefined) {
if (filename === undefined) {
self.listHelper.selectNone();
} else {
self.listHelper.selectItem(function(item) {
if (item.type == "folder") {
if (item.type === "folder") {
return _.startsWith(filename, item.path + "/");
} else {
return item.path == filename;
return item.path === filename;
}
});
}
@@ -307,11 +309,11 @@ $(function() {
}
}
if (response.free != undefined) {
if (response.free !== undefined) {
self.freeSpace(response.free);
}
if (response.total != undefined) {
if (response.total !== undefined) {
self.totalSpace(response.total);
}
@@ -386,7 +388,7 @@ $(function() {
return;
}
if (folder.type != "folder") {
if (folder.type !== "folder") {
return;
}
@@ -426,7 +428,7 @@ $(function() {
return;
}
if (file.type == "folder") {
if (file.type === "folder") {
return;
}
@@ -457,7 +459,7 @@ $(function() {
self.activeRemovals.push(entry.origin + ":" + entry.path);
var finishActiveRemoval = function() {
self.activeRemovals(_.filter(self.activeRemovals(), function(e) {
return e != entry.origin + ":" + entry.path;
return e !== entry.origin + ":" + entry.path;
}));
};
@@ -550,7 +552,7 @@ $(function() {
}
var busy = false;
if (data.type == "folder") {
if (data.type === "folder") {
busy = _.any(self.printerState.busyFiles(), function(name) {
return _.startsWith(name, data.origin + ":" + data.path + "/");
});
@@ -594,16 +596,16 @@ $(function() {
output += gettext("Model size") + ": " + _.sprintf("%(width).2fmm &times; %(depth).2fmm &times; %(height).2fmm", dimensions);
output += "<br>";
}
if (data["gcodeAnalysis"]["filament"] && typeof(data["gcodeAnalysis"]["filament"]) == "object") {
if (data["gcodeAnalysis"]["filament"] && typeof(data["gcodeAnalysis"]["filament"]) === "object") {
var filament = data["gcodeAnalysis"]["filament"];
if (_.keys(filament).length == 1) {
if (_.keys(filament).length === 1) {
output += gettext("Filament") + ": " + formatFilament(data["gcodeAnalysis"]["filament"]["tool" + 0]) + "<br>";
} else if (_.keys(filament).length > 1) {
for (var toolKey in filament) {
if (!_.startsWith(toolKey, "tool") || !filament[toolKey] || !filament[toolKey].hasOwnProperty("length") || filament[toolKey]["length"] <= 0) continue;
output += gettext("Filament") + " (" + gettext("Tool") + " " + toolKey.substr("tool".length) + "): " + formatFilament(filament[toolKey]) + "<br>";
}
_.each(filament, function(f, k) {
if (!_.startsWith(k, "tool") || !f || !f.hasOwnProperty("length") || f["length"] <= 0) return;
output += gettext("Filament") + " (" + gettext("Tool") + " " + k.substr("tool".length)
+ "): " + formatFilament(f) + "<br>";
});
}
}
output += gettext("Estimated print time") + ": " + formatFuzzyPrintTime(data["gcodeAnalysis"]["estimatedPrintTime"]) + "<br>";
@@ -662,7 +664,7 @@ $(function() {
minZ : 0,
maxZ : volumeInfo.height()
};
if (volumeInfo.origin() == "center") {
if (volumeInfo.origin() === "center") {
boundaries["maxX"] = volumeInfo.width() / 2;
boundaries["minX"] = -1 * boundaries["maxX"];
boundaries["maxY"] = volumeInfo.depth() / 2;
@@ -691,7 +693,7 @@ $(function() {
}
//warn user
if (info != "") {
if (info !== "") {
if (notify) {
info += _.sprintf(gettext("Object's bounding box: (%(object.minX).2f, %(object.minY).2f, %(object.minZ).2f) &times; (%(object.maxX).2f, %(object.maxY).2f, %(object.maxZ).2f)"), formatData);
info += "<br>";
@@ -716,7 +718,7 @@ $(function() {
self.performSearch = function(e) {
var query = self.searchQuery();
if (query !== undefined && query.trim() != "") {
if (query !== undefined && query.trim() !== "") {
query = query.toLocaleLowerCase();
var recursiveSearch = function(entry) {
@@ -725,7 +727,7 @@ $(function() {
}
var success = entry["name"].toLocaleLowerCase().indexOf(query) > -1;
if (!success && entry["type"] == "folder" && entry["children"]) {
if (!success && entry["type"] === "folder" && entry["children"]) {
return _.any(entry["children"], recursiveSearch);
}
@@ -744,7 +746,7 @@ $(function() {
root = root || {children: self.allItems()};
var recursiveSearch = function(location, element) {
if (location.length == 0) {
if (location.length === 0) {
return element;
}
@@ -754,7 +756,7 @@ $(function() {
var name = location.shift();
for (var i = 0; i < element.children.length; i++) {
if (name == element.children[i].name) {
if (name === element.children[i].name) {
return recursiveSearch(location, element.children[i]);
}
}
@@ -815,14 +817,6 @@ $(function() {
self.uploadProgress = $("#gcode_upload_progress");
self.uploadProgressBar = $(".bar", self.uploadProgress);
if (CONFIG_SD_SUPPORT) {
self.localTarget = $("#drop_locally");
} else {
self.localTarget = $("#drop");
self.listHelper.removeFilter('sd');
}
self.sdTarget = $("#drop_sd");
self.dropOverlay = $("#drop_overlay");
self.dropZone = $("#drop");
self.dropZoneLocal = $("#drop_locally");
@@ -831,6 +825,14 @@ $(function() {
self.dropZoneLocalBackground = $("#drop_locally_background");
self.dropZoneSdBackground = $("#drop_sd_background");
if (CONFIG_SD_SUPPORT) {
self.localTarget = self.dropZoneLocal;
} else {
self.localTarget = self.dropZone;
self.listHelper.removeFilter('sd');
}
self.sdTarget = self.dropZoneSd;
self.dropOverlay.on('drop', self._forceEndDragNDrop);
function evaluateDropzones() {
@@ -975,8 +977,8 @@ $(function() {
};
self._setDropzone = function(dropzone, enable) {
var button = (dropzone == "local") ? self.uploadButton : self.uploadSdButton;
var drop = (dropzone == "local") ? self.localTarget : self.sdTarget;
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)
@@ -995,19 +997,21 @@ $(function() {
always: self._handleUploadAlways,
progressall: self._handleUploadProgress
}).bind('fileuploadsubmit', function(e, data) {
if (self.currentPath() != "")
if (self.currentPath() !== "")
data.formData = { path: self.currentPath() };
});
};
self._enableDragNDrop = function(enable) {
if (enable) {
$(document).bind("dragenter", self._handleDragNDrop);
$(document).bind("dragleave", self._endDragNDrop);
$(document).bind("dragenter", self._handleDragEnter);
$(document).bind("dragleave", self._handleDragLeave);
$(document).bind("dragover", self._handleDragOver);
log.debug("Enabled drag-n-drop");
} else {
$(document).unbind("dragenter", self._handleDragNDrop);
$(document).unbind("dragleave", self._endDragNDrop);
$(document).unbind("dragenter", self._handleDragEnter);
$(document).unbind("dragleave", self._handleDragLeave);
$(document).unbind("dragover", self._handleDragOver);
log.debug("Disabled drag-n-drop");
}
};
@@ -1081,6 +1085,8 @@ $(function() {
};
self._dragNDropTarget = null;
self._dragNDropFFTimeout = undefined;
self._dragNDropFFTimeoutDelay = 100;
self._forceEndDragNDrop = function () {
self.dropOverlay.removeClass("in");
if (self.dropZoneLocal) self.dropZoneLocalBackground.removeClass("hover");
@@ -1089,12 +1095,39 @@ $(function() {
self._dragNDropTarget = null;
};
self._endDragNDrop = function (e) {
if (e.target != self._dragNDropTarget) return;
self._handleDragLeave = function (e) {
if (e.target !== self._dragNDropTarget) return;
self._forceEndDragNDrop();
};
self._handleDragNDrop = function (e) {
self._handleDragOver = function(e) {
// Workaround for Firefox
//
// Due to a browser bug (https://bugzilla.mozilla.org/show_bug.cgi?id=656164),
// if you drag a file out of the window no drag leave event will be fired. So on Firefox we check if
// our last dragover event was within a timeout. If not, we assume that's because the mouse
// cursor left the browser window and force a drag stop.
//
// Since Firefox keeps on triggering dragover events even if the mouse is not moved while over the
// browser window, this should work without side effects (e.g. the overlay should stay even if the user
// keeps the mouse perfectly still).
//
// See #2166
if (!OctoPrint.coreui.browser.firefox) return;
if (e.target !== self._dragNDropTarget) return;
if (self._dragNDropFFTimeout !== undefined) {
window.clearTimeout(self._dragNDropFFTimeout);
self._dragNDropFFTimeout = undefined;
}
self._dragNDropFFTimeout = window.setTimeout(function() {
self._forceEndDragNDrop();
self._dragNDropFFTimeout = undefined;
}, self._dragNDropFFTimeoutDelay);
};
self._handleDragEnter = function (e) {
self.dropOverlay.addClass('in');
var foundLocal = false;
@@ -1113,7 +1146,7 @@ $(function() {
break;
}
node = node.parentNode;
} while (node != null);
} while (node !== null);
if (foundLocal) {
self.dropZoneLocalBackground.addClass("hover");
@@ -1129,6 +1162,7 @@ $(function() {
if (self.dropZoneBackground) self.dropZoneBackground.removeClass("hover");
}
self._dragNDropTarget = e.target;
self._dragNDropLastOver = Date.now();
}
}
+102 -17
View File
@@ -56,11 +56,17 @@ $(function() {
self.reader_sortLayers = ko.observable(true);
self.reader_hideEmptyLayers = ko.observable(true);
self.reader_ignoreOutsideBed = ko.observable(true);
self.layerSelectionEnabled = ko.observable(false);
self.layerUpEnabled = ko.observable(false);
self.layerDownEnabled = ko.observable(false);
self.synchronizeOptionsAndReload = function(additionalRendererOptions, additionalReaderOptions) {
self.synchronizeOptions(additionalRendererOptions, additionalReaderOptions);
self.reload();
};
self.synchronizeOptions = function(additionalRendererOptions, additionalReaderOptions) {
var renderer = {
moveModel: self.renderer_centerModel(),
@@ -82,7 +88,7 @@ $(function() {
var reader = {
sortLayers: self.reader_sortLayers(),
purgeEmptyLayers: self.reader_hideEmptyLayers(),
ignoreOutsideBed: true
ignoreOutsideBed: self.reader_ignoreOutsideBed(),
};
if (additionalReaderOptions) {
_.extend(reader, additionalReaderOptions);
@@ -94,20 +100,32 @@ $(function() {
});
};
self.rendererOptionUpdated = function() {
self.synchronizeOptions();
self._toLocalStorage();
};
self.readerOptionUpdated = function() {
self.synchronizeOptionsAndReload();
self._toLocalStorage();
};
// subscribe to update Gcode view on updates...
self.renderer_centerModel.subscribe(self.synchronizeOptions);
self.renderer_centerViewport.subscribe(self.synchronizeOptions);
self.renderer_zoomOnModel.subscribe(self.synchronizeOptions);
self.renderer_showMoves.subscribe(self.synchronizeOptions);
self.renderer_showRetracts.subscribe(self.synchronizeOptions);
self.renderer_showBoundingBox.subscribe(self.synchronizeOptions);
self.renderer_showFullSize.subscribe(self.synchronizeOptions);
self.renderer_extrusionWidthEnabled.subscribe(self.synchronizeOptions);
self.renderer_extrusionWidth.subscribe(self.synchronizeOptions);
self.renderer_showNext.subscribe(self.synchronizeOptions);
self.renderer_showPrevious.subscribe(self.synchronizeOptions);
self.reader_sortLayers.subscribe(self.synchronizeOptions);
self.reader_hideEmptyLayers.subscribe(self.synchronizeOptions);
self.renderer_centerModel.subscribe(self.rendererOptionUpdated);
self.renderer_centerViewport.subscribe(self.rendererOptionUpdated);
self.renderer_zoomOnModel.subscribe(self.rendererOptionUpdated);
self.renderer_showMoves.subscribe(self.rendererOptionUpdated);
self.renderer_showRetracts.subscribe(self.rendererOptionUpdated);
self.renderer_showBoundingBox.subscribe(self.rendererOptionUpdated);
self.renderer_showFullSize.subscribe(self.rendererOptionUpdated);
self.renderer_extrusionWidthEnabled.subscribe(self.rendererOptionUpdated);
self.renderer_extrusionWidth.subscribe(self.rendererOptionUpdated);
self.renderer_showNext.subscribe(self.rendererOptionUpdated);
self.renderer_showPrevious.subscribe(self.rendererOptionUpdated);
self.reader_sortLayers.subscribe(self.readerOptionUpdated);
self.reader_hideEmptyLayers.subscribe(self.readerOptionUpdated);
self.reader_ignoreOutsideBed.subscribe(self.readerOptionUpdated);
self._printerProfileUpdated = function() {
if (!self.enabled) return;
@@ -122,7 +140,6 @@ $(function() {
toolOffsets: toolOffsets
}
});
}
var bedDimensions = self._retrieveBedDimensions(currentProfileData);
@@ -298,6 +315,7 @@ $(function() {
self.synchronizeOptions();
self.enabled = true;
self._fromLocalStorage();
});
};
@@ -308,6 +326,25 @@ $(function() {
self.clear();
};
self.resetOptions = function() {
self.renderer_centerModel(false);
self.renderer_centerViewport(false);
self.renderer_zoomOnModel(false);
self.renderer_showMoves(true);
self.renderer_showRetracts(true);
self.renderer_showBoundingBox(false);
self.renderer_showFullSize(false);
self.renderer_extrusionWidthEnabled(false);
self.renderer_extrusionWidth(2);
self.renderer_showNext(false);
self.renderer_showPrevious(false);
self.renderer_syncProgress(true);
self.reader_sortLayers(true);
self.reader_hideEmptyLayers(true);
self.reader_ignoreOutsideBed(true);
};
self.clear = function() {
GCODE.ui.clear();
};
@@ -323,7 +360,7 @@ $(function() {
step: 1,
value: 0,
enabled: false,
formatter: function(value) { return "Layer #" + (value + 1); }
formatter: function(value) { return "Layer #" + (value + 1) + " (Z = " + GCODE.renderer.getZ(value) + ")"; }
}).on("slide", self.changeLayer);
};
@@ -535,7 +572,6 @@ $(function() {
self.ui_layerInfo(output.join("<br>"));
console.log("#### Layer number:", layer.number, ", max layer:", self.maxLayer);
if (self.layerCommandSlider != undefined) {
self.layerCommandSlider.slider("enable");
self.layerCommandSlider.slider("setMax", layer.commands - 1);
@@ -655,6 +691,55 @@ $(function() {
var value = self.layerSlider.slider('getValue') - 1;
self.shiftLayer(value);
};
var optionsLocalStorageKey = "core.gcodeviewer.options";
self._toLocalStorage = function() {
if (!Modernizr.localstorage)
return;
var current = {};
current["centerViewport"] = self.renderer_centerViewport();
current["zoomOnModel"] = self.renderer_zoomOnModel();
current["showMoves"] = self.renderer_showMoves();
current["showRetracts"] = self.renderer_showRetracts();
current["showPrevious"] = self.renderer_showPrevious();
current["showNext"] = self.renderer_showNext();
current["showFullsize"] = self.renderer_showFullSize();
current["showBoundingBox"] = self.renderer_showBoundingBox();
current["hideEmptyLayers"] = self.reader_hideEmptyLayers();
current["sortLayers"] = self.reader_sortLayers();
localStorage[optionsLocalStorageKey] = JSON.stringify(current);
};
self._fromLocalStorage = function() {
self.resetOptions();
if (!Modernizr.localstorage)
return;
var currentString = localStorage[optionsLocalStorageKey];
var current;
if (currentString === undefined) {
current = {};
} else {
try {
current = JSON.parse(currentString);
} catch (ex) {
current = {};
}
}
if (current["centerViewport"] !== undefined) self.renderer_centerViewport(current["centerViewport"]) ;
if (current["zoomOnModel"] !== undefined) self.renderer_zoomOnModel(current["zoomOnModel"]) ;
if (current["showMoves"] !== undefined) self.renderer_showMoves(current["showMoves"]) ;
if (current["showRetracts"] !== undefined) self.renderer_showRetracts(current["showRetracts"]) ;
if (current["showPrevious"] !== undefined) self.renderer_showPrevious(current["showPrevious"]) ;
if (current["showNext"] !== undefined) self.renderer_showNext(current["showNext"]) ;
if (current["showFullsize"] !== undefined) self.renderer_showFullSize(current["showFullsize"]) ;
if (current["showBoundingBox"] !== undefined) self.renderer_showBoundingBox(current["showBoundingBox"]) ;
if (current["hideEmptyLayers"] !== undefined) self.reader_hideEmptyLayers(current["hideEmptyLayers"]) ;
if (current["sortLayers"] !== undefined) self.reader_sortLayers(current["sortLayers"]) ;
};
}
OCTOPRINT_VIEWMODELS.push([
@@ -230,6 +230,15 @@ $(function() {
self.webcam_ffmpegPathBroken(false);
};
self.server_onlineCheckText = ko.observable();
self.server_onlineCheckOk = ko.observable(false);
self.server_onlineCheckBroken = ko.observable(false);
self.server_onlineCheckReset = function() {
self.server_onlineCheckText("");
self.server_onlineCheckOk(false);
self.server_onlineCheckBroken(false);
};
self.addTemperatureProfile = function() {
self.temperature_profiles.push({name: "New", extruder:0, bed:0});
};
@@ -356,8 +365,31 @@ $(function() {
});
};
self.testOnlineConnectivityConfigBusy = ko.observable(false);
self.testOnlineConnectivityConfig = function() {
if (!self.server_onlineCheck_host()) return;
if (!self.server_onlineCheck_port()) return;
if (self.testOnlineConnectivityConfigBusy()) return;
self.testOnlineConnectivityConfigBusy(true);
OctoPrint.util.testServer(self.server_onlineCheck_host(), self.server_onlineCheck_port())
.done(function(response) {
if (!response.result) {
self.server_onlineCheckText(gettext("The server is not reachable"));
} else {
self.server_onlineCheckText(gettext("The server is reachable"));
}
self.server_onlineCheckOk(response.result);
self.server_onlineCheckBroken(!response.result);
})
.always(function() {
self.testOnlineConnectivityConfigBusy(false);
});
};
self.onSettingsHidden = function() {
self.webcam_ffmpegPathReset();
self.server_onlineCheckReset();
};
self.isDialogActive = function() {
@@ -330,10 +330,14 @@ $(function() {
// convert to minutes
var diffInMins = Math.round(diff / (60 * 1000));
if (diffInMins === 0)
if (diffInMins === 0) {
return gettext("just now");
else
} else if (diffInMins < 0) {
// we can't look into the future
return "";
} else {
return "- " + diffInMins + " " + gettext("min");
}
}
},
legend: {
@@ -357,6 +361,7 @@ $(function() {
if (!heaterOptions) return undefined;
var maxTemps = [310/1.1];
var now = Date.now();
var showFahrenheit = self._shallShowFahrenheit();
@@ -379,12 +384,12 @@ $(function() {
data.push({
label: gettext("Actual") + " " + heaterOptions[type].name + ": " + actualTemp,
color: heaterOptions[type].color,
data: actuals
data: actuals.length ? actuals : [[now, undefined]]
});
data.push({
label: gettext("Target") + " " + heaterOptions[type].name + ": " + targetTemp,
color: pusher.color(heaterOptions[type].color).tint(0.5).html(),
data: targets
data: targets.length ? targets : [[now, undefined]]
});
maxTemps.push(self.getMaxTemp(actuals, targets));
@@ -450,7 +455,6 @@ $(function() {
};
self.getMaxTemp = function(actuals, targets) {
var pair;
var maxTemp = 0;
actuals.forEach(function(pair) {
if (pair[1] > maxTemp){
+7
View File
@@ -901,6 +901,13 @@ ul.dropdown-menu li a {
}
}
#wizard_firstrun_start,
#wizard_firstrun_end {
p {
margin-bottom: 1.5em;
line-height: 1.5;
}
}
#settings_appearance_managelanguagesdialog_emptylist {
@@ -9,7 +9,7 @@
</thead>
<tbody data-bind="foreach: users.listHelper.paginatedItems">
<tr>
<td class="settings_users_name"><span data-bind="text: name"></span><span class="muted" data-bind="visible: $root.api_enabled() && apikey"><br /><small>{{ _('API Key') }}: <span data-bind="text: apikey"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: copyToClipboard(apikey)"><i class="fa fa-copy"></i></a></small></span></td>
<td class="settings_users_name"><span data-bind="text: name"></span><span class="muted" data-bind="visible: $root.api_enabled() && apikey"><br /><small>{{ _('API Key') }}: <span data-bind="text: apikey"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(apikey) }"><i class="fa fa-copy"></i></a></small></span></td>
<td class="settings_users_active"><i class="fa" data-bind="css: { 'fa-check-square-o': active, 'fa-square-o': !active }"></i></td>
<td class="settings_users_admin"><i class="fa" data-bind="css: { 'fa-check-square-o': admin, 'fa-square-o': !admin }"></i></td>
<td class="settings_users_actions">
@@ -1,12 +1,26 @@
<h3>{{ _('All Done!') }}</h3>
<p>{% trans %}
Your OctoPrint installation is now all set up and ready to go. Happy
printing!
Your OctoPrint installation is now all set up and ready to go.
{% endtrans %}</p>
<h4>{{ _('On your printer\'s safety') }}</h4>
<p>{% trans %}
Even with OctoPrint attached you should <strong class="text-error">never leave
your printer run completely unattended</strong>. The electronics in our consumer printers can and sometimes sadly do
catch fire, so stay or have someone else stay close enough to physically intervene in case of such catastrophic
failure.
{% endtrans %}</p>
<h4>{{ _('If you enjoy OctoPrint...') }}</h4>
<p>{% trans url='http://octoprint.org/support-octoprint/' %}
If you enjoy OctoPrint, please consider <a href="{{ url }}" target="_blank">supporting its ongoing
development</a>, which is fully funded by users like you! You can also find this link in the "About" dialog. <strong>Thank you!</strong>
Please consider to <strong><a href="{{ url }}" target="_blank">support OctoPrint's ongoing development</a></strong>,
which is only possible thanks to funding by users like you! You can also find this link in the "About" dialog.
<strong>Thank you!</strong>
{% endtrans %}</p>
<p>{% trans %}
With all that being said, <strong>Happy and Safe Printing</strong>!
{% endtrans %}</p>
@@ -1,7 +1,9 @@
<h3>{{ _('Hello!') }}</h3>
{% trans %}
Thank you for installing OctoPrint! This wizard will lead you through the
final steps to get your OctoPrint instance all setup and ready to go. We'll
<p>{% trans %}
Thank you for installing OctoPrint!
{% endtrans %}</p>
<p>{% trans %}
This wizard will guide you through the final steps to get your OctoPrint instance all setup and ready to go. We'll
get you printing in no time!
{% endtrans %}
{% endtrans %}</p>
+1 -1
View File
@@ -5,7 +5,7 @@
<!-- ko foreach: filament -->
<span data-bind="text: 'Filament (' + name() + '): ', title: 'Filament usage for ' + name()"></span><strong data-bind="text: formatFilament(data())"></strong><br>
<!-- /ko -->
<span title="{{ _('Estimated total print time base on statical analysis or past prints') }}">{{ _('Approx. Total Print Time') }}</span>: <strong data-bind="text: estimatedPrintTimeString"></strong><br>
<span title="{{ _('Estimated total print time based on analysis of the file or past prints') }}">{{ _('Approx. Total Print Time') }}</span>: <strong data-bind="text: estimatedPrintTimeString"></strong><br>
<hr>
<span title="{{ _('Total print time so far') }}">{{ _('Print Time') }}</span>: <strong data-bind="text: printTimeString"></strong><br>
<span title="{{ _('Estimated time until the print job is done. This is only an estimate and accuracy depends heavily on various factors!') }}">{{ _('Print Time Left') }}</span>: <strong data-bind="text: printTimeLeftString"></strong> <span id="state_printtimeleft_popover" style="display: none" data-bind="visible: printTimeLeftOrigin, attr: {title: printTimeLeftOriginString}, css: printTimeLeftOriginClass">&#9679;</span><br>
@@ -15,4 +15,5 @@
{% include "snippets/settings/server/serverOnlineCheckInterval.jinja2" %}
{% include "snippets/settings/server/serverOnlineCheckHost.jinja2" %}
{% include "snippets/settings/server/serverOnlineCheckPort.jinja2" %}
{% include "snippets/settings/server/serverOnlineCheckTest.jinja2" %}
</div>
@@ -1,4 +1,4 @@
<div class="control-group" title="{{ _('Host against which to check for internet connectivity') }}">
<div class="control-group" title="{{ _('Host against which to check for internet connectivity') }}" data-bind="css: {error: server_onlineCheckBroken, success: server_onlineCheckOk}">
<label class="control-label" for="settings-serverOnlineCheckHost">{{ _('Host IP') }}</label>
<div class="controls">
<input type="text" class="input-small" data-bind="value: server_onlineCheck_host" id="settings-serverOnlineCheckHost">
@@ -1,4 +1,4 @@
<div class="control-group" title="{{ _('Port against which to check for internet connectivity') }}">
<div class="control-group" title="{{ _('Port against which to check for internet connectivity') }}" data-bind="css: {error: server_onlineCheckBroken, success: server_onlineCheckOk}">
<label class="control-label" for="settings-serverOnlineCheckHost">{{ _('Port') }}</label>
<div class="controls">
<input type="number" min="1" max="65535" step="1" class="input-small" data-bind="value: server_onlineCheck_port" id="settings-serverOnlineCheckPort">
@@ -0,0 +1,6 @@
<div class="control-group" title="{{ _('Test') }}" data-bind="css: {error: server_onlineCheckBroken, success: server_onlineCheckOk}">
<div class="controls">
<button class="btn" data-bind="click: testOnlineConnectivityConfig, enable: server_onlineCheck_host() && server_onlineCheck_port() && !testOnlineConnectivityConfigBusy(), css: {disabled: !server_onlineCheck_host() || !server_onlineCheck_port() || testOnlineConnectivityConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testOnlineConnectivityConfigBusy"></i> {{ _('Test host & port') }}</button>
<span class="help-block" data-bind="visible: server_onlineCheckBroken() || server_onlineCheckOk(), text: server_onlineCheckText"></span>
</div>
</div>
@@ -69,6 +69,31 @@
<p>
<button class="btn btn-block" data-bind="click: reload, enable: enableReload">{{ _('Reload') }}</button>
</p>
<div class="advanced_options">
<div><small><a href="#" class="muted" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.advanced_options', container: '.hide' }"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
<div class="hide">
<p>
<label class="checkbox">
<input type="checkbox" data-bind="checked: renderer_showFullSize">{{ _('Show visited bounding box') }}
</label>
<label class="checkbox">
<input type="checkbox" data-bind="checked: renderer_showBoundingBox">{{ _('Show printed bounding box') }}
</label>
</p>
<p>
<label class="checkbox">
<input type="checkbox" data-bind="checked: reader_hideEmptyLayers">{{ _('Hide empty layers') }} <label class="label">{{ _('Causes reload') }}</label>
</label>
<label class="checkbox">
<input type="checkbox" data-bind="checked: reader_sortLayers">{{ _('Sort layers') }} <label class="label">{{ _('Causes reload') }}</label>
</label>
</p>
<p>
<button class="btn btn-block" data-bind="click: resetOptions">{{ _('Reset options') }}</button>
</p>
</div>
</div>
</div>
</div>