diff --git a/CHANGELOG.md b/CHANGELOG.md index 07abd8dba..e5b37bf07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,84 @@ # OctoPrint Changelog +## 1.3.3rc1 (2017-05-11) + +### Improvements + + * [#478](https://github.com/foosel/OctoPrint/issues/478) - Made webcam stream contained fixed height (with selectable aspect ratio) to prevent jumps of the controls beneath it on load. + * [#748](https://github.com/foosel/OctoPrint/issues/748) - Added delete confirmation and bulk delete for timelapses. See also the discussion in brainstorming ticket [#1807].(https://github.com/foosel/OctoPrint/issues/1807). + * [#1092](https://github.com/foosel/OctoPrint/issues/1092) - Added new event to the file manager: `FileAdded`, `FileRemoved`, `FolderAdded`, `FolderRemoved`. Contrary to the `Upload` event, `FileAdded` will always fire when a file was added to storage through the file manager, not only when added through the web interface. Extended documentation accordingly. + * [#1521](https://github.com/foosel/OctoPrint/issues/1521) - Software update plugin: Display timestamp of last version cache refresh in "Advanced options" area. + * [#1734](https://github.com/foosel/OctoPrint/issues/1734) - Treat default/initial printer profile like all other printer profiles, persisting it to disk instead of `config.yaml` and allowing deletion. OctoPrint will migrate the existing default profile to the new location on first start. + * [#1734](https://github.com/foosel/OctoPrint/issues/1734) - Better communication of what actions are available for printer profiles. + * [#1739](https://github.com/foosel/OctoPrint/issues/1739) - Software update plugin: Added option to hide update notification from users without admin rights, added "ignore" button and note to get in touch with an admit to update notifications for non admin users. + * [#1762](https://github.com/foosel/OctoPrint/issues/1762) - Added Malyan M200/Monoprice Select Mini to firmware autodetection. + * [#1811](https://github.com/foosel/OctoPrint/issues/1811) - Slight rewording and rearrangement in timelapse configuration, better feedback if settings have been saved. + * [#1818](https://github.com/foosel/OctoPrint/issues/1818) - Support both Marlin/Repetier and Smoothieware interpretations of `G90` after an `M83` in GCODE viewer and analysis. Select "G90/G91 overrides relative extruder mode" in Settings > Features for the Smoothieware interpretation. + * [#1858](https://github.com/foosel/OctoPrint/issues/1858) - Announcement plugin: Images from registered feeds now are lazy loading. + * [#1862](https://github.com/foosel/OctoPrint/issues/1862) - Automatically re-enable fancy terminal functionality when performance recovers. + * [#1875](https://github.com/foosel/OctoPrint/issues/1875) - Marked the command input field in the Terminal tab as not supporting autocomplete to work around an issue in Safari. Note that this is probably only a temporary workaround due to browser vendors [working on deprecating `autocomplete="off"` support](https://bugs.chromium.org/p/chromium/issues/detail?id=468153#c164) and a different solution will need to be found in the future. + * Added link to [`SerialException` FAQ entry](https://github.com/foosel/OctoPrint/wiki/FAQ#octoprint-randomly-loses-connection-to-the-printer-with-a-serialexception) to terminal output when such an error is encountered, as suggested in [#1876](https://github.com/foosel/OctoPrint/issues/1876). + * Force refresh of settings on login/logout. + * Made system wide API key management mirror user API key management. + * Make sure to always migrate and merge saved printer profiles with default profile to ensure all parameters are set. Should avoid issues with plugins trying to save outdated/incomplete profiles. + * Added note on lack of language pack repository & to use the wiki for now. + * Earlier validation of file to select for printing. + * Limit verbosity of failed system event handlers. + * Made bundled python client `octoprint_client` support multiple client instances. + * Disable "Reload" button in the "Please reload" overlay once clicked, added spinner. + * Updated pnotify to 2.1.0. + * Get rid of ridiculous float precision in temperature commands. + * Detect invalid settings data to persist (not a dict), send 400 status in such a case. + * More logging for preemptive caching, to help narrow down any performance issues that might be related to this. + * Further decoupling of some startup tasks from initial server startup thread for better parallelization and improved startup times. + * Announcement plugin: Added combined OctoBlog feed, replacing news and spotlight feed, added corresponding config migration. + * Announcement plugin: Subscribe to all registered feeds by default to ensure better communication flow (all subscriptions but the "Important" channel can however be unsubscribed easily, added corresponding note to the notifications and also a configuration button to the announcement reader). + * Announcement plugin: Auto-hide announcements on logout. + * Announcement plugin: Order channels server-side based on new order config setting. + * Plugin manager: Show warning when disabling a bundled plugin that is not recommended to be disabled, including a reason why disabling it is not recommended. Applies to the bundled announcement, core wizard, discovery and software update plugins. + * Plugin manager: Support for plugin notices for specific plugins from the plugin repository, e.g. to inform users of specific plugins about known issues with the plugin or instruct to update when the software update mechanism of the current plugin version turns out to be misconfigured. Supports matching installed plugin versions and OctoPrint versions to target only affected users. + * Plugin manager: Better visualization of plugins disabled on the repository, no longer shown as "incompatible" but "disabled", with link to the plugin repository page that contains more information. + * Plugin manager: Detect necessity to reinstall a plugin provided through archive URL or upload and immediately do that instead of reporting an "unknown error" without further information. + * Plugin manager: Added `freebsd` for compatibility check. + * Plugin manager: More general flexibility for OS compatibility check: + * Support for arbitrary values to match against + * Allow 1:1 check again `sys.platform` values (with `startswith`). + * Support black listing (`!windows`) additionally to white listing. A detected OS must match all provided white list elements (if the white list is empty that is considered to be always the case) and none of the black list elements (if the black list is empty that is also considered to be always the case). + * Software update plugin: New check type `bitbucket_commit` (see also [#1898](https://github.com/foosel/OctoPrint/pull/1898)) + * Docs: Now referring to dedicated Jinja 2.8 documentation as hosted at [jinja.octoprint.org](http://jinja.octoprint.org) for all template needs, to avoid confusion when consulting current Jinja documentation as available on its project page (2.9+, which OctoPrint can't upgrade to due to backwards incompatible changes). + * Docs: Better documentation of what kind of input the `FileManager` accepts for `select_file`. + * Docs: Specified OctoPrint version required for plugin tutorial. + +### Bug fixes + + * [#202](https://github.com/foosel/OctoPrint/issues/202) - Fixed an issue with the drag-n-drop area flickering if the mouse was moved too slow while dragging (see also [#1867](https://github.com/foosel/OctoPrint/pull/1867)). + * [#1671](https://github.com/foosel/OctoPrint/issues/1671) - Removed obsolete entry of no longer available filter for empty folders from file list options. + * [#1821](https://github.com/foosel/OctoPrint/issues/1821) - Fixed a wrong default value for "capture post roll images" in timelapse configuration. + * [#1822](https://github.com/foosel/OctoPrint/issues/1822) - Properly reset file metadata when a file is overwritten with a new version. + * [#1836](https://github.com/foosel/OctoPrint/issues/1836) - Fixed order of `PrintCancelled` and `PrintFailed` events on print cancel. + * [#1837](https://github.com/foosel/OctoPrint/issues/1837) - Fixed a race condition causing OctoPrint trying to read data from the current job on job cancel that was no longer there. + * [#1838](https://github.com/foosel/OctoPrint/issues/1838) - Fixed a rare race condition causing an error right at the very start of a print. + * [#1863](https://github.com/foosel/OctoPrint/issues/1863) - Fixed an issue in the analysis of GCODE files containing coordinate offsets for X, Y or Z via `G92`, leading to a wrong calculation of the model size thanks to accumulating offsets. + * [#1882](https://github.com/foosel/OctoPrint/issues/1882) - Fixed a rare race condition occurring at the start of streaming a file to the printer's SD card, leading to endless line number mismatches. + * [#1884](https://github.com/foosel/OctoPrint/issues/1884) - CuraEngine plugin: Fixed a potential encoding issue when logging non-ASCII parameters supplied to CuraEngine + * [#1891](https://github.com/foosel/OctoPrint/issues/1891) - Fixed error when handling unicode passwords. + * [#1893](https://github.com/foosel/OctoPrint/issues/1893) - CuraEngine plugin: Fixed handling of multiple consecutive uploads of slicing profiles (see also [#1894](https://github.com/foosel/OctoPrint/issues/1894)) + * [#1897](https://github.com/foosel/OctoPrint/issues/1897) - Removed possibility to concurrently try to perform multiple tests of the configured snapshot URL. + * [#1906](https://github.com/foosel/OctoPrint/issues/1906) - Fixed interpretation of `G92` in GCODE analysis. + * [#1907](https://github.com/foosel/OctoPrint/issues/1907) - Don't send temperature commands with tool parameter when a shared nozzle is defined. + * Fixed API key QR Code being shown (for "n/a" value) when no API key was set. + * Fixed timelapse configuration API not returning 400 status code on some bad parameters. + * Fixed a typo (see also [#1826](https://github.com/foosel/OctoPrint/pull/1826)). + * Fixed `filter` and `force` parameters on `/api/files/`. + * Fixed message catchall `*` not working in the socket client library. + * Fixed analysis backlog calculation for sub folders. + * Fixed `PrinterInterface.is_ready` to behave as documented. + * Use black listing instead of white listing again to detect if the `daemon` sub command is supported or not. Should resolve issues users of FreeBSD and the like where having with `octoprint daemon`. + * Use `pip` instead of `python setup.py develop` in `octoprint dev plugin:install` command to avoid issues on Windows. + * Docs: Fixed a wrong command in the plugin tutorial (see also [#1860](https://github.com/foosel/OctoPrint/pull/1860)). + +([Commits](https://github.com/foosel/OctoPrint/compare/1.3.2...1.3.3rc1)) + ## 1.3.2 (2017-03-16) ### Note for plugin authors diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4e3a47439..f3fb34118 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -380,7 +380,7 @@ Those usually have one of the following prefixes: * `dev/...` or `feature/...`: New functionality under development that is to be merged into the `devel` branch. -There is also the `gh-pages` branch, which holds OctoPrint's web page, and a couple of +There is also the `gh-pages` branch, which holds OctoPrint's web page, and a few older development branches that are slowly being migrated or deleted. ## How OctoPrint is versioned diff --git a/README.md b/README.md index dfe174be2..817884a57 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ and at its settings. ## Dependencies -OctoPrint depends on a couple of python modules to do its job. Those are automatically installed when installing +OctoPrint depends on a few python modules to do its job. Those are automatically installed when installing OctoPrint via `setup.py`: python setup.py install diff --git a/SUPPORTERS.md b/SUPPORTERS.md index 8fd085416..50a82c764 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -1,4 +1,4 @@ -# Supporters +# Supporters Development of this version of OctoPrint wouldn't have been possible without [financial support by the community](http://octoprint.org/support-octoprint/) - @@ -12,9 +12,8 @@ thanks to everyone who contributed! * Arnljot Arntsen * Boris Hussein * Brad Jackson - * Brent Fiegle * Brian E. Tyler - * Christopher Day + * Chris Day * Christian Petropolis * CreativeTools * D Brian Kimmel @@ -23,13 +22,15 @@ thanks to everyone who contributed! * E3D BigBox * Ernesto Martinez * Exovite + * F. Kunsmann * Frank Sander * Gary Deen * Gary N McKinney * George Robles + * günter weber + * Ivan Krasin * James Seigel * Jamie R McGuigan - * Jamie van Dyke * Jeff Moe * Josh Daniels * Kaile Riser @@ -59,9 +60,8 @@ thanks to everyone who contributed! * Stefan Krister * Stephane Schittly * Sven Mueller - * Terrance Shaw * Thomas Hatley * Timeshell.ca * Trent Shumay -and 1041 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! +and 1076 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! \ No newline at end of file diff --git a/docs/api/datamodel.rst b/docs/api/datamodel.rst index 076e7dbe4..768e420b0 100644 --- a/docs/api/datamodel.rst +++ b/docs/api/datamodel.rst @@ -31,7 +31,7 @@ Printer State * - ``flags`` - 1 - Printer state flags - - A couple of boolean printer state flags + - A few boolean printer state flags * - ``flags.operational`` - 1 - Boolean diff --git a/docs/bundledplugins/softwareupdate.rst b/docs/bundledplugins/softwareupdate.rst index a4e1213ee..17efc535c 100644 --- a/docs/bundledplugins/softwareupdate.rst +++ b/docs/bundledplugins/softwareupdate.rst @@ -188,6 +188,16 @@ Version checks * ``repo``: (mandatory) Github repository to check * ``branch``: Branch of the Github repository to check, defaults to ``master`` if not set. + * ``current``: Current commit hash. Will be updated automatically. + + * ``bitbucket_commit``: Checks against commits pushed to Bitbucket. Additional + config parameters: + + * ``user``: (mandatory) Bitbucket user the repository to check belongs to + * ``repo``: (mandatory) Bitbucket repository to check + * ``branch``: Branch of the Bitbucket repository to check, defaults to + ``master`` if not set. + * ``current``: Current commit hash. Will be updated automatically. * ``git_commit``: Checks a local git repository for new commits on its configured remote. Additional config parameters: diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index c48389ae8..debb35d16 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -943,8 +943,8 @@ Use the following settings to configure the server: * ``X-Scheme``: should contain your custom URL scheme to use (if different from ``http``), e.g. ``https`` If you use these headers OctoPrint will work both via the reverse proxy as well as when called directly. Take a look - `into OctoPrint's wiki `_ for a couple - of examples on how to configure this. + `into OctoPrint's wiki `_ for some + examples on how to configure this. .. _sec-configuration-config_yaml-slicing: diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst index e58cfdbc5..ee3136da8 100644 --- a/docs/features/gcode_scripts.rst +++ b/docs/features/gcode_scripts.rst @@ -13,11 +13,19 @@ Unless :ref:`configured otherwise `, OctoP the ``scripts/gcode`` folder in OctoPrint configuration directory (per default ``~/.octoprint`` on Linux, ``%APPDATA%\OctoPrint`` on Windows and ``~/Library/Application Support/OctoPrint`` on MacOS). -These GCODE scripts are backed by the templating engine `Jinja2 `_, allowing more than just +These GCODE scripts are backed by the templating engine Jinja2, allowing more than just simple "send-as-is" scripts but making use of a full blown templating language in order to create your scripts. To -this end, OctoPrint injects a couple of variables into the :ref:`template rendering context ` +this end, OctoPrint injects some variables into the :ref:`template rendering context ` as described below. +You can find the docs on the Jinja templating engine as used in OctoPrint at `jinja.octoprint.org `_. + +.. note:: + + Due to backwards compatibility issues with Jinja versions 2.9+, OctoPrint currently only supports Jinja 2.8. For this + reason use the template documentation at `jinja.octoprint.org `_ instead of the + documentation of current stable Jinja versions. + .. _sec-features-gcode_scripts-predefined: Predefined Scripts @@ -64,19 +72,21 @@ All GCODE scripts have access to the following template variables through the te * ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type`` and ``script.name`` respectively. -There are a couple of additional template variables available for the following specific scripts: +There are a few additional template variables available for the following specific scripts: * ``afterPrintPaused`` and ``beforePrintResumed`` * ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and current tool - ``t`` taken from commands sent through OctoPrint. + ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no position could be + retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)! * ``afterPrintCancelled`` * ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled. Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and - current tool ``t`` taken from commands sent through OctoPrint. + current tool ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no + position could be retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)! .. warning:: @@ -150,6 +160,7 @@ to 0 if a heated bed is configured. .. seealso:: - `Jinja Template Designer Documentation `_ + `Jinja Template Designer Documentation `_ Jinja's Template Designer Documentation describes the syntax and semantics of the template language used - also by OctoPrint's GCODE scripts. + also by OctoPrint's GCODE scripts. Linked here are the docs for Jinja 2.8.1, which OctoPrint still + relies on for backwards compatibility reasons. diff --git a/docs/plugins/gettingstarted.rst b/docs/plugins/gettingstarted.rst index 6bb554921..ca4f3935d 100644 --- a/docs/plugins/gettingstarted.rst +++ b/docs/plugins/gettingstarted.rst @@ -20,7 +20,7 @@ development environment:: $ virtualenv venv [...] $ source venv/bin/activate - (venv) $ pip install -e[develop] + (venv) $ pip install -e .[develop] [...] (venv) $ octoprint --help Usage: octoprint [OPTIONS] COMMAND [ARGS]... @@ -41,7 +41,15 @@ development environment:: [...] -We'll start at the most basic form a plugin can take - just a couple of simple lines of Python code: +.. important:: + + This tutorial assumes you are running OctoPrint 1.3.0 and up. Please make sure your version of + OctoPrint is up to date before proceeding. If you did a fresh checkout, that should already + be the case but if not you might have to update first. You can check your version of OctoPrint + by running ``octoprint --version`` or by taking a look into the lower left corner in OctoPrint's + web interface. + +We'll start at the most basic form a plugin can take - just a few simple lines of Python code: .. code-block:: python :linenos: @@ -108,7 +116,7 @@ used :func:`~octoprint.plugin.StartupPlugin.on_startup` instead, in which case o up and ready to serve requests. You'll also note that we are using ``self._logger`` for logging. Where did that one come from? OctoPrint's plugin system -injects :ref:`a couple of useful objects ` into our plugin implementation classes, +injects :ref:`a some useful objects ` into our plugin implementation classes, one of those being a fully instantiated `python logger `_ ready to be used by your plugin. As you can see in the log output above, that logger uses the namespace ``octoprint.plugins.helloworld`` for our little plugin here, or more generally ``octoprint.plugins.``. @@ -482,7 +490,7 @@ Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this: OctoPrint injects the template variables that your plugin defines prefixed with ``plugin__`` into the template renderer, so your ``url`` got turned into ``plugin_helloworld_url`` which you can now use as a simple -`Jinja2 Variable `_ in your plugin's template. +`Jinja2 Variable `_ in your plugin's template. Restart OctoPrint and shift-reload the page in your browser (to make sure you really get a fresh copy). The link should still work and point to the URL we defined as default. @@ -1070,8 +1078,14 @@ For some insight on how to create plugins that react to various events within Oc add support for a slicer, OctoPrint's own bundled `CuraEngine plugin `_ might give some hints. For extending OctoPrint's interface, the `NavbarTemp plugin `_ might show what's possible with a few lines of code already. Finally, just take a look at the -`list of available plugins `_ on the OctoPrint wiki if you are -looking for examples. +`official Plugin Repository `_ if you are looking for examples. + +.. seealso:: + + `Jinja Template Designer Documentation `_ + Jinja's Template Designer Documentation describes the syntax and semantics of the template language used + by OctoPrint's frontend. Linked here are the docs for Jinja 2.8.1, which OctoPrint still + relies on for backwards compatibility reasons [#f3]_. .. rubric:: Footnotes @@ -1084,3 +1098,7 @@ looking for examples. .. [#f2] Refer to the `LESS documentation `_ on how to do that. If you are developing your plugin under Windows you might also want to give `WinLESS `_ a look which will run in the background and keep your CSS files up to date with your various project's LESS files automatically. +.. [#f3] Please always consult the Jinja documentation at `jinja.octoprint.org `_ instead of + the current stable documentation available at Jinja's project page. The reason for that is that for backwards + compatibility reasons OctoPrint currently sadly has to rely on an older version of Jinja. The documentation + available at `jinja.octoprint.org `_ matches that older version. diff --git a/docs/plugins/helpers.rst b/docs/plugins/helpers.rst index 047811d8b..17cd18289 100644 --- a/docs/plugins/helpers.rst +++ b/docs/plugins/helpers.rst @@ -6,7 +6,7 @@ Helpers Helpers are methods that plugin can exposed to other plugins in order to make common functionality available on the system. They are registered with the OctoPrint plugin system through the use of the control property ``__plugin_helpers__``. -An example for providing a couple of helper functions to the system can be found in the +An example for providing some helper functions to the system can be found in the `Discovery Plugin `_, which provides it's SSDP browsing and Zeroconf browsing and publishing functions as helper methods. diff --git a/setup.cfg b/setup.cfg index cbda2efbf..9be46c443 100644 --- a/setup.cfg +++ b/setup.cfg @@ -3,7 +3,7 @@ description-file = README.md [versioneer] VCS = git -style = pep440-post +style = pep440-tag versionfile_source = src/octoprint/_version.py versionfile_build = octoprint/_version.py tag_prefix = diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py index 8ea8db7f1..7a4133ce9 100644 --- a/src/octoprint/cli/__init__.py +++ b/src/octoprint/cli/__init__.py @@ -160,11 +160,11 @@ def octo(ctx, **kwargs): "start|stop|restart\" is deprecated, please use " "\"octoprint daemon start|stop|restart\" from now on") - if sys.platform.startswith("linux") or sys.platform.startswith("freebsd"): + if sys.platform == "win32" or sys.platform == "darwin": + click.echo("Sorry, daemon mode is not supported under your operating system right now") + else: from octoprint.cli.server import daemon_command ctx.invoke(daemon_command, command=daemon, **kwargs) - else: - click.echo("Sorry, daemon mode is not supported under your operating system right now") else: click.echo("Starting the server via \"octoprint\" is deprecated, " "please use \"octoprint serve\" from now on.") diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py index 070806ad6..97fcce652 100644 --- a/src/octoprint/cli/client.py +++ b/src/octoprint/cli/client.py @@ -79,30 +79,33 @@ def log_response(response, status_code=True, body=True, headers=False): @client.command("get") @click.argument("path") +@click.option("--timeout", type=float, default=None) @click.pass_context -def get(ctx, path): +def get(ctx, path, timeout): """Performs a GET request against the specified server path.""" - r = ctx.obj.client.get(path) + r = ctx.obj.client.get(path, timeout=timeout) log_response(r) @client.command("post_json") @click.argument("path") @click.argument("data", type=JsonStringParamType()) +@click.option("--timeout", type=float, default=None) @click.pass_context -def post_json(ctx, path, data): +def post_json(ctx, path, data, timeout): """POSTs JSON data to the specified server path.""" - r = ctx.obj.client.post_json(path, data) + r = ctx.obj.client.post_json(path, data, timeout=timeout) log_response(r) @client.command("patch_json") @click.argument("path") @click.argument("data", type=JsonStringParamType()) +@click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context -def patch_json(ctx, path, data): +def patch_json(ctx, path, data, timeout): """PATCHes JSON data to the specified server path.""" - r = ctx.obj.client.patch(path, data, encoding="json") + r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout) log_response(r) @@ -111,9 +114,10 @@ def patch_json(ctx, path, data): @click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True)) @click.option("--json", is_flag=True) @click.option("--yaml", is_flag=True) +@click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context -def post_from_file(ctx, path, file_path, json_flag, yaml_flag): - """POSTs JSON data to the specified server path.""" +def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout): + """POSTs JSON data to the specified server path, taking the data from the specified file.""" if json_flag or yaml_flag: if json_flag: with open(file_path, "rb") as fp: @@ -123,12 +127,12 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag): with open(file_path, "rb") as fp: data = yaml.safe_load(fp) - r = ctx.obj.client.post_json(path, data) + r = ctx.obj.client.post_json(path, data, timeout=timeout) else: with open(file_path, "rb") as fp: data = fp.read() - r = ctx.obj.client.post(path, data) + r = ctx.obj.client.post(path, data, timeout=timeout) log_response(r) @@ -140,14 +144,15 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag): @click.option("--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int])) @click.option("--float", "-f", "float_params", multiple=True, nargs=2, type=click.Tuple([unicode, float])) @click.option("--bool", "-b", "bool_params", multiple=True, nargs=2, type=click.Tuple([unicode, bool])) +@click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context -def command(ctx, path, command, str_params, int_params, float_params, bool_params): +def command(ctx, path, command, str_params, int_params, float_params, bool_params, timeout): """Sends a JSON command to the specified server path.""" data = dict() params = str_params + int_params + float_params + bool_params for param in params: data[param[0]] = param[1] - r = ctx.obj.client.post_command(path, command, additional=data) + r = ctx.obj.client.post_command(path, command, additional=data, timeout=timeout) log_response(r, body=False) @@ -157,23 +162,26 @@ def command(ctx, path, command, str_params, int_params, float_params, bool_param @click.option("--parameter", "-P", "params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode])) @click.option("--file-name", type=click.STRING) @click.option("--content-type", type=click.STRING) +@click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context -def upload(ctx, path, file_path, params, file_name, content_type): +def upload(ctx, path, file_path, params, file_name, content_type, timeout): """Uploads the specified file to the specified server path.""" data = dict() for param in params: data[param[0]] = param[1] - r = ctx.obj.client.upload(path, file_path, additional=data, file_name=file_name, content_type=content_type) + r = ctx.obj.client.upload(path, file_path, + additional=data, file_name=file_name, content_type=content_type, timeout=timeout) log_response(r) @client.command("delete") @click.argument("path") +@click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context -def delete(ctx, path): +def delete(ctx, path, timeout): """Sends a DELETE request to the specified server path.""" - r = ctx.obj.client.delete(path) + r = ctx.obj.client.delete(path, timeout=timeout) log_response(r) diff --git a/src/octoprint/cli/dev.py b/src/octoprint/cli/dev.py index baf678bcc..7273b8ba0 100644 --- a/src/octoprint/cli/dev.py +++ b/src/octoprint/cli/dev.py @@ -204,7 +204,7 @@ class OctoPrintDevelCommands(click.MultiCommand): click.echo("This doesn't look like an OctoPrint plugin folder") sys.exit(1) - self.command_caller.call([sys.executable, "setup.py", "develop"], cwd=path) + self.command_caller.call([sys.executable, "-m", "pip", "install", "-e", "."], cwd=path) return command diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index f7539d0a0..cfadc559b 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -150,8 +150,8 @@ def serve_command(ctx, **kwargs): allow_root, logging, verbosity, safe_mode) -if sys.platform.startswith("linux") or sys.platform.startswith("freebsd"): - # we only support daemon mode under Linux and FreeBSD for now +if sys.platform != "win32" and sys.platform != "darwin": + # we do not support daemon mode under windows or macosx @server_commands.command(name="daemon") @server_options diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 367fd9851..c8630e59a 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -376,7 +376,7 @@ class CommandTrigger(GenericEventListener): def _processCommand(self, command, payload): """ - Performs string substitutions in the command string based on a couple of current parameters. + Performs string substitutions in the command string based on a few current parameters. The following substitutions are currently supported: diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index bbc90b090..c69b3e14c 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -669,16 +669,9 @@ class LocalFileStorage(StorageInterface): # save the file's hash to the metadata of the folder file_hash = self._create_hash(file_path) metadata = self._get_metadata_entry(path, name, default=dict()) - metadata_dirty = False if not "hash" in metadata or metadata["hash"] != file_hash: - metadata["hash"] = file_hash - metadata_dirty = True - if "analysis" in metadata: - del metadata["analysis"] - metadata_dirty = True - - if metadata_dirty: - self._update_metadata_entry(path, name, metadata) + # hash changed -> throw away old metadata + self._update_metadata_entry(path, name, dict(hash=file_hash)) # process any links that were also provided for adding to the file if not links: diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index 31367e542..57adfb2ed 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -239,7 +239,7 @@ class PluginSettings(object): """ The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings. - It provides a couple of convenience methods for directly accessing plugin settings via the regular + It provides some convenience methods for directly accessing plugin settings via the regular :class:`octoprint.settings.Settings` interfaces as well as means to access plugin specific folder locations. All getter and setter methods will ensure that plugin settings are stored in their correct location within the diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index f8a168f5d..4f98a29ab 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -571,6 +571,10 @@ class PluginManager(object): key = entry.name elif entry.is_file() and entry.name.endswith(".py"): key = entry.name[:-3] # strip off the .py extension + if key.startswith("__"): + # might be an __init__.py in our plugins folder, or something else we don't want + # to handle + continue else: continue diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index 2886fb208..c76ff0a46 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -531,7 +531,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): provided request by calling :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` with the Flask `Request `_ object as parameter. If you plugin returns `True` here, OctoPrint will next call - :meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a couple of parameters like + :meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a few parameters like - again - the Flask Request object and the render keyword arguments as used by the default OctoPrint web interface. For more information see below. @@ -582,7 +582,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): it only gets re-rendered if the request demands that (by having no-cache headers set) or if the cache gets invalidated otherwise. - In order to be able to do that, the ``UiPlugin`` offers overriding a couple of cache specific + In order to be able to do that, the ``UiPlugin`` offers overriding some cache specific methods used for figuring out the source files whose modification time to use for cache invalidation as well as override possibilities for ETag and LastModified calculation. Additionally there are methods to allow persisting call parameters to allow for preemptively caching your UI during @@ -1038,7 +1038,7 @@ class SimpleApiPlugin(OctoPrintPlugin): mixin offers. Use this mixin if all you need to do is return some kind of dynamic data to your plugin from the backend - and/or want to react to simple commands which boil down to a type of command and a couple of flat parameters + and/or want to react to simple commands which boil down to a type of command and a few flat parameters supplied with it. The simple API constructed by OctoPrint for you will be made available under ``/api/plugin//``. diff --git a/src/octoprint/plugins/__init__.py b/src/octoprint/plugins/__init__.py new file mode 100644 index 000000000..1b0510c60 --- /dev/null +++ b/src/octoprint/plugins/__init__.py @@ -0,0 +1 @@ +# make our plugins testable diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 00a2664a9..7f73efb20 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -41,7 +41,13 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, # StartupPlugin def on_after_startup(self): - self._fetch_all_channels() + # decouple channel fetching from server startup + def fetch_data(): + self._fetch_all_channels() + + thread = threading.Thread(target=fetch_data) + thread.daemon = True + thread.start() # SettingsPlugin @@ -324,7 +330,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, url = config["url"] try: start = time.time() - r = requests.get(url) + r = requests.get(url, timeout=30) + r.raise_for_status() self._logger.info(u"Loaded channel {} from {} in {:.2}s".format(key, config["url"], time.time() - start)) except Exception as e: self._logger.exception( @@ -359,7 +366,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, return dict(title=entry["title"], title_without_tags=_strip_tags(entry["title"]), - summary=entry["summary"], + summary=_lazy_images(entry["summary"]), summary_without_images=_strip_images(entry["summary"]), published=published, link=entry["link"], @@ -374,8 +381,57 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, _image_tag_re = re.compile(r'') def _strip_images(text): + """ + >>> _strip_images(u"I'm a link and this is an image: foo") + u"I'm a link and this is an image: " + >>> _strip_images(u"One and two and three and four \\"four\\"") + u'One and two and three and four ' + >>> _strip_images(u"No images here") + u'No images here' + """ return _image_tag_re.sub('', text) +def _replace_images(text, callback): + """ + >>> callback = lambda img: "foobar" + >>> _replace_images(u"I'm a link and this is an image: foo", callback) + u"I'm a link and this is an image: foobar" + >>> _replace_images(u"One and two and three and four \\"four\\"", callback) + u'One foobar and two foobar and three foobar and four foobar' + """ + result = text + for match in _image_tag_re.finditer(text): + tag = match.group(0) + replaced = callback(tag) + result = result.replace(tag, replaced) + return result + +_image_src_re = re.compile(r'src=(?P[\'"]*)(?P.*?)(?P=quote)(?=\s+|>)') +def _lazy_images(text, placeholder=None): + """ + >>> _lazy_images(u"I'm a link and this is an image: foo") + u'I\\'m a link and this is an image: \\'foo\\'' + >>> _lazy_images(u"I'm a link and this is an image: foo", placeholder="ph.png") + u'I\\'m a link and this is an image: \\'foo\\'' + >>> _lazy_images(u"One and two and three and four \\"four\\"", placeholder="ph.png") + u'One and two and three and four four' + >>> _lazy_images(u"No images here") + u'No images here' + """ + if placeholder is None: + # 1px transparent gif + placeholder = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" + + def callback(img_tag): + match = _image_src_re.search(img_tag) + if match is not None: + src = match.group("src") + quote = match.group("quote") + quoted_src = quote + src + quote + img_tag = img_tag.replace(match.group(0), 'src="{}" data-src={}'.format(placeholder, quoted_src)) + return img_tag + + return _replace_images(text, callback) def _strip_tags(text): """ diff --git a/src/octoprint/plugins/announcements/static/js/announcements.js b/src/octoprint/plugins/announcements/static/js/announcements.js index dfd6d7d9a..2fe4dbb7d 100644 --- a/src/octoprint/plugins/announcements/static/js/announcements.js +++ b/src/octoprint/plugins/announcements/static/js/announcements.js @@ -143,6 +143,9 @@ $(function() { self.showAnnouncementDialog = function(channel) { if (!self.loginState.isAdmin()) return; + // lazy load images that still need lazy-loading + $("#plugin_announcements_dialog_content article img").lazyload(); + self.announcementDialogContent.scrollTop(0); if (!self.announcementDialog.hasClass("in")) { diff --git a/src/octoprint/plugins/cura/__init__.py b/src/octoprint/plugins/cura/__init__.py index 5fd933fb0..8713c3778 100644 --- a/src/octoprint/plugins/cura/__init__.py +++ b/src/octoprint/plugins/cura/__init__.py @@ -17,6 +17,7 @@ import octoprint.slicing import octoprint.settings from octoprint.util.paths import normalize as normalize_path +from octoprint.util import to_unicode from .profile import Profile from .profile import GcodeFlavors @@ -236,7 +237,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, self._save_profile(path, new_profile, allow_overwrite=allow_overwrite) - def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None): + def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, + on_progress=None, on_progress_args=None, on_progress_kwargs=None): try: with self._job_mutex: if not profile_path: @@ -258,7 +260,10 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, if not on_progress_kwargs: on_progress_kwargs = dict() - self._cura_logger.info(u"### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path)) + self._cura_logger.info(u"### Slicing {} to {} using profile stored at {}" + .format(to_unicode(model_path, errors="replace"), + to_unicode(machinecode_path, errors="replace"), + to_unicode(profile_path, errors="replace"))) executable = normalize_path(self._settings.get(["cura_engine"])) if not executable: @@ -293,7 +298,9 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, args += ["-s", "%s=%s" % (k, str(v))] args += ["-o", machinecode_path, model_path] - self._logger.info(u"Running %r in %s" % (" ".join(args), working_dir)) + self._logger.info(u"Running {!r} in {}".format(u" ".join(map(lambda x: to_unicode(x, errors="replace"), + args)), + working_dir)) import sarge p = sarge.run(args, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture()) @@ -314,7 +321,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, p.commands[0].poll() continue - line = octoprint.util.to_unicode(line, errors="replace") + line = to_unicode(line, errors="replace") self._cura_logger.debug(line.strip()) if on_progress is not None: @@ -437,7 +444,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, command = self._slicing_commands[machinecode_path] if command is not None: command.terminate() - self._logger.info(u"Cancelled slicing of %s" % machinecode_path) + self._logger.info(u"Cancelled slicing of {}" + .format(to_unicode(machinecode_path, errors="replace"))) def _load_profile(self, path): import yaml diff --git a/src/octoprint/plugins/cura/static/js/cura.js b/src/octoprint/plugins/cura/static/js/cura.js index 4b57e623b..87f9d5f64 100644 --- a/src/octoprint/plugins/cura/static/js/cura.js +++ b/src/octoprint/plugins/cura/static/js/cura.js @@ -25,11 +25,35 @@ $(function() { self.profileAllowOverwrite = ko.observable(true); self.profileMakeDefault = ko.observable(false); + // make sure to update form data if any of the metadata changes + self.profileName.subscribe(function() { self.copyProfileMetadata(); }); + self.profileDisplayName.subscribe(function() { + if (self.profileDisplayName()) { + self.placeholderName(self._sanitize(self.profileDisplayName()).toLowerCase()); + } + self.copyProfileMetadata(); + }); + self.profileDescription.subscribe(function() { self.copyProfileMetadata(); }); + self.profileAllowOverwrite.subscribe(function() { self.copyProfileMetadata(); }); + self.profileMakeDefault.subscribe(function() { self.copyProfileMetadata(); }); + self.unconfiguredCuraEngine = ko.observable(); self.unconfiguredSlicingProfile = ko.observable(); + self.uploadDialog = $("#settings_plugin_cura_import"); self.uploadElement = $("#settings-cura-import"); - self.uploadButton = $("#settings-cura-import-start"); + self.uploadData = ko.observable(undefined); + self.uploadBusy = ko.observable(false); + + self.uploadEnabled = ko.pureComputed(function() { + return self.fieldsEnabled(); + }); + self.fieldsEnabled = ko.pureComputed(function() { + return self.uploadData() && !self.uploadBusy() + && (self.profileName() || self.placeholderName()) + && (self.profileDisplayName() || self.placeholderDisplayName()) + && (self.profileDescription() || self.placeholderDescription()); + }); self.profiles = new ItemListHelper( "plugin_cura_profiles", @@ -66,6 +90,53 @@ $(function() { return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_"); }; + self.performUpload = function() { + if (self.uploadData()) { + self.uploadData().submit(); + } + }; + + self.copyProfileMetadata = function(form) { + form = form || (self.uploadData() ? self.uploadData().formData : {}); + + if (self.profileName() !== undefined) { + form["name"] = self.profileName(); + } else if (self.placeholderName() !== undefined) { + form["name"] = self.placeholderName(); + } + + if (self.profileDisplayName() !== undefined) { + form["displayName"] = self.profileDisplayName(); + } else if (self.placeholderDisplayName() !== undefined) { + form["displayName"] = self.placeholderDisplayName(); + } + + if (self.profileDescription() !== undefined) { + form["description"] = self.profileDescription(); + } else if (self.placeholderDescription() !== undefined) { + form["description"] = self.placeholderDescription(); + } + + if (self.profileMakeDefault()) { + form["default"] = true; + } + + return form; + }; + + self.clearUpload = function() { + self.uploadData(undefined); + self.fileName(undefined); + self.placeholderName(undefined); + self.placeholderDisplayName(undefined); + self.placeholderDescription(undefined); + self.profileName(undefined); + self.profileDisplayName(undefined); + self.profileDescription(undefined); + self.profileAllowOverwrite(true); + self.profileMakeDefault(false); + }; + self.uploadElement.fileupload({ dataType: "json", maxNumberOfFiles: 1, @@ -73,6 +144,11 @@ $(function() { headers: OctoPrint.getRequestHeaders(), add: function(e, data) { if (data.files.length == 0) { + // no files? ignore + return false; + } + if (self.uploadData()) { + // data already defined? ignore (should never happen) return false; } @@ -83,41 +159,22 @@ $(function() { self.placeholderDisplayName(name); self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000)); - self.uploadButton.unbind("click"); - self.uploadButton.on("click", function() { - var form = { - allowOverwrite: self.profileAllowOverwrite() - }; + var form = { + allowOverwrite: self.profileAllowOverwrite() + }; + data.formData = self.copyProfileMetadata(form); - if (self.profileName() !== undefined) { - form["name"] = self.profileName(); - } - if (self.profileDisplayName() !== undefined) { - form["displayName"] = self.profileDisplayName(); - } - if (self.profileDescription() !== undefined) { - form["description"] = self.profileDescription(); - } - if (self.profileMakeDefault()) { - form["default"] = true; - } - - data.formData = form; - data.submit(); - }); + self.uploadData(data); + }, + submit: function(e, data) { + self.copyProfileMetadata(); + self.uploadBusy(true); }, done: function(e, data) { - self.fileName(undefined); - self.placeholderName(undefined); - self.placeholderDisplayName(undefined); - self.placeholderDescription(undefined); - self.profileName(undefined); - self.profileDisplayName(undefined); - self.profileDescription(undefined); - self.profileAllowOverwrite(true); - self.profileMakeDefault(false); + self.uploadBusy(false); + self.clearUpload(); - $("#settings_plugin_cura_import").modal("hide"); + self.uploadDialog.modal("hide"); self.requestData(); self.slicingViewModel.requestData(); } @@ -160,12 +217,9 @@ $(function() { }); }; - self.showImportProfileDialog = function(makeDefault) { - if (makeDefault == undefined) { - makeDefault = _.filter(self.profiles.items(), function(profile) { profile.isdefault() }).length == 0; - } - self.profileMakeDefault(makeDefault); - $("#settings_plugin_cura_import").modal("show"); + self.showImportProfileDialog = function() { + self.clearUpload(); + self.uploadDialog.modal("show"); }; self.testEnginePath = function() { @@ -207,7 +261,18 @@ $(function() { self.onBeforeBinding = function () { self.settings = self.settingsViewModel.settings; - //self.requestData(); + }; + + self.onAllBound = function() { + self.uploadDialog.on("hidden", function(event) { + if (event.target.id == "settings_plugin_cura_import") { + self.clearUpload(); + } + }); + }; + + self.onSettingsShown = function() { + self.requestData(); }; self.onSettingsHidden = function() { diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 index 063fd5b7c..7057bff27 100644 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 +++ b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 @@ -20,31 +20,31 @@
- +
- +
- +
-
-
@@ -59,6 +59,6 @@
diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 8dfabd050..03b81a40c 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -28,6 +28,7 @@ import pkg_resources import copy import dateutil.parser import time +import threading class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, octoprint.plugin.TemplatePlugin, @@ -39,8 +40,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar") OPERATING_SYSTEMS = dict(windows=["win32"], - linux=["linux2"], - macos=["darwin"]) + linux=lambda x: x.startswith("linux"), + macos=["darwin"], + freebsd=lambda x: x.startswith("freebsd")) pip_inapplicable_arguments = dict(uninstall=["--user"]) @@ -84,7 +86,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, ##~~ StartupPlugin - def on_startup(self, host, port): + def on_after_startup(self): from octoprint.logging.handlers import CleaningTimedRotatingFileHandler console_logging_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), when="D", backupCount=3) console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) @@ -94,8 +96,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._console_logger.setLevel(logging.DEBUG) self._console_logger.propagate = False - self._repository_available = self._fetch_repository_from_disk() - self._notices_available = self._fetch_notices_from_disk() + # decouple repository fetching from server startup + def fetch_data(): + self._repository_available = self._fetch_repository_from_disk() + self._notices_available = self._fetch_notices_from_disk() + + thread = threading.Thread(target=fetch_data) + thread.daemon = True + thread.start() ##~~ SettingsPlugin @@ -675,7 +683,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def _fetch_repository_from_url(self): repository_url = self._settings.get(["repository"]) try: - r = requests.get(repository_url) + r = requests.get(repository_url, timeout=30) + r.raise_for_status() self._logger.info("Loaded plugin repository data from {}".format(repository_url)) except Exception as e: self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=str(e))) @@ -743,7 +752,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, def _fetch_notices_from_url(self): notices_url = self._settings.get(["notices"]) try: - r = requests.get(notices_url) + r = requests.get(notices_url, timeout=30) + r.raise_for_status() self._logger.info("Loaded plugin notices data from {}".format(notices_url)) except Exception as e: self._logger.exception("Could not fetch notices from {notices_url}: {message}".format(notices_url=notices_url, message=str(e))) @@ -807,18 +817,37 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return True - def _is_os_compatible(self, current_os, compatibility_entries): + @staticmethod + def _is_os_compatible(current_os, compatibility_entries): """ - Tests if the ``current_os`` matches any of the provided ``compatibility_entries``. + Tests if the ``current_os`` or ``sys.platform`` are blacklisted or whitelisted in ``compatibility_entries`` """ - return current_os in filter(lambda x: x in self.__class__.OPERATING_SYSTEMS.keys(), compatibility_entries) + if len(compatibility_entries) == 0: + # shortcut - no compatibility info means we are compatible + return True - def _get_os(self): - for identifier, platforms in self.__class__.OPERATING_SYSTEMS.items(): - if sys.platform in platforms: + negative_entries = map(lambda x: x[1:], filter(lambda x: x.startswith("!"), compatibility_entries)) + positive_entries = filter(lambda x: not x.startswith("!"), compatibility_entries) + + negative_match = False + if negative_entries: + # check if we are blacklisted + negative_match = current_os in negative_entries or any(map(lambda x: sys.platform.startswith(x), negative_entries)) + + positive_match = True + if positive_entries: + # check if we are whitelisted + positive_match = current_os in positive_entries or any(map(lambda x: sys.platform.startswith(x), positive_entries)) + + return positive_match and not negative_match + + @classmethod + def _get_os(cls): + for identifier, platforms in cls.OPERATING_SYSTEMS.items(): + if (callable(platforms) and platforms(sys.platform)) or (isinstance(platforms, list) and sys.platform in platforms): return identifier else: - return "unknown" + return "unmapped" def _get_octoprint_version_string(self): return VERSION diff --git a/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css b/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css index 91383181e..65ae4796c 100644 --- a/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css +++ b/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css @@ -1 +1 @@ -table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px 10px 5px 5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009} \ No newline at end of file +table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px 10px 5px 5px}#settings_plugin_pluginmanager_workingdialog_output span{display:block}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009} \ No newline at end of file diff --git a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less index 2b591e9cb..cd49e51db 100644 --- a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less +++ b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less @@ -85,6 +85,10 @@ table { } #settings_plugin_pluginmanager_workingdialog_output { + span { + display: block; + } + .message { font-weight: bold; } diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index 93b65dfd3..8e8e614f9 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -108,7 +108,7 @@

diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index 4e127d8bb..98a24d5b7 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -398,7 +398,7 @@ function formatFuzzyPrintTime(totalSeconds) { * * Accuracy decreases the higher the estimation is: * - * * less than 30s: "a couple of seconds" + * * less than 30s: "a few seconds" * * 30s to a minute: "less than a minute" * * 1 to 30min: rounded to full minutes, above 30s is minute + 1 ("27 minutes", "2 minutes") * * 30min to 40min: "40 minutes" @@ -495,7 +495,7 @@ function formatFuzzyPrintTime(totalSeconds) { } else { // only seconds if (seconds < 30) { - text = gettext("a couple of seconds"); + text = gettext("a few seconds"); } else { text = gettext("less than a minute"); } diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index 072de84ae..486109fbf 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -444,6 +444,18 @@ $(function() { } }; + $.fn.lazyload = function() { + return this.each(function() { + if (this.tagName.toLowerCase() != "img") return; + + var src = this.getAttribute("data-src"); + if (src) { + this.setAttribute("src", src); + this.removeAttribute("data-src"); + } + }); + }; + // Use bootstrap tabdrop for tabs and pills $('.nav-pills, .nav-tabs').tabdrop(); diff --git a/src/octoprint/static/js/app/viewmodels/control.js b/src/octoprint/static/js/app/viewmodels/control.js index d878eef56..544eeeede 100644 --- a/src/octoprint/static/js/app/viewmodels/control.js +++ b/src/octoprint/static/js/app/viewmodels/control.js @@ -37,6 +37,8 @@ $(function() { self.additionalControls = []; self.webcamDisableTimeout = undefined; + self.webcamLoaded = ko.observable(false); + self.webcamError = ko.observable(false); self.keycontrolActive = ko.observable(false); self.keycontrolHelpActive = ko.observable(false); @@ -47,6 +49,14 @@ $(function() { return self.keycontrolActive() && self.keycontrolPossible(); }); + self.webcamRatioClass = ko.pureComputed(function() { + if (self.settings.webcam_streamRatio() == "4:3") { + return "ratio43"; + } else { + return "ratio169"; + } + }); + self.settings.printerProfiles.currentProfileData.subscribe(function () { self._updateExtruderCount(); self.settings.printerProfiles.currentProfileData().extruder.count.subscribe(self._updateExtruderCount); @@ -343,42 +353,24 @@ $(function() { self.requestData(); }; - self.updateRotatorWidth = function() { - var webcamImage = $("#webcam_image"); - if (self.settings.webcam_rotate90()) { - if (webcamImage.width() > 0) { - $("#webcam_rotator").css("height", webcamImage.width()); - } else { - webcamImage.off("load.rotator"); - webcamImage.on("load.rotator", function() { - $("#webcam_rotator").css("height", webcamImage.width()); - webcamImage.off("load.rotator"); - }); - } - } else { - $("#webcam_rotator").css("height", ""); - } - }; - - self.onSettingsBeforeSave = self.updateRotatorWidth; - self._isSafari = function() { var is_chrome = navigator.userAgent.indexOf('Chrome') > -1; var is_safari = navigator.userAgent.indexOf("Safari") > -1; return is_safari && !is_chrome; - } + }; self._disableWebcam = function() { // only disable webcam stream if tab is out of focus for more than 5s, otherwise we might cause // more load by the constant connection creation than by the actual webcam stream - + // safari bug doesn't release the mjpeg stream, so we just disable this for safari. if (self._isSafari()) { return; } - + self.webcamDisableTimeout = setTimeout(function () { $("#webcam_image").attr("src", ""); + self.webcamLoaded(false); }, 5000); }; @@ -392,12 +384,12 @@ $(function() { } var webcamImage = $("#webcam_image"); var currentSrc = webcamImage.attr("src"); - + // safari bug doesn't release the mjpeg stream, so we just set it up the once if (self._isSafari() && currentSrc != undefined) { return; } - + var newSrc = self.settings.webcam_streamUrl(); if (currentSrc != newSrc) { if (newSrc.lastIndexOf("?") > -1) { @@ -407,11 +399,24 @@ $(function() { } newSrc += new Date().getTime(); - self.updateRotatorWidth(); + self.webcamLoaded(false); + self.webcamError(false); webcamImage.attr("src", newSrc); } }; + self.onWebcamLoaded = function() { + log.debug("Webcam stream loaded"); + self.webcamLoaded(true); + self.webcamError(false); + }; + + self.onWebcamErrored = function() { + log.debug("Webcam stream failed to load/disabled"); + self.webcamLoaded(false); + self.webcamError(true); + }; + self.onTabChange = function (current, previous) { if (current == "#control") { self._enableWebcam(); diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index 75bb00926..5da2cd3a5 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -59,6 +59,14 @@ $(function() { self.localTarget = undefined; self.sdTarget = undefined; + self.dropOverlay = undefined; + self.dropZone = undefined; + self.dropZoneLocal = undefined; + self.dropZoneSd = undefined; + self.dropZoneBackground = undefined; + self.dropZoneLocalBackground = undefined; + self.dropZoneSdBackground = undefined; + self.ignoreUpdatedFilesEvent = false; self.addingFolder = ko.observable(false); @@ -395,14 +403,21 @@ $(function() { } }; - self.loadFile = function(file, printAfterLoad) { - if (!file) { + self.loadFile = function(data, printAfterLoad) { + if (!data) { return; } - var withinPrintDimensions = self.evaluatePrintDimensions(file, true); - var print = printAfterLoad && withinPrintDimensions; - OctoPrint.files.select(file.origin, file.path, print); + if (printAfterLoad && self.listHelper.isSelected(data) && self.enablePrint(data)) { + // file was already selected, just start the print job + OctoPrint.job.start(); + } else { + // select file, start print job (if requested and within dimensions) + var withinPrintDimensions = self.evaluatePrintDimensions(data, true); + var print = printAfterLoad && withinPrintDimensions; + + OctoPrint.files.select(data.origin, data.path, print); + } }; self.removeFile = function(file, event) { @@ -545,8 +560,11 @@ $(function() { }; self.enableSelect = function(data, printAfterSelect) { - var isLoadActionPossible = self.loginState.isUser() && self.isOperational() && !(self.isPrinting() || self.isPaused() || self.isLoading()); - return isLoadActionPossible && !self.listHelper.isSelected(data); + return self.enablePrint(data) && !self.listHelper.isSelected(data); + }; + + self.enablePrint = function(data) { + return self.loginState.isUser() && self.isOperational() && !(self.isPrinting() || self.isPaused() || self.isLoading()); }; self.enableSlicing = function(data) { @@ -811,6 +829,16 @@ $(function() { } self.sdTarget = $("#drop_sd"); + self.dropOverlay = $("#drop_overlay"); + self.dropZone = $("#drop"); + self.dropZoneLocal = $("#drop_locally"); + self.dropZoneSd = $("#drop_sd"); + self.dropZoneBackground = $("#drop_background"); + self.dropZoneLocalBackground = $("#drop_locally_background"); + self.dropZoneSdBackground = $("#drop_sd_background"); + + self.dropOverlay.on('drop', self._forceEndDragNDrop); + function evaluateDropzones() { var enableLocal = self.loginState.isUser(); var enableSd = enableLocal && CONFIG_SD_SUPPORT && self.printerState.isSdReady(); @@ -962,10 +990,12 @@ $(function() { self._enableDragNDrop = function(enable) { if (enable) { - $(document).bind("dragover", self._handleDragNDrop); + $(document).bind("dragenter", self._handleDragNDrop); + $(document).bind("dragleave", self._endDragNDrop); log.debug("Enabled drag-n-drop"); } else { - $(document).unbind("dragover", self._handleDragNDrop); + $(document).unbind("dragenter", self._handleDragNDrop); + $(document).unbind("dragleave", self._endDragNDrop); log.debug("Disabled drag-n-drop"); } }; @@ -1038,34 +1068,35 @@ $(function() { self._setProgressBar(progress, uploaded ? gettext("Saving ...") : gettext("Uploading ..."), uploaded); }; - self._handleDragNDrop = function (e) { - var dropOverlay = $("#drop_overlay"); - var dropZone = $("#drop"); - var dropZoneLocal = $("#drop_locally"); - var dropZoneSd = $("#drop_sd"); - var dropZoneBackground = $("#drop_background"); - var dropZoneLocalBackground = $("#drop_locally_background"); - var dropZoneSdBackground = $("#drop_sd_background"); - var timeout = window.dropZoneTimeout; + self._dragNDropTarget = null; + self._forceEndDragNDrop = function () { + self.dropOverlay.removeClass("in"); + if (self.dropZoneLocal) self.dropZoneLocalBackground.removeClass("hover"); + if (self.dropZoneSd) self.dropZoneSdBackground.removeClass("hover"); + if (self.dropZone) self.dropZoneBackground.removeClass("hover"); + self._dragNDropTarget = null; + }; - if (!timeout) { - dropOverlay.addClass('in'); - } else { - clearTimeout(timeout); - } + self._endDragNDrop = function (e) { + if (e.target != self._dragNDropTarget) return; + self._forceEndDragNDrop(); + }; + + self._handleDragNDrop = function (e) { + self.dropOverlay.addClass('in'); var foundLocal = false; var foundSd = false; var found = false; var node = e.target; do { - if (dropZoneLocal && node === dropZoneLocal[0]) { + if (self.dropZoneLocal && node === self.dropZoneLocal[0]) { foundLocal = true; break; - } else if (dropZoneSd && node === dropZoneSd[0]) { + } else if (self.dropZoneSd && node === self.dropZoneSd[0]) { foundSd = true; break; - } else if (dropZone && node === dropZone[0]) { + } else if (self.dropZone && node === self.dropZone[0]) { found = true; break; } @@ -1073,26 +1104,19 @@ $(function() { } while (node != null); if (foundLocal) { - dropZoneLocalBackground.addClass("hover"); - dropZoneSdBackground.removeClass("hover"); + self.dropZoneLocalBackground.addClass("hover"); + self.dropZoneSdBackground.removeClass("hover"); } else if (foundSd && self.printerState.isSdReady()) { - dropZoneSdBackground.addClass("hover"); - dropZoneLocalBackground.removeClass("hover"); + self.dropZoneSdBackground.addClass("hover"); + self.dropZoneLocalBackground.removeClass("hover"); } else if (found) { - dropZoneBackground.addClass("hover"); + self.dropZoneBackground.addClass("hover"); } else { - if (dropZoneLocalBackground) dropZoneLocalBackground.removeClass("hover"); - if (dropZoneSdBackground) dropZoneSdBackground.removeClass("hover"); - if (dropZoneBackground) dropZoneBackground.removeClass("hover"); + if (self.dropZoneLocalBackground) self.dropZoneLocalBackground.removeClass("hover"); + if (self.dropZoneSdBackground) self.dropZoneSdBackground.removeClass("hover"); + if (self.dropZoneBackground) self.dropZoneBackground.removeClass("hover"); } - - window.dropZoneTimeout = setTimeout(function () { - window.dropZoneTimeout = null; - dropOverlay.removeClass("in"); - if (dropZoneLocal) dropZoneLocalBackground.removeClass("hover"); - if (dropZoneSd) dropZoneSdBackground.removeClass("hover"); - if (dropZone) dropZoneBackground.removeClass("hover"); - }, 100); + self._dragNDropTarget = e.target; } } diff --git a/src/octoprint/static/js/app/viewmodels/gcode.js b/src/octoprint/static/js/app/viewmodels/gcode.js index ea8b4c6ea..f1611873a 100644 --- a/src/octoprint/static/js/app/viewmodels/gcode.js +++ b/src/octoprint/static/js/app/viewmodels/gcode.js @@ -138,6 +138,14 @@ $(function() { } }); + self.settings.feature_g90InfluencesExtruder.subscribe(function() { + GCODE.ui.updateOptions({ + reader: { + g90InfluencesExtruder: self.settings.feature_g90InfluencesExtruder() + } + }); + }); + self._retrieveBedDimensions = function(currentProfileData) { if (currentProfileData == undefined) { currentProfileData = self.settings.printerProfiles.currentProfileData(); diff --git a/src/octoprint/static/js/app/viewmodels/printerprofiles.js b/src/octoprint/static/js/app/viewmodels/printerprofiles.js index 717d10038..f19484a64 100644 --- a/src/octoprint/static/js/app/viewmodels/printerprofiles.js +++ b/src/octoprint/static/js/app/viewmodels/printerprofiles.js @@ -453,7 +453,7 @@ $(function() { }; self.requestData = function() { - OctoPrint.printerprofiles.list() + return OctoPrint.printerprofiles.list() .done(self.fromResponse); }; @@ -504,7 +504,10 @@ $(function() { self.requestInProgress(true); OctoPrint.printerprofiles.delete(data.id, {url: data.resource}) .done(function() { - self.requestData(); + self.requestData() + .always(function() { + self.requestInProgress(false); + }); }) .fail(function(xhr) { var text; @@ -514,8 +517,6 @@ $(function() { text = gettext("There was unexpected error while removing the printer profile, please consult the logs."); } new PNotify({title: gettext("Could not delete profile"), text: text, type: "error", hide: false}); - }) - .always(function() { self.requestInProgress(false); }); }; @@ -535,13 +536,14 @@ $(function() { if (callback !== undefined) { callback(); } - self.requestData(); + self.requestData() + .always(function() { + self.requestInProgress(false); + }); }) .fail(function() { var text = gettext("There was unexpected error while updating the printer profile, please consult the logs."); new PNotify({title: gettext("Could not update profile"), text: text, type: "error", hide: false}); - }) - .always(function() { self.requestInProgress(false); }); }; diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 785abf971..4b805eadb 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -91,6 +91,8 @@ $(function() { } }; + self.webcam_available_ratios = ["16:9", "4:3"]; + var auto_locale = {language: "_default", display: gettext("Autodetect from browser"), english: undefined}; self.locales = ko.observableArray([auto_locale].concat(_.sortBy(_.values(AVAILABLE_LOCALES), function(n) { return n.display; @@ -110,6 +112,7 @@ $(function() { self.printer_defaultExtrusionLength = ko.observable(undefined); self.webcam_streamUrl = ko.observable(undefined); + self.webcam_streamRatio = ko.observable(undefined); self.webcam_snapshotUrl = ko.observable(undefined); self.webcam_ffmpegPath = ko.observable(undefined); self.webcam_bitrate = ko.observable(undefined); @@ -140,6 +143,7 @@ $(function() { self.feature_firmwareDetection = ko.observable(undefined); self.feature_printCancelConfirmation = ko.observable(undefined); self.feature_blockWhileDwelling = ko.observable(undefined); + self.feature_g90InfluencesExtruder = ko.observable(undefined); self.serial_port = ko.observable(); self.serial_baudrate = ko.observable(); @@ -224,37 +228,48 @@ $(function() { self.terminalFilters.remove(filter); }; + self.testWebcamStreamUrlBusy = ko.observable(false); self.testWebcamStreamUrl = function() { if (!self.webcam_streamUrl()) { return; } + if (self.testWebcamStreamUrlBusy()) { + return; + } + var text = gettext("If you see your webcam stream below, the entered stream URL is ok."); var image = $(''); var message = $("

") .append(text) .append(image); + + self.testWebcamStreamUrlBusy(true); showMessageDialog({ title: gettext("Stream test"), - message: message + message: message, + onclose: function() { + self.testWebcamStreamUrlBusy(false); + } }); }; + self.testWebcamSnapshotUrlBusy = ko.observable(false); self.testWebcamSnapshotUrl = function(viewModel, event) { if (!self.webcam_snapshotUrl()) { return; } - var target = $(event.target); - target.prepend(' '); + if (self.testWebcamSnapshotUrlBusy()) { + return; + } var errorText = gettext("Could not retrieve snapshot URL, please double check the URL"); var errorTitle = gettext("Snapshot test failed"); + self.testWebcamSnapshotUrlBusy(true); OctoPrint.util.testUrl(self.webcam_snapshotUrl(), {method: "GET", response: "bytes"}) .done(function(response) { - $("i.icon-spinner", target).remove(); - if (!response.result) { showMessageDialog({ title: errorTitle, @@ -274,23 +289,34 @@ $(function() { var text = gettext("If you see your webcam snapshot picture below, the entered snapshot URL is ok."); showMessageDialog({ title: gettext("Snapshot test"), - message: $('

' + text + '

') + message: $('

' + text + '

'), + onclose: function() { + self.testWebcamSnapshotUrlBusy(false); + } }); }) .fail(function() { - $("i.icon-spinner", target).remove(); showMessageDialog({ title: errorTitle, - message: errorText + message: errorText, + onclose: function() { + self.testWebcamSnapshotUrlBusy(false); + } }); }); }; + self.testWebcamFfmpegPathBusy = ko.observable(false); self.testWebcamFfmpegPath = function() { if (!self.webcam_ffmpegPath()) { return; } + if (self.testWebcamFfmpegPathBusy()) { + return; + } + + self.testWebcamFfmpegPathBusy(true); OctoPrint.util.testExecutable(self.webcam_ffmpegPath()) .done(function(response) { if (!response.result) { @@ -306,6 +332,9 @@ $(function() { } self.webcam_ffmpegPathOk(response.result); self.webcam_ffmpegPathBroken(!response.result); + }) + .always(function() { + self.testWebcamFfmpegPathBusy(false); }); }; diff --git a/src/octoprint/static/js/app/viewmodels/terminal.js b/src/octoprint/static/js/app/viewmodels/terminal.js index baa58678b..4fdd47e7a 100644 --- a/src/octoprint/static/js/app/viewmodels/terminal.js +++ b/src/octoprint/static/js/app/viewmodels/terminal.js @@ -35,8 +35,10 @@ $(function() { self.enableFancyFunctionality = ko.observable(true); self.disableTerminalLogDuringPrinting = ko.observable(false); - self.acceptableTime = 500; + + self.acceptableFancyTime = 500; self.acceptableUnfancyTime = 300; + self.reenableTimeout = 5000; self.forceFancyFunctionality = ko.observable(false); self.forceTerminalLogDuringPrinting = ko.observable(false); @@ -122,23 +124,63 @@ $(function() { self.updateFilterRegex(); }); + self._reenableFancyTimer = undefined; + self._reenableUnfancyTimer = undefined; + self._disableFancy = function(difference) { + log.warn("Terminal: Detected slow client (needed " + difference + "ms for processing new log data), disabling fancy terminal functionality"); + if (self._reenableFancyTimer) { + window.clearTimeout(self._reenableFancyTimer); + self._reenableFancyTimer = undefined; + } + self.enableFancyFunctionality(false); + }; + self._reenableFancy = function(difference) { + if (self._reenableFancyTimer) return; + self._reenableFancyTimer = window.setTimeout(function() { + log.info("Terminal: Client speed recovered, enabling fancy terminal functionality"); + self.enableFancyFunctionality(true); + }, self.reenableTimeout); + }; + self._disableUnfancy = function(difference) { + log.warn("Terminal: Detected very slow client (needed " + difference + "ms for processing new log data), completely disabling terminal output during printing"); + if (self._reenableUnfancyTimer) { + window.clearTimeout(self._reenableUnfancyTimer); + self._reenableUnfancyTimer = undefined; + } + self.disableTerminalLogDuringPrinting(true); + }; + self._reenableUnfancy = function() { + if (self._reenableUnfancyTimer) return; + self._reenableUnfancyTimer = window.setTimeout(function() { + log.info("Terminal: Client speed recovered, enabling terminal output during printing"); + self.disableTerminalLogDuringPrinting(false); + }, self.reenableTimeout); + }; + self.fromCurrentData = function(data) { self._processStateData(data.state); var start = new Date().getTime(); self._processCurrentLogData(data.logs); var end = new Date().getTime(); - var difference = end - start; + if (self.enableFancyFunctionality()) { - if (difference > self.acceptableTime) { - self.enableFancyFunctionality(false); - log.warn("Terminal: Detected slow client (needed " + difference + "ms for processing new log data), disabling fancy terminal functionality"); + // fancy enabled -> check if we need to disable fancy + if (difference >= self.acceptableFancyTime) { + self._disableFancy(difference); + } + } else if (!self.disableTerminalLogDuringPrinting()) { + // fancy disabled, unfancy not -> check if we need to disable unfancy or re-enable fancy + if (difference >= self.acceptableUnfancyTime) { + self._disableUnfancy(difference); + } else if (difference < self.acceptableFancyTime / 2.0) { + self._reenableFancy(difference); } } else { - if (!self.disableTerminalLogDuringPrinting() && difference > self.acceptableUnfancyTime) { - self.disableTerminalLogDuringPrinting(true); - log.warn("Terminal: Detected very slow client (needed " + difference + "ms for processing new log data), completely disabling terminal output during printing"); + // fancy & unfancy disabled -> check if we need to re-enable unfancy + if (difference < self.acceptableUnfancyTime / 2.0) { + self._reenableUnfancy(difference); } } }; diff --git a/src/octoprint/static/less/octoprint.less b/src/octoprint/static/less/octoprint.less index b0c3855d8..369d64f45 100644 --- a/src/octoprint/static/less/octoprint.less +++ b/src/octoprint/static/less/octoprint.less @@ -491,7 +491,7 @@ ul.dropdown-menu li a { position: relative; outline: none; - //min-height: 440px; + background-color: black; .keycontrol_overlay { position: absolute; @@ -526,6 +526,84 @@ ul.dropdown-menu li a { float: left; } } + + .nowebcam { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + + .text { + color: white; + text-align: center; + position: relative; + margin: auto; + width: 80%; + top: 50%; + transform: translateY(-50%); + display: block; + + &.webcam_loading { + animation: pulsate 3s ease-out; + animation-iteration-count: infinite; + } + } + } + + .webcam_rotated { + position: relative; + width: 100%; + padding-bottom: 100%; + + .webcam_fixed_ratio { + position: absolute; + transform: rotate(-90deg); + top: 0; + bottom: 0; + + .webcam_fixed_ratio_inner { + width: 100%; + height: 100%; + } + } + } + + .webcam_unrotated { + .webcam_fixed_ratio { + width: 100%; + padding-bottom: 100%; + + &.ratio43 { + padding-bottom: 75%; + } + + &.ratio169 { + padding-bottom: 56.25%; + } + + &.ratio1610 { + padding-bottom: 62.5%; + } + + position: relative; + + .webcam_fixed_ratio_inner { + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; + } + } + } + + + img { + width: 100%; + height: 100%; + object-fit: contain; + } } /** State sidebar panel */ @@ -757,6 +835,10 @@ ul.dropdown-menu li a { #terminal-sendpanel { text-align: right; } + + #terminal-output span { + display: block; + } } #settings_dialog { @@ -867,6 +949,18 @@ textarea.block { width: 100%; } +@keyframes pulsate { + 0% { + opacity: 0.5; + } + 50% { + opacity: 1.0; + } + 100% { + opacity: 0.5; + } +} + #drop_overlay { position: fixed; top: 0; diff --git a/src/octoprint/templates/dialogs/settings/features.jinja2 b/src/octoprint/templates/dialogs/settings/features.jinja2 index c90bebabb..ab1264890 100644 --- a/src/octoprint/templates/dialogs/settings/features.jinja2 +++ b/src/octoprint/templates/dialogs/settings/features.jinja2 @@ -41,12 +41,19 @@ +
+
+ +
+
diff --git a/src/octoprint/templates/dialogs/settings/webcam.jinja2 b/src/octoprint/templates/dialogs/settings/webcam.jinja2 index 97d5924bf..5b86f7bc9 100644 --- a/src/octoprint/templates/dialogs/settings/webcam.jinja2 +++ b/src/octoprint/templates/dialogs/settings/webcam.jinja2 @@ -2,6 +2,7 @@
{% include "snippets/settings/webcam/webcamStreamUrl.jinja2" %} + {% include "snippets/settings/webcam/webcamStreamRatio.jinja2" %} {% include "snippets/settings/webcam/webcamOrientation.jinja2" %}
diff --git a/src/octoprint/templates/sidebar/files.jinja2 b/src/octoprint/templates/sidebar/files.jinja2 index 3fde22c9e..99b199df8 100644 --- a/src/octoprint/templates/sidebar/files.jinja2 +++ b/src/octoprint/templates/sidebar/files.jinja2 @@ -21,7 +21,7 @@
-
+
diff --git a/src/octoprint/templates/snippets/settings/printerprofiles/profiles.jinja2 b/src/octoprint/templates/snippets/settings/printerprofiles/profiles.jinja2 index 8ad8f4617..7c8520a62 100644 --- a/src/octoprint/templates/snippets/settings/printerprofiles/profiles.jinja2 +++ b/src/octoprint/templates/snippets/settings/printerprofiles/profiles.jinja2 @@ -11,7 +11,7 @@ -  |  |  +  |  |  diff --git a/src/octoprint/templates/snippets/settings/webcam/ffmpegPath.jinja2 b/src/octoprint/templates/snippets/settings/webcam/ffmpegPath.jinja2 index 14375942a..478e61661 100644 --- a/src/octoprint/templates/snippets/settings/webcam/ffmpegPath.jinja2 +++ b/src/octoprint/templates/snippets/settings/webcam/ffmpegPath.jinja2 @@ -3,7 +3,7 @@
- +
diff --git a/src/octoprint/templates/snippets/settings/webcam/webcamSnapshotUrl.jinja2 b/src/octoprint/templates/snippets/settings/webcam/webcamSnapshotUrl.jinja2 index da33fc48f..cf1495406 100644 --- a/src/octoprint/templates/snippets/settings/webcam/webcamSnapshotUrl.jinja2 +++ b/src/octoprint/templates/snippets/settings/webcam/webcamSnapshotUrl.jinja2 @@ -3,7 +3,7 @@
- +
{% trans %}Fully qualified URL, needs to be reachable by OctoPrint's server{% endtrans %}
diff --git a/src/octoprint/templates/snippets/settings/webcam/webcamStreamRatio.jinja2 b/src/octoprint/templates/snippets/settings/webcam/webcamStreamRatio.jinja2 new file mode 100644 index 000000000..ee5cdd1dc --- /dev/null +++ b/src/octoprint/templates/snippets/settings/webcam/webcamStreamRatio.jinja2 @@ -0,0 +1,7 @@ +
+ +
+ + {% trans %}If the stream has a different aspect ratio than configured here it will be letterboxed.{% endtrans %} +
+
diff --git a/src/octoprint/templates/snippets/settings/webcam/webcamStreamUrl.jinja2 b/src/octoprint/templates/snippets/settings/webcam/webcamStreamUrl.jinja2 index a26337fa5..42aaa5296 100644 --- a/src/octoprint/templates/snippets/settings/webcam/webcamStreamUrl.jinja2 +++ b/src/octoprint/templates/snippets/settings/webcam/webcamStreamUrl.jinja2 @@ -3,7 +3,7 @@
- +
{% trans %}Needs to be reachable from the browser displaying the OctoPrint UI, used to embed the webcam stream into the page.{% endtrans %}
diff --git a/src/octoprint/templates/tabs/control.jinja2 b/src/octoprint/templates/tabs/control.jinja2 index 93d6e5246..b3b69e477 100644 --- a/src/octoprint/templates/tabs/control.jinja2 +++ b/src/octoprint/templates/tabs/control.jinja2 @@ -1,7 +1,20 @@ {% if webcamStream %}
-
- +
+
+

{{ _('Webcam stream loading...') }}

+
+
+

{{ _('Webcam stream not loaded') }}

+

{{ _('It might not be correctly configured. You can change the URL of the stream under "Settings" > "Webcam & Timelapse" > "Stream URL". If you don\'t have a webcam just set the URL to an empty value.') }}

+
+
+
+
+
+ +
+
{{ _("Keyboard controls active") }}
diff --git a/src/octoprint/templates/tabs/terminal.jinja2 b/src/octoprint/templates/tabs/terminal.jinja2 index e826de000..c258c978e 100644 --- a/src/octoprint/templates/tabs/terminal.jinja2 +++ b/src/octoprint/templates/tabs/terminal.jinja2 @@ -1,5 +1,5 @@
-

+
{{ _("Scroll to end") }} | {{ _("Select all") }} @@ -16,7 +16,7 @@