Merge branch 'devel' into dev/firstRunWizard
Conflicts: src/octoprint/static/js/app/viewmodels/settings.js
This commit is contained in:
commit
d97f92ea3d
58 files changed
+12451
-596
No files matched your search
+3
-3
@@ -10,10 +10,10 @@
|
||||
# master shall not use the lookup table, only tags
|
||||
master
|
||||
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.2.4
|
||||
# maintenance is currently the branch for preparation of maintenance release 1.2.5
|
||||
# so are any fix/... branches
|
||||
maintenance 1.2.4 3761995aff94acf32495556730f133a1626245b3
|
||||
fix/.* 1.2.4 3761995aff94acf32495556730f133a1626245b3
|
||||
maintenance 1.2.5 9a6099ffc2982455d631c9d68a3273d9eb55885c
|
||||
fix/.* 1.2.5 9a6099ffc2982455d631c9d68a3273d9eb55885c
|
||||
|
||||
# every other branch is a development branch and thus gets resolved to 1.3.0-dev for now
|
||||
.* 1.3.0 198d3450d94be1a2 pep440-dev
|
||||
@@ -51,6 +51,8 @@ date of first contribution):
|
||||
* [Mark Walker](https://github.com/markwal)
|
||||
* [Lucas Clemente](https://github.com/lucas-clemente)
|
||||
* [Andrew Erickson](https://github.com/aerickson)
|
||||
* [Nicanor Romero Venier](https://github.com/nicanor-romero)
|
||||
* [Thomas Hou](https://github.com/masterhou)
|
||||
|
||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||
|
||||
+59
-1
@@ -11,11 +11,69 @@
|
||||
Manager install and uninstall dialog.
|
||||
* Allow hiding plugins from Plugin Manager via ``config.yaml``.
|
||||
* Cura Plugin: "Test" button to check if path to cura engine is valid.
|
||||
* Cura Plugin: Now also supports 15.06 version of CuraEngine.
|
||||
* New central configuration option for commands to restart OctoPrint and to
|
||||
restart and shut down the system OctoPrint is running on. This allows plugins
|
||||
(like the Software Update Plugin or the Plugin Manager) and core functionality
|
||||
to perform these common administrative tasks without the user needing to define
|
||||
everything redundantly.
|
||||
* `pip` helper now adjusts `pip install` parameters corresponding to detected
|
||||
`pip` version:
|
||||
* Removes `--process-dependency-links` when it's not needed
|
||||
* Adds `--no-use-wheel` when it's needed
|
||||
* Detects and reports on completely broken versions
|
||||
* Better tracking of printer connection state for plugins and scripts:
|
||||
* Introduced three new Events `Connecting`, `Disconnecting` and
|
||||
`PrinterStateChanged`.
|
||||
* Introduced new GCODE script `beforePrinterDisconnected` which will get sent
|
||||
before a (controlled) disconnect from the printer. This can be used to send
|
||||
some final commands to the printer before the connection goes down, e.g.
|
||||
`M117 Bye from OctoPrint`.
|
||||
* The communication layer will now wait for the send queue to be fully processed
|
||||
before disconnecting from the printer for good. This way it is ensured that
|
||||
the `beforePrinterDisconnected` script or any further GCODE injected into it
|
||||
will actually get sent.
|
||||
* Additional baud rates to allow for connecting can now be specified along side
|
||||
additional serial ports via the settings dialog and the configuration file.
|
||||
* Documentation improvements
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* It's not possible anymore to select files that are not machinecode files (e.g.
|
||||
GCODE) for printing on the file API.
|
||||
* Changes to a user's personal settings via the UI now propagate across sessions.
|
||||
|
||||
## 1.2.4 (2015-07-23)
|
||||
|
||||
### Improvements
|
||||
|
||||
* `RepeatedTimer` now defaults to `daemon` set to `True`. This makes sure
|
||||
plugins using it don't have to remember to set that flag themselves in
|
||||
order for the server to properly shut down when timers are still active.
|
||||
* Fixed a typo in the docs about `logging.yaml` (top level element is
|
||||
`loggers`, not `logger`).
|
||||
* Support for plugins with external dependencies (`dependency_links` in
|
||||
setuptools), interesting for plugin authors who need to depend on Python
|
||||
libraries that are (not yet) available on PyPI.
|
||||
* Better resilience against errors within plugins.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Do not cache web page when running for the first time, to avoid caching
|
||||
the first run dialog popup along side with it. This should solve issues
|
||||
people were having when configuring OctoPrint for the first time, then
|
||||
reloading the page without clearing the cache, being again prompted with
|
||||
the dialog with no chance to clear it.
|
||||
* Fix/workaround for occasional white panes in settings dialog on Safari 8,
|
||||
which appears to have an issue with fixed positioning.
|
||||
* Fixed form field truncation in upload requests that could lead to problems
|
||||
when trying to import Cura profiles with names longer than 28 characters.
|
||||
* Fixed webcam rotation for timelapse rendering.
|
||||
* Fixed user settings not reaching the editor in the frontend.
|
||||
* Notifications that are in process of being closed don't open again on
|
||||
mouse over (that was actually more of an unwanted feature).
|
||||
|
||||
([Commits](https://github.com/foosel/OctoPrint/compare/1.2.3...1.2.4))
|
||||
|
||||
## 1.2.3 (2015-07-09)
|
||||
|
||||
@@ -225,7 +283,7 @@
|
||||
changed under "Temperatures" in the Settings ([#343](https://github.com/foosel/OctoPrint/issues/343)).
|
||||
* High-DPI support for the GCode viewer ([#837](https://github.com/foosel/OctoPrint/issues/837)).
|
||||
* Stop websocket connections from multiplying ([#888](https://github.com/foosel/OctoPrint/pull/888)).
|
||||
* New setting to rotate webcam by 90° counter clockwise ([#895](https://github.com/foosel/OctoPrint/issues/895) and
|
||||
* New setting to rotate webcam by 90° counter clockwise ([#895](https://github.com/foosel/OctoPrint/issues/895) and
|
||||
[#906](https://github.com/foosel/OctoPrint/pull/906))
|
||||
* System commands now be set to a) run asynchronized by setting their `async` property to `true` and b) to ignore their
|
||||
result by setting their `ignore` property to `true`.
|
||||
|
||||
@@ -1,17 +1,35 @@
|
||||
OctoPrint
|
||||
=========
|
||||
|
||||
[](https://flattr.com/submit/auto?user_id=foosel&url=https://github.com/foosel/OctoPrint&title=OctoPrint&language=&tags=github&category=software)
|
||||
|
||||
OctoPrint provides a responsive web interface for controlling a 3D printer (RepRap, Ultimaker, ...). It is Free Software
|
||||
OctoPrint provides a snappy web interface for controlling a 3D printer (RepRap, Ultimaker, ...). It is Free Software
|
||||
and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html).
|
||||
|
||||
Its website can be found at [octoprint.org](http://octoprint.org).
|
||||
|
||||
The documentation is located at [docs.octoprint.org](http://docs.octoprint.org).
|
||||
|
||||
You are currently looking at the source code repository of OctoPrint. If you already installed it
|
||||
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
|
||||
want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki)
|
||||
might be of more interest for you. You might also want to subscribe to [the mailing list](https://groups.google.com/group/octoprint)
|
||||
or the [G+ Community](https://plus.google.com/communities/102771308349328485741) where there are other active users who might be
|
||||
able to help you with any questions you might have.
|
||||
|
||||
Contributing
|
||||
------------
|
||||
|
||||
Please see the project's [Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md).
|
||||
Contributions of all kinds are welcome, not only in the form of code but also with regards to the
|
||||
[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), support
|
||||
of other users in the [bug tracker](https://github.com/foosel/OctoPrint/issues),
|
||||
[the Mailinglist](https://groups.google.com/group/octoprint) or
|
||||
[the G+ Community](https://plus.google.com/communities/102771308349328485741).
|
||||
|
||||
If you think something is bad as it is about OctoPrint or its documentation the way it is, please help
|
||||
in any way to make it better instead of just complaining about it -- this is an Open Source Project
|
||||
after all :)
|
||||
|
||||
For information about how to go about contributions of any kind, please see the project's
|
||||
[Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md).
|
||||
|
||||
Installation
|
||||
------------
|
||||
@@ -21,6 +39,11 @@ Installation instructions for installing from source for different operating sys
|
||||
If you want to run OctoPrint on a Raspberry Pi you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi)
|
||||
which is a custom SD card image that includes OctoPrint plus dependencies.
|
||||
|
||||
After installation, please make sure you follow the first-run wizard and set up
|
||||
access control as necessary. If you want to not only be notified about new
|
||||
releases but also be able to automatically upgrade to them from within
|
||||
OctoPrint, take a look [at the documentation of the Software Update Plugin](https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update#making-octoprint-updateable-on-existing-installations).
|
||||
|
||||
Dependencies
|
||||
------------
|
||||
|
||||
@@ -36,7 +59,11 @@ OctoPrint currently only supports Python 2.7.
|
||||
Usage
|
||||
-----
|
||||
|
||||
Running the `setup.py` script installs the `octoprint` script in your Python installation's scripts folder
|
||||
Running the `setup.py` script via
|
||||
|
||||
python setup.py install
|
||||
|
||||
installs the `octoprint` script in your Python installation's scripts folder
|
||||
(which depending on whether you installed OctoPrint globally or into a virtual env will be on your `PATH` or not). The
|
||||
following usage examples assume that said `octoprint` script is on your `PATH`.
|
||||
|
||||
@@ -77,5 +104,12 @@ which is located at `~/.octoprint` on Linux, at `%APPDATA%/OctoPrint` on Windows
|
||||
at `~/Library/Application Support/OctoPrint` on MacOS.
|
||||
|
||||
A comprehensive overview of all available configuration settings can be found
|
||||
[on the wiki](https://github.com/foosel/OctoPrint/wiki/Configuration). Please note that the most commonly used
|
||||
configuration settings can also easily be edited from OctoPrint's settings dialog.
|
||||
[in the docs](http://docs.octoprint.org/en/master/configuration/config_yaml.html).
|
||||
Please note that the most commonly used configuration settings can also easily
|
||||
be edited from OctoPrint's settings dialog.
|
||||
|
||||
Special Thanks
|
||||
--------------
|
||||
|
||||
The development of OctoPrint is sponsored and maintained by [BQ](http://www.bq.com/).
|
||||
Cross-browser testing services are kindly provided by [BrowserStack](http://www.browserstack.com/).
|
||||
@@ -611,6 +611,32 @@ Use the following settings to configure the serial connection to the printer:
|
||||
additionalPorts:
|
||||
- /dev/myPrinterSymlink
|
||||
|
||||
# Use this to define additional baud rates to offer for connecting to serial ports. Must be a
|
||||
# valid integer. Defaults to not set
|
||||
additionalBaudrates:
|
||||
- 123456
|
||||
|
||||
# Commands which are known to take a long time to be acknowledged by the firmware. E.g.
|
||||
# homing, dwelling, auto leveling etc. Defaults to the below commands.
|
||||
longRunningCommands:
|
||||
- G4
|
||||
- G28
|
||||
- G29
|
||||
- G30
|
||||
- G32
|
||||
- M400
|
||||
- M226
|
||||
|
||||
# Commands which need to always be send with a checksum. Defaults to only M110
|
||||
checksumRequiringCommands:
|
||||
- M110
|
||||
|
||||
# Command to send in order to initiate a handshake with the printer.
|
||||
# Defaults to "M110 N0" which simply resets the line numbers in the firmware and which
|
||||
# should be acknowledged with a simple "ok".
|
||||
helloCommand:
|
||||
- M110 N0
|
||||
|
||||
.. _sec-configuration-config_yaml-server:
|
||||
|
||||
Server
|
||||
@@ -621,7 +647,8 @@ Use the following settings to configure the server:
|
||||
.. code-block:: yaml
|
||||
|
||||
server:
|
||||
# Use this option to define the host to which to bind the server, defaults to "0.0.0.0" (= all interfaces)
|
||||
# Use this option to define the host to which to bind the server, defaults to "0.0.0.0" (= all
|
||||
# interfaces)
|
||||
host: 0.0.0.0
|
||||
|
||||
# Use this option to define the port to which to bind the server, defaults to 5000
|
||||
@@ -691,6 +718,18 @@ Use the following settings to configure the server:
|
||||
# Maximum size of requests other than file uploads in bytes, defaults to 100KB.
|
||||
maxSize: 102400
|
||||
|
||||
# Commands to restart/shutdown octoprint or the system it's running on
|
||||
commands:
|
||||
|
||||
# Command to restart OctoPrint, defaults to being unset
|
||||
serverRestartCommand: sudo service octoprint restart
|
||||
|
||||
# Command to restart the system OctoPrint is running on, defaults to being unset
|
||||
systemRestartCommand: sudo shutdown -r now
|
||||
|
||||
# Command to shut down the system OctoPrint is running on, defaults to being unset
|
||||
systemShutdownCommand: sudo shutdown -h now
|
||||
|
||||
|
||||
.. note::
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ Changing log levels
|
||||
If you need to change the default logging level within OctoPrint, create the file with a text editor of your choice
|
||||
(it's usually not there). The general format is this::
|
||||
|
||||
logger:
|
||||
loggers:
|
||||
<component>:
|
||||
level: <loglevel>
|
||||
|
||||
@@ -27,7 +27,7 @@ new log level to set. An example for increasing the log level of the events and
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
logger:
|
||||
loggers:
|
||||
octoprint.events:
|
||||
level: DEBUG
|
||||
octoprint.filemanager:
|
||||
@@ -97,4 +97,4 @@ expressed in YAML as follows:
|
||||
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
|
||||
The possible keys for the logging format can be found in the
|
||||
`Python documentation on LogRecord attributes <https://docs.python.org/2/library/logging.html#logrecord-attributes>`_.
|
||||
`Python documentation on LogRecord attributes <https://docs.python.org/2/library/logging.html#logrecord-attributes>`_.
|
||||
@@ -106,6 +106,9 @@ ClientClosed
|
||||
Printer communication
|
||||
---------------------
|
||||
|
||||
Connecting
|
||||
The server is attempting to connect to the printer.
|
||||
|
||||
Connected
|
||||
The server has connected to the printer.
|
||||
|
||||
@@ -114,6 +117,11 @@ Connected
|
||||
* ``port``: the connected serial port
|
||||
* ``baudrate``: the baud rate
|
||||
|
||||
Disconnecting
|
||||
The server is going to disconnect from the printer. Note that this
|
||||
event might not always be sent when the server and printer get disconnected
|
||||
from each other. Do not depend on this for critical life cycle management.
|
||||
|
||||
Disconnected
|
||||
The server has disconnected from the printer
|
||||
|
||||
@@ -124,6 +132,15 @@ Error
|
||||
|
||||
* ``error``: the error string
|
||||
|
||||
PrinterStateChanged
|
||||
The state of the printer changed.
|
||||
|
||||
Payload:
|
||||
|
||||
* ``state_id``: Id of the new state. See
|
||||
:func:`~octoprint.printer.PrinterInterface.get_state_id` for possible values.
|
||||
* ``state_string``: Text representation of the new state.
|
||||
|
||||
File handling
|
||||
-------------
|
||||
|
||||
|
||||
@@ -26,6 +26,10 @@ Predefined Scripts
|
||||
The following GCODE scripts are sent by OctoPrint automatically:
|
||||
|
||||
* ``afterPrinterConnected``: Sent after OctoPrint successfully connected to a printer. Defaults to an empty script.
|
||||
* ``beforePrinterDisconnected``: Sent just before OctoPrint (actively) closes the connection to the printer. Defaults
|
||||
to an empty script. Note that this will *not* be sent for unexpected connection cut offs, e.g. in case of errors
|
||||
on the serial line, only when the user clicks the "Disconnect" button or the printer requests a disconnect via an
|
||||
:ref:`action command <sec-features-action_commands>` .
|
||||
* ``beforePrintStarted``: Sent just before a print job is started. Defaults to an empty script.
|
||||
* ``afterPrintCancelled``: Sent just after a print job was cancelled. Defaults to the
|
||||
:ref:`bundled script listed below <sec-features-gcode_scripts-bundled>`.
|
||||
|
||||
@@ -116,6 +116,9 @@ case "$1" in
|
||||
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
|
||||
esac
|
||||
;;
|
||||
status)
|
||||
status_of_proc -p $PIDFILE $DAEMON $NAME && exit 0 || exit $?
|
||||
;;
|
||||
restart)
|
||||
log_daemon_msg "Restarting $DESC" "$NAME"
|
||||
do_stop
|
||||
@@ -135,8 +138,7 @@ case "$1" in
|
||||
esac
|
||||
;;
|
||||
*)
|
||||
echo "Usage: $SCRIPTNAME {start|stop|restart}" >&2
|
||||
echo "Usage: $SCRIPTNAME {start|stop|status|restart}" >&2
|
||||
exit 3
|
||||
;;
|
||||
esac
|
||||
|
||||
@@ -28,9 +28,14 @@ class Events(object):
|
||||
STARTUP = "Startup"
|
||||
|
||||
# connect/disconnect to printer
|
||||
CONNECTING = "Connecting"
|
||||
CONNECTED = "Connected"
|
||||
DISCONNECTING = "Disconnecting"
|
||||
DISCONNECTED = "Disconnected"
|
||||
|
||||
# State changes
|
||||
PRINTER_STATE_CHANGED = "PrinterStateChanged"
|
||||
|
||||
# connect/disconnect by client
|
||||
CLIENT_OPENED = "ClientOpened"
|
||||
CLIENT_CLOSED = "ClientClosed"
|
||||
@@ -74,6 +79,9 @@ class Events(object):
|
||||
# Timelapse
|
||||
CAPTURE_START = "CaptureStart"
|
||||
CAPTURE_DONE = "CaptureDone"
|
||||
CAPTURE_FAILED = "CaptureFailed"
|
||||
POSTROLL_START = "PostRollStart"
|
||||
POSTROLL_END = "PostRollEnd"
|
||||
MOVIE_RENDERING = "MovieRendering"
|
||||
MOVIE_DONE = "MovieDone"
|
||||
MOVIE_FAILED = "MovieFailed"
|
||||
|
||||
@@ -19,6 +19,8 @@ import octoprint.settings
|
||||
from octoprint.util.paths import normalize as normalize_path
|
||||
|
||||
from .profile import Profile
|
||||
from .profile import GcodeFlavors
|
||||
from .profile import parse_gcode_flavor
|
||||
|
||||
class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
octoprint.plugin.SettingsPlugin,
|
||||
@@ -260,15 +262,29 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
self._cura_logger.info(u"### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path))
|
||||
|
||||
engine_settings = self._convert_to_engine(profile_path, printer_profile, posX, posY)
|
||||
|
||||
executable = normalize_path(self._settings.get(["cura_engine"]))
|
||||
if not executable:
|
||||
return False, "Path to CuraEngine is not configured "
|
||||
|
||||
working_dir, _ = os.path.split(executable)
|
||||
working_dir = os.path.dirname(executable)
|
||||
|
||||
# Start building the argument list for the CuraEngine command execution
|
||||
args = [executable, '-v', '-p']
|
||||
for k, v in engine_settings.items():
|
||||
|
||||
# Get the CuraEngine version out of the "usage" line that is gotten when calling the CuraEngine with the -h argument
|
||||
new_engine = self._is_new_engine_version(executable)
|
||||
|
||||
# If the CuraEngine is the new version, add the JSON file path as argument
|
||||
if new_engine:
|
||||
args += ['-j', os.path.join(self._basefolder, "profiles", "fdmprinter.json")]
|
||||
|
||||
profile = Profile(self._load_profile(profile_path), printer_profile, posX, posY)
|
||||
|
||||
engine_settings = self._convert_to_engine(profile, new_engine=new_engine)
|
||||
|
||||
# Add the settings (sorted alphabetically) to the command
|
||||
|
||||
for k, v in sorted(engine_settings.items(), key=lambda s: s[0]):
|
||||
args += ["-s", "%s=%s" % (k, str(v))]
|
||||
args += ["-o", machinecode_path, model_path]
|
||||
|
||||
@@ -351,6 +367,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
except:
|
||||
pass
|
||||
|
||||
# Get the filament usage
|
||||
|
||||
elif line.startswith(u"Filament:") or line.startswith(u"Filament2:"):
|
||||
if line.startswith(u"Filament:"):
|
||||
filament_str = line[len(u"Filament:"):].strip()
|
||||
@@ -361,17 +379,25 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
|
||||
try:
|
||||
filament = int(filament_str)
|
||||
|
||||
if analysis is None:
|
||||
analysis = dict()
|
||||
if not "filament" in analysis:
|
||||
analysis["filament"] = dict()
|
||||
if not tool_key in analysis["filament"]:
|
||||
analysis["filament"][tool_key] = dict()
|
||||
analysis["filament"][tool_key]["length"] = filament
|
||||
if "filamentDiameter" in engine_settings:
|
||||
radius_in_cm = float(int(engine_settings["filamentDiameter"]) / 10000.0) / 2.0
|
||||
filament_in_cm = filament / 10.0
|
||||
analysis["filament"][tool_key]["volume"] = filament_in_cm * math.pi * radius_in_cm * radius_in_cm
|
||||
|
||||
if profile.get_float("filament_diameter") != None:
|
||||
# The new CuraEngine outputs the "Filament" value as volume independently from the Gcode flavor
|
||||
if new_engine:
|
||||
analysis["filament"][tool_key] = _get_usage_from_volume(filament, profile.get_float("filament_diameter"))
|
||||
# The old CuraEngine outputs the "Filament" value as volume only for ULTIGCODE and REPRAP_VOLUME
|
||||
else:
|
||||
if profile.get("gcode_flavor") == GcodeFlavors.ULTIGCODE or profile.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME:
|
||||
analysis["filament"][tool_key] = _get_usage_from_volume(filament, profile.get_float("filament_diameter"))
|
||||
else:
|
||||
analysis["filament"][tool_key] = _get_usage_from_length(filament, profile.get_float("filament_diameter"))
|
||||
|
||||
except:
|
||||
pass
|
||||
finally:
|
||||
@@ -421,6 +447,11 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
profile_dict = yaml.safe_load(f)
|
||||
except:
|
||||
raise IOError("Couldn't read profile from {path}".format(path=path))
|
||||
|
||||
if "gcode_flavor" in profile_dict and not isinstance(profile_dict["gcode_flavor"], (list, tuple)):
|
||||
profile_dict["gcode_flavor"] = parse_gcode_flavor(profile_dict["gcode_flavor"])
|
||||
self._save_profile(path, profile_dict)
|
||||
|
||||
return profile_dict
|
||||
|
||||
def _save_profile(self, path, profile, allow_overwrite=True):
|
||||
@@ -428,9 +459,28 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
|
||||
with open(path, "wb") as f:
|
||||
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
|
||||
|
||||
def _convert_to_engine(self, profile_path, printer_profile, posX, posY):
|
||||
profile = Profile(self._load_profile(profile_path), printer_profile, posX, posY)
|
||||
return profile.convert_to_engine()
|
||||
def _convert_to_engine(self, profile, new_engine):
|
||||
if new_engine:
|
||||
return profile.convert_to_new_engine()
|
||||
else:
|
||||
return profile.convert_to_engine()
|
||||
|
||||
def _is_new_engine_version(self, executable):
|
||||
import sarge
|
||||
|
||||
command = [executable, "-j", os.path.join(self._basefolder, "profiles", "fdmprinter.json")]
|
||||
p = sarge.run(command, stdout=sarge.Capture(), stderr=sarge.Capture())
|
||||
if p.returncode != 0:
|
||||
self._logger.warn("Could not run {} -j, returned {}".format(executable, p.returncode))
|
||||
self._logger.info(u"Assuming pre 15.06 version of CuraEngine.")
|
||||
return False
|
||||
|
||||
for line in p.stderr.read().split('\n'):
|
||||
if "unknown option: j" in line.strip().lower():
|
||||
self._logger.info(u"Using pre 15.06 version of CuraEngine.")
|
||||
return False
|
||||
self._logger.info(u"Using post 15.06 version of CuraEngine.")
|
||||
return True
|
||||
|
||||
def _sanitize_name(name):
|
||||
if name is None:
|
||||
@@ -445,9 +495,39 @@ def _sanitize_name(name):
|
||||
sanitized_name = sanitized_name.replace(" ", "_")
|
||||
return sanitized_name.lower()
|
||||
|
||||
def _get_usage_from_volume(filament_volume, filament_diameter):
|
||||
|
||||
# filament_volume is expressed in mm^3
|
||||
# usage["volume"] is in cm^3 and usage["length"] is in mm
|
||||
|
||||
usage = dict()
|
||||
usage["volume"] = filament_volume / 1000.0
|
||||
|
||||
radius_in_mm = filament_diameter / 2.0
|
||||
usage["length"] = filament_volume / (math.pi * radius_in_mm * radius_in_mm)
|
||||
|
||||
return usage
|
||||
|
||||
def _get_usage_from_length(filament_length, filament_diameter):
|
||||
|
||||
# filament_length is expressed in mm
|
||||
# usage["volume"] is in cm^3 and usage["length"] is in mm
|
||||
|
||||
usage = dict()
|
||||
usage["length"] = filament_length
|
||||
|
||||
radius_in_cm = (filament_diameter / 10.0) / 2.0
|
||||
length_in_cm = filament_length / 10.0
|
||||
usage["volume"] = length_in_cm * math.pi * radius_in_cm * radius_in_cm
|
||||
|
||||
return usage
|
||||
|
||||
__plugin_name__ = "CuraEngine"
|
||||
__plugin_author__ = "Gina Häußge"
|
||||
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura"
|
||||
__plugin_description__ = "Adds support for slicing via CuraEngine from within OctoPrint"
|
||||
__plugin_license__ = "AGPLv3"
|
||||
__plugin_implementation__ = CuraPlugin()
|
||||
|
||||
|
||||
|
||||
@@ -32,12 +32,12 @@ class MachineShapeTypes(object):
|
||||
CIRCULAR = "circular"
|
||||
|
||||
class GcodeFlavors(object):
|
||||
REPRAP = "reprap"
|
||||
REPRAP_VOLUME = "reprap_volume"
|
||||
ULTIGCODE = "ultigcode"
|
||||
MAKERBOT = "makerbot"
|
||||
BFB = "bfb"
|
||||
MACH3 = "mach3"
|
||||
REPRAP = (0, "reprap")
|
||||
ULTIGCODE = (1, "ultigcode")
|
||||
MAKERBOT = (2, "makerbot")
|
||||
BFB = (3, "bfb")
|
||||
MACH3 = (4, "mach3")
|
||||
REPRAP_VOLUME = (5, "reprap_volume")
|
||||
|
||||
|
||||
defaults = dict(
|
||||
@@ -393,15 +393,45 @@ class Profile(object):
|
||||
}
|
||||
)
|
||||
|
||||
# Translation dict for new CuraEngine option names
|
||||
new_engine_options = dict(
|
||||
fill_sparse_density="fill_density",
|
||||
machine_nozzle_size="nozzle_size",
|
||||
material_print_temperature="print_temperature",
|
||||
#support_type="support", # In conflict with "support_type" from old CuraEngine
|
||||
support_pattern="support_type",
|
||||
adhesion_type="platform_adhesion",
|
||||
material_diameter="filament_diameter",
|
||||
material_flow="filament_flow",
|
||||
speed_travel="travel_speed",
|
||||
speed_layer_0="bottom_layer_speed",
|
||||
speed_print="print_speed",
|
||||
speed_infill="infill_speed",
|
||||
speed_wall_0="outer_shell_speed",
|
||||
speed_wall_x="inner_shell_speed",
|
||||
cool_fan_enabled="fan_enabled",
|
||||
cool_fan_full_at_height="fan_full_height",
|
||||
cool_fan_speed="fan_speed",
|
||||
cool_fan_speed_max="fan_speed_max",
|
||||
cool_lift_head="cool_head_lift",
|
||||
cool_min_speed="cool_min_feedrate",
|
||||
machine_start_gcode="start_gcode",
|
||||
machine_end_gcode="end_gcode",
|
||||
machine_gcode_flavor="gcode_flavor")
|
||||
|
||||
result = dict()
|
||||
for section in config.sections():
|
||||
if not section in ("profile", "alterations"):
|
||||
|
||||
if not section in ("profile", "alterations", "machine"):
|
||||
continue
|
||||
|
||||
for option in config.options(section):
|
||||
ignored = False
|
||||
key = option
|
||||
|
||||
if section == "machine" and key != "gcode_flavor":
|
||||
continue
|
||||
|
||||
# try to fetch the value in the correct type
|
||||
try:
|
||||
value = config.getboolean(section, option)
|
||||
@@ -438,9 +468,16 @@ class Profile(object):
|
||||
# if the key has to be translated to a new value, do that now
|
||||
key = translated_options[key]
|
||||
|
||||
if key in new_engine_options:
|
||||
# if the key has to be translated from the new CuraEngine versions, do that now
|
||||
key = new_engine_options[key]
|
||||
|
||||
if key in value_conversions and value in value_conversions[key]:
|
||||
value = value_conversions[key][value]
|
||||
|
||||
if key == "gcode_flavor":
|
||||
value = parse_gcode_flavor(value)
|
||||
|
||||
if index is not None:
|
||||
# if we have an array to fill, make sure the target array exists and has the right size
|
||||
if not key in result:
|
||||
@@ -710,61 +747,70 @@ class Profile(object):
|
||||
|
||||
return pre + str(f)
|
||||
|
||||
def get_gcode(self, key):
|
||||
extruder_count = self.get_int("extruder_amount")
|
||||
|
||||
def get_gcode(self, key, new_engine=False):
|
||||
prefix = ""
|
||||
postfix = ""
|
||||
|
||||
if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE:
|
||||
if key == "end_gcode":
|
||||
return "M25 ;Stop reading from this point on.\n;CURA_PROFILE_STRING:%s\n" % (self.get_profile_string())
|
||||
return "M25 ;Stop reading from this point on.\n;CURA_OCTO_PROFILE_STRING:%s\n" % (self.get_profile_string())
|
||||
return ""
|
||||
|
||||
if key == "start_gcode":
|
||||
contents = self.get_gcode_template("start_gcode")
|
||||
|
||||
e_steps = self.get_float("steps_per_e")
|
||||
if e_steps > 0:
|
||||
prefix += "M92 E{e_steps}\n" % (e_steps)
|
||||
temp = self.get_float("print_temperature")
|
||||
|
||||
bed_temp = 0
|
||||
if self.get_boolean("has_heated_bed"):
|
||||
bed_temp = self.get_float("print_bed_temperature")
|
||||
include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
|
||||
|
||||
if include_bed_temp:
|
||||
prefix += "M140 S{bed_temp}\n".format(bed_temp=bed_temp)
|
||||
|
||||
if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
|
||||
if extruder_count > 0:
|
||||
def temp_line(temp, extruder, template):
|
||||
t = temp
|
||||
if extruder > 0:
|
||||
print_temp = self.get_float("print_temperature%d" % (extruder + 1))
|
||||
if print_temp > 0:
|
||||
t = print_temp
|
||||
return template.format(extruder=extruder, temp=t)
|
||||
|
||||
prefix_preheat = ""
|
||||
prefix_waitheat = ""
|
||||
for n in xrange(0, extruder_count):
|
||||
if n > 0:
|
||||
prefix_preheat += temp_line(temp, n, "M104 T{extruder} S{temp}\n")
|
||||
prefix_waitheat += temp_line(temp, n, "M109 T{extruder} S{temp}\n")
|
||||
prefix += prefix_preheat + prefix_waitheat + "T0\n"
|
||||
else:
|
||||
prefix += "M109 S{temp}\n".format(temp=temp)
|
||||
|
||||
if include_bed_temp:
|
||||
prefix += "M190 S{bed_temp}\n".format(bed_temp=bed_temp)
|
||||
# If using the new CuraEngine, there is no need to extend the start_gcode
|
||||
if not new_engine:
|
||||
prefix += self.get_start_gcode_prefix(contents)
|
||||
|
||||
else:
|
||||
contents = self.get_gcode_template(key)
|
||||
|
||||
return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
|
||||
|
||||
def get_start_gcode_prefix(self, contents):
|
||||
extruder_count = self.get_int("extruder_amount")
|
||||
|
||||
prefix = ""
|
||||
|
||||
e_steps = self.get_float("steps_per_e")
|
||||
if e_steps > 0:
|
||||
prefix += "M92 E{e_steps}\n" % (e_steps)
|
||||
temp = self.get_float("print_temperature")
|
||||
|
||||
bed_temp = 0
|
||||
if self.get_boolean("has_heated_bed"):
|
||||
bed_temp = self.get_float("print_bed_temperature")
|
||||
include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
|
||||
|
||||
if include_bed_temp:
|
||||
prefix += "M140 S{bed_temp}\n".format(bed_temp=bed_temp)
|
||||
|
||||
if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
|
||||
if extruder_count > 0:
|
||||
def temp_line(temp, extruder, template):
|
||||
t = temp
|
||||
if extruder > 0:
|
||||
print_temp = self.get_float("print_temperature%d" % (extruder + 1))
|
||||
if print_temp > 0:
|
||||
t = print_temp
|
||||
return template.format(extruder=extruder, temp=t)
|
||||
|
||||
prefix_preheat = ""
|
||||
prefix_waitheat = ""
|
||||
for n in xrange(0, extruder_count):
|
||||
if n > 0:
|
||||
prefix_preheat += temp_line(temp, n, "M104 T{extruder} S{temp}\n")
|
||||
prefix_waitheat += temp_line(temp, n, "M109 T{extruder} S{temp}\n")
|
||||
prefix += prefix_preheat + prefix_waitheat + "T0\n"
|
||||
else:
|
||||
prefix += "M109 S{temp}\n".format(temp=temp)
|
||||
|
||||
if include_bed_temp:
|
||||
prefix += "M190 S{bed_temp}\n".format(bed_temp=bed_temp)
|
||||
|
||||
return prefix
|
||||
|
||||
def calculate_edge_width_and_line_count(self):
|
||||
wall_thickness = self.get_float("wall_thickness")
|
||||
nozzle_size = self._printer_profile["extruder"]["nozzleDiameter"]
|
||||
@@ -810,20 +856,20 @@ class Profile(object):
|
||||
def get_pos_x(self):
|
||||
if self._posX:
|
||||
try:
|
||||
return int(float(self._posX) * 1000)
|
||||
return int(float(self._posX))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return int(self.get_float("machine_width") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0
|
||||
return int(self.get_float("machine_width") / 2.0 ) if not self.get_boolean("machine_center_is_zero") else 0.0
|
||||
|
||||
def get_pos_y(self):
|
||||
if self._posY:
|
||||
try:
|
||||
return int(float(self._posY) * 1000)
|
||||
return int(float(self._posY))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return int(self.get_float("machine_depth") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0
|
||||
return int(self.get_float("machine_depth") / 2.0) if not self.get_boolean("machine_center_is_zero") else 0.0
|
||||
|
||||
def convert_to_engine(self):
|
||||
|
||||
@@ -873,8 +919,8 @@ class Profile(object):
|
||||
"coolHeadLift": 1 if self.get_boolean("cool_head_lift") else 0,
|
||||
|
||||
# model positioning
|
||||
"posx": self.get_pos_x(),
|
||||
"posy": self.get_pos_y(),
|
||||
"posx": self.get_pos_x() * 1000, # in microns
|
||||
"posy": self.get_pos_y() * 1000, # in microns
|
||||
|
||||
# gcodes
|
||||
"startCode": self.get_gcode("start_gcode"),
|
||||
@@ -953,16 +999,7 @@ class Profile(object):
|
||||
settings["layerThickness"] = 1000
|
||||
|
||||
# gcode flavor
|
||||
if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE:
|
||||
settings["gcodeFlavor"] = 1
|
||||
elif self.get("gcode_flavor") == GcodeFlavors.MAKERBOT:
|
||||
settings["gcodeFlavor"] = 2
|
||||
elif self.get("gcode_flavor") == GcodeFlavors.BFB:
|
||||
settings["gcodeFlavor"] = 3
|
||||
elif self.get("gcode_flavor") == GcodeFlavors.MACH3:
|
||||
settings["gcodeFlavor"] = 4
|
||||
elif self.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME:
|
||||
settings["gcodeFlavor"] = 5
|
||||
settings["gcodeFlavor"] = self.get("gcode_flavor")[0]
|
||||
|
||||
# extras
|
||||
if self.get_boolean("spiralize"):
|
||||
@@ -978,3 +1015,132 @@ class Profile(object):
|
||||
settings["enableOozeShield"] = 1
|
||||
|
||||
return settings
|
||||
|
||||
def convert_to_new_engine(self):
|
||||
|
||||
settings = {
|
||||
"layer_height": self.get_float("layer_height"),
|
||||
"wall_thickness": self.get_float("wall_thickness"),
|
||||
"retraction_enable": self.get_boolean("retraction_enable"),
|
||||
"top_bottom_thickness": self.get_float("solid_layer_thickness"),
|
||||
"fill_sparse_density": self.get_float("fill_density"),
|
||||
"machine_nozzle_size": self.get_float("nozzle_size"),
|
||||
"speed_print": self.get_float("print_speed"),
|
||||
"material_print_temperature": self.get_float("print_temperature"),
|
||||
"material_diameter": self.get_float("filament_diameter"),
|
||||
"material_flow": self.get_float("filament_flow"),
|
||||
"retraction_speed": self.get_float("retraction_speed"),
|
||||
"retraction_amount": self.get_float("retraction_amount") if self.get_boolean("retraction_enable") else 0,
|
||||
"retraction_min_travel": self.get_float("retraction_min_travel"),
|
||||
"retraction_combing": self.get_boolean("retraction_combing"),
|
||||
"retraction_hop": self.get_float("retraction_hop"),
|
||||
"bottom_thickness": self.get_float("bottom_thickness"),
|
||||
"top_layers": self.calculate_solid_layer_count(),
|
||||
"bottom_layers": self.calculate_solid_layer_count(),
|
||||
"speed_travel": self.get_float("travel_speed"),
|
||||
"speed_layer_0": self.get_float("bottom_layer_speed"),
|
||||
"speed_infill": self.get_float("infill_speed") if self.get_float("infill_speed") > 0 else self.get_float("print_speed"),
|
||||
"speed_wall_0": self.get_float("outer_shell_speed") if self.get_float("outer_shell_speed") > 0 else self.get_float("print_speed"), # Translated from "inset0_speed"
|
||||
"speed_wall_x": self.get_float("inner_shell_speed") if self.get_float("inner_shell_speed") > 0 else self.get_float("print_speed"), # Translated from "insetx_speed"
|
||||
"cool_min_layer_time": self.get_float("cool_min_layer_time"),
|
||||
"cool_fan_enabled": self.get_boolean("fan_enabled"),
|
||||
"cool_fan_full_at_height": self.get_int("fan_full_height"),
|
||||
"cool_fan_speed": self.get_float("fan_speed"),
|
||||
"cool_fan_speed_max": self.get_float("fan_speed_max") if self.get_boolean("fan_enabled") else 0,
|
||||
"cool_lift_head": self.get_boolean("cool_head_lift"),
|
||||
"cool_min_speed": self.get_float("cool_min_feedrate"),
|
||||
"skirt_line_count": self.get_int("skirt_line_count"),
|
||||
"fill_overlap": self.get_float("fill_overlap"),
|
||||
"magic_spiralize": self.get_boolean("spiralize"),
|
||||
|
||||
# machine settings
|
||||
|
||||
"machine_width": self.get_float("machine_width"),
|
||||
"machine_depth": self.get_float("machine_depth"),
|
||||
"machine_center_is_zero": self.get_boolean("machine_center_is_zero"),
|
||||
"machine_heated_bed": self.get_boolean("has_heated_bed"),
|
||||
|
||||
# gcodes
|
||||
|
||||
"machine_start_gcode": self.get_gcode("start_gcode", new_engine=True),
|
||||
"machine_end_gcode": self.get_gcode("end_gcode", new_engine=True),
|
||||
}
|
||||
|
||||
# gcode flavor
|
||||
|
||||
settings["machine_gcode_flavor"] = self.get("gcode_flavor")[0]
|
||||
|
||||
# heated bed - The new CuraEngine uses the integer "material_bed_temperature" instead of the boolean "machine_heated_bed"
|
||||
|
||||
if self.get_boolean("has_heated_bed"):
|
||||
settings["material_bed_temperature"] = self.get_float("print_bed_temperature")
|
||||
else:
|
||||
settings["material_bed_temperature"] = 0
|
||||
|
||||
# support
|
||||
|
||||
if self.get("support") == SupportLocationTypes.NONE:
|
||||
settings["support_enable"] = False
|
||||
else:
|
||||
settings["support_enable"] = True
|
||||
settings["support_angle"] = self.get_float("support_angle")
|
||||
settings["support_fill_rate"] = self.get_float("support_fill_rate")
|
||||
settings["support_xy_distance"] = self.get_float("support_xy_distance")
|
||||
settings["support_z_distance"] = self.get_float("support_z_distance")
|
||||
|
||||
# support type
|
||||
|
||||
if self.get("support") == SupportLocationTypes.TOUCHING_BUILDPLATE:
|
||||
settings["support_type"] = "Touching Buildplate"
|
||||
elif self.get("support") == SupportLocationTypes.EVERYWHERE:
|
||||
settings["support_type"] = "Everywhere"
|
||||
|
||||
# support pattern
|
||||
|
||||
if self.get("support_type") == SupportTypes.GRID:
|
||||
settings["support_pattern"] = "Grid"
|
||||
elif self.get("support_type") == SupportTypes.LINES:
|
||||
settings["support_pattern"] = "Lines"
|
||||
|
||||
# adhesion type
|
||||
|
||||
if self.get("platform_adhesion") == PlatformAdhesionTypes.NONE:
|
||||
settings["adhesion_type"] = "None"
|
||||
elif self.get("platform_adhesion") == PlatformAdhesionTypes.BRIM:
|
||||
settings["adhesion_type"] = "Brim"
|
||||
settings["brim_line_count"] = self.get_int("brim_line_count")
|
||||
elif self.get("platform_adhesion") == PlatformAdhesionTypes.RAFT:
|
||||
settings["adhesion_type"] = "Raft"
|
||||
settings["raft_margin"] = self.get_int("raft_margin")
|
||||
settings["raft_line_spacing"] = self.get_float("raft_line_spacing")
|
||||
settings["raft_base_thickness"] = self.get_float("raft_base_thickness")
|
||||
settings["raft_base_linewidth"] = self.get_float("raft_base_linewidth")
|
||||
settings["raft_interface_thickness"] = self.get_float("raft_interface_thickness")
|
||||
settings["raft_interface_linewidth"] = self.get_float("raft_interface_linewidth")
|
||||
settings["raft_airgap"] = self.get_float("raft_airgap")
|
||||
settings["raft_surface_layers"] = self.get_int("raft_surface_layers")
|
||||
|
||||
# skirt
|
||||
|
||||
if self.get_int("skirt_line_count") != 0:
|
||||
settings["skirt_gap"] = self.get_float("skirt_gap")
|
||||
settings["skirt_minimal_length"] = self.get_float("skirt_minimal_length")
|
||||
|
||||
return settings
|
||||
|
||||
def parse_gcode_flavor(value):
|
||||
|
||||
value = value.lower()
|
||||
|
||||
if "reprap" in value and ("volume" in value or "volumatric" in value):
|
||||
return GcodeFlavors.REPRAP_VOLUME
|
||||
elif "ultigcode" in value:
|
||||
return GcodeFlavors.ULTIGCODE
|
||||
elif "makerbot" in value:
|
||||
return GcodeFlavors.MAKERBOT
|
||||
elif "bfb" in value:
|
||||
return GcodeFlavors.BFB
|
||||
elif "mach3" in value:
|
||||
return GcodeFlavors.MACH3
|
||||
else:
|
||||
return GcodeFlavors.REPRAP
|
||||
File diff suppressed because it is too large.
Load diff
@@ -83,6 +83,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
repository="http://plugins.octoprint.org/plugins.json",
|
||||
repository_ttl=24*60,
|
||||
pip=None,
|
||||
dependency_links=False,
|
||||
hidden=[]
|
||||
)
|
||||
|
||||
@@ -187,6 +188,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
plugin_name = data["plugin"] if "plugin" in data else None
|
||||
return self.command_install(url=url,
|
||||
force="force" in data and data["force"] in valid_boolean_trues,
|
||||
dependency_links="dependency_links" in data and data["dependency_links"] in valid_boolean_trues,
|
||||
reinstall=plugin_name)
|
||||
|
||||
elif command == "uninstall":
|
||||
@@ -205,7 +207,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
plugin = self._plugin_manager.plugins[plugin_name]
|
||||
return self.command_toggle(plugin, command)
|
||||
|
||||
def command_install(self, url=None, path=None, force=False, reinstall=None):
|
||||
def command_install(self, url=None, path=None, force=False, reinstall=None, dependency_links=False):
|
||||
if url is not None:
|
||||
pip_args = ["install", sarge.shell_quote(url)]
|
||||
elif path is not None:
|
||||
@@ -213,6 +215,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
else:
|
||||
raise ValueError("Either url or path must be provided")
|
||||
|
||||
if dependency_links or self._settings.get_boolean(["dependency_links"]):
|
||||
pip_args.append("--process-dependency-links")
|
||||
|
||||
all_plugins_before = self._plugin_manager.find_plugins()
|
||||
|
||||
success_string = "Successfully installed"
|
||||
@@ -421,8 +426,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
def _call_pip(self, args):
|
||||
if self._pip_caller is None or not self._pip_caller.available:
|
||||
raise RuntimeError(u"No pip available, can't operate".format(**locals()))
|
||||
|
||||
if "--process-dependency-links" in args:
|
||||
self._log_message(u"Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version")
|
||||
|
||||
return self._pip_caller.execute(*args)
|
||||
|
||||
def _log_message(self, *lines):
|
||||
self._log(lines, prefix=u"*", stream="message")
|
||||
|
||||
def _log_call(self, *lines):
|
||||
self._log(lines, prefix=u" ", stream="call")
|
||||
|
||||
@@ -519,6 +531,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
def map_repository_entry(entry):
|
||||
result = dict(entry)
|
||||
|
||||
if not "follow_dependency_links" in result:
|
||||
result["follow_dependency_links"] = False
|
||||
|
||||
if not "follow_dependency_links" in result:
|
||||
result["follow_dependency_links"] = False
|
||||
|
||||
result["is_compatible"] = dict(
|
||||
octoprint=True,
|
||||
os=True
|
||||
|
||||
@@ -70,6 +70,8 @@ $(function() {
|
||||
self.loglines = ko.observableArray([]);
|
||||
self.installedPlugins = ko.observableArray([]);
|
||||
|
||||
self.followDependencyLinks = ko.observable(false);
|
||||
|
||||
self.working = ko.observable(false);
|
||||
self.workingTitle = ko.observable();
|
||||
self.workingDialog = undefined;
|
||||
@@ -125,6 +127,9 @@ $(function() {
|
||||
self.uploadButton.unbind("click");
|
||||
self.uploadButton.bind("click", function() {
|
||||
self._markWorking(gettext("Installing plugin..."), gettext("Installing plugin from uploaded archive..."));
|
||||
data.formData = {
|
||||
dependency_links: self.followDependencyLinks()
|
||||
};
|
||||
data.submit();
|
||||
return false;
|
||||
});
|
||||
@@ -240,13 +245,13 @@ $(function() {
|
||||
}
|
||||
|
||||
if (self.installed(data)) {
|
||||
self.installPlugin(data.archive, data.title, data.id);
|
||||
self.installPlugin(data.archive, data.title, data.id, data.follow_dependency_links || self.followDependencyLinks());
|
||||
} else {
|
||||
self.installPlugin(data.archive, data.title, undefined);
|
||||
self.installPlugin(data.archive, data.title, undefined, data.follow_dependency_links || self.followDependencyLinks());
|
||||
}
|
||||
};
|
||||
|
||||
self.installPlugin = function(url, name, reinstall) {
|
||||
self.installPlugin = function(url, name, reinstall, followDependencyLinks) {
|
||||
if (!self.loginState.isAdmin()) {
|
||||
return;
|
||||
}
|
||||
@@ -260,6 +265,10 @@ $(function() {
|
||||
}
|
||||
if (!url) return;
|
||||
|
||||
if (followDependencyLinks === undefined) {
|
||||
followDependencyLinks = self.followDependencyLinks();
|
||||
}
|
||||
|
||||
var workTitle, workText;
|
||||
if (!reinstall) {
|
||||
workTitle = gettext("Installing plugin...");
|
||||
@@ -275,7 +284,7 @@ $(function() {
|
||||
self._markWorking(workTitle, workText);
|
||||
|
||||
var command = "install";
|
||||
var payload = {url: url};
|
||||
var payload = {url: url, dependency_links: followDependencyLinks};
|
||||
if (reinstall) {
|
||||
payload["plugin"] = reinstall;
|
||||
payload["force"] = true;
|
||||
|
||||
@@ -147,6 +147,21 @@
|
||||
</div>
|
||||
<span class="help-block" data-bind="visible: invalidArchive">{{ _('This does not look like a valid plugin archive. Valid plugin archives should be either zip files or tarballs and have the extension ".zip", ".tar.gz", ".tgz" or ".tar"') }}</span>
|
||||
</form>
|
||||
|
||||
<div>
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: followDependencyLinks"> {{ _('Use <code>--process-dependency-links</code> with <code>pip install</code>') }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Close') }}</button>
|
||||
|
||||
@@ -150,9 +150,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
"restart": "octoprint"
|
||||
},
|
||||
},
|
||||
|
||||
"octoprint_restart_command": None,
|
||||
"environment_restart_command": None,
|
||||
"pip_command": None,
|
||||
|
||||
"cache_ttl": 24 * 60,
|
||||
@@ -177,13 +174,35 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60
|
||||
|
||||
def get_settings_version(self):
|
||||
return 3
|
||||
return 4
|
||||
|
||||
def on_settings_migrate(self, target, current=None):
|
||||
|
||||
if current is None or current < 4:
|
||||
# config version 4 and higher moves octoprint_restart_command and
|
||||
# environment_restart_command to the core configuration
|
||||
|
||||
# current plugin commands
|
||||
configured_octoprint_restart_command = self._settings.get(["octoprint_restart_command"])
|
||||
configured_environment_restart_command = self._settings.get(["environment_restart_command"])
|
||||
|
||||
# current global commands
|
||||
configured_system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
|
||||
configured_server_restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||
|
||||
# only set global commands if they are not yet set
|
||||
if configured_system_restart_command is None and configured_environment_restart_command is not None:
|
||||
self._settings.global_set(["server", "commands", "systemRestartCommand"], configured_environment_restart_command)
|
||||
if configured_server_restart_command is None and configured_octoprint_restart_command is not None:
|
||||
self._settings.global_set(["server", "commands", "serverRestartCommand"], configured_octoprint_restart_command)
|
||||
|
||||
# delete current plugin commands from config
|
||||
self._settings.set(["environment_restart_command"], None)
|
||||
self._settings.set(["octoprint_restart_command"], None)
|
||||
|
||||
if current is None or current == 2:
|
||||
# there might be some left over data from the time we still persisted everything to settings,
|
||||
# even the stuff that shouldn't be persisted but always provided by the hook - let's
|
||||
# clean up
|
||||
# No config version and config version 2 need the same fix, stripping
|
||||
# accidentally persisted data off the checks
|
||||
|
||||
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
||||
if configured_checks is None:
|
||||
@@ -229,6 +248,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
self._settings.set(["checks", key], None, defaults=dummy_defaults)
|
||||
|
||||
elif current == 1:
|
||||
# config version 1 had the error that the octoprint check got accidentally
|
||||
# included in checks["octoprint"], leading to recursion and hence to
|
||||
# yaml parser errors
|
||||
|
||||
configured_checks = self._settings.get(["checks"], incl_defaults=False)
|
||||
if configured_checks is None:
|
||||
return
|
||||
@@ -239,7 +262,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
dummy_defaults["plugins"][self._identifier] = dict(checks=dict())
|
||||
dummy_defaults["plugins"][self._identifier]["checks"]["octoprint"] = None
|
||||
self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults)
|
||||
self._settings.save()
|
||||
|
||||
def _clean_settings_check(self, key, data, defaults, delete=None, save=True):
|
||||
if delete is None:
|
||||
@@ -496,7 +518,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
|
||||
if restart_type is not None and restart_type in ("octoprint", "environment"):
|
||||
# one of our updates requires a restart of either type "octoprint" or "environment". Let's see if
|
||||
# we can actually perform that
|
||||
restart_command = self._settings.get(["%s_restart_command" % restart_type])
|
||||
|
||||
if restart_type == "octoprint":
|
||||
restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
|
||||
elif restart_type == "environment":
|
||||
restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
|
||||
|
||||
if restart_command is not None:
|
||||
self._send_client_message("restarting", dict(restart_type=restart_type, results=target_results))
|
||||
|
||||
@@ -19,8 +19,6 @@ $(function() {
|
||||
self.workingOutput = undefined;
|
||||
self.loglines = ko.observableArray([]);
|
||||
|
||||
self.config_restartCommand = ko.observable();
|
||||
self.config_rebootCommand = ko.observable();
|
||||
self.config_cacheTtl = ko.observable();
|
||||
|
||||
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
|
||||
@@ -84,8 +82,6 @@ $(function() {
|
||||
var data = {
|
||||
plugins: {
|
||||
softwareupdate: {
|
||||
octoprint_restart_command: self.config_restartCommand(),
|
||||
environment_restart_command: self.config_rebootCommand(),
|
||||
cache_ttl: parseInt(self.config_cacheTtl())
|
||||
}
|
||||
}
|
||||
@@ -94,8 +90,6 @@ $(function() {
|
||||
};
|
||||
|
||||
self._copyConfig = function() {
|
||||
self.config_restartCommand(self.settings.settings.plugins.softwareupdate.octoprint_restart_command());
|
||||
self.config_rebootCommand(self.settings.settings.plugins.softwareupdate.environment_restart_command());
|
||||
self.config_cacheTtl(self.settings.settings.plugins.softwareupdate.cache_ttl());
|
||||
};
|
||||
|
||||
|
||||
@@ -55,18 +55,6 @@
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-horizontal">
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Restart Command') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_restartCommand">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Reboot Command') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: config_rebootCommand">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Version cache TTL') }}</label>
|
||||
<div class="controls">
|
||||
|
||||
@@ -7,13 +7,16 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
|
||||
import logging
|
||||
import pkg_resources
|
||||
|
||||
from octoprint.util.pip import PipCaller, UnknownPip
|
||||
from .. import exceptions
|
||||
|
||||
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip")
|
||||
console_logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip.console")
|
||||
|
||||
_pip_callers = dict()
|
||||
_pip_version_dependency_links = pkg_resources.parse_version("1.5")
|
||||
|
||||
def can_perform_update(target, check):
|
||||
pip_caller = _get_pip_caller(command=check["pip_command"] if "pip_command" in check else None)
|
||||
@@ -39,7 +42,7 @@ def perform_update(target, check, target_version, log_cb=None):
|
||||
|
||||
pip_caller = _get_pip_caller(command=pip_command)
|
||||
if pip_caller is None:
|
||||
raise RuntimeError("Can't run pip")
|
||||
raise exceptions.UpdateError("Can't run pip", None)
|
||||
|
||||
def _log_call(*lines):
|
||||
_log(lines, prefix=" ", stream="call")
|
||||
@@ -65,11 +68,18 @@ def perform_update(target, check, target_version, log_cb=None):
|
||||
logger.debug(u"Target: %s, executing pip install %s" % (target, install_arg))
|
||||
pip_args = ["install", check["pip"].format(target_version=target_version, target=target_version)]
|
||||
|
||||
pip_caller.execute(*pip_args)
|
||||
if "dependency_links" in check and check["dependency_links"]:
|
||||
pip_args += ["--process-dependency-links"]
|
||||
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args)
|
||||
if returncode != 0:
|
||||
raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr))
|
||||
|
||||
logger.debug(u"Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg))
|
||||
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
|
||||
|
||||
pip_caller.execute(*pip_args)
|
||||
returncode, stdout, stderr = pip_caller.execute(*pip_args)
|
||||
if returncode != 0:
|
||||
raise exceptions.UpdateError("Error while executing pip install --force-reinstall", (stdout, stderr))
|
||||
|
||||
return "ok"
|
||||
@@ -16,8 +16,15 @@ class VirtualPrinterPlugin(octoprint.plugin.SettingsPlugin):
|
||||
if not self._settings.global_get_boolean(["devel", "virtualPrinter", "enabled"]):
|
||||
return None
|
||||
|
||||
import logging
|
||||
import logging.handlers
|
||||
|
||||
seriallog_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="serial"), maxBytes=2*1024*1024)
|
||||
seriallog_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
|
||||
seriallog_handler.setLevel(logging.DEBUG)
|
||||
|
||||
from . import virtual
|
||||
serial_obj = virtual.VirtualPrinter(read_timeout=float(read_timeout))
|
||||
serial_obj = virtual.VirtualPrinter(seriallog_handler=seriallog_handler, read_timeout=float(read_timeout))
|
||||
return serial_obj
|
||||
|
||||
__plugin_name__ = "Virtual Printer"
|
||||
|
||||
@@ -16,17 +16,28 @@ from serial import SerialTimeoutException
|
||||
from octoprint.settings import settings
|
||||
from octoprint.plugin import plugin_manager
|
||||
|
||||
class VirtualPrinter():
|
||||
class VirtualPrinter(object):
|
||||
command_regex = re.compile("[GM]\d+")
|
||||
sleep_regex = re.compile("sleep (\d+)")
|
||||
sleep_after_regex = re.compile("sleep_after ([GM]\d+) (\d+)")
|
||||
sleep_after_next_regex = re.compile("sleep_after_next ([GM]\d+) (\d+)")
|
||||
custom_action_regex = re.compile("action_custom ([a-zA-Z0-9_]+)(\s+.*)?")
|
||||
|
||||
def __init__(self, read_timeout=5.0, write_timeout=10.0):
|
||||
def __init__(self, seriallog_handler=None, read_timeout=5.0, write_timeout=10.0):
|
||||
import logging
|
||||
self._logger = logging.getLogger("octoprint.plugin.virtual_printer.VirtualPrinter")
|
||||
|
||||
self._seriallog = logging.getLogger("octoprint.plugin.virtual_printer.VirtualPrinter.serial")
|
||||
self._seriallog.setLevel(logging.CRITICAL)
|
||||
self._seriallog.propagate = False
|
||||
|
||||
if seriallog_handler is not None:
|
||||
import logging.handlers
|
||||
self._seriallog.addHandler(seriallog_handler)
|
||||
self._seriallog.setLevel(logging.INFO)
|
||||
|
||||
self._seriallog.info("-"*78)
|
||||
|
||||
self._read_timeout = read_timeout
|
||||
self._write_timeout = write_timeout
|
||||
|
||||
@@ -35,7 +46,7 @@ class VirtualPrinter():
|
||||
self.buffered = Queue.Queue(maxsize=settings().getInt(["devel", "virtualPrinter", "commandBuffer"]))
|
||||
|
||||
for item in ['start\n', 'Marlin: Virtual Marlin!\n', '\x80\n', 'SD card ok\n']:
|
||||
self.outgoing.put(item)
|
||||
self._send(item)
|
||||
|
||||
self.currentExtruder = 0
|
||||
self.temp = [0.0] * settings().getInt(["devel", "virtualPrinter", "numExtruders"])
|
||||
@@ -113,7 +124,7 @@ class VirtualPrinter():
|
||||
data = self.incoming.get(timeout=0.01)
|
||||
except Queue.Empty:
|
||||
if self._sendWait and time.time() > next_wait_timeout:
|
||||
self.outgoing.put("wait")
|
||||
self._send("wait")
|
||||
next_wait_timeout = time.time() + self._waitInterval
|
||||
continue
|
||||
|
||||
@@ -133,7 +144,7 @@ class VirtualPrinter():
|
||||
data = data[:data.rfind("*")]
|
||||
self.currentLine += 1
|
||||
elif settings().getBoolean(["devel", "virtualPrinter", "forceChecksum"]):
|
||||
self.outgoing.put("Error: Missing checksum")
|
||||
self._send("Error: Missing checksum")
|
||||
continue
|
||||
|
||||
# track N = N + 1
|
||||
@@ -168,7 +179,7 @@ class VirtualPrinter():
|
||||
|
||||
if data.strip() == "version":
|
||||
from octoprint._version import get_versions
|
||||
self.outgoing.put("OctoPrint VirtualPrinter v" + get_versions()["version"])
|
||||
self._send("OctoPrint VirtualPrinter v" + get_versions()["version"])
|
||||
continue
|
||||
elif data.startswith("!!DEBUG:"):
|
||||
self._debugTrigger(data[len("!!DEBUG:"):].strip())
|
||||
@@ -192,7 +203,7 @@ class VirtualPrinter():
|
||||
self._listSd()
|
||||
elif 'M21' in data:
|
||||
self._sdCardReady = True
|
||||
self.outgoing.put("SD card ok")
|
||||
self._send("SD card ok")
|
||||
elif 'M22' in data:
|
||||
self._sdCardReady = False
|
||||
elif 'M23' in data:
|
||||
@@ -228,17 +239,17 @@ class VirtualPrinter():
|
||||
output = "C: X:10.00 Y:3.20 Z:5.20 E:1.24"
|
||||
if not self._okBeforeCommandOutput:
|
||||
output = "ok " + output
|
||||
self.outgoing.put(output)
|
||||
self._send(output)
|
||||
continue
|
||||
elif "M117" in data:
|
||||
# we'll just use this to echo a message, to allow playing around with pause triggers
|
||||
self.outgoing.put("echo:%s" % re.search("M117\s+(.*)", data).group(1))
|
||||
self._send("echo:%s" % re.search("M117\s+(.*)", data).group(1))
|
||||
elif "M999" in data:
|
||||
# mirror Marlin behaviour
|
||||
self.outgoing.put("Resend: 1")
|
||||
self._send("Resend: 1")
|
||||
elif data.startswith("T"):
|
||||
self.currentExtruder = int(re.search("T(\d+)", data).group(1))
|
||||
self.outgoing.put("Active Extruder: %d" % self.currentExtruder)
|
||||
self._send("Active Extruder: %d" % self.currentExtruder)
|
||||
elif "G20" in data:
|
||||
self._unitModifier = 1.0 / 2.54
|
||||
if self._lastX is not None:
|
||||
@@ -285,7 +296,7 @@ class VirtualPrinter():
|
||||
del self._sleepAfterNext[command]
|
||||
|
||||
if interval is not None:
|
||||
self.outgoing.put("// sleeping for {interval} seconds".format(interval=interval))
|
||||
self._send("// sleeping for {interval} seconds".format(interval=interval))
|
||||
time.sleep(interval)
|
||||
|
||||
if len(data.strip()) > 0 and not self._okBeforeCommandOutput:
|
||||
@@ -299,20 +310,20 @@ class VirtualPrinter():
|
||||
self.lastN = expected - 1
|
||||
|
||||
if actual is None:
|
||||
self.outgoing.put("Error: Wrong checksum")
|
||||
self._send("Error: Wrong checksum")
|
||||
else:
|
||||
self.outgoing.put("Error: expected line %d got %d" % (expected, actual))
|
||||
self._send("Error: expected line %d got %d" % (expected, actual))
|
||||
|
||||
self.outgoing.put("Resend:%d" % expected)
|
||||
self.outgoing.put("ok")
|
||||
self._send("Resend:%d" % expected)
|
||||
self._send("ok")
|
||||
|
||||
def _debugTrigger(self, data):
|
||||
if data == "action_pause":
|
||||
self.outgoing.put("// action:pause")
|
||||
self._send("// action:pause")
|
||||
elif data == "action_resume":
|
||||
self.outgoing.put("// action:resume")
|
||||
self._send("// action:resume")
|
||||
elif data == "action_disconnect":
|
||||
self.outgoing.put("// action:disconnect")
|
||||
self._send("// action:disconnect")
|
||||
elif data == "dont_answer":
|
||||
self._dont_answer = True
|
||||
elif data == "trigger_resend_lineno":
|
||||
@@ -330,28 +341,28 @@ class VirtualPrinter():
|
||||
|
||||
if sleep_match is not None:
|
||||
interval = int(sleep_match.group(1))
|
||||
self.outgoing.put("// sleeping for {interval} seconds".format(interval=interval))
|
||||
self._send("// sleeping for {interval} seconds".format(interval=interval))
|
||||
time.sleep(interval)
|
||||
elif sleep_after_match is not None:
|
||||
command = sleep_after_match.group(1)
|
||||
interval = int(sleep_after_match.group(2))
|
||||
self._sleepAfter[command] = interval
|
||||
self.outgoing.put("// going to sleep {interval} seconds after each {command}".format(**locals()))
|
||||
self._send("// going to sleep {interval} seconds after each {command}".format(**locals()))
|
||||
elif sleep_after_next_match is not None:
|
||||
command = sleep_after_next_match.group(1)
|
||||
interval = int(sleep_after_next_match.group(2))
|
||||
self._sleepAfterNext[command] = interval
|
||||
self.outgoing.put("// going to sleep {interval} seconds after next {command}".format(**locals()))
|
||||
self._send("// going to sleep {interval} seconds after next {command}".format(**locals()))
|
||||
elif custom_action_match is not None:
|
||||
action = custom_action_match.group(1)
|
||||
params = custom_action_match.group(2)
|
||||
params = params.strip() if params is not None else ""
|
||||
self.outgoing.put("// action:{action} {params}".format(**locals()).strip())
|
||||
self._send("// action:{action} {params}".format(**locals()).strip())
|
||||
except:
|
||||
pass
|
||||
|
||||
def _listSd(self):
|
||||
self.outgoing.put("Begin file list")
|
||||
self._send("Begin file list")
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "extendedSdFileList"]):
|
||||
items = map(
|
||||
lambda x: "%s %d" % (x.upper(), os.stat(os.path.join(self._virtualSd, x)).st_size),
|
||||
@@ -363,20 +374,20 @@ class VirtualPrinter():
|
||||
os.listdir(self._virtualSd)
|
||||
)
|
||||
for item in items:
|
||||
self.outgoing.put(item)
|
||||
self.outgoing.put("End file list")
|
||||
self._send(item)
|
||||
self._send("End file list")
|
||||
|
||||
def _selectSdFile(self, filename):
|
||||
if filename.startswith("/"):
|
||||
filename = filename[1:]
|
||||
file = os.path.join(self._virtualSd, filename.lower())
|
||||
if not os.path.exists(file) or not os.path.isfile(file):
|
||||
self.outgoing.put("open failed, File: %s." % filename)
|
||||
self._send("open failed, File: %s." % filename)
|
||||
else:
|
||||
self._selectedSdFile = file
|
||||
self._selectedSdFileSize = os.stat(file).st_size
|
||||
self.outgoing.put("File opened: %s Size: %d" % (filename, self._selectedSdFileSize))
|
||||
self.outgoing.put("File selected")
|
||||
self._send("File opened: %s Size: %d" % (filename, self._selectedSdFileSize))
|
||||
self._send("File selected")
|
||||
|
||||
def _startSdPrint(self):
|
||||
if self._selectedSdFile is not None:
|
||||
@@ -393,9 +404,9 @@ class VirtualPrinter():
|
||||
|
||||
def _reportSdStatus(self):
|
||||
if self._sdPrinter is not None and self._sdPrintingSemaphore.is_set:
|
||||
self.outgoing.put("SD printing byte %d/%d" % (self._selectedSdFilePos, self._selectedSdFileSize))
|
||||
self._send("SD printing byte %d/%d" % (self._selectedSdFilePos, self._selectedSdFileSize))
|
||||
else:
|
||||
self.outgoing.put("Not SD printing")
|
||||
self._send("Not SD printing")
|
||||
|
||||
def _processTemperatureQuery(self):
|
||||
includeTarget = not settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"])
|
||||
@@ -432,7 +443,7 @@ class VirtualPrinter():
|
||||
|
||||
if includeOk:
|
||||
output = "ok " + output
|
||||
self.outgoing.put(output)
|
||||
self._send(output)
|
||||
|
||||
def _parseHotendCommand(self, line):
|
||||
tool = 0
|
||||
@@ -454,7 +465,7 @@ class VirtualPrinter():
|
||||
if "M109" in line:
|
||||
self._waitForHeatup("tool%d" % tool)
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"]):
|
||||
self.outgoing.put("TargetExtr%d:%d" % (tool, self.targetTemp[tool]))
|
||||
self._send("TargetExtr%d:%d" % (tool, self.targetTemp[tool]))
|
||||
|
||||
def _parseBedCommand(self, line):
|
||||
try:
|
||||
@@ -465,7 +476,7 @@ class VirtualPrinter():
|
||||
if "M190" in line:
|
||||
self._waitForHeatup("bed")
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"]):
|
||||
self.outgoing.put("TargetBed:%d" % self.bedTargetTemp)
|
||||
self._send("TargetBed:%d" % self.bedTargetTemp)
|
||||
|
||||
def _performMove(self, line):
|
||||
matchX = re.search("X([0-9.]+)", line)
|
||||
@@ -520,7 +531,7 @@ class VirtualPrinter():
|
||||
slept = 0
|
||||
while duration - slept > self._read_timeout:
|
||||
time.sleep(self._read_timeout)
|
||||
self.outgoing.put("wait")
|
||||
self._send("wait")
|
||||
slept += self._read_timeout
|
||||
else:
|
||||
time.sleep(duration)
|
||||
@@ -563,11 +574,11 @@ class VirtualPrinter():
|
||||
if os.path.isfile(file):
|
||||
os.remove(file)
|
||||
else:
|
||||
self.outgoing.put("error writing to file")
|
||||
self._send("error writing to file")
|
||||
|
||||
self._writingToSd = True
|
||||
self._selectedSdFile = file
|
||||
self.outgoing.put("Writing to file: %s" % filename)
|
||||
self._send("Writing to file: %s" % filename)
|
||||
|
||||
def _finishSdFile(self):
|
||||
self._writingToSd = False
|
||||
@@ -599,7 +610,7 @@ class VirtualPrinter():
|
||||
self._sdPrintingSemaphore.clear()
|
||||
self._selectedSdFilePos = 0
|
||||
self._sdPrinter = None
|
||||
self.outgoing.put("Done printing file")
|
||||
self._send("Done printing file")
|
||||
|
||||
def _waitForHeatup(self, heater):
|
||||
delta = 1
|
||||
@@ -608,12 +619,12 @@ class VirtualPrinter():
|
||||
toolNum = int(heater[len("tool"):])
|
||||
while self.temp[toolNum] < self.targetTemp[toolNum] - delta or self.temp[toolNum] > self.targetTemp[toolNum] + delta:
|
||||
self._simulateTemps(delta=delta)
|
||||
self.outgoing.put("T:%0.2f" % self.temp[toolNum])
|
||||
self._send("T:%0.2f" % self.temp[toolNum])
|
||||
time.sleep(delay)
|
||||
elif heater == "bed":
|
||||
while self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta:
|
||||
self._simulateTemps(delta=delta)
|
||||
self.outgoing.put("B:%0.2f" % self.bedTemp)
|
||||
self._send("B:%0.2f" % self.bedTemp)
|
||||
time.sleep(delay)
|
||||
|
||||
def _deleteSdFile(self, filename):
|
||||
@@ -664,6 +675,7 @@ class VirtualPrinter():
|
||||
return
|
||||
try:
|
||||
self.incoming.put(data, timeout=self._write_timeout)
|
||||
self._seriallog.info("<<< {}".format(data.strip()))
|
||||
except Queue.Full:
|
||||
self._logger.info("Incoming queue is full, raising SerialTimeoutException")
|
||||
raise SerialTimeoutException()
|
||||
@@ -675,6 +687,7 @@ class VirtualPrinter():
|
||||
try:
|
||||
line = self.outgoing.get(timeout=self._read_timeout)
|
||||
time.sleep(settings().getFloat(["devel", "virtualPrinter", "throttle"]))
|
||||
self._seriallog.info(">>> {}".format(line.strip()))
|
||||
return line
|
||||
except Queue.Empty:
|
||||
return ""
|
||||
@@ -686,14 +699,18 @@ class VirtualPrinter():
|
||||
|
||||
def _sendOk(self):
|
||||
if settings().getBoolean(["devel", "virtualPrinter", "okWithLinenumber"]):
|
||||
self.outgoing.put("ok %d" % self.lastN)
|
||||
self._send("ok %d" % self.lastN)
|
||||
else:
|
||||
self.outgoing.put("ok")
|
||||
self._send("ok")
|
||||
|
||||
def _sendWaitAfterTimeout(self, timeout=5):
|
||||
time.sleep(timeout)
|
||||
if self.outgoing is not None:
|
||||
self.outgoing.put("wait")
|
||||
self._send("wait")
|
||||
|
||||
def _send(self, line):
|
||||
if self.outgoing is not None:
|
||||
self.outgoing.put(line)
|
||||
|
||||
class CharCountingQueue(Queue.Queue):
|
||||
|
||||
|
||||
@@ -221,6 +221,10 @@ class PrinterInterface(object):
|
||||
|
||||
Arguments:
|
||||
path (str): The path to select for printing. Either an absolute path (local file) or a
|
||||
filename (SD card).
|
||||
sd (boolean): Indicates whether the file is on the SD card or not.
|
||||
printAfterSelect (boolean): Indicates whether a print should be started
|
||||
after the file is selected.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@@ -255,6 +259,31 @@ class PrinterInterface(object):
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def get_state_id(self):
|
||||
"""
|
||||
Identifier of the current communication state.
|
||||
|
||||
Possible values are:
|
||||
|
||||
* OPEN_SERIAL
|
||||
* DETECT_SERIAL
|
||||
* DETECT_BAUDRATE
|
||||
* CONNECTING
|
||||
* OPERATIONAL
|
||||
* PRINTING
|
||||
* PAUSED
|
||||
* CLOSED
|
||||
* ERROR
|
||||
* CLOSED_WITH_ERROR
|
||||
* TRANFERING_FILE
|
||||
* OFFLINE
|
||||
* UNKNOWN
|
||||
* NONE
|
||||
|
||||
Returns:
|
||||
(str) A unique identifier corresponding to the current communication state.
|
||||
"""
|
||||
|
||||
def get_current_data(self):
|
||||
"""
|
||||
Returns:
|
||||
|
||||
@@ -191,7 +191,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
will be attempted.
|
||||
"""
|
||||
if self._comm is not None:
|
||||
self._comm.close()
|
||||
self.disconnect()
|
||||
|
||||
eventManager().fire(Events.CONNECTING)
|
||||
self._printerProfileManager.select(profile)
|
||||
self._comm = comm.MachineCom(port, baudrate, callbackObject=self, printerProfileManager=self._printerProfileManager)
|
||||
|
||||
@@ -199,11 +201,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
"""
|
||||
Closes the connection to the printer.
|
||||
"""
|
||||
eventManager().fire(Events.DISCONNECTING)
|
||||
if self._comm is not None:
|
||||
self._comm.close()
|
||||
self._comm = None
|
||||
self._printerProfileManager.deselect()
|
||||
eventManager().fire(Events.DISCONNECTED)
|
||||
else:
|
||||
eventManager().fire(Events.DISCONNECTED)
|
||||
|
||||
def get_transport(self):
|
||||
|
||||
@@ -389,6 +391,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window, threshold=threshold, countdown=countdown)
|
||||
|
||||
self._lastProgressReport = None
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setCurrentZ(None)
|
||||
self._comm.startPrint()
|
||||
|
||||
@@ -425,14 +428,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
payload["origin"] = FileDestinations.SDCARD
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
|
||||
def get_state_string(self):
|
||||
"""
|
||||
Returns a human readable string corresponding to the current communication state.
|
||||
"""
|
||||
def get_state_string(self, state=None):
|
||||
if self._comm is None:
|
||||
return "Offline"
|
||||
else:
|
||||
return self._comm.getStateString()
|
||||
return self._comm.getStateString(state=state)
|
||||
|
||||
def get_state_id(self, state=None):
|
||||
if self._comm is None:
|
||||
return "OFFLINE"
|
||||
else:
|
||||
return self._comm.getStateId(state=state)
|
||||
|
||||
def get_current_data(self):
|
||||
return self._stateMonitor.get_current_data()
|
||||
@@ -560,6 +566,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._state = state
|
||||
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
|
||||
|
||||
payload = dict(
|
||||
state_id=self.get_state_id(self._state),
|
||||
state_string=self.get_state_string(self._state)
|
||||
)
|
||||
eventManager().fire(Events.PRINTER_STATE_CHANGED, payload)
|
||||
|
||||
def _addLog(self, log):
|
||||
self._log.append(log)
|
||||
self._stateMonitor.add_log(log)
|
||||
@@ -774,6 +786,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
|
||||
self._setProgressData(0, None, None, None)
|
||||
self._setCurrentZ(None)
|
||||
self._setJobData(None, None, None)
|
||||
self._printerProfileManager.deselect()
|
||||
eventManager().fire(Events.DISCONNECTED)
|
||||
|
||||
self._setState(state)
|
||||
|
||||
|
||||
@@ -623,6 +623,7 @@ class Server():
|
||||
|
||||
def _setup_jinja2(self):
|
||||
app.jinja_env.add_extension("jinja2.ext.do")
|
||||
app.jinja_env.add_extension("octoprint.server.util.jinja.trycatch")
|
||||
|
||||
# configure additional template folders for jinja2
|
||||
import jinja2
|
||||
@@ -736,16 +737,58 @@ class Server():
|
||||
# clean the folder
|
||||
if settings().getBoolean(["devel", "webassets", "clean_on_startup"]):
|
||||
import shutil
|
||||
import errno
|
||||
import sys
|
||||
|
||||
for entry in ("webassets", ".webassets-cache"):
|
||||
path = os.path.join(base_folder, entry)
|
||||
self._logger.debug("Deleting {path}...".format(**locals()))
|
||||
|
||||
# delete path if it exists
|
||||
if os.path.isdir(path):
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
elif os.path.isfile(path):
|
||||
try:
|
||||
os.remove(path)
|
||||
self._logger.debug("Deleting {path}...".format(**locals()))
|
||||
shutil.rmtree(path)
|
||||
except:
|
||||
self._logger.exception("Exception while trying to delete {entry} from {base_folder}".format(**locals()))
|
||||
self._logger.exception("Error while trying to delete {path}, leaving it alone".format(**locals()))
|
||||
continue
|
||||
|
||||
# re-create path
|
||||
self._logger.debug("Creating {path}...".format(**locals()))
|
||||
error_text = "Error while trying to re-create {path}, that might cause errors with the webassets cache".format(**locals())
|
||||
try:
|
||||
os.makedirs(path)
|
||||
except OSError as e:
|
||||
if e.errno == errno.EACCES:
|
||||
# that might be caused by the user still having the folder open somewhere, let's try again after
|
||||
# waiting a bit
|
||||
import time
|
||||
for n in xrange(3):
|
||||
time.sleep(0.5)
|
||||
self._logger.debug("Creating {path}: Retry #{retry} after {time}s".format(path=path, retry=n+1, time=(n + 1)*0.5))
|
||||
try:
|
||||
os.makedirs(path)
|
||||
break
|
||||
except:
|
||||
if self._logger.isEnabledFor(logging.DEBUG):
|
||||
self._logger.exception("Ignored error while creating directory {path}".format(**locals()))
|
||||
pass
|
||||
else:
|
||||
# this will only get executed if we never did
|
||||
# successfully execute makedirs above
|
||||
self._logger.exception(error_text)
|
||||
continue
|
||||
else:
|
||||
# not an access error, so something we don't understand
|
||||
# went wrong -> log an error and stop
|
||||
self._logger.exception(error_text)
|
||||
continue
|
||||
except:
|
||||
# not an OSError, so something we don't understand
|
||||
# went wrong -> log an error and stop
|
||||
self._logger.exception(error_text)
|
||||
continue
|
||||
|
||||
self._logger.info("Reset webasset folder {path}...".format(**locals()))
|
||||
|
||||
AdjustedEnvironment = type(Environment)(Environment.__name__, (Environment,), dict(
|
||||
resolver_class=util.flask.PluginAssetResolver
|
||||
@@ -766,6 +809,7 @@ class Server():
|
||||
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
|
||||
enable_timelapse = (settings().get(["webcam", "snapshot"]) and settings().get(["webcam", "ffmpeg"]))
|
||||
preferred_stylesheet = settings().get(["devel", "stylesheet"])
|
||||
minify = settings().getBoolean(["devel", "webassets", "minify"])
|
||||
|
||||
dynamic_assets = util.flask.collect_plugin_assets(
|
||||
enable_gcodeviewer=enable_gcodeviewer,
|
||||
@@ -774,7 +818,7 @@ class Server():
|
||||
)
|
||||
|
||||
js_libs = [
|
||||
"js/lib/jquery/jquery.min.js",
|
||||
"js/lib/jquery/jquery-2.1.4.min.js" if minify else "js/lib/jquery/jquery-2.1.4.js",
|
||||
"js/lib/modernizr.custom.js",
|
||||
"js/lib/lodash.min.js",
|
||||
"js/lib/sprintf.min.js",
|
||||
@@ -858,7 +902,7 @@ class Server():
|
||||
register_filter(JsDelimiterBundle)
|
||||
|
||||
js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters="js_delimiter_bundler")
|
||||
if settings().getBoolean(["devel", "webassets", "minify"]):
|
||||
if minify:
|
||||
js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="rjsmin, js_delimiter_bundler")
|
||||
else:
|
||||
js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="js_delimiter_bundler")
|
||||
|
||||
@@ -263,6 +263,9 @@ def utilTestPath():
|
||||
from octoprint.util.paths import normalize
|
||||
|
||||
path = normalize(data["path"])
|
||||
if not path:
|
||||
return jsonify(path=path, exists=False, typeok=False, access=False, result=False)
|
||||
|
||||
check_type = None
|
||||
check_access = []
|
||||
|
||||
|
||||
@@ -84,7 +84,10 @@ def getSettings():
|
||||
"timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]),
|
||||
"log": s.getBoolean(["serial", "log"]),
|
||||
"additionalPorts": s.get(["serial", "additionalPorts"]),
|
||||
"longRunningCommands": s.get(["serial", "longRunningCommands"])
|
||||
"additionalBaudrates": s.get(["serial", "additionalBaudrates"]),
|
||||
"longRunningCommands": s.get(["serial", "longRunningCommands"]),
|
||||
"checksumRequiringCommands": s.get(["serial", "checksumRequiringCommands"]),
|
||||
"helloCommand": s.get(["serial", "helloCommand"])
|
||||
},
|
||||
"folder": {
|
||||
"uploads": s.getBaseFolder("uploads"),
|
||||
@@ -105,6 +108,7 @@ def getSettings():
|
||||
"scripts": {
|
||||
"gcode": {
|
||||
"afterPrinterConnected": None,
|
||||
"beforePrinterDisconnected": None,
|
||||
"beforePrintStarted": None,
|
||||
"afterPrintCancelled": None,
|
||||
"afterPrintDone": None,
|
||||
@@ -112,6 +116,13 @@ def getSettings():
|
||||
"afterPrintResumed": None,
|
||||
"snippets": dict()
|
||||
}
|
||||
},
|
||||
"server": {
|
||||
"commands": {
|
||||
"systemShutdownCommand": s.get(["server", "commands", "systemShutdownCommand"]),
|
||||
"systemRestartCommand": s.get(["server", "commands", "systemRestartCommand"]),
|
||||
"serverRestartCommand": s.get(["server", "commands", "serverRestartCommand"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,7 +223,10 @@ def setSettings():
|
||||
if "timeoutTemperature" in data["serial"].keys(): s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"])
|
||||
if "timeoutSdStatus" in data["serial"].keys(): s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
|
||||
if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"])
|
||||
if "additionalBaudrates" in data["serial"] and isinstance(data["serial"]["additionalBaudrates"], (list, tuple)): s.set(["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"])
|
||||
if "longRunningCommands" in data["serial"] and isinstance(data["serial"]["longRunningCommands"], (list, tuple)): s.set(["serial", "longRunningCommands"], data["serial"]["longRunningCommands"])
|
||||
if "checksumRequiringCommands" in data["serial"] and isinstance(data["serial"]["checksumRequiringCommands"], (list, tuple)): s.set(["serial", "checksumRequiringCommands"], data["serial"]["checksumRequiringCommands"])
|
||||
if "helloCommand" in data["serial"]: s.set(["serial", "helloCommand"], data["serial"]["helloCommand"])
|
||||
|
||||
oldLog = s.getBoolean(["serial", "log"])
|
||||
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
|
||||
@@ -250,6 +264,12 @@ def setSettings():
|
||||
continue
|
||||
s.saveScript("gcode", name, script.replace("\r\n", "\n").replace("\r", "\n"))
|
||||
|
||||
if "server" in data:
|
||||
if "commands" in data["server"]:
|
||||
if "systemShutdownCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemShutdownCommand"], data["server"]["commands"]["systemShutdownCommand"])
|
||||
if "systemRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "systemRestartCommand"], data["server"]["commands"]["systemRestartCommand"])
|
||||
if "serverRestartCommand" in data["server"]["commands"].keys(): s.set(["server", "commands", "serverRestartCommand"], data["server"]["commands"]["serverRestartCommand"])
|
||||
|
||||
if "plugins" in data:
|
||||
for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin):
|
||||
plugin_id = plugin._identifier
|
||||
|
||||
@@ -29,14 +29,14 @@ def getTimelapseData():
|
||||
config = {"type": "off"}
|
||||
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
|
||||
config["type"] = "zchange"
|
||||
config["postRoll"] = timelapse.postRoll()
|
||||
config["fps"] = timelapse.fps()
|
||||
config["postRoll"] = timelapse.post_roll
|
||||
config["fps"] = timelapse.fps
|
||||
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
|
||||
config["type"] = "timed"
|
||||
config["postRoll"] = timelapse.postRoll()
|
||||
config["fps"] = timelapse.fps()
|
||||
config["postRoll"] = timelapse.post_roll
|
||||
config["fps"] = timelapse.fps
|
||||
config.update({
|
||||
"interval": timelapse.interval()
|
||||
"interval": timelapse.interval
|
||||
})
|
||||
|
||||
files = octoprint.timelapse.getFinishedTimelapses()
|
||||
|
||||
@@ -123,12 +123,19 @@ def enable_additional_translations(default_locale="en", additional_folders=None)
|
||||
|
||||
def fix_webassets_cache():
|
||||
from webassets import cache
|
||||
import os
|
||||
import tempfile
|
||||
import pickle
|
||||
import shutil
|
||||
|
||||
error_logger = logging.getLogger(__name__ + ".fix_webassets_cache")
|
||||
|
||||
def fixed_set(self, key, data):
|
||||
import os
|
||||
import tempfile
|
||||
import pickle
|
||||
import shutil
|
||||
|
||||
if not os.path.exists(self.directory):
|
||||
error_logger.warn("Cache directory {} doesn't exist, not going "
|
||||
"to attempt to write cache file".format(self.directory))
|
||||
|
||||
md5 = '%s' % cache.make_md5(self.V, key)
|
||||
filename = os.path.join(self.directory, md5)
|
||||
fd, temp_filename = tempfile.mkstemp(prefix='.' + md5,
|
||||
@@ -148,6 +155,11 @@ def fix_webassets_cache():
|
||||
import warnings
|
||||
from webassets.cache import make_md5
|
||||
|
||||
if not os.path.exists(self.directory):
|
||||
error_logger.warn("Cache directory {} doesn't exist, not going "
|
||||
"to attempt to read cache file".format(self.directory))
|
||||
return None
|
||||
|
||||
try:
|
||||
hash = make_md5(self.V, key)
|
||||
except IOError as e:
|
||||
@@ -194,12 +206,15 @@ def fix_webassets_filtertool():
|
||||
try:
|
||||
content = func().getvalue()
|
||||
if self.cache:
|
||||
log.debug('Storing result in cache with key %s', key,)
|
||||
self.cache.set(key, content)
|
||||
try:
|
||||
log.debug('Storing result in cache with key %s', key,)
|
||||
self.cache.set(key, content)
|
||||
except:
|
||||
error_logger.exception("Got an exception while trying to save file to cache, not caching")
|
||||
return MemoryHunk(content)
|
||||
except:
|
||||
error_logger.exception("Got an exception while trying to apply filter, ignoring file")
|
||||
return MemoryHunk("")
|
||||
return MemoryHunk(u"")
|
||||
|
||||
FilterTool._wrap_cache = fixed_wrap_cache
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
from jinja2 import nodes
|
||||
from jinja2.ext import Extension
|
||||
|
||||
import logging
|
||||
|
||||
class ExceptionHandlerExtension(Extension):
|
||||
tags = {"try"}
|
||||
|
||||
def __init__(self, environment):
|
||||
super(ExceptionHandlerExtension, self).__init__(environment)
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
def parse(self, parser):
|
||||
token = parser.stream.next()
|
||||
lineno = token.lineno
|
||||
filename = parser.name
|
||||
error = parser.parse_expression()
|
||||
|
||||
args = [error, nodes.Const(filename), nodes.Const(lineno)]
|
||||
try:
|
||||
body = parser.parse_statements(["name:endtry"], drop_needle=True)
|
||||
node = nodes.CallBlock(self.call_method("_handle_body", args),
|
||||
[], [], body).set_lineno(lineno)
|
||||
except Exception as e:
|
||||
# that was expected
|
||||
self._logger.exception("Caught exception while parsing template")
|
||||
node = nodes.CallBlock(self.call_method("_handle_error", [nodes.Const(self._format_error(error, e, filename, lineno))]),
|
||||
[], [], []).set_lineno(lineno)
|
||||
|
||||
return node
|
||||
|
||||
def _handle_body(self, error, filename, lineno, caller):
|
||||
try:
|
||||
return caller()
|
||||
except Exception as e:
|
||||
self._logger.exception("Caught exception while compiling template {filename} at line {lineno}".format(**locals()))
|
||||
error_string = self._format_error(error, e, filename, lineno)
|
||||
return error_string if error_string else ""
|
||||
|
||||
def _handle_error(self, error, caller):
|
||||
return error if error else ""
|
||||
|
||||
def _format_error(self, error, exception, filename, lineno):
|
||||
if not error:
|
||||
return ""
|
||||
|
||||
try:
|
||||
return error.format(exception=exception, filename=filename, lineno=lineno)
|
||||
except:
|
||||
self._logger.exception("Error while compiling exception output for template {filename} at line {lineno}".format(**locals()))
|
||||
return "Unknown error"
|
||||
|
||||
trycatch = ExceptionHandlerExtension
|
||||
@@ -245,7 +245,7 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
|
||||
self._on_part_header(self._buffer[delimiter_len+2:end_of_header])
|
||||
self._buffer = self._buffer[end_of_header + 4:]
|
||||
|
||||
if delimiter_loc != -1 and self._buffer[delimiter_len:delimiter_len+2] == "--":
|
||||
if delimiter_loc != -1 and self._buffer.strip() == delimiter + "--":
|
||||
# we saw the last boundary and are at the end of our request
|
||||
if self._current_part:
|
||||
self._on_part_finish(self._current_part)
|
||||
@@ -360,13 +360,24 @@ class UploadStorageFallbackHandler(tornado.web.RequestHandler):
|
||||
for name, part in self._parts.iteritems():
|
||||
if "filename" in part:
|
||||
# add form fields for filename, path, size and content_type for all files contained in the request
|
||||
fields = dict((self._suffixes[key], value) for (key, value) in dict(name=part["filename"], path=part["path"], size=str(os.stat(part["path"]).st_size), content_type=part["content_type"]).iteritems())
|
||||
if not "path" in part:
|
||||
continue
|
||||
|
||||
parameters = dict(
|
||||
name=part["filename"],
|
||||
path=part["path"],
|
||||
size=str(os.stat(part["path"]).st_size)
|
||||
)
|
||||
if "content_type" in part:
|
||||
parameters["content_type"] = part["content_type"]
|
||||
|
||||
fields = dict((self._suffixes[key], value) for (key, value) in parameters.iteritems())
|
||||
for n, p in fields.iteritems():
|
||||
key = name + "." + n
|
||||
self._new_body += b"--%s\r\n" % self._multipart_boundary
|
||||
self._new_body += b"Content-Disposition: form-data; name=\"%s\"\r\n" % key
|
||||
self._new_body += b"\r\n"
|
||||
self._new_body += p + b"\r\n"
|
||||
self._new_body += b"%s\r\n" % p
|
||||
elif "data" in part:
|
||||
self._new_body += b"--%s\r\n" % self._multipart_boundary
|
||||
value = part["data"]
|
||||
@@ -924,4 +935,4 @@ def path_validation_factory(path_filter, status_code=404):
|
||||
def f(path):
|
||||
if not path_filter(path):
|
||||
raise tornado.web.HTTPError(status_code)
|
||||
return f
|
||||
return f
|
||||
@@ -154,6 +154,7 @@ def index():
|
||||
folders=(gettext("Folders"), dict(template="dialogs/settings/folders.jinja2", _div="settings_folders", custom_bindings=False)),
|
||||
appearance=(gettext("Appearance"), dict(template="dialogs/settings/appearance.jinja2", _div="settings_appearance", custom_bindings=False)),
|
||||
logs=(gettext("Logs"), dict(template="dialogs/settings/logs.jinja2", _div="settings_logs")),
|
||||
server=(gettext("Server"), dict(template="dialogs/settings/server.jinja2", _div="settings_server", custom_bindings=False)),
|
||||
)
|
||||
if enable_accesscontrol:
|
||||
templates["settings"]["entries"]["accesscontrol"] = (gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False))
|
||||
@@ -257,9 +258,30 @@ def index():
|
||||
# finally add anything that's not included in our order yet
|
||||
sorted_missing = list(missing_in_order)
|
||||
if template_sorting[t]["key"] is not None:
|
||||
# anything but navbar and generic components get sorted by their name
|
||||
if template_sorting[t]["key"] == "name":
|
||||
sorted_missing = sorted(missing_in_order, key=lambda x: templates[t]["entries"][x][0])
|
||||
# default extractor: works with entries that are dicts and entries that are 2-tuples with the
|
||||
# entry data at index 1
|
||||
def extractor(item, key):
|
||||
if isinstance(item, dict) and key in item:
|
||||
return item[key]
|
||||
elif isinstance(item, tuple) and len(item) > 1 and isinstance(item[1], dict) and key in item[1]:
|
||||
return item[1][key]
|
||||
|
||||
return None
|
||||
|
||||
# if template type provides custom extractor, make sure its exceptions are handled
|
||||
if "key_extractor" in template_sorting[t] and callable(template_sorting[t]["key_extractor"]):
|
||||
def create_safe_extractor(extractor):
|
||||
def f(x, k):
|
||||
try:
|
||||
return extractor(x, k)
|
||||
except:
|
||||
_logger.exception("Error while extracting sorting keys for template {}".format(t))
|
||||
return None
|
||||
return f
|
||||
extractor = create_safe_extractor(template_sorting[t]["key_extractor"])
|
||||
|
||||
sort_key = template_sorting[t]["key"]
|
||||
sorted_missing = sorted(missing_in_order, key=lambda x: extractor(templates[t]["entries"][x], sort_key))
|
||||
|
||||
if template_sorting[t]["add"] == "prepend":
|
||||
templates[t]["order"] = sorted_missing + templates[t]["order"]
|
||||
@@ -351,6 +373,8 @@ def _process_template_configs(name, implementation, configs, rules):
|
||||
app.jinja_env.get_or_select_template(data["template"])
|
||||
except TemplateNotFound:
|
||||
pass
|
||||
except:
|
||||
_logger.exception("Error in template {}, not going to include it".format(data["template"]))
|
||||
else:
|
||||
includes[template_type].append(rule["to_entry"](data))
|
||||
|
||||
|
||||
@@ -83,7 +83,10 @@ default_settings = {
|
||||
"sdStatus": 1
|
||||
},
|
||||
"additionalPorts": [],
|
||||
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32"]
|
||||
"additionalBaudrates": [],
|
||||
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226"],
|
||||
"checksumRequiringCommands": ["M110"],
|
||||
"helloCommand": "M110 N0"
|
||||
},
|
||||
"server": {
|
||||
"host": "0.0.0.0",
|
||||
@@ -104,6 +107,11 @@ default_settings = {
|
||||
"pathSuffix": "path"
|
||||
},
|
||||
"maxSize": 100 * 1024, # 100 KB
|
||||
"commands": {
|
||||
"systemShutdownCommand": None,
|
||||
"systemRestartCommand": None,
|
||||
"serverRestartCommand": None
|
||||
}
|
||||
},
|
||||
"webcam": {
|
||||
"stream": None,
|
||||
@@ -188,7 +196,7 @@ default_settings = {
|
||||
"settings": [
|
||||
"section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts",
|
||||
"section_features", "features", "webcam", "accesscontrol", "api",
|
||||
"section_octoprint", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate"
|
||||
"section_octoprint", "server", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate"
|
||||
],
|
||||
"usersettings": ["access", "interface"],
|
||||
"wizard": ["access"],
|
||||
@@ -322,14 +330,14 @@ class Settings(object):
|
||||
|
||||
"/dev/ttyACM0"
|
||||
|
||||
``["serial", "timeouts"]`` ::
|
||||
``["serial", "timeout"]`` ::
|
||||
|
||||
communication: 20.0
|
||||
temperature: 5.0
|
||||
sdStatus: 1.0
|
||||
connection: 10.0
|
||||
|
||||
``["serial", "timeouts", "temperature"]`` ::
|
||||
``["serial", "timeout", "temperature"]`` ::
|
||||
|
||||
5.0
|
||||
|
||||
@@ -971,7 +979,7 @@ class Settings(object):
|
||||
if not force and key in defaults and key in config and defaults[key] == value:
|
||||
del config[key]
|
||||
self._dirty = True
|
||||
elif force or (not key in config and defaults[key] != value) or (key in config and config[key] != value):
|
||||
elif force or (not key in config and key in defaults and defaults[key] != value) or (key in config and config[key] != value):
|
||||
if value is None and key in config:
|
||||
del config[key]
|
||||
else:
|
||||
|
||||
@@ -176,6 +176,7 @@ function DataUpdater(allViewModels) {
|
||||
var type = data["type"];
|
||||
var payload = data["payload"];
|
||||
var html = "";
|
||||
var format = {};
|
||||
|
||||
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
|
||||
|
||||
@@ -186,7 +187,23 @@ function DataUpdater(allViewModels) {
|
||||
} else if (type == "MovieFailed") {
|
||||
html = "<p>" + _.sprintf(gettext("Rendering of timelapse %(movie_basename)s failed with return code %(returncode)s"), payload) + "</p>";
|
||||
html += pnotifyAdditionalInfo('<pre style="overflow: auto">' + payload.error + '</pre>');
|
||||
new PNotify({title: gettext("Rendering failed"), text: html, type: "error", hide: false});
|
||||
new PNotify({
|
||||
title: gettext("Rendering failed"),
|
||||
text: html,
|
||||
type: "error",
|
||||
hide: false
|
||||
});
|
||||
} else if (type == "PostRollStart") {
|
||||
if (payload.postroll_duration > 60) {
|
||||
format = {duration: _.sprintf(gettext("%(minutes)d min"), {minutes: payload.postroll_duration / 60})};
|
||||
} else {
|
||||
format = {duration: _.sprintf(gettext("%(seconds)d sec"), {seconds: payload.postroll_duration})};
|
||||
}
|
||||
|
||||
new PNotify({
|
||||
title: gettext("Capturing timelapse postroll"),
|
||||
text: _.sprintf(gettext("Now capturing timelapse post roll, this will take approximately %(duration)s..."), format)
|
||||
});
|
||||
} else if (type == "SlicingStarted") {
|
||||
gcodeUploadProgress.addClass("progress-striped").addClass("active");
|
||||
gcodeUploadProgressBar.css("width", "100%");
|
||||
|
||||
@@ -51,6 +51,7 @@ $(function() {
|
||||
//~~ Initialize PNotify
|
||||
|
||||
PNotify.prototype.options.styling = "bootstrap2";
|
||||
PNotify.prototype.options.mouse_reset = false;
|
||||
|
||||
//~~ Initialize view models
|
||||
|
||||
@@ -58,7 +59,7 @@ $(function() {
|
||||
var viewModelMap = {};
|
||||
|
||||
// Fix Function#name on browsers that do not support it (IE):
|
||||
// see: http://stackoverflow.com/questions/6903762/function-name-not-supported-in-ie
|
||||
// see: http://stackoverflow.com/questions/6903762/function-name-not-supported-in-ie
|
||||
if (!(function f() {}).name) {
|
||||
Object.defineProperty(Function.prototype, 'name', {
|
||||
get: function() {
|
||||
|
||||
@@ -86,6 +86,15 @@ $(function() {
|
||||
self._processStateData(data.state);
|
||||
};
|
||||
|
||||
self.openOrCloseOnStateChange = function() {
|
||||
var connectionTab = $("#connection");
|
||||
if (self.isOperational() && connectionTab.hasClass("in")) {
|
||||
connectionTab.collapse("hide");
|
||||
} else if (!self.isOperational() && !connectionTab.hasClass("in")) {
|
||||
connectionTab.collapse("show");
|
||||
}
|
||||
}
|
||||
|
||||
self._processStateData = function(data) {
|
||||
self.previousIsOperational = self.isOperational();
|
||||
|
||||
@@ -97,15 +106,10 @@ $(function() {
|
||||
self.isReady(data.flags.ready);
|
||||
self.isLoading(data.flags.loading);
|
||||
|
||||
var connectionTab = $("#connection");
|
||||
if (self.previousIsOperational != self.isOperational()) {
|
||||
if (self.isOperational() && connectionTab.hasClass("in")) {
|
||||
// connection just got established, close connection tab for now
|
||||
connectionTab.collapse("hide");
|
||||
} else if (!connectionTab.hasClass("in")) {
|
||||
// connection just dropped, make sure connection tab is open
|
||||
connectionTab.collapse("show");
|
||||
}
|
||||
if (self.loginState.isAdmin() && self.previousIsOperational != self.isOperational()) {
|
||||
// only open or close if the panel is visible (for admins) and
|
||||
// the state just changed to avoid thwarting manual open/close
|
||||
self.openOrCloseOnStateChange();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -147,6 +151,16 @@ $(function() {
|
||||
|
||||
self.onStartup = function() {
|
||||
self.requestData();
|
||||
|
||||
// when isAdmin becomes true the first time, set the panel open or
|
||||
// closed based on the connection state
|
||||
var subscription = self.loginState.isAdmin.subscribe(function(newValue) {
|
||||
if (newValue) {
|
||||
// wait until after the isAdmin state has run through all subscriptions
|
||||
setTimeout(self.openOrCloseOnStateChange, 0);
|
||||
subscription.dispose();
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,10 @@ $(function() {
|
||||
self.users = parameters[1];
|
||||
self.printerProfiles = parameters[2];
|
||||
|
||||
self.receiving = ko.observable(false);
|
||||
self.sending = ko.observable(false);
|
||||
self.callbacks = [];
|
||||
|
||||
self.enqueuedForSaving = undefined;
|
||||
|
||||
self.api_enabled = ko.observable(undefined);
|
||||
@@ -129,7 +133,10 @@ $(function() {
|
||||
self.serial_timeoutSdStatus = ko.observable(undefined);
|
||||
self.serial_log = ko.observable(undefined);
|
||||
self.serial_additionalPorts = ko.observable(undefined);
|
||||
self.serial_additionalBaudrates = ko.observable(undefined);
|
||||
self.serial_longRunningCommands = ko.observable(undefined);
|
||||
self.serial_checksumRequiringCommands = ko.observable(undefined);
|
||||
self.serial_helloCommand = ko.observable(undefined);
|
||||
|
||||
self.folder_uploads = ko.observable(undefined);
|
||||
self.folder_timelapse = ko.observable(undefined);
|
||||
@@ -143,6 +150,7 @@ $(function() {
|
||||
self.scripts_gcode_afterPrintPaused = ko.observable(undefined);
|
||||
self.scripts_gcode_beforePrintResumed = ko.observable(undefined);
|
||||
self.scripts_gcode_afterPrinterConnected = ko.observable(undefined);
|
||||
self.scripts_gcode_beforePrinterDisconnected = ko.observable(undefined);
|
||||
|
||||
self.temperature_profiles = ko.observableArray(undefined);
|
||||
self.temperature_cutoff = ko.observable(undefined);
|
||||
@@ -151,6 +159,10 @@ $(function() {
|
||||
|
||||
self.terminalFilters = ko.observableArray([]);
|
||||
|
||||
self.server_commands_systemShutdownCommand = ko.observable(undefined);
|
||||
self.server_commands_systemRestartCommand = ko.observable(undefined);
|
||||
self.server_commands_serverRestartCommand = ko.observable(undefined);
|
||||
|
||||
self.settings = undefined;
|
||||
|
||||
self.addTemperatureProfile = function() {
|
||||
@@ -259,13 +271,42 @@ $(function() {
|
||||
};
|
||||
|
||||
self.requestData = function(callback) {
|
||||
if (self.receiving()) {
|
||||
if (callback) {
|
||||
self.callbacks.push(callback);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
self.receiving(true);
|
||||
$.ajax({
|
||||
url: API_BASEURL + "settings",
|
||||
type: "GET",
|
||||
dataType: "json",
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
if (callback) callback();
|
||||
if (callback) {
|
||||
self.callbacks.push(callback);
|
||||
}
|
||||
|
||||
try {
|
||||
self.fromResponse(response);
|
||||
|
||||
var cb;
|
||||
while (self.callbacks.length) {
|
||||
cb = self.callbacks.shift();
|
||||
try {
|
||||
cb();
|
||||
} catch(exc) {
|
||||
log.error("Error calling settings callback", cb, ":", (exc.stack || exc));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
self.receiving(false);
|
||||
self.callbacks = [];
|
||||
}
|
||||
},
|
||||
error: function(xhr) {
|
||||
self.receiving(false);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -394,7 +435,10 @@ $(function() {
|
||||
self.serial_timeoutSdStatus(response.serial.timeoutSdStatus);
|
||||
self.serial_log(response.serial.log);
|
||||
self.serial_additionalPorts(response.serial.additionalPorts.join("\n"));
|
||||
self.serial_additionalBaudrates(response.serial.additionalBaudrates.join(", "));
|
||||
self.serial_longRunningCommands(response.serial.longRunningCommands.join(", "));
|
||||
self.serial_checksumRequiringCommands(response.serial.checksumRequiringCommands.join(", "));
|
||||
self.serial_helloCommand(response.serial.helloCommand);
|
||||
|
||||
self.folder_uploads(response.folder.uploads);
|
||||
self.folder_timelapse(response.folder.timelapse);
|
||||
@@ -410,6 +454,7 @@ $(function() {
|
||||
self.scripts_gcode_afterPrintPaused(response.scripts.gcode.afterPrintPaused);
|
||||
self.scripts_gcode_beforePrintResumed(response.scripts.gcode.beforePrintResumed);
|
||||
self.scripts_gcode_afterPrinterConnected(response.scripts.gcode.afterPrinterConnected);
|
||||
self.scripts_gcode_beforePrinterDisconnected(response.scripts.gcode.beforePrinterDisconnected);
|
||||
|
||||
self.temperature_profiles(response.temperature.profiles);
|
||||
self.temperature_cutoff(response.temperature.cutoff);
|
||||
@@ -417,12 +462,18 @@ $(function() {
|
||||
self.system_actions(response.system.actions);
|
||||
|
||||
self.terminalFilters(response.terminalFilters);
|
||||
|
||||
self.server_commands_systemShutdownCommand(response.server.commands.systemShutdownCommand);
|
||||
self.server_commands_systemRestartCommand(response.server.commands.systemRestartCommand);
|
||||
self.server_commands_serverRestartCommand(response.server.commands.serverRestartCommand);
|
||||
};
|
||||
|
||||
self.saveData = function (data, successCallback) {
|
||||
self.settingsDialog.trigger("beforeSave");
|
||||
|
||||
if (data == undefined) {
|
||||
// we only set sending to true when we didn't include data
|
||||
self.sending(true);
|
||||
data = ko.mapping.toJS(self.settings);
|
||||
|
||||
data = _.extend(data, {
|
||||
@@ -475,7 +526,10 @@ $(function() {
|
||||
"timeoutSdStatus": self.serial_timeoutSdStatus(),
|
||||
"log": self.serial_log(),
|
||||
"additionalPorts": commentableLinesToArray(self.serial_additionalPorts()),
|
||||
"longRunningCommands": splitTextToArray(self.serial_longRunningCommands(), ",", true)
|
||||
"additionalBaudrates": _.map(splitTextToArray(self.serial_additionalBaudrates(), ",", true, function(item) { return !isNaN(parseInt(item)); }), function(item) { return parseInt(item); }),
|
||||
"longRunningCommands": splitTextToArray(self.serial_longRunningCommands(), ",", true),
|
||||
"checksumRequiringCommands": splitTextToArray(self.serial_checksumRequiringCommands(), ",", true),
|
||||
"helloCommand": self.serial_helloCommand()
|
||||
},
|
||||
"folder": {
|
||||
"uploads": self.folder_uploads(),
|
||||
@@ -499,7 +553,15 @@ $(function() {
|
||||
"afterPrintCancelled": self.scripts_gcode_afterPrintCancelled(),
|
||||
"afterPrintPaused": self.scripts_gcode_afterPrintPaused(),
|
||||
"beforePrintResumed": self.scripts_gcode_beforePrintResumed(),
|
||||
"afterPrinterConnected": self.scripts_gcode_afterPrinterConnected()
|
||||
"afterPrinterConnected": self.scripts_gcode_afterPrinterConnected(),
|
||||
"beforePrinterDisconnected": self.scripts_gcode_beforePrinterDisconnected()
|
||||
}
|
||||
},
|
||||
"server": {
|
||||
"commands": {
|
||||
"systemShutdownCommand": self.server_commands_systemShutdownCommand(),
|
||||
"systemRestartCommand": self.server_commands_systemRestartCommand(),
|
||||
"serverRestartCommand": self.server_commands_serverRestartCommand()
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -512,12 +574,25 @@ $(function() {
|
||||
contentType: "application/json; charset=UTF-8",
|
||||
data: JSON.stringify(data),
|
||||
success: function(response) {
|
||||
self.fromResponse(response);
|
||||
if (successCallback) successCallback(response);
|
||||
self.receiving(true);
|
||||
self.sending(false);
|
||||
try {
|
||||
self.fromResponse(response);
|
||||
if (successCallback) successCallback(response);
|
||||
} finally {
|
||||
self.receiving(false);
|
||||
}
|
||||
},
|
||||
error: function(xhr) {
|
||||
self.sending(false);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
self.onEventSettingsUpdated = function() {
|
||||
self.requestData();
|
||||
};
|
||||
|
||||
self.enqueueForSaving = function(data) {
|
||||
if (self.enqueuedForSaving == undefined) {
|
||||
self.enqueuedForSaving = data;
|
||||
|
||||
@@ -86,7 +86,7 @@ $(function() {
|
||||
self._processCurrentLogData = function(data) {
|
||||
self.log(self.log().concat(_.map(data, function(line) { return self._toInternalFormat(line) })));
|
||||
if (self.autoscrollEnabled()) {
|
||||
self.log(self.log.slice(-300));
|
||||
self.log(self.log.slice(-self.buffer()));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+230
-109
@@ -1,8 +1,8 @@
|
||||
/* ===================================================
|
||||
* bootstrap-transition.js v2.2.2
|
||||
* http://twitter.github.com/bootstrap/javascript.html#transitions
|
||||
* bootstrap-transition.js v2.3.2
|
||||
* http://getbootstrap.com/2.3.2/javascript.html#transitions
|
||||
* ===================================================
|
||||
* Copyright 2012 Twitter, Inc.
|
||||
* Copyright 2013 Twitter, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -58,10 +58,10 @@
|
||||
})
|
||||
|
||||
}(window.jQuery);/* ==========================================================
|
||||
* bootstrap-alert.js v2.2.2
|
||||
* http://twitter.github.com/bootstrap/javascript.html#alerts
|
||||
* bootstrap-alert.js v2.3.2
|
||||
* http://getbootstrap.com/2.3.2/javascript.html#alerts
|
||||
* ==========================================================
|
||||
* Copyright 2012 Twitter, Inc.
|
||||
* Copyright 2013 Twitter, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -156,10 +156,10 @@
|
||||
$(document).on('click.alert.data-api', dismiss, Alert.prototype.close)
|
||||
|
||||
}(window.jQuery);/* ============================================================
|
||||
* bootstrap-button.js v2.2.2
|
||||
* http://twitter.github.com/bootstrap/javascript.html#buttons
|
||||
* bootstrap-button.js v2.3.2
|
||||
* http://getbootstrap.com/2.3.2/javascript.html#buttons
|
||||
* ============================================================
|
||||
* Copyright 2012 Twitter, Inc.
|
||||
* Copyright 2013 Twitter, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -260,10 +260,10 @@
|
||||
})
|
||||
|
||||
}(window.jQuery);/* ==========================================================
|
||||
* bootstrap-carousel.js v2.2.2
|
||||
* http://twitter.github.com/bootstrap/javascript.html#carousel
|
||||
* bootstrap-carousel.js v2.3.2
|
||||
* http://getbootstrap.com/2.3.2/javascript.html#carousel
|
||||
* ==========================================================
|
||||
* Copyright 2012 Twitter, Inc.
|
||||
* Copyright 2013 Twitter, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -289,6 +289,7 @@
|
||||
|
||||
var Carousel = function (element, options) {
|
||||
this.$element = $(element)
|
||||
this.$indicators = this.$element.find('.carousel-indicators')
|
||||
this.options = options
|
||||
this.options.pause == 'hover' && this.$element
|
||||
.on('mouseenter', $.proxy(this.pause, this))
|
||||
@@ -299,19 +300,24 @@
|
||||
|
||||
cycle: function (e) {
|
||||
if (!e) this.paused = false
|
||||
if (this.interval) clearInterval(this.interval);
|
||||
this.options.interval
|
||||
&& !this.paused
|
||||
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
|
||||
return this
|
||||
}
|
||||
|
||||
, getActiveIndex: function () {
|
||||
this.$active = this.$element.find('.item.active')
|
||||
this.$items = this.$active.parent().children()
|
||||
return this.$items.index(this.$active)
|
||||
}
|
||||
|
||||
, to: function (pos) {
|
||||
var $active = this.$element.find('.item.active')
|
||||
, children = $active.parent().children()
|
||||
, activePos = children.index($active)
|
||||
var activeIndex = this.getActiveIndex()
|
||||
, that = this
|
||||
|
||||
if (pos > (children.length - 1) || pos < 0) return
|
||||
if (pos > (this.$items.length - 1) || pos < 0) return
|
||||
|
||||
if (this.sliding) {
|
||||
return this.$element.one('slid', function () {
|
||||
@@ -319,18 +325,18 @@
|
||||
})
|
||||
}
|
||||
|
||||
if (activePos == pos) {
|
||||
if (activeIndex == pos) {
|
||||
return this.pause().cycle()
|
||||
}
|
||||
|
||||
return this.slide(pos > activePos ? 'next' : 'prev', $(children[pos]))
|
||||
return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos]))
|
||||
}
|
||||
|
||||
, pause: function (e) {
|
||||
if (!e) this.paused = true
|
||||
if (this.$element.find('.next, .prev').length && $.support.transition.end) {
|
||||
this.$element.trigger($.support.transition.end)
|
||||
this.cycle()
|
||||
this.cycle(true)
|
||||
}
|
||||
clearInterval(this.interval)
|
||||
this.interval = null
|
||||
@@ -364,10 +370,19 @@
|
||||
|
||||
e = $.Event('slide', {
|
||||
relatedTarget: $next[0]
|
||||
, direction: direction
|
||||
})
|
||||
|
||||
if ($next.hasClass('active')) return
|
||||
|
||||
if (this.$indicators.length) {
|
||||
this.$indicators.find('.active').removeClass('active')
|
||||
this.$element.one('slid', function () {
|
||||
var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()])
|
||||
$nextIndicator && $nextIndicator.addClass('active')
|
||||
})
|
||||
}
|
||||
|
||||
if ($.support.transition && this.$element.hasClass('slide')) {
|
||||
this.$element.trigger(e)
|
||||
if (e.isDefaultPrevented()) return
|
||||
@@ -412,7 +427,7 @@
|
||||
if (!data) $this.data('carousel', (data = new Carousel(this, options)))
|
||||
if (typeof option == 'number') data.to(option)
|
||||
else if (action) data[action]()
|
||||
else if (options.interval) data.cycle()
|
||||
else if (options.interval) data.pause().cycle()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -435,19 +450,26 @@
|
||||
/* CAROUSEL DATA-API
|
||||
* ================= */
|
||||
|
||||
$(document).on('click.carousel.data-api', '[data-slide]', function (e) {
|
||||
$(document).on('click.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
|
||||
var $this = $(this), href
|
||||
, $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
|
||||
, options = $.extend({}, $target.data(), $this.data())
|
||||
, slideIndex
|
||||
|
||||
$target.carousel(options)
|
||||
|
||||
if (slideIndex = $this.attr('data-slide-to')) {
|
||||
$target.data('carousel').pause().to(slideIndex).cycle()
|
||||
}
|
||||
|
||||
e.preventDefault()
|
||||
})
|
||||
|
||||
}(window.jQuery);/* =============================================================
|
||||
* bootstrap-collapse.js v2.2.2
|
||||
* http://twitter.github.com/bootstrap/javascript.html#collapse
|
||||
* bootstrap-collapse.js v2.3.2
|
||||
* http://getbootstrap.com/2.3.2/javascript.html#collapse
|
||||
* =============================================================
|
||||
* Copyright 2012 Twitter, Inc.
|
||||
* Copyright 2013 Twitter, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -497,7 +519,7 @@
|
||||
, actives
|
||||
, hasData
|
||||
|
||||
if (this.transitioning) return
|
||||
if (this.transitioning || this.$element.hasClass('in')) return
|
||||
|
||||
dimension = this.dimension()
|
||||
scroll = $.camelCase(['scroll', dimension].join('-'))
|
||||
@@ -517,7 +539,7 @@
|
||||
|
||||
, hide: function () {
|
||||
var dimension
|
||||
if (this.transitioning) return
|
||||
if (this.transitioning || !this.$element.hasClass('in')) return
|
||||
dimension = this.dimension()
|
||||
this.reset(this.$element[dimension]())
|
||||
this.transition('removeClass', $.Event('hide'), 'hidden')
|
||||
@@ -574,7 +596,7 @@
|
||||
return this.each(function () {
|
||||
var $this = $(this)
|
||||
, data = $this.data('collapse')
|
||||
, options = typeof option == 'object' && option
|
||||
, options = $.extend({}, $.fn.collapse.defaults, $this.data(), typeof option == 'object' && option)
|
||||
if (!data) $this.data('collapse', (data = new Collapse(this, options)))
|
||||
if (typeof option == 'string') data[option]()
|
||||
})
|
||||
@@ -610,10 +632,10 @@
|
||||
})
|
||||
|
||||
}(window.jQuery);/* ============================================================
|
||||
* bootstrap-dropdown.js v2.2.2
|
||||
* http://twitter.github.com/bootstrap/javascript.html#dropdowns
|
||||
* bootstrap-dropdown.js v2.3.2
|
||||
* http://getbootstrap.com/2.3.2/javascript.html#dropdowns
|
||||
* ============================================================
|
||||
* Copyright 2012 Twitter, Inc.
|
||||
* Copyright 2013 Twitter, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -663,6 +685,10 @@
|
||||
clearMenus()
|
||||
|
||||
if (!isActive) {
|
||||
if ('ontouchstart' in document.documentElement) {
|
||||
// if mobile we we use a backdrop because click events don't delegate
|
||||
$('<div class="dropdown-backdrop"/>').insertBefore($(this)).on('click', clearMenus)
|
||||
}
|
||||
$parent.toggleClass('open')
|
||||
}
|
||||
|
||||
@@ -692,7 +718,10 @@
|
||||
|
||||
isActive = $parent.hasClass('open')
|
||||
|
||||
if (!isActive || (isActive && e.keyCode == 27)) return $this.click()
|
||||
if (!isActive || (isActive && e.keyCode == 27)) {
|
||||
if (e.which == 27) $parent.find(toggle).focus()
|
||||
return $this.click()
|
||||
}
|
||||
|
||||
$items = $('[role=menu] li:not(.divider):visible a', $parent)
|
||||
|
||||
@@ -712,6 +741,7 @@
|
||||
}
|
||||
|
||||
function clearMenus() {
|
||||
$('.dropdown-backdrop').remove()
|
||||
$(toggle).each(function () {
|
||||
getParent($(this)).removeClass('open')
|
||||
})
|
||||
@@ -726,8 +756,9 @@
|
||||
selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
|
||||
}
|
||||
|
||||
$parent = $(selector)
|
||||
$parent.length || ($parent = $this.parent())
|
||||
$parent = selector && (selector != "#") && $(selector)
|
||||
|
||||
if (!$parent || !$parent.length) $parent = $this.parent()
|
||||
|
||||
return $parent
|
||||
}
|
||||
@@ -763,17 +794,17 @@
|
||||
* =================================== */
|
||||
|
||||
$(document)
|
||||
.on('click.dropdown.data-api touchstart.dropdown.data-api', clearMenus)
|
||||
.on('click.dropdown touchstart.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
|
||||
.on('touchstart.dropdown.data-api', '.dropdown-menu', function (e) { e.stopPropagation() })
|
||||
.on('click.dropdown.data-api touchstart.dropdown.data-api' , toggle, Dropdown.prototype.toggle)
|
||||
.on('keydown.dropdown.data-api touchstart.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown)
|
||||
.on('click.dropdown.data-api', clearMenus)
|
||||
.on('click.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
|
||||
.on('click.dropdown.data-api' , toggle, Dropdown.prototype.toggle)
|
||||
.on('keydown.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown)
|
||||
|
||||
}(window.jQuery);/* =========================================================
|
||||
* bootstrap-modal.js v2.2.2
|
||||
* http://twitter.github.com/bootstrap/javascript.html#modals
|
||||
}(window.jQuery);
|
||||
/* =========================================================
|
||||
* bootstrap-modal.js v2.3.2
|
||||
* http://getbootstrap.com/2.3.2/javascript.html#modals
|
||||
* =========================================================
|
||||
* Copyright 2012 Twitter, Inc.
|
||||
* Copyright 2013 Twitter, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -831,8 +862,7 @@
|
||||
that.$element.appendTo(document.body) //don't move modals dom position
|
||||
}
|
||||
|
||||
that.$element
|
||||
.show()
|
||||
that.$element.show()
|
||||
|
||||
if (transition) {
|
||||
that.$element[0].offsetWidth // force reflow
|
||||
@@ -910,16 +940,17 @@
|
||||
})
|
||||
}
|
||||
|
||||
, hideModal: function (that) {
|
||||
this.$element
|
||||
.hide()
|
||||
.trigger('hidden')
|
||||
|
||||
this.backdrop()
|
||||
, hideModal: function () {
|
||||
var that = this
|
||||
this.$element.hide()
|
||||
this.backdrop(function () {
|
||||
that.removeBackdrop()
|
||||
that.$element.trigger('hidden')
|
||||
})
|
||||
}
|
||||
|
||||
, removeBackdrop: function () {
|
||||
this.$backdrop.remove()
|
||||
this.$backdrop && this.$backdrop.remove()
|
||||
this.$backdrop = null
|
||||
}
|
||||
|
||||
@@ -943,6 +974,8 @@
|
||||
|
||||
this.$backdrop.addClass('in')
|
||||
|
||||
if (!callback) return
|
||||
|
||||
doAnimate ?
|
||||
this.$backdrop.one($.support.transition.end, callback) :
|
||||
callback()
|
||||
@@ -951,8 +984,8 @@
|
||||
this.$backdrop.removeClass('in')
|
||||
|
||||
$.support.transition && this.$element.hasClass('fade')?
|
||||
this.$backdrop.one($.support.transition.end, $.proxy(this.removeBackdrop, this)) :
|
||||
this.removeBackdrop()
|
||||
this.$backdrop.one($.support.transition.end, callback) :
|
||||
callback()
|
||||
|
||||
} else if (callback) {
|
||||
callback()
|
||||
@@ -1015,11 +1048,11 @@
|
||||
|
||||
}(window.jQuery);
|
||||
/* ===========================================================
|
||||
* bootstrap-tooltip.js v2.2.2
|
||||
* http://twitter.github.com/bootstrap/javascript.html#tooltips
|
||||
* bootstrap-tooltip.js v2.3.2
|
||||
* http://getbootstrap.com/2.3.2/javascript.html#tooltips
|
||||
* Inspired by the original jQuery.tipsy by Jason Frame
|
||||
* ===========================================================
|
||||
* Copyright 2012 Twitter, Inc.
|
||||
* Copyright 2013 Twitter, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -1054,19 +1087,27 @@
|
||||
, init: function (type, element, options) {
|
||||
var eventIn
|
||||
, eventOut
|
||||
, triggers
|
||||
, trigger
|
||||
, i
|
||||
|
||||
this.type = type
|
||||
this.$element = $(element)
|
||||
this.options = this.getOptions(options)
|
||||
this.enabled = true
|
||||
|
||||
if (this.options.trigger == 'click') {
|
||||
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
|
||||
} else if (this.options.trigger != 'manual') {
|
||||
eventIn = this.options.trigger == 'hover' ? 'mouseenter' : 'focus'
|
||||
eventOut = this.options.trigger == 'hover' ? 'mouseleave' : 'blur'
|
||||
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
|
||||
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
|
||||
triggers = this.options.trigger.split(' ')
|
||||
|
||||
for (i = triggers.length; i--;) {
|
||||
trigger = triggers[i]
|
||||
if (trigger == 'click') {
|
||||
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
|
||||
} else if (trigger != 'manual') {
|
||||
eventIn = trigger == 'hover' ? 'mouseenter' : 'focus'
|
||||
eventOut = trigger == 'hover' ? 'mouseleave' : 'blur'
|
||||
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
|
||||
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
|
||||
}
|
||||
}
|
||||
|
||||
this.options.selector ?
|
||||
@@ -1075,7 +1116,7 @@
|
||||
}
|
||||
|
||||
, getOptions: function (options) {
|
||||
options = $.extend({}, $.fn[this.type].defaults, options, this.$element.data())
|
||||
options = $.extend({}, $.fn[this.type].defaults, this.$element.data(), options)
|
||||
|
||||
if (options.delay && typeof options.delay == 'number') {
|
||||
options.delay = {
|
||||
@@ -1088,7 +1129,15 @@
|
||||
}
|
||||
|
||||
, enter: function (e) {
|
||||
var self = $(e.currentTarget)[this.type](this._options).data(this.type)
|
||||
var defaults = $.fn[this.type].defaults
|
||||
, options = {}
|
||||
, self
|
||||
|
||||
this._options && $.each(this._options, function (key, value) {
|
||||
if (defaults[key] != value) options[key] = value
|
||||
}, this)
|
||||
|
||||
self = $(e.currentTarget)[this.type](options).data(this.type)
|
||||
|
||||
if (!self.options.delay || !self.options.delay.show) return self.show()
|
||||
|
||||
@@ -1113,14 +1162,16 @@
|
||||
|
||||
, show: function () {
|
||||
var $tip
|
||||
, inside
|
||||
, pos
|
||||
, actualWidth
|
||||
, actualHeight
|
||||
, placement
|
||||
, tp
|
||||
, e = $.Event('show')
|
||||
|
||||
if (this.hasContent() && this.enabled) {
|
||||
this.$element.trigger(e)
|
||||
if (e.isDefaultPrevented()) return
|
||||
$tip = this.tip()
|
||||
this.setContent()
|
||||
|
||||
@@ -1132,19 +1183,18 @@
|
||||
this.options.placement.call(this, $tip[0], this.$element[0]) :
|
||||
this.options.placement
|
||||
|
||||
inside = /in/.test(placement)
|
||||
|
||||
$tip
|
||||
.detach()
|
||||
.css({ top: 0, left: 0, display: 'block' })
|
||||
.insertAfter(this.$element)
|
||||
|
||||
pos = this.getPosition(inside)
|
||||
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
|
||||
|
||||
pos = this.getPosition()
|
||||
|
||||
actualWidth = $tip[0].offsetWidth
|
||||
actualHeight = $tip[0].offsetHeight
|
||||
|
||||
switch (inside ? placement.split(' ')[1] : placement) {
|
||||
switch (placement) {
|
||||
case 'bottom':
|
||||
tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}
|
||||
break
|
||||
@@ -1159,13 +1209,58 @@
|
||||
break
|
||||
}
|
||||
|
||||
$tip
|
||||
.offset(tp)
|
||||
.addClass(placement)
|
||||
.addClass('in')
|
||||
this.applyPlacement(tp, placement)
|
||||
this.$element.trigger('shown')
|
||||
}
|
||||
}
|
||||
|
||||
, applyPlacement: function(offset, placement){
|
||||
var $tip = this.tip()
|
||||
, width = $tip[0].offsetWidth
|
||||
, height = $tip[0].offsetHeight
|
||||
, actualWidth
|
||||
, actualHeight
|
||||
, delta
|
||||
, replace
|
||||
|
||||
$tip
|
||||
.offset(offset)
|
||||
.addClass(placement)
|
||||
.addClass('in')
|
||||
|
||||
actualWidth = $tip[0].offsetWidth
|
||||
actualHeight = $tip[0].offsetHeight
|
||||
|
||||
if (placement == 'top' && actualHeight != height) {
|
||||
offset.top = offset.top + height - actualHeight
|
||||
replace = true
|
||||
}
|
||||
|
||||
if (placement == 'bottom' || placement == 'top') {
|
||||
delta = 0
|
||||
|
||||
if (offset.left < 0){
|
||||
delta = offset.left * -2
|
||||
offset.left = 0
|
||||
$tip.offset(offset)
|
||||
actualWidth = $tip[0].offsetWidth
|
||||
actualHeight = $tip[0].offsetHeight
|
||||
}
|
||||
|
||||
this.replaceArrow(delta - width + actualWidth, actualWidth, 'left')
|
||||
} else {
|
||||
this.replaceArrow(actualHeight - height, actualHeight, 'top')
|
||||
}
|
||||
|
||||
if (replace) $tip.offset(offset)
|
||||
}
|
||||
|
||||
, replaceArrow: function(delta, dimension, position){
|
||||
this
|
||||
.arrow()
|
||||
.css(position, delta ? (50 * (1 - delta / dimension) + "%") : '')
|
||||
}
|
||||
|
||||
, setContent: function () {
|
||||
var $tip = this.tip()
|
||||
, title = this.getTitle()
|
||||
@@ -1177,6 +1272,10 @@
|
||||
, hide: function () {
|
||||
var that = this
|
||||
, $tip = this.tip()
|
||||
, e = $.Event('hide')
|
||||
|
||||
this.$element.trigger(e)
|
||||
if (e.isDefaultPrevented()) return
|
||||
|
||||
$tip.removeClass('in')
|
||||
|
||||
@@ -1195,13 +1294,15 @@
|
||||
removeWithAnimation() :
|
||||
$tip.detach()
|
||||
|
||||
this.$element.trigger('hidden')
|
||||
|
||||
return this
|
||||
}
|
||||
|
||||
, fixTitle: function () {
|
||||
var $e = this.$element
|
||||
if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
|
||||
$e.attr('data-original-title', $e.attr('title') || '').removeAttr('title')
|
||||
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1209,11 +1310,12 @@
|
||||
return this.getTitle()
|
||||
}
|
||||
|
||||
, getPosition: function (inside) {
|
||||
return $.extend({}, (inside ? {top: 0, left: 0} : this.$element.offset()), {
|
||||
width: this.$element[0].offsetWidth
|
||||
, height: this.$element[0].offsetHeight
|
||||
})
|
||||
, getPosition: function () {
|
||||
var el = this.$element[0]
|
||||
return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
|
||||
width: el.offsetWidth
|
||||
, height: el.offsetHeight
|
||||
}, this.$element.offset())
|
||||
}
|
||||
|
||||
, getTitle: function () {
|
||||
@@ -1231,6 +1333,10 @@
|
||||
return this.$tip = this.$tip || $(this.options.template)
|
||||
}
|
||||
|
||||
, arrow: function(){
|
||||
return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow")
|
||||
}
|
||||
|
||||
, validate: function () {
|
||||
if (!this.$element[0].parentNode) {
|
||||
this.hide()
|
||||
@@ -1252,8 +1358,8 @@
|
||||
}
|
||||
|
||||
, toggle: function (e) {
|
||||
var self = $(e.currentTarget)[this.type](this._options).data(this.type)
|
||||
self[self.tip().hasClass('in') ? 'hide' : 'show']()
|
||||
var self = e ? $(e.currentTarget)[this.type](this._options).data(this.type) : this
|
||||
self.tip().hasClass('in') ? self.hide() : self.show()
|
||||
}
|
||||
|
||||
, destroy: function () {
|
||||
@@ -1285,10 +1391,11 @@
|
||||
, placement: 'top'
|
||||
, selector: false
|
||||
, template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
|
||||
, trigger: 'hover'
|
||||
, trigger: 'hover focus'
|
||||
, title: ''
|
||||
, delay: 0
|
||||
, html: false
|
||||
, container: false
|
||||
}
|
||||
|
||||
|
||||
@@ -1300,11 +1407,12 @@
|
||||
return this
|
||||
}
|
||||
|
||||
}(window.jQuery);/* ===========================================================
|
||||
* bootstrap-popover.js v2.2.2
|
||||
* http://twitter.github.com/bootstrap/javascript.html#popovers
|
||||
}(window.jQuery);
|
||||
/* ===========================================================
|
||||
* bootstrap-popover.js v2.3.2
|
||||
* http://getbootstrap.com/2.3.2/javascript.html#popovers
|
||||
* ===========================================================
|
||||
* Copyright 2012 Twitter, Inc.
|
||||
* Copyright 2013 Twitter, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -1360,8 +1468,8 @@
|
||||
, $e = this.$element
|
||||
, o = this.options
|
||||
|
||||
content = $e.attr('data-content')
|
||||
|| (typeof o.content == 'function' ? o.content.call($e[0]) : o.content)
|
||||
content = (typeof o.content == 'function' ? o.content.call($e[0]) : o.content)
|
||||
|| $e.attr('data-content')
|
||||
|
||||
return content
|
||||
}
|
||||
@@ -1401,7 +1509,7 @@
|
||||
placement: 'right'
|
||||
, trigger: 'click'
|
||||
, content: ''
|
||||
, template: '<div class="popover"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"></div></div></div>'
|
||||
, template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
|
||||
})
|
||||
|
||||
|
||||
@@ -1413,11 +1521,12 @@
|
||||
return this
|
||||
}
|
||||
|
||||
}(window.jQuery);/* =============================================================
|
||||
* bootstrap-scrollspy.js v2.2.2
|
||||
* http://twitter.github.com/bootstrap/javascript.html#scrollspy
|
||||
}(window.jQuery);
|
||||
/* =============================================================
|
||||
* bootstrap-scrollspy.js v2.3.2
|
||||
* http://getbootstrap.com/2.3.2/javascript.html#scrollspy
|
||||
* =============================================================
|
||||
* Copyright 2012 Twitter, Inc.
|
||||
* Copyright 2013 Twitter, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -1474,7 +1583,7 @@
|
||||
, $href = /^#\w/.test(href) && $(href)
|
||||
return ( $href
|
||||
&& $href.length
|
||||
&& [[ $href.position().top + self.$scrollElement.scrollTop(), href ]] ) || null
|
||||
&& [[ $href.position().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]] ) || null
|
||||
})
|
||||
.sort(function (a, b) { return a[0] - b[0] })
|
||||
.each(function () {
|
||||
@@ -1575,10 +1684,10 @@
|
||||
})
|
||||
|
||||
}(window.jQuery);/* ========================================================
|
||||
* bootstrap-tab.js v2.2.2
|
||||
* http://twitter.github.com/bootstrap/javascript.html#tabs
|
||||
* bootstrap-tab.js v2.3.2
|
||||
* http://getbootstrap.com/2.3.2/javascript.html#tabs
|
||||
* ========================================================
|
||||
* Copyright 2012 Twitter, Inc.
|
||||
* Copyright 2013 Twitter, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -1718,10 +1827,10 @@
|
||||
})
|
||||
|
||||
}(window.jQuery);/* =============================================================
|
||||
* bootstrap-typeahead.js v2.2.2
|
||||
* http://twitter.github.com/bootstrap/javascript.html#typeahead
|
||||
* bootstrap-typeahead.js v2.3.2
|
||||
* http://getbootstrap.com/2.3.2/javascript.html#typeahead
|
||||
* =============================================================
|
||||
* Copyright 2012 Twitter, Inc.
|
||||
* Copyright 2013 Twitter, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -1891,6 +2000,7 @@
|
||||
|
||||
, listen: function () {
|
||||
this.$element
|
||||
.on('focus', $.proxy(this.focus, this))
|
||||
.on('blur', $.proxy(this.blur, this))
|
||||
.on('keypress', $.proxy(this.keypress, this))
|
||||
.on('keyup', $.proxy(this.keyup, this))
|
||||
@@ -1902,6 +2012,7 @@
|
||||
this.$menu
|
||||
.on('click', $.proxy(this.click, this))
|
||||
.on('mouseenter', 'li', $.proxy(this.mouseenter, this))
|
||||
.on('mouseleave', 'li', $.proxy(this.mouseleave, this))
|
||||
}
|
||||
|
||||
, eventSupported: function(eventName) {
|
||||
@@ -1975,22 +2086,33 @@
|
||||
e.preventDefault()
|
||||
}
|
||||
|
||||
, focus: function (e) {
|
||||
this.focused = true
|
||||
}
|
||||
|
||||
, blur: function (e) {
|
||||
var that = this
|
||||
setTimeout(function () { that.hide() }, 150)
|
||||
this.focused = false
|
||||
if (!this.mousedover && this.shown) this.hide()
|
||||
}
|
||||
|
||||
, click: function (e) {
|
||||
e.stopPropagation()
|
||||
e.preventDefault()
|
||||
this.select()
|
||||
this.$element.focus()
|
||||
}
|
||||
|
||||
, mouseenter: function (e) {
|
||||
this.mousedover = true
|
||||
this.$menu.find('.active').removeClass('active')
|
||||
$(e.currentTarget).addClass('active')
|
||||
}
|
||||
|
||||
, mouseleave: function (e) {
|
||||
this.mousedover = false
|
||||
if (!this.focused && this.shown) this.hide()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -2035,16 +2157,15 @@
|
||||
$(document).on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
|
||||
var $this = $(this)
|
||||
if ($this.data('typeahead')) return
|
||||
e.preventDefault()
|
||||
$this.typeahead($this.data())
|
||||
})
|
||||
|
||||
}(window.jQuery);
|
||||
/* ==========================================================
|
||||
* bootstrap-affix.js v2.2.2
|
||||
* http://twitter.github.com/bootstrap/javascript.html#affix
|
||||
* bootstrap-affix.js v2.3.2
|
||||
* http://getbootstrap.com/2.3.2/javascript.html#affix
|
||||
* ==========================================================
|
||||
* Copyright 2012 Twitter, Inc.
|
||||
* Copyright 2013 Twitter, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -2156,4 +2277,4 @@
|
||||
})
|
||||
|
||||
|
||||
}(window.jQuery);
|
||||
}(window.jQuery);
|
||||
@@ -1,6 +0,0 @@
|
||||
/*!
|
||||
* Bootstrap.js by @fat & @mdo
|
||||
* Copyright 2012 Twitter, Inc.
|
||||
* http://www.apache.org/licenses/LICENSE-2.0.txt
|
||||
*/
|
||||
!function($){"use strict";$(function(){$.support.transition=function(){var transitionEnd=function(){var name,el=document.createElement("bootstrap"),transEndEventNames={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(name in transEndEventNames)if(void 0!==el.style[name])return transEndEventNames[name]}();return transitionEnd&&{end:transitionEnd}}()})}(window.jQuery),!function($){"use strict";var dismiss='[data-dismiss="alert"]',Alert=function(el){$(el).on("click",dismiss,this.close)};Alert.prototype.close=function(e){function removeElement(){$parent.trigger("closed").remove()}var $parent,$this=$(this),selector=$this.attr("data-target");selector||(selector=$this.attr("href"),selector=selector&&selector.replace(/.*(?=#[^\s]*$)/,"")),$parent=$(selector),e&&e.preventDefault(),$parent.length||($parent=$this.hasClass("alert")?$this:$this.parent()),$parent.trigger(e=$.Event("close")),e.isDefaultPrevented()||($parent.removeClass("in"),$.support.transition&&$parent.hasClass("fade")?$parent.on($.support.transition.end,removeElement):removeElement())};var old=$.fn.alert;$.fn.alert=function(option){return this.each(function(){var $this=$(this),data=$this.data("alert");data||$this.data("alert",data=new Alert(this)),"string"==typeof option&&data[option].call($this)})},$.fn.alert.Constructor=Alert,$.fn.alert.noConflict=function(){return $.fn.alert=old,this},$(document).on("click.alert.data-api",dismiss,Alert.prototype.close)}(window.jQuery),!function($){"use strict";var Button=function(element,options){this.$element=$(element),this.options=$.extend({},$.fn.button.defaults,options)};Button.prototype.setState=function(state){var d="disabled",$el=this.$element,data=$el.data(),val=$el.is("input")?"val":"html";state+="Text",data.resetText||$el.data("resetText",$el[val]()),$el[val](data[state]||this.options[state]),setTimeout(function(){"loadingText"==state?$el.addClass(d).attr(d,d):$el.removeClass(d).removeAttr(d)},0)},Button.prototype.toggle=function(){var $parent=this.$element.closest('[data-toggle="buttons-radio"]');$parent&&$parent.find(".active").removeClass("active"),this.$element.toggleClass("active")};var old=$.fn.button;$.fn.button=function(option){return this.each(function(){var $this=$(this),data=$this.data("button"),options="object"==typeof option&&option;data||$this.data("button",data=new Button(this,options)),"toggle"==option?data.toggle():option&&data.setState(option)})},$.fn.button.defaults={loadingText:"loading..."},$.fn.button.Constructor=Button,$.fn.button.noConflict=function(){return $.fn.button=old,this},$(document).on("click.button.data-api","[data-toggle^=button]",function(e){var $btn=$(e.target);$btn.hasClass("btn")||($btn=$btn.closest(".btn")),$btn.button("toggle")})}(window.jQuery),!function($){"use strict";var Carousel=function(element,options){this.$element=$(element),this.options=options,"hover"==this.options.pause&&this.$element.on("mouseenter",$.proxy(this.pause,this)).on("mouseleave",$.proxy(this.cycle,this))};Carousel.prototype={cycle:function(e){return e||(this.paused=!1),this.options.interval&&!this.paused&&(this.interval=setInterval($.proxy(this.next,this),this.options.interval)),this},to:function(pos){var $active=this.$element.find(".item.active"),children=$active.parent().children(),activePos=children.index($active),that=this;if(!(pos>children.length-1||0>pos))return this.sliding?this.$element.one("slid",function(){that.to(pos)}):activePos==pos?this.pause().cycle():this.slide(pos>activePos?"next":"prev",$(children[pos]))},pause:function(e){return e||(this.paused=!0),this.$element.find(".next, .prev").length&&$.support.transition.end&&(this.$element.trigger($.support.transition.end),this.cycle()),clearInterval(this.interval),this.interval=null,this},next:function(){return this.sliding?void 0:this.slide("next")},prev:function(){return this.sliding?void 0:this.slide("prev")},slide:function(type,next){var e,$active=this.$element.find(".item.active"),$next=next||$active[type](),isCycling=this.interval,direction="next"==type?"left":"right",fallback="next"==type?"first":"last",that=this;if(this.sliding=!0,isCycling&&this.pause(),$next=$next.length?$next:this.$element.find(".item")[fallback](),e=$.Event("slide",{relatedTarget:$next[0]}),!$next.hasClass("active")){if($.support.transition&&this.$element.hasClass("slide")){if(this.$element.trigger(e),e.isDefaultPrevented())return;$next.addClass(type),$next[0].offsetWidth,$active.addClass(direction),$next.addClass(direction),this.$element.one($.support.transition.end,function(){$next.removeClass([type,direction].join(" ")).addClass("active"),$active.removeClass(["active",direction].join(" ")),that.sliding=!1,setTimeout(function(){that.$element.trigger("slid")},0)})}else{if(this.$element.trigger(e),e.isDefaultPrevented())return;$active.removeClass("active"),$next.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return isCycling&&this.cycle()Line truncated
|
||||
+9210
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,4 @@
|
||||
/*! jQuery v2.1.4 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */
|
||||
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l=a.document,m="2.1.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!n.isArray(a)&&a-parseFloat(a)+1>=0},isPlainObject:function(a){return"object"!==n.type(a)||a.nodeType||n.isWindow(a)?!1:a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=l.createElement("script"),b.text=a,l.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:k}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b="length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+Line truncated
|
||||
return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=n.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||n.isArray(c)?d=L.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:n.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=L.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var Q=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,R=["Top","Right","Bottom","Left"],S=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},T=/^(?:checkbox|radio)$/i;!function(){var a=l.createDocumentFragment(),b=a.appendChild(l.createElement("div")),c=l.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3Line truncated
|
||||
void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),Za={set:function(a,b,c){return b===!1?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=$a[b]||n.find.attr;$a[b]=function(a,b,d){var e,f;return d||(f=$a[b],$a[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,$a[b]=f),e}});var _a=/^(?:input|select|textarea|button)$/i;n.fn.extend({prop:function(a,b){return J(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){return a.hasAttribute("tabindex")||_a.test(a.nodeName)||a.href?a.tabIndex:-1}}}}),k.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var ab=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h="string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ab," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0===arguments.length||"string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ab," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===U||"boolean"===c)&&(this.className&&L.set(this,"__className__",this.className),this.className=this.className||a===!1?"":L.get(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ab," ").indexOf(b)>=0)return!0;return!1}});var bb=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(bb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(d.value,f)>=0)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},k.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenLine truncated
|
||||
@@ -1,5 +0,0 @@
|
||||
/*! jQuery v2.0.0 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
|
||||
*/
|
||||
(function(e,undefined){var t,n,r=typeof undefined,i=e.location,o=e.document,s=o.documentElement,a=e.jQuery,u=e.$,l={},c=[],f="2.0.0",p=c.concat,h=c.push,d=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=f.trim,x=function(e,n){return new x.fn.init(e,n,t)},b=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^-ms-/,N=/-([\da-z])/gi,E=function(e,t){return t.toUpperCase()},S=function(){o.removeEventListener("DOMContentLoaded",S,!1),e.removeEventListener("load",S,!1),x.ready()};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,t,n){var r,i;if(!e)return this;if("string"==typeof e){if(r="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:T.exec(e),!r||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof x?t[0]:t,x.merge(this,x.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:o,!0)),C.test(r[1])&&x.isPlainObject(t))for(r in t)x.isFunction(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return i=o.getElementById(r[2]),i&&i.parentNode&&(this.length=1,this[0]=i),this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?n.ready(e):(e.selector!==undefined&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return d.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,t,n,r,i,o,s=arguments[0]||{},a=1,u=arguments.length,l=!1;for("boolean"==typeof s&&(l=s,s=arguments[1]||{},a=2),"object"==typeof s||x.isFunction(s)||(s={}),u===a&&(s=this,--a);u>a;a++)if(null!=(e=arguments[a]))for(t in e)n=s[t],r=e[t],s!==r&&(l&&r&&(x.isPlainObject(r)||(i=x.isArray(r)))?(i?(i=!1,o=n&&x.isArray(n)?n:[]):o=n&&x.isPlainObject(n)?n:{},s[t]=x.extend(l,o,r)):r!==undefined&&(s[t]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=a),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){(e===!0?--x.readyWait:x.isReady)||(x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(o,[x]),x.fn.trigger&&x(o).trigger("ready").off("ready")))},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray,isWindow:function(e){return null!=e&&e===e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if("object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:JSON.parse,parseXML:function(e){var t,n;if(!e||"string"!=typeof e)return null;try{n=new DOMParser,t=n.parseFromString(e,"text/xml")}catch(r){t=undefined}return(!t||t.getElementsByTagName("parsererror").length)&&x.error("Invalid XML: "+e),t},noop:function(){},globalEval:function(e){var t,n=eval;e=x.trim(e),e&&(1===e.indexOf("use strict")?(t=o.createElement("script"),t.text=e,o.head.appendChild(t).parentNode.removeChild(t)):n(e))},camelCase:function(e){return e.replace(k,"ms-").replace(N,E)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,s=j(e);if(n){if(s){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(s){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:function(e){return null==e?"":v.call(e)},makeArray:function(e,t){var n=t||[];return null!=e&&(j(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:g.call(t,e,n)},merge:function(e,t){var n=t.length,r=e.length,i=0;if("number"==typeof n)for(;n>i;i++)e[r++]=t[i];else while(t[i]Line truncated
|
||||
x._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=x.Deferred(),o=this,s=this.length,a=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=undefined),e=e||"fx";while(s--)n=q.get(o[s],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(a));return a(),i.promise(t)}});var R,M,W=/[\t\r\n]/g,$=/\r/g,B=/^(?:input|select|textarea|button)$/i;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[x.propFix[e]||e]})},addClass:function(e){var t,n,r,i,o,s=0,a=this.length,u="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];a>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(W," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,s=0,a=this.length,u=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];a>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(W," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,i="boolean"==typeof t;return x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,s=0,a=x(this),u=t,l=e.match(w)||[];while(o=l[s++])u=i?u:!a.hasClass(o),a[u?"addClass":"removeClass"](o)}else(n===r||"boolean"===n)&&(this.className&&q.set(this,"__className__",this.className),this.className=this.className||e===!1?"":q.get(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(W," ").indexOf(t)>=0)return!0;return!1},val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=x.isFunction(e),this.each(function(n){var i,o=x(this);1===this.nodeType&&(i=r?e.call(this,n,o.val()):e,null==i?i="":"number"==typeof i?i+="":x.isArray(i)&&(i=x.map(i,function(e){return null==e?"":e+""})),t=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&t.set(this,i,"value")!==undefined||(this.value=i))});if(i)return t=x.valHooks[i.type]||x.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&(n=t.get(i,"value"))!==undefined?n:(n=i.value,"string"==typeof n?n.replace($,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,s=o?null:[],a=o?i+1:r.length,u=0>i?a:o?i:0;for(;a>u;u++)if(n=r[u],!(!n.selected&&u!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),s=i.length;while(s--)r=i[s],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,t,n){var i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===r?x.prop(e,t,n):(1===s&&x.isXMLDoc(e)||(t=t.toLowerCase(),i=x.attrHooks[t]||(x.expr.match.boolean.test(t)?M:R)),n===undefined?i&&"get"in i&&null!==(o=i.get(e,t))?o:(o=x.find.attr(e,t),null==o?undefined:o):null!==n?i&&"set"in i&&(o=i.set(e,n,t))!==undefined?o:(e.setAttribute(t,n+""),n):(x.removeAttr(e,t),undefined))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.boolean.test(n)&&(e[r]=!1),e.removeAttribute(n)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return o=1!==s||!x.isXMLDoc(e),o&&(t=x.propFix[t]||t,i=x.propHooks[t]),n!==undefined?i&&"set"in i&&(r=i.set(e,n,t))!==undefined?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){return e.hasAttribute("tabindex")||B.test(e.nodeName)||e.href?e.tabIndex:-1}}}}),M={set:function(e,t,n){return t===!1?x.removeAttr(e,n):e.setAttribute(n,n),n}},x.each(x.expr.match.boolean.source.match(/\w+/g),function(e,t){varLine truncated
|
||||
if(x.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function un(e,t,n,r){var i={},o=e===rn;function s(a){var u;return i[a]=!0,x.each(e[a]||[],function(e,a){var l=a(t,n,r);return"string"!=typeof l||o||i[l]?o?!(u=l):undefined:(t.dataTypes.unshift(l),s(l),!1)}),u}return s(t.dataTypes[0])||!i["*"]&&s("*")}function ln(e,t){var n,r,i=x.ajaxSettings.flatOptions||{};for(n in t)t[n]!==undefined&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,t,n){if("string"!=typeof e&&tn)return tn.apply(this,arguments);var r,i,o,s=this,a=e.indexOf(" ");return a>=0&&(r=e.slice(a),e=e.slice(0,a)),x.isFunction(t)?(n=t,t=undefined):t&&"object"==typeof t&&(i="POST"),s.length>0&&x.ajax({url:e,type:i,dataType:"html",data:t}).done(function(e){o=arguments,s.html(r?x("<div>").append(x.parseHTML(e)).find(r):e)}).complete(n&&function(e,t){s.each(n,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Xt,type:"GET",isLocal:Qt.test(_t[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":on,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?ln(ln(e,x.ajaxSettings),t):ln(x.ajaxSettings,e)},ajaxPrefilter:an(nn),ajaxTransport:an(rn),ajax:function(e,t){"object"==typeof e&&(t=e,e=undefined),t=t||{};var n,r,i,o,s,a,u,l,c=x.ajaxSetup({},t),f=c.context||c,p=c.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),d=x.Callbacks("once memory"),g=c.statusCode||{},m={},y={},v=0,b="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(2===v){if(!o){o={};while(t=Jt.exec(i))o[t[1].toLowerCase()]=t[2]}t=o[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===v?i:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return v||(e=y[n]=y[n]||e,m[e]=t),this},overrideMimeType:function(e){return v||(c.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>v)for(t in e)g[t]=[g[t],e[t]];else T.always(e[T.status]);return this},abort:function(e){var t=e||b;return n&&n.abort(t),k(0,t),this}};if(h.promise(T).complete=d.add,T.success=T.done,T.error=T.fail,c.url=((e||c.url||Xt)+"").replace(Vt,"").replace(Zt,_t[1]+"//"),c.type=t.method||t.type||c.method||c.type,c.dataTypes=x.trim(c.dataType||"*").toLowerCase().match(w)||[""],null==c.crossDomain&&(a=en.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===_t[1]&&a[2]===_t[2]&&(a[3]||("http:"===a[1]?"80":"443"))===(_t[3]||("http:"===_t[1]?"80":"443")))),c.data&&c.processData&&"string"!=typeof c.data&&(c.data=x.param(c.data,c.traditional)),un(nn,c,t,T),2===v)return T;u=c.global,u&&0===x.active++&&x.event.trigger("ajaxStart"),c.type=c.type.toUpperCase(),c.hasContent=!Kt.test(c.type),r=c.url,c.hasContent||(c.data&&(r=c.url+=(Yt.test(r)?"&":"?")+c.data,delete c.data),c.cache===!1&&(c.url=Gt.test(r)?r.replace(Gt,"$1_="+Ut++):r+(Yt.test(r)?"&":"?")+"_="+Ut++)),c.ifModified&&(x.lastModified[r]&&T.setRequestHeader("If-Modified-Since",x.lastModified[r]),x.etag[r]&&T.setRequestHeader("If-None-Match",x.etag[r])),(c.data&&c.hasContent&&c.contentType!==!1||t.contentType)&&T.setRequestHeader("Content-Type",c.contentType),T.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+("*"!==c.dataTypes[0]?", "+on+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)T.setRequestHeader(l,c.headers[l]);if(c.beforeSend&&(c.beforeSend.call(f,T,c)===!1||2===v))return T.abort();b="abort";for(l in{success:1,error:1,complete:1})T[l](c[l]);if(n=un(rn,c,t,T)){T.readyState=1,u&&p.trigger("ajaxSend",[T,c]),c.async&&c.timeout>0&&(s=setTimeout(function(){T.abort("timeout")},c.timeout));try{v=1,n.send(m,k)}catch(C){if(!(2>v))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,t,o,a){var l,m,y,b,w,C=t;2!==v&&(v=2,s&&clearTimeout(s),n=undefined,i=a||"",T.readyState=e>0?4:0,l=e>=200&&300>e||304===e,o&&(b=cn(c,T,o)),b=fn(c,b,T,l),l?(c.ifModified&&(w=T.getResponseHeader("Last-Modified"),w&&(x.lastModified[r]=w),w=T.getResponseHeader("etag"),w&&(x.etag[r]=w)),204===e?C="nocontent":304===e?C="notmodified":(C=b.state,m=b.data,y=b.error,l=!y)):(y=C,(e||!C)&&(C="error",0>e&&(e=0))),T.status=e,T.statusText=(t||C)+"",l?h.resolveWith(f,[m,C,T]):h.rejectWith(f,[T,C,y]),T.statusCode(g),g=undefined,u&&p.trigger(l?"ajaxSuccess":"ajaxError",[T,c,l?m:y]),d.fireWith(f,[T,C]),u&&(p.trigger("ajaxComplete",[T,c]),--x.active||x.event.trigger("ajaxStop")))}return T},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,Line truncated
|
||||
@@ -1,7 +1,7 @@
|
||||
<div id="settings_dialog" class="modal hide fade large" tabindex="-1" role="dialog" aria-labelledby="settings_dialog_label" aria-hidden="true">
|
||||
<div class="modal-header">
|
||||
<button type="button" class="close" data-dismiss="modal">×</button>
|
||||
<h3 id="settings_dialog_label">{{ _('OctoPrint Settings') }}</h3>
|
||||
<h3 id="settings_dialog_label">{{ _('OctoPrint Settings') }} <i class="icon-spinner icon-spin" data-bind="visible: receiving"></i></h3>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="full-sized-box">
|
||||
@@ -49,6 +49,6 @@
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { saveData(undefined, $root.hide) }">{{ _('Save') }}</button>
|
||||
<button class="btn btn-primary" data-bind="click: function() { saveData(undefined, $root.hide) }, enable: !sending(), css: {disabled: sending()}"><i class="icon-spinner icon-spin" data-bind="visible: sending"></i> {{ _('Save') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -35,4 +35,11 @@
|
||||
<textarea rows="4" class="block" data-bind="value: scripts_gcode_afterPrinterConnected"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label">{{ _('Before connection to printer is closed') }}</label>
|
||||
<div class="controls">
|
||||
<textarea rows="4" class="block" data-bind="value: scripts_gcode_beforePrinterDisconnected"></textarea>
|
||||
</div>
|
||||
<small>{{ _('This will only be executed when closing the connection actively. If the connection to the printer is suddenly lost nothing will be sent.') }}</small>
|
||||
</div>
|
||||
</form>
|
||||
@@ -70,13 +70,6 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-serialLongRunningCommands">{{ _('Long running commands') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-serialLongRunningCommands" data-bind="value: serial_longRunningCommands">
|
||||
<span class="help-inline">{{ _('Use this to specify the commands known to take a long time to complete without output from your printer and hence might cause timeout issues. Just the G or M code, comma separated.')|format(glob_url="http://docs.python.org/2/library/glob.html") }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-serialAdditionalPorts">{{ _('Additional serial ports') }}</label>
|
||||
<div class="controls">
|
||||
@@ -84,4 +77,39 @@
|
||||
<span class="help-inline">{{ _('Use this to define additional <a href="%%(glob_url)s">glob patterns</a> matching serial ports to list for connecting against, e.g. <code>/dev/ttyAMA*</code>. One entry per line.')|format(glob_url="http://docs.python.org/2/library/glob.html") }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<label class="control-label" for="settings-serialAdditionalBaudrates">{{ _('Additional baud rates') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-serialAdditionalBaudrates" data-bind="value: serial_additionalBaudrates">
|
||||
<span class="help-inline">{{ _('Use this to define additional serial port baud rates to list for connecting with, e.g. <code>123456</code>. Comma separated.')|format(glob_url="http://docs.python.org/2/library/glob.html") }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="icon-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
|
||||
<div class="hide">
|
||||
<div class="control-group" title="{{ _('Command to send to the firmware on first handshake attempt.') }}">
|
||||
<label class="control-label" for="settings-serialHelloCommand">{{ _('"Hello" command') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-serialHelloCommand" data-bind="value: serial_helloCommand">
|
||||
<span class="help-inline">{{ _('Use this to specify a different command than the default <code>M110</code> to send to the printer on initial connection to trigger a communication handshake.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Commands that are know to run long and hence should suppress communication timeouts from being triggered.') }}">
|
||||
<label class="control-label" for="settings-serialLongRunningCommands">{{ _('Long running commands') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-serialLongRunningCommands" data-bind="value: serial_longRunningCommands">
|
||||
<span class="help-inline">{{ _('Use this to specify the commands known to take a long time to complete without output from your printer and hence might cause timeout issues. Just the G or M code, comma separated.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Commands that always require a line number and checksum to be sent with them.') }}">
|
||||
<label class="control-label" for="settings-serialChecksumRequiringCommands">{{ _('Commands that always require a checksum') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" id="settings-checksumRequiringCommands" data-bind="value: serial_checksumRequiringCommands">
|
||||
<span class="help-inline">{{ _('Use this to specify which commands <strong>always</strong> need to be sent with a checksum. Comma separated list.') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
@@ -0,0 +1,22 @@
|
||||
<form class="form-horizontal">
|
||||
<h3>Commands</h3>
|
||||
|
||||
<div class="control-group" title="{{ _('Command to restart the OctoPrint server') }}">
|
||||
<label class="control-label" for="settings-serverRestartCommand">{{ _('Restart OctoPrint') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: server_commands_serverRestartCommand" id="settings-serverRestartCommand">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Command to restart the system OctoPrint is running on') }}">
|
||||
<label class="control-label" for="settings-systemRestartCommand">{{ _('Restart system') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: server_commands_systemRestartCommand" id="settings-systemRestartCommand">
|
||||
</div>
|
||||
</div>
|
||||
<div class="control-group" title="{{ _('Command to shut down the system OctoPrint is running on') }}">
|
||||
<label class="control-label" for="settings-systemShutdownCommand">{{ _('Shutdown system') }}</label>
|
||||
<div class="controls">
|
||||
<input type="text" class="input-block-level" data-bind="value: server_commands_systemShutdownCommand" id="settings-systemShutdownCommand">
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -10,11 +10,11 @@
|
||||
<div class="size">{{ _('Size') }}: <span data-bind="text: formatSize(size)"></span></div>
|
||||
<div class="additionalInfo hide" data-bind="html: $root.getAdditionalData($data)"></div>
|
||||
<div class="btn-group action-buttons">
|
||||
<div class="btn btn-mini toggleAdditionalData" data-bind="click: function() { if ($root.enableAdditionalData($data)) { $root.toggleAdditionalData($data); } else { return; } }, css: { disabled: !$root.enableAdditionalData($data) }"><i class="icon-chevron-down"></i></div>
|
||||
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}"><i class="icon-download-alt" title="{{ _('Download') }}"></i></a>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}"><i class="icon-trash" title="{{ _('Remove') }}"></i></div>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-folder-open" title="{{ _('Load') }}"></i></div>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, true); } else { return; } }, css: {disabled: !$root.enableSelect($data)}"><i class="icon-print" title="{{ _('Load and Print') }}"></i></div>
|
||||
<div class="btn btn-mini toggleAdditionalData" data-bind="click: function() { if ($root.enableAdditionalData($data)) { $root.toggleAdditionalData($data); } else { return; } }, css: { disabled: !$root.enableAdditionalData($data) }" title="{{ _('Additional data') }}"><i class="icon-chevron-down"></i></div>
|
||||
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}" title="{{ _('Download') }}"><i class="icon-download-alt"></i></a>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove') }}"><i class="icon-trash"></i></div>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, false); } else { return; } }, css: {disabled: !$root.enableSelect($data)}" title="{{ _('Load') }}"><i class="icon-folder-open"></i></div>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSelect($data)) { $root.loadFile($data, true); } else { return; } }, css: {disabled: !$root.enableSelect($data)}" title="{{ _('Load and Print') }}"><i class="icon-print"></i></div>
|
||||
</div>
|
||||
</script>
|
||||
|
||||
@@ -23,9 +23,9 @@
|
||||
<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">
|
||||
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}"><i class="icon-download-alt" title="{{ _('Download') }}"></i></a>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}"><i class="icon-trash" title="{{ _('Remove') }}"></i></div>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSlicing($data)) { $root.sliceFile($data); } else { return; } }, css: {disabled: !$root.enableSlicing($data)}"><i class="icon-magic" title="{{ _('Slice') }}"></i></div>
|
||||
<a class="btn btn-mini" data-bind="attr: {href: $root.downloadLink($data), css: {disabled: !$root.downloadLink($data)}}" title="{{ _('Download') }}"><i class="icon-download-alt"></i></a>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableRemove($data)) { $root.removeFile($data); } else { return; } }, css: {disabled: !$root.enableRemove($data)}" title="{{ _('Remove') }}"><i class="icon-trash"></i></div>
|
||||
<div class="btn btn-mini" data-bind="click: function() { if ($root.enableSlicing($data)) { $root.sliceFile($data); } else { return; } }, css: {disabled: !$root.enableSlicing($data)}" title="{{ _('Slice') }}"><i class="icon-magic"></i></div>
|
||||
</div>
|
||||
</script>
|
||||
|
||||
|
||||
+201
-135
@@ -6,13 +6,13 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import urllib
|
||||
import time
|
||||
import subprocess
|
||||
import fnmatch
|
||||
import datetime
|
||||
import sys
|
||||
import shutil
|
||||
import Queue
|
||||
import requests
|
||||
|
||||
import octoprint.util as util
|
||||
|
||||
@@ -58,7 +58,7 @@ def notifyCallbacks(timelapse):
|
||||
if timelapse is None:
|
||||
config = None
|
||||
else:
|
||||
config = timelapse.configData()
|
||||
config = timelapse.config_data()
|
||||
for callback in updateCallbacks:
|
||||
try: callback.sendTimelapseConfig(config)
|
||||
except: logging.getLogger(__name__).exception("Exception while pushing timelapse configuration")
|
||||
@@ -86,12 +86,12 @@ def configureTimelapse(config=None, persist=False):
|
||||
if type is None or "off" == type:
|
||||
current = None
|
||||
elif "zchange" == type:
|
||||
current = ZTimelapse(postRoll=postRoll, fps=fps)
|
||||
current = ZTimelapse(post_roll=postRoll, fps=fps)
|
||||
elif "timed" == type:
|
||||
interval = 10
|
||||
if "options" in config and "interval" in config["options"] and config["options"]["interval"] > 0:
|
||||
interval = config["options"]["interval"]
|
||||
current = TimedTimelapse(postRoll=postRoll, interval=interval, fps=fps)
|
||||
current = TimedTimelapse(post_roll=postRoll, interval=interval, fps=fps)
|
||||
|
||||
notifyCallbacks(current)
|
||||
|
||||
@@ -101,72 +101,83 @@ def configureTimelapse(config=None, persist=False):
|
||||
|
||||
|
||||
class Timelapse(object):
|
||||
def __init__(self, postRoll=0, fps=25):
|
||||
QUEUE_ENTRY_TYPE_CAPTURE = "capture"
|
||||
QUEUE_ENTRY_TYPE_CALLBACK = "callback"
|
||||
|
||||
def __init__(self, post_roll=0, fps=25):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._imageNumber = None
|
||||
self._inTimelapse = False
|
||||
self._gcodeFile = None
|
||||
self._image_number = None
|
||||
self._in_timelapse = False
|
||||
self._gcode_file = None
|
||||
|
||||
self._postRoll = postRoll
|
||||
self._postRollStart = None
|
||||
self._onPostRollDone = None
|
||||
self._post_roll = post_roll
|
||||
self._on_post_roll_done = None
|
||||
|
||||
self._captureDir = settings().getBaseFolder("timelapse_tmp")
|
||||
self._movieDir = settings().getBaseFolder("timelapse")
|
||||
self._snapshotUrl = settings().get(["webcam", "snapshot"])
|
||||
self._ffmpegThreads = settings().get(["webcam", "ffmpegThreads"])
|
||||
self._capture_dir = settings().getBaseFolder("timelapse_tmp")
|
||||
self._movie_dir = settings().getBaseFolder("timelapse")
|
||||
self._snapshot_url = settings().get(["webcam", "snapshot"])
|
||||
self._ffmpeg_threads = settings().get(["webcam", "ffmpegThreads"])
|
||||
|
||||
self._fps = fps
|
||||
|
||||
self._renderThread = None
|
||||
self._captureMutex = threading.Lock()
|
||||
self._render_thread = None
|
||||
|
||||
self._capture_mutex = threading.Lock()
|
||||
self._capture_queue = Queue.Queue()
|
||||
self._capture_queue_active = True
|
||||
|
||||
self._capture_queue_thread = threading.Thread(target=self._capture_queue_worker)
|
||||
self._capture_queue_thread.daemon = True
|
||||
self._capture_queue_thread.start()
|
||||
|
||||
# subscribe events
|
||||
eventManager().subscribe(Events.PRINT_STARTED, self.onPrintStarted)
|
||||
eventManager().subscribe(Events.PRINT_FAILED, self.onPrintDone)
|
||||
eventManager().subscribe(Events.PRINT_DONE, self.onPrintDone)
|
||||
eventManager().subscribe(Events.PRINT_RESUMED, self.onPrintResumed)
|
||||
for (event, callback) in self.eventSubscriptions():
|
||||
eventManager().subscribe(Events.PRINT_STARTED, self.on_print_started)
|
||||
eventManager().subscribe(Events.PRINT_FAILED, self.on_print_done)
|
||||
eventManager().subscribe(Events.PRINT_DONE, self.on_print_done)
|
||||
eventManager().subscribe(Events.PRINT_RESUMED, self.on_print_resumed)
|
||||
for (event, callback) in self.event_subscriptions():
|
||||
eventManager().subscribe(event, callback)
|
||||
|
||||
def postRoll(self):
|
||||
return self._postRoll
|
||||
@property
|
||||
def post_roll(self):
|
||||
return self._post_roll
|
||||
|
||||
@property
|
||||
def fps(self):
|
||||
return self._fps
|
||||
|
||||
def unload(self):
|
||||
if self._inTimelapse:
|
||||
self.stopTimelapse(doCreateMovie=False)
|
||||
if self._in_timelapse:
|
||||
self.stop_timelapse(doCreateMovie=False)
|
||||
|
||||
# unsubscribe events
|
||||
eventManager().unsubscribe(Events.PRINT_STARTED, self.onPrintStarted)
|
||||
eventManager().unsubscribe(Events.PRINT_FAILED, self.onPrintDone)
|
||||
eventManager().unsubscribe(Events.PRINT_DONE, self.onPrintDone)
|
||||
eventManager().unsubscribe(Events.PRINT_RESUMED, self.onPrintResumed)
|
||||
for (event, callback) in self.eventSubscriptions():
|
||||
eventManager().unsubscribe(Events.PRINT_STARTED, self.on_print_started)
|
||||
eventManager().unsubscribe(Events.PRINT_FAILED, self.on_print_done)
|
||||
eventManager().unsubscribe(Events.PRINT_DONE, self.on_print_done)
|
||||
eventManager().unsubscribe(Events.PRINT_RESUMED, self.on_print_resumed)
|
||||
for (event, callback) in self.event_subscriptions():
|
||||
eventManager().unsubscribe(event, callback)
|
||||
|
||||
def onPrintStarted(self, event, payload):
|
||||
def on_print_started(self, event, payload):
|
||||
"""
|
||||
Override this to perform additional actions upon start of a print job.
|
||||
"""
|
||||
self.startTimelapse(payload["file"])
|
||||
self.start_timelapse(payload["file"])
|
||||
|
||||
def onPrintDone(self, event, payload):
|
||||
def on_print_done(self, event, payload):
|
||||
"""
|
||||
Override this to perform additional actions upon the stop of a print job.
|
||||
"""
|
||||
self.stopTimelapse(success=(event==Events.PRINT_DONE))
|
||||
self.stop_timelapse(success=(event==Events.PRINT_DONE))
|
||||
|
||||
def onPrintResumed(self, event, payload):
|
||||
def on_print_resumed(self, event, payload):
|
||||
"""
|
||||
Override this to perform additional actions upon the pausing of a print job.
|
||||
"""
|
||||
if not self._inTimelapse:
|
||||
self.startTimelapse(payload["file"])
|
||||
if not self._in_timelapse:
|
||||
self.start_timelapse(payload["file"])
|
||||
|
||||
def eventSubscriptions(self):
|
||||
def event_subscriptions(self):
|
||||
"""
|
||||
Override this method to subscribe to additional events by returning an array of (event, callback) tuples.
|
||||
|
||||
@@ -178,7 +189,7 @@ class Timelapse(object):
|
||||
"""
|
||||
return []
|
||||
|
||||
def configData(self):
|
||||
def config_data(self):
|
||||
"""
|
||||
Override this method to return the current timelapse configuration data. The data should have the following
|
||||
form:
|
||||
@@ -188,105 +199,150 @@ class Timelapse(object):
|
||||
"""
|
||||
return None
|
||||
|
||||
def startTimelapse(self, gcodeFile):
|
||||
def start_timelapse(self, gcodeFile):
|
||||
self._logger.debug("Starting timelapse for %s" % gcodeFile)
|
||||
self.cleanCaptureDir()
|
||||
self.clean_capture_dir()
|
||||
|
||||
self._imageNumber = 0
|
||||
self._inTimelapse = True
|
||||
self._gcodeFile = os.path.basename(gcodeFile)
|
||||
self._image_number = 0
|
||||
self._in_timelapse = True
|
||||
self._gcode_file = os.path.basename(gcodeFile)
|
||||
|
||||
def stopTimelapse(self, doCreateMovie=True, success=True):
|
||||
def stop_timelapse(self, doCreateMovie=True, success=True):
|
||||
self._logger.debug("Stopping timelapse")
|
||||
|
||||
self._inTimelapse = False
|
||||
self._in_timelapse = False
|
||||
|
||||
def resetImageNumber():
|
||||
self._imageNumber = None
|
||||
self._image_number = None
|
||||
|
||||
def createMovie():
|
||||
self._renderThread = threading.Thread(target=self._createMovie, kwargs={"success": success})
|
||||
self._renderThread.daemon = True
|
||||
self._renderThread.start()
|
||||
self._render_thread = threading.Thread(target=self._create_movie, kwargs={"success": success})
|
||||
self._render_thread.daemon = True
|
||||
self._render_thread.start()
|
||||
|
||||
def resetAndCreate():
|
||||
resetImageNumber()
|
||||
createMovie()
|
||||
|
||||
if self._postRoll > 0:
|
||||
self._postRollStart = time.time()
|
||||
def waitForCaptures(callback):
|
||||
self._capture_queue.put(dict(type=self.__class__.QUEUE_ENTRY_TYPE_CALLBACK, callback=callback))
|
||||
|
||||
def getWaitForCaptures(callback):
|
||||
def f():
|
||||
waitForCaptures(callback)
|
||||
return f
|
||||
|
||||
if self._post_roll > 0:
|
||||
eventManager().fire(Events.POSTROLL_START, dict(postroll_duration=self.post_roll * self.fps, postroll_length=self.post_roll, postroll_fps=self.fps))
|
||||
self._post_roll_start = time.time()
|
||||
if doCreateMovie:
|
||||
self._onPostRollDone = resetAndCreate
|
||||
self._on_post_roll_done = getWaitForCaptures(resetAndCreate)
|
||||
else:
|
||||
self._onPostRollDone = resetImageNumber
|
||||
self.processPostRoll()
|
||||
self._on_post_roll_done = resetImageNumber
|
||||
self.process_post_roll()
|
||||
else:
|
||||
self._postRollStart = None
|
||||
self._post_roll_start = None
|
||||
if doCreateMovie:
|
||||
resetAndCreate()
|
||||
waitForCaptures(resetAndCreate)
|
||||
else:
|
||||
resetImageNumber()
|
||||
|
||||
def processPostRoll(self):
|
||||
pass
|
||||
def process_post_roll(self):
|
||||
self.post_roll_finished()
|
||||
|
||||
def post_roll_finished(self):
|
||||
if self.post_roll:
|
||||
eventManager().fire(Events.POSTROLL_END)
|
||||
if self._on_post_roll_done is not None:
|
||||
self._on_post_roll_done()
|
||||
|
||||
def captureImage(self):
|
||||
if self._captureDir is None:
|
||||
if self._capture_dir is None:
|
||||
self._logger.warn("Cannot capture image, capture directory is unset")
|
||||
return
|
||||
|
||||
if self._imageNumber is None:
|
||||
self._logger.warn("Cannot capture image, image number is unset")
|
||||
return
|
||||
with self._capture_mutex:
|
||||
if self._image_number is None:
|
||||
self._logger.warn("Cannot capture image, image number is unset")
|
||||
return
|
||||
|
||||
filename = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
|
||||
self._image_number += 1
|
||||
|
||||
with self._captureMutex:
|
||||
filename = os.path.join(self._captureDir, "tmp_%05d.jpg" % self._imageNumber)
|
||||
self._imageNumber += 1
|
||||
self._logger.debug("Capturing image to %s" % filename)
|
||||
captureThread = threading.Thread(target=self._captureWorker, kwargs={"filename": filename})
|
||||
captureThread.daemon = True
|
||||
captureThread.start()
|
||||
entry = dict(type=self.__class__.QUEUE_ENTRY_TYPE_CAPTURE,
|
||||
filename=filename,
|
||||
onerror=self._on_capture_error)
|
||||
self._capture_queue.put(entry)
|
||||
return filename
|
||||
|
||||
def _captureWorker(self, filename):
|
||||
def _on_capture_error(self):
|
||||
with self._capture_mutex:
|
||||
if self._image_number is not None and self._image_number > 0:
|
||||
self._image_number -= 1
|
||||
|
||||
def _capture_queue_worker(self):
|
||||
while self._capture_queue_active:
|
||||
entry = self._capture_queue.get(block=True)
|
||||
|
||||
if entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CAPTURE and "filename" in entry:
|
||||
filename = entry["filename"]
|
||||
onerror = entry.pop("onerror", None)
|
||||
self._perform_capture(filename, onerror=onerror)
|
||||
|
||||
elif entry["type"] == self.__class__.QUEUE_ENTRY_TYPE_CALLBACK and "callback" in entry:
|
||||
args = entry.pop("args", [])
|
||||
kwargs = entry.pop("kwargs", dict())
|
||||
entry["callback"](*args, **kwargs)
|
||||
|
||||
def _perform_capture(self, filename, onerror=None):
|
||||
eventManager().fire(Events.CAPTURE_START, {"file": filename})
|
||||
try:
|
||||
urllib.urlretrieve(self._snapshotUrl, filename)
|
||||
self._logger.debug("Image %s captured from %s" % (filename, self._snapshotUrl))
|
||||
self._logger.debug("Going to capture %s from %s" % (filename, self._snapshot_url))
|
||||
r = requests.get(self._snapshot_url, stream=True)
|
||||
with open (filename, "wb") as f:
|
||||
for chunk in r.iter_content(chunk_size=1024):
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
f.flush()
|
||||
self._logger.debug("Image %s captured from %s" % (filename, self._snapshot_url))
|
||||
except:
|
||||
self._logger.exception("Could not capture image %s from %s, decreasing image counter again" % (filename, self._snapshotUrl))
|
||||
with self._captureMutex:
|
||||
if self._imageNumber is not None and self._imageNumber > 0:
|
||||
self._imageNumber -= 1
|
||||
eventManager().fire(Events.CAPTURE_DONE, {"file": filename})
|
||||
self._logger.exception("Could not capture image %s from %s" % (filename, self._snapshot_url))
|
||||
if callable(onerror):
|
||||
onerror()
|
||||
eventManager().fire(Events.CAPTURE_FAILED, {"file": filename})
|
||||
return False
|
||||
else:
|
||||
eventManager().fire(Events.CAPTURE_DONE, {"file": filename})
|
||||
return True
|
||||
|
||||
def _createMovie(self, success=True):
|
||||
def _create_movie(self, success=True):
|
||||
ffmpeg = settings().get(["webcam", "ffmpeg"])
|
||||
bitrate = settings().get(["webcam", "bitrate"])
|
||||
if ffmpeg is None or bitrate is None:
|
||||
self._logger.warn("Cannot create movie, path to ffmpeg or desired bitrate is unset")
|
||||
return
|
||||
|
||||
input = os.path.join(self._captureDir, "tmp_%05d.jpg")
|
||||
input = os.path.join(self._capture_dir, "tmp_%05d.jpg")
|
||||
if success:
|
||||
output = os.path.join(self._movieDir, "%s_%s.mpg" % (os.path.splitext(self._gcodeFile)[0], time.strftime("%Y%m%d%H%M%S")))
|
||||
output = os.path.join(self._movie_dir, "%s_%s.mpg" % (os.path.splitext(self._gcode_file)[0], time.strftime("%Y%m%d%H%M%S")))
|
||||
else:
|
||||
output = os.path.join(self._movieDir, "%s_%s-failed.mpg" % (os.path.splitext(self._gcodeFile)[0], time.strftime("%Y%m%d%H%M%S")))
|
||||
output = os.path.join(self._movie_dir, "%s_%s-failed.mpg" % (os.path.splitext(self._gcode_file)[0], time.strftime("%Y%m%d%H%M%S")))
|
||||
|
||||
# prepare ffmpeg command
|
||||
command = [
|
||||
ffmpeg, '-framerate', str(self._fps), '-loglevel', 'error', '-i', input, '-vcodec', 'mpeg2video', '-threads', str(self._ffmpegThreads), '-pix_fmt', 'yuv420p', '-r', str(self._fps), '-y', '-b', bitrate,
|
||||
ffmpeg, '-framerate', str(self._fps), '-loglevel', 'error', '-i', input, '-vcodec', 'mpeg2video', '-threads', str(self._ffmpeg_threads), '-pix_fmt', 'yuv420p', '-r', str(self._fps), '-y', '-b', bitrate,
|
||||
'-f', 'vob']
|
||||
|
||||
filters = []
|
||||
|
||||
# flip video if configured
|
||||
if settings().getBoolean(["webcam", "rotate90"]):
|
||||
filters.append('transpose=1')
|
||||
if settings().getBoolean(["webcam", "flipH"]):
|
||||
filters.append('hflip')
|
||||
if settings().getBoolean(["webcam", "flipV"]):
|
||||
filters.append('vflip')
|
||||
if settings().getBoolean(["webcam", "rotate90"]):
|
||||
filters.append('transpose=2')
|
||||
|
||||
# add watermark if configured
|
||||
watermarkFilter = None
|
||||
@@ -315,7 +371,7 @@ class Timelapse(object):
|
||||
# finalize command with output file
|
||||
self._logger.debug("Rendering movie to %s" % output)
|
||||
command.append("\"" + output + "\"")
|
||||
eventManager().fire(Events.MOVIE_RENDERING, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)})
|
||||
eventManager().fire(Events.MOVIE_RENDERING, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output)})
|
||||
|
||||
command_str = " ".join(command)
|
||||
self._logger.debug("Executing command: %s" % command_str)
|
||||
@@ -323,75 +379,74 @@ class Timelapse(object):
|
||||
try:
|
||||
p = sarge.run(command_str, stderr=sarge.Capture())
|
||||
if p.returncode == 0:
|
||||
eventManager().fire(Events.MOVIE_DONE, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output)})
|
||||
eventManager().fire(Events.MOVIE_DONE, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output)})
|
||||
else:
|
||||
returncode = p.returncode
|
||||
stderr_text = p.stderr.text
|
||||
self._logger.warn("Could not render movie, got return code %r: %s" % (returncode, stderr_text))
|
||||
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output), "returncode": returncode, "error": stderr_text})
|
||||
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output), "returncode": returncode, "error": stderr_text})
|
||||
except:
|
||||
self._logger.exception("Could not render movie due to unknown error")
|
||||
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcodeFile, "movie": output, "movie_basename": os.path.basename(output), "returncode": 255, "error": "Unknown error"})
|
||||
eventManager().fire(Events.MOVIE_FAILED, {"gcode": self._gcode_file, "movie": output, "movie_basename": os.path.basename(output), "returncode": 255, "error": "Unknown error"})
|
||||
|
||||
def cleanCaptureDir(self):
|
||||
if not os.path.isdir(self._captureDir):
|
||||
def clean_capture_dir(self):
|
||||
if not os.path.isdir(self._capture_dir):
|
||||
self._logger.warn("Cannot clean capture directory, it is unset")
|
||||
return
|
||||
|
||||
for filename in os.listdir(self._captureDir):
|
||||
for filename in os.listdir(self._capture_dir):
|
||||
if not fnmatch.fnmatch(filename, "*.jpg"):
|
||||
continue
|
||||
os.remove(os.path.join(self._captureDir, filename))
|
||||
os.remove(os.path.join(self._capture_dir, filename))
|
||||
|
||||
|
||||
class ZTimelapse(Timelapse):
|
||||
def __init__(self, postRoll=0, fps=25):
|
||||
Timelapse.__init__(self, postRoll=postRoll, fps=fps)
|
||||
def __init__(self, post_roll=0, fps=25):
|
||||
Timelapse.__init__(self, post_roll=post_roll, fps=fps)
|
||||
self._logger.debug("ZTimelapse initialized")
|
||||
|
||||
def eventSubscriptions(self):
|
||||
def event_subscriptions(self):
|
||||
return [
|
||||
(Events.Z_CHANGE, self._onZChange)
|
||||
(Events.Z_CHANGE, self._on_z_change)
|
||||
]
|
||||
|
||||
def configData(self):
|
||||
def config_data(self):
|
||||
return {
|
||||
"type": "zchange"
|
||||
}
|
||||
|
||||
def processPostRoll(self):
|
||||
Timelapse.processPostRoll(self)
|
||||
def process_post_roll(self):
|
||||
with self._capture_mutex:
|
||||
filename = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
|
||||
self._image_number += 1
|
||||
|
||||
filename = os.path.join(self._captureDir, "tmp_%05d.jpg" % self._imageNumber)
|
||||
self._imageNumber += 1
|
||||
with self._captureMutex:
|
||||
self._captureWorker(filename)
|
||||
if self._perform_capture(filename):
|
||||
for _ in range(self._post_roll * self._fps):
|
||||
newFile = os.path.join(self._capture_dir, "tmp_%05d.jpg" % self._image_number)
|
||||
self._image_number += 1
|
||||
shutil.copyfile(filename, newFile)
|
||||
|
||||
for i in range(self._postRoll * self._fps):
|
||||
newFile = os.path.join(self._captureDir, "tmp_%05d.jpg" % (self._imageNumber))
|
||||
self._imageNumber += 1
|
||||
shutil.copyfile(filename, newFile)
|
||||
Timelapse.process_post_roll(self)
|
||||
|
||||
if self._onPostRollDone is not None:
|
||||
self._onPostRollDone()
|
||||
|
||||
def _onZChange(self, event, payload):
|
||||
def _on_z_change(self, event, payload):
|
||||
self.captureImage()
|
||||
|
||||
|
||||
class TimedTimelapse(Timelapse):
|
||||
def __init__(self, postRoll=0, interval=1, fps=25):
|
||||
Timelapse.__init__(self, postRoll=postRoll, fps=fps)
|
||||
def __init__(self, post_roll=0, interval=1, fps=25):
|
||||
Timelapse.__init__(self, post_roll=post_roll, fps=fps)
|
||||
self._interval = interval
|
||||
if self._interval < 1:
|
||||
self._interval = 1 # force minimum interval of 1s
|
||||
self._timerThread = None
|
||||
self._postroll_captures = 0
|
||||
self._timer = None
|
||||
self._logger.debug("TimedTimelapse initialized")
|
||||
|
||||
@property
|
||||
def interval(self):
|
||||
return self._interval
|
||||
|
||||
def configData(self):
|
||||
def config_data(self):
|
||||
return {
|
||||
"type": "timed",
|
||||
"options": {
|
||||
@@ -399,25 +454,36 @@ class TimedTimelapse(Timelapse):
|
||||
}
|
||||
}
|
||||
|
||||
def onPrintStarted(self, event, payload):
|
||||
Timelapse.onPrintStarted(self, event, payload)
|
||||
if self._timerThread is not None:
|
||||
def on_print_started(self, event, payload):
|
||||
Timelapse.on_print_started(self, event, payload)
|
||||
if self._timer is not None:
|
||||
return
|
||||
|
||||
self._timerThread = threading.Thread(target=self._timerWorker)
|
||||
self._timerThread.daemon = True
|
||||
self._timerThread.start()
|
||||
|
||||
def onPrintDone(self, event, payload):
|
||||
Timelapse.onPrintDone(self, event, payload)
|
||||
self._timerThread = None
|
||||
|
||||
def _timerWorker(self):
|
||||
self._logger.debug("Starting timer for interval based timelapse")
|
||||
while self._inTimelapse or (self._postRollStart and time.time() - self._postRollStart <= self._postRoll * self._fps):
|
||||
self.captureImage()
|
||||
time.sleep(self._interval)
|
||||
from octoprint.util import RepeatedTimer
|
||||
self._timer = RepeatedTimer(self._interval, self._timer_task,
|
||||
run_first=True, condition=self._timer_active,
|
||||
on_finish=self._on_timer_finished)
|
||||
self._timer.start()
|
||||
|
||||
if self._postRollStart is not None and self._onPostRollDone is not None:
|
||||
self._onPostRollDone()
|
||||
self._postRollStart = None
|
||||
def on_print_done(self, event, payload):
|
||||
self._postroll_captures = self.post_roll * self.fps
|
||||
Timelapse.on_print_done(self, event, payload)
|
||||
|
||||
def process_post_roll(self):
|
||||
pass
|
||||
|
||||
def post_roll_finished(self):
|
||||
Timelapse.post_roll_finished(self)
|
||||
self._timer = None
|
||||
|
||||
def _timer_active(self):
|
||||
return self._in_timelapse or self._postroll_captures > 0
|
||||
|
||||
def _timer_task(self):
|
||||
self.captureImage()
|
||||
if self._postroll_captures > 0:
|
||||
self._postroll_captures -= 1
|
||||
|
||||
def _on_timer_finished(self):
|
||||
self.post_roll_finished()
|
||||
+16
-3
@@ -149,7 +149,7 @@ class UserManager(object):
|
||||
if session is not None:
|
||||
for session in self._session_users_by_session:
|
||||
user = self._session_users_by_session[session]
|
||||
if username is None or username == user.get_name():
|
||||
if username is None or username == user.get_id():
|
||||
return user
|
||||
break
|
||||
|
||||
@@ -443,7 +443,7 @@ class User(UserMixin):
|
||||
path = [key]
|
||||
else:
|
||||
path = key
|
||||
self._set_setting(path, value)
|
||||
return self._set_setting(path, value)
|
||||
|
||||
def _get_setting(self, path):
|
||||
s = self._settings
|
||||
@@ -474,7 +474,8 @@ class User(UserMixin):
|
||||
|
||||
class SessionUser(User):
|
||||
def __init__(self, user):
|
||||
User.__init__(self, user._username, user._passwordHash, user._active, user._roles, user._apikey)
|
||||
self._user = user
|
||||
User.__init__(self, user._username, user._passwordHash, user._active, user._roles, user._apikey, user._settings)
|
||||
|
||||
import string
|
||||
import random
|
||||
@@ -483,6 +484,18 @@ class SessionUser(User):
|
||||
self._session = "".join(random.choice(chars) for _ in xrange(10))
|
||||
self._created = time.time()
|
||||
|
||||
def __getattribute__(self, item):
|
||||
if item in ("get_session", "_user", "_session", "_created"):
|
||||
return object.__getattribute__(self, item)
|
||||
else:
|
||||
return getattr(object.__getattribute__(self, "_user"), item)
|
||||
|
||||
def __setattr__(self, item, value):
|
||||
if item in ("_user", "_session", "_created"):
|
||||
return object.__setattr__(self, item, value)
|
||||
else:
|
||||
return setattr(self._user, item, value)
|
||||
|
||||
def get_session(self):
|
||||
return self._session
|
||||
|
||||
|
||||
@@ -570,9 +570,13 @@ class RepeatedTimer(threading.Thread):
|
||||
run_first (boolean): If set to True, the function will be run for the first time *before* the first wait period.
|
||||
If set to False (the default), the function will be run for the first time *after* the first wait period.
|
||||
condition (callable): Condition that needs to be True for loop to continue. Defaults to ``lambda: True``.
|
||||
on_finish (callable): Callback to call when the timer finishes, either due to being cancelled or since
|
||||
the condition became false.
|
||||
daemon (bool): daemon flag to set on underlying thread.
|
||||
"""
|
||||
|
||||
def __init__(self, interval, function, args=None, kwargs=None, run_first=False, condition=None):
|
||||
def __init__(self, interval, function, args=None, kwargs=None,
|
||||
run_first=False, condition=None, on_finish=None, daemon=True):
|
||||
threading.Thread.__init__(self)
|
||||
|
||||
if args is None:
|
||||
@@ -593,9 +597,11 @@ class RepeatedTimer(threading.Thread):
|
||||
self.kwargs = kwargs
|
||||
self.run_first = run_first
|
||||
self.condition = condition
|
||||
self.on_finish = on_finish
|
||||
self.daemon = daemon
|
||||
|
||||
def cancel(self):
|
||||
self.finished.set()
|
||||
self.finish()
|
||||
|
||||
def run(self):
|
||||
while self.condition():
|
||||
@@ -616,8 +622,13 @@ class RepeatedTimer(threading.Thread):
|
||||
# if we are to run the function AFTER waiting for the first time
|
||||
self.function(*self.args, **self.kwargs)
|
||||
|
||||
self.finish()
|
||||
|
||||
def finish(self):
|
||||
# make sure we set our finished event so we can detect that the loop was finished
|
||||
self.finished.set()
|
||||
if callable(self.on_finish):
|
||||
self.on_finish()
|
||||
|
||||
|
||||
class CountedEvent(object):
|
||||
|
||||
+177
-82
@@ -31,6 +31,8 @@ try:
|
||||
except:
|
||||
pass
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
def serialList():
|
||||
baselist=[]
|
||||
if os.name=="nt":
|
||||
@@ -64,6 +66,15 @@ def serialList():
|
||||
|
||||
def baudrateList():
|
||||
ret = [250000, 230400, 115200, 57600, 38400, 19200, 9600]
|
||||
additionalBaudrates = settings().get(["serial", "additionalBaudrates"])
|
||||
for additional in additionalBaudrates:
|
||||
try:
|
||||
ret.append(int(additional))
|
||||
except:
|
||||
_logger.warn("{} is not a valid additional baudrate, ignoring it".format(additional))
|
||||
|
||||
ret.sort(reverse=True)
|
||||
|
||||
prev = settings().getInt(["serial", "baudrate"])
|
||||
if prev in ret:
|
||||
ret.remove(prev)
|
||||
@@ -151,9 +162,12 @@ class MachineCom(object):
|
||||
|
||||
self._long_running_command = False
|
||||
self._heating = False
|
||||
self._connection_closing = False
|
||||
|
||||
self._timeout = None
|
||||
|
||||
self._hello_command = settings().get(["serial", "helloCommand"])
|
||||
|
||||
self._alwaysSendChecksum = settings().getBoolean(["feature", "alwaysSendChecksum"])
|
||||
self._sendChecksumWithUnknownCommands = settings().getBoolean(["feature", "sendChecksumWithUnknownCommands"])
|
||||
self._unknownCommandsNeedAck = settings().getBoolean(["feature", "unknownCommandsNeedAck"])
|
||||
@@ -164,6 +178,7 @@ class MachineCom(object):
|
||||
self._lastResendNumber = None
|
||||
self._currentResendCount = 0
|
||||
self._resendSwallowNextOk = False
|
||||
self._checksum_requiring_commands = settings().get(["serial", "checksumRequiringCommands"])
|
||||
|
||||
self._clear_to_send = CountedEvent(max=10, name="comm.clear_to_send")
|
||||
self._send_queue = TypedQueue()
|
||||
@@ -271,37 +286,51 @@ class MachineCom(object):
|
||||
def getState(self):
|
||||
return self._state
|
||||
|
||||
def getStateString(self):
|
||||
if self._state == self.STATE_NONE:
|
||||
def getStateId(self, state=None):
|
||||
if state is None:
|
||||
state = self._state
|
||||
|
||||
possible_states = filter(lambda x: x.startswith("STATE_"), self.__class__.__dict__.keys())
|
||||
for possible_state in possible_states:
|
||||
if getattr(self, possible_state) == state:
|
||||
return possible_state[len("STATE_"):]
|
||||
|
||||
return "UNKNOWN"
|
||||
|
||||
def getStateString(self, state=None):
|
||||
if state is None:
|
||||
state = self._state
|
||||
|
||||
if state == self.STATE_NONE:
|
||||
return "Offline"
|
||||
if self._state == self.STATE_OPEN_SERIAL:
|
||||
if state == self.STATE_OPEN_SERIAL:
|
||||
return "Opening serial port"
|
||||
if self._state == self.STATE_DETECT_SERIAL:
|
||||
if state == self.STATE_DETECT_SERIAL:
|
||||
return "Detecting serial port"
|
||||
if self._state == self.STATE_DETECT_BAUDRATE:
|
||||
if state == self.STATE_DETECT_BAUDRATE:
|
||||
return "Detecting baudrate"
|
||||
if self._state == self.STATE_CONNECTING:
|
||||
if state == self.STATE_CONNECTING:
|
||||
return "Connecting"
|
||||
if self._state == self.STATE_OPERATIONAL:
|
||||
if state == self.STATE_OPERATIONAL:
|
||||
return "Operational"
|
||||
if self._state == self.STATE_PRINTING:
|
||||
if state == self.STATE_PRINTING:
|
||||
if self.isSdFileSelected():
|
||||
return "Printing from SD"
|
||||
elif self.isStreaming():
|
||||
return "Sending file to SD"
|
||||
else:
|
||||
return "Printing"
|
||||
if self._state == self.STATE_PAUSED:
|
||||
if state == self.STATE_PAUSED:
|
||||
return "Paused"
|
||||
if self._state == self.STATE_CLOSED:
|
||||
if state == self.STATE_CLOSED:
|
||||
return "Closed"
|
||||
if self._state == self.STATE_ERROR:
|
||||
if state == self.STATE_ERROR:
|
||||
return "Error: %s" % (self.getErrorString())
|
||||
if self._state == self.STATE_CLOSED_WITH_ERROR:
|
||||
if state == self.STATE_CLOSED_WITH_ERROR:
|
||||
return "Error: %s" % (self.getErrorString())
|
||||
if self._state == self.STATE_TRANSFERING_FILE:
|
||||
if state == self.STATE_TRANSFERING_FILE:
|
||||
return "Transfering file to SD"
|
||||
return "?%d?" % (self._state)
|
||||
return "Unknown State (%d)" % (self._state)
|
||||
|
||||
def getErrorString(self):
|
||||
return self._errorValue
|
||||
@@ -382,7 +411,29 @@ class MachineCom(object):
|
||||
|
||||
##~~ external interface
|
||||
|
||||
def close(self, isError = False):
|
||||
def close(self, is_error=False, wait=True, *args, **kwargs):
|
||||
"""
|
||||
Closes the connection to the printer.
|
||||
|
||||
If ``is_error`` is False, will attempt to send the ``beforePrinterDisconnected``
|
||||
gcode script. If ``is_error`` is False and ``wait`` is True, will wait
|
||||
until all messages in the send queue (including the ``beforePrinterDisconnected``
|
||||
gcode script) have been sent to the printer.
|
||||
|
||||
Arguments:
|
||||
is_error (bool): Whether the closing takes place due to an error (True)
|
||||
or not (False, default)
|
||||
wait (bool): Whether to wait for all messages in the send
|
||||
queue to be processed before closing (True, default) or not (False)
|
||||
"""
|
||||
|
||||
# legacy parameters
|
||||
is_error = kwargs.get("isError", is_error)
|
||||
|
||||
if self._connection_closing:
|
||||
return
|
||||
self._connection_closing = True
|
||||
|
||||
if self._temperature_timer is not None:
|
||||
try:
|
||||
self._temperature_timer.cancel()
|
||||
@@ -395,16 +446,31 @@ class MachineCom(object):
|
||||
except:
|
||||
pass
|
||||
|
||||
self._monitoring_active = False
|
||||
self._send_queue_active = False
|
||||
def deactivate_monitoring_and_send_queue():
|
||||
self._monitoring_active = False
|
||||
self._send_queue_active = False
|
||||
|
||||
printing = self.isPrinting() or self.isPaused()
|
||||
if self._serial is not None:
|
||||
if isError:
|
||||
if not is_error:
|
||||
self.sendGcodeScript("beforePrinterDisconnected")
|
||||
if wait:
|
||||
self._send_queue.join()
|
||||
|
||||
deactivate_monitoring_and_send_queue()
|
||||
|
||||
try:
|
||||
self._serial.close()
|
||||
except:
|
||||
self._logger.exception("Error while trying to close serial port")
|
||||
is_error = True
|
||||
|
||||
if is_error:
|
||||
self._changeState(self.STATE_CLOSED_WITH_ERROR)
|
||||
else:
|
||||
self._changeState(self.STATE_CLOSED)
|
||||
self._serial.close()
|
||||
else:
|
||||
deactivate_monitoring_and_send_queue()
|
||||
self._serial = None
|
||||
|
||||
if settings().getBoolean(["feature", "sdSupport"]):
|
||||
@@ -419,7 +485,6 @@ class MachineCom(object):
|
||||
"origin": self._currentFile.getFileLocation()
|
||||
}
|
||||
eventManager().fire(Events.PRINT_FAILED, payload)
|
||||
eventManager().fire(Events.DISCONNECTED)
|
||||
|
||||
def setTemperatureOffset(self, offsets):
|
||||
self._tempOffsets.update(offsets)
|
||||
@@ -427,7 +492,7 @@ class MachineCom(object):
|
||||
def fakeOk(self):
|
||||
self._clear_to_send.set()
|
||||
|
||||
def sendCommand(self, cmd, cmd_type=None, processed=False):
|
||||
def sendCommand(self, cmd, cmd_type=None, processed=False, force=False):
|
||||
cmd = cmd.encode('ascii', 'replace')
|
||||
if not processed:
|
||||
cmd = process_gcode_line(cmd)
|
||||
@@ -436,7 +501,7 @@ class MachineCom(object):
|
||||
|
||||
if self.isPrinting() and not self.isSdFileSelected():
|
||||
self._commandQueue.put((cmd, cmd_type))
|
||||
elif self.isOperational():
|
||||
elif self.isOperational() or force:
|
||||
self._sendCommand(cmd, cmd_type=cmd_type)
|
||||
|
||||
def sendGcodeScript(self, scriptName, replacements=None):
|
||||
@@ -508,7 +573,7 @@ class MachineCom(object):
|
||||
|
||||
self._changeState(self.STATE_PRINTING)
|
||||
|
||||
self.sendCommand("M110 N0")
|
||||
self.resetLineNumbers()
|
||||
|
||||
payload = {
|
||||
"file": self._currentFile.getFilename(),
|
||||
@@ -706,6 +771,16 @@ class MachineCom(object):
|
||||
self._callback.on_comm_sd_state_change(self._sdAvailable)
|
||||
self._callback.on_comm_sd_files(self._sdFiles)
|
||||
|
||||
def sayHello(self):
|
||||
self.sendCommand(self._hello_command, force=True)
|
||||
self._clear_to_send.set()
|
||||
|
||||
def resetLineNumbers(self, number=0):
|
||||
if not self.isOperational():
|
||||
return
|
||||
|
||||
self.sendCommand("M110 N%d" % number)
|
||||
|
||||
##~~ communication monitoring and handling
|
||||
|
||||
def _parseTemperatures(self, line):
|
||||
@@ -814,10 +889,9 @@ class MachineCom(object):
|
||||
connection_timeout = settings().getFloat(["serial", "timeout", "connection"])
|
||||
detection_timeout = settings().getFloat(["serial", "timeout", "detection"])
|
||||
|
||||
# enqueue an M105 first thing
|
||||
# enqueue the "hello command" first thing
|
||||
if try_hello:
|
||||
self._sendCommand("M110")
|
||||
self._clear_to_send.set()
|
||||
self.sayHello()
|
||||
|
||||
while self._monitoring_active:
|
||||
try:
|
||||
@@ -1038,8 +1112,7 @@ class MachineCom(object):
|
||||
self._baudrateDetectRetry -= 1
|
||||
self._serial.write('\n')
|
||||
self._log("Baudrate test retry: %d" % (self._baudrateDetectRetry))
|
||||
self._sendCommand("M110")
|
||||
self._clear_to_send.set()
|
||||
self.sayHello()
|
||||
elif len(self._baudrateDetectList) > 0:
|
||||
baudrate = self._baudrateDetectList.pop(0)
|
||||
try:
|
||||
@@ -1050,12 +1123,11 @@ class MachineCom(object):
|
||||
self._baudrateDetectRetry = 5
|
||||
self._timeout = get_new_timeout("communication")
|
||||
self._serial.write('\n')
|
||||
self._sendCommand("M110")
|
||||
self._clear_to_send.set()
|
||||
self.sayHello()
|
||||
except:
|
||||
self._log("Unexpected error while setting baudrate: %d %s" % (baudrate, get_exception_string()))
|
||||
else:
|
||||
self.close()
|
||||
self.close(wait=False)
|
||||
self._errorValue = "No more baudrates to test, and no suitable baudrate found."
|
||||
self._changeState(self.STATE_ERROR)
|
||||
eventManager().fire(Events.ERROR, {"error": self.getErrorString()})
|
||||
@@ -1067,12 +1139,11 @@ class MachineCom(object):
|
||||
elif self._state == self.STATE_CONNECTING:
|
||||
if "start" in line and not startSeen:
|
||||
startSeen = True
|
||||
self._sendCommand("M110")
|
||||
self._clear_to_send.set()
|
||||
self.sayHello()
|
||||
elif "ok" in line:
|
||||
self._onConnected()
|
||||
elif time.time() > self._timeout:
|
||||
self.close()
|
||||
self.close(wait=False)
|
||||
|
||||
### Operational
|
||||
elif self._state == self.STATE_OPERATIONAL or self._state == self.STATE_PAUSED:
|
||||
@@ -1190,6 +1261,8 @@ class MachineCom(object):
|
||||
|
||||
self._changeState(self.STATE_OPERATIONAL)
|
||||
|
||||
self.resetLineNumbers()
|
||||
|
||||
if self._sdAvailable:
|
||||
self.refreshSdFiles()
|
||||
else:
|
||||
@@ -1317,14 +1390,17 @@ class MachineCom(object):
|
||||
return line
|
||||
|
||||
def _readline(self):
|
||||
if self._serial == None:
|
||||
if self._serial is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
ret = self._serial.readline()
|
||||
except:
|
||||
self._log("Unexpected error while reading serial port: %s" % (get_exception_string()))
|
||||
self._errorValue = get_exception_string()
|
||||
self.close(True)
|
||||
if not self._connection_closing:
|
||||
self._logger.exception("Unexpected error while reading from serial port")
|
||||
self._log("Unexpected error while reading serial port, please consult octoprint.log for details: %s" % (get_exception_string()))
|
||||
self._errorValue = get_exception_string()
|
||||
self.close(is_error=True)
|
||||
return None
|
||||
if ret == '':
|
||||
#self._log("Recv: TIMEOUT")
|
||||
@@ -1509,52 +1585,66 @@ class MachineCom(object):
|
||||
# wait until we have something in the queue
|
||||
entry = self._send_queue.get()
|
||||
|
||||
# make sure we are still active
|
||||
if not self._send_queue_active:
|
||||
break
|
||||
try:
|
||||
# make sure we are still active
|
||||
if not self._send_queue_active:
|
||||
break
|
||||
|
||||
# fetch command and optional linenumber from queue
|
||||
command, linenumber, command_type = entry
|
||||
# fetch command and optional linenumber from queue
|
||||
command, linenumber, command_type = entry
|
||||
|
||||
# some firmwares (e.g. Smoothie) might support additional in-band communication that will not
|
||||
# stick to the acknowledgement behaviour of GCODE, so we check here if we have a GCODE command
|
||||
# at hand here and only clear our clear_to_send flag later if that's the case
|
||||
gcode = self.gcode_command_for_cmd(command)
|
||||
# some firmwares (e.g. Smoothie) might support additional in-band communication that will not
|
||||
# stick to the acknowledgement behaviour of GCODE, so we check here if we have a GCODE command
|
||||
# at hand here and only clear our clear_to_send flag later if that's the case
|
||||
gcode = self.gcode_command_for_cmd(command)
|
||||
|
||||
if linenumber is not None:
|
||||
# line number predetermined - this only happens for resends, so we'll use the number and
|
||||
# send directly without any processing (since that already took place on the first sending!)
|
||||
self._doSendWithChecksum(command, linenumber)
|
||||
|
||||
else:
|
||||
# trigger "sending" phase
|
||||
command, _, gcode = self._process_command_phase("sending", command, command_type, gcode=gcode)
|
||||
|
||||
if command is None:
|
||||
# so no, we are not going to send this, that was a last-minute bail, let's fetch the next item from the queue
|
||||
continue
|
||||
|
||||
# now comes the part where we increase line numbers and send stuff - no turning back now
|
||||
if (gcode is not None or self._sendChecksumWithUnknownCommands) and (self.isPrinting() or self._alwaysSendChecksum):
|
||||
linenumber = self._currentLine
|
||||
self._addToLastLines(command)
|
||||
self._currentLine += 1
|
||||
if linenumber is not None:
|
||||
# line number predetermined - this only happens for resends, so we'll use the number and
|
||||
# send directly without any processing (since that already took place on the first sending!)
|
||||
self._doSendWithChecksum(command, linenumber)
|
||||
|
||||
else:
|
||||
self._doSendWithoutChecksum(command)
|
||||
# trigger "sending" phase
|
||||
command, _, gcode = self._process_command_phase("sending", command, command_type, gcode=gcode)
|
||||
|
||||
# trigger "sent" phase and use up one "ok"
|
||||
self._process_command_phase("sent", command, command_type, gcode=gcode)
|
||||
if command is None:
|
||||
# so no, we are not going to send this, that was a last-minute bail, let's fetch the next item from the queue
|
||||
continue
|
||||
|
||||
# we only need to use up a clear if the command we just sent was either a gcode command or if we also
|
||||
# require ack's for unknown commands
|
||||
use_up_clear = self._unknownCommandsNeedAck
|
||||
if gcode is not None:
|
||||
use_up_clear = True
|
||||
if command.strip() == "":
|
||||
self._logger.info("Refusing to send an empty line to the printer")
|
||||
continue
|
||||
|
||||
# if we need to use up a clear, do that now
|
||||
if use_up_clear:
|
||||
self._clear_to_send.clear()
|
||||
# now comes the part where we increase line numbers and send stuff - no turning back now
|
||||
command_requiring_checksum = gcode is not None and gcode in self._checksum_requiring_commands
|
||||
command_allowing_checksum = gcode is not None or self._sendChecksumWithUnknownCommands
|
||||
checksum_enabled = self.isPrinting() or self._alwaysSendChecksum
|
||||
|
||||
if command_requiring_checksum or (command_allowing_checksum and checksum_enabled):
|
||||
linenumber = self._currentLine
|
||||
self._addToLastLines(command)
|
||||
self._currentLine += 1
|
||||
self._doSendWithChecksum(command, linenumber)
|
||||
else:
|
||||
self._doSendWithoutChecksum(command)
|
||||
|
||||
# trigger "sent" phase and use up one "ok"
|
||||
self._process_command_phase("sent", command, command_type, gcode=gcode)
|
||||
|
||||
# we only need to use up a clear if the command we just sent was either a gcode command or if we also
|
||||
# require ack's for unknown commands
|
||||
use_up_clear = self._unknownCommandsNeedAck
|
||||
if gcode is not None:
|
||||
use_up_clear = True
|
||||
|
||||
# if we need to use up a clear, do that now
|
||||
if use_up_clear:
|
||||
self._clear_to_send.clear()
|
||||
|
||||
finally:
|
||||
# no matter _how_ we exit this block, we signal that we
|
||||
# are done processing the last fetched queue entry
|
||||
self._send_queue.task_done()
|
||||
|
||||
# now we just wait for the next clear and then start again
|
||||
self._clear_to_send.wait()
|
||||
@@ -1634,6 +1724,9 @@ class MachineCom(object):
|
||||
self._doSendWithoutChecksum(commandToSend)
|
||||
|
||||
def _doSendWithoutChecksum(self, cmd):
|
||||
if self._serial is None:
|
||||
return
|
||||
|
||||
self._log("Send: %s" % cmd)
|
||||
try:
|
||||
self._serial.write(cmd + '\n')
|
||||
@@ -1642,15 +1735,17 @@ class MachineCom(object):
|
||||
try:
|
||||
self._serial.write(cmd + '\n')
|
||||
except:
|
||||
if not self._connection_closing:
|
||||
self._logger.exception("Unexpected error while writing to serial port")
|
||||
self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
|
||||
self._errorValue = get_exception_string()
|
||||
self.close(is_error=True)
|
||||
except:
|
||||
if not self._connection_closing:
|
||||
self._logger.exception("Unexpected error while writing to serial port")
|
||||
self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
|
||||
self._errorValue = get_exception_string()
|
||||
self.close(True)
|
||||
except:
|
||||
self._logger.exception("Unexpected error while writing to serial port")
|
||||
self._log("Unexpected error while writing to serial port: %s" % (get_exception_string()))
|
||||
self._errorValue = get_exception_string()
|
||||
self.close(True)
|
||||
self.close(is_error=True)
|
||||
|
||||
##~~ command handlers
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ import sarge
|
||||
import sys
|
||||
import logging
|
||||
|
||||
import pkg_resources
|
||||
|
||||
from .commandline import CommandlineCaller
|
||||
|
||||
|
||||
@@ -17,6 +19,10 @@ class UnknownPip(Exception):
|
||||
pass
|
||||
|
||||
class PipCaller(CommandlineCaller):
|
||||
process_dependency_links = pkg_resources.parse_requirements("pip>=1.5")
|
||||
no_use_wheel = pkg_resources.parse_requirements("pip==1.5.0")
|
||||
broken = pkg_resources.parse_requirements("pip>=6.0.1,<=6.0.3")
|
||||
|
||||
def __init__(self, configured=None):
|
||||
CommandlineCaller.__init__(self)
|
||||
self._logger = logging.getLogger(__name__)
|
||||
@@ -62,7 +68,16 @@ class PipCaller(CommandlineCaller):
|
||||
if self._command is None:
|
||||
raise UnknownPip()
|
||||
|
||||
command = [self._command] + list(args)
|
||||
arg_list = list(args)
|
||||
if "install" in arg_list:
|
||||
if not self.version in self.__class__.process_dependency_links and "--process-dependency-links" in arg_list:
|
||||
self._logger.debug("Found --process-dependency-links flag, version {} doesn't need that yet though, removing.".format(self.version))
|
||||
arg_list.remove("--process-dependency-links")
|
||||
if self.version in self.__class__.no_use_wheel and not "--no-use-wheel" in arg_list:
|
||||
self._logger.debug("Version {} needs --no-use-wheel to properly work.".format(self.version))
|
||||
arg_list.append("--no-use-wheel")
|
||||
|
||||
command = [self._command] + arg_list
|
||||
return self.call(command)
|
||||
|
||||
def _find_pip(self):
|
||||
@@ -121,12 +136,16 @@ class PipCaller(CommandlineCaller):
|
||||
|
||||
version_segment = split_output[1]
|
||||
|
||||
from pkg_resources import parse_version
|
||||
try:
|
||||
pip_version = parse_version(version_segment)
|
||||
pip_version = pkg_resources.parse_version(version_segment)
|
||||
except:
|
||||
self._logger.exception("Error while trying to parse version string from pip command")
|
||||
return None, None
|
||||
else:
|
||||
self._logger.info("Found pip at {}, version is {}".format(pip_command, version_segment))
|
||||
|
||||
if pip_version in self.__class__.broken:
|
||||
self._logger.error("This version of pip is known to have errors that make it incompatible with how it needs to be used by OctoPrint. Please upgrade your pip version.")
|
||||
return None, None
|
||||
|
||||
return pip_command, pip_version
|
||||
@@ -444,7 +444,7 @@ def get_babel_commandclasses(pot_file=None,
|
||||
def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1", description="TODO", author="TODO",
|
||||
mail="todo@example.com", url="TODO", license="AGPLv3", source_folder=".", additional_data=None,
|
||||
additional_packages=None, ignored_packages=None, requires=None, extra_requires=None,
|
||||
cmdclass=None, eggs=None, package=None):
|
||||
cmdclass=None, eggs=None, package=None, dependency_links=None):
|
||||
import pkg_resources
|
||||
|
||||
if package is None:
|
||||
@@ -459,6 +459,9 @@ def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1"
|
||||
if ignored_packages is None:
|
||||
ignored_packages = list()
|
||||
|
||||
if dependency_links is None:
|
||||
dependency_links = list()
|
||||
|
||||
if requires is None:
|
||||
requires = ["OctoPrint"]
|
||||
if not isinstance(requires, list):
|
||||
@@ -524,6 +527,7 @@ def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1"
|
||||
|
||||
install_requires=requires,
|
||||
extras_require=extra_requires,
|
||||
dependency_links=dependency_links,
|
||||
|
||||
# Hook the plugin into the "octoprint.plugin" entry point, mapping the plugin_identifier to the plugin_package.
|
||||
# That way OctoPrint will be able to find the plugin and load it.
|
||||
|
||||
@@ -259,4 +259,4 @@ class FileManagerTest(unittest.TestCase):
|
||||
mocked_os.assert_called_once_with("tmp.file")
|
||||
|
||||
# assert that time.time was only called once
|
||||
mocked_time.assert_called_once()
|
||||
self.assertEqual(mocked_time.call_count, 1)
|
||||
@@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
import unittest
|
||||
import os
|
||||
import mock
|
||||
import os.path
|
||||
|
||||
from ddt import ddt, unpack, data
|
||||
|
||||
@@ -41,7 +42,7 @@ class LocalStorageTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
import tempfile
|
||||
self.basefolder = tempfile.mkdtemp()
|
||||
self.basefolder = os.path.realpath(os.path.abspath(tempfile.mkdtemp()))
|
||||
self.storage = octoprint.filemanager.storage.LocalFileStorage(self.basefolder)
|
||||
|
||||
# mock file manager module
|
||||
|
||||
@@ -142,11 +142,10 @@ class TestSlicingManager(unittest.TestCase):
|
||||
|
||||
# assert that temporary profile was created properly
|
||||
self.slicer_plugin.save_slicer_profile.assert_called_once_with("tmp.file", default_profile, overrides=overrides)
|
||||
|
||||
# assert that slicing thread was created properly
|
||||
mocked_thread.assert_called_once_with(target=mock.ANY, args=(self.slicer_plugin, source_path, dest_path, profile_name, overrides, printer_profile, position, callback, callback_args, callback_kwargs))
|
||||
self.assertTrue(mock_thread.mock.daemon)
|
||||
mock_thread.mock.start.assert_called_once()
|
||||
self.assertEqual(mock_thread.mock.start.call_count, 1)
|
||||
|
||||
# assert that slicer was called correctly
|
||||
self.slicer_plugin.do_slice.assert_called_once_with(source_path, printer_profile, machinecode_path=dest_path, profile_path="tmp.file", position=position, on_progress=None, on_progress_args=None, on_progress_kwargs=None)
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
# coding=utf-8
|
||||
"""
|
||||
Unit tests for octoprint.users
|
||||
"""
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import unittest
|
||||
import ddt
|
||||
|
||||
import octoprint.users
|
||||
from octoprint.util import dict_merge
|
||||
|
||||
default_settings = dict(key="value", sub=dict(subkey="subvalue"))
|
||||
|
||||
@ddt.ddt
|
||||
class UserTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.user = octoprint.users.User("user", "passwordHash", True, ("user",), apikey="apikey_user", settings=default_settings)
|
||||
self.admin = octoprint.users.User("admin", "passwordHash", True, ("user","admin"), apikey="apikey_admin", settings=default_settings)
|
||||
self.inactive = octoprint.users.User("inactive", "passwordHash", False, ("user",), apikey="apikey_inactive", settings=default_settings)
|
||||
|
||||
@ddt.data(
|
||||
("user", dict(name="user",
|
||||
active=True,
|
||||
admin=False,
|
||||
user=True,
|
||||
apikey="apikey_user",
|
||||
settings=default_settings)),
|
||||
("admin", dict(name="admin",
|
||||
active=True,
|
||||
admin=True,
|
||||
user=True,
|
||||
apikey="apikey_admin",
|
||||
settings=default_settings)),
|
||||
("inactive", dict(name="inactive",
|
||||
active=False,
|
||||
admin=False,
|
||||
user=True,
|
||||
apikey="apikey_inactive",
|
||||
settings=default_settings))
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_as_dict(self, uservar, expected):
|
||||
user = getattr(self, uservar)
|
||||
self.assertDictEqual(expected, user.asDict())
|
||||
|
||||
@ddt.data(
|
||||
("key", "value"),
|
||||
(["sub", "subkey"], "subvalue"),
|
||||
("doesntexist", None)
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_get_setting(self, key, expected):
|
||||
value = self.user.get_setting(key)
|
||||
self.assertEquals(expected, value)
|
||||
|
||||
@ddt.data(
|
||||
("otherkey", "othervalue", dict(otherkey="othervalue"), True),
|
||||
(["sub", "othersubkey"], "othersubvalue", dict(sub=dict(othersubkey="othersubvalue")), True),
|
||||
("booleankey", True, dict(booleankey=True), True),
|
||||
(["newsub", "newsubkey"], "newsubvalue", dict(newsub=dict(newsubkey="newsubvalue")), True),
|
||||
(["sub", "subkey", "wontwork"], "wontwork", dict(), False)
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_set_setting_string(self, key, value, update, expected_returnvalue):
|
||||
returnvalue = self.user.set_setting(key, value)
|
||||
|
||||
expected = dict_merge(default_settings, update)
|
||||
|
||||
self.assertDictEqual(expected, self.user.get_all_settings())
|
||||
self.assertEqual(expected_returnvalue, returnvalue)
|
||||
|
||||
def test_check_password(self):
|
||||
self.assertTrue(self.user.check_password("passwordHash"))
|
||||
self.assertFalse(self.user.check_password("notThePasswordHash"))
|
||||
|
||||
@ddt.data(
|
||||
("user", "User(id=user,name=user,active=True,user=True,admin=False)"),
|
||||
("admin", "User(id=admin,name=admin,active=True,user=True,admin=True)"),
|
||||
("inactive", "User(id=inactive,name=inactive,active=False,user=True,admin=False)")
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_repr(self, uservar, output):
|
||||
self.assertEqual(output, repr(getattr(self, uservar)))
|
||||
|
||||
class SessionUserTestCase(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.user = octoprint.users.User("username", "passwordHash", True, ("user",), apikey="apikey", settings=dict(key="value"))
|
||||
|
||||
def test_two_sessions(self):
|
||||
session1 = octoprint.users.SessionUser(self.user)
|
||||
session2 = octoprint.users.SessionUser(self.user)
|
||||
|
||||
self.assertNotEqual(session1.get_session(), session2.get_session())
|
||||
self.assertEqual(session1._user, session2._user)
|
||||
self.assertEqual(session1._username, session2._username)
|
||||
|
||||
def test_settings_change_propagates(self):
|
||||
user = octoprint.users.SessionUser(self.user)
|
||||
self.user.set_setting("otherkey", "othervalue")
|
||||
|
||||
self.assertDictEqual(dict(key="value", otherkey="othervalue"), user.get_all_settings())
|
||||
|
||||
def test_repr(self):
|
||||
user = octoprint.users.SessionUser(self.user)
|
||||
expected = "SessionUser(id=username,name=username,active=True,user=True,admin=False,session={},created={})".format(user._session, user._created)
|
||||
self.assertEquals(expected, repr(user))
|
||||
Reference in new issue
Block a user