Merge branch 'devel' of github.com:foosel/OctoPrint into dev/permission

This commit is contained in:
Marc Hannappel committed 2017-10-25 09:11:13 +02:00
commit d88b1fbec0
42 files changed
+1134 -498

No files matched your search

+4 -4
View File
@@ -16,16 +16,16 @@ prerelease
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.3.5
# maintenance is currently the branch for preparation of maintenance release 1.3.6
# so are any fix/... and improve/... branches
maintenance 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
fix/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
improve/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.5rc5
# staging/maintenance is currently the branch for preparation of 1.3.6rc1
# so is regressionfix/...
staging/maintenance 1.3.5rc5 e88e6ba29203757b07a3237a51f1346ab1e5aaae pep440-dev
regressionfix/.* 1.3.5rc5 e88e6ba29203757b07a3237a51f1346ab1e5aaae pep440-dev
staging/maintenance 1.3.6rc1 77753ca02602d3a798d6b0a22535e6fd69ff448a pep440-dev
regressionfix/.* 1.3.6rc1 77753ca02602d3a798d6b0a22535e6fd69ff448a pep440-dev
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
+26 -39
View File
@@ -1,41 +1,6 @@
# OctoPrint Changelog
## 1.3.5rc4 (2017-10-04)
### Bug fixes
* [#2135](https://github.com/foosel/OctoPrint/issues/2135) - Fix an issue causing import errors inside the GCODE analysis tool in certain environments due to `sys.path` entries causing relative imports.
* [#2136](https://github.com/foosel/OctoPrint/issues/2136) - Fix wrong minimum version for `sockjs-tornado` dependency.
* [#2137](https://github.com/foosel/OctoPrint/issues/2137) - Fix issue with session cookies getting lost when running an OctoPrint instance on a subpath of another (e.g. `octopi.local/` and `octopi.local/octoprint2`).
* [#2140](https://github.com/foosel/OctoPrint/issues/2140) - Fix issue with locale dependent sorting of sub wizards during first time setup causing issues leading to the wizard not being able to complete.
([Commits](https://github.com/foosel/OctoPrint/compare/1.3.5rc3...1.3.5rc4))
## 1.3.5rc3 (2017-08-25)
### Bug fixes
* [#2059](https://github.com/foosel/OctoPrint/issues/2059) - Fix an issue causing the new temperature controls to wrap on touch enabled devices when the temperature dropdown is opened.
* [#2090](https://github.com/foosel/OctoPrint/issues/2090) - Fix an issue causing an aborted server startup under Windows if the timing is just right.
* Fix an issue causing rollover of `serial.log` to fail under Windows.
([Commits](https://github.com/foosel/OctoPrint/compare/1.3.5rc2...1.3.5rc3))
## 1.3.5rc2 (2017-07-27)
### Bug fixes
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) - Temperature tab: Fix for legend in graph not updating with current values on mouse over.
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) - Temperature tab: Fix for new temperature inputs not fitting on one line in Firefox.
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) - Temperature tab & GCODE viewer: Fix for available tools (and offsets) not properly updating on change of printer profile.
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) - Wizard: Fix sorting of required wizards not properly handling non-ASCII unicode.
* [#2035](https://github.com/foosel/OctoPrint/issues/2035) - Fix an issue of the server not starting up if there's a file in the analysis backlog. The reason for this is that spawning a new process while the intermediary server is active causes the server port to be blocked (this is due to how subprocessing works by default), in turn leading to an error on startup since the port cannot be bound by the actual server. Since the GCODE analysis takes now place in its own subprocess and hence triggers this problem, it had to be moved until after the actual server has already started up to avoid this problem.
* Wizard: Fix `onWizardPreventSettingsRefreshDialog` callback invocation.
* Corewizard plugin: Fix `firstrunonly` wizards (e.g. for printer profile configuration) being displayed again if _any_ of the sub wizards (e.g. for the online check opt-in and configuration) is active.
([Commits](https://github.com/foosel/OctoPrint/compare/1.3.5rc1...1.3.5rc2))
## 1.3.5rc1 (2017-07-26)
## 1.3.5 (2017-10-16)
### Improvements
@@ -43,7 +8,7 @@
* [#1572](https://github.com/foosel/OctoPrint/issues/1572) & [#1881](https://github.com/foosel/OctoPrint/issues/1881) - Refactored web interface startup process to minimise risk of race conditions and speed improvements. Also added sequence diagram to the documentation showing the new processing order.
* [#1640](https://github.com/foosel/OctoPrint/issues/1640) - Mouse over temperature graph to get exact data for that time.
* [#1679](https://github.com/foosel/OctoPrint/issues/1679) - Support temperature autoreporting by the firmware instead of polling if the firmware reports to support it. For this to work with Marlin 1.1.0 to 1.1.3 you'll need to explicitly enable `EXTENDED_CAPABILITIES_REPORT` *and* `AUTO_REPORT_TEMPERATURES` in your firmware configuration, otherwise your firmware won't report that it actually supports this feature.
* [#1737](https://github.com/foosel/OctoPrint/issues/1737) - Auto-detect Anet A8 firmware and treat as Repetier Firmware (which it actually appears to be, just renamed - thanks Anet for making this even harder).
* [#1737](https://github.com/foosel/OctoPrint/issues/1737) - Auto-detect Anet A8 firmware and treat as Repetier Firmware (which it actually appears to be, just renamed - thanks Anet for making this even harder).
* [#1842](https://github.com/foosel/OctoPrint/issues/1842) - Update bundled FontAwesome to 4.7 (see also [#1915](https://github.com/foosel/OctoPrint/pull/1915)).
* [#1910](https://github.com/foosel/OctoPrint/issues/1910) - Make last/pause/cancel temperature available for GCODE scripts.
* [#1925](https://github.com/foosel/OctoPrint/issues/1925) - Include configured webcam stream URL in "Webcam stream not loaded" message for logged in users/admins. Slightly different wording for guests vs users vs admins.
@@ -91,11 +56,22 @@
* [#2007](https://github.com/foosel/OctoPrint/issues/2007) - Fix issue parsing temperature lines from the printer that contain negative values.
* [#2012](https://github.com/foosel/OctoPrint/issues/2012) - Fix command line interface of Software Update plugin.
* [#2017](https://github.com/foosel/OctoPrint/issues/2017) - Fix issue in GCODE viewer with files that contain a visit to the first layer twice (e.g. brim, then nose dive from higher z for actual model), causing all but the last layer segment to not be rendered.
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab: Fix for legend in graph not updating with current values on mouse over.
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab: Fix for new temperature inputs not fitting on one line in Firefox.
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Temperature tab & GCODE viewer: Fix for available tools (and offsets) not properly updating on change of printer profile.
* [#2033](https://github.com/foosel/OctoPrint/issues/2033) (regression) - Wizard: Fix sorting of required wizards not properly handling non-ASCII unicode.
* [#2035](https://github.com/foosel/OctoPrint/issues/2035) (regression) - Fix an issue of the server not starting up if there's a file in the analysis backlog. The reason for this is that spawning a new process while the intermediary server is active causes the server port to be blocked (this is due to how subprocessing works by default), in turn leading to an error on startup since the port cannot be bound by the actual server. Since the GCODE analysis takes now place in its own subprocess and hence triggers this problem, it had to be moved until after the actual server has already started up to avoid this problem.
* [#2059](https://github.com/foosel/OctoPrint/issues/2059) (regression) - Fix an issue causing the new temperature controls to wrap on touch enabled devices when the temperature dropdown is opened.
* [#2090](https://github.com/foosel/OctoPrint/issues/2090) (regression) - Fix an issue causing an aborted server startup under Windows if the timing is just right.
* [#2135](https://github.com/foosel/OctoPrint/issues/2135) (regression) - Fix an issue causing import errors inside the GCODE analysis tool in certain environments due to `sys.path` entries causing relative imports.
* [#2136](https://github.com/foosel/OctoPrint/issues/2136) (regression) - Fix wrong minimum version for `sockjs-tornado` dependency.
* [#2137](https://github.com/foosel/OctoPrint/issues/2137) (regression) - Fix issue with session cookies getting lost when running an OctoPrint instance on a subpath of another (e.g. `octopi.local/` and `octopi.local/octoprint2`).
* [#2140](https://github.com/foosel/OctoPrint/issues/2140) (regression) - Fix issue with locale dependent sorting of sub wizards during first time setup causing issues leading to the wizard not being able to complete.
* Fix various popup buttons allowing multiple clicks (suggested in [#1914](https://github.com/foosel/OctoPrint/issues/1914))
* Software Update Plugin: Perform server restart asynchronously. Should reduce restart times on updates significantly.
* Don't hex-escape `\t`, `\r` or `\n` in terminal output
* Use client side default printer profile if the default profile could not be found on the server
* Use both "to" and "from" coordinates of a given move for min/max model coordinate calculation in GCODE analysis. Otherwise wrong values could be calculated under certain circumstances.
* Use both "to" and "from" coordinates of a given move for min/max model coordinate calculation in GCODE analysis. Otherwise wrong values could be calculated under certain circumstances.
* Fix potential race condition in resend request handling.
* Fix potential race condition in web socket handling.
* Fix handling of tool offsets in GCODE analysis - diverted too far from firmware implementations, causing wrong calculations.
@@ -103,8 +79,19 @@
* Fix potential division by zero in progress reporting if the timing was just right.
* Fix sorting order for multiple tools in the "State" panel.
* Fix file position vs. line ending handling in GCODE viewer. Could lead to slightly off file position calculation and hence possibly to the wrong move being plotted when synchronizing with print progress.
* Wizard: Fix `onWizardPreventSettingsRefreshDialog` callback invocation. (regression)
* Corewizard plugin: Fix `firstrunonly` wizards (e.g. for printer profile configuration) being displayed again if _any_ of the sub wizards (e.g. for the online check opt-in and configuration) is active. (regression)
* Fix an issue causing rollover of `serial.log` to fail under Windows. (regression)
([Commits](https://github.com/foosel/OctoPrint/compare/1.3.4...1.3.5rc1))
### More Information
* [Commits](https://github.com/foosel/OctoPrint/compare/1.3.4...1.3.5)
* Release Candidates:
* [1.3.5rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc1)
* [1.3.5rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc2)
* [1.3.5rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc3)
* [1.3.5rc4](https://github.com/foosel/OctoPrint/releases/tag/1.3.5rc4)
* A special **Thank you!** to everyone who reported back on these release candidates this time: [alexxy](https://github.com/alexxy), [andrivet](https://github.com/andrivet), [b-morgan](https://github.com/b-morgan), [BillyBlaze](https://github.com/BillyBlaze), [CapnBry](https://github.com/CapnBry), [chippypilot](https://github.com/chippypilot), [ctgreybeard](https://github.com/ctgreybeard), [cxt666](https://github.com/cxt666), [DaSTIG](https://github.com/DaSTIG), [fhbmax](https://github.com/fhbmax), [fiveangle](https://github.com/fiveangle), [goeland86](https://github.com/goeland86), [JohnOCFII](https://github.com/JohnOCFII), [Kunsi](https://github.com/Kunsi), [mgrl](https://github.com/mgrl), [MoonshineSG](https://github.com/MoonshineSG), [nate-ubiquisoft](https://github.com/nate-ubiquisoft), [Neoolog](https://github.com/Neoolog), [ntoff](https://github.com/ntoff), [oferfrid](https://github.com/oferfrid), [roygilby](https://github.com/roygilby), [SAinc](https://github.com/SAinc), [sbts](https://github.com/sbts), [thess](https://github.com/thess), [tkurbad](https://github.com/tkurbad), [tsillini](https://github.com/tsillini) and [TylonHH](https://github.com/TylonHH).
## 1.3.4 (2017-06-01)
+1 -1
View File
@@ -64,4 +64,4 @@ thanks to everyone who contributed!
* Timeshell.ca
* Trent Shumay
and 1121 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 1133 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
+15 -3
View File
@@ -232,12 +232,18 @@ File information
* - ``name``
- 1
- String
- The name of the file without path. E.g. "file.gco" for a file "file.gco" located anywhere in the file system.
- The name of the file without path. E.g. "file.gco" for a file "file.gco" located anywhere in the file system. Currently
this will always fit into ASCII.
* - ``display``
- 1
- String
- The name of the file without the path, this time potentially with non-ASCII unicode characters.
E.g. "a turtle 🐢.gco" for a file "a_turtle_turtle.gco" located anywhere in the file system.
* - ``path``
- 1
- String
- The path to the file within the location. E.g. "folder/subfolder/file.gco" for a file "file.gco" located within
"folder" and "subfolder" relative to the root of the location.
"folder" and "subfolder" relative to the root of the location. Currently this will always fit into ASCII.
* - ``type``
- 1
- String
@@ -329,11 +335,17 @@ Abridged file or folder information
- 1
- String
- The name of the file or folder without path. E.g. "file.gco" for a file "file.gco" located anywhere in the file system.
Currently this will always fit into ASCII.
* - ``display``
- 1
- String
- The name of the file without the path, this potentially with non-ASCII unicode characters.
E.g. "a turtle 🐢.gco" for a file "a_turtle_turtle.gco" located anywhere in the file system.
* - ``path``
- 1
- String
- The path to the file or folder within the location. E.g. "folder/subfolder/file.gco" for a file "file.gco" located within
"folder" and "subfolder" relative to the root of the location.
"folder" and "subfolder" relative to the root of the location. Currently this will always fit into ASCII.
* - ``origin``
- 1
- String, either ``local`` or ``sdcard``
+6 -6
View File
@@ -39,7 +39,7 @@ List all registered system commands
"action": "shutdown",
"name": "Shutdown",
"command": "sudo shutdown -h now",
"confirm": "You are about to shutdown the system.",
"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).",
"async": true,
"ignore": true,
"source": "core",
@@ -49,7 +49,7 @@ List all registered system commands
"action": "reboot",
"name": "Reboot",
"command": "sudo reboot",
"confirm": "You are about to reboot the system.",
"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).",
"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": "You are about to restart the OctoPrint server.",
"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).",
"async": true,
"ignore": true,
"source": "core",
@@ -100,7 +100,7 @@ List all registered system commands for a source
"action": "shutdown",
"name": "Shutdown",
"command": "sudo shutdown -h now",
"confirm": "You are about to shutdown the system.",
"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).",
"async": true,
"ignore": true,
"source": "core",
@@ -110,7 +110,7 @@ List all registered system commands for a source
"action": "reboot",
"name": "Reboot",
"command": "sudo reboot",
"confirm": "You are about to reboot the system.",
"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).",
"async": true,
"ignore": true,
"source": "core",
@@ -120,7 +120,7 @@ List all registered system commands for a source
"action": "restart",
"name": "Restart OctoPrint",
"command": "sudo service octoprint restart",
"confirm": "You are about to restart the OctoPrint server.",
"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).",
"async": true,
"ignore": true,
"source": "core",
+177
View File
@@ -0,0 +1,177 @@
.. _sec-development-environment:
Setting up a Development environment
====================================
.. _sec-development-environment-source:
Obtaining, building and running the source
------------------------------------------
This describes the general steps in obtaining, building and running. OS specific instructions can be found
below.
* Prerequisites:
* `Python 2.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Git <https://git-scm.com>`_
* Checkout the OctoPrint sources from their Git repository: ``git clone https://github.com/foosel/OctoPrint.git``
* Create a virtual environment in the checkout folder to use for installing and running OctoPrint and its
dependencies (this avoids potential versioning issues for the dependencies with system wide installed
instances): ``virtualenv venv``
* Activate the virtual environment: ``source venv/bin/activate`` (might differ per your platform/OS)
* Update ``pip`` in the virtual environment: ``pip install --upgrade pip``
* Install OctoPrint in `"editable" mode <https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs>`_,
including its regular *and* development dependencies: ``pip install -e .[develop]``
.. _sec-development-environment-source-linux:
Linux
.....
This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
location, please substitute accordingly.
First make sure you have python including its header files, pip, setuptools, virtualenv, git and some build requirements
installed:
* On apt based distributions (e.g. Debian, Ubuntu, ...):
.. code-block:: none
sudo apt-get install python python-pip python-dev python-setuptools python-virtualenv git libyaml-dev build-essential
.. todo::
Using a Linux distribution that doesn't use ``apt``? Please send a
`Pull Request <https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
steps into this guide!
Then:
.. code-block:: none
cd ~/devel
git clone https://github.com/foosel/OctoPrint.git
cd OctoPrint
virtualenv venv
source ./venv/bin/activate
pip install --upgrade pip
pip install -e .[develop]
You can then start OctoPrint via ``~/devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
environment.
.. _sec-development-environment-windows:
Windows
.......
This assumes you'll host your OctoPrint development checkout at ``C:\Devel\OctoPrint``. If you want to use a different
location, please substitute accordingly.
First download & install:
* `Python 2.7.12 Windows x86 MSI installer <https://www.python.org/downloads/release/python-2712/>`_
* make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too
* `Microsoft Visual C++ Compiler for Python 2.7 <http://www.microsoft.com/en-us/download/details.aspx?id=44266>`_
* `Git for Windows <https://git-for-windows.github.io/>`_
Open the Git Bash you just installed and in that:
.. code-block:: none
pip install virtualenv
cd /c/Devel
git clone https://github.com/foosel/OctoPrint.git
cd OctoPrint
virtualenv venv
source ./venv/bin/activate
pip install --upgrade pip
pip install -e .[develop]
You can then start OctoPrint via ``/c/Devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
environment.
.. _sec-development-environment-mac:
Mac OS X
........
.. note::
This guide is based on the `Setup Guide for Mac OS X on OctoPrint's wiki <https://github.com/foosel/OctoPrint/wiki/Setup-on-Mac/>`_.
Please report back if it works for you, due to lack of access to a Mac I cannot test it myself. Thanks.
This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
location, please substitute accordingly.
You'll need a user account with administrator privileges.
* Install the latest version of Xcode suitable for your OS. For example, OS X 10.11 (El Capitan) requires Xcode 7.
* Install Xcode's command line tools:
* ``xcode-select --install``
* ``sudo xcodebuild`` (ensure the license was accepted)
* If you have more than one Xcode installed: ``sudo xcode-select -s /Applications/Xcode.app/Contents/Developer``
* Install Homebrew and use that to install Python:
* ``ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"``
* ``brew install python``
* Install `virtualenv <https://virtualenv.pypa.io/>`_
* ``pip install virtualenv``
* Install OctoPrint
.. code-block:: none
cd ~/devel
git clone https://github.com/foosel/OctoPrint.git
cd OctoPrint
virtualenv venv
source venv/bin/activate
pip install -e .[develop]
You can then start OctoPrint via ``~/devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
environment.
.. _sec-development-environment-ides:
IDE Setup
---------
.. todo::
Using another IDE than the ones below? Please send a
`Pull Request <https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
steps into this guide!
.. _sec-development-environment-ides-pycharm:
PyCharm
.......
- "File" > "Open ...", select OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
- "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv
folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``)
- Right click "src" in project tree, mark as source folder
- Add Run/Debug Configuration, select "Python":
* Name: OctoPrint server
* Script: path to ``run`` in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/run`` or ``C:\Devel\OctoPrint\run``)
* Script parameters: ``--debug``
* Project: ``OctoPrint``
* Python interpreter: the ``venv`` local virtual environment
* Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
.. note::
Make sure you are running a PyCharm version of 2016.1 or later, or manually fix
`a debugger bug contained in earlier versions <https://youtrack.jetbrains.com/issue/PY-18365>`_ or plugin management
will not work in your developer install when running OctoPrint from PyCharm in debug mode.
+4 -179
View File
@@ -4,183 +4,8 @@
Development
###########
.. contents::
:local:
.. toctree::
:maxdepth: 3
.. _sec-development-environment:
Setting up a Development environment
====================================
.. _sec-development-environment-source:
Obtaining, building and running the source
------------------------------------------
This describes the general steps in obtaining, building and running. OS specific instructions can be found
below.
* Prerequisites:
* `Python 2.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Git <https://git-scm.com>`_
* Checkout the OctoPrint sources from their Git repository: ``git clone https://github.com/foosel/OctoPrint.git``
* Create a virtual environment in the checkout folder to use for installing and running OctoPrint and its
dependencies (this avoids potential versioning issues for the dependencies with system wide installed
instances): ``virtualenv venv``
* Activate the virtual environment: ``source venv/bin/activate`` (might differ per your platform/OS)
* Update ``pip`` in the virtual environment: ``pip install --upgrade pip``
* Install OctoPrint in `"editable" mode <https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs>`_,
including its regular *and* development dependencies: ``pip install -e .[develop]``
.. _sec-development-environment-source-linux:
Linux
.....
This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
location, please substitute accordingly.
First make sure you have python including its header files, pip, setuptools, virtualenv, git and some build requirements
installed:
* On apt based distributions (e.g. Debian, Ubuntu, ...):
.. code-block:: none
sudo apt-get install python python-pip python-dev python-setuptools python-virtualenv git libyaml-dev build-essential
.. todo::
Using a Linux distribution that doesn't use ``apt``? Please send a
`Pull Request <https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
steps into this guide!
Then:
.. code-block:: none
cd ~/devel
git clone https://github.com/foosel/OctoPrint.git
cd OctoPrint
virtualenv venv
source ./venv/bin/activate
pip install --upgrade pip
pip install -e .[develop]
You can then start OctoPrint via ``~/devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
environment.
.. _sec-development-environment-windows:
Windows
.......
This assumes you'll host your OctoPrint development checkout at ``C:\Devel\OctoPrint``. If you want to use a different
location, please substitute accordingly.
First download & install:
* `Python 2.7.12 Windows x86 MSI installer <https://www.python.org/downloads/release/python-2712/>`_
* make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too
* `Microsoft Visual C++ Compiler for Python 2.7 <http://www.microsoft.com/en-us/download/details.aspx?id=44266>`_
* `Git for Windows <https://git-for-windows.github.io/>`_
Open the Git Bash you just installed and in that:
.. code-block:: none
pip install virtualenv
cd /c/Devel
git clone https://github.com/foosel/OctoPrint.git
cd OctoPrint
virtualenv venv
source ./venv/bin/activate
pip install --upgrade pip
pip install -e .[develop]
You can then start OctoPrint via ``/c/Devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
environment.
.. _sec-development-environment-mac:
Mac OS X
........
.. note::
This guide is based on the `Setup Guide for Mac OS X on OctoPrint's wiki <https://github.com/foosel/OctoPrint/wiki/Setup-on-Mac/>`_.
Please report back if it works for you, due to lack of access to a Mac I cannot test it myself. Thanks.
This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different
location, please substitute accordingly.
You'll need a user account with administrator privileges.
* Install the latest version of Xcode suitable for your OS. For example, OS X 10.11 (El Capitan) requires Xcode 7.
* Install Xcode's command line tools:
* ``xcode-select --install``
* ``sudo xcodebuild`` (ensure the license was accepted)
* If you have more than one Xcode installed: ``sudo xcode-select -s /Applications/Xcode.app/Contents/Developer``
* Install Homebrew and use that to install Python:
* ``ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"``
* ``brew install python``
* Install `virtualenv <https://virtualenv.pypa.io/>`_
* ``pip install virtualenv``
* Install OctoPrint
.. code-block:: none
cd ~/devel
git clone https://github.com/foosel/OctoPrint.git
cd OctoPrint
virtualenv venv
source venv/bin/activate
pip install -e .[develop]
You can then start OctoPrint via ``~/devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual
environment.
.. _sec-development-environment-ides:
IDE Setup
---------
.. todo::
Using another IDE than the ones below? Please send a
`Pull Request <https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
steps into this guide!
.. _sec-development-environment-ides-pycharm:
PyCharm
.......
- "File" > "Open ...", select OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
- "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv
folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``)
- Right click "src" in project tree, mark as source folder
- Add Run/Debug Configuration, select "Python":
* Name: OctoPrint server
* Script: path to ``run`` in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/run`` or ``C:\Devel\OctoPrint\run``)
* Script parameters: ``--debug``
* Project: ``OctoPrint``
* Python interpreter: the ``venv`` local virtual environment
* Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
.. note::
Make sure you are running a PyCharm version of 2016.1 or later, or manually fix
`a debugger bug contained in earlier versions <https://youtrack.jetbrains.com/issue/PY-18365>`_ or plugin management
will not work in your developer install when running OctoPrint from PyCharm in debug mode.
environment.rst
virtual_printer.rst
+116
View File
@@ -0,0 +1,116 @@
.. _sec-development-virtual-printer:
Setting up the virtual printer for debugging
============================================
OctoPrint includes, by default, a virtual printer plugin. This plugin allows you to debug OctoPrint's serial
communication without connecting to an actual printer. Furthermore, it is possible to create certain edge conditions
that may be hard to reproduce with a real printer.
.. _sec-development-virtual-printer-enable:
Enabling the virtual printer
----------------------------
The virtual printer is enabled by editing OctoPrint's config.yaml file. Details on the configuration file can
be found in the full :ref:`config.yaml documentation <sec-configuration-config_yaml>`.
The steps to take are as follows:
* Find config.yaml in the OctoPrint settings folder. Usually in ``~/.octoprint`` on Linux, in ``%APPDATA%/OctoPrint`` on Windows and in ``~/Library/Application Support/OctoPrint`` on MacOS.
* Add or extend the ``devel`` section with:
.. code-block:: yaml
devel:
virtualPrinter:
enabled: true
* Restart OctoPrint.
* In the connection panel, a new option will appear in the Serial Port dropdown labeled ``VIRTUAL``.
* Select this option and click ``connect``.
* The virtual printer is now active.
.. _sec-development-virtual-printer-config:
Virtual printer configuration options
-------------------------------------
The config.yaml file has many configuration options for the virtual printer that allow you to fine-tune its behavior.
Please see the relevant :ref:`config.yaml section <sec-configuration-config_yaml-devel>` for the full details.
.. _sec-development-virtual-printer-log:
Log file
--------
Once activated, the virtual printer will log all serial communication in the ``plugin_virtual_printer_serial.log`` file
that can be found in the OctoPrint settings folder.
.. _sec-development-virtual-printer-debug:
Debug commands
--------------
You can simulate certain conditions and communications through the terminal tab in OctoPrint's interface.
All commands start with ``!!DEBUG:`` and are followed by the command you want to execute. For instance, sending
``!!DEBUG:action_disconnect`` will disconnect the printer. Sending ``!!DEBUG`` without command will show a help
message with all the available commands.
Action Triggers
...............
``action_pause``
Sends a "// action:pause" action trigger to the host.
``action_resume``
Sends a "// action:resume" action trigger to the host.
``action_disconnect``
Sends a "// action:disconnect" action trigger to the host.
``action_custom <action>[ <parameters>]``
Sends a custom "// action:<action> <parameters>" action trigger to the host.
Communication Errors
....................
``dont_answer``
Will not acknowledge the next command.
``go_awol``
Will completely stop replying.
``trigger_resend_lineno``
Triggers a resend error with a line number mismatch
``trigger_resend_checksum``
Triggers a resend error with a checksum mismatch
``drop_connection``
Drops the serial connection
``prepare_ok <broken ok>``
Will cause <broken ok> to be enqueued for use, will be used instead of actual "ok"
Reply Timing / Sleeping
.......................
``sleep <int:seconds>``
Sleep <seconds> s
``sleep_after <str:command> <int:seconds>``
Sleeps <seconds> s after each execution of <command>
``sleep_after_next <str:command> <int:seconds>``
Sleeps <seconds> s after execution of next <command>
Misc
....
``help``
Show the available commands.
``send <str:message>``
Sends back <message>
+2 -1
View File
@@ -47,7 +47,8 @@ INSTALL_REQUIRES = [
"websocket-client>=0.40,<0.41",
"python-dateutil>=2.6,<2.7",
"wrapt>=1.10.10,<1.11",
"futures>=3.1.1,<3.2"
"futures>=3.1.1,<3.2",
"emoji>=0.4.5,<0.5"
]
if sys.platform == "darwin":
+17 -11
View File
@@ -277,10 +277,12 @@ class FileManager(object):
return False
def slice(self, slicer_name, source_location, source_path, dest_location, dest_path,
position=None, profile=None, printer_profile_id=None, overrides=None, callback=None, callback_args=None):
position=None, profile=None, printer_profile_id=None, overrides=None, display=None,
callback=None, callback_args=None):
absolute_source_path = self.path_on_disk(source_location, source_path)
def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time,
printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
try:
if _error:
eventManager().fire(Events.SLICING_FAILED, dict(stl=source_path,
@@ -305,7 +307,9 @@ class FileManager(object):
io.FileIO(tmp_path, "rb"))
printer_profile = self._printer_profile_manager.get(printer_profile_id)
self.add_file(dest_location, dest_path, file_obj, links=links, allow_overwrite=True, printer_profile=printer_profile, analysis=_analysis)
self.add_file(dest_location, dest_path, file_obj,
display=display, links=links, allow_overwrite=True,
printer_profile=printer_profile, analysis=_analysis)
end_time = time.time()
eventManager().fire(Events.SLICING_DONE, dict(stl=source_path,
@@ -417,7 +421,7 @@ class FileManager(object):
result[dst] = self._storage_managers[dst].list_files(path=path, filter=filter, recursive=recursive)
return result
def add_file(self, destination, path, file_object, links=None, allow_overwrite=False, printer_profile=None, analysis=None):
def add_file(self, destination, path, file_object, links=None, allow_overwrite=False, printer_profile=None, analysis=None, display=None):
if printer_profile is None:
printer_profile = self._printer_profile_manager.get_current_or_default()
@@ -434,7 +438,7 @@ class FileManager(object):
queue_entry = self._analysis_queue_entry(destination, path)
self._analysis_queue.dequeue(queue_entry)
path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite, display=display)
if analysis is None:
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile)
@@ -501,8 +505,8 @@ class FileManager(object):
type=get_file_type(dst_name)))
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def add_folder(self, destination, path, ignore_existing=True):
path_in_storage = self._storage(destination).add_folder(path, ignore_existing=ignore_existing)
def add_folder(self, destination, path, ignore_existing=True, display=None):
path_in_storage = self._storage(destination).add_folder(path, ignore_existing=ignore_existing, display=display)
_, name = self._storage(destination).split_path(path_in_storage)
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
@@ -525,7 +529,7 @@ class FileManager(object):
def copy_folder(self, destination, source, dst):
path_in_storage = self._storage(destination).copy_folder(source, dst)
self._determine_analysis_backlog(destination, self._storage(destination), root=dst)
self._determine_analysis_backlog(destination, self._storage(destination), root=path_in_storage)
_, name = self._storage(destination).split_path(path_in_storage)
eventManager().fire(Events.FOLDER_ADDED, dict(storage=destination,
@@ -536,13 +540,12 @@ class FileManager(object):
def move_folder(self, destination, source, dst):
self._analysis_queue.dequeue_folder(destination, source)
self._analysis_queue.pause()
self._storage(destination).move_folder(source, dst)
self._determine_analysis_backlog(destination, self._storage(destination), root=dst)
dst_path_in_storage = self._storage(destination).move_folder(source, dst)
self._determine_analysis_backlog(destination, self._storage(destination), root=dst_path_in_storage)
self._analysis_queue.resume()
source_path_in_storage = self._storage(destination).path_in_storage(source)
_, source_name = self._storage(destination).split_path(source_path_in_storage)
dst_path_in_storage = self._storage(destination).path_in_storage(destination)
_, dst_name = self._storage(destination).split_path(dst_path_in_storage)
eventManager().fire(Events.FOLDER_REMOVED, dict(storage=destination,
@@ -622,6 +625,9 @@ class FileManager(object):
def path_on_disk(self, destination, path):
return self._storage(destination).path_on_disk(path)
def canonicalize(self, destination, path):
return self._storage(destination).canonicalize(path)
def sanitize(self, destination, path):
return self._storage(destination).sanitize(path)
+234 -71
View File
@@ -10,6 +10,7 @@ import logging
import os
import pylru
import shutil
import re
try:
from os import scandir, walk
@@ -22,9 +23,12 @@ from copy import deepcopy
from past.builtins import basestring
from emoji import demojize
from slugify import Slugify
import octoprint.filemanager
from octoprint.util import is_hidden_path
from octoprint.util import is_hidden_path, to_unicode
class StorageInterface(object):
"""
@@ -154,7 +158,7 @@ class StorageInterface(object):
"""
raise NotImplementedError()
def add_folder(self, path, ignore_existing=True):
def add_folder(self, path, ignore_existing=True, display=None):
"""
Adds a folder as ``path``
@@ -162,6 +166,7 @@ class StorageInterface(object):
:param string path: the path of the new folder
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
:param unicode display: display name of the folder
:return: the sanitized name of the new folder to be used for future references to the folder
"""
raise NotImplementedError()
@@ -198,7 +203,7 @@ class StorageInterface(object):
"""
raise NotImplementedError()
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
"""
Adds the file ``file_object`` as ``path``
@@ -209,6 +214,7 @@ class StorageInterface(object):
:param list links: any links to add with the file
:param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
and its metadata will just be silently overwritten
:param unicode display: display name of the file
:return: the sanitized name of the file to be used for future references to it
"""
raise NotImplementedError()
@@ -327,6 +333,23 @@ class StorageInterface(object):
"""
raise NotImplementedError()
def canonicalize(self, path):
"""
Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying
implementation must separate those if necessary.
By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care
of stripping any invalid characters.
Args:
path: the path to canonicalize
Returns:
a 2-tuple containing the canonicalized path and file name
"""
return self.sanitize(path)
def sanitize(self, path):
"""
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
@@ -403,6 +426,7 @@ class StorageError(Exception):
INVALID_DESTINATION = "invalid_destination"
DOES_NOT_EXIST = "does_not_exist"
ALREADY_EXISTS = "already_exists"
SOURCE_EQUALS_DESTINATION = "source_equals_destination"
NOT_EMPTY = "not_empty"
def __init__(self, message, code=None, cause=None):
@@ -425,6 +449,22 @@ class LocalFileStorage(StorageInterface):
This storage type implements :func:`path_on_disk`.
"""
_UNICODE_VARIATIONS = re.compile(u"[\uFE00-\uFE0F]")
@classmethod
def _no_unicode_variations(cls, text):
return cls._UNICODE_VARIATIONS.sub(u"", text)
_SLUGIFY = Slugify()
_SLUGIFY.safe_chars = "-_.()[] "
@classmethod
def _slugify(cls, text):
text = to_unicode(text)
text = cls._no_unicode_variations(text)
text = demojize(text, delimiters=(u"", u""))
return cls._SLUGIFY(text)
def __init__(self, basefolder, create=False):
"""
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
@@ -435,7 +475,7 @@ class LocalFileStorage(StorageInterface):
"""
self._logger = logging.getLogger(__name__)
self.basefolder = os.path.realpath(os.path.abspath(basefolder))
self.basefolder = os.path.realpath(os.path.abspath(to_unicode(basefolder)))
if not os.path.exists(self.basefolder) and create:
os.makedirs(self.basefolder)
if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder):
@@ -447,10 +487,6 @@ class LocalFileStorage(StorageInterface):
self._metadata_cache = pylru.lrucache(10)
from slugify import Slugify
self._slugify = Slugify()
self._slugify.safe_chars = "-_.()[] "
self._old_metadata = None
self._initialize_metadata()
@@ -557,17 +593,22 @@ class LocalFileStorage(StorageInterface):
def list_files(self, path=None, filter=None, recursive=True):
if path:
path = self.sanitize_path(path)
path = self.sanitize_path(to_unicode(path))
base = self.path_in_storage(path)
if base:
base += "/"
base += u"/"
else:
path = self.basefolder
base = ""
base = u""
return self._list_folder(path, base=base, entry_filter=filter, recursive=recursive)
def add_folder(self, path, ignore_existing=True):
path, name = self.sanitize(path)
def add_folder(self, path, ignore_existing=True, display=None):
display_path, display_name = self.canonicalize(path)
path = self.sanitize_path(display_path)
name = self.sanitize_name(display_name)
if display is not None:
display_name = display
folder_path = os.path.join(path, name)
if os.path.exists(folder_path):
@@ -576,6 +617,11 @@ class LocalFileStorage(StorageInterface):
else:
os.mkdir(folder_path)
if display_name != name:
metadata = self._get_metadata_entry(path, name, default=dict())
metadata["display"] = display_name
self._update_metadata_entry(path, name, metadata)
return self.path_in_storage((path, name))
def remove_folder(self, path, recursive=True):
@@ -598,12 +644,15 @@ class LocalFileStorage(StorageInterface):
import shutil
shutil.rmtree(folder_path)
self._delete_metadata(folder_path)
self._remove_metadata_entry(path, name)
def _get_source_destination_data(self, source, destination):
def _get_source_destination_data(self, source, destination, must_not_equal=False):
"""Prepares data dicts about source and destination for copy/move."""
source_path, source_name = self.sanitize(source)
destination_path, destination_name = self.sanitize(destination)
destination_canon_path, destination_canon_name = self.canonicalize(destination)
destination_path = self.sanitize_path(destination_canon_path)
destination_name = self.sanitize_name(destination_canon_name)
source_fullpath = os.path.join(source_path, source_name)
destination_fullpath = os.path.join(destination_path, destination_name)
@@ -613,45 +662,88 @@ class LocalFileStorage(StorageInterface):
if not os.path.isdir(destination_path):
raise StorageError("Destination path {} does not exist or is not a folder".format(destination_path), code=StorageError.INVALID_DESTINATION)
if os.path.exists(destination_fullpath):
if os.path.exists(destination_fullpath) and source_fullpath != destination_fullpath:
raise StorageError("{} does already exist in {}".format(destination_name, destination_path), code=StorageError.INVALID_DESTINATION)
source_meta = self._get_metadata_entry(source_path, source_name)
if source_meta:
source_display = source_meta.get("display", source_name)
else:
source_display = source_name
if (must_not_equal or source_display == destination_canon_name) and source_fullpath == destination_fullpath:
raise StorageError("Source {} and destination {} are the same folder".format(source_path, destination_path), code=StorageError.SOURCE_EQUALS_DESTINATION)
source_data = dict(
path=source_path,
name=source_name,
display=source_display,
fullpath=source_fullpath,
)
destination_data = dict(
path=destination_path,
name=destination_name,
display=destination_canon_name,
fullpath=destination_fullpath,
)
return source_data, destination_data
def _set_display_metadata(self, destination_data, source_data=None):
if source_data and destination_data["name"] == source_data["name"] and source_data["name"] != source_data["display"]:
display = source_data["display"]
elif destination_data["name"] != destination_data["display"]:
display = destination_data["display"]
else:
display = None
destination_meta = self._get_metadata_entry(destination_data["path"], destination_data["name"],
default=dict())
if display:
destination_meta["display"] = display
self._update_metadata_entry(destination_data["path"], destination_data["name"], destination_meta)
elif "display" in destination_meta:
del destination_meta["display"]
self._update_metadata_entry(destination_data["path"], destination_data["name"], destination_meta)
def copy_folder(self, source, destination):
source_data, destination_data = self._get_source_destination_data(source, destination)
source_data, destination_data = self._get_source_destination_data(source, destination, must_not_equal=True)
try:
shutil.copytree(source_data["fullpath"], destination_data["fullpath"])
except Exception as e:
raise StorageError("Could not copy %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e)
self._set_display_metadata(destination_data, source_data=source_data)
return self.path_in_storage(destination_data["fullpath"])
def move_folder(self, source, destination):
source_data, destination_data = self._get_source_destination_data(source, destination)
# only a display rename? Update that and bail early
if source_data["fullpath"] == destination_data["fullpath"]:
self._set_display_metadata(destination_data)
return self.path_in_storage(destination_data["fullpath"])
try:
shutil.move(source_data["fullpath"], destination_data["fullpath"])
except Exception as e:
raise StorageError("Could not move %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e)
self._set_display_metadata(destination_data, source_data=source_data)
self._remove_metadata_entry(source_data["path"], source_data["name"])
self._delete_metadata(source_data["fullpath"])
return self.path_in_storage(destination_data["fullpath"])
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
path, name = self.sanitize(path)
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
display_path, display_name = self.canonicalize(path)
path = self.sanitize_path(display_path)
name = self.sanitize_name(display_name)
if display:
display_name = display
if not octoprint.filemanager.valid_file_type(name):
raise StorageError("{name} is an unrecognized file type".format(**locals()), code=StorageError.INVALID_FILE)
@@ -663,6 +755,7 @@ class LocalFileStorage(StorageInterface):
# make sure folders exist
if not os.path.exists(path):
# TODO persist display names of path segments!
os.makedirs(path)
# save the file
@@ -671,9 +764,19 @@ 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:
# hash changed -> throw away old metadata
self._update_metadata_entry(path, name, dict(hash=file_hash))
metadata = dict(hash=file_hash)
metadata_dirty = True
if not "display" in metadata and display_name != name:
# display name is not the same as file name -> store in metadata
metadata["display"] = display_name
metadata_dirty = True
if metadata_dirty:
self._update_metadata_entry(path, name, metadata)
# process any links that were also provided for adding to the file
if not links:
@@ -706,7 +809,7 @@ class LocalFileStorage(StorageInterface):
self._remove_metadata_entry(path, name)
def copy_file(self, source, destination):
source_data, destination_data = self._get_source_destination_data(source, destination)
source_data, destination_data = self._get_source_destination_data(source, destination, must_not_equal=True)
try:
shutil.copy2(source_data["fullpath"], destination_data["fullpath"])
@@ -715,12 +818,18 @@ class LocalFileStorage(StorageInterface):
self._copy_metadata_entry(source_data["path"], source_data["name"],
destination_data["path"], destination_data["name"])
self._set_display_metadata(destination_data, source_data=source_data)
return self.path_in_storage(destination_data["fullpath"])
def move_file(self, source, destination, allow_overwrite=False):
source_data, destination_data = self._get_source_destination_data(source, destination)
# only a display rename? Update that and bail early
if source_data["fullpath"] == destination_data["fullpath"]:
self._set_display_metadata(destination_data)
return self.path_in_storage(destination_data["fullpath"])
try:
shutil.move(source_data["fullpath"], destination_data["fullpath"])
except Exception as e:
@@ -729,7 +838,8 @@ class LocalFileStorage(StorageInterface):
self._copy_metadata_entry(source_data["path"], source_data["name"],
destination_data["path"], destination_data["name"],
delete_source=True)
self._set_display_metadata(destination_data, source_data=source_data)
return self.path_in_storage(destination_data["fullpath"])
def has_analysis(self, path):
@@ -762,7 +872,7 @@ class LocalFileStorage(StorageInterface):
def remove_history(self, path, index):
path, name = self.sanitize(path)
self._update_history(name, path, index)
self._delete_history(name, path, index)
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
path, name = self.sanitize(path)
@@ -800,14 +910,15 @@ class LocalFileStorage(StorageInterface):
self._save_metadata(path, metadata)
def split_path(self, path):
split = path.split("/")
path = to_unicode(path)
split = path.split(u"/")
if len(split) == 1:
return "", split[0]
return u"", split[0]
else:
return self.join_path(*split[:-1]), split[-1]
def join_path(self, *path):
return "/".join(path)
return u"/".join(map(to_unicode, path))
def sanitize(self, path):
"""
@@ -824,40 +935,48 @@ class LocalFileStorage(StorageInterface):
hence be returned at second position. If you only need to convert a folder path, be sure to
include a trailing slash for a string ``path`` or an empty last element for a list ``path``.
"""
name = None
if isinstance(path, (str, unicode, basestring)):
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, "/")
path = path.split("/")
if isinstance(path, (list, tuple)):
if len(path) == 1:
name = path[0]
path = "/"
else:
name = path[-1]
path = "/" + self.join_path(*path[:-1])
if not path:
path = "/"
path, name = self.canonicalize(path)
name = self.sanitize_name(name)
path = self.sanitize_path(path)
return path, name
def canonicalize(self, path):
name = None
if isinstance(path, basestring):
path = to_unicode(path)
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, u"/")
path = path.split(u"/")
if isinstance(path, (list, tuple)):
if len(path) == 1:
name = to_unicode(path[0])
path = u""
else:
name = to_unicode(path[-1])
path = self.join_path(*map(to_unicode, path[:-1]))
if not path:
path = u""
return path, name
def sanitize_name(self, name):
"""
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise
slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``,
``(``, and ``)`` as is.
"""
name = to_unicode(name)
if name is None:
return None
if "/" in name or "\\" in name:
if u"/" in name or u"\\" in name:
raise ValueError("name must not contain / or \\")
result = self._slugify(name).replace(" ", "_")
if result and result != "." and result != ".." and result[0] == ".":
result = self._slugify(name).replace(u" ", u"_")
if result and result != u"." and result != u".." and result[0] == u".":
# hidden files under *nix
result = result[1:]
return result
@@ -868,12 +987,15 @@ class LocalFileStorage(StorageInterface):
relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the
absolute path including leading ``basefolder`` path.
"""
if path[0] == "/":
path = path[1:]
elif path[0] == "." and path[1] == "/":
path = path[2:]
path = to_unicode(path)
if len(path):
if path[0] == u"/":
path = path[1:]
elif path[0] == u"." and path[1] == u"/":
path = path[2:]
path_elements = path.split("/")
path_elements = path.split(u"/")
joined_path = self.basefolder
for path_element in path_elements:
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
@@ -883,6 +1005,7 @@ class LocalFileStorage(StorageInterface):
return path
def _sanitize_entry(self, entry, path, entry_path):
entry = to_unicode(entry)
sanitized = self.sanitize_name(entry)
if sanitized != entry:
# entry is not sanitized yet, let's take care of that
@@ -892,16 +1015,16 @@ class LocalFileStorage(StorageInterface):
counter = 1
while os.path.exists(sanitized_path):
counter += 1
sanitized = self.sanitize_name("{}_({}){}".format(sanitized_name, counter, sanitized_ext))
sanitized = self.sanitize_name(u"{}_({}){}".format(sanitized_name, counter, sanitized_ext))
sanitized_path = os.path.join(path, sanitized)
try:
shutil.move(entry_path, sanitized_path)
self._logger.info("Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path))
self._logger.info(u"Sanitized \"{}\" to \"{}\"".format(entry_path, sanitized_path))
return sanitized, sanitized_path
except:
self._logger.exception("Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path))
self._logger.exception(u"Error while trying to rename \"{}\" to \"{}\", ignoring file".format(entry_path, sanitized_path))
raise
return entry, entry_path
@@ -910,10 +1033,11 @@ class LocalFileStorage(StorageInterface):
if isinstance(path, (tuple, list)):
path = self.join_path(*path)
if isinstance(path, (str, unicode, basestring)):
path = to_unicode(path)
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, "/")
if path.startswith("/"):
path = path.replace(os.path.sep, u"/")
if path.startswith(u"/"):
path = path[1:]
return path
@@ -1169,7 +1293,7 @@ class LocalFileStorage(StorageInterface):
continue
try:
entry_name = entry.name
entry_name = entry_display = entry.name
entry_path = entry.path
entry_is_file = entry.is_file()
entry_is_dir = entry.is_dir()
@@ -1182,6 +1306,7 @@ class LocalFileStorage(StorageInterface):
try:
new_entry_name, new_entry_path = self._sanitize_entry(entry_name, path, entry_path)
if entry_name != new_entry_name or entry_path != new_entry_path:
entry_display = to_unicode(entry_name)
entry_name = new_entry_name
entry_path = new_entry_path
entry_stat = os.stat(entry_path)
@@ -1201,18 +1326,26 @@ class LocalFileStorage(StorageInterface):
file_type = type_path[0]
if entry_name in metadata and isinstance(metadata[entry_name], dict):
entry_data = metadata[entry_name]
entry_metadata = metadata[entry_name]
if not "display" in entry_metadata and entry_display != entry_name:
metadata[entry_name]["display"] = entry_display
entry_metadata["display"] = entry_display
metadata_dirty = True
else:
entry_data = self._add_basic_metadata(path, entry_name, save=False, metadata=metadata)
entry_metadata = self._add_basic_metadata(path, entry_name,
display_name=entry_display,
save=False,
metadata=metadata)
metadata_dirty = True
# TODO extract model hash from source if possible to recreate link
if not entry_filter or entry_filter(entry_name, entry_data):
if not entry_filter or entry_filter(entry_name, entry_metadata):
# only add files passing the optional filter
extended_entry_data = dict()
extended_entry_data.update(entry_data)
extended_entry_data.update(entry_metadata)
extended_entry_data["name"] = entry_name
extended_entry_data["display"] = entry_metadata.get("display", entry_name)
extended_entry_data["path"] = path_in_location
extended_entry_data["type"] = file_type
extended_entry_data["typePath"] = type_path
@@ -1225,11 +1358,27 @@ class LocalFileStorage(StorageInterface):
# folder recursion
elif entry_is_dir:
if entry_name in metadata and isinstance(metadata[entry_name], dict):
entry_metadata = metadata[entry_name]
if not "display" in entry_metadata and entry_display != entry_name:
metadata[entry_name]["display"] = entry_display
entry_metadata["display"] = entry_display
metadata_dirty = True
elif entry_name != entry_display:
entry_metadata = self._add_basic_metadata(path, entry_name,
display_name=entry_display,
save=False,
metadata=metadata)
metadata_dirty = True
else:
entry_metadata = dict()
entry_data = dict(
name=entry_name,
display=entry_metadata.get("display", entry_name),
path=path_in_location,
type="folder",
type_path=["folder"]
typePath=["folder"]
)
if recursive:
sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter,
@@ -1261,22 +1410,33 @@ class LocalFileStorage(StorageInterface):
return result
def _add_basic_metadata(self, path, entry, additional_metadata=None, save=True, metadata=None):
def _add_basic_metadata(self, path, entry, display_name=None, additional_metadata=None, save=True, metadata=None):
if additional_metadata is None:
additional_metadata = dict()
if metadata is None:
metadata = self._get_metadata(path)
entry_data = dict(
hash=self._create_hash(os.path.join(path, entry)),
links=[],
notes=[]
)
entry_path = os.path.join(path, entry)
if path == self.basefolder and self._old_metadata is not None and entry in self._old_metadata and "gcodeAnalysis" in self._old_metadata[entry]:
# if there is still old metadata available and that contains an analysis for this file, use it!
entry_data["analysis"] = self._old_metadata[entry]["gcodeAnalysis"]
if os.path.isfile(entry_path):
entry_data = dict(
hash=self._create_hash(os.path.join(path, entry)),
links=[],
notes=[]
)
if path == self.basefolder and self._old_metadata is not None and entry in self._old_metadata and "gcodeAnalysis" in self._old_metadata[entry]:
# if there is still old metadata available and that contains an analysis for this file, use it!
entry_data["analysis"] = self._old_metadata[entry]["gcodeAnalysis"]
elif os.path.isdir(entry_path):
entry_data = dict()
else:
return
if display_name is not None and not display_name == entry:
entry_data["display"] = display_name
entry_data.update(additional_metadata)
metadata[entry] = entry_data
@@ -1327,7 +1487,7 @@ class LocalFileStorage(StorageInterface):
metadata[name] = data
self._save_metadata(path, metadata)
def _copy_metadata_entry(self, source_path, source_name, destination_path, destination_name, delete_source=False):
def _copy_metadata_entry(self, source_path, source_name, destination_path, destination_name, delete_source=False, updates=None):
with self._get_metadata_lock(source_path):
source_data = self._get_metadata_entry(source_path, source_name, default=dict())
if not source_data:
@@ -1336,6 +1496,9 @@ class LocalFileStorage(StorageInterface):
if delete_source:
self._remove_metadata_entry(source_path, source_name)
if updates is not None:
source_data.update(updates)
with self._get_metadata_lock(destination_path):
self._update_metadata_entry(destination_path, destination_name, source_data)
@@ -319,7 +319,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
def command_install(self, url=None, path=None, force=False, reinstall=None, dependency_links=False):
if url is not None:
if not any(map(lambda scheme: url.starts_with(scheme + "://"), self.URL_SCHEMES)):
if not any(map(lambda scheme: url.startswith(scheme + "://"), self.URL_SCHEMES)):
raise ValueError("Invalid URL to pip install from")
source = url
@@ -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}
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;padding-right:12px}#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}
@@ -732,7 +732,7 @@ $(function() {
if (restartClicked) return;
restartClicked = true;
showConfirmationDialog({
message: gettext("This will restart your OctoPrint server."),
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)."),
onproceed: function() {
OctoPrint.system.executeCommand("core", "restart")
.done(function() {
@@ -1078,15 +1078,6 @@ $(function() {
self.workingDialog = $("#settings_plugin_pluginmanager_workingdialog");
self.workingOutput = $("#settings_plugin_pluginmanager_workingdialog_output");
self.repositoryDialog = $("#settings_plugin_pluginmanager_repositorydialog");
$("#settings_plugin_pluginmanager_repositorydialog_list").slimScroll({
height: "306px",
size: "5px",
distance: "0",
railVisible: true,
alwaysVisible: true,
scrollBy: "102px"
});
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
@@ -24,7 +24,10 @@ table {
#settings_plugin_pluginmanager_repositorydialog {
.slimScrollDiv {
@scrollBar: 10px;
margin-bottom: 20px;
padding-right: @scrollBar + 2px;
}
h4 {
@@ -155,7 +155,7 @@
</form>
<div data-bind="visible: repositoryAvailable()">
<div id="settings_plugin_pluginmanager_repositorydialog_list" data-bind="slimScrolledForeach: repositoryplugins.paginatedItems">
<div id="settings_plugin_pluginmanager_repositorydialog_list" data-bind="slimScrolledForeach: {data: repositoryplugins.paginatedItems, slimscroll: {height: '306px', size: '10px', distance: 0, railVisible: true, alwaysVisible: true, scrollBy: '102px'} }">
<div class="entry">
<div class="row-fluid">
<div class="span9">
@@ -398,7 +398,6 @@ $(function() {
if (showIfNothingNew) {
self._showPopup({
title: gettext("Everything is up-to-date"),
hide: false,
type: "success"
});
} else {
@@ -18,6 +18,12 @@
<p>
{{ _('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>
</p>
<p>
{{ _('Depending on your printer\'s controller and general setup, restarting OctoPrint may cause your printer to be reset.') }}
</p>
<p>
{{ _('Are you sure you want to proceed?') }}
</p>
+5
View File
@@ -887,6 +887,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
"file": {
"name": None,
"path": None,
"display": None,
"origin": None,
"size": None,
"date": None
@@ -903,6 +904,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
averagePrintTime = None
date = None
filament = None
display_name = name_in_storage
if path_on_disk:
# Use a string for mtime because it could be float and the
# javascript needs to exact match
@@ -914,6 +916,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
except:
fileData = None
if fileData is not None:
if "display" in fileData:
display_name = fileData["display"]
if "analysis" in fileData:
if estimatedPrintTime is None and "estimatedPrintTime" in fileData["analysis"]:
estimatedPrintTime = fileData["analysis"]["estimatedPrintTime"]
@@ -938,6 +942,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
"file": {
"name": name_in_storage,
"path": path_in_storage,
"display": display_name,
"origin": FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
"size": filesize,
"date": date
+8 -1
View File
@@ -514,6 +514,11 @@ class Server(object):
from octoprint.filemanager import get_mime_type
return get_mime_type(path)
def download_name_generator(path):
metadata = fileManager.get_metadata("local", path)
if metadata and "display" in metadata:
return metadata["display"]
download_handler_kwargs = dict(
as_attachment=True,
allow_client_caching=False
@@ -547,7 +552,9 @@ class Server(object):
timelapse_permission_validator,
download_handler_kwargs,
no_hidden_files_validator)),
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("uploads")),
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("uploads"),
as_attachment=True,
name_generator=download_name_generator),
download_permission_validator,
download_handler_kwargs,
no_hidden_files_validator,
+42 -7
View File
@@ -31,6 +31,8 @@ import threading
_file_cache = dict()
_file_cache_mutex = threading.RLock()
_FILES_DATA_VERSION = 1
def _clear_file_cache():
with _file_cache_mutex:
_file_cache.clear()
@@ -73,6 +75,7 @@ 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))
@@ -152,6 +155,7 @@ def _getFileList(origin, path=None, filter=None, recursive=False, allow_from_cac
file = {
"type": "machinecode",
"name": sdFile,
"display": sdFile,
"path": sdFile,
"origin": FileDestinations.SDCARD,
"refs": {
@@ -292,8 +296,11 @@ def uploadGcodeFile(target):
# determine future filename of file to be uploaded, abort if it can't be uploaded
try:
# FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet
futurePath, futureFilename = fileManager.sanitize(FileDestinations.LOCAL, upload.filename)
canonPath, canonFilename = fileManager.canonicalize(FileDestinations.LOCAL, upload.filename)
futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, canonPath)
futureFilename = fileManager.sanitize_name(FileDestinations.LOCAL, canonFilename)
except:
canonFilename = None
futurePath = None
futureFilename = None
@@ -340,7 +347,9 @@ def uploadGcodeFile(target):
printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect)
try:
added_file = fileManager.add_file(FileDestinations.LOCAL, futureFullPathInStorage, upload, allow_overwrite=True)
added_file = fileManager.add_file(FileDestinations.LOCAL, futureFullPathInStorage, upload,
allow_overwrite=True,
display=canonFilename)
except octoprint.filemanager.storage.StorageError as e:
if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE:
return make_response("Could not upload the file \"{}\", invalid type".format(upload.filename), 400)
@@ -406,7 +415,9 @@ def uploadGcodeFile(target):
if not target in [FileDestinations.LOCAL]:
return make_response("Unknown target: %s" % target, 400)
futurePath, futureName = fileManager.sanitize(target, foldername)
canonPath, canonName = fileManager.canonicalize(target, foldername)
futurePath = fileManager.sanitize_path(target, canonPath)
futureName = fileManager.sanitize_name(target, canonName)
if not futureName or not futurePath:
return make_response("Can't create a folder with an empty name", 400)
@@ -419,7 +430,7 @@ def uploadGcodeFile(target):
return make_response("Can't create a folder named %s, please try another name" % futureName, 409)
try:
added_folder = fileManager.add_folder(target, futureFullPath)
added_folder = fileManager.add_folder(target, futureFullPath, display=canonName)
except octoprint.filemanager.storage.StorageError as e:
if e.code == octoprint.filemanager.storage.StorageError.INVALID_DIRECTORY:
return make_response("Could not create folder {}, invalid directory".format(futureName))
@@ -550,6 +561,14 @@ def gcodeFileCommand(filename, target):
if path:
full_path = fileManager.join_path(target, path, destination)
canon_path, canon_name = fileManager.canonicalize(target, full_path)
sanitized_name = fileManager.sanitize_name(target, canon_name)
if canon_path:
full_path = fileManager.join_path(target, canon_path, sanitized_name)
else:
full_path = sanitized_name
# prohibit overwriting the file that is currently being printed
currentOrigin, currentFilename = _getCurrentFile()
if currentFilename == full_path and currentOrigin == target and (printer.is_printing() or printer.is_paused()):
@@ -606,6 +625,7 @@ def gcodeFileCommand(filename, target):
printer_profile_id=printerProfile,
position=position,
overrides=overrides,
display=canon_name,
callback=slicing_done,
callback_args=(target, full_path, select_after_slicing, print_after_slicing))
except octoprint.slicing.UnknownProfile:
@@ -616,6 +636,7 @@ def gcodeFileCommand(filename, target):
result = {
"name": destination,
"path": full_path,
"display": canon_name,
"origin": FileDestinations.LOCAL,
"refs": {
"resource": location,
@@ -648,10 +669,14 @@ def gcodeFileCommand(filename, target):
return make_response("File or folder not found on {}: {}".format(target, filename), 404)
path, name = fileManager.split_path(target, filename)
destination = data["destination"]
if _verifyFolderExists(target, destination):
# destination is an existing folder, we'll assume we are supposed to move filename to this
# folder under the same name
dst_path, dst_name = fileManager.split_path(target, destination)
sanitized_destination = fileManager.join_path(target, dst_path, fileManager.sanitize_name(target, dst_name))
if _verifyFolderExists(target, destination) and sanitized_destination != filename:
# destination is an existing folder and not ourselves (= display rename), we'll assume we are supposed
# to move filename to this folder under the same name
destination = fileManager.join_path(target, destination, name)
if _verifyFileExists(target, destination) or _verifyFolderExists(target, destination):
@@ -664,14 +689,24 @@ def gcodeFileCommand(filename, target):
return make_response("{} on {} is neither file or folder, can't {}".format(filename, target, command), 400)
if command == "copy":
# destination already there? error...
if _verifyFileExists(target, destination) or _verifyFolderExists(target, destination):
return make_response("File or folder does already exist on {}: {}".format(target, destination), 409)
if is_file:
fileManager.copy_file(target, filename, destination)
else:
fileManager.copy_folder(target, filename, destination)
elif command == "move":
if _isBusy(target, filename):
return make_response("Trying to move a file or folder that is currently in use: {}".format(filename), 409)
# destination already there AND not ourselves (= display rename)? error...
if (_verifyFileExists(target, destination) or _verifyFolderExists(target, destination)) \
and sanitized_destination != filename:
return make_response("File or folder does already exist on {}: {}".format(target, destination), 409)
# deselect the file if it's currently selected
currentOrigin, currentFilename = _getCurrentFile()
if currentFilename is not None and filename == currentFilename:
+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("You are about to shutdown the 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).")),
reboot=dict(
command=s().get(["server", "commands", "systemRestartCommand"]),
name=gettext("Reboot system"),
confirm=gettext("You are about to reboot the 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).")),
restart=dict(
command=s().get(["server", "commands", "serverRestartCommand"]),
name=gettext("Restart OctoPrint"),
confirm=gettext("You are about to restart the OctoPrint server.")),
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).")),
restart_safe=dict(
command=s().get(["server", "commands", "serverRestartCommand"]),
name=gettext("Restart OctoPrint in safe mode"),
confirm=gettext("You are about to restart the OctoPrint server 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)."),
before=enable_safe_mode)
)
+11 -2
View File
@@ -858,7 +858,7 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
"""
def initialize(self, path, default_filename=None, as_attachment=False, allow_client_caching=True,
access_validation=None, path_validation=None, etag_generator=None,
access_validation=None, path_validation=None, etag_generator=None, name_generator=None,
mime_type_guesser=None):
tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename)
self._as_attachment = as_attachment
@@ -866,6 +866,7 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
self._access_validation = access_validation
self._path_validation = path_validation
self._etag_generator = etag_generator
self._name_generator = name_generator
self._mime_type_guesser = mime_type_guesser
def get(self, path, include_body=True):
@@ -882,7 +883,15 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
def set_extra_headers(self, path):
if self._as_attachment:
self.set_header("Content-Disposition", "attachment; filename=%s" % os.path.basename(path))
filename = None
if callable(self._name_generator):
filename = self._name_generator(path)
if filename is None:
filename = os.path.basename(path)
filename = tornado.escape.url_escape(filename, plus=False)
self.set_header("Content-Disposition", "attachment; filename=\"{}\"; filename*=UTF-8''{}".format(filename,
filename))
if not self._allow_client_caching:
self.set_header("Cache-Control", "max-age=0, must-revalidate, private")
+1 -1
View File
@@ -472,7 +472,7 @@ def _process_templates():
else:
# Finally everything else
return u"2:{}".format(to_unicode(d[0]))
template_sorting = dict(
navbar=dict(add="prepend", key=None),
sidebar=dict(add="append", key="name"),
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6}.btn.active,.btn:active{background-color:#ccc\9}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-danger.active,.btn-info.active,.btn-inverse.active,.btn-primary.active,.btn-success.active,.btn-warning.active{color:rgba(255,255,255,.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c}.btn-primary.active,.btn-primary:active{background-color:#039\9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406}.btn-warning.active,.btn-warning:active{background-color:#c67605\9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);backLine truncated
.btn{display:inline-block;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn.active,.btn.disabled,.btn:active,.btn:focus,.btn:hover,.btn[disabled]{color:#333;background-color:#e6e6e6}.btn.active,.btn:active{background-color:#ccc\9}.btn:focus,.btn:hover{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class*=" icon-"],.btn-large [class^=icon-]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class*=" icon-"],.btn-small [class^=icon-]{margin-top:0}.btn-mini [class*=" icon-"],.btn-mini [class^=icon-]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-danger.active,.btn-info.active,.btn-inverse.active,.btn-primary.active,.btn-success.active,.btn-warning.active{color:rgba(255,255,255,.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary.active,.btn-primary.disabled,.btn-primary:active,.btn-primary:focus,.btn-primary:hover,.btn-primary[disabled]{color:#fff;background-color:#04c}.btn-primary.active,.btn-primary:active{background-color:#039\9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning.active,.btn-warning.disabled,.btn-warning:active,.btn-warning:focus,.btn-warning:hover,.btn-warning[disabled]{color:#fff;background-color:#f89406}.btn-warning.active,.btn-warning:active{background-color:#c67605\9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);backLine truncated
@@ -1,17 +1,57 @@
ko.bindingHandlers.slimScrolledForeach = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
return ko.bindingHandlers.foreach.init(element, valueAccessor(), allBindings, viewModel, bindingContext);
makeTemplateValueAccessor: function(valueAccessor) {
var modelValue = valueAccessor(),
unwrappedValue = ko.utils.peekObservable(modelValue), // Unwrap without setting a dependency here
result, slimscroll;
// If unwrappedValue is the array, pass in the wrapped value on its own
// The value will be unwrapped and tracked within the template binding
// (See https://github.com/SteveSanderson/knockout/issues/523)
if ((!unwrappedValue) || typeof unwrappedValue.length === "number") {
result = { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
slimscroll = {};
} else {
// If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
ko.utils.unwrapObservable(modelValue);
result = {
'foreach': unwrappedValue['data'],
'as': unwrappedValue['as'],
'includeDestroyed': unwrappedValue['includeDestroyed'],
'afterAdd': unwrappedValue['afterAdd'],
'beforeRemove': unwrappedValue['beforeRemove'],
'afterRender': unwrappedValue['afterRender'],
'beforeMove': unwrappedValue['beforeMove'],
'afterMove': unwrappedValue['afterMove'],
'templateEngine': ko.nativeTemplateEngine.instance
};
slimscroll = unwrappedValue['slimscroll'];
}
return {accessor: function() { return result; }, slimscroll: slimscroll};
},
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
slimscroll: function(element, options) {
options = options || {};
setTimeout(function() {
if (element.nodeName == "#comment") {
if (element.nodeName === "#comment") {
// foreach is bound to a virtual element
$(element.parentElement).slimScroll({scrollBy: 0});
$(element.parentElement).slimScroll(options);
} else {
$(element).slimScroll({scrollBy: 0});
$(element).slimScroll(options);
}
}, 10);
return ko.bindingHandlers.foreach.update(element, valueAccessor(), allBindings, viewModel, bindingContext);
},
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var prepped = ko.bindingHandlers["slimScrolledForeach"].makeTemplateValueAccessor(valueAccessor);
ko.bindingHandlers["slimScrolledForeach"].slimscroll(element, prepped.slimscroll);
return ko.bindingHandlers['template']['init'](element, prepped.accessor);
},
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var prepped = ko.bindingHandlers["slimScrolledForeach"].makeTemplateValueAccessor(valueAccessor);
var options = $.extend(prepped.slimscroll, {scrollBy: 0});
ko.bindingHandlers["slimScrolledForeach"].slimscroll(element, options);
return ko.bindingHandlers['template']['update'](element, prepped.accessor, allBindings, viewModel, bindingContext);
}
};
ko.virtualElements.allowedBindings.slimScrolledForeach = true;
+2
View File
@@ -191,6 +191,8 @@ $(function() {
PNotify.prototype.options.stack.firstpos2 = 20;
PNotify.prototype.options.stack.spacing1 = 20;
PNotify.prototype.options.stack.spacing2 = 20;
PNotify.prototype.options.delay = 5000;
PNotify.prototype.options.animate_speed = "fast";
PNotify.singleButtonNotify = function(options) {
if (!options.confirm || !options.confirm.buttons || !options.confirm.buttons.length) {
@@ -67,6 +67,7 @@ $(function() {
self.dropZoneBackground = undefined;
self.dropZoneLocalBackground = undefined;
self.dropZoneSdBackground = undefined;
self.listElement = undefined;
self.ignoreUpdatedFilesEvent = false;
@@ -90,8 +91,8 @@ $(function() {
{
"name": function(a, b) {
// sorts ascending
if (a["name"].toLocaleLowerCase() < b["name"].toLocaleLowerCase()) return -1;
if (a["name"].toLocaleLowerCase() > b["name"].toLocaleLowerCase()) return 1;
if (a["display"].toLowerCase() < b["display"].toLowerCase()) return -1;
if (a["display"].toLowerCase() > b["display"].toLowerCase()) return 1;
return 0;
},
"upload": function(a, b) {
@@ -301,7 +302,7 @@ $(function() {
if (entryElement) {
// scroll to uploaded element
var entryOffset = entryElement.offsetTop;
$(".gcode_files").slimScroll({
self.listElement.slimScroll({
scrollTo: entryOffset + "px"
});
@@ -446,7 +447,7 @@ $(function() {
return;
}
self.slicing.show(file.origin, file.path, true);
self.slicing.show(file.origin, file.path, true, undefined, {display: file.display});
};
self.initSdCard = function() {
@@ -813,14 +814,7 @@ $(function() {
}
});
$(".gcode_files").slimScroll({
height: "306px",
size: "5px",
distance: "0",
railVisible: true,
alwaysVisible: true,
scrollBy: "102px"
});
self.listElement = $(".gcode_files");
self.addFolderDialog = $("#add_folder_dialog");
self.addFolderDialog.on("shown", function() {
@@ -34,6 +34,7 @@ $(function() {
self.filename = ko.observable(undefined);
self.filepath = ko.observable(undefined);
self.filedisplay = ko.observable(undefined);
self.progress = ko.observable(undefined);
self.filesize = ko.observable(undefined);
self.filepos = ko.observable(undefined);
@@ -219,11 +220,13 @@ $(function() {
self.filename(data.file.name);
self.filepath(data.file.path);
self.filesize(data.file.size);
self.filedisplay(data.file.display);
self.sd(data.file.origin == "sdcard");
} else {
self.filename(undefined);
self.filepath(undefined);
self.filesize(undefined);
self.filedisplay(undefined);
self.sd(undefined);
}
@@ -126,23 +126,28 @@ $(function() {
];
self.afterSlicing = ko.observable("none");
self.show = function(target, file, force, path) {
self.show = function(target, file, force, path, options) {
options = options || {};
if (!self.enableSlicingDialog() && !force) {
return;
}
var filename = file.substr(0, file.lastIndexOf("."));
var filename = file;
if (filename.lastIndexOf("/") != 0) {
path = path || filename.substr(0, filename.lastIndexOf("/"));
filename = filename.substr(filename.lastIndexOf("/") + 1);
}
var display = options.display || filename;
var destination = display.substr(0, display.lastIndexOf("."));
self.requestData();
self.target = target;
self.file(file);
self.path = path;
self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: filename}));
self.destinationFilename(filename);
self.title(_.sprintf(gettext("Slicing %(filename)s"), {filename: display}));
self.destinationFilename(destination);
self.printerProfile(self.printerProfiles.currentProfile());
self.afterSlicing("none");
@@ -253,7 +258,7 @@ $(function() {
return;
}
var destinationFilename = self._sanitize(self.destinationFilename());
var destinationFilename = self.destinationFilename();
var destinationExtensions = self.data[self.slicer()] && self.data[self.slicer()].extensions && self.data[self.slicer()].extensions.destination
? self.data[self.slicer()].extensions.destination
@@ -146,7 +146,7 @@ $(function() {
if (!self._printerProfileInitialized) {
self._triggerBacklog();
}
self.updatePlot(false);
self.updatePlot();
};
self.settingsViewModel.printerProfiles.currentProfileData.subscribe(function() {
self._printerProfileUpdated();
@@ -246,12 +246,12 @@ $(function() {
if (!CONFIG_TEMPERATURE_GRAPH) return;
self.temperatures = self._processTemperatureData(serverTime, data, self.temperatures);
self.updatePlot(false);
self.updatePlot();
};
self._processTemperatureHistoryData = function(serverTime, data) {
self.temperatures = self._processTemperatureData(serverTime, data);
self.updatePlot(false);
self.updatePlot();
};
self._processOffsetData = function(data) {
@@ -310,100 +310,112 @@ $(function() {
return result;
};
self.updatePlot = function(force) {
force = force == undefined ? true : force;
self.updatePlot = function() {
var graph = $("#temperature-graph");
if (graph.length) {
var data = [];
var heaterOptions = self.heaterOptions();
if (!heaterOptions) return;
if (!graph.length) return; // no graph
if (!self.plot) return; // plot not yet initialized
var maxTemps = [310/1.1];
var plotInfo = self._getPlotInfo();
if (plotInfo === undefined) return;
var showFahrenheit = self._shallShowFahrenheit();
// update the data
self.plot.setData(plotInfo.data);
self.plot.getAxes().yaxis.max = Math.max(Math.max.apply(null, plotInfo.max) * 1.1, 310);
self.updateLegend(self._replaceLegendLabel);
self.plot.draw();
};
_.each(_.keys(heaterOptions), function(type) {
if (type == "bed" && !self.hasBed()) {
return;
self._initializePlot = function(force) {
var graph = $("#temperature-graph");
if (!graph.length) return; // no graph
if (self.plot && !force) return; // already initialized
var plotInfo = self._getPlotInfo();
if (plotInfo === undefined) return;
// we don't have a plot yet, we need to set stuff up
var options = {
yaxis: {
min: 0,
max: Math.max(Math.max.apply(null, plotInfo.max) * 1.1, 310),
ticks: 10
},
xaxis: {
mode: "time",
minTickSize: [2, "minute"],
tickFormatter: function(val, axis) {
if (val === undefined || val === 0)
return ""; // we don't want to display the minutes since the epoch if not connected yet ;)
// current time in milliseconds in UTC
var timestampUtc = Date.now();
// calculate difference in milliseconds
var diff = timestampUtc - val;
// convert to minutes
var diffInMins = Math.round(diff / (60 * 1000));
if (diffInMins === 0)
return gettext("just now");
else
return "- " + diffInMins + " " + gettext("min");
}
},
legend: {
position: "sw",
noColumns: 2,
backgroundOpacity: 0
}
};
var actuals = [];
var targets = [];
if (!OctoPrint.coreui.browser.mobile) {
options["crosshair"] = { mode: "x" };
options["grid"] = { hoverable: true, autoHighlight: false };
}
if (self.temperatures[type]) {
actuals = self.temperatures[type].actual;
targets = self.temperatures[type].target;
}
self.plot = $.plot(graph, plotInfo.data, options);
};
var actualTemp = actuals && actuals.length ? formatTemperature(actuals[actuals.length - 1][1], showFahrenheit) : "-";
var targetTemp = targets && targets.length ? formatTemperature(targets[targets.length - 1][1], showFahrenheit) : "-";
self._getPlotInfo = function() {
var data = [];
var heaterOptions = self.heaterOptions();
if (!heaterOptions) return undefined;
data.push({
label: gettext("Actual") + " " + heaterOptions[type].name + ": " + actualTemp,
color: heaterOptions[type].color,
data: actuals
});
data.push({
label: gettext("Target") + " " + heaterOptions[type].name + ": " + targetTemp,
color: pusher.color(heaterOptions[type].color).tint(0.5).html(),
data: targets
});
var maxTemps = [310/1.1];
maxTemps.push(self.getMaxTemp(actuals, targets));
var showFahrenheit = self._shallShowFahrenheit();
_.each(_.keys(heaterOptions), function(type) {
if (type === "bed" && !self.hasBed()) {
return;
}
var actuals = [];
var targets = [];
if (self.temperatures[type]) {
actuals = self.temperatures[type].actual;
targets = self.temperatures[type].target;
}
var actualTemp = actuals && actuals.length ? formatTemperature(actuals[actuals.length - 1][1], showFahrenheit) : "-";
var targetTemp = targets && targets.length ? formatTemperature(targets[targets.length - 1][1], showFahrenheit) : "-";
data.push({
label: gettext("Actual") + " " + heaterOptions[type].name + ": " + actualTemp,
color: heaterOptions[type].color,
data: actuals
});
data.push({
label: gettext("Target") + " " + heaterOptions[type].name + ": " + targetTemp,
color: pusher.color(heaterOptions[type].color).tint(0.5).html(),
data: targets
});
if (!self.plot || force) {
// we don't have a plot yet, we need to set stuff up
var options = {
yaxis: {
min: 0,
max: Math.max(Math.max.apply(null, maxTemps) * 1.1, 310),
ticks: 10
},
xaxis: {
mode: "time",
minTickSize: [2, "minute"],
tickFormatter: function(val, axis) {
if (val == undefined || val == 0)
return ""; // we don't want to display the minutes since the epoch if not connected yet ;)
maxTemps.push(self.getMaxTemp(actuals, targets));
});
// current time in milliseconds in UTC
var timestampUtc = Date.now();
// calculate difference in milliseconds
var diff = timestampUtc - val;
// convert to minutes
var diffInMins = Math.round(diff / (60 * 1000));
if (diffInMins == 0)
return gettext("just now");
else
return "- " + diffInMins + " " + gettext("min");
}
},
legend: {
position: "sw",
noColumns: 2,
backgroundOpacity: 0
}
};
if (!OctoPrint.coreui.browser.mobile) {
options["crosshair"] = { mode: "x" };
options["grid"] = { hoverable: true, autoHighlight: false };
}
self.plot = $.plot(graph, data, options);
} else {
// graph already active, let's just update the data
self.plot.setData(data);
self.plot.getAxes().yaxis.max = Math.max(Math.max.apply(null, maxTemps) * 1.1, 310);
self.updateLegend(self._replaceLegendLabel);
self.plot.draw();
}
}
return {max: maxTemps, data: data};
};
self.updateLegend = function(replaceLegendLabel) {
@@ -729,10 +741,15 @@ $(function() {
};
self.onAfterTabChange = function(current, previous) {
if (current != "#temp") {
if (current !== "#temp") {
return;
}
self.updatePlot(false);
if (!self.plot) {
self._initializePlot();
} else {
self.updatePlot();
}
};
self.onStartup = function() {
+10 -10
View File
@@ -2,15 +2,15 @@
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Version: 1.3.2
* Version: 1.3.8
*
*/
(function(f){jQuery.fn.extend({slimScroll:function(g){var a=f.extend({width:"auto",height:"250px",size:"7px",color:"#000",position:"right",distance:"1px",start:"top",opacity:0.4,alwaysVisible:!1,disableFadeOut:!1,railVisible:!1,railColor:"#333",railOpacity:0.2,railDraggable:!0,railClass:"slimScrollRail",barClass:"slimScrollBar",wrapperClass:"slimScrollDiv",allowPageScroll:!1,wheelStep:20,touchScrollStep:200,borderRadius:"7px",railBorderRadius:"7px"},g);this.each(function(){function u(d){if(r){d=d||
window.event;var c=0;d.wheelDelta&&(c=-d.wheelDelta/120);d.detail&&(c=d.detail/3);f(d.target||d.srcTarget||d.srcElement).closest("."+a.wrapperClass).is(b.parent())&&m(c,!0);d.preventDefault&&!k&&d.preventDefault();k||(d.returnValue=!1)}}function m(d,f,g){k=!1;var e=d,h=b.outerHeight()-c.outerHeight();f&&(e=parseInt(c.css("top"))+d*parseInt(a.wheelStep)/100*c.outerHeight(),e=Math.min(Math.max(e,0),h),e=0<d?Math.ceil(e):Math.floor(e),c.css({top:e+"px"}));l=parseInt(c.css("top"))/(b.outerHeight()-c.outerHeight());
e=l*(b[0].scrollHeight-b.outerHeight());g&&(e=d,d=e/b[0].scrollHeight*b.outerHeight(),d=Math.min(Math.max(d,0),h),c.css({top:d+"px"}));b.scrollTop(e);b.trigger("slimscrolling",~~e);v();p()}function C(){window.addEventListener?(this.addEventListener("DOMMouseScroll",u,!1),this.addEventListener("mousewheel",u,!1)):document.attachEvent("onmousewheel",u)}function w(){s=Math.max(b.outerHeight()/b[0].scrollHeight*b.outerHeight(),D);c.css({height:s+"px"});var a=s==b.outerHeight()?"none":"block";c.css({display:a})}
function v(){w();clearTimeout(A);l==~~l?(k=a.allowPageScroll,B!=l&&b.trigger("slimscroll",0==~~l?"top":"bottom")):k=!1;B=l;s>=b.outerHeight()?k=!0:(c.stop(!0,!0).fadeIn("fast"),a.railVisible&&h.stop(!0,!0).fadeIn("fast"))}function p(){a.alwaysVisible||(A=setTimeout(function(){a.disableFadeOut&&r||x||y||(c.fadeOut("slow"),h.fadeOut("slow"))},1E3))}var r,x,y,A,z,s,l,B,D=30,k=!1,b=f(this);if(b.parent().hasClass(a.wrapperClass)){var n=b.scrollTop(),c=b.parent().find("."+a.barClass),h=b.parent().find("."+
a.railClass);w();if(f.isPlainObject(g)){if("height"in g&&"auto"==g.height){b.parent().css("height","auto");b.css("height","auto");var q=b.parent().parent().height();b.parent().css("height",q);b.css("height",q)}if("scrollTo"in g)n=parseInt(a.scrollTo);else if("scrollBy"in g)n+=parseInt(a.scrollBy);else if("destroy"in g){c.remove();h.remove();b.unwrap();return}m(n,!1,!0)}}else{a.height="auto"==g.height?b.parent().height():g.height;n=f("<div></div>").addClass(a.wrapperClass).css({position:"relative",
overflow:"hidden",width:a.width,height:a.height});b.css({overflow:"hidden",width:a.width,height:a.height});var h=f("<div></div>").addClass(a.railClass).css({width:a.size,height:"100%",position:"absolute",top:0,display:a.alwaysVisible&&a.railVisible?"block":"none","border-radius":a.railBorderRadius,background:a.railColor,opacity:a.railOpacity,zIndex:90}),c=f("<div></div>").addClass(a.barClass).css({background:a.color,width:a.size,position:"absolute",top:0,opacity:a.opacity,display:a.alwaysVisible?
"block":"none","border-radius":a.borderRadius,BorderRadius:a.borderRadius,MozBorderRadius:a.borderRadius,WebkitBorderRadius:a.borderRadius,zIndex:99}),q="right"==a.position?{right:a.distance}:{left:a.distance};h.css(q);c.css(q);b.wrap(n);b.parent().append(c);b.parent().append(h);a.railDraggable&&c.bind("mousedown",function(a){var b=f(document);y=!0;t=parseFloat(c.css("top"));pageY=a.pageY;b.bind("mousemove.slimscroll",function(a){currTop=t+a.pageY-pageY;c.css("top",currTop);m(0,c.position().top,!1)});
b.bind("mouseup.slimscroll",function(a){y=!1;p();b.unbind(".slimscroll")});return!1}).bind("selectstart.slimscroll",function(a){a.stopPropagation();a.preventDefault();return!1});h.hover(function(){v()},function(){p()});c.hover(function(){x=!0},function(){x=!1});b.hover(function(){r=!0;v();p()},function(){r=!1;p()});b.bind("touchstart",function(a,b){a.originalEvent.touches.length&&(z=a.originalEvent.touches[0].pageY)});b.bind("touchmove",function(b){k||b.originalEvent.preventDefault();b.originalEvent.touches.length&&
(m((z-b.originalEvent.touches[0].pageY)/a.touchScrollStep,!0),z=b.originalEvent.touches[0].pageY)});w();"bottom"===a.start?(c.css({top:b.outerHeight()-c.outerHeight()}),m(0,!0)):"top"!==a.start&&(m(f(a.start).position().top,null,!0),a.alwaysVisible||c.hide());C()}});return this}});jQuery.fn.extend({slimscroll:jQuery.fn.slimScroll})})(jQuery);
(function(e){e.fn.extend({slimScroll:function(f){var a=e.extend({width:"auto",height:"250px",size:"7px",color:"#000",position:"right",distance:"1px",start:"top",opacity:.4,alwaysVisible:!1,disableFadeOut:!1,railVisible:!1,railColor:"#333",railOpacity:.2,railDraggable:!0,railClass:"slimScrollRail",barClass:"slimScrollBar",wrapperClass:"slimScrollDiv",allowPageScroll:!1,wheelStep:20,touchScrollStep:200,borderRadius:"7px",railBorderRadius:"7px"},f);this.each(function(){function v(d){if(r){d=d||window.event;
var c=0;d.wheelDelta&&(c=-d.wheelDelta/120);d.detail&&(c=d.detail/3);e(d.target||d.srcTarget||d.srcElement).closest("."+a.wrapperClass).is(b.parent())&&n(c,!0);d.preventDefault&&!k&&d.preventDefault();k||(d.returnValue=!1)}}function n(d,g,e){k=!1;var f=b.outerHeight()-c.outerHeight();g&&(g=parseInt(c.css("top"))+d*parseInt(a.wheelStep)/100*c.outerHeight(),g=Math.min(Math.max(g,0),f),g=0<d?Math.ceil(g):Math.floor(g),c.css({top:g+"px"}));l=parseInt(c.css("top"))/(b.outerHeight()-c.outerHeight());g=
l*(b[0].scrollHeight-b.outerHeight());e&&(g=d,d=g/b[0].scrollHeight*b.outerHeight(),d=Math.min(Math.max(d,0),f),c.css({top:d+"px"}));b.scrollTop(g);b.trigger("slimscrolling",~~g);w();p()}function x(){u=Math.max(b.outerHeight()/b[0].scrollHeight*b.outerHeight(),30);c.css({height:u+"px"});var a=u==b.outerHeight()?"none":"block";c.css({display:a})}function w(){x();clearTimeout(B);l==~~l?(k=a.allowPageScroll,C!=l&&b.trigger("slimscroll",0==~~l?"top":"bottom")):k=!1;C=l;u>=b.outerHeight()?k=!0:(c.stop(!0,
!0).fadeIn("fast"),a.railVisible&&m.stop(!0,!0).fadeIn("fast"))}function p(){a.alwaysVisible||(B=setTimeout(function(){a.disableFadeOut&&r||y||z||(c.fadeOut("slow"),m.fadeOut("slow"))},1E3))}var r,y,z,B,A,u,l,C,k=!1,b=e(this);if(b.parent().hasClass(a.wrapperClass)){var q=b.scrollTop(),c=b.siblings("."+a.barClass),m=b.siblings("."+a.railClass);x();if(e.isPlainObject(f)){if("height"in f&&"auto"==f.height){b.parent().css("height","auto");b.css("height","auto");var h=b.parent().parent().height();b.parent().css("height",
h);b.css("height",h)}else"height"in f&&(h=f.height,b.parent().css("height",h),b.css("height",h));if("scrollTo"in f)q=parseInt(a.scrollTo);else if("scrollBy"in f)q+=parseInt(a.scrollBy);else if("destroy"in f){c.remove();m.remove();b.unwrap();return}n(q,!1,!0)}}else if(!(e.isPlainObject(f)&&"destroy"in f)){a.height="auto"==a.height?b.parent().height():a.height;q=e("<div></div>").addClass(a.wrapperClass).css({position:"relative",overflow:"hidden",width:a.width,height:a.height});b.css({overflow:"hidden",
width:a.width,height:a.height});var m=e("<div></div>").addClass(a.railClass).css({width:a.size,height:"100%",position:"absolute",top:0,display:a.alwaysVisible&&a.railVisible?"block":"none","border-radius":a.railBorderRadius,background:a.railColor,opacity:a.railOpacity,zIndex:90}),c=e("<div></div>").addClass(a.barClass).css({background:a.color,width:a.size,position:"absolute",top:0,opacity:a.opacity,display:a.alwaysVisible?"block":"none","border-radius":a.borderRadius,BorderRadius:a.borderRadius,MozBorderRadius:a.borderRadius,
WebkitBorderRadius:a.borderRadius,zIndex:99}),h="right"==a.position?{right:a.distance}:{left:a.distance};m.css(h);c.css(h);b.wrap(q);b.parent().append(c);b.parent().append(m);a.railDraggable&&c.bind("mousedown",function(a){var b=e(document);z=!0;t=parseFloat(c.css("top"));pageY=a.pageY;b.bind("mousemove.slimscroll",function(a){currTop=t+a.pageY-pageY;c.css("top",currTop);n(0,c.position().top,!1)});b.bind("mouseup.slimscroll",function(a){z=!1;p();b.unbind(".slimscroll")});return!1}).bind("selectstart.slimscroll",
function(a){a.stopPropagation();a.preventDefault();return!1});m.hover(function(){w()},function(){p()});c.hover(function(){y=!0},function(){y=!1});b.hover(function(){r=!0;w();p()},function(){r=!1;p()});b.bind("touchstart",function(a,b){a.originalEvent.touches.length&&(A=a.originalEvent.touches[0].pageY)});b.bind("touchmove",function(b){k||b.originalEvent.preventDefault();b.originalEvent.touches.length&&(n((A-b.originalEvent.touches[0].pageY)/a.touchScrollStep,!0),A=b.originalEvent.touches[0].pageY)});
x();"bottom"===a.start?(c.css({top:b.outerHeight()-c.outerHeight()}),n(0,!0)):"top"!==a.start&&(n(e(a.start).position().top,null,!0),a.alwaysVisible||c.hide());window.addEventListener?(this.addEventListener("DOMMouseScroll",v,!1),this.addEventListener("mousewheel",v,!1)):document.attachEvent("onmousewheel",v)}});return this}});e.fn.extend({slimscroll:e.fn.slimScroll})})(jQuery);
+6 -2
View File
@@ -673,7 +673,7 @@ ul.dropdown-menu li a {
#files {
.gcode_files {
@padding: 5px;
@scrollBar: 5px;
@scrollBar: 10px;
@line-height: 20px;
padding-right: @scrollBar + 2px;
@@ -693,11 +693,15 @@ ul.dropdown-menu li a {
word-break: break-all;
}
.uploaded, .size, .additionalInfo {
.internal, .uploaded, .size, .additionalInfo {
font-size: 85%;
color: #999;
}
.internal {
word-break: break-all;
}
.action-buttons {
position: absolute;
bottom: @padding;
+7 -4
View File
@@ -7,12 +7,13 @@
<div class="back-path"><small class="muted">{{ _('Currently in') }} <span data-bind="text: currentPath"></span></small></div>
</div>
<!-- ko slimScrolledForeach: filesAndFolders -->
<!-- ko slimScrolledForeach: {data: filesAndFolders, slimscroll: {height: "306px", size: "10px", distance: 0, railVisible: true, alwaysVisible: true, scrollBy: "102px"} } -->
<div class="entry" data-bind="attr: { id: $root.getEntryId($data) }, template: { name: $root.templateFor($data), data: $data }, css: $data.type"></div>
<!-- /ko -->
<script type="text/html" id="files_template_machinecode">
<div class="title clickable" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: $root.getSuccessClass($data), style: { 'font-weight': $root.listHelper.isSelected($data) ? 'bold' : 'normal' }, text: name"></div>
<div class="title clickable" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: $root.getSuccessClass($data), style: { 'font-weight': $root.listHelper.isSelected($data) ? 'bold' : 'normal' }, text: display"></div>
<div class="internal" data-bind="visible: display && name != display">{{ _('Internal') }}: <span data-bind="text: name"></span></div>
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date)"></span></div>
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
<div class="additionalInfo hide" data-bind="html: $root.getAdditionalData($data)"></div>
@@ -26,7 +27,8 @@
</script>
<script type="text/html" id="files_template_model">
<div class="title muted" data-bind="text: name"></div>
<div class="title muted" data-bind="text: display"></div>
<div class="internal" data-bind="visible: name != display">{{ _('Internal') }}: <span data-bind="text: name"></span></div>
<div class="uploaded">{{ _('Uploaded') }}: <span data-bind="text: formatTimeAgo(date)"></span></div>
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
<div class="btn-group action-buttons">
@@ -37,7 +39,8 @@
</script>
<script type="text/html" id="files_template_folder">
<div class="title clickable" data-bind="click: $root.changeFolder, style: { 'font-weight': $root.listHelper.isSelected($data) ? 'bold' : 'normal' }"><i class="fa fa-folder-open"></i> <span data-bind="text: name"></span></div>
<div class="title clickable" data-bind="click: $root.changeFolder, style: { 'font-weight': $root.listHelper.isSelected($data) ? 'bold' : 'normal' }"><i class="fa fa-folder-open"></i> <span data-bind="text: display"></span></div>
<div class="internal" data-bind="visible: name != display">{{ _('Internal') }}: <span data-bind="text: name"></span></div>
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
<div class="btn-group action-buttons">
<div class="btn btn-mini" data-bind="visible: $root.loginState.hasPermissionKo($root.access.permissions.DELETE), click: function(data, event) { if ($root.enableRemove($data)) { $root.removeFolder($data, event); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove') }}"><i class="fa fa-trash-o"></i></div>
+1 -1
View File
@@ -1,6 +1,6 @@
<span title="{{ _('Current printer state') }}">{{ _('State') }}</span>: <strong data-bind="text: stateString"></strong><br>
<hr>
<span title="{{ _('Name of file currently selected for printing') }}">{{ _('File') }}</span>: <strong data-bind="text: filename, attr: {title: filepath}"></strong>&nbsp;<strong data-bind="visible: sd">(SD)</strong><br>
<span title="{{ _('Name of file currently selected for printing') }}">{{ _('File') }}</span>: <strong data-bind="text: filedisplay, attr: {title: filepath}"></strong>&nbsp;<strong data-bind="visible: sd">(SD)</strong><br>
<span title="{{ _('Current timelapse configuration') }}">{{ _('Timelapse') }}</span>: <strong data-bind="text: timelapseString"></strong><br>
<!-- ko foreach: filament -->
<span data-bind="text: 'Filament (' + name() + '): ', title: 'Filament usage for ' + name()"></span><strong data-bind="text: formatFilament(data())"></strong><br>
+5 -2
View File
@@ -140,12 +140,14 @@ def get_unrendered_timelapses():
def delete_unrendered_timelapse(name):
global _cleanup_lock
pattern = "{}*.jpg".format(util.glob_escape(name))
basedir = settings().getBaseFolder("timelapse_tmp")
with _cleanup_lock:
for entry in scandir(basedir):
try:
if fnmatch.fnmatch(entry.name, "{}*.jpg".format(name)):
if fnmatch.fnmatch(entry.name, pattern):
os.remove(entry.path)
except:
if logging.getLogger(__name__).isEnabledFor(logging.DEBUG):
@@ -193,7 +195,8 @@ def delete_old_unrendered_timelapses():
if prefix in prefixes_to_clean:
continue
if entry.stat().st_mtime < cutoff:
# delete if both creation and modification time are older than the cutoff
if max(entry.stat().st_ctime, entry.stat().st_mtime) < cutoff:
prefixes_to_clean.append(prefix)
except:
if logging.getLogger(__name__).isEnabledFor(logging.DEBUG):
+27 -2
View File
@@ -911,8 +911,10 @@ def is_hidden_path(path):
# we define a None path as not hidden here
return False
path = to_unicode(path)
filename = os.path.basename(path)
if filename.startswith("."):
if filename.startswith(u"."):
# filenames starting with a . are hidden
return True
@@ -921,7 +923,7 @@ def is_hidden_path(path):
# attribute via the windows api
try:
import ctypes
attrs = ctypes.windll.kernel32.GetFileAttributesW(unicode(path))
attrs = ctypes.windll.kernel32.GetFileAttributesW(path)
assert attrs != -1 # INVALID_FILE_ATTRIBUTES == -1
return bool(attrs & 2) # FILE_ATTRIBUTE_HIDDEN == 2
except (AttributeError, AssertionError):
@@ -931,6 +933,29 @@ def is_hidden_path(path):
return False
try:
from glob import escape
glob_escape = escape
except ImportError:
# no glob.escape - we need to implement our own
_glob_escape_check = re.compile("([*?[])")
_glob_escape_check_bytes = re.compile(b"([*?[])")
def glob_escape(pathname):
"""
Ported from Python 3.4
See https://github.com/python/cpython/commit/fd32fffa5ada8b8be8a65bd51b001d989f99a3d3
"""
drive, pathname = os.path.splitdrive(pathname)
if isinstance(pathname, bytes):
pathname = _glob_escape_check_bytes.sub(br"[\1]", pathname)
else:
pathname = _glob_escape_check.sub(r"[\1]", pathname)
return drive + pathname
class RepeatedTimer(threading.Thread):
"""
This class represents an action that should be run repeatedly in an interval. It is similar to python's
+5 -2
View File
@@ -111,8 +111,11 @@ class Stk500v2(ispBase.IspBase):
state = 'Start'
checksum = 0
while True:
s = self.serial.read()
if len(s) < 1:
for _ in range(0, 5):
s = self.serial.read()
if len(s) > 0:
break
else:
raise ispBase.IspError("Timeout")
b = struct.unpack(">B", s)[0]
checksum ^= b
+1 -1
View File
@@ -1868,7 +1868,7 @@ class MachineCom(object):
elif len(potentials) > 1:
programmer = stk500v2.Stk500v2()
for p in serialList():
for p in potentials:
serial_obj = None
try:
+49 -5
View File
@@ -167,7 +167,11 @@ class FileManagerTest(unittest.TestCase):
file_path = self.file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL, "test.gcode", wrapper)
self.assertEqual(("", "test.gcode"), file_path)
self.local_storage.add_file.assert_called_once_with("test.gcode", wrapper, printer_profile=test_profile, allow_overwrite=False, links=None)
self.local_storage.add_file.assert_called_once_with("test.gcode", wrapper,
printer_profile=test_profile,
allow_overwrite=False,
links=None,
display=None)
expected_events = [mock.call(octoprint.filemanager.Events.FILE_ADDED, dict(storage=octoprint.filemanager.FileDestinations.LOCAL,
name="test.gcode",
@@ -176,6 +180,26 @@ class FileManagerTest(unittest.TestCase):
mock.call(octoprint.filemanager.Events.UPDATED_FILES, dict(type="printables"))]
self.fire_event.call_args_list = expected_events
def test_add_file_display(self):
wrapper = object()
self.local_storage.add_file.return_value = ("", "test.gcode")
self.local_storage.path_on_disk.return_value = "prefix/test.gcode"
self.local_storage.split_path.return_value = ("", "test.gcode")
test_profile = dict(id="_default", name="My Default Profile")
self.printer_profile_manager.get_current_or_default.return_value = test_profile
file_path = self.file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL, "test.gcode", wrapper,
display=u"täst.gcode")
self.assertEqual(("", "test.gcode"), file_path)
self.local_storage.add_file.assert_called_once_with("test.gcode", wrapper,
printer_profile=test_profile,
allow_overwrite=False,
links=None,
display=u"täst.gcode")
def test_remove_file(self):
self.local_storage.path_on_disk.return_value = "prefix/test.gcode"
self.local_storage.split_path.return_value = ("", "test.gcode")
@@ -198,7 +222,10 @@ class FileManagerTest(unittest.TestCase):
folder_path = self.file_manager.add_folder(octoprint.filemanager.FileDestinations.LOCAL, "test_folder")
self.assertEqual(("", "test_folder"), folder_path)
self.local_storage.add_folder.assert_called_once_with("test_folder", ignore_existing=True)
self.local_storage.add_folder.assert_called_once_with("test_folder",
ignore_existing=True,
display=None)
expected_events = [mock.call(octoprint.filemanager.Events.FOLDER_ADDED, dict(storage=octoprint.filemanager.FileDestinations.LOCAL,
name="test_folder",
path="test_folder")),
@@ -213,7 +240,20 @@ class FileManagerTest(unittest.TestCase):
self.fail("Expected an exception to occur!")
except RuntimeError as e:
self.assertEqual("already there", e.message)
self.local_storage.add_folder.assert_called_once_with("test_folder", ignore_existing=False)
self.local_storage.add_folder.assert_called_once_with("test_folder", ignore_existing=False, display=None)
def test_add_folder_display(self):
self.local_storage.add_folder.side_effect = RuntimeError("already there")
try:
self.file_manager.add_folder(octoprint.filemanager.FileDestinations.LOCAL, "test_folder",
display=u"täst_folder")
self.fail("Expected an exception to occur!")
except RuntimeError as e:
self.assertEqual("already there", e.message)
self.local_storage.add_folder.assert_called_once_with("test_folder",
ignore_existing=True,
display=u"täst_folder")
def test_remove_folder(self):
self.local_storage.split_path.return_value = ("", "test_folder")
@@ -409,7 +449,7 @@ class FileManagerTest(unittest.TestCase):
self.local_storage.split_path.side_effect = split_path
# mock add_file method on local storage
def add_file(path, file_obj, printer_profile=None, links=None, allow_overwrite=False):
def add_file(path, file_obj, printer_profile=None, links=None, allow_overwrite=False, display=None):
file_obj.save("prefix/" + path)
return path
self.local_storage.add_file.side_effect = add_file
@@ -447,7 +487,11 @@ class FileManagerTest(unittest.TestCase):
# assert that model links were added
expected_links = [("model", dict(name="source.file"))]
self.local_storage.add_file.assert_called_once_with("dest.file", mock.ANY, printer_profile=expected_printer_profile, allow_overwrite=True, links=expected_links)
self.local_storage.add_file.assert_called_once_with("dest.file", mock.ANY,
printer_profile=expected_printer_profile,
allow_overwrite=True,
links=expected_links,
display=None)
# assert that the generated gcode was manipulated as required
expected_atomic_write_calls = [mock.call("prefix/dest.file", "wb")]
+123 -14
View File
@@ -79,6 +79,13 @@ class LocalStorageTest(unittest.TestCase):
self._add_and_verify_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL, overwrite=True)
def test_add_file_with_display(self):
stl_name = self._add_and_verify_file("bp_case.stl", "bp_case.stl", FILE_BP_CASE_STL, display=u"bp_cäse.stl")
stl_metadata = self.storage.get_metadata(stl_name)
self.assertIsNotNone(stl_metadata)
self.assertDictContainsSubset(dict(display=u"bp_cäse.stl"), stl_metadata)
def test_add_file_with_web(self):
import time
href = "http://www.example.com"
@@ -182,6 +189,48 @@ class LocalStorageTest(unittest.TestCase):
self.assertIsNone(after_stl_metadata)
self.assertIsNotNone(copied_metadata)
self.assertDictEqual(before_stl_metadata, copied_metadata)
def test_copy_file_new_display(self):
self._add_file("bp_case.stl", FILE_BP_CASE_STL)
try:
self.storage.copy_file("bp_case.stl", u"bp_cäse.stl")
self.fail("Expected an exception")
except StorageError as e:
self.assertEqual(e.code, StorageError.SOURCE_EQUALS_DESTINATION)
def test_move_file_new_display(self):
self._add_file("bp_case.stl", FILE_BP_CASE_STL)
before_metadata = self.storage.get_metadata("bp_case.stl")
self.storage.move_file("bp_case.stl", u"bp_cäse.stl")
after_metadata = self.storage.get_metadata("bp_case.stl")
self.assertTrue(os.path.isfile(os.path.join(self.basefolder, "bp_case.stl")))
self.assertIsNotNone(before_metadata)
self.assertIsNotNone(after_metadata)
self.assertDictContainsSubset(dict(display=u"bp_cäse.stl"), after_metadata)
@data("copy_file", "move_file")
def test_copy_move_file_different_display(self, operation):
self._add_file("bp_case.stl", FILE_BP_CASE_STL, display=u"bp_cäse.stl")
before_metadata = self.storage.get_metadata("bp_case.stl")
getattr(self.storage, operation)("bp_case.stl", "test.stl")
after_metadata = self.storage.get_metadata("test.stl")
self.assertIsNotNone(before_metadata)
self.assertIsNotNone(after_metadata)
self.assertNotIn("display", after_metadata)
@data("copy_file", "move_file")
def test_copy_move_file_same(self, operation):
self._add_file("bp_case.stl", FILE_BP_CASE_STL)
try:
getattr(self.storage, operation)("bp_case.stl", "bp_case.stl")
self.fail("Expected an exception")
except StorageError as e:
self.assertEqual(e.code, StorageError.SOURCE_EQUALS_DESTINATION)
@data("copy_file", "move_file")
def test_copy_move_file_missing_source(self, operation):
@@ -215,6 +264,12 @@ class LocalStorageTest(unittest.TestCase):
def test_add_folder(self):
self._add_and_verify_folder("test", "test")
def test_add_folder_with_display(self):
self._add_and_verify_folder("test", "test", display=u"täst")
metadata = self.storage.get_metadata("test")
self.assertIsNotNone(metadata)
self.assertDictContainsSubset(dict(display=u"täst"), metadata)
def test_add_subfolder(self):
folder_name = self._add_and_verify_folder("folder with some spaces", "folder_with_some_spaces")
@@ -247,12 +302,16 @@ class LocalStorageTest(unittest.TestCase):
self.assertFalse(os.path.exists(os.path.join(self.basefolder, empty_folder)))
self.assertFalse(os.path.isdir(os.path.join(self.basefolder, empty_folder)))
def test_remove_folder_with_metadata(self):
content_folder = self._add_and_verify_folder("content", "content")
other_stl_name = self._add_and_verify_file((content_folder, "crazyradio.stl"), content_folder + "/crazyradio.stl", FILE_CRAZYRADIO_STL)
self.storage.remove_file(other_stl_name)
self.storage.remove_folder(content_folder, recursive=False)
def test_remove_folder_with_display(self):
self._add_folder("folder", display=u"földer")
before_metadata = self.storage.get_metadata("folder")
self.storage.remove_folder("folder")
after_metadata = self.storage.get_metadata("folder")
self.assertIsNotNone(before_metadata)
self.assertDictEqual(before_metadata, dict(display=u"földer"))
self.assertIsNone(after_metadata)
def test_copy_folder(self):
self._add_folder("source")
@@ -296,6 +355,46 @@ class LocalStorageTest(unittest.TestCase):
self.assertIsNotNone(copied_metadata)
self.assertDictEqual(before_source_metadata, copied_metadata)
def test_copy_folder_new_display(self):
self._add_folder("folder")
try:
self.storage.copy_folder("folder", u"földer")
self.fail("Expected an exception")
except StorageError as e:
self.assertEqual(e.code, StorageError.SOURCE_EQUALS_DESTINATION)
def test_move_folder_new_display(self):
self._add_folder("folder")
before_metadata = self.storage.get_metadata("folder")
self.storage.move_folder("folder", u"földer")
after_metadata = self.storage.get_metadata("folder")
self.assertIsNone(before_metadata)
self.assertIsNotNone(after_metadata)
self.assertDictEqual(after_metadata, dict(display=u"földer"))
@data("copy_folder", "move_folder")
def test_copy_move_folder_different_display(self, operation):
self._add_folder("folder", display=u"földer")
before_metadata = self.storage.get_metadata("folder")
getattr(self.storage, operation)("folder", "test")
after_metadata = self.storage.get_metadata("test")
self.assertIsNotNone(before_metadata)
self.assertDictEqual(before_metadata, dict(display=u"földer"))
self.assertIsNone(after_metadata)
@data("copy_folder", "move_folder")
def test_copy_move_folder_same(self, operation):
self._add_folder("folder")
try:
getattr(self.storage, operation)("folder", "folder")
self.fail("Expected an exception")
except StorageError as e:
self.assertEqual(e.code, StorageError.SOURCE_EQUALS_DESTINATION)
@data("copy_folder", "move_folder")
def test_copy_move_folder_missing_source(self, operation):
try:
@@ -524,13 +623,23 @@ class LocalStorageTest(unittest.TestCase):
self.assertEqual(expected_path, actual_path)
self.assertEqual(expected_name, actual_name)
def _add_and_verify_file(self, path, expected_path, file_object, links=None, overwrite=False):
@data(
(u"test", u"test"),
(u"\u2764", u"red_heart"),
(u"\u2764\ufe00", u"red_heart")
)
@unpack
def test_slugify(self, input, expected):
output = LocalFileStorage._slugify(input)
self.assertEqual(output, expected)
def _add_and_verify_file(self, path, expected_path, file_object, links=None, overwrite=False, display=None):
"""Adds a file to the storage and verifies the sanitized path."""
sanitized_path = self._add_file(path, file_object, links=links, overwrite=overwrite)
sanitized_path = self._add_file(path, file_object, links=links, overwrite=overwrite, display=display)
self.assertEqual(expected_path, sanitized_path)
return sanitized_path
def _add_file(self, path, file_object, links=None, overwrite=False):
def _add_file(self, path, file_object, links=None, overwrite=False, display=None):
"""
Adds a file to the storage.
@@ -539,7 +648,7 @@ class LocalStorageTest(unittest.TestCase):
Returns sanitized path.
"""
sanitized_path = self.storage.add_file(path, file_object, links=links, allow_overwrite=overwrite)
sanitized_path = self.storage.add_file(path, file_object, links=links, allow_overwrite=overwrite, display=display)
split_path = sanitized_path.split("/")
if len(split_path) == 1:
@@ -565,13 +674,13 @@ class LocalStorageTest(unittest.TestCase):
return sanitized_path
def _add_and_verify_folder(self, path, expected_path):
def _add_and_verify_folder(self, path, expected_path, display=None):
"""Adds a folder to the storage and verifies sanitized path."""
sanitized_path = self._add_folder(path)
sanitized_path = self._add_folder(path, display=display)
self.assertEqual(expected_path, sanitized_path)
return sanitized_path
def _add_folder(self, path):
def _add_folder(self, path, display=None):
"""
Adds a folder to the storage.
@@ -579,7 +688,7 @@ class LocalStorageTest(unittest.TestCase):
Returns sanitized path.
"""
sanitized_path = self.storage.add_folder(path)
sanitized_path = self.storage.add_folder(path, display=display)
self.assertTrue(os.path.isdir(os.path.join(self.basefolder, os.path.join(*sanitized_path.split("/")))))
return sanitized_path
+42
View File
@@ -358,3 +358,45 @@ class IsHiddenPathTest(unittest.TestCase):
def test_is_hidden_path(self, path_id, expected):
path = getattr(self, path_id) if path_id is not None else None
self.assertEqual(octoprint.util.is_hidden_path(path), expected)
try:
from glob import escape
except ImportError:
# no glob.escape - tests for our ported implementation
@ddt.ddt
class GlobEscapeTest(unittest.TestCase):
"""
Ported from Python 3.4
See https://github.com/python/cpython/commit/fd32fffa5ada8b8be8a65bd51b001d989f99a3d3
"""
@ddt.data(
("abc", "abc"),
("[", "[[]"),
("?", "[?]"),
("*", "[*]"),
("[[_/*?*/_]]", "[[][[]_/[*][?][*]/_]]"),
("/[[_/*?*/_]]/", "/[[][[]_/[*][?][*]/_]]/")
)
@ddt.unpack
def test_glob_escape(self, text, expected):
actual = octoprint.util.glob_escape(text)
self.assertEqual(actual, expected)
@ddt.data(
("?:?", "?:[?]"),
("*:*", "*:[*]"),
(r"\\?\c:\?", r"\\?\c:\[?]"),
(r"\\*\*\*", r"\\*\*\[*]"),
("//?/c:/?", "//?/c:/[?]"),
("//*/*/*", "//*/*/[*]")
)
@ddt.unpack
@unittest.skipUnless(sys.platform == "win32", "Win32 specific test")
def test_glob_escape_windows(self, text, expected):
actual = octoprint.util.glob_escape(text)
self.assertEqual(actual, expected)